Apache2: Unterschied zwischen den Versionen

Aus crazylinux.de
Zur Navigation springen Zur Suche springen
K (cat)
K (syntaxhighlight)
 
(45 dazwischenliegende Versionen desselben Benutzers werden nicht angezeigt)
Zeile 1: Zeile 1:
als Webserver verwenden wir Apache2 mit PHP4, mod_security, mod_auth_pam, mod_deflate. Desweiteren lassen wir die Logfiles nach einem Tag rotieren. Rotiert wird nach UTC, d.h. wir müssen eine Stunde wieder abziehen (-60).  
als Webserver verwenden wir Apache2 mit PHP, mod_security, mod_auth_pam, mod_deflate. Desweiteren lassen wir die Logfiles nach einem Tag rotieren.


== Multihome-Umgebung ==
=== conf.d/myconfig  ===


In einer Multihome-Umgebung laufen z.b. mehrere verschiedene Domains/Apache-Prozesse auf einem Server. Diese Domains haben aber überhaupt nichts miteinander zu tun. D. h. wiederrum, daß die Domains bzw. der User, die dahinter stehen, natürlich auch kein Zugriff auf die jeweiligen Dateien der andere Domains haben. Gleiches gilt natürlich für den Apache-Prozess! Desweiteren sollten die Apache-Prozesse aus Sicherheitsgründen in einem [http://de.wikipedia.org/wiki/Chroot Chroot] laufen. Diese Funktionalität bringt mod-security mit. Alternativen zu Chroot wären noch z.b. BSD-Jails, Xen, uml (user mode linux), virtuozzo(openvz), bochs, Sun-Zones, qemu bzw. vmware, da chroot auch nicht immer das beste ist, siehe [http://www.bpfh.net/simes/computing/chroot-break.html hier]. Der Vorteil beim chroot von mod-security ist, das man selbst '''kein''' eigenes Chroot bauen muß, da mod-security den chroot-call erst am Ende der Konfiguration macht. Der Apache-Prozess ist also in seinem Document-Root ''gefangen''.
<syntaxhighlight lang="apache">
LogFormat "%v %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" vcombined
LogFormat "%{Host}i %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined


Für die technische Umsetzung bedeutet das folgendes:
# global access log
CustomLog "|| /usr/sbin/vlogger -s access.log -t access.log.%Y.%m -u ${APACHE_RUN_USER} -g ${APACHE_RUN_GROUP} ${APACHE_LOG_DIR}/vlogger" vcombined


*Jede Domain hat eine eigenen User/Gruppe (der User ist nicht in seiner eigene Gruppe!, der User bekommt nur r-Rechte, die Gruppe rw-Rechte. In dieser Gruppe muß auch der User sein, der die Seiten der Website pflegt.)
UseCanonicalName Off
*Chroot ins Document-Root
</syntaxhighlight>
*Jede Domain hat eigene apache2_xxx.conf
*init-script "multidomain"-fähig machen
*Der Sitename darf keine Zahlen am anfang haben, sonst gehen die Scripts nicht.


=== apache2.conf ===
<br>


Bisher war die globale Config in der Datei apache2.conf. Das wollen wir jetzt ändern, aber so, daß die orginal-apache-scripts noch funktionieren. Deshalb kopieren wir apache2.conf nach apache2_common.conf und entfernen die letzte Zeile. Nun eine neue apache2.conf:
=== conf.d/z_security  ===
<pre># include global-apache2.conf
include /etc/apache2/apache2_common.conf
# Include the virtual host configurations:
Include /etc/apache2/sites-enabled/[^.#]
</pre>
=== apache2_website.conf ===


Nun kommt die eigentliche Website-Config /etc/apache2/chroot/xxx.conf
<syntaxhighlight lang="apache"><Directory />
<pre># include global-apache2.conf
        AllowOverride None
include /etc/apache2/apache2_common.conf
      <IfVersion >= 2.4>
LockFile /data/www/meine.de/www/var/lock/apache2/accept.lock
    Require all denied
    </IfVersion>
    <IfVersion < 2.4>
        Order Deny,Allow
        Deny from all
    </IfVersion>
</Directory>


User wwwxxx
Group wwwxxx
ServerRoot "/data/www/meine.de/www"
SecChrootLock /data/www/meine.de/www/log/modsec_chroot.lock
SecChrootDir /data/www/meine.de/www


# PidFile: The file in which the server should record its process
ServerTokens Prod
# identification number when it starts.
ServerSignature Off
PidFile /data/www/meine.de/www/var/run/apache2.pid
TraceEnable Off


Listen 10.0.0.2:82
#SSL
&lt;VirtualHost 10.0.0.2:82&gt;
ServerName www.meine.de
ServerAdmin webmaster@website.tld
DocumentRoot htdocs/
&lt;Directory /&gt;
  Options FollowSymLinks
  AllowOverride all
&lt;/Directory&gt;
ErrorLog log/error.log


php_admin_value open_basedir /var/www/user1/user1-1.tld/
#against BEAST
php_admin_value upload_tmp_dir /var/www/user1/user1-1.tld/temp
SSLHonorCipherOrder On
php_admin_value session.save_path /var/www/user1/user1-1.tld/temp/
php_admin_value safe_mode 1


CustomLog "|/usr/sbin/rotatelogs log/access.log.%Y-%m-%d 86400 -60" combined
SSLCipherSuite          "ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS:!LOW:!MEDIUM"
&lt;/VirtualHost&gt;
SSLCipherSuite AES256+EECDH:AES256+EDH:AES128+EECDH:AES128+EDH:!DES:!NULL:!RC2:!RC4:!3DES:!MD5:!ADH:!AECDH:!EXP:!SHA1
</pre>
== virt. Host ==


bsp site-conf /etc/apache2/sites-available/xxxtemplate:
# enable only secure protocols: TLSv1.2, but not SSLv2
SSLProtocol -ALL -TLSv1 -TLSv1.1 +TLSv1.2
</syntaxhighlight>


  Listen 62.146.xxx.xxx:80
=== conf-avaiable/joomla-admin-block.conf ===
&lt;VirtualHost 62.146.xxx.xxx:80&gt;
Blocks access to /administrator, eg. from joomla
        ServerAdmin webmaster@xxx
and to sample files
        ServerName www.xxxx
 
        ServerAlias xxxx2
But if you have a special cookie you are allowd to access
        DocumentRoot /home/www/xxxx/htdocs
 
        &lt;Directory /&gt;
Just type /admin-mega-hidden
                Options FollowSymLinks
 
                AllowOverride None
<syntaxhighlight lang="apache">
        &lt;/Directory&gt;
#this is global
        ErrorLog "|/usr/sbin/rotatelogs /home/www/xxxx/logs/error.log.%Y.%m.%d 86400 -60"
RewriteEngine On
        # Possible values include: debug, info, notice, warn, error, crit,
 
        # alert, emerg.
#the rules from the current scope are applied before rules specified in any child's scope
        LogLevel warn
#works only if child has 'RewriteEngine On'
        CustomLog "|/usr/sbin/rotatelogs /home/www/xxxx/logs/access.log.%Y.%m.%d 86400 -60" combined
RewriteOptions InheritDownBefore
&lt;/VirtualHost&gt;
 
RewriteCond %{REQUEST_URI} ^/administrator
RewriteCond %{REQUEST_URI} ^/wp-login.php [or]
RewriteCond %{REQUEST_URI} ^/README.txt [OR]
RewriteCond %{REQUEST_URI} ^/LICENSE.txt [OR]
RewriteCond %{REQUEST_URI} ^/htaccess.txt [OR]
RewriteCond %{REQUEST_URI} ^/robots.txt.dist [OR]
RewriteCond %{REQUEST_URI} ^/web.config.txt
RewriteCond %{HTTP_COOKIE} !JoomlaAdminSession=19283ddfgdfgdfgdfgdgdgdg65
 
#send error 404, so it will not be logged in audit.log
RewriteRule .* - [L,F,R=404]
 
 
 
#this php file creates a cookie to access /administrator
Alias /admin-mega-hidden /srv/www/_webrootauth/joomla-admin-12345
<Directory "/srv/www/_webrootauth/joomla-admin-12345/">
        Require all granted
</Directory>
</syntaxhighlight>
 
 
<syntaxhighlight lang="php">
#/srv/www/_webrootauth/joomla-admin-12345/index.php
<?php
$admin_cookie_code="19283ddfgdfgdfgdfgdgdgdg65";
setcookie("JoomlaAdminSession",$admin_cookie_code,0,"/");
header("Location: /administrator/index.php");
?>
</syntaxhighlight>
 
 
<syntaxhighlight lang="bash">
#enable module
a2enconf joomla-admin-block
</syntaxhighlight>


== Module ==
== Module ==
Zeile 82: Zeile 102:
=== Verzeichnisschutz ===
=== Verzeichnisschutz ===


==== mod_auth_pam ====
==== authnz_external (pwauth) ====
replaces mod_auth_pam
 
<syntaxhighlight lang="bash">
apt-get install libapache2-mod-authnz-external pwauth
</syntaxhighlight>
 


Für den Verzeichnisschutz verwenden wir mod_auth_pam, d.h. wir können die gleichen Logindaten wie am System nutzen. '''Damit man eine Gruppe nutzen kann, wird libapache2-mod-auth-sys-group benötigt!'''


eine bsp. .htaccess:
<syntaxhighlight lang="apache">
#/etc/apache2/conf-available/auth_external.conf
AddExternalAuth pwauth /usr/sbin/pwauth
SetExternalAuthMethod pwauth pipe
</syntaxhighlight>


AuthPAM_Enabled on
AuthType Basic
AuthName "secure area"
require group staff


Falls es nicht geht, vom error.log:


[error] [client 217.229.133.31] PAM: user 'xyz' - not authenticated: Authentication failure
<syntaxhighlight lang="apache">
AuthBasicProvider external
AuthExternal pwauth
Require user user
</syntaxhighlight>


'''Der User www-data muß Mitglied der Gruppe shadow sein!'''
see http://icephoenix.us/linuxunix/apache-and-http-authentication-with-pam/


==== mod_auth_mysql ====
==== authnz_external (imap) ====
replaces mod_auth_imap
[http://www.namazustudios.com/files/checkpasswd-imap.tar.bz2 Download]


alternativ kann man die User für den Schutz auch in eine MySQL-DB ablegen, anstatt z.b. aus passwd (PAM)
<syntaxhighlight lang="ini">
#/etc/checkpasswd-imap.ini
[localhost]
host = localhost
port = 1143
cache-dir = /srv/www/_tmp
allow-everybody = .*
</syntaxhighlight>


*MySQL-DB und Tabelle anlegen
<pre>CREATE TABLE `clients` (
`username` varchar(25) NOT NULL default '',
`passwd` varchar(25) NOT NULL default '',
`groups` varchar(25) NOT NULL default '',
PRIMARY KEY (`username`),
KEY `groups` (`groups`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;


INSERT INTO `clients` VALUES ('&lt;username&gt;', password('&lt;password&gt;'), '&lt;group&gt;');
<syntaxhighlight lang="apache">
</pre>  
#/etc/apache2/conf-available/auth_external.conf
*Modul in der Site (VirtualHost) aktivieren
AddExternalAuth imapauth /usr/bin/checkpasswd-imap-pipe.py
<pre>#/etc/apache2/sites-available/domain.com
SetExternalAuthMethod imapauth pipe
Auth_MySQL_Info localhost mysqluser mysqlpasswd
</syntaxhighlight>
</pre>
und Schutz aktivieren (.htaccess)
<pre>AuthMYSQL on
AuthMySQL_Authoritative on
AuthMySQL_DB mysqldb
AuthMySQL_Password_Table clients
AuthMySQL_Group_Table clients
AuthMySQL_Empty_Passwords off
AuthMySQL_Encryption_Types MySQL


AuthName Adminarea
 
<syntaxhighlight lang="apache">
#virtual host
AuthType Basic
AuthType Basic
    AuthName "Authentication Required"
    AuthBasicProvider external
    AuthExternal imapauth
require valid-user
</syntaxhighlight>


&lt;Limit GET POST&gt;
=== mod_security  ===
require group www
&lt;/Limit&gt;


</pre>  
ModSecurity is an open source, free web application firewall (WAF) Apache module. With over 70% of all attacks now carried out over the web application level, organizations need all the help they can get in making their systems secure. WAFs are deployed to establish an external security layer that increases security, detects and prevents attacks before they reach web applications. It provides protection from a range of attacks against web applications and allows for HTTP traffic monitoring and real-time analysis with little or no changes to existing infrastructure.<br>  
==== mod-auth-imap ====


Source: http://ben.brillat.net/projects/mod_auth_imap/<br> kleines Howto: https://hw.cs.southern.edu/prot/mod_auth_imap.htm
Installation http://www.thefanclub.co.za/how-to/how-install-apache2-modsecurity-and-modevasive-ubuntu-1204-lts-server<br>  


Debian-Package (http://debian.gallet.info/locale.do?language=en): http://www.gallet.info.free.fr/debian/pool/main/sarge/libapache2-mod-auth-imap/libapache2-mod-auth-imap_2.0.2-1_i386.deb oder per source.list
==== Links ====
<pre>deb http://www.gallet.info.free.fr/debian/ sarge contrib main non-free
*http://www.atomicorp.com/wiki/index.php/Mod_security
deb-src http://www.gallet.info.free.fr/debian/ sarge contrib main non-free
*https://blog.art-of-coding.eu/implementing-a-web-application-firewall/


deb http://www.gallet.info.free.fr/debian/ sarge-update contrib main non-free
====Install====
deb-src http://www.gallet.info.free.fr/debian/ sarge-update contrib main non-free
<syntaxhighlight lang="apache">
</pre>
#/etc/modsecurity/modsecurity.conf
<br> .htaccess
SecRuleEngine On
<pre>#Turn on IMAP Authentication
Auth_IMAP_Enabled on


#Give a name to the authentication domain, whatever you want:
SecRequestBodyLimit 16384000
AuthName "SAU Email username and password"
SecRequestBodyInMemoryLimit 16384000


#Only basic authentication is supported for now:
SecTmpDir /var/cache/modsecurity/
AuthType Basic
SecDataDir /var/cache/modsecurity/
SecUploadDir /var/cache/modsecurity/upload/


#If you feel like it, restrict the users or allow all valid users:
#don't log credentials to logfile
Require valid-user
SecDefaultAction "phase:1,deny,log,sanitiseRequestHeader:Authorization"
#Make IMAP Authentication authoritative for this .htaccess file:
SecDefaultAction "phase:2,deny,log,sanitiseRequestHeader:Authorization"
Auth_IMAP_Authoritative on
</syntaxhighlight>
<br> <br> <syntaxhighlight lang="bash">
cd /etc/modsecurity
mv /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf
mkdir activated_rules activated_optional_rules
ln -s /usr/share/modsecurity-crs/base_rules base_rules
ln -s /usr/share/modsecurity-crs/optional_rules/ optional_rules
cd base_rules
for f in `ls *` ; do ln -s /etc/modsecurity/base_rules/$f /etc/modsecurity/activated_rules/$f ; done
cd ..


#Set the IMAP Server to which you want to connect (default=localhost):
cd optional_rules
Auth_IMAP_Server imap.southern.edu
for f in `ls *` ; do ln -s /etc/modsecurity/optional_rules/$f /etc/modsecurity/activated_optional_rules/$f ; done
cd ..


#Set the port on which the imap server is running (default=143):
ln -s /usr/share/modsecurity-crs/modsecurity_crs_10_config.conf
Auth_IMAP_Port 143
</syntaxhighlight>


#Turn on some extra logging (login attempts, etc.) in Apache's Error Log
====Enable module in apache====
Auth_IMAP_Log on
<syntaxhighlight lang="apache">
</pre>  
#/etc/apache2/mods-available/mod-security.conf
=== mod_security ===
...
Include "/etc/modsecurity/*.conf"
Include "/etc/modsecurity/activated_rules/*.conf"
Include "/etc/modsecurity/activated_optional_rules/*.conf"
...
</syntaxhighlight>  


ModSecurity is an open source, free web application firewall (WAF) Apache module. With over 70% of all attacks now carried out over the web application level, organizations need all the help they can get in making their systems secure. WAFs are deployed to establish an external security layer that increases security, detects and prevents attacks before they reach web applications. It provides protection from a range of attacks against web applications and allows for HTTP traffic monitoring and real-time analysis with little or no changes to existing infrastructure.<br>  
====optional disable filter====
Für bestimmte Verzeichnisse kann man den Filter auch ausstellen: <syntaxhighlight lang="apache">


Installation http://www.vinno.net/linux/server/how-to-install-mod-security-2<br>  
<LocationMatch "/ajaxplorer/">
SecRuleRemoveById 200003 960024 960915
</LocationMatch>


<source lang="apache">
OR
#v1.9x
#/etc/apache2/mods-avaible/mod-security.conf
<IfModule mod_security.c>
    # Turn the filtering engine On or Off
    SecFilterEngine On
    # Make sure that URL encoding is valid
    SecFilterCheckURLEncoding On
    # Only allow bytes from this range
    SecFilterForceByteRange 1 255
    # The audit engine works independently and
    # can be turned On of Off on the per-server or
    # on the per-directory basis
    SecAuditEngine RelevantOnly
    # The name of the audit log file
    SecAuditLog /var/log/apache2/audit_log
    SecFilterDebugLog /var/log/apache2/modsec_debug_log
    SecFilterDebugLevel 0
    # Should mod_security inspect POST payloads
    SecFilterScanPOST On
    # Action to take by default
    SecFilterDefaultAction "deny,log,status:406"
    # Prevent OS specific keywords
    SecFilter /etc/ password
    SecFilter /bin/ ls
    # Prevent path traversal (..) attacks
    SecFilter "\.\./"
    # Weaker XSS protection but allows common HTML tags
    SecFilter "<( |\n)*script"
    # Prevent XSS atacks (HTML/Javascript injection)
    #SecFilter "<(.|\n)+>"
</IfModule>
</source>


Für bestimmte Verzeichnisse kann man den Filter auch ausstellen: <source lang="apache">
<Location /upload.php>
<Location /upload.php>
     # Do not inherit filters from the parent folder
     # Do not inherit filters from the parent folder
     SecFilterInheritance Off
     SecFilterInheritance Off
</Location>
</Location>
</source>  
</syntaxhighlight>  


[http://www.infosecwriters.com/texts.php?op=display&id=255Defending Web Services using Mod Security (Apache) Methodology and Filtering Techniques by Shreeraj Shah on 19/01/05]


http://www.gotroot.com/mod_security+rules
====Virus-Scanner for uploaded files ====
<syntaxhighlight lang="apache">
#in modsecurity_crs_46_av_scanning.conf
#
# Modify the operator to use the correct AV scanning script/tool
# Example tools are in the util directory.
#


[http://www.heise.de/security/artikel/69070/0 Die Apache-Firewall: Web-Server mit mod_security absichern]
SecRule FILES_TMPNAMES "@inspectFile /usr/bin/runAV.pl" \
        "phase:2,t:none,block,msg:'Virus found in uploaded file',id:'950115',tag:'MALICIOUS_SOFTWARE/VIRUS',tag:'PCI/5.1',severity:'2',setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},setvar:tx.%{rule.id}-MALICIOUS_SOFTWARE/VIRUS-%{matched_var_name}=%{tx.0}"
</syntaxhighlight>


=== mod_php ===
==== Global Blacklist ====
<syntaxhighlight lang="apache">
#/etc/apache2/conf.d/modsecurity-blacklist
#disable rule for all domains


Aus Sicherheitsgründen vestecken wir die PHP-Version im HTTP-Header /etc/php4/apache2/php.ini
#missing_request_header
SecRuleRemoveById 960015


expose_php = off
#Request Missing a User Agent Header
memory_limit = 50M    &nbsp;; Maximum amount of memory a script may consume (8MB)
SecRuleRemoveById 960009
allow_url_fopen = Off
</syntaxhighlight>
[Zend]
zend_optimizer.optimization_level=15
zend_extension_manager.optimizer=/usr/lib/php4/Zend/lib/Optimizer-2.5.10
zend_extension_manager.optimizer_ts=/usr/lib/php4/Zend/lib/Optimizer_TS-2.5.10
zend_optimizer.version=2.5.10a
#zend_extension=/usr/lib/php4/Zend/lib/ZendExtensionManager.so
zend_extension=/usr/lib/php4/20020429/php_accelerator_1.3.3r2.so
#zend_extension_ts=/usr/lib/php4/Zend/lib/ZendExtensionManager_TS.so


PHP kann man auch mit Hilfe von fastcgi als cgi installieren. Desweiteren ist es dann möglich, die einzelnen PHP-prozesse unter verschiedenen Usern laufen zu lassen. Die Anleitung gibts hier: http://www.debianhowto.de/doku.php/de:howtos:sarge:apache2_php-fcgi


Security-Tips: http://aymanh.com/checklist-for-securing-php-configuration
==== bad robot data ====
/etc/modsecurity/activated_rules/modsecurity_35_bad_robots.data
e.g. to remove surveybot


=== mod_dav ===
====Links====
*[http://youresuchageek.blogspot.de/2012/11/howto-apache2-modsecurity-enhance-your.html Howto - Apache2 ModSecurity - Enhance your Web Server and Applications security with an Opensource Web Application Firewall (WAF)]
*[https://github.com/SpiderLabs/ModSecurity/wiki/Reference-Manual Reference Manual]
*[http://www.infosecwriters.com/texts.php?op=display&id=255Defending Web Services using Mod Security (Apache) Methodology and Filtering Techniques by Shreeraj Shah on 19/01/05]
*http://www.gotroot.com/mod_security+rules
*[http://www.heise.de/security/artikel/69070/0 Die Apache-Firewall: Web-Server mit mod_security absichern]


[http://httpd.apache.org/docs/2.0/mod/mod_dav.html WEBDAV-Modul] für Apache. Damit ist es möglich Dateien über https zu manipulieren (ändern, löschen, erstellen usw.). installieren: a2enmod dav
=== mod_php  ===


<br> gretchen:/etc/mail# more /etc/apache2/mods-enabled/dav_fs.conf
see [[PHP|PHP]]


DAVLockDB /var/lock/apache2/DAVLock
=== mod_dav ===


httpd.conf
[http://httpd.apache.org/docs/2.0/mod/mod_dav.html WEBDAV-Modul] für Apache. Damit ist es möglich Dateien über https zu manipulieren (ändern, löschen, erstellen usw.). installieren: a2enmod dav


<syntaxhighlight lang="apache">
#httpd.conf
  Alias /phparea /home/gstein/php_files
  Alias /phparea /home/gstein/php_files
  Alias /php-source /home/gstein/php_files
  Alias /php-source /home/gstein/php_files
  DavLockDB /tmp/DavLock.myvhost
  DavLockDB /tmp/DavLock.myvhost
  &lt;Location /php-source&gt;
  <Location /php-source>
   Dav On
   Dav On
   AuthType Basic
   AuthType Basic
Zeile 263: Zeile 282:
   require group staff
   require group staff
   php_flag engine off # oder  ForceType text/plain
   php_flag engine off # oder  ForceType text/plain
  &lt;/Location&gt;
  </Location>
</syntaxhighlight>


=== mod_evasive ===
=== mod_evasive ===
Zeile 275: Zeile 295:
*Making any requests while temporarily blacklisted (on a blocking list)
*Making any requests while temporarily blacklisted (on a blocking list)


http://www.debianhowto.de/doku.php/de:howtos:sarge:mod_evasive
<syntaxhighlight lang="apache">
 
ungetestet: <source lang="apache">
<IfModule mod_evasive.c>
<IfModule mod_evasive.c>
   #DOSHashTableSize gibt die Größe der Hashtabelle in Bytes an
   #DOSHashTableSize gibt die Größe der Hashtabelle in Bytes an
Zeile 283: Zeile 301:


   #DOSPageCount gibt die Anzahl der Seitenaufrufe eines Clients pro DOSPageInterval-Zeitintervall
   #DOSPageCount gibt die Anzahl der Seitenaufrufe eines Clients pro DOSPageInterval-Zeitintervall
   DOSPageCount 5
   DOSPageCount 2


   #DOSSiteCount gibt die Anzahl der Seitenaufrufe auf einen Child-Prozess pro DOSSiteInterval-Zeitintervall
   #DOSSiteCount gibt die Anzahl der Seitenaufrufe auf einen Child-Prozess pro DOSSiteInterval-Zeitintervall
Zeile 302: Zeile 320:


   #DOSLogDir gibt das Verzeichnis an in dem das Modul seine Logfiles schreibt
   #DOSLogDir gibt das Verzeichnis an in dem das Modul seine Logfiles schreibt
   DOSLogDir "/var/log/apache2/"
   DOSLogDir /srv/www/vlogger/_mod_evasive


   #DOSWhitelist beinhaltet eine Aufzählung aller IP-Adressen für die mod_evasive NICHT gilt
   #DOSWhitelist beinhaltet eine Aufzählung aller IP-Adressen für die mod_evasive NICHT gilt
   #DOSWhitelist 127.0.0.1
   DOSWhitelist 127.0.0.1
</IfModule>
</IfModule>
</source>  
</syntaxhighlight>


=== mod_cband  ===
=== mod_cband  ===
Zeile 314: Zeile 332:


=== mod_ssl  ===
=== mod_ssl  ===
config see above (z_security)
SSL-Test: https://www.ssllabs.com/ssltest/ or https://observatory.mozilla.org/


Disable SSLv2, from http://aruljohn.com/info/sslversion/  
== Logging POST requests with Apache ==
found on https://www.technovelty.org/web/logging-post-requests-with-apache.html


<source lang="apache">
<syntaxhighlight lang="apache">
SSLProtocol -all +SSLv3
SecRuleEngine On
SSLCipherSuite SSLv3:+HIGH:+MEDIUM
SecAuditEngine on
</source>  
SecAuditLog /var/log/apache2/website-audit.log
SecRequestBodyAccess on
SecAuditLogParts ABIFHZ
 
SecDefaultAction "nolog,noauditlog,allow,phase:2"
 
SecRule REQUEST_METHOD "^POST$" "chain,allow,phase:2"
SecRule REQUEST_URI ".*" "auditlog"
 
</syntaxhighlight>


== Links ==
== Links ==


http://httpd.apache.org/docs/2.0/programs/rotatelogs.html<br> http://www.php-accelerator.co.uk/<br> [http://mambo.edes.at/index.php?option=com_docman&Itemid=30&task=view_category&catid=81&order=dmdate_published&ascdesc=DESC, ''PHPACA Web Front End'']<br> http://www.modsecurity.org/<br> http://www.nuclearelephant.com/projects/mod_evasive/<br> [http://www.askapache.com/2006/htaccess/speed-up-sites-with-htaccess-caching.html/ Speed Up Sites with htaccess Caching]
* http://www.modsecurity.org/
 
* http://www.nuclearelephant.com/projects/mod_evasive/
[[Category:WWW]]
* [https://www.askapache.com/htaccess/speed-up-sites-with-htaccess-caching/ Speed Up Sites with htaccess Caching]


[[Kategorie:WWW]]
[[Kategorie:WWW]]
[[Kategorie:Apache]]
[[Kategorie:Apache]]

Aktuelle Version vom 13. September 2024, 12:21 Uhr

als Webserver verwenden wir Apache2 mit PHP, mod_security, mod_auth_pam, mod_deflate. Desweiteren lassen wir die Logfiles nach einem Tag rotieren.

conf.d/myconfig

LogFormat "%v %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" vcombined
LogFormat "%{Host}i %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined

# global access log
CustomLog "|| /usr/sbin/vlogger -s access.log -t access.log.%Y.%m -u ${APACHE_RUN_USER} -g ${APACHE_RUN_GROUP} ${APACHE_LOG_DIR}/vlogger" vcombined

UseCanonicalName Off


conf.d/z_security

<Directory />
        AllowOverride None
      <IfVersion >= 2.4>
    Require all denied
    </IfVersion>
    <IfVersion < 2.4>
        Order Deny,Allow
        Deny from all
    </IfVersion>
</Directory>


ServerTokens Prod
ServerSignature Off
TraceEnable Off

#SSL

#against BEAST
SSLHonorCipherOrder On

SSLCipherSuite          "ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS:!LOW:!MEDIUM"
SSLCipherSuite AES256+EECDH:AES256+EDH:AES128+EECDH:AES128+EDH:!DES:!NULL:!RC2:!RC4:!3DES:!MD5:!ADH:!AECDH:!EXP:!SHA1

# enable only secure protocols: TLSv1.2, but not SSLv2
SSLProtocol -ALL -TLSv1 -TLSv1.1 +TLSv1.2

conf-avaiable/joomla-admin-block.conf

Blocks access to /administrator, eg. from joomla and to sample files

But if you have a special cookie you are allowd to access

Just type /admin-mega-hidden

#this is global
RewriteEngine On

#the rules from the current scope are applied before rules specified in any child's scope
#works only if child has 'RewriteEngine On'
RewriteOptions InheritDownBefore

RewriteCond %{REQUEST_URI} ^/administrator
RewriteCond %{REQUEST_URI} ^/wp-login.php [or]
RewriteCond %{REQUEST_URI} ^/README.txt [OR]
RewriteCond %{REQUEST_URI} ^/LICENSE.txt [OR]
RewriteCond %{REQUEST_URI} ^/htaccess.txt [OR]
RewriteCond %{REQUEST_URI} ^/robots.txt.dist [OR]
RewriteCond %{REQUEST_URI} ^/web.config.txt
RewriteCond %{HTTP_COOKIE} !JoomlaAdminSession=19283ddfgdfgdfgdfgdgdgdg65

#send error 404, so it will not be logged in audit.log
RewriteRule .* - [L,F,R=404]



#this php file creates a cookie to access /administrator
Alias /admin-mega-hidden /srv/www/_webrootauth/joomla-admin-12345
<Directory "/srv/www/_webrootauth/joomla-admin-12345/">
        Require all granted
</Directory>


#/srv/www/_webrootauth/joomla-admin-12345/index.php
<?php
$admin_cookie_code="19283ddfgdfgdfgdfgdgdgdg65";
setcookie("JoomlaAdminSession",$admin_cookie_code,0,"/");
header("Location: /administrator/index.php");
?>


#enable module
a2enconf joomla-admin-block

Module

Verzeichnisschutz

authnz_external (pwauth)

replaces mod_auth_pam

apt-get install libapache2-mod-authnz-external pwauth


#/etc/apache2/conf-available/auth_external.conf
AddExternalAuth pwauth /usr/sbin/pwauth
SetExternalAuthMethod pwauth pipe


AuthBasicProvider external
AuthExternal pwauth
Require user user

see http://icephoenix.us/linuxunix/apache-and-http-authentication-with-pam/

authnz_external (imap)

replaces mod_auth_imap Download

#/etc/checkpasswd-imap.ini
[localhost]
host = localhost
port = 1143
cache-dir = /srv/www/_tmp
allow-everybody = .*


#/etc/apache2/conf-available/auth_external.conf
AddExternalAuth imapauth /usr/bin/checkpasswd-imap-pipe.py
SetExternalAuthMethod imapauth pipe


#virtual host
AuthType Basic
    AuthName "Authentication Required"
    AuthBasicProvider external
    AuthExternal imapauth
require valid-user

mod_security

ModSecurity is an open source, free web application firewall (WAF) Apache module. With over 70% of all attacks now carried out over the web application level, organizations need all the help they can get in making their systems secure. WAFs are deployed to establish an external security layer that increases security, detects and prevents attacks before they reach web applications. It provides protection from a range of attacks against web applications and allows for HTTP traffic monitoring and real-time analysis with little or no changes to existing infrastructure.

Installation http://www.thefanclub.co.za/how-to/how-install-apache2-modsecurity-and-modevasive-ubuntu-1204-lts-server

Links

Install

#/etc/modsecurity/modsecurity.conf
SecRuleEngine On

SecRequestBodyLimit 16384000
SecRequestBodyInMemoryLimit 16384000

SecTmpDir /var/cache/modsecurity/
SecDataDir /var/cache/modsecurity/
SecUploadDir /var/cache/modsecurity/upload/

#don't log credentials to logfile
SecDefaultAction "phase:1,deny,log,sanitiseRequestHeader:Authorization"
SecDefaultAction "phase:2,deny,log,sanitiseRequestHeader:Authorization"



cd /etc/modsecurity
mv /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf
mkdir activated_rules activated_optional_rules
ln -s /usr/share/modsecurity-crs/base_rules base_rules
ln -s /usr/share/modsecurity-crs/optional_rules/ optional_rules
cd base_rules
for f in `ls *` ; do ln -s /etc/modsecurity/base_rules/$f /etc/modsecurity/activated_rules/$f ; done
cd ..

cd optional_rules
for f in `ls *` ; do ln -s /etc/modsecurity/optional_rules/$f /etc/modsecurity/activated_optional_rules/$f ; done
cd ..

ln -s /usr/share/modsecurity-crs/modsecurity_crs_10_config.conf

Enable module in apache

#/etc/apache2/mods-available/mod-security.conf
...
Include "/etc/modsecurity/*.conf"
Include "/etc/modsecurity/activated_rules/*.conf"
Include "/etc/modsecurity/activated_optional_rules/*.conf"
...

optional disable filter

Für bestimmte Verzeichnisse kann man den Filter auch ausstellen:

<LocationMatch "/ajaxplorer/">
SecRuleRemoveById 200003 960024 960915
</LocationMatch>

OR

<Location /upload.php>
    # Do not inherit filters from the parent folder
    SecFilterInheritance Off
</Location>


Virus-Scanner for uploaded files

#in modsecurity_crs_46_av_scanning.conf
#
# Modify the operator to use the correct AV scanning script/tool
# Example tools are in the util directory.
#

SecRule FILES_TMPNAMES "@inspectFile /usr/bin/runAV.pl" \
        "phase:2,t:none,block,msg:'Virus found in uploaded file',id:'950115',tag:'MALICIOUS_SOFTWARE/VIRUS',tag:'PCI/5.1',severity:'2',setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},setvar:tx.%{rule.id}-MALICIOUS_SOFTWARE/VIRUS-%{matched_var_name}=%{tx.0}"

Global Blacklist

#/etc/apache2/conf.d/modsecurity-blacklist 
#disable rule for all domains

#missing_request_header
SecRuleRemoveById 960015

#Request Missing a User Agent Header
SecRuleRemoveById 960009


bad robot data

/etc/modsecurity/activated_rules/modsecurity_35_bad_robots.data e.g. to remove surveybot

Links

mod_php

see PHP

mod_dav

WEBDAV-Modul für Apache. Damit ist es möglich Dateien über https zu manipulieren (ändern, löschen, erstellen usw.). installieren: a2enmod dav

#httpd.conf 
 Alias /phparea /home/gstein/php_files
 Alias /php-source /home/gstein/php_files
 DavLockDB /tmp/DavLock.myvhost
 <Location /php-source>
  Dav On
  AuthType Basic
  AuthName DAV
  AuthPAM_Enabled on
  require group staff
  php_flag engine off # oder  ForceType text/plain
 </Location>

mod_evasive

mod_evasive is an evasive maneuvers module for Apache to provide evasive action in the event of an HTTP DoS or DDoS attack or brute force attack. It is also designed to be a detection and network management tool, and can be easily configured to talk to ipchains, firewalls, routers, and etcetera. mod_evasive presently reports abuses via email and syslog facilities.

Detection is performed by creating an internal dynamic hash table of IP Addresses and URIs, and denying any single IP address from any of the following:

  • Requesting the same page more than a few times per second
  • Making more than 50 concurrent requests on the same child per second
  • Making any requests while temporarily blacklisted (on a blocking list)
<IfModule mod_evasive.c>
  #DOSHashTableSize gibt die Größe der Hashtabelle in Bytes an
  DOSHashTableSize 3097

  #DOSPageCount gibt die Anzahl der Seitenaufrufe eines Clients pro DOSPageInterval-Zeitintervall
  DOSPageCount 2

  #DOSSiteCount gibt die Anzahl der Seitenaufrufe auf einen Child-Prozess pro DOSSiteInterval-Zeitintervall
  DOSSiteCount 50

  #DOSPageInterval und DOSSiteInterval werden in Sekunden angegeben
  DOSPageInterval 1
  DOSSiteInterval 1

  #DOSBlockingPeriod gibt die Sperrzeit in Seknunden an
  DOSBlockingPeriod 60

  #DOSEmailNotify gibts die eMail Adresse an, an welche eine Warnmail geschickt wird
  DOSEmailNotify admin@mydomain.net

  #DOSSystemCommand führt bei einem Angriff weitere Programme/Scripte aus wenn gewünscht
  #DOSSystemCommand "su - someuser -c '/sbin/... %s ...'"

  #DOSLogDir gibt das Verzeichnis an in dem das Modul seine Logfiles schreibt
  DOSLogDir /srv/www/vlogger/_mod_evasive

  #DOSWhitelist beinhaltet eine Aufzählung aller IP-Adressen für die mod_evasive NICHT gilt
  DOSWhitelist 127.0.0.1
</IfModule>

mod_cband

Bandbreiten-Beschränkung http://nodomain.cc/archives/2007/01/05/684-Apache2-Zugriffskontrolle-mit-mod_cband.html

mod_ssl

config see above (z_security)

SSL-Test: https://www.ssllabs.com/ssltest/ or https://observatory.mozilla.org/

Logging POST requests with Apache

found on https://www.technovelty.org/web/logging-post-requests-with-apache.html

SecRuleEngine On
SecAuditEngine on
SecAuditLog /var/log/apache2/website-audit.log
SecRequestBodyAccess on
SecAuditLogParts ABIFHZ

SecDefaultAction "nolog,noauditlog,allow,phase:2"

SecRule REQUEST_METHOD "^POST$" "chain,allow,phase:2"
SecRule REQUEST_URI ".*" "auditlog"

Links