7 Coding/Design practices to secure your web application

  1. Input Validation:
    1. 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.
    2. 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;}
    3. One should always prefer third party while list validatiors. Apache Commons validatior can be a good choice for input validation.
  2. Secure File Upload:
    1. Try to upload files on some dedicated file area instead of directly storing in database or on some location in website tree.
    2. Also apply validation checks for size, mime type and file type.
    3. Java Mime magic library can be a good choice to validate mime type.
    4. Also use to scan uploaded files. You can invoke antivirus CLI via Java Run Time to scan files on the fly.
  3. Output Encoding ( Escaping):
    1. Escape html before inserting data into html elements for e.g. <body> escapeHTML(data) </body> .
    2. Encode following 5 characters into html entities (& to &amp; > to &lt; < to &gt;“ to &qot;  to &#x27; / to &#x2f
    3. Escape java script before putting any data in java script elements for e.g.<script>alert(‘escapeJavaScript(data)’ </script>
    4. Escape URLs e.g < a href="escapeURL(url)" />
    5. Escape XML
    6. You can use a apache commons StringEscapeUtils class to perform all above encodings. There are readymade methods like escapeHtml, escapeJavaScript, escapeXML, escapeURL
  4. Exception Handling: 
    1. Exception stack traces should not be displayed on browser.
    2. Never let any exception leak any sensitive information to user/browser.
    3. Catch each and every exception on the server and translate exception in a relevant error message.
    4. Global exception handler can work for all uncaught errors.
  5. Logging:
    1. What to log: All security related events like login, accessing a URL, changing role, assessing a resource.
    2. What not to log: Any confidential or sensitive information like passwords, user credit card details etc.
  6. Security API:
    1. OWASP Enterprise security API provides all essentials security services.
    2. Spring security can be a good decision for Authentication and Authorizations.
    3. Bouncycastle can be used as light weight cryptography API.
  7. Avoid SQL injection:
    1. Always use prepared statement to support parametrized queries.
    2. Avoid string concatenation or string replacement to form queries.