07nov08 updated 19feb09 / 2010-04-30
Check what is already installed
dpkg --get-selections > installed-software.txt apt-get autoremove dpkg --set-selections < installed-software.txt dselect //allow to unselect packages?
apt-get install apache2.2-common
yum install apache
Downloading it again if you need to see the defaults
OR IF YOU REALLY SCREW THINGS UP :), you can restore the default settings too!
mkdir /test apt-get download apache2.2-common dpkg -x apache2.2-common*.deb /test cp /test/etc/apache2/* /etc/apache2/*
If required you can remove & install apache2-common again
apt-get purge apache2-common cd /etc/apache2 rm -R * //be careful that you really are in /etc/apache2!!!! cd .. rmdir apache2
Configuring and Starting and Stopping Apache Web Server
To modify any file from bash shell command prompt or ssh, use vi filename or nano filename
The configuration file is at (Ubuntu) /etc/apache2/apache2.conf
Loglevel warn //You can configure how much logging and where to log LogFormat
ports.conf (Ubuntu) contains the configuration of what port(s) to listen to
Listen 80 Listen 8080 <IfModule mod_ssl.c> Listen 443 </IfModule>
Log files at /var/log/apache2/access.log (error.log)
Whenever you modify a configuration file you will have to run the following commands (ubuntu specific)
/etc/init.d/apache2 stop /etc/init.d/apache2 start
Optionally and alternatively run the following (NOTE that reload may give a result FAILED if apache/httpd isn't yet running) /etc/init.d/apache2 reload /etc/init.d/apache2 restart (combines stop & start commands)
To see the changes... or a slightly "nicer" command is to use the Apache control command:
/usr/sbin/apache2ctl directive e.g. sudo apache2ctl graceful
Directives: start / stop / graceful (restarts w/ aborting connections) / restart / status /
The user running apache should not be root
ENSURE APACHE IS NOT BEING RUN AS ROOT (if an attacker controls apache, they can modify the whole system)
ps aux //shows you all processes from all users, is /usr/sbin/apache2 running from root? //in Centos the httpd web server has user "apache" groupadd www-data useradd -g www-data www-data
In /etc/apache2/apache2.conf change to "User www-data Group www-data" (not root!)
AND ENSURE THAT ONLY ROOT CAN ACCESS APACHE CONFIGURATION & BINARY/EXECUTABLE FILES
chown -R root:root /usr/sbin/apache2 chmod -R o-rwx /usr/sbin/apache2 chown -R root:root /etc/apache2 chmod -R o-rwx /etc/apache2
e.g. ServerTokens Full to Server Tokens Prod
ServerSignature Off UseCanonicalName Off
Less Info is more Secure
REDUCE THE AMOUNT OF INFO YOU GIVE WITH HTTP HEADERS (SERVERTOKENS)
/etc/apache2/apache2.conf nano /etc/httpd/conf/httpd.conf
Change your ServerTokens Full to Server Tokens Prod
#ServerTokens Prod //most restrictive, response -> Server: Apache #ServerTokens Major //response -> Server: Apache/2 #ServerTokens Minor //response -> Server: Apache/2.0 #ServerTokens Min //response -> Server: Apache/2.0.55 #ServerTokens Os //response -> Server: Apache/2.0.55 (Ubuntu) #ServerTokens Full //response -> Server: Apache/2.0.55 (Ubuntu) PHP/5.1.4-1.dotdeb.2 mymod1/X.Y mymod2/W.Z
ServerSignature Off UseCanonicalName Off #Default: on #Server config, virtual host, directory, .htaccess #If UseCanonical-Name is on (the default), then the hostname and port used in the redirect #will be those set by ServerName and Port. If it is off, then the name and port used will be #the ones in the original request.
Lower the Timeout Value (seconds) to mitigate the effects of any Denial Of Service attacks Timeout 45
Limit the size of a request (again mitigating DoS) to whatever you allow file uploads to be.
LimitRequestBody 1048576 //uploads/requests at most at 1 MB
APACHE2, If you are running mod_dav (used with Subversion)
LimitXMLRequestBody 10485760 //uploads at 10 MB
This is where most people hate Linux. It's the most stable and most secure BECAUSE you have to work hard to set the permissions right... but it isn't easy.
The root html serving directory is usually around:
DON'T FORGET, YOUR APACHE/HTTPD USER MUST HAVE PERMISSIONS (execute permission for a directory allows opening/traversing it)
sudo chown -R root:apache /var/www/html sudo chmod -R 550 /var/www/html
(This removes the default permission of "everyone" being able to read/execute)
Prevent browsing root and file folders
/etc/apache2/sites-available/default (ubuntu / apache2) /etc/httpd/conf/httpd.conf
Ensure files outside of the web root are not shared
<Directory /> Order Deny,Allow Deny from all Options None AllowOverride None </Directory> <Directory /web> Order Allow,Deny Allow from all </Directory> #Directory does not appear to support AuthType the same as Location
Turn off default options:
Options -Indexes -Includes -ExecCGI -FollowSymLinks -Multiviews Indexes=Directory Browsing, Includes=ServerSideIncludes(.shtml, .stm, .shtm), ExecCGI=CGI execution, FollowSymLinks=FollowingSymbolicLinks, Multiviews=if address is /dirname but it doesn't exist, it will find a matching dirname.htm or .php
(Or if you don't need anything, "Options None")
Example of applying some security tips
mkdir /var/www/html/web touch /var/www/html/web/file1.html touch /var/www/html/web/file2.html chgrp root:apache /var/www/html/web/* chmod 440 /var/www/html/web/* nano /etc/httpd/conf/httpd.conf (add the Virtual Host area?) <Directory /web> Options Indexes FollowSymLinks Order Allow,Deny Allow from all </Directory>
browse to http://example.com/web
Note that if you use http://example.com/ you will get a FORBIDDEN error as Root browsing is off (-Indexes)
PREVENT UNNEEDED MODULES FROM LOADING
Look in httpd.conf for LoadModule. To disable a module you can add a # at the beginning (comment it out). To search for modules run:grep LoadModule httpd.conf
Some typically enabled but unneeded: mod_imap, mod_include, mod_info, mod_userdir, mod_status, mod_cgi, mod_autoindex. http://httpd.apache.org/docs/2.0/mod/
mod_proxy A forward proxy provides access to internal clients that are restricted by a firewall, or improves caching A reverse proxy
PER DIRECTORY / LOCATION PERMISSIONS (through the main config file)
When applying directives to objects that reside in the filesystem, use
An exception is
Since several different URLs may map to the same filesystem location, such access controls may by circumvented.
The URL may use wildcards In a wild-card string, '?' matches any single character, and '*' matches any sequences of characters.
Apache 1.2 and above: Extended regular expressions can also be used, with the addition of the ~ character.
would match URLs that contained the substring "/extra/data" or "/special/data"
NOTE: the following example uses regular expressions...
<LocationMatch "/projects/[^/]+/login"> AuthType Basic AuthName "Trac Environment" //this name appears on the popup box AuthUserFile /projects/projects.password //file of authorized users, htpasswd --help Require valid-user //requires any user to be authenticated </LocationMatch>
NOTE YOUR APACHE USER, E.G. WWW-DATA, MUST HAVE READ ACCESS TO THE PASSWORD FILE!!!!!
You can also create a groups file and if it is required in the above "default" or vhosts.conf then it will only allow users access to the resource if they are in the group, and if they are the user/password combination as in the password file.
YOU WILL HAVE TO ENSURE THAT YOUR "LOCATION" refers to some content, a "handler"
Handlers can either be built into the server or included in a module, or they can be added with the Action directive
default-handler: Send the file using the default_handler(), which is the handler used by default to handle static content. (core)
send-as-is: Send file with HTTP headers as is. (mod_asis) cgi-script: Treat the file as a CGI script. (mod_cgi) imap-file: Parse as an imagemap rule file. (mod_imap) server-info: Get the server's configuration information. (mod_info) server-status: Get the server's status report. (mod_status) type-map: Parse as a type map file for content negotiation. (mod_negotiation)
The purpose of .htaccess files is to provide a means to configure Apache for users who cannot modify the main configuration file (usually httpd.conf)
.htaccess is a Unix/Linux based file for Apache web servers that allows you to change access permissions on a per directory basis.
When an .htaccess file is in the root directory, it will affect all directories below it.
If you place it in a subdirectory it will affect all the files of that directory (and below).
NOTE: any .htaccess file in the root directory will override those in subdirectories.
Allowing .htaccess files will make Apache look for them upon every access to your server.
Since parent directories are searched as well, this will take some (small) amount of time, and can impact your server's performance.
You must place the .htaccess file in the directory where you want it to take effect.
AuthType Basic AuthName "Authentication Required" AuthUserFile /etc/htpasswds/.htpasswd.example.com Require valid-user Order deny,allow
Most servers have this option disabled, however, some do not. This could leave to a security risk.
Most of the time a directory list will appear if you do not have a Default index file in it.
to hide everything IndexIgnore *
to hide images IndexIgnore .gif .jpg .png .swf
IndexIgnore .htaccess */.??* *~ *# */HEADER* */README* */_vti*
prevent directory listings Options -Indexes
show directory listings Options +Indexes
to hide/prevent access to the .htaccess file
order allow,deny deny from all
<Limit GET POST> order deny,allow deny from all allow from all </Limit> <Limit PUT DELETE> order deny,allow deny from all </Limit>
HOW CAN I DISABLE .HTACCESS TO IMPROVE PERFORMANCE OF APACHE?
AllowOverride is valid only in
Syntax: AllowOverride All|None|directive-type [directive-type] ... Default: AllowOverride All
Ubuntu / apache2 keeps this file in /etc/apache2/sites-available/default
In your server config modify the top-level
<Directory /var/www/html> ... other directives AllowOverride None </Directory>
ACCESS ALLOWED ONLY TO A SPECIFIC SUBNET (or ip address)
Order Deny,Allow Deny from all Allow from 126.96.36.199/16
Note that for Parallels (Virtuozzo?) Virtual Servers they have virtual hosts - after you configure your domains (which will give you ftp access to the www files):
you will have to create a vhost.conf file that when you run the management script will be included via an include statement (therefore your vhosts.conf should NOT include a /Virtual directory clause)
PRODUCT_ROOT_D/admin/sbin/websrvmng --reconfigure-vhost --vhost-name=<domain_name> /usr/local/psa/admin/sbin/websrvmng -u --vhost-name=<domainname>
Restart your server and then type: "more /etc/www/hosts/
htpasswd /usr/local/apache/passwd/passwords username AuthType Basic AuthName "By Invitation Only" AuthUserFile /usr/local/apache/passwd/passwords Require user firstuser seconduser
this will prompt them with a box saying "By Invitation Only" and will lookup the response in the passwords file - only allowing users first/second
create a group file (example of the contents)
authors: rich daniel allan AuthType Basic AuthName "Apache Admin Guide Authors" AuthUserFile /usr/local/apache/passwd/passwords AuthGroupFile /usr/local/apache/passwd/groups Require group authors
Note that in addition to specifically listing the users to whom you want to grant access, you can specify that any valid user should be let in. This is done with the valid-user keyword:
httpd.conf, or create your own virtual host section
In the first line, change ip.address.of.host.some_domain.com to your server's IP address. Change the ServerName to a valid DNS name
<VirtualHost ip.address.of.host.some_domain.com> # ServerAdmin email@example.com_domain.com # DocumentRoot /www/docs/host.some_domain.com # ServerName host.some_domain.com # ErrorLog logs/host.some_domain.com-error_log # CustomLog logs/host.some_domain.com-access_log common #</VirtualHost> #NameVirtualHost 188.8.131.52:80 #NameVirtualHost 184.108.40.206 <VirtualHost ip_address_of_your_server:12331> Listen 12331
Max number of Concurrent Requests
MaxClients= max # of child processes to serve requests (each uses RAM & VSZ) MaxSpareServers MaxRequestsPerChild ThreadsPerChild ServerLimit MaxSpareThreads
You may need to ensure that the DAV is on for apache, a2enmod dav_fs //installs the dav_fs module in apache
STATISTICS AND PERFORMANCE
apt-get install apache2.2-common apt-get install apache2 df -h goes from 450MB to 461MB
DEFAULT: free returns 118MB used
ps -aux USER PID CPU MEM VSZ RSS TTY START COMMAND root 4417 0.0 0.6 10472 2584 ? Ss 15:30 0:00 /usr/sbin/apache2 -k start www-data 4418 0.0 0.4 10244 1780 ? S 15:30 0:00 /usr/sbin/apache2 -k start www-data 4420 0.0 0.6 231808 2396 ? Sl 15:30 0:00 /usr/sbin/apache2 -k start www-data 4424 0.0 0.6 231808 2400 ? Sl 15:30 0:00 /usr/sbin/apache2 -k start
VSZ is a decimal integer, the size in kilobytes of the process in virtual memory.
VSZ includes RSS... Virtual memory usage of entire process = VmLib + VmExe + VmData + VmStk
RSS is real memory (resident set) size of the process in pages in 1KB units
Thus VSZ for apache2 = 231,808 KB x 2 = 500KB...
Dynamically loaded modules: code is loaded when the module is required
Static mode comes at a price - the more modules, the more memory you use. Thus, a forked multi-processing module can have a significant effect on the machine's memory requirements.
MPM WORKER versus PREFORK
Multi-Processing Module with PHP... http://brian.moonspot.net/2008/02/13/apache-worker-and-php/
each apache/php process allocates it's own memory, at ~15MB per process x 50 = 750MB RAM
Having a prefork Apache/PHP process that has 15MB of RAM allocated serve a 10k jpeg image or some CSS file is a waste of resources.
each worker process can have 5 child processes with 10 threads BUT they can reuse memory from other threads in the same process
YOU cannot use radical php extensions ...
ADDING PHP TO CENTOS 5 APACHE 2.2 (HTTPD)
yum search php apt-cache search php
Please follow the best practice of only installing what you need.
If you want to learn/practice with php you'd be better off not using a "production" web server.
Additionally only install the PHP modules you need - installing unnecessary software introduces more places for there to be a backdoor or security hole.