Posts

SQLi – PHP Secure Coding

Method #1
Escaping special characters in a string for use in an SQL statement

<?php
  $name = mysql_real_escape_string( $_POST[‘name’] );
  $pwd  = mysql_real_escape_string( $_POST[‘pwd’] );
 
  $str_sql = "SELECT * from `tbl_users` WHERE " .
             "usr_name=’" . $name . "’ AND " .
             "usr_pwd=’" . $pwd . "’";
 
  $result = mysql_query( $str_sql ) or die ( mysql_error() );
?>

Method #2
Using prepared statements and parameterized queries:

Case #1
While connecting to database

<?php
  $pdo = new PDO('mysql:dbname=db;host=127.0.0.1;charset=utf8', 'username', 'password');

  $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>

Case #2
While retrieving data

<?php
  $stmt = $pdo->prepare('SELECT * FROM tables WHERE name = :name');
  $stmt->execute(array(':name' => $name));
  foreach ($stmt as $row) {
      echo $row[0];
  }
?>

Case #3
While inserting

<?php
   $preparedStatement = $pdo->prepare('INSERT INTO table (column) VALUES (:column)');
   $preparedStatement->execute(array(':column' => $unsafeValue));
?>

This technique can also be applied in case of update and delete.

References
http://php.net/manual/en/security.database.sql-injection.php
http://php.net/manual/en/function.mysql-real-escape-string.php
http://php.net/manual/en/book.pdo.php

SQLi – ASP.NET Secure Coding

Using Paramaterized Query/Prepared Statement

The use of parameterized stored procedures is an effective mechanism to avoid most forms of SQL Injection. Parameterized queries do proper substitution of arguments prior to running the SQL query. They completely remove the possibility of “dirty” input changing the meaning of your query.

// Build the query statement using parameterized query.

string sql = "SELECT UserId FROM Users WHERE " + "UserName = @UserName AND Password =@Password";
using (SqlCommand cmd = new SqlCommand(sql))
{   
    // Create the parameter objects as specific as possible.  
    cmd.Parameters.Add("@UserName", System.Data.SqlDbType.NVarChar, 50);   
    cmd.Parameters.Add("@Password", System.Data.SqlDbType.NVarChar, 25);
   
    // Add the parameter values.  Validation should have already happened. 
    cmd.Parameters["@UserName"].Value = UserName; 
    cmd.Parameters["@Password"].Value = Password;  
    cmd.Connection = connnection; 
    try
    {    
       cmd.Connection.Open();    
       var userId = cmd.ExecuteScalar();   
    }  
    catch (SqlException sx)   
    {    
       // Handle exceptions before moving on. 
    }
}

References
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
http://msdn.microsoft.com/en-us/library/ff648339.aspx

SQLi – JAVA Secure Coding

Use PreparedStatement instead of dynamic queries.

All data access techniques provide some means for escaping SQL meta-characters automatically.
Variables passed as arguments to prepared statements will automatically be escaped by the JDBC driver.

String selectStatement = "SELECT * FROM User WHERE userId = ? ";
PreparedStatement prepStmt = con.prepareStatement(selectStatement);
prepStmt.setString(1, userId);
ResultSet rs = prepStmt.executeQuery();

References
https://www.owasp.org/index.php/Preventing_SQL_Injection_in_Java
https://www.java.net/node/678819
http://download.oracle.com/oll/tutorials/SQLInjection/index.htm

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