tcp wrappers hosts.deny and hosts.allow

  1. TCP Wrapper is a host-based networking ACL system, used to filter network access to Internet Protocol servers on (Unix-like) operating systems such as Linux or BSD. It allows host or subnetwork IP addresses, names and/or ident query replies, to be used as tokens on which to filter for access control purposes.
TCP wrapper based access List Rules can be included in the two files
/etc/hosts.allow and
/etc/hosts.deny .
Work precedence:
  1. /etc/hosts.allow-
    1. if allow will not check 2
    2. if not found then go to 2
  2. /etc/hosts.deny .
    1. if not found allow access.
Points to remember
  • You can have only one rule per service in hosts.allow and hosts.deny file.
  • Any changes to hosts.allow and hosts.deny file takes immediate effect.
  • The last line in the files hosts.allow and hosts.deny must be a new line character. Or else the rule will fail.
Rule Syntax
The syntax for both hosts.allow and hosts.deny file takes the following form:
daemon : client [:option1:option2:…]
Examples
Allow SSH
for xyz.com and
deny access to all the others.
sshd : .xyz.com
… and in the hosts.deny file I include the rule:
sshd : ALL
Denys FTP access to all in abc.com domain  and hosts in the 192.168.1.0 network.
#FILE: /etc/hosts.deny
vsftpd : 192.168.1. , .abc.com
Beautification
#FILE: /etc/hosts.deny
vsftpd : 192.168.1. , .abc.co.in : spawn /bin/echo  `/bin/date` access denied >> /var/log/vsftpd.log : deny
In the above rule, spawn logs a message to the vsftpd log file each time the rule matches. deny is optional if you are including this rule in the hosts.deny file.
For example, you can use spawn option to send mail to the admin when ever a deny rule is matched.
Wildcards
You can use wildcards in the client section of the rule to broadly classify a set of hosts. These are the valid wildcards that can be used.
  • ALL – Matches everything
  • LOCAL – Matches any host that does not contain a dot (.) like localhost.
  • KNOWN – Matches any host where the hostname and host addresses are known or where the user is known.
  • UNKNOWN – Matches any host where the hostname or host address are unknown or where the user is unknown.
  • PARANOID – Matches any host where the hostname does not match the host address.
Patterns
ALL : 123.12.
Matches all the hosts in the 123.12.0.0 network. Note the dot (.) in the end of the rule.
ALL : 192.168.0.1/255.255.255.0
IP address/Netmask can be used in the rule.
sshd : /etc/sshd.deny
If the client list begins with a slash (/), it is treated as a filename. In the above rule, TCP wrappers looks up the file sshd.deny for all SSH connections.
sshd : ALL EXCEPT 192.168.0.15
will allow ssh connection for only the machine with the IP address 192.168.0.15 and block all other connections.
You can use the options allow or deny to allow or restrict on a per client basis in either of the files hosts.allow and hosts.deny
in.telnetd : 192.168.5.5 : deny
in.telnetd : 192.168.5.6 : allow
Shell Commands
As mentioned above, you can couple the rules to certain shell commands by using the following two options.
spawn – This option launches a shell command as a child process. For example, look at the following rule:
sshd : 192.168.5.5 : spawn /bin/echo `/bin/date` from %h >> /var/log/ssh.log : deny
Each time the rule is satisfied, the current date and the clients hostname %h is appended to the ssh.log file.
twist – This is an option which replaces the request with the specified command. For example, if you want to send to the client trying to connect using ssh to your machine, that they are prohibited from accessing SSH, you can use this option.
sshd : client1.xyz.com : twist /bin/echo “You are prohibited from accessing this service!!” : deny
When using spawn and twist, you can use a set of expressions. They are as follows :
%a — The client’s IP address.
%A — The server’s IP address.
%c — Supplies a variety of client information, such as the username and hostname, or the username and IP address.
%d — The daemon process name.
%h — The client’s hostname (or IP address, if the hostname is unavailable).
%H — The server’s hostname (or IP address, if the hostname is unavailable).
%n — The client’s hostname. If unavailable, unknown is printed. If the client’s hostname and host address do not match, paranoid is printed.
%N — The server’s hostname. If unavailable, unknown is printed. If the server’s hostname and host address do not match, paranoid is printed.
%p — The daemon process ID.
%s — Various types of server information, such as the daemon process and the host or IP address of the server.
%u — The client’s username. If unavailable, unknown is printed.

awstats for apache webserver

https://hottiehunter.com/awstats/awstats.pl?config=hottiehunter.com
Ubuntu 14.04, awstat version=7.2

#apt-get install awstats libgeo-ipfree-perl libnet-ip-perl
#a2enmod cgi 
 
 cp /etc/awstats/awstats.conf /etc/awstats/awstats.hottiehunter.com.conf
 
LogFile="/var/log/apache2/access.log"
LogFormat=1
 
SiteDomain="example.com"
#HostAliases="localhost 127.0.0.1 example.com"  #lesser is better for performance
 HostAliases="www.hottiehunter.com"
DirCgi="/awstats"
 
LoadPlugin="tooltips"
LoadPlugin="graphgooglechartapi"
LoadPlugin="geoipfree"
 
SkipDNSLookupFor="REGEX[^192\.168\.]"
 
AllowFullYearView=3 


Manually running update
========================

/usr/lib/cgi-bin/awstats.pl -config=hottiehunter.com -update
 
 

Automatic Stat Updates

To maintain the stats on a regular basis you will need a cron job to run the awstats update script. Change the user who will be running the script from www-data to root. There area bunch of permission errors when run as www-data.
The cron job below will run every 10 minutes, adjust the time to your needs.

*/10 * * * * root /usr/lib/cgi-bin/awstats.pl -config=hottiehunter.com -update > /dev/null
 
Configure Apache2 for awstats

vim /etc/apache2/sites-available/awstats.conf
 #for user password authentication to view stats
<Directory /usr/lib/cgi-bin/>
 AuthName "Enter Your User Name and Password"
  AuthType Basic
  AuthUserFile /etc/apache2/auth_users
  Require valid-user
</Directory> 
#alias configuration
Alias /awstatsclasses "/usr/share/awstats/lib/"
Alias /awstats-icon/ "/usr/share/awstats/icon/"
Alias /awstatscss "/usr/share/doc/awstats/examples/css"
ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
ScriptAlias /awstats/ /usr/lib/cgi-bin/
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch

if you receive some warnings with command :
apache2ctl -t 

grep search in /etc/apache2 with "alias and scriptalias as keywords"
for example
grep -i -R "ScriptAlias" /etc/apache2/*   #find duplicatoins and remove accordingly
Currently my config looks like:
 
Alias /awstatsclasses "/usr/share/awstats/lib/"
Alias /awstats-icon/ "/usr/share/awstats/icon/"
Alias /awstatscss "/usr/share/doc/awstats/examples/css"
#ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/    #this is commented due to duplicaton
ScriptAlias /awstats/ /usr/lib/cgi-bin/
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch 


Stop Unauthorised Users

As the above setup stands anyone, that is the world and his dog can now see your web serrver stats. Probably not a good idea or something you want. We can let Awstats protect itself with the rather well named parameter AllowAccessFromWebToFollowingIPAddresses or as it is also simple to restrict access by forcing the user to enter a password or simple only allow IP addresses on your local LAN not from external IPs.
To allow awstats to protect itself edit the config file and add a list of IP addresses or ranges see the comment above the option of the syntax.
sudo nano /etc/awstats/awstats.example.com.conf
 
AllowAccessFromWebToFollowingIPAddresses="127.0.0.1 192.168.2.0-192.168.2.255" 
 

Access via a User Name and Password

To create a new user file and add the username “richard” to the file /etc/apache2/auth_users

To append other users do not use the -c flag.

htpasswd -c /etc/apache2/auth_users richard
 
#configuration is already on top for awstats.conf file for user/pass authentication

#service apache2 restart
 

Logging Data From Old logs

If you want to log the data in old log files rotated out of the way you can do that using a command line similar to the below. This may take some time depending on the number and size of your log files and the files need to be run in chronological order. If you ran the manual update above you will need to delete the database. Anyway, it was worth while as that is generally very quick and you can see some data being displayed. Also, it is worth moving the cron file for awstats to stop that from running.
The database files are where ever you pointed the option DirData to, it defaults to /var/lib/awstats. The second command mv the awstats cron job out of the way.

sudo rm /var/lib/awstats/*
 
sudo mv /etc/cron.d/awstats /root
 
Now we can run the log import or update from the command line. My Apache
 logs are compressed and called access.log,  access.log.1 or 
access.log.n.gz. Giving the following command line to import them all. 
Depending on the size and number of files this may put a heavy load on 
the server, so i also run the command through nice.

Note: the command should all be on one line.
 
sudo nice /usr/lib/cgi-bin/awstats.pl -update -config="example.com" -LogFile="/usr/share/awstats/tools/logresolvemerge.pl /var/log/apache2/access.log* |"
 

Remember to put the cron file back again.
sudo mv /root/awstats  /etc/cron.d
 
1) The URL should be
http://example.com/awstats/awstats.pl?config=example.com
2) Unless the CGI module is enabled, the perl script will be offered for download instead of being executed.
An additional step was required on my Ubuntu 14.04 system:
a2enmod cgi
 
Additional resource:
http://computers.in4mnation.com/install-and-secure-awstats-ubuntu-apache2/#set_up_cron_to_update_awstats
http://blogging.dragon.org.uk/installing-awstats-on-ubuntu-14-04-lts/




Nginx brief introduction

why exactly is nginx so much faster than the typical Apache setup of the prefork MPM and mod_php? The technical explanation is that nginx is a non-blocking event based architecture while Apache is a blocking process based architecture. To simplify it heavily the theory is like this:

Apache "Prefork Processes":

    Receive PHP request, send it to a process.
    Process receives the request and pass it to PHP.
    Receive an image request, see process is busy.
    Process finishes PHP request, returns output.
    Process gets image requests and returns the image.

While the process is handling the request it is not capable of serving another request, this means the amount of requests you can do simultaneously is directly proportional to the amount of processes you have running.
Apache + PHP setup has the PHP binary embedded directly into the Apache processes. This means Apache can talk to PHP incredibly fast and without much overhead, but it also means that the Apache process is going to be 25-50MB in size. Not just for requests for PHP requests, but also for all static file requests. This is because the processes keep PHP embedded at all times due to cost of spawning new processes. This effectively means you will be limited by the amount of memory you have as you can only run a small amount of processes and a lot of image requests can quickly make you hit your maximum amount of processes.

Nginx "Event Based Processing:"

    Receive request, trigger events in a process.
    The process handles all the events and returns the output


Nginx
Nginx, on the other hand, requires the use of PHP-FPM if you want to run a PHP application. It
doesn’t have a module to load in PHP like Apache can. I always use Nginx, as it does everything I
need with a simpler configuration, and better overall performance.

Process Management
PHP-FPM’s master process creates child processes to handle all PHP requests. Processes are
expensive to create and manage. How we treat them is important.
PHP-FPM is an implementation of FastCGI, which uses “persistent processes”. Rather than killing
and re-creating a process on each request, FPM will re-use processes.
This is much more efficient than Apache’s mod_php, which requires Apache to create and destroy a
process on every request.

nginx –s stop Stops the daemon immediately (using the TERM signal)
nginx –s quit Stops the daemon gracefully (using the QUIT signal)
nginx –s reopen Reopens the log files
nginx –s reload Reloads the configuration

part 5 apache MOD REWRITE

url rewrite with mod_rewrite.so  engine#
 
feature:
1)changes url or underlying request based on condition
2)based on perl regex
  important characters are
  . = matches a  single character
  * = matches zero or more of previous character
  + = matches one or more
  ? = optional match
  [] = character class  i,e '/prod[123]*'
  [^] = character class negation
  () = groups character for assignation to backreference , eg '/(prod|products)'
3) ability to parse:
  HTTP headers
  Server VARs - %{HTTP_HOST}
  enviromental VARs i,e IE
 
 http://hostname/URI
 HTTP= scheme
 host=hostname
 urlpath = /.. = basic rewrites operate here

  •        <Directory>
  •        .htaccess
      
      
RewirteRule - basic requirement - Takes 3 argument
usage: 'RewriteRule Pattern(URL-Path) Substitution [flag[s]]
Note: URL-Path matches after HOST and before Query String
eg http://site2.example.com/prod/index.php?pid=1&user=current

Note: substitution can be:
    a) File system path(mod_alias):
    RewriteRule ^/docs /usr/local/share/apache2/docs
    Note: The above uses 'mod_rewrite' as mod_alias
   
    b)web path:
    RewirteRule ^/docs$ /documents
    note: '/documents' exists beneath the DocumentRoot
   
    c)absolute URL: 'RewirteRule ^/docs$ http://www.testing.com/docs [R]'
    rewrites users browser URL to reflect new absolute URL
   
    Redirect
    No Change: '-'
    RewriteRule \.(jpg|png) - [E=image:1]  =>this enable VAR for later usage
Note Flags are optional can be multiple [f1,f2,f3...] and include common option
[NC] = case insensitive
[E=Var:Value] - setting of enviroment VAR -useful in logs,other rewrite rule, CGI
[F] = Returns 403 to client forbidding access to resource
[G] = Returns 410 to client resource is no longer available
[R] = returns redirect 300-399 to client

note: consult mod_rewrite docs for more flags

======================================================================

ensure module is loaded

ln -s . /etc/apache2/mods-available/rewrite.loaded

vim 000-default.conf
<virtualhost>
..
#request for example.com/index.html is sent to example.com/index2.html
RewriteEngine on   #enables processing
RewriteRule ^/index.html$ /index2.html #fetches new content but does not Redirect BROWSER (eg. example.com/index.html will serve content from index2.html but BROWSER url bar is not changed )
RewriteRule ^/index.html$ /index2.html [R] #fetches new content ALSO Redirect bROWSER #url is changed in browser
RewriteRule ^/docs$ http://testing.com/docs [R]


</virtualhost>


#mod rewrite - rewrite condition
 

features:

 stackability of logic
 rules are implicitly ANDed: use [OR] to enable ORing
 one or more tests may be performed on current request
 Supports backreferences using: %N - %1..%9
 Usage 'RewriteCond TestString CondPattern (RegEx) [OR, ornext, NC,NV
   teststring:
      RewriteRule
     
Task:
omit localhost (127.0.x.y) from apache logs
 a)  RewriteCond %{REMOTE_ADDR} ^127\.0\.
 b)  RewriteRule .* - [E=localnolog] => Defines VAR to indicate request from localhost
 c)  'CustomLog /var/log/apache/access.log combined env=!localnolog'



 Force SSL for url path '/login$'

 'RewriteCond %{REQUEST_URI} ^/login'
 'RewriteCond ${SERVER_PORT} !443'
 'RewriteRule .* https://%{HTTP_HOST}/login'
OR
 RewriteCond %{REQUEST_URI} ^(/login.*)
RewriteCond %{SERVER_PORT} !443
RewriteRule .* https://%{HTTP_HOST}/login.html

Force ssl for all
RewriteCond %{SERVER_PORT} !443
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI

RewriteEngine on
RewriteCond %{HTTP_HOST} ^lokeshworhandicraft.com.np [NC,OR]
RewriteCond %{HTTP_HOST} ^www.lokeshworhandicraft.com.np [NC]
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(.*)$ /public/$1 [L]

 

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}





Back reference

##mod rewrite##
Backreferences

feature
 #tokenize portion of URL for reuse
 #token range form $1 .. $9
 #uses '()' to create token
 #per server and per directory (.htaccess | <Directory>)
 Note: normally placed at site-wide or virtualHost layer
 Note: normally used to match: URL-Path

 task:
 rewrite index.html -> /new/index.html
 ------------------------------------------
 RewriteRule ^/(index.html)$ /new/$1  #equivalent to redirect[Match]
 RewriteRule ^/(index.html)$ /new/$1 [R] #equivalent to Redirect[Match] - Force redirect


 Rewrite 'localhost/docs*' -> 'http://www.facebook.com/docs*
 a. RewriteRule ^(/docs.*)$ http://linuxorg.com$1 - Redirects: '/docs* to remote server










part 4 apache conditional handling

conditional handling features:

A) make decisions based on current conditions:
 1) modules available
 2) remote HOST
 3) browser type - useragent(http header request)

B) <IfDefine> parameter - directives to be processed at server startup
C) <IfModule> - directive to be processed based on module existence. Eg mod_ssl
D) <IfVersion> - directive processed based on version of apache
E) SetEnvIf[NoCase] -sets environmental VAR (variable) based on :
   HTTP Request Header : i,e User-Agent, Referer , Accept-Language
   Remote_(Addr|Host) server_addr, Request_(method|Protocol), Request_URI
   Predefined Environmental VARs using : SetEnvIf[NoCase]
  
Task:

 Explore <IfModule>

 apachectl -D DUMP_MODULES 
 or
 apache2ctl -M | grep -E "(static|shared)" | wc -l

 cd /etc/apache2 && grep -R -i 'ifmodule' *   --searches for ifmodule

 inside the <VirutalHost>
 <VirtualHost>
 ..
 SetEnvIf Referer "site1.linuxcbt.internal" site1_referrer
 CustomLog /var/log/apache2/site2.site1_referral.access.log combined env=site1_referrer
 </VirtualHost>

part 3 apache content negotiation and content restriction

content negotiation

responds to http/1.1 request header options
presents client with bestmatch resources http/1.1
-alternate language, character set ,media type etc
handled by - mod_negotiation

content negotiation is based on 2 methods-
1 type maps - *.var file -include variants
2 MultiViews - server auto searches for alternatives based on client request

task:
negotiate content based on language

vim  index.html.var

URI: index.html

URI: index.html
Content-type: text/html
Content-language: en

URI: index.html.es
Content-type: text/html
Content-language: es


content restriction

restricts access to content based on
1 <Directory>
2 <Location> -url webspace
3 <Files>
4 <Auth> authentication related directives

default config restricts access to .htaccess , .ht* files

Tasks:
1) <Directory> - applies to filesystem location
<Directory /home/site2/www/private>
  Order allow,deny
  Allow from 127.0.0.1 192.179.90.22
</Directory>

 effectively take content offline from webspace
 <Directory /home/site2/www/private>
     Order deny,allow
     Deny from all
 </Directory>

 Use <Location> applies restriction based on URL string

 <LocationMatch ^/priv> - traps variants including but not limited to "/private , /priv ,/privilege , /primary etc"
 <LocationMatch ^/priv>
     Order deny,allow
     Deny from all
 </LocationMatch>
   eg -  example.com/privtt is restricted OR
  
   <Location ~ ^/priv>
   Order deny,allow
   Deny from all
   </Location>

 <Files> to restrict based on files
 NOTE:- it should be placed under <Directory> block or in .htaccess in particular directory as needed
 <Files ~ "\.(xls|docx|sql|pdf)">
 Order deny,allow
 deny from all
 </Files>
 <FilesMatch "\.">
   Order deny,allow
   Deny from all
 </FilesMatch




part 2 apache socket binding and htaccess

default port 80
binding facilitate virtual hosting
bindings are tagged to virtual host containers
Listen - key directive
grep -i listen #across apache config
on debian system check ports.conf

#bind to alternates ports



HTACCESS

-on demand configuration  updates to your sites managed by Apache
-substitute for "<Directory></Directory>" directives
-configure per directory options
-indirect site control via ftp,sftp etc
-

Options +Indexes
<Files *xls>
Order allow,deny
allow from 127.0.0.127 192.168.0.12/24
</Files>


Redirect /docs http://facebook.com

 

part 1 apache url mapping and redirect

Alias /doc/ "/usr/share/doc/"

if any other new directory except document root then it must be published with <Directory /your/directory/> </Directory>

AliasMatch
==========
AliasMatch ^/docs/(.*pdf) /var/www/docs2/$1

#$1 is first parenthesized block (.*pdf)<=its called reference


#anything terminating with pdf suffix

AliasMatch ^/docs/(.*pdf|txt) /var/www/docs2/$1
#anything terminating with pdf OR txt suffix
AliasMatch ^/docs/(.*) /var/www/docs2/$1
#reroute every thing to/docs2

AliasMatch ^/(docs)/(projectx)/(.*) /var/www/$2/$1/TXT/$3
#same as above but variablized

AliasMatch ^/(docs)/(projectx)/(.*\.pdf) /var/www/$2/$1/PDF/$3

                                                                                                                       

Redirect sends client to new destination
remaps url path beginning with '/' to new url
implementation of mod_alias as Redirect, RedirectMatch , RedirectPermanent, RedirectTemp
dafault status : 302
301: permanent
302:temporary

Redirect /docs  /docs2
#docs is redirected to docs2

Redirect /docs http://192.123.12.33/docs
#sends client to remote system

Redirect /docs http://www.google.com/docs

#invoke-rc.d apache2 reload


#  Using Redirect Match

RedirectMatch (.*)\.doc  $1.pdf #applies .pdf substitution across the site
eg.  google.com/docs2/TXT/file.doc

google.com/docs2/TXT/file # this is preserved and
.doc is replaced with .pdf and redirected


RedirectMatch /docs/(.*)\.doc /PDF/$1.pdf
anyfile terminating with .doc extension is redirected with same scheme
and same server









SED editor sed

Remove multiple spaces
= = = = = = =
 Remove leading spaces and number from history cmmand output

history | sed 's/^ *[0-9][0-9]* *//'

 
root@vm2:~# cat hello 
#ab 12
cd      99
   zz    te
#ef
    test
      #tellso


root@vm2:~# cat hello  | sed 's/^\s\+//g'

#ab 12
cd      99
zz    te
#ef
test
#tellso

Combinig sed expression
root@vm2:~# cat hello  | sed 's/^\s\+//g;s/\s\+/ /g'
#ab 12
cd 99
zz te
#ef
test
#tellso


sed 'p' passwd  #prints file content but double content
sed -n '1p' file.txt  #print 1st line
sed -n  '2p' file.txt  #print 2nd line
sed -n 4,13p file.txt #print 4 to 14 line
sed -n '$p'  file.txt  #print last
sed -n '1!p' file.txt  #print all except line 1
sed -n '1,3!p' file.txt #print all except line 1 to 3

AWK

will print all but very first column:

awk '{$1=""; print $0}' somefile

will print all but two first columns:

awk '{$1=$2=""; print $0}' somefile

history | awk '{$1=$1;print}' | cut -d' ' -f2-       #remove beginning spaces and history number , cut -f2- will start printing from 2nd field to last
history | awk '{$1=$1;print}' | cut -d' ' -f1-4     # cut -f1-4 will print from field 1 to 4

SED editor sed

cat test | sed 's#first#second#Ig'     ## use `I` for case insensitive

Remove multiple spaces
= = = = = = =
root@vm2:~# cat hello
#ab 12
cd      99
   zz    te
#ef
    test
      #tellso


root@vm2:~# cat hello  | sed 's/^\s\+//g'
#ab 12
cd      99
zz    te
#ef
test
#tellso

Combinig sed expression
root@vm2:~# cat hello  | sed 's/^\s\+//g;s/\s\+/ /g'
#ab 12
cd 99
zz te
#ef
test
#tellso


sed 'p' passwd  #prints file content but double content
sed -n '1p' file.txt  #print 1st line
sed -n  '2p' file.txt  #print 2nd line
sed -n 4,13p file.txt #print 4 to 14 line
sed -n '$p'  file.txt  #print last
sed -n '1!p' file.txt  #print all except line 1
sed -n '1,3!p' file.txt #print all except line 1 to 3
=======================using regular expression=======================
we use '-e' option when we use expression

sed -n -e '/2011/p' file.txt     # print line containing 2011
sed -n -e '/^root/p' passwd      # print lines starting with word 'root'
sed -n -e '/root$/p' passwd      # print lines Ending with word 'root'
sed -n -e '/^harke101$/p' passwd
sed -n -e '/^harke101.*$/p' passwd     # print lines Starting and Ending with word 'root'
sed -n -e '/[0-9]/p' firewall.txt     # print lines containing number 0-9
sed -n -e '/^[0-9][0-9][0-9]$/p'  firewall.txt #print beginning and ending with 3 char number
sed -n -e '/[0-9]\{3\}/p' firewall.txt # print beginning and ending with 3 char number
sed -n -e '/^[0-9]\{3\}$/p' firewall.txt # print beginning and ending with 3 char number




3.3 Overview of Regular Expression Syntax

To know how to use sed, people should understand regular expressions (regexp for short). A regular expression is a pattern that is matched against a subject string from left to right. Most characters are ordinary: they stand for themselves in a pattern, and match the corresponding characters in the subject. As a trivial example, the pattern
     The quick brown fox
matches a portion of a subject string that is identical to itself. The power of regular expressions comes from the ability to include alternatives and repetitions in the pattern. These are encoded in the pattern by the use of special characters, which do not stand for themselves but instead are interpreted in some special way. Here is a brief description of regular expression syntax as used in sed.
char
A single ordinary character matches itself.
*
Matches a sequence of zero or more instances of matches for the preceding regular expression, which must be an ordinary character, a special character preceded by \, a ., a grouped regexp (see below), or a bracket expression. As a GNU extension, a postfixed regular expression can also be followed by *; for example, a** is equivalent to a*. POSIX 1003.1-2001 says that * stands for itself when it appears at the start of a regular expression or subexpression, but many nonGNU implementations do not support this and portable scripts should instead use \* in these contexts.
\+
As *, but matches one or more. It is a GNU extension.
\?
As *, but only matches zero or one. It is a GNU extension.
\{i\}
As *, but matches exactly i sequences (i is a decimal integer; for portability, keep it between 0 and 255 inclusive).
\{i,j\}
Matches between i and j, inclusive, sequences.
\{i,\}
Matches more than or equal to i sequences.
\(regexp\)
Groups the inner regexp as a whole, this is used to:
  • Apply postfix operators, like \(abcd\)*: this will search for zero or more whole sequences of ‘abcd’, while abcd* would search for ‘abc’ followed by zero or more occurrences of ‘d’. Note that support for \(abcd\)* is required by POSIX 1003.1-2001, but many non-GNU implementations do not support it and hence it is not universally portable.
  • Use back references (see below).
.
Matches any character, including newline.
^
Matches the null string at beginning of the pattern space, i.e. what appears after the circumflex must appear at the beginning of the pattern space. In most scripts, pattern space is initialized to the content of each line (see How sed works). So, it is a useful simplification to think of ^#include as matching only lines where ‘#include’ is the first thing on line—if there are spaces before, for example, the match fails. This simplification is valid as long as the original content of pattern space is not modified, for example with an s command.
^ acts as a special character only at the beginning of the regular expression or subexpression (that is, after \( or \|). Portable scripts should avoid ^ at the beginning of a subexpression, though, as POSIX allows implementations that treat ^ as an ordinary character in that context.
$
It is the same as ^, but refers to end of pattern space. $ also acts as a special character only at the end of the regular expression or subexpression (that is, before \) or \|), and its use at the end of a subexpression is not portable.
[list]
[^list]
Matches any single character in list: for example, [aeiou] matches all vowels. A list may include sequences like char1-char2, which matches any character between (inclusive) char1 and char2. A leading ^ reverses the meaning of list, so that it matches any single character not in list. To include ] in the list, make it the first character (after the ^ if needed), to include - in the list, make it the first or last; to include ^ put it after the first character.
The characters $, *, ., [, and \ are normally not special within list. For example, [\*] matches either ‘\’ or ‘*’, because the \ is not special here. However, strings like [.ch.], [=a=], and [:space:] are special within list and represent collating symbols, equivalence classes, and character classes, respectively, and [ is therefore special within list when it is followed by ., =, or :. Also, when not in POSIXLY_CORRECT mode, special escapes like \n and \t are recognized within list. See Escapes.
regexp1\|regexp2
Matches either regexp1 or regexp2. Use parentheses to use complex alternative regular expressions. The matching process tries each alternative in turn, from left to right, and the first one that succeeds is used. It is a GNU extension.
regexp1regexp2
Matches the concatenation of regexp1 and regexp2. Concatenation binds more tightly than \|, ^, and $, but less tightly than the other regular expression operators.
\digit
Matches the digit-th \(...\) parenthesized subexpression in the regular expression. This is called a back reference. Subexpressions are implicity numbered by counting occurrences of \( left-to-right.
\n
Matches the newline character.
\char
Matches char, where char is one of $, *, ., [, \, or ^. Note that the only C-like backslash sequences that you can portably assume to be interpreted are \n and \\; in particular \t is not portable, and matches a ‘t’ under most implementations of sed, rather than a tab character.
Note that the regular expression matcher is greedy, i.e., matches are attempted from left to right and, if two or more matches are possible starting at the same character, it selects the longest.
Examples:
‘abcdef’
Matches ‘abcdef’.
‘a*b’
Matches zero or more ‘a’s followed by a single ‘b’. For example, ‘b’ or ‘aaaaab’.
‘a\?b’
Matches ‘b’ or ‘ab’.
‘a\+b\+’
Matches one or more ‘a’s followed by one or more ‘b’s: ‘ab’ is the shortest possible match, but other examples are ‘aaaab’ or ‘abbbbb’ or ‘aaaaaabbbbbbb’.
‘.*’
‘.\+’
These two both match all the characters in a string; however, the first matches every string (including the empty string), while the second matches only strings containing at least one character.
‘^main.*(.*)’
This matches a string starting with ‘main’, followed by an opening and closing parenthesis. The ‘n’, ‘(’ and ‘)’ need not be adjacent.
‘^#’
This matches a string beginning with ‘#’.
‘\\$’
This matches a string ending with a single backslash. The regexp contains two backslashes for escaping.
‘\$’
Instead, this matches a string consisting of a single dollar sign, because it is escaped.
‘[a-zA-Z0-9]’
In the C locale, this matches any ASCII letters or digits.
‘[^ tab]\+’
(Here tab stands for a single tab character.) This matches a string of one or more characters, none of which is a space or a tab. Usually this means a word.
‘^\(.*\)\n\1$’
This matches a string consisting of two equal substrings separated by a newline.
‘.\{9\}A$’
This matches nine characters followed by an ‘A’.
‘^.\{15\}A’
This matches the start of a string that contains 16 characters, the last of which is an ‘A’.

generate entropy to help speed up key generation

apt-get install rng-tools

vim /etc/default/rng-tools
HRNGDEVICE=/dev/urandom

/etc/init.d/rng-tools start
 /etc/init.d/rng-tools stop