Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

HTML Encode and Decode in web application

WebUtility.HtmlEncode and WebUtility.HtmlDecode

Introduction

Previously I shared around six articles on security , in this article I am going to explain what is html encoding and how It prevent from xss attacks in web application and also I a am going to explain html decoding with sample example.

HtmlEncode

WebUtility.HtmlEncode Method converts a string to an HTML-encoded string.

The HTMLEncode method applies HTML encoding to a specified string. This is useful as a quick method of encoding form data and other client request data before using it in your Web application.

WebUtility.HtmlEncode converts characters as follows,

=> The apostrophe character (‘) is converted to '
=> The less-than character (<) is converted to &lt;.
=> The greater-than character (>) is converted to &gt;.
=> The ampersand character (&) is converted to &amp;.
=> The double-quote character (") is converted to &quot;.

Any ASCII code character whose code is greater-than or equal to 0x80 is converted to &#<number>, where is the ASCII character value.

HTML encode and Cross Site Scripting

What is XSS?

Cross Site Scripting (often abbreviated as XSS) when attacker uses web application send or injects malicious code like browser script, to different user. This malicious script executes and access user resources, trusted website data, website critical information. More info… http://www.codechef4u.com/post/2015/06/29/Anti-Cross-Site-Scripting-Library

HTML encode used to prevent possible XSS attack?

Encoding data converts potentially unsafe characters to their HTML-encoded equivalent.

It prevents XSS (cross site scripting) attacks, means that if you are going to save some data In database that allow following script and you used WebUtility.HtmlEncode method to encode string in that case following actual string special characters (i.e “< “is converted to “&lt”) converted into safe plain string.

  In web environment this script will be rendered safely rather than actually executing script.

Actual Script:

<script type="text/javascript">
    function FetchSomeCriticlInfo() { /* some dangerous script code */ }
</script>

In this case, Server.HTMLEncode would encode the <, >, and " characters leaving this:

Encoded Script:

&lt;script type=&quot;text/javascript&quot;&gt;
    function FetchSomeCriticlInfo() { /* some dangerous script code*/ }
&lt;/script&gt;

 

 

This script, if rendered in the browser will look like this

 

<script type="text/javascript"> function FetchSomeCriticlInfo() { /* some dangerous script code */ }
</script>

 

 

HTML Decode

 

WebUtility.HtmlDecode(String) Method converts a string that has been HTML-encoded for HTTP transmission into a decoded string.

 

HtmlDecode(String, TextWriter) overloaded method converts a string that has been HTML-encoded into a decoded string, and sends the decoded string to a TextWriter output stream.

 

Example

Follwing address is encoded using WebUtility.HtmlEncode Method

Encoded Address:

Bill Address
Nagnath Kendre
Kendre&apos;s Villa,Kendrewadi
Mahrashtra,India.

 

If I want to use this address into email or display to user I require to decode this &apos; string to actual character.

 

Following Address is Decoded using WebUtility.HtmlDecode Method

Decoded Address:

Bill Address
Nagnath Kendre
Kendres Villa,Kendrewadi
Mahrashtra,India.

 

धन्यवाद मित्रानो !! Thanks  friends !!

Review SQL queries for security vulnerabilities

Introduction:

After lot of code quality related issues and bad code quality blame game our project team started
New magical process called peer programming.
In this game you are more happy to find mistakes from collogue, and according to me that is perfect definition of magic process called peer programming.

In peer programming I found following code with attribute SuppressMessage and detail as Review SQL queries for security vulnerabilities.

 

[SuppressMessage("Microsoft.Security""CA2100:Review SQL queries for security vulnerabilities")]
        private static bool UpdateProducts(string procedureName, Product product)
        {
            var oConn = new SqlConnection(conString);
          
            oConn.Open();
            var oCmdProducts = new SqlCommand(procedureName, oConn);
            oCmdProducts.CommandType = CommandType.StoredProcedure;
            oCmdProducts.Parameters.Add(new SqlParameter("@ProductId"SqlDbType.Int)).Value =
               product.ProductId;
            oCmdProducts.Parameters.Add(new SqlParameter("@Pice"SqlDbType.Int)).Value =
            product.Price;
            if (oCmdProducts.ExecuteNonQuery() > 0)
            {
                return true// success
            }
            else
            {
                return false//fail
            }
        }
 
I started looking what is meaning of that attribute on MSDN I found these are some warning rules provided by Microsoft Managed Code Analysis tool.

What is Managed Code Analysis tool?

The Managed Code Analysis tool provides warnings that indicate rule violations in managed code libraries. The warnings are organized into rule areas such as design, localization, performance, and security. Each warning signifies a violation of a Managed Code Analysis rule.

Rule CA2100: Review SQL queries for security vulnerabilities

This rule assumes that the string argument contains user input. A SQL command string that is built from user input is vulnerable to SQL injection attacks. In a SQL injection attack, a malicious user supplies input that alters the design of a query in an attempt to damage or gain unauthorized access to the underlying database. Typical techniques include injection of a single quotation mark or apostrophe, which is the SQL literal string delimiter; two dashes, which signifies a SQL comment; and a semicolon, which indicates that a new command follows.

Violations of Rule:

Notice that this rule is violated when the ToString method of a type is used explicitly or implicitly to construct the query string.

Example:

ToString():

string query = "SELECT * FROM Products where CategoryId in (Select id from Categories where
CategoryName="+CategoryName.ToString()+")";

 

In this Example the rule is violated because a malicious user can override the ToString() method.

 

Implicit string conversion:

var TopCount = 10; string query = String.Format("SELECT TOP{0}
Productname,price FROM Products", TopCount);

 

In this example the rule is violated when ToString is used implicitly.

How to Fix Violations

To fix these violations use a parameterized query.

Other some suggestion are,

=> Use a stored procedure.
=> Use a parameterized command string.
=> Validate the user input for both type and content before you build the command string.

Safe code and Unsafe Code Example:

Safe Code example:

  public static List<Product> SafeProductsDeatilCall(string CategoryName)
      {
          var products = new List<Product>();
          var con = new SqlConnection(conString);
          try
          {
              con.Open();
              SqlCommand cmd = new SqlCommand("GetProductDetails", con);
              cmd.Parameters.Add("@CategoryName"SqlDbType.NChar).Value = CategoryName;
              string query = "SELECT * FROM Products where CategoryId in (Select id from Categories where CategoryName=@CategoryName";
              cmd.CommandText = query;
              SqlDataReader dr = cmd.ExecuteReader();
              while (dr.Read())
              {
                  Product p = new Product();
                  p.ProductId = Convert.ToInt32(dr["ProductID"]);
                  p.ProductName = dr["ProductName"].ToString();
                  p.Price = Convert.ToDecimal(dr["Price"].ToString());
                  p.CategoryId = (dr["CategoryId"] != DBNull.Value) ? Convert.ToInt32(dr["CategoryId"]) : 0;
                  p.ImageUrl = (dr["Imageurl"] != DBNull.Value) ? dr["Imageurl"].ToString() : string.Empty;
                  products.Add(p);
              }
              return products;
          }
          catch (Exception ex)
          {
              //log ex
              return null;
          }
          finally
          {
              con.Close();
          }
      }

 

     Unsafe Code Example:

 

      public static List<Product> UnsafeProductsDeatilCall(string CategoryName )
      {
          var products = new List<Product>();
          var con = new SqlConnection(conString);
          try
          {
              con.Open();
              SqlCommand cmd = new SqlCommand("GetProductDetails", con);
              string query = "SELECT * FROM Products where CategoryId in (Select id from Categories where CategoryName=" + CategoryName.ToString() + ")";
              cmd.CommandText = query;
              SqlDataReader dr = cmd.ExecuteReader();
              while (dr.Read())
              {
                  Product p = new Product();
                  p.ProductId = Convert.ToInt32(dr["ProductID"]);
                  p.ProductName = dr["ProductName"].ToString();
                  p.Price = Convert.ToDecimal(dr["Price"].ToString());
                  p.CategoryId = (dr["CategoryId"] != DBNull.Value) ? Convert.ToInt32(dr["CategoryId"]) : 0;
                  p.ImageUrl = (dr["Imageurl"] != DBNull.Value) ? dr["Imageurl"].ToString() : string.Empty;
                  products.Add(p);
              }
              return products;
          }
          catch (Exception ex)
          {
              //log ex
              return null;
          }
          finally
          {
              con.Close();
          }
      }

 Conclusion:

Consider Managed Code Analysis tool security rule in database coding, better use stored procedure.
If you are using inline query use parameterized sql query suggested by code analysis tool. 

 reference:

https://msdn.microsoft.com/en-us/library/ms182310.aspx 

Security Vulnerabilities in Web.config or Security misconfigurations

Security misconfigurations OR Security Vulnerabilities in Web.config

Single change in machine.config file could affect every website on network or single change in web.config create security risk for asp.net web application.

Note :This article is written considering all asp.net environments(Asp.net 1+), may be some new security features added in current asp.net version to avoid this security mistake and those are missing in this article. we will update those if found any ,we suggest users please add new configuration measures in your comment. 
This article lists possible mistakes programmer could avoid while creating web application.

1.  Missing Custom Error Handling:

As programmer always remember to enable custom error pages in order to prevent attackers from mining information from the framework's built-in error responses.

Typical misconfigurations:

<customErrors mode="Off" />
This is improper error handling; system exception could provide useful information like database information, file information. Error messages provide quite useful information to the attacker that can be used to launch further attacks such as code Injection,SQL Injection,XSS attacks.
<customErrors mode="RemoteOnly" />
Custom error message mode for remote user only. No defaultRedirect error page specified. The local user on the web server will see a detailed stack trace. For remote users, an ASP.NET error message with the server customError configuration setting and the platform version will be returned.

Secure error handling:

 
<customErrors mode="RemoteOnly" />
  <customErrors mode="On" defaultRedirect="YourErrorPage.htm" />
Or such as
    <customErrors mode="RemoteOnly" defaultRedirect="~/error.aspx" redirectMode="ResponseRewrite">
      <error statusCode="404" redirect="~/error404.aspx" />
    </customErrors>

This will display only generic message on specific custom error page.

2.  Password in configuration file:

Using hardcoded user credentials in configuration file is dangerous and bad practice, with such practice you are providing blindly hacker security hole in your application.

Clear-text passwords in the configuration files are subject to exposure in a variety of ways, including people getting access to the file, the file being served directly to a user due to a server error, a file download flaw, access to a backup copy, or some other exposure.

Typical misconfiguration:

    <authentication mode="Forms">
      <forms>
        <credentials>
          <user name="nagnath" password="test@1224"/>
          <user name="shourya" password="fgdf25"/>
        </credentials>
      </forms>
    </authentication>


Secure use:

<authentication mode="Forms">
      <forms timeout="129600" name="myWebApp" protection="All" slidingExpiration="false" loginUrl="~/Account/login.aspx" cookieless="UseCookies" />
    </authentication>


3.  Sliding Expiration:

The slidingExpiration setting is a security measure used to reduce risk in case the authentication token is stolen.Hacker or attacker use stolen authentication ,but he don’t know user credentials.

Typical misconfiguration:

<authentication mode="Forms">
 <forms name="myWebApp" protection="All" slidingExpiration="true" loginUrl="~/Account/login.aspx" cookieless="UseCookies" />
 </authentication>


When sliding expiration is enabled, as long as an attacker makes at least one request to the system every 15 minutes (or half of the timeout interval), the session will remain open indefinitely. This gives attackers more opportunities to steal information and cause other mischief.

Secure use:

<authentication mode="Forms">
      <forms name="myWebApp" protection="All" slidingExpiration="false" loginUrl="~/Account/login.aspx" cookieless="UseCookies"/>
    </authentication>
when slidingExpiration setting is disabled, they can't log back in as the legitimate user, so the stolen authentication token is now useless and the threat is mitigated. When set to false, the specified timeout interval becomes a fixed period of time from the initial login, rather than a period of inactivity

4.  Debugging Enabled/ Disabled:

Leaving debugging enabled is not good practice, debugging messages help attackers learn about the system and plan a form of attack.

The debug attribute of the <compilation> tag defines whether compiled binaries should include debugging information. Symbols (.pdb files) tell the debugger how to find the original source files for a binary, and how to map breakpoints in code to lines in those source files.

 Leaving debugging enabled is dangerous because you are providing inside information to end users who shouldn't have access to it, and who may use it to attack your applications

Typical misconfiguration:

<configuration> 
<system.web>
<compilation debug="true" targetFramework="4.5">
….
</compilation>
</system.web>
</configuration>

Secure use:

<configuration> 
<system.web>
<compilation debug="false " targetFramework="4.5">
….
</compilation>
</system.web>
</configuration>

5.  Cookieless Session State Enabled:

Asp.net web application allows storing the session token in the page URLs rather than a cookie.

Example: 

http://mySecuritrytestApp.com /default.aspx  to
http://mySecuritrytestApp.com /(912345678ABCDEFG)/default.aspx. In this case, 912345678ABCDEFG represents the current user's session token.
Multiple users browsing site sate time would receive completely different session resulting deferent URL.

Typical misconfiguration:

<configuration>
        <system.Web>
          <sessionState cookieless="UseUri"/>
   </system.Web>
</configuration>


Allowing session storing in the page URLs is dangerous because side effect of making those applications much more vulnerable to session hijacking attacks.

Secure use:

<configuration>
        <system.Web>
          <sessionState cookieless="UseCookies"/>
  </system.Web>
</configuration>
Best prevention from these session hijacking attacks is to force your Web application to use cookies to store the session token. This is accomplished by setting the cookieless attribute of the <sessionState> element to UseCookies or false.

 

6. Tracing Enabled:

 The tracing feature of ASP.NET is useful tool for developers and programmers to debug and profile your applications.

Unfortunately tracing enabled in production environment is dangerous because it is also one of the most useful tools that a hacker can use to attack your applications.

Typical misconfiguration:

<configuration>
        <system.Web>
          <trace enabled="true" localOnly="false"/>
  </system.Web>
</configuration>
When tracing is enabled simply browsing trace.axd hacker can view an incredibly detailed list of recent requests to the application

Secure use:

<configuration>
        <system.Web>
          <trace enabled="false" localOnly="true"/>
  </system.Web>
</configuration>
Best prevention from obtaining trace data is to disable the trace viewer completely by setting the enabled attribute of the <trace> element to false.

7.  Cookies Accessible Through Client-Side Script

When httpOnlyCookies disabled in that case cookies are accessible in client side script like JavaScript, VbScript. Hacker initiates a cross-site scripting (XSS) attack by attempting to insert his script code into the Web page.

Typical hacker example:

on blogging site users provide feedback, comments, but an attacker, rather than posting about the current topic, will instead post a message such as <script>alert(document.cookie);</script>.

The comments now include the attacker's script code in its page code—and the browser then interprets and executes it for future site visitors. Usually attackers use such script code to try to obtain the user's authentication token (usually stored in a cookie), which they could then use to impersonate the user. When cookies are marked with the HttpOnly property, their values are hidden from the client, so this attack will fail.

Typical misconfiguration:

 <configuration>
   <system.Web>
      <httpCookies httpOnlyCookies="false">
</system.Web>
</configuration>


Secure Use:

<configuration>
   <system.Web>
      <httpCookies httpOnlyCookies="true">
</system.Web>
</configuration>

 

8.  Cookieless Authentication Enabled

Like cookieless sessionstate  allowing Cookieless Authentication is dangerous because it leads to session hijacking. When a session or authentication token appears in the request URL rather than in a secure cookie, hacker can easily identify user.

Typical misconfiguration:

<configuration>
    <system.Web>
      <authentication mode="Forms">
        <forms cookieless="UseUri"/>
      </authentication>
    </system.Web>
    </configuration>


Secure Use:

<configuration>
    <system.Web>
      <authentication mode="Forms">
        <forms cookieless="UseCookies"/>
      </authentication>
    </system.Web>
    </configuration>


9.  SSL For authentication:

Web application uses the Secure Sockets Layer (SSL) protocol to encrypt data passed between the Web server and the client. If you are using SSL hacker not able to attack your data passed between from server and the client.

Typical misconfiguration:

  <configuration>
    <system.Web>
      <authentication mode="Forms">
        <forms requireSSL="false"/>
      </authentication>
    </system.Web>
    </configuration>


Secure use:

  <configuration>
    <system.Web>
      <authentication mode="Forms">
        <forms requireSSL="true "/>
      </authentication>
    </system.Web>
    </configuration>


Using SSL means that attackers using network sniffers will not be able to interpret the exchanged data. Rather than seeing plaintext requests and responses.
We recommend using HTTP Strict Transport Security(HSTS) for enforcing all pages with HTTPS protocol that uses Secure Sockets Layer (SSL). For more …http://codechef4u.com/post/2015/06/10/HSTS