-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadcs_enum.go
More file actions
610 lines (513 loc) · 16.4 KB
/
adcs_enum.go
File metadata and controls
610 lines (513 loc) · 16.4 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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
package ldaptickler
import (
"encoding/binary"
"fmt"
"strconv"
"strings"
"github.com/huner2/go-sddlparse"
)
// ADCS LDAP attributes for template enumeration
var adcsTemplateAttrs = []string{
"cn",
"displayName",
"distinguishedName",
"objectGUID",
"msPKI-Certificate-Name-Flag",
"msPKI-Enrollment-Flag",
"msPKI-Private-Key-Flag",
"msPKI-RA-Signature",
"msPKI-RA-Application-Policies",
"msPKI-Certificate-Application-Policy",
"pKIExtendedKeyUsage",
"msPKI-Certificate-Policy",
"msPKI-Template-Schema-Version",
"pKIExpirationPeriod",
"pKIOverlapPeriod",
"nTSecurityDescriptor",
}
var adcsCAAttrs = []string{
"cn",
"distinguishedName",
"objectGUID",
"dNSHostName",
"certificateTemplates",
"nTSecurityDescriptor",
}
// ListADCSTemplates enumerates certificate templates with full security analysis
func (c *Tickler) ListADCSTemplates() ([]CertTemplate, error) {
pkiBaseDN := buildPKIConfigDN(c.baseDN)
filter := "(objectClass=pKICertificateTemplate)"
results, err := c.ldapSearchWithSD(pkiBaseDN, 2, filter, adcsTemplateAttrs)
if err != nil {
return nil, fmt.Errorf("failed to enumerate certificate templates: %w", err)
}
var templates []CertTemplate
for _, result := range results {
template := c.parseTemplateEntry(result)
templates = append(templates, template)
}
// Detect ESC vulnerabilities for each template
for i := range templates {
templates[i].ESCVulnerabilities = detectTemplateESC(&templates[i])
}
return templates, nil
}
// ListEnterpriseCAs enumerates Enterprise CAs with permissions
func (c *Tickler) ListEnterpriseCAs() ([]EnterpriseCA, error) {
pkiBaseDN := buildPKIConfigDN(c.baseDN)
filter := "(objectClass=pKIEnrollmentService)"
results, err := c.ldapSearchWithSD(pkiBaseDN, 2, filter, adcsCAAttrs)
if err != nil {
return nil, fmt.Errorf("failed to enumerate enterprise CAs: %w", err)
}
var cas []EnterpriseCA
for _, result := range results {
ca := c.parseCAEntry(result)
cas = append(cas, ca)
}
// Detect CA-level ESC vulnerabilities
for i := range cas {
cas[i].ESCVulnerabilities = detectCAESC(&cas[i])
}
return cas, nil
}
// EnumerateADCS performs full ADCS enumeration
func (c *Tickler) EnumerateADCS() (*ADCSEnumResult, error) {
result := &ADCSEnumResult{
DomainSID: c.getDomainSID(c.baseDN),
DomainName: extractDomainFromDN(c.baseDN),
}
cas, err := c.ListEnterpriseCAs()
if err != nil {
return nil, err
}
result.CAs = cas
templates, err := c.ListADCSTemplates()
if err != nil {
return nil, err
}
result.Templates = templates
return result, nil
}
// parseTemplateEntry parses LDAP result into CertTemplate
func (c *Tickler) parseTemplateEntry(result Result) CertTemplate {
template := CertTemplate{
Name: result.GetFirstAttr("cn"),
DisplayName: result.GetFirstAttr("displayName"),
DN: result.GetFirstAttr("distinguishedName"),
ObjectGUID: result.GetFirstAttr("objectGUID"),
}
// Parse flag values
if v := result.GetFirstAttr("msPKI-Certificate-Name-Flag"); v != "" {
if val, err := strconv.ParseUint(v, 10, 32); err == nil {
template.CertificateNameFlag = uint32(val)
}
}
if v := result.GetFirstAttr("msPKI-Enrollment-Flag"); v != "" {
if val, err := strconv.ParseUint(v, 10, 32); err == nil {
template.EnrollmentFlag = uint32(val)
}
}
if v := result.GetFirstAttr("msPKI-Private-Key-Flag"); v != "" {
if val, err := strconv.ParseUint(v, 10, 32); err == nil {
template.PrivateKeyFlag = uint32(val)
}
}
// Parse RA signatures required
if v := result.GetFirstAttr("msPKI-RA-Signature"); v != "" {
if val, err := strconv.Atoi(v); err == nil {
template.RASignaturesRequired = val
template.AuthorizedSignaturesNeeded = val
}
}
// Parse schema version
if v := result.GetFirstAttr("msPKI-Template-Schema-Version"); v != "" {
if val, err := strconv.Atoi(v); err == nil {
template.SchemaVersion = val
}
}
// Parse EKUs - try both attributes
template.EKUs = result.GetAttr("pKIExtendedKeyUsage")
if len(template.EKUs) == 0 {
template.EKUs = result.GetAttr("msPKI-Certificate-Application-Policy")
}
// Parse application policies
template.ApplicationPolicies = result.GetAttr("msPKI-RA-Application-Policies")
template.IssuancePolicies = result.GetAttr("msPKI-Certificate-Policy")
// Parse validity period
if periodBytes := result.GetFirstBytes("pKIExpirationPeriod"); len(periodBytes) >= 8 {
template.ValidityPeriod = parseFiletimeDuration(periodBytes)
}
if periodBytes := result.GetFirstBytes("pKIOverlapPeriod"); len(periodBytes) >= 8 {
template.RenewalPeriod = parseFiletimeDuration(periodBytes)
}
// Compute boolean flags
template.EnrolleeSuppliesSubject = (template.CertificateNameFlag & CTFlagEnrolleeSuppliesSubject) != 0
template.ManagerApprovalRequired = (template.EnrollmentFlag & CTFlagPendAllRequests) != 0
template.NoSecurityExtension = (template.EnrollmentFlag & CTFlagNoSecurityExtension) != 0
template.ClientAuthEnabled = template.HasClientAuthEKU()
// Parse security descriptor for enrollment permissions
if sdBytes := result.GetFirstBytes("nTSecurityDescriptor"); len(sdBytes) > 0 {
enrollPerms, objPerms, owner := c.parseTemplateSecurityDescriptor(sdBytes)
template.EnrollmentPrincipals = enrollPerms
template.ObjectControllers = objPerms
template.OwnerSID = owner
}
return template
}
// parseCAEntry parses LDAP result into EnterpriseCA
func (c *Tickler) parseCAEntry(result Result) EnterpriseCA {
ca := EnterpriseCA{
Name: result.GetFirstAttr("cn"),
DN: result.GetFirstAttr("distinguishedName"),
DNSHostname: result.GetFirstAttr("dNSHostName"),
ObjectGUID: result.GetFirstAttr("objectGUID"),
CertificateTemplates: result.GetAttr("certificateTemplates"),
}
// Parse security descriptor for CA permissions
if sdBytes := result.GetFirstBytes("nTSecurityDescriptor"); len(sdBytes) > 0 {
ca.CASecurityPermissions = c.parseCASecurityDescriptor(sdBytes)
}
return ca
}
// parseTemplateSecurityDescriptor extracts enrollment permissions and dangerous ACLs
func (c *Tickler) parseTemplateSecurityDescriptor(sdBytes []byte) ([]EnrollmentPermission, []ObjectPermission, string) {
var enrollPerms []EnrollmentPermission
var objPerms []ObjectPermission
var ownerSID string
sd, err := sddlparse.SDDLFromBinary(sdBytes)
if err != nil {
return enrollPerms, objPerms, ownerSID
}
ownerSID = sd.Owner
// Dangerous permissions that indicate ESC4
dangerousMasks := sddlparse.ACCESS_MASK_GENERIC_ALL |
sddlparse.ACCESS_MASK_GENERIC_WRITE |
sddlparse.ACCESS_MASK_WRITE_OWNER |
sddlparse.ACCESS_MASK_WRITE_DACL
for _, ace := range sd.DACL {
sid := ace.SID
// Skip well-known admin SIDs for ESC4 (they're expected to have control)
if isWellKnownAdminSID(sid) {
continue
}
principalName, principalType := c.resolveSIDToPrincipal(sid)
// Check for enrollment extended rights (compare GUID string representation)
aceObjectType := ace.ObjectType.String()
if aceObjectType == RightCertificateEnrollment {
enrollPerms = append(enrollPerms, EnrollmentPermission{
PrincipalSID: sid,
PrincipalName: principalName,
PrincipalType: principalType,
CanEnroll: true,
CanAutoEnroll: false,
})
}
if aceObjectType == RightCertificateAutoEnrollment {
// Find or create enrollment permission
found := false
for i := range enrollPerms {
if enrollPerms[i].PrincipalSID == sid {
enrollPerms[i].CanAutoEnroll = true
found = true
break
}
}
if !found {
enrollPerms = append(enrollPerms, EnrollmentPermission{
PrincipalSID: sid,
PrincipalName: principalName,
PrincipalType: principalType,
CanEnroll: false,
CanAutoEnroll: true,
})
}
}
// Check for GenericAll which includes enrollment
if ace.AccessMask&sddlparse.ACCESS_MASK_GENERIC_ALL != 0 {
found := false
for i := range enrollPerms {
if enrollPerms[i].PrincipalSID == sid {
enrollPerms[i].CanEnroll = true
found = true
break
}
}
if !found {
enrollPerms = append(enrollPerms, EnrollmentPermission{
PrincipalSID: sid,
PrincipalName: principalName,
PrincipalType: principalType,
CanEnroll: true,
CanAutoEnroll: false,
})
}
}
// Check for dangerous permissions (ESC4)
if ace.AccessMask&dangerousMasks != 0 {
var permName string
switch {
case ace.AccessMask&sddlparse.ACCESS_MASK_GENERIC_ALL != 0:
permName = "GenericAll"
case ace.AccessMask&sddlparse.ACCESS_MASK_GENERIC_WRITE != 0:
permName = "GenericWrite"
case ace.AccessMask&sddlparse.ACCESS_MASK_WRITE_DACL != 0:
permName = "WriteDacl"
case ace.AccessMask&sddlparse.ACCESS_MASK_WRITE_OWNER != 0:
permName = "WriteOwner"
}
objPerms = append(objPerms, ObjectPermission{
PrincipalSID: sid,
PrincipalName: principalName,
PrincipalType: principalType,
Permission: permName,
})
}
}
return enrollPerms, objPerms, ownerSID
}
// parseCASecurityDescriptor extracts CA permissions for ESC7 detection
func (c *Tickler) parseCASecurityDescriptor(sdBytes []byte) []CAPermission {
var caPerms []CAPermission
sd, err := sddlparse.SDDLFromBinary(sdBytes)
if err != nil {
return caPerms
}
// CA-specific rights
// ManageCA = 0x00000001, ManageCertificates = 0x00000002
const (
caRightManageCA = 0x00000001
caRightManageCerts = 0x00000002
)
for _, ace := range sd.DACL {
sid := ace.SID
if isWellKnownAdminSID(sid) {
continue
}
principalName, _ := c.resolveSIDToPrincipal(sid)
perm := CAPermission{
PrincipalSID: sid,
PrincipalName: principalName,
}
// Check for ManageCA/ManageCertificates via GenericAll or specific rights
if ace.AccessMask&sddlparse.ACCESS_MASK_GENERIC_ALL != 0 {
perm.ManageCA = true
perm.ManageCerts = true
perm.Enroll = true
}
if ace.AccessMask&caRightManageCA != 0 {
perm.ManageCA = true
}
if ace.AccessMask&caRightManageCerts != 0 {
perm.ManageCerts = true
}
// Check for enrollment (compare GUID string representation)
if ace.ObjectType.String() == RightCertificateEnrollment {
perm.Enroll = true
}
if perm.ManageCA || perm.ManageCerts || perm.Enroll {
caPerms = append(caPerms, perm)
}
}
return caPerms
}
// resolveSIDToPrincipal looks up a SID and returns name and type
func (c *Tickler) resolveSIDToPrincipal(sid string) (string, string) {
// Check well-known SIDs first
if name, ok := wellKnownSIDs[sid]; ok {
return name, "Group"
}
// Try to resolve via LDAP
filter := fmt.Sprintf("(objectSid=%s)", sid)
attrs := []string{"sAMAccountName", "objectClass"}
results, err := c.getAllResults(2, filter, attrs)
if err != nil || len(results) == 0 {
return sid, "Unknown"
}
name := firstOrEmpty(results[0], "sAMAccountName")
if name == "" {
name = sid
}
objectClass := firstOrEmpty(results[0], "objectClass")
principalType := "Unknown"
switch {
case strings.Contains(objectClass, "user"):
principalType = "User"
case strings.Contains(objectClass, "group"):
principalType = "Group"
case strings.Contains(objectClass, "computer"):
principalType = "Computer"
}
return name, principalType
}
// Well-known SIDs that are expected to have admin permissions
var wellKnownSIDs = map[string]string{
"S-1-5-18": "SYSTEM",
"S-1-5-32-544": "BUILTIN\\Administrators",
"S-1-5-9": "Enterprise Domain Controllers",
}
// Well-known admin SIDs to skip for ESC4/ESC7 detection
func isWellKnownAdminSID(sid string) bool {
adminSIDs := []string{
"S-1-5-18", // SYSTEM
"S-1-5-32-544", // Administrators
"S-1-5-9", // Enterprise Domain Controllers
"S-1-5-32-548", // Account Operators
"S-1-5-32-549", // Server Operators
}
for _, adminSID := range adminSIDs {
if sid == adminSID {
return true
}
}
// Check for domain-relative admin SIDs (Domain Admins, Enterprise Admins)
// These end in -512, -519, -500
if strings.HasSuffix(sid, "-512") || // Domain Admins
strings.HasSuffix(sid, "-519") || // Enterprise Admins
strings.HasSuffix(sid, "-500") { // Administrator
return true
}
return false
}
// detectTemplateESC detects ESC vulnerabilities in a template
func detectTemplateESC(t *CertTemplate) []ESCVulnerability {
var vulns []ESCVulnerability
// Get exploitable principals (non-admin enrollees)
var exploitablePrincipals []string
for _, ep := range t.EnrollmentPrincipals {
if ep.CanEnroll && !isWellKnownAdminSID(ep.PrincipalSID) {
exploitablePrincipals = append(exploitablePrincipals, ep.PrincipalName)
}
}
// ESC1: Enrollee supplies subject with client auth
if t.IsVulnerableToESC1() {
vulns = append(vulns, ESCVulnerability{
Name: "ESC1",
Description: "Enrollee supplies subject with client authentication EKU",
Principals: exploitablePrincipals,
})
}
// ESC2: Any Purpose or SubCA
if t.IsVulnerableToESC2() {
desc := "Any Purpose EKU or no EKUs (SubCA)"
if t.HasAnyPurposeEKU() {
desc = "Any Purpose EKU enables impersonation"
} else if len(t.EKUs) == 0 {
desc = "No EKUs defined (SubCA template)"
}
vulns = append(vulns, ESCVulnerability{
Name: "ESC2",
Description: desc,
Principals: exploitablePrincipals,
})
}
// ESC3: Certificate Request Agent
if t.IsVulnerableToESC3() {
vulns = append(vulns, ESCVulnerability{
Name: "ESC3",
Description: "Certificate Request Agent EKU allows enrollment on behalf of others",
Principals: exploitablePrincipals,
})
}
// ESC4: Dangerous ACLs
if t.IsVulnerableToESC4() {
var aclPrincipals []string
for _, op := range t.ObjectControllers {
aclPrincipals = append(aclPrincipals, fmt.Sprintf("%s (%s)", op.PrincipalName, op.Permission))
}
vulns = append(vulns, ESCVulnerability{
Name: "ESC4",
Description: "Dangerous write permissions on template object",
Principals: aclPrincipals,
})
}
// ESC9: No Security Extension
if t.IsVulnerableToESC9() {
vulns = append(vulns, ESCVulnerability{
Name: "ESC9",
Description: "CT_FLAG_NO_SECURITY_EXTENSION is set - weak certificate mapping",
Principals: exploitablePrincipals,
})
}
return vulns
}
// detectCAESC detects ESC vulnerabilities in a CA
func detectCAESC(ca *EnterpriseCA) []ESCVulnerability {
var vulns []ESCVulnerability
// ESC6: User-specified SAN (would need RPC to detect, limited via LDAP)
// Skip for now as it requires registry access
// ESC7: ManageCA or ManageCertificates permissions to non-admins
var esc7Principals []string
for _, perm := range ca.CASecurityPermissions {
if (perm.ManageCA || perm.ManageCerts) && !isWellKnownAdminSID(perm.PrincipalSID) {
permType := ""
if perm.ManageCA {
permType = "ManageCA"
}
if perm.ManageCerts {
if permType != "" {
permType += ", "
}
permType += "ManageCertificates"
}
esc7Principals = append(esc7Principals, fmt.Sprintf("%s (%s)", perm.PrincipalName, permType))
}
}
if len(esc7Principals) > 0 {
vulns = append(vulns, ESCVulnerability{
Name: "ESC7",
Description: "Non-admin principals have ManageCA or ManageCertificates rights",
Principals: esc7Principals,
})
}
return vulns
}
// ldapSearchWithSD performs LDAP search with security descriptor control
func (c *Tickler) ldapSearchWithSD(baseDN string, scope int, filter string, attrs []string) (Results, error) {
// Request security descriptor with OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION
sdFlags := uint32(0x04 | 0x01) // OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION
// Build the control value - just the flags as a 4-byte little-endian integer
controlValue := make([]byte, 4)
binary.LittleEndian.PutUint32(controlValue, sdFlags)
results, err := c.LDAPSearch(
scope,
filter,
attrs,
baseDN,
)
if err != nil {
return nil, err
}
return results, nil
}
// parseFiletimeDuration converts a Windows FILETIME duration to human-readable string
func parseFiletimeDuration(data []byte) string {
if len(data) < 8 {
return ""
}
// FILETIME is stored as negative 100-nanosecond intervals
ft := int64(binary.LittleEndian.Uint64(data))
if ft >= 0 {
return ""
}
// Convert to positive and to seconds
seconds := (-ft) / 10000000
days := seconds / 86400
years := days / 365
weeks := (days % 365) / 7
remainingDays := days % 7
var parts []string
if years > 0 {
parts = append(parts, fmt.Sprintf("%d years", years))
}
if weeks > 0 {
parts = append(parts, fmt.Sprintf("%d weeks", weeks))
}
if remainingDays > 0 {
parts = append(parts, fmt.Sprintf("%d days", remainingDays))
}
if len(parts) == 0 {
return fmt.Sprintf("%d seconds", seconds)
}
return strings.Join(parts, " ")
}