Is there any way to validate given password is valid with computer object created in AD? - active-directory

I just created computer object in active directory. I set password for computer object using SetPassword Command. How can we verify password for computer object or authenticate with that password? Is there any way to validate that password is valid with that computer?

Validating a computer account password can be done in the same way as user passwords. Computer accounts also have a username SamAccountName.
I'm not sure how to provide an example as you have not specified any programming platform but for the sake of it here is an example using c# and the System.DirectoryServices.AccountManagement namespace.
string password = "securepassword";
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
using (ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(context, "Temp1"))
{
computer.SetPassword(password);
Console.WriteLine(context.ValidateCredentials(computer.SamAccountName, string.Empty).ToString()); // Returns False
Console.WriteLine(context.ValidateCredentials(computer.SamAccountName, password).ToString()); //Returns True
}

Related

LDAP Bind allowing incorrect (non-blank) password

We have a customers AD system that we authenticate users against using LDAP, specifically by doing a bind using their username and password. Depending on how the username is structured the results of an incorrect password are different. If we include the domain name on the username then ANY password will return an authenticated result. I've pasted some results using LDP.exe for each of the scenarios:
Bind with myusername & invalid (non blank) password:
res = ldap_bind_s(ld, NULL, &NtAuthIdentity, 1158); // v.3
{NtAuthIdentity: User='[username]'; Pwd= <unavailable>; domain = 'DC=[domain],DC=co,DC=uk'.}
Error <49>: ldap_bind_s() failed: Invalid Credentials.
Server error: 8009030C: LdapErr: DSID-0C090585, comment: AcceptSecurityContext error, data 52e, v4563
Bind with myusername#domain.org & invalid (non blank) password:
res = ldap_bind_s(ld, NULL, &NtAuthIdentity, 1158); // v.3
{NtAuthIdentity: User='[myusername#domain.org]'; Pwd= <unavailable>; domain = 'DC=[domain],DC=co,DC=uk'.}
Authenticated as dn:'[username#domain.org]'.
What I have noticed is that the users full username is username#domain.org and the domain provided to LDAP is DC=domain,DC=co,DC=uk, not sure if this would make a difference?
Does anyone have any ideas on what maybe causing this and whether there is some sort of setup somehwere that needs addressing?
Cheers.
Is the Guest account enabled on the domain? If so, any random credentials will work. It will only tell you that the password is incorrect if you use a valid username.
When you use the myusername format, it must match the sAMAccountName attribute on the account. If you use the myusername#domain.org format, it must match the userPrincipalName on the account - so it's possible that myusername#domain.org is not really the userPrincipalName of your account.

Not able to login after create the user in AD using Java

I have written code using JNDI for creating users using DirContext in AD.
After I create the user I am not able to login with those credentials. When I manually reset the password for that user in AD, I am able to login.
Here I have placed my code for your reference,
Hashtable<String, String> ldapenv = new Hashtable<>();
ldapenv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
ldapenv.put(Context.PROVIDER_URL, "ldap://10.95.144.139:389");
ldapenv.put(Context.SECURITY_AUTHENTICATION, "simple");
ldapenv.put(Context.SECURITY_PRINCIPAL, "CN=Administrator,CN=Users,dc=Merck,dc=local");
ldapenv.put(Context.SECURITY_CREDENTIALS, "Merck2017");
DirContext context = new InitialDirContext(ldapenv);
Attributes attributes = new BasicAttributes();
// Create the objectclass to add
Attribute objClasses = new BasicAttribute("objectClass");
objClasses.add("top");
objClasses.add("person");
objClasses.add("organizationalPerson");
objClasses.add("user");
// Assign the username, first name, and last name
String cnValue = new StringBuffer(user.getFirstName()).append(" ").append(user.getLastName()).toString();
Attribute cn = new BasicAttribute("cn", cnValue);
Attribute sAMAccountName = new BasicAttribute("sAMAccountName", user.getUserName());
Attribute principalName = new BasicAttribute("userPrincipalName", user.getUserName()
+ "#" + "merck.local");
Attribute givenName = new BasicAttribute("givenName", user.getFirstName());
Attribute sn = new BasicAttribute("sn", user.getLastName());
Attribute uid = new BasicAttribute("uid", user.getUserName());
// Add password
Attribute userPassword = new BasicAttribute("userPassword", user.getPassword());
Attribute pwdAge = new BasicAttribute("pwdLastSet","-1");
Attribute userAccountControl = new BasicAttribute("userAccountControl", "544");
// Add these to the container
attributes.put(objClasses);
attributes.put(sAMAccountName);
attributes.put(principalName);
attributes.put(cn);
attributes.put(sn);
attributes.put(givenName);
attributes.put(uid);
attributes.put(userPassword);
attributes.put(userAccountControl);
attributes.put(pwdAge);
// Create the entry
try {
context.createSubcontext(getUserDN(cnValue,"Merck-Users"), attributes);
System.out.println("success === ");
} catch (Exception e) {
System.out.println("Error --- "+e.getMessage());
}
Please help me resolve the following issues:
How do I set AD user password while creating the user using the above code?
How do I set userAccountControl to 66048 in the above code?
How do I create the user enabled while using the above code?
How do I disable the option "user must change the password in next login" while creating the user in the above code?
Thanks in advance.
I don't have all the answers, but this should get you started:
Passwords can only be set over a secure channel, like LDAPS (LDAP over SSL). Since you are connecting to port 389, that is not SSL and AD won't let you set the password. You must connect to the LDAPS port: 636. You may run into issues trusting the SSL certificate. I can't help much here since I'm not a Java developer, but there is an example here.
The answer to your second and third questions is the same: Accounts with no passwords are always disabled. Since you haven't set the password properly, the account will be disabled. Once you figure out how to set the password, you can also set userAccountControl to whatever you need.
You are disabling the "user must change password" option correctly: by setting pwdLastSet to -1. That's the right way to do it. But you may have to fix the other issues first.
Another important thing: I have created AD accounts in .NET, and I have found that I had to create the account first, then go back and set the password and set the userAccountControl attribute after. You may have to do the same.

What "domain" should I specify in JNDI login to an Active Directory Server?

I'm wondering what "principal" I should specify to login in to an Active Directory server. Should the principal be a user inside the AD I try to log into? Or it can be a user in the domain I specify as long as the user has privileges to access the AD?
I tried both with credentials error 49. But I can log in to the AD with ldp.exe by using the Administrator account of the server that AD is installed on.
Here is my code. Many thanks for any prompt help.
Hashtable env= new Hashtable(11);
env.put(Context.SECURITY_AUTHENTICATION,"simple"); // Also tried none w/ the same error
// What principal should I use??
env.put(Context.SECURITY_PRINCIPAL,"CN=Ross,OU=Eng,DC=RossInc");//User
//env.put(Context.SECURITY_PRINCIPAL, user + "#" + domain); // Tried w/ the same error
env.put(Context.SECURITY_CREDENTIALS, "ross");//Password
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL,"ldap://myserver:389/DC=RossInc");
DirContext ctx = new InitialDirContext(env); <-- Fails with AuthenticationException: [LDAP: error code 49 - 8009030C
You either can provide:
NT-style login name
Kerberos UPN (implicit UPN)
explicit UPN (if additional UPN suffices have been defined)
More over, NEVER ever perform a simple bind! Either Digest or GSS-API.
According to the following example from Oracle site, the security Principal is a distinguished name.
Here is some code working for me from a computer inside the domain :
Hashtable<String, String> ldapEnv = new Hashtable<String, String>(11);
ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
ldapEnv.put(Context.PROVIDER_URL, "ldap://societe.fr:389");
ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
ldapEnv.put(Context.SECURITY_PRINCIPAL, "cn=administrateur,cn=users,dc=societe,dc=fr");
ldapEnv.put(Context.SECURITY_CREDENTIALS, "test.2011");
ldapContext = new InitialDirContext(ldapEnv);
The principal can be a user inside the AD as long as he has privileges to access the AD.

Winform user authorization via active directory

I have a situation where I am using the following code to verify user membership in AD before executing tasks in my app
using System.Security.Principal;
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole("someGroup");
The above code works fine for machines on my domain, however I do have some machines which are not on my domain on which I have the WINFORM application installed. How can I verify the user membership in AD?
Edit - is there a way to prompt the windows login?
Since your computer is not joined to domain at all, we cannot use WindowsIdentity or WindowsPrincipal and then check its IsInRole() method. The IsInRole() method works only if your computer is joined to the domain and it's using your domain machine account to do S4USelf.
You cannot use LogonUser approach too because your computer won't let you create a logon session from an untrusted forest.
I think we can only query the Active Directory directly to get the information we want. The code in your posted Microsoft KB does not work very well as far as I can tell. It's trying to query from memberOf attribute. The group information is not always available from the memberOf attributes.
I just wrote an IsInRole() function using AccountManagement. I guess this is what you want. The IsInRole() function will call a recursive function IsInGroup() to find out all the groups the user belongs to.
private bool IsInRole(string domain, string username, string password, string role)
{
using (var context = new PrincipalContext(ContextType.Domain, domain, username, password))
{
GroupPrincipal group = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, role);
UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username);
return IsInGroup(user, group);
}
}
private bool IsInGroup(Principal principal, GroupPrincipal group )
{
if (principal.IsMemberOf(group))
return true;
foreach (var g in principal.GetGroups())
{
if (IsInGroup(g, group))
return true;
}
return false;
}
To use this IsInRole() function, you need to provide your domain name and domain credentials. If the username and password provided are wrong, you will get an exception.
You need .NET 3.5 SP1 to use AccountManagement API. Also, you may like to pay attention to this hotfix. The AccountManagement API got some bugs if running in some environment. You may need to apply the hotfix.

Need help debugging a custom authentication plugin for Moodle

I'm trying to authenticate against the user db of my website (CMS based) and it uses a slightly different approach at storing hashed passwords. It uses a randomly generated salt for each user. The salt is stored in the user db along with the hashed passwords. Hence, direct field-mapped authentication (as the External DB plugin does) won't work for me.
To start off, I just mirrored the DB plugin and modified the user_login() procedure to read the hashed password and the salt from the database and then hash the entered password again with the salt and match it up with the password in the database. Here's the code for my user_login() function
function user_login($username, $password) {
global $CFG;
$textlib = textlib_get_instance();
$extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->extencoding);
$extpassword = $textlib->convert(stripslashes($password), 'utf-8', $this->config->extencoding);
$authdb = $this->db_init();
// normal case: use external db for passwords
// Get user data
$sql = "SELECT
*
FROM {$this->config->table}
WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."' ";
$authdb->SetFetchMode(ADODB_FETCH_ASSOC);
// No DB Connection
if ( !$rs = $authdb->Execute( $sql ) ) {
$authdb->Close();
print_error('auth_dbcantconnect','auth');
return false;
}
// No records returned
if( $rs->EOF ) {
$rs->Close();
$authdb->Close();
return false;
}
// Get password
$db_password = $rs->fields['user_password'];
$salt = $rs->fields['user_salt'];
// Close DB Conn
$rs->Close();
$authdb->Close();
// Return match
return sha1( $extpassword . $salt ) == $db_password;
}
But when I try to login, username / passwords corresponding to the website (CMS) database are failing. However, the password (for the same user) that was stored in Moodle earlier on (before I tried using this custom plugin) is getting me through.
That means, either my authentication routine is failing or moodle's internal db based auth mechanism is taking precedence over it.
I've enabled ADODB debug mode - but that isn't helping either. When I enable the debug output from Server settings, the error messages are being sent prior to the page headers. Thus the login page won't display at all.
I have all other forms of authentication turned off (except for Manual which can't be turned off) and my own.
Any ideas on how to solve this issue?
Can you confirm the order that the authentication pluggins are displayed? This will determine the order in which they are used. See..
http://docs.moodle.org/en/Manage_authentication
Either way, the behaviour you're seeing suggests that your code is returning false and the fall through logic described here...
http://moodle.org/mod/forum/discuss.php?d=102070
... and here...
http://docs.moodle.org/en/Development:Authentication_plugins
... is kicking in.
Have you tried returning "true" always from your plugin to ensure that it's being called. Then, you can start returning "true" based upon other things (hard coded usernames etc). This approach will allow you to get to the point where you are either continuing to fail or seeing more targetted failures. Are you sure, for example, that it's the user_login function and not the subsequent call to update_user_record that is failing?
Finally, are you sure you're generating the salted password in the exact same way that it was created in the first place? This would be, for me, the most likely cause of the problem. Can you take control of the creation of the salted password so that you own both creation of new users and authentication of users - this would ensure that you were in sync with how the salted password and hash were generated.

Resources