Saturday, June 22, 2013

TODO: ESAPI, Spring Security, Tomcat




Java Security:
http://docs.redhat.com/docs/en-US/JBoss_Enterprise_Application_Platform/5/html/Security_Guide/chap-Java_EE_Security_Manager.html

http://java.sun.com/developer/onlineTraining/Programming/JDCBook/appA.html

http://onjava.com/onjava/2007/01/03/discovering-java-security-requirements.html

http://www.techrepublic.com/article/java-security-policies-and-permission-management/6178805



Spring

CROSS SITE REQUEST FORGERY AND OAUTH2


http://java.dzone.com/tips/pathway-acegi-spring-security-
http://forum.springsource.org/showthread.php?93561-Remote-authentication-over-HTTP-Basic-Auth

JOSSO - Java Open Single Sign-On Project HomeJOSSO is an Open Source Internet SSO solution for rapid and standards-based (SAML) Internet-scale Single Sign-On implementations, allowing secure Internet access to the Web-based applications or services of customers, suppliers, and business partners.





tomcat
http://www.kopz.org/public/documents/tomcat/jaasintomcat.html


Implementing Ajax Authentication using jQuery, Spring Security and HTTPS
Java Web Application Security - Part I: Java EE 6 Login Demo
Java Web Application Security - Part II: Spring Security Login Demo
Java Web Application Security - Part III: Apache Shiro Login Demo
Java Web Application Security - Part IV: Programmatic Login APIs
Java Web Application Security - Part IV: Programmatic Login APIs


ESAPI
https://lists.owasp.org/pipermail/owasp-esapi/2009-September/000883.html


ESAPI-Spring Authenticator







Saturday, June 1, 2013

Security: OWASP ESAPI


ESAPI
  • Create a standardized mechanism for Java EE applications to address security concerns
  • ESAPI is NOT a framework.  It’s a set of well defined interfaces and a reference
  • implementation of the “right” way to do security controls


Input Validation & Encoding

  • Canonicalizing - reducing a possibly encoded string down to its simplest form.
  • Double encoding is not something a user does so generally regarded as an attack
  • Encoding - various methods for different destinations. Whitelist acceptable characters and encode those that don’t pass muster 
  • Validating - after canonicalizing, ensures data is of the correct type, in acceptable ranges, etc
  • Supports either boolean returns or throwing exceptions “to allow maximum flexibility because
  • not all validation errors are security problems”
  • safeReadLine() to prevent DoS attack
  • File name and directory path validation
  • Basic credit card validation
  • AntiSamy protection

Encryption


  • Reference implementation utilizes Java Cryptography Extension (JCE)
  • Ensure strong salt and password values are used - takes away the chance for developers to make poor choices for these crucial values
  • Algorithms configurable via properties
  • Seal - encrypts data and includes an expiration timestamp

Indirect Object References


  • Reference implementation includes 2 concrete classes: integer based and random strings
  • Defeats parameter tampering attacks
  • Can help combat CSRF if per-user access reference maps are used

HTTP Utilities


  • Provides useful methods relating to request, response, cookies, sessions, etc.
  • addCSRFToken()
  • changeSessionIdentifier()
  • encrypt/decrypt fields
  • safeXXX() methods for adding headers, sending forwards & redirects to ensure character encoding
  • Reference implementation utilizes Apache Commons FileUploader
  • Reference implementation relies on current request & response being stored in ThreadLocal variables - means you have to utilize the ESAPI authenticator or explicitly call ESAPI.authenticator().setCurrentHTTP()

Authentication & Access Control


  • Reference implementation includes a file based authenticator.
  • Provides login/logout capabilities, user authentication using hashed passwords
  • Utility methods for password generation and to ensure account name and password strength
  • Carries out some of the required setup for other components such as HTTPUtilities

Intrusion Detection


  • Reference implementation has a default detector that does rudimentary calculations of number of errors per time period

OWASP Top 10 and ESAPI mapping

  • Injection
    • Encoder
  • XSS
    • Validator, Encoder
  • Malicious File Execution
    • HTTPUtilities(FileUpload)
  • Insecure Direct Object Reference
    • AccessReferenceMap
  • CSRF
    • User(csrf token)
  • Leakage and Improper Error handling
    • EnterpriseSecurityException, HttpUtils
  • Broken Authentication and Sessions
    • Authenticator, User, HttpUtils
  • Insecure Cryptographic Storage
    • Encryptor
  • Failure to Restrict URL access
    • AccessController







Intrusion Detection

To enable intrusion detection in your application, the only requirement is to configure it to be enabled in your ESAPI.properties file. Simply set the IntrusionDetector.Disable property to be false and you are in business. Once intrusion detection is enabled in your application, any exception that extends the EnterpriseSecurityException will raise an event that the intrusion detector can be configured to respond to.

In the ESAPI.properties file you will find a section for IntrusionDetection with a sample configuration for events. You can add custom events here and configure what actions should be taken as well as thresholds for those events.

Introducing AppSensor
Some friends at OWASP took the ESAPI Intrusion Detector and some ideas that they had and built one of the most powerful application layer intrusion detection and prevention components available today. This project, called AppSensor - is built on top of ESAPI so it integrates seamlessly with ESAPI and provides fantastic protection to your application. I highly recommend using AppSensor for anything other than the most basic of intrusion detection and prevention needs.


Encryption

performing the encryption and decryption of sensitive information is incredibly simple.

view plainprint?
// Populate User Object from Request
// ...
// Encrypt Sensitive Information
CipherText encryptedSSN = ESAPI.encryptor().encrypt(new PlainText(userInfo.getSSN()));
userInfo.setSSN(new String(encryptedSSN.asPortableSerializedByteArray());
// Persist User Object
// ...

To decrypt the data is just as simple.
view plainprint?
// Retrieve persisted User Object
// ...
// Decrypt Sensitive Information
CipherText encryptedSSN = CipherText.fromPortableSerializedBytes(user.getSSN());
PlainText decryptedSSN = ESAPI.encryptor().decrypt(encryptedSSN);
userInfo.setSSN(decryptedSSN.toString());
// Prepare User Object for use in application
// ...

Of course this can be abstracted into a service, added as an annotation processor in your persistence layer, and altered to be used in a more generic form that meets your specific platform needs. Additionally, depending on the type of information you are dealing with and the perceived risk of that information being leaked - it may make sense for the data to be encrypted all the time until it needs to be viewed or altered on the front end. This approach can also increase performance of the encryption and decryption because you are only ever performing this step when it is needed.



The ESAPI Web Application Firewall
This presentation was by Arshan Dabirsiaghi and was about the OWASP ESAPI Web Application Firewall (WAF) project.  My notes are below:

WAF Fallacies (at least in regards to OWASP ESAPI WAF)

  • WAFs add attack surface
  • WAFs can create culture problems
  • WAFs can't fix business logic vulnerabilities
  • WAFs are way too expensive
  • WAFs complicate networks
Why fix in ESAPI WAF vs Fix in code?


  • Changing in ESAPI WAF is just a text file
  • Shorter gap between time discovered and WAF fix vs code fix

Advantages of WAF


  • Performance - Only your rules are checked, plus state is already managed by the app server
  • Capability - being closer to the app lets us do more
  • Process - Rules are closer to application owner, shortening discovery-to-patch time, also fix-to-patch-removal time
Principle: Make common tasks easy, uncommon tasks possible.

Notes:

  • General virtual patching functionality is easy to understand.
  • Ability to write custom script rules as well "bean-shell-rules"
  • Fixing Injection Flaws is easy.
  • Can fix business logic flaws with the WAF (missing authentication, missing functional access control, missing data layer access control).
  • Can add "outbound" security as well.
    • Add anti-clickjacking header
    • Set uniform content-type
    • Add HttpOnly flag
    • Add secure flag
    • Detect outbound information
    • Replace outbound information
  • Takes advantage of early failing to make rules as optimized as possible


Now we see the tool demonstrated with several different vulnerabilities in a real-world application (JForum):

  • Cross-Site Scripting Flaw (JForum XSS flaw is unable to be fixed with a WAF because of dynamic URLs)
  • Unchecked Redirect
  • Add HttpOnly
  • Add anti-clickjacking header
  • Privilege escalation
3 Different WAF Modes

  • Log
  • Block
  • Redirect

Latency with all of the rules turned on is about 5%.  With selected rules is closer to 0%.  Basically an order of n magnitude where n is the number of rules enabled.  Comes out to milliseconds.



Using ESAPI with Struts

  •  extend the struts tag library and embed the ESAPI libraries within it.
  •  The biggest advantage of this approach is that there are no or minimal changes required to JSP pages. You can retro fit this solution into existing struts 2 application. The only JSP’s you may need to change are ones that use the s:property tag directly which are outputting into a HTML attribute, JavaScript or CSS. 

 Customizing the s:property Tag

At the core of the struts tags there is the property tag (<s:property ../>). You’ll find that all the struts freemarker templates use the property tag within them for actually outputting the values, hence also becoming the core of the problem.

The main problem with the property tag is that it has few options for escaping the outputs by default (escape and escapeJavaScript), and then what escaping it does do is fairly limited. So to get around this we’ll create a more robust version of the property tag that has options to escape for HTML attribute, HTML value, CSS etc.

General Use

The features of the new property tag can be used directly within a JSP page.

<s:property value="name" escapeHtmlAttribute="true"/>
An additional feature added to the property tag is the encrypt attribute. Setting this attribute to true will encrypt the value. According to OWASP object ID’s should not be used on their own, but they should be encrypted. Having the encrypt attribute makes it very easy to folow this rule. The value has to be decrypted in the action code.


Securing Inputs

  • Inputs in this instance includes securing HTML forms as well as general HTTP requests that are sent to your application.

Servlet Filter
  • Checks for double encoded values
  • Valid characters, it needs to be fairly broad though (printable characters)
  • Canonicalization

  • ESAPI supplies the SecurityWrapper filter that will perform the above validation and sanitation. It can found under the following package: org.owasp.esapi.filters.SecurityWrapper
  • The SecurityWrapper wraps up the HttpServletRequest and HttpServletResponse in it’s own copies. These wrappers validates and canoncalizes inputs included within the request as well as HTTP header values.
  • The validation within the request and response wrappers is done using the ESAPI.validator().getValidInput(…) methods. The validation rules that this method uses is driven from the regular expressions set within the esapi.properties and validation.properties. The default expressions found within these properties files are very restrictive

The same theory applies for values within HTML forms. Any hidden values should also be encrypted to stop tampering. The same technique described above can be used.

Validation

Server side validation in struts can be done in a number of ways, within annotations or by using validation XML files. One can create custom validators and add them to Validator.xml file. 

References
http://www.nutshellsoftware.org/software/securing-struts-2-using-esapi-part-1-securing-outputs/
http://www.nutshellsoftware.org/software/securing-struts-2-using-esapi-%E2%80%93-part-2-securing-inputs/


Appendix: Encodings

HTML character references
  • Numeric character references can be in decimal format, &#DD;, where DD is a variable number of decimal digits. 
  • Similarly there is a hexadecimal format, &#xHHHH;, where HHHH is a variable number of hexadecimal digits. Hexadecimal character references are case-insensitive in HTML. 
  • Characters in the hexadecimal ranges 00–08, 0B–0C, 0E–1F, 7F, and 80–9F cannot be used in an HTML document, not even by reference, so "&#153;", for example, is not allowed. However, for backward compatibility with early HTML authors and browsers that ignored this restriction.
  • Character entity references have the format &name; where "name" is a case-sensitive alphanumeric string. For example, '?' can also be encoded as &lambda; in an HTML document.
  • If HTML attributes are not fully quoted, then you must entity encode whitespace like space, tab, and others
Attribute Encoding Attribute encoding replaces three characters that are not valid to use inside attribute values in HTML. Those characters are ampersand ‘&’, less-than ‘<’, and quotation marks ‘”’. The first two for the same reason you HTML encode to prevent HTML injection attacks and the last one because quotation marks are used to define the value of the attribute.

Appendix: ESAPI API

Note: ESAPI canonicalizes input before validation to prevent bypassing filters with encoded attacks. Failure to canonicalize input is a very common mistake when implementing validation schemes. Canonicalization is automatic when using the ESAPI Validator.

Important Methods

  • canonicalize()
Default canonicalize() method only decodes HTMLEntity, percent (URL) encoding, and JavaScript encoding. Although ESAPI is able to canonicalize multiple, mixed, or nested encoding, it's safer to not accept this stuff in the first place. In ESAPI, the default is "strict" mode that throws an IntrusionException if it receives anything not single-encoded with a single scheme. This is configurable in ESAPI.properties using the properties:
  • Encoder.AllowMultipleEncoding=false
  • Encoder.AllowMixedEncoding=false
  • encodeForHTML
& --> &amp; < --> &lt; > --> &gt; " --> &quot; ' --> &#x27; &apos; is not recommended / --> &#x2F; forward slash is included as it helps end an HTML entity
  • encodeForHTMLAttribute
Except for alphanumeric characters, escape all characters with ASCII values less than 256 with the &#xHH; format (or a named entity if available) to prevent switching out of the attribute. The reason this rule is so broad is that developers frequently leave attributes unquoted. Properly quoted attributes can only be escaped with the corresponding quote.
  • encodeForJavaScript

Except for alphanumeric characters, escape all characters less than 256 with the \xHH format to prevent switching out of the data value into the script context or into another attribute. DO NOT use any escaping shortcuts like \" because the quote character may be matched by the HTML attribute parser which runs first. These escaping shortcuts are also susceptible to "escape-the-escape" attacks where the attacker sends \" and the vulnerable code turns that into \\" which enables the quote.

Encode data for insertion inside a data value or function argument in JavaScript. Including user data directly inside a script is quite dangerous. Great care must be taken to prevent including user data directly into script code itself, as no amount of encoding will prevent attacks there. Please note there are some JavaScript functions that can never safely receive untrusted data as input – even if the user input is encoded.
  • encodeForCSS
Except for alphanumeric characters, escape all characters with ASCII values less than 256 with the \HH escaping format. DO NOT use any escaping shortcuts like \"
  • encodeForXPath
Encode data for use in an XPath query. NB: The reference implementation encodes almost everything and may over-encode. The difficulty with XPath encoding is that XPath has no built in mechanism for escaping characters. It is possible to use XQuery in a parameterized way to prevent injection. For more information, refer to this article which specifies the following list of characters as the most dangerous: ^&"*';<>(). This paper suggests disallowing ' and " in queries.
  • encodeForURL
Encode for use in a URL. This method performs URL encoding on the entire string.
Except for alphanumeric characters, escape all characters with ASCII values less than 256 with the %HH escaping format.

References:
http://yet-another-dev.blogspot.com.au/
http://www.webadminblog.com/index.php/2009/11/12/the-esapi-web-application-firewall/

Sunday, May 19, 2013

Cloud computing - capacity planning



One of the problems of traditional capacity management is that resources are often underutilized. Not to mention the fact that it is very slow and sometimes painful process to get access to new capacity and it almost impossible to voluntarily relinquish excess capacity. Never ignore the human factor in cloud and capacity planning because often times that is the difference between success in the cloud or failure and disillusionment.

Cloud Computing provides the illusion of infinite computing resources available on-demand but you need to manage budgets. so capacity planning is still very important.

Cloud computing cannot magically solve business problems. I guess it was Etrade that somehow
discovered that one of their competitor was charging money less than the Etrades transaction cost. When an organization is up against such core issues, cloud computing is not going to solve them but instead exacerbate them. What we need is an effective analysis detailing the reasons for the current state of things and then attempting to figure out not if but how cloud computing can solve this.

Since cloud resources could be virtualized, Capacity planning, first includes the ability to measure in cloud terms and not be confused about the units. For instance, CPU is typically standardized at 1 Ghz, and is considered 1 CPU.

It is important to consider the maximum "single" VM request that can be fulfilled. for instance can we provision a VM with 24 CPUs and not run against the actual physical CPU limits? The same applies to memory as well.

In cloud computing it is easier to relinquish control over resources because one knows that they can quickly get it again.

A few of the important things in capacity planning is understanding:
- Current capacity
- Current utilization
- Future utilization
- Trend and spikes
    - can we handle the temporary or seasonal "spikes" in demand and also handle the general up or down trend.

The above considerations help in answering the questions around ROI (return on investment). 

But how do I estimate?
There are tools available including one from IBM; IBM infrastructure planner for cloud computing.

Saturday, April 20, 2013

SQL Joins

SQL joins summarized:

INNER JOIN



SELECT * FROM T1 INNER JOIN T2 ON T1.id = T2.id

id  name       id   name
--  ----       --   ----
1   Aa     2    Aa
3   Bb      4    Bb

Inner join produces only the set of records that match in both T1 and T2.

FULL OUTER JOIN

SELECT * FROM T1
FULL OUTER JOIN T2
ON T1.id = T2.id

id    name       id    name
--    ----       --    ----
1     a     2     a
2     b     null  null
3     c       4     c
4     d   null   null
null  null       1     e    
null  null       3     f

Full outer join produces the set of all records in T1 and T2, with matching records from both sides where available. If there is no match, the missing side will contain null.

LEFT OUTER JOIN

SELECT * FROM T1
LEFT OUTER JOIN T2
ON T1.id = T2.id

id  name       id    name
--  ----       --    ----
1   P     2     P
2   M     null  null
3   N       4     N
4   S    null  null

Left outer join produces a complete set of records from T1, with the matching records (where available) in T2. If there is no match, the right side will contain null.

Saturday, April 6, 2013

Security: Secure Coding practices


We need to understand that client side controls like client based input validation, hidden fields and interface controls provide little if any security benefit.

  •  An attacker can use tools like client side web proxies (e.g. OWASP WebScarab, Burp) or network packet capture tools (e.g., WireShark) to analyze application traffic and submit custom built requests, bypassing the interface all together. 
  • Additionally, Flash, Java Applets and other client side objects can be decompiled and analyzed for flaws
Software security flaws can be introduced at any stage of the software development lifecycle, including: 
 Not identifying security requirements up front
 Creating conceptual designs that have logic errors
 Using poor coding practices
 Deploying the software improperly 
 Introducing flaws during maintenance or updating


Secure Coding Practices Checklist

Input Validation:

 Conduct all data validation on a trusted system (e.g., The server)  
 Identify all data sources and validate all data from untrusted sources (e.g., Databases, file streams, etc.) 
 There should be a centralized input validation
 proper character sets, such as UTF-8, for all sources of input
 Encode data to a common character set before validating (Canonicalize)
 All validation failures should result in input rejection
 Determine if the system supports UTF-8 extended character sets and if so, validate after UTF-8 
decoding is completed
 Validate all client provided data including all parameters, URLs and HTTP header 
content (e.g. Cookie names and values). Be sure to include automated post backs from JavaScript, 
Flash or other embedded code
 Verify that header values in both requests and responses contain only ASCII characters
 Validate data from redirects (An attacker may submit malicious content directly to the target of the 
redirect, thus circumventing application logic and any validation performed before the redirect)  
 Validate for expected data types 
 Validate data range
 Validate data length
 Validate all input against a "white" list of allowed characters, whenever possible
 If any potentially hazardous characters must be allowed as input, be sure that you implement 
additional controls like output encoding, secure task specific APIs and accounting for the utilization 
of that data throughout the application . Examples of common hazardous characters include: 
< > " ' % ( ) & + \ \' \" 
 If your standard validation routine cannot address the following inputs, then they should be checked 
discretely
   o Check for null bytes ()
   o Check for new line characters (%0d, %0a, \r, \n)
   o Check for “dot-dot-slash" (../ or ..\) path alterations characters. In cases where UTF-8 extended 
character set encoding is supported, address alternate representation like: %c0%ae%c0%ae/ 
(Utilize canonicalization to address double encoding or other forms of obfuscation attacks)

Output Encoding:

 Conduct all encoding on a trusted system (e.g., The server)
 Utilize a standard, tested routine for each type of outbound encoding
 Contextually output encode all data returned to the client that originated outside the application's trust 
boundary. HTML entity encoding is one example, but does not work in all cases
 Encode all characters unless they are known to be safe for the intended interpreter
 Contextually sanitize all output of un-trusted data to queries for SQL, XML, and LDAP
 Sanitize all output of un-trusted data to operating system commandsNovember 2010
Version 2.0 6
Authentication and Password Management:
 Require authentication for all pages and resources, except those specifically intended to be public
 All authentication controls must be enforced on a trusted system (e.g., The server)  
 Establish and utilize standard, tested, authentication services whenever possible
 Use a centralized implementation for all authentication controls, including libraries that call external 
authentication services
 Segregate authentication logic from the resource being requested and use redirection to and from the 
centralized authentication control
 All authentication controls should fail securely
 All administrative and account management functions must be at least as secure as the primary 
authentication mechanism
 If your application manages a credential store, it should ensure that only cryptographically strong oneway salted hashes of passwords are stored and that the table/file that stores the passwords and keys is
write-able only by the application. (Do not use the MD5 algorithm if it can be avoided)
 Password hashing must be implemented on a trusted system (e.g., The server).
 Validate the authentication data only on completion of all data input, especially for sequential 
authentication implementations
 Authentication failure responses should not indicate which part of the authentication data was 
incorrect. For example, instead of "Invalid username" or "Invalid password", just use "Invalid 
username and/or password" for both. Error responses must be truly identical in both display and 
source code
 Utilize authentication for connections to external systems that involve sensitive information or 
functions
 Authentication credentials for accessing services external to the application should be encrypted and 
stored in a protected location on a trusted system (e.g., The server). The source code is NOT a secure 
location
 Use only HTTP POST requests to transmit authentication credentials
 Only send non-temporary passwords over an encrypted connection or as encrypted data, such as in an 
encrypted email. Temporary passwords associated with email resets may be an exception
 Enforce password complexity requirements established by policy or regulation. Authentication 
credentials should be sufficient to withstand attacks that are typical of the threats in the deployed 
environment. (e.g., requiring the use of alphabetic as well as numeric and/or special characters)
 Enforce password length requirements established by policy or regulation. Eight characters is 
commonly used, but 16 is better or consider the use of multi-w ord pass phrases
 Password entry should be obscured on the user's screen. (e.g., on web forms use the input type 
"password")
 Enforce account disabling after an established number of invalid login attempts (e.g., five attempts is 
common).  The account must be disabled for a period of time sufficient to discourage brute force 
guessing of credentials, but not so long as to allow for a denial-of-service attack to be performed
 Password reset and changing operations require the same level of controls as account creation and 
authentication. 
 Password reset questions should support sufficiently random answers. (e.g., "favorite book" is a bad 
question because “The Bible” is a very common answer)
 If using email based resets, only send email to a pre-registered address with a temporary
link/password
 Temporary passwords and links should have a short expiration time
 Enforce the changing of temporary passwords on the next useNovember 2010
Version 2.0 7
 Notify users when a password reset occurs
 Prevent password re-use
 Passwords should be at least one day old before they can be changed, to prevent attacks on password 
re-use
 Enforce password changes based on requirements established in policy or regulation. Critical systems
may require more frequent changes. The time between resets must be administratively controlled 
 Disable "remember me" functionality for password fields
 The last use (successful or unsuccessful) of a user account should be reported to the user at their next 
successful login
 Implement monitoring to identify attacks against multiple user accounts, utilizing the same password. 
This attack pattern is used to bypass standard lockouts, when user IDs can be harvested or guessed
 Change all vendor-supplied default passwords and user IDs or disable the associated accounts
 Re-authenticate users prior to performing critical operations
 Use Multi-Factor Authentication for highly sensitive or high value transactional accounts
 If using third party code for authentication, inspect the code carefully to ensure it is not affected by 
any malicious code 

Session Management:

 Use the server or framework’s session management controls. The application should only recognize 
these session identifiers as valid
 Session identifier creation must always be done on a trusted system (e.g., The server)
 Session management controls should use well vetted algorithms that ensure sufficiently random 
session identifiers
 Set the domain and path for cookies containing authenticated session identifiers to an appropriately 
restricted value for the site
 Logout functionality should fully terminate the associated session or connection
 Logout functionality should be available from all pages protected by authorization
 Establish a session inactivity timeout that is as short as possible, based on balancing risk and business 
functional requirements. In most cases it should be no more than several hours
 Disallow persistent logins and enforce periodic session terminations, even when the session is active. 
Especially for applications supporting rich network connections or connecting to critical systems. 
Termination times should support business requirements and the user should receive sufficient 
notification to mitigate negative impacts
 If a session was established before login, close that session and establish a new session after a 
successful login
 Generate a new session identifier on any re-authentication
 Do not allow concurrent logins with the same user ID
 Do not expose session identifiers in URLs, error messages or logs. Session identifiers should only be 
located in the HTTP cookie header. For example, do not pass session identifiers as GET parameters
 Protect server side session data from unauthorized access, by other users of the server, by 
implementing appropriate access controls on the server
 Generate a new session identifier and deactivate the old one periodically. (This can mitigate certain 
session hijacking scenarios where the original identif ier was compromised)
 Generate a new session identifier if the connection security changes from HTTP to HTTPS, as can 
occur during authentication. Within an application, it is recommended to consistently utilize HTTPS 
rather than switching between HTTP to HTTPS.November 2010
Version 2.0 8
 Supplement standard session management for sensitive server-side operations, like account 
management, by utilizing per-session strong random tokens or parameters. This method can be used 
to prevent Cross Site Request Forgery attacks
 Supplement standard session management for highly sensitive or critical operations by utilizing perrequest, as opposed to per-session, strong random tokens or parameters
 Set the "secure" attribute for cookies transmitted over an TLS connection
 Set cookies with the HttpOnly attribute, unless you specifically require client-side scripts within your 
application to read or set a cookie's value

Access Control:

 Use only trusted system objects, e.g. server side session objects, for making access authorization 
decisions
 Use a single site-wide component to check access authorization. This includes libraries that call 
external authorization services
 Access controls should fail securely 
 Deny all access if the application cannot access its security configuration information
 Enforce authorization controls on every request, including those made by server side scripts,
"includes" and requests from rich client-side technologies like AJAX and Flash
 Segregate privileged logic from other application code
 Restrict access to files or other resources, including those outside the application's direct control, to 
only authorized users
 Restrict access to protected URLs to only authorized users 
 Restrict access to protected functions to only authorized users 
 Restrict direct object references to only authorized users
 Restrict access  to services to only authorized users
 Restrict access  to application data to only authorized users
 Restrict access to user and data attributes and policy information used by access controls
 Restrict access security-relevant configuration information to only authorized users
 Server side implementation and presentation layer representations of access control rules must match
 If state data must be stored on the client, use encryption and integrity checking on the server side to 
catch state tampering.
 Enforce application logic flows to comply with business rules
 Limit the number of transactions a single user or device can perform in a given period of time. The 
transactions/time should be above the actual business requirement, but low enough to deter automated 
attacks
 Use the "referer" header as a supplemental check only, it should never be the sole authorization check, 
as it is can be spoofed
 If long authenticated sessions are allowed, periodically re-validate a user’s authorization to ensure that 
their privileges have not changed and if they have, log the user out and force them to re-authenticate
 Implement account auditing and enforce the disabling of unused accounts (e.g., After no more than 30 
days from the expiration of an account’s password.)
 The application must support disabling of accounts and terminating sessions when authorization 
ceases (e.g., Changes to role, employment status, business process, etc.)
 Service accounts or accounts supporting connections to or from external systems should have the least 
privilege possibleNovember 2010
Version 2.0 9
 Create an Access Control Policy to document an application's business rules, data types and access 
authorization criteria and/or processes so that access can be properly provisioned and controlled. This 
includes identifying access requirements for both the data and system resources
Cryptographic Practices:
 All cryptographic functions used to protect secrets from the application user must be implemented on 
a trusted system (e.g., The server)
 Protect master secrets from unauthorized access
 Cryptographic modules should fail securely
 All random numbers, random file names, random GUIDs, and random strings should be generated 
using the cryptographic module’s approved random number generator when these random values are 
intended to be un-guessable
 Cryptographic modules used by the application should be compliant to FIPS 140-2 or an equivalent 
standard. (See http://csrc.nist.gov/groups/STM/cmvp/validation.html)
 Establish and utilize a policy and process for how cryptographic keys will be managed
Error Handling and Logging:
 Do not disclose sensitive information in error responses, including system details, session identifiers 
or account information
 Use error handlers that do not display debugging or stack trace information
 Implement generic error messages and use custom error pages 
 The application should handle application errors and not rely on the server configuration
 Properly free allocated memory when error conditions occur
 Error handling logic associated with security controls should deny access by default
 All logging controls should be implemented on a trusted system (e.g., The server)
 Logging controls should support both success and failure of specified security events
 Ensure logs contain important log event data
 Ensure log entries that include un-trusted data will not execute as code in the intended log viewing 
interface or software
 Restrict access to logs to only authorized individuals
 Utilize a master routine for all logging operations
 Do not store sensitive information in logs, including unnecessary system details, session identifiers or 
passwords
 Ensure that a mechanism exists to conduct log analysis
 Log all input validation failures
 Log all authentication attempts, especially failures
 Log all access control failures
 Log all apparent tampering events, including unexpected changes to state data
 Log attempts to connect with invalid or expired session tokens
 Log all system exceptions
 Log all administrative functions, including changes to the security configuration settings
 Log all backend TLS connection failures
 Log cryptographic module failures
 Use a cryptographic hash function to validate log entry integrityNovember 2010
Version 2.0 10

Data Protection:

 Implement least privilege, restrict users to only the functionality, data and system information that is 
required to perform their tasks
 Protect all cached or temporary copies of sensitive data stored on the server from unauthorized access 
and purge those temporary working files a soon as they are no longer required.
 Encrypt highly sensitive stored information, like authentication verification data, even on the server 
side. Always use well vetted algorithms, see "Cryptographic Practices" for additional guidance
 Protect server-side source-code from being downloaded by a user
 Do not store passwords, connection strings or other sensitive information in clear text or in any noncryptographically secure manner on the client side. This includes embedding in insecure formats like:
MS viewstate, Adobe flash or compiled code
 Remove comments in user accessible production code that may reveal backend system or other 
sensitive information
 Remove unnecessary application and system documentation as this can reveal useful information to 
attackers
 Do not include sensitive information in HTTP GET request parameters
 Disable auto complete features on forms expected to contain sensitive information, including
authentication
 Disable client side caching on pages containing sensitive information. Cache-Control: no-store, may 
be used in conjunction with the HTTP header control "Pragma: no-cache", which is less effective, but 
is HTTP/1.0 backward compatible
 The application should support the removal of sensitive data when that data is no longer required. 
(e.g. personal information or certain financial data)
 Implement appropriate access controls for sensitive data stored on the server. This includes cached 
data, temporary files and data that should be accessible only by specific system users
Communication Security:
 Implement encryption for the transmission of all sensitive information. This should include TLS for 
protecting the connection and may be supplemented by discrete encryption of sensitive files or nonHTTP based connections
 TLS certificates should be valid and have the correct domain name, not be expired, and be installed 
with intermediate certificates when required
 Failed TLS connections should not fall back to an insecure connection
 Utilize TLS connections for all content requiring authenticated access and for all other sensitive 
information
 Utilize TLS for connections to external systems that involve sensitive information or functions
 Utilize a single standard TLS implementation that is configured appropriately
 Specify character encodings for all connections
 Filter parameters containing sensitive information from the HTTP referer, when linking to external 
sites

System Configuration:

 Ensure servers, frameworks and system components are running the latest approved version 
 Ensure servers, frameworks and system components have all patches issued for the version in use
 Turn off directory listings
 Restrict the web server, process and service accounts to the least privileges possible
 When exceptions occur, fail securely
 Remove all unnecessary functionality and files
 Remove test code or any functionality not intended for production, prior to deployment
 Prevent disclosure of your directory structure in the robots.txt file by placing directories not intended 
for public indexing into an isolated parent directory. Then "Disallow" that entire parent directory in 
the robots.txt file rather than Disallowing each individual directory
 Define which HTTP methods, Get or Post, the application will support and whether it will be handled 
differently in different pages in the application
 Disable unnecessary HTTP methods, such as WebDAV extensions. If an extended HTTP method that 
supports file handling is required, utilize a well-vetted authentication mechanism
 If the web server handles both HTTP 1.0 and 1.1, ensure that both are configured in a similar manor 
or insure that you understand any difference that may exist (e.g. handling of extended HTTP methods) 
 Remove unnecessary information from HTTP response headers related to the OS, web-server version 
and application frameworks 
 The security configuration store for the application should be able to be output in human readable 
form to support auditing
 Implement an asset management system and register system components and software in it
 Isolate development environments from the production network and provide access only to authorized 
development and test groups. Development environments are often configured less securely than 
production environments and attackers may use this difference to discover shared weaknesses or as an 
avenue for exploitation
 Implement a software change control system to manage and record changes to the code both 
in development and production

Database Security:

 Use strongly typed parameterized queries
 Utilize input validation and output encoding and be sure to address meta characters. If these fail, do 
not run the database command
 Ensure that variables are strongly typed
 The application should use the lowest possible level of privilege when accessing the database
 Use secure credentials for database access
 Connection strings should not be hard coded within the application. Connection strings should be 
stored in a separate configuration file on a trusted system and they should be encrypted.
 Use stored procedures to abstract data access and allow for the removal of permissions to the base 
tables in the database
 Close the connection as soon as possible
 Remove or change all default database administrative passwords. Utilize strong passwords/phrases or 
implement multi-factor authentication
 Turn off all unnecessary database functionality (e.g., unnecessary stored procedures or services, utility 
packages, install only the minimum set of features and options required (surface area reduction))

 Remove unnecessary default vendor content (e.g., sample schemas)
 Disable any default accounts that are not required to support business requirements
 The application should connect to the database with different credentials for every trust distinction 
(e.g., user, read-only user, guest, administrators)

File Management:

 Do not pass user supplied data directly to any dynamic include function
 Require authentication before allowing a file to be uploaded
 Limit the type of files that can be uploaded to only those types that are needed for business purposes
 Validate uploaded files are the expected type by checking file headers. Checking for file type by 
extension alone is not sufficient
 Do not save files in the same web context as the application. Files should either go to the content 
server or in the database. 
 Prevent or restrict the uploading of any file that may be interpreted by the web server. 
 Turn off execution privileges on file upload directories
 Implement safe uploading in UNIX by mounting the targeted file directory as a logical drive using the 
associated path or the chrooted environment
 When referencing existing files, use a white list of allowed file names and types. Validate the value of 
the parameter being passed and if it does not match one of the expected values, either reject it or use a 
hard coded default file value for the content instead
 Do not pass user supplied data into a dynamic redirect. If this must be allowed, then the redirect 
should accept only validated, relative path URLs
 Do not pass directory or file paths, use index values mapped to pre-defined list of paths
 Never send the absolute file path to the client
 Ensure application files and resources are read-only
 Scan user uploaded files for viruses and malware

Memory Management:

 Utilize input and output control for un-trusted data
 Double check that the buffer is as large as specified
 When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the 
destination buffer size is equal to the source buffer size, it may not NULL-terminate the string
 Check buffer boundaries if calling the function in a loop and make sure there is no danger of writing 
past the allocated space
 Truncate all input strings to a reasonable length before passing them to the copy and concatenation 
functions
 Specifically close resources, don’t rely on garbage collection. (e.g., connection objects, file handles, 
etc.)
 Use non-executable stacks when available
 Avoid the use of known vulnerable functions (e.g., printf, strcat, strcpy etc.)
 Properly free allocated memory upon the completion of functions and at all exit points

General Coding Practices:

 Use tested and approved managed code rather than creating new unmanaged code for common tasks
 Utilize task specific built-in APIs to conduct operating system tasks. Do not allow the application to 
issue commands directly to the Operating System, especially through the use of application initiated 
command shells
 Use checksums or hashes to verify the integrity of interpreted code, libraries, executables, and 
configuration files 
 Utilize locking to prevent multiple simultaneous requests or use a synchronization mechanism to 
prevent race conditions
 Protect shared variables and resources from inappropriate concurrent access
 Explicitly initialize all your variables and other data stores, either during declaration or just before the 
first usage
 In cases where the application must run with elevated privileges, raise privileges as late as possible, 
and drop them as soon as possible
 Avoid calculation errors by understanding your programming language's underlying representation 
and how it interacts with numeric calculation. Pay close attention to byte size discrepancies, precision, 
signed/unsigned distinctions, truncation, conversion and casting between types, "not-a-number" 
calculations, and how your language handles numbers that are too large or too small for its underlying 
representation
 Do not pass user supplied data to any dynamic execution function
 Restrict users from generating new code or altering existing code
 Review all secondary applications, third party code and libraries to determine business necessity and 
validate safe functionality, as these can introduce new vulnerabilities
 Implement safe updating. If the application will utilize automatic updates, then use cryptographic 
signatures for your code and ensure your download clients verify those signatures. Use encrypted 
channels to transfer the code from the host server

Resources:

Copyright

This document is released under the Creative Commons Attribution ShareAlike 3.0 license. For any reuse or 
distribution, you must make clear to others the license terms of this work

Saturday, March 23, 2013

Security: Attacks


This blog post summarizes the attacks described in OWASP and is a continuation of the security series of blog posts.

OWASP Top 10 Application Security Risks - 2010

Attacks

Attacks are the techniques that attackers use to exploit the vulnerabilities in applications. Anatomy of an Attack
  • Survey and assess
  • Exploit and penetrate
  • Escalate privileges
  • Maintain access
  • Deny service

Threats


Top network level threats include:
  • Information gathering
  • Sniffing
  • Spoofing
  • Session hijacking
  • Denial of service
Top host level threats include:
  • Viruses, Trojan horses, and worms
  • Footprinting ( ping sweep, NETBIOS enumeration).
  • Profiling
  • Password cracking
  • Denial of service
  • Arbitrary code execution
  • Unauthorized access
For details on categorizing threats, please refer Appendix A in the blog post on "<TODO>Information security, threats, risks"


The below is a summary of the known attacks in their respective categories:

Abuse of Functionality

Account lockout attack

Attacker attempts to lock out all user accounts, typically by failing login more times than the threshold defined by the authentication system

 Cache Poisoning

This attack is rather difficult to carry out in a real environment. The list of conditions is long and hard to accomplish by the attacker. However it's easier to use this technique than Cross-User Defacement. To successfully carry out such an attack, an attacker:
  • Finds the vulnerable service code, which allows them to fill the HTTP header field with many headers.
  • Forces the cache server to flush its actual cache content, which we want to be cached by the servers.
  • Sends a specially crafted request, which will be stored in cache.
  • Sends the next request. The previously injected content stored in cache will be the response to this request.
A Cache Poisoning attack is possible because of HTTP Response Splitting and flaws in the web application. It is crucial from the attacker's point of view that the application allows for filling the header field with more than one header using CR (Carriage Return) and LF (Line Feed) characters.

Cross-User Defacement

This attack is rather difficult to carry out in the real environment. An attacker can make a single request to a vulnerable server that will cause the sever to create two responses, the second of which may be misinterpreted as a response to a different request, possibly one made by another user sharing the same TCP connection with the sever.

Mobile code: invoking untrusted mobile code

 By intercepting client traffic using the man-in-the-middle technique, a malicious user could modify the original mobile code with arbitrary operations that will be executed on the client’s machine under his credentials.
To solve this issue, it’s necessary to use some type of integrity mechanism to assure that the mobile code has not been modified.

Mobile code: non-final public field

This attack aims to manipulate non-final public variables used in mobile code, by injecting malicious values on it, mostly in Java and C++ applications.
When a public member variable or class used in mobile code isn’t declared as final, its values can be maliciously manipulated by any function that has access to it in order to extend the application code or acquire critical information about the application.

Mobile code: object hijack

This attack consists of a technique to create objects without constructors’ methods by taking advantage of the clone() method of Java-based applications.
If a certain class implements cloneable() method declared as public, but doesn’t has a public constructor method nor is declared as final, it is possible to extend it into a new class and create objects using the clone() method.

Data Structure Attacks


Buffer overflow attack

Buffer overflow errors are characterized by the overwriting of memory fragments of the process, which should have never been modified intentionally or unintentionally. Overwriting values of the IP (Instruction Pointer), BP (Base Pointer) and other registers causes exceptions, segmentation faults, and other errors to occur. Usually these errors end execution of the application in an unexpected way. Buffer overflow errors occur when we operate on buffers of char type.

Buffer Overflow via Environment Variables

Same as above except used with Env vars.

Overflow Binary Resource File

The source of a buffer overflow may be input data. When it comes from the Overflow Binary Resource File, the attacker has to modify/prepare the binary file in such a way that the application, after reading this file, has become prone to a classic Buffer overflow attack. The only difference between this attack and the classic one is the source of the input data. Common examples are specially crafted MP3, JPEG or ANI files, which cause buffer overflows.

Embedded Malicious Code


Cross-Site Request Forgery (CSRF) or One-Click Attack or XSRF

CSRF is an attack which forces an end user to execute unwanted actions on a web application in which he/she is currently authenticated. With a little help of social engineering (like sending a link via email/chat), an attacker may force the users of a web application to execute actions of the attacker's choosing. A successful CSRF exploit can compromise end user data and operation in case of normal user. If the targeted end user is the administrator account, this can compromise the entire web application.

Sometimes, it is possible to store the CSRF attack on the vulnerable site itself. Such vulnerabilities are called Stored CSRF flaws. This can be accomplished by simply storing an IMG or IFRAME tag in a field that accepts HTML, or by a more complex cross-site scripting attack. If the attack can store a CSRF attack in the site, the severity of the attack is amplified.
These are also known by a number of other names, including XSRF, "Sea Surf", Session Riding, Cross-Site Reference Forgery, Hostile Linking. Microsoft refers to this type of attack as a One-Click attack

Logic/time bomb

This is a threat agent.

Replicating (virus)


Trojan Horse

A Trojan Horse is a program that uses malicious code masqueraded as a trusted application. The malicious code can be injected on benign applications, masqueraded in e-mail links, or sometimes hidden in JavaScript pages to make furtive attacks against vulnerable internet Browsers.
Other details can be found in Man-in-the-browser attack.
The 7 Main Types of Trojan Horse
1.   Remote Access Trojan (RAT)
2.   Data Sending Trojan
3.   Destructive Trojan
4.   Proxy Trojan
5.   FTP Trojan
6.   Security software disabler Trojan
7.   Denial-of-Service attack Trojan

Exploitation of Authentication


Session fixation

Session Fixation is an attack that exploits a vulnerability in web applications that don't generate a new sessionid after login and use an existent session id.

The attack consists of inducing a user to authenticate himself with a known session ID, and then hijacking the user-validated session by the knowledge of the used session ID. The attacker has to provide a legitimate Web application session ID and try to make the victim's browser use it.
The session fixation attack is a class of Session Hijacking, which steals the established session between the client and the Web Server after the user logs in. Instead, the Session Fixation attack fixes an established session on the victim's browser, so the attack starts before the user logs in.
There are several techniques to execute the attack; it depends on how the Web application deals with session tokens. Below are some of the most common techniques:
• Session token in the URL argument: The Session ID is sent to the victim in a hyperlink.
• Session token in a hidden form field: In this method, the victim must be tricked to authenticate in the target Web Server, using a login form developed for the attacker. The form could be hosted in the evil web server or directly in html formatted e-mail.
• Session ID in a cookie:
o Client-side script
Most browsers support the execution of client-side scripting. In this case, the aggressor could use attacks of code injection as the XSS (Cross-site scripting) attack to insert a malicious code in the hyperlink sent to the victim and fix a Session ID in its cookie. Using the function document.cookie, the browser which executes the command becomes capable of fixing values inside of the cookie that it will use to keep a session between the client and the Web Application.
o <META> tag
<META> tag also is considered a code injection attack, however, different from the XSS attack where undesirable scripts can be disabled, or the execution can be denied. The attack using this method becomes much more efficient because it's impossible to disable the processing of these tags in the browsers.
o HTTP header response
This method explores the server response to fix the Session ID in the victim's browser. Including the parameter Set-Cookie in the HTTP header response, the attacker is able to insert the value of Session ID in the cookie and sends it to the victim's browser.

Session hijacking attack

This attack compromises the session token by stealing or predicting a valid session token to gain unauthorized access to the Web Server.
The session token could be compromised in different ways; the most common are:
§  Predictable session token;
§  Session Sniffing;
§  Client-side attacks (XSS, malicious JavaScript Codes, Trojans, etc);

Session Prediction

The session prediction attack focuses on predicting session ID values that permit an attacker to bypass the authentication schema of an application. By analyzing and understanding the session ID generation process, an attacker can predict a valid session ID value and get access to the application.

Injection


Argument Injection or Modification 

type of Injection attack. Modifying or injecting data as an argument may lead to very similar, often the same, results as in other injection attacks. It makes no difference if the attacker wants to inject the system command into arguments or into any other part of the code.

Blind SQL Injection

Blind SQL injection is identical to normal SQL Injection except that when an attacker attempts to exploit an application, rather then getting a useful error message, they get a generic page specified by the developer instead. This makes exploiting a potential SQL Injection attack more difficult but not impossible.

Blind XPath Injection

The attacker may be successful using two methods: Boolenization and XML Crawling. By adding to the XPath syntax, the attacker uses additional expressions (replacing what the attacker entered in the place of login to the specially crafted expression).
·       Boolenization
Using the "Boolenization" method the attacker may find out if the given XPath expression is True or False. Let's assume that the aim of the attacker is to log in to the account. 
·       XML Crawling
To get to know the XML document structure the attacker may use:
o   count(expression)
o   stringlength(string)
o   substring(string, number, number)

Code Injection

Code Injection is the general name for a lot of types of attacks which depend on inserting code, which is interpreted by the application. Such an attack may be be performed by adding strings of characters into a cookie or argument values in the URI. This attack makes use of lack of accurate input/output data validation, for example:
  • If a site uses the include() function, which operates on variables sent with the GET method, and there is no validation performed on them, then the attacker may try to execute different code other than the author of the code had in mind.
  • When a programmer uses the eval() function and operates on the data inside it, and these data may be altered by the attacker, then it's only one step closer to Code Injection.

Command Injection

The purpose of the command injection attack is to inject and execute commands specified by the attacker in the vulnerable application. There is a variant of the Code Injection attack.
    An OS command injection attack occurs when an attacker attempts to execute system level commands through a vulnerable application. Applications are considered vulnerable to the OS command injection attack if they utilize user input in a system level command.

Comment Injection Attack

Comments injected into an application through input can be used to compromise a system. As data is parsed, an injected/malformed comment may cause the process to take unexpected actions that result in an attack.
  • sql comments which serve like sql injection attacks
  • html comments which could comment the rest of html output.

Cross-site Scripting (XSS)

Cross-Site Scripting attacks are a type of injection problem, in which malicious scripts are injected into the otherwise benign and trusted web sites.
Cross-Site Scripting (XSS) attacks occur when:
1.   Data enters a Web application through an untrusted source, most frequently a web request.
1.   The data is included in dynamic content that is sent to a web user without being validated for malicious code.

The malicious content sent to the web browser often takes the form of a segment of JavaScript, but may also include HTML, Flash or any other type of code that the browser may execute. The variety of attacks based on XSS is almost limitless, but they commonly include transmitting private data like cookies or other session information to the attacker, redirecting the victim to web content controlled by the attacker, or performing other malicious operations on the user's machine under the guise of the vulnerable site.
Stored attacks are those where the injected code is permanently stored on the target servers, such as in a database, in a message forum, visitor log, comment field, etc. The victim then retrieves the malicious script from the server when it requests the stored information.
Reflected attacks are those where the injected code is reflected off the web server, such as in an error message, search result, or any other response that includes some or all of the input sent to the server as part of the request. Reflected attacks are delivered to victims via another route, such as in an e-mail message, or on some other web server. When a user is tricked into clicking on a malicious link or submitting a specially crafted form, the injected code travels to the vulnerable web server, which reflects the attack back to the user’s browser. The browser then executes the code because it came from a "trusted" server.
DOM based XSS attacks involve using the client side JavaScript to process the untrusted user input.
The most severe XSS attacks involve disclosure of the user’s session cookie, allowing an attacker to hijack the user’s session and take over the account. Other damaging attacks include the disclosure of end user files, installation of Trojan horse programs, redirect the user to some other page or site, or modify presentation of content. An XSS vulnerability allowing an attacker to modify a press release or news item could affect a company’s stock price or lessen consumer confidence.
A good practice to follow is to review the code and search for all places where input from an HTTP request could possibly make its way into the HTML output.
Nessus, Nikto, and some other available tools can help scan a website for these flaws

Custom Special Character Injection

The software does not properly filter or quote special characters or reserved words that are used in a custom or proprietary language or representation that is used by the product. That allows attackers to modify the syntax, content, or commands before they are processed by the end system.

Direct Dynamic Code Evaluation ('Eval Injection')

This attack consists of a script that does not properly validate user inputs in the page parameter. A remote user can supply a specially crafted URL to pass arbitrary code to an eval() statement, which results in code execution.
Note 1: This attack will execute the code with the same permission like the target web service, including operation system commands.
Note 2: Eval injection is prevalent in handler/dispatch procedures that might want to invoke a large number of functions, or set a large number of variables.

Similar to the above XSS and other injections.

Direct Static Code Injection

This attack consists of a script that does not properly validate user inputs in the page parameter. A remote user can supply a specially crafted URL to pass arbitrary code to an eval() statement, which results in code execution.
Note 1: This attack will execute the code with the same permission like the target web service, including operation system commands.
Note 2: Eval injection is prevalent in handler/dispatch procedures that might want to invoke a large number of functions, or set a large number of variables.

Format string attack

probably c/C++ specific.

The attack could be executed when the application doesn’t properly validate the submitted input. In this case, if a Format String parameter, like %x, is inserted into the posted data, the string is parsed by the Format Function, and the conversion specified in the parameters is executed. However, the Format Function is expecting more arguments as input, and if these arguments are not supplied, the function could read or write the stack.

Full Path Disclosure

Full Path Disclosure (FPD) vulnerabilities enable the attacker to see the path to the webroot/file. e.g.: /home/omg/htdocs/file/. Certain vulnerabilities, such as using the load_file() (within a SQL Injection) query to view the page source, require the attacker to have the full path to the file they wish to view.

For instance, sending invalid argument to a page loading web site might display the full path of the non-existent  page.

LDAP injection

LDAP Injection is an attack used to exploit web based applications that construct LDAP statements based on user input. When an application fails to properly sanitize user input, it’s possible to modify LDAP statements using a local proxy. This could result in the execution of arbitrary commands such as granting permissions to unauthorized queries, and content modification inside the LDAP tree. The same advanced exploitation techniques available in SQL Injection can be similarly applied in LDAP Injection.

Example:
The LDAP query is narrowed down for performance and the underlying code for this function might be the following:
String ldapSearchQuery = "(cn=" + $userName + ")";
 System.out.println(ldapSearchQuery);
If the variable $userName is not validated, it could be possible accomplish LDAP injection, as follows:
§  If a user puts “*” on box search, the system may return all the usernames on the LDAP base
§  If a user puts “jonys) (| (password = * ) )”, it will generate the code bellow revealing jonys’ password ( cn = jonys ) ( | (password = * ) 

Parameter Delimiter

This attack is based on the manipulation of parameter delimiters used by web application input vectors in order to cause unexpected behaviors like access control and authorization bypass and information disclosure, among others.
Example:
Attacker can simply provide a value with the delimiter in it and extra commands or information. The web app would process it as if it were part of regular data.

Regular expression Denial of Service - ReDoS

The Regular expression Denial of Service (ReDoS) is a Denial of Service attack, that exploits the fact that most Regular Expression implementations may reach extreme situations that cause them to work very slowly (exponentially related to input size). An attacker can then cause a program using a Regular Expression to enter these extreme situations and then hang for a very long time.

The attacker might use the above knowledge to look for applications that use Regular Expressions, containing an Evil Regex, and send a well-crafted input, that will hang the system. Alternatively, if a Regex itself is affected by a user input, the attacker can inject an Evil Regex, and make the system vulnerable.

Resource Injection

This attack consists of changing resource identifiers used by an application in order to perform a malicious task. When an application permits a user input to define a resource, like a file name or port number, this data can be manipulated to execute or access different resources. 
In order to be properly executed, the attacker must have the possibility to specify a resource identifier through the application form and the application must permit its execution

The resource injection attack focuses on accessing other resources than the local filesystem, which is different attack technique known as a Path Manipulation attack.

Server-Side Includes (SSI) Injection

The Server-Side Includes attack allows the exploitation of a web application by injecting scripts in HTML pages or executing arbitrary codes remotely. It can be exploited through manipulation of SSI in use in the application or force its use through user input fields.

In any case, the attack will be successful only if the web server permits SSI execution without proper validation. This can lead to access and manipulation of file system and process under the permission of the web server process owner.

Example ( showing the SSI code on the server side) : Windows:
List files of directory:
< !--#exec cmd="dir" -->

Special Element Injection

Special Element Injection is a type of injection attack that exploits a weakness related to reserved words and special characters.
Every programming language and operating system has special characters considered as reserved words for it. However, when an application receives such data as user input, it is possible to observe unexpected behavior in the application when parsing this information. This can lead to information disclosure, access control and authorization bypass, code injection, and many other variants.
According to the characters used, the Special Element Injection attack can be performed using macro symbols, parameter delimiter and null characters/null bytes, among others.

Parameter Delimiter is another variant of Special Element Injection. 


SQL Injection

SQL injection attack consists of insertion or "injection" of a SQL query via the input data from the client to the application. A successful SQL injection exploit can read sensitive data from the database, modify database data (Insert/Update/Delete), execute administration operations on the database (such as shutdown the DBMS), recover the content of a given file present on the DBMS file system and in some cases issue commands to the operating system. SQL injection attacks are a type of injection attack, in which SQL commands are injected into data-plane input in order to effect the execution of predefined SQL commands.

Threat Modeling

  • SQL injection attacks allow attackers to spoof identity, tamper with existing data, cause repudiation issues such as voiding transactions or changing balances, allow the complete disclosure of all data on the system, destroy the data or make it otherwise unavailable, and become administrators of the database server.
  • SQL Injection is very common with PHP and ASP applications due to the prevalence of older functional interfaces. Due to the nature of programmatic interfaces available, J2EE and ASP.NET applications are less likely to have easily exploited SQL injections.
  • The severity of SQL Injection attacks is limited by the attacker’s skill and imagination, and to a lesser extent, defense in depth countermeasures, such as low privilege connections to the database server and so on. In general, consider SQL Injection a high impact severity.


Web Parameter Tampering

The Web Parameter Tampering attack is based on the manipulation of parameters exchanged between client and server in order to modify application data, such as user credentials and permissions, price and quantity of products, etc. Usually, this information is stored in cookies, hidden form fields, or URL Query Strings, and is used to increase application functionality and control.
This attack can be performed by a malicious user who wants to exploit the application for their own benefit, or an attacker who wishes to attack a third-person using a Man-in-the-middle attack. In both cases, tools likes Webscarab and Paros proxy are mostly used.
The attack success depends on integrity and logic validation mechanism errors, and its exploitation can result in other consequences including XSSSQL Injection, file inclusion, and path disclosure attacks.


XPATH Injection

Similar to SQL Injection, XPath Injection attacks occur when a web site uses user-supplied information to construct an XPath query for XML data. By sending intentionally malformed information into the web site, an attacker can find out how the XML data is structured, or access data that he may not normally have access to. He may even be able to elevate his privileges on the web site if the XML data is being used for authentication (such as an XML based user file).

Because there is no level access control it's possible to get the entire document. We won't encounter any limitations as we may know from SQL injection attacks.


Path Traversal Attack


This category of attacks exploit various path vulnerabilities to access files or directories that are not intended to be accessed. This attack works on applications that take user input and use it in a "path" that is used to access a filesystem. If the attacker includes special characters that modify the meaning of the path, the application will misbehave and may allow the attacker to access unauthorized resources. This type of attack has been successful on web servers, application servers, and custom code.


Path Traversal

A Path Traversal attack aims to access files and directories that are stored outside the web root folder. By browsing the application, the attacker looks for absolute links to files stored on the web server. By manipulating variables that reference files with “dot-dot-slash (../)” sequences and its variations, it may be possible to access arbitrary files and directories stored on file system, including application source code, configuration and critical system files, limited by system operational access control. The attacker uses “../” sequences to move up to root directory, thus permitting navigation through the file system.


Probabilistic Techniques


Brute force attack


 the attacker is trying to bypass security mechanisms while having minimal knowledge about them.
Brute-force attacks are mainly used for guessing passwords and bypassing access control. Very often the target of an attack are data in forms (GET/POST) and users' Session-IDs.

Cash Overflow


A Cash Overflow attack is a Denial of Service attack specifically aimed at exceeding the hosting costs for a cloud application, either essentially bankrupting the service owner or exceeding the application cost limits leading the Cloud Service Provider disabling the application.



Cryptanalysis


Cryptanalysis is a process of finding weaknesses in cryptographic algorithms and using these weaknesses to decipher the ciphertext without knowing the secret key (instance deduction). Sometimes the weakness is not in the cryptographic algorithm itself, but rather in how it is applied that makes cryptanalysis successful


An attacker may have other goals as well, such as:
§  Total Break - Finding the secret key.
§  Gobal Deduction - Finding a functionally equivalent algorithm for encryption and decryption that does not require knowledge of the secret key.
§  Information Deduction - Gaining some information about plaintexts or ciphertexts that was not previously known.
§  Distinguishing Algorithm - The attacker has the ability to distinguish the output of the encryption (ciphertext) from a random permutation of bits.



Denial of Service


The Denial of Service (DoS) attack is focused on making unavailable a resource (site, application, server) for the purpose it was designed. There are many ways to make a service unavailable for legitimate users by manipulating network packets, programming, logical, or resources handling vulnerabilities, among others. 

DoS User Specified Object Allocation
result: Out of memory.
DoS User Input as a Loop Counter
result:unnecessary execution
DoS Storing too Much Data in Session
DoS Locking Customer Accounts
DoS Failure to Release Resources
DoS Buffer Overflows


Protocol Manipulation

HTTP Request Smuggling

To exploit the HTTP Request Smuggling, some specific conditions must exist, such as the presence of specific proxy system and version such as SunOne Proxy 3.6 (SP4) or FW-1/FP4-R55W beta or an XSS vulnerability in the web server.
Basically the attack consists of submitting an HTTP request that encapsulates a second HTTP request in the same header, as shown below.
GET /some_page.jsp?param1=value1&param2=
Content-Type: application/x-www-form-
Content-Length: 0
Foobar: GET /mypage.jsp HTTP/1.0
Cookie: my_id=1234567
Authorization: Basic ugwerwguwygruwy
In this case, the first HTTP header is parsed by the proxy system and the second by the final system, permitting the attacker to bypass the proxy’s access control.
Also...
HTTP Request Smuggling is an attack technique that abuses the discrepancy in parsing of non RFC compliant HTTP requests between two HTTP devices (typically a front-end proxy or HTTP-enabled firewall and a back-end web server) to smuggle a request to the second device "through" the first device. This technique enables the attacker to send one set of requests to the second device while the first device sees a different set of requests. In turn, this facilitates several possible exploitations, such as partial cache poisoning, bypassing firewall protection and XSS.

HTTP Response Splitting

HTTP response splitting occurs when:
  • Data enters a web application through an untrusted source, most frequently an HTTP request.
  • The data is included in an HTTP response header sent to a web user without being validated for malicious characters.
HTTP response splitting is a means to an end, not an end in itself. At its root, the attack is straightforward: an attacker passes malicious data to a vulnerable application, and the application includes the data in an HTTP response header.
To mount a successful exploit, the application must allow input that contains CR (carriage return, also given by %0d or \r) and LF (line feed, also given by %0a or \n)characters into the header. These characters not only give attackers control of the remaining headers and body of the response the application intends to send, but also allow them to create additional responses entirely under their control.

Traffic flood

Traffic Flood is a type of DoS attack targeting web servers. The attack explores the way that the TCP connection is managed. The attack consists of the generation of a lot of well-crafted TCP requisitions, with the objective to stop the Web Server or cause a performance decrease.
The attack explores a characteristic of the HTTP protocol, opening many connections at the same time to attend a single requisition. This special feature of the http protocol, which consists of opening a TCP connection for every html object and closing it, could be used to make two different kinds of exploitations. The Connect attack is done during the establishment of the connection, and the Closing attack is done during the connection closing.

Examples:
Connect attack
This type of attack consists of establishing a big number of fake TCP connections with an incomplete HTTP request until the web server is overwhelmed with connections and stops responding.
The aim of the incomplete HTTP request is to keep the web server, with the TCP connection in Established state, waiting for the completion of the request, as shown in figure 1. Depending on the implementation of the web server, the connection stays in this state until there is a timeout of the TCP connection or of the web server. In this way it’s possible to establish a great number of new connections before the first ones begin to timeout. Moreover, the generation rate of new connections grows faster than the expiring ones.

The attack could also affect a firewall that implements a proxy like access control as Checkpoint FW1.

Closing Attack
The Closing Attack is done during the ending steps of a TCP connection, exploring how some web servers deal with the finalization of the TCP connection especially with the FIN_WAIT_1 state. The attack, as explained by Stanislav Shalunov, "comes in two flavors: mbufs exhaustion and process saturation.
When doing mbufs exhaustion, one wants the user-level process on the other end to write the data without blocking and closing the descriptor. The kernel will have to deal with all the data, and the user-level process will be free, so that more requests can be sent this way and eventually consume all the mbufs or all physical memory, if mbufs are allocated dynamically.
When doing process saturation, one wants user-level process to block while trying to write data. The architecture of many HTTP servers will allow serving only a certain number of connections at a time. When this number of connections is reached, the server will stop responding to legitimate users. If the server doesn't put a bound on the number of connections, resources will still be tied up and eventually the machine comes to a crawling halt.
Asymmetric resource consumption
An attacker can force a victim to consume more resources than should be allowed for the attacker's level of access. The program can potentially fail to release or incorrectly release a system resource. 


Spoofing



Man-in-the-middle attack

The man-in-the middle attack intercepts a communication between two systems.The MITM attack is very effective because of the nature of the http protocol and data transfer which are all ASCII based.

MITM Attack tools

There are several tools to realize a MITM attack. These tools are particularly efficient in LAN network environments, because they implement extra functionalities, like the arp spoof capabilities that permit the interception of communication between hosts.
  • PacketCreator
  • Ettercap
  • Dsniff
  • Cain e Abel

MITM Proxy only tools

Proxy tools only permit interactiion with the parts of the HTTP protocol, like the header and the body of a transaction, but do not have the capability to intercept the TCP connection between client and server. To intercept the communication, it’s necessary to use other network attack tools or configure the browser.
  • OWASP WebScarab
  • Paros Proxy
  • Burp Proxy
  • ProxyFuzz
  • Odysseus Proxy
  • Fiddler (by Microsoft)


Sniffing Attacks

Network Eavesdropping


Network Eavesdropping or network sniffing is a network layer attack consisting of capturing packets from the network transmitted by others' computers and reading the data content in search of sensitive information like passwords, session tokens, or any kind of confidential information.
The attack could be done using tools called network sniffers. These tools collect packets on the network and, depending on the quality of the tool, analyze the collected data like protocol decoders or stream reassembling.
Depending on the network context, for the sniffing to be the effective, some conditions must be met:

• LAN environment with HUBs

This is the ideal case because the hub is a network repeater that duplicates every network frame received to all ports, so the attack is very simple to implement because no other condition must be met.

• LAN environment with switches

To be effective for eavesdropping, a preliminary condition must be met. Because a switch by default only transmits a frame to the port, a mechanism that will duplicate or will redirect the network packets to an evil system is necessary. For example, to duplicate traffic from one port to another port, a special configuration on the switch is necessary. To redirect the traffic from one port to another, there must be a preliminary exploitation like the arp spoof attack. In this attack, the evil system acts like a router between the victim’s communication, making it possible to sniff the exchanged packets.

• WAN environment

In this case, to make a network sniff it's necessary that the evil system becomes a router between the client server communications. One way to implement this exploit is with a DNS spoof attack to the client system.
Network Eavesdropping is a passive attack which is very difficult to discover. It could be identified by the effect of the preliminary condition or, in some cases, by inducing the evil system to respond a fake request directed to the evil system IP but with the MAC address of a different system.

Resource Manipulation

Double Encoding

This attack technique consists of encoding user request parameters twice in hexadecimal format in order to bypass security controls or cause unexpected behavior from the application. It's possible because the webserver accepts and processes client requests in many encoded forms.
By using double encoding it’s possible to bypass security filters that only decode user input once. The second decoding process is executed by the backend platform or modules that properly handle encoded data, but don't have the corresponding security checks in place.
Attackers can inject double encoding in pathnames or query strings to bypass the authentication schema and security filters in use by the web application.
There are some common characters sets that are used in Web applications attacks. For example, Path Traversal attacks use “../” (dot-dot-slash) , while XSS attacks use “<” and “>” characters. These characters give a hexadecimal representation that differs from normal data.
For example, “../” (dot-dot-slash) characters represent %2E%2E%2f in hexadecimal representation. When the % symbol is encoded again, its representation in hexadecimal code is %25. The result from the double encoding process ”../”(dot-dot-slash) would be %252E%252E%252F:

Forced browsing

Forced browsing is an attack where the aim is to enumerate and access resources that are not referenced by the application, but are still accessible.
An attacker can use Brute Force techniques to search for unlinked contents in the domain directory, such as temporary directories and files, and old backup and configuration files. These resources may store sensitive information about web applications and operational systems, such as source code, credentials, internal network addressing, and so on, thus being considered a valuable resource for intruders.
This attack is performed manually when the application index directories and pages are based on number generation or predictable values, or using automated tools for common files and directory names.
This attack is also known as Predictable Resource Location, File Enumeration, Directory Enumeration, and Resource Enumeration.


Repudiation Attack

A repudiation attack happens when an application or system does not adopt controls to properly track and log users' actions, thus permitting malicious manipulation or forging the identification of new actions. This attack can be used to change the authoring information of actions executed by a malicious user in order to log wrong data to log files. Its usage can be extended to general data manipulation in the name of others, in a similar manner as spoofing mail messages. If this attack takes place, the data stored on log files can be considered invalid or misleading.

Consider a web application that makes access control and authorization based on SESSIONID, but registers user actions based on a user parameter defined on the Cookie header

Setting Manipulation

This attack aims to modify application settings in order to cause misleading data or advantages on the attacker's behalf. He may manipulate values in the system and manage specific user resources of the application or affect its functionalities.
An attacker can exploit several functionalities of the application using this attack technique, but it would not possible to describe all the ways of exploration, due to innumerable options that attacker may use to control the system values.
Using this attack technique, it is possible to manipulate settings by changing the application functions, such as calls to the database, blocking access to external libraries, and/or modification log files.

Spyware

Spyware is a program that captures statistical information from a user's computer and sends it over internet without user acceptance. This information is usually obtained from cookies and the web browser’s history. Spyware can also install other software, display advertisements, or redirect the web browser activity. Spyware differs from a virus, worm, and adware in various ways. Spyware does not self-replicate and distribute itself like viruses and worms, and does not necessarily display advertisements like adware. The common characteristics between spyware and viruses, worms, and adware are:
1.   exploitation of the infected computer for commercial purposes
2.   the display, in some cases, of advertisements

Unicode Encoding
The attack aims to explore flaws in the decoding mechanism implemented on applications when decoding Unicode data format. An attacker can use this technique to encode certain characters in the URL to bypass application filters, thus accessing restricted resources on the Web server or to force browsing to protected pages. 

Path Traversal attack URL with Unicode Encoding(original url: http://vulneapplication/../../appusers.txt) :
http://vulneapplication/%C0AE%C0AE%C0AF%C0AE%C0AE%C0AFappusers.txt