angle-uparrow-clockwisearrow-counterclockwisearrow-down-uparrow-leftatcalendarcard-listchatcheckenvelopefolderhouseinfo-circlepencilpeoplepersonperson-fillperson-plusphoneplusquestion-circlesearchtagtrashx

OWASP Zed Attack Proxy (ZAP) тестирование безопасности

Когда вы являетесь разработчиком сайтов, вы можете получить уязвимости простым способом, используя приложение OWASP Zed Attack Proxy (ZAP).

13 января 2020
post main image
https://unsplash.com/@ostshem

Время радости или кризиса: запуск приложения OWASP Zed Attack Proxy (ZAP) для проверки уязвимостей нашего веб-приложения. Разработчики часто знают, что в их коде есть слабые места, но всегда есть дата доставки. Так почему бы не использовать инструмент, который перечисляет известные и важные? Я впервые использую ZAP, так что если вы эксперт, вам лучше перестать читать здесь. По ссылкам ниже вы найдете информацию об установке и запуске, а также о том, как войти в систему. На моем Ubuntu 18.04 установка системы была безутешной, просто скачайте, в терминале перейдите в каталог скачивания и введите тип:

./zap.sh

Я запустил это не на моем производственном сайте, а на той же машине, на которой запущена версия моего сайта для разработки. Для запуска при входе в систему перейдите в раздел "Ручной просмотр", введите URL локального веб-сайта и нажмите кнопку "Запустить браузер". Это запускает новое окно браузера с вашим сайтом с кнопками ZAP с левой и правой стороны. Войдите в систему как обычно и нажмите на кнопку (Паук) Start, чтобы начать работу. Кнопка входа на мой сайт была немного под левой кнопкой, мне пришлось изменить ширину экрана, чтобы перепозиционироваться и получить доступ к кнопке.

Предупреждения ZAP

Ниже приведены некоторые предупреждения, о которых сообщил ZAP. Все тексты в нижеследующих блоках взяты из приложения ZAP. Я показываю только несколько строк, но во многих случаях есть гораздо больше информации. "После расследования" означает большую часть времени, что я..:

  • Перейдите на вкладку Предупреждения
  • Выберите линию с проблемой
  • Перейдите на вкладку Запрос и посмотрите на запрос
  • Нажмите на вкладку "Ответ" и посмотрите на ответ.

Path Traversal

Сообщается ZAP:

Alert priority: High
Path Traversal
Evidence: etc
Description: 
The  Path Traversal  attack technique allows an attacker access to files, directories, and commands that potentially reside outside the web document root directory. 
An attacker may manipulate a URL in such a way that the web site will execute or reveal the contents of arbitrary files anywhere on the web server. 
Any device that exposes an HTTP-based interface is potentially vulnerable to  Path Traversal.
...

После расследования:

Хотя это требует гораздо большего изучения, оказалось, что процессор выбора тем не проверял, есть ли запрашиваемая тема в доступных темах. Исправлено. Также после более подробного рассмотрения ответа я заметил, что в посте блога у меня было предложение, содержащее слово "и т.д.". Это было подчеркнуто в ответе. Речь идет об атаках на /etc из c:tc. Нет проблем.

Absence of Anti-CSRF Tokens

Сообщается ZAP:

Alert priority: Low
Absence of Anti-CSRF Tokens
Evidence: <form name="search" action="/en/blog/posts/search" method="post">
Description: No Anti-CSRF tokens were found in a  HTML  submission form.
A cross-site request forgery is an attack that involves forcing a victim to send an HTTP request to a target destination without their knowledge or intent in order to perform an action as the victim. 
The underlying cause is application functionality using predictable URL/form actions in a repeatable way. 
The nature of the attack is that CSRF exploits the trust that a web site has for a user. 
...

После расследования:

В поисковых формах неправильно использовался метод POST. Я изменил метод на GET и, конечно же, метод Flask принимает только GET-метод.

Private IP Disclosure

Сообщается ZAP:

Alert priority: Low
Private IP Disclosure
Evidence: 192.168.0.0
Description: A private IP (such as 10.x.x.x, 172.x.x.x, 192.168.x.x) or an Amazon EC2 private hostname (for example, ip-10-0-56-78) 
has been found in the HTTP response body. This information might be helpful for further attacks targeting internal systems.
...

После расследования:

Сообщение пришло из текста сообщения в блоге, где я упомянул этот IP-адрес. Нет проблем.

Format String Error

Сообщается ZAP:

Alert priority: Medium
Format String Error
Parameter: lc
Attack: ZAP %1!s%2!s%3!s%4!s%5!s%6!s%7!s%8!s%9!s%10!s%11!s%12!s%13!s%14!s%15!s%16!s%17!s%18!s%19!s%20!s%21!n%22!n%23!n%24!n%25!n%26!n%27!n%28!n%29!n%30!n%31!n%32!n%33!n%34!n%35!n%36!n%37!n%38!n%39!n%40!n
Description: A Format String error occurs when the submitted data of an input string is evaluated as a command by the application. 
...

После расследования:

В ответе была обнаружена ошибка 500 с текстом: sqlalchemy.exc.DataError: (pymysql.err.DataError) (1406, &quot;Data too long for column 'request_url' at row 1&quot;) В данном случае это был объект PageRequest SQLAlchemy , где я храню каждый входящий запрос. Я надеялся, ожидая, что слишком длинные значения будут автоматически усечены, но это было неверное предположение! Возможно, это может произойти и в других местах программы. Я все равно изменил это для этого объекта, получив длину колонки и усечив значение перед тем, как вставить его.

Buffer Overflow

Сообщается ZAP:

Alert priority: Medium
Buffer Overflow
Parameter: lc
Attack: GET http://127.0.0.1:8000/en/auth/register?lc=aofyVsiquNyUZJJWRvcyMtmOKToYwtFlLIjVPAnQbvLMSuvapNZbePEuuZUgyEVHmcDklTcXYhZDCGFNtEFpbiJaafhHTrJobQWgcGKHjrYuDDaYbddfJxoemFoxRtesJrGieOviBIdFHhoYngoGNKaowenBuwavrUdOAfKElNWLoGHVTTsQDUTRgZMYKUTAOQJuNqQqBNkjuuMgAxqCQKvEvSvHviRyXrFRylXFjQuDeRosheUMCjjEFZRLMFpmRcYsjYZKPaALNOBvjLMcYJtoUIxGCKqYBSPwRTilwkaxxPmCekriFLVOkVtpVlSMWvtgHdrnjuAEesIuwfWyByZQjJKblYBXbRBHoHjCJKssKKdynuuGTnGlCMrRQHUnTcgbOPhCoTgIAcyDxBerlYELKJlCiIEbAnkFbtgCqnBKaUsHglhcVcyjqFnXtUEAKoHDSXMHhTJmXFvmYBxvEFITqJQgaWOsHIutVZYDiuRBSMwOXQYlmTenZHXPnchCHTfxtvsqlgZQZYmyNKYXRETmBRKyHKTbgoJGtVFaMCOPkvQAGasEylqdVEutnJiHSIBhovlKfMbPpctsMTsukniTThWTFqLJLS
Description: Buffer overflow errors are characterized by the overwriting of memory spaces of the background web process, which should have never been modified intentionally or unintentionally. Overwriting values of the IP (Instruction Pointer), BP (Base Pointer) and other registers causes exceptions, segmentation faults, and other process errors to occur. Usually these errors end execution of the application in an unexpected way.  
...

После расследования:

Опять же в ответе была обнаружена ошибка 500 с текстом: sqlalchemy.exc.DataError: (pymysql.err.DataError) (1406, &quot;Data too long for column 'request_url' at row 1&quot;) И снова это был объект PageRequest SQLAlchemy , где я храню каждый входящий запрос. То же самое решение.

Application Error Disclosure

Сообщается ZAP:

Alert priority: Low
Application Error Disclosure
Url: http://127.0.0.1:8000/run
Evidence: HTTP/1.0 500 INTERNAL SERVER ERROR (KeyError: 'babel' // Werkzeug Debugger)
Description: 
This page contains an error/warning message that may disclose sensitive information like the location of the file that produced the unhandled exception. This information can be used to launch further attacks against the web application. The alert could be a false positive if the error message is found inside a documentation page.
...

После расследования:

Урл был обнаружен ZAP из-за заголовка Content-Security-Policy-Report-Only, содержащего (csp) отчет-uri. Урл / прогон не является частью видимого приложения. Я только что использовал обработчики ошибок приложения, которые вызывают Babel для переводов. Изменили это, добавив одноязычные основные страницы ошибок для приложения на /run url.

X-Content-Type-Options Header Missing

Сообщается ZAP:

Alert priority: Low
X-Content-Type-Options Header Missing
Url: http://127.0.0.1:8000/run/raw?__debugger__=yes&cmd=resource&f=console.png
Parameter: X-Content-Type-Options
Description: 
The Anti-MIME-Sniffing header X-Content-Type-Options was not set to 'nosniff'. This allows older versions of Internet Explorer and Chrome to perform MIME-sniffing on the response body, potentially causing the response body to be interpreted and displayed as a content type other than the declared content type. 
...

После расследования:

Было возвращено несуществующее изображение. Я добавил в ответ security headers, конечно же, исключив CSP-заголовок. Также я добавил основные страницы ошибок HTTP. Браузер показывает несуществующее изображение. Хорошо.

Application Error Disclosure

Сообщается ZAP:

Alert priority: Low
Application Error Disclosure
Url: http://127.0.0.1:8000/admin/static/
Evidence: HTTP/1.0 500 INTERNAL SERVER ERROR
Description: 
This page contains an error/warning message that may disclose sensitive information like the location of the file that produced the unhandled exception. This information can be used to launch further attacks against the web application. The alert could be a false positive if the error message is found inside a documentation page.
...

После расследования:

Это происходит только в (локальном) режиме разработки Flask . В производстве все статические элементы обслуживаются Nginx. Нет проблем... Я думаю.

Резюме

Инструмент вроде OWASP Zed Attack Proxy (ZAP) позволяет даже такому нобу, как я, легко находить уязвимости. Я могу порекомендовать этот инструмент всем разработчикам. И поскольку он пытается атаковать ваш сайт на все доступные urls, он также чрезвычайно полезен для поиска других проблем, таких как пропущенные страницы и нарушения CSP.

Ссылки / кредиты

Getting Started with ZAP and the OWASP Top 10: Common Questions
https://www.denimgroup.com/resources/blog/2019/09/getting-started-questions/

How can ZAP automatically authenticate via forms?
https://github.com/zaproxy/zaproxy/wiki/FAQformauth

OWASP ZAP for Dummies
https://devonblog.com/security/owasp-zap-for-dummies/

proxy settings for localhost not obeyed unless network.proxy.allow_hijacking_localhost is set
https://bugzilla.mozilla.org/show_bug.cgi?id=1535581

Running Penetration Tests for your Website as a Simple Developer with OWASP ZAP
https://medium.com/volosoft/running-penetration-tests-for-your-website-as-a-simple-developer-with-owasp-zap-493d6a7e182b

The Open Web Application Security Project (OWASP)
https://www.owasp.org

The OWASP Zed Attack Proxy (ZAP)
https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project

Подробнее

Security testing

Оставить комментарий

Комментируйте анонимно или войдите в систему, чтобы прокомментировать.

Комментарии

Оставьте ответ

Ответьте анонимно или войдите в систему, чтобы ответить.