Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Here is my compiled .htaccess for security. do you see anything wrong with it that needs to be corrected?

is there anything here that might mess up a legit website?

did I cover all the basics?

RewriteEngine on
Options +SymLinksIfOwnerMatch
Options -Indexes

# disable the server signature
ServerSignature Off

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
# mysql related
RewriteCond %{QUERY_STRING} union([^a]*a)+ll([^s]*s)+elect [NC,OR]
RewriteCond %{QUERY_STRING} (order).*(by).*(\%[0-9A-Z]{0,2}) [NC,OR]
RewriteCond %{QUERY_STRING} (waitfor|delay|shutdown).*(nowait) [NC,OR]
RewriteCond %{QUERY_STRING} (union|and|\^).*(select).*(ascii\(|bin\(|benchmark\(|cast\(|char\(|charset\(|collation\(|concat\(|concat_ws\(|table_schema) [NC,OR]
RewriteCond %{QUERY_STRING} (union|and|\^).*(select).*(conv\(|convert\(|count\(|database\(|decode\(|diff\(|distinct\(|elt\(}encode\(|encrypt\(|extract\() [NC,OR]
RewriteCond %{QUERY_STRING} (union|and|\^).*(select).*(field\(|floor\(|format\(|from|hex\(|if\(|in\(|information_schema|insert\(|instr\(|interval\(|lcase\() [NC,OR]
RewriteCond %{QUERY_STRING} (union|and|\^).*(select).*(left\(|length\(|load_file\(|locate\(|lock\(|log\(|lower\(|lpad\(|ltrim\(|max\(|md5\(|mid\() [NC,OR]
RewriteCond %{QUERY_STRING} (union|and|\^).*(select).*(mod\(|now\(|null\(|ord\(|password\(|position\(|quote\(|rand\(|repeat\(|replace\(|reverse\() [NC,OR]
RewriteCond %{QUERY_STRING} (union|and|\^).*(select).*(right\(|rlike\(|row_count\(|rpad\(|rtrim\(|_set\(|schema\(|sha1\(|sha2\(|sleep\(|soundex\() [NC,OR]
RewriteCond %{QUERY_STRING} (union|and|\^).*(select).*(space\(|strcmp\(|substr\(|substr_index\(|substring\(|sum\(|time\(|trim\(|truncate\(|ucase\() [NC,OR]
RewriteCond %{QUERY_STRING} (union|and|\^).*(select).*(unhex\(|upper\(|_user\(|user\(|values\(|varchar\(|version\(|xor\() [NC,OR]

# cookies
RewriteCond %{HTTP_COOKIE} (<|>|'|%0A|%0D|%27|%3C|%3E|%00) [NC,OR]
RewriteCond %{HTTP_COOKIE} (eval\%28|eval\%2528|eval\(|information_schema) [NC,OR]
RewriteCond %{HTTP_COOKIE} union([^a]*a)+ll([^s]*s)+elect [NC,OR]
RewriteCond %{HTTP_COOKIE} (union|and|\^).*(select).*(ascii\(|bin\(|benchmark\(|cast\(|char\(|charset\(|collation\(|concat\(|concat_ws\(|table_schema) [NC,OR]
RewriteCond %{HTTP_COOKIE} (union|and|\^).*(select).*(conv\(|convert\(|count\(|database\(|decode\(|diff\(|distinct\(|elt\(}encode\(|encrypt\(|extract\() [NC,OR]
RewriteCond %{HTTP_COOKIE} (union|and|\^).*(select).*(field\(|floor\(|format\(|from|hex\(|if\(|in\(|information_schema|insert\(|instr\(|interval\(|lcase\() [NC,OR]
RewriteCond %{HTTP_COOKIE} (union|and|\^).*(select).*(left\(|length\(|load_file\(|locate\(|lock\(|log\(|lower\(|lpad\(|ltrim\(|max\(|md5\(|mid\() [NC,OR]
RewriteCond %{HTTP_COOKIE} (union|and|\^).*(select).*(mod\(|now\(|null\(|ord\(|password\(|position\(|quote\(|rand\(|repeat\(|replace\(|reverse\() [NC,OR]
RewriteCond %{HTTP_COOKIE} (union|and|\^).*(select).*(right\(|rlike\(|row_count\(|rpad\(|rtrim\(|_set\(|schema\(|sha1\(|sha2\(|sleep\(|soundex\() [NC,OR]
RewriteCond %{HTTP_COOKIE} (union|and|\^).*(select).*(space\(|strcmp\(|substr\(|substr_index\(|substring\(|sum\(|time\(|trim\(|truncate\(|ucase\() [NC,OR]
RewriteCond %{HTTP_COOKIE} (union|and|\^).*(select).*(unhex\(|upper\(|_user\(|user\(|values\(|varchar\(|version\(|xor\() [NC,OR]

# LFI and session hijacking
RewriteCond %{QUERY_STRING} \=(\.\./\.\.//?)+ [OR]
RewriteCond %{QUERY_STRING} \=(\.\.//\./?)+ [OR]
RewriteCond %{QUERY_STRING} \=(\.\.\\\.\./?)+ [OR]
RewriteCond %{QUERY_STRING} \=(\.\.\\\\\./?)+ [OR]
RewriteCond %{QUERY_STRING} \/tmp\/sess_ [NC,OR]
RewriteCond %{QUERY_STRING} php:\/\/filter\/read=convert\.base64-(en|de)code\/ [NC,OR]

# BAD UAS
RewriteCond %{HTTP_USER_AGENT} @nonymouse|ADSARobot|amzn_assoc|Anarchie|ASPSeek|Atomz|^[^?]*addresses\.com|Advanced\ Email\ Extractor|ah-ha|aktuelles|almaden|Art-Online|AspiWeb|ASSORT|ATHENS|attach|attache|autoemailspider|BackWeb|Bandit|BatchFTP|bdfetch|big.brother|BlackWidow|bmclient|Boston\ Project|Bot\ mailto:craftbot@yahoo.com|BravoBrian\ SpiderEngine\ MarcoPolo|Buddy|Bullseye|bumblebee|capture|CherryPicker|ChinaClaw|CICC|clipping|Crescent\ Internet\ ToolPack|cURL|Custo|cyberalert|Deweb|diagem|Digger|Digimarc|DIIbot|DirectUpdate|DISCo|Download\ Accelerator|Download\ Demon|Download\ Wonder|Downloader|Drip|DSurf15a|DTS.Agent|EasyDL|eCatch|echo\ extense|ecollector|efp@gmx\.net|EirGrabber|EmailCollector|Email\ Extractor|EmailSiphon|EmailWolf|Express\ WebPictures|ExtractorPro|EyeNetIE|fastlwspider|FavOrg|Favorites\ Sweeper|Fetch\ API\ Request|FEZhead|FileHound|FlashGet|FlickBot|fluffy|frontpage|GalaxyBot|Generic|Getleft|GetRight|GetSmart|GetWeb!|GetWebPage|gigabaz|Girafabot|Go!Zilla|Go-Ahead-Got-It|GornKer|Grabber|GrabNet|Grafula|Green\ Research|Harvest|hhjhj@yahoo|hloader|HMView|HomePageSearch|HTTP\ agent|HTTPConnect|httpdown|http\ generic|HTTrack|^[^?]*iaea\.org|IBM_Planetwide|^[^?]*\.ideography\.co\.uk|Image\ Stripper|Image\ Sucker|imagefetch|IncyWincy|Indy\ Library|informant|Ingelin|InterGET|Internet\ Ninja|InternetLinkAgent|InternetSeer\.com|Iria|Irvine|iOpus|IPiumBot\ laurion(dot)com|Jakarta|JBH*Agent|JetCar|JustView|Kapere|KWebGet|Lachesis|larbin|LeechFTP|LexiBot|lftp|libwww|likse|Link*Sleuth|LINKS\ ARoMATIZED|LinkWalker|LWP|lwp-trivial|Magnet|Mac\ Finder|Mag-Net|Mass\ Downloader|MemoWeb|MCspider|Microsoft\ URL\ Control|MIDown\ tool|minibot\(NaverRobot\)|Mirror|Missigua\ Locator|Mister\ PiX|MMMtoCrawl\/UrlDispatcherLLL|MSProxy|multithreaddb|nationaldirectory|Navroad|NearSite|NetAnts|NetCarta|netfactual|netcraft|NetMechanic|netprospector|NetResearchServer|NetSpider|Net\ Vampire|NetZIP|NEWT|nicerspro|NPBot|Octopus|Offline\ Explorer|Offline\ Navigator|OpaL|Openfind|OpenTextSiteCrawler|OutWit|PackRat|PageGrabber|Papa\ Foto|pavuk|pcBrowser|PersonaPilot|PingALink|Pockey|Program\ Shareware|psbot|PSurf|puf|Pump|PushSite|QRVA|QuepasaCreep|RealDownload|Reaper|Recorder|ReGet|replacer|RepoMonkey|Robozilla|Rover|RPT-HTTPClient|Rsync|SearchExpress|searchhippo|searchterms\.it|Second\ Street\ Research|Shai|sitecheck|SiteMapper|SiteSnagger|SlySearch|SmartDownload|snagger|SpaceBison|Spegla|SpiderBot|SqWorm|Star\ Downloader|Stripper|Sucker|SuperBot|SuperHTTP|Surfbot|SurfWalker|Szukacz|tAkeOut|tarspider|Teleport\ Pro|Telesoft|Templeton|traffixer|TrueRobot|TuringOS|TurnitinBot|TV33_Mercator|UIowaCrawler|URL_Spider_Pro|UtilMind|Vacuum|vagabondo|vayala|visibilitygap|vobsub|VoidEYE|vspider|w3mir|web\.by\.mail|Web\ Data\ Extractor|Web\ Downloader|Web\ Image\ Collector|Web\ Sucker|WebAuto|webbandit|Webclipping|webcollector|webcollage|WebCopier|webcraft@bea|WebDAV|webdevil|webdownloader|Webdup|WebEmailExtractor|WebFetch|WebGo\ IS|WebHook|Webinator|WebLeacher|WebMiner|WebMirror|webmole|WebReaper|WebSauger|WEBsaver|Website\ eXtractor|Website\ Quester|WebSnake|Webster|WebStripper|websucker|webvac|webwalk|webweasel|WebWhacker|WebZIP|Wget|whizbang|WhosTalking|Widow|WISEbot|WUMPUS|Wweb|WWWOFFLE|Wysigot|Xaldon\ WebSpider|XGET|x-Tractor|Zeus.* [OR]

# SHELLS
RewriteCond %{REQUEST_URI} .*((php|my)?shell|remview.*|phpremoteview.*|sshphp.*|pcom|nstview.*|c99|r57|webadmin.*|phpget.*|phpwriter.*|fileditor.*|locus7.*|storm7.*)\.(p?s?x?htm?l?|txt|aspx?|cfml?|cgi|pl|php[3-9]{0,1}|jsp?|sql|xml) [NC,OR]
RewriteCond %{REQUEST_METHOD} (GET|POST) [NC]
RewriteCond %{QUERY_STRING} ^(.*)=/home(.+)?/(.*)/(.*)$ [OR]
RewriteCond %{QUERY_STRING} ^work_dir=.*$ [OR]
RewriteCond %{QUERY_STRING} ^command=.*&output.*$ [OR]
RewriteCond %{QUERY_STRING} ^nts_[a-z0-9_]{0,10}=.*$ [OR]
RewriteCond %{QUERY_STRING} ^c=(t|setup|codes)$ [OR]
RewriteCond %{QUERY_STRING} ^act=((about|cmd|selfremove|chbd|trojan|backc|massbrowsersploit|exploits|grablogins|upload.*)|((chmod|f)&f=.*))$ [OR]
RewriteCond %{QUERY_STRING} ^act=(ls|search|fsbuff|encoder|tools|processes|ftpquickbrute|security|sql|eval|update|feedback|cmd|gofile|mkfile)&d=.*$ [OR]
RewriteCond %{QUERY_STRING} ^&?c=(l?v?i?&d=|v&fnot=|setup&ref=|l&r=|d&d=|tree&d|t&d=|e&d=|i&d=|codes|md5crack).*$ [OR]
RewriteCond %{QUERY_STRING} ^(.*)([-_a-z]{1,15})=(ls|cd|cat|rm|mv|vim|chmod|chdir|mkdir|rmdir|pwd|clear|whoami|uname|tar|zip|unzip|tar|gzip|gunzip|grep|more|ln|umask|telnet|ssh|ftp|head|tail|which|mkmode|touch|logname|edit_file|search_text|find_text|php_eval|download_file|ftp_file_down|ftp_file_up|ftp_brute|mail_file|mysql|mysql_dump|db_query)([^a-zA-Z0-9].+)*$ [OR]
RewriteCond %{QUERY_STRING} ^(.*)(wget|shell_exec|passthru|system|exec|popen|proc_open)(.*)$

# if expose_php is set to on
RewriteCond %{QUERY_STRING} \=PHP[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12} [NC]

# others
RewriteCond %{REQUEST_METHOD} (GET|POST) [NC]
RewriteCond %{QUERY_STRING} ^(.*)(%20SELECT%20|%20INSERT%20|CHAR\(|%20UPDATE%20|%20REPLACE%20)(.*)$ [NC]

RewriteCond %{REQUEST_METHOD} (GET|POST) [NC]
RewriteCond %{QUERY_STRING} ^(.*)(%3C|<)/?script(.*)$ [NC,OR]
RewriteCond %{QUERY_STRING} ^(.*)(%3D|=)?javascript(%3A|:)(.*)$ [NC,OR]
RewriteCond %{QUERY_STRING} ^(.*)document\.location\.href(.*)$ [OR]

RewriteCond %{QUERY_STRING} ^(.*)(%3D|=|%3A|%09)http%3a(%3A|:)(/|%2F){2}(.*)$ [NC,OR]
RewriteCond %{QUERY_STRING} ^(.*)(%3D|=|%3A|%09)ftp(%3A|:)(/|%2F){2}(.*)$ [NC,OR]
RewriteCond %{QUERY_STRING} ^(.*)(%3D|=|%3A|%09)ht%20tp(%3A|:)(/|%2F){2}(.*)$ [NC,OR]
RewriteCond %{QUERY_STRING} ^(.*)(%3D|=|%3A|%09)htt%20p(%3A|:)(/|%2F){2}(.*)$ [NC,OR]
RewriteCond %{QUERY_STRING} ^(.*)(%3D|=|%3A|%09)http%20(%3A|:)(/|%2F){2}(.*)$ [NC,OR]
RewriteCond %{QUERY_STRING} ^(.*)(%3D|=|%3A|%09)h%20ttp(%3A|:)(/|%2F){2}(.*)$ [NC,OR]

RewriteCond %{QUERY_STRING} ^(.*)base64_encode(.*)$ [OR]
RewriteCond %{QUERY_STRING} ^(.*)GLOBALS(=|[|%[0-9A-Z]{0,2})(.*)$ [OR]
RewriteCond %{QUERY_STRING} ^(.*)_REQUEST(=|[|%[0-9A-Z]{0,2})(.*)$ [OR]
RewriteCond %{REQUEST_URI} ^(.*)_vti(.*)$ [OR]
RewriteCond %{REQUEST_URI} ^(.*)MSOffice(.*)$ [OR]
RewriteCond %{QUERY_STRING} ^(.*)/etc/passwd(.*)$ [OR]
RewriteCond %{QUERY_STRING} ^(.*)//(.*)$ [OR]
RewriteCond %{REQUEST_URI} ^(.*)ShellAdresi.TXT(.*)$ [OR]
RewriteCond %{REQUEST_URI} ^(.*)\[evil_root\]?(.*)$ [OR]
RewriteCond %{QUERY_STRING} ^(.*)\.\./\.\./\.\./(.*)$ [OR]
RewriteCond %{QUERY_STRING} ^(.*)/proc/self/environ(.*)$

RewriteCond %{QUERY_STRING} base64_encode.*\(.*\) [OR]
RewriteCond %{QUERY_STRING} http:.*\/.*\/ [OR]
RewriteCond %{QUERY_STRING} ..*\/ [OR]
RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
RewriteCond %{QUERY_STRING} [^a-z](declare|char|set|cast|convert|delete|drop|exec|insert|meta|script|select|truncate|update)[^a-z] [NC]

# Block out any script trying to set a mosConfig value through the URL
RewriteCond %{QUERY_STRING} mosConfig_[a-zA-Z_]{1,21}(=|\%3D) [OR]

# Block out any script trying to base64_encode crap to send via URL
RewriteCond %{QUERY_STRING} base64_encode.*\(.*\) [OR]

# Block out any script trying to set a mosConfig value through the URL
RewriteCond %{QUERY_STRING} mosConfig_[a-zA-Z_]{1,21}(=|\%3D) [OR]

# Block out any script trying to base64_encode crap to send via URL
RewriteCond %{QUERY_STRING} base64_encode.*\(.*\) [OR]

# Block out any script that includes a <script> tag in URL
RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]

# Block out any script trying to set a PHP GLOBALS variable via URL
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]

# Block out any script trying to modify a _REQUEST variable via URL
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})

# Send all blocked request to homepage with 403 Forbidden error!
RewriteRule ^(.*)$ - [F,L]

RewriteCond %{REQUEST_METHOD} ^(HEAD|TRACE|DELETE|TRACK) [NC,OR]
RewriteCond %{THE_REQUEST} ^.*(\\r|\\n|%0A|%0D).* [NC,OR]

RewriteCond %{HTTP_REFERER} ^(.*)(<|>|'|%0A|%0D|%27|%3C|%3E|).* [NC,OR]
RewriteCond %{HTTP_COOKIE} ^.*(<|>|'|%0A|%0D|%27|%3C|%3E|).* [NC,OR]
RewriteCond %{REQUEST_URI} ^/(,|;|:|<|>|">|"<|/|\\\.\.\\).{0,9999}.* [NC,OR]

RewriteCond %{HTTP_USER_AGENT} ^$ [OR]
RewriteCond %{HTTP_USER_AGENT} ^(java|curl|wget).* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^.*(winhttp|HTTrack|clshttp|archiver|loader|email|harvest|extract|grab|miner).* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^.*(libwww-perl|curl|wget|python|nikto|scan).* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^.*(<|>|'|%0A|%0D|%27|%3C|%3E|).* [NC,OR]

RewriteCond %{QUERY_STRING} ^.*(;|<|>|'|"|\)|%0A|%0D|%22|%27|%3C|%3E|).*(/\*|union|select|insert|cast|set|declare|drop|update|md5|benchmark).* [NC,OR]
RewriteCond %{QUERY_STRING} ^.*(localhost|loopback|127\.0\.0\.1).* [NC,OR]
#RewriteCond %{QUERY_STRING} ^.*\.[A-Za-z0-9].* [NC,OR]
RewriteCond %{QUERY_STRING} ^.*(<|>|'|%0A|%0D|%27|%3C|%3E|).* [NC]

RewriteCond %{REQUEST_METHOD} (GET) [NC]
RewriteCond %{QUERY_STRING} ^(.*)(%3D|=|%3A|%09)https(%3A|:)(/|%2F){2}(.*)$ [NC,OR]
RewriteCond %{QUERY_STRING} ^(.*)(%3D|=|%3A|%09)https%3a(%3A|:)(/|%2F){2}(.*)$ [NC,OR]
RewriteCond %{QUERY_STRING} ^(.*)(%3D|=|%3A|%09)http(%3A|:)(/|%2F){2}(.*)$ [NC]
RewriteRule .* - [F]

# Anti XSS protection
RewriteCond %{QUERY_STRING} base64_encode.*\(.*\) [OR]
RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} (\<|%3C).*iframe.*(\>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
RewriteRule ^(.*)$ index_error.php [F,L]
RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK)
RewriteRule .* - [F]

# Anti cross site tracing - protection
RewriteCond %{REQUEST_METHOD} ^TRACE 
RewriteRule .* - [F] 

RewriteCond %{QUERY_STRING} ^(.*)base64_encode(.*)$ [OR]
RewriteCond %{QUERY_STRING} ^(.*)GLOBALS(=|[|%[0-9A-Z]{0,2})(.*)$ [OR]
RewriteCond %{QUERY_STRING} ^(.*)_REQUEST(=|[|%[0-9A-Z]{0,2})(.*)$ [OR]
RewriteCond %{REQUEST_URI} ^(.*)_vti(.*)$ [OR]
RewriteCond %{REQUEST_URI} ^(.*)MSOffice(.*)$ [OR]
RewriteCond %{QUERY_STRING} ^(.*)/etc/passwd(.*)$ [OR]
RewriteCond %{QUERY_STRING} ^(.*)//(.*)$ [OR]
RewriteCond %{REQUEST_URI} ^(.*)ShellAdresi.TXT(.*)$ [OR]
RewriteCond %{REQUEST_URI} ^(.*)\[evil_root\]?(.*)$ [OR]
RewriteCond %{QUERY_STRING} ^(.*)\.\./\.\./\.\./(.*)$ [OR]
RewriteCond %{QUERY_STRING} ^(.*)/proc/self/environ(.*)$
RewriteRule .* - [F]

# Send all blocked request to homepage with 403 Forbidden error!
RewriteRule .* - [F]
# 
########## End - Rewrite rules to block out some common exploits

<FilesMatch "\.(htaccess|htpasswd|ini|phps|fla|psd|log|sh)$">
 Order Allow,Deny
 Deny from all
</FilesMatch>

<FilesMatch "(\.htaccess|\.htpasswd)$">
Order Allow,Deny
Deny from all
</FilesMatch>

# add whatever configuration files here that are hosted on your server that you want blocked
<FilesMatch "^(php\.ini|php5\.ini)$">
Order allow,deny
Deny from all
</FilesMatch>

# deny all .htaccess, .DS_Store $hî and ._* (resource fork) files
<Files ~ "^\.([Hh][Tt]|[Dd][Ss]_[Ss]|[_])">
 Order allow,deny
 Deny from all
 Satisfy All
</Files>

# deny access to all .log and .comment files
<Files ~ "^.*\.([Ll][Oo][Gg]|[cC][oO][mM][mM][eE][nN][tT])">
 Order allow,deny
 Deny from all
 Satisfy All
</Files>
share|improve this question
2  
<IfModule mod_rewrite.c>... So if the server admin has not enabled mod_rewrite, you want to just allow all this stuff? Seems like you might want to remove this, and let it be an error if the admin hasn't enabled mod_rewrite. –  stew Feb 7 '12 at 16:37

2 Answers 2

up vote 1 down vote accepted

The biggest problems with this are:

  1. It's far too large and far too complex.
  2. It's giving you a false sense of security.
  3. It will block legitimate users.

The problems with 1. are that it will cause excessive load on your server processing all those rules for every request and that when the rules are this complex, even the slightest change can have large consequences. Being extremely large also makes it very difficult to know the entire thing.

The problem with 2. (the false sense of security) is that you will take less care when writing server side code or you will be slower upgrading apps because you have this RewriteRule protection. More on why it's a false sense of security later.

I'm sure I don't have to tell you why blocking legitimate users is a problem.

To give some examples:

The second FilesMatch in the following snippet is redundant. Everything that could be blocked by the second is already blocked by the first:

<FilesMatch "\.(htaccess|htpasswd|ini|phps|fla|psd|log|sh)$">
 Order Allow,Deny
 Deny from all
</FilesMatch>

<FilesMatch "(\.htaccess|\.htpasswd)$">
Order Allow,Deny
Deny from all
</FilesMatch>

The FilesMatch following those two also redundantly matches .htaccess files yet again with this time with case insensitivity.

The second one here is also redundant:

RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK)
RewriteRule .* - [F]

# Anti cross site tracing - protection
RewriteCond %{REQUEST_METHOD} ^TRACE 
RewriteRule .* - [F]

Some lines are repeated verbatim. This one:

RewriteCond %{REQUEST_METHOD} (GET|POST) [NC]

Appears three times before the first RewriteRule.

You have lots of RewriteCond directives with [OR] after them but not all of them have this option. By my count, you have 79 RewriteConds, 10 of which don't have [OR] before your first RewriteRule. Keeping track of what will be allowed and what won't here is beyond my mental capacity.

Adding a new rule without an [OR] or adding a rule just before a RewriteRule and forgetting to add an [OR] to the previous RewriteCond can change the logic of all the other RewriteConds before and after it up to the next RewriteRule.


On the security side, some of the rules here are solid and some of them (such as the ones blocking .htaccess files from being served) are even included in the default Apache config files (which probably makes them redundant in your .htaccess), but many of them are based on blacklisting keywords and this will not work.

SQL injection attacks can happen in any user-controlled parameter. You have checked for a list of SQL-related keywords in %{QUERY_STRING} and %{HTTP_COOKIE} but you have missed %{REQUEST_URI}, %{HTTP_USER_AGENT}, %{HTTP­_RE­FERER}, %{HTTP­_FO­RWA­RDED}, %{HTTP­_HOST}, %{HTTP­_PR­OXY­_CO­NNE­CTION} and %{HTTP­_AC­CEPT}. That's not a complete list of user-controlled parameters by any means and attackers can happily add any headers they want to a request.

Blacklisting in this way is fundamentally flawed. If you are running parts of the query string as SQL you have far larger problems than this .htaccess file. There will always be a keyword you have missed or a way of encoding a keyword so that you miss it.

The following snippet is an example of this:

h%20ttp://
ht%20tp://
htt%20p://
http%20://

An attacker can put a URL-encoded space in the query string and it will still be parsed and requested correctly. But you have missed all of these combinations:

%20http://
h%20ttp%20://
ht%20tp%20://
htt%20p%20://
ht%20t%20p%20://
h%20t%20t%20p%20://

Since there are essentially an infinite number of "bad" strings, trying to enumerate them all in a .htaccess file is futile.

There are cheat sheets for SQL injection and XSS designed precisely to evade filtering of this sort.


Blocking legitimate users is surprisingly easy. Query strings can be appended on by all sorts of people. This example comes from my Google reader account and is added on to the link I click on to view the original blog entry:

?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+DilbertDailyStrip+(Dilbert+Daily+Strip)&utm_content=Google+Reader

If that RSS feed had been called "The Casting Couch" and linked to your site, you would serve me with a 403. Because the keyword "cast" appeared in the query string, even though I am a legitimate user, I'm blocked.

This pattern:

^(.*)//(.*)$

Is fairly likely to end up matching someone that you have sent to your site yourself and this one:

RewriteCond %{HTTP_COOKIE} (<|>|'|%0A|%0D|%27|%3C|%3E|%00) [NC,OR]

Means that you can never use an apostrophe or a carriage return or a slash in any of your cookies.

TL;DR

Don't do it. It's a bad idea.

Add security in your app and try mod_security.

share|improve this answer
    
Great write-up :) –  Shane Madden Feb 7 '12 at 21:09
    
Good points. Will look into using mod_sec instead. –  Mike Williams Feb 7 '12 at 21:16

This is not worth the time and effort; obfuscation, escaping, and any number of other code tricks can always defeat a simple blacklist.

This time is better spent on securing the application. But, if you are interested in this approach from the web server layer, you should instead look to have your rules be aware of the normal behavior of your web application and block any deviations from that behavior.

And, mod_security may be a more sanity-preserving approach than the leaning tower of mod_rewrite rules ;)

share|improve this answer
    
Would mod_sec be faster? Also, figured with .htaccess it would allow users to control/edit the rules on their own as well in case one was breaking something. –  Mike Williams Feb 7 '12 at 21:13

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.