Top Ten способов предотвращения веб-уязвимостей по версии OWASP

Содержание

Слайд 2

OWASP Top Ten Proactive Controls – v2

OWASP Top Ten Proactive Controls – v2

Слайд 3

C1: Проверять всю безопасность рано и часто

C1: Проверять всю безопасность рано и часто

Слайд 5

Проверять безопасность рано и часто !

Security testing needs to be an integral

Проверять безопасность рано и часто ! Security testing needs to be an
part of a developer’s software engineering practice.
Consider OWASP ASVS as a guide to define security requirements and testing.
Convert scanning output into reusable Proactive Controls to avoid entire classes of problems.

Слайд 6

The DevOps challenge to security …

http://fr.slideshare.net/StephendeVries2/continuous-security-testing-with-devops

DevOps : continuous delivery pipeline.
Mature DevOps velocity

The DevOps challenge to security … http://fr.slideshare.net/StephendeVries2/continuous-security-testing-with-devops DevOps : continuous delivery pipeline.
is fast : build, test and deploy can be entirely automated.
Code is deploy to production multiple times. Examples :
Amazon : deploy every 11.6 seconds
Etsy : deploy 25+ times/day
Gov.uk : deploys 30 times/day

Agile/continuous development process can be interrupted during a sprint by security testing !

Слайд 7

Автоматическое тестирование безопасности в a Continuous Delivery Pipeline !

http://devops.com/2015/04/06/automated-security-testing-continuous-delivery-pipeline/

An easy approach to

Автоматическое тестирование безопасности в a Continuous Delivery Pipeline ! http://devops.com/2015/04/06/automated-security-testing-continuous-delivery-pipeline/ An easy
include security testing into continuous integration.
Classical/essential security tests can be automated and executed as standard unit/integration tests.
SecDevOps !

Слайд 8

BDD-Security Testing framework

http://www.continuumsecurity.net/bdd-intro.html

The BDD-Security framework может быть сконфигурирован с использованием естественного

BDD-Security Testing framework http://www.continuumsecurity.net/bdd-intro.html The BDD-Security framework может быть сконфигурирован с использованием
языка (Given, When & Then формат) для описания требований безопасности, и выполнять автоматическое сканирование и поиск основных уязвимостей.
Автоматическое (не)функциональное тестирование безопасности!
Комбинирование нескольких инструментальных средств безопасности:
OWASP ZAP, Nessus, Port Scanning и т.п.
Тесты написаны на Jbehave : «сценарий" эквивалентен тесту, "story" эквивалентна набору тестов.

Слайд 9

Среда тестирования BDD-Security

http://www.continuumsecurity.net/bdd-intro.html

Автоматическое сканирование XSS

Senario: The application should not contain Cross Site

Среда тестирования BDD-Security http://www.continuumsecurity.net/bdd-intro.html Автоматическое сканирование XSS Senario: The application should not
Scripting vulnerabilities
Meta: @id scan_xss
Given a fresh scanner with all policies disabled
And the attack strength is set to High
And the Cross-Site-Scripting policy is enabled
When the scanner is run
And false positives described in: tables/false_positives.table are removed
Then no medium or higher risk vulnerabilities should be present

Автоматическое сканирование проверок политик паролей

Senario: The application should not contain Cross Site Scripting vulnerabilities
Meta: @id auth_case
When the default user logs in with credentials from: users.table
Then the user is logged in
When the case of the password is changed
And the user logs in from a fresh login page
Then the user is no logged in

Слайд 10

BDD-Security Testing framework

http://www.continuumsecurity.net/bdd-intro.html

Тестирование управления доступом

@Restricted(users = {"admin"}, sensitiveData = "User List")
public

BDD-Security Testing framework http://www.continuumsecurity.net/bdd-intro.html Тестирование управления доступом @Restricted(users = {"admin"}, sensitiveData =
void viewUserList() {
driver.get(Config.getInstance().getBaseUrl() + "admin/list");
}

Используется аннотация @Restricted , чтобы определить, какие пользователи могут иметь доступ к каким страницам:

Слайд 11

Охватываемые риски: все!

Охватываемые риски: все!

Слайд 12

C2: Параметризованные запросы

C2: Параметризованные запросы

Слайд 13

Power of SQL Injection …

Power of SQL Injection …

Слайд 14

Сильный пароль…

✓ Upper
✓ Lower
✓ Number
✓ Special
✓ Over 16

Сильный пароль… ✓ Upper ✓ Lower ✓ Number ✓ Special ✓ Over
characters

X' or '1'='1' --

Слайд 15

Уязвимое использование

Безопасное использование

//SQL
PreparedStatement pstmt = con.prepareStatement("UPDATE EMPLOYEES SET NAME = ? WHERE

Уязвимое использование Безопасное использование //SQL PreparedStatement pstmt = con.prepareStatement("UPDATE EMPLOYEES SET NAME
ID = ?");
pstmt.setString(1, newName);
pstmt.setString(2, id);
//HQL
Query safeHQLQuery = session.createQuery("from Employees where id=:empId");
safeHQLQuery.setParameter("empId", id);

SQL Injection

String newName = request.getParameter("newName");
String id = request.getParameter("id");
String query = " UPDATE EMPLOYEES SET NAME="+ newName + " WHERE ID ="+ id;
Statement stmt = connection.createStatement();

Слайд 16

Охватываемые риски

Охватываемые риски

Слайд 17

C3: Кодирование данных перед их использованием парсером

C3: Кодирование данных перед их использованием парсером

Слайд 20

Атака 1 : кража cookie

Attack 2 : искажение веб-сайта



Анатомия XSS-атаки

Слайд 21

Проблема

Решение

OWASP Java Encoder Project
OWASP Java HTML Sanitizer Project

Microsoft Encoder and AntiXSS

Проблема Решение OWASP Java Encoder Project OWASP Java HTML Sanitizer Project Microsoft
Library
Веб-страница уязвима для XSS !

XSS-атака : проблема & решение

Слайд 22

System.Web.Security.AntiXSS
Microsoft.Security.Application. AntiXSS
Может использоваться для кодирования HTML, HTML-атрибутов, XML, CSS и JavaScript.
Native .NET

System.Web.Security.AntiXSS Microsoft.Security.Application. AntiXSS Может использоваться для кодирования HTML, HTML-атрибутов, XML, CSS и
библиотека
Сильная и хорошо написанная библиотека
For use in your User Interface code to defuse script in output

Microsoft Encoder и AntiXSS библиотека

Слайд 23

Нет необходимости в библиотеках третьих сторон или конфигурации
Данный код был разработан с

Нет необходимости в библиотеках третьих сторон или конфигурации Данный код был разработан
учетом высокой доступности и высокой производительности кодирования
Простая drop-in функциональность кодирования
Проектирование с учетом производительности
Во многом более полный API (кодирование URI и компонентов URI и т.п.).
Совместимость : Java 1.5+
Текущая версия 1.2

OWASP Java Encoder Project

https://www.owasp.org/index.php/OWASP_Java_Encoder_Project

Последнее изменение 2015-04-12 :
https://github.com/OWASP/owasp-java-encoder/

Слайд 24

OWASP Java Encoder Project

https://www.owasp.org/index.php/OWASP_Java_Encoder_Project

HTML Contexts

Encode#forHtml
Encode#forHtmlContent
Encode#forHtmlAttribute
Encode#forHtmlUnquotedAttribute

XML Contexts

Encode#forXml
Encode#forXmlContent
Encode#forXmlAttribute
Encode#forXmlComment
Encode#forCDATA

Javascript Contexts

Encode#forHtml
Encode#forHtmlContent
Encode#forHtmlAttribute
Encode#forHtmlUnquotedAttribute

CSS Contexts

Encode#forCssString
Encode#forCssUrl

URI/URL Contexts

Encode#forUri
Encode#forUriComponent

OWASP Java Encoder Project https://www.owasp.org/index.php/OWASP_Java_Encoder_Project HTML Contexts Encode#forHtml Encode#forHtmlContent Encode#forHtmlAttribute Encode#forHtmlUnquotedAttribute XML

Слайд 25

Ruby on Rails :
http://api.rubyonrails.org/classes/ERB/Util.html
PHP :
http://twig.sensiolabs.org/doc/filters/escape.html
http://framework.zend.com/manual/2.1/en/modules/zend.escaper.introduction.html
Java/Scala (Updated January 2015) :
https://www.owasp.org/index.php/OWASP_Java_Encoder_Project
.NET AntiXSS Library (v4.3

Ruby on Rails : http://api.rubyonrails.org/classes/ERB/Util.html PHP : http://twig.sensiolabs.org/doc/filters/escape.html http://framework.zend.com/manual/2.1/en/modules/zend.escaper.introduction.html Java/Scala (Updated January
NuGet released June 2, 2014) :
http://www.nuget.org/packages/AntiXss/
GO :
http://golang.org/pkg/html/template/
Reform project
https://www.owasp.org/index.php/Category:OWASP_Encoding_Project

Другие ресурсы

Слайд 26

LDAP Encoding Functions :
ESAPI and .NET AntiXSS
Command Injection Encoding Functions :
Careful here

LDAP Encoding Functions : ESAPI and .NET AntiXSS Command Injection Encoding Functions
!
ESAPI
XML Encoding Functions :
OWASP Java Encoder
Encoder comparison reference :
http://boldersecurity.github.io/encoder-comparison-reference/

Другие ресурсы

Слайд 27

Охватываемые риски

Охватываемые риски

Слайд 28

C4: – Проверка действительности всех входных данных

C4: – Проверка действительности всех входных данных

Слайд 30

HTML Sanitizer написан на Java which lets you include HTML authored by

HTML Sanitizer написан на Java which lets you include HTML authored by
third-parties in your web application while protecting against XSS.
Written with security best practices in mind, has an extensive test suite, and has undergone adversarial security review
https://code.google.com/p/owasp-java-html-sanitizer/wiki/AttackReviewGroundRules.
Простая программируемая конфигурация политики POSITIVE. Нет XML config.
Это код от Caja project that was donated by Google's AppSec team.
High performance and low memory utilization.

OWASP HTML Sanitizer Project

https://www.owasp.org/index.php/OWASP_Java_HTML_Sanitizer_Project

Слайд 31

Caja

Caja (pronounced /ˈkɑːhɑː/ kah-hah)[1] является проектом Google и реализован на JavaScript для "virtual iframes" , основанных на принципах object-capabilities.

Caja Caja (pronounced /ˈkɑːhɑː/ kah-hah)[1] является проектом Google и реализован на JavaScript
Caja использует JavaScript (а именно, ECMAScript 5 strict mode код), HTML и CSS в качестве входных данных и записывает их в безопасное подмножество HTML и CSS, плюс единственная функция JavaScript без free variables. Это означает, что единственно, когда функция может модифицировать объект, если существует ссылка на объект со страницы. Вместо предоставления прямых ссылок на объекты DOM, страница обычно предоставляет ссылки к wrappers, которые очищают HTML, прокси URLs, и предотвращают перенаправление страницы; это позволяет Caja предотвратить основные phishing атаки, предотвратить cross-site scripting атаки, и предотвратить загрузку malware. Также, так как все переписанные программы выполняются в безопасном фрейме, страница может позволить одной программе экспортировать ссылку на объект для другой программы; такое внутрифреймовое взаимодействие является просто вызовом метода.
The word "caja" is Spanish for "box" or "safe" (as in a bank), the idea being that Caja can safely contain JavaScript programs as well as being a capabilities-based JavaScript.
Caja is currently used by Google in its Orkut,[2] Google Sites,[3] and Google Apps Script[4] products; in 2008 MySpace[5][6] and Yahoo![7] and Allianz had both deployed a very early version of Caja but later abandoned it.

Слайд 32

OWASP HTML Sanitizer Project

https://www.owasp.org/index.php/OWASP_Java_HTML_Sanitizer_Project

Пример использования: validate img tags

public static final PolicyFactory

OWASP HTML Sanitizer Project https://www.owasp.org/index.php/OWASP_Java_HTML_Sanitizer_Project Пример использования: validate img tags public static
IMAGES = new HtmlPolicyBuilder()
.allowUrlProtocols("http", "https").allowElements("img")
.allowAttributes("alt", "src").onElements("img")
.allowAttributes("border", "height", "width").matching(INTEGER)
.onElements("img")
.toFactory();

Пример использования: validate link elements

public static final PolicyFactory LINKS = new HtmlPolicyBuilder()
.allowStandardUrlProtocols().allowElements("a")
.allowAttributes("href").onElements("a").requireRelNofollowOnLinks()
.toFactory();

Слайд 33

Pure JavaScript, client side HTML Sanitization with CAJA!
http://code.google.com/p/google-caja/wiki/JsHtmlSanitizer
https://code.google.com/p/google-caja/source/browse/trunk/src/com/google/caja/plugin/html-sanitizer.js
Python
https://pypi.python.org/pypi/bleach
PHP
http://htmlpurifier.org/
http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed/
.NET

Pure JavaScript, client side HTML Sanitization with CAJA! http://code.google.com/p/google-caja/wiki/JsHtmlSanitizer https://code.google.com/p/google-caja/source/browse/trunk/src/com/google/caja/plugin/html-sanitizer.js Python https://pypi.python.org/pypi/bleach
(v4.3 released June 2, 2014)
AntiXSS.getSafeHTML/getSafeHTMLFragment
http://www.nuget.org/packages/AntiXss/
https://github.com/mganss/HtmlSanitizer
Ruby on Rails
https://rubygems.org/gems/loofah
http://api.rubyonrails.org/classes/HTML.html

Другие ресурсы

Слайд 34

Проверка Upload
Проверка имени файла и размера + антивирус
Хранение загруженных файлов
Использовать только проверенные

Проверка Upload Проверка имени файла и размера + антивирус Хранение загруженных файлов
имена файлов + отдельный домен
Следует опасаться «специальных" файлов
"crossdomain.xml" или "clientaccesspolicy.xml".
Проверка загружаемых изображений
Ограничение размера изображения
Использование библиотек перезаписываемых изображений
Установить расширение хранимого изображения в действительное расширение изображения
Гарантировать определение типа содержимого в изображении
Общая проверка загружаемой информации
Гарантировать, что размер декомпрессирванного файла < максимального размера
Гарантировать, что загружаемый архив соответствует ожидаемому типу (zip, rar)
Гарантировать, что структурированные загрузки, такие как add-on, соответствуют стандарту

Загрузка файлов

Слайд 35

A1 – Injection

A2 – Broken Authentication and Session Management

A3 – Cross-Site Scripting

A1 – Injection A2 – Broken Authentication and Session Management A3 –
(XSS)

A4 – Insecure Direct Object References

A5 – Security Misconfiguration

A6 – Sensitive Data Exposure

A7 – Missing Function Level Access Control

A8 – Cross-Site Request Forgery

A9 – Using Components with Known Vulnerabilities

A10 – Unvalidated Redirects and Forwards

Охватываемые риски

Слайд 36

C5: Выполнение аутентификации и управление идентификациями

C5: Выполнение аутентификации и управление идентификациями

Слайд 38

Взлом пароля

Взлом пароля

Слайд 39

1) Не ограничивать тип символов или длину пароля пользователя по следующим причинам
Ограничение

1) Не ограничивать тип символов или длину пароля пользователя по следующим причинам
паролей для защиты от атак проникновения обречено на неудачу
Вместо этого следует использовать корректное декодирование и другие способы защиты
Следует быть осторожным с системами, которые допускают неограниченный размер паролей (Django DOS Sept 2013)

Наилучшие практики управления паролями

Слайд 40

2) Использовать криптографически сильную специфичную для креденциала salt
protect( [salt] + [password] );
Использовать

2) Использовать криптографически сильную специфичную для креденциала salt protect( [salt] + [password]
32char или 64char salt (реальный размер зависит от защищающей функции);
Не следует полагаться на сокрытие, расщепление или другие способы запутывания salt

Наилучшие практики управления паролями

Слайд 41

3a) навязывать трудную проверку как для атакующего, так и для проверяющей стороны
PBKDF2([salt]

3a) навязывать трудную проверку как для атакующего, так и для проверяющей стороны
+ [password], c=140,000);
Использовать PBKDF2 с FIPS –сертификацией или когда требуется поддержка на многих платформах
Следует использовать Scrypt, если аппаратура препятствует быстрым атакам, но не поддерживатеся масштабирование. (bcrypt is also a reasonable choice)

Наилучшие практики управления паролями

Слайд 42

3b) Навязывать трудную проверку только для атакующего
HMAC-SHA-256( [private key], [salt] + [password]

3b) Навязывать трудную проверку только для атакующего HMAC-SHA-256( [private key], [salt] +
)
Защищать данный ключ также как закрытый ключ, используя лучшие практики
Хранить ключ вне хранилища креденциалов
Выполнить преобразование пароля в хэш в виде отдельного веб-сервиса (криптографически изолированного).

Наилучшие практики управления паролями

Слайд 43

И снова… идеальный пароль!

✓ Upper
✓ Lower
✓ Number
✓ Special

И снова… идеальный пароль! ✓ Upper ✓ Lower ✓ Number ✓ Special
Over 8 characters

Password1!

Слайд 44

Использовать 2 идентификационных вопроса
Фамилия, номер аккаунта, email, DOB
Обеспечить политику блокировки
Задавать несколько вопросов,

Использовать 2 идентификационных вопроса Фамилия, номер аккаунта, email, DOB Обеспечить политику блокировки
относящихся к безопасности
https://www.owasp.org/index.php/Choosing_and_Using_Security_Questions_Cheat_Sheet
Посылать пользователю случайно сгенерированный токен по внешнему каналу
app, SMS или token
Проверять код Verify code в веб-сессии
Обеспечить политику блокировки
Изменять пароль
Обеспечить политику изменения пароля

Использовать лучшие практики аутентификации пользователя

Слайд 45

Лучшие практики аутентификации пользователя – реальные примеры

Лучшие практики аутентификации пользователя – реальные примеры

Слайд 46

Authentication Cheat Sheet
https://www.owasp.org/index.php/Authentication_Cheat_Sheet
Password Storage Cheat Sheet
https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet
Forgot Password Cheat Sheet
https://www.owasp.org/index.php/Forgot_Password_Cheat_Sheet
Session Management Cheat Sheet
https://www.owasp.org/index.php/Session_Management_Cheat_Sheet
ASVS

Authentication Cheat Sheet https://www.owasp.org/index.php/Authentication_Cheat_Sheet Password Storage Cheat Sheet https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet Forgot Password Cheat
AuthN and Session Requirements
Obviously, Identity is a BIG topic !

Другие ресурсы

Слайд 47

A1 – Injection

A2 – Broken Authentication and Session Management

A3 – Cross-Site Scripting

A1 – Injection A2 – Broken Authentication and Session Management A3 –
(XSS)

A4 – Insecure Direct Object References

A5 – Security Misconfiguration

A6 – Sensitive Data Exposure

A7 – Missing Function Level Access Control

A8 – Cross-Site Request Forgery

A9 – Using Components with Known Vulnerabilities

A10 – Unvalidated Redirects and Forwards

Охватываемые риски

Слайд 48

C6: Реализация необходимого управления доступом

C6: Реализация необходимого управления доступом

Слайд 50

Жестко встроенная в прикладной код проверка роли
Недостаток, связанный с логикой централизованного управления

Жестко встроенная в прикладной код проверка роли Недостаток, связанный с логикой централизованного
доступом
Недоверяемые данные, на основе которых принимается решение по управлению доступом
Управление доступом, которое “отрыто по умолчанию”
Недостаток, связанный с горизонтальным управлением доступом в стандартном случае (если не во всех)
Логика управления доступом, которую необходимо вручную добавлять в каждую точку кода
Управление доступом, которое “прилипает” к сессии
Управление доступом, которое требует отдельной политики для каждого пользователя

Примеры плохого управления доступом

Слайд 51

Сравнение вертикального и горизонтального управления доступом

Вертикальное управление доступом: разрешать различным типам пользователей

Сравнение вертикального и горизонтального управления доступом Вертикальное управление доступом: разрешать различным типам
доступ к различным функциям приложения
? создание границы между обычными пользователями и администраторами
Горизонтальное управление доступом: разрешать пользователям доступ к определенному подмножеству из широкого диапазона ресурсов определенного типа
? приложение веб-почты может разрешить вам читать свою собственную почту, но не чью-то еще; вы можете видеть только свои собственные детали

Слайд 52

Проверки роли, жество зашитые в код

RBAC

RBAC (Role based access control)

if (user.hasRole("ADMIN")) ||

Проверки роли, жество зашитые в код RBAC RBAC (Role based access control)
(user.hasRole("MANAGER")) {
deleteAccount();
}

if (user.hasAccess("DELETE_ACCOUNT")) {
deleteAccount();
}

Слайд 53

ASP.NET Roles vs Claims Authorization

[Authorize(Roles = "Jedi", "Sith")]
public ActionResult WieldLightsaber() {

ASP.NET Roles vs Claims Authorization [Authorize(Roles = "Jedi", "Sith")] public ActionResult WieldLightsaber()

return View();
}

Role Based Authorization

[ClaimAuthorize(Permission="CanWieldLightsaber")]
public ActionResult WieldLightsaber()
{
return View();
}

Claim Based Authorization

Слайд 54

Claims-Based Authorization

When an identity is created it may be assigned one or

Claims-Based Authorization When an identity is created it may be assigned one
more claims issued by a trusted party. A claim is name value pair that represents what the subject is, not what the subject can do. For example you may have a Drivers License, issued by a local driving license authority. Your driver's license has your date of birth on it. In this case the claim name would be DateOfBirth, the claim value would be your date of birth, for example 8th June 1970 and the issuer would be the driving license authority. Claims based authorization, at its simplest, checks the value of a claim and allows access to a resource based upon that value. For example if you want access to a night club the authorization process might be:1
The door security officer would evaluate the value of your date of birth claim and whether they trust the issuer (the driving license authority) before granting you access.
An identity can contain multiple claims with multiple values and can contain multiple claims of the same type.

Слайд 55

Apache Shiro Permission Based Access Control

http://shiro.apache.org/

Проверка, имеет ли текущее использование определенную роль

Apache Shiro Permission Based Access Control http://shiro.apache.org/ Проверка, имеет ли текущее использование
или нет:

if ( currentUser.hasRole( "schwartz" ) ) {
log.info("May the Schwartz be with you!" );
} else {
log.info( "Hello, mere mortal." );
}

Слайд 56

http://shiro.apache.org/

Check if the current user have a permission to act on a

http://shiro.apache.org/ Check if the current user have a permission to act on
certain type of entity

if ( currentUser.isPermitted( "lightsaber:wield" ) ) {
log.info("You may use a lightsaber ring. Use it wisely.");
} else {
log.info("Sorry, lightsaber rings are for schwartz masters only.");
}

Apache Shiro Permission Based Access Control

Слайд 57

http://shiro.apache.org/

Check if the current user have access to a specific instance of

http://shiro.apache.org/ Check if the current user have access to a specific instance
a type : instance-level permission check

if ( currentUser.isPermitted( "winnebago:drive:eagle5" ) ) {
log.info("You are permitted to 'drive' the 'winnebago' with license plate (id) 'eagle5'. " +
"Here are the keys - have fun!");
} else {
log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
}

Apache Shiro Permission Based Access Control

Слайд 58

A1 – Injection

A2 – Broken Authentication and Session Management

A3 – Cross-Site Scripting

A1 – Injection A2 – Broken Authentication and Session Management A3 –
(XSS)

A4 – Insecure Direct Object References

A5 – Security Misconfiguration

A6 – Sensitive Data Exposure

A7 – Missing Function Level Access Control

A8 – Cross-Site Request Forgery

A9 – Using Components with Known Vulnerabilities

A10 – Unvalidated Redirects and Forwards

Охватываемые риски

Слайд 59

C7: Защита данных

C7: Защита данных

Слайд 60

Какие преимущества обеспечивает HTTPS?
Конфиденциальность : шпион не может просмотреть ваши данные
Целостность: шпион

Какие преимущества обеспечивает HTTPS? Конфиденциальность : шпион не может просмотреть ваши данные
не может изменить ваши данные
Аутентификация: посещаемый сервер корректный
Высокая производительность!
Примеры наилучших кнфигураций HTTPS
https://www.owasp.org/index.php/Transport_Layer_Protection_Cheat_Sheet
https://www.ssllabs.com/projects/best-practices/

Шифрование данных при передачи

Слайд 61

HSTS (Strict Transport Security – строгая безопасность на транспортном уровне – rfc

HSTS (Strict Transport Security – строгая безопасность на транспортном уровне – rfc
6797)
http://www.youtube.com/watch?v=zEV3HOuM_Vw
Forward Secrecy
https://whispersystems.org/blog/asynchronous-security/
Certificate Creation Transparency
http://certificate-transparency.org
Certificate Pinning
https://www.owasp.org/index.php/Pinning_Cheat_Sheet
Browser Certificate Pruning

Шифрование данных при передачи

Слайд 62

Шифрование данных при передачи: HSTS (Strict Transport Security)

Forces browser to only make

Шифрование данных при передачи: HSTS (Strict Transport Security) Forces browser to only
HTTPS connection to server
Must be initially delivered over a HTTPS connection
Current HSTS Chrome preload list http://src.chromium.org/viewvc/chrome/trunk/src/net/http/transport_security_state_static.json
If you own a site that you would like to see included in the preloaded Chromium HSTS list, start sending the HSTS header and then contact: https://hstspreload.appspot.com/
A site is included in the Firefox preload list if the following hold:
It is in the Chromium list (with force-https).
It sends an HSTS header.
The max-age sent is at least 10886400 (18 weeks).

http://dev.chromium.org/sts

Слайд 63

What is Pinning ?
Pinning is a key continuity scheme
Detect when an

What is Pinning ? Pinning is a key continuity scheme Detect when
imposter with a fake but CA validated certificate attempts to act like the real server
2 Types of pinning
Carry around a copy of the server's public key;
Great if you are distributing a dedicated client-server application since you know the server's certificate or public key in advance
Note of the server's public key on first use
Trust-on-First-Use (TOFU) pinning
Useful when no a priori knowledge exists, such as SSH or a Browser

Encrypting data in Transit : Certificate Pinning

https://www.owasp.org/index.php/Pinning_Cheat_Sheet

Слайд 64

Encrypting data in Transit : Browser-Based TOFU Pinning

https://www.owasp.org/index.php/Pinning_Cheat_Sheet

Browser-Based TOFU Pinning :

Encrypting data in Transit : Browser-Based TOFU Pinning https://www.owasp.org/index.php/Pinning_Cheat_Sheet Browser-Based TOFU Pinning
Trust on First Use
HTTP Public Key Pinning IETF Draft
http://tools.ietf.org/html/draft-ietf-websec-key-pinning-11
Freezes the certificate by pushing a fingerprint of (parts of) the certificate chain to the browser
Example:

Public-Key-Pins: pin-sha1="4n972HfV354KP560yw4uqe/baXc=";
pin-sha1="qvTGHdzF6KLavt4PO0gs2a6pQ00=";
pin-sha256="LPJNul+wow4m6DsqxbninhsWHlwfp0JecwQzYpOLmCQ=";
max-age=10000; includeSubDomains

Слайд 65

Encrypting data in Transit : Pinning in Play (Chrome)

https://www.owasp.org/index.php/Pinning_Cheat_Sheet

Encrypting data in Transit : Pinning in Play (Chrome) https://www.owasp.org/index.php/Pinning_Cheat_Sheet

Слайд 66

Encrypting data in Transit : Forward Secrecy

If you use older SSL ciphers,

Encrypting data in Transit : Forward Secrecy If you use older SSL
every time anyone makes a SSL connection to your server, that message is encrypted with (basically) the same private server key
Perfect forward secrecy: Peers in a conversation instead negotiate secrets through an ephemeral (temporary) key exchange
With PFS, recording ciphertext traffic doesn't help an attacker even if the private server key is stolen!

https://whispersystems.org/blog/asynchronous-security/

Слайд 72

Unique IV per message

Unique IV per message

Слайд 74

Key storage and management + Cryptographic process isolation

Key storage and management + Cryptographic process isolation

Слайд 75

Confidentiality !

Confidentiality !

Слайд 76

HMAC your ciphertext

HMAC your ciphertext

Слайд 77

Integrity !

Integrity !

Слайд 78

Derive integrity and confidentiality keys from same master key with labeling

Derive integrity and confidentiality keys from same master key with labeling

Слайд 79

Don't forget to generate a master key from a good random source

Don't forget to generate a master key from a good random source

Слайд 81

Encrypting data at Rest : Google KeyCzar

https://github.com/google/keyczar

Sample Usage :

Crypter crypter = new

Encrypting data at Rest : Google KeyCzar https://github.com/google/keyczar Sample Usage : Crypter
Crypter("/path/to/your/keys");
String ciphertext = crypter.encrypt("Secret message");
String plaintext = crypter.decrypt(ciphertext);

Keyczar is an open source cryptographic toolkit for Java, Python and C++.
Designed to make it easier and safer for developers to use cryptography in their applications.
Secure key rotation and versioning
Safe default algorithms, modes, and key lengths
Automated generation of initialization vectors and ciphertext signatures

Слайд 82

Encrypting data at Rest : Libsodium

https://www.gitbook.com/book/jedisct1/libsodium/details

A high-security, cross-platform & easy-to-use crypto library.

Encrypting data at Rest : Libsodium https://www.gitbook.com/book/jedisct1/libsodium/details A high-security, cross-platform & easy-to-use

Modern, easy-to-use software library for encryption, decryption, signatures, password hashing and more.
It is a portable, cross-compilable, installable & packageable fork of NaCl, with a compatible API, and an extended API to improve usability even further
Provides all of the core operations needed to build higher-level cryptographic tools.
Sodium supports a variety of compilers and operating systems, including Windows (with MinGW or Visual Studio, x86 and x86_64), iOS and Android.
The design choices emphasize security, and "magic constants" have clear rationales.

Слайд 83

C8: Implement Logging And Intrusion Detection

C8: Implement Logging And Intrusion Detection

Слайд 84

Tips for proper application logging

Use a common/standard logging approach to facilitate correlation

Tips for proper application logging Use a common/standard logging approach to facilitate
and analysis
Logging framework : SLF4J with Logback or Apache Log4j2.
Avoid side effects : define a minimal but effective logging approach to track user activities
Perform encoding on untrusted data : protection against Log injection attacks !

Слайд 85

App Layer Intrusion Detection : Detection Points Examples

Input validation failure server side

App Layer Intrusion Detection : Detection Points Examples Input validation failure server
when client side validation exists
Input validation failure server side on non-user editable parameters such as hidden fields, checkboxes, radio buttons or select lists
Forced browsing to common attack entry points
Honeypot URL (e.g. a fake path listed in robots.txt like e.g. /admin/secretlogin.jsp)

Слайд 86

App Layer Intrusion Detection : Detection Points Examples

Blatant SQLi or XSS injection

App Layer Intrusion Detection : Detection Points Examples Blatant SQLi or XSS
attacks.
Workflow sequence abuse (e.g. multi-part form in wrong order).
Custom business logic (e.g. basket vs catalogue price mismatch).
Further study :
AppeSensor OWASP Project
libinjection : from SQLi to XSS – Nick Galbreath
Attack Driven Defense – Zane Lackey

Слайд 87

C9: Leverage Security Frameworks and Libraries

C9: Leverage Security Frameworks and Libraries

Слайд 88

Leverage Security Frameworks and Libraries

Don't reinvent the wheel : use existing coding

Leverage Security Frameworks and Libraries Don't reinvent the wheel : use existing
libraries and software frameworks
Use native secure features of frameworks rather than importing third party libraries.
Stay up to date !

Слайд 89

A1 – Injection

A2 – Broken Authentication and Session Management

A3 – Cross-Site Scripting

A1 – Injection A2 – Broken Authentication and Session Management A3 –
(XSS)

A4 – Insecure Direct Object References

A5 – Security Misconfiguration

A6 – Sensitive Data Exposure

A7 – Missing Function Level Access Control

A8 – Cross-Site Request Forgery

A9 – Using Components with Known Vulnerabilities

A10 – Unvalidated Redirects and Forwards

Охватываемые риски: все из них (but not consistently)

Слайд 90

C10: Error and Exception Handling

C10: Error and Exception Handling

Слайд 92

Best practices

Manage exceptions in a centralized manner to avoid duplicated try/catch blocks in

Best practices Manage exceptions in a centralized manner to avoid duplicated try/catch
the code, and to ensure that all unexpected behaviors are correctly handled inside the application.
Ensure that error messages displayed to users do not leak critical data, but are still verbose enough to explain the issue to the user.
Ensure that exceptions are logged in a way that gives enough information for Q/A, forensics or incident response teams to understand the problem.
Имя файла: Top-Ten-способов-предотвращения-веб-уязвимостей-по-версии-OWASP.pptx
Количество просмотров: 33
Количество скачиваний: 0