Version : 2021.01

Dernière mise-à-jour : 2021/02/03 16:56

SER705 - Gestion de l'Authentification d'Apache avec OpenLDAP

Contenu du Module

  • SER705 - Gestion de l'Authentification d'Apache avec OpenLDAP
    • Contenu du Module
    • Présentation d'Apache
    • Préparation
    • Installation à partir des dépôts
    • LAB #1 - Gestion de l'authentification avec OpenLDAP et mod_authnz_ldap
      • Configuration d'OpenLDAP
      • Configuration d'Apache

Présentation d'Apache

Un serveur web est une machine doté d'un logiciel serveur qui attend des requêtes de la part de machines clientes afin de leur livrer de documents de types différents.

En 1994 le développement du serveur web le plus connue à l'époque, le démon HTTP, a été arrêté suite au départ de la NCSA de son principal développeur, Rob McCool.

Au début de l'année 1995, un groupe de webmestres indépendants s'est mis en place sous la direction de Brian Behlendorf et Cliff Skolnick pour reprendre le travail sur ce démon. Ce projet a pris le nom Apache. En même temps la NCSA a repris son propre travail de développement sur son démon HTTP. L'arrivée dans le groupe Apache de deux personnes de la NCSA en tant que membres honoraires, Brandon Long et Beth Frank a permis la mise en commun des connaissances des deux groupes.

Le projet Apache est un projet de développement d'un serveur web libre pour les plateformes Unix et Windows™. La première version officielle, la 0.6.2 est sortie en avril 1995.

La Fondation Apache, créée en 1999 par l'équipe Apache, gère aujourd'hui non seulement le projet Apache mais aussi un grand nombre d'autres projets. La liste des projets de la Fondation peut être trouvée ici.

Apache est modulaire. Certains modules fondamentaux conditionnent comment Apache traite la question du multitraitement. Les modules multitraitements - MPM - Multi-Processing Modules - sont différents selon le système d'exploitation utilisé et la charge attendue.

  • mpm-winnt - module propre à Windows™ qui utilise son support réseau natif,
  • mpm_netware - un serveur web basé exclusivement sur les threads et optimisé pour Novell NetWare™,
  • mpmt_os2 - un serveur hybride multi-processus, multi-thread pour OS/2,
  • prefork - module propre à Unix et Linux qui implémente un serveur mono-tâche à duplication,
  • worker - module propre à Unix et Linux qui implémente un serveur hybride multi-tâche et multitraitement,
  • event - module propre à Unix et Linux conçu pour permettre le traitement d'un nombre accru de requêtes simultanées en déléguant certaines tâches aux threads d'écoute, libérant par là-même les threads de travail et leur permettant de traiter les nouvelles requêtes.

Ces modules sont compilés statiquement au binaire Apache et sont mutuellement exclusifs.

Préparation

Démarrer la Machine Virtuelle :

desktop@serverXX:~$ VBoxManage startvm CentOS_7 --type headless
Waiting for VM "CentOS_7" to power on...
VM "CentOS_7" has been successfully started.

Connectez-vous à la machine virtuelle CentOS_7 à partir d'un terminal de votre serveur dédié :

desktop@serverXX:~$ ssh -l trainee localhost -p 3022

Désactivez le mode enforcing de SELINUX afin de pouvoir librement travailler avec Apache :

[root@centos7 ~]# setenforce permissive
[root@centos7 ~]# getenforce
Permissive
[root@centos7 ~]# vi /etc/sysconfig/selinux 
[root@centos7 ~]# cat /etc/sysconfig/selinux 

# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing - SELinux security policy is enforced.
#     permissive - SELinux prints warnings instead of enforcing.
#     disabled - No SELinux policy is loaded.
SELINUX=permissive
# SELINUXTYPE= can take one of three two values:
#     targeted - Targeted processes are protected,
#     minimum - Modification of targeted policy. Only selected processes are protected. 
#     mls - Multi Level Security protection.
SELINUXTYPE=targeted 

Afin d'éviter les problèmes liés au pare-feu arrêtez le service firewalld :

[root@centos7 ~]# systemctl stop firewalld
[root@centos7 ~]# systemctl disable firewalld
[root@centos7 ~]# systemctl status firewalld
● firewalld.service - firewalld - dynamic firewall daemon
   Loaded: loaded (/usr/lib/systemd/system/firewalld.service; disabled; vendor preset: enabled)
   Active: inactive (dead)
     Docs: man:firewalld(1)

Aug 21 16:23:02 centos7.fenestros.loc systemd[1]: Starting firewalld - dynamic firewall daemon...
Aug 21 16:23:07 centos7.fenestros.loc systemd[1]: Started firewalld - dynamic firewall daemon.
Aug 21 16:29:49 centos7.fenestros.loc systemd[1]: Stopping firewalld - dynamic firewall daemon...
Aug 21 16:29:49 centos7.fenestros.loc systemd[1]: Stopped firewalld - dynamic firewall daemon.

Installation à partir des dépôts

Sous RHEL / CentOS 7, Apache n'est pas installé par défaut. Utilisez donc yum pour l'installer :

[root@centos7 ~]# rpm -qa | grep httpd
[root@centos7 ~]#
[root@centos7 ~]# yum install httpd

La version d'Apache est la 2.4.6 :

[root@centos7 ~]# rpm -qa | grep httpd
httpd-2.4.6-45.el7.centos.4.x86_64
httpd-tools-2.4.6-45.el7.centos.4.x86_64

Configurez le service pour démarrer automatiquement :

[root@centos7 ~]# systemctl status httpd
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
   Active: inactive (dead)
     Docs: man:httpd(8)
           man:apachectl(8)
[root@centos7 ~]# systemctl enable httpd
Created symlink from /etc/systemd/system/multi-user.target.wants/httpd.service to /usr/lib/systemd/system/httpd.service.

Créez la page d'accueil du site par défaut :

[root@centos7 ~]# vi /var/www/html/index.html
[root@centos7 ~]# cat /var/www/html/index.html
<html>
<body>
<center>Accueil du site par défaut</center>
</body>
</html>

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.

LAB #1 - Gestion de l'authentification avec OpenLDAP et mod_authnz_ldap

Vous devez maintenant utiliser mod_authnz_ldap pour protéger l'accès à votre site principal. Pour activer l'authentification en utilisant OpenLDAP sous apache 2.4, le module mod_ldap doit être installée :

[root@centos7 ~]# yum install mod_ldap

Pour installer le serveur OpenLDAP sous GNU/Linux ou Unix vous pouvez soit utiliser la version binaire fournie par les dépôts de paquets de votre distribution GNU/Linux ou Unix soit télécharger la dernière version à compiler du site d'OpenLDAP.

Dans notre cas, nous allons installer OpenLDAP à partir des dépôts. Commencez par installer OpenLDAP :

[root@centos7 ~]# yum install openldap-servers openldap-clients openldap

Sous CentOS le service OpenLDAP s'appelle slapd :

[root@centos7 ~]# systemctl status slapd.service
● slapd.service - OpenLDAP Server Daemon
   Loaded: loaded (/usr/lib/systemd/system/slapd.service; disabled; vendor preset: disabled)
   Active: inactive (dead)
     Docs: man:slapd
           man:slapd-config
           man:slapd-hdb
           man:slapd-mdb
           file:///usr/share/doc/openldap-servers/guide.html
[root@centos7 ~]# systemctl enable slapd.service
Created symlink from /etc/systemd/system/multi-user.target.wants/slapd.service to /usr/lib/systemd/system/slapd.service.
[root@centos7 ~]# systemctl start slapd.service
[root@centos7 ~]# systemctl status slapd.service
● slapd.service - OpenLDAP Server Daemon
   Loaded: loaded (/usr/lib/systemd/system/slapd.service; enabled; vendor preset: disabled)
   Active: active (running) since Sun 2017-11-05 12:39:40 CET; 6s ago
     Docs: man:slapd
           man:slapd-config
           man:slapd-hdb
           man:slapd-mdb
           file:///usr/share/doc/openldap-servers/guide.html
  Process: 28650 ExecStart=/usr/sbin/slapd -u ldap -h ${SLAPD_URLS} $SLAPD_OPTIONS (code=exited, status=0/SUCCESS)
  Process: 28632 ExecStartPre=/usr/libexec/openldap/check-config.sh (code=exited, status=0/SUCCESS)
 Main PID: 28653 (slapd)
   CGroup: /system.slice/slapd.service
           └─28653 /usr/sbin/slapd -u ldap -h ldapi:/// ldap:///

Nov 05 12:39:39 centos7.fenestros.loc systemd[1]: Starting OpenLDAP Server Daemon...
Nov 05 12:39:39 centos7.fenestros.loc runuser[28637]: pam_unix(runuser:session): session opened for user ldap by (uid=0)
Nov 05 12:39:39 centos7.fenestros.loc slapcat[28643]: DIGEST-MD5 common mech free
Nov 05 12:39:40 centos7.fenestros.loc slapd[28650]: @(#) $OpenLDAP: slapd 2.4.44 (Aug  4 2017 14:23:27) $
                                                            mockbuild@c1bm.rdu2.centos.org:/builddir/build/BUILD/openldap-2.4.../slapd
Nov 05 12:39:40 centos7.fenestros.loc slapd[28653]: hdb_db_open: warning - no DB_CONFIG file found in directory /var/lib/ldap: (2).
                                                    Expect poor performance for suffix "dc=my-domain,dc=com".
Nov 05 12:39:40 centos7.fenestros.loc slapd[28653]: slapd starting
Nov 05 12:39:40 centos7.fenestros.loc systemd[1]: Started OpenLDAP Server Daemon.
Hint: Some lines were ellipsized, use -l to show in full.

Configuration d'OpenLDAP

Créez le répertoire /var/lib/ldap/ittraining pour contenir un nouveau base de données :

[root@centos7 ~]# mkdir /var/lib/ldap/ittraining

Nettoyez les anciens fichiers de configuration et fichiers de données :

[root@centos7 ~]# rm -Rf /etc/openldap/slapd.d/*
[root@centos7 ~]# rm -f /var/lib/ldap/alock
[root@centos7 ~]# rm -f /var/lib/ldap/__db.00?

Créez le fichier /etc/openldap/slapd.conf :

[root@centos7 ~]# vi /etc/openldap/slapd.conf
[root@centos7 ~]# cat /etc/openldap/slapd.conf
include		/etc/openldap/schema/corba.schema
include		/etc/openldap/schema/core.schema
include		/etc/openldap/schema/cosine.schema
include		/etc/openldap/schema/duaconf.schema
include		/etc/openldap/schema/dyngroup.schema
include		/etc/openldap/schema/inetorgperson.schema
include		/etc/openldap/schema/java.schema
include		/etc/openldap/schema/misc.schema
include		/etc/openldap/schema/nis.schema
include		/etc/openldap/schema/openldap.schema
include		/etc/openldap/schema/ppolicy.schema
include		/etc/openldap/schema/collective.schema

allow bind_v2

pidfile		/var/run/openldap/slapd.pid
argsfile	/var/run/openldap/slapd.args

TLSCACertificatePath /etc/openldap/certs
TLSCertificateFile "\"OpenLDAP Server\""
TLSCertificateKeyFile /etc/openldap/certs/password

database config
access to *
	by dn.exact="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" manage
	by * none

database monitor
access to *
	by dn.exact="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" read
        by dn.exact="cn=Admin,o=fenestros" read
        by * none

###############################################
 
database	bdb
suffix		"o=ittraining"
checkpoint      1024 15
rootdn		"cn=Admin,o=ittraining"
rootpw          
directory	/var/lib/ldap/ittraining
lastmod         on
index           cn,sn,st		eq,pres,sub

Créez un mot de passe crypté pour l'admistrateur LDAP :

[root@centos7 ~]# slappasswd -s fenestros
{SSHA}RRo5UcZ9zzb2nYZuE5ZH+74u/Y2cyco2

Editez ensuite la section database du fichier /etc/openldap/slapd.conf :

...
database        bdb
suffix          "o=ittraining"
checkpoint      1024 15
rootdn          "cn=Admin,o=ittraining"
rootpw          {SSHA}RRo5UcZ9zzb2nYZuE5ZH+74u/Y2cyco2
directory       /var/lib/ldap/ittraining
lastmod         on
index           cn,sn,st                eq,pres,sub

Copiez le fichier /usr/share/openldap-servers/DB_CONFIG.example vers /var/lib/ldap/ittraining/DB_CONFIG :

[root@centos7 ~]# cp /usr/share/openldap-servers/DB_CONFIG.example /var/lib/ldap/ittraining/DB_CONFIG

Initialisez la première base de données :

[root@centos7 ~]# echo “” | slapadd -f /etc/openldap/slapd.conf
59ff01da The first database does not allow slapadd; using the first available one (2)
59ff01da str2entry: entry -1 has no dn
slapadd: could not parse entry (line=1)

Initialisez ensuite l'arborescence dans /etc/openldap/slapd.d :

[root@centos7 ~]# slaptest -f /etc/openldap/slapd.conf -F /etc/openldap/slapd.d
config file testing succeeded

Vérifiez que l'arborescence initiale soit créée :

[root@centos7 ~]# ls -l /etc/openldap/slapd.d
total 8
drwxr-x--- 3 root root 4096 Nov  5 13:20 cn=config
-rw------- 1 root root 1258 Nov  5 13:20 cn=config.ldif

Modifiez le propriétaire, le groupe ainsi que le droits du répertoire /etc/openldap/slapd.d :

[root@centos7 ~]# chown -R ldap:ldap /etc/openldap/slapd.d
[root@centos7 ~]# chmod -R u+rwX /etc/openldap/slapd.d

Modifiez le propriétaire et le groupe répertoire /var/lib/ldap/ittraining ainsi que le fichier /etc/openldap/slapd.conf :

[root@centos7 ~]# chown -R ldap:ldap /var/lib/ldap/ittraining /etc/openldap/slapd.conf

Démarrez ensuite le service slapd :

[root@centos7 ~]# systemctl restart slapd

Créez le fichier ittraining.ldif :

[root@centos7 ~]# vi ittraining.ldif
[root@centos7 ~]# cat ittraining.ldif
dn: o=ittraining
objectClass: top
objectClass: organization
o: ittraining
description: LDAP Authentification

dn: cn=Admin,o=ittraining
objectClass: organizationalRole
cn: Admin
description: Administrateur LDAP

dn: ou=GroupA,o=ittraining
ou: GroupA
objectClass: top
objectClass: organizationalUnit
description: Membres de GroupA

dn: ou=GroupB,o=ittraining
ou: GroupB
objectClass: top
objectClass: organizationalUnit
description: Membres de GroupB

dn: ou=group,o=ittraining
ou: group
objectclass: organizationalUnit
objectclass: domainRelatedObject
associatedDomain: ittraining

dn: cn=users,ou=group,o=ittraining
cn: users
objectClass: top
objectClass: posixGroup
gidNumber: 100
memberUid: jean
memberUid: jacques

dn: cn=Jean Legrand,ou=GroupA,o=ittraining
ou: GroupA
o: ittraining
cn: Jean Legrand
objectClass: person
objectClass: organizationalPerson
objectClass: inetOrgPerson
objectClass: posixAccount
objectClass: shadowAccount
objectClass: top
mail: jean.legrand@ittraining.loc
givenname: Jean
sn: Legrand
uid: jean
uidNumber: 1001
gidNumber: 100
gecos: Jean Legrand
loginShell: /bin/bash
homeDirectory: /home/jean
shadowLastChange: 14368
shadowMin: 0
shadowMax: 999999
shadowWarning: 7
userPassword: secret1
homePostalAddress: 99 avenue de Linux, 75000 Paris
postalAddress: 99 avenue de Linux.
l: Paris
st: 75
postalcode: 75000
telephoneNumber: 01.10.20.30.40
homePhone: 01.50.60.70.80
facsimileTelephoneNumber: 01.99.99.99.99
title: Ingénieur

dn: cn=Jacques Lebeau,ou=GroupA,o=ittraining
ou: GroupA
o: ittraining
cn: Jacques Lebeau
objectClass: person
objectClass: organizationalPerson
objectClass: inetOrgPerson
objectClass: posixAccount
objectClass: shadowAccount
objectClass: top
mail: jacques.lebeau@ittraining.loc
givenname: Jacques
sn: Lebeau
uid: jacques
uidNumber: 1002
gidNumber: 100
gecos: Jacques Lebeau
loginShell: /bin/bash
homeDirectory: /home/jacques
shadowLastChange: 14365
shadowMin: 0
shadowMax: 999999
shadowWarning: 7
userPassword: secret2
initials: JL
homePostalAddress: 99 route d'Unix, 75000 Paris
postalAddress: 99 route d'Unix.
l: Paris
st: 75
postalcode: 75000
pager: 01.04.04.04.04
homePhone: 01.05.05.05.05
telephoneNumber: 01.06.06.06.06
mobile: 06.01.02.03.04
title: Technicienne
facsimileTelephoneNumber: 01.04.09.09.09
manager: cn=Jean Legrand,ou=GroupA,o=ittraining

Injectez le fichier ittraining.ldif dans OpenLDAP :

[root@centos7 ~]# ldapadd -f ittraining.ldif -xv -D "cn=Admin,o=ittraining" -h 127.0.0.1 -w fenestros
ldap_initialize( ldap://127.0.0.1 )
add objectClass:
	top
	organization
add o:
	ittraining
add description:
	LDAP Authentification
adding new entry "o=ittraining"
modify complete

add objectClass:
	organizationalRole
add cn:
	Admin
add description:
	Administrateur LDAP
adding new entry "cn=Admin,o=ittraining"
modify complete

add ou:
	GroupA
add objectClass:
	top
	organizationalUnit
add description:
	Membres de GroupA
adding new entry "ou=GroupA,o=ittraining"
modify complete

add ou:
	GroupB
add objectClass:
	top
	organizationalUnit
add description:
	Membres de GroupB
adding new entry "ou=GroupB,o=ittraining"
modify complete

add ou:
	group
add objectclass:
	organizationalUnit
	domainRelatedObject
add associatedDomain:
	ittraining
adding new entry "ou=group,o=ittraining"
modify complete

add cn:
	users
add objectClass:
	top
	posixGroup
add gidNumber:
	100
add memberUid:
	jean
	jacques
adding new entry "cn=users,ou=group,o=ittraining"
modify complete

add ou:
	GroupA
add o:
	ittraining
add cn:
	Jean Legrand
add objectClass:
	person
	organizationalPerson
	inetOrgPerson
	posixAccount
	shadowAccount
	top
add mail:
	jean.legrand@ittraining.loc
add givenname:
	Jean
add sn:
	Legrand
add uid:
	jean
add uidNumber:
	1001
add gidNumber:
	100
add gecos:
	Jean Legrand
add loginShell:
	/bin/bash
add homeDirectory:
	/home/jean
add shadowLastChange:
	14368
add shadowMin:
	0
add shadowMax:
	999999
add shadowWarning:
	7
add userPassword:
	secret1
add homePostalAddress:
	99 avenue de Linux, 75000 Paris
add postalAddress:
	99 avenue de Linux.
add l:
	Paris
add st:
	75
add postalcode:
	75000
add telephoneNumber:
	01.10.20.30.40
add homePhone:
	01.50.60.70.80
add facsimileTelephoneNumber:
	01.99.99.99.99
add title:
	NOT ASCII (10 bytes)
adding new entry "cn=Jean Legrand,ou=GroupA,o=ittraining"
modify complete

add ou:
	GroupA
add o:
	ittraining
add cn:
	Jacques Lebeau
add objectClass:
	person
	organizationalPerson
	inetOrgPerson
	posixAccount
	shadowAccount
	top
add mail:
	jacques.lebeau@ittraining.loc
add givenname:
	Jacques
add sn:
	Lebeau
add uid:
	jacques
add uidNumber:
	1002
add gidNumber:
	100
add gecos:
	Jacques Lebeau
add loginShell:
	/bin/bash
add homeDirectory:
	/home/jacques
add shadowLastChange:
	14365
add shadowMin:
	0
add shadowMax:
	999999
add shadowWarning:
	7
add userPassword:
	secret2
add initials:
	JL
add homePostalAddress:
	99 route d'Unix, 75000 Paris
add postalAddress:
	99 route d'Unix.
add l:
	Paris
add st:
	75
add postalcode:
	75000
add pager:
	01.04.04.04.04
add homePhone:
	01.05.05.05.05
add telephoneNumber:
	01.06.06.06.06
add mobile:
	06.01.02.03.04
add title:
	Technicienne
add facsimileTelephoneNumber:
	01.04.09.09.09
add manager:
	cn=Jean Legrand,ou=GroupA,o=ittraining
adding new entry "cn=Jacques Lebeau,ou=GroupA,o=ittraining"
modify complete

Configuration d'Apache

Arrêtez le serveur Apache :

[root@centos7 ~]# systemctl stop httpd

Remplacez la section <Directory “/var/www/html”> du fichier /etc/httpd/conf/httpd.conf avec les lignes suivantes :

...
# <Directory "/var/www/html">
    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.4/mod/core.html#options
    # for more information.
    #
    # Options Indexes FollowSymLinks
    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   Options FileInfo AuthConfig Limit
    #
    # AllowOverride None
    #
    # Controls who can get stuff from this server.
    #
    # Require all granted
# </Directory>

<Directory "/var/www/html">
   AuthType Basic
   AuthName "LDAP Authentifaction"
   AuthBasicProvider ldap
   AuthLDAPURL ldap://localhost:389/o=ittraining?uid?sub
   AuthLDAPBindDN "cn=Admin,o=ittraining"
   AuthLDAPBindPassword fenestros
   require ldap-user jean jacques
   AllowOverride None
   Options Indexes FollowSymLinks
</Directory>
...

Re-démarrez le serveur apache :

[root@centos7 ~]# systemctl restart httpd

Connectez-vous à http://localhost en utilisant le compte de jean et le mot de passe secret1 :

[root@centos7 ~]# curl http://localhost
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>401 Unauthorized</title>
</head><body>
<h1>Unauthorized</h1>
<p>This server could not verify that you
are authorized to access the document
requested.  Either you supplied the wrong
credentials (e.g., bad password), or your
browser doesn't understand how to supply
the credentials required.</p>
</body></html>
[root@centos7 ~]#
[root@centos7 ~]# curl -u jean:secret1 http://localhost
<html>
<body>
<center>Accueil du site par défaut</center>
</body>
</html>

<html>

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

</html>

Menu