Showing posts with label AD. Show all posts
Showing posts with label AD. Show all posts

Wednesday, July 23, 2014

C# Learning - Creating new AD accounts

I've been coding in PowerShell for 2 years now, and I gotta say switching over to C# is a nightmare! I do like it though, its has been a great fun experience. Once I got past the whole "Hello world" tutorials and learning the syntax it got a lot more fun. I'm not that I'm an expert in any way, but I believe I'm starting to get a hang of what is going on, which makes me happy.

Today as part of my on going project I had to create a function to create AD users through C#, and I'm using System.DirectoryServices class which actually requires that you add each property to the user, but doesn't actually tell you what does properties are, so after some looking around I found a table in this article. It made it a lot simpler than trying to guess the names. Here is the table for those that just want to get a quick look:


LDAP Attribute

Example

CCountry: e.g GB for Great Britain.
CN - Common NameCN=Guy Thomas.  Actually, this LDAP attribute can be made up from givenName joined to SN.
CNMaps to 'Name' in the LDAP provider. Remember CN is a mandatory property.  See also sAMAccountName.
descriptionWhat you see in Active Directory Users and Computers.  Not to be confused with displayName on the Users property sheet.
displayNamedisplayName = Guy Thomas.  If you script this property, be sure you understand which field you are configuring.  DisplayName can be confused with CN or description.

DN - also distinguishedNameDN is simply the most important LDAP attribute.
CN=Jay Jamieson, OU= Newport,DC=cp,DC=com
givenNameFirstname also called Christian name
homeDriveHome Folder : connect.  Tricky to configure
initialsUseful in some cultures.
namename = Guy Thomas.  Exactly the same as CN.
objectCategoryDefines the Active Directory Schema category. For example, objectCategory = Person
objectClassobjectClass = User.  Also used for Computer, organizationalUnit, even container.  Important top level container.
physicalDeliveryOfficeNameOffice! on the user's General property sheet
postOfficeBoxP.O. box.
profilePathRoaming profile path: connect.  Trick to set up
sAMAccountNameThis is a mandatory property, sAMAccountName = guyt.  The old NT 4.0 logon name, must be unique in the domain. 
sAMAccountNameIf you are using an LDAP provider 'Name' automatically maps to sAMAcountName and CN. The default value is same as CN, but can be given a different value.
SNSN = Thomas. This would be referred to as last name or surname.
titleJob title.  For example Manager.
userAccountControlUsed to disable an account.  A value of 514 disables the account, while 512 makes the account ready for logon.
userPrincipalNameuserPrincipalName = guyt@CP.com  Often abbreviated to UPN, and looks like an email address.  Very useful for logging on especially in a large Forest.  Note UPN must be unique in the forest.
wWWHomePageUser's home page.

Examples of Exchange Specific LDAP attributes

homeMDB Here is where you set the MailStore
legacyExchangeDNLegacy distinguished name for creating Contacts. In the following example,
Guy Thomas is a Contact in the first administrative group of GUYDOMAIN: /o=GUYDOMAIN/ou=first administrative group/cn=Recipients/cn=Guy Thomas
mailAn easy, but important attribute.  A simple SMTP address is all that is required billyn@ourdom.com
mAPIRecipient - FALSEIndicates that a contact is not a domain user.
mailNicknameNormally this is the same value as the sAMAccountName, but could be different if you wished.  Needed for mail enabled contacts.
mDBUseDefaultsAnother straightforward field, just the value to:True
msExchHomeServerNameExchange needs to know which server to deliver the mail.  Example:
/o=YourOrg/ou=First Administrative Group/cn=Configuration/cn=Servers/cn=MailSrv
proxyAddressesAs the name 'proxy' suggests, it is possible for one recipient to have more than one email address.  Note the plural spelling of proxyAddresses.
 targetAddressSMTP:@ e-mail address.  Note that SMTP is case sensitive.  All capitals means the default address.
 showInAddressBookDisplays the contact in the Global Address List.

cCountry or Region
companyCompany or organization name
departmentUseful category to fill in and use for filtering
homephoneHome Phone number, (Lots more phone LDAPs)
l  (Lower case L)L = Location.  City ( Maybe Office
locationImportant, particularly for printers and computers.
managerBoss, manager
mobileMobile Phone number
ObjectClassUsually, User, or Computer
OUOrganizational unit.  See also DN
pwdLastSetForce users to change their passwords at next logon
postalCodeZip or post code
stState, Province or County
streetAddressFirst line of address
telephoneNumberOffice Phone
userAccountControlEnable (512) / disable account (514)

Examples of Obscure LDAP Attributes

dNSHostname
rID
url
uSNCreated, uSNChanged

I removed the Ads because I'm not sure if they would affect his stuff. 

Here is the difference in code from creating users in PowerShell and in C#:

PowerShell * In this particular example I'm taking the values from a CSV, which allows me to create multiple accounts very quickly. 

//This is needed
Import-Module ActiveDirectory

New-ADUser -AccountPassword (ConvertTo-SecureString -AsPlainText "PASSWORDHERE" -Force-Server 'DCHOSTNAME' `
        -Enabled $true `
        -Name $file.username `
        -GivenName $file.name `
        -Surname $file.lastname `
        -Initials $file.middle `
        -DisplayName $file.displayname `
        -SamAccountName $file.username `
        -Office $file.office `
        -Department $file.Department `
        -Company $file.company `
        -StreetAddress $file.Street `
        -City $file.city `
        -State $file.state `
        -PostalCode $file.postalcode `
        -Country $file.country  `
        -Description $file.description `
        -Path $file.path `
        -UserPrincipalName $file.userprincipalname `
        -EmailAddress $file.userprincipalname `
        -OtherAttributes @{'co'="United States"'countryCode'="840"


C# * Please note that I am passing the variables from the "OnClick" function for a button, and also that all the properties name are not provided to you as they are in PowerShell. Final note there is some parameters that have not yet been used as they will be added at a later point when I create the mailbox. 

//These are required
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;

public void createUser(int ticketnumber, string firstname, string middleIn, string lastName, 
string samaccountname, string email, string telephone, string hemisphere, string company, 
string office, string address, string city, string state, string division, string Code, 
string OrganizationalUnit, string country, string department, string title, string displayName, 
string postalCode, string co, string Manager)
        {
            string path = "LDAP://" + OrganizationalUnit;
            int NORMAL_ACCOUNT = 0x200;
            int PWD_NOTREQD = 0x20;
            try
            {
                using (DirectoryEntry ou = new DirectoryEntry(path))
                {
                    DirectoryEntry user = ou.Children.Add("CN=" + samaccountname, "user");
                    user.Properties["SamAccountName"].Add(samaccountname);
                    user.Properties["userPrincipalName"].Add(samaccountname + "@DOMAIN");
                    user.Properties["name"].Add(firstname + " " + lastName);
                    user.Properties["givenName"].Add(firstname);
                    user.Properties["initials"].Add(middleIn);
                    user.Properties["SN"].Add(lastName);
                    user.Properties["telephoneNumber"].Add(telephone);
                    user.Properties["company"].Add(company);
                    user.Properties["physicalDeliveryOfficeName"].Add(office);
                    user.Properties["streetAddress"].Add(address);
                    user.Properties["l"].Add(city);
                    user.Properties["st"].Add(state);
                    user.Properties["co"].Add(country);
                    user.Properties["C"].Add(co);
                    user.Properties["department"].Add(department);
                    user.Properties["title"].Add(title);
                    user.Properties["userAccountControl"].Value = NORMAL_ACCOUNT | PWD_NOTREQD;
                    user.Properties["description"].Add("AC #" + ticketnumber + " JB | Created with JBSoftware");
                    user.Properties["displayName"].Add(displayName);
                    user.Properties["objectCategory"].Add("PERSON");
                    user.Properties["postalCode"].Add(postalCode);
                    user.Properties["manager"].Add(Manager);
                    user.CommitChanges();
                }
            }
            catch (System.DirectoryServices.DirectoryServicesCOMException E)
            {
                MessageBox.Show(E, "ERROR!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw;
            }        }


Well I think that is it for the day, I hope that this information might be useful to someone out there!

Edit >
It seems that I forgot a simple o in the Country property. (see in bold)

Wednesday, July 16, 2014

Locked Account

Very often I get tickets of accounts that keep getting locked out. When I check the logs all I get is that the service name Kerberos Authentication Service (krbtgt) is the one that is causing the issue. Recently I wanted to provide a user with more information and started looking at exactly what each error code meant, and I found the following table, I thought it was worth sharing it.



Result code Kerberos RFC description Notes on common failure codes
0x1 Client's entry in database has expired
0x2 Server's entry in database has expired
0x3 Requested protocol version # not supported
0x4 Client's key encrypted in old master key
0x5 Server's key encrypted in old master key
0x6 Client not found in Kerberos database Bad user name, or new computer/user account has not replicated to DC yet
0x7 Server not found in Kerberos database  New computer account has not replicated yet or computer is pre-w2k
0x8 Multiple principal entries in database
0x9 The client or server has a null key  administrator should reset the password on the account
0xA Ticket not eligible for postdating
0xB Requested start time is later than end time
0xC KDC policy rejects request Workstation restriction
0xD KDC cannot accommodate requested option
0xE KDC has no support for encryption type
0xF KDC has no support for checksum type
0x10 KDC has no support for padata type
0x11 KDC has no support for transited type
0x12 Clients credentials have been revoked Account disabled, expired, locked out, logon hours.
0x13 Credentials for server have been revoked
0x14 TGT has been revoked
0x15 Client not yet valid - try again later
0x16 Server not yet valid - try again later
0x17 Password has expired The user’s password has expired.
0x18 Pre-authentication information was invalid Usually means bad password
0x19 Additional pre-authentication required*
0x1F Integrity check on decrypted field failed
0x20 Ticket expired Frequently logged by computer accounts
0x21 Ticket not yet valid
0x21 Ticket not yet valid
0x22 Request is a replay
0x23 The ticket isn't for us
0x24 Ticket and authenticator don't match
0x25 Clock skew too great Workstation’s clock too far out of sync with the DC’s
0x26 Incorrect net address  IP address change?
0x27 Protocol version mismatch
0x28 Invalid msg type
0x29 Message stream modified
0x2A Message out of order
0x2C Specified version of key is not available
0x2D Service key not available
0x2E Mutual authentication failed  may be a memory allocation failure
0x2F Incorrect message direction
0x30 Alternative authentication method required*
0x31 Incorrect sequence number in message
0x32 Inappropriate type of checksum in message
0x3C Generic error (description in e-text)
0x3D Field is too long for this implementation




Source: http://www.ultimatewindowssecurity.com/securitylog/encyclopedia/event.aspx?eventid=4768

I was able to find even more information in the Technet post:

http://technet.microsoft.com/en-us/library/bb463166.aspx