Module IV. Web Security (II) Chapter 10 Secure Web Programming Web Security: Theory & Applications School of Software, Sun Yat-sen University
Outline 10.1 Introduction to Web Programming Tools for Web Development Designing CGI Implementing Web Services Accessing Database Through Web Web Security : Theory And Applications 2 / 128
Outline 10.2 Learning Secure Web Programming With Examples Introduction to Gruyere Codelab Brief Introduction to Python Cross-Site Scripting (XSS) Client-State Manipulation Cross-Site Request Forgery (XSRF) Cross Site Script Inclusion (XSSI) Path Traversal Denial of Service (DoS) Arbitrary Code Execution Configuration Vulnerabilities AJAX vulnerabilities Web Security : Theory And Applications 3 / 128
10.1 Introduction to Web Programming Tools for Web Development Designing CGI Implementing Web Services Accessing Database Through Web Web Security : Theory And Applications 4 / 128
10.1 Introduction to Web Programming 10.1.1 Tools for Web Development Aptana Studio Dreamweaver Eclipse Flash Builder/Flex Builder IntelliJ IDEA NetBeans PhpDesigner Visual Studio Visual Web Developer Zend Studio Web Security : Theory And Applications 5 / 128
10.1 Introduction to Web Programming Aptana Studio Aptana Studio is an open source integrated development environment (IDE) for building Ajax web applications. It includes support for JavaScript, HTML, DOM, and CSS with code-completion, outlining, JavaScript debugging, error and warning notification and integrated documentation. Additional plugins allow Aptana Studio to be extended to support Ruby on Rails, PHP, Python, Perl, Adobe AIR, Apple iphone and Nokia WRT (Web Runtime). Web Security : Theory And Applications 6 / 128
10.1 Introduction to Web Programming Adobe Dreamweaver Adobe Dreamweaver (formerly, Macromedia Dreamweaver) is a web development application originally created by Macromedia, and is now developed by Adobe System, which acquired Macromedia in 2005. Web Security : Theory And Applications 7 / 128
10.1 Introduction to Web Programming Dreamweaver allows users to preview websites in locally installed web browsers. It provides transfer and synchronization features, the ability to find and replace lines of text or code by search terms and regular expressions across the entire site, and a templating feature that allows single-source update of shared code and layout across entire sites without server-side includes or scripting. The behaviors panel also enables use of basic JavaScript without any coding knowledge, and integration with Adobe's Spry Ajax framework offers easy access to dynamically-generated content and interfaces. Web Security : Theory And Applications 8 / 128
10.1 Introduction to Web Programming Eclipse Eclipse is a multi-language software development environment comprising an integrated development environment (IDE) and an extensible plug-in system. It is written mostly in Java and can be used to develop applications in Java and, by means of various plug-ins, other programming languages including Ada, C, C++, COBOL, Perl, PHP, Python, R. Ruby (including Ruby on Rails framework), Scala, Clojure, and Scheme. It can also be used to develop packages for the software Mathematica. The IDE is often called Eclipse ADT (Ada Development Toolkit) for Ada, Eclipse CDT for C/C++, Eclipse JDT for Java, and Eclipse PDT for PHP. Web Security : Theory And Applications 9 / 128
10.1 Introduction to Web Programming Adobe Flash Builder Adobe Flash Builder (previously known as Adobe Flex Builder) is an integrated development environment (IDE) built on the Eclipse platform that speeds development of rich Internet applications (RIAs) and cross-platform desktop applications, particularly for the Adobe Flash platform. Web Security : Theory And Applications 10 / 128
10.1 Introduction to Web Programming Adobe Flex Adobe Flex is a software development kit (SDK) released by Adobe System for the development and deployment of cross-platform rich Internet applications based on the Adobe Flash platform. Flex applications can be written using Adobe Flash Builder or by using the freely available Flex compiler from Adobe. Web Security : Theory And Applications 11 / 128
10.1 Introduction to Web Programming IntelliJ IDEA IntelliJ IDEA is a commercial Java IDE by JetBrains. It is often simply referred to as "IDEA" or "IntelliJ". The latest version of IDEA (10.0) includes UML-like class diagrams, visual Hibernate modeling, Spring 3.0 support, Dependency and Data Flow Analysis, Apache Maven support as well as a lot of other features and technologies. Web Security : Theory And Applications 12 / 128
10.1 Introduction to Web Programming NetBeans NetBeans refers to both a platform framework for Java desktop applications, and an integrated development environment (IDE) for developing with Java, JavaScript, PHP, Python, Ruby, Groovy, C, C++, Scala, Clojure, and others. The NetBeans IDE is written in Java and can run anywhere a JVM is installed, including Windows, Mac OS, Linux, and Solaris. The NetBeans platform allows applications to be developed from a set of modular software components called modules. Applications based on the NetBeans platform (including the NetBeans IDE) can be extended by third party developers. Web Security : Theory And Applications 13 / 128
10.1 Introduction to Web Programming PhpDesigner The latest version of PhpDesigner is phpdesigner 7. PhpDesigner 7 is more than just a powerful and lightning fast PHP IDE and PHP EDITOR - it's also a full-featured HTML-, CSS- and JavaScript editor boosted with features so you can get your work done.it can assists you with everything from editing, analyzing, debugging to publishing websites powered by PHP, HTML, CSS to JavaScript plus other languages. PhpDesigner 7 supports not only working with your favorite PHP frameworks but also popular JavaScript frameworks jquery, Ext JS, YUI, Dojo, MooTools and Prototype. Web Security : Theory And Applications 14 / 128
10.1 Introduction to Web Programming Microsoft Visual Studio Microsoft Visual Studio is an integrated development environment (IDE) from Microsoft. It is used to develop console and graphical user interface applications along with Windows Forms applications, web sites, web applications, and web services in both native code together with managed code for all platforms supported by Microsoft Windows, Windows Mobile, Windows CE,.NET Framework,.NET Compact Framework and Microsoft Silverlight. Web Security : Theory And Applications 15 / 128
10.1 Introduction to Web Programming Visual Web Developer Express Visual Web Developer Express is a freeware web development tool that allows developers to evaluate the web development and editing capabilities of the other Visual Studio 2008 editions at no charge. Its main function is to create ASP.NET websites. It has a WYSIWYG interface, drag-and-drop user interface designer, enhanced HTML and code editors, a (limited) database explorer, support for other web technologies (e.g., CSS, JavaScript, XML), and integrated, designtime validation for standards including XHTML 1.0/1.1 and CSS 2.1. Web Security : Theory And Applications 16 / 128
10.1 Introduction to Web Programming Zend Studio Zend Studio is a commercial, proprietary integrated development environment (IDE) for PHP developed by Zend Technologies, based on the PHP Development Tools (PDT) plugin for the Eclipse platform (the PDT project is led by Zend). Web Security : Theory And Applications 17 / 128
10.1 Introduction to Web Programming 10.1.2 Designing CGI Introduction Comparisons with Other Scripting Techniques Requirements for CGI Scripting Running CGI Scripts CGI Variables Advantages Disadvantages Alternatives Web Security : Theory And Applications 18 / 128
10.1 Introduction to Web Programming Introduction CGI: Common Gateway Interface Commonly known as CGI scripts receives and process browser input returns the results to the users CGI scripts can be ANYTHING EXECUTABLE batch compiled executables Unix/Linux shell scripts C Java Visual Basic Perl - most commonly used Web Security : Theory And Applications 19 / 128
10.1 Introduction to Web Programming Comparisons with other scripting techniques Web Security : Theory And Applications 20 / 128
10.1 Introduction to Web Programming Comparisons with Other Scripting Techniques Do I have the capability of running my own CGI scripts? A Web server - NOT a FTP or Gopher server Properly configuration - directory: cgi-bin/ Prepare for possible large payloads Does my CGI capability include support for SSI (Server Side Includes)? SSI: commands to the Web server to include some information the server has in the displayed Web page A common use: to display the current date and time on a Web page Web Security : Theory And Applications 21 / 128
10.1 Introduction to Web Programming Running CGI Scripts CGI in the server system Web Security : Theory And Applications 22 / 128
10.1 Introduction to Web Programming Web files locations (on Apache) htdocs/:.html,.php, etc. cgi-bin/: CGI scripts Extensions: anything (.sh,.cgi), or none logs/: log files are helpful Permissions: r & x at least Web Security : Theory And Applications 23 / 128
10.1 Introduction to Web Programming CGI Variables Data is passed into the program using environment variables User-submitted data is provided to the program via the standard input Server specific variables: SERVER_SOFTWARE name/version of HTTP server. SERVER_NAME host name of the server, may be dot-decimal IP address. GATEWAY_INTERFACE CGI/version. Web Security : Theory And Applications 24 / 128
10.1 Introduction to Web Programming Request specific variables: SERVER_PROTOCOL HTTP/version SERVER_PORT TCP port (decimal) REQUEST_METHOD name of HTTP method (see above) PATH_INFO path suffix, if appended to URL after program name and a slash PATH_TRANSLATED corresponding full path as supposed by server, if PATH_INFO is present SCRIPT_NAME relative path to the program, like /cgibin/script.cgi QUERY_STRING the part of URL after? character. May be composed of *name=value pairs separated with ampersands (such as var1=val1&var2=val2 ) when used to submit form data transferred via GET method as defined by HTML application/x-www-form-urlencoded Web Security : Theory And Applications 25 / 128
10.1 Introduction to Web Programming Request specific variables (continued): REMOTE_HOST host name of the client, unset if server did not perform such lookup REMOTE_ADDR IP address of the client (dot-decimal) AUTH_TYPE identification type, if applicable REMOTE_USER used for certain AUTH_TYPEs REMOTE_IDENT see ident, only if server performed such lookup CONTENT_TYPE MIME type of input data if PUT or POST method are used, as provided via HTTP header CONTENT_LENGTH similarly, size of input data (decimal, in octets) if provided via HTTP header Web Security : Theory And Applications 26 / 128
10.1 Introduction to Web Programming Advantages Scripts are stored in files Thousands of freely available scripts on the Internet Bestdam Website Visitor Logger: http://www.parkansky.com/bdl/bdlogger.htm Web Security : Theory And Applications 27 / 128
10.1 Introduction to Web Programming Disadvantages Each execution: invocation of a newly created process Worse if scripts need to be interpreted or compiled Server may be overwhelmed Web Security : Theory And Applications 28 / 128
10.1 Introduction to Web Programming Alternatives Use compiled CGI programs Apache modules, Netscape NSAPI plug-ins, IIS ISAPI plug-ins: own extension mechanisms developed by popular Web servers that allow third-party software to run inside the web server itself SCGI: Simple Common Gateway Interface FastCGI A single, long-running process to handle more than one user request while keeping close to the CGI programming model Independent of the web server Java Platform, Enterprise Edition (Java EE): replacement architecture Generates and destroys threads Servlet Libraries Web Security : Theory And Applications 29 / 128
10.1 Introduction to Web Programming 10.1.3 Implementing Web Services Introduction Purposes Web Services Platform Elements Architecture Agents and Services How Does It Work WSD/WSDL Semantics The Service Registry Interactions Styles of Use Drawbacks Web Security : Theory And Applications 30 / 128
10.1 Introduction to Web Programming Introduction Web services: software systems designed to support interoperable ( 互 操 作 ) machine-to-machine interaction over a network. They are application components communicate using open protocols are self-contained and self-describing can be discovered using UDDI can be used by other applications are based on XML Examples Google Maps API Web Services itunes Store Web Service Search API Documents for developers Web Security : Theory And Applications 31 / 128
10.1 Introduction to Web Programming Purposes Web services can convert your application into a Web application, which can publish its function or message to the rest of the world Web services themselves do not provide the user with a GUI, but instead share business logic, data and processes through a programmatic interface across a network Developers can then add the Web service to a GUI (such as a Web page or an executable program) to offer specific functionality to users Web services allow different applications from different sources to communicate with each other without timeconsuming custom coding Java can talk with Perl; Windows applications can talk with UNIX applications; etc. Web Security : Theory And Applications 32 / 128
10.1 Introduction to Web Programming Web Services Platform Elements SOAP (Simple Object Access Protocol): a protocol specification for exchanging structured information in the implementation of Web Services in computer networks Nothing to do with SOA (Service-oriented Architecture) UDDI (Universal Description, Discovery and Integration): a platform-independent, Extensible Markup Language (XML)-based registry for businesses worldwide to list themselves on the Internet and a mechanism to register and locate web service applications WSDL (Web Services Description Language): an XMLbased language that provides a model for describing Web services Web Security : Theory And Applications 33 / 128
10.1 Introduction to Web Programming Web services architecture Web Security : Theory And Applications 34 / 128
10.1 Introduction to Web Programming Agents and Services Agent: the concrete piece of software or hardware that sends and receives messages Service: the resource characterized by the abstract set of functionality that is provided Although the agent may have changed, the Web service remains the same Web Security : Theory And Applications 35 / 128
10.1 Introduction to Web Programming How Does It Work The general process of engaging a Web service Web Security : Theory And Applications 36 / 128
10.1 Introduction to Web Programming WSD/WSDL In order for message exchange to be successful, the requester entity and the provider entity must first agree on both the semantics and the mechanics of the message exchange The mechanics of this message exchange are documented in a Web Service Description (WSD) The WSD is a machine-processable specification of the Web service's interface WSD is written in WSDL (L: language) Web Security : Theory And Applications 37 / 128
10.1 Introduction to Web Programming Semantics WSD: a contract governing the mechanics of interacting with a particular service Semantics: a contract governing the meaning and purpose of that interaction Web Security : Theory And Applications 38 / 128
10.1 Introduction to Web Programming The Service Registry The service registry is a central location where service providers can publish their service descriptions, and where service requesters can find those service descriptions Web Security : Theory And Applications 39 / 128
10.1 Introduction to Web Programming Interactions Web services components and interactions Web Security : Theory And Applications 40 / 128
10.1 Introduction to Web Programming The interactions between the service provider, service requester, and service registry involve the following operations Publish: When a service registry is used, a service provider publishes its service description in a service registry for the service requester to find Find: When a service registry is used, a service requester finds the service description in the registry Bind: The service requester uses the service description to bind with the service provider and interact with the Web service implementation Web Security : Theory And Applications 41 / 128
10.1 Introduction to Web Programming Styles of Use RPC: Remote Procedure Calls Present a distributed function (or method) call interface that is familiar to many developers Early adopted, widely deployed and supported Criticized for not being loosely coupled ( 松 耦 合 ) SOA: Service-Oriented Architecture Basic unit of communication is a message, rather than an operation Supported by most major software vendors Loose coupling is more likely: focused on the "contract" that WSDL provides, not implementation details. Web Security : Theory And Applications 42 / 128
10.1 Introduction to Web Programming REST: REpresentational State Transfer ( 表 述 性 状 态 转 移 ) Describes architectures that use HTTP or similar protocols by constraining the interface to a set of well-known, standard operations (like GET, POST, PUT, DELETE for HTTP) Focused on interacting with stateful resources, not messages or operations Support for this specification is still poor in software development kits Ref to http://www.xfront.com/rest-web-services.html http://blog.csdn.net/wangjj_016/article/details/3615948 Web Security : Theory And Applications 43 / 128
10.1 Introduction to Web Programming Drawbacks Composite Web services: Not reliable: the service provider may remove, change or update their services without giving notice to users. Reliability and fault tolerance not well supported: faults may happen during the execution; exception handling is still an open research issue Non-RESTful Web services: too complex and based upon large software vendors or integrators, rather than typical open source implementations REST Web services: A minor change on the server (even an upgrade of the SOAP stack) can result in different WSDL and a different service interface Web Security : Theory And Applications 44 / 128
10.1 Introduction to Web Programming 10.1.4 Accessing Database Through Web Introduction API s Web Security : Theory And Applications 45 / 128
10.1 Introduction to Web Programming Introduction Database connection: a facility that allows client software to communicate with database server software Can happen on the same machine or not Required to send commands and receive answers A key concept in data-centric programming Connection pooling: Improves performance Connection string: a way of addressing a specific database or server and instance as well as user authentication credentials An example: Server=sql_box; Database=Common; User ID=uid; Pwd=password; Web Security : Theory And Applications 46 / 128
10.1 Introduction to Web Programming Concurrency Some only allow one operation to be performed at a time on each connection, like PostgreSQL Others do not impose this limitation, like SQL Server 2005 (and later), but usually incur far more overhead. ( 导 致 过 高 的 管 理 耗 费 ) Web Security : Theory And Applications 47 / 128
10.1 Introduction to Web Programming API s ODBC: Open Database Connectivity ADO: Microsoft's ActiveX Data Objects OLE DB: Object Linking and Embedding, Database JDBC: Java DataBase Connectivity Other Specific API's e.g. OCI (Oracle Call Interface): php Oracle Web Security : Theory And Applications 48 / 128
Outline 10.1 Introduction to Web Programming 10.2 Learning Secure Web Programming With Examples Introduction to Gruyere Codelab Brief Introduction to Python Path Traversal Denial of Service (DoS) Cross-Site Scripting (XSS) Client-State Manipulation Cross-Site Request Forgery (XSRF) Cross Site Script Inclusion (XSSI) Arbitrary Code Execution Configuration Vulnerabilities AJAX vulnerabilities Other Vulnerabilities Web Security : Theory And Applications 49 / 128
10.2.1 Introduction to Gruyere Codelab What Is It & What Is It For Requirements How to Use Web Security : Theory And Applications 50 / 128
What Is It Its website: http://google-gruyere.appspot.com/ A small, cheesy web application designed of insecure conceptions It has so many bugs ranging from XSS and request forgery, to information disclosure, denial of service, and remote code execution. What Is It For You can do experiments on this codelab. This codelab guide you through discovering these bug and finding the ways to defend and fix them both in Gruyere and in general. Web Security : Theory And Applications 51 / 128
Requirements Some familiarity with how a web application works (e.g., general knowledge of HTML, templates, cookies, AJAX, etc.) Try to use a proxy, VPN, or IPV6. How to Use It has a tutorial for its use, including the description of each vulnerability, tasks to find and fix that. Ways to test and hack: Black Box White Box In real life, security researchers use both hacking methods for their jobs. Web Security : Theory And Applications 52 / 128
10.2.2 Brief Introduction to Python Basic Idea and Rudimentary Syntax Setting Environment for Python Programming Learn Python Web Security : Theory And Applications 53 / 128
Basic Idea and Rudimentary Syntax What's Python: Python is a programming language that lets you work more quickly and integrate your systems more effectively. Syntax: Similar to C/C++/JAVA in many keywords and arithmetic operators. Indentation and newline take part in deciding program syntax as well. Web Security : Theory And Applications 54 / 128
Setting Environment for Python Programming Setup: First get your computer setup to run Python. IDE: There are copious IDEs for python programming, such as ActivePython, Komodo, Python-mode for Emacs and Eclipse for Python, etc. Learn Python Read books. For beginners, LearnPythonTheHardWay http://learnpythonthehardway.org/book/ is recommended. Practice more. Try to program something more practical in life. Web Security : Theory And Applications 55 / 128
10.2.3 Path Traversal A Path Traversal attack aims to access files and directories that are stored outside the web root folder. How to Avoid Path Traversal Vulnerabilities How to Test for Path Traversal Vulnerabilities Web Security : Theory And Applications 56 / 128
How to Avoid Path Traversal Vulnerabilities Identify if you are vulnerable. Be sure you understand how the underlying operating system will process filenames handed off to it. (OS 如 何 处 理 移 交 给 它 的 文 件 名 ) Don't store sensitive configuration files inside the web root. Protect yourself Prefer working without user input when using file system call. Validate the user s input by only accepting known good do not sanitize the data. Web Security : Theory And Applications 57 / 128
How to Test for Path Traversal Vulnerabilities Input Vectors Enumeration: a systematic evaluation of each input vector Testing Techniques: a methodical evaluation of each attack technique used by an attacker to exploit the vulnerability Web Security : Theory And Applications 58 / 128
10.2.4 Denial of Service (DoS) Types of DoS Attacks Defending against Smurf and Fraggle Defending against SYN Flood Web Security : Theory And Applications 59 / 128
Types of DoS Attacks Bandwidth Consumption: This kind of attack usually consumes all available bandwidth in a variety of insidious ways. What's dangerous is that it can amplify itself. Example: Smurf and fraggle. Resource Starvation: This kind of attack differs from the bandwidth consumption in that it consumes system resources rather than network resources. Generally, this involves consuming system resources such as CPU utilization, memory, file-system quotas, or other system process. Example: SYN flood. Web Security : Theory And Applications 60 / 128
Programming Flaws: Programming flaws are failures of an application, operating system, or embedded logic chip to handle exceptional conditions. Attackers will use bugs in your applications and take full advantage of crashing critical parts and sensitive systems. Example: IP fragmentation, Windows NT Spool Leak. Routing and DNS Attacks: A routing-based DoS attack involves attackers manipulating routing table entries to deny service to legitimate systems or networks. The same situation occurs to DNS where DoS attacks convince server to cache bogus address information. Besides, DNS packets are also a major tools for amplifying use. Example: Routing and DNS attacks. Web Security : Theory And Applications 61 / 128
Defending against Smurf and Fraggle No Responding: Configure individual hosts and routers not to respond to ping requests or broadcasts. No Directed Broadcast: Configure routers not to forward packets directed to broadcast addresses. Filtering Spoofed Address: Network Ingress Filtering which rejects the attacking packets on the basis of the forged source address. Web Security : Theory And Applications 62 / 128
Rate Limit: Attacks using particular packet types, such as ICMP floods or UDP floods to diagnostic services, can be throttled by imposing limits on the rate at which these packets will be accepted. Trace Back: By systematically reviewing each router starting with the amplifying site and working upstream, it is possible to trace the attack back to the attacking network. Example: MCI s dostracker (Dos Tracker) Web Security : Theory And Applications 63 / 128
Contingency Strategy ( 意 外 响 应 策 略 ): To respond successfully to a DoS attack, a good incident response plan is needed. Detection: When a DoS attack is detected, it's very important and emergent to identify the type of attack and hence best approach to defend against it. Backup: Switch to alternate backup servers, or to rapidly commission new servers at a new site with new addresses, in order to restore service. Future Handling: Analyze the attack, gain benefit from the experience and improve future handling. Human Intervention ( 人 工 干 预 ): Web Security : Theory And Applications 64 / 128
Defending against SYN Flood Check SYN_RECV: To determine if you are under attack, you can issue the netstat command if it is supported by your operating system. If you see many connections in a SYN_RECV state, it may indicate that a SYN attack is in progress. Fix in the queue: Obviously it's the connection queue that is the weakness. There are 2 countermeasures which can do some mending on the hole: 1. Increase the size of the connection queue; 2. Decrease the connection establishment time-out period ; While each countermeasure has pros and cons (for and against, 利 和 弊 ), they can be used to help reduce the effects of a focused SYN attack. Web Security : Theory And Applications 65 / 128
SYN Cookies : It is possible to specifically defend against the SYN spoofing attack by using a modified version of the TCP connection handling code. Instead of saving the connection details on the server, critical information about the requested connection is cryptographically encoded in a cookie that is sent as the server's initial sequence number. Network IDPS (IDS/IPS): Detection and prevention are always the important tasks in security against attack. Web Security : Theory And Applications 66 / 128
10.2.5 Leave no space for XSS Brief introduction to XSS Methods effective to avert XSS Questions you may have Web Security : Theory And Applications 67 / 128
Brief introduction: We have already gone through in chapter 9. So, let me see. XSS is alert(1)? Oh, I got it. XSS is short for Cross-site Scriping. Web Security : Theory And Applications 68 / 128
Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications that enables attackers to inject client-side script into web pages viewed by other users. Injection is an attack that involves breaking out of a data context and switching into a code context through the use of special characters that are significant in the interpreter being used. Code Injection: the exploitation of a computer bug caused by processing invalid data. Code injection can be used by an attacker to introduce (or "inject") code into a computer program to change the course of execution. Web Security : Theory And Applications 69 / 128
Example: Try to inject code (like alert( XSS )): 1.<div>YourInput</div> 2.<td bgcolor=yourinput>abc</td> 3.<iframe src=youruploadfile/> So if all above has been done, check your answer. 1.</div><script>alert( XSS );</script><div> 2. #F00 ><script>alert( XSS );</script></td><td 3.Just upload a file contents: <script>alert( XSS );</script> Suggestions Keep on thinking about how XSS works. And you ll find the key hold by hackers. If you ve already designed some web pages, try to find out the vulnerabilities they have. Web Security : Theory And Applications 70 / 128
Effective Methods It s hard to say which method can do everything for you, because your asset has been nailed by different kinds of bad guys (e.g. thieves, robbers or trickers ). So, let s get started to arm ourselves now. Use Whitelist Model HTML is just like a template with slots where a developer is allowed to put untrusted data. What can we do with these slots that will exposed to attacker? And what appears in your mind immediately? Calm down and have a brainstorm WHITELIST! Web Security : Theory And Applications 71 / 128
Whitelist model is a kind of positive prevention model. In this model, the slots are defined and a few examples of each are provided. Developers should not put data into any other slots without a very careful analysis to ensure that what they are doing is safe. Browser parsing is extremely tricky and many innocuous looking characters can be significant in the right context. Web Security : Theory And Applications 72 / 128
Imagine this: You want to create a page whose background color can be changed by users. Emm.. Will an <input> tag be right <select name= Bgcolor > for receiving users <option value= #F00 >red</option> <option value= #0F0 >green</option> input? Like this. <option Cheers! value= #00F >blue</option> I m </select> gonna design my first web page. <input type= text name= Bgcolor /> A <select> tag works better indeed, though the choices are limited. Web Security : Theory And Applications 73 / 128
Escaping Escaping is a technique used to ensure that characters are treated as data, not as characters that are relevant to the interpreter s parser. You see that if we treat users input as string or some other type of data instead of characters that can be parsed by the interpreter, the code injection seems to be kept away from our website. Example: The plain input : <script> After escaping: <script> As we know, < equals < and > equals > in HTML, just like \\ means \ in C. Web Security : Theory And Applications 74 / 128
Note: There re a lot of escaping functions in programming language, like PHP s htmlspecialchars() function and so on. But do remember that javascript also has a function called escape(), but it only makes a string portable not for security. Escaping is the primary means to make sure that untrusted data can t be used to convey an injection attack. There is no harm in escaping data properly it will still render in the browser properly. Escaping simply lets the interpreter know that the data is not intended to be executed, and therefore prevents attacks from working. Web Security : Theory And Applications 75 / 128
You Need a Security Encoding Library OWASP recommends using a security-focused encoding library to make sure these rules are properly implemented. The OWASP ESAPI project has created an escaping library in a variety of languages including Java,.NET, PHP, Classic ASP, Cold Fusion, Python, and Haskell. The ESAPI library can be used for escaping as described here and also for decoding (aka canonicalization), which is critical for input validation. Microsoft provides an encoding library named AntiXSS. Web Security : Theory And Applications 76 / 128
Give Your Own Rules The following rules are intended to prevent all XSS in your application. They should cover the vast majority of common use cases. (You do not have to allow all the rules in your organization) RULE #0 - Never Insert Untrusted Data Except in Allowed Locations RULE #1 - HTML Escape Before Inserting Untrusted Data into HTML Element Content RULE #2 - Attribute Escape Before Inserting Untrusted Data into HTML Common Attributes RULE #3 - JavaScript Escape Before Inserting Untrusted Data into HTML JavaScript Data Values RULE #4 - CSS Escape Before Inserting Untrusted Data into HTML Style Property Values Web Security : Theory And Applications 77 / 128
RULE #5 - URL Escape Before Inserting Untrusted Data into HTML URL Parameter Values RULE #6 - Use an HTML Policy engine to validate or clean user-driven HTML in an outbound way RULE #7 - Prevent DOM-based XSS Many organizations may find that allowing only Rule #1 and Rule #2 are sufficient for their needs. Web Security : Theory And Applications 78 / 128
10.2.6 CSRF & XSSI Brief Introduction to XSRF & XSSI Methods effective to avert XSRF & XSSI Questions you may have Web Security : Theory And Applications 79 / 128
Brief Introduction to CSRF & XSSI Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious Web site, email, blog, instant message, or program causes a user s Web browser to perform an unwanted action on a trusted site for which the user is currently authenticated. Web Security : Theory And Applications 80 / 128
Cross Site Script Inclusion (XSSI): Browsers prevent pages of one domain from reading pages in other domains. But they do not prevent pages of a domain from referencing resources in other domains. In particular, they allow images to be rendered from other domains and scripts to be executed from other domains. An included script doesn't have its own security context. It runs in the security context of the page that included it. Web Security : Theory And Applications 81 / 128
A CSRF diagram Web Security : Theory And Applications 82 / 128
So that s really terrible if the XSRF or XSSI attack works. Do you have some effective measures in mind to prevent your web pages from them? Before we learning the measures, let s have a look at some measures which do not work and discuss why. 1. Using a Secret Cookie 2. Only Accepting POST Requests 3. Multi-Step Transactions 4. URL Rewriting Web Security : Theory And Applications 83 / 128
Effective Methods Synchronizer Token Pattern Checking Referer Header Client/User Prevention No Cross-Site Scripting (XSS) Vulnerabilities Web Security : Theory And Applications 84 / 128
Synchronizer Token Pattern When a Web application formulates a request, the application should include a hidden input parameter with a common name such as "CSRF Token". Like this <form> <input type= hidden id= CSRFToken value= values Hackers cannot get > </form> Web Security : Theory And Applications 85 / 128
The synchronizer token pattern requires the generating of random "challenge" tokens that are associated with the user's current session. These challenge tokens are the inserted within the HTML forms and links associated with sensitive serverside operations. When the user wishes to invoke these sensitive operations, the HTTP request should include this challenge token. Checking Referer Header This method is desirable for securing embedded network hardware such as modems, routers, and printers because it does not increase memory requirements. Web Security : Theory And Applications 86 / 128
Client/User Prevention Logoff immediately after using a Web application Do not allow your browser to save username/passwords, and do not allow sites to remember your login Do not use the same browser to access sensitive applications and to surf the Internet freely (tabbed browsing). The use of plugins such as No-Script makes POST based CSRF vulnerabilities difficult to exploit. This is because JavaScript is used to automatically submit the form when the exploit is loaded. Without JavaScript the attacker would have to trick the user into submitting the form manually. Web Security : Theory And Applications 87 / 128
No XSS Vulnerabilities Cross-Site Scripting is not necessary for CSRF to work. However, all stored cross-site scripting attacks and special case reflected cross-site scripting attacks can be used to defeat token based CSRF defenses, since a malicious XSS script can simply read the site generated token from the response, and include that token with a forged request. Web Security : Theory And Applications 88 / 128
10.2.7 Arbitrary Code Execution Introduction Severity Causes Defenses Experiments Web Security : Theory And Applications 89 / 128
Introduction Arbitrary code execution: an attacker's ability to execute any commands of the attacker's choice on a target machine or in a target process Most allow the execution of machine code Most inject and execute shellcode to give an attacker an easy way to manually run arbitrary commands Web Security : Theory And Applications 90 / 128
Severity Usually GAME OVER Attackers may be able to take control over the running program What s worse, they may break out the process to open a new shell on the computer From here, it's usually not hard to compromise the entire machine the server is running on There is often an attempt at a privilege escalation exploit in order to gain additional control Web Security : Theory And Applications 91 / 128
Causes Malware Control over the program counter (instruction pointer) of a running process Control over which instruction is executed next Inject code into the process Change the instruction pointer to have it point to the injected code Von Neumann architecture computers: do not make a general distinction between code and data Many newer CPUs have mechanisms to make this harder, such as a no-execute bit Web Security : Theory And Applications 92 / 128
Defenses No recipe or specific defense to prevent remote code execution A short list of some preventative measures Least Privilege: always run your application with the least privileges it needs Application Level Checks: avoid passing user input directly into commands that evaluate arbitrary code, like eval() or system(). Instead, use the user input as a switch to choose from a set of developer controlled commands Bounds Checks: implement proper bounds checks for non-safe languages like C++. Avoid unsafe string functions. Keep in mind that even safe languages like Python and Java use native libraries Web Security : Theory And Applications 93 / 128
10.2.8 Configuration Vulnerabilities Introduction Causes Severity Vulnerabilities Examples Defenses Experiments Web Security : Theory And Applications 94 / 128
Introduction Good security requires having a secure configuration defined and deployed for the application, frameworks, application server, web server, database server, and platform All these settings should be defined, implemented, and maintained as many are not shipped with secure defaults This includes keeping all software up to date, including all code libraries used by the application Web Security : Theory And Applications 95 / 128
Security misconfiguration in OWASP Top 10 Web Security : Theory And Applications 96 / 128
Causes Default settings: attackers can use them to attack your third party software, because they have easy access to a copy of it and they know the default account names and passwords Features that increase attack surface ( 表 面 积 ): a common example is a feature that is on by default but you are not using, so you didn't configure it and the default configuration is vulnerable Web Security : Theory And Applications 97 / 128
Severity Incorrect configurations can open Web sites to application security holes such as session hijacking, Cross-Site Scripting attacks, and even allow the disclosure of private data to attackers Web Security : Theory And Applications 98 / 128
Vulnerabilities Examples Early versions of the fingerd service finger: displays information about the system users In servicing a query finger user, this program needs to read a file named.plan in the home directory of user The fingerd service runs with root privileges, and in the earlier versions of UNIX used to open the.plan as root User u could symbolically link a file f as his/her.plan even if u has no read access to f User u can then read f by simply running finger u Web Security : Theory And Applications 99 / 128
Defenses Strategies Overview Default Passwords Secure Connection Strings Secure Network Transmission Encrypted Data Database Security Model-Based Analysis of Configuration Vulnerabilities Error Handling Web Security : Theory And Applications 100 / 128
Strategies Overview Turn off all unnecessary features by default Ensure that all switches and configuration for every feature is configured initially to be the safest possible choice Inspect the design to see if the less safe choices could be designed in another way e.g., password reset systems are intrinsically unsound from a security point of view. If you do not ship this component, your application s users will be safer Do not configure anything in preparation for an optionally deployable feature Web Security : Theory And Applications 101 / 128
Default Passwords Problems Applications often ship with well-known passwords Example: in a particularly excellent effort, NGS Software determined that Oracle s Unbreakable database server contained 168 default passwords out of the box Defenses Do not ship the product with any configured accounts Do not hard code any backdoor accounts or special access mechanisms Web Security : Theory And Applications 102 / 128
Secure Connection Strings Problem: connection strings to the database are rarely encrypted Defenses: Sometimes, no password is just as good as a clear text password Develop a method to obfuscate the password in some form, such as encrypting the name using the hostname or similar within code in a nonobvious way Ask the database developer to provide a library which allows remote connections using a password hash instead of a clear text credential Web Security : Theory And Applications 103 / 128
Secure Network Transmission Problem: by default, no unencrypted data should transit the network Defense: Use SSL, SSH and other forms of encryption (such as encrypted database connections) to prevent data from being intercepted or interfered with over the wire Web Security : Theory And Applications 104 / 128
Encrypted Data Problems: Some information security policies and standards require the database on-disk data to be encrypted But this is essentially useless if the database connection allows clear text access to the data Web Security : Theory And Applications 105 / 128
Defenses Passwords should only be stored in a nonreversible format, such as SHA-256 or similar Sensitive data like credit cards should be carefully considered do they have to be stored at all? Encrypted data should not have the key on the database server The encryption key should be able to be changed on a regular basis, and the algorithm should be sufficient to protect the data in a temporal timeframe Web Security : Theory And Applications 106 / 128
Database Security Problems Data obtained from the user needs to be stored securely Data shouldn t be obtained from the database itself Defenses The application should connect to the database using as low privilege user as is possible The application should connect to the database with different credentials for every trust distinction (e.g., user, read-only user, guest, administrators) and permissions applied to those tables and databases to prevent unauthorized access and modification The application should prefer safer constructs, such as stored procedures which do not require direct table access. Once all access is through stored procedures, access to the tables should be revoked Web Security : Theory And Applications 107 / 128
Defenses (continued) * For highly protected applications: The database should be on another host, which should be locked down with all current patches deployed and latest database software in use The application should connect to the database using an encrypted link. If not, the application server and database server must reside in a restricted network with minimal other hosts Do not deploy the database server in the main office network Web Security : Theory And Applications 108 / 128
Model-Based Analysis of Configuration Vulnerabilities: a method for automated and systematic analysis of system misconfiguration, from a paper with the same name, by C.R. Ramakrishnan and R. Sekar Main points Construction of high-level models of system components Formal statement of desired security-relevant properties of the composite system Automated analysis of system model to check deviation from desired security properties Web Security : Theory And Applications 109 / 128
Error Handling An important aspect of secure application development is to prevent information leakage. Error messages give an attacker great insight into the inner workings of an application Defenses Checked exceptions: the compiler shall complain if an exception for a particular API call is not caught. Java and C# are good examples of this, though not all types of error are checked; languages like C++ and C do not provide this safety When an exception or error is thrown we also need to log this occurrence Web Security : Theory And Applications 110 / 128
10.2.9 AJAX vulnerabilities Introduction How Does It Work AJAX Example Attacks and Vulnerabilities Defenses AJAX Security Tools Experiments Web Security : Theory And Applications 111 / 128
Introduction AJAX = Asynchronous JavaScript and XML AJAX is a technique for creating fast and dynamic web pages AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. But classic web pages, (which do not use AJAX) must reload the entire page if the content should change Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs Web Security : Theory And Applications 112 / 128
How Does It Work Here is a figure demonstrating how AJAX works Web Security : Theory And Applications 113 / 128
AJAX is based on internet standards, and uses a combination of XMLHttpRequest object: to exchange data asynchronously with a server JavaScript/DOM: to display/interact with the information CSS (to style the data) XML/JSON (JavaScript Object Notation): the format for transferring data Browser-and-platform-independent Web Security : Theory And Applications 114 / 128
Attacks and Vulnerabilities Vulnerabilities Overview XMLHttpRequest Vulnerabilities Increased Attack Surface SQL Injection XSS Client Side Injection Threats AJAX Bridging CSRF DoS Browser Based Attacks Web Security : Theory And Applications 115 / 128
Vulnerabilities Overview Increased attack surface with many more inputs to secure Exposed internal functions of the application Client access to third-party resources with no built-in security and encoding mechanisms Failure to protect authentication information and sessions Blurred line between client-side and server-side code Web Security : Theory And Applications 116 / 128
Defenses Philosophies Overview: You must start with good planning. Efforts should be focused on reducing and simplifying the AJAX calls, and creating a standard format for responses that follows convention (ideally XML) where possible Follow best practice from sites such as the OWASP. This especially includes checking for Access Control and Input Validation flaws, whilst ensuring sensitive information travels over SSL rather than in the clear Never assume that browser side AJAX checks for access control or user input validation will replace the need for final rechecking at the Server. Adding AJAX controls will never reduce your validation workload, they will only increase it Web Security : Theory And Applications 117 / 128
Philosophies Overview (continued): Never assume that Client Side obfuscation (making the JavaScript difficult to read or decode) will protect your most important commercial secrets. Using JavaScript is a poor way to hide programming tricks and advances from your competitors Finally, you must be prepared to exercise a tight reign over your development team. Wonderful ideas using AJAX may sound compelling, but you should consider saving them for version 2, whilst you focus on building a rock-solid version Web Security : Theory And Applications 118 / 128
AJAX Security Tools Hardening tools assl HTMLProtector Acunetix Web Vulnerability Scanner Free Edition AjaxDNS Tools Despoof 2. Firefox tools Setting your master password Setting privacy options 3. Firefox add-ons Session Manager Homeland Security Threat Levels WiKID Web Security : Theory And Applications 119 / 128
Example: MySpace Attack What happened Samy (also known as JS.Spacehero) was an XSS worm developed to propagate across the MySpace social-networking site Carried a payload that would display the string "but most of all, Samy is my hero" on a victim's profile When a user viewed that profile, they would have the payload planted on their page. Within just 20 hours of its October 4, 2005 release, over one million users had run the payload, making Samy one of the fastest spreading viruses of all time Execution of the payload resulted in a friend request automatically being made to the author of the virus and in messages containing the payload being left on the profiles of the friends of the victim Web Security : Theory And Applications 120 / 128
Attacking method A combination of XSS tricks and lax security in certain Web browsers Trick: not <script>..</script>, but <div style="background:url('javascript:alert(1)')"> Browser fault: java<newline>script Trick: eval () Also utilized XMLHTTPRequest - a JavaScript object used in AJAX Web Security : Theory And Applications 121 / 128
Example: Yahoo! Mail Attack In June 2006, the Yamanner worm infected Yahoo's mail service The worm, using XSS and AJAX, took advantage of a vulnerability in Yahoo Mail's onload event handling When an infected email was opened, the worm code executed its JavaScript, sending a copy of itself to all the Yahoo contacts of the infected user The infected email carried a spoofed 'From' address picked randomly from the infected system, which made it look like an email from a known user. Web Security : Theory And Applications 122 / 128
References 1. http://developer.51cto.com/art/201106/268236.htm 2. http://www.jdon.com/idea/cgi.htm 3. http://en.wikipedia.org/wiki/web_service 4. http://google-gruyere.appspot.com/part1 5. http://en.wikipedia.org/wiki/common_gateway_interface 6. http://www.jdon.com/idea/cgi.htm 7. http://www.webopedia.com/term/c/cgi.html 8. http://www.jdon.com/idea/cgi.htm 9. http://www.parkansky.com/tutorials/bdlogcgi.htm 10. http://www.85flash.com/get/wangyebiancheng/perl/2006-8- 17/205923183_3.html 11. http://en.wikipedia.org/wiki/web_service 12. http://en.wikiversity.org/wiki/web_service 13. http://www.w3schools.com/webservices/default.asp 14. http://www.w3.org/tr/ws-arch/ Web Security : Theory And Applications 123 / 128
References 15. https://publib.boulder.ibm.com/infocenter/cicsts/v4r1/index.jsp?topic= %2Fcom.ibm.cics.ts.webservices.doc%2Fconcepts%2Fdfhws_definit ion.html 16. http://www.webopedia.com/term/w/web_services.html 17. http://en.wikipedia.org/wiki/database_connection 18. http://en.wikipedia.org/wiki/odbc 19. http://en.wikipedia.org/wiki/activex_data_objects 20. http://en.wikipedia.org/wiki/ole_db 21. http://en.wikipedia.org/wiki/jdbc 22. http://en.wikipedia.org/wiki/arbitrary_code_execution 23. http://google-gruyere.appspot.com/part4#4 code_execution 24. http://google-gruyere.appspot.com/part5 25. http://h71028.www7.hp.com/erc/cache/571914-0-0-0-121.html 26. http://www.lumension.com/vulnerability-management/securityconfiguration-management.aspx Web Security : Theory And Applications 124 / 128
References 27. C.R. Ramakrishnan and R. Sekar, Model-Based Analysis of Configuration Vulnerabilities 28. https://www.owasp.org/index.php/top_10_2010-a6 29. http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first 30. http://www.w3schools.com/ajax/ajax_intro.asp 31. http://www.w3schools.com/ajax/ajax_example.asp 32. https://www.owasp.org/index.php/top_10_2010-main 33. https://www.owasp.org/index.php/configuration 34. https://www.owasp.org/index.php/error_handling 35. https://www.owasp.org/index.php/testing_for_configuration_manage ment 36. https://www.owasp.org/index.php/testing_for_error_code_(owasp- IG-006) 37. https://www.owasp.org/index.php/testing_for_ajax_vulnerabilities_ (OWASP-AJ-001) Web Security : Theory And Applications 125 / 128
References 38. http://namb.la/popular/tech.html 39. http://webhostinggeeks.com/blog/2009/04/13/the-vulnerability-ofajax-applications/ 40. http://antivirus.about.com/b/2007/09/19/ajax-vulnerabilities-how-bigthe-threat.htm 41. http://www.scmagazineus.com/hot-or-not-ajaxvulnerabilities/article/35698/ 42. http://www.betanews.com/article/crosssite-scripting-worm-hits- MySpace/1129232391 43. http://antivirus.about.com/od/securitytips/a/plainttextemail.htm 44. http://google-gruyere.appspot.com/part5#5 ajax_vulnerabilities 45. http://php.net/manual/en/book.oci8.php 46. http://php.net/manual/en/book.mysql.php 47. http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_suggest 48. http://en.wikipedia.org/wiki/samy_(xss) Web Security : Theory And Applications 126 / 128
References 49. http://www.it-observer.com/ajax-security.html 50. http://www.ibm.com/developerworks/web/library/wa-ajsectools/index.html 51. http://en.wikipedia.org/wiki/aptana 52. http://en.wikipedia.org/wiki/adobe_dreamweaver 53. http://en.wikipedia.org/wiki/eclipse_%28software%29 54. http://en.wikipedia.org/wiki/adobe_flash_builder 55. http://en.wikipedia.org/wiki/adobe_flex 56. http://en.wikipedia.org/wiki/intellij_idea 57. http://en.wikipedia.org/wiki/netbeans 58. http://www.mpsoftware.dk/phpdesigner.php 59. http://en.wikipedia.org/wiki/microsoft_visual_studio 60. http://en.wikipedia.org/wiki/microsoft_visual_studio_express#visual _Web_Developer_Express 61. http://en.wikipedia.org/wiki/zend_studio Web Security : Theory And Applications 127 / 128
Thank you! Web Security : Theory And Applications 128 / 128