Code Best Practices

reference

Good approach when handle the upload file.

  • Handle DDoS
using(var stream = file.FileContent)
{
    DoProcessing(stream);
}

Bad approach, when using FileBytes, it will read all the file content into memory, which is possible for Denial of Service.

DoProcessing(file.FileBytes) // Bad approach sample
  • Validate the upload extension name, to prevent the malicious file attack
<validationsettings allowedfileextensions=".jpg,.png"></validationsettings>


Secure the way when displaying binary images

  • Handle the ContentType properly
Response.ContentType = "image/jpeg"; #specify content-type to prevent the vulnerability
Response.Headers.Add("X-Content-Type-Options", "nosniff");

Typciall the jpg xss attack: jpg xss attack

Prevent Open Redirect

  • IsLocalUrl Validation
private IActionResult RedirectToLocal(string returnUrl)
{
    if (Url.IsLocalUrl(returnUrl))
    {
        return Redirect(returnUrl);
    }
    else
    {
        return RedirectToAction(nameof(HomeController.Index), "Home");
    }
}
  • LocalRedirect
public IActionResult SomeAction(string redirectUrl)
{
    return LocalRedirect(redirectUrl);
}


Enable CSRF token

ASP.net sample:

[ValidateAntiForgeryToken]


Path Manipulation and Path.Combine()

public static bytes[] getFile(String filename) {
  String imageDir = "C:\\Image\\";
  filepath = Path.Combine(imageDir, filename);

  return File.ReadAllBytes(filepath);
}

The security issue of the above code is using Path.Combine() to generate the path string. However, if the second parameter filename is using absolute path, then the first parameter imageDir will be ignored
From MS Doc it says:

If path2 does not include a root (for example, if path2 does not start with a separator character or a drive specification), the result is a concatenation of the two paths, with an intervening separator character. If path2 includes a root, path2 is returned.

The parameters are not parsed if they have white space. Therefore, if path2 includes white space (for example, “ \file.txt “), the Combine method appends path2 to path1 instead of returning only path2.

Preventation: Using Path.GetFileName() to get the “base name” of the parameter

public static bytes[] GetFile(String filename) {

  if (string.IsNullOrEmpty(filename) || Path.GetFileName(filename) != filename)
  {
    throw new ArgumentNullException("error");
  }

  String filepath = Path.Combine("\\FILESHARE\images", filename);
  return File.ReadAllBytes(filepath);
}