Linux connect to ldap server

Вики IT-KB

Пошаговые руководства, шпаргалки, полезные ссылки.

Инструменты пользователя

Инструменты сайта

Боковая панель

Утилита ldapsearch (клиент OpenLDAP) и проверка подключения к контроллеру домена Active Directory

Проверку выполняем на примере Debian GNU/Linux 8 (Jessie). Сначала убедимся в том, что клиент OpenLDAP установлен в системе:

Исходные данные для проверки подключения клиента OpenLDAP к LDAP-каталогу на примере контроллера домена Active Directory (AD):

Проверка подключения по протоколу LDAP (TCP 389)

Используется подключение типа ldap:/. Учётные данные пользователя s-LDAP-Check-User передаются по сети в открытом виде:

Проверка подключения по протоколу LDAPS (TCP 636)

Используется подключение типа ldaps:/. LDAP-сессия шифруется с помощью SSL-сертификата, предоставляемого контроллером домена. Чтобы LDAP-клиент доверял сертификату контроллера домена, нам нужно создать файл, содержащий корневые сертификаты доменных Центров сертификации, которыми подписан сертификат контроллера домена. Назовём этот файл, например /etc/ssl/certs/cacerts.pem, и скопируем в него корневые сертификаты доменных ЦС в формате PEM и кодировке Base-64.

Изменим на время проверки конфигурационный файл клиента OpenLDAP /etc/ldap/ldap.conf, указав в переменной TLS_CACERT путь к созданному нами файлу с корневыми сертификатами доменных ЦС:

После этого можно попробовать выполнить поиск по протоколу LDAPS:

Проверка подключения по протоколу LDAP с защитой StartTLS (TCP 389)

Используется подключение типа ldap:/ с дополнительными ключами, включающими TLS : -Z и -ZZ. LDAP-сессия также шифруется с помощью SSL-сертификата, предоставляемого контроллером домена. Первичное подключение к контроллеру домена AD происходит по порту 389, затем создаётся отдельный защищённый TLS-туннель, внутри которого и происходит весь LDAP-обмен между клиентом и сервером. Используется настроенный нами ранее файл корневых сертификатов доменных ЦС.

Автор первичной редакции:
Алексей Максимов
Время публикации: 19.03.2017 18:04

Источник

How to Configure LDAP Client to Connect External Authentication

LDAP (short for Lightweight Directory Access Protocol) is an industry standard, widely used set of protocols for accessing directory services.

A directory service in simple terms is a centralized, network-based database optimized for read access. It stores and provides access to information that must either be shared between applications or is highly distributed.

Directory services play an important role in developing intranet and Internet applications by helping you share information about users, systems, networks, applications, and services throughout the network.

A typical use case for LDAP is to offer a centralized storage of usernames and passwords. This allows various applications (or services) to connect to the LDAP server to validate users.

After setting up a working LDAP server, you will need to install libraries on the client for connecting to it. In this article, we will show how to configure an LDAP client to connect to an external authentication source.

I hope you already having a working LDAP server environment, if not setup Up LDAP Server for LDAP-based Authentication.

How to Install and Configure LDAP Client in Ubuntu and CentOS

On the client systems, you will needs to install a few necessary packages to make authentication mechanism function correctly with an LDAP server.

Configure LDAP Client in Ubuntu 16.04 and 18.04

First start by installing the necessary packages by running the following command.

During the installation, you will be prompted for details of your LDAP server (provide the values according to your environment). Note that the ldap-auth-config package which is auto-installed does the most of the configurations based on the inputs you enter.

Enter LDAP Server URI

Читайте также:  Как отображать расширение файлов windows

Next, enter the name of the LDAP search base, you can use the components of their domain names for this purpose as shown in the screenshot.

Enter LDAP Search Base

Also choose the LDAP version to use and click Ok.

Select LDAP Version

Now configure the option to allow you to make password utilities that use pam to behave like you would be changing local passwords and click Yes to continue..

Make Local Root Database Admin

Next, disable login requirement to the LDAP database using the next option.

Disable Login to LDAP Database

Also define LDAP account for root and click Ok.

Define LDAP Account for Root

Next, enter the password to use when ldap-auth-config tries to login to the LDAP directory using the LDAP account for root.

Enter LDAP Root Password

The results of the dialog will be stored in the file /etc/ldap.conf. If you want to make any alterations, open and edit this file using your favorite command line editor.

Next, configure the LDAP profile for NSS by running.

Then configure the system to use LDAP for authentication by updating PAM configurations. From the menu, choose LDAP and any other authentication mechanisms you need. You should now be able to log in using LDAP-based credentials.

Configure PAM Authentication Mechanism

In case you want the home directory of the user to be created automatically, then you need to perform one more configuration in the common-session PAM file.

Add this line in it.

Save the changes and close the file. Then restart the NCSD (Name Service Cache Daemon) service with the following command.

Note: If you are using replication, LDAP clients will need to refer to multiple servers specified in /etc/ldap.conf. You can specify all the servers in this form:

This implies that the request will time out and if the Provider (ldap1.example.com) becomes unresponsive, the Consumer (ldap2.example.com) will attempt to be reached to process it.

To check the LDAP entries for a particular user from the server, run the getent command, for example.

If the above command displays details of the specified user from the /etc/passwd file, your client machine is now configured to authenticate with the LDAP server, you should be able to log in using LDAP-based credentials.

Configure LDAP Client in CentOS 7

To install the necessary packages, run the following command. Note that in this section, if you are operating the system as a non-root administrative user, use the sudo command to run all commands.

Next, enable the client system to authenticate using LDAP. You can use the authconfig utility, which is an interface for configuring system authentication resources.

Run the following command and replace example.com with your domain and dc=example,dc=com with your LDAP domain controller.

In the above command, the —enablemkhomedir option creates a local user home directory at the first connection if none exists.

Next, test if the LDAP entries for a particular user from the server, for example user tecmint.

The above command should display details of the specified user from the /etc/passwd file, which implies that the client machine is now configured to authenticate with the LDAP server.

Important: If SELinux is enabled on your system, you need to add a rule to allow creating home directories automatically by mkhomedir.

For more information, consult the appropriate documentation from OpenLDAP Software document catalog.

Summary

LDAP, is a widely used protocol for querying and modifying a directory service. In this guide, we have shown how to configure an LDAP client to connect to an external authentication source, in Ubuntu and CentOS client machines. You can leave any questions or comments you may have using the feedback form below.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

Step-by-Step Tutorial: Configure LDAP client to authenticate with LDAP server

Table of Contents

This is a multi-part article where I will cover different areas of configuration of OpenLDAP server in CentOS 7 Linux node. You can use below links to refer different parts of this tutorial

Читайте также:  Установка veracrypt linux mint


Install Openldap client packages

First let us install all the required openldap client and dependent packages

Since we plan to use authconfig to configure ldap client for our RHEL/CentOS 7 Linux node, we only install SSSD and authconfig packages. oddjob-mkhomedir is required to be able to create active directory user’s home directory automatically.

Configure LDAP client to authenticate with LDAP server

Before you start make sure you copy /etc/openldap/cacerts/ca.cert.pem from the ldap-server to ldap-client in the same location under /etc/openldap/cacerts/ca.cert.pem . This key will be referred by the authconfig tool

Method 1: Using authconfig-tui

Configuring a client system to use an LDAP directory for user authentication is as easy as pie on a Fedora or RHEL system. Fedora has command-line utilities as well as GUI tools (for example, system-config-authentication , authconfig-gtk ) that make it easy.

One of the command-line tools is provided by the package authconfig . To launch the tool from the command line, type the following:

A screen similar to the one shown next will appear:

  • In the Authentication Configuration screen, navigate to (using TAB on your keyboard) and then select (using SPACEBAR on your keyboard) the following:
    Use LDAP → Under the User Information section
    Use LDAP Authentication → Under the Authentication section
  • Navigate to the Next button and press ENTER to select it.

  • Use the following information to complete the fields in the ensuing LDAP Settings screen:
    Server: ldap://10.0.2.20/
    Base DN: dc=example,dc=com
  • When we click OK, this will automatically change a series of files that otherwise would have to be changed by hand. For example, it will add the following lines to the /etc/openldap/ldap.conf file:

Method 2: Using authconfig CLI

You can also configure ldap on the client using authconfig as shown below

Configure OpenLDAP

Next configure your openldap client to communicate with the ldap server and the communication method. Add the below content in /etc/openldap/ldap.conf

Configure oddjob-mkhomedir to auto create home directories

We can use oddjob-mkhomedir to create home directories automatically for any ldap user which logs into the client node. This requires pam_mkhomedir.so provided by ddjob-mkhomedir which we had already installed earlier.

Modify the PAM configuration to use pam_oddjob_mkhomedir . For example, add this line at the bottom of /etc/pam.d/system-auth :

Next enable and start oddjobd.service

Instead of manual editing, the authconfig command can be used:

Also restart sssd.service

Create LDAP user (Optional)

You can ignore this step if you already a ldap user.

In order to authenticate as an LDAP user, when we create the user, we have to include a series of fields, such as shell, uid, gid, etc. As an example, let’s add the user testuser1 . We begin by creating the testuser1.ldif file, with the following content:

Create LDAP group (Optional)

You can ignore this step if you already a ldap group.

Also we will need a group for this testuser1 so I will add it to our existing OU » users «

Add user and group to LDAP database (Optional)

Add the users and groups to the ldap directory using the below commands

and then re-try the ldapadd command for user/group.

Validate the new user and group (Optional)

Run the ldapsearch command again and verify users and groups are listed under the base DN to complete the configuration.

Connect via LDAP User

Since we have installed oddjob , so we don’t need to create ldap user’s home directory manually and it will created during the first login of the user. Now we’ll be able to authenticate with an LDAP user

Conclusion

In this tutorial I shared the step by step instructions to configure LDAP client using RHEL/CentOS 7 Linux server. Additionally I have also shared the commands to create ldap user and group which you can use to verify your configuration. Since we are using oddjob, we don’t have the dependency to create ldap user’s home directory manually any more.

Lastly I hope the steps from the article to Configure LDAP client to authenticate with LDAP server on Linux was helpful. So, let me know your suggestions and feedback using the comment section.

References:

I have used below external references for this tutorial guide
Learn CentOS Linux Network Services

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

Читайте также:  Kmspico all windows office activator

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

34 thoughts on “Step-by-Step Tutorial: Configure LDAP client to authenticate with LDAP server”

While adding a user and group to LDAP database from client machine , I am getting the following error.
ldap_add: Invalid syntax (21)
additional info: objectClass: value #0 invalid per syntax
The same issue came in Server and there you said that “object inetOrgPerson isn’t loaded in the core schema”

I checked couple of forums and they claim that trailing white space can cause such errors, please check Why does this ldapadd command quit with an “Invalid syntax” error?

Yes I was aware of that space issues.
That’s why, I also tried by manually typing all the details in a new file.
But still, I am getting the same error. 🙁

I am afraid I also am not familiar with this error, once you manage to fix it please do share the troubleshooting steps as it may help others.

Yayyy!
I fixed it.
This was happening because the objects such as shadowAccount , top & person were not loaded in core schema. So I added nis.ldif file (which contains the above terms) using that ldapadd command.

I am glad you fixed it and thank you for sharing the solution.

Runnig this command gives below error
ldapadd -f testuser1.ldif -x -D cn=admin,dc=indiaeri,dc=com -w password
ldap_bind: Invalid credentials (49)

Please help over here

Can you try the steps from here for troubleshooting

How do we configure ldap client using SSSD in centos 8? What do we need under /etc/sssd/sssd.conf?

I will try to write an article on this in few days with all the steps.

Created new tutorial to configure ldap client on rhel/centos 8 using sssd
Please subscribe to get latest updates.

hey Admin how did u create testuser1 passwd on ldap server?
i tried : #slappasswd -s testuser1
it just provided me an encrypted password, it did not prompt me to enter the password…

-s is used to provide the password so here you are already providing your password i.e. testuser1 which then slappasswd uses to generate an encrypted form of your password. If you want an interactive output, just hit “ slappasswd ” on the console and it will prompt you for the password

I have a requirement to use, users from on-prem AD which has one-way trust with my cloud AD, where my VM will be domain joined.
In this scenario, i was able to domain join using ldap to my cloud AD but not able use the users from on-prem AD to login to the VMs.
Any directions please!

Great Articles! I followed these to the letter but still getting id: “testuser1: no such user”. Despite the ldapsearch command returning good with that very uid and all the rest of the ldap directory info. Is there anything we need to check with PAM to ensure this works? I also tried your linked SSSD article above to no avail. My setup has CentOS 6 openldap server with other Centos 6/7 clients (none of which can use the getent or id to query a known/existing ldap user. Tcpdump shows traffic hitting on the ldap ports. I inherited these servers from a previously admin who abandoned the effort. I’m thinking PAM or some other software is interfering and wondering if there is a way to clean-slate (used as verb here) just the authentication pieces. Rebuilding the whole network isn’t really an option because there are many other services at play. Thanks!

Are you able to query the user on ldap server?
If the issue is only ldap client then it could be come config issue or may be firewall/SELinux ?
Since you are on CentOS 6/7, you can check iptables, switch to permissive mode on SELinux and give a try

Thanks, I ended up re-installing the ldap server from scratch on Rocky Linux 8.4 and got things working (so far, even from the CentOS 6 clients that weren’t working before). I’ll repost if I come across anything. I appreciate the help!

Источник

Оцените статью