System.SystemException: The trust relationship between this workstation and the primary domain failed

Indupriya Ashwathkumar 1 Reputation point
2022-04-20T04:18:38.753+00:00

we have software Tool on which we are trying to create a windows user as Service Account , to run some of the Services using that userService Account. In one of the machine, we have got the following exception which failed to create an UserAccount .

Error : 2022/02/21 10:24:06.276|ERROR|Failed to create Service Account : System.SystemException: The trust relationship between this workstation and the primary domain failed.
at System.Security.Principal.NTAccount.TranslateToSids(IdentityReferenceCollection sourceAccounts, Boolean& someFailed)
at System.Security.Principal.NTAccount.Translate(IdentityReferenceCollection sourceAccounts, Type targetType, Boolean forceSuccess)
at System.Security.Principal.NTAccount.Translate(Type targetType)
at InstallPackage.Models.ServiceAccount.ServiceAccountManager.IsServiceAccountExists(String name)
at InstallPackage.Models.ServiceAccount.ServiceAccountCreateTask.<OperationFunction>d__6.MoveNext() |features|

The following is the piece of code related to User Creation.

public bool CreateServiceAccount(string userName)
{
var isUserCreated = false;
//create service Account to install and run services
bool userExists = IsServiceAccountExists(userName);
if (userExists)
{
DeleteUser(userName, serviceCredentialsFile);
}
isUserCreated = CreateUser(userName, serviceCredentialsFile);
return isUserCreated;
}
private bool IsServiceAccountExists(string name)
{
bool exists = false;
try
{
NTAccount acct = new NTAccount(name);
SecurityIdentifier id = (SecurityIdentifier)acct.Translate(typeof(SecurityIdentifier));
exists = id.IsAccountSid();
}
catch (IdentityNotMappedException ex)
{
_log.LogError("Invalid user account " + ex.ToString());
}
catch (Exception ex)
{
_log.LogError("Error in verifying the service account exist: " + ex);
}
return exists;
}
private bool CreateUser(string userName, string serviceCredentialsFile)
{
try
{
var encryptedPwd = string.Empty;
string plainPassword = CommonHelper.GetRandomPassword();
encryptedPwd = Crypto.ProtectStringV1(plainPassword);
DirectoryEntry activeDirectory = new DirectoryEntry("WinNT://" +
Environment.MachineName + ",computer");
DirectoryEntry newUser = activeDirectory.Children.Add(userName, "user");
newUser.Invoke("SetPassword", new object[] { plainPassword });
newUser.Invoke("Put", new object[] { "Description", "Service account for Windows Services" });
newUser.CommitChanges();
DirectoryEntry grp;
ServiceAccountStoreSettings serviceAccountCredentialDetails = new ServiceAccountStoreSettings
{
UserName = userName,
EncryptedPassword = encryptedPwd
};
var protectedJsonData = Protect.ProtectSettingFile(JsonSerializer.Serialize(serviceAccountCredentialDetails));
File.WriteAllText(serviceCredentialsFile, protectedJsonData);
var UsersGroup = WindowsGroupPermissionsManager.GetGroupByName(
WindowsGroupPermissionsManager.USERS_GROUP_NAME, WindowsGroupPermissionsManager.USERS_GROUP_DESC);
// add ServiceUser to Group
AddUserToGroups(activeDirectory, newUser,UsersGroup.Name);
var principalContext = new PrincipalContext(ContextType.Machine);
var performanceMonitorGroup = GroupPrincipal.FindByIdentity(principalContext, "Performance Monitor Users");
// add ServiceUser to Performance Monitor Users Group
AddUserToGroups(activeDirectory ,newUser,performanceMonitorGroup.Name);
var performanceLogUsersGroup = GroupPrincipal.FindByIdentity(principalContext, "Performance Log Users");
// add ServiceUser to Performance Log Users Group
AddUserToGroups(activeDirectory ,newUser,performanceLogUsersGroup.Name);
_log.LogInformation("Account Created Successfully");
GrantLogonAsServiceRight(userName);
return true;
}
catch (Exception ex)
{
_log.LogError("unable to create user Account", ex.ToString());
return false;
}
}

.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,137 questions
{count} votes