| | 1 | | using System; |
| | 2 | | using System.Collections.Generic; |
| | 3 | | using System.DirectoryServices; |
| | 4 | | using System.DirectoryServices.Protocols; |
| | 5 | | using System.Linq; |
| | 6 | | using System.Security.Cryptography.X509Certificates; |
| | 7 | | using System.Security.Principal; |
| | 8 | | using System.Text; |
| | 9 | | using System.Threading.Tasks; |
| | 10 | | using Microsoft.Extensions.Logging; |
| | 11 | | using SharpHoundCommonLib.Enums; |
| | 12 | |
|
| | 13 | | namespace SharpHoundCommonLib |
| | 14 | | { |
| | 15 | | public static class Extensions |
| | 16 | | { |
| | 17 | | private const string GMSAClass = "msds-groupmanagedserviceaccount"; |
| | 18 | | private const string MSAClass = "msds-managedserviceaccount"; |
| | 19 | | private static readonly ILogger Log; |
| | 20 | |
|
| | 21 | | static Extensions() |
| 1 | 22 | | { |
| 1 | 23 | | Log = Logging.LogProvider.CreateLogger("Extensions"); |
| 1 | 24 | | } |
| | 25 | |
|
| | 26 | | internal static async Task<List<T>> ToListAsync<T>(this IAsyncEnumerable<T> items) |
| 4 | 27 | | { |
| 4 | 28 | | var results = new List<T>(); |
| 18 | 29 | | await foreach (var item in items |
| 4 | 30 | | .ConfigureAwait(false)) |
| 3 | 31 | | results.Add(item); |
| 4 | 32 | | return results; |
| 4 | 33 | | } |
| | 34 | |
|
| | 35 | | /// <summary> |
| | 36 | | /// Helper function to print attributes of a SearchResultEntry |
| | 37 | | /// </summary> |
| | 38 | | /// <param name="searchResultEntry"></param> |
| | 39 | | public static string PrintEntry(this SearchResultEntry searchResultEntry) |
| 0 | 40 | | { |
| 0 | 41 | | var sb = new StringBuilder(); |
| 0 | 42 | | if (searchResultEntry.Attributes.AttributeNames == null) return sb.ToString(); |
| 0 | 43 | | foreach (var propertyName in searchResultEntry.Attributes.AttributeNames) |
| 0 | 44 | | { |
| 0 | 45 | | var property = propertyName.ToString(); |
| 0 | 46 | | sb.Append(property).Append("\t").Append(searchResultEntry.GetProperty(property)).Append("\n"); |
| 0 | 47 | | } |
| | 48 | |
|
| 0 | 49 | | return sb.ToString(); |
| 0 | 50 | | } |
| | 51 | |
|
| | 52 | | public static string LdapValue(this SecurityIdentifier s) |
| 0 | 53 | | { |
| 0 | 54 | | var bytes = new byte[s.BinaryLength]; |
| 0 | 55 | | s.GetBinaryForm(bytes, 0); |
| | 56 | |
|
| 0 | 57 | | var output = $"\\{BitConverter.ToString(bytes).Replace('-', '\\')}"; |
| 0 | 58 | | return output; |
| 0 | 59 | | } |
| | 60 | |
|
| | 61 | | public static string LdapValue(this Guid s) |
| 0 | 62 | | { |
| 0 | 63 | | var bytes = s.ToByteArray(); |
| 0 | 64 | | var output = $"\\{BitConverter.ToString(bytes).Replace('-', '\\')}"; |
| 0 | 65 | | return output; |
| 0 | 66 | | } |
| | 67 | |
|
| | 68 | | public static string GetSid(this DirectoryEntry result) |
| 0 | 69 | | { |
| | 70 | | try |
| 0 | 71 | | { |
| 0 | 72 | | if (!result.Properties.Contains(LDAPProperties.ObjectSID)) |
| 0 | 73 | | return null; |
| 0 | 74 | | } |
| 0 | 75 | | catch |
| 0 | 76 | | { |
| 0 | 77 | | return null; |
| | 78 | | } |
| | 79 | |
|
| 0 | 80 | | var s = result.Properties[LDAPProperties.ObjectSID][0]; |
| 0 | 81 | | return s switch |
| 0 | 82 | | { |
| 0 | 83 | | byte[] b => new SecurityIdentifier(b, 0).ToString(), |
| 0 | 84 | | string st => new SecurityIdentifier(Encoding.ASCII.GetBytes(st), 0).ToString(), |
| 0 | 85 | | _ => null |
| 0 | 86 | | }; |
| 0 | 87 | | } |
| | 88 | |
|
| | 89 | | /// <summary> |
| | 90 | | /// Returns true if any computer collection methods are set |
| | 91 | | /// </summary> |
| | 92 | | /// <param name="methods"></param> |
| | 93 | | /// <returns></returns> |
| | 94 | | public static bool IsComputerCollectionSet(this ResolvedCollectionMethod methods) |
| 0 | 95 | | { |
| 0 | 96 | | return (methods & ResolvedCollectionMethod.ComputerOnly) != 0; |
| 0 | 97 | | } |
| | 98 | |
|
| | 99 | | /// <summary> |
| | 100 | | /// Returns true if any local group collections are set |
| | 101 | | /// </summary> |
| | 102 | | /// <param name="methods"></param> |
| | 103 | | /// <returns></returns> |
| | 104 | | public static bool IsLocalGroupCollectionSet(this ResolvedCollectionMethod methods) |
| 0 | 105 | | { |
| 0 | 106 | | return (methods & ResolvedCollectionMethod.LocalGroups) != 0; |
| 0 | 107 | | } |
| | 108 | |
|
| | 109 | | /// <summary> |
| | 110 | | /// Gets the relative identifier for a SID |
| | 111 | | /// </summary> |
| | 112 | | /// <param name="securityIdentifier"></param> |
| | 113 | | /// <returns></returns> |
| | 114 | | public static int Rid(this SecurityIdentifier securityIdentifier) |
| 5 | 115 | | { |
| 5 | 116 | | var value = securityIdentifier.Value; |
| 5 | 117 | | var rid = int.Parse(value.Substring(value.LastIndexOf("-", StringComparison.Ordinal) + 1)); |
| 5 | 118 | | return rid; |
| 5 | 119 | | } |
| | 120 | |
|
| | 121 | | #region SearchResultEntry |
| | 122 | |
|
| | 123 | | /// <summary> |
| | 124 | | /// Gets the specified property as a string from the SearchResultEntry |
| | 125 | | /// </summary> |
| | 126 | | /// <param name="entry"></param> |
| | 127 | | /// <param name="property">The LDAP name of the property you want to get</param> |
| | 128 | | /// <returns>The string value of the property if it exists or null</returns> |
| | 129 | | public static string GetProperty(this SearchResultEntry entry, string property) |
| 3 | 130 | | { |
| 3 | 131 | | if (!entry.Attributes.Contains(property)) |
| 2 | 132 | | return null; |
| | 133 | |
|
| 1 | 134 | | var collection = entry.Attributes[property]; |
| | 135 | | //Use GetValues to auto-convert to the proper type |
| 1 | 136 | | var lookups = collection.GetValues(typeof(string)); |
| 1 | 137 | | if (lookups.Length == 0) |
| 0 | 138 | | return null; |
| | 139 | |
|
| 1 | 140 | | if (lookups[0] is not string prop || prop.Length == 0) |
| 0 | 141 | | return null; |
| | 142 | |
|
| 1 | 143 | | return prop; |
| 3 | 144 | | } |
| | 145 | |
|
| | 146 | | /// <summary> |
| | 147 | | /// Get's the string representation of the "objectguid" property from the SearchResultEntry |
| | 148 | | /// </summary> |
| | 149 | | /// <param name="entry"></param> |
| | 150 | | /// <returns>The string representation of the object's GUID if possible, otherwise null</returns> |
| | 151 | | public static string GetGuid(this SearchResultEntry entry) |
| 0 | 152 | | { |
| 0 | 153 | | if (entry.Attributes.Contains(LDAPProperties.ObjectGUID)) |
| 0 | 154 | | { |
| 0 | 155 | | var guidBytes = entry.GetPropertyAsBytes(LDAPProperties.ObjectGUID); |
| | 156 | |
|
| 0 | 157 | | return new Guid(guidBytes).ToString().ToUpper(); |
| | 158 | | } |
| | 159 | |
|
| 0 | 160 | | return null; |
| 0 | 161 | | } |
| | 162 | |
|
| | 163 | | /// <summary> |
| | 164 | | /// Gets the "objectsid" property as a string from the SearchResultEntry |
| | 165 | | /// </summary> |
| | 166 | | /// <param name="entry"></param> |
| | 167 | | /// <returns>The string representation of the object's SID if possible, otherwise null</returns> |
| | 168 | | public static string GetSid(this SearchResultEntry entry) |
| 2 | 169 | | { |
| 2 | 170 | | if (!entry.Attributes.Contains(LDAPProperties.ObjectSID)) return null; |
| | 171 | |
|
| | 172 | | object[] s; |
| | 173 | | try |
| 2 | 174 | | { |
| 2 | 175 | | s = entry.Attributes[LDAPProperties.ObjectSID].GetValues(typeof(byte[])); |
| 2 | 176 | | } |
| 0 | 177 | | catch (NotSupportedException) |
| 0 | 178 | | { |
| 0 | 179 | | return null; |
| | 180 | | } |
| | 181 | |
|
| 2 | 182 | | if (s.Length == 0) |
| 0 | 183 | | return null; |
| | 184 | |
|
| 2 | 185 | | if (s[0] is not byte[] sidBytes || sidBytes.Length == 0) |
| 0 | 186 | | return null; |
| | 187 | |
|
| | 188 | | try |
| 2 | 189 | | { |
| 2 | 190 | | var sid = new SecurityIdentifier(sidBytes, 0); |
| 2 | 191 | | return sid.Value.ToUpper(); |
| | 192 | | } |
| 0 | 193 | | catch (ArgumentNullException) |
| 0 | 194 | | { |
| 0 | 195 | | return null; |
| | 196 | | } |
| 2 | 197 | | } |
| | 198 | |
|
| | 199 | | /// <summary> |
| | 200 | | /// Gets the specified property as a string array from the SearchResultEntry |
| | 201 | | /// </summary> |
| | 202 | | /// <param name="entry"></param> |
| | 203 | | /// <param name="property">The LDAP name of the property you want to get</param> |
| | 204 | | /// <returns>The specified property as an array of strings if possible, else an empty array</returns> |
| | 205 | | public static string[] GetPropertyAsArray(this SearchResultEntry entry, string property) |
| 2 | 206 | | { |
| 2 | 207 | | if (!entry.Attributes.Contains(property)) |
| 0 | 208 | | return Array.Empty<string>(); |
| | 209 | |
|
| 2 | 210 | | var values = entry.Attributes[property]; |
| 2 | 211 | | var strings = values.GetValues(typeof(string)); |
| | 212 | |
|
| 2 | 213 | | return strings is not string[] result ? Array.Empty<string>() : result; |
| 2 | 214 | | } |
| | 215 | |
|
| | 216 | | /// <summary> |
| | 217 | | /// Gets the specified property as an array of byte arrays from the SearchResultEntry |
| | 218 | | /// Used for SIDHistory |
| | 219 | | /// </summary> |
| | 220 | | /// <param name="entry"></param> |
| | 221 | | /// <param name="property">The LDAP name of the property you want to get</param> |
| | 222 | | /// <returns>The specified property as an array of bytes if possible, else an empty array</returns> |
| | 223 | | public static byte[][] GetPropertyAsArrayOfBytes(this SearchResultEntry entry, string property) |
| 0 | 224 | | { |
| 0 | 225 | | if (!entry.Attributes.Contains(property)) |
| 0 | 226 | | return Array.Empty<byte[]>(); |
| | 227 | |
|
| 0 | 228 | | var values = entry.Attributes[property]; |
| 0 | 229 | | var bytes = values.GetValues(typeof(byte[])); |
| | 230 | |
|
| 0 | 231 | | return bytes is not byte[][] result ? Array.Empty<byte[]>() : result; |
| 0 | 232 | | } |
| | 233 | |
|
| | 234 | | /// <summary> |
| | 235 | | /// Gets the specified property as a byte array |
| | 236 | | /// </summary> |
| | 237 | | /// <param name="searchResultEntry"></param> |
| | 238 | | /// <param name="property">The LDAP name of the property you want to get</param> |
| | 239 | | /// <returns>An array of bytes if possible, else null</returns> |
| | 240 | | public static byte[] GetPropertyAsBytes(this SearchResultEntry searchResultEntry, string property) |
| 0 | 241 | | { |
| 0 | 242 | | if (!searchResultEntry.Attributes.Contains(property)) |
| 0 | 243 | | return null; |
| | 244 | |
|
| 0 | 245 | | var collection = searchResultEntry.Attributes[property]; |
| 0 | 246 | | var lookups = collection.GetValues(typeof(byte[])); |
| | 247 | |
|
| 0 | 248 | | if (lookups.Length == 0) |
| 0 | 249 | | return Array.Empty<byte>(); |
| | 250 | |
|
| 0 | 251 | | if (lookups[0] is not byte[] bytes || bytes.Length == 0) |
| 0 | 252 | | return Array.Empty<byte>(); |
| | 253 | |
|
| 0 | 254 | | return bytes; |
| 0 | 255 | | } |
| | 256 | |
|
| | 257 | | /// <summary> |
| | 258 | | /// Gets the specified property as an int |
| | 259 | | /// </summary> |
| | 260 | | /// <param name="entry"></param> |
| | 261 | | /// <param name="property"></param> |
| | 262 | | /// <param name="value"></param> |
| | 263 | | /// <returns></returns> |
| | 264 | | public static bool GetPropertyAsInt(this SearchResultEntry entry, string property, out int value) |
| 1 | 265 | | { |
| 1 | 266 | | var prop = entry.GetProperty(property); |
| 2 | 267 | | if (prop != null) return int.TryParse(prop, out value); |
| 0 | 268 | | value = 0; |
| 0 | 269 | | return false; |
| 1 | 270 | | } |
| | 271 | |
|
| | 272 | | /// <summary> |
| | 273 | | /// Gets the specified property as an array of X509 certificates. |
| | 274 | | /// </summary> |
| | 275 | | /// <param name="searchResultEntry"></param> |
| | 276 | | /// <param name="property"></param> |
| | 277 | | /// <returns></returns> |
| | 278 | | public static X509Certificate2[] GetPropertyAsArrayOfCertificates(this SearchResultEntry searchResultEntry, |
| | 279 | | string property) |
| 0 | 280 | | { |
| 0 | 281 | | if (!searchResultEntry.Attributes.Contains(property)) |
| 0 | 282 | | return null; |
| | 283 | |
|
| 0 | 284 | | return searchResultEntry.GetPropertyAsArrayOfBytes(property).Select(x => new X509Certificate2(x)).ToArray(); |
| 0 | 285 | | } |
| | 286 | |
|
| | 287 | |
|
| | 288 | | /// <summary> |
| | 289 | | /// Attempts to get the unique object identifier as used by BloodHound for the Search Result Entry. Tries to |
| | 290 | | /// objectsid first, and then objectguid next. |
| | 291 | | /// </summary> |
| | 292 | | /// <param name="entry"></param> |
| | 293 | | /// <returns>String representation of the entry's object identifier or null</returns> |
| | 294 | | public static string GetObjectIdentifier(this SearchResultEntry entry) |
| 2 | 295 | | { |
| 2 | 296 | | return entry.GetSid() ?? entry.GetGuid(); |
| 2 | 297 | | } |
| | 298 | |
|
| | 299 | | /// <summary> |
| | 300 | | /// Checks the isDeleted LDAP property to determine if an entry has been deleted from the directory |
| | 301 | | /// </summary> |
| | 302 | | /// <param name="entry"></param> |
| | 303 | | /// <returns></returns> |
| | 304 | | public static bool IsDeleted(this SearchResultEntry entry) |
| 0 | 305 | | { |
| 0 | 306 | | var deleted = entry.GetProperty(LDAPProperties.IsDeleted); |
| 0 | 307 | | return bool.TryParse(deleted, out var isDeleted) && isDeleted; |
| 0 | 308 | | } |
| | 309 | |
|
| | 310 | | /// <summary> |
| | 311 | | /// Extension method to determine the BloodHound type of a SearchResultEntry using LDAP properties |
| | 312 | | /// Requires ldap properties objectsid, samaccounttype, objectclass |
| | 313 | | /// </summary> |
| | 314 | | /// <param name="entry"></param> |
| | 315 | | /// <returns></returns> |
| | 316 | | public static Label GetLabel(this SearchResultEntry entry) |
| 2 | 317 | | { |
| 2 | 318 | | var objectId = entry.GetObjectIdentifier(); |
| | 319 | |
|
| 2 | 320 | | if (objectId == null) |
| 0 | 321 | | { |
| 0 | 322 | | Log.LogWarning("Failed to get an object identifier for {DN}", entry.DistinguishedName); |
| 0 | 323 | | return Label.Base; |
| | 324 | | } |
| | 325 | |
|
| 2 | 326 | | if (objectId.StartsWith("S-1") && |
| 2 | 327 | | WellKnownPrincipal.GetWellKnownPrincipal(objectId, out var commonPrincipal)) |
| 0 | 328 | | { |
| 0 | 329 | | Log.LogDebug("GetLabel - {ObjectID} is a WellKnownPrincipal with {Type}", objectId, |
| 0 | 330 | | commonPrincipal.ObjectType); |
| 0 | 331 | | return commonPrincipal.ObjectType; |
| | 332 | | } |
| | 333 | |
|
| | 334 | |
|
| 2 | 335 | | var objectType = Label.Base; |
| 2 | 336 | | var samAccountType = entry.GetProperty(LDAPProperties.SAMAccountType); |
| 2 | 337 | | var objectClasses = entry.GetPropertyAsArray(LDAPProperties.ObjectClass); |
| | 338 | |
|
| | 339 | | //Override object class for GMSA/MSA accounts |
| 2 | 340 | | if (objectClasses != null && (objectClasses.Contains(MSAClass, StringComparer.OrdinalIgnoreCase) || |
| 2 | 341 | | objectClasses.Contains(GMSAClass, StringComparer.OrdinalIgnoreCase))) |
| 0 | 342 | | { |
| 0 | 343 | | Log.LogDebug("GetLabel - {ObjectID} is an MSA/GMSA, returning User", objectId); |
| 0 | 344 | | Cache.AddConvertedValue(entry.DistinguishedName, objectId); |
| 0 | 345 | | Cache.AddType(objectId, objectType); |
| 0 | 346 | | return Label.User; |
| | 347 | | } |
| | 348 | |
|
| | 349 | |
|
| | 350 | | //Its not a common principal. Lets use properties to figure out what it actually is |
| 2 | 351 | | if (samAccountType != null) objectType = Helpers.SamAccountTypeToType(samAccountType); |
| | 352 | |
|
| 2 | 353 | | Log.LogDebug("GetLabel - SamAccountTypeToType returned {Label}", objectType); |
| 2 | 354 | | if (objectType != Label.Base) |
| 0 | 355 | | { |
| 0 | 356 | | Cache.AddConvertedValue(entry.DistinguishedName, objectId); |
| 0 | 357 | | Cache.AddType(objectId, objectType); |
| 0 | 358 | | return objectType; |
| | 359 | | } |
| | 360 | |
|
| | 361 | |
|
| 2 | 362 | | if (objectClasses == null) |
| 0 | 363 | | { |
| 0 | 364 | | Log.LogDebug("GetLabel - ObjectClasses for {ObjectID} is null", objectId); |
| 0 | 365 | | objectType = Label.Base; |
| 0 | 366 | | } |
| | 367 | | else |
| 2 | 368 | | { |
| 2 | 369 | | Log.LogDebug("GetLabel - ObjectClasses for {ObjectID}: {Classes}", objectId, |
| 2 | 370 | | string.Join(", ", objectClasses)); |
| 2 | 371 | | if (objectClasses.Contains(GroupPolicyContainerClass, StringComparer.InvariantCultureIgnoreCase)) |
| 0 | 372 | | objectType = Label.GPO; |
| 2 | 373 | | else if (objectClasses.Contains(OrganizationalUnitClass, StringComparer.InvariantCultureIgnoreCase)) |
| 0 | 374 | | objectType = Label.OU; |
| 2 | 375 | | else if (objectClasses.Contains(DomainClass, StringComparer.InvariantCultureIgnoreCase)) |
| 0 | 376 | | objectType = Label.Domain; |
| 2 | 377 | | else if (objectClasses.Contains(ContainerClass, StringComparer.InvariantCultureIgnoreCase)) |
| 0 | 378 | | objectType = Label.Container; |
| 2 | 379 | | else if (objectClasses.Contains(ConfigurationClass, StringComparer.InvariantCultureIgnoreCase)) |
| 0 | 380 | | objectType = Label.Configuration; |
| 2 | 381 | | else if (objectClasses.Contains(PKICertificateTemplateClass, StringComparer.InvariantCultureIgnoreCase)) |
| 0 | 382 | | objectType = Label.CertTemplate; |
| 2 | 383 | | else if (objectClasses.Contains(PKIEnrollmentServiceClass, StringComparer.InvariantCultureIgnoreCase)) |
| 0 | 384 | | objectType = Label.EnterpriseCA; |
| 2 | 385 | | else if (objectClasses.Contains(CertificationAuthorityClass, StringComparer.InvariantCultureIgnoreCase)) |
| 0 | 386 | | { |
| 0 | 387 | | if (entry.DistinguishedName.Contains(DirectoryPaths.RootCALocation)) |
| 0 | 388 | | objectType = Label.RootCA; |
| 0 | 389 | | else if (entry.DistinguishedName.Contains(DirectoryPaths.AIACALocation)) |
| 0 | 390 | | objectType = Label.AIACA; |
| 0 | 391 | | else if (entry.DistinguishedName.Contains(DirectoryPaths.NTAuthStoreLocation)) |
| 0 | 392 | | objectType = Label.NTAuthStore; |
| 2 | 393 | | }else if (objectClasses.Contains(OIDContainerClass, StringComparer.InvariantCultureIgnoreCase)) |
| 2 | 394 | | { |
| 2 | 395 | | if (entry.DistinguishedName.StartsWith(DirectoryPaths.OIDContainerLocation, |
| 2 | 396 | | StringComparison.InvariantCultureIgnoreCase)) |
| 1 | 397 | | objectType = Label.Container; |
| | 398 | | else |
| 1 | 399 | | { |
| 1 | 400 | | if (entry.GetPropertyAsInt(LDAPProperties.Flags, out var flags) && flags == 2) |
| 1 | 401 | | { |
| 1 | 402 | | objectType = Label.IssuancePolicy; |
| 1 | 403 | | } |
| 1 | 404 | | } |
| 2 | 405 | | } |
| 2 | 406 | | } |
| | 407 | |
|
| 2 | 408 | | Log.LogDebug("GetLabel - Final label for {ObjectID}: {Label}", objectId, objectType); |
| | 409 | |
|
| 2 | 410 | | Cache.AddConvertedValue(entry.DistinguishedName, objectId); |
| 2 | 411 | | Cache.AddType(objectId, objectType); |
| 2 | 412 | | return objectType; |
| 2 | 413 | | } |
| | 414 | |
|
| | 415 | | private const string GroupPolicyContainerClass = "groupPolicyContainer"; |
| | 416 | | private const string OrganizationalUnitClass = "organizationalUnit"; |
| | 417 | | private const string DomainClass = "domain"; |
| | 418 | | private const string ContainerClass = "container"; |
| | 419 | | private const string ConfigurationClass = "configuration"; |
| | 420 | | private const string PKICertificateTemplateClass = "pKICertificateTemplate"; |
| | 421 | | private const string PKIEnrollmentServiceClass = "pKIEnrollmentService"; |
| | 422 | | private const string CertificationAuthorityClass = "certificationAuthority"; |
| | 423 | | private const string OIDContainerClass = "msPKI-Enterprise-Oid"; |
| | 424 | |
|
| | 425 | | #endregion |
| | 426 | | } |
| | 427 | | } |