Меню

Сбой при изменении пароля ошибка ldap

Ozzy

Ozzy

Случайный прохожий


  • #1

Всем привет! Подскажите как пофиксить проблему. Пользователи подключаются к чекпойнту через endpoint security vpn по логину и паролю. Если у пользователя просрочен пароль то клиент предлагает его сменить или обновить, но это сделать не удается. Появляется ошибка: Failed to modify password, LDAP Error
Где искать правду ?

1.png

Последнее редактирование: 07.03.2022

  • #5

Такое ощущение что как будто нет разрешений на смену пароля в AD

А если к примеру домен админ будет так пытаться пароль поменять через gaia или через endpoint security VPN?

  • #10

По моему опыту оно вообще через раз работает. И работоспособность сильно зависит от версии клиента.

  • Remove From My Forums
  • Question

  • While changing password of Active directory user with service account ,However i am getting LDAP Error no 53 Unwilling to perform error. So anbody well aware about this Error please tell how this error is getting.
    • Edited by

      Wednesday, May 6, 2015 11:18 AM

Answers

  • The error indicates that the LDAP server cannot process the request because of server-defined restrictions. This error is returned for the following reasons: The add entry request violates the server’s structure rules.

    Or the modify attribute request specifies attributes that users cannot modify…OR…Password restrictions prevent the action…OR…Connection restrictions prevent the action.

    You may follow this informative article for LDAP Password Changes in Active Directory :

    http://www.dirmgr.com/blog/2010/8/26/ldap-password-changes-in-active-directory.html

    Moreover, If the user is available within the domain, you may also try our free
    Lepide local user management tool that would be nice approach to easily reset passwords in few clicks.


    Lepide — Simplifying IT Management

    • Proposed as answer by
      Mary Dong
      Wednesday, May 13, 2015 7:45 AM
    • Marked as answer by
      Mary Dong
      Wednesday, May 20, 2015 6:29 AM

  • Remove From My Forums
  • Question

  • While changing password of Active directory user with service account ,However i am getting LDAP Error no 53 Unwilling to perform error. So anbody well aware about this Error please tell how this error is getting.
    • Edited by

      Wednesday, May 6, 2015 11:18 AM

Answers

  • The error indicates that the LDAP server cannot process the request because of server-defined restrictions. This error is returned for the following reasons: The add entry request violates the server’s structure rules.

    Or the modify attribute request specifies attributes that users cannot modify…OR…Password restrictions prevent the action…OR…Connection restrictions prevent the action.

    You may follow this informative article for LDAP Password Changes in Active Directory :

    http://www.dirmgr.com/blog/2010/8/26/ldap-password-changes-in-active-directory.html

    Moreover, If the user is available within the domain, you may also try our free
    Lepide local user management tool that would be nice approach to easily reset passwords in few clicks.


    Lepide — Simplifying IT Management

    • Proposed as answer by
      Mary Dong
      Wednesday, May 13, 2015 7:45 AM
    • Marked as answer by
      Mary Dong
      Wednesday, May 20, 2015 6:29 AM

  • Remove From My Forums
  • Question

  • While changing password of Active directory user with service account ,However i am getting LDAP Error no 53 Unwilling to perform error. So anbody well aware about this Error please tell how this error is getting.
    • Edited by

      Wednesday, May 6, 2015 11:18 AM

Answers

  • The error indicates that the LDAP server cannot process the request because of server-defined restrictions. This error is returned for the following reasons: The add entry request violates the server’s structure rules.

    Or the modify attribute request specifies attributes that users cannot modify…OR…Password restrictions prevent the action…OR…Connection restrictions prevent the action.

    You may follow this informative article for LDAP Password Changes in Active Directory :

    http://www.dirmgr.com/blog/2010/8/26/ldap-password-changes-in-active-directory.html

    Moreover, If the user is available within the domain, you may also try our free
    Lepide local user management tool that would be nice approach to easily reset passwords in few clicks.


    Lepide — Simplifying IT Management

    • Proposed as answer by
      Mary Dong
      Wednesday, May 13, 2015 7:45 AM
    • Marked as answer by
      Mary Dong
      Wednesday, May 20, 2015 6:29 AM

  • Remove From My Forums
  • Question

  • While changing password of Active directory user with service account ,However i am getting LDAP Error no 53 Unwilling to perform error. So anbody well aware about this Error please tell how this error is getting.
    • Edited by

      Wednesday, May 6, 2015 11:18 AM

Answers

  • The error indicates that the LDAP server cannot process the request because of server-defined restrictions. This error is returned for the following reasons: The add entry request violates the server’s structure rules.

    Or the modify attribute request specifies attributes that users cannot modify…OR…Password restrictions prevent the action…OR…Connection restrictions prevent the action.

    You may follow this informative article for LDAP Password Changes in Active Directory :

    http://www.dirmgr.com/blog/2010/8/26/ldap-password-changes-in-active-directory.html

    Moreover, If the user is available within the domain, you may also try our free
    Lepide local user management tool that would be nice approach to easily reset passwords in few clicks.


    Lepide — Simplifying IT Management

    • Proposed as answer by
      Mary Dong
      Wednesday, May 13, 2015 7:45 AM
    • Marked as answer by
      Mary Dong
      Wednesday, May 20, 2015 6:29 AM

в настоящее время я проверять подлинность пользователей против некоторых ad, используя следующий код:

DirectoryEntry entry = new DirectoryEntry(_path, username, pwd);

try
{
    // Bind to the native AdsObject to force authentication.
    Object obj = entry.NativeObject;

    DirectorySearcher search = new DirectorySearcher(entry) { Filter = "(sAMAccountName=" + username + ")" };
    search.PropertiesToLoad.Add("cn");
    SearchResult result = search.FindOne();
    if (result == null)
    {
        return false;
    }
    // Update the new path to the user in the directory
    _path = result.Path;
    _filterAttribute = (String)result.Properties["cn"][0];
}
catch (Exception ex)
{
    throw new Exception("Error authenticating user. " + ex.Message);
}

это отлично работает для проверки пароля против имени пользователя.

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

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

Как бы я узнал, если он терпит неудачу из-за того, что он заперто?

я наткнулся на статьи, в которых говорится, что вы можете использовать:

Convert.ToBoolean(entry.InvokeGet("IsAccountLocked"))

или сделать что-то вроде объяснил здесь

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

любое другое предложение о том, как добраться до фактической причины сбоя аутентификации? (учетная запись заблокирована / пароль истек / etc.)

рекламу я подключиться не может скорее быть сервер Windows.

4 ответов


немного поздно, но я оставлю это там.

Если вы хотите действительно иметь возможность определить конкретную причину, по которой учетная запись не проходит проверку подлинности (есть еще много причин, кроме неправильного пароля, истекшего срока действия, блокировки и т. д.), вы можете использовать Windows API LogonUser. Не пугайтесь этого — это легче, чем кажется. Вы просто вызываете LogonUser, и если это не удается, вы смотрите на Маршала.GetLastWin32Error (), который даст вам код возврата, указывающий (очень) конкретная причина сбоя входа в систему.

однако вы не сможете вызвать это в контексте пользователя, которого вы аутентифицируете; вам понадобится учетная запись priveleged-я считаю, что требование SE_TCB_NAME (aka SeTcbPrivilege) — учетная запись пользователя, которая имеет право «действовать как часть операционной системы».

//Your new authenticate code snippet:
        try
        {
            if (!LogonUser(user, domain, pass, LogonTypes.Network, LogonProviders.Default, out token))
            {
                errorCode = Marshal.GetLastWin32Error();
                success = false;
            }
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            CloseHandle(token);    
        }            
        success = true;

если это не удается, вы получите один из кодов возврата (есть больше, что вы можете посмотреть, но это важно из них:

 //See http://support.microsoft.com/kb/155012
    const int ERROR_PASSWORD_MUST_CHANGE = 1907;
    const int ERROR_LOGON_FAILURE = 1326;
    const int ERROR_ACCOUNT_RESTRICTION = 1327;
    const int ERROR_ACCOUNT_DISABLED = 1331;
    const int ERROR_INVALID_LOGON_HOURS = 1328;
    const int ERROR_NO_LOGON_SERVERS = 1311;
    const int ERROR_INVALID_WORKSTATION = 1329;
    const int ERROR_ACCOUNT_LOCKED_OUT = 1909;      //It gives this error if the account is locked, REGARDLESS OF WHETHER VALID CREDENTIALS WERE PROVIDED!!!
    const int ERROR_ACCOUNT_EXPIRED = 1793;
    const int ERROR_PASSWORD_EXPIRED = 1330;  

остальное просто скопируйте / вставьте, чтобы получить DLLImports и значения для передачи в

  //here are enums
    enum LogonTypes : uint
        {
            Interactive = 2,
            Network =3,
            Batch = 4,
            Service = 5,
            Unlock = 7,
            NetworkCleartext = 8,
            NewCredentials = 9
        }
        enum LogonProviders : uint
        {
            Default = 0, // default for platform (use this!)
            WinNT35,     // sends smoke signals to authority
            WinNT40,     // uses NTLM
            WinNT50      // negotiates Kerb or NTLM
        }

//Paste these DLLImports

[DllImport("advapi32.dll", SetLastError = true)]
        static extern bool LogonUser(
         string principal,
         string authority,
         string password,
         LogonTypes logonType,
         LogonProviders logonProvider,
         out IntPtr token);

[DllImport("kernel32.dll", SetLastError = true)]
        static extern bool CloseHandle(IntPtr handle);

Я знаю, что этот ответ опоздал на несколько лет, но мы просто столкнулись с той же ситуацией, что и оригинальный плакат. К сожалению, в нашей среде мы не можем использовать LogonUser — нам нужно чистое решение LDAP. Оказывается, есть способ получить расширенный код ошибки из операции привязки. Это немного уродливо, но это работает:

catch(DirectoryServicesCOMException exc)
{
    if((uint)exc.ExtendedError == 0x80090308)
    {
        LDAPErrors errCode = 0;

        try
        {
            // Unfortunately, the only place to get the LDAP bind error code is in the "data" field of the 
            // extended error message, which is in this format:
            // 80090308: LdapErr: DSID-0C09030B, comment: AcceptSecurityContext error, data 52e, v893
            if(!string.IsNullOrEmpty(exc.ExtendedErrorMessage))
            {
                Match match = Regex.Match(exc.ExtendedErrorMessage, @" data (?<errCode>[0-9A-Fa-f]+),");
                if(match.Success)
                {
                    string errCodeHex = match.Groups["errCode"].Value;
                    errCode = (LDAPErrors)Convert.ToInt32(errCodeHex, fromBase: 16);
                }
            }
        }
        catch { }

        switch(errCode)
        {
            case LDAPErrors.ERROR_PASSWORD_EXPIRED:
            case LDAPErrors.ERROR_PASSWORD_MUST_CHANGE:
                throw new Exception("Your password has expired and must be changed.");

            // Add any other special error handling here (account disabled, locked out, etc...).
        }
    }

    // If the extended error handling doesn't work out, just throw the original exception.
    throw;
}

и вам понадобятся определения для кодов ошибок (их намного больше на http://www.lifeasbob.com/code/errorcodes.aspx):

private enum LDAPErrors
{
    ERROR_INVALID_PASSWORD = 0x56,
    ERROR_PASSWORD_RESTRICTION = 0x52D,
    ERROR_LOGON_FAILURE = 0x52e,
    ERROR_ACCOUNT_RESTRICTION = 0x52f,
    ERROR_INVALID_LOGON_HOURS = 0x530,
    ERROR_INVALID_WORKSTATION = 0x531,
    ERROR_PASSWORD_EXPIRED = 0x532,
    ERROR_ACCOUNT_DISABLED = 0x533,
    ERROR_ACCOUNT_EXPIRED = 0x701,
    ERROR_PASSWORD_MUST_CHANGE = 0x773,
    ERROR_ACCOUNT_LOCKED_OUT = 0x775,
    ERROR_ENTRY_EXISTS = 0x2071,
}

Я не мог найти эту информацию в другом месте-все просто говорят, что вы должны использовать LogonUser. Если есть лучшее решение, я с удовольствием его выслушаю. Если нет, я надеюсь, что это поможет другим людям, которые не могут позвонить LogonUser.


проверка «пароль истекает» относительно проста — по крайней мере, в Windows (не уверен, как другие системы справляются с этим): когда значение Int64 «pwdLastSet» равно 0, пользователю придется изменить свой пароль при следующем входе в систему. Самый простой способ проверить это-включить это свойство в DirectorySearcher:

DirectorySearcher search = new DirectorySearcher(entry)
      { Filter = "(sAMAccountName=" + username + ")" };
search.PropertiesToLoad.Add("cn");
search.PropertiesToLoad.Add("pwdLastSet");

SearchResult result = search.FindOne();
if (result == null)
{
    return false;
}

Int64 pwdLastSetValue = (Int64)result.Properties["pwdLastSet"][0];

что касается проверки» учетная запись заблокирована » — сначала это кажется легким, но это не так…. Флаг» UF_Lockout » на «userAccountControl» не выполняет свою работу надежно.

начиная с Windows 2003 AD, есть новый вычисляемый атрибут, который вы можете проверить:msDS-User-Account-Control-Computed.

дали класс directoryentry user, вы можете сделать:

string attribName = "msDS-User-Account-Control-Computed";
user.RefreshCache(new string[] { attribName });

const int UF_LOCKOUT = 0x0010;

int userFlags = (int)user.Properties[attribName].Value;

if(userFlags & UF_LOCKOUT == UF_LOCKOUT) 
{
   // if this is the case, the account is locked out
}

если вы можете использовать .NET 3.5, все стало намного проще-проверьте статья MSDN о том, как обращаться с пользователями и группами в .NET 3.5 с помощью System.DirectoryServices.AccountManagement пространство имен. Е. Г. теперь у вас есть собственность IsAccountLockedOut на классе UserPrincipal который надежно говорит вам является ли учетная запись заблокирована.

надеюсь, что это помогает!

Марк


вот атрибуты ad LDAP, которые изменяются для пользователя, когда пароль заблокирован (первое значение) против, когда пароль не заблокирован (второе значение). badPwdCount и lockoutTime, очевидно, наиболее актуальна. Я не уверен, должны ли uSNChanged и whenChanged обновляться вручную или нет.

$ diff LockedOut.ldif NotLockedOut.ldif:

< badPwdCount: 3
> badPwdCount: 0

< lockoutTime: 129144318210315776
> lockoutTime: 0

< uSNChanged: 8064871
> uSNChanged: 8065084

< whenChanged: 20100330141028.0Z
> whenChanged: 20100330141932.0Z

Я хочу изменить пароль пользователя [unicodePwd] в Windows Active Directory, используя PHP LDAP.

Я использую Windows Active Directory через PHP LDAP.

У меня нет никаких проблем с этим.

У меня нет проблем со сбором данных.

У меня нет проблем с изменением атрибутов с помощью ldap_mod_replace или ldap_modify

за исключением «UnicodePwd».

* обратите внимание, что это работает

$user['telephonenumber'] = '1234567890';

* обратите внимание, что это не работает

$user['unicodePwd'] = mb_convert_encoding('my_new_password', "UTF-16LE");

// КОД

$result = ldap_modify($ldap, $dn, $user);
return ldap_error($ldap);

// КОД

// ОШИБКА ПРИ ИЗМЕНЕНИИ unicodePwd

ldap_modify(): Modify: Server is unwilling to perform

// НЕТ ОШИБКИ ДЛЯ ТЕЛЕФОНА

  • 06/11/2018 Проблема,

Я не могу настроить свой сервер на ldap поверх ssl.
Уже пытался установить AD CS, пока ничего не получалось. Все еще настраиваете на моем сервере какие-либо идеи об установке CA (центра сертификации) для использования в LDAP через SSL?

  • 20.06.2008 Проблема, НОВАЯ ПРОБЛЕМА

Уже настроен LDAP OVER SSL, я также могу использовать ldap, используя

Cmd-> LDP; порт 389 и 636 с ssl это хорошо.

но когда я запускаю его в своем php, используя порт 636 или ldaps: // имя_сервера, это ошибка,

ldap_bind(): Unable to bind to server: Can't contact LDAP server

1

Решение

Вы должны быть на защищенное соединение для изменения пароля (и, возможно, другие варианты, связанные с безопасностью).

Добавьте следующее, прежде чем позвонить ldap_bind():

ldap_start_tls($ldap);

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


Если вы видите эту ошибку:

Предупреждение: ldap_start_tls (): невозможно запустить TLS: ошибка подключения в …

Вы можете обойти проблему, добавив следующую строку до ты звонишь ldap_connect:

putenv('LDAPTLS_REQCERT=never');

ПРЕДУПРЕЖДЕНИЕ: Это отключает проверку действительности сертификата сервера LDAP! В идеале вы должны добавить сертификат сервера (или его подписывающий CA) в доверенное хранилище.

0

Другие решения

Других решений пока нет …

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

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

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Сбой при возврате нового элемента кода возможно синтаксическая ошибка
  • Сбой при активации imessage произошла ошибка