Thursday, June 8, 2017

Security training - All 18 attack vectors

Command Injection
  1. If you are running System commands - don't take user input blindly which would be used in commands
  2. Apply filtering, rules.
  3. For e.g. user can provide ';id' as part of the input which will expose current user details.
  4. Simple fix - put a regex filter to ensure what all is allowed.
SQL Injection
  1. Don't trust user input blindly.
  2. Escape or rather use parametrized queries.
Session FixationIf you take user supplied session identifier, another user could use that to take the identity of someone else.

Use of insufficiently random values - for e.g. to generate session ids

Reflected XSS (Cross side scripting)

If you print user provided input as it is :
For e.g.

https://tradesearch.codebashing.com/projects?search=%3Cscript%3Ealert('You got hacked')%3C%2Fscript%3E

So, escape user input before printing.

Remedy in Java
In JSP - use <c:out>

Persistent XSSIf you allow the user to submit values to database which will be later printed on a web page. For e.g. if I am viewing someone else's profile, and that person has put javascript in his name - that javascript will execute in my session and send out my cookie information somewhere.

Remedy in Java
Again use <c:out> in JSP

Directory traversal
If you allow user to supply filepath as a request parameter.

For e.g. https://traderesearch.codebashing.com/article/show_file?file=../etc/passwd
Remedy
Don't allow access in this manner. Rather provide ids for files. And manage user access to those ids.
Else

public void doGet(HttpServletRequest request, HttpServletResponse response) {

  String result;

  String filename = request.getParameter("file");


  try {

     File file = new File("/tmp/" + filename);
String canonicalPath = file.getCanonicalPath();
if(!canonicalPath.startsWith("/tmp/")) {
  throw new GenericException("Unauthorized access");
}
BufferedReader reader = new BufferedReader(new FileReader(file));
     String line = null;
     while((line = reader.readLine()) != null) {
        result = line;
     }

  } catch (Exception e) {

     e.printStackTrace();
  }

  try {

Privileged interface exposure

For e.g. remove your admin interfaces from google search results.
If they ain't supposed to be exposed outside, don't.

Leftover Debug code

For e.g. you can leave a comment in JS code that add debug =1 to URL. Remove such comments.

Authentication credentials in URL - logs etc.


Session exposure within URL  - 


User Enumeration - for e.g. forgot password interface, don't show whether successful or not.


Horizontal privilege escalation- for e.g. just by changing user id I can access someone else's edit profile page.


Vertical privilege escalation  - For e.g. if I just replace "user" with "admin" I get to another page with more privileges - https://tradesocial.codebashing.com/trade_social/admin/show


Insecure redirects - for e.g. yourserver.com/redirect?url=someotherurl . So your server is responsible for redirects. Don't redirect to urls which you don't trust.


Click Jacking - Display an iframe of my stock broking website with opacity 0 in an iframe and place "Research report" button on the malicious website such that clicking that button actually clicks a button beneath in the iframe and sells my stocks.


Remedy :


To defend against Click Jacking attacks the web server should be configured to send X-Frame-Options in the response headers. 


Configuring the X-Frame-Options to either DENY, SAMEORIGIN, or ALLOW-FROM will prevent malicious websites from embedding your application's content. 

I.e. it will prevent the browser from loading your application content within <frame> or <iframe> tags of other websites. 

CSRF  - Cross site request forgery (GET) - if I am using GET requests to perform actions like delete/update etc., someone can embed those URLs in a webpage as img src. If I open that web page, using my cookies/session that URL will perform updates on server.

CSRF (POST) - A malicious website could include a form with your POST URL. And if someone clicks on submit, it would use your cookies etc. to execute that action. Or even without clicking on submit, form could be submitted programatically.
Remedy - use Anti CSRF token, synchronizer token, challange token etc.


XML External Entity Injection

  1. If users are allowed to upload XML files which your server is going to parse, you are at risk.
  2. An XXE attack works by taking advantage of a feature in XML, namely XML eXternal entities (XXE) that allows external XML resources to be loaded within an XML document.
  3. By submitting an XML file that defines an external entity with a file:// URI, an attacker can effectively trick the application's SAX parser into reading the contents of arbitrary file(s) that reside on the server-side filesystem.

Example:
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE foo [<!ELEMENT foo ANY >
<!ENTITY bar SYSTEM "file:///etc/passwd" >]>

<trades>
    <metadata>
        <name>Apple Inc</name>
        <stock>APPL</stock>
        <trader>
   
<foo>&bar;</foo>
</trades>

  1. Java web applications using XML libraries are particularly vulnerable to external entity (XXE) injection attacks because the default settings for most Java XML SAX parsers is to have XXE enabled by default.
  2. To use these parsers safely, you have to explicitly disable referencing of external entities in the SAX parser implementation you use. We'll revisit this in the remediation section later.
  3. Problem code:
public class TradeDocumentBuilderFactory {

    public static DocumentBuilderFactory newDocumentBuilderFactory() {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        try {
              documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", true);
              documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", true);
        } catch(ParserConfigurationException e) {
            throw new RuntimeException(e);
        }
        return documentBuilderFactory;
    }

}

Remedy:
  1. Because user supplied XML input comes from an "untrusted source" it is very difficult to properly validate the XML document in a manner to prevent against this type of attack.
  2. Instead the XML processor should be configured to use only a locally defined Document Type Definition (DTD) and disallow any inline DTD that is specified within user supplied XML document(s).
  3. Due to the fact that there are numerous XML parsing engines available for Java, each has its own mechanism for disabling inline DTD to prevent XXE. You may need to search your XML parser's documentation for how to "disable inline DTD" specifically.

For example with Java XMLInputFactory:
xmlInputFactory.setProperty(
XMLInputFactory.SUPPORT_DTD, false
);

Let's see how the above fix can be applied to our vulnerable example to remediate the XXE vulnerability.

Improved code :

public class TradeDocumentBuilderFactory {

    public static DocumentBuilderFactory newDocumentBuilderFactory() {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        try {
//              documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", true);
//              documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", true);
documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);    
documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
} catch(ParserConfigurationException e) {
            throw new RuntimeException(e);
        }
        return documentBuilderFactory;
    }

}

DOM XSS (Cross side scripting)

1. Landing page URL : https://tradenews.codebashing.com/guests/landing#guest
2. Pseudocode for Landing JSP web page

 <h6>
<script>
   var name = document.location.hash.split('#')[1]; //https://tradenews.codebashing.com/guests/landing#guest
   document.write("Hello " + name + "! Please login or signup to access news stories");
</script>
</h6>


Attack
Part 1 : Attacker sends email like this :

Hi Alice, Hope you are well ! Please find below a 20% discount code to join TradeNEWS.

https://tradenews.codebashing.com/guests/landing#<script>window.location = 'https://fake-tradenews.codebashing.com';</script> Kind Regards, Bob



Note the username is replaced with javascript code. Once user clicks on the link, he/she is redirected to a fake website. There credit card information can be stolen.


RemedyTo defend against Cross Site Scripting attacks within the application user's Browser Document Object Model (DOM) environment a defense-in-depth approach is required, combining a number of security best practices.

Note You should recall that for Stored XSS and Reflected XSS injection takes place server side, rather than client browser side. Whereas with DOM XSS, the attack is injected into the Browser DOM, this adds additional complexity and makes it very difficult to prevent and highly context specific, because an attacker can inject HTML, HTML Attributes, CSS as well as URLs.

As a general set of principles the application should first HTML encode and then Javascript encode any user supplied data that is returned to the client. For example using OWASP ESAPI:



document.write(<%=Encoder.encodeForJS(Encoder.encodeForHTML(userSuppliedData))%>);



Due to the very large attack surface this approach is no silver bullet, and as such developers are strongly encouraged to review areas of code that are potentially susceptible to DOM XSS, including but not limited to:



window.name
document.referrer
document.URL
document.documentURIlocation
location.href
location.search
location.hash
eval
setTimeout
setInterval
document.write
document.writeIn


Note: OWASP ESAPI (The OWASP Enterprise Security API) is a free, open source, web application security control library that makes it easier for programmers to write lower-risk applications.

Let's apply a suitable Regex pattern to remediate this particular DOM XSS vulnerability.

<h6>

<script>



   var name = document.location.hash.split('#')[1]; //https://tradenews.codebashing.com/guests/landing#guest



if (name.match(/^[a-zA-Z0-9]*$/))

{

   document.write("Hello " + name + "! Please login or signup to access news stories");

}

else

{

window.alert("Security error");

}



</script>

No comments:

Blog Archive