Security is more often an artist job than engineering. Its a vital organism for an ethical growth of a responsible application.
The information provided here will be focused towards web based applications; however, some of the concepts can be universally applied to all application development platforms.
While there are 100s of articles and discussion about securing a website and developing a safe authentication system, there are less of synchronization from topic to implementation.
My motto is to provide a pin point to help you start researching and blending into this subject. Note, this blog doesn’t covers learning programming languages, it gives an overview and basically some ideologies on security precautions.
Firstly we need to understand that security is nothing which has some definite checklists to secure things permanently. Keeping things secure is a process and cannot be treated as a generic commodity.
The basic and ethical reason towards considering security a primary focus, is when you store some data with intention to not publically broadcast it to the world. And then it becomes your responsibility to provide appropriate levels of security for its protection.
We everyday deal with many applications and websites which are manufactured and manifested with some basics of security stuffs like:
Nowdays having a strongly salted hashed encryption is considered as enough for securing password. There are many types of hashing like: MD5, SHA-1, SHA-256, SHA-512 (the latter two are collectively known as “SHA-2″). Some loop-holes have been found in MD5 and SHA-1, so I deeply recommend using SHA-256 and SHA-512. Between SHA-256 and SHA-512, they differ by their output size and performance (on some systems, SHA-256 is much faster than SHA-512, and on others SHA-512 is faster than SHA-256). Whenever you create or modify a password, generate a new random salt S (16 bytes). Then hash the password p as SHA-256(S||p||S||p||S||p||…||S||p) where the ‘ S||p ‘ pattern is repeated enough times to that the hashing process takes 10ms. Store both S and the hash result. To verify a user password, retrieve S, recompute the hash, and compare it with the stored value.
Retrieving forgotten password
Always send password resetting link to the associated Email address, and validate the link within a fixed lifespan. Also never tell user that the entered Email ID is valid or invalid, like: “ An email has been sent to the email address you have mentioned. We will validate your credential and send the requested account reset link with further information. Please click the link in email and reset your password. NOTE : The link will be valid for next 1 hour only. “. The reason behind this is to insure that we are not providing any sensitive information that would allow an attacker to determine if an entered username/email address is valid or invalid. Otherwise an attacker could enumerate valid accounts for phishing attacks or brute force attack. Also, the Email verification link must expire after the first use.
Session ID’s should be created on logins and should be explicitly deleted while logout. It has to be 128-bit or greater and should time-out after a determined period of inactivity (15 minutes is recommended). Also, it will be a great practice for session token to be handled by web server via cryptographically generated secure random number. Another important thing to remember is secure flag while setting every set-cookie so that browser shouldn’t send the cookie over HTTP, and the “ HTTP-Only ” flag that will be set to disable malicious script access to the session ID (e.g. XSS).
Restricting login attempts
This layer of security is usually seen on Bank sites where multiple failed login attempts are registered in the log and the IP address of suspected attempt is blocked for few hours like for 12 hours or maybe 24 or so on.
Password complexity system
To allow users only if the user entered new password contain atleast some special characters with minimum of one Uppercase and one Lowercase letter. Some sites also limit users to meet the minimum number of characters and also matches if the password contains any dictionary keyword.
Password rotation policy
The application/website provider rotates an optionally acceptable movement to help its users secure their accounts, by asking users to change their password if they haven’t changed it since 6 Months or maybe 1 year, or so on. But you also need to make it sure that your users should not end up writing all their passwords on notes, papers or somewhere else as it will be considered as a security risk too. So you need to take special efforts to educate them and help them understanding the threats. This also becomes annoying sometimes, so you can ask user if they want to be notified for this step again in future or not.
Validating input data
My first suggestion would be “Never trust any input data” Its also very important to take appropriate steps to minimize the malformed data from entering into the database or server. A good practice is to validate all type of data that is coming from a user and also apply relevant input length validation like: Simple US Zipcode: can only contain Numbers and could be maximum 5 characters OR Username: can only contain Letters, numbers, certain special characters and could be 3 to 10 characters in length
Fail securely – Avoid displaying errors to visitors
Handling errors securely is a key aspect of secure coding. For example, security methods like isAuthorized(), isAuthenticated(), and isValidated() should all return false if there is an exception during processing. If security controls can throw exceptions, they must be very clear about exactly what that condition means. Refer the below example:
Most important with captcha (Completely automated Turing Tests To Tell Humans and Computers Apart) is that it has to be really human-solvable, as many out there are very annoying and are ineffective against bots. I personally recommond using reCAPTCHA since it uses already OCR-misclassified book scans. However I was going through a talk atOWASP and found this beautiful PPT about Breaking CAPTCHA Myths. So basically the captcha stuff is really in controversy these days, but it atleast provides a layer to secure the span hits on websites.
NOTE: Although CAPTCHAs seem useful, they are in fact, trivial to break using any of the following methods:
- Optical Character Recognition. Most common CAPTCHAs are solvable using specialist CAPTCHA breaking OCR software.
- Break a test, get free access to foo, where foo is a desirable resource
- Pay someone to solve the CAPTCHAs. The current rate at the time of writing is $12 per 500 tests.
Password Guidelines (Good Practices)
- Credentials should only traverse encrypted links
- Store the password in a strongly hashed and salted format to prevent rainbow table attacks.
- Pass phrases (long passwords over 20 characters in length) should be encouraged
- Short passwords should be prohibited
- Do not force folks to change passwords frequently as this results in the users writing the passwords down insecurely (Try it for 6 months or maybe an year)
- Where suitable, try to share the credential with as many low value systems as possible to encourage one single high quality password
- Allow expert users to store strong passwords in approved password managers. Encourage them to use unique random passwords for each service
Some other important things to understand
Always validate all the types of data coming to you like: Form data, URL parameters, Hidden fields, Cookie data, HTTP Headers, and essentially anything in the HTTP request. But sometimes it becomes very difficult to validate when we deal with Rich Texts, for this we should use formal approaches such asHTML Purifier (PHP) or AntiSamy or bleach (Python)
Two factor authentication
Typical two factor solutions involve registering a hardware device such as a token, phone or biometric device on top of the “something you know”. In all cases, the two factors should be used together for best results.
- Something you know (account details or passwords)
- Something you have (tokens or mobile phones)
- Something you are (biometrics)
Understanding cross domains
Firstly, the possible issues related to cross domains are Cross Site Request Forgery (CSRF), Malicious Framing (Clickjacking), 3rd Party Scripts, and insecure interaction with 3rd party sites.
To understand prevention from CSRF first we need to understand that an attacker creates a self posting form or image tag which executes an action on behalf of the authenticated user. And then it forces an end user to execute unwanted actions on a web application in which he/she is currently authenticated. With a little help of social engineering (like sending a link via email/chat), an attacker may trick the users of a web application into executing actions of the attacker’s choosing. A successful CSRF exploit can compromise end user data and operation in case of normal user. If the targeted end user is the administrator account, this can compromise the entire web application. Now what we need to study:
- Any state changing operation requires a secure random token (e.g CSRF token) to prevent against CSRF attacks
- Characteristics of a CSRF Token
- Unique per user & per user session
- Tied to a single user session
- Large random value
- Generated by a cryptographically secure random number generator
- The CSRF token is added as a hidden field for forms or within the URL if the state changing operation occurs via a GET
- The server rejects the requested action if the CSRF token fails validation
Note: Some frameworks (such as django) provide this capability. Use the established CSRF protection from the framework instead of creating your own.
Preventing Malicious Site Framing (ClickJacking)
A newer attack that uses page layering and framing to convince the user to click or enter data on particular parts of the screen. These actions are actually sent to the framed site to perform actions unbeknown to the victim user. Get a better overview from Sectheory
Set the x-frame-options header for all responses containing HTML content. The possible values are “DENY” or “SAMEORIGIN”.
- DENY will block any site (regardless of domain) from framing the content.
- SAMEORIGIN will block all sites from framing the content, except sites within the same domain.
The “DENY” setting is recommended unless a specific need has been identified for framing.
3rd Party Scripts
- Careful consideration should be used when using third party scripts. While I am sure everybody would do an initial review, updates to scripts should be reviewed with the same due diligence.
- Ensure any scripts that are used are hosted locally and not dynamically referenced from a third party site.
Connecting with Twitter, Facebook, etc
- If using OAuth make sure the entire chain of communication is over HTTPS. This includes the initial OAuth request and any URLs passed as parameters.
- If redirecting to a login page for the app itself, ensure that URL is HTTPS and also that the selected URL does not simply redirect to a HTTP version
- Ensure the “tweet this” or “like this” button does not generate a request to the 3rd party site simply by loading the Mozilla webpage the button is on (e.g. no requests to third party site without user’s intent via clicking on the button)
There are substantial amount of topics to be covered in security and I will try to cover as much as I can. The notes above should not be considered covering all aspects to the topics discussed, and should be considered as an overview of the same.
In continuation to this topic I will be adding in-depth insights over the topics discussed and many others like: File Uploading, Client-Server Security, Timestamp, Sanitization, Database access and privileges, Error Handling, Penetration Testing, Intrusion detection, Prepared statements benefits, DDoS Attacks, Brute Force and many more. Stay tuned and I will be back with other stuffs ASAP, after I get time from my office work.