Thursday 19 January 2012


Who Should Read:
  1. All java architects/developers/designers.
  2. All who are interested to understand the best practices to avoid secuirty loop holes in a web application.



7 Coding/Design practices to secure your web application

  1. Input Validation:
    • Prefer to have white list validation instead of black list validation.Idea is to accept input data which belongs to the set of known good values.
    • Regular Expression can be a good choice for implementing while list validations.For e.g
      public boolean validatePostCode(String code) {
        return (code != null && 
        Pattern.matches("/^(((2|8|9)\d{2})|((02|08|09)\d{2})|
        ([1-9]\d{3}))$/",code)) ? true : false;
      }
    • One should always prefer third party while list validatiors. Apache Commons validatior can be a good choice for input validation.
     
  1. Secure File Upload:
    • Try to upload files on some dedicated file area instead of directly storing in database or on some location in website tree.
    • Also apply validation checks for size, mime type and file type.
    • Java Mime magic library can be a good choice to validate mime type.
    • Also use to scan uploaded files. You can invoke antivirus CLI via Java Run Time to scan files on the fly.
  1. Output Encoding ( Escaping):
    • Escape html before inserting data into html elements for e.g. <body> escapeHTML(data) </body> .
    • Encode following 5 characters into html entities (& to &amp; > to &lt; < to &gt; “ to &qot; to &#x27; / to &#x2f
    • Escape java script before putting any data in java script elements for e.g. <script>alert(‘escapeJavaScript(data)’ </script>
    • Escape URLs e.g < a href="escapeURL(url)" />
    • Escape XML
    • You can use a apache commons StringEscapeUtils class to perform all above encodings. There are readymade methods like escapeHtml, escapeJavaScript, escapeXML, escapeURL
  1. Exception Handling:
    • Exception stack traces should not be displayed on browser.
    • Never let any exception leak any sensitive information to user/browser.
    • Catch each and every exception on the server and translate exception in a relevant error message.
    • Global exception handler can work for all uncaught errors.
  1. Logging:
    • What to log: All security related events like login, accessing a URL, changing role, assessing a resource.
    • What not to log: Any confidential or sensitive information like passwords, user credit card details etc.
  1. Security API:
  1. Avoid SQL injection:
    • Always use prepared statement to support parametrized queries.
    • Avoid string concatenation or string replacement to form queries.