Search code examples
c#windowsactive-directoryaccount

How can I check whether the domain account of a computer got invalid (the trust is broken)?


I must recognize notebooks whose domain accounts are no longer valid.

Invalid domain accounts may happen due to several problems. Mostly the client got restored from a backup and afterwards the domain account is not valid any more

Int this case the behavour is:

  • The user's logon works through cached credentials
  • The user has access to shares and files on the server (NTLM)
  • Access via Kerberos does not work

Is there any possibility to check the validity of the computer account?


Solution

  • With this code I can find invalid computer domain accounts:

    try
    {
        string sMyComputer = "MyComputer"
        Domain computerDomain = Domain.GetComputerDomain(); // may! throw ActiveDirectoryObjectNotFoundException if computer account is invalid 
        string sComputerDomain = computerDomain.Name;
        NTAccount acc_machine = new NTAccount(sComputerDomain, sMyComputer + "$"); 
        SecurityIdentifier sid = (SecurityIdentifier)acc_machine.Translate(typeof(SecurityIdentifier)); // always throws an SystemException if computer account is invalid
    }
    catch    
    { 
       // something is wrong with the account    
    }
    
    • sMyComputer + "$" is how the account name is stored in the active directory
    • my experience is that the first exception is mostly not thrown and the return value is the correct name of the domain the computer had once a working computer account
    • the second exception (SystemException) is always thrown if computeraccount is now invalid. The errocode is 80004005. (I had expected an IdentityNotMappedException)

    EDIT:
    corrected error in code