Ldap search error no such object

I'm new to LDAP so I will try to explain correctly I have a hostname "energia.sise" I need to get all users which are located in energia.sise/nej/users could you advise me how to do that? in thi...

Update

UPDATE: Using the LDAP Browser Free edition (Check it out here) was good because you can simply browse through the LDAP server, it helps you understand if you can bind anonymous etc. etc. But the biggest benefit was to get the DN (copy and paste). After that I was able to read the data.

I had the following issues and that’s how I resolved:

Problem 1

  • Problem 1: Can’t bind even though I could connect anonymously through the LDAP Browser Software

  • Solution: added the following lines before the bind as suggested above:

    ldap_set_option( $ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3 );
    ldap_set_option( $ldapconn, LDAP_OPT_REFERRALS, 0 );
    

    After this I was able to bind…

Problem 2

  • Problem 2: Can’t Search…

  • Solution: Open the LDAP browser. Check connectivity to make sure you can connect to the LDAP server. Browse an example record. Right click and goto Properties and copy the DN and replace it in the code and that’s it!


Original Post shown below:

I can’t seem to search and I am using LDAP Browser 4.5 Free edition to make sure everything is working…

This is my Code:

function ldap_anon_connect($ein){

    $ldaphost = "ldap://link_to_ldap.com";

    //create a connection to ldap server
    $ldapconn = ldap_connect($ldaphost) or die("Couldn't connect to " .$ldaphost);
        if ($ldapconn) {

            ldap_set_option( $ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3 );
            ldap_set_option( $ldapconn, LDAP_OPT_REFERRALS, 0 );

            $ldapbind = ldap_bind($ldapconn);
            if ($ldapbind) {

                // if binds, look some stuff up
                $info = ldap_annon_get_profile($ein, $ldapconn);
                return $info;
             } 
             else{
                echo "Invalid EIN. Please Try again";
                die();
             }

    }

}

function ldap_annon_get_profile($ein, $ldapconn){

        $filter = "(cn=".$ein.")";

    $justthese = array(
                                "cn","sn","givenName","displayName","mail","EmployeeClass","ManagerEIN",
                                "mobile","title","c","PersonalTitle"
                );

                $sr = ldap_search($ldapconn, "o=CO,ou=COplc,ou=people", $filter, $justthese);
                        $info = ldap_get_entries($ldapconn, $sr);

                        return $info;

    }

I have double checked my DN=»o=CO,ou=COplc,ou=people» this is the right string as I can lookup the stuff at LDAP Browser…

Any ideas?

Update

UPDATE: Using the LDAP Browser Free edition (Check it out here) was good because you can simply browse through the LDAP server, it helps you understand if you can bind anonymous etc. etc. But the biggest benefit was to get the DN (copy and paste). After that I was able to read the data.

I had the following issues and that’s how I resolved:

Problem 1

  • Problem 1: Can’t bind even though I could connect anonymously through the LDAP Browser Software

  • Solution: added the following lines before the bind as suggested above:

    ldap_set_option( $ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3 );
    ldap_set_option( $ldapconn, LDAP_OPT_REFERRALS, 0 );
    

    After this I was able to bind…

Problem 2

  • Problem 2: Can’t Search…

  • Solution: Open the LDAP browser. Check connectivity to make sure you can connect to the LDAP server. Browse an example record. Right click and goto Properties and copy the DN and replace it in the code and that’s it!


Original Post shown below:

I can’t seem to search and I am using LDAP Browser 4.5 Free edition to make sure everything is working…

This is my Code:

function ldap_anon_connect($ein){

    $ldaphost = "ldap://link_to_ldap.com";

    //create a connection to ldap server
    $ldapconn = ldap_connect($ldaphost) or die("Couldn't connect to " .$ldaphost);
        if ($ldapconn) {

            ldap_set_option( $ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3 );
            ldap_set_option( $ldapconn, LDAP_OPT_REFERRALS, 0 );

            $ldapbind = ldap_bind($ldapconn);
            if ($ldapbind) {

                // if binds, look some stuff up
                $info = ldap_annon_get_profile($ein, $ldapconn);
                return $info;
             } 
             else{
                echo "Invalid EIN. Please Try again";
                die();
             }

    }

}

function ldap_annon_get_profile($ein, $ldapconn){

        $filter = "(cn=".$ein.")";

    $justthese = array(
                                "cn","sn","givenName","displayName","mail","EmployeeClass","ManagerEIN",
                                "mobile","title","c","PersonalTitle"
                );

                $sr = ldap_search($ldapconn, "o=CO,ou=COplc,ou=people", $filter, $justthese);
                        $info = ldap_get_entries($ldapconn, $sr);

                        return $info;

    }

I have double checked my DN=»o=CO,ou=COplc,ou=people» this is the right string as I can lookup the stuff at LDAP Browser…

Any ideas?

C. Распространённые ошибки при использовании программного обеспечения OpenLDAP

В следующих подразделах предпринята попытка обобщить наиболее распространённые причины ошибок LDAP при использовании OpenLDAP.

Ошибка Can’t contact LDAP server обычно возвращается, когда к серверу LDAP невозможно подключиться. Такое может произойти по многим причинам:

  • Сервер LDAP не запущен; это можно проверить, запустив, например,

заменяя и именем хоста и портом, на котором сервер должен принимать запросы.

  • клиенту не сообщили, как соединиться с работающим сервером; при использовании инструментов командной строки OpenLDAP это достигается путём предоставления параметра -H, аргумент которого — корректный LDAP url, соответствующий интерфейсу, на котором сервер должен принимать запросы.

Ошибка no such object обычно возвращается, когда невозможно найти целевой DN операции. В этом подразделе описаны причины, общие для всех типов операций. Необходимо также искать частные причины для конкретных типов операций (указанных в сообщении об ошибке).

Наиболее распространённой причиной этой ошибки является то, что объекта с таким именем не существует. Прежде всего, проверьте наличие опечаток.

Также имейте в виду, что по умолчанию вновь созданный сервер каталогов не содержит объектов (за исключением нескольких системных записей). Таким образом, если Вы настроили новый сервер каталогов и получили такое сообщение, то это может попросту означать, что Вы еще не добавили объект, который пытаетесь найти.

Обычно такая ошибка возникает, когда при запросе не указан базовый DN поиска, а значение по умолчанию не было корректно настроено.

Если, например, в slapd.conf Вы определили суффикс

то Вам нужно использовать параметр -b

чтобы указать утилите, где начинать поиск.

Параметр -b должен быть указан для всех команд LDAP, если Вы не настроили значение по умолчанию в ldap.conf (5).

Подробнее об этом смотрите в ldapsearch (1), ldapmodify (1).

Кроме того, slapadd (8) и её вспомогательные команды очень строго относятся к синтаксису файла LDIF.

Если в файле LDIF допущены некоторые вольности, то в результате его обработки может создаться видимость успешного создания базы данных, однако доступ к некотором частям этой базы может быть затруднён.

Одна из известнейших распространённых ошибок при создании базы данных — помещение пустой строки перед первой записью в файле LDIF. В начале файла LDIF не должно быть пустых строк.

При добавлении новых записей в каталог в общем случае рекомендуется использовать ldapadd (1) вместо slapadd (8). slapadd (8) нужно использовать для загрузки большого количества записей достоверно правильного формата.

Другой причиной появления этого сообщения может быть запись referral (смотрите Построение распределённой службы каталогов), ссылающаяся на незаполненный каталог.

В таком случае либо удалите эту запись referral, либо добавьте одну запись с базовым DN, на который ссылается referral, в пустой каталог.

Также данная ошибка может возникнуть, если slapd не может получить доступ к своим базам данных из-за проблем с правами на файлы. Например, в системе Red Hat Linux slapd запускается от имени пользователя ‘ldap’. Если при создании базы данных с нуля slapadd был запущен от root, файлы в директории /var/lib/ldap будет созданы с владельцем и группой root и правами 600, делая тем самым содержимое каталога недоступным для сервера slapd.

Причиной этого является строка

в slapd.conf . В оригинальном файле данная строка помещена как пример использования объектов referrals. Однако, если Ваша машина не подключена к Internet постоянно, она не сможет найти этот сервер, и, как следствие, выводит данное сообщение об ошибке.

Чтобы решить эту проблему, просто поместите # в начало данной строки и перезапустите slapd, либо направьте его на доступный сервер LDAP.

Смотрите также ldapadd (1), ldapmodify (1) и slapd.conf (5)

slapd вернёт ошибку unwilling to perform, если механизм манипуляции данными, содержащий целевую запись, не поддерживает запрошенную операцию.

Механизм манипуляции данными password может выполнять только поиски. Он будет возвращать ошибку unwilling to perform для всех остальных операций.

Механизм манипуляции данными shell является настраиваемым и может поддерживать ограниченное подмножество операций. Проверьте также другие ошибки, свидетельствующие о нехватке ресурсов, необходимых для сервера каталогов, например, у Вас может быть переполнен диск и т.п.

Эта ошибка возникает, когда сервер запрещает операцию из-за недостаточных прав доступа. Обычно это происходит из-за подключения от имени DN, не обладающего достаточными привилегиями для выполнения операции (либо анонимного подключения).

Для получения полного доступа Вы можете подсоединиться от имени rootdn/rootpw, указанных в slapd.conf (5). В противном случае, Вы должны выполнять подключение от имени записи, которой предоставлены соответствующие права при настройке контроля доступа.

Целевой (или другой) DN операции является неверным. Это означает, что либо строковое представление DN не соответствует требуемой форме, один из типов в утверждениях значений атрибута не определён, либо одно из значений в утверждениях значений атрибута не соответствует требуемому синтаксису.

Обычно эта ошибка возникает, когда клиент переходит по ссылке на сервер, который в свою очередь возвращает ему ссылку обратно на тот сервер, с которым он уже связывался. Этот сервер вновь отвечает также, как и в прошлый раз, и клиент зацикливается. Зацикливание обнаруживается, когда превышается лимит переходов.

Чаще всего причиной этого является неправильная настройка ссылки по умолчанию сервера. Ссылка по умолчанию не должна указывать на сам сервер, то есть на сервере ldap://myldap/ ссылка по умолчанию не должна указывать на ldap://myldap/ (или любое имя хоста/ip-адрес, эквивалентный myldap).

В некоторых версиях slapd (8), ошибка operationsError выдавалась вместо других.

В результате выполнения операции был возвращен нестандартный код неудачного завершения, свидетельствующий о внутренней ошибке. Возможно, проблему прояснит дополнительная информация, предоставляемая с кодом возврата, однако, скорее всего, придётся просматривать файлы журнала сервера.

Сообщение об этой ошибке поступает, когда значение атрибута не соответствует ограничениям синтаксиса. Обычно в сопутствующей дополнительной информации даётся указание, какое значение и какого именно атрибута определено как неверное. Дважды проверьте это значение и другие значения, поскольку сервер выдаёт сообщение только о первой найденной им ошибке.

Типичные причины возникновения:

  • посторонние пробелы (особенно конечные пробелы);
  • символы в неправильной кодировке (LDAPv3 использует кодировку Unicode UTF-8);
  • пустые значения (лишь немногие синтаксисы позволяют оставлять значения пустыми).

Для некоторых синтаксисов, таких как OBJECT IDENTIFIER (OID), данная ошибка свидетельствует о том, что предоставленный дескриптор («короткое название») OID не распознан. Например, данная ошибка возвращается, если предоставленное значение objectClass не распознано.

Данная ошибка возвращается, когда добавляемая или изменяемая запись нарушает правила схемы объектного класса. Обычно в сопутствующей дополнительной информации данное нарушение детализируется. Ниже приведены некоторые информационные сообщения и описание причин их появления.

Нарушения, связанные с атрибутами записей:

Предоставленный атрибут не разрешён объектным классом (классами) записи.

Атрибут, обязательный для объектного класса (классов) записи, не был предоставлен.

Нарушения, связанные с классом (классами) записи:

В записи не указано, к какому объектному классу она принадлежит.

Одно (или несколько) из перечисленных значений атрибута objectClass не распознано.

Ни одно из перечисленных значений атрибута objectClass не является структурным объектным классом.

Два или более структурных объектных класса в значениях атрибута objectClass не принадлежат одной и той же цепочке структурного объектного класса.

Попытка изменить структурный объектный класс записи в ходе операции модификации.

Абстрактный класс не подчиняется ни одному из перечисленных структурных или вспомогательных классов.

Другая проблема со структурным объектным классом.

Данное сообщение обычно возвращается, когда теневой сервер предоставляет запись, не содержащую операционного атрибута structuralObjectClass.

Имейте в виду, что приведённые выше сообщения об ошибке и их описания предполагают наличие базовых знаний о схемах LDAP/X.500.

Ошибка «ldap_add: No such object» обычно возвращается, когда не существует родительской записи для той записи, которую хотят добавить. Сначала добавьте родительскую запись.

Например, если при добавлении «cn=bob,dc=domain,dc=com» Вы получаете:

похоже, что запись «dc=domain,dc=com» не существует. Проверьте, существует ли она, с помощью ldapsearch:

Если нет, добавьте её. Если нужна помощь, обратитесь к Руководству по быстрому развёртыванию и началу работы.

Примечание: если добавляемая запись совпадает с суффиксом базы данных, наличие родительской записи не требуется. Например, если Ваш суффикс — «dc=domain,dc=com», для добавления «dc=domain,dc=com» не требуется наличия «dc=com».

Также данная ошибка возникает, когда Вы пытаетесь добавить какую-либо запись, на хранение которой Ваш сервер не сконфигурирован.

Например, если суффикс Вашей базы данных — «dc=domain,dc=com» и Вы попытаетесь добавить «dc=domain2,dc=com», «dc=com», «dc=domain,dc=org», «o=domain,c=us», или какой либо другой DN в поддереве «dc=domain,dc=com» (не добавив предварительно саму эту запись), сервер вернёт ошибку «No such object» (либо отсылку).

slapd (8) обычно возвращает «no global superior knowledge» в качестве дополнительной информации, указывая, почему он вернул noSuchObject вместо отсылки. То есть в настройках сервера не было дано информации о глобальном вышестоящем сервере.

Данная ошибка относится к правилу о СТРУКТУРНЫХ объектных классах, которое утверждает, что объект может иметь только один СТРУКТУРНЫЙ класс, структурный класс данного объекта. Говорят, что объект принадлежит этому классу, нулю или более вспомогательным классам и их суперклассам.

Хотя все эти классы обычно перечислены в атрибуте objectClass записи, один из этих классов является структурным объектным классом записи. Таким образом, считается нормальным для атрибута objectClass иметь значения inetOrgPerson, organizationalPerson и person, поскольку они наследуются один от другого в форме одной цепочки суперкласса. То есть, inetOrgPerson наследуется от organizationPerson, который в свою очередь наследуется от person. С другой стороны, неверным будет перечислить в атрибуте objectClass сразу inetOrgPerson и account, поскольку inetOrgPerson и account не являются частью одной и той же цепочки суперкласса (если только вместе с ними не перечислен какой-то другой класс, являющийся подклассом от обоих).

Для решения этой проблемы необходимо определить, какой из классов будет лучше использовать в качестве структурного объектного класса для данной записи, добавить этот класс в атрибут objectClass (если он ещё не добавлен), и убрать из атрибута objectClass записи все остальные структурные классы, не являющиеся суперклассом для данного структурного объектного класса.

Какой объектный класс лучше использовать, зависит от конкретной ситуации. В общем случае, нужно проконсультироваться с документацией по тому приложению, которое использует данный объект из Вашего каталога. Скорее всего, это поможет сделать выбор.

ldapadd(1) может выдать ошибку:

если slapd(8) не может определить на основании содержимого атрибута objectClass, какой должен быть структурный объектный класс.

OpenLDAP slapd проверяет целостность атрибутов именования и отличительных значений в соответствии с RFC4512 (рус.) .

Атрибуты именования — это атрибуты тех типов, которые присутствуют в RDN записи; отличительные значения — это значения атрибутов именования, которые присутствуют в RDN записи, например, в записи

атрибуты именования — cn и mail, а отличительные значения — Someone и someone@example.com.

OpenLDAP slapd проверяет целостность когда:

  • добавляется запись;
  • изменяется запись, если при этом изменяются значения атрибутов именования;
  • переименовывается запись, если при этом изменяется RDN записи.

Возможные причины появления ошибки:

  • атрибуты именования не присутствуют в записи, например:

  • атрибуты именования присутствуют в записи, но те типы атрибутов, которыми они определены, помечены как:
    • коллективные;
    • операционные;
    • устаревшие.
  • атрибуты именования присутствуют в записи, а отличительные значения — нет, например:

  • атрибуты именования присутствуют в записи вместе с отличительными значениями, но атрибуты именования:
    • не имеют поля равенства (equality field), вследствие чего невозможно утверждать равенство;
    • не поддерживают правило соответствия (возможно, пока);
    • не удовлетворяют правилу соответствия.
  • предоставленные отличительные значения не соответствуют установленному для них синтаксису.
  • другие ошибки, возникающие в процессе проверки/нормализации/сравнения; даже если Вам не подошел ни один из описанных выше вариантов, ситуация может проясниться при просмотре файлов журнала.

В любом случае, убедитесь, что определение типа атрибута для атрибута именования содержит соответствующее поле EQUALITY; либо же поле EQUALITY содержит вышестоящий тип атрибута, если определение данного типа атрибута основано на вышестоящем типе (смотрите поле SUP). Подробности можно найти в RFC4512 (рус.) .

Если имя целевой записи указывает, что она должна быть размещена в поддереве, на обслуживание которого не настроена ни одна из баз данных сервера, и, при этом, у сервера нет сведений о глобальной вышестоящей части дерева, сервер покажет, что он не желает выполнять операцию и выдаст «no global superior knowledge» в качестве дополнительного текста.

Возможно, допущена ошибка в имени записи, либо сервер должен хранить записи с таким именем, но был неверно настроен, либо, если каталог распределённый, не была настроена отсылка по умолчанию.

В текущих версиях slapd(8) перед тем, как допустить клиентов к выполнению операции подключения, требуется, чтобы у них были права на аутентификацию к тем типам атрибутов, которые используются в целях аутентификации. Поскольку все операции подключения выполняются анонимно (независимо от предыдущих успешных подключений), пользователю anonymous должны быть предоставлены права доступа auth.

В приведённом ниже примере ACL предоставляются следующие права доступа:

  • анонимным пользователям:
    • права на прохождение аутентификации с использованием значений атрибута userPassword
  • аутентифицированным пользователям:
    • права на обновление (но не чтение) своих собственных значений атрибута userPassword
    • права на чтение любого объекта, за исключением значений атрибута userPassword

Весь остальной доступ запрещён.

Данная ошибка обычно возникает, когда предоставленные учётные данные (пароль) не совпадают с хранимыми в атрибуте userPassword той записи, от имени которой Вы пытаетесь подключиться.

Также данная ошибка может возникнуть, когда указанный при подключении DN неизвестен тому серверу, к которому Вы пытаетесь подключиться.

Проверьте и то, и другое! Кроме двух вышеуказанных причин, проверьте также, не запрещён ли доступ к атрибутам userPassword в выбранной части каталога. Фактически, slapd всегда возвращает «Invalid credentials» в случае неудачной попытки подключения, независимо от причины неудачи, поскольку другие коды возврата могут помочь злоумышленнику выяснить, правильное ли имя пользователя он предоставляет.

Для отладки правил доступа, определённых в slapd.conf, добавьте уровень журналирования «ACL».

Данная ошибка обычно возникает, когда запрашиваемая клиентом версия LDAP не поддерживается сервером.

Сервер OpenLDAP 2.x по умолчанию принимает запросы на подсоединение только LDAP версии 3, но может быть настроен для приёма запросов на подсоединение LDAP версии 2.

Примечание: если клиент запрашивает 3-ю версию протокола, сервер OpenLDAP 2.x ожидает, что будет использоваться LDAPv3 [RFC4510], если же запрашивается 2-я версия протокола, сервер ожидает, что будет использоваться ограниченный вариант LDAPv3 (в основном, синтаксис и семантика LDAPv3 в PDU LDAPv2).

Данный вариант также иногда называется LDAPv2+. Он отличается от U-Mich варианта LDAP в ряде направлений.

Данное сообщение обычно возвращается, когда предпринята попытка изменения атрибута objectClass способом, несовместимым с информационной моделью LDAP/X.500. На практике, такая ошибка обычно возникает, когда кто-то пытается изменить структуру объекта с одного класса на другой, например, пытается поменять ‘яблоко’ на ‘грушу’ или ‘фрукт’ на ‘грушу’.

slapd(8) не допускает такие изменения в соответствии с ограничениями LDAP и X.500.

Если Вы хотели подсоединиться, используя DN и пароль, и получили ошибку из семейства ldap_sasl_interactive_bind_s, возможно, Вы просто забыли указать команде аргумент ‘-x’. По умолчанию используется SASL-аутентификация. Для выбора простой («simple») аутентификации требуется аргумент ‘-x’.

Данное сообщение указывает на то, что функция SASL-аутентификации LDAP не может прочитать Root DSE. Эта ошибка возникает, когда сервер не предоставляет root DSE. Такое может происходить из-за ограничений контроля доступа.

Данное сообщение указывает на то, что функция SASL-аутентификации LDAP может прочитать Root DSE, но эта запись не содержит атрибута supportedSASLMechanism.

В атрибуте supportedSASLmechanism перечисляются механизмы, доступные в настоящее время. Данный список может быть пустым, если ни один из поддерживаемых механизмов в данный момент не доступен. Например, EXTERNAL перечисляется, только если клиент установил свою идентичность с помощью аутентификации на более низком уровне (например, TLS).

Примечание: данный атрибут может быть невидим из-за ограничений контроля доступа

Примечание: подсоединение с использованием SASL применяется по умолчанию для всех инструментов OpenLDAP, таких как ldapsearch(1), ldapmodify(1). Чтобы принудительно использовать подсоединение «simple», воспользуйтесь аргументом «-x». Использование подсоединения «simple» не рекомендовано, если не предприняты адекватные меры по защите конфиденциальности (такие, как TLS/SSL, IPSEC).

Данное сообщение указывает, что ни один из поддерживаемых сервером механизмов аутентификации SASL не поддерживается клиентом, либо они слишком слабы, либо по иной причине не подходят для использования клиентом. Имейте в виду, что параметры безопасности по умолчанию запрещают использование определённых механизмов, таких как ANONYMOUS и PLAIN (без TLS).

Примечание: подсоединение с использованием SASL применяется по умолчанию для всех инструментов OpenLDAP, таких как ldapsearch(1), ldapmodify(1). Чтобы принудительно использовать подсоединение «simple», воспользуйтесь аргументом «-x». Использование подсоединения «simple» не рекомендовано, если не предприняты адекватные меры по защите конфиденциальности (такие, как TLS/SSL, IPSEC).

Возможная причина возникновения этой ошибки — отсутствие прямой и обратной записи DNS для сервера LDAP.

Данная ошибка возвращается, если при ответе на поисковый запрос LDAPv2 сервер возвращает сразу и результаты (ноль или более совпавших записей), и ссылки (отсылки на другие серверы). Смотрите также ldapsearch(1).

Если при операции обновления реплики на ней не существует записи, которую требуется обновить (updatedn), будет возвращена отсылка. Также это может произойти, если ACL требует корректировки.

ldapsearch(1) и другие инструменты возвращают

когда пользователь (с помощью аргументов командной строки и/или файла ldap.conf(5)) запрашивает второй раз запустить TLS (SSL). Например, когда указываются сразу и «-H ldaps://server.do.main» и «-ZZ».

Данная ошибка slapd обычно указывает на то, что клиент отправил сообщение, превысившее административное ограничение. Смотрите директивы конфигурации sockbuf_max_incoming и sockbuf_max_incoming_auth в slapd.conf(5).

Это сообщение не указывает на ненормальное поведение или ошибку. Оно просто означает, что ожидаемые данные еще не доступны из запрошенного ресурса, в запрошенном контексте, либо из запрошенного сетевого сокета. slapd(8) обработает данные, как только они станут доступны.

Это сообщение указывает на то, что операционная система не поддерживает одно из семейств адресов (протоколов), на поддержку которого настроен slapd(8). Чаще всего это происходит, когда slapd(8) настраивался на поддержку IPv6, а ядро операционной системы — нет. В таких случаях данное сообщение можно проигнорировать.

Это сообщение означает, что slapd был запущен не с правами root, и поэтому не может получить свой ключ Kerberos 5 из keytab, обычно файл /etc/krb5.keytab.

Файл keytab используется для хранения ключей, которые требуются сервисам и демонам, запускающимся во время загрузки. Очень важно хранить эти секретные сведения вне досягаемости злоумышленников.

Поэтому по умолчанию владельцем файла keytab является root, а для всех остальных чтение этого файла не разрешено. Не следует ослаблять эти ограничения на права. Вместо этого создайте другой файл keytab для slapd и убедитесь, что владельцем его является тот пользователь, с правами которого запускается slapd.

Чтобы это сделать, запустите kadmin и введите следующие команды:

Затем, перейдя в оболочку, сделайте:

Теперь нужно сообщить slapd (ну, на самом деле сообщить библиотеке gssapi Kerberos 5, вызываемой Cyrus SASL), где найти новый keytab. Сделайте это путём задания переменной окружения KRB5_KTNAME примерно так:

Задайте эту переменную окружения в скрипте запуска slapd (на Red Hat лучше задать её в более подходящем месте /etc/sysconfig/ldap).

Всё это работает, только если Вы используете MIT kerberos. Это не будет работать, к примеру, с Heimdal.

В Heimdal есть функция gsskrb5_register_acceptor_identity(), устанавливающая путь к файлу keytab, который Вы хотите использовать. В Cyrus SASL 2 для использования данной функции Вы можете добавить

в конфигурационный файл SASL Вашего приложения. Это работает только с Heimdal.

Появление сообщения «access from unknown denied» в файле журнала связано с TCP wrappers. Дополнительную информацию смотрите в hosts_access(5). Чтобы избавиться от этой ошибки, Вы можете, например, добавить строку «slapd: .hosts.you.want.to.allow» в /etc/hosts.allow.

Появление данного сообщения является нормальным. Это означает, что необходимые данные еще не доступны из запрошенного ресурса, либо из запрошенного сетевого сокета. slapd(8) обработает данные, как только они станут доступны.

Иногда `make test’ завершается неудачей на самых ранних тестах с невразумительным сообщением вроде такого:

Обычно, пять строк:

Waiting 5 seconds for slapd to start.

указывают на то, что slapd вообще не запустился.

В tests/testrun/slapd.1.log есть полный отчёт о том, что выдавал slapd во время попыток запуска. Уровень журналирования может быть повышен путём задания переменной окружения SLAPD_DEBUG в соответствующее значение; о том, что означают различные уровни журналирования, смотрите loglevel в slapd.conf(5).

Типичная причина такого поведения — проблема компоновки времени исполнения, то есть slapd не может найти некоторые динамические библиотеки, для работы с которыми он скомпонован. Попробуйте запустить ldd(1) на slapd (для тех архитектур, которые поддерживают компоновку времени исполнения).

Также могут быть и другие причины; содержимое файла журнала должно прояснить их.

Тесты, запускающие сразу несколько экземпляров slapd обычно помещают отчёты в tests/testrun/slapd. .log, с различным для каждого экземпляра slapd; такие тесты просматривают tests/testrun/ для назначения возможного значения .

Возможно, это связано с неправильной принадлежностью директории BDB (/var/lib/ldap) и файлов в ней. Эти файлы должны принадлежать пользователю, с правами которого запускается slapd.

устраняет данную ошибку в Debian.

При использовании SASL, когда клиент соединяется с сервером LDAP, сервис slapd немедленно аварийно завершает работу и клиент получает сообщение об ошибке:

Если проверить сервис slapd, он окажется остановленным.

Это может произойти из-за использования различных несовместимых между собой версий BerkeleyDB при установке SASL и установке OpenLDAP. Проблема возникает при использовании нескольких версий BerkeleyDB. Решение: проверьте, какая версия BerkeleyDB использовалась при установке Cyrus SASL.

Переустановите OpenLDAP с нужной версией BerkeleyDB.

Источник

LDAP Troubleshooting for Administrators (FREE SELF)

Common Problems & Workflows

Connection

Connection refused

If you’re getting Connection Refused error messages when attempting to
connect to the LDAP server, review the LDAP port and encryption settings
used by GitLab. Common combinations are encryption: 'plain' and port: 389,
or encryption: 'simple_tls' and port: 636.

Connection times out

If GitLab cannot reach your LDAP endpoint, you see a message like this:

Could not authenticate you from Ldapmain because "Connection timed out - user specified timeout".

If your configured LDAP provider and/or endpoint is offline or otherwise
unreachable by GitLab, no LDAP user is able to authenticate and sign-in.
GitLab does not cache or store credentials for LDAP users to provide authentication
during an LDAP outage.

Contact your LDAP provider or administrator if you are seeing this error.

Referral error

If you see LDAP search error: Referral in the logs, or when troubleshooting
LDAP Group Sync, this error may indicate a configuration problem. The LDAP
configuration /etc/gitlab/gitlab.rb (Omnibus) or config/gitlab.yml (source)
is in YAML format and is sensitive to indentation. Check that group_base and
admin_group configuration keys are indented 2 spaces past the server
identifier. The default identifier is main and an example snippet looks like
the following:

main: # 'main' is the GitLab 'provider ID' of this LDAP server
  label: 'LDAP'
  host: 'ldap.example.com'
  ...
  group_base: 'cn=my_group,ou=groups,dc=example,dc=com'
  admin_group: 'my_admin_group'

Query LDAP (PREMIUM SELF)

The following allows you to perform a search in LDAP using the rails console.
Depending on what you’re trying to do, it may make more sense to query a user
or a group directly, or even use ldapsearch instead.

adapter = Gitlab::Auth::Ldap::Adapter.new('ldapmain')
options = {
    # :base is required
    # use .base or .group_base
    base: adapter.config.group_base,

    # :filter is optional
    # 'cn' looks for all "cn"s under :base
    # '*' is the search string - here, it's a wildcard
    filter: Net::LDAP::Filter.eq('cn', '*'),

    # :attributes is optional
    # the attributes we want to get returned
    attributes: %w(dn cn memberuid member submember uniquemember memberof)
}
adapter.ldap_search(options)

When using OIDs in the filter, replace Net::LDAP::Filter.eq with Net::LDAP::Filter.construct:

adapter = Gitlab::Auth::Ldap::Adapter.new('ldapmain')
options = {
    # :base is required
    # use .base or .group_base
    base: adapter.config.base,

    # :filter is optional
    # This filter includes OID 1.2.840.113556.1.4.1941
    # It will search for all direct and nested members of the group gitlab_grp in the LDAP directory
    filter: Net::LDAP::Filter.construct("(memberOf:1.2.840.113556.1.4.1941:=CN=gitlab_grp,DC=example,DC=com)"),

    # :attributes is optional
    # the attributes we want to get returned
    attributes: %w(dn cn memberuid member submember uniquemember memberof)
}
adapter.ldap_search(options)

For examples of how this is run,
review the Adapter module.

User sign-ins

No users are found

If you’ve confirmed that a connection to LDAP can be
established but GitLab doesn’t show you LDAP users in the output, one of the
following is most likely true:

  • The bind_dn user doesn’t have enough permissions to traverse the user tree.
  • The users don’t fall under the configured base.
  • The configured user_filter blocks access to the users.

In this case, you con confirm which of the above is true using
ldapsearch with the existing LDAP configuration in your
/etc/gitlab/gitlab.rb.

Users cannot sign-in

A user can have trouble signing in for any number of reasons. To get started,
here are some questions to ask yourself:

  • Does the user fall under the configured base in
    LDAP? The user must fall under this base to sign in.
  • Does the user pass through the configured user_filter?
    If one is not configured, this question can be ignored. If it is, then the
    user must also pass through this filter to be allowed to sign in.

    • Refer to our documentation on debugging the user_filter.

If the above are both okay, the next place to look for the problem is
the logs themselves while reproducing the issue.

  • Ask the user to sign in and let it fail.
  • Look through the output for any errors or other
    messages about the sign-in. You may see one of the other error messages on
    this page, in which case that section can help resolve the issue.

If the logs don’t lead to the root of the problem, use the
rails console to query this user
to see if GitLab can read this user on the LDAP server.

It can also be helpful to
debug a user sync to
investigate further.

Invalid credentials on sign-in

If that the sign-in credentials used are accurate on LDAP, ensure the following
are true for the user in question:

  • Make sure the user you are binding with has enough permissions to read the user’s
    tree and traverse it.
  • Check that the user_filter is not blocking otherwise valid users.
  • Run an LDAP check command to make sure that the LDAP settings
    are correct and GitLab can see your users.

Access denied for your LDAP account

There is a bug that
may affect users with Auditor level access. When
downgrading from Premium/Ultimate, Auditor users who try to sign in
may see the following message: Access denied for your LDAP account.

We have a workaround, based on toggling the access level of affected users:

  1. As an administrator, on the top bar, select Menu > Admin.
  2. On the left sidebar, select Overview > Users.
  3. Select the name of the affected user.
  4. In the user’s administrative page, press Edit on the top right of the page.
  5. Change the user’s access level from Regular to Admin (or vice versa),
    and press Save changes at the bottom of the page.
  6. Press Edit on the top right of the user’s profile page
    again.
  7. Restore the user’s original access level (Regular or Admin)
    and press Save changes again.

The user should now be able to sign in.

Email has already been taken

A user tries to sign in with the correct LDAP credentials, is denied access,
and the production.log shows an error that looks like this:

(LDAP) Error saving user <USER DN> (email@example.com): ["Email has already been taken"]

This error is referring to the email address in LDAP, email@example.com. Email
addresses must be unique in GitLab and LDAP links to a user’s primary email (as opposed
to any of their possibly-numerous secondary emails). Another user (or even the
same user) has the email email@example.com set as a secondary email, which
is throwing this error.

We can check where this conflicting email address is coming from using the
rails console. Once in the console, run the following:

# This searches for an email among the primary AND secondary emails
user = User.find_by_any_email('email@example.com')
user.username

This shows you which user has this email address. One of two steps must be taken here:

  • To create a new GitLab user/username for this user when signing in with LDAP,
    remove the secondary email to remove the conflict.
  • To use an existing GitLab user/username for this user to use with LDAP,
    remove this email as a secondary email and make it a primary one so GitLab
    associates this profile to the LDAP identity.

The user can do either of these steps
in their profile or an administrator can do it.

Projects limit errors

The following errors indicate that a limit or restriction is activated, but an associated data
field contains no data:

  • Projects limit can't be blank.
  • Projects limit is not a number.

To resolve this:

  1. On the top bar, select Menu > Admin.
  2. On the left sidebar, go to Settings > General.
  3. Expand both of the following:
    • Account and limit.
    • Sign-up restrictions.
  4. Check, for example, the Default projects limit or Allowed domains for sign-ups
    fields and ensure that a relevant value is configured.

Debug LDAP user filter

ldapsearch allows you to test your configured
user filter
to confirm that it returns the users you expect it to return.

ldapsearch -H ldaps://$host:$port -D "$bind_dn" -y bind_dn_password.txt  -b "$base" "$user_filter" sAMAccountName
  • Variables beginning with a $ refer to a variable from the LDAP section of
    your configuration file.
  • Replace ldaps:// with ldap:// if you are using the plain authentication method.
    Port 389 is the default ldap:// port and 636 is the default ldaps://
    port.
  • We are assuming the password for the bind_dn user is in bind_dn_password.txt.

Sync all users (PREMIUM SELF)

The output from a manual user sync can show you what happens when
GitLab tries to sync its users against LDAP. Enter the rails console
and then run:

Rails.logger.level = Logger::DEBUG

LdapSyncWorker.new.perform

Next, learn how to read the output.

Example console output after a user sync (PREMIUM SELF)

The output from a manual user sync is very verbose, and a
single user’s successful sync can look like this:

Syncing user John, email@example.com
  Identity Load (0.9ms)  SELECT  "identities".* FROM "identities" WHERE "identities"."user_id" = 20 AND (provider LIKE 'ldap%') LIMIT 1
Instantiating Gitlab::Auth::Ldap::Person with LDIF:
dn: cn=John Smith,ou=people,dc=example,dc=com
cn: John Smith
mail: email@example.com
memberof: cn=admin_staff,ou=people,dc=example,dc=com
uid: John

  UserSyncedAttributesMetadata Load (0.9ms)  SELECT  "user_synced_attributes_metadata".* FROM "user_synced_attributes_metadata" WHERE "user_synced_attributes_metadata"."user_id" = 20 LIMIT 1
   (0.3ms)  BEGIN
  Namespace Load (1.0ms)  SELECT  "namespaces".* FROM "namespaces" WHERE "namespaces"."owner_id" = 20 AND "namespaces"."type" IS NULL LIMIT 1
  Route Load (0.8ms)  SELECT  "routes".* FROM "routes" WHERE "routes"."source_id" = 27 AND "routes"."source_type" = 'Namespace' LIMIT 1
  Ci::Runner Load (1.1ms)  SELECT "ci_runners".* FROM "ci_runners" INNER JOIN "ci_runner_namespaces" ON "ci_runners"."id" = "ci_runner_namespaces"."runner_id" WHERE "ci_runner_namespaces"."namespace_id" = 27
   (0.7ms)  COMMIT
   (0.4ms)  BEGIN
  Route Load (0.8ms)  SELECT "routes".* FROM "routes" WHERE (LOWER("routes"."path") = LOWER('John'))
  Namespace Load (1.0ms)  SELECT  "namespaces".* FROM "namespaces" WHERE "namespaces"."id" = 27 LIMIT 1
  Route Exists (0.9ms)  SELECT  1 AS one FROM "routes" WHERE LOWER("routes"."path") = LOWER('John') AND "routes"."id" != 50 LIMIT 1
  User Update (1.1ms)  UPDATE "users" SET "updated_at" = '2019-10-17 14:40:59.751685', "last_credential_check_at" = '2019-10-17 14:40:59.738714' WHERE "users"."id" = 20

There’s a lot here, so let’s go over what could be helpful when debugging.

First, GitLab looks for all users that have previously
signed in with LDAP and iterate on them. Each user’s sync starts with
the following line that contains the user’s username and email, as they
exist in GitLab now:

Syncing user John, email@example.com

If you don’t find a particular user’s GitLab email in the output, then that
user hasn’t signed in with LDAP yet.

Next, GitLab searches its identities table for the existing
link between this user and the configured LDAP providers:

  Identity Load (0.9ms)  SELECT  "identities".* FROM "identities" WHERE "identities"."user_id" = 20 AND (provider LIKE 'ldap%') LIMIT 1

The identity object has the DN that GitLab uses to look for the user
in LDAP. If the DN isn’t found, the email is used instead. We can see that
this user is found in LDAP:

Instantiating Gitlab::Auth::Ldap::Person with LDIF:
dn: cn=John Smith,ou=people,dc=example,dc=com
cn: John Smith
mail: email@example.com
memberof: cn=admin_staff,ou=people,dc=example,dc=com
uid: John

If the user wasn’t found in LDAP with either the DN or email, you may see the
following message instead:

LDAP search error: No Such Object

…in which case the user is blocked:

  User Update (0.4ms)  UPDATE "users" SET "state" = $1, "updated_at" = $2 WHERE "users"."id" = $3  [["state", "ldap_blocked"], ["updated_at", "2019-10-18 15:46:22.902177"], ["id", 20]]

After the user is found in LDAP, the rest of the output updates the GitLab
database with any changes.

Query a user in LDAP

This tests that GitLab can reach out to LDAP and read a particular user.
It can expose potential errors connecting to and/or querying LDAP
that may seem to fail silently in the GitLab UI.

Rails.logger.level = Logger::DEBUG

adapter = Gitlab::Auth::Ldap::Adapter.new('ldapmain') # If `main` is the LDAP provider
Gitlab::Auth::Ldap::Person.find_by_uid('<uid>', adapter)

Group memberships (PREMIUM SELF)

Memberships not granted

Sometimes you may think a particular user should be added to a GitLab group via
LDAP group sync, but for some reason it’s not happening. You can check several
things to debug the situation.

  • Ensure LDAP configuration has a group_base specified.
    This configuration is required for group sync to work properly.
  • Ensure the correct LDAP group link is added to the GitLab group.
  • Check that the user has an LDAP identity:
    1. Sign in to GitLab as an administrator user.
    2. On the top bar, select Menu > Admin.
    3. On the left sidebar, select Overview > Users.
    4. Search for the user.
    5. Open the user by selecting their name. Do not select Edit.
    6. Select the Identities tab. There should be an LDAP identity with
      an LDAP DN as the ‘Identifier’. If not, this user hasn’t signed in with
      LDAP yet and must do so first.
  • You’ve waited an hour or the configured interval for
    the group to sync. To speed up the process, either go to the GitLab group Group information > Members
    and press Sync now (sync one group) or run the group sync Rake task
    (sync all groups).

If all of the above looks good, jump in to a little more advanced debugging in
the rails console.

  1. Enter the rails console.
  2. Choose a GitLab group to test with. This group should have an LDAP group link
    already configured.
  3. Enable debug logging, find the above GitLab group, and sync it with LDAP.
  4. Look through the output of the sync. See example log output
    for how to read the output.
  5. If you still aren’t able to see why the user isn’t being added, query the LDAP group directly
    to see what members are listed.
  6. Is the user’s DN or UID in one of the lists from the above output? One of the DNs or
    UIDs here should match the ‘Identifier’ from the LDAP identity checked earlier. If it doesn’t,
    the user does not appear to be in the LDAP group.

Administrator privileges not granted

When Administrator sync has been configured
but the configured users aren’t granted the correct administrator privileges, confirm
the following are true:

  • A group_base is also configured.
  • The configured admin_group in the gitlab.rb is a CN, rather than a DN or an array.
  • This CN falls under the scope of the configured group_base.
  • The members of the admin_group have already signed into GitLab with their LDAP
    credentials. GitLab only grants administrator access to the users whose
    accounts are already connected to LDAP.

If all the above are true and the users are still not getting access,
run a manual group sync in the rails console and
look through the output to see what happens when
GitLab syncs the admin_group.

Sync all groups

NOTE:
To sync all groups manually when debugging is unnecessary,
use the Rake task instead.

The output from a manual group sync can show you what happens
when GitLab syncs its LDAP group memberships against LDAP.

Rails.logger.level = Logger::DEBUG

LdapAllGroupsSyncWorker.new.perform

Next, learn how to read the output.

Example console output after a group sync

Like the output from the user sync, the output from the
manual group sync is also very verbose. However, it contains lots
of helpful information.

Indicates the point where syncing actually begins:

Started syncing 'ldapmain' provider for 'my_group' group

The following entry shows an array of all user DNs GitLab sees in the LDAP server.
These DNs are the users for a single LDAP group, not a GitLab group. If
you have multiple LDAP groups linked to this GitLab group, you see multiple
log entries like this — one for each LDAP group. If you don’t see an LDAP user
DN in this log entry, LDAP is not returning the user when we do the lookup.
Verify the user is actually in the LDAP group.

Members in 'ldap_group_1' LDAP group: ["uid=john0,ou=people,dc=example,dc=com",
"uid=mary0,ou=people,dc=example,dc=com", "uid=john1,ou=people,dc=example,dc=com",
"uid=mary1,ou=people,dc=example,dc=com", "uid=john2,ou=people,dc=example,dc=com",
"uid=mary2,ou=people,dc=example,dc=com", "uid=john3,ou=people,dc=example,dc=com",
"uid=mary3,ou=people,dc=example,dc=com", "uid=john4,ou=people,dc=example,dc=com",
"uid=mary4,ou=people,dc=example,dc=com"]

Shortly after each of the above entries, you see a hash of resolved member
access levels. This hash represents all user DNs GitLab thinks should have
access to this group, and at which access level (role). This hash is additive,
and more DNs may be added, or existing entries modified, based on additional
LDAP group lookups. The very last occurrence of this entry should indicate
exactly which users GitLab believes should be added to the group.

NOTE:
10 is ‘Guest’, 20 is ‘Reporter’, 30 is ‘Developer’, 40 is ‘Maintainer’
and 50 is ‘Owner’.

Resolved 'my_group' group member access: {"uid=john0,ou=people,dc=example,dc=com"=>30,
"uid=mary0,ou=people,dc=example,dc=com"=>30, "uid=john1,ou=people,dc=example,dc=com"=>30,
"uid=mary1,ou=people,dc=example,dc=com"=>30, "uid=john2,ou=people,dc=example,dc=com"=>30,
"uid=mary2,ou=people,dc=example,dc=com"=>30, "uid=john3,ou=people,dc=example,dc=com"=>30,
"uid=mary3,ou=people,dc=example,dc=com"=>30, "uid=john4,ou=people,dc=example,dc=com"=>30,
"uid=mary4,ou=people,dc=example,dc=com"=>30}

It’s not uncommon to see warnings like the following. These indicate that GitLab
would have added the user to a group, but the user could not be found in GitLab.
Usually this is not a cause for concern.

If you think a particular user should already exist in GitLab, but you’re seeing
this entry, it could be due to a mismatched DN stored in GitLab. See
User DN and/or email have changed to update the user’s LDAP identity.

User with DN `uid=john0,ou=people,dc=example,dc=com` should have access
to 'my_group' group but there is no user in GitLab with that
identity. Membership will be updated once the user signs in for
the first time.

Finally, the following entry says syncing has finished for this group:

Finished syncing all providers for 'my_group' group

Once all the configured group links have been synchronized, GitLab looks
for any Administrators or External users to sync:

Syncing admin users for 'ldapmain' provider

The output looks similar to what happens with a single group, and then
this line indicates the sync is finished:

Finished syncing admin users for 'ldapmain' provider

If administrator sync is not configured, you see a message
stating as such:

No `admin_group` configured for 'ldapmain' provider. Skipping

Sync one group

Syncing all groups can produce a lot of noise in the output, which can be
distracting when you’re only interested in troubleshooting the memberships of
a single GitLab group. In that case, here’s how you can just sync this group
and see its debug output:

Rails.logger.level = Logger::DEBUG

# Find the GitLab group.
# If the output is `nil`, the group could not be found.
# If a bunch of group attributes are in the output, your group was found successfully.
group = Group.find_by(name: 'my_gitlab_group')

# Sync this group against LDAP
EE::Gitlab::Auth::Ldap::Sync::Group.execute_all_providers(group)

The output is similar to
that you get from syncing all groups.

Query a group in LDAP

When you’d like to confirm that GitLab can read a LDAP group and see all its members,
you can run the following:

# Find the adapter and the group itself
adapter = Gitlab::Auth::Ldap::Adapter.new('ldapmain') # If `main` is the LDAP provider
ldap_group = EE::Gitlab::Auth::Ldap::Group.find_by_cn('group_cn_here', adapter)

# Find the members of the LDAP group
ldap_group.member_dns
ldap_group.member_uids

User DN or/and email have changed

When an LDAP user is created in GitLab, their LDAP DN is stored for later reference.

If GitLab cannot find a user by their DN, it falls back
to finding the user by their email. If the lookup is successful, GitLab
updates the stored DN to the new value so both values now match what’s in
LDAP.

If the email has changed and the DN has not, GitLab finds the user with
the DN and updates its own record of the user’s email to match the one in LDAP.

However, if the primary email and the DN change in LDAP, then GitLab
has no way of identifying the correct LDAP record of the user and, as a
result, the user is blocked. To rectify this, the user’s existing
profile must be updated with at least one of the new values (primary
email or DN) so the LDAP record can be found.

The following script updates the emails for all provided users so they
aren’t blocked or unable to access their accounts.

NOTE:
The following script requires that any new accounts with the new
email address are removed first. Email addresses must be unique in GitLab.

Go to the rails console and then run:

# Each entry must include the old username and the new email
emails = {
  'ORIGINAL_USERNAME' => 'NEW_EMAIL_ADDRESS',
  ...
}

emails.each do |username, email|
  user = User.find_by_username(username)
  user.email = email
  user.skip_reconfirmation!
  user.save!
end

You can then run a UserSync (PREMIUM SELF) to sync the latest DN
for each of these users.

Expired license causes errors with multiple LDAP servers

Using multiple LDAP servers requires a valid license. An expired license can
cause:

  • 502 errors in the web interface.

  • The following error in logs (the actual strategy name depends on the name configured in /etc/gitlab/gitlab.rb):

    Could not find a strategy with name `Ldapsecondary'. Please ensure it is required or explicitly set it using the :strategy_class option. (Devise::OmniAuth::StrategyNotFound)

To resolve this error, you must apply a new license to the GitLab instance without the web interface:

  1. Remove or comment out the GitLab configuration lines for all non-primary LDAP servers.
  2. Reconfigure GitLab so that it temporarily uses only one LDAP server.
  3. Enter the Rails console and add the license key.
  4. Re-enable the additional LDAP servers in the GitLab configuration and reconfigure GitLab again.

Debugging Tools

LDAP check

The Rake task to check LDAP is a valuable tool
to help determine whether GitLab can successfully establish a connection to
LDAP and can get so far as to even read users.

If a connection can’t be established, it is likely either because of a problem
with your configuration or a firewall blocking the connection.

  • Ensure you don’t have a firewall blocking the
    connection, and that the LDAP server is accessible to the GitLab host.
  • Look for an error message in the Rake check output, which may lead to your LDAP configuration to
    confirm that the configuration values (specifically host, port, bind_dn, and
    password) are correct.
  • Look for errors in the logs to further debug connection failures.

If GitLab can successfully connect to LDAP but doesn’t return any
users, see what to do when no users are found.

GitLab logs

If a user account is blocked or unblocked due to the LDAP configuration, a
message is logged to application.log.

If there is an unexpected error during an LDAP lookup (configuration error,
timeout), the sign-in is rejected and a message is logged to production.log.

ldapsearch

ldapsearch is a utility that allows you to query your LDAP server. You can
use it to test your LDAP settings and ensure that the settings you’re using
get you the results you expect.

When using ldapsearch, be sure to use the same settings you’ve already
specified in your gitlab.rb configuration so you can confirm what happens
when those exact settings are used.

Running this command on the GitLab host also helps confirm that there’s no
obstruction between the GitLab host and LDAP.

For example, consider the following GitLab configuration:

gitlab_rails['ldap_servers'] = YAML.load <<-'EOS' # remember to close this block with 'EOS' below
   main: # 'main' is the GitLab 'provider ID' of this LDAP server
     label: 'LDAP'
     host: '127.0.0.1'
     port: 389
     uid: 'uid'
     encryption: 'plain'
     bind_dn: 'cn=admin,dc=ldap-testing,dc=example,dc=com'
     password: 'Password1'
     active_directory: true
     allow_username_or_email_login: false
     block_auto_created_users: false
     base: 'dc=ldap-testing,dc=example,dc=com'
     user_filter: ''
     attributes:
       username: ['uid', 'userid', 'sAMAccountName']
       email:    ['mail', 'email', 'userPrincipalName']
       name:       'cn'
       first_name: 'givenName'
       last_name:  'sn'
     group_base: 'ou=groups,dc=ldap-testing,dc=example,dc=com'
     admin_group: 'gitlab_admin'
EOS

You would run the following ldapsearch to find the bind_dn user:

ldapsearch -D "cn=admin,dc=ldap-testing,dc=example,dc=com" 
  -w Password1 
  -p 389 
  -h 127.0.0.1 
  -b "dc=ldap-testing,dc=example,dc=com"

The bind_dn, password, port, host, and base are all
identical to what’s configured in the gitlab.rb.

For more information, see the official ldapsearch documentation.

Using AdFind (Windows)

You can use the AdFind utility (on Windows based systems) to test that your LDAP server is accessible and authentication is working correctly. AdFind is a freeware utility built by Joe Richards.

Return all objects

You can use the filter objectclass=* to return all directory objects.

adfind -h ad.example.org:636 -ssl -u "CN=GitLabSRV,CN=Users,DC=GitLab,DC=org" -up Password1 -b "OU=GitLab INT,DC=GitLab,DC=org" -f (objectClass=*)

Return single object using filter

You can also retrieve a single object by specifying the object name or full DN. In this example we specify the object name only CN=Leroy Fox.

adfind -h ad.example.org:636 -ssl -u "CN=GitLabSRV,CN=Users,DC=GitLab,DC=org" -up Password1 -b "OU=GitLab INT,DC=GitLab,DC=org" -f "(&(objectcategory=person)(CN=Leroy Fox))"

Rails console

WARNING:
It is very easy to create, read, modify, and destroy data with the rails
console. Be sure to run commands exactly as listed.

The rails console is a valuable tool to help debug LDAP problems. It allows you to
directly interact with the application by running commands and seeing how GitLab
responds to them.

For instructions about how to use the rails console, refer to this
guide.

Enable debug output

This provides debug output that shows what GitLab is doing and with what.
This value is not persisted, and is only enabled for this session in the Rails console.

To enable debug output in the rails console, enter the rails console and run:

Rails.logger.level = Logger::DEBUG

LDAP Administration Guide
Previous Page Home Next Page

C.1.1. ldap_*: Can’t contact LDAP server

The {[B:Can’t contact LDAP server}} error is usually returned when the LDAP server cannot be contacted. This may occur for many reasons:

  • the LDAP server is not running; this can be checked by running, for example,
      telnet <host> <port>

replacing <host> and <port> with the hostname and the port the server is supposed to listen on.

  • the client has not been instructed to contact a running server; with OpenLDAP command-line tools this is accomplished by providing the -H switch, whose argument is a valid LDAP url corresponding to the interface the server is supposed to be listening on.

C.1.2. ldap_*: No such object

The no such object error is generally returned when the target DN of the operation cannot be located. This section details reasons common to all operations. You should also look for answers specific to the operation (as indicated in the error message).

The most common reason for this error is non-existence of the named object. First, check for typos.

Also note that, by default, a new directory server holds no objects (except for a few system entries). So, if you are setting up a new directory server and get this message, it may simply be that you have yet to add the object you are trying to locate.

The error commonly occurs because a DN was not specified and a default was not properly configured.

If you have a suffix specified in slapd.conf eg.

      suffix "dc=example,dc=com"

You should use

      ldapsearch -b 'dc=example,dc=com' '(cn=jane*)'

to tell it where to start the search.

The -b should be specified for all LDAP commands unless you have an ldap.conf(5) default configured.

See Also: ldapsearch(1), ldapmodify(1), and (Xref) How do I specify default base DN for clients? Also, slapadd(8) and its ancillary programs are very strict about the syntax of the LDIF file. Some liberties in the LDIF file may result in an apparently successful creation of the database, but accessing some parts of it may be difficult.

One known common error in database creation is putting a blank line before the first entry in the LDIF file. There must be no leading blank lines in the LDIF file.

It is generally recommended that ldapadd(1) be used instead of slapadd(8) when adding new entries your directory. slapadd(8) should be used to bulk load entries known to be valid. Another cause of this message is a referral entry to an unpopulated directory. Either remove the referral, or add a single record with the referral base DN to the empty directory. This error may also occur when slapd is unable to access the contents of its database because of file permission problems. For instance, on a Red Hat Linux system, slapd runs as user ‘ldap’. When slapadd is run as root to create a database from scratch, the contents of /var/lib/ldap are created with user and group root and with permission 600, making the contents inaccessible to the slapd server.

C.1.3. ldap_*: Can’t chase referral

This is caused by the line

      referral        ldap://root.openldap.org

in slapd.conf, It was provided as an example for how to use referrals in the original file. however if your machine is not permanently connected to the Internet, it will fail to find the server, and hence produce an error message.

To resolve, just place a # in front of line and restart slapd or point it to an available ldap server. See also: ldapadd(1) ldapmodify(1) slapd.conf(5)

C.1.4. ldap_*: server is unwilling to perform

The OpenLDAP server will return an unwilling to perform error if the backend holding the target entry does not support the given operation. The password backend is only willing to perform searches. It will return an unwilling to perform error for all other operations. The shell backend is configurable and may support a limited subset of operations. Check for other errors indicating a shortage of resources required by the directory server. i.e. you may have a full disk etc

C.1.5. ldap_*: Insufficient access

This error occurs when server denies the operation due to insufficient access. This is usually caused by binding to a DN with insufficient privileges (or binding anonymously) to perform the operation. You can bind as the rootdn/rootpw specified in slapd.conf(5) to gain full access. Otherwise, you must bind to an entry which has been granted the appropriate rights through access controls. See also: ldapadd(1) ldapdelete(1) ldapmodify(1) ldapmodrdn(1) ldapsearch(1) slapd.conf(5) (Xref) ldap_bind: Insufficient access (Xref) Access Control

C.1.6. ldap_*: Invalid DN syntax

The target (or other) DN of the operation is invalid. This implies that either the string representation of the DN is not in the required form, one of the types in the attribute value assertions is not defined, or one of the values in the attribute value assertions does not conform to the appropriate syntax.

C.1.7. ldap_*: Referral hop limit exceeded

This error generally occurs when the client chases a referral which refers itself back to a server it already contacted. The server responds as it did before and the client loops. This loop is detected when the hop limit is exceeded.

This is most often caused through misconfiguration of the server’s default referral. The default referral should not be itself:

That is, on ldap://myldap/ the default referral should not be ldap://myldap/ (or any hostname/ip which is equivalent to myldap).

C.1.8. ldap_*: operations error

In some versions of slapd(8), operationsError was returned instead of other. See also: (Xref) ldap_*: other error.

C.1.9. ldap_*: other error

The other result code indicates an internal error has occurred. While the additional information provided with the result code might provide some hint as to the problem, often one will need to consult the server’s log files.

C.1.10. ldap_add/modify: Invalid syntax

This error is reported when a value of an attribute does not conform to syntax restrictions. Additional information is commonly provided stating which value of which attribute was found to be invalid. Double check this value and other values (the server will only report the first error it finds).

Common causes include:

  • extraneous white space (especially trailing white space)
  • improperly encoded characters (LDAPv3 uses UTF-8 encoded Unicode)
  • empty values (few syntaxes allow empty values)

For certain syntax, like OBJECT IDENTIFIER (OID), this error can indicate that the OID descriptor (a «short name») provided is unrecognized. For instance, this error is returned if the objectClass value provided is unrecognized.

C.1.11. ldap_add/modify: Object class violation

This error is returned with the entry to be added or the entry as modified violates the object class schema rules. Normally additional information is returned the error detailing the violation. Some of these are detailed below.

Violations related to the entry’s attributes:

      Attribute not allowed A provided attribute is not allowed by the entry's object class(es).
      Missing required attribute An attribute required by the entry's object class(es) was not provided.

Violations related to the entry’s class(es):

      Entry has no objectClass attribute The entry did not state which object classes it belonged to.
      Unrecognized objectClass One (or more) of the listed objectClass values is not recognized.
      No structural object class provided None of the listed objectClass values is structural.
      Invalid structural object class chain Two or more structural objectClass values are not in same structural object class chain. See also (Xref) ldap add: invalid structural object class chain.
      Structural object class modification Modify operation attempts to change the structural class of the entry. See also (Xref) ldap_modify: cannot modify object class.
      Instanstantiation of abstract objectClass. An abstract class is not subordinate to any listed structural or auxiliary class.
      Invalid structural object class Other structural object class problem.
      No structuralObjectClass operational attribute This is commonly returned when a shadow server is provided an entry which does not contain the structuralObjectClass operational attribute.

Note that the above error messages as well as the above answer assumes basic knowledge of LDAP/X.500 schema.

C.1.12. ldap_add: No such object

The «ldap_add: No such object» error is commonly returned if parent of the entry being added does not exist. Add the parent entry first…

For example, if you are adding «cn=bob,dc=domain,dc=com» and you get:

      ldap_add: No such object

The entry «dc=domain,dc=com» likely doesn’t exist. You can use ldapsearch to see if does exist:

      ldapsearch -b 'dc=domain,dc=com' -s base '(objectclass=*)'

If it doesn’t, add it. See the Quick Start Guide (https://www.openldap.org/doc/admin/quickstart.html) for assistance.


Note: if the entry being added is the same as database suffix, it’s parent isn’t required. i.e.: if your suffix is «dc=domain,dc=com», «dc=com» doesn’t need to exist to add «dc=domain,dc=com». This error will also occur if you try to add any entry that the server is not configured to hold.


For example, if your database suffix is «dc=domain,dc=com» and you attempt to add «dc=domain2,dc=com», «dc=com», «dc=domain,dc=org», «o=domain,c=us», or an other DN in the «dc=domain,dc=com» subtree, the server will return a «No such object» (or referral) error.

slapd(8) will generally return «no global superior knowledge» as additional information indicating its return noSuchObject instead of a referral as the server is not configured with knowledge of a global superior server. See also: ldapadd(1) ldapmodify(1) (Xref) ldap_add/delete/modify/rename: no global superior knowledge

C.1.13. ldap add: invalid structural object class chain

This particular error refers to the rule about STRUCTURAL objectclasses, which states that an object is of one STRUCTURAL class, the structural class of the object. The object is said to belong to this class, zero or more auxiliaries classes, and their super classes. While all of these classes are commonly listed in the objectClass attribute of the entry, one of these classes is the structural object class of the entry. Thus, it is OK for an objectClass attribute to contain inetOrgPerson, organizationalPerson, and person because they inherit one from another to form a single super class chain. That is, inetOrgPerson SUPs organizationPerson SUPs person. On the other hand, it is invalid for both inetOrgPerson and account to be listed in objectClass as inetOrgPerson and account are not part of the same super class chain (unless some other class is also listed with is a subclass of both).

To resolve this problem, one must determine which class will better serve structural object class for the entry, adding this class to the objectClass attribute (if not already present), and remove any other structural class from the entry’s objectClass attribute which is not a super class of the structural object class.

Which object class is better depends on the particulars of the situation. One generally should consult the documentation for the applications one is using for help in making the determination.

C.1.14. ldap_add: no structuralObjectClass operational attribute

ldapadd(1) may error:

      adding new entry "uid=XXX,ou=People,o=campus,c=ru"
        ldap_add: Internal (implementation specific) error (80)
           additional info: no structuralObjectClass operational attribute

when slapd(8) cannot determine, based upon the contents of the objectClass attribute, what the structural class of the object should be.

While this normally should produce an object class violation error, some versions of slapd(8) contain a minor bug which cause the object class error not to be properly detected. In these versions, slapd(8) instead catches its failure to populate the structuralObjectClass operational attribute (hence the internal error). [email protected] See also: (Xref) ldap add: invalid structural object class chain [email protected]

C.1.15. ldap_add/modify/rename: Naming violation

OpenLDAP’s slapd checks for naming attributes and distinguished values consistency, according to RFC 4512.

Naming attributes are those attributeTypes that appear in an entry’s RDN; distinguished values are the values of the naming attributes that appear in an entry’s RDN, e.g, in

      [email protected],dc=example,dc=com

the naming attributes are cn and mail, and the distinguished values are Someone and [email protected]

OpenLDAP’s slapd checks for consistency when:

  • adding an entry
  • modifying an entry, if the values of the naming attributes are changed
  • renaming an entry, if the RDN of the entry changes

Possible causes of error are:

  • the naming attributes are not present in the entry; for example:
                dn: dc=example,dc=com
                objectClass: organization
                o: Example
                # note: "dc: example" is missing
  • the naming attributes are present in the entry, but in the attributeType definition they are marked as: o collective o operational o obsolete
  • the naming attributes are present in the entry, but the distinguished values are not; for example:
                dn: dc=example,dc=com
                objectClass: domain
                dc: foobar
                # note: "dc" is present, but the value is not "example"
  • the naming attributes are present in the entry, with the distinguished values, but the naming attributes: o do not have an equality field, so equality cannot be asserted o the matching rule is not supported (yet) o the matching rule is not appropriate
  • the given distinguished values do not comply with their syntax
  • other errors occurred during the validation/normalization/match process; this is a catchall: look at previous logs for details in case none of the above apply to your case.

In any case, make sure that the attributeType definition for the naming attributes contains an appropriate EQUALITY field; or that of the superior, if they are defined based on a superior attributeType (look at the SUP field). See RFC 4512 for details. [email protected], [email protected]

C.1.16. ldap_add/delete/modify/rename: no global superior knowledge

If the target entry name places is not within any of the databases the server is configured to hold and the server has no knowledge of a global superior, the server will indicate it is unwilling to perform the operation and provide the text «no global superior knowledge» as additional text.

Likely the entry name is incorrect, or the server is not properly configured to hold the named entry, or, in distributed directory environments, a default referral was not configured. [email protected]

C.1.17. ldap_bind: Insufficient access

Current versions of slapd(8) requires that clients have authentication permission to attribute types used for authentication purposes before accessing them to perform the bind operation. As all bind operations are done anonymously (regardless of previous bind success), the auth access must be granted to anonymous.

In the example ACL below grants the following access:

  • to anonymous users: o permission to authenticate using values of userPassword
  • to authenticated users: o permission to update (but not read) their userPassword o permission to read any object excepting values of userPassword

All other access is denied.

        access to attr=userPassword
          by self =w
          by anonymous auth
        access *
          by self write
          by users read

Note that latest versions of slapd(8) will report invalid credentials in cases where the client has insufficient access to complete the operation. This is avoid inappropriate disclosure of the validity of the user’s name. See also: ldapadd(1) ldapdelete(1) ldapmodify(1) ldapmodrdn(1) ldapsearch(1) slapd.conf(5) (Xref) Access Control

C.1.18. ldap_bind: Invalid credentials

The error usually occurs when the credentials (password) provided does not match the userPassword held in entry you are binding to.

The error can also occur when the bind DN specified is not known to the server.

Check both! In addition to the cases mentioned above you should check if the server denied access to userPassword on selected parts of the directory. In fact, slapd always returns «Invalid credentials» in case of failed bind, regardless of the failure reason, since other return codes could reveal the validity of the user’s name.

To debug access rules defined in slapd.conf, add «ACL» to log level. See also: ldapadd(1) ldapdelete(1) ldapmodify(1) ldapmodrdn(1) ldapsearch(1) slapd.conf(5) (Xref) ldap_bind: No such object

C.1.19. ldap_bind: No such object

This answer is specific to OpenLDAP 1.2 and earlier releases. In later releases, ldap_bind returns (Xref) ldap_bind: Invalid credentials instead. ‘No such object’ is only returned by ldap_bind operation in a few special cases. Normally, the server returns (Xref) ldap_bind: Invalid credentials when the entry associated with the bind DN cannot be located. This error occurs when binding using the rootdn and the asserted value doesn’t match configured password value. Rootpw values must be conform to RFC 2307 format defined for userPassword. See also: ldapadd(1) ldapdelete(1) ldapmodify(1) ldapmodrdn(1) ldapsearch(1) slapd.conf(5) (Xref) ldap_bind: Invalid credentials

C.1.20. ldap_bind: Protocol error

There error is generally occurs when the LDAP version requested by the client is not supported by the server.

The OpenLDAP Software 1.x server only accepts version 2 LDAP Bind requests. Note that 1.x server expects U-Mich LDAP, an LDAPv2 variant, to be used. This variant is sometimes referred to as LDAPv2+.

The OpenLDAP Software 2.x server, by default, only accepts version 3 LDAP Bind requests but can be configured to accept a version 2 LDAP Bind request. Note that the 2.x server expects LDAPv3 [RFC4510] to be used when the client requests version 3 and expects a limited LDAPv3 variant (basically, LDAPv3 syntax and semantics in an LDAPv2 PDUs) to be used when version 2 is expected. This variant is also sometimes referred to as LDAPv2+, but differs from the U-Mich LDAP variant in a number of ways.

Use of LDAPv3! See also: (Xref) How to configure slapd(8) with LDAPv2 support (for legacy clients)?.

C.1.21. ldap_modify: cannot modify object class

This message is commonly returned when attempting to modify the objectClass attribute in a manner inconsistent with the LDAP/X.500 information model. In particular, it commonly occurs when one tries to change the structure of the object from one class to another, for instance, trying to change an ‘apple’ into a ‘pear’ or a ‘fruit’ into a ‘pear’. Such changes are disallowed by the slapd(8) in accordance with LDAP and X.500 restrictions.

To overcome this restriction in 2.3 (and prior releases), one must re-create the object with the desired new structural object class (e.g., delete old object then add new object). In 2.4, support for a new control will (hopefully) be introduced to allow the (authorized) user to request this (and various other model restrictions) be temporarily relaxed.

C.1.22. ldap_sasl_interactive_bind_s: …

If you intended to bind using a DN and password and get an error from ldap_sasl_interactive_bind_s, you likely forgot to provide a ‘-x’ option to the command. By default, SASL authentication is used. ‘-x’ is necessary to select «simple» authentication. [email protected]

C.1.23. ldap_sasl_interactive_bind_s: No such Object

This indicates that LDAP SASL authentication function could not read the Root DSE. The error will occur when the server doesn’t provide a root DSE. This may be due to access controls.

Note, also, that LDAPv2 servers, such as those OpenLDAP 1.x’s slapd(8), do not provide a root DSE. Use -P 2 when LDAPv2 is desired. LDAPv2 servers also do not support SASL binds, so you will need to use a «simple» bind instead.


Note: SASL bind is the default for all OpenLDAP tools. To force use of «simple» bind, use the «-x» option. Use of «simple» bind is not recommended unless one has adequate confidentiality protection in place (e.g. TLS/SSL, IPSEC).


C.1.24. ldap_sasl_interactive_bind_s: No such attribute

This indicates that LDAP SASL authentication function could read the Root DSE but it contained no supportedSASLMechanism attribute. The supportedSASLmechanism attribute lists mechanisms currently available. The list may be empty because none of the supported mechanisms are currently available. For example, EXTERNAL is listed only if the client has established its identity by authenticating at a lower level (e.g. TLS).


Note: the attribute may not be visible due to access controls



Note: SASL bind is the default for all OpenLDAP tools, e.g. ldapsearch(1), ldapmodify(1). To force use of «simple» bind, use the «-x» option. Use of «simple» bind is not recommended unless one has adequate confidentiality protection in place (e.g. TLS/SSL, IPSEC).


C.1.25. ldap_sasl_interactive_bind_s: Unknown authentication method

This indicates that none of the SASL authentication supported by the server are supported by the client, or that they are too weak or otherwise inappropriate for use by the client. Note that the default security options disallows the use of certain mechanisms such as ANONYMOUS and PLAIN (without TLS).


Note: SASL bind is the default for all OpenLDAP tools. To force use of «simple» bind, use the «-x» option. Use of «simple» bind is not recommended unless one has adequate confidentiality protection in place (e.g. TLS/SSL, IPSEC).


C.1.26. ldap_sasl_interactive_bind_s: Local error (82)

Apparently not having forward and reverse DNS entries for the LDAP server can result in this error.

C.1.27. ldap_search: Partial results and referral received

This error is returned with the server responses to an LDAPv2 search query with both results (zero or more matched entries) and references (referrals to other servers). See also: ldapsearch(1). If the updatedn on the replica does not exist, a referral will be returned. It may do this as well if the ACL needs tweaking.

C.1.28. ldap_start_tls: Operations error

ldapsearch(1) and other tools will return

        ldap_start_tls: Operations error (1)
              additional info: TLS already started

when the user (though command line options and/or ldap.conf(5)) has requested TLS (SSL) be started twice. For instance, when specifying both «-H ldaps://server.do.main» and «-ZZ».


LDAP Administration Guide
Previous Page Home Next Page

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Ldap error size limit exceeded
  • Ldap error codes
  • Launcher interface check failed with error 2 казаки gameranger
  • Launcher exe системная ошибка
  • Launcher exe ошибочный образ

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии