- Настройка и проверка LDAP
- Вики IT-KB
- Инструменты пользователя
- Инструменты сайта
- Боковая панель
- Утилита ldapsearch (клиент OpenLDAP) и проверка подключения к контроллеру домена Active Directory
- Проверка подключения по протоколу LDAP (TCP 389)
- Проверка подключения по протоколу LDAPS (TCP 636)
- Проверка подключения по протоколу LDAP с защитой StartTLS (TCP 389)
- How to Use ldapsearch Command Query with Examples
- 1) Query Ldap server and extract information
- 2) Query SSL / TLS
- 3) Search Specific Base DN and Scope
- 4) Read operation using file
- 5) Sort Result of Query
- 6) Limits, user-friendly and Non-character output
- 7) Persistent search
- 8) Virtual List View
- Test an LDAP connection
- Conclusion
- geekdudes
- Categories
- Archives
- Recent Posts
- Subscribe to Blog via Email
- Linux – Connecting to Windows LDAP over SSL (LDAPS) using certificate
- Creating Certificate templates
- Exporting Certification authority (CA) certificate
- Enrolling certificate to Domain Controller
- Exporting Domain controller certificate to Linux machine
- Exporting Trusted Root Certification authority (CA) certificate
- Testing LDAPS connection – Windows
- Testing LDAPS connection – Linux
- Apache – configuring LDAPS authentication
- Share this:
- Like this:
- Related
Настройка и проверка LDAP
Вопрос по LDAP, есть возможность проверить корректность работы его через команды? Также в systemctl status nslcd.service вижу
systemd[1]: Can’t open PID file /var/run/nslcd/nslcd.pid (yet?) after start: No such file or directory
Насколько это критичное сообщение?
А можно поподробнее, пожалуйста: 1. Какими командами можно проверить? 2. И как исправить, сам PID на месте, сервис находится в running. Проверял директорию, права выставлены root.
ldap — это база данных. Содержимое в нём может быть любое. В зависимости от того, что ты хочешь от ldap получить ты сможешь понять как его проверить. Ты тут об этом нам ничего не сказал.
Формулировка абстрактно «проверить корректность работы» совершенно, полностью абсолютно бессмысленная.
И как исправить, сам PID на месте
Тебе русским языком говорят, что
/var/run/nslcd/nslcd.pid
No such file or directory
Но тебе нужно чьё-то время занять, чтобы он тебе сказал что нет, не на месте?
Господи, куда всё катится.
вот тудысь и катитси. хотя нет, ты видать романтик неисправимый, оно уже прикатилось, и давно, а кое кто уже и обои поклеить успел.да.
Ну вот представь, что он себе авторизацию какого-то сервиса прикручивает, или пытается поднять упавшую.
Вопрос, что ты этой командой проверил? Что у тебя slapd запущен и что-то отвечает? Это типа ты «корректность работы» проверил?)
Это типа ты «корректность работы» проверил?)
ну каков вопрос, такой и ответ)) Я лишь усугубил твоё брюзжание «кудыть катимси», этакая рекурсия без проверки условия. А так — проверка из ряда «оно хоть живое?». Ну а что ещё можно посоветовать то? Ну не хотят они ничего читать, про понимание вообще помолчу, куды бедному крестьянину податься.
А ты я смотрю мастер за моником рассказывать, что Земля не квадратная. Я пришел на форум, за помощью к профессионалам своего дела т.к. из других источников не нашел подходящих ответов. А ты тут устроил холивар. Сразу складывается о тебе первое впечатление (профессионал, своего дела).
Тебе русским языком говорят, что
/var/run/nslcd/nslcd.pid
No such file or directory
Я не слепой и видел, у меня процесс на месте, также как и права, а не пустая директория.
Спасибо за помощь, а тебе отдельное Удачи по жизни!!
к профессионалам за деньги приходят, я что-то денег от тебя не видел.
к профессионалам за деньги приходят, я что-то денег от тебя не видел.
Ну и профессионального ответа, чет я от тебя и не услышал как бы!
Ответ на уровне джуниор был)
Ошибку эту можно игнорить — это багофича systemd.
На многих юнитах вылезает, не только на nslcd.
Systemd пытается открыть PID-файл до того, как приложение его создаст. На что намекает слово yet в скобочках в самом сообщении: «(yet?)». Если приложение стартует, то не обращай внимания.
Источник
Вики 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 Use ldapsearch Command Query with Examples
In this article, we will consider one of the main LDAP utilities — ldapsearch. It’s a shell-accessible interface that opens a connection to the specified LDAP server using the specified distinguished name and password and locates entries base on a specific search filter, parameters and options.
Before you start, please make sure you have installed and successfully configured LDAP server. If you do not have LDAP installed, please refer to simple installation guide (please skip Mirror-mode configuration part).
1) Query Ldap server and extract information
Below three commands will query and extract all entries from LDAP server
So, all three commands will give the same output:
2) Query SSL / TLS
In order to use LDAP Uniform Resource Identifier (URI), you need to user -H flag that specifies a URI to use to connect to the server and port in the following format: ldap[s]://hostname[:port]
The port is optional, it will use default LDAP of 389 or LDAPS port of 636 if the port is not given. The output will be all your LDAP database.
3) Search Specific Base DN and Scope
Now, we will try to search for specific base distinguish name and scope.
The output of the command above will be the base distinguish name of ou=users,ou=department,dc=example,dc=com scope.
In case of the same base dn and subtree scope search you will get everything (all subtrees) that goes under the ou=users,ou=department,dc=example,dc=com tree. In our case, you will get both entries for admins:
4) Read operation using file
Moving forward, we will use ldapsearch utility together with a file. Please create a file with following content:
Now, you need to run the command:
Please note, that it will give the same output as:
5) Sort Result of Query
In this topic, we will consider main input and output options. To start with, we will sort the results of our query by attribute ‘uidnumber’
As we see, -S flag sorts the result by defined attribute. Since in our case we have only 2 entries, the output was sorted by uidnumber = 5001 and 5002.
6) Limits, user-friendly and Non-character output
In the next example, we will specify the maximum number of entries to return in response to a search request (-z flag), then we will include User-Friendly name form of the Distinguish Name in the output (-u flag) and the jpegPhoto and audio values will be retrieved and written to temporary files (-t «()» jpegPhoto audio). Unfortunately, in our example, we don’t have such attributes, but If you had those, you would get the following output:
-t flag is useful for dealing with values containing non-character data such as photo or audio. It will generate a temporary file output, each attribute of each entry will be written to a separate file in the system’s temporary directory, usually it is /tmp/.
7) Persistent search
A persistent search leave the search operation open after the command outputs are returned. This allows the entries returned in the search to remain in cache and updates to be transmitted and included as they occur. This remains open until the client closes the connection with ctrl-c key.
-C flag will run the search as a persistent search. ps:changeType specifies which type of changes to entries allow the entry to be returned (add/delete/modify/moddn/all). changesOnly sets whether to return all existing entries which match the search filter or return modified entries. By default, it will return modified entries. entryChangeControls sets whether to send entry change controls, additional information about the modification made to the entry. If the value set to 0, then only the entry is returned, if set to 1, then a line is added to the entry as it is returned to the search that lists the changeType performed on the entry. Default value is 1.
8) Virtual List View
In next example, we will try to extract only a portion of results with -G flag. So-called, virtual list view always requires -S and -x flags to specify sorting order. entriesBefore:entriesAfter:value — specify the search target as the first entry in the results for which the sort attribute is > or = to the given value. Since we do not have much entries in our LDAP, we will consider an example. For instance,
Would give us 6 entries in uidnumber order. 2 entries before admin1, the entry equal to or following admin1, and the 3 subsequent entries.
Test an LDAP connection
You can bind to your LDAP directory server by running this ldapsearch command from the client/server. I run this command from my client machine to my LDAP server and save the details in a text file.
We can even use this command to return all entries in our preferred directory service using filters as below.
Conclusion
In this article, we have used ldapsearch utility options for querying LDAP database. This tool tends to be very foreign to users when they first encounter them. However, with the mentioned command you can completely direct your search to return the exact data that you require.
Источник
geekdudes
Categories
Archives
Recent Posts
Subscribe to Blog via Email
Linux – Connecting to Windows LDAP over SSL (LDAPS) using certificate
By default, LDAP communications (port 389) between client and server applications are not encrypted. This means that it would be possible to use a network monitoring device or software and view the communications traveling between LDAP client and server computers. LDAP over SSL/TLS (LDAPS-port 636) is automatically enabled when you install an Public key (PKI) infrastructure, (Certificate Authority-CA). In this post i wan’t cover installing and configuring PKI infrastructure, i’ll concentrate on enabling LDAPS on windows and configuring secure connection to Windows Domain controllers from linux machines using SSL certificates.
Creating Certificate templates
On Issuing certificate authority, in Certification authority console right click on Certificate templates-Manage
Certification Templates console will launch, right click on template Kerberos Authentication-duplicate template
In compatibility tab,make sure that for Compatibility settings Windows Server 2003 is specified
In Request handling tab, make sure Signature and encryption is selected for purpose
If you plan to import the certificate into the Active Directory Domain Services certificate store, then should also mark the private key as exportable.
In general tab, specify validity period and template name
In subject name tab make sure DNS name and Service principal nane (SPN) are checked in.
In security tab, make sure Domain controllers are added and Enroll, Read and Autoenroll (if you want this template is enrolled automatically) are set to Allow
Once all is set click OK, right click Certificate Templates-New-Certificate Template to Issue
Select template and click OK
Exporting Certification authority (CA) certificate
On CA machine we issued certificate, name of this CA will be written in that certificate, so we need to export personal certificate of this CA and transfer it to Linux machine.This certificate will be used to validate certificate of Domain controller we are going to enroll in next steps.
Open Local computer certificate store (start-run- certlm.msc )
Expand Personal,right click on Certificates-All tasks-Export
Select No, do not export private key, for format select Base-64 encoded X.509 (.CER)
Save certificate to file with cer extension and move it to Linux machine
Enrolling certificate to Domain Controller
Now we need to enroll Certificate we just issued on Certification Authority machine.Go to Domain controller,open Local computer certificate store (start-run- certlm.msc )
Expand Personal,right click on Certificates-All tasks-Request New Certificate
Click Next twice and select certificate we just issued-Enroll
Exporting Domain controller certificate to Linux machine
Now we need to export this enrolled certificate to Linux machine.
Right click on certificate we just enrolled-All tasks-Export
Select No, do not export private key, for format select Base-64 encoded X.509 (.CER)
Save certificate as cer file and move it to linux machine
Exporting Trusted Root Certification authority (CA) certificate
In case you’re using intermediate CA (as in my case), you need to export Trusted Root certification authority certificate also, again, in Computer certificate store, expand Trusted root certification authorities-click Certificates-right click om Root certificate-export
Export in same way as in previous steps
Testing LDAPS connection – Windows
Before moving to linux, let’s first test LDAP over SSL connection.
On Domain controler from command prompt, type ldp.exe , click on Connection tab-Connect..
Type DNS name, port 636, check SSL and click OK
If all is OK, connection should be sucessfull
Testing LDAPS connection – Linux
Certification authority certificate is exported to /etc/pki/tls/certs/issuingca.cer ,domain controller certificate is exported to /etc/pki/tls/certs/dc.cer and trusted root CA to /etc/pki/tls/certs/ca.cer
Add CA Root and issuing CA certs to Linux (CentOS) ca store
Apache – configuring LDAPS authentication
Share this:
Like this:
Related
Thank you for adding this very helpful
hi and thank you for that guide. I still have trouble connecting from my Linux-Machine to my Windows AD DC. My test environment consist of one Certifaction Authority which provides Self-Signed Certs. Then i have 2 Dmaincontroller where the Ports 636 are listening. every Windowsmachine in my Network already talks via LDAP over SSL but i cant connect my Linux-Machines. I already imported the root and dc certs to my local trusted store of the Linux-Machine, but everytime i want to test the connection i get an Error:
My Input on Linux Mint: openssl s_client -connect hostname.dc1.net:636
and the Output is:
CONNECTED(00000003)
write:errno=104
—
no peer certificate available
—
No client certificate CA names sent
—
SSL handshake has read 0 bytes and written 247 bytes
—
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
—
you didn’t import CA certs to linux machine
Thank you for that fast Reply. In my ca-certificates.crt file are both, the root.crt and the dc.crt.
in previous question you mentioned “My test environment consist of one Certifaction Authority which provides Self-Signed Certs”. Maybe that’s the issue. What “self-signed” means?. On CA machine just create CA template as i did.
Test you CA infrastructure in following way:
Install IIS on your DC, enroll cert to your DC. Assign cert to IIS and from DC access default web page by using HTTPS, if your’re not getting “invalid cert” in web browser then, on some test machine, import CA and DC cert and try accessing again web page on DC.If not getting “invalid certificate” error, then no reason why it shouldn’t work from linux
Also, thanks very much and I hope you can help clarify and resolve the issues I still see in my setup:
* Windows Root-CA. Exported as described and saved to myca.cer
* Windows Domain Controller. Exported as described and saved to mydc.cer
both files are imported and verified fine on my Linux client but openssl s_client shows a similar response to what ANUB1S wrote.
Updating certificates …
Doing .
2 added, 0 removed; done.
Running hooks in /etc/ca-certificates/update.d…
done.
openssl verify /etc/ssl/certs/myca.pem
/etc/ssl/certs/myca.pem: OK
openssl verify /etc/ssl/certs/mydc.pem
/etc/ssl/certs/mydc.pem: OK
openssl s_client -connect mydc:636 -CAfile /etc/ssl/certs/myca.pem # same when using mydc.pem
CONNECTED(00000005)
write:errno=104
—
no peer certificate available
—
No client certificate CA names sent
—
SSL handshake has read 0 bytes and written 317 bytes
Verification: OK
—
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
Early data was not sent
Verify return code: 0 (ok)
—
In your instructions you mention exporting 3 certificates: CA, DC and intermediate, but on your linux you seem to never use the dc.cer anywhere? I’m not using an intermediate CA.
My Linux machine is not a member in the domain, if that’s important.
How to resolve/fix the
no peer certificate available
no client certificate CA names sent
Thanks very much in advance!
It seems as certificate is not properly installed on Domain controller or that cert is invalid. Make sure you created Certificate template from Kerberos Authentication template, instead of FQDN of Domain controller, i used just domain name in Apache config file.
Источник