11/11/2015 Secure Coding Guidelines for Content Security Policy | GnuDeveloper.com
http://www.gnudeveloper.com/cyber_security/secure_coding_guidelines_for_content_security_policy.html 1/4
Home Search Groups About Us Contact SignUp
Home > Groups > CyberSecurity
Secure Coding Guidelines for Content Security Policy
Submitted by vivekanandan on Wed, 11/04/2015 ­ 23:23
The CSP is the key concept for protecting the Cross­site scripting (XSS) from the browser side. Since XSS is the top most vulenerable injection attack. The
content  means  the  web  page  resource  as  javascript,  images  etc..  For  browser  side  security  we  need  to  understand  the  same­origin  policy,  cross­  origin  policy
(COP)
Why we need Content Security Policy:
The Server needs to clearly mention the trusted origin for the resources like javascript,images etc.. so that client will take the action accordingly. Since The
browser(client) and server are disconnected the server needs to mention the security policy for each page as part of HTTP header response
Secure coding guidelines for CSP:
1. Always use JavaScript in separate js file.
2. Always bind HTML element with Event Handlers so that clear separation of HTML & JavaScript can be maintained. js framework like jQuery supports this
feature .
example for button click event in jquery : $("#btnClick").click(function() { }
3. If legacy project already had inline JavaScript add script nonce with it, but consider unsafe and reduce ASAP.
4. Avoid use eval statement in JavaScript code.
5. Avoid using setTimeout methods since it internally the eval statement.
6. Always have separate css file means don't use inline styles.
Same­ origin policy (SOP):
The browser will decide the same ­origin policy based on 3 parts of
URL
http://www.gnudeveloper.com:80/
Protocol: HTTP
Domain name: www.gnudeveloper.com
Port number: 80
Based on the URL information browser will consider the web page belongs to same­ origin policy or cross­origin policy
Self: it represents same­origin policy
   script­src 'self'  ;
Cross­ origin policy (COP) or Cross­Origin Resource Sharing (CORS):
It represents content belongs to different origin, opposed to same­origin policy. By default Firefox browser won't allow cross­origin policy for the web pages since
it will create chance for Cross­site scripting (XSS). To allow all host specify as asterisk character *
   script­src *  ; 
The CSP Violation message can be viewed in the console.
self DIRECTIVE value  enforce the source domain(gnudeveloper.com) and image src,script src should be same hence error message as below 
 
Content Security Policy: The page's settings blocked the loading of a resource at infotree.in/themes/bartik/logo.png ("img‐src gnudeveloper.com").
Content Security Policy: The page's settings blocked the loading of a resource at code.jquery.com/jquery‐1.9.1.js ("script‐src gnudeveloper.com 'unsa
Since eval‐script is missing http header response, browser blocked the eval method 
call to eval() or related function blocked by CSP
Note: setTimeout will be allowed since it is indirect eval statement
11/11/2015 Secure Coding Guidelines for Content Security Policy | GnuDeveloper.com
http://www.gnudeveloper.com/cyber_security/secure_coding_guidelines_for_content_security_policy.html 2/4
The Firefox default settings as below
  default‐src *; script‐src 'self'; object‐src 'none'; style‐src 'self'  'unsafe‐inline'
11/11/2015 Secure Coding Guidelines for Content Security Policy | GnuDeveloper.com
http://www.gnudeveloper.com/cyber_security/secure_coding_guidelines_for_content_security_policy.html 3/4
Output: HTTP header Response
  HTTP/1.1 304 Not Modified
  Server: Apache‐Coyote/1.1
  Content‐Security‐Policy: default‐src 'none'; script‐src 'self' 'unsafe‐inline' ; options
  inline‐script eval‐script; xhr‐src 'self'; object‐src 'self'; style‐src
  'self'; img‐src 'self'; form‐action 'self'; connect‐src 'self';
  frame‐src 'self';sandbox;frame‐ancestors 'self'
  ETag: W/"268381‐1446607260430"
  Date: Sun, 08 Nov 2015 01:32:04 GMT
ContentSecurityPolicyFilter.java
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
@WebFilter("/*")
public class ContentSecurityPolicyFilter implements Filter {
 
  /** Filter configuration */
  @SuppressWarnings("unused")
  private FilterConfig filterConfig = null;
 
  /** List CSP HTTP Headers */
  private List<String> cspHeaders = new ArrayList<String>();
 
  /** Collection of CSP polcies that will be applied */
  private String policies = null;
 
  /**
   * Used to prepare (one time for all) set of CSP policies that will be
   * applied on each HTTP response.
   * 
   * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
   */
  @Override
  public void init(FilterConfig fConfig) throws ServletException {
    // Get filter configuration
    this.filterConfig = fConfig;
 
    // Define list of CSP HTTP Headers
    this.cspHeaders.add("Content‐Security‐Policy");
    this.cspHeaders.add("X‐Content‐Security‐Policy");
    this.cspHeaders.add("X‐WebKit‐CSP");  
 
    // Define CSP policies
    // Loading policies for Frame and Sandboxing will be dynamically defined
    // : We need to know if context use Frame
    List<String> cspPolicies = new ArrayList<String>();
    String originSOPRef = "'self'";
    String originAllRef = "*";
 
    cspPolicies.add("default‐src 'none'");
    // cspPolicies.add("script‐src " + "*" + " 'unsafe‐inline' ");
    cspPolicies.add("script‐src " + originSOPRef + " 'unsafe‐inline' ");
    // ‐‐Define loading policies for Styles (CSS)
    cspPolicies.add("style‐src " + originSOPRef);
    // ‐‐Define loading policies for Images
    cspPolicies.add("img‐src " + originSOPRef);
    // ‐‐Define loading policies for Form
    cspPolicies.add("form‐action " + originSOPRef);
 
    // ‐‐Define loading policies for Connection
    cspPolicies.add("connect‐src " + originSOPRef);
11/11/2015 Secure Coding Guidelines for Content Security Policy | GnuDeveloper.com
http://www.gnudeveloper.com/cyber_security/secure_coding_guidelines_for_content_security_policy.html 4/4
 
    // Target formating
    this.policies = cspPolicies.toString().replaceAll("([|])", "")
        .replaceAll(",", ";").trim();
  }
 
  @Override
  public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain fchain) throws IOException, ServletException {
    HttpServletRequest httpRequest = ((HttpServletRequest) request);
    HttpServletResponse httpResponse = ((HttpServletResponse) response);
 
    /* Step 2 : Add CSP policies to HTTP response */
    StringBuilder policiesBuffer = new StringBuilder(this.policies);
 
    // Add policies to all HTTP headers
    for (String header : this.cspHeaders) {
      httpResponse.setHeader(header, policiesBuffer.toString());
    }
 
    /* Step 3 : Let request continue chain filter */
    fchain.doFilter(request, response);
  }
 
  @Override
  public void destroy() {
    // TODO Auto‐generated method stub
  }
}
Source Code Download :
ContentSecurityPolicyFilter.java
CSPFilter.war
Groups:
CyberSecurity

Secure coding guidelines for content security policy

  • 1.
    11/11/2015 Secure Coding Guidelines for Content Security Policy | GnuDeveloper.com http://www.gnudeveloper.com/cyber_security/secure_coding_guidelines_for_content_security_policy.html 1/4 HomeSearch Groups About Us Contact SignUp Home > Groups > CyberSecurity Secure Coding Guidelines for Content Security Policy Submitted by vivekanandan on Wed, 11/04/2015 ­ 23:23 The CSP is the key concept for protecting the Cross­site scripting (XSS) from the browser side. Since XSS is the top most vulenerable injection attack. The content  means  the  web  page  resource  as  javascript,  images  etc..  For  browser  side  security  we  need  to  understand  the  same­origin  policy,  cross­  origin  policy (COP) Why we need Content Security Policy: The Server needs to clearly mention the trusted origin for the resources like javascript,images etc.. so that client will take the action accordingly. Since The browser(client) and server are disconnected the server needs to mention the security policy for each page as part of HTTP header response Secure coding guidelines for CSP: 1. Always use JavaScript in separate js file. 2. Always bind HTML element with Event Handlers so that clear separation of HTML & JavaScript can be maintained. js framework like jQuery supports this feature . example for button click event in jquery : $("#btnClick").click(function() { } 3. If legacy project already had inline JavaScript add script nonce with it, but consider unsafe and reduce ASAP. 4. Avoid use eval statement in JavaScript code. 5. Avoid using setTimeout methods since it internally the eval statement. 6. Always have separate css file means don't use inline styles. Same­ origin policy (SOP): The browser will decide the same ­origin policy based on 3 parts of URL http://www.gnudeveloper.com:80/ Protocol: HTTP Domain name: www.gnudeveloper.com Port number: 80 Based on the URL information browser will consider the web page belongs to same­ origin policy or cross­origin policy Self: it represents same­origin policy    script­src 'self'  ; Cross­ origin policy (COP) or Cross­Origin Resource Sharing (CORS): It represents content belongs to different origin, opposed to same­origin policy. By default Firefox browser won't allow cross­origin policy for the web pages since it will create chance for Cross­site scripting (XSS). To allow all host specify as asterisk character *    script­src *  ;  The CSP Violation message can be viewed in the console. self DIRECTIVE value  enforce the source domain(gnudeveloper.com) and image src,script src should be same hence error message as below    Content Security Policy: The page's settings blocked the loading of a resource at infotree.in/themes/bartik/logo.png ("img‐src gnudeveloper.com"). Content Security Policy: The page's settings blocked the loading of a resource at code.jquery.com/jquery‐1.9.1.js ("script‐src gnudeveloper.com 'unsa Since eval‐script is missing http header response, browser blocked the eval method  call to eval() or related function blocked by CSP Note: setTimeout will be allowed since it is indirect eval statement
  • 2.
  • 3.
    11/11/2015 Secure Coding Guidelines for Content Security Policy | GnuDeveloper.com http://www.gnudeveloper.com/cyber_security/secure_coding_guidelines_for_content_security_policy.html 3/4 Output: HTTP header Response  HTTP/1.1 304 Not Modified   Server: Apache‐Coyote/1.1   Content‐Security‐Policy: default‐src 'none'; script‐src 'self' 'unsafe‐inline' ; options   inline‐script eval‐script; xhr‐src 'self'; object‐src 'self'; style‐src   'self'; img‐src 'self'; form‐action 'self'; connect‐src 'self';   frame‐src 'self';sandbox;frame‐ancestors 'self'   ETag: W/"268381‐1446607260430"   Date: Sun, 08 Nov 2015 01:32:04 GMT ContentSecurityPolicyFilter.java import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;   @WebFilter("/*") public class ContentSecurityPolicyFilter implements Filter {     /** Filter configuration */   @SuppressWarnings("unused")   private FilterConfig filterConfig = null;     /** List CSP HTTP Headers */   private List<String> cspHeaders = new ArrayList<String>();     /** Collection of CSP polcies that will be applied */   private String policies = null;     /**    * Used to prepare (one time for all) set of CSP policies that will be    * applied on each HTTP response.    *     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)    */   @Override   public void init(FilterConfig fConfig) throws ServletException {     // Get filter configuration     this.filterConfig = fConfig;       // Define list of CSP HTTP Headers     this.cspHeaders.add("Content‐Security‐Policy");     this.cspHeaders.add("X‐Content‐Security‐Policy");     this.cspHeaders.add("X‐WebKit‐CSP");         // Define CSP policies     // Loading policies for Frame and Sandboxing will be dynamically defined     // : We need to know if context use Frame     List<String> cspPolicies = new ArrayList<String>();     String originSOPRef = "'self'";     String originAllRef = "*";       cspPolicies.add("default‐src 'none'");     // cspPolicies.add("script‐src " + "*" + " 'unsafe‐inline' ");     cspPolicies.add("script‐src " + originSOPRef + " 'unsafe‐inline' ");     // ‐‐Define loading policies for Styles (CSS)     cspPolicies.add("style‐src " + originSOPRef);     // ‐‐Define loading policies for Images     cspPolicies.add("img‐src " + originSOPRef);     // ‐‐Define loading policies for Form     cspPolicies.add("form‐action " + originSOPRef);       // ‐‐Define loading policies for Connection     cspPolicies.add("connect‐src " + originSOPRef);
  • 4.
    11/11/2015 Secure Coding Guidelines for Content Security Policy | GnuDeveloper.com http://www.gnudeveloper.com/cyber_security/secure_coding_guidelines_for_content_security_policy.html 4/4      // Target formating     this.policies = cspPolicies.toString().replaceAll("([|])", "")         .replaceAll(",", ";").trim();   }     @Override   public void doFilter(ServletRequest request, ServletResponse response,       FilterChain fchain) throws IOException, ServletException {     HttpServletRequest httpRequest = ((HttpServletRequest) request);     HttpServletResponse httpResponse = ((HttpServletResponse) response);       /* Step 2 : Add CSP policies to HTTP response */     StringBuilder policiesBuffer = new StringBuilder(this.policies);       // Add policies to all HTTP headers     for (String header : this.cspHeaders) {       httpResponse.setHeader(header, policiesBuffer.toString());     }       /* Step 3 : Let request continue chain filter */     fchain.doFilter(request, response);   }     @Override   public void destroy() {     // TODO Auto‐generated method stub   } } Source Code Download : ContentSecurityPolicyFilter.java CSPFilter.war Groups: CyberSecurity