Monday, May 14, 2012

Best Practice fix issues from MSOCAF checking – Part 3

Case 7: Information disclosure through exception

When you are building a web part and catch the exception to show the detail error on web part UI. However, there is no trouble if that exception is showed without customzation, unless you will get the error “Information disclosure through exception”. See example:

Exception without customization as safe security:

     //TODO: your code here
catch (Exception ex)
     lblError.Text  = ex.Message;

Exception with customization:

   //TODO: your code here
catch(Exception ex)
   lblError.Text = "Error: <b>" + ex.Message + "</b>";

The second example will show error if we do check by MSOCAF because the error message is not encrypted and make it be weakness security. 

To fix this issuse, just encrypt the message before assign to control. Use AntiXSS or HttpUtility.JavaScriptEncode.

Case 8: File canonicalization

In generally, when we work on File System we forget the validation of file name or file path. We process the data based on the default string of file. In many case, SharePoint and Windows System is a little different acceptable formatting file name/path. To make sure the input file name is validated, checking file name before pass it to procedure or function.

See example:

for (int i = 0; i < bn.Count; i++)
    string fileName = bn[i].FileName;
    FileInfo f = new FileInfo(fileName);
    SPWeb web = item.Web;
    SPFile file = folder.Files.Add(f.Name, buffer, true);
    item = file.Item;

Fix this issue:

   1:  for (int i = 0; i < bn.Count; i++)
   2:  {
   3:     //...  
   4:      string fileName = Path.GetFileName(bn[i].FileName);
   5:      if(fileName != string.Empty)
   6:      {
   7:          FileInfo f = new FileInfo(fileName);
   8:          //....
   9:          SPWeb web = item.Web;
  10:          //....
  11:          SPFile file = folder.Files.Add(f.Name, buffer, true);
  12:          item = file.Item;
  13:      }
  14:   }

The method Path.GetFileName will check there is any invalid character of the path is existed.

Case 9: SQL Injection

The data was enterred by user is always checked/validated before pass it into the routines. Especially the data will be sent to SQL command and execute under code behide. Thes issue is very common and easy to fix.

To resolve this issue, just use the parameter instead of concatenate directly in the string. Look example:

   1:  sqlCommand.CommandText = "SELECT * FROM tb_cus WHERE cusname='" + cusName + "'";
   2:  SqlDataReader reader = sqlCommand.ExecuteReader();

The code fixed:

   1:  sqlCommand.CommandText = "SELECT * FROM tb_cus WHERE cusname= @cusName";  
   2:  sqlCommand.Parameters.Clear();
   3:  sqlCommand.Parameters.AddWithValue("cusName", cusName);
   5:  SqlDataReader reader = sqlCommand.ExecuteReader();

No comments: