• No results found

Secure Web Programming

N/A
N/A
Protected

Academic year: 2021

Share "Secure Web Programming"

Copied!
128
0
0

Loading.... (view fulltext now)

Full text

(1)

Web Security: Theory & Applications

School of Software, Sun Yat-sen University

Module IV. Web Security (II)

Chapter 10

(2)

Outline

10.1 Introduction to Web Programming

Tools for Web Development

Designing CGI

Implementing Web Services
(3)

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
(4)

10.1 Introduction to Web Programming

 Tools for Web Development  Designing CGI

 Implementing Web Services

(5)

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
(6)

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).

(7)

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.

(8)

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.

(9)

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.
(10)

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.

(11)

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.

(12)

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.

(13)

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.

(14)

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.

(15)

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.

(16)

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, design-time validation for standards including XHTML 1.0/1.1 and CSS 2.1.

(17)

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).

(18)

10.1.2 Designing CGI

Introduction

Comparisons with Other Scripting Techniques

Requirements for CGI Scripting

Running CGI Scripts

CGI Variables

Advantages

Disadvantages

Alternatives
(19)

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
(20)

Comparisons with other scripting techniques

(21)

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
(22)

Running CGI Scripts

CGI in the server system
(23)

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
(24)

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.
(25)

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 HTML

application/x-www-form-urlencoded

(26)

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
(27)

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

(28)

Disadvantages

Each execution: invocation of a newly created process

Worse if scripts need to be interpreted or compiled

Server may be overwhelmed
(29)

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
(30)

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
(31)

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
(32)

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 time-consuming custom coding

Java can talk with Perl; Windows applications can talk with UNIX applications; etc.
(33)

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 XML-based language that provides a model for describing Web services
(34)

Web services architecture

(35)

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
(36)

How Does It Work

The general process of engaging a Web service
(37)

 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)
(38)

Semantics

WSD: a contract governing the mechanics of interacting with a particular service

Semantics: a contract governing the meaning and purpose of that interaction
(39)

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
(40)

Interactions

Web services components and interactions
(41)

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

(42)

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.

(43)

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
(44)

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
(45)

10.1.4 Accessing Database Through Web

Introduction

API’s
(46)

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;
(47)

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. (导致过高的管理耗费)

(48)

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
(49)

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
(50)

10.2.1 Introduction to Gruyere Codelab

What Is It & What Is It For

Requirements

How to Use
(51)

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.

(52)

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.
(53)

10.2.2 Brief Introduction to Python

Basic Idea and Rudimentary Syntax

Setting Environment for Python Programming

Learn Python
(54)

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.
(55)

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.
(56)

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
(57)

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.
(58)

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
(59)

10.2.4 Denial of Service (DoS)

Types of DoS Attacks

Defending against Smurf and Fraggle

Defending against SYN Flood
(60)

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.

(61)

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.

(62)

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.

(63)

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)

(64)

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 (人工干预):
(65)

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.

(66)

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.
(67)

10.2.5 Leave no space for XSS

 Brief introduction to XSS

 Methods effective to avert XSS  Questions you may have

(68)

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.

(69)

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.

(70)

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.
(71)

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!”
(72)

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.

(73)

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>

(74)

“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: &ltscript&gt

As we know, &lt equals ‘<‘ and &gt equals ‘>’ in HTML, just like ‘\\’ means ‘\’ in C.
(75)

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.

(76)

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.

(77)

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
(78)

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.
(79)

10.2.6 CSRF & XSSI

 Brief Introduction to XSRF & XSSI

 Methods effective to avert XSRF & XSSI  Questions you may have

(80)

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.

(81)

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.

(82)

A CSRF diagram
(83)

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

(84)

Effective Methods

Synchronizer Token Pattern

Checking Referer Header

Client/User Prevention

No Cross-Site Scripting (XSS) Vulnerabilities
(85)

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>

(86)

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 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 memory

requirements.

(87)

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.

(88)

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.

(89)

10.2.7 Arbitrary Code Execution

Introduction

Severity

Causes

Defenses

Experiments
(90)

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
(91)

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
(92)

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
(93)

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
(94)

10.2.8 Configuration Vulnerabilities

Introduction

Causes

Severity

Vulnerabilities Examples

Defenses

Experiments
(95)

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
(96)

Security misconfiguration in OWASP Top 10
(97)

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

(98)

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

(99)

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
(100)

Defenses

Strategies Overview

Default Passwords

Secure Connection Strings

Secure Network Transmission

Encrypted Data

Database Security

Model-Based Analysis of Configuration Vulnerabilities

Error Handling
(101)

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
(102)

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
(103)

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

non-obvious way

Ask the database developer to provide a library which allows remote connections using a

password hash instead of a clear text credential

(104)

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

(105)

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
(106)

Defenses

Passwords should only be stored in a non-reversible 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

(107)

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

(108)

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
(109)

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
(110)

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
(111)

10.2.9 AJAX vulnerabilities

Introduction

How Does It Work

AJAX Example

Attacks and Vulnerabilities

Defenses

AJAX Security Tools

Experiments
(112)

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
(113)

How Does It Work

Here is a figure demonstrating how AJAX works
(114)

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
(115)

Attacks and Vulnerabilities

Vulnerabilities Overview

XMLHttpRequest Vulnerabilities

Increased Attack Surface

SQL Injection

XSS

Client Side Injection Threats

AJAX Bridging

CSRF

DoS

Browser Based Attacks
(116)

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
(117)

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 re-checking at the Server. Adding AJAX controls will never reduce your validation workload, they will only increase it

(118)

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
(119)

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
(120)

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

(121)

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
(122)

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.
(123)

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/
(124)

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.aspx
(125)

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)

(126)

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)
(127)

References

49. http://www.it-observer.com/ajax-security.html 50. http://www.ibm.com/developerworks/web/library/wa-aj-sectools/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
(128)

References

Related documents

Podjetje je imelo v obdobju pred povišanjem DDV močno negativen neto obratni kapital, vendar so ga pozneje močno izboljšali, zadnji dve leti je bil celo pozitiven, kar pomeni, da

Middle/intermediate and high school teachers believed challenges of implementing games effectively to be a more serious barrier than primary school teachers, while primary school

In order to probe Intangible Benefits as in table 5, the highest ranking by mean degree of benefits in managerial benefits are “Better resource management “and

Komunikasi pengguna HT biasanya melakukan perubahan frekuensi mereka jika terjadi hal-hal yang dapat mengganggu privasi komunitas.Perubahan frekuensi pada stasiun

On appeal, however, the Fifth Circuit reversed, holding that the failure to place wheelchair accessible seats within the stadium-style section of theaters does not

Boudart, Jesse Alexander, &#34;Bus Replacement Modeling and the Impacts of Budget Constraints, Fleet Cost Variability, and Market Changes on Fleet Costs and Optimal Bus Replacement

These early interactions in my career intrigued me to pursue special education, primarily working with autism, and also resulted in the research conducted in answering the question

The stages of creating and analysing risk factors, the zones of amplification of disruptions as well as designing the IT tool and simulation models (Can &amp; Chan, 2006), (Celik,