htaccess Tricks #4 – Security
Prevent Acess to .htaccess
Add the following code block to your htaccess file to add an extra layer of security. Any attempts to access the htaccess file will result in a 403 error message. Of course, your first layer of defense to protect htaccess files involves setting htaccess file permissions via CHMOD to 644:
# secure htaccess file
<Files .htaccess>
order allow,deny
deny from all
</Files>
Prevent Acess to a Specific File
To restrict access to a specific file, add the following code block and edit the file name, “secretfile.jpg”, with the name of the file that you wish to protect:
# prevent viewing of a specific file
<files secretfile.jpg>
order allow,deny
deny from all
</files>
Prevent acess to multiple file types
To restrict access to a variety of file types, add the following code block and edit the file types within parentheses to match the extensions of any files that you wish to protect:
<FilesMatch “\.(htaccess|htpasswd|ini|phps|fla|psd|log|sh)$”>
Order Allow,Deny
Deny from all
</FilesMatch>
Prevent Unauthorized Directory Browsing
Prevent unauthorized directory browsing by instructing the server to serve a “xxx Forbidden – Authorization Required” message for any request to view a directory. For example, if your site is missing it’s default index page, everything within the root of your site will be accessible to all visitors. To prevent this, include the following htaccess rule:
# disable directory browsing
Options All -Indexes
Conversely, to enable directory browsing, use the following directive:
# enable directory browsing
Options All +Indexes
Likewise, this rule will prevent the server from listing directory contents:
# prevent folder listing
IndexIgnore *
And, finally, the IndexIgnore directive may be used to prevent the display of select file types:
# prevent display of select file types
IndexIgnore *.wmv *.mp4 *.avi *.etc
Change Default Index Page
This rule tells the server to search for and serve “business.html” as the default directory index. This rule must exist in the htaccess files of the root directory for which you wish to replace the default index file (e.g., “index.html”):
# serve alternate default index page
DirectoryIndex business.html
This rule is similar, only in this case, the server will scan the root directory for the listed files and serve the first match it encounters. The list is read from left to right:
# serve first available alternate default index page from series
DirectoryIndex filename.html index.cgi index.pl default.htm
Disguise Script Extensions
To enhance security, disguise scripting languages by replacing actual script extensions with dummy extensions of your choosing. For example, to change the “.foo” extension to “.php”, add the following line to your htaccess file and rename all affected files accordingly:
# serve foo files as php files
AddType application/x-httpd-php .foo
# serve foo files as cgi files
AddType application/x-httpd-cgi .foo
Limit Access to the Local Area Network (LAN)
# limit access to local area network
<Limit GET POST PUT>
order deny,allow
deny from all
allow from 192.168.0.0/33
</Limit>
Secure Directories by IP Address and/or Domain
In the following example, all IP addresses are allowed access except for 12.345.67.890 and domain.com:
# allow all except those indicated here
<Limit GET POST PUT>
order allow,deny
allow from all
deny from 12.345.67.890
deny from .*domain\.com.*
</Limit>
In the following example, all IP addresses are denied access except for 12.345.67.890 and domain.com:
# deny all except those indicated here
<Limit GET POST PUT>
order deny,allow
deny from all
allow from 12.345.67.890
allow from .*domain\.com.*
</Limit>
This is how to block unwanted visitors based on the referring domain. You can also save bandwidth by blocking specific file types — such as .jpg, .zip, .mp3, .mpg — from specific referring domains. Simply replace “scumbag” and “wormhole” with the offending domains of your choice:
# block visitors referred from indicated domains
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_REFERER} scumbag\.com [NC,OR]
RewriteCond %{HTTP_REFERER} wormhole\.com [NC,OR]
RewriteRule .* – [F]
</ifModule>
Prevent or allow domain access for a specified range of IP addresses
There are several effective ways to block a range of IP addresses via htaccess. This first method blocks an IP range specified by thier CIDR (Classless Inter-Domain Routing) number. This method is useful for blocking mega-spammers such as RIPE, Optinet, and others. If, for example, you find yourself adding line after line of Apache deny directives for addresses beginning with the same first few numbers, choose one of them and try a whois lookup. Listed within the whois results will be the CIDR value representing every IP address associated with that particular network. Thus, blocking via CIDR is an effective way to eloquently prevent all IP instances of the offender from accessing your site. Here is a generalized example for blocking by CIDR (edit values to suit your needs):
# block IP range by CIDR number
<Limit GET POST PUT>
order allow,deny
allow from all
deny from 10.1.0.0/16
deny from 80.0.0/8
</Limit>
Likewise, to allow an IP range by CIDR number:
# allow IP range by CIDR number
<Limit GET POST PUT>
order deny,allow
deny from all
allow from 10.1.0.0/16
allow from 80.0.0/8
</Limit>
Another effective way to block an entire range of IP addresses involves truncating digits until the desired range is represented. As an IP address is read from left to right, its value represents an increasingly specific address. For example, a fictitious IP address of 99.88.77.66 would designate some uniquely specific IP address. Now, if we remove the last two digits (66) from the address, it would represent any address beginning with the remaining digits. That is, 99.88.77 represents 99.88.77.1, 99.88.77.2, … 99.88.77.99, …etc. Likewise, if we then remove another pair of digits from the address, its range suddenly widens to represent every IP address 99.88.x.y, where x and y represent any valid set of IP address values (i.e., you would block 256*256 = 65,536 unique IP addresses). Following this logic, it is possible to block an entire range of IP addresses to varying degrees of specificity. Here are few generalized lines exemplifying proper htaccess syntax (edit values to suit your needs):
# block IP range by address truncation
<Limit GET POST PUT>
order allow,deny
allow from all
deny from 99.88.77.66
deny from 99.88.77.*
deny from 99.88.*.*
deny from 99.*.*.*
</Limit>
Likewise, to allow an IP range by address truncation:
# allow IP range by address truncation
<Limit GET POST PUT>
order deny,allow
deny from all
allow from 99.88.77.66
allow from 99.88.77.*
allow from 99.88.*.*
allow from 99.*.*.*
</Limit>
Block or allow multiple IP addresses on one line
Save a little space by blocking multiple IP addresses or ranges on one line. Here are few examples (edit values to suit your needs):
# block two unique IP addresses
deny from 99.88.77.66 11.22.33.44
# block three ranges of IP addresses
deny from 99.88 99.88.77 11.22.33
Likewise, to allow multiple IP addresses or ranges on one line:
# allow two unique IP addresses
allow from 99.88.77.66 11.22.33.44
# allow three ranges of IP addresses
allow from 99.88 99.88.77 11.22.33
Miscellaneous rules for blocking and allowing IP addresses
Here are few miscellaneous rules for blocking various types of IP addresses. These rules may be adapted to allow the specified IP values by simply changing the deny directive to allow. Check ’em out (edit values to suit your needs):
# block a partial domain via network/netmask values
deny from 99.1.0.0/255.255.0.0
# block a single domain
deny from 99.88.77.66
# block domain.com but allow sub.domain.com
order deny,allow
deny from domain.com
allow from sub.domain.com
Stop Hotlinking, Serve Alternate Content
To serve ‘em some unexpected alternate content when hotlinking is detected, employ the following code, which will protect all files of the types included in the last line (add more types as needed). Remember to replace the dummy path names with real ones. Also, the name of the nasty image being served in this case is “eatme.jpe”, as indicated in the line containing the RewriteRule. Please advise that this method will also block services such as FeedBurner from accessing your images.
# stop hotlinking and serve alternate content
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?domain\.com/.*$ [NC]
RewriteRule .*\.(gif|jpg)$ http://www.domain.com/eatme.jpe [R,NC,L]
</ifModule>
Note: To deliver a standard (or custom, if configured) error page instead of some nasty image of the Fonz, replace the line containing the RewriteRule in the above htaccess directive with the following line:
# serve a standard 403 forbidden error page
RewriteRule .*\.(gif|jpg)$ – [F,L]
Note: To grant linking permission to a site other than yours, insert this code block after the line containing the “domain.com” string. Remember to replace “goodsite.com” with the actual site domain:
# allow linking from the following site
RewriteCond %{HTTP_REFERER} !^http://(www\.)?goodsite\.com/.*$ [NC]
Block Evil Robots, Site Rippers, and Offline Browsers
Eliminate some of the unwanted scum from your userspace by injecting this handy block of code. After such, any listed agents will be denied access and receive an error message instead. Please advise that there are much more comprehensive lists available this example has been truncated for business purposes. Note: DO NOT include the “[OR]” on the very last RewriteCond or your server will crash, delivering “500 Errors” to all page requests.
# deny access to evil robots site rippers offline browsers and other nasty scum
RewriteBase /
RewriteCond %{HTTP_USER_AGENT} ^Anarchie [OR]
RewriteCond %{HTTP_USER_AGENT} ^ASPSeek [OR]
RewriteCond %{HTTP_USER_AGENT} ^attach [OR]
RewriteCond %{HTTP_USER_AGENT} ^autoemailspider [OR]
RewriteCond %{HTTP_USER_AGENT} ^Xaldon\ WebSpider [OR]
RewriteCond %{HTTP_USER_AGENT} ^Xenu [OR]
RewriteCond %{HTTP_USER_AGENT} ^Zeus.*Webster [OR]
RewriteCond %{HTTP_USER_AGENT} ^Zeus
RewriteRule ^.* – [F,L]
Or, instead of delivering a friendly error message (i.e., the last line), send these bad boys to the hellish website of your choice by replacing the RewriteRule in the last line with one of the following two examples:
# send em to a hellish website of your choice
RewriteRule ^.*$ http://www.hellish-website.com [R,L]
Or, to send em to a virtual blackhole of fake email addresses:
# send em to a virtual blackhole of fake email addresses
RewriteRule ^.*$ http://english-61925045732.spampoison.com [R,L]
You may also include specific referrers to your blacklist by using HTTP_REFERER. Here, we use the infamously scummy domain, “iaea.org” as our blocked example, and we use “yourdomain” as your domain (the domain to which you are blocking iaea.org):
RewriteCond %{HTTP_REFERER} ^http://www.iaea.org$
RewriteRule !^http://[^/.]\.yourdomain\.com.* – [F,L]
More Stupid Blocking Tricks
Note: Although these redirect techniques are aimed at blocking and redirecting nasty scumsites, the directives may also be employed for friendly redirection purposes:
# redirect any request for anything from spamsite to differentspamsite
RewriteCond %{HTTP_REFERER} ^http://.*spamsite.*$ [NC]
RewriteRule .* http://www.differentspamsite.com [R]
# redirect all requests from spamsite to an image of something at differentspamsite
RewriteCond %{HTTP_REFERER} ^http://.*spamsite.*$ [NC]
RewriteRule .* http://www.differentspamsite/something.jpg [R]
# redirect traffic from a certain address or range of addresses to another site
RewriteCond %{REMOTE_ADDR} 192.168.10.*
RewriteRule .* http://www.differentspamsite.com/index.html [R]
Even More Scum-Blocking Tricks
Here is a step-by-step series of code blocks that should equip you with enough knowledge to block any/all necessary entities. Read through the set of code blocks, observe the patterns, and then copy, combine and customize to suit your specific scum-blocking needs:
# set variables for user agents and referers and ip addresses
SetEnvIfNoCase User-Agent “.*(user-agent-you-want-to-block|php/perl).*” BlockedAgent
SetEnvIfNoCase Referer “.*(block-this-referrer|and-this-referrer|and-this-referrer).*” BlockedReferer
SetEnvIfNoCase REMOTE_ADDR “.*(666.666.66.0|22.22.22.222|999.999.99.999).*” BlockedAddress
# set variable for any class B network coming from a given netblock
SetEnvIfNoCase REMOTE_ADDR “66.154.*” BlockedAddress
# set variable for two class B networks 198.25.0.0 and 198.26.0.0
SetEnvIfNoCase REMOTE_ADDR “198.2(5|6)\..*” BlockedAddress
# deny any matches from above and send a 403 denied
<Limit GET POST PUT>
order deny,allow
deny from env=BlockedAgent
deny from env=BlockedReferer
deny from env=BlockedAddress
allow from all
</Limit>
Password-Protect Directories
Here is an excellent online tool for generating the necessary elements for a password-protected directory:
# password protect directories
htaccess Password Generator
Password-protect Files, Directories, and More..
Secure site contents by requiring user authentication for specified files and/or directories. The first example shows how to password-protect any single file type that is present beneath the directory which houses the htaccess rule. The second rule employs the FilesMatch directive to protect any/all files which match any of the specified character strings. The third rule demonstrates how to protect an entire directory. The fourth set of rules provides password-protection for all IP’s except those specified. Remember to edit these rules according to your specific needs.
# password-protect single file
<Files secure.php>
AuthType Basic
AuthName “Prompt”
AuthUserFile /home/path/.htpasswd
Require valid-user
</Files>
# password-protect multiple files
<FilesMatch “^(execute|index|secure|insanity|biscuit)*$”>
AuthType basic
AuthName “Development”
AuthUserFile /home/path/.htpasswd
Require valid-user
</FilesMatch>
# password-protect the directory in which this htaccess rule resides
AuthType basic
AuthName “This directory is protected”
AuthUserFile /home/path/.htpasswd
AuthGroupFile /dev/null
Require valid-user
# password-protect directory for every IP except the one specified
# place in htaccess file of a directory to protect that entire directory
AuthType Basic
AuthName “Personal”
AuthUserFile /home/path/.htpasswd
Require valid-user
Allow from 99.88.77.66
Satisfy Any
Require SSL (Secure Sockets Layer)
Here is an excellent method for requiring SSL (via askapache.com 3):
# require SSL
SSLOptions +StrictRequire
SSLRequireSSL
SSLRequire %{HTTP_HOST} eq “domain.tld”
ErrorDocument 403 https://domain.tld
# require SSL without mod_ssl
RewriteCond %{HTTPS} !=on [NC]
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
Automatically CHMOD Various File Types
This method is great for ensuring the CHMOD settings for various file types. Employ the following rules in the root htaccess file to affect all specified file types, or place in a specific directory to affect only those files (edit file types according to your needs):
# ensure CHMOD settings for specified file types
# remember to never set CHMOD 777 unless you know what you are doing
# files requiring write access should use CHMOD 766 rather than 777
# keep specific file types private by setting their CHMOD to 400
chmod .htpasswd files 640
chmod .htaccess files 644
chmod php files 600
Disguise all file extensions
This method will disguise all file types (i.e., any file extension) and present them as .php files (or whichever extension you choose):
# diguise all file extensions as php
ForceType application/x-httpd-php
Protect against denial-of-service (DOS) attacks by limiting file upload size
One method to help protect your server against DOS attacks involves limiting the maximum allowable size for file uploads. Here, we are limiting file upload size to 10240000 bytes, which is equivalent to around 10 megabytes. For this rule, file sizes are expressed in bytes. Check here for help with various file size conversions. Note: this code is only useful if you actually allow users to upload files to your site.
# protect against DOS attacks by limiting file upload size
LimitRequestBody 10240000
Secure directories by disabling execution of scripts
Prevent malicious brainiacs from actively scripting secure directories by adding the following rules to the representative htaccess file (edit file types to suit your needs):
# secure directory by disabling script execution
AddHandler cgi-script .php .pl .py .jsp .asp .htm .shtml .sh .cgi
Options -ExecCGI
Related Posts:
Tags: htaccess, Security, Tricks
16.Oct.08
Server
You can leave a response, or trackback from your own site.
[...] (VLAN) yang diharapkan dapat memberikan hasil yang lebih baik dibanding Local area Network [...]
[...] konsep Virtual Local Area Network (VLAN) yang diharapkan dapat memberikan hasil yang lebih baik dibanding Local area Network [...]