Showing posts with label Secure Coding. Show all posts
Showing posts with label Secure Coding. Show all posts

Sunday, February 06, 2011

7 Security tips for secure coding your HTML 5 applications

Since the release of HTML 5 standard is expected in 2011, it is important to prepare for the potential impacts on security due the adoption of HTML 5. Currently, we can review the working draft from W3C and start looking at this standard from the secure coding perspective and specifically on how to write secure HTML 5 software. Since this blog is dedicated to software security, I thought I should try to put out a list of top security concerns that need to be addressed when coding applications in HTML 5. Herein included is my top 7 list of software security best practices that need to be addressed when coding HTML 5 applications:

1) Be careful when using cross domain messaging features
HTML 5 APIs allow to process messages from an origin that is different from the one of the application processing the message. You should check the origin of the domain of the message to validate that can be trusted such as by whitelisting the domain (accept only request from trusted domains and rejects the others). Specifically, when using HTML 5.0 APIs such as PostMessage(), check the dom-MessageEvent-origin attribute before accepting the request.

2) Always validate input and filter malicious input before using HTML 5.0 APIs.
You should validate data input before you process any messages of HTML 5.0  APIs such as the PostMessage() API. Input validation should be done at a minimum, on the server side since client side validation can be potentially bypassed with a web proxy. . If you are using client side SQL such as WebSQL (like Google gears for example) you should filter data for any SQL injection attack vectors and use prepared SQL statements. 

3) Make sure that the use of any offline-local storage is secure
Whenever possible, do not store any confidential or sensitive data in the offline-local storage, if you do, make sure you encrypt the data. If you do encrypt the data in the offline-local storage, do not store any encryption keys on the client rather, use the server to encrypt this data on demand. Make sure the encryption key is tied to the user's session and to the device that is storing it. Beware that HTML 5 offline applications are vulnerable to cache and cache poisoning hence validate the data before putting anything in offline/local storage. If should also consider to restrict the use of offline/local storage as requirement of your HTML 5.0 security coding standards is possible. Consider that right now (Jan 2011), offline-local storage is not supported by IE browsers, only by Google Chrome, Safari, Firefox and the beta of the Opera browsers.

4) Secure code review HTML 5 code and the coding of HTML 5 tags, attributes and CSS.
You should update your secure code analysis rules to include security checks for special HTML coding attributes and HTML 5.0 tags. Some of HTML 5 tags attributes for example can be potentially be injected JavaScript (JS). You should made a requirement to source code review these new HTML 5 tags for security to make sure any JS input is validated. A new version of HTML 5 CSS also might allow an attacker to control display elements via JS injection. HTML 5 source code with tags, attributes and HTML 5 CSS files should be considered in scope for source code reviews before deployment.

5) Consider to restrict or ban the use of HTLM 5.0 websocket API.
HTML 5.0 websocket API provide a network communication stack to the browser that can be used for backdoors. You should check with your security team whether the use of web sockets is allowed by your organization information security policies and application security standards.

6) Make sure your company legal approve any use of geolocation API.
Consider the impact of privacy when using geolocation APIs to make sure the use is allowed and compliant by your company legal-privacy laws/regulations. The use of geolocation might have privacy impacts, hence should be reviewed to be in compliance with privacy policies that might include notify the user when these APIs are deployed as part of your application.

7) Leverage the security of sandboxing iFrame attributes
One of the HTML 5  features is the sandboxing attribute for iFrame that enables a set of extra restrictions on any content hosted by the iFrame. When this is attribute is set, the content is treated as being from a unique origin, forms and scripts are disabled and links are prevented from targeting other browsing contexts and plug-ins are disabled. Ian Hickson, the editor of the HTML 5 has a post on what the sandbox is good for. You should consider updating your organization's secure coding standards to cover how to code securely applications that leverage the HTML 5.0 sandbox attribute for IFrames.

Tuesday, March 31, 2009

OWASP Releases World’s First Security Code Review Guide for Free

The OWASP Foundation, March 30, 2009 – The Open Web Application Security Project (OWASP) today announced the official release of the free OWASP Security Code Review Guide v1.1. The Code Review Guide provides details on how to review code for all sorts of application vulnerabilities. Together with the OWASP Security Developer Guide and OWASP Security Testing Guide, OWASP has created a powerful suite of books that covers most of what people need to know about application security. The 216 page book can be downloaded from the OWASP website or a bound copy can be ordered for the cost of printing.

The Code Review Project is led by long time OWASP participant Eoin Keary from Dublin, Ireland. Like all OWASP projects, the work is performed by Eoin’s team in a free and open manner, and coordinated via the OWASP wiki and project mailing list. Everyone is welcome to download the guide and benefit from OWASP’s research. You can also join the project and contribute to making the guide even better.

“Despite the many claims that code review is too expensive or time consuming, there is no question that it is the fastest and most accurate way to find and diagnose many security problems. There are also dozens of serious security problems that simply can't be found any other way.” said OWASP Chair Jeff Williams. “Still, code review is no panacea. Static tools, dynamic tools, and manual testing all have an important role to play in verifying the security of an application.”

There is overwhelming evidence that the vast majority of web applications contain security holes that are increasingly putting people and organizations at serious risk. Our Code Review Guide is one part of OWASP’s strategy to make application security visible and enable the market to support the development of secure application software.

OWASP is a free and open community that focuses on improving application security. Join the thousands of organizations that are using OWASP guidance to run a responsible application security program. Anyone can join our community and use our free tools and documents, attend our free conferences and local chapter meetings, and join projects to make the world’s software safe for the Internet.

About OWASP -The Open Web Application Security Project (OWASP) is an open community dedicated to enabling organizations to develop, purchase, and maintain applications that can be trusted. All of the OWASP tools, documents, forums, and chapters are free and open to anyone interested in improving application security. We advocate approaching application security as a people, process, and technology problem because the most effective approaches to application security include improvements in all of these areas. We can be found at http://www.owasp.org.

Saturday, March 28, 2009

Insecure Implementations Of Challenge Question Answers (CQA) For Password Resets

An example of C/Q
setup for on-line banking
Challenge Questions Answer (CQA)are widely used in web sites as a form to validate the user during un-authenticated transactions such as password resets, user name resets as well as extra authentication factor besides passwords during logins. The problem with CQA is the degree of freedom given to the implementation leaves a lot of room to deliver in-secure validation. Some of you might be familiar for example with the Gov. Sarah Palin's yahoo email hack via yahoo email password reset. It was due because yahoo email reset validate users with questions that can be easily guessed from public profiles such as birthday, country of residence and postal code. This is from implementation. Gov Palin as any user of yahoo email is allowed to select easy questions among a list, such as "Where did you first meet your spouse". This, again is implementation problem, for a public person like she is (but this applies also to users of Facebook and social sites) the answer to that question could be easily guessed (Wasilla high). The other control on yahoo email reset is to validate a secondary email address associated with the account for which hints are given. Apparently this was not set up. The attack that was highly publicized that time simply highlights that even companies like yahoo still do not get how to get email password reset securely implemented.

This example underlines a problem of 1) user awareness on which CQA to choose, 2) Force user to choose CQA that are not easy to guess, for example asking DOB (date of birth) besides being considered Personal Identifiable Information is a bad question where asking a user to choose a date that is memorable may be better. The concept that CQA need to learn also is the one of entropy that is not easily guessable with different means, besides by public profile searches is also by the length of the question that at minimum has to be of a certain number of characters. In this context if my favorite town is New Your City, NYC cannot be entered because three letter city names are not allowed.

In the case of financial web applications, good secret questions are the ones that require specific shared knowledge between the user and the authenticator such as shared knowledge of events (e.g. the last time you make a payment) or specific knowledge of data (e.g. the exact amount of customer's monthly mortgage payment).
To improve entropy of the shared secret, you can prompt the user to answer different shared secrets by randomly choosing them from a previously set of pre-registered answer/questions.

The mortgage question that is not usually deducted from public records (obviously does not include dumpster diving) is better than a question such as most favorite movie or soccer team, or the high school where you dated your husband/wife. But also this is not immune from attacks a typical Monday morning dumpster dive may reveal the others or a simple call to the mark with a refinance question to capture in your example the "monthly" mortgage payment.

The emphasis I am making is that the CQA have to be shared secrets between the authenticator and the authenticatee. An example can be to validate time and information data that is shared secret between the user and the Bank such as when you visited the ATM and how much money you withdrew. Of course these requires query data sources and are not easy to implement.

Ideally web site architects that implement this controls they need to be guided on how to implement CQA securely in the application uses cases of password and userID reset as well as a form of "extra" factor of authentication besides passwords. The concept of what constitutes a good non-guessable CQA should be covered as well as how to implement the password reset security.

A good guideline for implementation of CQA is OWASP Using Secret Questions Page

You can also test if you password reset is done security by looking at the password reset section of the OWASP testing guide.

For example once you had the password rest after CQA validation, a good practice is to deliver the one time temporary password out of band to the user with a different channel such as SMS. This will allow for identification of the user via a call back and also another layer of defense against someone attacking the email channel during the outbound password delivery such as in the case of Man In The Middle Attacks.

In the case when CQA are not pre-registred such as in the case of validation of question based upon demographic information that is known about a user from Knowledge Based Authentication system, ideally you want to consider this only to validate low risk application function since the degree of security of these questions is one notch lower then CAQ based upon shared secrets and two notch lower than passwords. This is to consider also in user validations that fall back to KBA from failing to validate a password at login as security expert Bruce Schneider points out in The Curse of the Secret Question . It would be ok if I am falling back from low risk authentication control such as one that uses IP for authentication to another low risk control such as KBA.

The best use case for using KBA CQA is in the case of a user applying for an on-line account for which no previous information is known about the user. It is better than validate the user with information that is sensitive and can be phished to attack other channels such as for example validating the user with ATM PINs or with PII such as SSN. A KBA with a rich set of CQA such as group of 20-25 questions selected ramndonly is also more difficult to phish than a set of 2,3 CQA (provides better entropy)

Saturday, January 17, 2009

Java Security: Why Not To Use String Objects For Storing Secrets

I participated to an OWASP email thread regarding the security of storing passwords in a JAVA string object vs. a char array.

The initial assumption is that since java String objects are handled by the garbage collection differently than other objects such as for example a char array, storing such passwords in string objects might represent a risk.

The threat scenario is potentially of information disclosure since additional instances of secrets stored with JAVA Strings such as for example passwords, even when are zeroed programmately they might allow the original values recovered from a memory dump.

Therefore when choosing between two method calls:
public Connection createConnection(String userName, String password) throw JMSException
or
public Connection createConnection(String userName, char[] password) throws
JMSException

The latter passes the password as a char array and is more secure then the first that uses a string object. I'll articulate why herein:

Let’s analyze the assumption first and point out the main differences when using char[] vs. using Strings. I would like to cover here first some background (for the non-java experts, I do not consider one myself too so bear with me) and terminology

According to the JAVA both specification all data types, char and String included are objects and the instances in memory of such objects are handled by the JVM and the garbage collector outside the control of the coding logic (different from C/C++ where memory instances can be handled by the programmers)

There are differences thought, in what a programmer can do with JAVA Strings. For example the value of a JAVA String object cannot be changed after has been initialized. If you would like to change a value to a string you need to use StringBuffer. This property of JAVA Strings is loosely defined as Strings being "immutable"

I say, loosely defined because refers to value hold by the object not the instance in memory. I stumbled on this definition myself (thanks Rogan Dawes to fail my assumption and shed the light). I assumed this relates to change the value in memory (that in JAVA is never the case). Indeed there are different flavors of immutability best described by the article herein:

So let's assume immutability in the "strong" sense, that means locking down a piece of data in perpetuity, such as creating an immutable object instance that cannot be changed by any code.

A char array, comparing with a String is mutable because the value assigned to the element can be changed.

For example, in the case of a char array,

char[] str = {‘a’,’b’,’c’};

the following will change the values to 0

for ( int i=0; i< str.length; i++) { str[i] = 0; } In the case of a JAVA String since is immutable, the value cannot be changed. For example, when a new instance is created when changing from uppercase to lower case the contents of the object: String str = “ABC”; str.toLowerCase(); Another example, illustrates the difference when assigning a new value: String str = “Hello”; str=”Goodbye”; The first creates an instance of "Hello" when the second one creates another instance (invoking the constructor of the class) and therefore assigning an object reference to be stored in str. The same will happen when concatenating strings with the + operators such as: String str=”Hello”; str = str + “Dolly”; There is also an additional consideration….(thanks to Rogan Dawes again..)
When using String objects get internalized (saved in an internal cache), which means
that even when you set the variable to null, the actual String object
may never be garbage collected.

Now back to the CreateConnection API examples, passing a password as char array to the API is better because, values of the passwords can be zeroed after used (same for keys and other shared secrets or confidential information) and no extra instances of passwords are left in memory to be garbage collected or cached.

This is also what JAVA recommends such as when using password based encryption:

Therefore, if you need to store passwords, a good reference on how to do it securely using char array instead of Strings it is shown herein;

On the issue about clearing password contents and using char[] instead of strings there is also a thread from Sun Inc herein

Indeed, the use of char[] instead of String is a good idea for security to prevent information disclosure of passwords via memory data access such as in the case of an attack toward information stored in memory such as memory dump caused by a denial of service attack. When handling encryption keys, the requirement to zeroes them is also driven by key management compliance such as FIPS140.

Now, I am still puzzled about this because immutability of Strings was devised by Sun as part of the JAVA security model. In 2001 J Gosling the inventor of JAVA had to say this: (ref http://www.artima.com/intv/gosling313.html)

“One of the things that forced Strings to be immutable was security. You have a file open method. You pass a String to it. And then it's doing all kind of authentication checks before it gets around to doing the OS call. If you manage to do something that effectively mutated the String, after the security check and before the OS call, then boom, you're in. But Strings are immutable, so that kind of attack doesn't work. That precise example is what really demanded that Strings be immutable.”

But there are problems and assumptions. Even in this case the immutability of Strings does not offer security value 100%. See another thread herein
It is actually shown that char[] can be used as a way to write the contents of a String when untrusted code is allowed via the JVM. This is possible by using reflection and by depending on the results of SecurityManager. Because of this, someone also even argued that because of this Strings are not really immutable

Indeed in the summary, please do not use JAVA Strings and use char array instead when storing confidential data, credentials (e.g passwords) and secrets such as encryption keys…

Wednesday, May 28, 2008

XHR, CSRF and bypassing the browser same origin policy

I did a presentation on CSRF for my local OWASP chapter and an interesting question come out about exploiting a CSRF vulnerability while using XMLHttpRequests (these are very popular wih Ajax nowdays..) CSRF vulnerabilities exploit the trust that a site has on the browser. In the case of an authenticated session, since the browser does not resend a NEW SessionID to the application as a proof that each HTTP request is authenticated it allow for riding the session with an interleaved malicious HTTP request (I like this term better actually because you are really riding an authenticated session..).

If I social engineer (phish) a victim forcing him to select a web page (via webmial for example) that has a malicious HTML tag such as iframe with an embedded GET request and if such request is issued (by the victim web page selection) when an authenticated session with the same application is still valid, then such malicious request will processed by the application. Attack of this nature can eventually force a business transaction such as money bank transfer, denial of service via forced logout, modification of shopping cart credentials to force a purchase with a price and address at the choice of a malicious user.

The main root causes of CSRF on the client is the lack of enforcement of the same origin policy. Such policy prevent two different documents loaded on the browser and one potentially being malicious to access each other via javascript. The same origin policy will check that such javascript invocation comes from two different sources and it will deny it. The problem is that such same origin policy does not work for HTML tags: an hacker can embed an URL from untrusted source/domain in one of the documents serve such document to the victim and the request will still be issued to the site and being authenticated by the application. Contrary to HTML tags, in the case of issuing asynch requests via XmlHttpRequest (XHR) the same origin policy is enforced on the browser and in-theory a CSRF attack will be mitigated by the browser control.
The reality is that if malware is present on the client (such as with XSS exploit for example), then you can potentially override this control, simply because XHR relies on client javascript. In other cases if the control is invoked via a flash the same origin policy can be actually disabled to this vulnerability as a configuration management issue.

Here are the facts in the details :
1) XMLHttpRequest has a same origin policy enforced in both IE and Mozilla
2) Because of the same origin policy you cannot access, a document/script loaded from one site of origin from a site from a different origin
3) XMLHttpRequest rely on javascript to issue POSTs such as:

var post_data = 'name=value';
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("POST", 'http://url/path/file.ext', true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4)
{
alert(xmlhttp.responseText);
}
};
xmlhttp.send(post_data);


4)Since XHR rely on javascript, you can have malware (like Samy webworm that exploits both XSS and CSRF) installed on the client that can overwrite the javascript function by overriding the constructor XMLHttpRequest() { } By doing so the hacker is bypassing the XHR call and will disables the same origin functionality enforced on XHR

5)The same origin policy can also be bypassed with a flash Adobe/Macromedia Flash to issue XHR because cross domain is permitted depending on a rule set in “crossdomain.xml” file present in the root of the target webserver.

So basically like everything else in security, there is no 100% mitigation of the risk. In the case of XHR CSRF browser controls can also be bypassed despite the same origin policy on the browser. The golden rule for security is to rely on multi layer security, XHR with same origin policy but also unique token for each URL and tied to the user session like you can do by using OWASP Guard. To remediate CSRF vulnerabilities every HTTP request (not just the one that you login into it) that can potentially exploited for unauthorized transactions (i.e. HTTP POST of confidential data, high risk transactions) need to be authenticated by issuing a new token/sessionID or event by requiring a PIN

References
http://taossa.com/index.php/2007/02/08/same-origin-policy/
http://www.cgisecurity.com/articles/csrf-faq.shtml
http://jeremiahgrossman.blogspot.com/2007/01/preventing-csrf-when-vulnerable-to-xss.html
http://taossa.com/index.php/2007/02/08/same-origin-policy/

Saturday, February 16, 2008

Current Industry Best Practices for Software Assurance: SAFECode


From Leigh Honeywell Presentation on Writing Secure Software
Source http://www.globalnerdy.com/tag/leigh-honeywell/

The Software Assurance Forum For Excellence in Code (SAFECode) has recently published a white paper on the software industry best practices for software assurance. The forum is lead by Paul Kurtz. Before SAFECode Mr Kurtz successfully led the Cyber Security Industry Alliance (CSIA) to raise the awareness on information security assurance by coordinating the effort with network security vendors such as ISS, Symantec, RSA and others. Now Mr. Kurtz leads the software security assurance forum of software security vendors such as EMC, Juniper, Microsoft, SAP and Symantec. Michael Howard of Microsoft is also chair of the Development Processes working group within SAFEcode. Quoting Michael on his blog:" SAFECode is a great example of "industry helping industry," because it is led by people who have "been there, done that" and have the battle scars to prove it".
The whitepaper on software security provides guidance to software vendors on software security disciplines that should be followed to build, deploy and support security into software products.
I summarized herein the disciplines, with emphasis on the best practices:
  1. Train application developers on software security issues
  2. Define the security requirements including for secure design, coding and tests of a product early during the Software Development Lifecycle (SLDC)
  3. Enforce security by design by identifying design flaws and addressing potential threats to the application with countermeasures so that risks can be mitigated before coding
  4. Follow secure coding best practices and secure coding standards during product development
  5. Protect the integrity and the confidentiality of source code being developed from un-authorized changes and disclosure of intellectual property
  6. Security test products/applications to verify that the meet security requirements as early as during design as well as during implementation
  7. Document the software and vulnerability managament processes such as how software vulnerabilities found by others can be disclosed and how the application/product need to be configured and deploy the product securely
  8. Validate and document security risks such as with a security control gap analysis prior product release
  9. Document how to handle any potential vulnerabilities security incident response processes, notify incidents to the appropriate team and mitigate the vulnerabilities
  10. Enforce trustworthy use of software. Offer customers a way to verify that the product being acquired indeed comes from a trusted vendor
  11. Research on new software threats and countermeasures
  12. Evangelize software security by promoting use of software assurance best practices and by discussing these in open forum as well as publishing of articles, papers and books.
On the resource page of SAFECode site you can also download the current "state-of-the-art" in software security assurance that collects recommendations and best practices for building software security into the SDLC and in particular a more in-depth variety of techniques and technologies in use in government, industry, and academia for specifying, acquiring, producing, assessing, and deploying secure software.
In some sections of this document there are references of my previous work on Software Security Frameworks that I did on behalf of Foundstone as well as references to this blog. Even if I am not working for a software vendor anymore (last time was between 1998-2001 developing software for ISS) I am practicing most of these software security best practices in my day to day working activities and I also advocate for software security initiatives within the bank(Citigroup) where I currently work for as Technology Information Security Officer . On point 12 in particular, I am committed to evangelize software security on this blog and through OWASP, publications and participation to conferences etc.

Saturday, February 02, 2008

Web Cache Security Issues

Most of web applications are designed to use web caching for end user convenience. Web caching improves the user browsing experience by reducing the latency time (e.g. time to wait for a web page to be served) and allow for better bandwidth usage and reduction of the web server load. Web pages with web cache enabled can be cached in the client browser as well as in the server proxies and gateways (e.g. reverse proxies and web accelerators) that are part of the web traffic between the client and the web server. When a web page is not available, a web server and/or a web proxy can serve the browser with a cached web page. More details on web caching and the caching directives and how can be used are well documented herein http://www.mnot.net/cache_docs/

Web caching is good for performance and covenience but there is a flip side: security. Web caching is a typical example of "security=1/convenience" that is, there is a security cost for user convenience:exposing your web application to potential security threats. For example, since cache information can contain sensitive data has to be protected from unauthorized access. In the case of web applications, you would like to avoid caching confidential information on the user's browser so it could be made accessible outside the control of the web application. Web caching of login pages also expose the application to specific threats such as reply a cached page to re-log on on the application besides stealing user credentials with a web proxy. The countermeasure: set the HTTP Header caching directives in any web page (not just login) that store confidential information. In this way you tell browsers , proxies and gateways not to cache any confidential information. More in the details, when web caching is enabled you need to worry about the following threats and implement the following necessary countermeasures:

Threat#1: Unauthorized information disclosure via cached data access: Web pages that are cached in the browser might contain confidential and sensitive information such as authentication data, session tokens and customer confidential information (e.g. PII, Account Numbers, Tax data). Every web page with user sensitive information that is served to a browser with the HTTP Headers caching directives not explicitly set to "no-cache, no-store" is cached in the browser memory. If the browser is left unattended and another user get access to it (like for example in the case of a shared PC at work, internet cafe etc) such user could gain access to the previous user confidential information from the browser cache. For example, if the web page was previously used to view a pdf file that contained sensitive information (i.e. tax form) such file could still be viewed by accessing the browser memory cache. The web cache exploit is very simple, type "about: cache" on the browser address bar (if you are using Firebox for example).

How you know if you are vulnerable? You know if your web application is vulnerable by doing a simple scan of your application web pages for HTTP headers cache settings. You can use freely available web proxies such as paros proxy with enabled scan policy check for finding secure web cache settings. If the scanner finds cache headers not set securely in web pages serving confidential information (e.g. logins, account queries etc) you should fix these pages.

The countermeasure from the web application perspective is to enforce explicit no-cache and no-store via the HTTP Headers or META tags. The no-cache directive will force any browser, web proxy and gateway to submit the web request to the origin web server for validation before releasing a cached copy, every time. The "no-cache" can be set via HTTP headers HTTP1.1 Cache-Control and via HTTP1.0 Pragma. Meta tags can also be used such as META HTTP-EQUIVALENT. The no-cache settings are:
HTTP/1.1: Cache-Control: no-cache or HTTP/1.1: equiv="Cache-Control"
and
HTTP/1.0: Pragma: no-cache or HTTP/1.0: equiv="Pragma" content="no-cache"
But the most important cache directive is the "no-store" that will tell browsers, web proxies and web servers to not store anything on the cache. From the browser perspective, no-store and no-cache directives are enforced differently depending on the browser you are using (IE vs Firefox) and the HTTP or HTTPs connection. For example in IE even if you are using no-cache you will still cache the page by default.

To be safe with all browsers and version of HTTP protocol you need to enforce no-store, no-cache and expires caching directives as follows:

HTTP/1.1: Cache-Control: no-cache, no-store, private, must-revalidate
HTTP/1.0:Pragma: no-cache
Expires:-1
By specifying "must-revalidate" you’re telling the cache that you want it to strictly follow your rules while by specifying "private" you enforce the default setting of keeping the cache private (if you explicity set the cache-control public will be cached in a shared cache even if a no-cache directive is set). By setting the "Expires:-1" directive you will ensure that the web page is already expired and the browser always gets a fresh copy.

This is for the browser cache. Beware that every web proxy and web gateway will also cache your web pages if cache headers are not enforced. Therefore information disclosure is also possible for any user such as admins that have access to such web servers, web proxies and gateways. Typically enforcing no-caching via HTTP headers is just a minimum countermeasure: servers should be hardened to prevent information disclosure via web caches. The HTTP standard has a section on proxies and caching that requires admins to protect the web cache as sensitive information (http://www.w3.org/Protocols/rfc2616/rfc2616-sec15.html)
Unfortunately you web application alone does not have control on cache beyond the HTTP cache headers settings and the web application trust boundary (i.e. the user browser). For example, web servers and proxies will cache and log every HTTP GET request by default while will not cache POST request. Your web application should use POST and not using GET to prevent both caching and logging of sensitive information. Using HTTPs also helps with cache: most of web proxies and gateways do not cache SSL requests by default.
Threat#2:Information disclosure via HTTP POST reply: When the "no-cache", "no-store" HTTP directives are not enforced on web pages used for authentication such as for logon, the cached web page can be replied by another user that has access to the same PC to log back to the application and/or capture previous logged used credentials with a web proxy. This vulnerability is known as HTTP POST Replay 200 OK and is exposed by a web application as a result of both caching headers not set to no cache no store and by not redirecting a user to a web page different then 200 OK (e.g. 302, 307) after logging in.
How you know if you are vulnerable? You can easily test if the web cache allows you to reply the login page by logging into the application, logging out and by reply the web page cached by the browser by hitting the “back” browser button or by refreshing a previous URL from the browser history. If you are vulnerable, the browser will just issue a warning that the web page you are re-playing is a cached web page and if you proceed then you will log back to the application. A detailed description on how this kind of vulnerability can be used to attack authentication and how can be performed to steal user credentials is explained herein
To be noticed, failing to invalidate sessionIDs during the previous user session logout or/and by application idle logout is not actually necessary for exploiting this vulnerability since the cached web page is re-posted (replayed) from the browser and the credentials are captured via a web proxy before sending the request to the web server.
The countermeasure: enable no-cache, no-store and by following the HTTP POST with a HTTP 302 or 307 redirect response.

Threat#3: Escalation of privileges and user impersonation via cached sessionIDs and cookies: web pages that allow caching of sessionIDs provide a malicious user another avenue for session hijacking, breaking of user authentication and horizontal or vertical escalation of privileges.
How you know if you are vulnerable? If sessionIDs has not been invalidated by the previous web session and can be retrieved by the browser cache and re-used by another malicious user. Such user could use such sessionID to escalate his privileges (e.g. gain access to someone else data). Typically, the exposure of this vulnerability besides caching is also due to weak web applicaton session management (e.g. fail to invalidate sessionIDs and fail to properly in-validate session IDs on the server side). Besides from cached data, session IDs can be retrieved from server logs when used in HTTP GET parameters and through eavesdropping during transmission if SSL is not used.
The countermeasure: Use SSL will mitigate the risk of getting sessionIDs via cache (SSL pages are by default setting not cached by web servers) as well as eavesdropping (data is encrypted). If the cached information is a cookie that contain sensitive information such as un-encrypted password or PIN obviously it can be retrieved from the browser memory and/or disk and be used to authenticate by impersonating that user. Therefore, no sensitive information should be stored in a cookie, otherwise you should at minimum encrypt the cookie contents as well as the channel using SSL. More information on how to test if your session variables are unsecured can be found on the OWASP testing guide: http://www.owasp.org/index.php/Testing_for_Exposed_Session_Variables








Saturday, January 19, 2008

Cross Frame Scripting: Not Necessarily a Web Application Vulnerability

Cross Frame Scripting (XFS) is a vulnerability that affects web applications that use frames in their web pages. Frames allow web pages to present the web content framed in different sections of the browser window. A basic description of frames is included herein http://www.quirksmode.org/js/frameintro.html. When the browser renders the framed web page it also tries to load the web pages that each frame references to. This can be done either via HTML tags or by using javascripts either to load a web page within one frame or by calling a section of javascript code that resides in another frame. The security issue by calling javascript across the frames of a web page is that such scripts could be malicious if loaded through a user controlled variable. You can think of a XFS vulnerability as a sub-set of cross site scripting (XSS) vulnerability that is due of lack of input validation and output encoding when processing script from un-trusted source.
The general mitigation of XFS vulnerabilities for sites that use frames is to validate malicious input such as user variable (e.g. URL parameter in a GET request) that can be injected with javascript into a frame and executed on the user's browser within the context of the main page frame. An example is provided herein: http://www.owasp.org/index.php/Cross_Frame_Scripting

A web site that uses frames is potentially vulnerable to several vulnerabilities such as XSS, XFS and CSRF. In the case of XFS this vulnerability should be checked as part of an ethical hack of the web application. The main threat of XFS is that can be used for a phishing attack to steal user credentials. In this case, the malicious phishing site will frame in the legitmate web page section such as a login web page and execute a malicious script for a trojan such as key logger. The malicious frame can be injected via a XSS vulnerability and execute in the context of the legitimate frame.
To mitigate XFS vulnerabilities, modern browsers such as IE7 can help since are designed with security access controls that do not allow a javascript in one frame that belong to a certain domain (e.g. bank.com) to call a javascript of a frame that belong to a different, untrusted domain (e.g. malicousite.com).
Unfortunately, in case of early versions of IE browsers (IE 5.5 and 6.x) this XFS browser control can be bypassed leading to a well known vulnerability: Cross Frame Scripting Bypass: http://labs.idefense.com/intelligence/vulnerabilities/display.php?id=77. If your web application use web frames and the user of your web application access your site via a vulnerable IE browser, the user is exposed to phising attacks that exploit this vulnerability. An example on how this XFS vulnerability is exposed by IE 6.x (will not work on IE7) and how can be used to execute a keylogger and display the user key strokes in the status bar is referenced herein: http://www.millersmiles.co.uk/identitytheft/cssb.html
The countermeasure for this browser vulnerability: use a non XFS control bypass vulnerable browser such as IE 7. Also, with Internet Explorer Vs 6 as well as Vs 7, inform the user of the browser setting "Navigate sub-frames across different domains", set to "Prompt" or "Disable": that protects your computer against the danger of cross-frame scripting attacks.

Other countermeasures are possible at the web application layer: introduce a frame busting javascript on the web pages. Such frame busting techniques consists on forcing the de-framing of the web pages to prevent the frames of your site to be jailed in someone else hacking frame. Basically a frame busting-out technique will cause the web page to be loaded by the browser to jump out of the frame that maliciously try to exploit your frame. The frame busting out technique consists on introducing the following javascript line on top of your web pages:
if(top != self) top.location = self.location;
When executing this javascript, the browser will check if the page is framed (top!=self) and set it to become the top frame (e.g. the whole page container) therefore causing the browser to render the full window without the frame.
The problem is that the effectiveness of this busting out javascript as XFS control should be considered more a deterrent then anything else. For example when using iframes the control can be rendered ineffective with IE by tagging iframes with "security=restricted "in the browser settings. This setting turns off JavaScript on the iframe and defeats the purpose of the anti-busting technique. An example is dealt with herein: http://crypto.stanford.edu/framebust/. Practically the effective risk mitigation from the user stand point is to use a non XFS vulnerable browser like IE 7.0 and newer versions of Firefox that have non vulnerable anti cross frame scripting controls. For users that use legacy browsers like IE5.5 and IE6.x versions the de-framing javascript (frame busting technique) in the web pages can help on mitigating the risk only as a deterrent control.

In summary you are much better off security wise not using frames and iframes in your web application. Possibly you should avoid using frames at least in all web pages that handle sensitive information (e.g. login web pages)

Monday, November 26, 2007

XSS UTF 7 encoded vulnerabilites and APIs that prevent them

You can check if your web application is vulnerable to XSS UTF-7 vulnerabilities by trying the following attack vectors:

1) +ADw-script+AD4-alert(+ACI-XSS+ACI-)+ADw-/script+AD4-
2) %2BADw-script%2BAD4-alert%281%29%2BADw-/script%2BAD4-
3) +ADw-SCRIPT+AD4-alert('XSS');+ADw-/SCRIPT+AD4-

If your application reflects back executable script (showing the dialog XSS alert) to the browser after entering such attack vectors from user input it is vulnerable to UTF-7 encoded XSS. As you might know, reflected XSS can be used maliciously to steal confidential data stored on the victim browser such as cookies and confidential information.

So if your web application is vulnerable to XSS UTF-7 encoded attacks you should check the server side API that filter input data and make sure that do not actually fail in the implementation of basic XSS countermeasures such as:
1) use white list filtering (e.g. default deny except for safe characters)
2) perform output encoding of input strings to the HTML equivalent before sending back the output string to the browser. Example:< becomes &lt and > becomes &gt

Unfortunately, some APIs being developed in commercial web applications still use black listing with regex to strip off script tags such as <> and fail miserably when the attack vector is provided in encoded fashion such as UTF 7.

If your application filter API is actually doing black listing , you can try to fix it by changing the regular expressions and filter the UTF-7 input equivalents.


The problem I see with this approach is that soon enough another XSS script could enter unfiltered when using a different encoding and therefore exploit the vulnerability again. The main problem is that trying to black listing all XSS attack vectors is hard since is difficult to predict what is malicious (black list) rather then define what is benign (white listing)

Also do not forget to enforce the correct encoding through the metatags like in UTF 7 XSS vulnerability that where previously found in google (now being fixed) http://www.governmentsecurity.org/forum/lofiversion/index.php/t18105.html.
Actually, if you enforce the encoding to a different charset such as UTF-8 or ISO 8859-1 you will not be vulnerable to UTF-7 XSS because the browser will switch to a UTF-8 encoding and will not render the UTF-7 attack vector.

But, if you really would like to implement an effective XSS filtering API make sure to perform white list filtering and output encoding and test that the API does not fail to filter different encoded attack vectors such as the one listed on http://ha.ckers.org/xss.html.

My suggestion: do not to re-invent the wheel :) use APIs that have been tested and vetted by the security community. Some of these APIs (e.g. HTML purifier) have been already developed and tested using XSS attack vectors: http://htmlpurifier.org/live/smoketests/xssAttacks.php When using .NET look at Microsoft Anti-XSS library the version 1.5 is freely available from MSDN: http://msdn2.microsoft.com/en-us/security/aa973814.aspx XSS filtering APIs are also available to download from OWASP such as Anti-Samy and the Encoding APIs.

The OWASP Anti-Samy http://www.owasp.org/index.php/AntiSamy it's a library that parses and cleans HTML/CSS using a whitelist validation technique. It has been presented by Arshan Dabirsiaghi at 07 OWASP/WASC Appsec Conference in San Jose: www.owasp.org/images/e/e9/OWASP-WASCAppSec2007SanJose_AntiSamy.ppt The OWASP encoding library is functionally equivalent to the Microsoft AntiXSS has been developed for several languages http://www.owasp.org/index.php/Category:OWASP_Encoding_Project
More specifically for php you can also look at the OWASP PHP AntiXSS library
http://www.owasp.org/index.php/Category:OWASP_PHP_AntiXSS_Library_Project

Sunday, January 29, 2006

Secure key storage in web applications

Whenever you encrypt data you had to solve the problem on where and how to store encryption keys securely. Now that you have encrypted the data and you have transferred the secret to the key you are as much as secure as the key! Where I can store the key securely? Well, ask yourself first, did you really have to encrypt your secrets? If you are using .NET and your secret are "windows secrets" such as connection strings, passwords the best option you have is to have windows handling the secrets for you such as using integrated security. For example, let say your web server connects to a SQL server, instead to store the credentials in clear in the web file (bad idea!) or encrypting them (ok idea) or ACLs the configuration file (better idea) you are much better off secure-wise by using windows trusted authentication, therefore no windows defined secrets have to be stored in a file. But what happen when you have to handle user defined secrets such as personal identified information, credit card information etc? Assume your web server encrypts a VISA card number to store the encrypted value in a SQL Server (very popular way to do it..) You certainly (I hope) decide to use symmetric encryption and you are faced with the dilemma on where to store the key securely. A security-wise solution is to encrypt the key and store it in a secure key container in dedicated server (I'll explain later why dedicated). You move the key from the web server to a dedicated server that is much more secure and less exposed (certainly being a DMZ!). How? In the January 2006 edition of MSDN Magazine Keith Brown shows a great nice example on how to write web applications that use secure key storage in .NET. First, public key cryptography is used to encrypt and decrypt the secret key.
With .NET you can use the RSACryptoServiceProvider API to generate a (PR) private/(PK) public key pairs to be stored "securely" in the CryptoAPI (CAPI) key container. The CAPI key container has actually two PR/PK key pairs, one for encrypting the secret such as secret keys and another for creating digital signatures. The key container is then stored in an hidden file directory (see previous post on this blog:"Where Cryptographic Service Providers store keys?"). As an option, CAPI allow you to save the PR key on a smartcard to reduce your attack surface even further. The key container can be given either user access or machine access. In the case of user access only the user that created the keys and the administrator of the machine can have access to the key pairs. In the case of machine access, you can set ACLs to grant access to specific user accounts on the machine where the key container resides. The best practice (and I agree) is to create an application to manage keys. Then you can restrict read access to the keys to the application that has to decrypt the key. In the article, the key manager application runs on the machine where the data has to be decrypted and allows to create and delete several key containers that can be retrieved by key container names. The key manager application also grants ACL (Access Control Lists) to give read access to the decryption agent. Once the key manager runs, it will generate a PK/PR pair. The PK is in base64 encoded format. During configuration such PK can be cut and pasted in the web config file of the web application that needs to encrypt the data. The encryptor application will generate the secret key such as using AES 256 bit random key, encrypt the data to be secured with the secret key and encrypt the key with the PK generated by the keymanager application. Finally, the key container name + encrypted AES key + the encrypted data + AES key length and initialization vector are given to the decryptor that will decrypt the AES key with his PR key (stored in the container) and use the AES key to decrypt the data.

To simplify (I hope) this is the scenario, step by step:

1) key manager running on the decryptor machine creates a CAPI Key container. The key container has a name and generates a PK/PR key pair
2) The encryptor running on a different machine (e.g. web server) get configured with the generated PK by copying it on the web.config file
3) The encryptor generates a secret AES key to encrypt the confidential data (i.e. credit card info, PII etc)
4) The encryptor encrypts the AES Key with the PK retrieved from the web.config file and appends other information such as the key container where the key pair is stored, the AES key length, the IV vector and the data encrypted and return it to the decryptor in a base64 blob
5) The decryptor takes the base64 encoded blob, gets the name of the container, gets the PR key from the container, decrypts the AES secret key with the PR key and then uses the AES key to decrypt the data

There are some important considerations:

1) the secret key is not stored on the web server
2) the secret key is encrypted with RSA encryption and stored encrypted in a more secure decryptor machine (such as behind the DMZ)
3) public key encryption provides confidentiality to the secret key exchanged between the web server (encryptor) and the decryptor machine
4) the PK/PR key pair to encrypt the secret key is stored securely in the key container
5) only the web server and the decryptor can have access to the key container
6) the ciphertext is stored in another machine

The application is an example of factoring encryption, such as using dedicated agents on different machines for encryption, decryption and storage of ciphertext.

Factoring encryption offer several advantages:
1) increases security because limit exposure of the secrets. In the example the most exposed machine such as the encryption web server not to store any secret.
2) optimizes performance by dedicating different resources to different operations. This is a big deal when dealing with public encryption since decryption is sever orders slower than encryption (in the article it is shown that encrypting a with RSA 4096 bit takes 3 milliseconds for encryption and 0.3 seconds (100 times slower!) for decryption).

As the article points out, you might want to use dedicated hardware solutions to speed up the process of decryption by offloading the process from the main CPU (it might just add 4000 $ to your hardware bill..) Another important point is to protect integrity of the secret key while transmitting it between servers.
One of things we the I stress out at my BSS class (check Foundstone training) is that when you use symmetric algorithms such as AES that is a CBC Cipher Block Chaining algorithm you do not protect the integrity of the data (that is you do not provide tampering protection), if you tamper the encrypted data during transmission you can still decrypt garbage. You might want to use digital signatures and hash the encrypted key to protect it from tampering or provide SSL between web server and the decryptor. This is also mentioned in the article (very good)

The article referred here is available on msdn web site

Monday, December 26, 2005

How to classify software vulnerabilities

I was recently involved in an email discussion about the value of taxonomies for classification of vulnerabilities and threats. Inspired by a paper on taxonomy of software change events: "Toward a Taxonomy of Software Evolution" http://lampwww.epfl.ch/papers/use03.pdf

My point was that a similar taxonomy can be applicable to threats: when in SDLC threats occur (i.e. during requirements, design, development, deployment) where (at which level, application, system subsystem, component) , how they manifest (i.e. because of spoofing, tampering, repudiation etc) and what security attributes affect to (for example Confidentiality, Integrity and Availability).

To validate this approach I decided to research on the available papers and research on taxonomies for vulnerabilities.

In a recent paper (September 2006) Matt Bishop (UC Davis) and David Bailey http://seclab.cs.ucdavis.edu/projects/vulnerabilities/scriv/ucd-ecs-96-11.pdf did a survey of different taxonomies for vulnerabilities and concluded that some classifications can be flawed. As a reference a good taxonomy could be the classification of biological systems. Plants and animal belong to the same "kingdom" of biological creatures but can be differentiated in different groups and two animals of the same can be "uniquely" classified as part of the same group. Ideally the classification of a plant or a animal uniquely belong to a six-tuple (kingdom, phylums,classes,orders,family, genus). Bishop tested some vulnerabilities classification following this criteria. Some classification vulnerabilities such as RISOS (Research into Secure O.S) , UNIX faults taxonomy from Aslam and Bisbey's Protection Analysis Project have flaws in the classification because of ambiguities (not uniqueness ) in the classification: for example depending on the point of view you might have classification for a buffer overflow in different categories. Classifications are also found to be dependent on the discriminatory criteria adopted at different levels of the tree. The problem stands also in how vulnerabilities are grouped together: while deciding which level and which group the same discriminatory question can be asked at different levels so it is not clear at which level the classification is correct. Bishop does not actually find a better classification for security taxonomies, it actually point out the limitations and his critique is that can be flawed suggesting some criteria for new research on the topic.

Gary Mc Graw et al. in the paper 7 Pernicious Kingdoms, A Taxonomy of Software Security Errors http://vulncat.fortifysoftware.com/docs/tcm_taxonomy_submission.pdf take a more pragmatic approach: research for a taxonomy of coding errors that can be fixed by a set of security rules that can be used by both manual and automated code reviews (i.e. static code parsers). In reviewing of existing taxonomies like Bishop, Mc Graw also agrees in the ambiguity and the lack of coverage of the classification of vulnerability in some previous projects such as RISOS. The main limitations of RISOS according to Mc Graw stand in the high level of abstraction and in the objective to allow classification of vulnerabilities from an agnostic knowledge security point of view. One of the main goals of the RISOS project was also to discover vulnerabilities through common patterns to be used for automation tools by building a catalogue of vulnerabilities to be published.

According to McGraw, RISOS project actually failed in the objective of building a repository for vulnerabilities since the database was never published.
Based on research on existing taxonomies and by understanding limitations, McGraw classification does not aim to be rigorous from the stand point of the classification but rather to be useful.
McGraw taxonomy (that also will appear in the next book due in 2006, building Security In) is based on specific type of coding errors (i.e. a phylum that is for example a illegal pointer value) and a collection of phyla called a kingdom that share a common theme (for example input validation). McGraw recognizes that the classification is not theoretically complete and can change but also points out that can serve well a classification for errors (i.e. security flaws) to be part of both a manual and automatic code review.
McGraw taxonomy has the following 7+1 classification:
  • Input Validation and Representation
  • Api Abuse
  • Security Features
  • Time and State
  • Errors
  • Code Quality
  • Encapsulation
  • environment
For example under input Validation and Representation you might have BO, XSS, SQL Injection and many others, under Api abuse you might have unsafe string manipulation APIs, under Time and State you might have TOCTOU time to check time to execute etc.
Other authors such as VIEGA have also developed a taxonomy as part of a methodology for building security into the SDLC such as CLASP. CLASP has a taxonomy for vulnerabilities based on a root cause classification. According to Mc Graw, Viega CLASP taxonomy extends the one researched by Landwehr's Taxonomy of Computer Security Flaws http://www.cs.virginia.edu/~soffa/cs851/p211-landwehr.pdf.
Landwehr's Taxonomy is a classification from three perspectives: HOW the problem entered the system, WHEN the problem entered the system and WHERE the problem manifested. How was broken in inadvertent (and further in malicious and not malicious) and intentional, when was broken at which stage of the SDLC such as during design, development, operation and where was broken in hardware vs software.
According to Mc Graw, Landwehr's Taxonomy has the advantage to identify remedies (i.e. countermeasures) for example if most of the vulnerabilities occur during development you could strategically focus on code reviews. The disadvantage according to Mc Graw is in the limitation to handle new vulnerabilities since it classifies them according to the genesis so if a vulnerability is not yet known on how enters the system cannot be classified.
According to Mc Graw, CLASP taxonomy expands Landwehr's How, Where, When, further by adding a risk based classification such as the effect from the error (i.e. consequence), likelihood of exploit, severity and other parameters. The purpose is to build a root cause taxonomy for example the root cause of a security flaw according to CLASP can be classified depending the point of introduction into the SDLC in a hierarchical view.
  • Level 1: Identify Range and Type of Errors:Part of Level 1 you might have buffer overflows (introduced during Requirements, Design and Implementation), Command Injection (design and implementation), Double Free (implementation)
  • Sub level 2: Identify Environment Problems:Part of sub level 2 you might have resource exhaustion (design and implementation)
  • Sub level 3:Identify Synchronization and timing errors: TOCTOU, race conditions (design and implementation)
  • Sub level 4:Identify Protocol Errors:Misuse of cryptography (design)
  • Sub level 5:Identify Generic logic Errors:Performing a chroot without a chdir (implementation)
The approach is effective in determining root causes of security flaws with emphasis on the when in the SDLC is actually might originate helping architects and developers to build security into the SDLC. The main critics from Mc Graw about Viega's CLASP taxonomy stands in the fact that struggles to provide a reliable lexicon for security flaws classification since some of the issues in the taxonomy cannot be actually classified as security problems.
Notably all taxonomies are "living and changing entities", referring to M. Klass presentation at OWASP on taxonomies for software assurance tools and the security bugs they catch http://www.owasp.org/docroot/owasp/misc/OWASP_DC_2005_Presentations/Track_2-Day1/AppSec2005DC-Mike_Kass-Tools_Taxonomy.ppt taxonomies have such limitations in common:
  • Vulnerabilities do not map to a security flaw but to a combination of security flaw
  • Categorization of security flaws is not always mutually exclusive
  • Taxonomies can categorize flaws but cannot be identified by tools
  • Some flaws are not in the code
  • Some flaws can be introduced at different stages of the SDLC
More to be researched...