Povezava: http://www.modsecurity.org/


ModSecurity je “Web Aplication Firewall” (WAF), ki nudi zaščito pred širokim razponom spletnih napadov in omogoča analizo, ter spremljanje HTTP prometa.

Avtor programa je Ivan Ristić.


Pred čim ščiti ModSecurity?

– Zaznava zahteve zlonamernih avtomatiziranih programov, kot so roboti, varnostni skenerji, pajki…

– SQL injections

– XSS (Cross Site Scripting)

– File name injection

– Zaznavanje trojanskih konjev in stranskih vrat

– Remote commnad access in OS commands injection




* Za demonstracijo bomo naložili modsecurity na operacijski sistem Debian 6.

1. Namestitev paketa:

apt-get install libapache-mod-security


2.Sedaj bomo naredili direktorij v katerega bomo shranili “mod-security rules”, na podlagi katerih apache filtrira in blokira zahteve.

mkdir /etc/apache2/mod_security


3. Prenesemo mod-security rules iz interneta:

cd /tmp


wget http://www.modsecurity.org/download/modsecurity-core-rules_2.5-1.6.1.tar.gz


4.Razpakiramo paket z ukazom:

tar zxvf modsecurity-core-rules_2.5-1.6.1.tar.gz

z ukazom “ls” pregledamo vsebino:



Datoteke z končnico “.conf” vsebujejo konfiguracije za filtriranje in blokiranje raznih napadov.


5. Pravila sedaj prenesemo v naš direktorij “/etc/apache2/mod_security”, ki smo ga skreirali predhodno.

mv *.conf /etc/apache2/mod_security/


6. Če želimo, da bo apache uporabljal mod_security, mu moramo to povedati. To storimo tako, da v “/etc/apache2/conf.d/” kreiramo konfiguracijsko datoteko.

vi /etc/apache2/conf.d/mod_security.conf

V datoteko mod_security.conf vpišemo naslednje:

Include /etc/apache2/mod_security/*.conf


7.Delovanje mod_security in glavna konfiguracija je shranjena v datoteki “/etc/apache2/mod_security/modsecurity_crs_10_config.conf“. Datoteko odprete z “vi editorjem”.

Pri “SecDefaultAction” odstranimo “#”. S tem smo nastavili, da bo v primeru napada ali “sumljivih” poskusov, strežnik zavrnil zahtevo in sporočil napako.

## — Configuration ———————————————————-

# Turn ModSecurity on (“On”), set to monitoring only
# (“DetectionOnly”) or turn off (“Off”).
SecRuleEngine On

# Define which part of the HTTP transaction to inspect.
# Inspecting request body (SecRequestBodyAccess) should probably be always set
# to “on”. Only very high volume sites that never use POST requests might want
# to set it to “off” to optimize performance.
# Inspecting response body is useful for monitoring for information leaks,
# or for signs of intrusion. However, it does require all responses to be
# buffered in memory. For most sites this should not be a problem, but special
# care must be taken to avoid buffering file downloads (through
# MIME type selection, as shown below).
# TODO If you decide to enable output filtering make sure to
#      review the list of scanned MIME types. If pages of the types specified
#      for outbound inspection are smaller than 512K in you application
#      (which is usually the case) you may reduce the SecResponseBodyLimit
#      to protect from potential denial of service attacks.
SecRequestBodyAccess On
SecResponseBodyAccess On
SecResponseBodyMimeType (null) text/html text/plain text/xml
SecResponseBodyLimit 524288

# Initiate XML Processor in case of xml content-type
# TODO Uncomment this rule if you wish to parse
#      text/xml requests using the XML parser.  Note
#      that this may cause considerable overhead in processing
#      text/xml requests.
#SecRule REQUEST_HEADERS:Content-Type “text/xml”

# What to do when an error is encountered.
# The default is to log the error and let the request go through.
# This is a reasonable setting to start with because you do not
# want to reject legitimate requests with an untuned rule set.
# If, after monitoring the performance of the rule set after a
# sufficient period, you determine the rules never (or rarely
# trigger on legitimate requests) you can change to something
# else, such as “log,deny,status:403”. You can also leave the
# default setting here as is, but use per rule action configuration
# to only configure some rules to reject requests, leaving most
# of them to work in detection mode.
SecDefaultAction “phase:2,log,deny,status:403,t:lowercase,t:replaceNulls,t:compressWhitespace”

# Set web server identification string
# TODO In case you use Apache, you may want specify a simple server signature
#      instead of the detailed Apache default signature that list most modules
#      used on the specific Apache deployment:
#      “Apache/2.2.0 (Fedora)”



175 # Log files structure
176 #
177 # You can select to log all events to a single log file (set SecAuditLogType to
178 # “Serial”) or to log each request to a separate file (set it to “Concurrent”).
179 # The former is usually easier to use, but if full logging is required or if
180 # the protected system supports a large transaction volume the later may
181 # be a better option.
182 #
183 # TODO Set the SecAuditLog (for “Serial” logging) or SecAuditLogStorageDir (for
184 #      “Concurrent” logging).
185 #
186 # TODO If you change from “Serial” to “Concurrent” uncomment the
187 #      SecAuditLogStorageDir directive and make sure the direcory specified
188 #      exists and has write permissions for the Apache user.
190 SecAuditLogType Serial
191 SecAuditLog /var/log/modsec_audit.log
192 # SecAuditLogStorageDir logs/modsec_audit




276 # Whether to send ModSecurity messages to a separate debug log.
277 #
278 # Debug messages are very useful for, well, debugging. The default
279 # setting here copies (they always appear in the Apache error log)
280 # only the most important messages (errors and warnings).
281 #
282 # NOTE Debug logging is generally very slow. You should never
283 #      use values greater than “3” in production.
284 #
285 SecDebugLog             /var/log/modsec_debug.log
286 SecDebugLogLevel        3
288 # Path where persistent data (e.g. IP address data, session data, etc) is to
289 # be stored. Must be writable by the web server user.
290 #
291 # TODO It is advisable to create a directory structure for ModSecurity such as
292 #      /var/log/msa and create sub directories for SecDataDir, SecTmpDir,
293 #      SecUploadDir, SecAuditLog and SecAuditLogStorageDir
294 #      underneath it and set the permission for read and write only by the
295 #      Apache user.



8. Sedaj moramo samo še ponovno zagnati apache servis:

service apache2 restart

Laho uporabite tudi apache frontend “apachectl”

apachectl restart


Sedaj vaš spletni strežnik varuje mod-security.


Kako izklopiti mod_security?

V apache”sites-available/default” konfiguracijo dodamo naslednje:

<IfModule mod_security2.c>
SecRuleEngine Off

SecRuleEngine Off (modsecurity ugasnjen). Primer:

<VirtualHost *:80>
ServerAdmin webmaster@localhost

DocumentRoot /var/www/mojaizmisljenastran
ServerAlias www.mojaizmisljenastran.si
<Directory />
Order Deny,Allow
Deny from all
Options none
AllowOverride None
<Directory /var/www/mojaizmisljenastran>
Options FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all

ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory “/usr/lib/cgi-bin”>
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Deny from all
<Directory /var/www/mojaizmisljenastran/administrator>
Allowoverride All

ErrorLog ${APACHE_LOG_DIR}/error.log

# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn

CustomLog ${APACHE_LOG_DIR}/access.log combined

Alias /doc/ “/usr/share/doc/”
<Directory “/usr/share/doc/”>
Options Indexes MultiViews FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
Allow from ::1/128

<IfModule mod_security2.c>
SecRuleEngine Off



Kako onemogočimo samo določena pravila?


Vsi dogodki, ki jih obravnava modsecurity se shranjujejo v dnevnik. V našem primeru smo dnevnik nastavili v “/var/log/modsec_audit.log”.

Primer izpisa:(poskus SQL injection):

Če želimo onemogočiti “rule”, moramo poiskati njegov ID (v našem primeru je to [id “950001”])

[16/Jul/2012:21:08:53 +0200] UAO@X8AAQEAAGU@EjAAAAL 2658 80
GET /?lastname=chapple&firstname=admin’+AND+(select+count(*)+from+fake)+%3e0+OR+’1’%3d’1 HTTP/1.1
Host: www.mojaizmisljenastran.si
Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: gzip,deflate,sdch
Accept-Language: sl-SI,sl;q=0.8,en-GB;q=0.6,en;q=0.4
Accept-Charset: ISO-8859-2,utf-8;q=0.7,*;q=0.3
Cookie: 8c3ef7aeef482dfd95e2c936=m5cvmv8m3e92esa2c6c9q0o258bg3; __utma=122055817.1876129464.1336821048.1340200248.1342420540.24; __utmb=122055817.24.10.1342420540; __utmc=122055817; __utmz=122055817.1337168390.13.3.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)

HTTP/1.1 403 Forbidden
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 179
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=iso-8859-1

Message: Access denied with code 403 (phase 2). Pattern match “(?:b(?:(?:s(?:electb(?:.{1,100}?b(?:(?:length|count|top)b.{1,100}?bfrom|fromb.{1,100}?bwhere)|.*?b(?:d(?:umpb.*bfrom|ata_type)|(?:to_(?:numbe|cha)|inst)r))|p_(?:(?:addextendedpro|sqlexe)c|(?:oacreat|prepar)e|execute(?:sql)?|makewebtask)|ql_(? …” at ARGS:firstname. [file “/etc/apache2/modsecurity/modsecurity_crs_40_generic_attacks.conf”] [line “66”] [id “950001”] [msg “SQL Injection Attack”] [data “select count(*) from”] [severity “CRITICAL”] [tag “WEB_ATTACK/SQL_INJECTION”]
Action: Intercepted (phase 2)
Stopwatch: 1342422533184603 5972 (2604 4268 -)
Producer: ModSecurity for Apache/2.5.12 (http://www.modsecurity.org/); core ruleset/1.6.1; core ruleset/1.6.1.
Server: Apache


Sedaj ko poznamo ID pravila, ustvarimo novo datoteko v /etc/apache2/mod_security/. Ime je lahko poljubno.

vi /etc/apache2/mod_security/onemogocena_pravila.conf

V datoteteko vpišemo naslednje parametre:

<IfModule security2_module>
<Directory /var/www/mojaizmisljenastran/>
SecRuleRemoveById 950001

Pravilo 950001 smo onemogočili z sintakso “SecRuleRemoveById” . (To je samo primer onemogočanja pravil! SQL injection pravil ni priporočjivo izklapljati!!!).


Kako testiramo ali modsecurity deluje?

Napad na spletno stran lahko testiramo z preprostim SQL injection. Primer napada preko brskalnika.:


http://www.mojaizmisljenastran.si/?id=hi’ or 1=1–


V tem primeru smo se poizkusili prijaviti na spletno stran z SQL queryom. Če bi bila stran ranljiva, bi dobili dostop brez gesla in uporabniškega imena.

Ker nas varuje modsecurity dobimo tak odgovor:

Iz spleta si lahko prenesete zastonj knjigo ModSecurity Handbook: Getting Started Guide, ki vam bo pomagala, da lažje prebrodite težak začetek.

3 Responses to Apache modsecuirty

Leave a Reply

Your email address will not be published. Required fields are marked *


Internetna zaščita

Copyright © 2013. All Rights Reserved.