Ceci est une ancienne révision du document !


Version : 2020.01

Dernière mise-à-jour : 2020/12/06 07:53

LCF408 - Sécurité Applicative

Dans cette unité, vous allez apprendre :

  • Comment installer et utiliser l'utilitaire netwox,
  • Comment installer et utiliser l'outil OpenVAS,,
  • Comment mettre en place un chroot pour un utilisateur,
  • Comment sécuriser le serveur Apache.

Le Problématique

La plupart des failles de sécurité ne sont pas du fait du système d'exploitation mais des applications installées.

Préparation

A Faire - Arrêtez votre VM et configurez la RAM à 2 Go. Redémarrez votre VM.

Les Outils

LAB #1 - Netwox

Le programme netwox est un utilitaire puissant de vérification de la sécurité.

Installation

Commencez par télécharger le paquet netwox-5.35.0-1.el6.rf.x86_64.rpm :

[root@centos7 ~]# wget http://ftp.tu-chemnitz.de/pub/linux/dag/redhat/el6/en/x86_64/rpmforge/RPMS/netwox-5.35.0-1.el6.rf.x86_64.rpm

Netwox s'installe en utilisant yum :

[root@centos7 ~]# yum localinstall netwox-5.35.0-1.el6.rf.x86_64.rpm --nogpgcheck

Utilisation

[root@centos7 ~]# netwox
Netwox toolbox version 5.35.0. Netwib library version 5.35.0.

######################## MAIN MENU #########################
 0 - leave netwox
 3 - search tools
 4 - display help of one tool
 5 - run a tool selecting parameters on command line
 6 - run a tool selecting parameters from keyboard
 a + information
 b + network protocol
 c + application protocol
 d + sniff (capture network packets)
 e + spoof (create and send packets)
 f + record (file containing captured packets)
 g + client
 h + server
 i + ping (check if a computer if reachable)
 j + traceroute (obtain list of gateways)
 k + scan (computer and port discovery)
 l + network audit
 m + brute force (check if passwords are weak)
 n + remote administration
 o + tools not related to network
Select a node (key in 03456abcdefghijklmno):  

L'utilisation de netwox en mode interactif se fait a l'aide des menus proposés. Dans notre cas, nous souhaitons utiliser un des outils de la section network audit. Il convient donc de choisir le menu l :

###################### network audit #######################
 0 - leave netwox
 1 - go to main menu
 2 - go to previous menu
 3 - search tools
 4 - display help of one tool
 5 - run a tool selecting parameters on command line
 6 - run a tool selecting parameters from keyboard
 a + network audit using Ethernet
 b + network audit using IP
 c + network audit using TCP
 d + network audit using ICMP
 e + network audit using ARP
Select a node (key in 0123456abcde):  

Choisissez ensuite le menu c :

################# network audit using TCP ##################
 0 - leave netwox
 1 - go to main menu
 2 - go to previous menu
 3 - search tools
 4 - display help of one tool
 5 - run a tool selecting parameters on command line
 6 - run a tool selecting parameters from keyboard
 a - 76:Synflood
 b - 77:Check if seqnum are predictible
 c - 78:Reset every TCP packet
 d - 79:Acknowledge every TCP SYN
Select a node (key in 0123456abcd): 

Notre choix de test s'arrête sur un test du type Synflood sur un de nos serveurs internes. Nous choisissons donc le menu a :

################# help for tool number 76 ##################
Title: Synflood
+------------------------------------------------------------------------+
| This tool sends a lot of TCP SYN packets.                              |
| It permits to check how a firewall behaves when receiving packets      |
| which have to be ignored.                                              |
| Parameter --spoofip indicates how to generate link layer for spoofing. |
| Values 'best', 'link' or 'raw' are common choices for --spoofip. Here  |
| is the list of accepted values:                                        |
|  - 'raw' means to spoof at IP4/IP6 level (it uses system IP stack). If |
|    a firewall is installed, or on some systems, this might not work.   |
|  - 'linkf' means to spoof at link level (currently, only Ethernet is   |
|    supported). The 'f' means to Fill source Ethernet address.          |
|    However, if source IP address is spoofed, it might be impossible    |
|    to Fill it. So, linkf will not work: use linkb or linkfb instead.   |
|  - 'linkb' means to spoof at link level. The 'b' means to left a Blank |
|    source Ethernet address (0:0:0:0:0:0, do not try to Fill it).       |
|  - 'linkfb' means to spoof at link level. The 'f' means to try to Fill |
|    source Ethernet address, but if it is not possible, it is left      |
|    Blank.                                                              |
|  - 'rawlinkf' means to try 'raw', then try 'linkf'                     |
|  - 'rawlinkb' means to try 'raw', then try 'linkb'                     |
|  - 'rawlinkfb' means to try 'raw', then try 'linkfb'                   |
|  - 'linkfraw' means to try 'linkf', then try 'raw'                     |
|  - 'linkbraw' means to try 'linkb', then try 'raw'                     |
|  - 'linkfbraw' means to try 'linkfb', then try 'raw'                   |
|  - 'link' is an alias for 'linkfb'                                     |
|  - 'rawlink' is an alias for 'rawlinkfb'                               |
|  - 'linkraw' is an alias for 'linkfbraw'                               |
|  - 'best' is an alias for 'linkraw'. It should work in all cases.      |
|                                                                        |
| This tool may need to be run with admin privilege in order to spoof.   |
+------------------------------------------------------------------------+
Usage: netwox 76 -i ip -p port [-s spoofip]
Parameters:
 -i|--dst-ip ip                 destination IP address {5.6.7.8}
 -p|--dst-port port             destination port number {80}
 -s|--spoofip spoofip           IP spoof initialization type {linkbraw}
Example: netwox 76 -i "5.6.7.8" -p "80"
Example: netwox 76 --dst-ip "5.6.7.8" --dst-port "80"
Press 'r' or 'k' to run this tool, or any other key to continue 

Il convient ensuite d'appuyer sur la touche [r] ou [k] pour lancer l'utilitaire.

Il est a noter que netwox peut être utilisé sans faire appel au menus interactifs, à condition de connaître le numéro netwox du test à lancer:

# netwox 76 -i "10.0.2.3" -p "80"

Avertissement important

netwox est un outil puissant. Il convient de noter que:

  • il ne doit pas être installé sur un serveur de production mais sur le poste de l'administrateur,
  • netwox existe aussi en version Windows™,
  • l'utilisation de netwox à des fins autres que de test est interdite.

LAB #2 - OpenVAS

Présentation

OpenVAS est le successeur libre du scanner Nessus, devenu propriétaire. OpenVAS, tout comme Nessus, est un scanner de vulnérabilité qui balaie un hôte ou une plage d'hôtes pour essayer de détecter des failles de sécurité.

Préparation

Mettez SELinux en mode permissive et désactivez-le dans le fichier /etc/selinux/config :

[root@centos7 ~]# setenforce permissive
[root@centos7 ~]# sed -i 's/=enforcing/=disabled/' /etc/selinux/config

Insérez une règle dans le pare-feu pour permettre la consultation de l'interface HTML du client OpenVAS :

[root@centos7 ~]# firewall-cmd --zone=public --add-port=9443/tcp --permanent
success
[root@centos7 ~]# firewall-cmd --reload
success

Installation

OpenVAS se trouve dans les dépôts d'EPEL. Installez donc ce dépôt :

[root@centos7 ~]# yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm

Installez ensuite openvas-scanner, openvas-manager, openvas-gsa et openvas-cli en utilisant yum :

[root@centos6 ~]# yum install openvas-scanner openvas-manager openvas-gsa openvas-cli

Configuration

Les commandes d'OpenVAS sont les suivantes :

[root@centos7 ~]# ls -l /usr/sbin/openvas*
-rwxr-xr-x. 1 root root   18066 Sep  6  2016 /usr/sbin/openvas-certdata-sync
-rwxr-xr-x. 1 root root 2182496 Sep  6  2016 /usr/sbin/openvasmd
-rwxr-xr-x. 1 root root   37993 Sep  6  2016 /usr/sbin/openvas-migrate-to-postgres
-rwxr-xr-x. 1 root root   11998 Sep  6  2016 /usr/sbin/openvas-mkcert
-rwxr-xr-x. 1 root root   10976 Sep  6  2016 /usr/sbin/openvas-nvt-sync
-rwxr-xr-x. 1 root root     766 Sep  6  2016 /usr/sbin/openvas-nvt-sync-cron
-rwxr-xr-x. 1 root root    2555 Sep  6  2016 /usr/sbin/openvas-portnames-update
-rwxr-xr-x. 1 root root   38378 Sep  6  2016 /usr/sbin/openvas-scapdata-sync
-rwxr-xr-x. 1 root root   86640 Sep  6  2016 /usr/sbin/openvassd
  • /usr/sbin/openvas-mkcert,
    • Cette commande permet de générer un certificat SSL,
  • /usr/sbin/openvas-nvt-sync,
    • Cette commande permet la mise à jour des modules d'extensions de OpenVAS,
  • /usr/sbin/openvasd,
    • Cette commande lance le serveur OpenVAS.

Exécutez maintenant la commande openvas-check-setup :

[root@centos7 ~]# openvas-check-setup 
openvas-check-setup 2.3.3
  Test completeness and readiness of OpenVAS-8
  (add '--v6' or '--v7' or '--v9'
   if you want to check for another OpenVAS version)

  Please report us any non-detected problems and
  help us to improve this check routine:
  http://lists.wald.intevation.org/mailman/listinfo/openvas-discuss

  Send us the log-file (/tmp/openvas-check-setup.log) to help analyze the problem.

  Use the parameter --server to skip checks for client tools
  like GSD and OpenVAS-CLI.

Step 1: Checking OpenVAS Scanner ... 
        OK: OpenVAS Scanner is present in version 5.0.6.
        ERROR: No CA certificate file of OpenVAS Scanner found.
        FIX: Run 'openvas-mkcert'.

 ERROR: Your OpenVAS-8 installation is not yet complete!

Please follow the instructions marked with FIX above and run this
script again.

If you think this result is wrong, please report your observation
and help us to improve this check routine:
http://lists.wald.intevation.org/mailman/listinfo/openvas-discuss
Please attach the log-file (/tmp/openvas-check-setup.log) to help us analyze the problem.

Important - Notez l'erreur ERROR: No CA certificate file of OpenVAS Scanner found.

Créez donc un certificat SSL :

[root@centos7 ~]# openvas-mkcert

-------------------------------------------------------------------------------
			Creation of the OpenVAS SSL Certificate
-------------------------------------------------------------------------------

This script will now ask you the relevant information to create the SSL certificate of OpenVAS.
Note that this information will *NOT* be sent to anybody (everything stays local), but anyone with the ability to connect to your OpenVAS daemon will be able to retrieve this information.


CA certificate life time in days [1460]: 3650
Server certificate life time in days [365]: 3650
Your country (two letter code) [DE]: UK
Your state or province name [none]: SURREY
Your location (e.g. town) [Berlin]: ADDLESTONE
Your organization [OpenVAS Users United]: I2TCH LIMITED

-------------------------------------------------------------------------------
			Creation of the OpenVAS SSL Certificate
-------------------------------------------------------------------------------

Congratulations. Your server certificate was properly created.

The following files were created:

. Certification authority:
   Certificate = /etc/pki/openvas/CA/cacert.pem
   Private key = /etc/pki/openvas/private/CA/cakey.pem

. OpenVAS Server : 
    Certificate = /etc/pki/openvas/CA/servercert.pem
    Private key = /etc/pki/openvas/private/CA/serverkey.pem

Press [ENTER] to exit

[Entrée]
[root@centos7 ~]# 

Exécutez de nouveau la commande openvas-check-setup :

[root@centos7 ~]# openvas-check-setup 
openvas-check-setup 2.3.3
  Test completeness and readiness of OpenVAS-8
  (add '--v6' or '--v7' or '--v9'
   if you want to check for another OpenVAS version)

  Please report us any non-detected problems and
  help us to improve this check routine:
  http://lists.wald.intevation.org/mailman/listinfo/openvas-discuss

  Send us the log-file (/tmp/openvas-check-setup.log) to help analyze the problem.

  Use the parameter --server to skip checks for client tools
  like GSD and OpenVAS-CLI.

Step 1: Checking OpenVAS Scanner ... 
        OK: OpenVAS Scanner is present in version 5.0.6.
        OK: OpenVAS Scanner CA Certificate is present as /etc/pki/openvas/CA/cacert.pem.
/bin/openvas-check-setup: line 219: redis-server: command not found
        ERROR: No redis-server installation found.
        FIX: You should install redis-server for improved scalability and ability to trace/debug the KB

 ERROR: Your OpenVAS-8 installation is not yet complete!

Please follow the instructions marked with FIX above and run this
script again.

If you think this result is wrong, please report your observation
and help us to improve this check routine:
http://lists.wald.intevation.org/mailman/listinfo/openvas-discuss
Please attach the log-file (/tmp/openvas-check-setup.log) to help us analyze the problem.

Important - Notez l'erreur ERROR: No redis-server installation found.

Installez donc redis :

[root@centos7 ~]# yum install redis

Activez les deux lignes suivantes dans le fichier /etc/redis.conf :

...
# unixsocket /tmp/redis.sock
# unixsocketperm 700...
[root@centos7 ~]# sed -i '/^#.*unixsocket/s/^# //' /etc/redis.conf

Ajoutez la ligne kb_location = /tmp/redis.sock dans le fichier /etc/openvas/openvassd.conf :

...
# KB test replay :
kb_dont_replay_scanners = no
kb_dont_replay_info_gathering = no
kb_dont_replay_attacks = no
kb_dont_replay_denials = no
kb_max_age = 864000
kb_location = /tmp/redis.sock
#--- end of the KB section
...

Activez et démarrez le service redis :

[root@centos7 ~]# systemctl enable redis
Created symlink from /etc/systemd/system/multi-user.target.wants/redis.service to /usr/lib/systemd/system/redis.service.
[root@centos7 ~]# systemctl start redis
[root@centos7 ~]# systemctl status redis
● redis.service - Redis persistent key-value database
   Loaded: loaded (/usr/lib/systemd/system/redis.service; enabled; vendor preset: disabled)
  Drop-In: /etc/systemd/system/redis.service.d
           └─limit.conf
   Active: active (running) since Wed 2018-06-20 02:58:35 CEST; 7s ago
 Main PID: 18881 (redis-server)
   CGroup: /system.slice/redis.service
           └─18881 /usr/bin/redis-server 127.0.0.1:6379

Jun 20 02:58:35 centos7.fenestros.loc systemd[1]: Started Redis persistent key-value database.
Jun 20 02:58:35 centos7.fenestros.loc systemd[1]: Starting Redis persistent key-value database...

Exécutez encore une fois la commande openvas-check-setup :

[root@centos7 ~]# openvas-check-setup
...
Step 1: Checking OpenVAS Scanner ... 
        OK: OpenVAS Scanner is present in version 5.0.6.
        OK: OpenVAS Scanner CA Certificate is present as /etc/pki/openvas/CA/cacert.pem.
        OK: redis-server is present in version v=3.2.10.
        OK: scanner (kb_location setting) is configured properly using the redis-server socket: /tmp/redis.sock
        OK: redis-server is running and listening on socket: /tmp/redis.sock.
        OK: redis-server configuration is OK and redis-server is running.
        ERROR: The NVT collection is very small.
        FIX: Run a synchronization script like openvas-nvt-sync or greenbone-nvt-sync.
...

Important - Notez l'erreur ERROR: The NVT collection is very small.

Mettez à jour les modules d'extensions de OpenVAS :

[root@centos7 ~]# openvas-nvt-sync

Dans le cas où cette commande retourne une erreur, procédez de la façon suivante pour mettre à jour les modules d'extensions :

[root@centos7 ~]# wget http://dl.greenbone.net/community-nvt-feed-current.tar.bz2 
[root@centos7 ~]# tar xvf community-nvt-feed-current.tar.bz2 -C /var/lib/openvas/plugins

Les modules d'extensions se trouvent dans le répertoire /var/lib/openvas/plugins :

[root@centos7 ~]# ls /var/lib/openvas/plugins | more
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
404.inc
404.inc.asc
aas_detect.nasl
aas_detect.nasl.asc
adaptbb_detect.nasl
adaptbb_detect.nasl.asc
AfterLogic_WebMail_Pro_detect.nasl
AfterLogic_WebMail_Pro_detect.nasl.asc
alcatel_backdoor_switch.nasl
alcatel_backdoor_switch.nasl.asc
amanda_detect.nasl
amanda_detect.nasl.asc
--More--

Exécutez de nouveau la commande openvas-check-setup :

[root@centos7 ~]# openvas-check-setup
...
Step 2: Checking OpenVAS Manager ... 
        OK: OpenVAS Manager is present in version 6.0.9.
        ERROR: No client certificate file of OpenVAS Manager found.
        FIX: Run 'openvas-mkcert-client -n -i'

 ERROR: Your OpenVAS-8 installation is not yet complete!
...

Important - Notez l'erreur ERROR: No client certificate file of OpenVAS Manager found.

Consultez la signification des options suggérées pour la commande openvas-mkcert-client :

[root@centos7 ~]# openvas-mkcert-client --help
/bin/openvas-mkcert-client: illegal option -- -
Usage:
  openvas-mkcert-client [OPTION...] - Create SSL client certificates for OpenVAS.

Options:
  -h           Display help
  -n           Run non-interactively, create certificates
               and register with the OpenVAS scanner
  -i           Install client certificates for use with OpenVAS manager

Exécutez donc la commande openvas-mkcert-client -i :

[root@centos7 ~]# openvas-mkcert-client -i
This script will now ask you the relevant information to create the SSL client certificates for OpenVAS.

Client certificates life time in days [365]: 3650
Your country (two letter code) [DE]: UK
Your state or province name [none]: SURREY
Your location (e.g. town) [Berlin]: ADDLESTONE
Your organization [none]: I2TCH LIMITED
Your organizational unit [none]: TRAINING
**********
We are going to ask you some question for each client certificate. 

If some question has a default answer, you can force an empty answer by entering a single dot '.'

*********
Client certificates life time in days [3650]: 
Country (two letter code) [UK]: 
State or province name [SURREY]: 
Location (e.g. town) [ADDLESTONE]: 
Organization [I2TCH LIMITED]: 
Organization unit [TRAINING]: 
e-Mail []: infos@i2tch.eu
Generating RSA private key, 4096 bit long modulus
....++
.......++
e is 65537 (0x10001)
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) [DE]:State or Province Name (full name) [Some-State]:Locality Name (eg, city) []:Organization Name (eg, company) [Internet Widgits Pty Ltd]:Organizational Unit Name (eg, section) []:Common Name (eg, your name or your server's hostname) []:Email Address []:Using configuration from /tmp/openvas-mkcert-client.13962/stdC.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName           :PRINTABLE:'UK'
stateOrProvinceName   :ASN.1 12:'SURREY'
localityName          :ASN.1 12:'ADDLESTONE'
organizationName      :ASN.1 12:'I2TCH LIMITED'
organizationalUnitName:ASN.1 12:'TRAINING'
commonName            :ASN.1 12:'om'
emailAddress          :IA5STRING:'infos@i2tch.eu'
Certificate is to be certified until Jun 17 02:03:34 2028 GMT (3650 days)

Write out database with 1 new entries
Data Base Updated
/bin/openvas-mkcert-client: line 370: [: argument expected

Exécutez encore une fois la commande openvas-check-setup :

[root@centos7 ~]# openvas-check-setup
...
Step 2: Checking OpenVAS Manager ... 
        OK: OpenVAS Manager is present in version 6.0.9.
        OK: OpenVAS Manager client certificate is present as /etc/pki/openvas/CA/clientcert.pem.
        ERROR: No OpenVAS Manager database found. (Tried: /var/lib/openvas/mgr/tasks.db)
        FIX: Run 'openvasmd --rebuild' while OpenVAS Scanner is running.
        WARNING: OpenVAS Scanner is NOT running!
        SUGGEST: Start OpenVAS Scanner (openvassd).

 ERROR: Your OpenVAS-8 installation is not yet complete!
...

Important - Notez l'erreur ERROR: No OpenVAS Manager database found. (Tried: /var/lib/openvas/mgr/tasks.db).

Afin de générer la base de données, OpenVAS Scanner doit être en cours d'exécution. Activez et démarrez donc le service :

[root@centos7 ~]# systemctl enable openvas-scanner
Created symlink from /etc/systemd/system/multi-user.target.wants/openvas-scanner.service to /usr/lib/systemd/system/openvas-scanner.service.
[root@centos7 ~]# systemctl start openvas-scanner
[root@centos7 ~]# systemctl status openvas-scanner
● openvas-scanner.service - OpenVAS Scanner
   Loaded: loaded (/usr/lib/systemd/system/openvas-scanner.service; enabled; vendor preset: disabled)
   Active: active (running) since Wed 2018-06-20 04:08:49 CEST; 11s ago
  Process: 16956 ExecStart=/usr/sbin/openvassd $SCANNER_PORT $SCANNER_LISTEN $SCANNER_SRCIP (code=exited, status=0/SUCCESS)
 Main PID: 16957 (openvassd)
   CGroup: /system.slice/openvas-scanner.service
           ├─16957 openvassd: Reloaded 200 of 45658 NVTs (0% / ETA: 26:31)
           └─16958 openvassd (Loading Handler)

Jun 20 04:08:49 centos7.fenestros.loc systemd[1]: Starting OpenVAS Scanner...
Jun 20 04:08:49 centos7.fenestros.loc systemd[1]: Started OpenVAS Scanner.

Contruisez maintenant la base de données :

[root@centos7 ~]# openvasmd --rebuild --progress
Rebuilding NVT cache... -

Exécutez de nouveau la commande openvas-check-setup :

[root@centos7 ~]# openvas-check-setup
...
Step 2: Checking OpenVAS Manager ... 
        OK: OpenVAS Manager is present in version 6.0.9.
        OK: OpenVAS Manager client certificate is present as /etc/pki/openvas/CA/clientcert.pem.
        OK: OpenVAS Manager database found in /var/lib/openvas/mgr/tasks.db.
        OK: Access rights for the OpenVAS Manager database are correct.
        OK: sqlite3 found, extended checks of the OpenVAS Manager installation enabled.
        OK: OpenVAS Manager database is at revision 146.
        OK: OpenVAS Manager expects database at revision 146.
        OK: Database schema is up to date.
        OK: OpenVAS Manager database contains information about 45654 NVTs.
        ERROR: No users found. You need to create at least one user to log in.
        It is recommended to have at least one user with role Admin.
        FIX: create a user by running 'openvasmd --create-user=<name> --role=Admin && openvasmd --user=<name> --new-password=<password>'
...

Important - Notez l'erreur ERROR: No users found. You need to create at least one user to log in.

Créez donc un utilisateur :

[root@centos7 ~]# openvasmd --create-user=fenestros --role=Admin
User created with password 'e366e2ec-8d8f-442d-9d19-5a158ccc50ae'.
[root@centos7 ~]# openvasmd --user=fenestros --new-password=fenestros

Exécutez encore une fois la commande openvas-check-setup :

[root@centos7 ~]# openvas-check-setup
...
Step 2: Checking OpenVAS Manager ... 
        OK: OpenVAS Manager is present in version 6.0.9.
        OK: OpenVAS Manager client certificate is present as /etc/pki/openvas/CA/clientcert.pem.
        OK: OpenVAS Manager database found in /var/lib/openvas/mgr/tasks.db.
        OK: Access rights for the OpenVAS Manager database are correct.
        OK: sqlite3 found, extended checks of the OpenVAS Manager installation enabled.
        OK: OpenVAS Manager database is at revision 146.
        OK: OpenVAS Manager expects database at revision 146.
        OK: Database schema is up to date.
        OK: OpenVAS Manager database contains information about 45654 NVTs.
        OK: At least one user exists.
        ERROR: No OpenVAS SCAP database found. (Tried: /var/lib/openvas/scap-data/scap.db)
        FIX: Run a SCAP synchronization script like openvas-scapdata-sync or greenbone-scapdata-sync.

 ERROR: Your OpenVAS-8 installation is not yet complete!
...

Important - Notez l'erreur ERROR: No OpenVAS SCAP database found. (Tried: /var/lib/openvas/scap-data/scap.db).

La prochaine étape donc consiste à récupérer la base SCAP (Security Content Automation Protocol) :

[root@centos7 ~]# openvas-scapdata-sync

Exécutez de nouveau la commande openvas-check-setup :

[root@centos7 ~]# openvas-check-setup
...
Step 2: Checking OpenVAS Manager ... 
        OK: OpenVAS Manager is present in version 6.0.9.
        OK: OpenVAS Manager client certificate is present as /etc/pki/openvas/CA/clientcert.pem.
        OK: OpenVAS Manager database found in /var/lib/openvas/mgr/tasks.db.
        OK: Access rights for the OpenVAS Manager database are correct.
        OK: sqlite3 found, extended checks of the OpenVAS Manager installation enabled.
        OK: OpenVAS Manager database is at revision 146.
        OK: OpenVAS Manager expects database at revision 146.
        OK: Database schema is up to date.
        OK: OpenVAS Manager database contains information about 45654 NVTs.
        OK: At least one user exists.
        OK: OpenVAS SCAP database found in /var/lib/openvas/scap-data/scap.db.
        ERROR: No OpenVAS CERT database found. (Tried: /var/lib/openvas/cert-data/cert.db)
        FIX: Run a CERT synchronization script like openvas-certdata-sync or greenbone-certdata-sync.

 ERROR: Your OpenVAS-8 installation is not yet complete!
...

Important - Notez l'erreur ERROR: No OpenVAS CERT database found. (Tried: /var/lib/openvas/cert-data/cert.db).

Récupérer donc la base CERT :

[root@centos7 ~]# openvas-certdata-sync

Exécutez encore une fois la commande openvas-check-setup :

[root@centos7 ~]# openvas-check-setup
...
Step 7: Checking if OpenVAS services are up and running ... 
        OK: netstat found, extended checks of the OpenVAS services enabled.
        OK: OpenVAS Scanner is running and listening on all interfaces.
        OK: OpenVAS Scanner is listening on port 9391, which is the default port.
        ERROR: OpenVAS Manager is NOT running!
        FIX: Start OpenVAS Manager (openvasmd).
        ERROR: Greenbone Security Assistant is NOT running!
        FIX: Start Greenbone Security Assistant (gsad).

 ERROR: Your OpenVAS-8 installation is not yet complete!
...

Important - Notez l'erreur ERROR: Greenbone Security Assistant is NOT running!.

Activer et démarrer OpenVAS Manager :

[root@centos7 ~]# systemctl enable openvas-manager
Created symlink from /etc/systemd/system/multi-user.target.wants/openvas-manager.service to /usr/lib/systemd/system/openvas-manager.service.
[root@centos7 ~]# systemctl start openvas-manager
[root@centos7 ~]# systemctl status openvas-manager
● openvas-manager.service - OpenVAS Manager
   Loaded: loaded (/usr/lib/systemd/system/openvas-manager.service; enabled; vendor preset: disabled)
   Active: active (running) since Thu 2018-06-21 11:49:32 CEST; 6s ago
  Process: 24857 ExecStart=/usr/sbin/openvasmd $MANAGER_LISTEN $MANAGER_PORT $SCANNER_LISTEN $SCANNER_PORT $MANAGER_OTP (code=exited, status=0/SUCCESS)
 Main PID: 24862 (openvasmd)
   CGroup: /system.slice/openvas-manager.service
           └─24862 openvasmd

Jun 21 11:49:31 centos7.fenestros.loc systemd[1]: Starting OpenVAS Manager...
Jun 21 11:49:32 centos7.fenestros.loc systemd[1]: Started OpenVAS Manager.

Activer et démarrer le Greenbone Security Assistant :

[root@centos7 ~]# systemctl enable openvas-gsa
Created symlink from /etc/systemd/system/multi-user.target.wants/openvas-gsa.service to /usr/lib/systemd/system/openvas-gsa.service.
[root@centos7 ~]# systemctl start openvas-gsa
[root@centos7 ~]# systemctl status openvas-gsa
● openvas-gsa.service - OpenVAS Greenbone Security Assistant
   Loaded: loaded (/usr/lib/systemd/system/openvas-gsa.service; enabled; vendor preset: disabled)
   Active: active (running) since Thu 2018-06-21 11:50:52 CEST; 8s ago
  Process: 25464 ExecStart=/usr/sbin/gsad $GSA_LISTEN $GSA_PORT $MANAGER_LISTEN $MANAGER_PORT $GNUTLSSTRING (code=exited, status=0/SUCCESS)
 Main PID: 25465 (gsad)
   CGroup: /system.slice/openvas-gsa.service
           ├─25465 /usr/sbin/gsad --port=9443 --mlisten=127.0.0.1 --mport=939...
           └─25466 /usr/sbin/gsad --port=9443 --mlisten=127.0.0.1 --mport=939...

Jun 21 11:50:51 centos7.fenestros.loc systemd[1]: Starting OpenVAS Greenbone ...
Jun 21 11:50:52 centos7.fenestros.loc systemd[1]: Started OpenVAS Greenbone S...
Hint: Some lines were ellipsized, use -l to show in full.

Exécutez encore une fois la commande openvas-check-setup :

[root@centos7 ~]# openvas-check-setup
...
Step 7: Checking if OpenVAS services are up and running ... 
        OK: netstat found, extended checks of the OpenVAS services enabled.
        OK: OpenVAS Scanner is running and listening on all interfaces.
        OK: OpenVAS Scanner is listening on port 9391, which is the default port.
        OK: OpenVAS Manager is running and listening on all interfaces.
        OK: OpenVAS Manager is listening on port 9390, which is the default port.
        WARNING: Greenbone Security Assistant is listening on port 9443, which is NOT the default port!
        SUGGEST: Ensure Greenbone Security Assistant is listening on one of the following ports: 80, 443, 9392.
Step 8: Checking nmap installation ...
        WARNING: Your version of nmap is not fully supported: 6.40
        SUGGEST: You should install nmap 5.51 if you plan to use the nmap NSE NVTs.
Step 10: Checking presence of optional tools ...
        WARNING: Could not find pdflatex binary, the PDF report format will not work.
        SUGGEST: Install pdflatex.
        OK: ssh-keygen found, LSC credential generation for GNU/Linux targets is likely to work.
        OK: rpm found, LSC credential package generation for RPM based targets is likely to work.
        WARNING: Could not find alien binary, LSC credential package generation for DEB based targets will not work.
        SUGGEST: Install alien.
        WARNING: Could not find makensis binary, LSC credential package generation for Microsoft Windows targets will not work.
        SUGGEST: Install nsis.
        OK: SELinux is disabled.

It seems like your OpenVAS-8 installation is OK.
...

Important - Notez les WARNINGS.

Installez les paquets suggérés :

[root@centos7 ~]# yum install texlive-latex-bin-bin alien mingw32-nsis

Exécutez de nouveau la commande openvas-check-setup :

[root@centos7 ~]# openvas-check-setup
...
Step 10: Checking presence of optional tools ...
        OK: pdflatex found.
        WARNING: PDF generation failed, most likely due to missing LaTeX packages. The PDF report format will not work.
        SUGGEST: Install required LaTeX packages.
        OK: ssh-keygen found, LSC credential generation for GNU/Linux targets is likely to work.
        OK: rpm found, LSC credential package generation for RPM based targets is likely to work.
        OK: alien found, LSC credential package generation for DEB based targets is likely to work.
        OK: nsis found, LSC credential package generation for Microsoft Windows targets is likely to work.
        OK: SELinux is disabled.

It seems like your OpenVAS-8 installation is OK.
...

Important - Notez la ligne WARNING: PDF generation failed, most likely due to missing LaTeX packages. The PDF report format will not work.

Pour pouvoir utiliser les rapports au format PDF, installez les paquets suivants :

[root@centos7 ~]# yum -y install texlive-collection-fontsrecommended texlive-collection-latexrecommended texlive-changepage texlive-titlesec

Téléchargez ensuite le fichier comment.sty vers le répertoire /usr/share/texlive/texmf-local/tex/latex/comment :

[root@centos7 ~]# mkdir -p /usr/share/texlive/texmf-local/tex/latex/comment
[root@centos7 ~]# cd /usr/share/texlive/texmf-local/tex/latex/comment
[root@centos7 comment]# wget http://mirrors.ctan.org/macros/latex/contrib/comment/comment.sty
--2018-06-21 12:49:45--  http://mirrors.ctan.org/macros/latex/contrib/comment/comment.sty
Resolving mirrors.ctan.org (mirrors.ctan.org)... 176.28.54.184, 2a01:488:67:1000:b01c:36b8:0:1
Connecting to mirrors.ctan.org (mirrors.ctan.org)|176.28.54.184|:80... connected.
HTTP request sent, awaiting response... 302 Moved Temporarily
Location: http://mirrors.standaloneinstaller.com/ctan/macros/latex/contrib/comment/comment.sty [following]
--2018-06-21 12:49:45--  http://mirrors.standaloneinstaller.com/ctan/macros/latex/contrib/comment/comment.sty
Resolving mirrors.standaloneinstaller.com (mirrors.standaloneinstaller.com)... 37.59.26.59
Connecting to mirrors.standaloneinstaller.com (mirrors.standaloneinstaller.com)|37.59.26.59|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 10197 (10.0K) [text/plain]
Saving to: ‘comment.sty’

100%[======================================>] 10,197      --.-K/s   in 0.02s   

2018-06-21 12:49:46 (592 KB/s) - ‘comment.sty’ saved [10197/10197]

[root@centos7 comment]# chmod 644 comment.sty
[root@centos7 comment]# texhash
texhash: Updating /usr/share/texlive/texmf/ls-R... 
texhash: Updating /usr/share/texlive/texmf-config/ls-R... 
texhash: Updating /usr/share/texlive/texmf-dist/ls-R... 
texhash: Updating /usr/share/texlive/texmf-local///ls-R... 
texhash: Updating /usr/share/texlive/texmf-var/ls-R... 
texhash: Done.

Exécutez une dernière fois la commande openvas-check-setup :

[root@centos7 ~]# openvas-check-setup
...
Step 10: Checking presence of optional tools ...
        OK: pdflatex found.
        OK: PDF generation successful. The PDF report format is likely to work.
        OK: ssh-keygen found, LSC credential generation for GNU/Linux targets is likely to work.
        OK: rpm found, LSC credential package generation for RPM based targets is likely to work.
        OK: alien found, LSC credential package generation for DEB based targets is likely to work.
        OK: nsis found, LSC credential package generation for Microsoft Windows targets is likely to work.
        OK: SELinux is disabled.

It seems like your OpenVAS-8 installation is OK.
...

Utilisation

Passez votre VM en mode graphique :

[root@centos7 bin]# ls -l /etc/systemd/system/default.target
lrwxrwxrwx. 1 root root 37 Apr 30  2016 /etc/systemd/system/default.target -> /lib/systemd/system/multi-user.target
[root@centos7 bin]# rm -rf /etc/systemd/system/default.target
[root@centos7 bin]# ln -s /lib/systemd/system/graphical.target /etc/systemd/system/default.target
[root@centos7 bin]# ls -l /etc/systemd/system/default.target                    
lrwxrwxrwx 1 root root 36 Apr 27 16:42 /etc/systemd/system/default.target -> /lib/systemd/system/graphical.target
[root@centos7 bin]# shutdown -r now

Ouvrez un navigateur web dans votre VM et saississez l'adresse https:>//localhost:9443. Vous obtiendrez une fenêtre similaire à celle-ci :

Créez une exception pour le Self Signed Certificate. Vous obtiendrez une fenêtre similaire à celle-ci:

Entrez le nom de votre utilisateur ainsi que son mot de passe et cliquez sur le bouton Login. Vous obtiendrez une fenêtre similaire à celle-ci :

Dans la boîte Quick start, entrez l'adresse IP de votre VM et cliquez sur le bouton Start Scan. Vous obtiendrez une fenêtre similaire à celle-ci :

Important - Vous pouvez indiquer un réseau entier de la forme 10.0.2.0/24

Analyse des Résultats

A l'issu de l'analyse, il est possible de consulter les résultats :

ainsi que les détails de celui-ci :

Vous trouverez aussi une solution ainsi qu'une évaluation du niveau de risque, Risk factor.

Les Contres-Mesures

Les contre-mesures consistent en la mise en place de chroot pour certains serveurs ainsi que le durcissement de la configuration de serveurs d'application.

LAB #3 - La commande chroot

Le chrootage permet de séparer un utilisateur ou un utilisateur système ( et donc un serveur ) du système.

Sous RHEL/CentOS 7 le binaire chroot est installé par défaut :

[root@centos7 ~]# whereis chroot
chroot: /usr/sbin/chroot /usr/share/man/man1/chroot.1.gz /usr/share/man/man2/chroot.2.gz

Commencez par créer un répertoire pour l'utilisateur qui sera emprisonné :

[root@centos7 ~]# mkdir /home/prison

Le binaire /usr/sbin/chroot doit prendre le SUID bit :

[root@centos7 ~]# ls -l /usr/sbin/chroot
-rwxr-xr-x. 1 root root 33240 Nov  5  2016 /usr/sbin/chroot
[root@centos7 ~]# chmod +s /usr/sbin/chroot
[root@centos7 ~]# ls -l /usr/sbin/chroot
-rwsr-sr-x. 1 root root 33240 Nov  5  2016 /usr/sbin/chroot

Créez maintenant un script de connexion générique pour que l'utilisateur prison puisse se connecter :

[root@centos7 ~]# vi /bin/chroot
[root@centos7 ~]# cat /bin/chroot
#!/bin/bash
exec -c /usr/sbin/chroot /home/$USER /bin/bash

Rendez ce script exécutable :

[root@centos7 ~]# chmod +x /bin/chroot 

Il est maintenant nécessaire de copier toutes les commandes dont l'utilisateur prison aura besoin. Dans cet exemple, nous allons nous contenter de copier /bin/bash et /bin/ls ainsi que les bibliothèques associées :

[root@centos7 ~]# mkdir /home/prison/bin
[root@centos7 ~]# cp /bin/bash /home/prison/bin/
[root@centos7 ~]# ldd /bin/bash
	linux-vdso.so.1 =>  (0x00007fffe4199000)
	libtinfo.so.5 => /lib64/libtinfo.so.5 (0x00007f0e3804c000)
	libdl.so.2 => /lib64/libdl.so.2 (0x00007f0e37e48000)
	libc.so.6 => /lib64/linux-vdso.so.1(0x00007f0e37a84000)
	/lib64/ld-linux-x86-64.so.2 (0x0000559894c7a000)
[root@centos7 ~]# mkdir /home/prison/lib64
[root@centos7 ~]# cp /lib64/libtinfo.so.5 /home/prison/lib64
[root@centos7 ~]# cp /lib64/libdl.so.2 /home/prison/lib64
[root@centos7 ~]# cp /lib64/libc.so.6 /home/prison/lib64
[root@centos7 ~]# cp /lib64/ld-linux-x86-64.so.2 /home/prison/lib64
[root@centos7 ~]# cp /bin/ls /home/prison/bin/
[root@centos7 ~]# ldd /bin/ls
	linux-vdso.so.1 =>  (0x00007ffc7a1b1000)
	libselinux.so.1 => /lib64/libselinux.so.1 (0x00007fc4fc9e7000)
	libcap.so.2 => /lib64/libcap.so.2 (0x00007fc4fc7e2000)
	libacl.so.1 => /lib64/libacl.so.1 (0x00007fc4fc5d8000)
	libc.so.6 => /lib64/libc.so.6 (0x00007fc4fc215000)
	libpcre.so.1 => /lib64/libpcre.so.1 (0x00007fc4fbfb3000)
	libdl.so.2 => /lib64/libdl.so.2 (0x00007fc4fbdae000)
	/lib64/ld-linux-x86-64.so.2 (0x000055f5b5006000)
	libattr.so.1 => /lib64/libattr.so.1 (0x00007fc4fbba9000)
	libpthread.so.0 => /lib64/libpthread.so.0 (0x00007fc4fb98d000)
[root@centos7 ~]# cp /lib64/libselinux.so.1 /home/prison/lib64
[root@centos7 ~]# cp /lib64/libcap.so.2 /home/prison/lib64
[root@centos7 ~]# cp /lib64/libacl.so.1 /home/prison/lib64
[root@centos7 ~]# cp /lib64/libpcre.so.1 /home/prison/lib64
[root@centos7 ~]# cp /lib64/libattr.so.1 /home/prison/lib64
[root@centos7 ~]# cp /lib64/libpthread.so.0 /home/prison/lib64

Créez maintenant le groupe chroot :

[root@centos7 ~]# groupadd chroot
[root@centos7 ~]# cat /etc/group | grep chroot
chroot:x:1002:

Créez maintenant l'utilisateur prison :

[root@centos7 ~]# useradd prison -c chroot_user -d /home/prison -g chroot -s /bin/chroot
useradd: warning: the home directory already exists.
Not copying any file from skel directory into it.

[root@centos7 ~]# cp /etc/skel/.* /home/prison
cp: omitting directory ‘/etc/skel/.’
cp: omitting directory ‘/etc/skel/..’
cp: omitting directory ‘/etc/skel/.mozilla’

[root@centos7 ~]# cp -pfR /etc/skel/.m* /home/prison

[root@centos7 ~]# passwd prison
Changing password for user prison.
New password: prison
BAD PASSWORD: The password is shorter than 8 characters
Retype new password: prison
passwd: all authentication tokens updated successfully.

Dernièrement, modifiez le propriétaire et le groupe du répertoire /home/prison :

[root@centos7 ~]# chown -R prison:chroot /home/prison

Essayez maintenant de vous connecter en tant que prison :

[root@centos7 ~]# su - prison
Last login: Wed Jun 20 00:01:21 CEST 2018 on pts/2
bash-4.2$ pwd
/
bash-4.2$ /bin/ls
bin  lib64
bash-4.2$ /bin/ls -la
total 28
drwxr-xr-x. 5 1002 1002 4096 Jun 19 21:52 .
drwxr-xr-x. 5 1002 1002 4096 Jun 19 21:52 ..
-rw-------. 1 1002 1002   47 Jun 19 22:01 .bash_history
-rw-r--r--. 1 1002 1002   18 Jun 19 19:01 .bash_logout
-rw-r--r--. 1 1002 1002  193 Jun 19 19:01 .bash_profile
-rw-r--r--. 1 1002 1002  231 Jun 19 19:01 .bashrc
drwxr-xr-x. 4 1002 1002   37 Dec 10  2015 .mozilla
drwxr-xr-x. 2 1002 1002   26 Jun 19 17:46 bin
drwxr-xr-x. 2 1002 1002 4096 Jun 19 18:05 lib64
bash-4.2$ exit
exit
[root@centos7 ~]# 

Notez que l'utilisateur prison est chrooté.

LAB #4 - Sécuriser Apache

Installation

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.

Testez le serveur apache

Avec un navigateur

Lancez maintenant le navigateur et saisissez l'adresse http://localhost dans la barre d'adresses. Vous devez obtenir une page web servie par votre apache.

Avec Telnet

Premièrement, ouvrez un console et en tant que root et installez telnet :

[root@centos7 ~]# yum install telnet
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
 * base: mirrors.atosworldline.com
 * extras: mirrors.atosworldline.com
 * updates: ftp.ciril.fr
Resolving Dependencies
--> Running transaction check
---> Package telnet.x86_64 1:0.17-60.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

======================================================================================================================================================
 Package                           Arch                              Version                                    Repository                       Size
======================================================================================================================================================
Installing:
 telnet                            x86_64                            1:0.17-60.el7                              base                             63 k

Transaction Summary
======================================================================================================================================================
Install  1 Package

Total download size: 63 k
Installed size: 113 k
Is this ok [y/d/N]: y

Utilisez ensuite telnet pour vérifier le bon fonctionnement d'Apache :

[root@centos7 ~]# telnet localhost 80
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
GET /
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
		<title>Apache HTTP Server Test Page powered by CentOS</title>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <!-- Bootstrap -->
    <link href="/noindex/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="noindex/css/open-sans.css" type="text/css" />

<style type="text/css"><!--		 

body {
  font-family: "Open Sans", Helvetica, sans-serif;
  font-weight: 100;
  color: #ccc;
  background: rgba(10, 24, 55, 1);
  font-size: 16px;
}

h2, h3, h4 {
  font-weight: 200;
}

h2 {
  font-size: 28px;
}

.jumbotron {
  margin-bottom: 0;
  color: #333;
  background: rgb(212,212,221); /* Old browsers */
  background: radial-gradient(ellipse at center top, rgba(255,255,255,1) 0%,rgba(174,174,183,1) 100%); /* W3C */
}

.jumbotron h1 {
  font-size: 128px;
  font-weight: 700;
  color: white;
  text-shadow: 0px 2px 0px #abc,
               0px 4px 10px rgba(0,0,0,0.15),
               0px 5px 2px rgba(0,0,0,0.1),
               0px 6px 30px rgba(0,0,0,0.1);
}

.jumbotron p {
  font-size: 28px;
  font-weight: 100;
}

.main {
   background: white;
   color: #234;
   border-top: 1px solid rgba(0,0,0,0.12);
   padding-top: 30px;
   padding-bottom: 40px;
}

.footer {
   border-top: 1px solid rgba(255,255,255,0.2);
   padding-top: 30px;
}

    --></style>
</head>
<body>
  <div class="jumbotron text-center">
    <div class="container">
   	  <h1>Testing 123..</h1>
  		<p class="lead">This page is used to test the proper operation of the <a href="http://apache.org">Apache HTTP server</a> after it has been installed. If you can read this page it means that this site is working properly. This server is powered by <a href="http://centos.org">CentOS</a>.</p>
		</div>
  </div>
  <div class="main">
    <div class="container">
       <div class="row">
  			<div class="col-sm-6">
    			<h2>Just visiting?</h2>
			  		<p class="lead">The website you just visited is either experiencing problems or is undergoing routine maintenance.</p>
  					<p>If you would like to let the administrators of this website know that you've seen this page instead of the page you expected, you should send them e-mail. In general, mail sent to the name "webmaster" and directed to the website's domain should reach the appropriate person.</p>
  					<p>For example, if you experienced problems while visiting www.example.com, you should send e-mail to "webmaster@example.com".</p>
	  			</div>
  				<div class="col-sm-6">
	  				<h2>Are you the Administrator?</h2>
		  			<p>You should add your website content to the directory <tt>/var/www/html/</tt>.</p>
		  			<p>To prevent this page from ever being used, follow the instructions in the file <tt>/etc/httpd/conf.d/welcome.conf</tt>.</p>

	  				<h2>Promoting Apache and CentOS</h2>
			  		<p>You are free to use the images below on Apache and CentOS Linux powered HTTP servers.  Thanks for using Apache and CentOS!</p>
				  	<p><a href="http://httpd.apache.org/"><img src="images/apache_pb.gif" alt="[ Powered by Apache ]"></a> <a href="http://www.centos.org/"><img src="images/poweredby.png" alt="[ Powered by CentOS Linux ]" height="31" width="88"></a></p>
  				</div>
	  		</div>
	    </div>
		</div>
	</div>
	  <div class="footer">
      <div class="container">
        <div class="row">
          <div class="col-sm-6">          
            <h2>Important note:</h2>
            <p class="lead">The CentOS Project has nothing to do with this website or its content,
            it just provides the software that makes the website run.</p>
            
            <p>If you have issues with the content of this site, contact the owner of the domain, not the CentOS project. 
            Unless you intended to visit CentOS.org, the CentOS Project does not have anything to do with this website,
            the content or the lack of it.</p>
            <p>For example, if this website is www.example.com, you would find the owner of the example.com domain at the following WHOIS server:</p>
            <p><a href="http://www.internic.net/whois.html">http://www.internic.net/whois.html</a></p>
          </div>
          <div class="col-sm-6">
            <h2>The CentOS Project</h2>
            <p>The CentOS Linux distribution is a stable, predictable, manageable and reproduceable platform derived from 
               the sources of Red Hat Enterprise Linux (RHEL).<p>
            
            <p>Additionally to being a popular choice for web hosting, CentOS also provides a rich platform for open source communities to build upon. For more information
               please visit the <a href="http://www.centos.org/">CentOS website</a>.</p>
          </div>
        </div>
		  </div>
    </div>
  </div>
</body></html>
Connection closed by foreign host.

Préparation

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.

Editez le fichier /etc/hosts et ajoutez la ligne suivante:

10.0.2.15       www.homeland.net

Re-démarrez le serveur httpd :

[root@centos7 ~]# systemctl restart 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 Thu 2017-08-24 10:19:38 CEST; 9s ago
     Docs: man:httpd(8)
           man:apachectl(8)
  Process: 17996 ExecStop=/bin/kill -WINCH ${MAINPID} (code=exited, status=0/SUCCESS)
  Process: 21235 ExecReload=/usr/sbin/httpd $OPTIONS -k graceful (code=exited, status=0/SUCCESS)
 Main PID: 18013 (httpd)
   Status: "Total requests: 0; Current requests/sec: 0; Current traffic:   0 B/sec"
   CGroup: /system.slice/httpd.service
           ├─18013 /usr/sbin/httpd -DFOREGROUND
           ├─18014 /usr/sbin/httpd -DFOREGROUND
           ├─18015 /usr/sbin/httpd -DFOREGROUND
           ├─18016 /usr/sbin/httpd -DFOREGROUND
           ├─18017 /usr/sbin/httpd -DFOREGROUND
           ├─18018 /usr/sbin/httpd -DFOREGROUND
           ├─18019 /usr/sbin/httpd -DFOREGROUND
           ├─18020 /usr/sbin/httpd -DFOREGROUND
           └─18021 /usr/sbin/httpd -DFOREGROUND

Aug 24 10:19:38 centos7.fenestros.loc systemd[1]: Starting The Apache HTTP Server...
Aug 24 10:19:38 centos7.fenestros.loc systemd[1]: Started The Apache HTTP Server.

Gestion de serveurs virtuels

Apache est capable de gérer de multiples sites hébergés sur la même machine. Ceci est rendu possible par un fichier de configuration spécifique appelé: /etc/httpd/conf/vhosts.d/Vhosts.conf. Le répertoire /etc/httpd/conf/vhosts.d/ n'existant pas, créez-le:

[root@centos7 ~]# mkdir /etc/httpd/conf/vhosts.d/

Créez ensuite le fichier /etc/httpd/conf/vhosts.d/Vhosts.conf :

[root@centos7 ~]# touch /etc/httpd/conf/vhosts.d/Vhosts.conf

Le contenu de fichier est inclus à l'intérieur de la configuration d'apache grâce à la directive suivante du fichier httpd.conf:

...
# Supplemental configuration
#
# Load config files in the "/etc/httpd/conf.d" directory, if any.
IncludeOptional conf.d/*.conf
Include conf/vhosts.d/*.conf

Ajoutez donc cette ligne au fichier /etc/httpd/conf/httpd.conf.

Il existe deux façons de créer des sites ( hôtes ) virtuels :

  • Hôte Virtuel par adresse IP
  • Hôte Virtuel par nom

Créez un répertoire /www/site1 à la racine de votre arborescence pour héberger notre premier hôte virtuel :

[root@centos7 ~]# mkdir -p /www/site1

Créez ensuite le fichier index.html du répertoire /www/site1:

[root@centos7 ~]# vi /www/site1/index.html

Editez-le ainsi :

index.html
<html>
<head>
<title>Page de Test</title>
<body>
<center>Accueil du site 1</center>
</body>
</html>
Hôte virtuel par nom

Nous allons d'abord considérer les sites virtuels par nom. Editez donc le fichier /etc/httpd/conf/vhosts.d/Vhosts.conf en suivant l'exemple ci-dessous :

Vhosts.conf
################# Named VirtualHosts
NameVirtualHost *:80
##################Default Site Virtual Host
<VirtualHost *:80>
DocumentRoot /var/www/html
ServerName www.homeland.net
</VirtualHost>
##################www.vhostnom.com
<VirtualHost *:80>
ServerName www.vhostnom.com
DirectoryIndex index.html
DocumentRoot /www/site1
<Directory /www/site1>
Require all granted
</Directory>
</VirtualHost>

Important : Notez qu'apache servira toujours le contenu da la première section des sites virtuels par défaut, sauf précision de la part de l'internaute. Il est donc impératif d'ajouter une section VirtualHost pour votre site par défaut.

Redémarrez ensuite le serveur Apache :

[root@centos7 ~]# systemctl restart httpd

Avant de pouvoir consulter le site virtuel, il faut renseigner votre fichier /etc/hosts :

10.0.2.15            www.homeland.net
10.0.2.15            www.vhostnom.com

Sauvegardez votre fichier hosts et installez le navigateur web en mode texte lynx :

[root@centos7 ~]# yum install lynx
Loaded plugins: fastestmirror, langpacks
adobe-linux-x86_64                                                                                                             | 2.9 kB  00:00:00     
base                                                                                                                           | 3.6 kB  00:00:00     
extras                                                                                                                         | 3.4 kB  00:00:00     
updates                                                                                                                        | 3.4 kB  00:00:00     
Loading mirror speeds from cached hostfile
 * base: centos.mirrors.ovh.net
 * extras: ftp.rezopole.net
 * updates: centos.mirrors.ovh.net
Resolving Dependencies
--> Running transaction check
---> Package lynx.x86_64 0:2.8.8-0.3.dev15.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

======================================================================================================================================================
 Package                        Arch                             Version                                         Repository                      Size
======================================================================================================================================================
Installing:
 lynx                           x86_64                           2.8.8-0.3.dev15.el7                             base                           1.4 M

Transaction Summary
======================================================================================================================================================
Install  1 Package

Total download size: 1.4 M
Installed size: 5.4 M
Is this ok [y/d/N]: y

Testez votre configuration avec lynx :

[root@centos7 ~]# lynx --dump http://www.vhostnom.com
                              Accueil du site 1


[root@centos7 ~]# 

Afin de mieux comprendre les visites à notre site virtuel, nous avons besoin d'un fichier log ainsi qu'un fichier de log des erreurs. Ouvrez donc le fichier /etc/httpd/conf/vhosts.d/Vhosts.conf et ajoutez les deux lignes suivantes:

Customlog /www/logs/site1/vhostnom.log combined
Errorlog /www/logs/site1/error.log

Vous obtiendrez une fenêtre similaire à celle-ci :

Vhosts.conf
################# Named VirtualHosts
NameVirtualHost *:80
##################Default Site Virtual Host
<VirtualHost *:80>
DocumentRoot /var/www/html
ServerName www.homeland.net
</VirtualHost>
##################www.vhostnom.com
<VirtualHost *:80>
ServerName www.vhostnom.com
DirectoryIndex index.html
DocumentRoot /www/site1
Customlog /www/logs/site1/vhostnom.log combined
Errorlog /www/logs/site1/error.log
<Directory /www/site1>
Require all granted
</Directory>
</VirtualHost>

Créez ensuite le répertoire /www/logs/site1 :

[root@centos7 ~]# mkdir -p /www/logs/site1

Redémarrez le serveur Apache :

[root@centos7 ~]# systemctl restart httpd

Testez votre configuration avec lynx :

[root@centos7 ~]# lynx --dump http://www.vhostnom.com
                              Accueil du site 1


[root@centos7 ~]# 

Contrôlez maintenant le contenu du répertoire /www/logs/site1. Vous devez y retrouver deux fichiers :

[root@centos7 ~]# ls -l /www/logs/site1/
total 4
-rw-r--r--. 1 root root   0 Aug 24 11:06 error.log
-rw-r--r--. 1 root root 138 Aug 24 11:06 vhostnom.log

Ces deux fichiers vhostnom.log et error.log sont créés automatiquement par Apache.

En contrôlant le contenu du fichier /www/logs/site1/vhostnom.log nous constatons que le log a été généré :

[root@centos7 ~]# cat /www/logs/site1/vhostnom.log
10.0.2.15 - - [24/Aug/2017:11:06:47 +0200] "GET / HTTP/1.0" 200 100 "-" "Lynx/2.8.8dev.15 libwww-FM/2.14 SSL-MM/1.4.1 OpenSSL/1.0.1e-fips"
Hôte virtuel par adresse IP

Commencez par créer une adresse IP fixe :

[root@centos7 ~]# nmcli connection add con-name ip_fixe ifname enp0s3 type ethernet ip4 10.0.2.16/24 gw4 10.0.2.2    
[root@centos7 ~]# nmcli connection up ip_fixe    
[root@centos7 ~]# nmcli connection mod ip_fixe ipv4.dns 8.8.8.8
[root@centos7 ~]# systemctl restart NetworkManager
[root@centos7 ~]# nslookup www.free.fr
Server:		8.8.8.8
Address:	8.8.8.8#53

Non-authoritative answer:
Name:	www.free.fr
Address: 212.27.48.10

Vous allez maintenant procéder à la création d'un site ( hôte ) virtuel par adresse IP. Normalement, votre serveur serait muni de deux cartes réseaux permettant ainsi d'attribuer un site ou hôte virtuel par numéro IP. Cependant, dans le cas suivant vous allez tout simplement affecté deux numéros IP à la même carte afin de procéder aux tests. Pour faire ceci, vous devez associer une deuxième adresse IP à votre carte réseau enp0s3. Saisissez donc la commande suivante dans une fenêtre de console en tant que root :

[root@centos7 ~]# ip a | grep 'inet '
    inet 127.0.0.1/8 scope host lo
    inet 10.0.2.16/24 brd 10.0.2.255 scope global enp0s3
[root@centos7 ~]# ip a add 192.168.1.99/24 dev enp0s3
[root@centos7 ~]# ip a | grep 'inet '
    inet 127.0.0.1/8 scope host lo
    inet 10.0.2.16/24 brd 10.0.2.255 scope global enp0s3
    inet 192.168.1.99/24 scope global enp0s3

Créez maintenant le répertoire pour notre site2 :

[root@centos7 ~]# mkdir /www/site2

Créez la page d'accueil :

[root@centos7 ~]# vi /www/site2/index.html

Editez la page d'accueil :

index.html
<html>
<body>
<center>Accueil du site 2</center>
</body>
</html>

Créez ensuite le répertoire /www/logs/site2 :

[root@centos7 ~]# mkdir /www/logs/site2

Editez maintenant le fichier /etc/httpd/conf/vhosts.d/Vhosts.conf:

Vhosts.conf
################# IP-based Virtual Hosts
<VirtualHost 192.168.1.99>
DocumentRoot /www/site2
ServerName www.vhostip.com
DirectoryIndex index.html
Customlog /www/logs/site2/vhostip.log combined
Errorlog /www/logs/site2/error.log
<Directory /www/site2>
Require all granted
</Directory>
</VirtualHost>
################# Named VirtualHosts
NameVirtualHost *:80
##################Default Site Virtual Host
<VirtualHost *:80>
DocumentRoot /var/www/html
ServerName www.homeland.net
</VirtualHost>
##################www.vhostnom.com
<VirtualHost *:80>
ServerName www.vhostnom.com
DirectoryIndex index.html
DocumentRoot /www/site1
Customlog /www/logs/site1/vhostnom.log combined
Errorlog /www/logs/site1/error.log
<Directory /www/site1>
Require all granted
</Directory>
</VirtualHost>

Éditez ensuite le 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	centos7.fenestros.loc
10.0.2.16	www.homeland.net
10.0.2.16       www.vhostnom.com
192.168.1.99    www.vhostip.com

Redémarrez votre serveur Apache :

[root@centos7 ~]# systemctl restart httpd

Testez votre configuration avec lynx :

[root@centos7 ~]# lynx --dump http://www.vhostip.com
                              Accueil du site 2


[root@centos7 ~]# 

Consultez maintenant le répertoire /www/logs/site2. Vous constaterez l'apparition d'un fichier log pour le site www.vhostip.com :

[root@centos7 ~]# ls -l /www/logs/site2/
total 4
-rw-r--r--. 1 root root   0 Aug 24 14:28 error.log
-rw-r--r--. 1 root root 141 Aug 24 14:29 vhostip.log

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@centos6 ~]# vi /www/site1/secret/.htaccess

Editez-le en suivant l'exemple ci-dessous :

.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

Maintenant, éditez-le ainsi :

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.vhostip.com
DirectoryIndex index.html
Customlog /www/logs/site2/vhostip.log combined
Errorlog /www/logs/site2/error.log
<Directory /www/site2>
Require all granted
</Directory>
</VirtualHost>
################# Named VirtualHosts
NameVirtualHost *:80
##################Default Site Virtual Host
<VirtualHost *:80>
DocumentRoot /var/www/html
ServerName www.homeland.net
</VirtualHost>
##################www.vhostnom.com
<VirtualHost *:80>
ServerName www.vhostnom.com
DirectoryIndex index.html
DocumentRoot /www/site1
Customlog /www/logs/site1/vhostnom.log combined
Errorlog /www/logs/site1/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 en tapant http://www.vhostnom.com/secret/index.html dans la barre d'adresses de votre navigateur. Vous constaterez qu'une boîte de dialogue apparaît en vous demandant de renseigner le nom d'utilisateur ainsi que le mot de passe pour pouvoir avoir accès à la section « Secret du Site1 ».

mod_auth_mysql

Vous devez utiliser mod_auth_mysql pour protéger l'accès à un répertoire secret2 dans votre site virtuel www.vhostnom.com.

Installation

Installez le serveur MariaDB ainsi que apr-util-mysql :

[root@centos7 ~]# yum install mariadb mariadb-server apr-util-mysql

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';

Vous obtiendrez :

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: 
[root@centos7 ~]# mysql -u root -p -e "SELECT * FROM auth.users;"
Enter password: 
+-----------+---------------------------------------+
| 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.vhostip.com
DirectoryIndex index.html
Customlog /www/logs/site2/vhostip.log combined
Errorlog /www/logs/site2/error.log
<Directory /www/site2>
Require all granted
</Directory>
</VirtualHost>
################# Named VirtualHosts
NameVirtualHost *:80
##################Default Site Virtual Host
<VirtualHost *:80>
DocumentRoot /var/www/html
ServerName www.homeland.net
</VirtualHost>
##################www.vhostnom.com
<VirtualHost *:80>
ServerName www.vhostnom.com
DirectoryIndex index.html
DocumentRoot /www/site1
Customlog /www/logs/site1/vhostnom.log combined
Errorlog /www/logs/site1/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

En utilisant le navigateur web graphique de votre VM, ouvrez le site http://www.vhostnom.com/secret2/index.html, renseignez l'utilisateur apache et le mot de passe password puis cliquez sur le bouton OK.

Vous devrez découvert le secret MySQL !

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
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
 * base: centos.mirror.ate.info
 * extras: distrib-coffee.ipsl.jussieu.fr
 * updates: mirror.guru
Resolving Dependencies
--> Running transaction check
---> Package openldap.x86_64 0:2.4.40-13.el7 will be updated
---> Package openldap.x86_64 0:2.4.44-5.el7 will be an update
---> Package openldap-clients.x86_64 0:2.4.44-5.el7 will be installed
---> Package openldap-servers.x86_64 0:2.4.44-5.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

======================================================================================================================================
 Package                               Arch                        Version                            Repository                 Size
======================================================================================================================================
Installing:
 openldap-clients                      x86_64                      2.4.44-5.el7                       base                      188 k
 openldap-servers                      x86_64                      2.4.44-5.el7                       base                      2.2 M
Updating:
 openldap                              x86_64                      2.4.44-5.el7                       base                      354 k

Transaction Summary
======================================================================================================================================
Install  2 Packages
Upgrade  1 Package

Total download size: 2.7 M
Is this ok [y/d/N]:  y

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.

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}B4p7daRzJZPbf7AjuuYzohaW9nS7hGXi

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}B4p7daRzJZPbf7AjuuYzohaW9nS7hGXi
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@centos6 ~]# 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

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>
...

AuthzLDAPAuthoritative

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.

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

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.

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
Loaded plugins: fastestmirror, langpacks
adobe-linux-x86_64                                                                                             | 2.9 kB  00:00:00     
base                                                                                                           | 3.6 kB  00:00:00     
extras                                                                                                         | 3.4 kB  00:00:00     
updates                                                                                                        | 3.4 kB  00:00:00     
Loading mirror speeds from cached hostfile
 * base: centos.mirrors.ovh.net
 * extras: distrib-coffee.ipsl.jussieu.fr
 * updates: mirror.guru
Resolving Dependencies
--> Running transaction check
---> Package mod_ssl.x86_64 1:2.4.6-67.el7.centos.6 will be installed
--> Processing Dependency: libcrypto.so.10(OPENSSL_1.0.2)(64bit) for package: 1:mod_ssl-2.4.6-67.el7.centos.6.x86_64
--> Running transaction check
---> Package openssl-libs.x86_64 1:1.0.1e-60.el7_3.1 will be updated
--> Processing Dependency: openssl-libs(x86-64) = 1:1.0.1e-60.el7_3.1 for package: 1:openssl-1.0.1e-60.el7_3.1.x86_64
---> Package openssl-libs.x86_64 1:1.0.2k-8.el7 will be an update
--> Running transaction check
---> Package openssl.x86_64 1:1.0.1e-60.el7_3.1 will be updated
---> Package openssl.x86_64 1:1.0.2k-8.el7 will be an update
--> Finished Dependency Resolution

Dependencies Resolved

======================================================================================================================================
 Package                        Arch                     Version                                      Repository                 Size
======================================================================================================================================
Installing:
 mod_ssl                        x86_64                   1:2.4.6-67.el7.centos.6                      updates                   109 k
Updating for dependencies:
 openssl                        x86_64                   1:1.0.2k-8.el7                               base                      492 k
 openssl-libs                   x86_64                   1:1.0.2k-8.el7                               base                      1.2 M

Transaction Summary
======================================================================================================================================
Install  1 Package
Upgrade             ( 2 Dependent packages)

Total download size: 1.8 M
Is this ok [y/d/N]: y
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.homeland.net.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.homeland.net.key -out www.homeland.net.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) []:centos7.fenestros.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.homeland.net.csr -signkey www.homeland.net.key -out www.homeland.net.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.homeland.net.key /etc/pki/tls/private/
[root@centos7 ~]# cp /root/www.homeland.net.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.homeland.net.crt 
SSLCertificateKeyFile /etc/pki/tls/private/www.homeland.net.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.homeland.net: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 le navigateur web de votre VM en saisissant l'adresse https://www.homeland.net.

Important - Il est normal que la vérification échoue car dans ce cas il s'agit du certificat de test auto-signé.

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>

<html>

Copyright © 2020 Hugh Norris.<br><br>

</html>

Menu