VB - Active Directory Klasse


SUBMITTED BY: TheSwarm

DATE: Oct. 21, 2015, 8:31 a.m.

FORMAT: Text only

SIZE: 23.9 kB

HITS: 1713

  1. Imports System.Collections.Generic
  2. Imports System.DirectoryServices
  3. Imports System.DirectoryServices.ActiveDirectory
  4. Imports System.Security.Permissions
  5. Imports System.ComponentModel
  6. Imports System.Security
  7. Imports System.Text
  8. <DirectoryServicesPermissionAttribute(SecurityAction.LinkDemand, Unrestricted:=True)> _
  9. <DirectoryServicesPermissionAttribute(SecurityAction.InheritanceDemand, Unrestricted:=True)> _
  10. <DirectoryServicesPermissionAttribute(SecurityAction.Assert, Unrestricted:=True)> _
  11. Public Class ActiveDirectory
  12. Private user As String
  13. Private pass As String
  14. Public Enum LogonType As Integer
  15. LOGON32_LOGON_INTERACTIVE = 2
  16. LOGON32_LOGON_NETWORK = 3
  17. LOGON32_LOGON_BATCH = 4
  18. LOGON32_LOGON_SERVICE = 5
  19. LOGON32_LOGON_UNLOCK = 7
  20. LOGON32_LOGON_NETWORK_CLEARTEXT = 8
  21. LOGON32_LOGON_NEW_CREDENTIALS = 9
  22. End Enum
  23. Public Structure __TrustInformation
  24. Public SourceName As String
  25. Public TargetName As String
  26. Public TrustDirection As String
  27. Public TrustType As String
  28. End Structure
  29. Public Structure __Domain
  30. Public DomainMode As String
  31. Public TrustRelationships As List(Of __TrustInformation)
  32. End Structure
  33. Public Structure __ReplicationOperationInformationFailures
  34. Public ConsecutiveFailureCount As String
  35. Public FirstFailureTime As String
  36. Public LastErrorCode As String
  37. Public LastErrorMessage As String
  38. Public SourceServer As String
  39. End Structure
  40. Public Structure __ReplicationOperationInformation
  41. Public CurrentOperation
  42. Public OperationStartTime
  43. Public PendingOperations
  44. Public Failures As List(Of __ReplicationOperationInformationFailures)
  45. End Structure
  46. Public Structure __DomainController
  47. Public CurrentTime As String
  48. Public DomainName As String
  49. Public ForestName As String
  50. Public HighestCommittedUsn As String
  51. Public InboundConnections As String
  52. Public IPAddress As String
  53. Public Name As String
  54. Public OSVersion As String
  55. Public OutboundConnections As String
  56. Public Partitions As String
  57. Public Roles As String
  58. Public SiteName As String
  59. Public SyncFromAllServersCallback As String
  60. Public IsGlobalCatalog As String
  61. Public ReplicationOperationInformation As __ReplicationOperationInformation
  62. End Structure
  63. Public Structure __Object
  64. Public Name As String
  65. Public Description As String
  66. Public DistinguishedName As String
  67. End Structure
  68. Public Structure __Group
  69. Public Name As String
  70. Public Description As String
  71. Public DistinguishedName As String
  72. Public Members As List(Of __Object)
  73. End Structure
  74. Public Property Username() As String
  75. Get
  76. Return user
  77. End Get
  78. Set(ByVal value As String)
  79. user = value
  80. End Set
  81. End Property
  82. Public Property Password() As String
  83. Get
  84. Return pass
  85. End Get
  86. Set(ByVal value As String)
  87. pass = value
  88. End Set
  89. End Property
  90. Public ReadOnly Property ClassName() As String
  91. Get
  92. Return "ActiveDirectory"
  93. End Get
  94. End Property
  95. Private Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal lpszUsername As String, _
  96. ByVal lpszDomain As String, _
  97. ByVal lpszPassword As String, _
  98. ByVal dwLogonType As LogonType, _
  99. ByVal dwLogonProvider As Integer, _
  100. ByRef phToken As IntPtr _
  101. ) As Integer
  102. Private Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal hObject As IntPtr) As Boolean
  103. Public Sub New()
  104. user = ""
  105. pass = ""
  106. End Sub
  107. Public Sub New(ByVal username As String, ByVal password As String)
  108. user = username
  109. pass = password
  110. End Sub
  111. Public Function AddDoaminUserToGroup(ByVal LocalSystemName As String, _
  112. ByVal DOMAIN As String, _
  113. ByVal DomainUserName As String, _
  114. ByVal AddToLocalGroup As String _
  115. ) As Boolean
  116. Try
  117. Dim LocalSystem As New DirectoryEntry("WinNT://" & LocalSystemName & ",computer")
  118. Dim DomainName As New DirectoryEntry("WinNT://" & DOMAIN)
  119. Dim DOMUSR As DirectoryEntry = DomainName.Children.Find(DomainUserName, "user")
  120. Dim LocalGroup As DirectoryEntry = LocalSystem.Children.Find("Test", "group")
  121. LocalGroup.Invoke("Add", New Object() {DOMUSR.Path.ToString})
  122. Return True
  123. Catch ex As Exception
  124. Return False
  125. End Try
  126. End Function
  127. ''' <summary>
  128. ''' Authenticates the user.
  129. ''' </summary>
  130. ''' <param name="domain">The domain.</param>
  131. ''' <param name="username">The username.</param>
  132. ''' <param name="password">The password.</param>
  133. ''' <returns></returns>
  134. Public Shared Function AuthenticateUser(ByVal domain As String, ByVal username As String, ByVal password As String) As Boolean
  135. Dim pwd As New SecureString()
  136. Dim bAuth As Boolean = False
  137. Dim entry As DirectoryEntry = Nothing
  138. For Each c As Char In password
  139. pwd.AppendChar(c)
  140. Next
  141. pwd.MakeReadOnly()
  142. Dim pPwd As IntPtr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(pwd)
  143. Try
  144. entry = New DirectoryEntry(String.Concat("LDAP://", domain), username, System.Runtime.InteropServices.Marshal.PtrToStringBSTR(pPwd))
  145. Dim nativeObject As Object = entry.NativeObject
  146. bAuth = True
  147. Catch ex As Exception
  148. bAuth = False
  149. Finally
  150. entry.Close()
  151. entry.Dispose()
  152. End Try
  153. Return bAuth
  154. End Function
  155. Public Function UserHasLevels() As String()
  156. Dim Result As New System.Collections.Generic.List(Of String)
  157. For Each Value As Integer In System.Enum.GetValues(GetType(Security.Principal.WindowsBuiltInRole))
  158. If CType(My.User.CurrentPrincipal, Security.Principal.WindowsPrincipal).IsInRole( _
  159. CType(Value, Security.Principal.WindowsBuiltInRole)) Then
  160. Result.Add(CType(Value, Security.Principal.WindowsBuiltInRole).ToString())
  161. End If
  162. Next
  163. Return Result.ToArray()
  164. End Function
  165. ''' <summary>
  166. ''' Gets the duplicate keys.
  167. ''' </summary>
  168. ''' <param name="property">The property.</param>
  169. ''' <param name="LoadedDE">The loaded DE.</param>
  170. ''' <param name="name">The name.</param>
  171. ''' <param name="domain">The domain.</param>
  172. ''' <returns></returns>
  173. Public Function GetDuplicateKeys(ByVal [property] As String, _
  174. Optional ByVal LoadedDE As DirectoryEntry = Nothing, _
  175. Optional ByVal name As String = "", _
  176. Optional ByVal domain As String = "" _
  177. ) As ArrayList
  178. Dim retval As New ArrayList
  179. Dim res As DirectoryEntry
  180. If LoadedDE Is Nothing Then
  181. Dim r As New DirectoryEntry("LDAP://" + domain + "/", user, pass, AuthenticationTypes.Delegation)
  182. Dim srv As New DirectorySearcher(r)
  183. srv.Filter = "(name=" + name + ")"
  184. res = srv.FindOne.GetDirectoryEntry
  185. Else
  186. res = LoadedDE
  187. End If
  188. If res IsNot Nothing Then
  189. If IsArray(res.Properties([property]).Value) Then
  190. If TypeOf (res.Properties([property]).Value) Is System.Byte() Then
  191. Dim proplist() As Byte = res.Properties([property]).Value
  192. Dim converted As New StringBuilder
  193. For Each tmp As Byte In proplist
  194. converted.Append(tmp)
  195. Next
  196. retval.Add(converted.ToString)
  197. Else
  198. Dim proplist() As Object = res.Properties([property]).Value
  199. For Each tmp As String In proplist
  200. retval.Add(tmp)
  201. Next
  202. End If
  203. Else
  204. retval.Add(Convert.ToString(res.Properties([property]).Value))
  205. End If
  206. End If
  207. Return retval
  208. End Function
  209. ''' <summary>
  210. ''' Gets an Active Directory object.
  211. ''' </summary>
  212. ''' <param name="name">The name.</param>
  213. ''' <param name="domain">The domain.</param>
  214. ''' <returns></returns>
  215. Public Function GetObject(ByVal name As String, ByVal domain As String) As SortedList(Of String, ArrayList)
  216. Dim retval As New SortedList(Of String, ArrayList)
  217. Dim r As New DirectoryEntry("LDAP://" + domain, user, pass, AuthenticationTypes.Delegation)
  218. Dim srv As New DirectorySearcher(r)
  219. srv.Filter = "(name=" + name + ")"
  220. Dim res As SearchResult = srv.FindOne
  221. If res IsNot Nothing Then
  222. Dim resv As DirectoryEntry = res.GetDirectoryEntry
  223. For Each tmp As String In resv.Properties.PropertyNames
  224. Dim itemvalue As ArrayList = GetDuplicateKeys(tmp, resv)
  225. retval.Add(tmp, itemvalue)
  226. Next
  227. End If
  228. Return retval
  229. End Function
  230. ''' <summary>
  231. ''' Gets the directory entry.
  232. ''' </summary>
  233. ''' <param name="name">The name.</param>
  234. ''' <param name="domain">The domain.</param>
  235. ''' <returns></returns>
  236. Public Function GetDirectoryEntry(ByVal name As String, ByVal domain As String) As DirectoryEntry
  237. Dim r As New DirectoryEntry("LDAP://" + domain, user, pass, AuthenticationTypes.Delegation)
  238. Dim srv As New DirectorySearcher(r)
  239. srv.Filter = "(name=" + name + ")"
  240. Dim res As SearchResult = srv.FindOne
  241. Return res.GetDirectoryEntry
  242. End Function
  243. Public Function GetDirectoryEntry(ByVal distinguishedname As String) As DirectoryEntry
  244. Dim r As New DirectoryEntry(distinguishedname, user, pass, AuthenticationTypes.Delegation)
  245. Dim srv As New DirectorySearcher(r)
  246. Dim res As SearchResult = srv.FindOne
  247. Return res.GetDirectoryEntry
  248. End Function
  249. ''' <summary>
  250. ''' Gets the property value.
  251. ''' </summary>
  252. ''' <param name="property">The property.</param>
  253. ''' <param name="LoadedDE">The loaded DE.</param>
  254. ''' <param name="objectname">The objectname.</param>
  255. ''' <param name="domain">The domain.</param>
  256. ''' <returns></returns>
  257. Public Function GetPropertyValue(ByVal [property] As String, _
  258. Optional ByVal LoadedDE As DirectoryEntry = Nothing, _
  259. Optional ByVal objectname As String = "", _
  260. Optional ByVal domain As String = "") As ArrayList
  261. Dim obj As DirectoryEntry
  262. If LoadedDE Is Nothing Then
  263. obj = GetDirectoryEntry(objectname, domain)
  264. Else
  265. obj = LoadedDE
  266. End If
  267. Dim retval As ArrayList = GetDuplicateKeys([property], obj)
  268. Return retval
  269. End Function
  270. ''' <summary>
  271. ''' Gets the group.
  272. ''' </summary>
  273. ''' <param name="GroupDSN">The group DSN.</param>
  274. ''' <param name="IncludeMembers">if set to <c>true</c> [include members].</param>
  275. ''' <returns></returns>
  276. Public Function GetGroup(ByVal GroupDSN As String, Optional ByVal IncludeMembers As Boolean = False) As __Group
  277. Dim retval As __Group
  278. Dim r As New DirectoryEntry(GroupDSN, user, pass, AuthenticationTypes.Delegation)
  279. retval.Name = GetGroupDetails(GroupDSN, r).Name
  280. retval.Description = GetGroupDetails(GroupDSN, r).Description
  281. retval.DistinguishedName = GetGroupDetails(GroupDSN, r).DistinguishedName
  282. Dim g As __Object
  283. g.DistinguishedName = retval.DistinguishedName
  284. g.Name = retval.Name
  285. g.Description = retval.Description
  286. If IncludeMembers Then
  287. retval.Members = GetGroupMembers(g)
  288. Else
  289. retval.Members = Nothing
  290. End If
  291. Return retval
  292. End Function
  293. ''' <summary>
  294. ''' Gets the members.
  295. ''' </summary>
  296. ''' <param name="searchpath">The searchpath.</param>
  297. ''' <returns></returns>
  298. Public Function GetMembers(ByVal searchpath As String) As List(Of __Object)
  299. Dim retval As New List(Of __Object)
  300. Try
  301. Dim r As New DirectoryEntry(searchpath, user, pass, AuthenticationTypes.Delegation)
  302. For Each tmp As DirectoryEntry In r.Children
  303. Dim x As __Object = GetGroupDetails(tmp.Path, tmp)
  304. retval.Add(x)
  305. Next
  306. Catch ex As Exception
  307. End Try
  308. Return retval
  309. End Function
  310. ''' <summary>
  311. ''' Gets the group members.
  312. ''' </summary>
  313. ''' <param name="Group">The group.</param>
  314. ''' <returns></returns>
  315. Public Function GetGroupMembers(ByVal Group As __Object) As List(Of __Object)
  316. Dim retval As New List(Of __Object)
  317. Dim start As Integer
  318. Dim len As Integer
  319. Dim ende As Integer
  320. Dim dom As String = ""
  321. Try
  322. start = Group.DistinguishedName.IndexOf("/") + 2
  323. len = Group.DistinguishedName.Length
  324. ende = Group.DistinguishedName.LastIndexOf("/")
  325. dom = Group.DistinguishedName.Substring(start, ende - start)
  326. Catch ex As Exception
  327. dom = ""
  328. End Try
  329. Dim r As New DirectoryEntry(Group.DistinguishedName, user, pass, AuthenticationTypes.Delegation)
  330. Dim isGroup As Boolean = False
  331. Dim isOU As Boolean = False
  332. For Each tmp As String In GetDuplicateKeys("objectClass", r)
  333. If tmp = "group" Then isGroup = True
  334. If tmp = "top" Then isOU = True
  335. Next
  336. 'groups
  337. If isGroup Then
  338. For Each tmp As String In r.Properties("member").Value
  339. If dom = "" Then
  340. retval.Add(GetGroupDetails("LDAP://" & dom & "/" & tmp))
  341. Else
  342. retval.Add(GetGroupDetails("LDAP://" & tmp))
  343. End If
  344. Next
  345. 'organizational units
  346. ElseIf isOU Then
  347. For Each tmp As __Object In GetMembers(Group.DistinguishedName)
  348. retval.Add(GetGroupDetails(tmp.DistinguishedName))
  349. Next
  350. End If
  351. Return retval
  352. End Function
  353. ''' <summary>
  354. ''' Gets the group details.
  355. ''' </summary>
  356. ''' <param name="groupcn">The groupcn.</param>
  357. ''' <param name="LoadedDE">The loaded DE.</param>
  358. ''' <returns></returns>
  359. Public Function GetGroupDetails(ByVal groupcn As String, Optional ByVal LoadedDE As DirectoryEntry = Nothing) As __Object
  360. Dim retval As __Object
  361. Dim r As DirectoryEntry
  362. Try
  363. If LoadedDE Is Nothing Then
  364. r = New DirectoryEntry(groupcn, user, pass, AuthenticationTypes.Delegation)
  365. Else
  366. r = LoadedDE
  367. End If
  368. retval.Name = r.Name.Split("=")(1)
  369. retval.DistinguishedName = r.Path
  370. retval.Description = r.Properties("Description").Value
  371. Catch ex As Exception
  372. retval.Name = ex.Message
  373. retval.DistinguishedName = groupcn
  374. retval.Description = ""
  375. End Try
  376. Return retval
  377. End Function
  378. 'TODO: Rewrite Procedure...
  379. Public Sub DumpForest(ByVal dmn As String, ByVal tabs As Integer, Optional ByVal getproperties As Boolean = False, Optional ByVal recursiv As Boolean = True, Optional ByVal printpartitions As Boolean = False)
  380. Dim dc As New DirectoryContext(DirectoryContextType.Domain, dmn)
  381. Dim fr As Domain = Domain.GetDomain(dc)
  382. Dim nw As New Net.NetworkInformation.Ping
  383. Console.Write(Space(tabs) + fr.Name + " (" + fr.Children.Count.ToString + " Childs) " + nw.Send(fr.Name).RoundtripTime.ToString + " ms ping time" + vbNewLine)
  384. If getproperties Then
  385. Dim PropertiesToSkip As New List(Of String)
  386. PropertiesToSkip.Add("uSNCreated")
  387. PropertiesToSkip.Add("dSASignature")
  388. PropertiesToSkip.Add("repsTo")
  389. PropertiesToSkip.Add("repsFrom")
  390. PropertiesToSkip.Add("uSNChanged")
  391. PropertiesToSkip.Add("objectGUID")
  392. PropertiesToSkip.Add("replUpToDateVector")
  393. PropertiesToSkip.Add("creationTime")
  394. PropertiesToSkip.Add("forceLogoff")
  395. PropertiesToSkip.Add("lockoutDuration")
  396. PropertiesToSkip.Add("lockOutObservationWindow")
  397. PropertiesToSkip.Add("maxPwdAge")
  398. PropertiesToSkip.Add("minPwdAge")
  399. PropertiesToSkip.Add("modifiedCountAtLastProm")
  400. PropertiesToSkip.Add("objectSid")
  401. PropertiesToSkip.Add("modifiedCount")
  402. PropertiesToSkip.Add("auditingPolicy")
  403. PropertiesToSkip.Add("wellKnownObjects")
  404. PropertiesToSkip.Add("nTSecurityDescriptor")
  405. Dim de As DirectoryEntry = fr.GetDirectoryEntry
  406. For Each tmp As String In de.Properties.PropertyNames
  407. If Not PropertiesToSkip.Contains(tmp) Then
  408. If de.Properties(tmp).Count > 1 Then
  409. Console.Write(Space(tabs + 2) + tmp + " : " + vbNewLine)
  410. For k As Integer = 0 To de.Properties(tmp).Count - 1
  411. Console.Write(Space(tabs + 4) + de.Properties(tmp).Item(k).ToString + vbNewLine)
  412. Next
  413. Else
  414. Console.Write(Space(tabs + 2) + tmp + " : " + de.Properties(tmp).Value.ToString + vbNewLine)
  415. End If
  416. End If
  417. Next
  418. End If
  419. 'DC list
  420. Dim df As DomainControllerCollection = fr.DomainControllers
  421. Console.WriteLine("Domain Controllers:")
  422. Console.WriteLine(Space(tabs + 1) + "Name ; IPAddress ; HighestCommittedUSN ; Site ; Round Trip Time")
  423. For Each dg As DomainController In df
  424. Console.Write(Space(tabs + 1) + dg.Name + " ; " + dg.IPAddress.ToString + " ; " + dg.HighestCommittedUsn.ToString + " ; " + dg.SiteName.ToString + " ; " + nw.Send(dg.Name).RoundtripTime.ToString + " ms" + vbNewLine)
  425. If printpartitions Then
  426. Console.WriteLine(Space(tabs + 1) + "Partitions:")
  427. For Each dh As String In dg.Partitions
  428. Console.Write(Space(tabs + 3) + dh.ToString + vbNewLine)
  429. Next
  430. End If
  431. Next
  432. Console.WriteLine()
  433. If recursiv Then
  434. For i As Integer = 0 To fr.Children.Count - 1
  435. DumpForest(fr.Children(i).Name, tabs + 1, getproperties, recursiv)
  436. Next
  437. End If
  438. End Sub
  439. ''' <summary>
  440. ''' Determines whether as client is deactivated
  441. ''' </summary>
  442. ''' <param name="userAccountControl">The user account control.</param>
  443. ''' <returns>
  444. ''' <c>true</c> if [is client deactivated] [the specified user account control]; otherwise, <c>false</c>.
  445. ''' </returns>
  446. Public Function isClientDeactivated(ByVal userAccountControl As String) As Boolean
  447. Return Right(Hex(userAccountControl), 1) <> 2
  448. End Function
  449. Public Function GetAllDomains(ByVal basepath As String) As List(Of String)
  450. Dim retval As New List(Of String)
  451. Dim dc As DomainController = Domain.GetDomain(New DirectoryContext(DirectoryContextType.Domain, basepath)).FindDomainController()
  452. For Each tmp As Domain In dc.Forest.Domains
  453. retval.Add(tmp.Name)
  454. Next
  455. Return retval
  456. End Function
  457. ''' <summary>
  458. ''' Gets the domain information.
  459. ''' </summary>
  460. ''' <param name="dc">The dc.</param>
  461. ''' <returns></returns>
  462. Public Function GetDomainInformation(ByVal dc As String) As __Domain
  463. Dim retval As New __Domain
  464. Try
  465. Dim context As DirectoryContext = _
  466. New DirectoryContext(DirectoryContextType.Domain, dc)
  467. Dim dcinfo As Domain = Domain.GetDomain(context)
  468. retval.DomainMode = dcinfo.DomainMode.ToString
  469. retval.TrustRelationships = New List(Of __TrustInformation)
  470. For Each tmp As TrustRelationshipInformation In dcinfo.GetAllTrustRelationships
  471. Dim x As __TrustInformation
  472. x.SourceName = tmp.SourceName.ToString
  473. x.TargetName = tmp.TargetName.ToString
  474. x.TrustDirection = tmp.TrustDirection.ToString
  475. x.TrustType = tmp.TrustType.ToString
  476. retval.TrustRelationships.Add(x)
  477. Next
  478. Catch ex As Exception
  479. Windows.Forms.MessageBox.Show(ex.ToString)
  480. End Try
  481. Return retval
  482. End Function
  483. Public Function GetDomainControllerInformation(ByVal domaincontroller As String) As __DomainController
  484. Dim retval As New __DomainController
  485. Try
  486. Dim context As New DirectoryContext(DirectoryContextType.DirectoryServer, domaincontroller)
  487. Dim dcinfo As DomainController = DirectoryServices.ActiveDirectory.DomainController.GetDomainController(context)
  488. retval.CurrentTime = dcinfo.CurrentTime
  489. retval.DomainName = dcinfo.Domain.Name
  490. retval.ForestName = dcinfo.Forest.Name
  491. retval.HighestCommittedUsn = dcinfo.HighestCommittedUsn
  492. retval.IPAddress = dcinfo.IPAddress
  493. retval.Name = dcinfo.Name
  494. retval.OSVersion = dcinfo.OSVersion
  495. retval.SiteName = dcinfo.SiteName
  496. retval.IsGlobalCatalog = dcinfo.IsGlobalCatalog()
  497. retval.ReplicationOperationInformation.CurrentOperation = dcinfo.GetReplicationOperationInformation.CurrentOperation
  498. retval.ReplicationOperationInformation.OperationStartTime = dcinfo.GetReplicationOperationInformation.OperationStartTime
  499. retval.ReplicationOperationInformation.PendingOperations = dcinfo.GetReplicationOperationInformation.PendingOperations
  500. Catch ex As Exception
  501. Windows.Forms.MessageBox.Show(ex.ToString)
  502. End Try
  503. Return retval
  504. End Function
  505. ''' <summary>
  506. ''' Gets the computer domain.
  507. ''' </summary>
  508. ''' <returns></returns>
  509. Public Function GetComputerDomain() As String
  510. Try
  511. Return Domain.GetComputerDomain.Name
  512. Catch ex As ActiveDirectoryObjectNotFoundException
  513. Logger.GetInstance.Log(ClassName)
  514. Logger.GetInstance.Log(ex.ToString)
  515. Return "This computer is not part of a domain"
  516. Catch ex As Exception
  517. Return Nothing
  518. End Try
  519. End Function
  520. End Class

comments powered by Disqus