Показать сообщение отдельно

продолжение...
  #2  
Старый 11.07.2005, 14:47
w00d
Banned
Регистрация: 30.06.2005
Сообщений: 236
Провел на форуме:
333859

Репутация: 53
Отправить сообщение для w00d с помощью ICQ
По умолчанию продолжение...

Маска выражения <\s*id[^>]*>.*[^a-zA-Z0-9][^<]*</\s*id\s*> отклоняет HTTP запрос, если переменная POST_PAYLOAD содержит символы, не являющимися строковыми. Это очень важная возможность в модуле mod_security.

Ниже показан запрос и ответ сервера на id 12’12:

POST /axis/getBalance.jws HTTP/1.0
Content-Type: text/xml; charset=utf-8
SOAPAction: ""
Content-Length: 576
Expect: 100-continue
Host: www.bluebank.example.com

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:tns="http://www.bluebank.example.com/axis/getBalance.jws" xmlns:types="
http://www.bluebank.example.com/axis/getBalance.jws/encodedTypes"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body
soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<q1:getInput xmlns:q1="http://DefaultNamespace">
<id xsi:type="xsd:string">12'12</id>
</q1:getInput>
</soap:Body>
</soap:Envelope>

...

500 Internal Server Error
HTTP/1.1 500 Internal Server Error
Date: Mon, 03 Jan 2005 22:00:33 GMT
Server: Apache/2.0.50 (Unix) mod_ssl/2.0.50 OpenSSL/0.9.7d mod_jk2/2.0.4
Content-Length: 657
Connection: close
Content-Type: text/html; charset=iso-8859-1

Эта атака тоже не удалась, а mod_security перехватил её.
Вид Атаки 3: SQL инъекция

В переменные можно вставлять и SQL операторы. Возможно и объединение нескольких SQL операторов. Если ваше приложение не очищает такие входные данные, то злоумышленники могут добавить SQL операторы к уже существующим, часто с плачевными последствиями. Blue Bank блокировал атаки типа SQL-инъекция, добавив следующие директивы:

<Location /axis/getBalance.jws>
SecFilterInheritance Off
SecFilterDefaultAction "deny,log,status:500"
SecFilterScanPOST On
SecFilterCheckURLEncoding On
SecFilterCheckUnicodeEncoding On

SecFilterSelective POST_PAYLOAD "<\s*id[^>]*>" chain
SecFilterSelective POST_PAYLOAD "<\s*id[^>]*>.{6,}</\s*id\s*>"
"deny,status:500"
SecFilterSelective POST_PAYLOAD "<\s*id[^>]*>.*[^a-zA-Z0-9][^<]*</\s*id\s*>"
"deny,status:500"
SecFilterSelective POST_PAYLOAD "<\s*id[^>]*>.*select.+from[^<]*</\s*id\s*>"
"deny,status:500"
</Location>


Выделенные жирным строки проверяют, содержатся ли в запросе слова "select * from . . .", а если находит их, то возвращает статус 500, как в предыдущем примере. Аналогично вы можете добавить SQL операторы, которые следует блокировать, обновлять и т.п.
Вид Атаки 4: SOAP Раскрытие Дефектного Кода

Один из основных источников информации в Web-сервисах – это дефектный код. Вызванная на сервере ошибка может создать дефектный код. Ниже представлен запрос злоумышленника и ответ сервера в результате подстановки символа «а» вместо целого числа в переменную id:

POST /axis/getBalance.jws HTTP/1.0
Content-Type: text/xml; charset=utf-8
SOAPAction: ""
Content-Length: 569
Expect: 100-continue
Host: www.bluebank.example.com

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:tns="http://www.bluebank.example.com/axis/getBalance.jws" xmlns:types="
http://www.bluebank.example.com/axis/getBalance.jws/encodedTypes"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<q1:getInput xmlns:q1="http://DefaultNamespace">
<id xsi:type="xsd:string">a</id>
</q1:getInput>
</soap:Body>
</soap:Envelope>

...

500 Internal Server Error
HTTP/1.1 500 Internal Server Error
Date: Tue, 04 Jan 2005 16:22:14 GMT
Server: Apache/2.0.50 (Unix) mod_ssl/2.0.50 OpenSSL/0.9.7d mod_jk2/2.0.4
Set-Cookie: JSESSIONID=1CAF4CD0ED0F38FB40ECBC7BDAB56C75; Path=/axis
Content-Type: text/xml;charset=utf-8
Connection: close

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<soapenv:Fault>
<faultcode>soapenv:Server.userException</faultcode>
<faultstring>java.lang.NumberFormatException:
For input string:"a"</faultstring>
<detail/>
</soapenv:Fault>
</soapenv:Body>
</soapenv:Envelope>


Как показано в ответе сервера, дефектный код может раскрыть критическую внутреннюю информацию. Это достаточно веский довод для создания соответствующих фильтров:

<Location /axis/getBalance.jws>
SecFilterInheritance Off

SecFilterDefaultAction "deny,log,status:500"
SecFilterScanPOST On
SecFilterCheckURLEncoding On
SecFilterCheckUnicodeEncoding On

SecFilterSelective POST_PAYLOAD "<\s*id[^>]*>" chain
SecFilterSelective POST_PAYLOAD "<\s*id[^>]*>.{6,}</\s*id\s*>"
"deny,status:500"
SecFilterSelective POST_PAYLOAD "<\s*id[^>]*>.*[^a-zA-Z0-9][^<]*</\s*id\s*>"
"deny,status:500"

SecFilterScanOutput On
SecFilterSelective OUTPUT "faultcode" "deny,status:500"
</Location>
SecFilterScanOutput On

Эта директива сканирует выходной блок данных и принимает определенные фильтры.

<code>SecFilterSelective OUTPUT "faultcode" "deny,status:500"</code>

Директива блокирует исходящий трафик, содержащий дефектные коды. Если атакующий посылает сформированный запрос с символом «а» в поле целых чисел, он получит ответ, похожий на этот:

HTTP/1.1 500 Internal Server Error
Date: Mon, 03 Jan 2005 22:00:33 GMT
Server: Apache/2.0.50 (Unix) mod_ssl/2.0.50 OpenSSL/0.9.7d mod_jk2/2.0.4
Content-Length: 657
Connection: close
Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>500 Internal Server Error</title>
</head><body>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error or misconfiguration and was
unable to complete your request.</p>
<p>Please contact the server administrator, you@example.com and inform
them of the time the error occurred, and anything you might have done that
may have caused the error.</p>
<p>More information about this error may be available in the server
error
log.</p>
<hr />
<address>Apache/2.0.50 (Unix) mod_ssl/2.0.50 OpenSSL/0.9.7d
mod_jk2/2.0.4
Server at 192.168.7.50 Port 80</address>
</body></html>

Заключение

mod_security выглядит как еще один продукт в области безопасности, однако имеет хорошее превосходство над другими уже доступными утилитами. Кроме обнаружения вторжений и системы защиты на уровне HTTP, mod_security также имеет возможности фильтрования POST_PAYLOAD.

Кроме того, превосходство mod_security состоит в том, что разработчики и Web администраторы могут защищать Web-сервисы без исправления исходного когда приложений. Он не сделает исходный код лучше; просто теперь организация может поднять эффективную дополнительную защиту своих Web-сервисов без необходимости правки множества строк кода.

Shreeraj Shah основатель и руководитель Net-Square.