The target principal name is incorrect ошибка

При попытке ручной репликации данных между контроллерами домена Active Directory в остатке Active Directory Sites and Services (dssite.msc) появилась ошибка:

The following error occurred during the attempt to synchronize naming context from Domain Controller X to Domain Controller Y.
The target principal name is incorrect.
This operation will not continue.

контроллер домена ошибка The target principal name is incorrect

При проверке репликации с помощью repadmin, у одного из DC появляется ошибка:

(2148074274) The target principal name is incorrect.

repadmin (2148074274) The target principal name is incorrect

В журнале событий DC есть такие ошибки:

Source: Security-Kerberos
Event ID: 4

The Kerberos client received a KRB_AP_ERR_MODIFIED error from the server DC2. The target name used was cifs/DC2.winitpro.ru. This indicates that the target server failed to decrypt the ticket provided by the client. This can occur when the target server principal name (SPN) is registered on an account other than the account the target service is using. Ensure that the target SPN is only registered on the account used by the server. This error can also happen if the target service account password is different than what is configured on the Kerberos Key Distribution Center for that target service. Ensure that the service on the server and the KDC are both configured to use the same password. If the server name is not fully qualified, and the target domain (winitpro.ru) is different from the client domain (winiptro.ru), check if there are identically named server accounts in these two domains, or use the fully-qualified name to identify the server.

Event ID 3210:

Failed to authenticate with \DC, a Windows NT domain controller for domain WINITPRO.

Event ID 5722:

The session setup from the computer 1 failed to authenticate. The name of the account referenced in the security database is 2. The following error occurred:

В первую очередь проверьте:

  1. Доступность проблемного контроллера домена с помощью простого ICMP ping
  2. Проверьте, что на нем доступен порт TCP 445 и опубликованы сетевые папки SysVol и NetLogon;

Если все ОК, значит проблема в том, между контроллерами домена нарушен безопасный канал передачи данных. Проверьте его с помощью PowerShell команды:

Test-ComputerSecureChannel -Verbose

Служба KDC на целевом контроллере домена не может расшифровать тикет Kerberos из-за того, что в ней хранится старый пароль этого контроллера домена.

Чтобы исправить проблему, нужно сбросить этот пароль. Сначала нужно найти текущий контроллер домена с FSMO ролью PDC.

netdom query fsmo |find "PDC"

В нашем примере PDC находится на MSK-DC02. Мы будем исопользовать это имя в команде
netdom resetpwd
далее.

netdom найти контроллер домена fsmo

Остановите службу Kerberos Key Distribution Center (KDC) на контроллере домена, на котором появляется ошибка “The target principal name is incorrect” и измените тип запуска на Disabled. Можно изменить настройки службы из консоли services.msc или с помощью PowerShell:

Get-Service kdc -ComputerName msk-dc03 | Set-Service –startuptype disabled –passthru

остановить службу KDC

Перезагрузите этот контроллер домена.

Теперь нужно сбросить безопасный канал связи с контроллером домена с ролью PDC:

netdom resetpwd /server:msk-dc02 /userd:winitproadministrator /passwordd:*

Укажите пароль администратора домена.

Перезагрузите проблемный DC и запустите службу KDC. Попробуйте запустить репликацию и проверить ошибки.

repadmin /syncall
repadmin /replsum
repadmin /showrepl

Если репликация успешно выполнена, в журнале Directory Service Event Viewerа должно появится событие Event ID 1394:

All Problems preventing updates to the Active Directory Domain Services database have been cleared. New Updates to the Active Directory Domain Services database are succeeding. The Net Logon service has restarted

Event ID 1394 успешная репликация AD

Проверьте состояние вашего домена и контроллеров домена Active Directory согласно этого гайда.

Обновлено 03.05.2022

Replication Logo

Добрый день! Уважаемые читатели и гости одного из крупнейших IT блогов Pyatilistnik.org. В прошлый раз я вам показал .как вы можете легко взаимодействовать с файлами папками с помощью утилиты robocopy, я показал как делать резервные копии и многое другое. В сегодняшней статье я покажу, как устраняется ошибка в репликации контроллеров домена Active Directory, ошибка звучит вот так (2148074274) The target principal name is incorrect. Давайте смотреть в чем дело.

🛑Описание ошибки 2148074274

Проверяя на одном из контроллеров домена репликацию через утилиту repadmin, я обнаружил, что от одного из участников стала появляться ошибка:

(2148074274) The target principal name is incorrect

(2148074274) The target principal name is incorrect

Оказалось, что перестал корректно работать безопасный режим между этим неисправным контроллером домена и основным контроллером домена. Как советует Microsoft, его нужно сбросить.

🛠Как исправить ошибку The target principal name is incorrect

Идем на неисправный контроллер домена и отключаем службу центра распространения ключей Kerberos (Kerberos Key Distribution Center service — KDC). Вызовите окно «Выполнить» и введите в нем:

services.msc

Найдите там службу «Центр распространения ключей Kerberos (Kerberos Key Distribution Center service — KDC)«, зайдите в ее свойства, остановите ее и выставите тип запуска «Вручную«. После этого перезагрузите сервер.

центра распространения ключей Kerberos (KDC)

После загрузки в командной строке выполните:

✅netdom query fsmo

✅net stop KDC

✅netdom resetpwd /server:dc01.root.pyatilistnik.org /userd:rootАдминистратор /passwordd: *

✅shutdown -r -t 0

Первой командой мы выясняем, кто у нас сервер PDC, далее мы будим к нему обращаться в команде по сбросу безопасного канала в параметре /server. В /userd указываем учетную запись имеющую права администратора в данном домене.

сброс безопасного канала

После сброса безопасного канала перезапустите контроллер домена. Даже если вы попытайтесь сбросить защищенный канал с помощью утилиты Netdom, и команда не будет успешно завершена, приступите к процессу перезапуска. После завершения перезапуска компьютеров запустите оснастку «Services», перезапустите службу KDC и повторите попытку репликации, не забудьте ей выставить тип запуска «Автоматический«.

Далее проверьте репликацию между контроллерами.

repadmin /syncall /APed

repadmin /syncall

repadmin /replsummary

Дополнительные ссылки


https://docs.microsoft.com/ru-RU/troubleshoot/windows-server/identity/target-principal-name-is-incorrect-when-replicating-data

На этом у меня все. Мы с вами устранили ошибку репликации (2148074274) The target principal name is incorrect. С вами был Иван Сёмин, автор и создатель IT портала Pyatilistnik.org.

The SSPI context error definitely indicates authentication is being attempted using Kerberos.

Since Kerberos authentication SQL Server’s Windows Authentication relies on Active Directory, which requires a trusted relationship between your computer and your network domain controller, you should start by validating that relationship.

You can quickly check that relationship, thru the following Powershell command Test-ComputerSecureChannel.

Test-ComputerSecureChannel -Verbose

enter image description here

If it returns False, you must repair your computer Active Directory secure channel, since without it no domain credencials validation is possible outside your computer.

You can repair your Computer Secure Channel, thru the following Powershell command:

Test-ComputerSecureChannel -Repair -Verbose

If the above doesn’t work (because your domain credentials don’t work because the machine isn’t trusted) you can use NETDOM RESET instead from an elevated cmd.exe (not PowerShell) prompt:

NETDOM RESET %COMPUTERNAME% /UserO:domainAdminUserName /Password0:* /SecurePasswordPrompt

(Yes, the command-line arguments really do have an O (Capital-«Oh», not zero 0). The /Password0:* /SecurePasswordPrompt option will use a credential popup instead of having you put your password directly in the command-line, which you must never do).

Check the security event logs, if you are using kerberos you should see logon attempts with authentication package: Kerberos.

The NTLM authentication may be failing and so a kerberos authentication attempt is being made. You might also see an NTLM logon attempt failure in your security event log?

You can turn on kerberos event logging in dev to try to debug why the kerberos is failing, although it is very verbose.

Microsoft’s Kerberos Configuration Manager for SQL Server may help you quickly diagnose and fix this issue.

Here is a good story to read: http://houseofbrick.com/microsoft-made-an-easy-button-for-spn-and-double-hop-issues/

  • Remove From My Forums
  • Question

  • Hi All,

    I am stuck in a strange issue post installation of SQL Server 2017 Standard. 

    I installed a Core licensed SQL Server 2017 Standard Edition on a Server with Mixed Mode Authentication. Set up was executed successfully.

    While I am connected to my network through VPN Connection. I am able to connect with Server through SQL Authentication However with Windows Authentication it does not connects and fails out with message as  «The target principal name is incorrect.
    Cannot generate SSPI Context.»

    However when i tried to connect through LAN with Windows Authentication it let me connect without any issues.

    Can you please help me in resolving the connectivity issue over VPN for Windows Authentication.

    Below are the error details

    ===================================

    The target principal name is incorrect.  Cannot generate SSPI context. (.Net SqlClient Data Provider)

    ——————————
    For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&EvtSrc=MSSQLServer&EvtID=0&LinkId=20476

    ——————————
    Server Name: 000.000.00.00
    Error Number: 0
    Severity: 11
    State: 0
    Procedure: GenClientContext

    ——————————
    Program Location:

       at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance,
    SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderManager)

    .

    .

    .

    .

    Thank You. 


    Best Regards, Sunil Sharma

    • Edited by

      Thursday, April 23, 2020 12:25 PM

    • Changed type
      pituachMVP
      Friday, April 24, 2020 5:58 PM
      not a question
    • Changed type
      pituachMVP
      Friday, April 24, 2020 5:59 PM
      mistakenly changed the type before

Answers

  • Hi Sunilsharma,

    >The target principal name is incorrect.  Cannot generate SSPI context. (.Net SqlClient Data Provider)

    This is a typical Kerberos authentication failure. There are various reasons for this error. The most common one is the SPN problem. Many cases of this error have been found due to abnormal KDC operation or abnormal TGS service. You can reference: how-to-troubleshoot-the-cannot-generate-sspi-context-error-message

    You can also try workaround as next:
    If you use your domain account to log in, you should grant the account rights of Read and Write SPN, and then restart the server with this account.
    1.Make sure TCP/IP Protocols are enabled and configured correctly;
    2.Close the firewall;
    3.In your DC, run->”adsiedit.msc”
    4.Assume that the start account is YXAdministrator, Administrator->Properties->Security->Advanced->Permissions->Add->Select a principle->Input “SELF”->OK  (as next screenshot shows)

    5.Choose “Read serverPrincipalName” and “Write serverPrincipalName” (as next screenshot shows)

    6.Use this account restart your server and browser;

    Note:
    You need to note that when solving Kerberos-related problems, you may encounter this situation: clearly all the conditions required for Kerberos are configured.
    OK, but you still get Kerberos errors or NTLM errors when you test the connection. At this time, you may wish to try the following two tricks:

    (1) There may be multiple DCs in a domain environment, and the series of changes you make during the investigation will only affect one of the DCs. maybe
    You can use another DC to connect the client to SQL Server, but this DC has not been synchronized to the series of changes you made before.
    At this time, you do not need to wait for automatic synchronization between DCs to occur, you can run the following statement to force synchronization between DCs:
    Repadmin / syncall

    (2) Credential Cache may also be a problem. Credential Cache is used by Kerberos to cache authentication information on this machine. It mainly contains TGT and Session tickets. Since Credential Cache has a life cycle (usually 10 hours) on the machine, if the
    client has received incorrect authentication information and cached it, it will use this information to access SQL Server until the cache expires. So you will always get errors. The solution is to clear the Credential Cache by any of the following three methods.
    1) Use the klist.exe purge command
    2) Use kerbtray tool
    3) Restart the entire machine

    Best Regards.

    yuxi


    MSDN Community Support
    Please remember to click «Mark as Answer» the responses that resolved your issue, and to click «Unmark as Answer» if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to
     MSDN Support, feel free to contact MSDNFSF@microsoft.com

    • Proposed as answer by
      pituachMVP
      Friday, April 24, 2020 6:01 PM
    • Marked as answer by
      Sunilsharma
      Thursday, April 30, 2020 3:36 PM

  • What
    yuxi666 mentioned is really good!

    What i can add… check if the SPN for SQL has been added to the SQL Service account.

    1. On your SQL Server, open SQL Server Configuration Manager

    2. Look at the Log On As column for the SQL Server service.

    3. Open a command prompt and type the following command:

    setspn -l [Log on account]

    For example, if the log on account is Domainsvc-sql the command line would be
    setspn -l Domainsvc-sql

    If the account is NT AuthorityLocal System, the account is the computer account.  Then the command line would be
    setspn -l [SQL_Computername]

    The SQL SPN should look like this: MSSQLSvc/[SQLServerName]:Port

    If the SPN is not configured, that should explain why you receive the error Cannot generate SSPI context

    https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/register-a-service-principal-name-for-kerberos-connections?view=sql-server-ver15

    hth


    This posting is provided AS IS without warranty of any kind

    • Proposed as answer by
      pituachMVP
      Friday, April 24, 2020 6:02 PM
    • Marked as answer by
      Sunilsharma
      Thursday, April 30, 2020 3:36 PM

  • Hi Sunilsharma,

    This may be one network issue.

    Could you please upload the error log here?

    the path is:

    Program FilesMicrosoft SQL ServerMSSQL.nMSSQLLOGERRORLOG and ERRORLOG.n 

    Please check whether this is helpful:

    trusted-connection-to-sql-fails-after-connecting-to-a-vpn, connect-to-sql-via-windows-authentication-over-vpn

    Best Regards.

    yuxi


    MSDN Community Support
    Please remember to click «Mark as Answer» the responses that resolved your issue, and to click «Unmark as Answer» if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to
     MSDN Support, feel free to contact MSDNFSF@microsoft.com

    • Marked as answer by
      Sunilsharma
      Thursday, April 30, 2020 3:25 PM


Table of Contents

  • The History
  • The Solution
    • A. Determine the Primary Domain Controller (PDC) by doing this steps:
    • B. Stop Kerberos Key Distribution Center (KDC) service in CHENSDC (problematic server):
    • C. Purge Kerberos keys in the CHENDC (problematic server)
    • 4. Reset the Computer’s Password in the Primary Domain Controller (PDC)
    • 5. Start the service in the CHENSDC (problematic server)
    • 6. Start IPV6 on both servers
    • 7. Check replication again

The History

I had a client today that reported the CEO’s computer enabled to login against Active Directory; it had the message ‘Trust Relationship was lost’. In this kind of issues, the solution is just to
take out the computer from the domain and re-join it. After removing the server from the AD, I was unable to join it again, because of error: «Logon failure: the target account name is incorrect.» After checking the replication in the domain controllers, I
figure out this: 

The CHENSDC2 and CHENSDC had 54 days without talking to each other. IPV6 was disabled on the servers And checking replication of Active Directory:

And this guide us to a headacheThe Headache

The Repadmin gives an error «The Target Principal Name is incorrect,» so replication from «CHENSDC2» to «CHENSDC» works, but from «CHENSDC» to «CHENSDC2», doesn’t. I tried several solutions to do
this job but none of those worked, so I’ll try to be as clean as I can be in the solution.

The Solution

To fix this issue, you just need to go to do the following:

    A. Determine the Primary Domain Controller (PDC) by doing this steps:

  1. Windows key + R (at the same time)
  2. Write cmd and then press Enter. Console windows will open.
  3. Netdom query fsmo

The output will be something like this, and determine the server that has the PDC role:

So our PDC is called CHENSDC2 in this example, and the problematic domain controller will be CHENSDC

    B. Stop Kerberos Key Distribution Center (KDC) service in CHENSDC (problematic server):

  1. Open the console (cmd) as the previous step, if you don’t have it
  2. Use the command Net stop KDC

Pre step Download WS2003 Resource kit in the link:
https://www.microsoft.com/en-us/download/details.aspx?id=17657″ then install it. I did it in windows server 2008 R2 with nothing but a warning about versions, just ignore it and install the software.

    C. Purge Kerberos keys in the CHENDC (problematic server)

  1. Navigate to: C:Program Files (x86)Windows Resource KitsTools and run «kerbtray.exe»

    You will get a Green bar Next to the time, like this

  2. Now just right click the green bar and select «Purge tickets.»

    After this, the server will be aware of the synchronization KDC from the PDC.

    4. Reset the Computer’s Password in the Primary Domain Controller (PDC)

  1. In the PDC computer, we got this computer in step A. Open the console (cmd) as the previous step, if you don’t have it
  2. netdom resetpwd /server:serverName /userd:DomainNameAdministrator /passwordd:AdminPassword

    5. Start the service in the CHENSDC (problematic server)

  1. Finally, in the PDC computer, we got this computer in step A. Open the console (cmd) as the previous step, if you don’t have it
  2. Then run the command: net start kdc

    6. Start IPV6 on both servers

  1. IPv6 is used by servers to communicate to each other, so enabled it and run «ipconfig /registerdns» so they can talk to each other, especially in the consoles for Active directory

Sidenote: This is basically to improve communication between domain controllers especially for the consoles of AD (AD sites and services, AD Users and Computers, etc.)

    7. Check replication again

  1. run repadmin /replsum
  2. repadmin /showrepl
  3. repadmin /showreps

And make sure that all is working good again.

Hey

I have 2 sites. Both are connected with through a VPN. Site 1 has the Main Domain Controller and Site 2 has a secondary domain controller. Site 1 and 2 were replicating totally fine with each other. But sometimes when one or the other Site has an extended power outage the replication stops between the domain controllers. 

This has happened almost 3 times and the problem always happens in the branch office (site 2). 

The main domain controller in Head Office (site 1) can always replicate from site 2 correctly but site 2 cannot replicate from Site 1 the Head Office. The error i get on the site  2 domain controller is «The target Principal Name is incorrect» Last Error -2146893022 (0x80090322)

This is the 3rd time this has happened in the last year. I have to end up deleting and removing that domain controller from the domain and then creating a fresh one and rejoining the domain for things to get working again. 

Does anyone have an idea of how i can fix this issue?

Понравилась статья? Поделить с друзьями:
  • The table is full ошибка
  • The system seems to lack either network cards ошибка
  • The system has been destroyed xiaomi как исправить ошибку
  • The system cannot find the file specified ошибка
  • The surge 2 ошибка при запуске vulkan