It's a real cool idea to conduct security code review using tools. Many companies have built these tools around and have become instant success but not until it was realized that these tools were good but not "good enough" to give you a complete fool proof solution. There are bunch of tools available from several companies which can detect Cross Site Scripting and SQL injection flaws. Security is not just all about XSS and SQL injection vulnerabilities. There are many many issues which can blow up your application.
So what went wrong with these tools ?
a) Many false positives (false alarms)
b) Designed to detect only handful of vulnerabiliites
c) Failing to detect newer attack patterns
d) Usability issues
What to do now ?
You should use a mixed approach. Use tools to weed-out low hanging issues and later perform a comprehensive line by line code review to uncover other complex security issues. This way you increase your productivity and get more time to concentrate on complex code.
To help you in this endevor, Microsoft ACE team has recently released XSSDetect tool , which is a free 30 day trial downloadable tool. You can get it from
http://www.microsoft.com/downloads/details.aspx?FamilyID=19a9e348-bdb9-45b3-a1b7-44ccdcb7cfbe&displaylang=en
XSSDetect is a static code analysis tool that helps identify Cross-Site Scripting security flaws found within Web applications. It is able to scan compiled managed assemblies (C#, Visual Basic .NET, J#) and analyze dataflow paths from sources of user-controlled input to vulnerable outputs
You can also rely on Microsoft ACE team's threat modeling tool to discover probable vulnerabilities in your application even before you have written hardly any code. This tool allows non-security subject matter experts to enter already known information including business requirements and application architecture which is then used to produce a feature-rich threat model. Along with automatically identifying threats, the tool can produce valuable security artifacts such as:
- Data access control matrix
- Component access control matrix
- Subject-object matrix
- Data Flow
- Call Flow
- Trust Flow
- Attack Surface
- Focused reports
You can download this tool for free from http://www.microsoft.com/downloads/details.aspx?familyid=59888078-9daf-4e96-b7d1-944703479451&displaylang=en
Moral of the story :
Current tools available in market are not mature enough ! so don't just completely rely on them.Please get your code reviewed by an expereinced security technologist who is far more reliable than tools. At ACE team here in Microsoft , we have highly experienced consultants who can eyeball your code thoroughly and provide you a comprehensive analysis of issues in your code. You also enjoy the benefit of knowing the best practices for your application security.
Happy Secure Coding !
Human brain is considered to be the super computer of the world. Multiple logical computations and decisions occur in the human brain within a fraction of second. The brain has several important parts which control the central nervous system and in turn drive the whole human activity.
Can the human brain be hacked? . This is the immediate question which stems in my mind.
Human brains cannot be hacked for the simple reason that they all live in a disconnected world. Every human brain is disconnected with that of others. Then what about telepathy, emotional bonding etc considered as ? Sure …sure that’s all there but apart from that every human brain is an individual computer by itself and that makes intrusion very difficult!
One of my friends in-jest used to say that he had two brains, one left and the other one right and that his ‘left brain had nothing right and his right brain had nothing left’ …..Isn’t it funny?
But coming to the actual computer world, this is no fun. 70 % of the computers in the world are connected either through internet or the intranet. This very nature of being in a connected world makes the computer systems hack able (unlike our brains!!!).
To prevent unauthorized access, mutual authentication and authorization plays a key role. Authentication helps identify the identity who is trying to access a resource. Establishing identity by supplying user name and password is still a valid method to authenticate systems.
Password security is most important factor in authentication. One should consider securing their passwords similar to their credit card number. The strength of the password decides how strong your authentication mechanism is. A weak password can be guessed by executing a brute force attack using a subset of all possible passwords or either by launching a dictionary attack.
Passwords are the first line of defense for protecting assets and guessing them is a popular and often successful attack method. A poorly chosen password can result in the compromise of our entire corporate network.
If an attacker obtains user’s passwords, she can create havoc in the user’s system. She can get to know their personal information or create a denial of service situation by simply deleting all the system files. In a web application scenario, she can just get into their bank account and steal all the money.
Isn’t it scary?
If you are a developer or a solution designer and really mean having secured authentication mechanisms in your applications, ensure to follow following best practices that encompass Password.
|
Password Strength |
|
The strong password should include at least eight characters, and should use a mixture of uppercase and lowercase letters, numbers, and other characters such as *, ?, or $ or other some special characters. |
|
Do not store or cache Passwords and corporate credentials in readable form ; Do not have credentials in clear text in the configuration files or Cookies. |
|
Do not use features like "Remember Password" ; Many applications store credentials in readable form, such mechanisms should not be used. |
|
Treat and handle Passwords as “High Business Impact (HBI)”information; Consider to encrypt passwords while stored on the disk and use SSL channel for transmitting Passwords. |
|
Passwords in Forms and Custom authentication |
|
Use one way hash on Passwords to store the passwords rather than the clear password itself; Use Hashing algorithm like SHA1 or above. |
|
Consider to use a salt value when creating the hash to slow an attacker who is attempting to perform a dictionary attack. This approach gives you additional time to detect and react to the compromise. |
|
Use RNGCryptoServiceProvider to create salt with better ‘entropy’
private static string CreateSalt(int size)
{
// Generate a cryptographic random number using the cryptographic
// service provider
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] buff = new byte[size];
rng.GetBytes(buff);
// Return a Base64 string representation of the random number
return Convert.ToBase64String(buff);
} |
|
Configure account lockout policy. By default if a user has 3 invalid password attempts in a 10 minute period, the account should get locked. |
|
Enforce strong passwords. The SqlMembershipProvider and ActiveDirectoryMembershipProvider, enforces a minimum password length of 7 characters with at least 1 non alphanumeric character. You can further strengthen the password requirements by configuring the attributes minRequiredPasswordLength, minRequiredNonAlphanumericCharacters and passwordStrengthRegularExpression. |
|
If you are using a fixed identity to impersonate by specifying account credentials on the <identity> element , you should consider to encrypt the credentials by using the Aspnet_setreg.exe utility. |
Last but not the least; please consider changing passwords for every 60 days. As a good security practice, passwords should be changed as frequently as possible to minimize the attack probability. Of course “Passwords are not forever!”
Resources for further reading:
Building secure web applications: http://msdn2.microsoft.com/en-us/library/aa302396.aspx
There is a saying in English “Old habits die harder” and there is a riddle around it
I have one, you have one.
If you remove the first letter, a bit remains.
If you remove the second, bit still remains.
After much trying, you might be able to remove the third one also, but it remains.
It dies hard!
What is it?
Here is the answer for above riddle :
If you remove the first letter “h” from the word “Habit” , still a-bit remains, further if you remove letter from a-bit, still ‘bit’ remains and unfortunately after you remove letter ‘b’ as well, still ‘it’ remains. What is the moral of the story? Habits do not die easily. They linger on and on….
I was wondering whether it is true for “Software developers” . Yes! It is! The evidence to support my argument is the number of security issues I find in several applications till date.
Clear text connection strings, Poor exception handling, un-sanitized user inputs , dynamic SQL and poor configuration issues and many more…and it’s all about poor habits [practices]. Can we do something about it is the problem question?
Why not? Inculcate good habits to erase the bad habits. Slowly over a period of time new habits superimpose themselves and take a charge.
SD3 is the Mantra to follow defense in depth principles. Developers have to follow the principles of SD3 to reduce security vulnerabilities in their applications.
SD 3 is Microsoft’s defense in depth strategy which stands for Secure by design, secure by default and secure in deployment.
Secure by Design: This means that developers follow secure coding best practices and implement security features in their applications to overcome vulnerabilities.
This principle consists of using security features like Authorization, Authentication, Auditing and logging, usage of least privilege account and cryptography etc.
Many designers and developers at the end just sprinkle few security features in their applications. Secure by design does not advocate that way.
Secure by design means blending security into your applications. It involves due consideration to security right from the design stage of your application and weaving security features into every aspect of application development process.
For Ex: If I know that my application handles sensitive data or information, I would like to encrypt the data and protect it from theft and tampering. I give due consideration to use cryptography in my application right at the design stage.
Secure by Default: This simply means that end users install applications without altering the default settings and therefore requires these users specifically select features that might not be used or that might reduce security.
Many users do not change the default settings after installation. Why to bother them by asking them to disable unwanted features to reduce the attack surface? Security should be by default. If a feature is specifically required by a user she will enable as per her choice and with knowledge of consequences in case of security breach.
For Ex: Users are prompted to select optional components during the setup procedure and have the option to add those components later by re-running setup.
Secure in deployment The applications can be maintained securely after deployment by updating with security patches, monitoring for attacks, and by auditing for malicious users and content.
This involves having a process to identify newly discovered security vulnerabilities and ability to patch them regularly to remove those vulnerabilities. Also involves taking data – backups so that you can restore to normal in the event of a compromise, monitoring events at regular intervals and check for intrusions.
For Ex: In the event of application failure or errors, a system should be in place so that users should be shown only generic error information and those events should be logged so that administrators can help resolve the issues.
So dear developers conform to SD3 to develop secure applications and advocate security best practices to your fellow colleagues.
More information and videos on SD3
http://msdn.microsoft.com/msdntv/episode.aspx?xml=episodes/en/20030513securitymh/manifest.xml
Introduction
Input validation is the “key” to application security. 50 to 60 % of security vulnerabilities in almost 70 % of applications are due to poor input validation.
There are several attack vectors possible due to poor input validation
1) Cross Site Scripting
2) SQL injection
3) Response splitting
4) Buffer overflow
5) XML injection
6) Directory Traversals
7) Denial of service
Need for user input:
Business Applications need data to work upon so that meaningful information is delivered to the user. The relevancy and the context of the information are ascertained by user supplied input like for ex: username and password or some personal data like address, telephone and email details. Many applications either store these data or do some manipulations to render useful results.
How attackers use them?
User input fields are the major entry points for most of the attackers. If the application has a cross site scripting vulnerability they can steal the cookie and thereby have an un-authorized access to the system or inject a malicious SQL query to launch an SQL injection attack or can cause buffer overrun and thereby execute a remote code or in the worst case can launch a denial of service attack (DoS)
What is the countermeasure?
Validate, validate and validate the user input.
àValidate data for type, length, format and range.
àAssume all input is malicious.
àCentralize your approach.
àDo not rely on client-side validation.
àConstrain, reject, and sanitize your input.
Input Validation Strategy
An effective strategy can adopt following ways
· Constrain input.
· Validate data for type, length, format, and range.
· Reject known bad input.
· Sanitize input
Input Validation Explained:
Input validation can be performed in two ways
1) Exclusion list approach (also called as blacklist approach)
2) inclusion list approach (also called as whitelist approach)
Exclusion list or a black list approach means filtering the bad data. It is basically a list of malicious user inputs and all other inputs is treated as good.
Inclusion list approach involves allowing only known good inputs. It is a list of all good inputs which a system can accept.
As a security strategy, it is better to adhere to inclusion list approach than to an exclusion list as the list of accepted values is limited in comparison to several un-known and unforeseen unacceptable values. Secondly, a black list approach may accidentally treat a malicious input to be safe.
But in certain situations where a whitelist approach cannot be easily implemented, a blacklist approach suits better. And in such situations it is advised to use a combination of whitelist as well as a blacklist, instead of following a single approach throughout the application.
Server side or Client side validation?
User input validation should be done both at client and server side. In security perspective, Server side validation is a must. Client side validation can be easily bypassed by turning off javacript in the browser. Hence never rely upon client side validation. But for several other benefits , client side validation should be done along with server side. The following table elucidates the reasons
|
Validation Type |
Superior User Experience |
Immediate Response |
Superior performance |
Increased Security |
|
Client Side |
ü |
ü |
ü |
|
|
Server Side |
|
|
|
ü |
It can be easily seen from the above table that client side validation brings in higher performance by reducing unnecessary round trips to the server. Since the validation is at the client, the error information can be immediately shown to the users so that they can correct without having to wait until a response comes from the server. This makes applications highly interactive and usable.
When it comes to security, the bottleneck with client side validation is that this technique heavily relies on client side scripting languages likes javascript or vbscript which can be thwarted very easily. Applications completely relying on client side validations are highly vulnerable as an attacker can easily bypass the validation on the browser.
ASP.NET Validator Controls
The .NET Framework provides validation controls that validate user input and show appropriate error messages whenever invalid data is encountered in a validation control. This helps to save huge time when there is a need to duplicate this validation on both the client and server. These controls can be used both on client and on server side and enhance performance by avoiding server round trips wherever possible.
Additionally, a ValidationSummary control is provided to display all error messages for a page in one area of the screen.
Usage of ASP.NET Validator control: <asp:control_name id="some_id" runat="server" />
|
Validation Type |
Appropriate Control |
Description |
|
Required Entry |
The RequiredFieldValidator Control |
Ensures that the user does not skip an entry. |
|
Comparison to a Value |
The CompareValidator Control |
Compares a user's entry against a constant value, against the value of another control (using a comparison operator such as less than, equal, or greater than), or for a specific data type |
|
Range Checking |
The RangeValidator Control |
Checks that a user's entry is between specified lower and upper boundaries. You can check ranges within pairs of numbers, alphabetic characters, and dates |
|
Pattern matching
|
The RegularExpressionValidator Control |
Checks that the entry matches a pattern defined by a regular expression. This type of validation enables you to check for predictable sequences of characters, such as those in e-mail addresses, telephone numbers, postal codes, and so on. For details, |
|
User-defined |
The CustomValidator Control |
Checks the user's entry using validation logic that you write yourself. This type of validation enables you to check for values derived at run time |
Courtesy - MSDN– http://msdn2.microsoft.com/en-us/library/bwd43d0x(VS.80).aspx
Input Validation using Regular Expressions
There are several validation routines freely available at http://www.guidancelibrary.com/default.aspx/Home.RegExInputValCode
These routines help defend against most common input related attacks.
For additional information, please visit following links
http://msdn2.microsoft.com/en-us/library/aa302420.aspx
http://www.guidancelibrary.com/