Connecting to remote Active Directory using C# .Net - c#

I want to connect to a ActiveDirectory using c#.
I need to be able to connect to an DC which I can only resolve using an IP Address (which I have).
The next step is to find a computer in the DC address leases to resolve the IP address of a computername entered by a user.
Can someone give me a heads up?
I should be using
DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://DC-IpAddress");
directoryEntry.Path = "LDAP://(What should I enter here for "Address Leases"?);
then I need a returned value which gives me the IP-Address of target Computer.
Hope you folks can help me out a bit.
FYI: The DHCP Server is installed on the target DC. just in case ;)

in this link VB project which is contains in the forth section a method that Listing all computers in the Active Directory .. may it helpful for you
http://www.codeproject.com/Articles/19689/Working-with-Active-Directory-in-VB-NET

Related

Port requirements for System.DirectoryServices.ActiveDirectory

We have a product which implements role based authentication using AD.
At the start of this application, it tries to enumerate through all the domains in the current forest to fetch some information which will be used later.
A snippet of the code is shown below
Domain currentDomain = Domain.GetDomain(new DirectoryContext(DirectoryContextType.Domain));
Forest currentForest = currentDomain.Forest;
string forestName = currentForest.Name;
foreach (Domain domain in currentForest.Domains)
{
//processing code.
}
The above code runs fine until 3rd statement and the forestName variable is initialized properly with the current forest name.
But it fails in the foreach loop when it tries to execute currentForest.Domains
We are getting an ActiveDirectoryServerDownException with the error message "The specified domain either does not exist or could not be contacted" with an error code 1355.
From the below link, I got to know that this could be a dns misconfiguration or the ports might be blocked by firewall.
https://social.technet.microsoft.com/Forums/msonline/en-US/53804e9d-ccdd-450a-967b-b7e8f67cddae/active-directory-error-code-1355?forum=winserverDS
I am trying to understand the ports that need to be open for communication on server machine(Active directory server) and client machine.
The below link specifies so many number of ports which confused me.
https://support.microsoft.com/en-us/help/832017/service-overview-and-network-port-requirements-for-windows
Can some one provide me information on what are the ports that are required to be open on server and client machines so that I can successfully enumerate all the domains in the forest.
Those methods use the LDAP protocol to talk to AD, which is all over port 389.
Just to be sure, I ran your code and watched the network connections it used, and it only used port 389.
As a side note, you can simplify your code a little by using Forest.GetCurrentForest() instead of looking up the current domain then looking up the forest for that domain.
Forest currentForest = Forest.GetCurrentForest();
Either way will get the same job done.

Get user groups call to LDAP server gets "The server is not operational" because the server called changes

I'm trying to get the groups for a user from an ADAM server using:
PrincipalContext yourDomain = new PrincipalContext(ContextType.ApplicationDirectory,
principalContextName,
principalContextContainer,
ContextOptions.ServerBind | ContextOptions.SimpleBind,
principalContextUserName,
principalContextPassword);
UserPrincipal user = UserPrincipal.FindByIdentity(yourDomain,
IdentityType.UserPrincipalName,
userName);
PrincipalSearchResult<Principal> groups = user.GetAuthorizationGroups();
And I keep getting the "server is not operational" error.
I finaly understood my problem but I dont know how to fix it.
The thing is that, the two ADAM servers are behind a firewall and an NLB, they both reply by the name of adam.company.local and the nslookup of that name, reply's 100.10.130.1
I can even ping the 100.10.130.1 and the name adam.company.local so the problem wasn't networking, but it is!
With WireShark I found out that at some point the server returns his own name and my calls start trying to call that name. Of course then the firewall blocks them and the exception occurs.
To confirm this, I made 2 lines on the hosts file, with both server names to 100.10.130.1 and the problem was gone, I could retrieve all the groups with ease.
Why is that? why does de connection change to a machine I cant get to?
The final question is how do I prevent it because on the publication machine I cant create these lines on the hosts file?

Dns.GetHostName() , From where information is retrived

I am facing problem where after changing host name my application is failing. In investigation i found that Dns.GetHostName() is still returning old host name .
I am trying to get info on source of host name for function Dns.GetHostName().
Thanks a lot
Dns.GetHostName queries your DNS servers registered in your IP settings for your name (that's why it can return socket exception). DNS info is cached. You can do ipconfig /flushdns to clear it.
You can also get the netbios machine name from Environment.MachineName which is the static machine name from the registry. Note that netbios machine names are limited to 15 chars while DNS names are not.
If you have just changed your MachineName, the new name doesn't take effect until the next time you restart your computer. I'm not 100% sure if this function works the Same way as Environment.Machinename (which is definately not updated until next restart).

Get mac address from IP using DHCP?

I am trying to create scripts/services that allow for waking PCs in a windows domain via WOL. Now i want to give the user the option to select an AD container as a starting point for the waking of PCs contained within. My initial thought is using DHCP as a repository to query for MAC addresses given the hostnames (which i can easily enough pull from AD given the container).
Is there a way to programmatically query the DHCP service/server, passing hostnames and recover the associated MAC addresses?
Or, is there a better/easier way to solve my problem?
This is a little bit wacky it seems that there's no way to query the DHCP server programmatically. Thanks cottsak for asking the question. I understand that the DHCP protocol doesn't have such a query, but I thought mayb the executable from Microsoft might have some way you can address it from the command line. I haven't heard anybody anywhere say that there is no such case, but it must be so.
WHOA, wait a minute... I think I found what we're looking for: NETSH. cf:
http://social.technet.microsoft.com/Forums/en/ITCG/thread/afb4be16-09bd-4260-b515-8323d85d4ccb
Where it says if you open a command prompt on the DHCP server you can run this command:
netsh dhcp server scope 192.168.1.0 show clients
and get a report such as this:
10.10.98.53 - 255.255.255.0 -00-0c-29-02-a4-09 - NEVER EXPIRES -D
10.10.98.54 - 255.255.255.0 - 00-22-19-10-29-75 -1/21/2012 8:39:25 AM -D
Yippeee! Thanks for the thread!! If it wasn't for this one, I enver would have narrowed my search to technet adn found that one.
Try dhcpexim.exe from microsoft.
or, if you prefer using pure C. DhcpEnumSubnetClientsV4
No problem; because all of the machines are in your domain you can put together a VBScript that will get the MACAddress(es) from the local machine and store it as an attribute of the computer object in Active Directory.
Here's a quick hack on how to do that (save this as a .vbs-file):
Option Explicit
Const ADS_PROPERTY_UPDATE = 2
Const COMPUTERLOCATION = "ou=Member Servers,dc=yourdomain,dc=com"
Const ATTRIBUTETOUSE = "otherTelephone"
Dim wshNetwork, strComputerName
Set wshNetwork = WScript.CreateObject("WScript.Network")
strComputerName = wshNetwork.ComputerName
Dim objWMIService, colNetCards, objComputer, objNetCard
Set objWMIService = GetObject("winmgmts:\\" & strComputerName & "\root\cimv2")
Set colNetCards = objWMIService.ExecQuery("Select * From Win32_NetworkAdapterConfiguration Where IPEnabled = True")
Set objComputer = GetObject("LDAP://cn=" & strComputerName & "," & COMPUTERLOCATION)
For Each objNetCard in colNetCards
objComputer.PutEx ADS_PROPERTY_APPEND, ATTRIBUTETOUSE, Array(objNetCard.MACAddress)
objComputer.SetInfo
Next
Because your clients aren't all in the "Member Servers" OU above you'll need to modify the above script to include a directory search for the strComputerName do get the COMPUTERLOCATION.
When you have a working script, ask your domain administrator to put the script as a start-up script targetting the computers you need to monitor; that way it'll execute whenever a computer boots up. You can also run the script as a scheduled task to get your data from any clients that haven't rebooted or use psexec or some other way you can think of to get the data immediately. Or you can rewrite the script entirely to remote connect to all of your machines and get the data that way (which might not be possible due to local firewalls). Or you could write a small .NET console application which does the same thing, it's up to you...
Also, although there is a networkAddress-attribute defined for computer objects; by default the computer object itself does not have access to write to this property. Because start up-scripts run in the context of the SYSTEM account on the particular machine the easiest thing is to use an attribute that the computer object (SELF) has write access to. The otherTelephone-attribute is multivalued and part of the Personal-Information Property Set which all computer objects has write access to by default. If you want to use the networkAddress-attribute you need to set explicit write access to that attribute for all of your computers.
Also you need to bear in mind that storing the the MAC address in Active Directory means that all of the users in your domain will have read access to it which in turn might possibly (depending on your environment) pose a small security risk.
To do it the way the network does.
Grab SharpPcap (Pcap wrapper for C#) and WinPcap (Windows) or libpcap (*nix). Write an application that creates SNMP packets to query the ARP table on the router.
Note: The ARP (Address Resolution Protocol) table is the table containing the mapping of IP address to MAC address.
I've been thinking about implementing an example that does this lately but I don't have one to show yet. Once I do, I'll make sure it gets added to the SharpPcap examples found in the project's source tree.
You can't do that with DHCP. DHCP attributes IP from MAC, not the other way around.
ARP is what converts IP into MAC but it's the machine itself that answers ARP requests so if it's off it's obviously not gonna answer ...
I suggest you store the MAC in your AD directly (I guess AD supports custom attributes ?)
you need to use arp to get a mac adress and doing so In C is a long process.
Mac adresses are hard coded, so if you have X computers go and get X mac addresses and tie them to the AD.
Note that the computer will have to be on to request its mac address.
Finding MAC address from IP address
Yeah dun worry about it, you can pull this info directly from DHCP if the PC has a lease.
Know how you right click and add a reservation in DHCP?
Look in DHCP for the 'unique ID'. It's the MAC address, sans the colons.

problem connecting to Active Directory server in C# .NET

I'm currently writing some software in C# which needs to connect to an AD server and get some user details. When I connect using the code below it works against most AD servers that I connect to but there are a couple where it fails with an error of "Logon failure: unknown user name or bad password.". The server name / credentials I'm using are definately correct as I've tested them with an LDAP Browser and the AD server is using standard security (port 389 etc). Can anyone offer any advice?
Cheers
Tim
DirectoryEntry d = new DirectoryEntry("LDAP://" + domain, admin_username, admin_password);
try
{
object x = d.NativeObject;
}
catch
{
throw;
}
I've had similar issues programming .net / AD in the past. One thing I found useful is using an LDAP viewer to see if I can connect to certain servers, etc. In this way, I can at least determine if it is a .NET error (perhaps my code), a credential error, etc.
I use the free/lite version of Softerra's LDAP viewer (http://www.ldapbrowser.com/download.htm) although I'm sure there are many others to choose from out there. If you try the one listed here, make sure to download the 'LDAP browser' and not 'LDAP Administrator'. The browser is the free one.
Try connecting to the same LDAP path you're having trouble with in code, using a LDAP browser/viewer. This will at least as step one determine if it is a .NET/code issue or not. If you can't connect via the browser, it can be helpful to play around with the connection options, such as port, domain (FQDN), etc.
Hope this might help narrow things down.
Active Directory allows at least three different logon name styles:
LDAP - i.e. LDAP DN. For example: cn=JohnS, ou=Users, dc=example, dc=com
NTLM. For example: EXAMPLE\JohnS
Kerberos principal name: For example: johns#example.com
However, you cannot login with just JohnS like you do with Windows box. It's a very common mistake.

Categories