knowledgebase sub-category

Anti CSRF Token – PHP

 

1. Add a unique token to the hidden field of user form on submit and store it on the session. Add the following codes to achieve this.

  <?php
     $token = md5(uniqid(rand(), TRUE));
     $_SESSION[“token_$token”] = time();
  ?>
  <form action="login.php" method="post">
    <input type="hidden" name="token" value="<?php echo $token; ?>" />
    <p>
     Username: <input type="text" name="username" /><br />
     Password: <input type="text" name="password" /><br />
     <input type="submit" value="Login" />
    </p>
  </form>

2. Before processing, validate the token on serverside.

  <?php
    if (isset($_SESSION['token_' . $_POST['token']])
    {
       // prevent use the token twice
       unset($_SESSION['token_' . $_POST['token']]);

      /* Valid Token */
    }
  ?> 

3. The validity of token can also be limited

  <?php
     $token_age = time() - $_SESSION['token_time'];
     if ($token_age <= 600)
     {
        /* Less than ten minutes has passed. */
     }
  ?>

References
https://www.owasp.org/index.php/PHP_CSRF_Guard

Anti CSRF Token – JAVA

Using OWASP ESAPI

  1. Download OWASP ESAPI Library from the ESAPI project page and add it to the library of the project.
  2. Generate a new CSRF token and add it to user login and store user in HTTP session.
  public String resetCSRFToken() {
    csrfToken = ESAPI.randomizer().getRandomString(8,DefaultEncoder.CHAR_ALPHANUMERICS);
    return csrfToken;
  }

3. Add the token as a parameter / hidden field, on any forms or URLs that should be protected.

   final static String CSRF_TOKEN_NAME = "cftoken";
   public String addCSRFToken(String href) {
	User user = ESAPI.authenticator().getCurrentUser();
	String token = CSRF_TOKEN_NAME + "=" + user.getCSRFToken();
	return href.indexOf( '?') != -1 ? href + "&" + token : href + "?" + token;
   }

   public String getCSRFToken() {
	User user = ESAPI.authenticator().getCurrentUser();
	if (user == null) return null;
	return user.getCSRFToken();
   }

4. On the server-side, check that the submitted token matches the token from the user object in the session.

   public void verifyCSRFToken(HttpServletRequest request) throws IntrusionException {
	User user = ESAPI.authenticator().getCurrentUser();
	if( request.getAttribute(user.getCSRFToken()) != null ) {
		return;
	}
	String token = request.getParameter(CSRF_TOKEN_NAME);
	if ( !user.getCSRFToken().equals( token ) ) {
		throw new IntrusionException("Authentication failed", "Possibly forged HTTP request without proper CSRF token detected");

	}

  }

References
https://www.owasp.org/index.php/Category:OWASP_Enterprise_Security_API
https://www.owasp.org/index.php/Category:OWASP_CSRFGuard_Project
http://code.google.com/p/owasp-esapi-java/downloads/list

Anti CSRF Token – ASP.NET

  1. Download AntiCSRF from the CSRF module for ASP.NET.
  2. In Project place Idunno.AntiCsrf.dll in Bin folder.
  3. Add a reference to the module into your web.config

 For IIS6/IIS7 in Classic ASP.NET mode:

  <system.web>
          
        <httpModules>            
            <add name="AntiCSRF" type="Idunno.AntiCsrf.AntiCsrfModule, Idunno.AntiCsrf"/>
        </httpModules>
                
  </system.web>

For IIS7 in integrated pipeline mode:

  <system.webmodules>
                  
       <modules>
          <add name="AntiCSRF" type="Idunno.AntiCsrf.AntiCsrfModule, Idunno.AntiCsrf"/>
       </modules>
                  
  </system.webmodules>

4. Add the following settings to web.config

  <configuration>
   
    <configSections>
        
        <section name="csrfSettings"  type="Idunno.AntiCsrf.Configuration.CsrfSettings, Idunno.AntiCsrf" />   
        
    </configSections>
    <csrfSettings cookieName="__CSRFCOOKIE" formFieldName="__CSRFTOKEN" detectionResult="RaiseException" errorPage="" />
  
 </configuration>  

5. Add the following codes in Page_Load Event.

   protected void Page_Load(object sender, EventArgs e)
   {
    string page_name = System.IO.Path.GetFileName(System.
    Web.HttpContext.Current.Request.Url.AbsolutePath);
    string page_token = page_name + "_ID";
    Session[page_token] = CSRF_Token; 
    HiddenField1.value = CSRF_Token;
   }

6. Add the following codes in Any Event.

   protected void Button1_Click(object sender, EventArgs e)
   {
    string Page_Token =   System.IO.Path.GetFileName(System.Web.HttpContext.Current.Request.Url.AbsolutePath)+"_ID";
  
       if (HiddenField1.Value.ToString() != Session[Page_Token].ToString())
       {
          Session.Abandon();
          Session.Clear();
          Response.Redirect("default.aspx");
       }
   }

References

http://anticsrf.codeplex.com/
http://www.asp.net/web-api/overview/security/preventing-cross-site-request-forgery-(csrf)-attacks
https://www.owasp.org/index.php/.Net_CSRF_Guard

XSS – PHP Secure Coding

Case #1

HTML escape before inserting untrusted data into HTML element content.

<?php
  $str=$_POST["data"];
  $str_safe=htmlspecialchars($str, ENT_QUOTES);
?>
<h1><?php echo $str_safe; ?></h1>

Case #2

JavaScript escape before inserting untrusted data into JavaScript data values.

<?php
  $str=$_POST["data"];
  $safe=strip_tags($str);
?>
<script>alert("<?php echo $safe; ?>");</script>

 

References
http://php.net/manual/en/function.htmlspecialchars.php
http://php.net/manual/en/function.htmlentities.php
http://in3.php.net/strip_tags

XSS – Java Secure Coding

Using Security Encoding Library

  1. Download ESAPI.jar from the ESAPI Project page, and add it to library of the project.
  2. Import the package in jsp page: <%@ page language=”java” import=”org.owasp.esapi.*” %>
  3. Add code according to the different cases:

Case #1

HTML escape before inserting untrusted data into HTML element content.


<%
String safe = ESAPI.encoder().encodeForHTML( request.getParameter( "input" ) );
%>
<div><%= safe %></div>

Case #2

Attribute escape before inserting untrusted data into HTML common attributes.


<%
String safe = ESAPI.encoder().encodeForHTMLAttribute( request.getParameter( "input" ) );
%>
<div attr='<%= safe %>'></div>

Case #3

JavaScript escape before inserting untrusted data into JavaScript data values.


<%
String safe = ESAPI.encoder().encodeForJavaScript( request.getParameter( "input" ) );
%>
<script>alert('<%= safe %>')</script>
<input type=’button’ onclick=”alert('<%= safe %>')”>

Case #4
URL escape before inserting untrusted data into HTML URL parameter values.


<%
String safe = ESAPI.encoder().encodeForURL( request.getParameter( "input" ) );
%>
<a href='http://www.victim-site.com?test=<%= safe %>'>link</a >

References 
http://owasp-esapi-java.googlecode.com/svn/trunk_doc/latest/org/owasp/es…
http://code.google.com/p/owasp-esapi-java/downloads/list

XSS – ASP.NET Secure Coding

Using Microsoft Anti XSS Library

  1. Download the AntiXss Library(AntiXSSLibrary.dll) from the Microsoft Web Protection Library.
  2. Right click the References node of the project to add a reference to the assembly.
  3. On particular cases :

Case #1

HTML escape before inserting untrusted data into HTML element content

string safedata = Microsoft.Security.Application.AntiXss.HtmlEncode( Request.QueryString[ "input" ] );
Response.Write(“<div>” + safedata + “</div>”);

Case #2

Attribute escape before inserting untrusted data into HTML common attributes

string safedata = Microsoft.Security.Application.AntiXss.HtmlAttributeEncode( Request.QueryString[ "input" ] );
Response.Write(‘<div name=”’ + safedata + ‘“>’);

Case #3

JavaScript escape before inserting untrusted data into HTML JavaScript data values

string safedata = Microsoft.Security.Application.AntiXss.JavaScriptEncode( Request.QueryString[ "input" ] );
Response.Write(“<script>alert(‘“+safedata+”’);</script>”);

References
http://msdn.microsoft.com/en-us/library/ff649310.aspx
http://msdn.microsoft.com/en-us/library/aa973813.aspx
http://wpl.codeplex.com/releases/view/80289