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