-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathCertAbuseProcessor.cs
More file actions
545 lines (467 loc) · 23.5 KB
/
CertAbuseProcessor.cs
File metadata and controls
545 lines (467 loc) · 23.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using SharpHoundCommonLib.Enums;
using SharpHoundCommonLib.OutputTypes;
using SharpHoundRPC;
using SharpHoundRPC.Wrappers;
using Encoder = Microsoft.Security.Application.Encoder;
namespace SharpHoundCommonLib.Processors
{
public class CertAbuseProcessor
{
private readonly ILogger _log;
private readonly ILdapUtils _utils;
private readonly AdaptiveTimeout _getMachineSidAdaptiveTimeout;
private readonly AdaptiveTimeout _openSamServerAdaptiveTimeout;
public delegate Task ComputerStatusDelegate(CSVComputerStatus status);
public event ComputerStatusDelegate ComputerStatusEvent;
public CertAbuseProcessor(ILdapUtils utils, ILogger log = null) {
_utils = utils;
_log = log ?? Logging.LogProvider.CreateLogger("CAProc");
_getMachineSidAdaptiveTimeout = new AdaptiveTimeout(maxTimeout: TimeSpan.FromMinutes(2), Logging.LogProvider.CreateLogger(nameof(ISAMServer.GetMachineSid)));
_openSamServerAdaptiveTimeout = new AdaptiveTimeout(maxTimeout: TimeSpan.FromMinutes(2), Logging.LogProvider.CreateLogger(nameof(SAMServer.OpenServer)));
}
/// <summary>
/// This function should be called with the security data fetched from <see cref="GetCASecurity"/>.
/// The resulting ACEs will contain the owner of the CA as well as Management rights.
/// </summary>
/// <param name="security"></param>
/// <param name="objectDomain"></param>
/// <param name="computerName"></param>
/// <returns></returns>
public async Task<AceRegistryAPIResult> ProcessRegistryEnrollmentPermissions(string caName, string objectDomain, string computerName, string computerObjectId)
{
var data = new AceRegistryAPIResult();
var aceData = GetCASecurity(computerName, caName);
data.Collected = aceData.Collected;
if (!aceData.Collected)
{
data.FailureReason = aceData.FailureReason;
return data;
}
if (aceData.Value == null)
{
return data;
}
var descriptor = _utils.MakeSecurityDescriptor();
descriptor.SetSecurityDescriptorBinaryForm(aceData.Value as byte[], AccessControlSections.All);
var ownerSid = Helpers.PreProcessSID(descriptor.GetOwner(typeof(SecurityIdentifier)));
var isDomainController = await _utils.IsDomainController(computerObjectId, objectDomain);
var machineSid = await GetMachineSid(computerName, computerObjectId);
var aces = new List<ACE>();
if (ownerSid != null) {
var processed = new SecurityIdentifier(ownerSid);
if (await GetRegistryPrincipal(processed, objectDomain, computerName,
isDomainController, computerObjectId, machineSid) is (true, var resolvedOwner)) {
aces.Add(new ACE
{
PrincipalType = resolvedOwner.ObjectType,
PrincipalSID = resolvedOwner.ObjectIdentifier,
RightName = EdgeNames.Owns,
IsInherited = false
});
} else {
aces.Add(new ACE
{
PrincipalType = Label.Base,
PrincipalSID = processed.Value,
RightName = EdgeNames.Owns,
IsInherited = false
});
}
}
else
{
_log.LogDebug("Owner on CA {Name} is null", computerName);
}
foreach (var rule in descriptor.GetAccessRules(true, true, typeof(SecurityIdentifier)))
{
if (rule == null)
continue;
if (rule.AccessControlType() == AccessControlType.Deny)
continue;
var principalSid = Helpers.PreProcessSID(rule.IdentityReference());
if (principalSid == null)
continue;
var (getDomainSuccess, principalDomain) = await _utils.GetDomainNameFromSid(principalSid);
if (!getDomainSuccess) {
//Fallback to computer's domain in case we cant resolve the principal domain
principalDomain = objectDomain;
}
var (resSuccess, resolvedPrincipal) = await GetRegistryPrincipal(new SecurityIdentifier(principalSid), principalDomain, computerName, isDomainController, computerObjectId, machineSid);
if (!resSuccess) {
resolvedPrincipal = new TypedPrincipal {
ObjectType = Label.Base,
ObjectIdentifier = principalSid
};
}
var isInherited = rule.IsInherited();
var cARights = (CertificationAuthorityRights)rule.ActiveDirectoryRights();
// TODO: These if statements are also present in ProcessACL. Move to shared location.
if ((cARights & CertificationAuthorityRights.ManageCA) != 0)
aces.Add(new ACE
{
PrincipalType = resolvedPrincipal.ObjectType,
PrincipalSID = resolvedPrincipal.ObjectIdentifier,
IsInherited = isInherited,
RightName = EdgeNames.ManageCA
});
if ((cARights & CertificationAuthorityRights.ManageCertificates) != 0)
aces.Add(new ACE
{
PrincipalType = resolvedPrincipal.ObjectType,
PrincipalSID = resolvedPrincipal.ObjectIdentifier,
IsInherited = isInherited,
RightName = EdgeNames.ManageCertificates
});
if ((cARights & CertificationAuthorityRights.Enroll) != 0)
aces.Add(new ACE
{
PrincipalType = resolvedPrincipal.ObjectType,
PrincipalSID = resolvedPrincipal.ObjectIdentifier,
IsInherited = isInherited,
RightName = EdgeNames.Enroll
});
}
data.Data = aces.ToArray();
return data;
}
/// <summary>
/// This function will retrieve the enrollment agent restrictions from a CA
/// </summary>
/// <param name="caName"></param>
/// <param name="objectDomain"></param>
/// <param name="computerName"></param>
/// <param name="computerObjectId"></param>
/// <returns></returns>
public async Task<EnrollmentAgentRegistryAPIResult> ProcessEAPermissions(string caName, string objectDomain, string computerName, string computerObjectId)
{
var ret = new EnrollmentAgentRegistryAPIResult();
var regData = GetEnrollmentAgentRights(computerName, caName);
ret.Collected = regData.Collected;
if (!ret.Collected)
{
ret.FailureReason = regData.FailureReason;
return ret;
}
if (regData.Value == null)
{
return ret;
}
var isDomainController = await _utils.IsDomainController(computerObjectId, objectDomain);
var machineSid = await GetMachineSid(computerName, computerObjectId);
var descriptor = new RawSecurityDescriptor(regData.Value as byte[], 0);
var enrollmentAgentRestrictions = new List<EnrollmentAgentRestriction>();
foreach (var genericAce in descriptor.DiscretionaryAcl)
{
var ace = (QualifiedAce)genericAce;
if (await CreateEnrollmentAgentRestriction(ace, objectDomain, computerName, isDomainController,
computerObjectId, machineSid) is (true, var restriction)) {
enrollmentAgentRestrictions.Add(restriction);
}
}
ret.Restrictions = enrollmentAgentRestrictions.ToArray();
return ret;
}
public async Task<(IEnumerable<TypedPrincipal> resolvedTemplates, IEnumerable<string> unresolvedTemplates)> ProcessCertTemplates(IEnumerable<string> templates, string domainName)
{
var resolvedTemplates = new List<TypedPrincipal>();
var unresolvedTemplates = new List<string>();
foreach (var templateCN in templates)
{
var res = await _utils.ResolveCertTemplateByProperty(Encoder.LdapFilterEncode(templateCN), LDAPProperties.CanonicalName, domainName);
if (res.Success) {
resolvedTemplates.Add(res.Principal);
} else {
unresolvedTemplates.Add(templateCN);
}
}
return (resolvedTemplates: resolvedTemplates, unresolvedTemplates: unresolvedTemplates);
}
/// <summary>
/// Get CA security registry value from the remote machine for processing security/enrollmentagentrights
/// </summary>
/// <param name="target"></param>
/// <param name="caName"></param>
/// <returns></returns>
[ExcludeFromCodeCoverage]
private RegistryResult GetCASecurity(string target, string caName)
{
var regSubKey = $"SYSTEM\\CurrentControlSet\\Services\\CertSvc\\Configuration\\{caName}";
const string regValue = "Security";
return Helpers.GetRegistryKeyData(target, regSubKey, regValue, _log);
}
/// <summary>
/// Get EnrollmentAgentRights registry value from the remote machine for processing security/enrollmentagentrights
/// </summary>
/// <param name="target"></param>
/// <param name="caName"></param>
/// <returns></returns>
[ExcludeFromCodeCoverage]
private RegistryResult GetEnrollmentAgentRights(string target, string caName)
{
var regSubKey = $"SYSTEM\\CurrentControlSet\\Services\\CertSvc\\Configuration\\{caName}";
var regValue = "EnrollmentAgentRights";
return Helpers.GetRegistryKeyData(target, regSubKey, regValue, _log);
}
/// <summary>
/// This function checks a registry setting on the target host for the specified CA to see if a requesting user can specify any SAN they want, which overrides template settings.
/// The ManageCA permission allows you to flip this bit as well. This appears to usually work, even if admin rights aren't available on the remote CA server
/// </summary>
/// <remarks>https://blog.keyfactor.com/hidden-dangers-certificate-subject-alternative-names-sans</remarks>
/// <param name="target"></param>
/// <param name="caName"></param>
/// <returns></returns>
[ExcludeFromCodeCoverage]
public BoolRegistryAPIResult IsUserSpecifiesSanEnabled(string target, string caName)
{
var ret = new BoolRegistryAPIResult();
var activePolicy = "CertificateAuthority_MicrosoftDefault.Policy";
var subKey =
$"SYSTEM\\CurrentControlSet\\Services\\CertSvc\\Configuration\\{caName}\\PolicyModules";
const string subValue = "Active";
var data = Helpers.GetRegistryKeyData(target, subKey, subValue, _log);
ret.Collected = data.Collected;
if (!data.Collected)
{
ret.FailureReason = data.FailureReason;
return ret;
}
if (data.Value != null)
{
activePolicy = (string)data.Value;
}
var subKey2 =
$"SYSTEM\\CurrentControlSet\\Services\\CertSvc\\Configuration\\{caName}\\PolicyModules\\{activePolicy}";
const string subValue2 = "EditFlags";
var data2 = Helpers.GetRegistryKeyData(target, subKey2, subValue2, _log);
ret.Collected = data2.Collected;
if (!data2.Collected)
{
ret.FailureReason = data2.FailureReason;
return ret;
}
if (data2.Value == null)
{
return ret;
}
var editFlags = (int)data2.Value;
ret.Value = (editFlags & 0x00040000) == 0x00040000;
return ret;
}
[ExcludeFromCodeCoverage]
public StringArrayRegistryAPIResult DisabledExtensions(string target, string caName)
{
var ret = new StringArrayRegistryAPIResult();
var activePolicy = "CertificateAuthority_MicrosoftDefault.Policy";
var subKey =
$"SYSTEM\\CurrentControlSet\\Services\\CertSvc\\Configuration\\{caName}\\PolicyModules";
const string subValue = "Active";
var data = Helpers.GetRegistryKeyData(target, subKey, subValue, _log);
ret.Collected = data.Collected;
if (!data.Collected)
{
ret.FailureReason = data.FailureReason;
return ret;
}
if (data.Value != null)
{
activePolicy = (string)data.Value;
}
var subKey2 =
$"SYSTEM\\CurrentControlSet\\Services\\CertSvc\\Configuration\\{caName}\\PolicyModules\\{activePolicy}";
const string subValue2 = "DisableExtensionList";
var data2 = Helpers.GetRegistryKeyData(target, subKey2, subValue2, _log);
ret.Collected = data2.Collected;
if (!data2.Collected)
{
ret.FailureReason = data2.FailureReason;
return ret;
}
if (data2.Value == null)
{
return ret;
}
var disableExtensionList = (string[])data2.Value;
ret.Data = disableExtensionList;
return ret;
}
/// <summary>
/// This function checks a registry setting on the target host for the specified CA to see if role seperation is enabled.
/// If enabled, you cannot perform any CA actions if you have both ManageCA and ManageCertificates permissions. Only CA admins can modify the setting.
/// </summary>
/// <remarks>https://www.itprotoday.com/security/q-how-can-i-make-sure-given-windows-account-assigned-only-single-certification-authority-ca</remarks>
/// <param name="target"></param>
/// <param name="caName"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
[ExcludeFromCodeCoverage]
public BoolRegistryAPIResult RoleSeparationEnabled(string target, string caName)
{
var ret = new BoolRegistryAPIResult();
var regSubKey = $"SYSTEM\\CurrentControlSet\\Services\\CertSvc\\Configuration\\{caName}";
const string regValue = "RoleSeparationEnabled";
var data = Helpers.GetRegistryKeyData(target, regSubKey, regValue, _log);
ret.Collected = data.Collected;
if (!data.Collected)
{
ret.FailureReason = data.FailureReason;
return ret;
}
if (data.Value == null)
{
return ret;
}
ret.Value = (int)data.Value == 1;
return ret;
}
public async Task<(bool Success, TypedPrincipal Principal)> GetRegistryPrincipal(SecurityIdentifier sid, string computerDomain, string computerName, bool isDomainController, string computerObjectId, SecurityIdentifier machineSid)
{
_log.LogTrace("Got principal with sid {SID} on computer {ComputerName}", sid.Value, computerName);
//Check if our sid is filtered
if (Helpers.IsSidFiltered(sid.Value))
return (false, default);
if (isDomainController &&
await _utils.ResolveIDAndType(sid.Value, computerDomain) is (true, var resolvedPrincipal)) {
return (true, resolvedPrincipal);
}
//If we get a local well known principal, we need to convert it using the computer's domain sid
if (await _utils.ConvertLocalWellKnownPrincipal(sid, computerObjectId, computerDomain) is
(true, var principal)) {
return (true, principal);
}
//If the security identifier starts with the machine sid, we need to resolve it as a local principal
if (machineSid != null && sid.IsEqualDomainSid(machineSid))
{
_log.LogTrace("Got local principal {sid} on computer {Computer}", sid.Value, computerName);
// Set label to be local group. It could be a local user or alias but I'm not sure how we can confirm. Besides, it will not have any effect on the end result
// The local group sid is computer machine sid - group rid.
var groupRid = sid.Rid();
var newSid = $"{computerObjectId}-{groupRid}";
return (true, new TypedPrincipal(newSid, Label.LocalGroup));
}
//If we get here, we most likely have a domain principal. Do a lookup
return await _utils.ResolveIDAndType(sid.Value, computerDomain);
}
private async Task<SecurityIdentifier> GetMachineSid(string computerName, string computerObjectId)
{
SecurityIdentifier machineSid = null;
//Try to get the machine sid for the computer if its not already cached
if (!Cache.GetMachineSid(computerObjectId, out var tempMachineSid))
{
// Open a handle to the server
var openServerResult = OpenSamServer(computerName);
if (openServerResult.IsFailed)
{
_log.LogTrace("OpenServer failed on {ComputerName}: {Error}", computerName, openServerResult.SError);
await SendComputerStatus(new CSVComputerStatus
{
Task = "SamConnect",
ComputerName = computerName,
Status = openServerResult.SError
});
return null;
}
var server = openServerResult.Value;
var getMachineSidResult = await _getMachineSidAdaptiveTimeout.ExecuteRPCWithTimeout((timeoutToken) => server.GetMachineSid(cancellationToken: timeoutToken));
if (getMachineSidResult.IsFailed)
{
_log.LogTrace("GetMachineSid failed on {ComputerName}: {Error}", computerName, getMachineSidResult.SError);
await SendComputerStatus(new CSVComputerStatus
{
Status = getMachineSidResult.SError,
ComputerName = computerName,
Task = "GetMachineSid"
});
//If we can't get a machine sid, we wont be able to make local principals with unique object ids, or differentiate local/domain objects
_log.LogWarning("Unable to get machineSid for {Computer}: {Status}", computerName, getMachineSidResult.SError);
return null;
}
machineSid = getMachineSidResult.Value;
Cache.AddMachineSid(computerObjectId, machineSid.Value);
}
else
{
machineSid = new SecurityIdentifier(tempMachineSid);
}
return machineSid;
}
private async Task<(bool success, EnrollmentAgentRestriction restriction)> CreateEnrollmentAgentRestriction(QualifiedAce ace, string computerDomain, string computerName, bool isDomainController, string computerObjectId, SecurityIdentifier machineSid) {
var targets = new List<TypedPrincipal>();
var index = 0;
var accessType = ace.AceType.ToString();
var agent = await GetRegistryPrincipal(ace.SecurityIdentifier, computerDomain, computerName, isDomainController,
computerObjectId, machineSid);
var opaque = ace.GetOpaque();
var sidCount = BitConverter.ToUInt32(opaque, 0);
index += 4;
for (var i = 0; i < sidCount; i++) {
var sid = new SecurityIdentifier(opaque, index);
if (await GetRegistryPrincipal(sid, computerDomain, computerName, isDomainController, computerObjectId,
machineSid) is (true, var regPrincipal)) {
targets.Add(regPrincipal);
}
index += sid.BinaryLength;
}
var finalTargets = targets.ToArray();
var allTemplates = index >= opaque.Length;
if (index < opaque.Length) {
var template = Encoding.Unicode.GetString(opaque, index, opaque.Length - index - 2).Replace("\u0000", string.Empty);
if (await _utils.ResolveCertTemplateByProperty(Encoder.LdapFilterEncode(template), LDAPProperties.CanonicalName, computerDomain) is (true, var resolvedTemplate)) {
return (true, new EnrollmentAgentRestriction {
Template = resolvedTemplate,
Agent = agent.Principal,
AllTemplates = allTemplates,
AccessType = accessType,
Targets = finalTargets
});
}
if (await _utils.ResolveCertTemplateByProperty(
Encoder.LdapFilterEncode(template), LDAPProperties.CertTemplateOID, computerDomain) is
(true, var resolvedOidTemplate)) {
return (true, new EnrollmentAgentRestriction {
Template = resolvedOidTemplate,
Agent = agent.Principal,
AllTemplates = allTemplates,
AccessType = accessType,
Targets = finalTargets
});
}
}
return (false, default);
}
public virtual SharpHoundRPC.Result<ISAMServer> OpenSamServer(string computerName)
{
var result = _openSamServerAdaptiveTimeout.ExecuteRPCWithTimeout((_) => SAMServer.OpenServer(computerName)).GetAwaiter().GetResult();
if (result.IsFailed)
{
return SharpHoundRPC.Result<ISAMServer>.Fail(result.SError);
}
return SharpHoundRPC.Result<ISAMServer>.Ok(result.Value);
}
private async Task SendComputerStatus(CSVComputerStatus status)
{
if (ComputerStatusEvent is not null) await ComputerStatusEvent(status);
}
}
public class EnrollmentAgentRestriction
{
public string AccessType { get; set; }
public TypedPrincipal Agent { get; set; }
public TypedPrincipal[] Targets { get; set; }
public TypedPrincipal Template { get; set; }
public bool AllTemplates { get; set; } = false;
}
public class CertRegistryResult
{
public bool Collected { get; set; } = false;
public byte[] Value { get; set; }
public string FailureReason { get; set; }
}
}