Web Security: Theory & Applications
School of Software, Sun Yat-sen University
Module IV. Web Security (II)
Chapter 10
Outline
10.1 Introduction to Web Programming
•
Tools for Web Development•
Designing CGI•
Implementing Web ServicesOutline
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 Vulnerabilities10.1 Introduction to Web Programming
Tools for Web Development Designing CGI
Implementing Web Services
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 Aptana Studio
•
Aptana Studio is an open source integrateddevelopment 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).
Adobe Dreamweaver
•
Adobe Dreamweaver (formerly, MacromediaDreamweaver) is a web development application originally created by Macromedia, and is now
developed by Adobe System, which acquired Macromedia in 2005.
•
Dreamweaver allows users to preview websites inlocally 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.
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. 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.
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.
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.0support, Dependency and Data Flow Analysis, Apache Maven support as well as a lot of other features and technologies.
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.
PhpDesigner
•
The latest version of PhpDesigner is phpDesigner 7.•
PhpDesigner 7 is more than just a powerful andlightning 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.
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, webapplications, 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.
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 theother 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, design-time validation for standards including XHTML 1.0/1.1 and CSS 2.1.
Zend Studio
•
Zend Studio is a commercial, proprietary integrateddevelopment 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).
10.1.2 Designing CGI
•
Introduction•
Comparisons with Other Scripting Techniques•
Requirements for CGI Scripting•
Running CGI Scripts•
CGI Variables•
Advantages•
Disadvantages•
Alternatives 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 Comparisons with other scripting techniques
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 Running CGI Scripts
•
CGI in the server system•
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 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.•
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 /cgi-bin/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 HTMLapplication/x-www-form-urlencoded
•
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 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
Disadvantages
•
Each execution: invocation of a newly created process•
Worse if scripts need to be interpreted or compiled•
Server may be overwhelmed 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•
Libraries10.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 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 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 andprocesses 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 time-consuming custom coding•
Java can talk with Perl; Windows applications can talk with UNIX applications; etc. Web Services Platform Elements
•
SOAP (Simple Object Access Protocol): a protocol specification for exchanging structured information in the implementation of Web Services in computernetworks
•
Nothing to do with SOA (Service-oriented Architecture)•
UDDI (Universal Description, Discovery andIntegration): 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 XML-based language that provides a model for describing Web services Web services architecture
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 How Does It Work
•
The general process of engaging a Web service 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 themessage 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) Semantics
•
WSD: a contract governing the mechanics of interacting with a particular service•
Semantics: a contract governing the meaning and purpose of that interaction 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 Interactions
•
Web services components and interactions•
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 aservice registry for the service requester to find
•
Find: When a service registry is used, a servicerequester finds the service description in the registry
•
Bind: The service requester uses the servicedescription to bind with the service provider and interact with the Web service implementation
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.
•
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 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 orintegrators, 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 interface10.1.4 Accessing Database Through Web
•
Introduction•
API’s 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;•
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 moreoverhead. (导致过高的管理耗费)
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
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 Vulnerabilities10.2.1 Introduction to Gruyere Codelab
•
What Is It & What Is It For•
Requirements•
How to Use 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 requestforgery, 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 inGruyere and in general.
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.10.2.2 Brief Introduction to Python
•
Basic Idea and Rudimentary Syntax•
Setting Environment for Python Programming•
Learn Python 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. 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 Emacsand Eclipse for Python, etc.
Learn Python
•
Read books. For beginners, LearnPythonTheHardWayhttp://learnpythonthehardway.org/book/ is recommended.
•
Practice more. Try to program something more practical in life.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 How to Avoid Path Traversal Vulnerabilities
•
Identify if you are vulnerable.•
Be sure you understand how the underlyingoperating 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. 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 vulnerability10.2.4 Denial of Service (DoS)
•
Types of DoS Attacks•
Defending against Smurf and Fraggle•
Defending against SYN Flood Types of DoS Attacks
•
Bandwidth Consumption: This kind of attack usually consumes all available bandwidth in a variety ofinsidious 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.
•
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 attacksconvince server to cache bogus address information. Besides, DNS packets are also a major tools for
amplifying use.
Example: Routing and DNS attacks.
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 Filteringwhich rejects the attacking packets on the basis of the forged source address.
•
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)
•
Contingency Strategy (意外响应策略): To respondsuccessfully 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 (人工干预): Defending against SYN Flood
•
Check SYN_RECV: To determine if you are under attack, you can issue the netstat command if it issupported 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.
•
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 iscryptographically 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.10.2.5 Leave no space for XSS
Brief introduction to XSS
Methods effective to avert XSS Questions you may have
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.
•
Cross-site scripting (XSS) is a type of computersecurity 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 adata 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 bugcaused 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.
•
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. 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 mindimmediately?
•
Calm down and have a brainstorm…“WHITELIST!”•
Whitelist model is a kind of positive prevention model.•
In this model, the slots are defined and a fewexamples 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.
•
Imagine this: You want to create a page whose background color can be changed by users.Cheers! I’m gonna design
my first web page.
Emm.. Will an <input> tag be right
for receiving users’ input? Like this.
<input type=‘text’ name=‘Bgcolor’ />
<input type=‘text’ name=‘Bgcolor’ />
A <select> tag works better indeed, though the choices
are limited. <select name=‘Bgcolor’> <option value=‘#F00’>red</option> <option value=‘#0F0’>green</option> <option value=‘#00F’>blue</option> </select> <select name=‘Bgcolor’> <option value=‘#F00’>red</option> <option value=‘#0F0’>green</option> <option value=‘#00F’>blue</option> </select>
•
“Escaping”•
“Escaping” is a technique used to ensure thatcharacters 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.•
Note: There’re a lot of escaping functions in programming language, like PHP’shtmlspecialchars() 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.
•
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 anescaping 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.
•
Give Your Own Rules•
The following rules are intended to prevent all XSS in your application. They should cover the vastmajority 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•
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.10.2.6 CSRF & XSSI
Brief Introduction to XSRF & XSSI
Methods effective to avert XSRF & XSSI Questions you may have
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 currentlyauthenticated.
•
Cross Site Script Inclusion (XSSI): Browsers prevent pages of one domain from reading pages in otherdomains. 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.
•
A CSRF diagram•
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
Effective Methods
•
Synchronizer Token Pattern•
Checking Referer Header•
Client/User Prevention•
No Cross-Site Scripting (XSS) Vulnerabilities•
Synchronizer Token Pattern•
When a Web application formulates a request , the application should include a hidden inputparameter with a common name such as "CSRF Token". Like this
<form> …
<input type=‘hidden’ id=‘CSRFToken’ value=‘values Hackers cannot get’>
…
</form>
•
The synchronizer token pattern requires thegenerating 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 server-side 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 memoryrequirements.
•
Client/User Prevention•
Logoff immediately after using a Web application•
Do not allow your browser to saveusername/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. WithoutJavaScript the attacker would have to trick the user into submitting the form manually.
•
No XSS Vulnerabilities•
Cross-Site Scripting is not necessary for CSRF to work. However, all stored cross-site scriptingattacks 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.
10.2.7 Arbitrary Code Execution
•
Introduction•
Severity•
Causes•
Defenses•
Experiments•
Introduction•
Arbitrary code execution: an attacker's ability toexecute 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•
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•
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•
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 developercontrolled 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 libraries10.2.8 Configuration Vulnerabilities
•
Introduction•
Causes•
Severity•
Vulnerabilities Examples•
Defenses•
Experiments 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 securedefaults
•
This includes keeping all software up to date, including all code libraries used by the application•
Security misconfiguration in OWASP Top 10 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 (表面积): acommon 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
Severity
•
Incorrect configurations can open Web sites toapplication security holes such as session hijacking, Cross-Site Scripting attacks, and even allow the
disclosure of private data to attackers
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 Defenses
•
Strategies Overview•
Default Passwords•
Secure Connection Strings•
Secure Network Transmission•
Encrypted Data•
Database Security•
Model-Based Analysis of Configuration Vulnerabilities•
Error Handling•
Strategies Overview•
Turn off all unnecessary features by default•
Ensure that all switches and configuration for every feature is configured initially to be the safestpossible 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•
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 defaultpasswords 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•
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 anon-obvious way
•
Ask the database developer to provide a library which allows remote connections using apassword hash instead of a clear text credential
•
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 databaseconnections) to prevent data from being intercepted or interfered with over the wire
•
Encrypted Data•
Problems:•
Some information security policies andstandards 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•
Defenses•
Passwords should only be stored in a non-reversible format, such as SHA-256 or similar•
Sensitive data like credit cards should becarefully 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 bechanged on a regular basis, and the algorithm should be sufficient to protect the data in a
temporal timeframe
•
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 withdifferent 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 asstored procedures which do not require direct table access. Once all access is through stored procedures, access to the tables should be revoked
•
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•
Model-Based Analysis of Configuration Vulnerabilities:•
a method for automated and systematic analysis of system misconfiguration, from a paper with thesame 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•
Error Handling•
An important aspect of secure applicationdevelopment 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 notcaught. 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 occurrence10.2.9 AJAX vulnerabilities
•
Introduction•
How Does It Work•
AJAX Example•
Attacks and Vulnerabilities•
Defenses•
AJAX Security Tools•
Experiments 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 thewhole 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 How Does It Work
•
Here is a figure demonstrating how AJAX works•
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 Attacks and Vulnerabilities
•
Vulnerabilities Overview•
XMLHttpRequest Vulnerabilities•
Increased Attack Surface•
SQL Injection•
XSS•
Client Side Injection Threats•
AJAX Bridging•
CSRF•
DoS•
Browser Based Attacks•
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 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 accesscontrol or user input validation will replace the need for final re-checking at the Server. Adding AJAX controls will never reduce your validation workload, they will only increase it
•
Philosophies Overview (continued):•
Never assume that Client Side obfuscation (making theJavaScript 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 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 Example: MySpace Attack
•
What happened•
Samy (also known as JS.Spacehero) was an XSS wormdeveloped 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
•
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 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.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/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/security-configuration-management.aspxReferences
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)
References
38. http://namb.la/popular/tech.html 39. http://webhostinggeeks.com/blog/2009/04/13/the-vulnerability-of-ajax-applications/ 40. http://antivirus.about.com/b/2007/09/19/ajax-vulnerabilities-how-big-the-threat.htm 41. http://www.scmagazineus.com/hot-or-not-ajax-vulnerabilities/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)