Difference between revisions of "Short Notes on Security"

From PaskvilWiki
Jump to: navigation, search
(Apache)
(.htaccess and mod_rewrite Tricks)
Line 42: Line 42:
 
to '''/etc/apache2/ports.conf''' and restart Apache.
 
to '''/etc/apache2/ports.conf''' and restart Apache.
  
=== <tt>.htaccess</tt> and <tt>mod_rewrite</tt> Tricks ===
+
=== .htaccess and mod_rewrite Tricks ===
  
 
Mostly based on [http://www.queness.com/post/5421/17-useful-htaccess-tricks-and-tips 17 Useful .htaccess Tricks and Tips]
 
Mostly based on [http://www.queness.com/post/5421/17-useful-htaccess-tricks-and-tips 17 Useful .htaccess Tricks and Tips]
Line 50: Line 50:
 
'''1. Set Timezone'''
 
'''1. Set Timezone'''
 
-----
 
-----
 +
 +
<pre>SetEnv TZ Australia/Melbourne</pre>
 +
[http://www.php.net/manual/en/timezones.php List of timezones].
  
 
'''2. SEO Friendly 301 Permanent Redirects'''
 
'''2. SEO Friendly 301 Permanent Redirects'''
 
-----
 
-----
 +
 +
Modern search engines have the capability to detect 301 Permanent Redirects and update its existing records.
 +
 +
<pre>Redirect 301 http://www.domain.com/home http://www.domain.com/</pre>
  
 
'''3. Skip the Download Dialogue'''
 
'''3. Skip the Download Dialogue'''
 
-----
 
-----
 +
 +
The following defines given types as octet-stream, thus making it "only to download"; clicking the link to such resource will skip "open / save" dialog and will start download immediately.
 +
 +
<pre>AddType application/octet-stream .pdf
 +
AddType application/octet-stream .zip
 +
AddType application/octet-stream .mov</pre>
  
 
'''4. Skip or Force www.'''
 
'''4. Skip or Force www.'''
 
-----
 
-----
 +
 +
One of the SEO guidelines is, make sure there is only one URL pointing to your website.
 +
 +
To force URL's without www.:
 +
 +
<pre>RewriteEngine On
 +
RewriteBase /
 +
RewriteCond %{HTTP_HOST} ^www.domain.com [NC]
 +
RewriteRule ^(.*)$ http://domain.com/$1 [L,R=301]</pre>
 +
 +
To force www. in the URL:
 +
 +
<pre>RewriteEngine On
 +
RewriteBase /
 +
RewriteCond %{HTTP_HOST} ^domain.com [NC]
 +
RewriteRule ^(.*)$ http://www.domain.com/$1 [L,R=301]</pre>
  
 
'''5. Custom Error Pages'''
 
'''5. Custom Error Pages'''
 
-----
 
-----
 +
 +
<pre>ErrorDocument 401 /error/401.php
 +
ErrorDocument 403 /error/403.php
 +
ErrorDocument 404 /error/404.php
 +
ErrorDocument 500 /error/500.php</pre>
  
 
'''6. Compress Files'''
 
'''6. Compress Files'''
 
-----
 
-----
 +
 +
You need to have <tt>deflate</tt> module installed and enabled.
 +
 +
<pre>AddOutputFilterByType DEFLATE text/plain
 +
AddOutputFilterByType DEFLATE text/html
 +
AddOutputFilterByType DEFLATE text/xml
 +
AddOutputFilterByType DEFLATE text/css
 +
AddOutputFilterByType DEFLATE application/xml
 +
AddOutputFilterByType DEFLATE application/xhtml+xml
 +
AddOutputFilterByType DEFLATE application/rss+xml
 +
AddOutputFilterByType DEFLATE application/javascript
 +
AddOutputFilterByType DEFLATE application/x-javascript</pre>
  
 
'''7. Cache Files'''
 
'''7. Cache Files'''
 
-----
 
-----
 +
 +
The following example sets caching of multimedia files to 30 days:
 +
 +
<pre><FilesMatch ".(flv|gif|jpg|jpeg|png|ico|swf|js|css|pdf)$">
 +
  Header set Cache-Control "max-age=2592000"
 +
</FilesMatch></pre>
  
 
'''8. Disable Caching for Certain File Type'''
 
'''8. Disable Caching for Certain File Type'''
 
-----
 
-----
 +
 +
The following example disables caching of scripts:
 +
 +
<pre><FilesMatch ".(pl|php|cgi|spl|scgi|fcgi)$">
 +
  Header unset Cache-Control
 +
</FilesMatch></pre>
  
 
'''9. Redirect (Sections) to https://'''
 
'''9. Redirect (Sections) to https://'''
 
-----
 
-----
 +
 +
The following forces /login and /signup sections of your site to use https.
 +
 +
Of course, it's recommendable that you have a signed SSL certificate.
 +
 +
<pre>RewriteEngine on
 +
RewriteCond %{HTTPS} =off
 +
RewriteCond %{REQUEST_URI} /login [NC,OR]
 +
RewriteCond %{REQUEST_URI} /signup [NC]
 +
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]</pre>
  
 
'''10. Simple MVC using .htaccess'''
 
'''10. Simple MVC using .htaccess'''
 
-----
 
-----
  
redirect all on handler script and act according to the request_uri
+
You can redirect all requests to a single script file, and serve content based on REQUEST_URI:
 +
 
 +
<pre>RewriteEngine On
 +
RewriteRule !robots\.txt|\.(js|ico|gif|jpg|png|css|flv|swf)$ index.php</pre>
  
 
'''11. Provide Different Page Versions based on User Agent'''
 
'''11. Provide Different Page Versions based on User Agent'''
 
-----
 
-----
  
redirect to light, full, ...
+
You can provide different versions of your site for different browsers (e.g. ''links'' as a text-based browser, and for mobile devices):
 +
 
 +
<pre>RewriteEngine On
 +
 
 +
# MSIE
 +
RewriteCond %{HTTP_USER_AGENT} ^Mozilla/4(.*)MSIE
 +
RewriteRule ^index\.html$ /index.ie.html [L]
 +
 
 +
# Netscape / Mozilla
 +
RewriteCond %{HTTP_USER_AGENT} ^Mozilla/5(.*)Gecko
 +
RewriteRule ^index\.html$ /index.full.html [L]
 +
 
 +
# Lynx, text based
 +
RewriteCond %{HTTP_USER_AGENT} ^Lynx/
 +
RewriteRule ^index\.html$ /index.light.html [L]
 +
 
 +
# Mobile version of your site
 +
RewriteCond %{HTTP_USER_AGENT} ^.*(iPad|iPhone).*$
 +
RewriteRule ^(.*)$ http://ipad.domain.com [R=301]
 +
 
 +
# All other
 +
RewriteRule ^index\.html$ /index.medium.html [L]</pre>
  
 
==== Security ====
 
==== Security ====
Line 89: Line 181:
 
'''1. Hotlinking Protection with .htaccess'''
 
'''1. Hotlinking Protection with .htaccess'''
 
-----
 
-----
 +
 +
Block all multimedia file requests that do not come from direct link or from your site:
 +
 +
<pre>RewriteEngine On
 +
RewriteCond %{HTTP_REFERER} !^$
 +
RewriteCond %{HTTP_REFERER} !^http://(www.)?domain.com/.*$ [NC]
 +
RewriteRule .(gif|jpg|swf|flv|png)$ /no-hotlink.html [R=302,L]</pre>
  
 
'''2. Prevent Hacks'''
 
'''2. Prevent Hacks'''
 
-----
 
-----
 +
 +
Block some common malicious URL hacks:
 +
 +
<pre>RewriteEngine On
 +
 +
# proc/self/environ? no way!
 +
RewriteCond %{QUERY_STRING} proc/self/environ [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 page with 403 Forbidden error!
 +
RewriteRule ^(.*)$ no-way.html [F,L]</pre>
  
 
'''3. Block Access to Your .htaccess File'''
 
'''3. Block Access to Your .htaccess File'''
 
-----
 
-----
 +
 +
<pre># secure .htaccess file
 +
<Files .htaccess>
 +
  Order Allow,Deny
 +
  Deny from All
 +
</Files>
 +
 +
# prevent viewing of a specific file
 +
<Files secretfile.jpg>
 +
  Order Allow,Deny
 +
  Deny from All
 +
</Files>
 +
 +
# multiple files / file types
 +
<FilesMatch ".(htaccess|htpasswd|ini|phps|fla|psd|log|sh)$">
 +
  Order Allow,Deny
 +
  Deny from All
 +
</FilesMatch></pre>
  
 
'''4. Rename .htaccess Files'''
 
'''4. Rename .htaccess Files'''
 
-----
 
-----
 +
 +
<pre>AccessFileName htacc.ess</pre>
  
 
'''5. Disable Directory Browsing'''
 
'''5. Disable Directory Browsing'''
 
-----
 
-----
 +
 +
<pre># disable directory browsing
 +
Options All -Indexes
 +
 +
# enable directory browsing
 +
Options All +Indexes</pre>
  
 
'''6. Change Default Index Page'''
 
'''6. Change Default Index Page'''
 
-----
 
-----
 +
 +
<pre>DirectoryIndex my-home.html</pre>
  
 
'''7. Block Unwanted Visitor based on Referring Domain'''
 
'''7. Block Unwanted Visitor based on Referring Domain'''
 
-----
 
-----
 +
 +
<pre># block visitors referred from indicated domains
 +
RewriteEngine on
 +
RewriteCond %{HTTP_REFERER} scumbag.com [NC,OR]
 +
RewriteCond %{HTTP_REFERER} wormhole.com [NC,OR]
 +
RewriteRule .* - [F]</pre>
  
 
'''8. Blocking Request based on User-Agent Header'''
 
'''8. Blocking Request based on User-Agent Header'''
 
-----
 
-----
 +
 +
<pre># block certain bots and spiders
 +
SetEnvIfNoCase ^User-Agent$ .*(craftbot|download|extract|stripper|sucker|ninja|clshttp|webspider|leacher|collector|grabber|webpictures) HTTP_SAFE_BADBOT
 +
SetEnvIfNoCase ^User-Agent$ .*(libwww-perl|aesop_com_spiderman) HTTP_SAFE_BADBOT
 +
Deny from env=HTTP_SAFE_BADBOT</pre>
  
 
'''9. Secure Directories by Disabling Execution of Scripts'''
 
'''9. Secure Directories by Disabling Execution of Scripts'''
 
-----
 
-----
 +
 +
<pre>AddHandler cgi-script .php .pl .py .jsp .asp .htm .shtml .sh .cgi
 +
Options -ExecCGI</pre>
  
 
== Other ==
 
== Other ==

Revision as of 11:19, 16 January 2012

Apache

Note - serving of local files

Note: Often the initial installation of Apache has <Directory /> directive (directive for the root of the filesystem) set to "Allow from All", in [Apache config dir]/sites-available/default! This means that server can server any file from the file system, not just the files in the htdocs document folder, which you typically want!

To avoid this, simply change this to "Deny from All".

Self-Signed SSL Certificate

They might not pass as customer-friendly - in fact, if you need https/ssl for customer communication, you should always use signed certificates, as those do induce trust - but often you have private sections/domains/sites where self-signed is just fine... or you might just wanna test the ssl while waiting for the signed certificate.

Here are only listed steps to get to your certificate; for details and explanations, see e.g. akadia.com.

# openssl genrsa -des3 -out server.key 1024
# openssl req -new -key server.key -out server.csr
# cp server.key server.key.org
# openssl rsa -in server.key.org -out server.key
# openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
# cp server.crt /etc/apache2/cert/ssl.crt
# cp server.key /etc/apache2/cert/ssl.key
# chmod 400 /etc/apache2/cert/ssl.crt /etc/apache2/cert/ssl.key

Enable SSL/HTTPS in Apache

HowTo: Use the following virtual host definition:

<VirtualHost *:443>
    ServerName ssl-name
    DocumentRoot /var/www/ssl/root
    SSLEngine on
    SSLCertificateFile /etc/apache2/server.crt
    SSLCertificateKeyFile /etc/apache2/server.key
    SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown
</VirtualHost>

where certificate file and the certificate key file are either authority-signed or self-signed certificate files (see above), and add

NameVirtualHost *:443
Listen 443

to /etc/apache2/ports.conf and restart Apache.

.htaccess and mod_rewrite Tricks

Mostly based on 17 Useful .htaccess Tricks and Tips

General

1. Set Timezone


SetEnv TZ Australia/Melbourne

List of timezones.

2. SEO Friendly 301 Permanent Redirects


Modern search engines have the capability to detect 301 Permanent Redirects and update its existing records.

Redirect 301 http://www.domain.com/home http://www.domain.com/

3. Skip the Download Dialogue


The following defines given types as octet-stream, thus making it "only to download"; clicking the link to such resource will skip "open / save" dialog and will start download immediately.

AddType application/octet-stream .pdf
AddType application/octet-stream .zip
AddType application/octet-stream .mov

4. Skip or Force www.


One of the SEO guidelines is, make sure there is only one URL pointing to your website.

To force URL's without www.:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www.domain.com [NC]
RewriteRule ^(.*)$ http://domain.com/$1 [L,R=301]

To force www. in the URL:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^domain.com [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [L,R=301]

5. Custom Error Pages


ErrorDocument 401 /error/401.php
ErrorDocument 403 /error/403.php
ErrorDocument 404 /error/404.php
ErrorDocument 500 /error/500.php

6. Compress Files


You need to have deflate module installed and enabled.

AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript

7. Cache Files


The following example sets caching of multimedia files to 30 days:

<FilesMatch ".(flv|gif|jpg|jpeg|png|ico|swf|js|css|pdf)$">
  Header set Cache-Control "max-age=2592000"
</FilesMatch>

8. Disable Caching for Certain File Type


The following example disables caching of scripts:

<FilesMatch ".(pl|php|cgi|spl|scgi|fcgi)$">
  Header unset Cache-Control
</FilesMatch>

9. Redirect (Sections) to https://


The following forces /login and /signup sections of your site to use https.

Of course, it's recommendable that you have a signed SSL certificate.

RewriteEngine on
RewriteCond %{HTTPS} =off
RewriteCond %{REQUEST_URI} /login [NC,OR]
RewriteCond %{REQUEST_URI} /signup [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

10. Simple MVC using .htaccess


You can redirect all requests to a single script file, and serve content based on REQUEST_URI:

RewriteEngine On
RewriteRule !robots\.txt|\.(js|ico|gif|jpg|png|css|flv|swf)$ index.php

11. Provide Different Page Versions based on User Agent


You can provide different versions of your site for different browsers (e.g. links as a text-based browser, and for mobile devices):

RewriteEngine On

# MSIE
RewriteCond %{HTTP_USER_AGENT} ^Mozilla/4(.*)MSIE
RewriteRule ^index\.html$ /index.ie.html [L]

# Netscape / Mozilla
RewriteCond %{HTTP_USER_AGENT} ^Mozilla/5(.*)Gecko
RewriteRule ^index\.html$ /index.full.html [L]

# Lynx, text based
RewriteCond %{HTTP_USER_AGENT} ^Lynx/
RewriteRule ^index\.html$ /index.light.html [L]

# Mobile version of your site
RewriteCond %{HTTP_USER_AGENT} ^.*(iPad|iPhone).*$
RewriteRule ^(.*)$ http://ipad.domain.com [R=301]

# All other
RewriteRule ^index\.html$ /index.medium.html [L]

Security

1. Hotlinking Protection with .htaccess


Block all multimedia file requests that do not come from direct link or from your site:

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www.)?domain.com/.*$ [NC]
RewriteRule .(gif|jpg|swf|flv|png)$ /no-hotlink.html [R=302,L]

2. Prevent Hacks


Block some common malicious URL hacks:

RewriteEngine On

# proc/self/environ? no way!
RewriteCond %{QUERY_STRING} proc/self/environ [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 page with 403 Forbidden error!
RewriteRule ^(.*)$ no-way.html [F,L]

3. Block Access to Your .htaccess File


# secure .htaccess file
<Files .htaccess>
  Order Allow,Deny
  Deny from All
</Files>

# prevent viewing of a specific file
<Files secretfile.jpg>
  Order Allow,Deny
  Deny from All
</Files>

# multiple files / file types
<FilesMatch ".(htaccess|htpasswd|ini|phps|fla|psd|log|sh)$">
  Order Allow,Deny
  Deny from All
</FilesMatch>

4. Rename .htaccess Files


AccessFileName htacc.ess

5. Disable Directory Browsing


# disable directory browsing
Options All -Indexes

# enable directory browsing
Options All +Indexes

6. Change Default Index Page


DirectoryIndex my-home.html

7. Block Unwanted Visitor based on Referring Domain


# block visitors referred from indicated domains
RewriteEngine on
RewriteCond %{HTTP_REFERER} scumbag.com [NC,OR]
RewriteCond %{HTTP_REFERER} wormhole.com [NC,OR]
RewriteRule .* - [F]

8. Blocking Request based on User-Agent Header


# block certain bots and spiders
SetEnvIfNoCase ^User-Agent$ .*(craftbot|download|extract|stripper|sucker|ninja|clshttp|webspider|leacher|collector|grabber|webpictures) HTTP_SAFE_BADBOT
SetEnvIfNoCase ^User-Agent$ .*(libwww-perl|aesop_com_spiderman) HTTP_SAFE_BADBOT
Deny from env=HTTP_SAFE_BADBOT

9. Secure Directories by Disabling Execution of Scripts


AddHandler cgi-script .php .pl .py .jsp .asp .htm .shtml .sh .cgi
Options -ExecCGI

Other

Password Generators

  • PHP - replace the '16' with length of the generated password (28 is most you can get):
$password = substr(str_replace(array('$1$', '$2$', '$2a$', '$', '.', '/'), '', crypt(php_uname() . microtime())), 0, 16);

or, terminal version:

$ php -r "echo substr(str_replace(array('$1$', '$2$', '$2a$', '$', '.', '/'), '', crypt(php_uname() . microtime())), 0, 16);"; echo
1hlNxRwBr4mCZWQF
  • Bash - replace the '64' with length of the generated password (no real limit here), and change the characters class in tr -d as you please, to control what characters can be contained in the password; the characters class presented here are all characters that are treated as a part of the word in terminal (i.e. you can double-click the word and it gets selected as a whole):
$ cat /dev/urandom | tr -d -c "a-zA-Z0-9@#%&\-\_+=:,.?/" | head -c 64; echo
uQ,XGSG4qPtE4.&UQT,jPA#=a8j-mhy+qjQUg:m#s7g1@c2-#J8D-,3zQFd+o_-W

External Links

Apache

Other