Thursday, June 11, 2015

Writing secure Javascript and HTML5

Web apps today are quite sophisticated on the client-side, with HTML, Javascript and CSS content. Security concerns have maginified especially because of multi-domain content on a page, such as is seen in Mashup applications. Areas to be considered carefully are:

Web Storage:

  • Storing sensitive data

Rather use sessionStorage.setItem() instead of localStorage which persists the stored data indefinitely, unless explicitly removed. Instead, the code should look like :


Cross Domain Communication:


  • Web Messaging

When using Web messaging, be sure to validate the origin of a message and the message itself. e.g.

window.addEventListener("message", receiveMessage, false);
...
function receiveMessage(event) {
    if  (event.origin !=== "http://www.example.com:")
       return;
    if (!validateEmail(event.data))
       return;
    div.getElementById('user_email_address').textContent = event.data;
    ...
}

  • CORS - Cross domain requests
Weak CORS Policy
(Preflight request is the initial request issued prior to sending a CORS request to determine the origins, HTTP methods, and custom headers that can be used to access a given resource on a server.)

Secure Cross-Domain Communications - Properly Sandboxed IFrames:



  • Other Communication mechanisms - if possible don't use them 
Browsers offer other mechanisms, in addition to CORS (Cross-origin resource sharing) and the Web Messaging API, to perform cross-domain communications. Each mechanism involves additional risks that must be considered.

  •  Do not use window.name for Messaging
  • Avoid Fragment Identifier Messaging (FIM)
  • Avoid setting the document.domain property
  • In case of communication over web sockets always be sure to check the WebSocket origin header to confirm that the packet-originator domain is not an unknown one.

Javascript Best Practices:


When using Javascript the main concern is to prevent malicious code from being included and executed in the context of legitimate web pages
Understanding the dataflow of your JS code is key, in order to apply input validation and output encoding. Data flow analysis is then important. It helps determine paths data takes from JS source to sink functions. Some common JS sources and sinks for data analysis.

  •  Sources:

   document referer - set by server that initiated HTTP-302  redirection
   window.name - can be used to carry out cross-domain communications between an iframe and its parent document
   location - property of an element that describes url at which element is hosted
   event.data - Message payload sent via html 5 web messaging postMessage() function
   localStorage.getItem - Retrieves data from the localStorage object
  sessionStorage.getItem - Retrieves data from the sessionStorage object
  document.cookie - Retrieves data from the client's cookies


  • Sinks:

  document.write() - writes content to the document object
  innerHTML() - reads or sets a DOM element's markup
  location.* - The location object contains info about the current URL
  location.assign() - Loads a new page into the browser
 eval(string) - evaluate or execute its argument. Ofetn used to execute dynamically built/concatenated expressions
  setTimeout(code, millisec, lang) - Calls a function or evaluates an expression after a specified number of millisec
 setInterval(code, millisec, lang) - Same as above but at specified timme intervals, repeatedly
 object.execScript(code, language) - Executes the specified script in the provided language.

Input Validation :


  •  Verify data origin

 if data has multiple components, like headers and payload, tokenize it and check syntax, finally semantics for appropriateness to the context it will be used in


  • Strategies for Input validation

 Black-listing ( exclude specified bad characters)
 White-listing ( include only known-good chars)
 rostering or mapping (only allow good complete strings or values)
indirect selection (only allow good indirect key values )

Output Encoding ( complement to input validation) 

Replace any chars that could be interpreted as special or as control chars in the context of their use,  with their corresponding encoded representation. The encoding scheme depends on the context of their use. When implementing output encoding :


  •  Identify output context - Conetxts may be HTML, dynamically assembled and evaluated JS, and CSS. Even within these there are sub-contexts where different encodings may apply. e.g. for HTML code :

 Element names
 Attribute names
 Attribute values
 HTML data (text node)
 Event Handlers

e.g. <a href="http://abc.com" onclick="function() {alert('hi');}">Contact Us!</a>
In the above string 'a' is an Element name, "href' an attribute name etc. Note how the value of the onclick HTML attribute is a Javascript sub-context within the enclosing HTML context.


  • Use Proper Encoding -

Use public encoding libraries e.g. OWASP ESAPI, JQuery, Dojo Toolkit, Microsoft's WPL. Dont write your own.
 e.g. of transformation by encoding:-
  HTML entity encoding
 "&<>   gets converted to &quot;&amp;&lt;&gt;

HTML attribute encoding also similar to above

URI encoding

param1=a&param2=b#something      to       param1%3Da%26param2%3Db%23something

Javascript parameter encoding

hello)\";(                 to            hello\x29\x22\x3B\x28

Additionally, there are several other best practices to follow:


  • Validate Poster attribute in <Video> elements - beware of scripts in the values

  •  Beware of oninput attribute - this event handler is new in HTML5 and applies to all elements. It may be used to inject malicious javascript when an element receives input.

  • Avoid using eval() function - If you have to, ensure that input that is passed is properly validated.

 e.g.
  Insecure use :
    function Test() { this.bar ="hi"; this.bar1="h1";}
    var foo = new Test();
    function access_property(prop) { var value = eval('foo.'+prop); alert(value); }
    access_property(document.getElementById('prop').value);
Secure Use:
   function Test() { this.bar ="hi"; this.bar1="h1";}
    var foo = new Test();
    function access_property(prop) { var value = foo[prop]; alert(value); }
    access_property(document.getElementById('prop').value);



  • Serve JS code securely

  Serve external JS libraries from an internal server
  Serve JS via HTTPS (SSL/TLS) ro avoid Man-in-the-Middle attackes which will change the JS script to cause harm to clients.



  • Set Cookies as HttpOnly so that malicious JS code can't access cookie info via document.cookie property, and can't hijack any session info stored in the cookie.



JSON Best practices:


  • Input Validation of Json data
 JSON data may be manipulated by Web Proxies (Fiddler) before reaching server.Similarly Man-in-Middle attacks could change JSON data before reaching client.


  • Do not include verbose error messages
Avoid JSON data containing detailed error messages when error occurs on the server.
e.g. { 'id': 39, 'error': 'db_query', 'message': 'Invalid parameters for SQL statement "SELECT id, username, password FROM users WHERE username=\'admin\' AND password=null;"'}


  • Validate JSONP callback Method parameter
<script type="text/javascript" src="http://www.otherdomain.com/orderservice.svc/GetOrders?jsonp=processResults"></script>

More about using JSONP

JSONP message format is basically a normal JSON format with padding. I will explain what padding is all about in JSONP. As I said in the previous section in the Same Origin Policy <Script> tag is exempted. So a cross domain call can be done as shown as below.
<script type="text/javascript" src="http://www.otherdomain.com/orderservice.svc/GetOrders"></script>

This cross-domain call will be successful and the result will be returned in a JSON format as shown below.
[
{"OrderId":1000, "OrderItem":"Cricket Bat", "Quantity": 10, "TotalPrice":20000}
{"OrderId":1001, "OrderItem":"Football", "Quantity": 100, "TotalPrice":50000}
]
But this is of no use since we have received the data and are not processing it. Now let's check what JSONP does. Modify the script URL with an additional query string value as shown below:
<script type="text/javascript" src="http://www.otherdomain.com/orderservice.svc/GetOrders?jsonp=processResults"></script>
The above JSONP call to the cross-domain service will return the JSON with padding the given query string value as a script callback method.
parseResults([
{"OrderId":1000, "OrderItem":"Cricket Bat", "Quantity": 10, "TotalPrice":20000}
{"OrderId":1001, "OrderItem":"Football", "Quantity": 100, "TotalPrice":50000}
])
You can implement JSONP callback JavaScript function as shown below.
function parseResults(results) {
      alert('Cross domain JS call achieved. Have your implementation going in here!');
}
processResults will be called with the JSON data returned by the  response from a call to a cross-domain URL. The callback method is echoed back in the JSONP response along with the requested data.This should be properly validated before use anywhere in calling page.




  • Avoid using eval on JSON data


eval() is often used to convert JSON into Javascript objects. But this should be avoided. Instead use JSON.parse( {...} ), since this will do the same thing without the potential to execute maliciously injected code.

Common Assessment approaches: 


  • Static code Analysis Security Code Reviews
 - manual and automated. Examples of Automated tools are AppScan Source, HP Fortify Source Code Analyzer, Coverity Statis Analysis. 


  • Dynamic Analysis - 
Dynamic Application Security Testing (DAST) tests and evaluates a program at runtime, in the production (deployed) environment.
  1. treats program as blackbox
  2. limited insight into architecture or source code
  3. similar to activity that hackers would perform
  4. findings have lower false positives
  5. e.g. of this type of testing is "Penetration testing".
  6. lower level of return since it is done at a late stage of the product lifecycle - i.e. on deployment

Test knowledge:








Tuesday, June 9, 2015

Web Application Security Notes -

Two broad classes of Security Defects

 - Implementation Bugs (e.g. SQL injection, Cross-Site Scripting(XSS), Buffer overflow, Unsafe system calls, predictable identifiers, unsafe environment variables)
 - Architectural Flaws (e.g. misuse of cryptography, broad trust between components, privileged block protection failure, client-side trust, type safety confusion error, insecure auditing, broken or illogical access control, method over-riding problems, over-reliance on crypto)

Trinity of Trouble (that make security difficult)

Connectivity
Complexity
Extensibility

Browser Security Model

Same Origin policy - prevents contents and scripts from different domains from interacting. Note that this policy is enforced only when manipulating browser windows , frames, documents, cookies and xml http requests. It is not enforced when including documents from other domains and html tags such images, scripts and stylesheets
Two origins are the same iff Protocol(e.g. http), Domain (e.g. foo.com), and Port number matches

Cross-site scripting (XSS)

Mailcious code (javascript) supplied by attacker (via input to app) is run in victim's browser because malicious input is interpreted as a client-side script in Web browser. The script is run as if it originated from the domain of the vulnerable website. Two common types of XSS
 Stored XSS (Persistent) - script code permanently stored on target servers (database)
 Web app retrieves bad data from its database and displays script to victims.
 Reflected XSS - script code is injected in HTTP request (via URL, POST parameters, cookies, or HTTP headers) which the web app reflects to victims. Wherever the app accepts user input (e.g. in formdata or URL parameters) and then pass it as response is a potential hole (e.g. in a jsp). Because user can give a string containing malicious script as input and the server will pass it as is, in the reponse leading to broswser evaluating the script and damage being caused.
Remedy for this -  Validate user input (on server) and Encode Output generated as response. E.g. a malicious input

   <script>alert ("hacker")</script>

will display (due to output encoding) as 
  

   &lt;script&gt;alert(&quot;hacker&quot;)&lt;/script&gt;

For stored XSS input page may be A but the damage may be caused on page B. For Reflected XSS, the input and output pag are the same.

SQL injection

exploits vulnerabilities in the way data base queries are constructed and evaluated.
SQL injection attacks emply user supplied data to manipulate the structure of sql query
Attackers inject sql control chars and command keywords to change query structure. 
  • Single quote ('), equal(=), or comment(--). 
  • OR, SELECT, JOIN, UPDATE
When combined properly, the sql syntax can violate assumptions and policy.
Example:
    public boolean authenticate(String name, String passwd) {
       Statement stmt - this.conn.createStatement();
       String sql = "SELECT display_name from user_t WHERE name=\'" + name + "\' AND passwd = \'" + pass + "\'";
       ResultSet results = stmt.executeQuery(sql);
       return results.first();
    }

When this is called as follows :
    authenticate("admin","' or 'a' = 'a");
See how this call will result in an sql statement whose structure is completely different from intended, and that the result of the query execution will always return true;

To spot vulnerabilities, Look in the code for dynamically built SQL strings that use unaltered user input and concatenate it with sql keywords to form the final sql query string.
To test for SQL injection try URL like
   http://foo.com/bar.jsp?value=123*1    instead of http://foo.com/bar.jsp?value=123
 or for charactr=er values
  http://foo.com/bar.jsp?value=A%2BBC  instead of http://foo.com/bar.jsp?value=ABC
where %2B is the url-encoded value for + sign. If the former and latter urls give the same result, then it is very likely that the values are being interpreted as code, and this is a potential sql injection hole.

To remedy this, Use bound parameters with parametrized queries (prepared statements). Use stored procedures ( but avoid string concatenation of user input) .
 Again Input validation is required.
Reimplementation of the authenticate method using prepared statements
     public boolean authenticate(String name, String passwd) {
       Statement stmt - this.conn.createStatement();
       String sql = "SELECT display_name from user_t WHERE name=? AND passwd = ?";
       PreparedStatement pstmt = this.conn.prepareStatement(sql);
       pstmt.setString(0, name);
       pstmt.setString(1, passwd);

       ResultSet results = pstmt.executeQuery();
       return results.first();
    }

Header Manipulation

Under normal situations this is what a reponse looks like


The attack makes use of redirect urls that can be specified as URL params e.g. If a site can take a URL request  like
  http://www.bank.com/order.jsp?page=http://www.bank.com/freechecking
and treat the value of the page parameter as a redirect url, without any encoding, by adding the redirect url to the response of the original request, then what happens is as shown in this diagram:


This behaviour of the server can be misused by an attacker by issuing a url request like so ( %0d%0a is the url-encoded version of \r\n which are the chars that separate various name-value pairs of the http header. Where two of these character pairs appear, it signals the end of the header and start of the response content).


Under normal circumstances a redirect response is as follows :


But if the user enters the following into the address bar:
www.site.com/hello6.jsp?bar=userinput%0d%0aContent-Type:%20text/html;charset=ISO-8859-1%0d%0aContent-Length:%2019%0d%0a%0d%0a<h1>My%20content</h1>
then the value of the bar parameter is assigned by the server as the redirect 'url' in the response header for the original request,www.site.com/hello.jsp

The attacked reponse is as follows :


The Content-length setting in the attacker's bar parameter is to tell the browser to not see the legitimate portion of the response.
Typically the attacker will have something like "script>alert(document.cookie)</script>" or some other script to perform an XSS attack rather than harmless "My Content" output reponse.
Header manipulation can do :
  •    Cross-site scripting attack
  •    Cross-user defacement
  •    Web cache poisoning
  •    Page hijacking
  •    Browser Cache poisoning
Remedy
  • URL-encode any non-valid char before inclusion in http headers
  • Validate and remove/encode all user input for
        - CR LF
        - \r\n
        - %0d%0a
        - Any other encoding of these or other malicious chars before using them in HTTP headers

System Information Leak

Too much info helps attackers know more about application
Usability v/s security tradeoff
  • Display info securely
Never permit user to access stack trace data (exception stack ! Internal error stacks ! They should go the server's error log)
  • reverse engineering
    Looking at this overly helpful error message. The attacker knows the user id is correct and he needs to guess from only 10000 numbers to get the correct password !

Environment info is readily available to attacker
  • Running systems
  • Social engineering

How to test for it
Do an action or input that forces the app into error conditions to gain info

examples:
 Injection - SQL, XPATH injection
Test valid usernames using the forgot passwd page
Pass invalid date, get stack trace
Exploit error handling mechanism - XSS against the "following input is invalid..." message

Risk:

Provides knowledge of the app

Remedy:

Use try.catch blocks instead of displaying stack to end user
redirect users to proper error pages - may be just a single generic error page so that too much info is not given out.

Path Manipulation

Inserting unaltered user input as part of paths used in File I/O APIs allowing attackers to access or modify otherwise protected system resources.

Examples:

 http://foo.com/../../../etc/passwd
http://foo.com/bar?display=/etc/passwd

How to test:

 use following file paths in url to see if they are accepted by server :
   ../../../../boot.ini
  ../../../../../../etc/passwd
  file:///c:/boot.ini
etc.

See if the following paths show equivalent response behaviour. If they do then there is a path vulnerability:
  /a/b/c/foo.txt
  /a/b/c/../c/foo.txt
  /a/b/c/d/e/f/../../../foo.txt

Remedy:

 Use chrooted jails on Unix servers. This effectively changes the root for the process and code cannot access anything outside this root.
 Perform white list input validation of user's input (using regular expressions maybe)

Cross-Site Request Forgery

Victim is already logged into a site. He is tricked into making a request to a legitimate operation (changing profile info, transferring money, sending a message etc). Works with both Get and Post requests









Use a tool such as Fiddler to check if the Requests are sent with CSRF token

If the server does not implement CSRF (NONCE) tokens for requests, then the site is vulnerable to CSRF attacks. The token which is generated by the server, is unpredictable and hence non-guessable, is sent to the client as a hidden field during first contact by the client from a legitimate App page (such as login page), is stored with the client and passed as a hidden form input field with every request made by the client. The server processes these requests only if it finds the token, else ignores it.
 Although the user can see the value of the token, a third party will not be able to do that - i.e. the number cannot be stolen from the user's browser window.

Hidden Field Manipulation

Malicious users can manipulate HTML form fields even though they are hidden or disabled
This may influence server side logic flow.
Firebug may be used to convert a disabled button in the response to enabled, and then can be clicked.
Other hidden fields can also be edited.
This vulnerability can be tested using Fiddler to change value of hidden params and then seeing how the app behaves after submitting the request.
If the app trusts that the values of hidden fields are invisible to the user, viewing the source of the page after submitting the changed value should show the changes as the value of the hidden field.
Alternately, there may be an exception because the app was depending the value not being changed. How your app responds to this changed value will show whether it is vulnerable to hidden field manipulation.


Cookie Security:

How cookie security can be compromised:

  • Exposing a cookie to an insecure transfer protocol
  • exposing one cookie to multiple applications
  • Not having a cookie expire in reasonable time
  • Allowing cookie to be accessed by client-side scripts

How to test for it

Script access to cookie can be chcked typing at the console after the page is loaded :
   javascript:alert(document.cookie);
If a popup appears containing the cookie data, it means the HTTPOnly flag is not set (it should be, so that scripts can't access cookie).

Use Fiddler to inspect cookie info such as secure flag, domain, path, expiration

Detecting in Code


Mitigation and remediation



Session and State Management:

Normal workflow for a session




Session under attack :

Session hijacking can be done by

  •   Session id theft ( through XSS or sniffing)
  •   Session id prediction (or brute forcing)
  •   Session fixation (forcing victim to the sid of the attackers choosing, once the victim authenticates the session id becomes valid)









Weak Access Control

Where users can access the data of others or perform unauthorized operations. In web apps this can be through forceful browsing or parameter tampering

Access Control Violations are of 2 types
  •  Horizontal - User can access data of other users at the same role level
  • Vertical - User ca perform operations/access data outside of those specified for his/her role.



Monday, June 8, 2015

The Deacon OOAD method outline

The Deacon OOAD method outline

Three Model Approach:

Subject Matter Model: Comprises of domain entities(discovered in the subject matter), which are intrinsic and extrinsic state storing packets with identy, and sometimes state transition diagrams

From requirements and other architecture considerations, compatibility with legacy frameworks and code etc. find the 'entities' of the domain from 'nouns', 'relevant remembered events' etc. 
Chunking is used to breakup the domain into right-sized chunks, relevant to the domain,  that have high cohesion and low coupling.
DOn't pay attention to the behaviour of the domain entities. They are unlikely to carry over to the final software system.
Pay attention to the intrinsic state of the entities i.e. the value attributes of an entity - like mass, colour, interest rate etc. and record them
Pay attention to the extrinsic state of the entities i.e. their associations with other entities, along with cardinality.
Rarely, you may need to record State transition diagrams for one or (very rarely) more entities.
Avoid Many-many relationships between entities by trying to find a connecting 'hub' entity that connects the two entities.

Object Type Model: Comprises the Entity Types that comprise the design along with interaction diagrams like sequence diagrams for different use cases

Using CRC (Class-Responsibility-Collaboration) card method, employed on Use cases of interest, come up with the messages that need to passed to an entity, which translate to responsibilities that entities have to own. When the number of such responsibilities exceed 7 or so, try to see if the responsibilities can be delegated to other entities keeping in mind high Cohesiveness and low Coupling considerations. If no suitable existing entities are found see if you can come up with new entities - these are the speculative and contrived, not discovered or inherent in the subject matter. 
 A responsibility, in turn requires to pass other messages to other entities, to do it job. This leads to Sequence diagrams or collaboration diagrams. 
 The entities themselves lead to discovering of Object Types.
The whole philosophy is to follow outside-in design. Responsibilities and more entities are introduced on an entity because some entities outside it require services from it.

Technical Model: Comprises the Type and Class hierarchy, properly named

This finally leads to Class diagrams. Here again you use CRC's to allot reponsibilities. Naming should be most general for the root and intermediate classes/interfaces and specific for the concrete classes/interfaces.



Is this stock advise worth taking seriously?

 Introduction Business related TV channels and newspapers are replete with stock advisory from investment firms and certified individua...