24 Eylül 2008 Çarşamba

OWASP Top Ten 2007 Most Critical Web Application Security Vulnerabilities

A1. Cross Site Scripting Flaws

A2. Injection Flaws

A3. Malicious File Execution

A4. Insecure Direct Object Reference

A5. Cross Site Request Forgery

A6. Information Leakage and Improper Error Handling

A7. Broken Authentication and Session Management

A8. Insecure Cryptographic Storage

A9. Insecure Communications

A10. Failure to Restrict URL Access


Resources

Books
• [ALS1] Alshanetsky, I. “php|architect's Guide to PHP Security”, ISBN 0973862106
• [BAI1] Baier, D., “Developing more secure ASP.NET 2.0 Applications”, ISBN 978-0-7356-2331-6
• [GAL1] Gallagher T., Landauer L., Jeffries B., "Hunting Security Bugs", Microsoft Press, ISBN 073562187X
• [GRO1] Fogie, Grossman, Hansen, Rager, “Cross Site Scripting Attacks: XSS Exploits and Defense”, ISBN 1597491543
• [HOW1] Howard M., Lipner S., "The Security Development Lifecycle", Microsoft Press, ISBN 0735622140
• [SCH1 Schneier B., “Practical Cryptography”, Wiley, ISBN 047122894X
• [SHI1] Shiflett, C., “Essential PHP Security”, ISBN 059600656X
• [WYS1] Wysopal et al, The Art of Software Security Testing: Identifying Software Security Flaws, ISBN 0321304861

Web Sites

• OWASP, http://www.owasp.org

• MITRE, Common Weakness Enumeration – Vulnerability Trends, http://cwe.mitre.org/documents/vuln-trends.html

• Web Application Security Consortium, http://www.webappsec.org

• SANS Top 20, http://www.sans.org/top20/

• PCI Security Standards Council, publishers of the PCI standards, relevant to all organizations processing or holding credit card data, https://www.pcisecuritystandards.org/

• PCI DSS v1.1, https://www.pcisecuritystandards.org/pdfs/pci_dss_v1-1.pdf

• Build Security In, US CERT, https://buildsecurityin.us-cert.gov/daisy/bsi/home.html

• The Microsoft Source Code Analyzer for SQL Injection tool is available to find SQL injection vulnerabilities in ASP code http://support.microsoft.com/kb/954476

• Application Architecture for .NET: Designing Applications and Services http://msdn.microsoft.com/en-us/library/ms978357.aspx

• ASP.NET Security Architecture http://msdn.microsoft.com/en-us/library/yedba920.aspx

• Building Secure ASP.NET Applications: Authentication, Authorization, and Secure Communication http://msdn.microsoft.com/en-us/library/aa302415.aspx

• .NET Security for Architects http://www.owasp.org/index.php/.NET_Security_for_Architects

• .NET Security for Developers http://www.owasp.org/index.php/.NET_Security_for_Developers

Failure to Restrict URL Access

Definition:

Frequently, the only protection for a URL is that links to that page are not presented to unauthorized users. However, a motivated, skilled, or just plain lucky attacker may be able to find and access these pages, invoke functions, and view data. Security by obscurity is not sufficient to protect sensitive functions and data in an application. Access control checks must be performed before a request to a sensitive function is granted, which ensures that the user is authorized to access that function.

Protection:

Taking the time to plan authorization by creating a matrix to map the roles and functions of the application is a key step in achieving protection against unrestricted URL access. Web applications must enforce access control on every URL and business function.

It is not sufficient to put access control into the presentation layer and leave the business logic unprotected.

It is also not sufficient to check once during the process to ensure the user is authorized, and then not check again on subsequent steps. Otherwise, an attacker can simply skip the step where authorization is checked, and forge the parameter values necessary to continue on at the next step.

Enabling URL access control takes some careful planning. Among the most important considerations are:

• Ensure the access control matrix is part of the business, architecture, and design of the application.

• Ensure that all URLs and business functions are protected by an effective access control mechanism that verifies the user’s role and entitlements prior to any processing taking place. Make sure this is done during every step of the way, not just once towards the beginning of any multi-step process.

• Perform a penetration test prior to deployment or code delivery to ensure that the application cannot be misused by a motivated skilled attacker.

• Do not assume that users will be unaware of special or hidden URLs or APIs. Always ensure that administrative and high privilege actions are protected.

• An administrator will have a menu with an URL /admin, A non-admin user can enter the URL manually but you will not allow access.

.Net Overview:
Web application contains code that requires more permissions than are granted by a particular ASP.NET trust level, the easiest option is customizing a policy file to grant the additional code access security permission to your Web application.

securityPolicy>
trustLevel name="Custom" policyFile="web_yourtrust.config"/>
. . .
/securityPolicy>

We annotate any strong named assembly with AllowPartiallyTrustedCallersAttribute to support partial-trust callers. This suppresses an implicit link demand for full trust made by the .NET Framework whenever code from a strong named assembly is loaded and JIT-compiled.

[assembly:AllowPartiallyTrustedCallersAttribute()]

For more information read the article.
http://msdn.microsoft.com/en-us/library/aa302425.aspx

Insecure Communications

Definition:

Applications frequently fail to encrypt network traffic when it is necessary to protect sensitive communications. Encryption (usually SSL) must be used for all authenticated connections, especially Internet-accessible web pages, but backend connections as well. Otherwise, the application will expose an authentication or session token. In addition, encryption should be used whenever sensitive data, such as credit card or health information is transmitted. Applications that fall back or can be forced out of an encrypting mode can be abused by attackers.

The PCI standard requires that all credit card information being transmitted over the internet be encrypted.

Having a strong server configuration standard is critical to a secure web application. These servers have many configuration options that affect security and are not secure out of the box.

Protection:

The most important protection is to use SSL on any authenticated connection or whenever sensitive data is being transmitted. There are a number of details involved with configuring SSL for web applications properly, so understanding and analyzing your environment is important. For example, IE 7.0 provides a green bar for high trust SSL certificates, but this is not a suitable control to prove safe use of cryptography alone.

• Use SSL for all connections that are authenticated or transmitting sensitive or value data, such as credentials, credit card details, health and other private information.

• Ensure that communications between infrastructure elements, such as between web servers and database systems, are appropriately protected via the use of transport layer security or protocol level encryption for credentials and intrinsic value data.

• When using SSL, do session encryption for the entire session. Only protecting the logon credentials is insufficient because data and session information must be encrypted too.

• Under PCI Data Security Standard requirement 4, you must protect cardholder data in transit. PCI DSS compliance is mandatory by 2008 for merchants and anyone else dealing with credit cards. In general, client, partner, staff and administrative online access to systems must be encrypted using SSL or similar.

.Net Overview:
We use SSL for necessary places. Our daha in public area is always encrypted. We protect our applications for “Man in the middle” attacks.

Insecure Cryptographic Storage

Definition:

Web applications frequently use cryptographic functions to protect information and credentials. These functions and the code to integrate them have proven difficult to code properly, frequently resulting in weak protection.

Protecting sensitive data with cryptography has become a key part of most web applications. Simply failing to encrypt sensitive data is very widespread. Applications that do encrypt frequently contain poorly designed cryptography, either using inappropriate ciphers or making serious mistakes using strong ciphers. These flaws can lead to disclosure of sensitive data and compliance violations.

Protection:

The most important aspect is to ensure that everything that should be encrypted is actually encrypted. Then you must ensure that the cryptography is implemented properly. As there are so many ways of using cryptography improperly, the following recommendations should be taken as part of your testing regime to help ensure secure cryptographic materials handling:

• Do not create cryptographic algorithms. Only use approved public algorithms such as AES, RSA public key cryptography, and SHA-256 or better for hashing.

• Do not use weak algorithms, such as MD5 / SHA1. Favor safer alternatives, such as SHA-256 or better.

• Generate keys offline and store private keys with extreme care. Never transmit private keys over insecure channels.

• Ensure that infrastructure credentials such as database credentials or MQ queue access details are properly secured (via tight file system permissions and controls), or securely encrypted and not easily decrypted by local or remote users

• Hashing is not encryption. If an attacker knows what hashing algorithm is being used, he can do a brute-force attack to crack the hash value.

• Ensure that encrypted data stored on disk is not easy to decrypt. For example, database encryption is worthless if the database connection pool provides unencrypted access.

• Under PCI Data Security Standard requirement 3, you must protect cardholder data. PCI DSS compliance is mandatory by 2008 for merchants and anyone else dealing with credit cards. Good practice is to never store unnecessary data, such as the magnetic stripe information or the primary account number (PAN, otherwise known as the credit card number). If you store the PAN, the DSS compliance requirements are significant. For example, you are NEVER allowed to store the CVV number (the three digit number on the rear of the card) under any circumstances. For more information, please see the PCI DSS Guidelines and implement controls as necessary.

.Net Overview:
Cryptography itself is not that difficult to work with, but it is important to decide which algorithm to use. .Net framewokr has many Crypto classes. We mostly use these classes for diffrent senarios.

We do not chose MD5 or SHA1 for hashing since we learn that they are insecure.

We also have a low level coded dll for 3DES encrpytion. It is not a .Net dll. We use it for high performence business. It is faster than .Net classes.

Classes available for symmetric encryption. All classes inherit from SymmetricAlgorithm
Algorithm Cryptographic class Description
DES DESCryptoServiceProvider Wrapper class to access the standard CSP for the Data Encryption Standard (DES) algorithm
RC2 RC2CryptoServiceProvider Wrapper class to access the standard CSP for the RC2 algorithm
Rijndael RijndaelManaged Wrapper class to access the standard CSP for the Rijndael algorithm. The CSP is made of managed code.
TripleDES TripleDESCryptoServiceProvider Wrapper class to access the standard CSP for the Triple DES algorithm

Classes available for asymmetric encryption. All classes inherit from AsymmetricAlgorithm.
Algorithm Cryptographic class Description
DSA DSACryptoServiceProvider Wrapper class to access the standard CSP for the Digital Signature Algorithm (DSA) algorithm.
RSA RSACryptoServiceProvider Wrapper class to access the standard CSP for the RSA algorithm.

Classes available for hash functions.
Algorithm Cryptographic class Description
MD5 MD5CryptoServiceProvider Computes the MD5 hash for the input data using the implementation provided by the CSP.
SHA1 SHA1CryptoServiceProvider, SHA1Managed The classes compute the SHA1 hash for the input data using the implementation provided by the CSP. The former class uses unmanaged code; the latter is based on managed code.
SHA256 SHA256Managed Computes the SHA256 hash for the input data using managed code.
SHA384 SHA384Managed Computes the SHA384 hash for the input data using managed code.
SHA512 SHA512Managed Computes the SHA512 hash for the input data using managed code.

RijndaelManaged crypto = new RijndaelManaged();
byte[] Key = {...};
byte[] IV = {...};
ICryptoTransform trans = crypto.CreateEncryptor(Key, IV);


And our connection strings are encrypted in web.config. We use manual encryption and decryption in some senarios. And encrypt using machine Keys (RSA Keys) if posibbly.

configProtectedData>
providers>
add keyContainerName="CustomKeys"
useMachineContainer="true"
name="CustomProvider"
type="System.Configuration.RsaProtectedConfigurationPr
ovider, System.Configuration, Version=2.0.0.0,
Cultural=neutral,
PublicKeyToken=b03f5f7f11d50a3a"/>
/providers>
/configProtectedData>

Broken Authentication and Session Management

Definition:

Proper authentication and session management is critical to web application security. Flaws in this area most frequently involve the failure to protect credentials and session tokens through their lifecycle. These flaws can lead to the hijacking of user or administrative accounts, undermine authorization and accountability controls, and cause privacy violations.

Protection:

Authentication relies on secure communication and credential storage. First ensure that SSL is the only option for all authenticated parts of the application and that all credentials are stored in
hashed or encrypted form.

Preventing authentication flaws takes careful planning. Among the most important considerations are:

• One of the most important things to implement is a decent audit logging for authentication and authorization controls. You must be able to answer the following questions easily:
o Who logged on?
o When?
o From where?
o What transactions did the user start?
o What data was accessed?

• Only use the inbuilt session management mechanism. Do not write or use secondary session handlers under any circumstances.

• Do not accept new, preset or invalid session identifiers from the URL or in the request. This is called a session fixation attack

• Limit or rid your code of custom cookies for authentication or session management purposes, such as “remember me” type functionality or home grown single-sign on functionality. This does not apply to robust, well proven SSO or federated authentication solutions. Use the session management of the application server.

• Use a single authentication mechanism with appropriate strength and number of factors. Make sure that this mechanism is not easily subjected to spoofing or replay attacks. Do not make this mechanism overly complex, which then may become subject to its own attack.

• Implement a strong password policy when allowing passwords. A strong password policy will prevent easy to guess passwords like words from a dictionary, but will also require account lockout when guessing passwords and more. This can be implemented using JAAS, but is now a feature in most application servers. See reference Informit01.

• Do not allow the login process to start from an unencrypted page. Always start the login process from a second, encrypted page with a fresh or new session token to prevent credential or session stealing, phishing attacks and session fixation attacks.

• Ensure that every page has a logout link. Logout should destroy all server side session state and client side cookies. Consider human factors: do not ask for confirmation as users will end up just closing the tab or window rather than logging out successfully.

• Use a timeout period that automatically logs out an inactive session as per the value of the data being protected (shorter is always better)

• Use only strong ancillary authentication functions (questions and answers, password reset) as these are credentials in the same way usernames and passwords or tokens are credentials. Apply a one-way hash to answers to prevent disclosure attacks.

• Require the user to enter the old password when the user changes to a new password

• Do not rely upon spoofable credentials as the sole form of authentication, such as IP addresses or address range masks, DNS or reverse DNS lookups, referrer headers or similar…

• Be careful of sending secrets to registered e-mail addresses as a mechanism for password resets. Use limited-time-only random numbers to reset access and send a follow up e-mail as soon as the password has been reset. Be careful of allowing self-registered users changingtheir e-mail address – send a message to the previous e-mail address before enacting the change

.Net Overview:
We set the session timeout and never live it default. We abandon sessions as soon as possinble after their job finished. Short period of session usage is the first step.

And we never put importent daha in session. We use a careful logic.

We also do not use “Remember me?” Because it makes applications vulnarable to attackes from every body who are close to the computer application running. Even they are not hacker every body can do something unwanted.

Information Leakage and Improper Error Handling

Definition:

Applications can unintentionally leak information about their configuration, internal workings, or violate privacy through a variety of application problems. Applications can also leak internal state via how long they take to process certain operations or via different responses to differing inputs, such as displaying the same error text with different error numbers. Web applications will often leak information about their internal state through detailed or debug error messages. Often, this information can be leveraged to launch or even automate more powerful attacks.

Error conditions that occur during normal operation are not handled properly. If an attacker can cause errors to occur that the web application does not handle, they can gain detailed system information, deny service, cause security mechanisms to fail, or crash the server.

Protection:

Developers should use tools like OWASP's WebScarab to try to make their application generate errors. Applications that have not been tested in this way will almost certainly generate unexpected error output.

Applications should also include a standard exception handling architecture to prevent unwanted information from leaking to attacker.

Preventing information leakage requires discipline. The following practices have proven effective:

• Ensure that the entire software development team shares a common approach to exception handling.

• Disable or limit detailed error handling. In particular, do not display debug information to end users, stack traces, or path information.

• Ensure that secure paths that have multiple outcomes return similar or identical error messages in roughly the same time.

• Various layers may return fatal or exceptional results, such as the database layer, the underlying web server (IIS, Apache, etc). It is vital that errors from all layers are adequately checked and configured to prevent error messages from being exploited by intruders.

• Be aware that common frameworks return different HTTP error codes depending on if the error is within your custom code or within the framework’s code. It is worthwhile creating a default error handler which returns an appropriately sanitized error message for most users in production for all error paths.

• Overriding the default error handler so that it always returns “200” (OK) error screens reduces the ability of automated scanning tools from determining if a serious error occurred. While this is “security through obscurity,” it can provide an extra layer of defense.

• Some larger organizations have chosen to include random / unique error codes amongst all their applications. This can assist the help desk with finding the correct solution for a particular error, but it may also allow attackers to determine exactly which path an application failed.

• Always give the error message that “The username/password is not correct” instead of “The password is not correct” for failed logins.

.Net Overview:
On .Net we set the web.config’s customErrors mode attirubute to RemoteOnly and redirect to an custom error page for all errors. We do not show any custom error message. Becuse we know it is a clue for the attacker.

configuration>
customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
error statusCode="403" redirect="NoAccess.htm" />
error statusCode="404" redirect="FileNotFound.htm" />
/customErrors>
/configuration>

We catch the application error and inform ourself via logging exeption message but we never inform users. We give general exception message like “Sorry we have a problem. We are going to fix this as soon as possible…”

protected void Application_Error(Object sender, EventArgs e)
{
HttpContext ctx = HttpContext.Current;
Exception ex = ctx.Server.GetLastError().InnerException;

// ex.Message to inform yourself not users or attackers…
}

Cross Site Request Forgery

Definition:

Cross site request forgery is not a new attack, but is simple and devastating. A CSRF attack forces a logged-on victim’s browser to send a request to a vulnerable web application, which then performs the chosen action on behalf of the victim.

This vulnerability is extremely widespread, as any web application that Has no authorization checks for vulnerable actions Will process an action if a default login is able to be given in the request (e.g. http://www.example.com/admin/doSomething.ctl?username=admin&passwd=admin)

Authorizes requests based only on credentials that are automatically submitted such as the session cookie if currently logged into the application, or “Remember me” functionality if not logged into the application, or a Kerberos token if part of an Intranet participating in integrated logon with Active Directory is at risk.

Unfortunately, today, most web applications rely solely on automatically submitted credentials such as session cookies, basic authentication credentials, source IP addresses, SSL certificates, or Windows domain credentials.

This vulnerability is also known by several other names including Session Riding, One-Click Attacks, Cross Site Reference Forgery, Hostile Linking, and Automation Attack. The acronym XSRF is also frequently used. OWASP and MITRE have both standardized on the term Cross Site Request Forgery and CSRF.

Protection:

Applications must ensure that they are not relying on credentials or tokens that are automatically submitted by browsers. The only solution is to use a custom token that the browser will not ‘remember’ like a unique hidden field or an additional unique GET/POST parameter and then automatically include this token with every request to the web application. A CSRF attack that does not use this token will be stopped.

The following strategies should be inherent in all web applications:

• Insert custom random tokens into every form and URL that will not be automatically submitted by the browser. and then verify that the submitted token is correct for the current user.

• For sensitive data or value transactions, re-authenticate or use transaction signing to ensure that the request is genuine. Set up external mechanisms such as e-mail or phone contact in order to verify requests or notify the user of the request.

• Do not use GET requests (URLs) for sensitive data or to perform value transactions. Use only POST methods when processing sensitive data from the user. POST alone is insufficient as a protection. You must also combine it with random tokens, out of band authentication or re-authentication to properly protect against CSRF.

• Verify the Content-Type to protect calls to Ajax functions and web services

While these suggestions will diminish your exposure dramatically, advanced CSRF attacks can bypass many of these restrictions. The strongest technique is the use of unique tokens, and eliminating all XSS vulnerabilities in your application.


.Net Overview:
We check that incoming requests have a Referer header referencing our domain.
And we put a user-specific token as a hidden field in legitimate forms, and check that the right value was submitted. Generally the user specific values are GUIDs.

Insecure Direct Object Reference

Definition:

A direct object reference occurs when a developer exposes a reference to an internal implementation object, such as a file, directory, database record, or key, as a URL or form parameter. An attacker can manipulate direct object references to access other objects without authorization, unless an access control check is in place.

For example, in Internet Banking applications, it is common to use the account number as the primary key. Therefore, it is tempting to use the account number directly in the web interface. Even if the developers have used parameterized SQL queries to prevent SQL injection, if there is no extra check that the user is the account holder and authorized to see the account, an attacker tampering with the account number parameter can see or change all accounts.

Protection:

The best protection is to avoid exposing direct object references to users by using an index, indirect reference map, or other indirect method that is easy to validate. If a direct object reference must be used, ensure that the user is authorized before using it.

Establishing a standard way of referring to application objects is important:

• Avoid exposing private object references to users whenever possible, such as primary keys or filenames.

• Validate any private object references extensively with an "accept known good" approach.

• Verify authorization to all referenced objects.

• Make sure that input does not contain attack patterns like ../ or

If you must expose direct references to database structures, ensure that SQL statements and other database access methods only allow authorized records to be shown:

Another solution is to check the integrity of parameters to verify that parameters are not changed. This integrity check can be added as an additional parameter using encryption or hashing techniques. We can add salt to the parameter and hash the total than check it before using so it can not work if changed.

.Net Overview:
We use Tamper-Proof Link generation methods. We do not allow users to change querystrings. If they change query strings some value they get an error page.

For more information read this articles
http://aspnet.4guysfromrolla.com/articles/083105-1.aspx
http://msdn.microsoft.com/en-us/magazine/cc163462.aspx

Malicious File Execution

Definition:

Malicious file execution vulnerabilities are found in many applications. Developers will often directly use or concatenate potentially hostile input with file or stream functions, or improperly trust input files.

On many platforms, frameworks allow the use of external object references, such as URLs or file system references. When the data is insufficiently checked, this can lead to arbitrary remote and hostile content being included, processed or invoked by the web server.

This allows attackers to perform:
1. Remote code execution when using runtime.exec()
2. Remote root kit installation and complete system compromise when an attacker can upload backdoors
3. Accessing sensitive files like web.xml than contain configuration properties like usernames and passwords for back-end databases

Protection:
Preventing remote file include flaws takes some careful planning at the architectural and design phases, through to thorough testing.

In general, a well-written application will not use user-supplied input in any filename for any server-based resource (such as images, XML and XSL transform documents, or script inclusions), and will have firewall rules in place preventing new outbound connections to the Internet or internally back to any other server.

However, many legacy applications will continue to have a need to accept user supplied input.
Among the most important considerations are:

• Use an indirect object reference map Where a partial filename was once used, consider a hash of the partial reference.

Instead of
select name=”language”>


Use
select name=”language”>


• Consider using salts to prevent brute forcing of the indirect object reference. Alternatively, just use index values such as 1, 2, 3, and ensure that the array bounds are checked to detect parameter tampering.

• Add firewall rules to prevent web servers making new connections to external web sites and internal systems. For high value systems, isolate the web server in its own VLAN or private subnet

• Check user supplied files or filenames cannot obviate other controls, such as tainting data in the session object, avatars and images, PDF reports, temporary files, and so on

.Net Overview:
Refer to the documentation on partial trust, and design your applications to be segmented in trust, so that most of the application exists in the lowest possible trust state possible.

For more information check Microsoft’s site.

http://msdn.microsoft.com/en-us/library/ms364059(VS.80).aspx
http://msdn.microsoft.com/en-us/library/3ak841sy(VS.80).aspx

Injection Flaws

Definition:

Injection occurs when user-supplied data is sent to an interpreter as part of a command or a particular query. Attackers trick the interpreter into executing unintended commands via supplying specially crafted data.

Injection flaws allow attackers to create, read, update, or delete any arbitrary data available to the application. In the worst case scenario, these flaws allow an attacker to completely compromise the application and the underlying systems, even bypassing deeply nested firewalled environments.

Web applications pass parameters when they access external systems or the local operating system. If an attacker can embed malicious commands in these parameters, the external system may execute those commands on behalf of the web application.

Protection:

Avoid the use of interpreters when possible. If you must invoke an interpreter, the key method to avoid injections is the use of safe APIs, such as strongly typed parameterized queries and object relational mapping (ORM) libraries like Hibernate, LLBLGEN.

These interfaces handle all data escaping, or do not require escaping. Note that while safe interfaces solve the problem, validation is still recommended in order to detect attacks. Using interpreters is dangerous, so it's worth it to take extra care.

• Input validation is a key for secure applications. In all topics you should consider INPUT VALIDATION. Use an "accept known good" validation strategy.

• Use strongly typed parameterized query APIs with placeholder substitution markers, even when calling stored procedures.

• Enforce least privilege when connecting to databases and other backend systems

• Avoid detailed error messages that are useful to an attacker. Don’t forget that attacker accumulate clues from your error messages.

.Net Overview:
As we mention above input validation is very important. Validation has two side server and client. Even you have scripts that validates input on client side, you can not trust the value. You have to check it with Regex class on server side. Because somebody can by pass your client side validation.

if ( !Regex.IsMatch(userIDTxt.Text, @"^[a-zA-Z'./s]{1,40}$"))
throw new FormatException("Invalid name format");

All of your ADO.Net work must be parameterized.

myCommand.SelectCommand.Parameters.Add("@au_id", SqlDbType.VarChar, 11);

To protect your application from SQL injection, perform the following steps:

• Constrain input.
• Use parameters with stored procedures.
• Use parameters with dynamic SQL.

http://msdn.microsoft.com/en-us/library/ms998271.aspx

Cross Site Scripting Flaws

Definition:

Cross-site scripting, better known as XSS, is in fact a subset of HTML injection. XSS is the most prevalent and pernicious web application security issue. XSS flaws occur whenever an application takes data that originated from a user and sends it to a web browser without first validating or encoding that content.

XSS allows attackers to execute scripts in the victim’s browser, which can hijack user sessions, deface web sites, insert hostile content, conduct phishing attacks, and take over the user’s browser using scripting malware. The malicious script is usually JavaScript, but any scripting language supported by the victim’s browser is a potential target for this attack.

The web application can be used as a mechanism to transport an attack to an end user's browser. A successful attack can disclose the end user’s session token, attack the local machine or spoof content to fool the user.

Protection:
The best protection for XSS is a combination of "white list" validation of all incoming data and appropriate encoding of all output data. Validation allows the detection of attacks, and encoding prevents any successful script injection from running in the browser.

Preventing XSS across an entire application requires a consistent architectural approach:

• Use a standard input validation mechanism to validate all input data for length, type, syntax, and business rules before accepting the data to be displayed or stored. Reject invalid input rather than attempting to sanitize potentially hostile data.

• Ensure that all user-supplied data is appropriately entity encoded (either HTML or XML depending on the output mechanism) before rendering, taking the approach to encode all characters other than a very limited subset.

• Specify the output encoding (such as ISO 8859-1 or UTF 8). Do not allow the attacker to choose this for your users .

• Do not use "blacklist" validation to detect XSS in input or to encode output. Searching for and replacing just a few characters ("<" ">" and other similar characters or phrases such as “script”) is weak and has been attacked successfully.

• Make sure that your application does not decode the same input twice. Such errors could be used to bypass white list schemes by introducing dangerous inputs after they have been checked


.Net Overview:
By default, ASP.NET versions 1.1 and 2.0 request validation detects any HTML elements and reserved characters in data posted to the server. This helps prevent users from inserting script into your application. Request validation checks all input data against a hard-coded list of potentially dangerous values. If a match occurs, it throws an exception of type HttpRequestValidationException.

[ConfigurationPropertyAttribute("validateRequest", DefaultValue = true)]
public bool ValidateRequest { get; set; }

You can set request validation from web.config file for all pages in application.


This property avoids most of attacks, but you should consider more.

Potentially Dangerous HTML Tags
While not an exhaustive list, the following commonly used HTML tags could allow a malicious user to inject script code:


applet>
body>
embed>
frame>
script>
frameset>
html>
iframe>
img>
style>
layer>
link>
ilayer>
meta>
object>


An attacker can use HTML attributes such as src, lowsrc, style, and href in conjunction with the preceding tags to inject cross-site scripting. For example, the src attribute of the tag can be a source of injection.

To prevent cross-site scripting in .NET Web Applications, perform the following steps:

1. Check That ASP.NET Request Validation Is Enabled
2. Review ASP.NET Code That Generates HTML Output
3. Determine Whether HTML Output Includes Input Parameters
4. Review Potentially Dangerous HTML Tags and Attributes
5. Evaluate Countermeasures

More information: http://msdn.microsoft.com/en-us/library/ms998274.aspx

23 Eylül 2008 Salı

Rules of Developing Secure Applications

INTRODUCTION

Document is based on OWASP (Open Web application Security Project) technology standarts.

The Open Web Application Security Project (OWASP) is a worldwide free and open community focused on improving the security of application software. Their mission is to make application security "visible," so that people and organizations can make informed decisions about application security risks.
(www.owasp.org)

Document also considers Payment Card Industry (PCI) Payment Application Data Security Standards (PA - DSS).

PA-DSS is the Council-managed program formerly under the supervision of the Visa Inc. program known as the Payment Application Best Practices (PABP). The goal of PA-DSS is to help software vendors and others develop secure payment applications that do not store prohibited data, such as full magnetic stripe, CVV2 or PIN data, and ensure their payment applications support compliance with the PCI DSS.
(https://www.pcisecuritystandards.org/security_standards/pa_dss.shtml)

After explanations of OWASP Top Ten 2007 and how we take care about it. On resource section you will find articles and some books about application security.

Documents text is a summary from wikipedia.

Before you start to read I would like to remind that;

Security is not a one-time event.

A secure coding initiative must deal with all stages of a program’s lifecycle.


Payment Card Industry (PCI) Data Security Standard
Build and Maintain a Secure Network
Requirement 1:
Install and maintain a firewall configuration to protect cardholder data
Requirement 2:
Do not use vendor-supplied defaults for system passwords and other security parameters

Protect Cardholder Data
Requirement 3:
Protect stored cardholder data
Requirement 4:
Encrypt transmission of cardholder data across open, public networks

Maintain a Vulnerability Management Program
Requirement 5:
Use and regularly update anti-virus software
Requirement 6:
Develop and maintain secure systems and applications

Implement Strong Access Control Measures
Requirement 7:
Restrict access to cardholder data by business need-to-know
Requirement 8:
Assign a unique ID to each person with computer access
Requirement 9:
Restrict physical access to cardholder data

Regularly Monitor and Test Networks
Requirement 10:
Track and monitor all access to network resources and cardholder data
Requirement 11:
Regularly test security systems and processes

Maintain an Information Security Policy
Requirement 12:
Maintain a policy that addresses information security