Ceci est une ancienne révision du document !
Table des matières
APF102 - Gestion Avancée du Serveur Web Apache 2.4
Contenu de ce Cours
Dans ce cours, vous allez apprendre par la pratique :
- LAB #1 - Gestion des pages dynamiques avec mod_php
- LAB #2 - Gestion de l'authentification avec .htpasswd et mod_auth_basic
- LAB #3 - Gestion de l'authentification avec MariaDB et mod_authn_dbd
- LAB #4 - Gestion de l'authentification avec OpenLDAP et mod_authnz_ldap
- LAB #5 - Gestion des pages web sécurisées en https avec mod_ssl
- LAB #6 - Gestion d'un Serveur Mandataire avec mod_proxy
- LAB #7 - Gestion du Content Caching avec mod_cache et mod_cache_disk
- LAB #8 - Gestion d'un Reverse Proxy avec mod_proxy
- LAB #9 - Gestion du Web-based Distributed Authoring and Versioning avec mod_dav
- LAB #10 - Gestion de la réécriture d'URL avec mod_rewrite
- LAB #11 - Personnalisation des en-têtes de requêtes et de réponses HTTP avec mod_header
- LAB #12 - L'exécution des scripts CGI sous un utilisateur et un groupe spécifiés avec mod_suexec
- LAB #13 - Améliorer l'utilisation de la Mémoire du Serveur avec mod_worker
Préparation
Désactivez le mode enforcing de SELINUX afin de pouvoir librement travailler avec Apache :
[root@centos7 ~]# setenforce permissive [root@centos7 ~]# getenforce Permissive [root@centos7 ~]# vi /etc/sysconfig/selinux [root@centos7 ~]# cat /etc/sysconfig/selinux # This file controls the state of SELinux on the system. # SELINUX= can take one of these three values: # enforcing - SELinux security policy is enforced. # permissive - SELinux prints warnings instead of enforcing. # disabled - No SELinux policy is loaded. SELINUX=permissive # SELINUXTYPE= can take one of three two values: # targeted - Targeted processes are protected, # minimum - Modification of targeted policy. Only selected processes are protected. # mls - Multi Level Security protection. SELINUXTYPE=targeted
Afin d'éviter les problèmes liés au pare-feu arrêtez le service firewalld :
[root@centos7 ~]# systemctl stop firewalld [root@centos7 ~]# systemctl disable firewalld [root@centos7 ~]# systemctl status firewalld ● firewalld.service - firewalld - dynamic firewall daemon Loaded: loaded (/usr/lib/systemd/system/firewalld.service; disabled; vendor preset: enabled) Active: inactive (dead) Docs: man:firewalld(1) Aug 21 16:23:02 centos7.fenestros.loc systemd[1]: Starting firewalld - dynamic firewall daemon... Aug 21 16:23:07 centos7.fenestros.loc systemd[1]: Started firewalld - dynamic firewall daemon. Aug 21 16:29:49 centos7.fenestros.loc systemd[1]: Stopping firewalld - dynamic firewall daemon... Aug 21 16:29:49 centos7.fenestros.loc systemd[1]: Stopped firewalld - dynamic firewall daemon.
Installation à partir des dépôts
Sous RHEL / CentOS 7, Apache n'est pas installé par défaut. Utilisez donc yum pour l'installer :
[root@centos7 ~]# rpm -qa | grep httpd [root@centos7 ~]# [root@centos7 ~]# yum install httpd
La version d'Apache est la 2.4.6 :
[root@centos7 ~]# rpm -qa | grep httpd httpd-2.4.6-45.el7.centos.4.x86_64 httpd-tools-2.4.6-45.el7.centos.4.x86_64
Configurez le service pour démarrer automatiquement :
[root@centos7 ~]# systemctl status httpd ● httpd.service - The Apache HTTP Server Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled) Active: inactive (dead) Docs: man:httpd(8) man:apachectl(8) [root@centos7 ~]# systemctl enable httpd Created symlink from /etc/systemd/system/multi-user.target.wants/httpd.service to /usr/lib/systemd/system/httpd.service.
Lancez votre service apache :
[root@centos7 ~]# systemctl start httpd [root@centos7 ~]# systemctl status httpd ● httpd.service - The Apache HTTP Server Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled) Active: active (running) since Tue 2017-08-22 11:19:18 CEST; 3s ago Docs: man:httpd(8) man:apachectl(8) Main PID: 1293 (httpd) Status: "Processing requests..." CGroup: /system.slice/httpd.service ├─1293 /usr/sbin/httpd -DFOREGROUND ├─1296 /usr/sbin/httpd -DFOREGROUND ├─1297 /usr/sbin/httpd -DFOREGROUND ├─1298 /usr/sbin/httpd -DFOREGROUND ├─1299 /usr/sbin/httpd -DFOREGROUND └─1300 /usr/sbin/httpd -DFOREGROUND Aug 22 11:19:18 centos7.fenestros.loc systemd[1]: Starting The Apache HTTP Server... Aug 22 11:19:18 centos7.fenestros.loc systemd[1]: Started The Apache HTTP Server.
Administration Avancée
Important - La suite de ce cours est basée sur l'utilisation de la distribution RHEL / CentOS 7.
LAB #1 - Gestion des pages dynamiques avec mod_php
Introduction
PHP existe en plusieurs versions dont les deux versions courrament utilisées sont :
- La version 5.6
- La version 7.x
Mise en place
Dans ce LAB, vous allez apprendre comment faire co-habiter les deux versions.
Commencez par installer le dépôt EPEL :
[root@centos7 ~]# yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
Continuez en installant le dépôt REMI qui contient les différentes versions de PHP dont nous aurons besoin :
[root@centos7 ~]# yum install http://rpms.remirepo.net/enterprise/remi-release-7.rpm
Installez maintenant les versions 5.6 et 7.2 de PHP :
[root@centos7 ~]# yum install yum-utils php56 php72 php56-php-fpm php72-php-fpm -y
Par défaut, les deux serveurs FPM écoutent sur le port 9000. Modifiez le port pour chaque version de PHP :
[root@centos7 ~]# sed -i 's/:9000/:9056/' /etc/opt/remi/php56/php-fpm.d/www.conf [root@centos7 ~]# sed -i 's/:9000/:9072/' /etc/opt/remi/php72/php-fpm.d/www.conf
Démarrez les deux serveurs FPM :
[root@centos7 ~]# systemctl start php56-php-fpm [root@centos7 ~]# systemctl status php56-php-fpm ● php56-php-fpm.service - The PHP FastCGI Process Manager Loaded: loaded (/usr/lib/systemd/system/php56-php-fpm.service; disabled; vendor preset: disabled) Active: active (running) since Sun 2018-09-02 16:12:39 CEST; 7s ago Main PID: 25889 (php-fpm) Status: "Ready to handle connections" CGroup: /system.slice/php56-php-fpm.service ├─25889 php-fpm: master process (/opt/remi/php56/root/etc/php-fpm.conf) ├─25890 php-fpm: pool www ├─25891 php-fpm: pool www ├─25892 php-fpm: pool www ├─25893 php-fpm: pool www └─25894 php-fpm: pool www Sep 02 16:12:39 centos7.fenestros.loc systemd[1]: Starting The PHP FastCGI Process Manager... Sep 02 16:12:39 centos7.fenestros.loc systemd[1]: Started The PHP FastCGI Process Manager. [root@centos7 ~]# [root@centos7 ~]# systemctl start php72-php-fpm [root@centos7 ~]# systemctl status php72-php-fpm ● php72-php-fpm.service - The PHP FastCGI Process Manager Loaded: loaded (/usr/lib/systemd/system/php72-php-fpm.service; disabled; vendor preset: disabled) Active: active (running) since Sun 2018-09-02 16:13:03 CEST; 1s ago Main PID: 26083 (php-fpm) Status: "Ready to handle connections" CGroup: /system.slice/php72-php-fpm.service ├─26083 php-fpm: master process (/etc/opt/remi/php72/php-fpm.conf) ├─26084 php-fpm: pool www ├─26085 php-fpm: pool www ├─26086 php-fpm: pool www ├─26087 php-fpm: pool www └─26088 php-fpm: pool www Sep 02 16:13:03 centos7.fenestros.loc systemd[1]: Starting The PHP FastCGI Process Manager... Sep 02 16:13:03 centos7.fenestros.loc systemd[1]: Started The PHP FastCGI Process Manager.
Créez deux scripts CGI pour appeler php56-cgi et php72-cgi :
[root@centos7 ~]# cat > /var/www/cgi-bin/php56.fcgi << EOF > #!/bin/bash > exec /bin/php56-cgi > EOF [root@centos7 ~]# cat > /var/www/cgi-bin/php72.fcgi << EOF > #!/bin/bash > exec /bin/php72-cgi > EOF
Rendez les deux scripts CGI exécutables :
[root@centos7 ~]# chmod 755 /var/www/cgi-bin/php56.fcgi [root@centos7 ~]# chmod 755 /var/www/cgi-bin/php72.fcgi
Créez maintenant la configuration php :
[root@centos7 ~]# vi /etc/httpd/conf.d/php.conf [root@centos7 ~]# cat /etc/httpd/conf.d/php.conf ScriptAlias /cgi-bin/ "/var/www/cgi-bin/" AddHandler php56-fcgi .php Action php56-fcgi /cgi-bin/php56.fcgi Action php72-fcgi /cgi-bin/php72.fcgi <Directory /var/www/html/_/php56> DirectoryIndex index.php AllowOverride all Require all granted </Directory> <Directory /var/www/html/_/php72> DirectoryIndex index.php AllowOverride all Require all granted </Directory>
Important : Notez que la configuration par défaut exécute le handler php56-fcgi.
Créez les pages de test PHP :
[root@centos7 ~]# mkdir -p /var/www/html/_/php56 [root@centos7 ~]# mkdir -p /var/www/html/_/php72 [root@centos7 ~]# echo "<?php phpinfo(); ?>" > /var/www/html/_/php56/index.php [root@centos7 ~]# echo "<?php phpinfo(); ?>" > /var/www/html/_/php72/index.php
Indiquez que le handler php72-fcgi doit être utilisé dans le répertoire php72 :
[root@centos7 ~]# echo "AddHandler php72-fcgi .php" > /var/www/html/_/php72/.htaccess
Re-démarrez le service httpd :
[root@centos7 ~]# systemctl restart httpd
Testez maintenant les versions de PHP :
[root@centos7 ~]# lynx http://i2tch.loc/php56 phpinfo() (p1 of 20) PHP logo PHP Version 5.6.37 System Linux centos7.fenestros.loc 3.10.0-693.21.1.el7.x86_64 #1 SMP Wed Mar 7 19:03:37 UTC 2018 x86_64 Build Date Jul 19 2018 19:35:58 Server API CGI/FastCGI Virtual Directory Support disabled Configuration File (php.ini) Path /opt/remi/php56/root/etc Loaded Configuration File /opt/remi/php56/root/etc/php.ini Scan this dir for additional .ini files /opt/remi/php56/root/etc/php.d Additional .ini files parsed /opt/remi/php56/root/etc/php.d/20-bz2.ini, /opt/remi/php56/root/etc/php.d/20-calendar.ini, /opt/remi/php56/root/etc/php.d/20-ctype.ini, /opt/remi/php56/root/etc/php.d/20-curl.ini, /opt/remi/php56/root/etc/php.d/20-dom.ini, /opt/remi/php56/root/etc/php.d/20-exif.ini, /opt/remi/php56/root/etc/php.d/20-fileinfo.ini, /opt/remi/php56/root/etc/php.d/20-ftp.ini, /opt/remi/php56/root/etc/php.d/20-gettext.ini, /opt/remi/php56/root/etc/php.d/20-iconv.ini, /opt/remi/php56/root/etc/php.d/20-phar.ini, /opt/remi/php56/root/etc/php.d/20-posix.ini, /opt/remi/php56/root/etc/php.d/20-shmop.ini, /opt/remi/php56/root/etc/php.d/20-simplexml.ini, /opt/remi/php56/root/etc/php.d/20-sockets.ini, /opt/remi/php56/root/etc/php.d/20-sysvmsg.ini, /opt/remi/php56/root/etc/php.d/20-sysvsem.ini, /opt/remi/php56/root/etc/php.d/20-sysvshm.ini, /opt/remi/php56/root/etc/php.d/20-tokenizer.ini, /opt/remi/php56/root/etc/php.d/20-xml.ini, /opt/remi/php56/root/etc/php.d/20-xmlwriter.ini, /opt/remi/php56/root/etc/php.d/20-xsl.ini, /opt/remi/php56/root/etc/php.d/30-wddx.ini, /opt/remi/php56/root/etc/php.d/30-xmlreader.ini, /opt/remi/php56/root/etc/php.d/40-json.ini, /opt/remi/php56/root/etc/php.d/40-zip.ini PHP API 20131106 PHP Extension 20131226 Zend Extension 220131226 Zend Extension Build API220131226,NTS PHP Extension Build API20131226,NTS Debug Build no Thread Safety disabled Zend Signal Handling disabled Zend Memory Manager enabled Zend Multibyte Support disabled IPv6 Support enabled DTrace Support available, disabled Registered PHP Streams https, ftps, compress.zlib, php, file, glob, data, http, ftp, compress.bzip2, phar, zip Registered Stream Socket Transports tcp, udp, unix, udg, ssl, sslv3, tls, tlsv1.0, tlsv1.1, tlsv1.2 Registered Stream Filters zlib.*, string.rot13, string.toupper, string.tolower, string.strip_tags, convert.*, consumed, dechunk, bzip2.*, convert.iconv.* Zend logo This program makes use of the Zend Scripting Language Engine: ...
[root@centos7 ~]# lynx http://i2tch.loc/php72 phpinfo() (p1 of 18) PHP logo PHP Version 7.2.9 System Linux centos7.fenestros.loc 3.10.0-693.21.1.el7.x86_64 #1 SMP Wed Mar 7 19:03:37 UTC 2018 x86_64 Build Date Aug 15 2018 08:05:24 Server API CGI/FastCGI Virtual Directory Support disabled Configuration File (php.ini) Path /etc/opt/remi/php72 Loaded Configuration File /etc/opt/remi/php72/php.ini Scan this dir for additional .ini files /etc/opt/remi/php72/php.d Additional .ini files parsed /etc/opt/remi/php72/php.d/20-bz2.ini, /etc/opt/remi/php72/php.d/20-calendar.ini, /etc/opt/remi/php72/php.d/20-ctype.ini, /etc/opt/remi/php72/php.d/20-curl.ini, /etc/opt/remi/php72/php.d/20-exif.ini, /etc/opt/remi/php72/php.d/20-fileinfo.ini, /etc/opt/remi/php72/php.d/20-ftp.ini, /etc/opt/remi/php72/php.d/20-gettext.ini, /etc/opt/remi/php72/php.d/20-iconv.ini, /etc/opt/remi/php72/php.d/20-json.ini, /etc/opt/remi/php72/php.d/20-phar.ini, /etc/opt/remi/php72/php.d/20-sockets.ini, /etc/opt/remi/php72/php.d/20-tokenizer.ini PHP API 20170718 PHP Extension 20170718 Zend Extension 320170718 Zend Extension Build API320170718,NTS PHP Extension Build API20170718,NTS Debug Build no Thread Safety disabled Zend Signal Handling enabled Zend Memory Manager enabled Zend Multibyte Support disabled IPv6 Support enabled DTrace Support available, disabled Registered PHP Streams https, ftps, compress.zlib, php, file, glob, data, http, ftp, compress.bzip2, phar Registered Stream Socket Transports tcp, udp, unix, udg, ssl, sslv3, tls, tlsv1.0, tlsv1.1, tlsv1.2 Registered Stream Filters zlib.*, string.rot13, string.toupper, string.tolower, string.strip_tags, convert.*, consumed, dechunk, bzip2.*, convert.iconv.* Zend logo This program makes use of the Zend Scripting Language Engine: Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies ___________________________________________________________________________________________________________________________________________________________ Configuration ...
LAB #2 - Gestion de l'authentification avec .htpasswd et mod_auth_basic
La sécurité sous Apache se gère grâce à deux fichiers :
- .htaccess
- Ce fichier contient les droits d'accès au répertoire dans lequel est situé le fichier.
- .htpasswd
- Ce fichier contient les noms d'utilisateurs et les mots de passe des personnes autorisées à accéder au répertoire protégé par le fichier .htaccess.
Pour activer la sécurité sous apache 2.4, les trois modules mod_auth_basic, mod_authn_file et mod_authz_host doivent être chargées. Vérifiez donc que les trois lignes suivantes ne sont pas en commentaires dans le fichier httpd.conf:
[root@centos7 ~]# cat /etc/httpd/conf.modules.d/00-base.conf | grep auth_basic LoadModule auth_basic_module modules/mod_auth_basic.so [root@centos7 ~]# cat /etc/httpd/conf.modules.d/00-base.conf | grep authn_file LoadModule authn_file_module modules/mod_authn_file.so [root@centos7 ~]# cat /etc/httpd/conf.modules.d/00-base.conf | grep authz_host_module LoadModule authz_host_module modules/mod_authz_host.so
Configuration de la sécurité avec .htaccess
Dans le cas de notre serveur, nous souhaitons mettre en place un répertoire privé appelé secret. Ce répertoire ne doit être accessible qu'au webmaster. Pour le faire, procédez ainsi :
Créez le répertoire secret dans le répertoire /www/site1 :
[root@centos7 ~]# mkdir /www/site1/secret/
Créez le fichier /www/site1/secret/.htaccess:
[root@centos7 ~]# vi /www/site1/secret/.htaccess [root@centos7 ~]# cat /www/site1/secret/.htaccess AuthUserFile /www/passwords/site1/.htpasswd AuthName "Secret du Site1" AuthType Basic <Limit GET> require valid-user </Limit>
Sauvegardez votre fichier.
Mise en place d'un fichier de mots de passe
Ensuite créez maintenant le répertoire /www/passwords/site1 :
[root@centos7 ~]# mkdir -p /www/passwords/site1
Créez maintenant le fichier .htpasswd avec une entrée pour le webmaster grâce à la commande htpasswd :
[root@centos7 ~]# htpasswd -c /www/passwords/site1/.htpasswd webmaster New password: fenestros Re-type new password: fenestros Adding password for user webmaster
Vérifiez le contenu du fichier /www/passwords/site1/.htpasswd grâce à la commande cat :
[root@centos7 ~]# cat /www/passwords/site1/.htpasswd webmaster:$apr1$jnlskgOH$a/SaUQCeDHobz.PM2pDun.
Créez maintenant une page html dans le répertoire secret :
[root@centos7 ~]# vi /www/site1/secret/index.html [root@centos7 ~]# cat /www/site1/secret/index.html <html> <body> <center>Si vous voyez ce message, vous avez decouvert mon secret !</center> </body> </html>
Finalement, pour que la sécurité par .htaccess soit prise en compte pour le répertoire secret, il faut rajouter une directive à la section de l'hôte virtuel par nom dans le fichier Vhosts.conf :
- Vhosts.conf
################# IP-based Virtual Hosts <VirtualHost 192.168.1.99> DocumentRoot /www/site2 ServerName www.rhelip.com DirectoryIndex index.html Customlog /www/logs/site2/rhelip.log combined Errorlog /www/logs/site2/rhelip_error.log <Directory /www/site2> Require all granted </Directory> </VirtualHost> ################# Named VirtualHosts NameVirtualHost *:80 ##################Default Site Virtual Host <VirtualHost *:80> VirtualDocumentRoot /var/www/html/%-3 ServerName i2tch.loc ServerAlias *.i2tch.loc ServerAdmin webmaster@localhost LogLevel info <Directory /> Options FollowSymLinks AllowOverride All Require all granted </Directory> </VirtualHost> ##################www.rhelnom.com <VirtualHost *:80> ServerName www.rhelnom.com DirectoryIndex index.html DocumentRoot /www/site1 Customlog /www/logs/site1/rhelnom.log combined Errorlog /www/logs/site1/rhelnom_error.log <Directory /www/site1> Require all granted </Directory> <Directory /www/site1/secret> AllowOverride AuthConfig </Directory> </VirtualHost>
Sauvegardez votre fichier et puis redémarrez votre serveur Apache :
[root@centos7 ~]# systemctl restart httpd
Testez ensuite votre section privée :
[root@centos7 ~]# curl http://www.rhelnom.com/secret/index.html <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>401 Unauthorized</title> </head><body> <h1>Unauthorized</h1> <p>This server could not verify that you are authorized to access the document requested. Either you supplied the wrong credentials (e.g., bad password), or your browser doesn't understand how to supply the credentials required.</p> </body></html> [root@centos7 ~]# [root@centos7 ~]# curl -u webmaster:fenestros http://www.rhelnom.com/secret/index.html <html> <body> <center>Si vous voyez ce message, vous avez decouvert mon secret !</center> </body> </html>
LAB #3 - Gestion de l'authentification avec MariaDB et mod_authn_dbd
Vous devez utiliser mod_authn_dbd pour protéger l'accès à un répertoire secret2 dans votre site virtuel www.rhelnom.com.
Installation
Installez le serveur MariaDB ainsi que apr-util-mysql :
[root@centos7 ~]# yum install mariadb mariadb-server apr-util-mysql -y
Vérifiez que le module mod_authn_dbd est activé :
[root@centos7 ~]# cat /etc/httpd/conf.modules.d/00-base.conf | grep authn_dbd LoadModule authn_dbd_module modules/mod_authn_dbd.so
Copiez le module /usr/lib64/apr-util-1/apr_dbd_mysql.so dans le répertoire /usr/lib64/httpd/modules/ :
[root@centos7 ~]# updatedb [root@centos7 ~]# locate apr_dbd_mysql.so /usr/lib64/apr-util-1/apr_dbd_mysql.so [root@centos7 ~]# cp /usr/lib64/apr-util-1/apr_dbd_mysql.so /usr/lib64/httpd/modules/
Configuration de MariaDB
Il est maintenant nécessaire de préparer une base de données MariaDB pour être compatible avec mod_authn_dbd. Démarrez donc le service mysqld :
[root@centos7 ~]# systemctl enable mariadb [root@centos7 ~]# systemctl start mariadb [root@centos7 ~]# systemctl status mariadb ● mariadb.service - MariaDB database server Loaded: loaded (/usr/lib/systemd/system/mariadb.service; enabled; vendor preset: disabled) Active: active (running) since Sun 2017-11-05 08:04:45 CET; 1h 41min ago Main PID: 1293 (mysqld_safe) CGroup: /system.slice/mariadb.service ├─1293 /bin/sh /usr/bin/mysqld_safe --basedir=/usr └─1964 /usr/libexec/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/lib64/mysql/plugin --log-error=/var... Nov 05 08:04:24 centos7.fenestros.loc systemd[1]: Starting MariaDB database server... Nov 05 08:04:31 centos7.fenestros.loc mariadb-prepare-db-dir[687]: Database MariaDB is probably initialized in /var/lib/mysql a...one. Nov 05 08:04:36 centos7.fenestros.loc mysqld_safe[1293]: 171105 08:04:36 mysqld_safe Logging to '/var/log/mariadb/mariadb.log'. Nov 05 08:04:37 centos7.fenestros.loc mysqld_safe[1293]: 171105 08:04:37 mysqld_safe Starting mysqld daemon with databases fro...mysql Nov 05 08:04:45 centos7.fenestros.loc systemd[1]: Started MariaDB database server. Hint: Some lines were ellipsized, use -l to show in full.
Définissez le mot de passe fenestros pour root avec la commande suivante :
[root@centos7 ~]# mysqladmin -u root password fenestros
Connectez-vous à MariaDB :
[root@centos7 ~]# mysql -u root -p Enter password: Welcome to the MariaDB monitor. Commands end with ; or \g. Your MariaDB connection id is 4 Server version: 5.5.56-MariaDB MariaDB Server Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. MariaDB [(none)]>
Puis saisissez les requêtes et commandes suivantes :
CREATE DATABASE auth;
USE auth;
CREATE TABLE users ( user_name VARCHAR(50) NOT NULL, user_passwd VARCHAR(50) NOT NULL, PRIMARY KEY (user_name) );
GRANT SELECT ON auth.users TO apache@localhost IDENTIFIED BY 'PaSsW0Rd';
Par exemple :
MariaDB [(none)]> CREATE DATABASE auth; Query OK, 1 row affected (0.00 sec) MariaDB [(none)]> USE auth; Database changed MariaDB [auth]> CREATE TABLE users ( -> user_name VARCHAR(50) NOT NULL, -> user_passwd VARCHAR(50) NOT NULL, -> PRIMARY KEY (user_name) -> ); Query OK, 0 rows affected (0.42 sec) MariaDB [auth]> GRANT SELECT -> ON auth.users -> TO apache@localhost -> IDENTIFIED BY 'PaSsW0Rd'; Query OK, 0 rows affected (0.32 sec) MariaDB [auth]> exit Bye [root@centos7 ~]# mysql -u root -p -e "INSERT INTO users (user_name, user_passwd) VALUES (\"apache\",\"$(htpasswd -nb apache password |cut -d ':' -f 2)\")" auth Enter password: fenestros [root@centos7 ~]# mysql -u root -p -e "SELECT * FROM auth.users;" Enter password: fenestros +-----------+---------------------------------------+ | user_name | user_passwd | +-----------+---------------------------------------+ | apache | $apr1$isUDg5bK$8oh0oMFUDfL41h84M9vYu1 | +-----------+---------------------------------------+ [root@centos7 ~]#
Configuration d'Apache
Créez maintenant le répertoire /www/site1/secret2 :
[root@centos7 ~]# mkdir /www/site1/secret2
Créez maintenant une page index.html dans le répertoire secret2 :
[root@centos7 ~]# vi /www/site1/secret2/index.html [root@centos7 ~]# cat /www/site1/secret2/index.html <html> <body> <center>Si vous voyez ce message, vous connaissez mon secret MariaDB !</center> </body> </html>
Ouvrez ensuite le fichier de configuration /etc/httpd/conf/vhosts.d/Vhosts.conf et modifiez-le ainsi :
[root@centos7 vhosts.d]# vi /etc/httpd/conf/vhosts.d/Vhosts.conf [root@centos7 vhosts.d]# cat /etc/httpd/conf/vhosts.d/Vhosts.conf ################# IP-based Virtual Hosts <VirtualHost 192.168.1.99> DocumentRoot /www/site2 ServerName www.rhelip.com DirectoryIndex index.html Customlog /www/logs/site2/rhelip.log combined Errorlog /www/logs/site2/rhelip_error.log <Directory /www/site2> Require all granted </Directory> </VirtualHost> ################# Named VirtualHosts NameVirtualHost *:80 ##################Default Site Virtual Host <VirtualHost *:80> VirtualDocumentRoot /var/www/html/%-3 ServerName i2tch.loc ServerAlias *.i2tch.loc ServerAdmin webmaster@localhost LogLevel info <Directory /> Options FollowSymLinks AllowOverride All Require all granted </Directory> </VirtualHost> ##################www.rhelnom.com <VirtualHost *:80> ServerName www.rhelnom.com DirectoryIndex index.html DocumentRoot /www/site1 Customlog /www/logs/site1/rhelnom.log combined Errorlog /www/logs/site1/rhelnom_error.log DBDriver mysql DBDParams "dbname=auth user=apache pass=PaSsW0Rd" DBDMin 4 DBDKeep 8 DBDMax 20 DBDExptime 300 <Directory /www/site1> Require all granted </Directory> <Directory /www/site1/secret> AllowOverride AuthConfig </Directory> <Directory /www/site1/secret2> AuthType Basic AuthName "MariaDB Secret" AuthBasicProvider dbd Require valid-user AuthDBDUserPWQuery "SELECT user_passwd FROM users WHERE user_name = %s" </Directory> </VirtualHost>
Afin que les modifications soient prises en charge par apache, redémarrez le service :
[root@centos7 ~]# systemctl restart httpd
Testez ensuite votre section privée :
[root@centos7 ~]# curl -u webmaster:fenestros http://www.rhelnom.com/secret/index.html <html> <body> <center>Si vous voyez ce message, vous avez decouvert mon secret !</center> </body> </html> [root@centos7 ~]# curl -u webmaster:fenestros http://www.rhelnom.com/secret2/index.html <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>401 Unauthorized</title> </head><body> <h1>Unauthorized</h1> <p>This server could not verify that you are authorized to access the document requested. Either you supplied the wrong credentials (e.g., bad password), or your browser doesn't understand how to supply the credentials required.</p> </body></html> [root@centos7 ~]# curl -u apache:password http://www.rhelnom.com/secret2/index.html <html> <body> <center>Si vous voyez ce message, vous connaissez mon secret MariaDB !</center> </body> </html>
LAB #4 - Gestion de l'authentification avec OpenLDAP et mod_authnz_ldap
Vous devez maintenant utiliser mod_authnz_ldap pour protéger l'accès à votre site principal. Pour activer l'authentification en utilisant OpenLDAP sous apache 2.4, le module mod_ldap doit être installée :
[root@centos7 ~]# yum install mod_ldap
Pour installer le serveur OpenLDAP sous GNU/Linux ou Unix vous pouvez soit utiliser la version binaire fournie par les dépôts de paquets de votre distribution GNU/Linux ou Unix soit télécharger la dernière version à compiler du site d'OpenLDAP.
Dans notre cas, nous allons installer OpenLDAP à partir des dépôts. Commencez par installer OpenLDAP :
[root@centos7 ~]# yum install openldap-servers openldap-clients openldap
Sous CentOS le service OpenLDAP s'appelle slapd :
[root@centos7 ~]# systemctl status slapd.service ● slapd.service - OpenLDAP Server Daemon Loaded: loaded (/usr/lib/systemd/system/slapd.service; disabled; vendor preset: disabled) Active: inactive (dead) Docs: man:slapd man:slapd-config man:slapd-hdb man:slapd-mdb file:///usr/share/doc/openldap-servers/guide.html [root@centos7 ~]# systemctl enable slapd.service Created symlink from /etc/systemd/system/multi-user.target.wants/slapd.service to /usr/lib/systemd/system/slapd.service. [root@centos7 ~]# systemctl start slapd.service [root@centos7 ~]# systemctl status slapd.service ● slapd.service - OpenLDAP Server Daemon Loaded: loaded (/usr/lib/systemd/system/slapd.service; enabled; vendor preset: disabled) Active: active (running) since Sun 2017-11-05 12:39:40 CET; 6s ago Docs: man:slapd man:slapd-config man:slapd-hdb man:slapd-mdb file:///usr/share/doc/openldap-servers/guide.html Process: 28650 ExecStart=/usr/sbin/slapd -u ldap -h ${SLAPD_URLS} $SLAPD_OPTIONS (code=exited, status=0/SUCCESS) Process: 28632 ExecStartPre=/usr/libexec/openldap/check-config.sh (code=exited, status=0/SUCCESS) Main PID: 28653 (slapd) CGroup: /system.slice/slapd.service └─28653 /usr/sbin/slapd -u ldap -h ldapi:/// ldap:/// Nov 05 12:39:39 centos7.fenestros.loc systemd[1]: Starting OpenLDAP Server Daemon... Nov 05 12:39:39 centos7.fenestros.loc runuser[28637]: pam_unix(runuser:session): session opened for user ldap by (uid=0) Nov 05 12:39:39 centos7.fenestros.loc slapcat[28643]: DIGEST-MD5 common mech free Nov 05 12:39:40 centos7.fenestros.loc slapd[28650]: @(#) $OpenLDAP: slapd 2.4.44 (Aug 4 2017 14:23:27) $ mockbuild@c1bm.rdu2.centos.org:/builddir/build/BUILD/openldap-2.4.../slapd Nov 05 12:39:40 centos7.fenestros.loc slapd[28653]: hdb_db_open: warning - no DB_CONFIG file found in directory /var/lib/ldap: (2). Expect poor performance for suffix "dc=my-domain,dc=com". Nov 05 12:39:40 centos7.fenestros.loc slapd[28653]: slapd starting Nov 05 12:39:40 centos7.fenestros.loc systemd[1]: Started OpenLDAP Server Daemon. Hint: Some lines were ellipsized, use -l to show in full.
Configuration d'OpenLDAP
Créez le répertoire /var/lib/ldap/ittraining pour contenir un nouveau base de données :
[root@centos7 ~]# mkdir /var/lib/ldap/ittraining
Nettoyez les anciens fichiers de configuration et fichiers de données :
[root@centos7 ~]# rm -Rf /etc/openldap/slapd.d/* [root@centos7 ~]# rm -f /var/lib/ldap/alock [root@centos7 ~]# rm -f /var/lib/ldap/__db.00?
Créez le fichier /etc/openldap/slapd.conf :
[root@centos7 ~]# vi /etc/openldap/slapd.conf [root@centos7 ~]# cat /etc/openldap/slapd.conf include /etc/openldap/schema/corba.schema include /etc/openldap/schema/core.schema include /etc/openldap/schema/cosine.schema include /etc/openldap/schema/duaconf.schema include /etc/openldap/schema/dyngroup.schema include /etc/openldap/schema/inetorgperson.schema include /etc/openldap/schema/java.schema include /etc/openldap/schema/misc.schema include /etc/openldap/schema/nis.schema include /etc/openldap/schema/openldap.schema include /etc/openldap/schema/ppolicy.schema include /etc/openldap/schema/collective.schema allow bind_v2 pidfile /var/run/openldap/slapd.pid argsfile /var/run/openldap/slapd.args TLSCACertificatePath /etc/openldap/certs TLSCertificateFile "\"OpenLDAP Server\"" TLSCertificateKeyFile /etc/openldap/certs/password database config access to * by dn.exact="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" manage by * none database monitor access to * by dn.exact="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" read by dn.exact="cn=Admin,o=fenestros" read by * none ############################################### database bdb suffix "o=ittraining" checkpoint 1024 15 rootdn "cn=Admin,o=ittraining" rootpw directory /var/lib/ldap/ittraining lastmod on index cn,sn,st eq,pres,sub
Créez un mot de passe crypté pour l'admistrateur LDAP :
[root@centos7 ~]# slappasswd -s fenestros {SSHA}RRo5UcZ9zzb2nYZuE5ZH+74u/Y2cyco2
Editez ensuite la section database du fichier /etc/openldap/slapd.conf :
... database bdb suffix "o=ittraining" checkpoint 1024 15 rootdn "cn=Admin,o=ittraining" rootpw {SSHA}RRo5UcZ9zzb2nYZuE5ZH+74u/Y2cyco2 directory /var/lib/ldap/ittraining lastmod on index cn,sn,st eq,pres,sub
Copiez le fichier /usr/share/openldap-servers/DB_CONFIG.example vers /var/lib/ldap/ittraining/DB_CONFIG :
[root@centos7 ~]# cp /usr/share/openldap-servers/DB_CONFIG.example /var/lib/ldap/ittraining/DB_CONFIG
Initialisez la première base de données :
[root@centos7 ~]# echo “” | slapadd -f /etc/openldap/slapd.conf 59ff01da The first database does not allow slapadd; using the first available one (2) 59ff01da str2entry: entry -1 has no dn slapadd: could not parse entry (line=1)
Initialisez ensuite l'arborescence dans /etc/openldap/slapd.d :
[root@centos7 ~]# slaptest -f /etc/openldap/slapd.conf -F /etc/openldap/slapd.d config file testing succeeded
Vérifiez que l'arborescence initiale soit créée :
[root@centos7 ~]# ls -l /etc/openldap/slapd.d total 8 drwxr-x--- 3 root root 4096 Nov 5 13:20 cn=config -rw------- 1 root root 1258 Nov 5 13:20 cn=config.ldif
Modifiez le propriétaire, le groupe ainsi que le droits du répertoire /etc/openldap/slapd.d :
[root@centos7 ~]# chown -R ldap:ldap /etc/openldap/slapd.d [root@centos7 ~]# chmod -R u+rwX /etc/openldap/slapd.d
Modifiez le propriétaire et le groupe répertoire /var/lib/ldap/ittraining ainsi que le fichier /etc/openldap/slapd.conf :
[root@centos7 ~]# chown -R ldap:ldap /var/lib/ldap/ittraining /etc/openldap/slapd.conf
Démarrez ensuite le service slapd :
[root@centos7 ~]# systemctl restart slapd
Créez le fichier ittraining.ldif :
[root@centos7 ~]# vi ittraining.ldif [root@centos7 ~]# cat ittraining.ldif dn: o=ittraining objectClass: top objectClass: organization o: ittraining description: LDAP Authentification dn: cn=Admin,o=ittraining objectClass: organizationalRole cn: Admin description: Administrateur LDAP dn: ou=GroupA,o=ittraining ou: GroupA objectClass: top objectClass: organizationalUnit description: Membres de GroupA dn: ou=GroupB,o=ittraining ou: GroupB objectClass: top objectClass: organizationalUnit description: Membres de GroupB dn: ou=group,o=ittraining ou: group objectclass: organizationalUnit objectclass: domainRelatedObject associatedDomain: ittraining dn: cn=users,ou=group,o=ittraining cn: users objectClass: top objectClass: posixGroup gidNumber: 100 memberUid: jean memberUid: jacques dn: cn=Jean Legrand,ou=GroupA,o=ittraining ou: GroupA o: ittraining cn: Jean Legrand objectClass: person objectClass: organizationalPerson objectClass: inetOrgPerson objectClass: posixAccount objectClass: shadowAccount objectClass: top mail: jean.legrand@ittraining.loc givenname: Jean sn: Legrand uid: jean uidNumber: 1001 gidNumber: 100 gecos: Jean Legrand loginShell: /bin/bash homeDirectory: /home/jean shadowLastChange: 14368 shadowMin: 0 shadowMax: 999999 shadowWarning: 7 userPassword: secret1 homePostalAddress: 99 avenue de Linux, 75000 Paris postalAddress: 99 avenue de Linux. l: Paris st: 75 postalcode: 75000 telephoneNumber: 01.10.20.30.40 homePhone: 01.50.60.70.80 facsimileTelephoneNumber: 01.99.99.99.99 title: Ingénieur dn: cn=Jacques Lebeau,ou=GroupA,o=ittraining ou: GroupA o: ittraining cn: Jacques Lebeau objectClass: person objectClass: organizationalPerson objectClass: inetOrgPerson objectClass: posixAccount objectClass: shadowAccount objectClass: top mail: jacques.lebeau@ittraining.loc givenname: Jacques sn: Lebeau uid: jacques uidNumber: 1002 gidNumber: 100 gecos: Jacques Lebeau loginShell: /bin/bash homeDirectory: /home/jacques shadowLastChange: 14365 shadowMin: 0 shadowMax: 999999 shadowWarning: 7 userPassword: secret2 initials: JL homePostalAddress: 99 route d'Unix, 75000 Paris postalAddress: 99 route d'Unix. l: Paris st: 75 postalcode: 75000 pager: 01.04.04.04.04 homePhone: 01.05.05.05.05 telephoneNumber: 01.06.06.06.06 mobile: 06.01.02.03.04 title: Technicienne facsimileTelephoneNumber: 01.04.09.09.09 manager: cn=Jean Legrand,ou=GroupA,o=ittraining
Injectez le fichier ittraining.ldif dans OpenLDAP :
[root@centos7 ~]# ldapadd -f ittraining.ldif -xv -D "cn=Admin,o=ittraining" -h 127.0.0.1 -w fenestros ldap_initialize( ldap://127.0.0.1 ) add objectClass: top organization add o: ittraining add description: LDAP Authentification adding new entry "o=ittraining" modify complete add objectClass: organizationalRole add cn: Admin add description: Administrateur LDAP adding new entry "cn=Admin,o=ittraining" modify complete add ou: GroupA add objectClass: top organizationalUnit add description: Membres de GroupA adding new entry "ou=GroupA,o=ittraining" modify complete add ou: GroupB add objectClass: top organizationalUnit add description: Membres de GroupB adding new entry "ou=GroupB,o=ittraining" modify complete add ou: group add objectclass: organizationalUnit domainRelatedObject add associatedDomain: ittraining adding new entry "ou=group,o=ittraining" modify complete add cn: users add objectClass: top posixGroup add gidNumber: 100 add memberUid: jean jacques adding new entry "cn=users,ou=group,o=ittraining" modify complete add ou: GroupA add o: ittraining add cn: Jean Legrand add objectClass: person organizationalPerson inetOrgPerson posixAccount shadowAccount top add mail: jean.legrand@ittraining.loc add givenname: Jean add sn: Legrand add uid: jean add uidNumber: 1001 add gidNumber: 100 add gecos: Jean Legrand add loginShell: /bin/bash add homeDirectory: /home/jean add shadowLastChange: 14368 add shadowMin: 0 add shadowMax: 999999 add shadowWarning: 7 add userPassword: secret1 add homePostalAddress: 99 avenue de Linux, 75000 Paris add postalAddress: 99 avenue de Linux. add l: Paris add st: 75 add postalcode: 75000 add telephoneNumber: 01.10.20.30.40 add homePhone: 01.50.60.70.80 add facsimileTelephoneNumber: 01.99.99.99.99 add title: NOT ASCII (10 bytes) adding new entry "cn=Jean Legrand,ou=GroupA,o=ittraining" modify complete add ou: GroupA add o: ittraining add cn: Jacques Lebeau add objectClass: person organizationalPerson inetOrgPerson posixAccount shadowAccount top add mail: jacques.lebeau@ittraining.loc add givenname: Jacques add sn: Lebeau add uid: jacques add uidNumber: 1002 add gidNumber: 100 add gecos: Jacques Lebeau add loginShell: /bin/bash add homeDirectory: /home/jacques add shadowLastChange: 14365 add shadowMin: 0 add shadowMax: 999999 add shadowWarning: 7 add userPassword: secret2 add initials: JL add homePostalAddress: 99 route d'Unix, 75000 Paris add postalAddress: 99 route d'Unix. add l: Paris add st: 75 add postalcode: 75000 add pager: 01.04.04.04.04 add homePhone: 01.05.05.05.05 add telephoneNumber: 01.06.06.06.06 add mobile: 06.01.02.03.04 add title: Technicienne add facsimileTelephoneNumber: 01.04.09.09.09 add manager: cn=Jean Legrand,ou=GroupA,o=ittraining adding new entry "cn=Jacques Lebeau,ou=GroupA,o=ittraining" modify complete
Configuration d'Apache
Arrêtez le serveur Apache :
[root@centos7 ~]# systemctl stop httpd
Remplacez la section <Directory “/var/www/html”> du fichier /etc/httpd/conf/httpd.conf avec les lignes suivantes :
... # <Directory "/var/www/html"> # # Possible values for the Options directive are "None", "All", # or any combination of: # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews # # Note that "MultiViews" must be named *explicitly* --- "Options All" # doesn't give it to you. # # The Options directive is both complicated and important. Please see # http://httpd.apache.org/docs/2.4/mod/core.html#options # for more information. # # Options Indexes FollowSymLinks # # AllowOverride controls what directives may be placed in .htaccess files. # It can be "All", "None", or any combination of the keywords: # Options FileInfo AuthConfig Limit # # AllowOverride None # # Controls who can get stuff from this server. # # Require all granted # </Directory> <Directory "/var/www/html"> AuthType Basic AuthName "LDAP Authentifaction" AuthBasicProvider ldap AuthLDAPURL ldap://localhost:389/o=ittraining?uid?sub AuthLDAPBindDN "cn=Admin,o=ittraining" AuthLDAPBindPassword fenestros require ldap-user jean jacques AllowOverride None Options Indexes FollowSymLinks </Directory> ...
Re-démarrez le serveur apache :
[root@centos7 ~]# systemctl restart httpd
Connectez-vous à http://localhost en utilisant le compte de jean et le mot de passe secret1 :
[root@centos7 ~]# curl http://localhost <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>401 Unauthorized</title> </head><body> <h1>Unauthorized</h1> <p>This server could not verify that you are authorized to access the document requested. Either you supplied the wrong credentials (e.g., bad password), or your browser doesn't understand how to supply the credentials required.</p> </body></html> [root@centos7 ~]# [root@centos7 ~]# curl -u jean:secret1 http://localhost <html> <body> <center>Accueil du site par défaut</center> </body> </html>
Préparer la Suite de la Formation
Editez de nouveau le fichier /etc/httpd/conf/httpd.conf en supprimant la section <Directory> de la configuration LDAP :
<Directory "/var/www/html"> # # Possible values for the Options directive are "None", "All", # or any combination of: # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews # # Note that "MultiViews" must be named *explicitly* --- "Options All" # doesn't give it to you. # # The Options directive is both complicated and important. Please see # http://httpd.apache.org/docs/2.4/mod/core.html#options # for more information. # Options Indexes FollowSymLinks # # AllowOverride controls what directives may be placed in .htaccess files. # It can be "All", "None", or any combination of the keywords: # Options FileInfo AuthConfig Limit # AllowOverride None # # Controls who can get stuff from this server. # Require all granted </Directory> # # DirectoryIndex: sets the file that Apache will serve if a directory # is requested. # ...
Re-démarrez le serveur apache :
[root@centos7 ~]# systemctl restart httpd
LAB #5 - Gestion des pages web sécurisées en https avec mod_ssl
Présentation de SSL
SSL ( Secure Sockets Layers ) est utilisé pour sécuriser des transactions effectuées sur le Web et a été mis au point par :
- Netscape
- MasterCard
- Bank of America
- MCI
- Silicon Graphics
SSL est indépendant du protocole utilisé et agit en tant que couche supplémentaire entre la couche Application et la couche Transport. Il peut être utilisé avec :
- HTTP
- FTP
- POP
- IMAP
Fonctionnement de SSL
Le fonctionnement de SSL suit la procédure suivante :
- Le navigateur demande une page web sécurisée en https,
- Le serveur web émet sa clé publique et son certificat,
- Le navigateur vérifie que le certificat a été émis par une autorité fiable, qu'il est valide et qu'il fait référence au site consulté,
- Le navigateur utilise la clé publique du serveur pour chiffrer une clé symétrique aléatoire, une clé de session, et l'envoie au serveur avec l'URL demandé ainsi que des données HTTP chiffrées,
- Le serveur déchiffre la clé symétrique avec sa clé privée et l'utilise pour récupérer l'URL demandé et les données HTTP,
- Le serveur renvoie le document référencé par l'URL ainsi que les données HTTP chiffrées avec la clé symétrique,
- Le navigateur déchiffre le tout avec la clé symétrique et affiche les informations.
Quand on parle de SSL, on parle de cryptologie.
PKI
On appelle PKI (Public Key Infrastucture, ou en français infrastructure à clé publique (ICP), parfois infrastructure de gestion de clés (IGC)) l’ensemble des solutions techniques basées sur la cryptographie à clé publique.
Les cryptosystèmes à clés publiques permettent de s'affranchir de la nécessité d'avoir recours systématiquement à un canal sécurisé pour s'échanger les clés. En revanche, la publication de la clé publique à grande échelle doit se faire en toute confiance pour assurer que :
- La clé publique est bien celle de son propriétaire ;
- Le propriétaire de la clé est digne de confiance ;
- La clé est toujours valide.
Ainsi, il est nécessaire d'associer au bi-clé (ensemble clé publique / clé privée) un certificat délivré par un tiers de confiance : l'infrastructure de gestion de clés.
Le tiers de confiance est une entité appelée communément autorité de certification (ou en anglais Certification authority, abrégé CA) chargée d'assurer la véracité des informations contenues dans le certificat de clé publique et de sa validité.
Pour ce faire, l'autorité signe le certificat de clé publique à l'aide de sa propre clé en utilisant le principe de signature numérique.
Le rôle de l'infrastructure de clés publiques est multiple et couvre notamment les champs suivants :
- enregistrer des demandes de clés en vérifiant l'identité des demandeurs ;
- générer les paires de clés (clé privée / clé publique) ;
- garantir la confidentialité des clés privées correspondant aux clés publiques ;
- certifier l'association entre chaque utilisateurs et sa clé publique ;
- révoquer des clés (en cas de perte par son propriétaire, d'expiration de sa date de validité ou de compromission).
Une infrastructure à clé publique est en règle générale composée de trois entités distinctes :
- L'autorité d'enregistrement (AE ou RA pour Recording authority), chargée des formalité administratives telles que la vérification de l'identité des demandeurs, le suivi et la gestion des demandes, etc.) ;
- L'autorité de certification (AC ou CA pour Certification Authority), chargée des tâches techniques de création de certificats. L'autorité de certification est ainsi chargée de la signature des demandes de certificat (CSR pour Certificate Signing Request, parfois appelées PKCS#10, nom du format correspondant). L'autorité de certification a également pour mission la signature des listes de révocations (CRL pour Certificate Revocation List) ;
- L'Autorité de dépôt (Repository) dont la mission est de conserver en sécurité les certificats.
Certificats X509
Pour palier aux problèmes liés à des clefs publiques piratées, un système de certificats a été mis en place.
Le certificat permet d’associer la clef publique à une entité ou une personne. Les certificats sont délivrés par des Organismes de Certification.
Les certificats sont des fichiers divisés en deux parties :
- La partie contenant les informations
- La partie contenant la signature de l'autorité de certification
La structure des certificats est normalisée par le standard X.509 de l’Union internationale des télécommunications.
Elle contient :
- Le nom de l'autorité de certification
- Le nom du propriétaire du certificat
- La date de validité du certificat
- L'algorithme de chiffrement utilisé
- La clé publique du propriétaire
Le Certificat est signé par l'autorité de certification:
La vérification se passe ainsi:
Installation de ssl
Afin de pouvoir configurer le serveur apache en mode ssl, il est necessaire d'installer les paquets mod_ssl et openssl. Le paquet openssl étant déjà installé, installez donc mod_ssl :
[root@centos7 ~]# yum install mod_ssl
Configuration de SSL
Dans le cas où vous souhaitez générer vos propres clés, vous devez d'abord générer une clé privée, nécessaire pour la création d'un Certificate Signing Request. Le CSR doit alors être envoyé à une des sociétés faisant autorité en la matière afin que celle-ci puisse vous retourner votre certificat définitif. Ce service est payant. C'est ce certificat définitif qui est utilisé pour des connexions sécurisées.
Saisissez donc la commande suivante pour générer votre clé privée :
[root@centos7 ~]# openssl genrsa -out www.i2tch.loc.key 1024 Generating RSA private key, 1024 bit long modulus .....................................++++++ ................................++++++ e is 65537 (0x10001)
Générer maintenant votre CSR :
[root@centos7 ~]# openssl req -new -key www.i2tch.loc.key -out www.i2tch.loc.csr You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Name (2 letter code) [XX]:GB State or Province Name (full name) []:SURREY Locality Name (eg, city) [Default City]:ADDLESTONE Organization Name (eg, company) [Default Company Ltd]:I2TCH LIMITED Organizational Unit Name (eg, section) []:TRAINING Common Name (eg, your name or your server's hostname) []:www.i2tch.loc Email Address []:infos@i2tch.co.uk Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []: An optional company name []:
et répondez aux questions qui vous sont posées. Notez bien la réponse à la question Common Name. Si vous ne donnez pas votre FQDN, certains navigateurs ne gèreront pas votre certificat correctement. Vous pouvez maintenant envoyé votre CSR à la société que vous avez choisie. Quand votre clé .crt vous est retournée, copiez-la, ainsi que votre clé privée dans le répertoire /etc/pki/tls/certs/.
Sans passer par un prestataire externe, vous pouvez signer votre CSR avec votre propre clé afin de générer votre certificat :
[root@centos7 ~]# openssl x509 -req -days 365 -in www.i2tch.loc.csr -signkey www.i2tch.loc.key -out www.i2tch.loc.crt Signature ok subject=/C=GB/ST=SURREY/L=ADDLESTONE/O=I2TCH LIMITED/OU=TRAINING/CN=centos7.fenestros.loc/emailAddress=infos@i2tch.co.uk Getting Private key
Cette procédure va générer trois fichiers dont votre clé privée et un certificat – une clé ayant une extension .crt.
Il convient ensuite de copier ces deux fichiers dans l'arborescence /etc/pki/tls :
[root@centos7 ~]# cp /root/www.i2tch.loc.key /etc/pki/tls/private/ [root@centos7 ~]# cp /root/www.i2tch.loc.crt /etc/pki/tls/certs/
Mise en place des paramètres de sécurité SSL
Créez maintenant le répertoire qui va contenir le site sécurisé :
[root@centos7 ~]# mkdir /www/ssl
Créez le fichier index.html pour notre site sécurisé :
[root@centos7 ~]# vi /www/ssl/index.html [root@centos7 ~]# cat /www/ssl/index.html <html> <body> <center>Accueil du site SSL</center> </body> </html>
En consultant le contenu du répertoire /etc/httpd/conf.d, vous constaterez un fichier ssl.conf :
[root@centos7 ~]# ls /etc/httpd/conf.d autoindex.conf README ssl.conf userdir.conf welcome.conf
Ouvrez ce fichier et modifiez la ligne suivante :
#DocumentRoot "/var/www/html"
en :
DocumentRoot "/www/ssl"
Cette directive indique que la racine du site sécurisé sera /www/ssl.
Définissez ensuite les droits d'accès à ce site en ajoutant la section suivante à l'emplacement indiqué :
<Files ~ "\.(cgi|shtml|phtml|php3?)$"> SSLOptions +StdEnvVars </Files> # Ajoutez la section suivante <Directory "/www/ssl"> Require all granted </Directory> # Fin <Directory "/var/www/cgi-bin"> SSLOptions +StdEnvVars </Directory>
Dernièrement modifiez les deux lignes suivantes :
SSLCertificateFile /etc/pki/tls/certs/localhost.crt SSLCertificateKeyFile /etc/pki/tls/private/localhost.key
en :
SSLCertificateFile /etc/pki/tls/certs/www.i2tch.loc.crt SSLCertificateKeyFile /etc/pki/tls/private/www.i2tch.loc.key
respectivement.
Sauvegardez votre fichier et redémarrez votre serveur apache :
[root@centos7 ~]# systemctl restart httpd
A Faire - Passez en revue les directives contenues dans le fichier ssl.conf en utilisant le Manuel en ligne d'Apache.
Tester Votre Configuration
Pour tester votre serveur apache en mode SSL saisissez la commande suivante :
[root@centos7 ~]# openssl s_client -connect www.i2tch.loc:443 CONNECTED(00000003) depth=0 C = GB, ST = SURREY, L = ADDLESTONE, O = I2TCH LIMITED, OU = TRAINING, CN = centos7.fenestros.loc, emailAddress = infos@i2tch.co.uk verify error:num=18:self signed certificate verify return:1 depth=0 C = GB, ST = SURREY, L = ADDLESTONE, O = I2TCH LIMITED, OU = TRAINING, CN = centos7.fenestros.loc, emailAddress = infos@i2tch.co.uk verify return:1 --- Certificate chain 0 s:/C=GB/ST=SURREY/L=ADDLESTONE/O=I2TCH LIMITED/OU=TRAINING/CN=centos7.fenestros.loc/emailAddress=infos@i2tch.co.uk i:/C=GB/ST=SURREY/L=ADDLESTONE/O=I2TCH LIMITED/OU=TRAINING/CN=centos7.fenestros.loc/emailAddress=infos@i2tch.co.uk --- Server certificate -----BEGIN CERTIFICATE----- MIICuTCCAiICCQDauUN3s4rA2zANBgkqhkiG9w0BAQsFADCBoDELMAkGA1UEBhMC R0IxDzANBgNVBAgMBlNVUlJFWTETMBEGA1UEBwwKQURETEVTVE9ORTEWMBQGA1UE CgwNSTJUQ0ggTElNSVRFRDERMA8GA1UECwwIVFJBSU5JTkcxHjAcBgNVBAMMFWNl bnRvczcuZmVuZXN0cm9zLmxvYzEgMB4GCSqGSIb3DQEJARYRaW5mb3NAaTJ0Y2gu Y28udWswHhcNMTcxMTA1MTI1NDM4WhcNMTgxMTA1MTI1NDM4WjCBoDELMAkGA1UE BhMCR0IxDzANBgNVBAgMBlNVUlJFWTETMBEGA1UEBwwKQURETEVTVE9ORTEWMBQG A1UECgwNSTJUQ0ggTElNSVRFRDERMA8GA1UECwwIVFJBSU5JTkcxHjAcBgNVBAMM FWNlbnRvczcuZmVuZXN0cm9zLmxvYzEgMB4GCSqGSIb3DQEJARYRaW5mb3NAaTJ0 Y2guY28udWswgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALTR07YEuayyb23D 2TXd6Zh4ZZg1cHLKURQN1sjxkJTKwmscKFHExqtQKEmQV+CKAAMj51DL5M1j55dp G9/72AEAniMVlXT6mOCihRcpEoiiESRz9i71EJtLAIT7c7/ptaxLdTMScDIAUqZN PcX6yTdDDyb4MqBjaHfaHTxS/JgzAgMBAAEwDQYJKoZIhvcNAQELBQADgYEAaNKp eBmvUNVmsYzK6N5WgVtdVgKARVlPRwrWAPp2KDTRBNNz7lkgyYt9zmjHFBYifcQW iLFSb+cl6EtDrty+zWBztKA3CRVdNejI3Q9YQ56ztOAYrGlrRMtUINNxnZcHBe05 bTSecVYeyRu6aChGIyISwL5LjNyMKpXiSjSi5u0= -----END CERTIFICATE----- subject=/C=GB/ST=SURREY/L=ADDLESTONE/O=I2TCH LIMITED/OU=TRAINING/CN=centos7.fenestros.loc/emailAddress=infos@i2tch.co.uk issuer=/C=GB/ST=SURREY/L=ADDLESTONE/O=I2TCH LIMITED/OU=TRAINING/CN=centos7.fenestros.loc/emailAddress=infos@i2tch.co.uk --- No client certificate CA names sent Peer signing digest: SHA512 Server Temp Key: ECDH, P-256, 256 bits --- SSL handshake has read 1264 bytes and written 415 bytes --- New, TLSv1/SSLv3, Cipher is ECDHE-RSA-AES256-GCM-SHA384 Server public key is 1024 bit Secure Renegotiation IS supported Compression: NONE Expansion: NONE No ALPN negotiated SSL-Session: Protocol : TLSv1.2 Cipher : ECDHE-RSA-AES256-GCM-SHA384 Session-ID: AF724406B1B2C2F3E8B33EEC51E51364F8E2B62374CCC16054217FBE866C4D09 Session-ID-ctx: Master-Key: A6BF30C3757101E375F74A3075E1F68FCEF2C6450D18DD3AF12F42F65162B53FBCC4B27C80BE5C3F27A104BFC40CEF15 Key-Arg : None Krb5 Principal: None PSK identity: None PSK identity hint: None TLS session ticket lifetime hint: 300 (seconds) TLS session ticket: 0000 - a8 28 11 9b 9f 2b 09 f9-ac 4c 20 5f 0c b7 ae 87 .(...+...L _.... 0010 - 7d 3b 12 4b b2 d1 f5 6f-ce 2e a8 74 9f 2d 59 a9 };.K...o...t.-Y. 0020 - 6a d6 53 c9 54 f9 3e cc-0b c3 e6 92 58 8d 45 9c j.S.T.>.....X.E. 0030 - 41 ab a7 a4 b5 24 7c 2a-f2 4f 67 48 d5 35 68 29 A....$|*.OgH.5h) 0040 - 3b 24 b6 2b 16 99 2d 6e-aa ea 4c c8 7e df 59 08 ;$.+..-n..L.~.Y. 0050 - 42 06 1b 88 fa 5b c1 0b-4b 7c 01 d3 1a 28 6b 61 B....[..K|...(ka 0060 - 70 c9 7b d0 74 93 f7 1e-c1 a6 58 54 b7 e6 4c 83 p.{.t.....XT..L. 0070 - 5a d4 53 ff 61 71 46 f1-14 55 26 8f 83 29 11 69 Z.S.aqF..U&..).i 0080 - e2 ee 08 dc 4e 7e 95 23-f7 54 c6 79 2e 88 7f 1d ....N~.#.T.y.... 0090 - 5a a7 72 be 80 84 e3 4f-77 aa 63 28 06 a5 58 d1 Z.r....Ow.c(..X. 00a0 - fa a8 28 9c 0d 22 ba 62-51 dc 33 d6 0c 56 57 c1 ..(..".bQ.3..VW. 00b0 - b7 8c e3 eb da 54 82 d0-df e1 63 66 2b 10 85 cd .....T....cf+... Start Time: 1509887084 Timeout : 300 (sec) Verify return code: 18 (self signed certificate) --- ^C
Procédez maintenant au test en utilisant curl :
[root@centos7 ~]# curl -k https://www.i2tch.loc <html> <body> <center>Accueil du site SSL</center> </body> </html>
Avec Apache 2.2.12 et OpenSSL v0.9.8j et versions ultérieurs, il est possible d'utiliser TLS Extension Server Name Indication (SNI) afin d'utiliser des certificats différents pour chaque hôte virtuel.
Par exemple :
NameVirtualHost *:443 <VirtualHost *:443> ServerName www.yoursite.com DocumentRoot /var/www/site SSLEngine on SSLCertificateFile /path/to/www_yoursite_com.crt SSLCertificateKeyFile /path/to/www_yoursite_com.key SSLCertificateChainFile /path/to/DigiCertCA.crt </VirtualHost> <VirtualHost *:443> ServerName www.yoursite2.com DocumentRoot /var/www/site2 SSLEngine on SSLCertificateFile /path/to/www_yoursite2_com.crt SSLCertificateKeyFile /path/to/www_yoursite2_com.key SSLCertificateChainFile /path/to/DigiCertCA.crt </VirtualHost>
LAB #6 - Gestion d'un Serveur Mandataire avec mod_proxy
Sous RHEL / CentOS 7 le support pour mod_proxy est installé par défaut :
[root@centos7 ~]# cat /etc/httpd/conf.modules.d/00-proxy.conf | grep mod_proxy LoadModule proxy_module modules/mod_proxy.so LoadModule proxy_ajp_module modules/mod_proxy_ajp.so LoadModule proxy_balancer_module modules/mod_proxy_balancer.so LoadModule proxy_connect_module modules/mod_proxy_connect.so LoadModule proxy_express_module modules/mod_proxy_express.so LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so LoadModule proxy_fdpass_module modules/mod_proxy_fdpass.so LoadModule proxy_ftp_module modules/mod_proxy_ftp.so LoadModule proxy_http_module modules/mod_proxy_http.so LoadModule proxy_scgi_module modules/mod_proxy_scgi.so LoadModule proxy_wstunnel_module modules/mod_proxy_wstunnel.so </proxy> Créez le fichier de configuration **/etc/httpd/conf.d/proxy.conf** : <code> [root@centos7 ~]# vi /etc/httpd/conf.d/proxy.conf [root@centos7 ~]# cat /etc/httpd/conf.d/proxy.conf <IfModule mod_proxy.c> ProxyRequests On listen 0.0.0.0:8081 <Proxy *> Require all denied Require ip 127.0.0.1 Require ip 10.0.2.0/24 </Proxy> </IfModule>
Sauvegardez le fichier et rechargez la configuration du serveur apache :
[root@centos7 ~]# systemctl restart httpd
Configurez votre navigateur pour utiliser le serveur mandataire (proxy):
localhost
port: 8081
Testez ensuite votre serveur proxy apache :
[root@centos7 ~]# curl --proxy http://127.0.0.1 http://www.redhat.com curl: (7) Failed connect to 127.0.0.1:1080; Connection refused [root@centos7 ~]# curl --proxy http://127.0.0.1:8081 http://www.redhat.com <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>301 Moved Permanently</title> </head><body> <h1>Moved Permanently</h1> <p>The document has moved <a href="https://www.redhat.com/">here</a>.</p> </body></html> [root@centos7 ~]# curl --proxy http://127.0.0.1:8081 http://www.microsoft.com <html><head><title>Microsoft Corporation</title><meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"></meta><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta><meta name="SearchTitle" content="Microsoft.com" scheme=""></meta><meta name="Description" content="Get product information, support, and news from Microsoft." scheme=""></meta><meta name="Title" content="Microsoft.com Home Page" scheme=""></meta><meta name="Keywords" content="Microsoft, product, support, help, training, Office, Windows, software, download, trial, preview, demo, business, security, update, free, computer, PC, server, search, download, install, news" scheme=""></meta><meta name="SearchDescription" content="Microsoft.com Homepage" scheme=""></meta></head><body><p>Your current User-Agent string appears to be from an automated process, if this is incorrect, please click this link:<a href="http://www.microsoft.com/en/us/default.aspx?redir=true">United States English Microsoft Homepage</a></p></body></html>
Consultez votre fichier de log access. Vous constaterez un résultat similaire à celui-ci :
[root@centos7 ~]# tail /var/log/httpd/access_log 10.0.2.16 - - [02/Sep/2018:17:21:00 +0200] "GET /php72/ HTTP/1.0" 200 886 "-" "Lynx/2.8.8dev.15 libwww-FM/2.14 SSL-MM/1.4.1 OpenSSL/1.0.1e-fips" 10.0.2.16 - - [02/Sep/2018:17:25:29 +0200] "GET /php72 HTTP/1.0" 301 231 "-" "Lynx/2.8.8dev.15 libwww-FM/2.14 SSL-MM/1.4.1 OpenSSL/1.0.1e-fips" 10.0.2.16 - - [02/Sep/2018:17:25:31 +0200] "GET /php72/ HTTP/1.0" 200 64036 "-" "Lynx/2.8.8dev.15 libwww-FM/2.14 SSL-MM/1.4.1 OpenSSL/1.0.1e-fips" 10.0.2.16 - - [02/Sep/2018:17:28:21 +0200] "GET /php56 HTTP/1.0" 301 231 "-" "Lynx/2.8.8dev.15 libwww-FM/2.14 SSL-MM/1.4.1 OpenSSL/1.0.1e-fips" 10.0.2.16 - - [02/Sep/2018:17:28:23 +0200] "GET /php56/ HTTP/1.0" 200 68473 "-" "Lynx/2.8.8dev.15 libwww-FM/2.14 SSL-MM/1.4.1 OpenSSL/1.0.1e-fips" 127.0.0.1 - jean [02/Sep/2018:18:15:32 +0200] "GET / HTTP/1.1" 200 75 "-" "curl/7.29.0" 127.0.0.1 - - [02/Sep/2018:18:15:49 +0200] "GET / HTTP/1.1" 401 381 "-" "curl/7.29.0" 127.0.0.1 - - [02/Sep/2018:18:28:31 +0200] "GET / HTTP/1.1" 200 75 "-" "curl/7.29.0" 127.0.0.1 - - [02/Sep/2018:22:27:20 +0200] "GET http://www.redhat.com/ HTTP/1.1" 301 231 "-" "curl/7.29.0" 127.0.0.1 - - [02/Sep/2018:22:27:33 +0200] "GET http://www.microsoft.com/ HTTP/1.1" 200 1020 "-" "curl/7.29.0"
LAB #7 - Gestion du Caching avec mod_file_cache, mod_socache_shmcb, mod_cache et mod_cache_disk
Qu'est-ce le cache sous Apache
L'utilisation du cache permet d'améliorer la performance du serveur en permettant à ce que du contenu régulièrement demandé soit stocké d'une manière temporaraire afin d'y réduire le temps d'accès.
Concretement, en créant des règles cache, le contenu qui peut être caché le sera de façon à :
- améliorer le temps de réponse,
- conserver des ressources,
- minimiser la charge.
Les types de cache
Apache propose plusieurs types de cache :
- File Caching - des fichiers ou/et des descripteurs de fichiers sont ouverts au démarrage d'Apache afin d'accelerer le temps d'accès,
- le File Caching est activé par le chargement du module mod_file_cache,
- l'utilisation de la directive CacheFile permet de stipuler le chemin vers les fichiers à ouvrir. Seul le descripteur de fichier est stocké dans le cache,
- l'utilisation de la directive MMapFile permet de stipuler le chemin vers les fichiers à ouvrir. Dans ce cas le descripteur de fichier et le contenu du fichier sont stockés dans le cache,
- le File Caching ne concerne que les fichiers statiques parce que les directives ne sont lues que lors du démarrage d'Apache,
- Attention - c'est expérimental !
- Key-Value Caching - principalement utilisé pour SSL et l'authentification, le Key-Value Caching utilise un modèle d'objets partagés qui stocke des éléments qui ont un coût élevé en termes de temps de traitement,
- le Key-Value Caching utilise les modules mod_socache_dbm, mod_socache_dc, mod_socache_memcache et mod_socache_shmcb,
- Standard HTTP caching - ce système à trois états peut stocker des réponses et les valider lors de leur expiration,
- le Standard HTTP caching est activé par le chargement du module mod_cache,
- le cache est géré par un des fournisseurs de cache, à savoir mod_cache_disk si le cache est stocké sur disque ou mod_cache_socache dans le cas d'utilisation d'un modèle d'objets partagés,
- dans le cas de l'utilisation de mod_cache_disk, le cache n'est pas nettoyé automatiquement et necéssite l'utilisation de l'outil htcacheclean,
- si la directive CacheQuickHandler est activée, le cache est servi avant l'évaluation des directives dans les blocs <Location> ou <Directory>. Dans ce cas donc l'authentification pour gérer l'accès au contenu ne fonctionne pas !
- Attention - le CacheQuickHandler est activé par défaut !!
Mise en place du File Caching
Pour mettre en place le file caching, créez le fichier /etc/httpd/conf.modules.d/00-cache.conf avec le contenu suivant :
[root@centos7 ~]# vi /etc/httpd/conf.modules.d/00-cache.conf [root@centos7 ~]# cat /etc/httpd/conf.modules.d/00-cache.conf LoadModule file_cache_module modules/mod_file_cache.so
Modifiez ensuite le fichier /etc/httpd/conf/vhosts.d/Vhosts.conf :
[root@centos7 ~]# vi /etc/httpd/conf/vhosts.d/Vhosts.conf [root@centos7 ~]# cat /etc/httpd/conf/vhosts.d/Vhosts.conf ################# IP-based Virtual Hosts <VirtualHost 192.168.1.99> DocumentRoot /www/site2 ServerName www.rhelip.com DirectoryIndex index.html Customlog /www/logs/site2/rhelip.log combined Errorlog /www/logs/site2/rhelip_error.log CacheFile /www/site2/index.html <Directory /www/site2> Require all granted </Directory> </VirtualHost> ...
Vérifiez la configuration d'Apache :
[root@centos7 ~]# apachectl configtest Syntax OK
Re-démarrez le service httpd :
[root@centos7 ~]# systemctl restart httpd
Mise en place de l'Authentication Caching
Vérifiez que le module mod_socache_shmcb soit activé :
[root@centos7 ~]# cat /etc/httpd/conf.modules.d/00-base.conf | grep mod_socache_shmcb LoadModule socache_shmcb_module modules/mod_socache_shmcb.so
Ajoutez la directive AuthnCacheSOCache shmcb au début du fichier /etc/httpd/conf/httpd.conf :
[root@centos7 ~]# vi /etc/httpd/conf/httpd.conf [root@centos7 ~]# more /etc/httpd/conf/httpd.conf # # This is the main Apache HTTP server configuration file. It contains the # configuration directives that give the server its instructions. # See <URL:http://httpd.apache.org/docs/2.4/> for detailed information. # In particular, see # <URL:http://httpd.apache.org/docs/2.4/mod/directives.html> # for a discussion of each configuration directive. # # Do NOT simply read the instructions in here without understanding # what they do. They're here only as hints or reminders. If you are unsure # consult the online docs. You have been warned. # # Configuration and logfile names: If the filenames you specify for many # of the server's control files begin with "/" (or "drive:/" for Win32), the # server will use that explicit path. If the filenames do *not* begin # with "/", the value of ServerRoot is prepended -- so 'log/access_log' # with ServerRoot set to '/www' will be interpreted by the # server as '/www/log/access_log', where as '/log/access_log' will be # interpreted as '/log/access_log'. # # ServerRoot: The top of the directory tree under which the server's # configuration, error, and log files are kept. # # Do not add a slash at the end of the directory path. If you point # ServerRoot at a non-local disk, be sure to specify a local disk on the # Mutex directive, if file-based mutexes are used. If you wish to share the # same ServerRoot for multiple httpd daemons, you will need to change at # least PidFile. # AuthnCacheSOCache shmcb ServerRoot "/etc/httpd" # # Listen: Allows you to bind Apache to specific IP addresses and/or # ports, instead of the default. See also the <VirtualHost> # directive. --More--(13%)
Editez le fichier /etc/httpd/conf/vhosts.d/Vhosts.conf en remplacant la directive AuthBasicProvider dbd dans la section du site www/rhelnom.com par les trois directives suivantes :
- AuthBasicProvider socache dbd
- AuthnCacheProvideFor dbd
- AuthnCacheTimeout 300
[root@centos7 ~]# vi /etc/httpd/conf/vhosts.d/Vhosts.conf [root@centos7 ~]# cat /etc/httpd/conf/vhosts.d/Vhosts.conf ... ##################www.rhelnom.com <VirtualHost *:80> ServerName www.rhelnom.com DirectoryIndex index.html DocumentRoot /www/site1 Customlog /www/logs/site1/rhelnom.log combined Errorlog /www/logs/site1/rhelnom_error.log DBDriver mysql DBDParams "dbname=auth user=apache pass=PaSsW0Rd" DBDMin 4 DBDKeep 8 DBDMax 20 DBDExptime 300 <Directory /www/site1> Require all granted </Directory> <Directory /www/site1/secret> AllowOverride AuthConfig </Directory> <Directory /www/site1/secret2> AuthType Basic AuthName "MariaDB Secret" # AuthBasicProvider dbd AuthBasicProvider socache dbd AuthnCacheProvideFor dbd AuthnCacheTimeout 300 Require valid-user AuthDBDUserPWQuery "SELECT user_passwd FROM users WHERE user_name = %s" </Directory> </VirtualHost> ##################dav.homeland.net ...
Vérifiez la configuration d'Apache :
[root@centos7 ~]# apachectl configtest Syntax OK
Re-démarrez le service httpd :
[root@centos7 ~]# systemctl restart httpd
Mise en place du SSL Session Caching
Sous CentOS 7, le SSL Session Caching est activé par défaut par les deux directives suivantes dans le fichier /etc/httpd/conf.d/ssl.conf :
[root@centos7 ~]# cat /etc/httpd/conf.d/ssl.conf ... # Inter-Process Session Cache: # Configure the SSL Session Cache: First the mechanism # to use and second the expiring timeout (in seconds). SSLSessionCache shmcb:/run/httpd/sslcache(512000) SSLSessionCacheTimeout 300 ...
Utilisez le client d'openssl pour visualiser le Session-ID :
[root@centos7 ~]# openssl s_client -connect 127.0.0.1:443 -reconnect -no_ticket | grep Session-ID depth=0 C = GB, ST = SURREY, L = ADDLESTONE, O = I2TCH LIMITED, OU = TRAINING, CN = www.i2tch.loc, emailAddress = infos@i2tch.co.uk verify error:num=18:self signed certificate verify return:1 depth=0 C = GB, ST = SURREY, L = ADDLESTONE, O = I2TCH LIMITED, OU = TRAINING, CN = www.i2tch.loc, emailAddress = infos@i2tch.co.uk verify return:1 Session-ID: 9484957F14038152A1FBD90FD200E4F11C283BDEEB7B6410422FF9FCD72F1600 Session-ID-ctx: Session-ID: 9484957F14038152A1FBD90FD200E4F11C283BDEEB7B6410422FF9FCD72F1600 Session-ID-ctx: Session-ID: 9484957F14038152A1FBD90FD200E4F11C283BDEEB7B6410422FF9FCD72F1600 Session-ID-ctx: Session-ID: 9484957F14038152A1FBD90FD200E4F11C283BDEEB7B6410422FF9FCD72F1600 Session-ID-ctx: Session-ID: 9484957F14038152A1FBD90FD200E4F11C283BDEEB7B6410422FF9FCD72F1600 Session-ID-ctx: Session-ID: 9484957F14038152A1FBD90FD200E4F11C283BDEEB7B6410422FF9FCD72F1600 Session-ID-ctx: ^C
Notez que le Session-ID est identique dans les 6 cas.
Mise en place du Standard HTTP Caching
Vérifiez que les modules mod_cache et mod_cache_disk soient activés :
[root@centos7 ~]# cat /etc/httpd/conf.modules.d/00-base.conf | grep mod_cache LoadModule cache_module modules/mod_cache.so LoadModule cache_disk_module modules/mod_cache_disk.so
ainsi que les modules mod_expires et mod_headers :
[root@centos7 ~]# cat /etc/httpd/conf.modules.d/00-base.conf | grep mod_expires LoadModule expires_module modules/mod_expires.so [root@centos7 ~]# cat /etc/httpd/conf.modules.d/00-base.conf | grep mod_headers LoadModule headers_module modules/mod_headers.so
Pour gérer l'utilitaire htcacheclean, un fichier d'unité systemd est installé par défaut lors de l'installation d'Apache :
[root@centos7 ~]# updatedb [root@centos7 ~]# locate htcacheclean.service /usr/lib/systemd/system/htcacheclean.service [root@centos7 ~]# cat /usr/lib/systemd/system/htcacheclean.service [Unit] Description=Disk Cache Cleaning Daemon for Apache HTTP Server After=httpd.service Documentation=man:htcacheclean(8) [Service] Type=forking User=apache PIDFile=/run/httpd/htcacheclean/pid EnvironmentFile=/etc/sysconfig/htcacheclean ExecStart=/usr/sbin/htcacheclean -P /run/httpd/htcacheclean/pid -d $INTERVAL -p $CACHE_ROOT -l $LIMIT $OPTIONS [root@centos7 ~]# systemctl status htcacheclean.service ● htcacheclean.service - Disk Cache Cleaning Daemon for Apache HTTP Server Loaded: loaded (/usr/lib/systemd/system/htcacheclean.service; static; vendor preset: disabled) Active: inactive (dead) Docs: man:htcacheclean(8)
Pour configurer ce service à démarrer lors du démarrage d'Apache, creéz le répertoire /etc/systemd/system/httpd.service.requires :
[root@centos7 ~]# mkdir -p /etc/systemd/system/httpd.service.requires
Ensuite créez un lien symbolique vers le fichier d'unité /usr/lib/systemd/system/htcacheclean.service dans le répertoire /etc/systemd/system/httpd.service.requires :
[root@centos7 ~]# ln -s /usr/lib/systemd/system/htcacheclean.service /etc/systemd/system/httpd.service.requires
L'utilitaire htcacheclean est configuré par l'édition du fichier /etc/sysconfig/htcacheclean :
[root@centos7 ~]# vi /etc/sysconfig/htcacheclean [root@centos7 ~]# cat /etc/sysconfig/htcacheclean # # Configuration options for systemd service, htcacheclean.service. # See htcacheclean(8) for more information on available options. # # Interval between cache clean runs, in minutes INTERVAL=15tp # Default cache root. CACHE_ROOT=/var/cache/httpd/proxy # Cache size limit in bytes (K=Kbytes, M=Mbytes) LIMIT=100M # Any other options... OPTIONS=
Important - Notez que si vous modifiez la directive CACHE_ROOT, vous devez aussi modifiez la directive CacheRoot dans le fichier /etc/httpd/conf/httpd.conf.
Re-démarrez le serveur httpd :
[root@centos7 ~]# systemctl restart httpd
Editez maintenant le fichier /etc/httpd/conf/httpd.conf en ajoutant les directives suivantes :
- CacheRoot
- CacheDirLevels
- CacheDirLength
[root@centos7 ~]# vi /etc/httpd/conf/httpd.conf [root@centos7 ~]# cat /etc/httpd/conf/httpd.conf # # This is the main Apache HTTP server configuration file. It contains the # configuration directives that give the server its instructions. # See <URL:http://httpd.apache.org/docs/2.4/> for detailed information. # In particular, see # <URL:http://httpd.apache.org/docs/2.4/mod/directives.html> # for a discussion of each configuration directive. # # Do NOT simply read the instructions in here without understanding # what they do. They're here only as hints or reminders. If you are unsure # consult the online docs. You have been warned. # # Configuration and logfile names: If the filenames you specify for many # of the server's control files begin with "/" (or "drive:/" for Win32), the # server will use that explicit path. If the filenames do *not* begin # with "/", the value of ServerRoot is prepended -- so 'log/access_log' # with ServerRoot set to '/www' will be interpreted by the # server as '/www/log/access_log', where as '/log/access_log' will be # interpreted as '/log/access_log'. # # ServerRoot: The top of the directory tree under which the server's # configuration, error, and log files are kept. # # Do not add a slash at the end of the directory path. If you point # ServerRoot at a non-local disk, be sure to specify a local disk on the # Mutex directive, if file-based mutexes are used. If you wish to share the # same ServerRoot for multiple httpd daemons, you will need to change at # least PidFile./ AuthnCacheSOCache shmcb CacheRoot /var/cache/httpd/proxy CacheDirLevels 2 CacheDirLength 1 ServerRoot "/etc/httpd" ...
Un hash md5 de l'URL servi est créé en tant que clef pour stocker les données. La valeur de CacheDirLevels spécifie le nombre de sous-répertoires à créer sur disque tandis que la valeur de CacheDirLength spécifie le nombre de caractères à utiliser pour le nom de chaque répertoire. Par exemple un hash de b1946ac92492d2347c6235b4d2611184 avec CacheDirLevels 2 et CacheDirLength 1 sera stocké dans une structure b/1/946ac92492d2347c6235b4d2611184.
Editez ensuite la section www.rhelnom.com du fichier /etc/httpd/conf/vhosts.d/Vhosts.conf en ajoutant les directives suivantes :
CacheQuickHandler off CacheLock on CacheLockPath /tmp/mod_cache-lock CacheLockMaxAge 5 CacheIgnoreHeaders Set-Cookie <Location /> CacheEnable disk CacheHeader on CacheDefaultExpire 600 CacheMaxExpire 86400 CacheLastModifiedFactor 0.5 </Location>
[root@centos7 ~]# vi /etc/httpd/conf/vhosts.d/Vhosts.conf [root@centos7 ~]# cat /etc/httpd/conf/vhosts.d/Vhosts.conf ... ##################www.rhelnom.com <VirtualHost *:80> ServerName www.rhelnom.com DirectoryIndex index.html DocumentRoot /www/site1 Customlog /www/logs/site1/rhelnom.log combined Errorlog /www/logs/site1/rhelnom_error.log CacheQuickHandler off CacheLock on CacheLockPath /tmp/mod_cache-lock CacheLockMaxAge 5 CacheIgnoreHeaders Set-Cookie <Location /> CacheEnable disk CacheHeader on CacheDefaultExpire 600 CacheMaxExpire 86400 CacheLastModifiedFactor 0.5 </Location> DBDriver mysql DBDParams "dbname=auth user=apache pass=PaSsW0Rd" DBDMin 4 DBDKeep 8 DBDMax 20 DBDExptime 300 <Directory /www/site1> Require all granted </Directory> <Directory /www/site1/secret> AllowOverride AuthConfig </Directory> <Directory /www/site1/secret2> AuthType Basic AuthName "MariaDB Secret" # AuthBasicProvider dbd AuthBasicProvider socache dbd AuthnCacheProvideFor dbd AuthnCacheTimeout 300 Require valid-user AuthDBDUserPWQuery "SELECT user_passwd FROM users WHERE user_name = %s" </Directory> </VirtualHost> ##################dav.homeland.net ...
CacheQuickHandler off
Pour des raions citées précédement, cette directive doit être mise à off.
CacheLock on
Le mécanisme de vérification de la page d'origine, afin de détecter des modifications éventuelles par rapport à la version en cache, génère un verrou sur la page en cache. De cette manière, en cas de demandes supplémentaires pour la ressource pendant la durée de vie du verrou, pourraient créer des problèmes de charge.
La mise en place du CacheLock avec la valeur on indique à Apache que la ressource est en cours de mise-à-jour. De cette façon, Apache sert la ressource expirée mais avec un avertissement dans le header.
CacheLockPath /tmp/mod_cache-lock
Dans le cas de ce LAB, nous mettons en place un CacheLockPath de /tmp.
CacheLockMaxAge 5
La valeur de la directive CacheLockMaxAge indique le nombre de secondes pendant lesquels le cache lock doit être considéré comme étant valide.
CacheIgnoreHeaders Set-Cookie
Cette directive indique à Apache de ne pas mettre en cache le header Set-Cookie de façon à ce que des informations confidentielles ne soient pas divulguées d'une manière inadvertante. Le header Set-Cookie est donc enlevé avant la mise en cache des autres headers.
<Location />
Cette directive indique que le cache sera mis en place pour tout le site www.rhelnom.com.
CacheEnable disk
Cette directive met en place le cache sur disque.
CacheHeader on
Cette directive indique que nous mettrosn en cache les headers.
CacheDefaultExpire 600
Cette directive indique le nombre par défaut de secondes qu'une ressource sera stocké en cache dans le cas de l'absence du header Expires ou Last-Modified
Another directive we'll set is CacheDefaultExpire so that we can set an expiration (in seconds) if neither the Expires nor the Last-Modified headers are set on the content. Similarly, we'll set CacheMaxExpire to cap the amount of time items will be saved. We'll set the CacheLastModifiedFactor so that Apache can create an expiration date if it has a Last-Modified date, but no expiration. The factor is multiplied by the time since modification to set a reasonable expiration.
CacheMaxExpire 86400
Cette directive indique le temps maximum en secondes qu'une ressource sera stockée en cache.
CacheLastModifiedFactor
Cette directive permet à Apache à calculer une date d'expiration de la ressource à partir de la valeur de la date Last-Modified.
Vérifiez maintenant la syntaxe des fichies de configuration :
[root@centos7 ~]# apachectl configtest Syntax OK
Redémarrez le service httpd :
[root@centos7 ~]# systemctl restart httpd Syntax OK
Testez votre configuration :
[root@centos7 ~]# lynx --dump www.rhelnom.com Accueil du site 1 [root@centos7 ~]# ls -lR /var/cache/httpd/proxy /var/cache/httpd/proxy: total 0 drwx------. 3 apache apache 14 Sep 10 15:26 W /var/cache/httpd/proxy/W: total 0 drwx------. 2 apache apache 72 Sep 10 15:26 J /var/cache/httpd/proxy/W/J: total 8 -rw-------. 1 apache apache 100 Sep 10 15:26 p19SR9R171waLwS6RcbA.data -rw-------. 1 apache apache 502 Sep 10 15:26 p19SR9R171waLwS6RcbA.header [root@centos7 ~]# cat /var/cache/httpd/proxy/W/J/p19SR9R171waLwS6RcbA.data <html> <head> <title>Page de Test</title> <body> <center>Accueil du site 1</center> </body> </html> [root@centos7 ~]# cat /var/cache/httpd/proxy/W/J/p19SR9R171waLwS6RcbA.data <html> <head> <title>Page de Test</title> <body> <center>Accueil du site 1</center> </body> </html> [root@centos7 ~]# cat /var/cache/httpd/proxy/W/J/p19SR9R171waLwS6RcbA.header �%r�dM�ur<k�u��dM�ur�dM�u����������������������������������http://www.rhelnom.com:80/index.html?Last-Modified: Sun, 02 Sep 2018 12:17:24 GMT ETag: "64-574e26843abdd" Accept-Ranges: bytes Content-Length: 100 Content-Type: text/html; charset=UTF-8 Host: www.rhelnom.com Accept: text/html, text/plain, text/css, text/sgml, */*;q=0.01 Accept-Language: en User-Agent: Lynx/2.8.8dev.15 libwww-FM/2.14 SSL-MM/1.4.1 OpenSSL/1.0.1e-fips
LAB #8 - Gestion d'un Reverse Proxy avec mod_proxy
LAB #9 - Gestion d'un Cluster de Répartition de Charge avec Tomcat et mod_jk
Pour installer Tomcat 8 sous CentOS 7, il convient de saisir les commandes suivantes :
[root@centos7 ~]# wget https://archive.apache.org/dist/tomcat/tomcat-8/v8.0.36/bin/apache-tomcat-8.0.36.tar.gz [root@centos7 ~]# tar xvf apache-tomcat-8.0.36.tar.gz [root@centos7 ~]# mv apache-tomcat-8.0.36 /usr/tomcat8
Installez maintenant le JDK :
[root@centos7 ~]# yum install java-1.8.0-openjdk-devel
Vérifiez la présence du jre-1.8.0-openjdk dans le répertoire /usr/lib/jvm :
[root@centos7 work]# ls -l /usr/lib/jvm/jre-1.8.0-openjdk* lrwxrwxrwx 1 root root 35 Apr 27 12:54 /usr/lib/jvm/jre-1.8.0-openjdk -> /etc/alternatives/jre_1.8.0_openjdk lrwxrwxrwx 1 root root 51 Apr 27 12:54 /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.131-2.b11.el7_3.x86_64 -> java-1.8.0-openjdk-1.8.0.131-2.b11.el7_3.x86_64/jre
Ajoutez les trois lignes suivantes au fichier /etc/profile :
... PATH=$PATH:/usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.131-2.b11.el7_3.x86_64/bin JAVA_HOME=/usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.131-2.b11.el7_3.x86_64 export PATH JAVA_HOME
Important : Vérifiez que la version du jre-1.8.0-openjdk dans le fichier /etc/profile est la même que dans le répertoire /usr/lib/jvm.
Rechargez le fichier /etc/profile et vérifiez les valeurs des deux variables précédement déclarées :
[root@centos7 ~]# source /etc/profile [root@centos7 ~]# echo $PATH /usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin:/usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.121-0.b13.el7_3.x86_64/bin:/usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.131-2.b11.el7_3.x86_64/bin [root@centos7 ~]# echo $JAVA_HOME /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.131-2.b11.el7_3.x86_64
Vérifiez ensuite la version de java :
[root@centos7 ~]# java -version openjdk version "1.8.0_131" OpenJDK Runtime Environment (build 1.8.0_131-b11) OpenJDK 64-Bit Server VM (build 25.131-b11, mixed mode)
Définissez maintenant la variable CATALINA_HOME dans le fichier /etc/profile :
... # Tomcat CATALINA_HOME="/usr/tomcat8" export CATALINA_HOME PATH=$PATH:/usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.131-2.b11.el7_3.x86_64/bin JAVA_HOME=/usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.131-2.b11.el7_3.x86_64 export PATH JAVA_HOME
Rechargez /etc/profile :
[root@centos7 ~]# source /etc/profile [root@centos7 ~]# echo $CATALINA_HOME /usr/tomcat8
Démarrez maintenant Tomcat 8 :
[root@centos7 ~]# cd /usr/tomcat8/bin [root@centos7 bin]# ./startup.sh Using CATALINA_BASE: /usr/tomcat8 Using CATALINA_HOME: /usr/tomcat8 Using CATALINA_TMPDIR: /usr/tomcat8/temp Using JRE_HOME: /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.131-2.b11.el7_3.x86_64 Using CLASSPATH: /usr/tomcat8/bin/bootstrap.jar:/usr/tomcat8/bin/tomcat-juli.jar Tomcat started.
Utilisez le navigateur de texte lynx pour tester Tomcat 8 :
[root@centos7 bin]# lynx --dump http://localhost:8080 [1]Home [2]Documentation [3]Configuration [4]Examples [5]Wiki [6]Mailing Lists [7]Find Help Apache Tomcat/8.0.36 If you're seeing this, you've successfully installed Tomcat. Congratulations! [tomcat logo] Recommended Reading: ...
Le schéma suivant indique le couplage Tomcat/Apache :
Téléchargez le connecteur mod-jk pour Apache :
[root@centos7 ~]# wget http://apache.mirrors.ovh.net/ftp.apache.org/dist/tomcat/tomcat-connectors/jk/tomcat-connectors-1.2.42-src.tar.gz [root@centos7 ~]# tar xvf tomcat-connectors-1.2.42-src.tar.gz [root@centos7 ~]# cd tomcat-connectors-1.2.42-src/
Installez le binaire apxs inclut dans le paquet httpd-devel. Le binaire apxs est utilisé pour construire les modules d'Apache :
[root@centos7 tomcat-connectors-1.2.42-src]# yum install httpd-devel
Placez-vous dans le sous-répertoire native et lancez les commandes pour effectuer la compilation :
[root@centos7 tomcat-connectors-1.2.42-src]# cd native/ [root@centos7 native]# which apxs /bin/apxs [root@centos7 native]# ./configure --with-apxs=/bin/apxs ... [root@centos7 native]# make ... [root@centos7 native]# make install Making install in common make[1]: Entering directory `/root/tomcat-connectors-1.2.42-src/native/common' make[1]: Nothing to be done for `install'. make[1]: Leaving directory `/root/tomcat-connectors-1.2.42-src/native/common' Making install in apache-2.0 make[1]: Entering directory `/root/tomcat-connectors-1.2.42-src/native/apache-2.0' Installing files to Apache Modules Directory... /bin/apxs -i mod_jk.la /usr/lib64/httpd/build/instdso.sh SH_LIBTOOL='/usr/lib64/apr-1/build/libtool' mod_jk.la /usr/lib64/httpd/modules /usr/lib64/apr-1/build/libtool --mode=install install mod_jk.la /usr/lib64/httpd/modules/ libtool: install: install .libs/mod_jk.so /usr/lib64/httpd/modules/mod_jk.so libtool: install: install .libs/mod_jk.lai /usr/lib64/httpd/modules/mod_jk.la libtool: install: install .libs/mod_jk.a /usr/lib64/httpd/modules/mod_jk.a libtool: install: chmod 644 /usr/lib64/httpd/modules/mod_jk.a libtool: install: ranlib /usr/lib64/httpd/modules/mod_jk.a libtool: finish: PATH="/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin:/usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.91-1.b14.el7_2.x86_64/bin:/usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.91-1.b14.el7_2.x86_64/bin:/usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.91-1.b14.el7_2.x86_64/bin:/usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.91-1.b14.el7_2.x86_64/bin:/sbin" ldconfig -n /usr/lib64/httpd/modules ---------------------------------------------------------------------- Libraries have been installed in: /usr/lib64/httpd/modules If you ever happen to want to link against installed libraries in a given directory, LIBDIR, you must either use libtool, and specify the full pathname of the library, or use the `-LLIBDIR' flag during linking and do at least one of the following: - add LIBDIR to the `LD_LIBRARY_PATH' environment variable during execution - add LIBDIR to the `LD_RUN_PATH' environment variable during linking - use the `-Wl,-rpath -Wl,LIBDIR' linker flag - have your system administrator add LIBDIR to `/etc/ld.so.conf' See any operating system documentation about shared libraries for more information, such as the ld(1) and ld.so(8) manual pages. ---------------------------------------------------------------------- chmod 755 /usr/lib64/httpd/modules/mod_jk.so Please be sure to arrange /etc/httpd/conf/httpd.conf... make[1]: Leaving directory `/root/tomcat-connectors-1.2.42-src/native/apache-2.0' make[1]: Entering directory `/root/tomcat-connectors-1.2.42-src/native' make[2]: Entering directory `/root/tomcat-connectors-1.2.42-src/native' make[2]: Nothing to be done for `install-exec-am'. make[2]: Nothing to be done for `install-data-am'. make[2]: Leaving directory `/root/tomcat-connectors-1.2.42-src/native' make[1]: Leaving directory `/root/tomcat-connectors-1.2.42-src/native'
Modifiez ensuite le fichier /etc/httpd/conf/httpd.conf ainsi :
... ServerName www.i2tch.loc:80 ...
et ajoutez les directives suivantes à la fin du fichier afin de prendre en compte mod_jk et sa configuration :
... LoadModule jk_module modules/mod_jk.so JkWorkersFile conf/workers.properties JkLogFile logs/mod_jk.log JkLogLevel info JkMount /docs/* worker1 JkMount /docs worker1
Les différentes directives Apache utilisables avec mod_jk sont :
Directive | Description |
---|---|
JkWorkersFile | Spécifie le nom et l'emplacement du fichier de configuration du module nommé workers.properties par convention. Le chemin peut être absolu ou rélatif à l'installation d'Apache. |
JkWorkerProperty | L'utilisation de cette directive est mutuellement exclusive avec l'utilisation de la directive JkWorkersFile. Elle permet de définir les directives du fichier workers.properties directement dans le fichier httpd.conf sous la forme JkWorkerProperty <Directive> avec une directive par ligne. Chaque ligne doit donc commencer par JkWorkerProperty. |
JkLogFile | Spécifie le nom et l'emplacement du fichier de journalisation du module. Le chemin peut être absolu ou rélatif à l'installation d'Apache. |
JkLogLevel | Spécifie le niveau de journalisation du module. Les valeurs ici peuvent être trace, debug, info, warn et error. Le fonctionnement est similaire à syslog dans la mesure où si la valeur est info alors tous les messages des niveaux info, warn et error seront journalisés. |
JkMount | Spécifie l'association d'un contexte d'application Tomcat avec un travailleur. Autrement dit, cette directive spécifie quelles sont les ressources d'une application Tomcat accessibles en passant par Apache. La syntaxe est JkMount <URL> <Nom du Travailleur>. |
JkUnMount | Spécifie une interdiction de redirection de requêtes vers une ressource d'une application Tomcat. La syntaxe est JkUnMount <URL> <Nom du Travailleur>. Notez que cette directive est prioritaire par rapport à la directive JkMount. |
JkAutoAlias | Spécifie un alias entre le répertoire des applications de Tomcat et le répertoire de publication des fichiers statiques d'Apache. De cette façon, les deux servuers partagent un répertoire de publication unique. |
JkLogStampFormat | Spécifie le format de la date inscrite dans le fichier de journalisation du module en utilisant des séquences de contrôle, par exemple, JkLogStampFormat “[%a %b %d %H:%M:%S %Y]“. |
JkExtractSSL | Spécifie que le module peut transmettre les informations SSL vers le serveur Tomcat. |
JkHTTPSIndicator | Spécifie le nom de la variable Apache contenant l'indication SSL. |
JkCERTSIndicator | Spécifie le nom de la variable Apache contenant le certificat SSL. |
JkSESSIONIndicator | Spécifie le nom de la variable Apache contenant l'identifiant de session SSL. |
Modifiez ensuite le fichier /etc/hosts pour la prise en charge du nom de notre serveur :
[root@centos7 native]# vi /etc/hosts [root@centos7 native]# cat /etc/hosts 127.0.0.1 localhost.localdomain localhost ::1 localhost6.localdomain6 localhost6 10.0.2.15 www.i2tch.loc
Créez ensuite le fichier /etc/httpd/conf/workers.properties :
[root@centos7 native]# cd ~ [root@centos7 ~]# vi /etc/httpd/conf/workers.properties [root@centos7 ~]# cat /etc/httpd/conf/workers.properties worker.list=worker1 worker.worker1.type=ajp13 worker.worker1.host=10.0.2.15 worker.worker1.port=8009
Vérifiez l'existence des lignes concernant le connecteur dans le fichier /usr/tomcat8/conf/server.xml :
[root@centos7 ~]# cat /usr/tomcat8/conf/server.xml | grep 8009 <!-- Define an AJP 1.3 Connector on port 8009 --> <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
Redémarrez ensuite les services httpd et tomcat8 :
[root@centos7 ~]# systemctl restart httpd.service [root@centos7 ~]# cd /usr/tomcat8/bin/ [root@centos7 bin]# ls bootstrap.jar catalina-tasks.xml configtest.bat digest.bat setclasspath.sh startup.bat tomcat-native.tar.gz version.bat catalina.bat commons-daemon.jar configtest.sh digest.sh shutdown.bat startup.sh tool-wrapper.bat version.sh catalina.sh commons-daemon-native.tar.gz daemon.sh setclasspath.bat shutdown.sh tomcat-juli.jar tool-wrapper.sh [root@centos7 bin]# ./shutdown.sh Using CATALINA_BASE: /usr/tomcat8 Using CATALINA_HOME: /usr/tomcat8 Using CATALINA_TMPDIR: /usr/tomcat8/temp Using JRE_HOME: /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.131-2.b11.el7_3.x86_64 Using CLASSPATH: /usr/tomcat8/bin/bootstrap.jar:/usr/tomcat8/bin/tomcat-juli.jar [root@centos7 bin]# ./startup.sh Using CATALINA_BASE: /usr/tomcat8 Using CATALINA_HOME: /usr/tomcat8 Using CATALINA_TMPDIR: /usr/tomcat8/temp Using JRE_HOME: /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.131-2.b11.el7_3.x86_64 Using CLASSPATH: /usr/tomcat8/bin/bootstrap.jar:/usr/tomcat8/bin/tomcat-juli.jar Tomcat started.
Vérifiez maintenant le bon fonctionnement d'Apache et de Tomcat en consultant les liens suivants :
[root@centos7 bin]# lynx --dump http://www.i2tch.loc [root@centos7 bin]# lynx --dump http://www.i2tch.loc:8080 [root@centos7 bin]# lynx --dump http://www.i2tch.loc/docs/
Important : Notez qu'en consultant l'adresse http://www.i2tch.loc/docs/ vous obtenez la même page que lors de votre consultation de l'adresse http://www.i2tch.loc:8080. Ceci implique que le serveur Apache est maintenant un serveur frontal pour le serveur Tomcat 8.
Créez maintenant deux répertoires en dessous de $CATALINA_HOME :
[root@centos7 ~]# mkdir $CATALINA_HOME/tomcat1 $CATALINA_HOME/tomcat2
Arrêtez le serveur Tomcat et copiez les répertoires $CATALINA_HOME/conf, $CATALINA_HOME/logs, $CATALINA_HOME/temp, $CATALINA_HOME/webapps, $CATALINA_HOME/work dans les répertoires $CATALINA_HOME/tomcat1 et $CATALINA_HOME/tomcat2 :
[root@centos7 ~]# cd $CATALINA_HOME [root@centos7 tomcat8]# cp -rp conf/ tomcat1/ [root@centos7 tomcat8]# cp -rp logs/ tomcat1 [root@centos7 tomcat8]# cp -rp temp/ tomcat1 [root@centos7 tomcat8]# cp -rp webapps/ tomcat1 [root@centos7 tomcat8]# cp -rp work/ tomcat1 [root@centos7 tomcat8]# cp -rp conf/ tomcat2/ [root@centos7 tomcat8]# cp -rp logs/ tomcat2/ [root@centos7 tomcat8]# cp -rp temp/ tomcat2/ [root@centos7 tomcat8]# cp -rp webapps/ tomcat2/ [root@centos7 tomcat8]# cp -rp work/ tomcat2/
Supprimez les répertoires $CATALINA_HOME/conf, $CATALINA_HOME/logs, $CATALINA_HOME/temp, $CATALINA_HOME/webapps, $CATALINA_HOME/work :
[root@centos7 tomcat8]# rm -rf conf/ logs/ temp/ webapps/ work/
Créez maintenant les scripts de démarrage et d'arrêt de chaque instance de Tomcat :
[root@centos7 tomcat8]# cd bin [root@centos7 bin]# vi startTomcat1 [root@centos7 bin]# cat startTomcat1 #!/bin/bash export CATALINA_BASE=/usr/tomcat8/tomcat1 . $CATALINA_HOME/bin/startup.sh [root@centos7 bin]# vi stopTomcat1 [root@centos7 bin]# cat stopTomcat1 #!/bin/bash export CATALINA_BASE=/usr/tomcat8/tomcat1 . $CATALINA_HOME/bin/shutdown.sh [root@centos7 bin]# vi startTomcat2 [root@centos7 bin]# cat startTomcat2 export CATALINA_BASE=/usr/tomcat8/tomcat2 . $CATALINA_HOME/bin/startup.sh [root@centos7 bin]# vi stopTomcat2 [root@centos7 bin]# cat stopTomcat2 #!/bin/bash export CATALINA_BASE=/usr/tomcat8/tomcat2 . $CATALINA_HOME/bin/shutdown.sh
Rendez les scripts exécutables :
[root@centos7 bin]# chmod a+x startTomcat1 [root@centos7 bin]# chmod a+x startTomcat2 [root@centos7 bin]# chmod a+x stopTomcat1 [root@centos7 bin]# chmod a+x stopTomcat2 [root@centos7 bin]# ls -l | grep startT -rwxr-xr-x 1 root root 86 Jun 29 01:47 startTomcat1 -rwxr-xr-x 1 root root 86 Jun 29 01:51 startTomcat2 [root@centos7 bin]# ls -l | grep stopT -rwxr-xr-x 1 root root 87 Jun 29 01:50 stopTomcat1 -rwxr-xr-x 1 root root 87 Jun 29 01:52 stopTomcat2
Modifiez les ports dans le fichier server.xml de chaque installation de Tomcat en utilisant VI :
[root@centos7 bin]# vi /usr/tomcat8/tomcat1/conf/server.xml [root@centos7 bin]# vi /usr/tomcat8/tomcat2/conf/server.xml
Les commandes VI suivantes peuvent vous aider :
Pour le fichier /usr/tomcat8/tomcat1/conf/server.xml : :g/8080/s//8180/g :g/8009/s//8109/g :g/8005/s//8105/g :g/8443/s//8143/g Pour le fichier /usr/tomcat8/tomcat2/conf/server.xml : :g/8080/s//8280/g :g/8009/s//8209/g :g/8005/s//8205/g :g/8443/s//8243/g
Démarrez les deux instances de Tomcat :
[root@centos7 bin]# ./startTomcat1 Using CATALINA_BASE: /usr/tomcat8/tomcat1 Using CATALINA_HOME: /usr/tomcat8 Using CATALINA_TMPDIR: /usr/tomcat8/tomcat1/temp Using JRE_HOME: /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.91-1.b14.el7_2.x86_64 Using CLASSPATH: /usr/tomcat8/bin/bootstrap.jar:/usr/tomcat8/bin/tomcat-juli.jar Tomcat started. [root@centos7 bin]# ps aux | grep tomcat root 25696 30.0 4.4 2399312 67900 pts/0 Sl 02:47 0:04 /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.91-1.b14.el7_2.x86_64/bin/java -Djava.util.logging.config.file=/usr/tomcat8/tomcat1/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djdk.tls.ephemeralDHKeySize=2048 -Djava.endorsed.dirs=/usr/tomcat8/endorsed -classpath /usr/tomcat8/bin/bootstrap.jar:/usr/tomcat8/bin/tomcat-juli.jar -Dcatalina.base=/usr/tomcat8/tomcat1 -Dcatalina.home=/usr/tomcat8 -Djava.io.tmpdir=/usr/tomcat8/tomcat1/temp org.apache.catalina.startup.Bootstrap start root 25785 0.0 0.0 112644 968 pts/0 R+ 02:47 0:00 grep --color=auto tomcat [root@centos7 bin]# ./startTomcat2 Using CATALINA_BASE: /usr/tomcat8/tomcat2 Using CATALINA_HOME: /usr/tomcat8 Using CATALINA_TMPDIR: /usr/tomcat8/tomcat2/temp Using JRE_HOME: /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.91-1.b14.el7_2.x86_64 Using CLASSPATH: /usr/tomcat8/bin/bootstrap.jar:/usr/tomcat8/bin/tomcat-juli.jar Tomcat started. [root@centos7 bin]# ps aux | grep tomcat root 25696 32.1 5.2 2403492 80468 pts/0 Sl 02:47 0:07 /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.91-1.b14.el7_2.x86_64/bin/java -Djava.util.logging.config.file=/usr/tomcat8/tomcat1/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djdk.tls.ephemeralDHKeySize=2048 -Djava.endorsed.dirs=/usr/tomcat8/endorsed -classpath /usr/tomcat8/bin/bootstrap.jar:/usr/tomcat8/bin/tomcat-juli.jar -Dcatalina.base=/usr/tomcat8/tomcat1 -Dcatalina.home=/usr/tomcat8 -Djava.io.tmpdir=/usr/tomcat8/tomcat1/temp org.apache.catalina.startup.Bootstrap start root 25817 32.6 2.4 2381580 37172 pts/0 Sl 02:47 0:00 /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.91-1.b14.el7_2.x86_64/bin/java -Djava.util.logging.config.file=/usr/tomcat8/tomcat2/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djdk.tls.ephemeralDHKeySize=2048 -Djava.endorsed.dirs=/usr/tomcat8/endorsed -classpath /usr/tomcat8/bin/bootstrap.jar:/usr/tomcat8/bin/tomcat-juli.jar -Dcatalina.base=/usr/tomcat8/tomcat2 -Dcatalina.home=/usr/tomcat8 -Djava.io.tmpdir=/usr/tomcat8/tomcat2/temp org.apache.catalina.startup.Bootstrap start root 25843 0.0 0.0 112644 968 pts/0 S+ 02:47 0:00 grep --color=auto tomcat
Vérifiez maintenant que les deux instances peuvent être arrêtés :
[root@centos7 bin]# ./stopTomcat2 Using CATALINA_BASE: /usr/tomcat8/tomcat2 Using CATALINA_HOME: /usr/tomcat8 Using CATALINA_TMPDIR: /usr/tomcat8/tomcat2/temp Using JRE_HOME: /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.91-1.b14.el7_2.x86_64 Using CLASSPATH: /usr/tomcat8/bin/bootstrap.jar:/usr/tomcat8/bin/tomcat-juli.jar [root@centos7 bin]# ./stopTomcat1 Using CATALINA_BASE: /usr/tomcat8/tomcat1 Using CATALINA_HOME: /usr/tomcat8 Using CATALINA_TMPDIR: /usr/tomcat8/tomcat1/temp Using JRE_HOME: /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.91-1.b14.el7_2.x86_64 Using CLASSPATH: /usr/tomcat8/bin/bootstrap.jar:/usr/tomcat8/bin/tomcat-juli.jar [root@centos7 bin]# ps aux | grep tomcat root 27318 0.0 0.0 112644 964 pts/0 R+ 02:52 0:00 grep --color=auto tomcat
Modifiez le fichier /etc/httpd/conf/workers.properties :
[root@centos7 bin]# vi /etc/httpd/conf/workers.properties [root@centos7 bin]# cat /etc/httpd/conf/workers.properties worker.list=balancer worker.tomcat1.type=ajp13 worker.tomcat1.host=10.0.2.15 worker.tomcat1.port=8109 worker.tomcat1.lbfactor=1 worker.tomcat2.type=ajp13 worker.tomcat2.host=10.0.2.15 worker.tomcat2.port=8209 worker.tomcat2.lbfactor=1 worker.balancer.type=lb worker.balancer.balance_workers=tomcat1,tomcat2 worker.balancer.sticky_session=1
Modifiez la section concernant Tomcat dans le fichier /etc/httpd/conf/httpd.conf et commentez la ligne IncludeOptional conf.d/*.conf :
[root@centos7 bin]# vi /etc/httpd/conf/httpd.conf [root@centos7 bin]# tail /etc/httpd/conf/httpd.conf # # Load config files in the "/etc/httpd/conf.d" directory, if any. # IncludeOptional conf.d/*.conf LoadModule jk_module modules/mod_jk.so JkWorkersFile conf/workers.properties JkLogFile logs/mod_jk.log JkLogLevel info JkMount /docs/* balancer JkMount /docs balancer
Modifiez la section <Engine> du fichier $CATALINA_HOME/tomcat1/conf/server.xml :
[root@centos7 bin]# vi $CATALINA_HOME/tomcat1/conf/server.xml ... <Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat1"> ...
Modifiez ensuite la section <Engine> du fichier $CATALINA_HOME/tomcat2/conf/server.xml :
[root@centos7 bin]# vi $CATALINA_HOME/tomcat2/conf/server.xml ... <Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat2"> ...
Pour pouvoir tester la configuration, remplacer les fichiers index.html de chaque application docs afin de pouvoir identifier quelle instance répond à des requêtes :
[root@centos7 bin]# mv $CATALINA_HOME/tomcat1/webapps/docs/index.html $CATALINA_HOME/tomcat1/webapps/docs/index.old [root@centos7 bin]# vi $CATALINA_HOME/tomcat1/webapps/docs/index.html [root@centos7 bin]# cat $CATALINA_HOME/tomcat1/webapps/docs/index.html <html> <title>Tomcat1</title> <body> <center>This is Tomcat1</center> </body> </html> [root@centos7 bin]# mv $CATALINA_HOME/tomcat2/webapps/docs/index.html $CATALINA_HOME/tomcat2/webapps/docs/index.old [root@centos7 bin]# vi $CATALINA_HOME/tomcat2/webapps/docs/index.html [root@centos7 bin]# cat $CATALINA_HOME/tomcat2/webapps/docs/index.html <html> <title>Tomcat2</title> <body> <center>This is Tomcat2</center> </body> </html> [root@centos7 bin]#
Redémarrez le service httpd.service :
[root@centos7 bin]# systemctl restart httpd.service
Démarrez les deux instances de Tomcat :
[root@centos7 bin]# ./startTomcat1 Using CATALINA_BASE: /usr/tomcat8/tomcat1 Using CATALINA_HOME: /usr/tomcat8 Using CATALINA_TMPDIR: /usr/tomcat8/tomcat1/temp Using JRE_HOME: /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.91-1.b14.el7_2.x86_64 Using CLASSPATH: /usr/tomcat8/bin/bootstrap.jar:/usr/tomcat8/bin/tomcat-juli.jar Tomcat started. [root@centos7 bin]# ./startTomcat2 Using CATALINA_BASE: /usr/tomcat8/tomcat2 Using CATALINA_HOME: /usr/tomcat8 Using CATALINA_TMPDIR: /usr/tomcat8/tomcat2/temp Using JRE_HOME: /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.91-1.b14.el7_2.x86_64 Using CLASSPATH: /usr/tomcat8/bin/bootstrap.jar:/usr/tomcat8/bin/tomcat-juli.jar Tomcat started.
Utilisez Lynx pour vous connecter à l'application docs :
[root@centos7 httpd]# lynx --dump http://www.i2tch.loc/docs This is Tomcat2 [root@centos7 httpd]# lynx --dump http://www.i2tch.loc/docs This is Tomcat2 [root@centos7 httpd]# lynx --dump http://www.i2tch.loc/docs This is Tomcat2
Attention : Notez que l'affinité de session est activée par défaut par le module AJP.
Arrêtez maintenant l'instance tomcat2 :
[root@centos7 bin]# ./stopTomcat2 Using CATALINA_BASE: /usr/tomcat8/tomcat2 Using CATALINA_HOME: /usr/tomcat8 Using CATALINA_TMPDIR: /usr/tomcat8/tomcat2/temp Using JRE_HOME: /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.91-1.b14.el7_2.x86_64 Using CLASSPATH: /usr/tomcat8/bin/bootstrap.jar:/usr/tomcat8/bin/tomcat-juli.jar
Connectez-vous de nouveau à l'application docs :
[root@centos7 bin]# lynx --dump http://www.i2tch.loc/docs This is Tomcat1 [root@centos7 bin]#
Important - Notez que c'est maintenant l'instance tomcat1 qui répond.
LAB #10 - Gestion d'un Cluster de Répartition de Charge avec mod_proxy_ajp
Vérifiez que les lignes LoadModule proxy_ajp_module modules/mod_proxy_ajp.so, LoadModule proxy_balancer_module modules/mod_proxy_balancer.so et LoadModule proxy_module modules/mod_proxy.so soient présentes dans le fichier /etc/httpd/conf.modules.d/00-proxy.conf :
[root@centos7 bin]# cat /etc/httpd/conf.modules.d/00-proxy.conf # This file configures all the proxy modules: LoadModule proxy_module modules/mod_proxy.so LoadModule lbmethod_bybusyness_module modules/mod_lbmethod_bybusyness.so LoadModule lbmethod_byrequests_module modules/mod_lbmethod_byrequests.so LoadModule lbmethod_bytraffic_module modules/mod_lbmethod_bytraffic.so LoadModule lbmethod_heartbeat_module modules/mod_lbmethod_heartbeat.so LoadModule proxy_ajp_module modules/mod_proxy_ajp.so LoadModule proxy_balancer_module modules/mod_proxy_balancer.so LoadModule proxy_connect_module modules/mod_proxy_connect.so LoadModule proxy_express_module modules/mod_proxy_express.so LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so LoadModule proxy_fdpass_module modules/mod_proxy_fdpass.so LoadModule proxy_ftp_module modules/mod_proxy_ftp.so LoadModule proxy_http_module modules/mod_proxy_http.so LoadModule proxy_scgi_module modules/mod_proxy_scgi.so LoadModule proxy_wstunnel_module modules/mod_proxy_wstunnel.so
Modifiez le fichier /etc/httpd/conf/httpd.conf :
[root@centos7 bin]# tail -n 15 /etc/httpd/conf/httpd.conf #LoadModule jk_module modules/mod_jk.so #JkWorkersFile conf/workers.properties #JkLogFile logs/mod_jk.log #JkLogLevel info #JkMount /docs/* balancer #JkMount /docs balancer ProxyTimeout 300 <Proxy balancer://tomcat8-docs> BalancerMember ajp://localhost:8109/docs route=tomcat1 BalancerMember ajp://localhost:8209/docs route=tomcat2 </Proxy> ProxyPass /docs balancer://tomcat8-docs ProxyPassReverse /docs balancer://tomcat8-docs
Redémarrez le serveur httpd :
[root@centos7 bin]# systemctl restart httpd.service
Démarrez l'instance tomcat2 de Tomcat :
[root@centos7 bin]# ./startTomcat2 Using CATALINA_BASE: /usr/tomcat8/tomcat2 Using CATALINA_HOME: /usr/tomcat8 Using CATALINA_TMPDIR: /usr/tomcat8/tomcat2/temp Using JRE_HOME: /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.91-1.b14.el7_2.x86_64 Using CLASSPATH: /usr/tomcat8/bin/bootstrap.jar:/usr/tomcat8/bin/tomcat-juli.jar Tomcat started
Utilisez Lynx pour vous connecter à l'application docs :
[root@centos7 bin]# lynx --dump http://www.i2tch.loc/docs This is Tomcat1 [root@centos7 bin]# lynx --dump http://www.i2tch.loc/docs This is Tomcat2 [root@centos7 bin]# lynx --dump http://www.i2tch.loc/docs This is Tomcat1 [root@centos7 bin]# lynx --dump http://www.i2tch.loc/docs This is Tomcat2
Attention : Notez que l'affinité de session n'est pas activée par défaut par le module proxy.
Afin de mettre en place l'affinité de session, il convient d'utiliser un cookie appelé ROUTEID.
Modifiez le fichier /etc/httdp/conf/httpd.conf ainsi :
... IncludeOptional conf.d/*.conf #LoadModule jk_module modules/mod_jk.so #JkWorkersFile conf/workers.properties #JkLogFile logs/mod_jk.log #JkLogLevel info #JkMount /docs/* balancer #JkMount /docs balancer Header add Set-Cookie "ROUTEID=.%{BALANCER_WORKER_ROUTE}e; path=/" env=BALANCER_ROUTE_CHANGED <Proxy balancer://tomcat8-docs> BalancerMember ajp://localhost:8109/docs route=tomcat1 BalancerMember ajp://localhost:8209/docs route=tomcat2 ProxySet stickysession=ROUTEID </Proxy> ProxyPass /docs balancer://tomcat8-docs ProxyPassReverse /docs balancer://tomcat8-docs
Testez ensuite l'affinité de session en utilisant un navigateur graphique.
Pour plus d'information concernant l'utilisation de mod_proxy, consultez cette page
Maintenir l'Etat des Clients
Editez le fichier web.xml de l'application /docs de chaque instance de Tomcat en incluant la directive <distributable/> :
[root@centos7 bin]# vi $CATALINA_HOME/tomcat1/webapps/docs/WEB-INF/web.xml [root@centos7 bin]# vi $CATALINA_HOME/tomcat2/webapps/docs/WEB-INF/web.xml [root@centos7 bin]# tail $CATALINA_HOME/tomcat2/webapps/docs/WEB-INF/web.xml http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1" metadata-complete="true"> <display-name>Tomcat Documentation</display-name> <description> Tomcat Documentation. </description> <distributable/> </web-app> [root@centos7 bin]# tail $CATALINA_HOME/tomcat1/webapps/docs/WEB-INF/web.xml http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1" metadata-complete="true"> <display-name>Tomcat Documentation</display-name> <description> Tomcat Documentation. </description> <distributable/> </web-app>
Créez les fichiers $CATALINA_HOME/tomcat1/webapps/docs/session.jsp et $CATALINA_HOME/tomcat2/webapps/docs/session.jsp :
[root@centos7 bin]# vi $CATALINA_HOME/tomcat1/webapps/docs/session.jsp [root@centos7 bin]# cat $CATALINA_HOME/tomcat1/webapps/docs/session.jsp <%@page language="java" %> <html> <body> <h3> Session : <%= session.getId() %> </h3> </body> </html>
[root@centos7 bin]# vi $CATALINA_HOME/tomcat2/webapps/docs/session.jsp [root@centos7 bin]# cat $CATALINA_HOME/tomcat2/webapps/docs/session.jsp <%@page language="java" %> <html> <body> <h3> Session : <%= session.getId() %> </h3> </body> </html>
Décommentez la ligne suivante dans les fichiers server.xml :
[root@centos7 bin]# vi $CATALINA_HOME/tomcat1/conf/server.xml ... <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/> ... [root@centos7 bin]# vi $CATALINA_HOME/tomcat2/conf/server.xml ... <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/> ...
Editez maintenant les fichier $CATALINA_HOME/tomcat1/conf/context.xml et $CATALINA_HOME/tomcat2/conf/context.xml en ajoutant la section suivante :
<Manager className="org.apache.catalina.session.PersistentManager" > <Store className="org.apache.catalina.session.FileStore" directory="/tmp/sessions/" /> </Manager>
Vous obtiendrez un résultat similaire à celui-ci :
[root@centos7 bin]# cat /usr/tomcat8/tomcat1/conf/context.xml <?xml version='1.0' encoding='utf-8'?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!-- The contents of this file will be loaded for each web application --> <Context> <Manager className="org.apache.catalina.session.PersistentManager" > <Store className="org.apache.catalina.session.FileStore" directory="/tmp/sessions/" /> </Manager> <!-- Default set of monitored resources. If one of these changes, the --> <!-- web application will be reloaded. --> <WatchedResource>WEB-INF/web.xml</WatchedResource> <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource> <!-- Uncomment this to disable session persistence across Tomcat restarts --> <!-- <Manager pathname="" /> --> <!-- Uncomment this to enable Comet connection tacking (provides events on session expiration as well as webapp lifecycle) --> <!-- <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" /> --> </Context>
Créez le répertoire /tmp/sessions pour contenir les fichiers de sessions :
[root@centos7 bin]# mkdir /tmp/sessions
En utilisant votre navigateur graphique, saisissez l'URL suivante :
http://www.i2tch.loc/docs/session.jsp
Vous obtiendrez une résultat similaire à l'exemple suivant :
Session : 7DA9FEE977543F1F574DADFA7B1FADD0.tomcat1
ou
Session : 7DA9FEE977543F1F574DADFA7B1FADD0.tomcat2
Selon l'instance de Tomcat qui a répondu, arrêtez cette instance :
[root@centos7 bin]# ./stopTomcat1 Using CATALINA_BASE: /usr/tomcat8/tomcat1 Using CATALINA_HOME: /usr/tomcat8 Using CATALINA_TMPDIR: /usr/tomcat8/tomcat1/temp Using JRE_HOME: /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.91-1.b14.el7_2.x86_64 Using CLASSPATH: /usr/tomcat8/bin/bootstrap.jar:/usr/tomcat8/bin/tomcat-juli.jar
ou
[root@centos7 bin]# ./stopTomcat2 Using CATALINA_BASE: /usr/tomcat8/tomcat2 Using CATALINA_HOME: /usr/tomcat8 Using CATALINA_TMPDIR: /usr/tomcat8/tomcat2/temp Using JRE_HOME: /usr/lib/jvm/jre-1.8.0-openjdk-1.8.0.91-1.b14.el7_2.x86_64 Using CLASSPATH: /usr/tomcat8/bin/bootstrap.jar:/usr/tomcat8/bin/tomcat-juli.jar
Contrôlez le contenu du répertoire /tmp/sessions :
[root@centos7 bin]# ls -l /tmp/sessions total 4 -rw-r--r-- 1 root root 263 Jul 5 23:32 7DA9FEE977543F1F574DADFA7B1FADD0.tomcat1.session
Revenez à votre navigateur Web graphique et rafraichissez la page. Vous obtiendrez un résultat démontrant que la session est resté la même malgré le fait que c'est l'autre instance de Tomcat qui vous a répondu.
Session : 7DA9FEE977543F1F574DADFA7B1FADD0.tomcat1
ou
Session : 7DA9FEE977543F1F574DADFA7B1FADD0.tomcat2
LAB #11 - Gestion du Web-based Distributed Authoring and Versioning avec mod_dav
Introduction
WebDAV (Web-based Distributed Authoring and Versioning) est une extension du protocole HTTP. Le protocole WebDAV :
- est décrit dans la RFC 2518,
- permet de simplifier la gestion de fichiers avec des serveurs distants
- permet de récupérer, déposer, synchroniser et publier des fichiers et dossiers,
- permet, grâce à un mécanisme de verrouillage et de déverrouillage de protéger contre l'écrasement,
- gère les métadonnées : titre, sujet, créateur, etc,
- gère les attributs de fichiers : copier, renommer, déplacer et supprimer des fichiers,
Installation
Pour activer WebDAV, il faut que les deux modules suivants soient activés dans le fichier httpd.conf :
[root@centos7 ~]# cat /etc/httpd/conf.modules.d/00-dav.conf LoadModule dav_module modules/mod_dav.so LoadModule dav_fs_module modules/mod_dav_fs.so LoadModule dav_lock_module modules/mod_dav_lock.so
Configuration
Afin de mettre en place un hôte virtuel pour contenir un site WebDAV, créez son répertoire racine :
[root@centos7 ~]# mkdir /www/dav
Créez ensuite le fichier /www/dav/dav.test contenant le mot test :
[root@centos7 ~]# echo test > /www/dav/dav.test
Ensuite éditez le fichier /etc/httpd/conf/vhosts.d/Vhosts.conf en y ajoutant la section suivante à la fin :
##################dav.homeland.net <VirtualHost *:80> ServerName dav.homeland.net DocumentRoot /www/dav <Directory /www/dav> Require all granted </Directory> <Location /> Dav On AuthType Basic AuthName "Accès WebDAV" AuthUserFile /www/passwords/dav/.davusers <LimitExcept GET HEAD OPTIONS> Require valid-user </LimitExcept> </Location> </VirtualHost>
Vous obtiendrez :
[root@centos7 ~]# vi /etc/httpd/conf/vhosts.d/Vhosts.conf [root@centos7 ~]# cat /etc/httpd/conf/vhosts.d/Vhosts.conf ################# IP-based Virtual Hosts <VirtualHost 192.168.1.99> DocumentRoot /www/site2 ServerName www.rhelip.com DirectoryIndex index.html Customlog /www/logs/site2/rhelip.log combined Errorlog /www/logs/site2/rhelip_error.log <Directory /www/site2> Require all granted </Directory> </VirtualHost> ################# Named VirtualHosts NameVirtualHost *:80 ##################Default Site Virtual Host <VirtualHost *:80> VirtualDocumentRoot /var/www/html/%-3 ServerName i2tch.loc ServerAlias *.i2tch.loc ServerAdmin webmaster@localhost LogLevel info <Directory /> Options FollowSymLinks AllowOverride All Require all granted </Directory> </VirtualHost> ##################www.rhelnom.com <VirtualHost *:80> ServerName www.rhelnom.com DirectoryIndex index.html DocumentRoot /www/site1 Customlog /www/logs/site1/rhelnom.log combined Errorlog /www/logs/site1/rhelnom_error.log DBDriver mysql DBDParams "dbname=auth user=apache pass=PaSsW0Rd" DBDMin 4 DBDKeep 8 DBDMax 20 DBDExptime 300 <Directory /www/site1> Require all granted </Directory> <Directory /www/site1/secret> AllowOverride AuthConfig </Directory> <Directory /www/site1/secret2> AuthType Basic AuthName "MariaDB Secret" AuthBasicProvider dbd Require valid-user AuthDBDUserPWQuery "SELECT user_passwd FROM users WHERE user_name = %s" </Directory> </VirtualHost> ##################dav.homeland.net <VirtualHost *:80> ServerName dav.homeland.net DocumentRoot /www/dav <Directory /www/dav> Require all granted </Directory> <Location /> Dav On AuthType Basic AuthName "Accès WebDAV" AuthUserFile /www/passwords/dav/.davusers <LimitExcept GET HEAD OPTIONS> Require valid-user </LimitExcept> </Location> </VirtualHost>
Créez maintenant le répertoire pour contenir le fichier des mots de passe :
[root@centos7 ~]# mkdir /www/passwords/dav
Créez le fichier .davusers avec un mot de passe pour webmaster :
[root@centos7 ~]# htpasswd -c /www/passwords/dav/.davusers webmaster New password: fenestros Re-type new password: fenestros Adding password for user webmaster
Ajoutez le site dav.homeland.net au fichier /etc/hosts :
[root@centos7 ~]# vi /etc/hosts [root@centos7 ~]# cat /etc/hosts 127.0.0.1 localhost.localdomain localhost ::1 localhost6.localdomain6 localhost6 10.0.2.16 i2tch.com 10.0.2.16 *.i2tch.loc 10.0.2.16 www.rhelnom.com 192.168.1.99 www.rhelip.com 10.0.2.16 dav.homeland.net
Rechargez les fichiers de configuration d'apache :
[root@centos7 ~]# systemctl reload httpd
Pour tester la configuration, il convient d'utiliser le client WebDAV en ligne de commande, cadaver.
Installez Cadaver :
[root@centos7 ~]yum install cadaver
Connectez-vous au site http://dav.homeland.net avec cadaver et saisissez votre mot de passe. Vous obtiendrez un résultat similaire à celui-ci :
[root@centos7 ~]# cadaver http://dav.homeland.net Authentication required for Accès WebDAV on server `dav.homeland.net': Username: webmaster Password: dav:/> ls Listing collection `/': succeeded. dav.test 5 Sep 2 23:37 dav:/> cat dav.test Displaying `/dav.test': test dav:/> exit Connection to `dav.homeland.net' closed. [root@centos7 ~]#
LAB #12 - Gestion de la réécriture d'URL avec mod_rewrite
Introduction
Le module mod_rewrite permet la réécriture d'URL en temps réel en utilisant des expressions régulières.
Activer mod_rewrite
Pour activer mod_rewrite, il convient de vérifier que la ligne suivante de votre fichier httpd.conf ne soit pas en commentaire :
[root@centos7 ~]# cat /etc/httpd/conf.modules.d/00-base.conf | grep mod_rewrite LoadModule rewrite_module modules/mod_rewrite.so
Mettre un site en maintenance
Dans cet exemple, vous allez rediriger votre site principal vers une page nommée maintenance.html.
Créez donc une page maintenance.html dans le répertoire /www/site2/ et éditez-la ainsi :
[root@centos7 ~]# vi /www/site2/maintenance.html [root@centos7 ~]# cat /www/site2/maintenance.html <html> <head> <title>Site en Maintenance</title> </head> <body> Notre site est actuellement en maintenance. Merci de revenir plus tard. </body> </html>
Editez ensuite le fichier /etc/httpd/conf/vhosts.d/Vhosts.conf ainsi :
[root@centos7 ~]# vi /etc/httpd/conf/vhosts.d/Vhosts.conf [root@centos7 ~]# cat /etc/httpd/conf/vhosts.d/Vhosts.conf ################# IP-based Virtual Hosts <VirtualHost 192.168.1.99> DocumentRoot /www/site2 ServerName www.rhelip.com DirectoryIndex index.html Customlog /www/logs/site2/rhelip.log combined Errorlog /www/logs/site2/rhelip_error.log <Directory /www/site2> Require all granted AllowOverride All </Directory> RewriteEngine on RewriteRule ^/$ /maintenance.html [R] </VirtualHost> ...
La directive RewriteEngine on active mod_rewrite pour le serveur virtuel principal.
La directive RewriteRule ^/$ /maintenance.html [R] permet de rediriger toute requête pour le site vers la page maintenance.html.
Sauvegardez votre fichier puis rechargez la configuration d'apache :
[root@centos7 ~]# systemctl reload httpd
Testez ensuite votre configuration avec lynx :
[root@centos7 ~]# lynx --dump http://www.rhelip.com Notre site est actuellement en maintenance. Merci de revenir plus tard. [root@centos7 ~]#
Interdire l'accès pour une adresse IP spécifique
Dans ce cas, vous avez constaté qu'un pirate vous crée problèmes et vous avez pu relever son adresse IP. Le but ici est donc de renvoyer ce pirate vers une page aurevoir.html créer spécialement pour l'acceuillir.
Commencez par créer la page aurevoir.html dans le répertoire /www/site2/ :
[root@centos7 ~]# vi /www/site2/bye.html [root@centos7 ~]# cat /www/site2/bye.html <html> <head> <title>Aurevoir</title> </head> <body> <center>Bye bye Pirate ! Ha! Ha! Ha!</center> </body> </html>
Editez ensuite le fichier /etc/httpd/conf/vhosts.d/Vhosts.conf afin de renvoyer toute requête d'une adresse IP spécifique vers la page aurevoir.html en y ajoutant les lignes suivantes :
[root@centos7 ~]# vi /etc/httpd/conf/vhosts.d/Vhosts.conf [root@centos7 ~]# cat /etc/httpd/conf/vhosts.d/Vhosts.conf ################# IP-based Virtual Hosts <VirtualHost 192.168.1.99> DocumentRoot /www/site2 ServerName www.rhelip.com DirectoryIndex index.html Customlog /www/logs/site2/rhelip.log combined Errorlog /www/logs/site2/rhelip_error.log <Directory /www/site2> Require all granted AllowOverride All </Directory> RewriteEngine on #RewriteRule ^/$ /maintenance.html [R] RewriteCond %{REMOTE_ADDR} ^192\.168\.1\.99$ RewriteCond %{REQUEST_URI} !^bye\.html RewriteRule .* /bye.html </VirtualHost> ...
Important - Notez bien que la règle precédente a été mise en commentaire.
Sauvegardez votre fichier puis rechargez la configuration d'apache :
[root@centos7 ~]# systemctl reload httpd
Testez ensuite votre configuration avec lynx :
[root@centos7 ~]# lynx --dump http://www.rhelip.com Bye bye Pirate ! Ha! Ha! Ha! [root@centos7 ~]#
Indiquer un déplacement permenant
Dans ce cas, votre but est de rediriger les internautes de l'oldpage.html vers la newpage.html, tout en indiquant aux moteurs de recherche que le déplacement de l'oldpage.html est définitif.
Commencez par créer vos deux fichiers oldpage.html et newpage.html dans /www/site2/.
Le fichier oldpage.html est vide car son contenu a été déplacé à la newpage.html :
[root@centos7 ~]# touch /www/site2/oldpage.html [root@centos7 ~]# vi /www/site2/newpage.html [root@centos7 ~]# cat /www/site2/newpage.html <html> <head> <title>Page déplacée</title> <body> <center>Exemple de DEPLACEMENT PERMENANT</center> </body> </html>
Editez ensuite le fichier /etc/httpd/conf/vhosts.d/Vhosts.conf en y ajoutant la ligne suivante :
[root@centos7 ~]# vi /etc/httpd/conf/vhosts.d/Vhosts.conf [root@centos7 ~]# cat /etc/httpd/conf/vhosts.d/Vhosts.conf ################# IP-based Virtual Hosts <VirtualHost 192.168.1.99> DocumentRoot /www/site2 ServerName www.rhelip.com DirectoryIndex index.html Customlog /www/logs/site2/rhelip.log combined Errorlog /www/logs/site2/rhelip_error.log <Directory /www/site2> Require all granted AllowOverride All </Directory> RewriteEngine on #RewriteRule ^/$ /maintenance.html [R] #RewriteCond %{REMOTE_ADDR} ^192\.168\.1\.99$ #RewriteCond %{REQUEST_URI} !^bye\.html #RewriteRule .* /bye.html RewriteRule ^/oldpage\.html /newpage.html [R=301,L] </VirtualHost> ...
Important - Notez bien que les règles précédentes ont été mises en commentaires.
Sauvegardez votre fichier puis rechargez la configuration d'apache :
[root@centos7 ~]# systemctl reload httpd
Testez ensuite votre configuration avec lynx :
[root@centos7 ~]# lynx --dump http://www.rhelip.com/oldpage.html Exemple de DEPLACEMENT PERMENANT [root@centos7 ~]#
Indiquer qu'une ressource est indisponible
Au bout d'une certaine période, on peux considérer que les moteurs de recherche soient mis à jours avec notre changement vers la newpage.html.
Dans ce cas, nous allons donc tout simplement indiquer que l'oldpage.html n'existe plus.
Editez ensuite le fichier /etc/httpd/conf/vhosts.d/Vhosts.conf en y ajoutant la ligne suivante :
[root@centos7 ~]# vi /etc/httpd/conf/vhosts.d/Vhosts.conf [root@centos7 ~]# cat /etc/httpd/conf/vhosts.d/Vhosts.conf ################# IP-based Virtual Hosts <VirtualHost 192.168.1.99> DocumentRoot /www/site2 ServerName www.rhelip.com DirectoryIndex index.html Customlog /www/logs/site2/rhelip.log combined Errorlog /www/logs/site2/rhelip_error.log <Directory /www/site2> Require all granted AllowOverride All </Directory> RewriteEngine on #RewriteRule ^/$ /maintenance.html [R] #RewriteCond %{REMOTE_ADDR} ^192\.168\.1\.99$ #RewriteCond %{REQUEST_URI} !^bye\.html #RewriteRule .* /bye.html #RewriteRule ^/oldpage\.html /newpage.html [R=301,L] RewriteRule ^/oldpage\.html - [G] </VirtualHost> ...
Important - Notez bien que les règles précédentes ont été mises en commentaires.
Sauvegardez votre fichier puis rechargez la configuration d'apache :
[root@centos7 ~]# systemctl reload httpd
Testez ensuite votre configuration avec lynx :
[root@centos7 ~]# lynx --dump http://www.rhelip.com/oldpage.html Gone The requested resource /oldpage.html is no longer available on this server and there is no forwarding address. Please remove all references to this resource.
Directives de mod_rewrite
RewriteEngine
RewriteEngine on|off
Cette directive active ou désactive le moteur de réécriture.
RewriteOptions
RewriteOptions options
Cette directive définit deux options :
- Inherit
- La configuration courante hérite de la configuration parente. Ceci peut être appliquer à un hôte virtuel ou un répertoire.
- MaxRedirects=nombre
- nombre dont la valeur par défaut est de 10, permet de sortir d'une règle mal écrite au bout de nombre boucles. Dans ce cas le serveur sert une page HTTP 500 - Internal Server Error.
RewriteLog
RewriteLog fichier
Cette directive consigne les activités de réécriture dans le fichier passé en argument.
RewriteLogLevel
RewriteLogLevel niveau
Cette directive définit le niveau de verbosité de 0 à 9 où 0 ne consigne rien et 9 consigne tout. En production la valeur ne devrait pas dépasser 2, sauf en cas de débogage.
RewriteLock
RewriteLock fichier
Cette directive désigne le fichier-verrou utilisé par mod_rewrite pour éviter des accès concurrentiels à des programmes et scripts définis par la directive RewriteMap.
RewriteMap
RewriteMap table txt|dbm|prg:fichier
Cette directive définit une table externe utilisée pour des réécritures. La règle de réécriture est écrite comme suit :
$ { table : clef : ValeurParDéfaut }
Lors de l'utilisation de cette règle, la table est consultée et la clef recherchée. Dans le cas où la clef est trouvée, la fonction retourne la ValeurDeSubstitution trouvée dans la table. Dans le cas contraire, la fonction retourne la ValeurParDéfaut stipulée dans la règle de réécriture
La table peut être au format texte brut, au format DBM ou être un binaire ou un script :
- txt:fichier
- La table contient une paire par ligne au format clef ValeurDeSubstitution
- dbm:fichier
- La table contient une paire par ligne au format clef ValeurDeSubstitution. La différence entre DBM et txt réside dans le fait que les fichiers binaires DBM sont optimisés pour la vitesse.
- prg:fichier
- prg est un binaire ou un script. prg reçoit sur stdin la clef et retourne sur stdout la ValeurDeSubstitution. Si aucune correspondance n'est trouvée, prg retourne la chaîne NULL sur stdout.
Par exemple, nous souhaitons rediriger les URLs de format suivant www.exampledomain.com/en/product1234/product_detail.php vers les URLs de format suivant www.exampledomain.com/en/travelbox_12/product_detail.php.
On commence par créer une table de correspondance :
vi /etc/apache2/conf.d/productrewrites.txt cat /etc/apache2/conf.d/productrewrites.txt product1234 travelbox_12 product1235 travelbox_13 product2310 case_07 product3126 case_12 product9320 anotheritem_54 ...
On crée une base de données avec l'utilitaire httxt2dbm :
httxt2dbm -f db -i /etc/apache2/conf.d/productrewrites.txt -o /etc/apache2/conf.d/productrewrites.db
puis on utilise les règles suivantes :
RewriteEngine On RewriteMap rewrites dbm=db:/etc/apache2/conf.d/productrewrites.db RewriteCond {rewrites:$1} !="" RewriteRule ^/(.*)/(.*)/(.*)$ http://www.exampledomain.com/(.*)/${rewrites:$1}/$2? [R=permanent,L]
RewriteBase
RewriteBase urlrélatif
Cette directive indique l'URL de base pour les règles de réécriture incluses dans un fichier .htaccess. Dans ce cas, l'action des règles est localisée dans le sens où la partie du chemin d'accès de l'url contenant le fichier .htaccess est enlevée. Après traitement des règles, l'URL au complet doit être réinjecter dans le serveur en utilisant la valeur de la directive RewriteBase.
RewriteCond
RewriteCond chaineatester motif [drapeau1,drapeau2,...]
La directive RewriteCond définit une condition d'application pour la ou les règle(s) de réécriture qui suit(vent). Plusieurs conditions d'application peuvent se suivre. Cependant notez que la ou les règle(s) de réécriture qui suivent ne seront interprétées que dans le cas où toutes les conditions d'applications soient remplies.
L'argument chaineatester est une chaîne de caractères sur laquelle sera appliquer le motif. Cet argument peut contenir des variables :
- La variable $N allant de 1 à 9 faisant référence à la règle de réécriture.
- Cette variable permet de récupérer la valeur d'un sous-motif, après l'application du motif sur la RewriteRule qui suit le bloc RewriteCondactuel à condition que les sous-motifs soient entourés de parenthèses.
- La variable %N allant de 1 à 9 faisant référence à la dernière condition remplie.
- Cette variable permet de récupérer la valeur d'un sous-motif du motif de la dernière RewriteCond remplie du bloc actuel à condition que les sous-motifs soient entourés de parenthèses.
- Une variable serveur :
- En-têtes HTTP
- HTTP_USER_AGENT
- HTTP_REFERER
- HTTP_COOKIE
- HTTP_FORWARDED
- HTTP_HOST
- HTTP_PROXY_CONNECTION
- HTTP_ACCEPT
- Connexions et requêtes
- REMOTE_ADDR
- REMOTE_HOST
- REMOTE_USER
- REMOTE_IDENT
- REQUEST_METHOD
- SCRIPT_FILENAME
- PATH_INFO
- QUERY_STRING
- AUTH_TYPE
- Variables internes
- DOCUMENT_ROOT
- SERVER_ADMIN
- SERVER_NAME
- SERVER_PORT
- SERVER_PROTOCAL
- SERVER_SOFTWARE
- SERVER_VERSION
- Variables système
- TIME_YEAR
- TIME_MON
- TIME_DAY
- TIME_HOUR
- TIME_MIN
- TIME_SEC
- TIME_WDAY
- TIME
- Variables spéciales
- API_VERSION
- THE_REQUEST
- REQUEST_URI
- REQUEST_FILE
- NAME
- IS_SUBREQ
A Faire - Passez en revue les variables serveur en utilisant le Manuel en ligne d'Apache.
Le motif est soit une expression régulière :
Caractère spécial | Description |
---|---|
^ | Trouver la chaîne au début de la ligne |
$ | Trouver la chaîne à la fin de la ligne |
. | Trouver n'importe quel caractère |
* | Trouver 0 ou plus du caractère qui précède |
+ | Trouver 1 ou plus du caractère qui précède |
\ | Annuler l'effet spécial du caractère suivant |
[ ] | Trouver n'importe quel des caractères entre les crochets |
[^] | Exclure les caractères entre crochets |
{a} | Trouver a occurrences de ce qui précède |
| | Trouver soit ce qui se trouve avant, soit ce qui se trouve après |
( ) | Limiter la portée d'une alternative |
soit une expression :
Expression | Description |
---|---|
<chaine | Vrai si chaineatester est lexicographiquement inférieur à chaine |
>chaine | Vrai si chaineatester est lexicographiquement supérieur à chaine |
=chaine | Vrai si chaineatester est lexicographiquement égal à chaine |
-d | Vrai si chaineatester est un répertoire qui existe |
-f | Vrai si chaineatester est un fichier normal qui existe |
-s | Vrai si chaineatester est un fichier normal non-vide qui existe |
-l | Vrai si chaineatester est un lien symbolique qui existe |
-F | Vrai si chaineatester est un fichier existant et accessible selon la configuration du serveur |
-F | Vrai si chaineatester est un URL existant et accessible selon la configuration du serveur |
Les drapeaux sont une liste de commutateurs séparés par des virgules et entourés de crochets. Voici une liste de commutateurs les plus utilisés :
Drapeaux | Description |
---|---|
[NC] | Insensible à la casse |
[OR] | Permet de lier deux conditions RewriteCond par un OU |
RewriteRule
RewriteRule motif substitution [drapeau1,drapeau2,...]
Cette directive définit la règle de réécriture.
Le motif est une expression régulière qui sera appliquée à l'URL courante. L'URL courante n'est pas nécessairement l'URL d'origine.
La substitution est une chaîne qui remplacera l'URL qui correspond au motif.
Cette chaîne peut contenir des variables :
- La variable $N allant de 1 à 9 faisant référence à la règle de réécriture.
- Cette variable permet de récupérer la valeur d'un sous-motif du motif de la règle courante à condition que les sous-motifs soient entourés de parenthèses.
- La variable %N allant de 1 à 9 faisant référence à la drective RewriteCond précédente.
- Cette variable permet de récupérer la valeur d'un sous-motif du motif de la dernière RewriteCond à condition que les sous-motifs soient entourés de parenthèses.
- Une variable serveur :
- En-têtes HTTP
- HTTP_USER_AGENT
- HTTP_REFERER
- HTTP_COOKIE
- HTTP_FORWARDED
- HTTP_HOST
- HTTP_PROXY_CONNECTION
- HTTP_ACCEPT
- Connexions et requêtes
- REMOTE_ADDR
- REMOTE_HOST
- REMOTE_USER
- REMOTE_IDENT
- REQUEST_METHOD
- SCRIPT_FILENAME
- PATH_INFO
- QUERY_STRING
- AUTH_TYPE
- Variables internes
- DOCUMENT_ROOT
- SERVER_ADMIN
- SERVER_NAME
- SERVER_PORT
- SERVER_PROTOCAL
- SERVER_SOFTWARE
- SERVER_VERSION
- Variables système
- TIME_YEAR
- TIME_MON
- TIME_DAY
- TIME_HOUR
- TIME_MIN
- TIME_SEC
- TIME_WDAY
- TIME
- Variables spéciales
- API_VERSION
- THE_REQUEST
- REQUEST_URI
- REQUEST_FILE
- NAME
- IS_SUBREQ
- Des appels à des fonctions RewriteMap.
Les drapeaux sont une liste de commutateurs séparés par des virgules et entourés de crochets. Voici une liste de commutateurs les plus utilisés :
Drapeaux | Description |
---|---|
[R[=code]] | Force la redirection |
[F] | L'URL sera interdit ( Erreur 403 ) |
[G] | L'URL sera marqué comme déménagé ( Erreur 410 ) |
[P] | Force la redirection à passer par le proxy d'apache |
[L] | Arrête le traitement de réécriture |
[C] | Force un chaînage avec la règle suivante |
[N] | Force un traitement en boucle de la règle de réécriture |
[NC] | Insensible à la casse |
Dernièrement il existe une expression de substitution spéciale définie par -. Dans ce cas, il n'y a pas de substitution.
Consultez la Liste des codes HTTP sur Wikipédia et notez la signification des codes 301 et 410.
LAB #13 - Personnalisation des en-têtes de requêtes et de réponses HTTP avec mod_header
HSTS ou HTTP Strict Transport Security est une caractéristique de sécurité qui permet à un site web d'informer les navigateurs qui le site web n'accepte que des connexions sécuriséés en faisant appel à mod_headers afin que l'en-tête soit modifié
[root@centos7 ~]# cat /etc/httpd/conf.modules.d/00-base.conf | grep mod_headers LoadModule headers_module modules/mod_headers.so
Pour mettre en place cette notification, il convient d'éditer le fichier /etc/httpd/conf.d/ssl.conf :
[root@centos7 ~]# vi /etc/httpd/conf.d/ssl.conf [root@centos7 ~]# cat /etc/httpd/conf.d/ssl.conf # # When we also provide SSL we have to listen to the # the HTTPS port in addition. # Listen 443 https Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains" ## ...
Dans ce cas, l'expiration de la notification est dans deux ans (63 072 000 secondes). Un navigateur visitant le site aujourd'hui verra donc l'expiration de deux ans. Si le navigateur reviens demain, celui-ci verra encore deux ans mais à partir de la date de demain.
Pour forcer les navigateurs à connecter en https, il convient d'inclure une règle de ré-ecriture dans la section du site principal de la balise VirtualHost qui se trouve dans notre cas dans le fichier /etc/httpd/conf/vhosts.d/Vhosts.conf :
... ################# Named VirtualHosts NameVirtualHost *:80 ##################Default Site Virtual Host <VirtualHost *:80> VirtualDocumentRoot /var/www/html/%-3 ServerName i2tch.loc ServerAlias *.i2tch.loc ServerAdmin webmaster@localhost LogLevel info <Directory /> Options FollowSymLinks AllowOverride All Require all granted </Directory> RewriteEngine on RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} </VirtualHost> ##################www.rhelnom.com ...
Rechargez la configuration d'apache :
[root@centos7 ~]# systemctl reload httpd
Testez ensuite avec un navigateur le lien http://i2tch.loc :
[root@centos7 ~]# lynx --dump http://i2tch.loc Looking up i2tch.loc Making HTTP connection to i2tch.loc Sending HTTP request. HTTP request sent; waiting for response. HTTP/1.1 302 Found Data transfer complete HTTP/1.1 302 Found Using https://i2tch.loc/ Looking up i2tch.loc Making HTTPS connection to i2tch.loc SSL callback:self signed certificate, preverify_ok=0, ssl_okay=0 Retrying connection without TLS. Looking up i2tch.loc Making HTTPS connection to i2tch.loc Alert!: Unable to make secure connection to remote host. lynx: Can't access startfile http://i2tch.loc/
Revenez à la configuration d'origine en mettant en commentaires les lignes ajoutées :
[root@centos7 cgi-bin]# vi /etc/httpd/conf.d/ssl.conf [root@centos7 cgi-bin]# cat /etc/httpd/conf.d/ssl.conf # # When we also provide SSL we have to listen to the # the HTTPS port in addition. # Listen 443 https # Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains" ...
[root@centos7 ~]# vi /etc/httpd/conf/vhosts.d/Vhosts.conf [root@centos7 ~]# cat /etc/httpd/conf/vhosts.d/Vhosts.conf | more ################# IP-based Virtual Hosts <VirtualHost 192.168.1.99> DocumentRoot /www/site2 ServerName www.rhelip.com DirectoryIndex index.html Customlog /www/logs/site2/rhelip.log combined Errorlog /www/logs/site2/rhelip_error.log <Directory /www/site2> Require all granted AllowOverride All </Directory> RewriteEngine on #RewriteRule ^/$ /maintenance.html [R] #RewriteCond %{REMOTE_ADDR} ^192\.168\.1\.99$ #RewriteCond %{REQUEST_URI} !^bye\.html #RewriteRule .* /bye.html #RewriteRule ^/oldpage\.html /newpage.html [R=301,L] RewriteRule ^/oldpage\.html - [G] </VirtualHost> ################# Named VirtualHosts NameVirtualHost *:80 ##################Default Site Virtual Host <VirtualHost *:80> VirtualDocumentRoot /var/www/html/%-3 ServerName i2tch.loc ServerAlias *.i2tch.loc ServerAdmin webmaster@localhost LogLevel info <Directory /> Options FollowSymLinks AllowOverride All Require all granted </Directory> #RewriteEngine on #RewriteCond %{HTTPS} off #RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} </VirtualHost> ##################www.rhelnom.com <VirtualHost *:80> --More--
Dernièrement, re-démarrez apache :
[root@centos7 ~]# systemctl restart httpd
LAB #14 - L'exécution des scripts CGI sous l'utilisateur et le groupe spécifiés avec mod_suexec
Le mod_suexec introduit un contrôle plus sévère en ce qui concerne quels comptes peuvent exécuter de CGI.
Naviguez au répertoire /var/www/cgi-bin/ :
[root@centos7 ~]# cd /var/www/cgi-bin/
Créez un script bash appelé whoami.cgi :
[root@centos7 cgi-bin]# vi /var/www/cgi-bin/whoami.cgi [root@centos7 cgi-bin]# cat /var/www/cgi-bin/whoami.cgi #!/bin/bash echo "Content-type: text/plain" echo "" echo "Nom de connexion :" `whoami`
Le but de ce script est de montrer qui exécute le CGI en question.
Rendez le script exécutable :
[root@centos7 cgi-bin]# chmod u+x whoami.cgi
Appelez le script CGI :
[root@centos7 cgi-bin]# lynx --dump http://localhost/cgi-bin/whoami.cgi Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at root@localhost to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log.
Important - Notez que l'appel génère une erreur “Internal Server Error”.
Regardez dans le fichier de journalisation /var/log/httpd/error_log. Vous verrez deux lignes similaires à celles-ci :
[root@centos7 cgi-bin]# tail /var/log/httpd/error_log [Mon Sep 03 00:51:39.292823 2018] [mpm_prefork:notice] [pid 1136] AH00170: caught SIGWINCH, shutting down gracefully [Mon Sep 03 00:51:40.387480 2018] [core:notice] [pid 3484] SELinux policy enabled; httpd running as context system_u:system_r:httpd_t:s0 [Mon Sep 03 00:51:40.388881 2018] [suexec:notice] [pid 3484] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec) [Mon Sep 03 00:51:40.412024 2018] [alias:warn] [pid 3484] AH00671: The ScriptAlias directive in /etc/httpd/conf.d/php.conf at line 1 will probably never match because it overlaps an earlier ScriptAlias. [Mon Sep 03 00:51:40.413924 2018] [auth_digest:notice] [pid 3484] AH01757: generating secret for digest authentication ... [Mon Sep 03 00:51:40.414925 2018] [lbmethod_heartbeat:notice] [pid 3484] AH02282: No slotmem from mod_heartmonitor [Mon Sep 03 00:51:40.420110 2018] [mpm_prefork:notice] [pid 3484] AH00163: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips configured -- resuming normal operations [Mon Sep 03 00:51:40.420256 2018] [core:notice] [pid 3484] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND' [Mon Sep 03 01:00:45.867408 2018] [cgi:error] [pid 3489] [client 127.0.0.1:57982] AH01215: (13)Permission denied: exec of '/var/www/cgi-bin/whoami.cgi' failed [Mon Sep 03 01:00:45.867459 2018] [cgi:error] [pid 3489] [client 127.0.0.1:57982] End of script output before headers: whoami.cgi
En effet, le fichier whoami.cgi apprtient à root :
[root@centos7 cgi-bin]# ls -l total 12 -rwxr-xr-x. 1 root root 32 Sep 2 16:14 php56.fcgi -rwxr-xr-x. 1 root root 32 Sep 2 16:14 php72.fcgi -rwxr--r--. 1 root root 87 Sep 3 01:00 whoami.cgi
Modifiez donc le propriétaire et le groupe à apache :
[root@centos7 cgi-bin]# chown apache:apache whoami.cgi
Appelez le script CGI :
[root@centos7 cgi-bin]# lynx --dump http://localhost/cgi-bin/whoami.cgi Nom de connexion : apache [root@centos7 cgi-bin]#
Vous allez maintenant créer un utilisateur spécifique pour l'exécution des scripts :
[root@centos7 cgi-bin]# useradd scripts
Créez le répertoire /var/www/scripts :
[root@centos7 cgi-bin]# mkdir /var/www/scripts
Modifiez le propriétaire, le groupe et les permissions du répertoire nouvellement créé :
[root@centos7 cgi-bin]# chown scripts:scripts /var/www/scripts/ [root@centos7 cgi-bin]# chmod 2755 /var/www/scripts/
Déplacez le script vers /var/www/scripts :
[root@centos7 cgi-bin]# mv whoami.cgi /var/www/scripts [root@centos7 cgi-bin]# cd !$ cd /var/www/scripts [root@centos7 scripts]# ls -l total 4 -rwxr--r--. 1 apache apache 87 Sep 3 01:00 whoami.cgi
Editez le fichier /etc/httpd/conf/httpd.conf en ajoutant la directive SuexecUserGroup :
... ServerRoot "/etc/httpd" SuexecUserGroup scripts scripts ...
Vérifiez que la ligne suivante existe dans le fichier /etc/httpd/conf.modules.d/00-base.conf :
[root@centos7 scripts]# cat /etc/httpd/conf.modules.d/00-base.conf | grep mod_suexec LoadModule suexec_module modules/mod_suexec.so
Ajoutez l'alias scripts et définissez les options pour le répertoire /var/www/scripts dans le fichier /etc/httpd/conf/httpd.conf :
... # # "/var/www/cgi-bin" should be changed to whatever your ScriptAliased # CGI directory exists, if you have that configured. # <Directory "/var/www/cgi-bin"> AllowOverride None Options None Require all granted </Directory> Alias /scripts/ "/var/www/scripts/" <Directory "/var/www/scripts/"> Options +ExecCGI SetHandler cgi-script </Directory> <IfModule mime_module> ...
Sauvegardez et vérifiez votre fichier de configuration :
[root@centos7 scripts]# httpd -t [Mon Sep 03 01:09:02.891762 2018] [alias:warn] [pid 11365] AH00671: The ScriptAlias directive in /etc/httpd/conf.d/php.conf at line 1 will probably never match because it overlaps an earlier ScriptAlias. AH00548: NameVirtualHost has no effect and will be removed in the next release /etc/httpd/conf/vhosts.d/Vhosts.conf:21 Syntax OK
Re-démarrez le serveur apache :
[root@centos7 scripts]# systemctl restart httpd
Modifiez donc le propriétaire et groupe du script :
[root@centos6 scripts]# chown scripts:scripts whoami.cgi
Appelez le script dans le répertoire scripts :
[root@centos7 scripts]# lynx --dump http://localhost/scripts/whoami.cgi Nom de connexion : scripts [root@centos7 scripts]#
LAB #15 - Améliorer l'utilisation de la Mémoire du Serveur avec mod_worker
Le module MPM worker utilise moins de mémoire que le module prefork pour le même nombre de connexions.
Ajoutez la section suivante au fichier /etc/httpd/conf.d/local.conf pour pouvoir gérer 800 connexions simultanées :
[root@centos7 ~]# vi /etc/httpd/conf.d/local.conf [root@centos7 ~]# more /etc/httpd/conf.d/local.conf ServerTokens OS Timeout 60 KeepAlive Off MaxKeepAliveRequests 100 KeepAliveTimeout 15 <IfModule prefork.c> StartServers 8 MinSpareServers 5 MaxSpareServers 20 ServerLimit 256 MaxClients 256 MaxRequestsPerChild 4000 </IfModule> <IfModule worker.c> ServerLimit 25 StartServers 10 MinSpareThreads 75 MaxSpareThreads 250 ThreadLimit 64 ThreadsPerChild 32 MaxClients 800 MaxRequestsPerChild 10000 </IfModule> --More--(22%)
A faire - Voir la page https://httpd.apache.org/docs/2.4/fr/mod/worker.html pour une description des directives.
Ouvrez maintenant le fichier /etc/httpd/conf.modules.d/00-mpm.conf, commentez la directive LoadModule mpm_prefork_module modules/mod_mpm_prefork.so et décommentez la directive LoadModule mpm_worker_module modules/mod_mpm_worker.so :
[root@centos7 ~]# vi /etc/httpd/conf.modules.d/00-mpm.conf [root@centos7 ~]# cat /etc/httpd/conf.modules.d/00-mpm.conf # Select the MPM module which should be used by uncommenting exactly # one of the following LoadModule lines: # prefork MPM: Implements a non-threaded, pre-forking web server # See: http://httpd.apache.org/docs/2.4/mod/prefork.html #LoadModule mpm_prefork_module modules/mod_mpm_prefork.so # worker MPM: Multi-Processing Module implementing a hybrid # multi-threaded multi-process web server # See: http://httpd.apache.org/docs/2.4/mod/worker.html # LoadModule mpm_worker_module modules/mod_mpm_worker.so # event MPM: A variant of the worker MPM with the goal of consuming # threads only for connections with active processing # See: http://httpd.apache.org/docs/2.4/mod/event.html # #LoadModule mpm_event_module modules/mod_mpm_event.so
Important - Le MPM Worker n'est pas comptible avec PHP.
Redémarrez ensuite apache :
[root@centos7 ~]# systemctl restart httpd
Consultez les adresses http://127.0.0.1/server-status et http://127.0.0.1/server-info pour vérifier que votre apache utilise le MPM worker :
[root@centos7 ~]# lynx http://127.0.0.1/server-status Apache Status (p1 of 2) Apache Server Status for 127.0.0.1 (via 127.0.0.1) Server Version: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips Server MPM: worker Server Built: Jun 27 2018 13:48:59 ___________________________________________________________________________________________________________________________________________________________ Current Time: Monday, 03-Sep-2018 01:16:18 CEST Restart Time: Monday, 03-Sep-2018 01:15:56 CEST Parent Server Config. Generation: 1 Parent Server MPM Generation: 0 Server uptime: 22 seconds Server load: 0.00 0.02 0.07 Total accesses: 0 - Total Traffic: 0 kB CPU Usage: u0 s0 cu0 cs0 0 requests/sec - 0 B/second - 1 requests currently being processed, 223 idle workers ................................________________________________ ________________________________________________________________ ____________________________________________________W___________ ................................................................ ________________________________________________________________ ................................................................ ................................................................ ................................................................ ................................................................ ................................................................ ................................................................ ................................................................ ................................ Scoreboard Key: "_" Waiting for Connection, "S" Starting up, "R" Reading Request, "W" Sending Reply, "K" Keepalive (read), "D" DNS Lookup, "C" Closing connection, "L" Logging, "G" Gracefully finishing, ...
[root@centos7 ~]# lynx http://127.0.0.1/server-info Server Information (p1 of 59) Apache Server Information Subpages: Configuration Files, Server Settings, Module List, Active Hooks, Available Providers ___________________________________________________________________________________________________________________________________________________________ Sections: Loaded Modules, Server Settings, Startup Hooks, Request Hooks, Other Hooks, Providers ___________________________________________________________________________________________________________________________________________________________ Loaded Modules core.c, http_core.c, mod_access_compat.c, mod_actions.c, mod_alias.c, mod_allowmethods.c, mod_auth_basic.c, mod_auth_digest.c, mod_authn_anon.c, mod_authn_core.c, mod_authn_dbd.c, mod_authn_dbm.c, mod_authn_file.c, mod_authn_socache.c, mod_authnz_ldap.c, mod_authz_core.c, mod_authz_dbd.c, mod_authz_dbm.c, mod_authz_groupfile.c, mod_authz_host.c, mod_authz_owner.c, mod_authz_user.c, mod_autoindex.c, mod_cache.c, mod_cache_disk.c, mod_cgid.c, mod_data.c, mod_dav.c, mod_dav_fs.c, mod_dav_lock.c, mod_dbd.c, mod_deflate.c, mod_dir.c, mod_dumpio.c, mod_echo.c, mod_env.c, mod_expires.c, mod_ext_filter.c, mod_filter.c, mod_headers.c, mod_include.c, mod_info.c, mod_lbmethod_bybusyness.c, mod_lbmethod_byrequests.c, mod_lbmethod_bytraffic.c, mod_lbmethod_heartbeat.c, mod_log_config.c, mod_logio.c, mod_lua.c, mod_mime.c, mod_mime_magic.c, mod_negotiation.c, mod_proxy.c, mod_proxy_ajp.c, mod_proxy_balancer.c, mod_proxy_connect.c, mod_proxy_express.c, mod_proxy_fcgi.c, mod_proxy_fdpass.c, mod_proxy_ftp.c, mod_proxy_http.c, mod_proxy_scgi.c, mod_proxy_wstunnel.c, mod_remoteip.c, mod_reqtimeout.c, mod_rewrite.c, mod_setenvif.c, mod_slotmem_plain.c, mod_slotmem_shm.c, mod_so.c, mod_socache_dbm.c, mod_socache_memcache.c, mod_socache_shmcb.c, mod_ssl.c, mod_status.c, mod_substitute.c, mod_suexec.c, mod_systemd.c, mod_unique_id.c, mod_unixd.c, mod_userdir.c, mod_version.c, mod_vhost_alias.c, util_ldap.c, worker.c, ___________________________________________________________________________________________________________________________________________________________ Server Settings Server Version: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips Server Built: Jun 27 2018 13:48:59 Server loaded APR Version: 1.4.8 Compiled with APR Version: 1.4.8 Server loaded APU Version: 1.5.2 Compiled with APU Version: 1.5.2 Module Magic Number: 20120211:24 Hostname/port: 127.0.0.1:80 Timeouts: connection: 60 keep-alive: 15 MPM Name: worker ...
<html> <DIV ALIGN=“CENTER”> Copyright © 2004-2018 Hugh Norris. </DIV> </html>