NGHIÊN CỨU ỨNG DỤNG MOD SECURITY ĐỂ BẢO VỆ WEB SERVER

Embed Size (px)

Citation preview

[email protected]

MC LCI.PHIU GIAO TI5II.NHP 6IV.GII THIU MOD_SECURITY7CHC NNG7Parsing7Buffering7Logging7Rule Engine8CU TRC RULE TRONG ModSecurity8QUY TRNH X L TRONG ModSecurity8Request Header (1)9Request body (2)9Response headers (3)9Response body (4)10Logging (5)10KHUYN CO KHI TRIN KHAI THC T10V.TNG QUAN V TIU CHUN OWASP TOP TEN11VI.CI T MODSECURITY12VII.CU HNH15Cu hnh th mc15Cc tp tin cu hnh15Cc ch th trong tp tin cu hnh16Qun l Request Body17Qun l Response Body18Filesystem Locations18File Uploads19Debug Log19Audit Log19Default Rule Match Policy20Verifying Installation20VIII.OWASP MODSECURITY CORE RULE SET20Gii thiu20Trin khai OWASP ModSecurity CRS21Kim tra kt qu22IX.TNG QUAN V RULE23Gii thiu23Variables24Request variables25Server variables26Response variables26Miscellaneouse variables27Parsing flags27Collections variables28Time variables28Operators29Stringmatching operators29Numerical operators30Validation operators30Miscellaneous operators30Actions31Disruptive actions31Flow actions31Metadata actions32Variable actions32Logging actions32Special actions33Miscellaneous Actions33X.RULE LANGUAGE TUTORIAL33Tng quan33Hng dn s dng bin (variable)33Hng dn s dng lin kt rule (chain)34Hng dn s dng ton t ph nh34Variable Counting35Hng dn v action35Action Defaults35Unconditional Rules36Using Transformation Functions36Blocking37Changing Rule Flow37Capturing Data38Variable Manipulation39Metadata39XI.PHN TCH CC RULE NG DNG THC T40Trng hp 1: Chng tn cng Replay attack thng qua c ch nh token ngu nhin.40Trng hp 2: Pht hin cc Session cookie khng hp l43Trng hp 3: Phng chng phng php khai thc HTTP Reponse Spliting48Trng hp 4: Phng chng phng php khai thc Path-Traversal50Trng hp 5: Pht hin nguy c l thng tin th tn dng52Trng hp 6: Pht hin hnh vi ng nhp bruteforce54XII.PH LC61DANH MC L HNG BO MT OWASP 201061DANH MC CNG C H TR KIM TRA BO MT NG DNG WEB64DANH MC THAM KHO KHAI THC L HNG BO MT NG DNG WEB67XIII.TI LIU THAM KHO91

I. PHIU GIAO TITn 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 SV2

I. Mc chCc 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 khoCc 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_SECURITYMod_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 NNGModSecurity hot ng vi chng trnh web server (v d: Apache) s thc hin cc tc v nh sau:ParsingModSecurity 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.BufferingChc 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)LoggingModSecurity 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.Rule EngineCc 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 HidingCU TRC RULE TRONG ModSecurityTt 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 "" log,deny,status:404Cu trc chun ca mt rule trong ModSecurity bao gm 3 phn chnh:SecRule VARIABLES OPERATOR ACTIONSVARIABLES: 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 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 ModSecurityTrong 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 TNhm 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).V. TNG QUAN V TIU CHUN OWASP TOP TENOWASP (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-InjectionNhm 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.

A2-Cross Site Scripting (XSS)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.

A3-Broken Authentication and Session ManagementPhn 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.

A4-Insecure Direct Object ReferencesNguy 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.

A5-Cross Site Request Forgery (CSRF)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.

A6-Security MisconfigurationCc 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.

A7-Insecure Cryptographic StorageRt nhiu ng dng web khng quan tm n vic bo v d 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 Restrict URL AccessHu ht cc ng dng thng thc hin kim sot vic truy cp 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 Transport Layer ProtectionThng tin xc thc c truyn qua mi trng mng truyn dn khng bo mt s to ra nguy c d liu b nghe ln. Vic ny 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 Redirects and ForwardsCc ng dng web thng chuyn hng ngi dng n 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 MODSECURITYTrc 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 TU IMNHC IM

Da vo phin bn ca h iu hnh T ng ci t D dng bo tr

C th l phin bn c

Gi ci t ca bn th ba T ng ci t C th l phin bn c Yu cu ti v cp nht thng xuyn Khng tin tng vo gi ci t ng gi

Ci t t m ngun Bo m l phin bn mi nht C th s dng phin bn th nghim C th ty bin, s dng cc bn v khn cp trong tnh hung pht hin li bo mt C th gp cc vn khi qun tr vin mun s dng li phin bn c trc

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-develTi 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.md5Kim tra gi tin ti v# md5sum c Modsecurity-apache_2.7.3.tar.gz.md5Hnh 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 installSau 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)B comment cho unique_id_moduleLoadModule unique_id_module modules/mod_unique_id.soThm 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

Hnh 3: Log thng bo trng thi khi ng ca ApacheApache hot ng bnh thng vi mod_security.VII. CU HNHCu hnh th mcTrc 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/binConfiguration files: /opt/modsecurity /etcAudit logs: /opt/modsecurity /var/auditPersistent data: /opt/modsecurity/var/dataLogs: /opt/modsecurity/var/logTemporary files: /opt/modsecurity/var/tmpFile uploads: /opt/modsecurity/var/upload

LocationOwnerGroupPermissions

/opt/modsecurityrootapacherwxr-x---

/opt/modsecurity/binrootapacherwxr-x---

/opt/modsecurity/etcrootrootrwx------

/opt/modsecurity/varrootapacherwxr-x---

/opt/modsecurity/var/auditapacherootrwx------

/opt/modsecurity/var/dataapacherootrwx------

/opt/modsecurity/var/logrootrootrwx------

/opt/modsecurity/var/tmpapacheapacherwxr-x---

/opt/modsecurity/var/uploadapacherootrwx------

Cc tp tin cu hnh

Tp tinM t

main.confTp tin cu hnh chnh

rules-first.confTp lnh thc hin u tin

rules.confTp lnh thc hin chnh

rules-last.confTp lnh thc hin cui cng

Thc hin to tp tin Modsecurity.conf trong th mc /etc/httpd/conf.d vi ni dung:

Include /opt/modsecurity/etc/main.confInclude /opt/modsecurity/etc/rules-first.confInclude /opt/modsecurity/etc/rules.confInclude /opt/modsecurity/etc/rules-last.conf

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.confCc ch th trong tp tin cu hnhCh thM t

SecArgumentSeparatorSets the application/x-www-form-urlencoded parameter separator

SecCookieFormatSets the cookie parser version

SecDataDirSets the folder for persistent storage

SecRequestBodyAccessControls request body buffering

SecRequestBodyInMemoryLimitSets the size of the per-request memory buffer

SecRequestBodyLimitSets the maximum request body size ModSecurity will accept

SecRequestBodyLimitActionControls what happens once the request body limit is reached

SecRequestBodyNoFilesLimitSets the maximum request body size, excluding uploaded files

SecResponseBodyAccessControls response body buffering

SecResponseBodyLimitSpecifies the response body buffering limit

SecResponseBodyLimitActionControls what happens once the response body limit is reached

SecResponseBodyMimeTypeSpecifies a list of response body MIME types to inspect

SecResponseBodyMimeTypesClearClears the list of response body MIME types

SecRuleEngineControls the operation of the rule engine

SecTmpDirSets the folder for temporary files

Qun l Request BodyRequest 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:# 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 13107200SecRequestBodyNoFilesLimit 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 BodyTng 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.# 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 OnSecResponseBodyAccess 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 LocationsTrong 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.#SecDataDir /tmp/

File UploadsTi 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 LogDebug 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 logSecDebugLog /opt/modsecurity/var/log/debug.logSecDebugLogLevel 3

Audit LogAudit 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).RelevantOnlySecAuditLogRelevantStatus ^5# Use a single file for logging.SecAuditLogType SerialSecAuditLog /opt/modsecurity/var/log/audit.log# Specify the path for concurrent audit logging.SecAuditLogStorageDir /opt/modsecurity/var/audit/

Default Rule Match PolicyPhn 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 InstallationSau 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.confSecRule 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/dangerousHTTP/1.1 406 Not AcceptableDate: Thu, 30 May 2013 22:56:06 GMTServer: ApacheConnection: closeContent-Type: text/html; charset=iso-8859-1

VIII. OWASP MODSECURITY CORE RULE SETGii thiuModSecurity 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. 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 CRSTin hnh ti gi tin SpiderLabs-owasp-modsecurity-crs phin bn mi nht ti:nh dngLin kt

GitHub Repositoryhttps://github.com/SpiderLabs/owasp-modsecurity-crs

TAR/GZ Archivehttps://github.com/SpiderLabs/owasp-modsecurity-crs/tarball/master

ZIP Archivehttps://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

#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

#STOP COMMON CONFIGURATION

#START OWASP MODSECURITY CORE RULE SET

Include /opt/modsecurity/etc/modsecurity_crs_10_setup.confInclude /opt/modsecurity/etc/crs/activated_rules/*.conf

#STOP OWASP MODSECURITY CORE RULE SET

#/etc/init.d/httpd restartKim tra kt quTa 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

Hnh 5:Tn cng SQLI sau khi trin khai OWASP CRSCnh 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 RULEGii thiuModsecurity nh ngha 9 loi ch th ngi dng c th trin khai cc tnh nng lc linh ng cho h thng web.DirectiveDescription

SecActionPerforms an unconditional action. This directive is essentially a rule that always matches.

SecDefaultActionSpecifies the default action list, which will be used in the rules that follow.

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

SecRuleCreates a rule.

SecRuleInheritanceControls whether rules are inherited in a child configuration context.

SecRuleRemoveByIdRemoves the rule with the given ID.

SecRuleRemoveByMsgRemoves the rule whose message matches the given regular expression.

SecRuleScriptCreates a rule implemented using Lua.

SecRuleUpdateActionByIdUpdates the action list of the rule with the given ID.

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

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.OperatorsTi 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_functionsChc 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 )ActionsCh r hnh ng s thc hin khi mt rule c so trng mu.VariablesC 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 variablesCc 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:VariableDescription

ARGSRequest parameters (read-only collection)

ARGS_COMBINED_SIZETotal size of all request parameters combined

ARGS_NAMESRequest parameters names (collection)

ARGS_GETQuery string parameters (read-only collection)

ARGS_GET_NAMESQuery string parameters names (read-only collection)

ARGS_POSTRequest body parameters (read-only collection)

ARGS_POST_NAMESRequest body parameters names (read-only collection)

FILESFile names (read-only collection)

FILES_COMBINED_SIZECombined size of all uploaded files

FILES_NAMESFile parameter names (read-only collection)

FILES_SIZESA list of file sizes (read-only collection)

FILES_TMPNAMESA list of temporary file names (read-only collection)

PATH_INFOExtra path information

QUERY_STRINGRequest query string

REMOTE_USERRemote user

REQUEST_BASENAMERequest URI basename

REQUEST_BODYRequest body

REQUEST_COOKIESRequest cookies (read-only collection)

REQUEST_COOKIES_NAMESRequest cookies names (read-only collection)

REQUEST_FILENAMERequest URI file name/path

REQUEST_HEADERSRequest headers (collection, read-only)

REQUEST_HEADERS_NAMESRequest headers names (read-only collection)

REQUEST_LINERequest line

REQUEST_METHODRequest method

REQUEST_PROTOCOLRequest protocol

REQUEST_URIRequest URI, convert to exclude hostname

REQUEST_URI_RAWRequest URI, as it was presented in the request

Server variablesCc 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:VariableDescription

AUTH_TYPEAuthentication type

REMOTE_ADDRRemote address

REMOTE_HOSTRemote host

REMOTE_PORTRemote port

SCRIPT_BASENAMEScript basename

SCRIPT_FILENAMEScript file name/path

SCRIPT_GIDScript group ID

SCRIPT_GROUPNAMEScript group name

SCRIPT_MODEScript permissions

SCRIPT_UIDScript user ID

SCRIPT_USERNAMEScript user name

SERVER_ADDRServer address

SERVER_NAMEServer name

SERVER_PORTServer port

Response variablesCc 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).Bng sau lit k cc gi tr bin (respone variable) m ModSecurity h tr:VariableDescription

RESPONSE_BODYResponse body

RESPONSE_CONTENT_LENGTHResponse content length

RESPONSE_CONTENT_TYPEResponse content type

RESPONSE_HEADERSResponse headers (read-only collection)

RESPONSE_HEADERS_NAMESResponse headers names (read-only collection)

RESPONSE_PROTOCOLResponse protocol

RESPONSE_STATUSResponse status code

Miscellaneouse variablesBng sau lit k cc gi tr bin (miscellaneouse variable) m ModSecurity h tr:VariableDescription

HIGHEST_SEVERITYHighest severity encountered

MATCHED_VARContents of the last variable that matched

MATCHED_VARSContents of all variables that matched int the most recent rule

MATCHED_VARS_NAMESNames of all variables that matched in the most recent rule

MATCHED_VAR_NAMEName of the last variable that matched

MODSEC_BUILDModSecurity build version (e.g., 02050102)

SESSIONIDSession ID associated with current transaction

UNIQUE_IDUnique transaction ID generated by mod_unique_id

USERIDUser ID associated with current transaction

WEBAPPIDWeb application ID associated with current transaction

WEBSERVER_ERROR_LOGError messages generated by Apache during current transaction

Parsing flags

VariableDescription

MULTIPART_BOUNDARY_QUOTEDMultipart parsing error: quoted boundary encountered

MULTIPART_BOUNDARY_WHITESPACEMultipart parsing error: whitespace in boundary

MULTIPART_CRLF_LF_LINESMultipart parsing error: mixed line endings used

MULTIPART_DATA_BEFOREMultipart parsing error: seen data before first boundary

MULTIPART_DATA_AFTERMultipart parsing error: seen data after last boundary

MULTIPART_FILE_LIMIT_EXCEEDEDMultipart parsing error: too many files

MULTIPART_HEADER_FOLDINGMultipart parsing error: header folding used

MULTIPART_INVALID_HEADER_FOLDINGMultipart parsing error: invalid header folding encountered

MULTIPART_LF_LINEMultipart parsing error: LFline ending detected

MULTIPART_MISSING_SEMICOLONMultipart parsing error: missing semicolon before boundary

MULTIPART_STRICT_ERRORAt least one multipart error except unmatched boundary occurred

MULTIPART_UNMATCHED_BOUNDARYMultipart parsing error: unmatched boundary detected

REQBODY_PROCESSORRequest processor that handled request body

REQBODY_PROCESSOR_ERRORRequest processor error flag (0 or 1)

REQBODY_PROCESSOR_ERROR_MSGRequest processor error message

Collections variablesCc 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.VariableDescription

ENVEnvironment variables (read-only collection, although its possible to use setvar

GEOto change it)

GLOBALGeo lookup information from the last @geoLookupinvocation (read-only collec

IPtion)

TXGlobal information, shared by all processes (read/write collection)

RULEIP address data storage (read/write collection)

SESSIONTransient transaction data (read/write collection)

USERCurrent rule metadata (read-only collection)

XMLSession data storage (read/write collection)

Time variablesCc bin v thi gian dng xc nh thi gian khi mt phin lm vic trn ModSecurity c thc hin.VariableDescription

TIMETime (HH:MM:SS)

TIME_DAYDay of the month (131)

TIME_EPOCHSeconds since January 1, 1970 (e.g., 1251029017)

TIME_HOURHour of the day (023)

TIME_MINMinute of the hour (059)

TIME_MONMonth of the year (011)

TIME_SECSecond of the minute (059)

TIME_WDAYWeek day (06)

TIME_YEARYear

OperatorsCc 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 operatorsStringmatching operatorsCc 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.OperatorDescription

@beginsWithInput begins with parameter

@containsInput contains parameter

@endsWithInput ends with parameter

@rsubManipulation of request and response bodies

@rxRegular pattern match in input

@pmParallel pattern matching

@pmFromFile(also @pmfas of 2.6)Parallel patterns matching, with patterns read from a file

@streqInput equal to parameter

@withinParameter contains input

Numerical operatorsTrong 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.OperatorDescription

@eqEqual

@geGreater or equal

@gtGreater than

@leLess or equal

@ltLess than

Validation operatorsCc ton t kim tra m ModSecurity h tr c lit k trong bng sau:OperatorDescription

@validateByteRangeValidates that parameter consists only of allowed byte values

@validateDTDValidates XML payload against a DTD

@validateSchemaValidates XML payload against a schema

@validateUrlEncodingValidates an URL-encoded string

@validateUtf8EncodingValidates an UTF-8-encoded string

Miscellaneous operatorsV 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 )OperatorDescription

@geoLookupDetermines the physical location of an IP address

@inspectFilenvokes an external script to inspect a file

@rblLooks up the parameter against a RBL (real-time block list)

@verifyCCChecks whether the parameter is a valid credit card number

@verifyCPFChecks whether the parameter is a valid Brazilian social security number

@verifySSNChecks whether the parameter is a valid US social security number

@ipMatchMatches input against one or more IP addresses or network segments

@ipMatchFromFile( and @ip MatchF), as of 2.7.0As @ipMatch, but reads input from a file

ActionsCc 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 ActionsDisruptive actionsTrong 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.ActionDescription

allowStop processing of one or more remaining phases

blockIndicate that a rule wants to block

denyBlock transaction with an error page

dropClose network connection

passDo not block, go to the next rule

pausePause for a period of time, then execute allow.

proxyProxy request to a backend web server

redirectRedirect request to some other web server

Flow actionsActionDescription

chainConnect two or more rules into a single logical rule

skipSkip over one or more rules that follow

skipAfterSkip after the rule or marker with the provided ID

Metadata actionsPhn 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.ActionDescription

idAssign unique ID to a rule

phasePhase for a rule to run in

msgMessage string

revRevision number

severitySeverity

tagTag

Variable actionsCch 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.ActionDescription

captureCapture results into one or more variables

deprecatevarDecrease numerical variable value over time

expirevarRemove variable after a time period

initcolCreate a new persistent collection

setenvSet or remove an environment variable

setvarSet, remove, increment, or decrement a variable

setuidAssociate current transaction with an application user ID (username)

setsidAssociate current transaction with an application session ID

Logging actionsCc 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.ActionDescription

auditlogLog current transaction to audit log

logLog error message; implies auditlog

logdataLog supplied data as part of error message

noauditlogDo not log current transaction to audit log

nologDo not log error message; implies noauditlog

sanitiseArgRemove request parameter from audit log

sanitiseMatchedRemove parameter in which a match occurred from audit log

sanitiseRequestHeaderRemove request header from audit log

Special actions

ActionDescription

ctlChange configuration of current transaction

multiMatchActivate multi-matching, where an operator runs after every transformation

tSpecify transformation functions to apply to variables before matching

Miscellaneous ActionsActionDescription

appendAppend content to response body

execExecute external script

prependPrepend content to response body

statusSpecify response status code to use with denyand redirect

xmlnsSpecify name space for use with XPath expressions

X. RULE LANGUAGE TUTORIALTng quanTrong 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 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 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 "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 khng phi l mt biu thc so snh, bi v chng khng cha k t c bit xc 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 "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 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 SecRule ARGS:p|ARGS:q Ta c th s dng cu trc nh v d trn so trng bng mu biu thc, v d bn di s tm chui trong cc tham s bt u bng k t p:SecRule ARGS:/^p/ 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 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 chainSecRule ARGS:q Hng dn s dng ton t ph nhModSecurity 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: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" chainSecRule ARGS:q "!@eq 5"Variable CountingBng 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 actionHnh 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,denyMt 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:404Mt 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 DefaultsModSecurity 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:SecRule ARGS K1Khi ModSecurity hot ng, th rule trn s c hiu nh sau:SecRule ARGS K1 phase:2,log,auditlog,passBng 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:404SecRule ARGS K1SecRule ARGS K2...SecRule ARGS K99Unconditional RulesHnh 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=10Using Transformation FunctionsTrong 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,blockKt qu m ModSecurity s thc hin l lc nhng t kha c dng:delete fromDELETE FROMdeLeTe fRoMDelete FromDELETE\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.BlockingCc 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 FlowGi 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:2SecRule ARGS K2 id:2,nolog,passSecRule ARGS K3 id:3,log,blockVi 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-ElseTuy 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:SecRule ARGS K1 id:1,nolog,pass,skip:2SecRule ARGS K2 id:2,blockSecAction nolog,pass,skip:1SecRule ARGS K3 id:3,blockSecRule 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 DataCc 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.htmlYu 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 URISecRule 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 thcGi tr TX

^/Xc nh v tr thu thp d liu, bt u bng k t /.TX.0 = /69d032331009e7b0/

([0-9a-fA-f]{16})Ni dung SessionID l mt chui bao gm 16 k t s, ch thng, ch hoa (biu thc phi c t trong du ngoc n).TX.1 = 69d032331009e7b0

/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})/" "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 ManipulationHu 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#gi tr tx.score s tng 2 mi khi thc hin action.SecAction nolog,pass,setvar:tx.score=-1#gi tr tx.score s gim mi khi thc hin action.MetadataMetadata 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)$" \"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 TTrng 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 (OWASP-WS-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:SecDisableBackendCompressionSecContentInjecitonSecStreamOutBodyInspectionSecHashEngineSecHashKeySecHashParamSecHashMethodRxPhng 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.confSecContentInjection OnSecStreamOutBodyInspection OnSecHashEngine OnSecHashKey rand keyOnlySecHashParam rv_tokenSecHashMethodrx "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

Hnh 7: Cc lin kt sau khi thc hin to tokenTa 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 hpURL

Token hp lhttp://www.modsec.com/2013/05/owasp-top-10-tools-and-tactics/?rv_token=f3f6de81f7e3014ff6c4c6affce95caaca29e75e

Khng c tokenhttp://www.modsec.com/2013/05/owasp-top-10-tools-and-tactics/%20and%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 lTham 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: 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 actionTn 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/

Hnh 8: BurpSuite Sequencer moduleTrong 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:

Hnh 9: Cookie thu thp

Hnh 10: Kt qu thng kTheo 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 trModSecurity 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 "(.*)" "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 CFSIDTrong 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:# -=[ 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 SplitingTham kho DANH MC L HNG BO MT OWASP 2010: Testing for HTTP Splitting/Smuggling (OWASP-DV-016)Cc thnh phn tham kho OWASP ModSecurity CRS Modsecurity_Crs_40generic_attacks.conf ModSecurity REQUEST_URI variable REQUEST_BODY variable REQUEST_HEADERS variable XML variable @rx operatorPhng 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:

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

RESPONSEHTTP/1.1 302 FoundLocation: /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=englishCotent-Length: 0HTTP/1.1 200 OKContent-Type: text/htmlContent-Length: 171

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 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.# # -=[ 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])|Burp Suit, WebScarab, Paros

DV-010XPath Injection - XPath InjectionXPathInjectionUnlike SQL,there are not ACLs enforced, as our query can access every part of the XML document* Check for XML error enumeration by supplying a single quote (')* Username: ' or '1' = '1Password: ' or '1' = '1

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

The standard attack patterns are: Identifying vulnerable parameters Understanding the data flow and deployment structure of the client IMAP/SMTP command injection

DV-012Code Injection - Code InjectionCodeInjectionEnter commands in the input field

DV-013OS Commanding - OS CommandingOSCommandingUnderstand the application platform, OS, folder structure, relative path and execute thoseWebscarab

DV-014Buffer overflow - Buffer overflowBufferoverflow Testing for heap overflow vulnerability Testing for stack overflow vulnerability Testing for format string vulnerabilityOllyDbg, Spike, Brute Force Binary Tester (BFB), Metasploit. RATS, Flawfinder and ITS4 are available for analyzing C-style languages

DV-015Incubated vulnerability - Incubated vulnerabilityIncubatedvulnerabilityFile Upload, Stored XSS , SQL/XPATH Injection, Manage server files via server misconfigsXSS-proxy, Paros, Burp, Metasploit

DV-016Testing for HTTP Splitting/Smuggling - HTTP Splitting, SmugglingHTTPSplitting,SmugglingOutcome - Cache Poisoning/XSSparam=foobar%0d%0aContent-Length:%200%0d%0a%0d%0aHTTP/1.1%20200%20OK%0d%0aContent-Type:%20text/html%0d%0aContent-Length:%2035%0d%0a%0d%0aSorry,%20System%20Down

Denial of Service TestingDS-001Testing for SQL Wildcard Attacks - SQL Wildcard vulnerabilitySQLWildcard vulnerability Starting with % and ending with % will generally cause longer running queries. Some search implementations may cache search results. During the testing, every search query should be slightlydifferent to avoid this. '%_[^!_%/%a?F%_D)_(F%)_%([)({}%){()}$&N%_)$*()$*R"_)][%](%[x])%a][$*"$-9]_%' '%64_[^!_%65/%aa?F%64_D)_(F%64)_%36([)({}%33){()}$&N%55_)$*()$*R"_)][%55](%66[x])%ba][$*"$-9]_%54' bypasses modsecurity _[r/a)_ _(r/b)_ _(r-d)_ %n[^n]y[^j]l[^k]d[^l]h[^z]t[^k]b[^q]t[^q][^n]!% %_[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[! -z]@$!_%

DS-002Locking Customer Accounts - Locking Customer AccountsLockingCustomer AccountsWrong AttemptsValid Username enumeration - Login Page, New User Reg Page, Password Reset Page

DS-003Testing for DoS Buffer Overflows - Buffer OverflowsBufferOverflowsif you have received a response (or a lack of) that makes you believethat 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

DS-004User Specified Object Allocation - User Specified Object AllocationUserSpecifiedObjectAllocationIf theapplication does not pose an upper limit to the number of items that can be in any given moment inside the user electroniccart, you can write an automated script that keeps adding items to the user cart until the cart object fills the servermemory.

DS-005User Input as a Loop Counter - User Input as a Loop CounterUserInputasaLoopCounterif the user can directly or indirectly assign a value that will beused as a counter in a loop function, this can cause performance problems on the server.

DS-006Writing User Provided Data to Disk - Writing User Provided Data to DiskWritingUserProvidedDatatoDisk1. The tester submits an extremely long value to the server in the request, and the application logs the value directlywithout 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, butthen still log the failed value (for auditing or error tracking purposes) into an application log.

DS-007Failure to Release Resources - Failure to Release ResourcesFailuretoReleaseResources 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 thecase where an error causes normal logic flow to be circumvented, the allocated memory may not be removed andmay 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 suchrepeated requests can cause the application to consume all the DB connections, as the code will still hold the openDB object, never releasing the resource.

DS-008Storing too Much Data in Session - Storing too Much Data in SessionStoringtooMuchDatainSessionThe developer may have chosento 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 ofcaching the data within the session for each one. Let the script run for a while, and then observe the responsiveness of theapplication for new sessions. It may be possible that a Virtual Machine (VM) or even the server itself will begin to run out ofmemory because of this attack.

Web Services TestingWS-001WS Information Gathering - N.A.N.A.curl --request POST --header Content-type: text/xml--data @my_request.xml http://api.google.com/search/beta2* inurl:wsdl site:example.com* Web Services Discovery DISCO, UDDI* http://seekda.com* http://www.wsindex.org* http://www.soapclient.comNet Square wsPawn, SOAPClient4XG, CURL, Perl - SOAPlite, OWASP WebScarab: Web Services plugin, WSDigger

WS-002Testing WSDL - WSDL WeaknessWSDLWeaknessWebScarab, WSDigger

WS-003XML Structural Testing - Weak XML StructureWeakXMLStructure* A web service utilizing DOM-based parsing can be "upset" by including a very large payload in the XML message, which theparser would be obliged to parse* Binary attachments - Large BLOB* WSDigger contains sample attack plug-ins for SQL injection, XSS, XPATH injection attacksWebScarab, WSDigger

WS-004XML content-level Testing - XML content-levelXMLcontent-level1) SQL Injection or XPath injection 2) Buffer Overflow and 3) Command Injection.WebScarab, MetaSploit

WS-005HTTP GET parameters/REST Testing - WS HTTP GET parameters/RESTWSHTTPGETparameters/RESThttps://www.ws.com/accountinfo?accountnumber=12039475' exec master..xp_cmdshell 'net user Vxrpass /Add &userId=asi9485jfuhe92

WS-006Naughty SOAP attachments - WS Naughty SOAP attachmentsWSNaughtySOAPattachmentsAttach a test virus attachment using a non-destructive virus like EICAR, to a SOAP message and post to the target WebService.

WS-007Replay Testing - WS Replay TestingWSReplayTestingCapture the Traffic with sniffers/proxy and replay the requestWebScarab, Ethreal, WireShark, TCPReplay

Ajax TestingAJ-001AJAX Vulnerabilities - N.A.N.A.* XMLHttpRequest Vulnerabilitie, SQL Injectio, XSS, DOM based XSS, JSON/XML/XSLT Injection* AJAX Bridging - Cross website requests are sent through this method* Cross Site Request Forgery (CSRF)* DOS - Multiple XMLHttpRequests

AJ-002AJAX Testing - AJAX weaknessAJAX weaknessParse the HTML and JavaScript files andusing a proxy to observe traffic.Proxy tools, FirebugOWASP Sprajax

I. 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. . OWASP Testing Guide . 3rd ed. N.p.: OWASP Foundation, n.d.OWASP Testing Guide V3. 2010. Web. . "OWASP Based Web Application Security Testing Checklist."OWASP Based Web Application Security Testing Checklist. N.p., 19 Oct. 2011. Web.