| | 1 | | using System; |
| | 2 | | using System.Collections.Generic; |
| | 3 | | using System.Globalization; |
| | 4 | | using System.Linq; |
| | 5 | | using System.Security.Principal; |
| | 6 | | using System.Text; |
| | 7 | | using System.Text.RegularExpressions; |
| | 8 | | using SharpHoundCommonLib.Enums; |
| | 9 | | using Microsoft.Extensions.Logging; |
| | 10 | | using System.IO; |
| | 11 | | using System.Security; |
| | 12 | | using SharpHoundCommonLib.Processors; |
| | 13 | | using Microsoft.Win32; |
| | 14 | |
|
| | 15 | | namespace SharpHoundCommonLib |
| | 16 | | { |
| | 17 | | public static class Helpers |
| | 18 | | { |
| 1 | 19 | | private static readonly HashSet<string> Groups = new() {"268435456", "268435457", "536870912", "536870913"}; |
| 1 | 20 | | private static readonly HashSet<string> Computers = new() {"805306369"}; |
| 1 | 21 | | private static readonly HashSet<string> Users = new() {"805306368"}; |
| | 22 | |
|
| 1 | 23 | | private static readonly Regex DCReplaceRegex = new("DC=", RegexOptions.IgnoreCase | RegexOptions.Compiled); |
| 1 | 24 | | private static readonly Regex SPNRegex = new(@".*\/.*", RegexOptions.Compiled); |
| 1 | 25 | | private static readonly DateTime EpochDiff = new(1970, 1, 1); |
| 1 | 26 | | private static readonly string[] FilteredSids = |
| 1 | 27 | | { |
| 1 | 28 | | "S-1-5-2", "S-1-5-3", "S-1-5-4", "S-1-5-6", "S-1-5-7", "S-1-2", "S-1-2-0", "S-1-5-18", |
| 1 | 29 | | "S-1-5-19", "S-1-5-20", "S-1-0-0", "S-1-0", "S-1-2-1" |
| 1 | 30 | | }; |
| | 31 | |
|
| | 32 | | public static string RemoveDistinguishedNamePrefix(string distinguishedName) |
| 8 | 33 | | { |
| 8 | 34 | | if (!distinguishedName.Contains(",")) |
| 1 | 35 | | { |
| 1 | 36 | | return ""; |
| | 37 | | } |
| 7 | 38 | | if (distinguishedName.IndexOf("DC=", StringComparison.OrdinalIgnoreCase) < 0) |
| 0 | 39 | | { |
| 0 | 40 | | return ""; |
| | 41 | | } |
| | 42 | |
|
| | 43 | | //Start at the first instance of a comma, and continue to loop while we still have commas. If we get -1, it |
| | 44 | | //This allows us to cleanly iterate over all indexes of commas in our DNs and find the first non-escaped one |
| 16 | 45 | | for (var i = distinguishedName.IndexOf(','); i > -1; i = distinguishedName.IndexOf(',', i + 1)) |
| 8 | 46 | | { |
| | 47 | | //If theres a comma at the beginning of the DN, something screwy is going on. Just ignore it |
| 8 | 48 | | if (i == 0) |
| 0 | 49 | | { |
| 0 | 50 | | continue; |
| | 51 | | } |
| | 52 | |
|
| | 53 | | //This indicates an escaped comma, which we should not use to split a DN |
| 8 | 54 | | if (distinguishedName[i-1] == '\\') |
| 1 | 55 | | { |
| 1 | 56 | | continue; |
| | 57 | | } |
| | 58 | |
|
| | 59 | | //This is an unescaped comma, so snip our DN from this comma onwards and return this as the cleaned dist |
| 7 | 60 | | return distinguishedName.Substring(i + 1); |
| | 61 | | } |
| | 62 | |
|
| 0 | 63 | | return ""; |
| 8 | 64 | | } |
| | 65 | |
|
| | 66 | | /// <summary> |
| | 67 | | /// Splits a GPLink property into its representative parts |
| | 68 | | /// Filters disabled links by default |
| | 69 | | /// </summary> |
| | 70 | | /// <param name="linkProp"></param> |
| | 71 | | /// <param name="filterDisabled"></param> |
| | 72 | | /// <returns></returns> |
| | 73 | | public static IEnumerable<ParsedGPLink> SplitGPLinkProperty(string linkProp, bool filterDisabled = true) |
| 8 | 74 | | { |
| 46 | 75 | | foreach (var link in linkProp.Split(']', '[') |
| 44 | 76 | | .Where(x => x.StartsWith("LDAP", StringComparison.OrdinalIgnoreCase))) |
| 11 | 77 | | { |
| 11 | 78 | | var s = link.Split(';'); |
| 11 | 79 | | var dn = s[0].Substring(s[0].IndexOf("CN=", StringComparison.OrdinalIgnoreCase)); |
| 11 | 80 | | var status = s[1]; |
| | 81 | |
|
| 11 | 82 | | if (filterDisabled) |
| | 83 | | // 1 and 3 represent Disabled, Not Enforced and Disabled, Enforced respectively. |
| 9 | 84 | | if (status is "3" or "1") |
| 0 | 85 | | continue; |
| | 86 | |
|
| 11 | 87 | | yield return new ParsedGPLink |
| 11 | 88 | | { |
| 11 | 89 | | Status = status.TrimStart().TrimEnd(), |
| 11 | 90 | | DistinguishedName = dn.TrimStart().TrimEnd() |
| 11 | 91 | | }; |
| 11 | 92 | | } |
| 8 | 93 | | } |
| | 94 | |
|
| | 95 | | /// <summary> |
| | 96 | | /// Attempts to convert a SamAccountType value to the appropriate type enum |
| | 97 | | /// </summary> |
| | 98 | | /// <param name="samAccountType"></param> |
| | 99 | | /// <returns><c>Label</c> value representing type</returns> |
| | 100 | | public static Label SamAccountTypeToType(string samAccountType) |
| 7 | 101 | | { |
| 7 | 102 | | if (Groups.Contains(samAccountType)) |
| 4 | 103 | | return Label.Group; |
| | 104 | |
|
| 3 | 105 | | if (Users.Contains(samAccountType)) |
| 1 | 106 | | return Label.User; |
| | 107 | |
|
| 2 | 108 | | if (Computers.Contains(samAccountType)) |
| 1 | 109 | | return Label.Computer; |
| | 110 | |
|
| 1 | 111 | | return Label.Base; |
| 7 | 112 | | } |
| | 113 | |
|
| | 114 | | /// <summary> |
| | 115 | | /// Converts a string SID to its hex representation for LDAP searches |
| | 116 | | /// </summary> |
| | 117 | | /// <param name="sid">String security identifier to convert</param> |
| | 118 | | /// <returns>String representation to use in LDAP filters</returns> |
| | 119 | | public static string ConvertSidToHexSid(string sid) |
| 0 | 120 | | { |
| 0 | 121 | | var securityIdentifier = new SecurityIdentifier(sid); |
| 0 | 122 | | var sidBytes = new byte[securityIdentifier.BinaryLength]; |
| 0 | 123 | | securityIdentifier.GetBinaryForm(sidBytes, 0); |
| | 124 | |
|
| 0 | 125 | | var output = $"\\{BitConverter.ToString(sidBytes).Replace('-', '\\')}"; |
| 0 | 126 | | return output; |
| 0 | 127 | | } |
| | 128 | |
|
| | 129 | | /// <summary> |
| | 130 | | /// Converts a string GUID to its hex representation for LDAP searches |
| | 131 | | /// </summary> |
| | 132 | | /// <param name="guid"></param> |
| | 133 | | /// <returns></returns> |
| | 134 | | public static string ConvertGuidToHexGuid(string guid) |
| 1 | 135 | | { |
| 1 | 136 | | var guidObj = new Guid(guid); |
| 1 | 137 | | var guidBytes = guidObj.ToByteArray(); |
| 1 | 138 | | var output = $"\\{BitConverter.ToString(guidBytes).Replace('-', '\\')}"; |
| 1 | 139 | | return output; |
| 1 | 140 | | } |
| | 141 | |
|
| | 142 | | /// <summary> |
| | 143 | | /// Extracts an active directory domain name from a DistinguishedName |
| | 144 | | /// </summary> |
| | 145 | | /// <param name="distinguishedName">Distinguished Name to extract domain from</param> |
| | 146 | | /// <returns>String representing the domain name of this object</returns> |
| | 147 | | public static string DistinguishedNameToDomain(string distinguishedName) |
| 23 | 148 | | { |
| | 149 | | int idx; |
| 23 | 150 | | if (distinguishedName.ToUpper().Contains("DELETED OBJECTS")) |
| 1 | 151 | | { |
| 1 | 152 | | idx = distinguishedName.IndexOf("DC=", 3, StringComparison.Ordinal); |
| 1 | 153 | | } |
| | 154 | | else |
| 22 | 155 | | { |
| 22 | 156 | | idx = distinguishedName.IndexOf("DC=", |
| 22 | 157 | | StringComparison.CurrentCultureIgnoreCase); |
| 22 | 158 | | } |
| | 159 | |
|
| 23 | 160 | | if (idx < 0) |
| 1 | 161 | | return null; |
| | 162 | |
|
| 22 | 163 | | var temp = distinguishedName.Substring(idx); |
| 22 | 164 | | temp = DCReplaceRegex.Replace(temp, "").Replace(",", ".").ToUpper(); |
| 22 | 165 | | return temp; |
| 23 | 166 | | } |
| | 167 | |
|
| | 168 | | /// <summary> |
| | 169 | | /// Strips a "serviceprincipalname" entry down to just its hostname |
| | 170 | | /// </summary> |
| | 171 | | /// <param name="target">Raw service principal name</param> |
| | 172 | | /// <returns>Stripped service principal name with (hopefully) just the hostname</returns> |
| | 173 | | public static string StripServicePrincipalName(string target) |
| 16 | 174 | | { |
| 16 | 175 | | return SPNRegex.IsMatch(target) ? target.Split('/')[1].Split(':')[0] : target; |
| 16 | 176 | | } |
| | 177 | |
|
| | 178 | | /// <summary> |
| | 179 | | /// Converts a string to its base64 representation |
| | 180 | | /// </summary> |
| | 181 | | /// <param name="input"></param> |
| | 182 | | /// <returns></returns> |
| | 183 | | public static string Base64(string input) |
| 1 | 184 | | { |
| 1 | 185 | | var plainBytes = Encoding.UTF8.GetBytes(input); |
| 1 | 186 | | return Convert.ToBase64String(plainBytes); |
| 1 | 187 | | } |
| | 188 | |
|
| | 189 | | /// <summary> |
| | 190 | | /// Converts a windows file time to unix epoch time |
| | 191 | | /// </summary> |
| | 192 | | /// <param name="ldapTime"></param> |
| | 193 | | /// <returns></returns> |
| | 194 | | public static long ConvertFileTimeToUnixEpoch(string ldapTime) |
| 28 | 195 | | { |
| 28 | 196 | | if (ldapTime == null) |
| 1 | 197 | | return -1; |
| | 198 | |
|
| 27 | 199 | | var time = long.Parse(ldapTime); |
| 25 | 200 | | if (time == 0) |
| 0 | 201 | | return 0; |
| | 202 | |
|
| | 203 | | long toReturn; |
| | 204 | |
|
| | 205 | | try |
| 25 | 206 | | { |
| 25 | 207 | | toReturn = (long) Math.Floor(DateTime.FromFileTimeUtc(time).Subtract(EpochDiff).TotalSeconds); |
| 24 | 208 | | } |
| 1 | 209 | | catch |
| 1 | 210 | | { |
| 1 | 211 | | toReturn = -1; |
| 1 | 212 | | } |
| | 213 | |
|
| 25 | 214 | | return toReturn; |
| 26 | 215 | | } |
| | 216 | |
|
| | 217 | | /// <summary> |
| | 218 | | /// Converts a windows file time to unix epoch time |
| | 219 | | /// </summary> |
| | 220 | | /// <param name="ldapTime"></param> |
| | 221 | | /// <returns></returns> |
| | 222 | | public static long ConvertTimestampToUnixEpoch(string ldapTime) |
| 20 | 223 | | { |
| | 224 | | try |
| 20 | 225 | | { |
| 20 | 226 | | var dt = DateTime.ParseExact(ldapTime, "yyyyMMddHHmmss.0K", CultureInfo.CurrentCulture); |
| 0 | 227 | | return (long) dt.Subtract(EpochDiff).TotalSeconds; |
| | 228 | | } |
| 20 | 229 | | catch |
| 20 | 230 | | { |
| 20 | 231 | | return 0; |
| | 232 | | } |
| 20 | 233 | | } |
| | 234 | |
|
| | 235 | | /// <summary> |
| | 236 | | /// Converts an LDAP time string into a long |
| | 237 | | /// </summary> |
| | 238 | | /// <param name="ldapTime"></param> |
| | 239 | | /// <returns></returns> |
| | 240 | | public static long ConvertLdapTimeToLong(string ldapTime) |
| 3 | 241 | | { |
| 3 | 242 | | if (ldapTime == null) |
| 0 | 243 | | return -1; |
| | 244 | |
|
| 3 | 245 | | var time = long.Parse(ldapTime); |
| 3 | 246 | | return time; |
| 3 | 247 | | } |
| | 248 | |
|
| | 249 | | /// <summary> |
| | 250 | | /// Removes some commonly seen SIDs that have no use in the schema |
| | 251 | | /// </summary> |
| | 252 | | /// <param name="sid"></param> |
| | 253 | | /// <returns></returns> |
| | 254 | | internal static string PreProcessSID(string sid) |
| 81 | 255 | | { |
| 81 | 256 | | sid = sid?.ToUpper(); |
| 81 | 257 | | if (sid != null) |
| | 258 | | //Ignore Local System/Creator Owner/Principal Self |
| 56 | 259 | | return sid is "S-1-5-18" or "S-1-3-0" or "S-1-5-10" ? null : sid; |
| | 260 | |
|
| 25 | 261 | | return null; |
| 81 | 262 | | } |
| | 263 | |
|
| | 264 | | public static bool IsSidFiltered(string sid) |
| 22 | 265 | | { |
| | 266 | | //Uppercase just in case we get a lowercase s |
| 22 | 267 | | sid = sid.ToUpper(); |
| 22 | 268 | | if (sid.StartsWith("S-1-5-80") || sid.StartsWith("S-1-5-82") || |
| 22 | 269 | | sid.StartsWith("S-1-5-90") || sid.StartsWith("S-1-5-96")) |
| 0 | 270 | | return true; |
| | 271 | |
|
| 22 | 272 | | if (FilteredSids.Contains(sid)) |
| 1 | 273 | | return true; |
| | 274 | |
|
| 21 | 275 | | return false; |
| 22 | 276 | | } |
| | 277 | |
|
| | 278 | | public static RegistryResult GetRegistryKeyData(string target, string subkey, string subvalue, ILogger log) |
| 0 | 279 | | { |
| 0 | 280 | | var data = new RegistryResult(); |
| | 281 | |
|
| | 282 | | try |
| 0 | 283 | | { |
| 0 | 284 | | var baseKey = OpenRemoteRegistry(target); |
| 0 | 285 | | var value = baseKey.GetValue(subkey, subvalue); |
| 0 | 286 | | data.Value = value; |
| | 287 | |
|
| 0 | 288 | | data.Collected = true; |
| 0 | 289 | | } |
| 0 | 290 | | catch (IOException e) |
| 0 | 291 | | { |
| 0 | 292 | | log.LogError(e, "Error getting data from registry for {Target}: {RegSubKey}:{RegValue}", |
| 0 | 293 | | target, subkey, subvalue); |
| 0 | 294 | | data.FailureReason = "Target machine was not found or not connectable"; |
| 0 | 295 | | } |
| 0 | 296 | | catch (SecurityException e) |
| 0 | 297 | | { |
| 0 | 298 | | log.LogError(e, "Error getting data from registry for {Target}: {RegSubKey}:{RegValue}", |
| 0 | 299 | | target, subkey, subvalue); |
| 0 | 300 | | data.FailureReason = "User does not have the proper permissions to perform this operation"; |
| 0 | 301 | | } |
| 0 | 302 | | catch (UnauthorizedAccessException e) |
| 0 | 303 | | { |
| 0 | 304 | | log.LogError(e, "Error getting data from registry for {Target}: {RegSubKey}:{RegValue}", |
| 0 | 305 | | target, subkey, subvalue); |
| 0 | 306 | | data.FailureReason = "User does not have the necessary registry rights"; |
| 0 | 307 | | } |
| 0 | 308 | | catch (Exception e) |
| 0 | 309 | | { |
| 0 | 310 | | log.LogError(e, "Error getting data from registry for {Target}: {RegSubKey}:{RegValue}", |
| 0 | 311 | | target, subkey, subvalue); |
| 0 | 312 | | data.FailureReason = e.Message; |
| 0 | 313 | | } |
| | 314 | |
|
| 0 | 315 | | return data; |
| 0 | 316 | | } |
| | 317 | |
|
| | 318 | | public static IRegistryKey OpenRemoteRegistry(string target) |
| 0 | 319 | | { |
| 0 | 320 | | var key = new SHRegistryKey(RegistryHive.LocalMachine, target); |
| 0 | 321 | | return key; |
| 0 | 322 | | } |
| | 323 | |
|
| 1 | 324 | | public static string[] AuthenticationOIDs = new string[] { |
| 1 | 325 | | CommonOids.ClientAuthentication, |
| 1 | 326 | | CommonOids.PKINITClientAuthentication, |
| 1 | 327 | | CommonOids.SmartcardLogon, |
| 1 | 328 | | CommonOids.AnyPurpose |
| 1 | 329 | | }; |
| | 330 | | } |
| | 331 | |
|
| | 332 | | public class ParsedGPLink |
| | 333 | | { |
| | 334 | | public string DistinguishedName { get; set; } |
| | 335 | | public string Status { get; set; } |
| | 336 | | } |
| | 337 | | } |