-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdn.go
More file actions
965 lines (890 loc) · 31 KB
/
Copy pathdn.go
File metadata and controls
965 lines (890 loc) · 31 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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
package certkit
import (
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/hex"
"errors"
"fmt"
"log/slog"
"net"
"net/url"
"slices"
"strconv"
"strings"
)
// ErrUnknownOtherNameType is returned when an OtherName type string is not a
// recognized label or a valid dotted-decimal OID.
var ErrUnknownOtherNameType = errors.New("unknown othername type")
// ErrEmptySANExtension is returned when MarshalSANExtension is called with no
// SAN entries of any type.
var ErrEmptySANExtension = errors.New("no SAN entries provided")
var (
errSANEmailEmpty = errors.New("marshaling email SAN: empty value")
errSANEmailNonASCII = errors.New("marshaling email SAN contains non-ASCII characters")
errSANDNSEmpty = errors.New("marshaling DNS SAN: empty value")
errSANDNSNonASCII = errors.New("marshaling DNS SAN contains non-ASCII characters")
errSANInvalidIP = errors.New("invalid IP address: must be 4 or 16 bytes")
errSANNilURI = errors.New("nil URI in SAN input")
errSANURIEmpty = errors.New("marshaling URI SAN: empty value")
errSANURINonASCII = errors.New("marshaling URI SAN contains non-ASCII characters")
errSANOtherNameSRVNonASCII = errors.New("marshaling othername SRV value contains non-ASCII characters")
errParseDNTrailingData = errors.New("parse DN: trailing data")
)
var extKeyUsageNames = map[x509.ExtKeyUsage]string{
x509.ExtKeyUsageAny: "Any",
x509.ExtKeyUsageServerAuth: "Server Authentication",
x509.ExtKeyUsageClientAuth: "Client Authentication",
x509.ExtKeyUsageCodeSigning: "Code Signing",
x509.ExtKeyUsageEmailProtection: "Email Protection",
x509.ExtKeyUsageTimeStamping: "Time Stamping",
x509.ExtKeyUsageOCSPSigning: "OCSP Signing",
x509.ExtKeyUsageMicrosoftServerGatedCrypto: "Microsoft Server Gated Crypto",
x509.ExtKeyUsageNetscapeServerGatedCrypto: "Netscape Server Gated Crypto",
}
// CertificateExtension summarizes one top-level X.509 certificate extension.
type CertificateExtension struct {
OID string `json:"oid"`
Name string `json:"name"`
Critical bool `json:"critical"`
Unhandled bool `json:"unhandled"`
}
// FormatEKUs returns human-readable names for extended key usages.
func FormatEKUs(ekus []x509.ExtKeyUsage) []string {
var out []string
for _, eku := range ekus {
if name, ok := extKeyUsageNames[eku]; ok {
out = append(out, name)
} else {
out = append(out, fmt.Sprintf("Unknown (%d)", int(eku)))
}
}
return out
}
// ekuOIDNames maps well-known Extended Key Usage OIDs to display names.
// Used for parsing EKU from raw ASN.1 extensions (e.g. in CSRs where Go
// does not populate typed fields).
var ekuOIDNames = map[string]string{
"1.3.6.1.5.5.7.3.1": "Server Authentication",
"1.3.6.1.5.5.7.3.2": "Client Authentication",
"1.3.6.1.5.5.7.3.3": "Code Signing",
"1.3.6.1.5.5.7.3.4": "Email Protection",
"1.3.6.1.5.5.7.3.8": "Time Stamping",
"1.3.6.1.5.5.7.3.9": "OCSP Signing",
"1.3.6.1.4.1.311.10.3.3": "Microsoft Server Gated Crypto",
"2.16.840.1.113730.4.1": "Netscape Server Gated Crypto",
"2.5.29.37.0": "Any",
}
// extensionOIDNames maps well-known top-level certificate extension OIDs to
// human-readable names. This intentionally covers extension OIDs only, not
// policy or EKU OIDs embedded inside extension values.
var extensionOIDNames = map[string]string{
// RFC 5280 core and CRL-related extensions.
"2.5.29.9": "Subject Directory Attributes",
"2.5.29.14": "Subject Key Identifier",
"2.5.29.15": "Key Usage",
"2.5.29.16": "Private Key Usage Period",
"2.5.29.17": "Subject Alternative Name",
"2.5.29.18": "Issuer Alternative Name",
"2.5.29.19": "Basic Constraints",
"2.5.29.20": "CRL Number",
"2.5.29.21": "Reason Code",
"2.5.29.23": "Hold Instruction Code",
"2.5.29.24": "Invalidity Date",
"2.5.29.27": "Delta CRL Indicator",
"2.5.29.28": "Issuing Distribution Point",
"2.5.29.29": "Certificate Issuer",
"2.5.29.30": "Name Constraints",
"2.5.29.31": "CRL Distribution Points",
"2.5.29.32": "Certificate Policies",
"2.5.29.33": "Policy Mappings",
"2.5.29.35": "Authority Key Identifier",
"2.5.29.36": "Policy Constraints",
"2.5.29.37": "Extended Key Usage",
"2.5.29.46": "Freshest CRL",
"2.5.29.54": "Inhibit Any Policy",
// PKIX.
"1.3.6.1.5.5.7.1.1": "Authority Information Access",
"1.3.6.1.5.5.7.1.3": "QC Statements",
"1.3.6.1.5.5.7.1.11": "Subject Information Access",
"1.3.6.1.5.5.7.1.24": "TLS Feature",
"1.3.6.1.5.5.7.48.1.5": "OCSP No Check",
"0.4.0.1862.1.1": "QC Statements",
"0.4.0.1862.1.3": "QC Retention Period",
"0.4.0.1862.1.4": "QC SSCD",
"0.4.0.1862.1.6": "QC Type",
"1.3.6.1.4.1.44947.1.1.1": "ACME Identifier",
// Certificate Transparency.
"1.3.6.1.4.1.11129.2.4.2": "Signed Certificate Timestamp List",
"1.3.6.1.4.1.11129.2.4.3": "CT Precertificate Poison",
"1.3.6.1.4.1.11129.2.4.5": "CT Embedded SCT List",
// Netscape.
"2.16.840.1.113730.1.1": "Netscape Certificate Type",
"2.16.840.1.113730.1.2": "Netscape Base URL",
"2.16.840.1.113730.1.3": "Netscape Revocation URL",
"2.16.840.1.113730.1.4": "Netscape CA Revocation URL",
"2.16.840.1.113730.1.7": "Netscape Renewal URL",
"2.16.840.1.113730.1.8": "Netscape CA Policy URL",
"2.16.840.1.113730.1.12": "Netscape SSL Server Name",
"2.16.840.1.113730.1.13": "Netscape Certificate Comment",
// Microsoft.
"1.3.6.1.4.1.311.20.2": "Microsoft Certificate Template Name",
"1.3.6.1.4.1.311.21.1": "Microsoft CA Version",
"1.3.6.1.4.1.311.21.7": "Microsoft Certificate Template Information",
"1.3.6.1.4.1.311.21.10": "Microsoft Application Policies",
// Apple proprietary certificate extensions.
"1.2.840.113635.100.6.1": "Apple Signing",
"1.2.840.113635.100.6.1.4": "Apple iPhone Developer",
"1.2.840.113635.100.6.1.13": "Apple Mac App Signing",
"1.2.840.113635.100.6.2": "Apple Intermediate Markers",
"1.2.840.113635.100.6.2.1": "Apple IST CA",
"1.2.840.113635.100.6.2.10": "Apple System Integration 2 Intermediate Marker",
"1.2.840.113635.100.6.2.12": "Apple Server Authentication Intermediate Marker",
"1.2.840.113635.100.6.2.13": "Apple System Integration G3 Intermediate Marker",
"1.2.840.113635.100.6.2.6": "Apple WWDR Intermediate",
"1.2.840.113635.100.6.24.17": "Apple Corporate Signing Sub-CA Marker",
"1.2.840.113635.100.6.26.6.1": "Apple Measured Boot Policy Signing",
"1.2.840.113635.100.6.27": "Apple Certificate Policy",
"1.2.840.113635.100.6.27.1": "Apple Server Authentication",
"1.2.840.113635.100.6.27.1.2": "Apple Server Authentication v2",
"1.2.840.113635.100.6.27.2": "Apple Client Authentication",
"1.2.840.113635.100.6.27.3": "Apple Push Service",
"1.2.840.113635.100.6.27.3.2": "Apple Push Notification Service",
"1.2.840.113635.100.6.27.4": "Apple Code Signing",
"1.2.840.113635.100.6.27.5": "Apple Timestamping",
"1.2.840.113635.100.6.27.7.1": "Apple Escrow Proxy Server Authentication (QA)",
"1.2.840.113635.100.6.27.7.2": "Apple Escrow Proxy Server Authentication",
"1.2.840.113635.100.6.27.8.1": "Apple System Integration 2",
"1.2.840.113635.100.6.27.11": "Apple PPQ Signing",
"1.2.840.113635.100.6.27.11.1": "Apple MMCS Server Authentication (QA)",
"1.2.840.113635.100.6.27.11.2": "Apple MMCS Server Authentication",
"1.2.840.113635.100.6.27.12": "Apple TestFlight",
"1.2.840.113635.100.6.27.14": "Apple Provisioning Profile Signing",
"1.2.840.113635.100.6.27.15.1": "Apple iCloud Setup Server Authentication (QA)",
"1.2.840.113635.100.6.27.15.2": "Apple iCloud Setup Server Authentication",
"1.2.840.113635.100.6.27.17": "Apple Configuration Profile Signing",
"1.2.840.113635.100.6.27.25": "Apple Developer Authentication",
"1.2.840.113635.100.6.29": "Apple Certificate Transparency Policy",
"1.2.840.113635.100.6.30": "Apple SMP Encryption",
"1.2.840.113635.100.6.38.1": "Apple PPQ Signing Test",
"1.2.840.113635.100.6.38.2": "Apple PPQ Signing",
"1.2.840.113635.100.6.39": "Apple Pay Issuer Encryption",
"1.2.840.113635.100.6.43": "Apple ATV VPN Profile Signing",
"1.2.840.113635.100.6.50": "Apple Static IO",
"1.2.840.113635.100.6.61": "Apple Asset Receipt",
// Google / Android.
"1.3.6.1.4.1.11129.2.1.17": "Android Key Attestation",
"1.3.6.1.4.1.11129.2.1.22": "Google Challenge Password",
}
// FormatEKUOIDs returns human-readable names for EKU OIDs extracted from
// raw ASN.1 extension bytes. This is needed for CSRs where Go does not
// populate ExtKeyUsage typed fields.
func FormatEKUOIDs(raw []byte) []string {
var oids []asn1.ObjectIdentifier
rest, err := asn1.Unmarshal(raw, &oids)
if err != nil || len(rest) != 0 {
return nil
}
var out []string
for _, oid := range oids {
if name, ok := ekuOIDNames[oid.String()]; ok {
out = append(out, name)
} else {
out = append(out, oid.String())
}
}
return out
}
var keyUsageBits = []struct {
bit x509.KeyUsage
name string
}{
{x509.KeyUsageDigitalSignature, "Digital Signature"},
{x509.KeyUsageContentCommitment, "Content Commitment"},
{x509.KeyUsageKeyEncipherment, "Key Encipherment"},
{x509.KeyUsageDataEncipherment, "Data Encipherment"},
{x509.KeyUsageKeyAgreement, "Key Agreement"},
{x509.KeyUsageCertSign, "Certificate Sign"},
{x509.KeyUsageCRLSign, "CRL Sign"},
{x509.KeyUsageEncipherOnly, "Encipher Only"},
{x509.KeyUsageDecipherOnly, "Decipher Only"},
}
// FormatKeyUsage returns human-readable names for key usage bits.
func FormatKeyUsage(ku x509.KeyUsage) []string {
var out []string
for _, entry := range keyUsageBits {
if ku&entry.bit != 0 {
out = append(out, entry.name)
}
}
return out
}
// FormatKeyUsageBitString returns human-readable names for key usage bits
// extracted from a raw ASN.1 BIT STRING extension value. This is needed for
// CSRs where Go does not populate KeyUsage typed fields.
func FormatKeyUsageBitString(raw []byte) []string {
var bs asn1.BitString
rest, err := asn1.Unmarshal(raw, &bs)
if err != nil || len(rest) != 0 {
return nil
}
// Reconstruct x509.KeyUsage by reading each bit from the BIT STRING,
// matching Go's internal parsing in crypto/x509.
var ku x509.KeyUsage
for i := range 9 {
if bs.At(i) != 0 {
ku |= 1 << uint(i)
}
}
return FormatKeyUsage(ku)
}
// oidSubjectAltName is the OID for the Subject Alternative Name extension.
var oidSubjectAltName = asn1.ObjectIdentifier{2, 5, 29, 17}
// otherNameLabels maps well-known OtherName OIDs to display labels.
var otherNameLabels = map[string]string{
"1.3.6.1.4.1.311.20.2.3": "UPN", // Microsoft User Principal Name
"1.3.6.1.5.5.7.8.5": "XMPP", // id-on-xmppAddr
"1.3.6.1.5.5.7.8.7": "SRV", // id-on-dnsSRV
"1.3.6.1.5.5.7.8.9": "SmtpUTF8Mailbox", // id-on-SmtpUTF8Mailbox
"1.3.6.1.4.1.311.25.1": "DC-GUID", // Microsoft DC GUID
"2.16.840.1.113733.1.9.7": "Strong-Extranet", // VeriSign SGC
}
// otherNameOIDs maps well-known OtherName labels to their OIDs.
// This is the reverse of otherNameLabels for the four string-typed OtherName types.
var otherNameOIDs = map[string]asn1.ObjectIdentifier{
"UPN": {1, 3, 6, 1, 4, 1, 311, 20, 2, 3},
"XMPP": {1, 3, 6, 1, 5, 5, 7, 8, 5},
"SRV": {1, 3, 6, 1, 5, 5, 7, 8, 7},
"SmtpUTF8Mailbox": {1, 3, 6, 1, 5, 5, 7, 8, 9},
}
// oidSRV is the OID for id-on-dnsSRV, the only well-known OtherName type
// encoded as IA5String instead of UTF8String.
var oidSRV = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 8, 7}
// OtherNameSAN represents a single OtherName entry in a Subject Alternative
// Name extension. OID identifies the type (e.g. UPN, SRV) and Value holds the
// string representation.
type OtherNameSAN struct {
OID asn1.ObjectIdentifier
Value string
}
// MarshalSANExtensionInput holds all SAN types for building a complete
// SubjectAltName extension. Use this when OtherName entries are needed
// alongside standard SAN types.
type MarshalSANExtensionInput struct {
DNSNames []string
EmailAddresses []string
IPAddresses []net.IP
URIs []*url.URL
OtherNames []OtherNameSAN
}
// isIA5String reports whether s contains only ASCII characters (bytes 0-127),
// as required for IA5String-encoded GeneralName fields (rfc822Name, dNSName,
// uniformResourceIdentifier).
func isIA5String(s string) bool {
for i := range len(s) {
if s[i] > 127 {
return false
}
}
return true
}
// MarshalSANExtension builds a complete Subject Alternative Name extension
// (OID 2.5.29.17) containing all GeneralName types from the input. The
// returned extension can be used in x509.Certificate.ExtraExtensions or
// x509.CertificateRequest.ExtraExtensions.
//
// When OtherNames are present, callers must nil out the typed SAN fields
// (DNSNames, IPAddresses, etc.) on the certificate/CSR template to avoid
// Go's x509 package generating a duplicate SAN extension.
func MarshalSANExtension(input MarshalSANExtensionInput) (pkix.Extension, error) {
var gnBytes []byte
for _, on := range input.OtherNames {
b, err := marshalOtherNameGN(on)
if err != nil {
return pkix.Extension{}, fmt.Errorf("marshaling othername SAN %q: %w", on.OID, err)
}
gnBytes = append(gnBytes, b...)
}
for _, email := range input.EmailAddresses {
if email == "" {
return pkix.Extension{}, errSANEmailEmpty
}
if !isIA5String(email) {
return pkix.Extension{}, fmt.Errorf("%w: %q", errSANEmailNonASCII, email)
}
b, err := asn1.Marshal(asn1.RawValue{
Class: asn1.ClassContextSpecific,
Tag: 1,
Bytes: []byte(email),
})
if err != nil {
return pkix.Extension{}, fmt.Errorf("marshaling email SAN: %w", err)
}
gnBytes = append(gnBytes, b...)
}
for _, dns := range input.DNSNames {
if dns == "" {
return pkix.Extension{}, errSANDNSEmpty
}
if !isIA5String(dns) {
return pkix.Extension{}, fmt.Errorf("%w: %q", errSANDNSNonASCII, dns)
}
b, err := asn1.Marshal(asn1.RawValue{
Class: asn1.ClassContextSpecific,
Tag: 2,
Bytes: []byte(dns),
})
if err != nil {
return pkix.Extension{}, fmt.Errorf("marshaling DNS SAN: %w", err)
}
gnBytes = append(gnBytes, b...)
}
for _, ip := range input.IPAddresses {
ipBytes := ip.To4()
if ipBytes == nil {
ipBytes = ip.To16()
}
if len(ipBytes) != 4 && len(ipBytes) != 16 {
return pkix.Extension{}, fmt.Errorf("%w: %v", errSANInvalidIP, ip)
}
b, err := asn1.Marshal(asn1.RawValue{
Class: asn1.ClassContextSpecific,
Tag: 7,
Bytes: ipBytes,
})
if err != nil {
return pkix.Extension{}, fmt.Errorf("marshaling IP SAN: %w", err)
}
gnBytes = append(gnBytes, b...)
}
for _, uri := range input.URIs {
if uri == nil {
return pkix.Extension{}, errSANNilURI
}
uriStr := uri.String()
if uriStr == "" {
return pkix.Extension{}, errSANURIEmpty
}
if !isIA5String(uriStr) {
return pkix.Extension{}, fmt.Errorf("%w: %q", errSANURINonASCII, uriStr)
}
b, err := asn1.Marshal(asn1.RawValue{
Class: asn1.ClassContextSpecific,
Tag: 6,
Bytes: []byte(uriStr),
})
if err != nil {
return pkix.Extension{}, fmt.Errorf("marshaling URI SAN: %w", err)
}
gnBytes = append(gnBytes, b...)
}
if len(gnBytes) == 0 {
return pkix.Extension{}, fmt.Errorf("marshaling SAN extension: %w", ErrEmptySANExtension)
}
sanSeq := asn1.RawValue{
Tag: asn1.TagSequence,
Class: asn1.ClassUniversal,
IsCompound: true,
Bytes: gnBytes,
}
sanBytes, err := asn1.Marshal(sanSeq)
if err != nil {
return pkix.Extension{}, fmt.Errorf("marshaling SAN extension: %w", err)
}
return pkix.Extension{
Id: oidSubjectAltName,
Value: sanBytes,
}, nil
}
// ResolveOtherNameOID resolves a human-readable label ("UPN", "SRV") or
// dotted-decimal OID string ("1.3.6.1.4.1.311.20.2.3") to an
// asn1.ObjectIdentifier.
func ResolveOtherNameOID(s string) (asn1.ObjectIdentifier, error) {
if s == "" {
return nil, fmt.Errorf("%w: empty othername type", ErrUnknownOtherNameType)
}
if oid, ok := otherNameOIDs[s]; ok {
return append(asn1.ObjectIdentifier(nil), oid...), nil
}
parts := strings.Split(s, ".")
if len(parts) < 2 {
return nil, fmt.Errorf("%w %q: not a known label or valid OID", ErrUnknownOtherNameType, s)
}
oid := make(asn1.ObjectIdentifier, 0, len(parts))
for _, part := range parts {
n, err := strconv.Atoi(part)
if err != nil || n < 0 {
return nil, fmt.Errorf("%w %q: not a known label or valid OID", ErrUnknownOtherNameType, s)
}
oid = append(oid, n)
}
return oid, nil
}
// otherNameStringTag returns the ASN.1 tag for encoding an OtherName value.
// SRV (id-on-dnsSRV) uses IA5String; all others use UTF8String.
func otherNameStringTag(oid asn1.ObjectIdentifier) int {
if oid.Equal(oidSRV) {
return asn1.TagIA5String
}
return asn1.TagUTF8String
}
// marshalOtherNameGN encodes a single OtherName as a GeneralName (context-
// specific tag 0). The encoding follows RFC 5280:
//
// OtherName ::= SEQUENCE { type-id OID, value [0] EXPLICIT ANY }
//
// With IMPLICIT tagging, the outer SEQUENCE tag is replaced by the
// context-specific tag 0 for the GeneralName CHOICE.
func marshalOtherNameGN(on OtherNameSAN) ([]byte, error) {
oidBytes, err := asn1.Marshal(on.OID)
if err != nil {
return nil, fmt.Errorf("marshaling othername OID: %w", err)
}
tag := otherNameStringTag(on.OID)
if tag == asn1.TagIA5String && !isIA5String(on.Value) {
return nil, fmt.Errorf("%w: %q", errSANOtherNameSRVNonASCII, on.Value)
}
var valueBytes []byte
if tag == asn1.TagIA5String {
valueBytes, err = asn1.Marshal(asn1.RawValue{
Tag: asn1.TagIA5String,
Class: asn1.ClassUniversal,
Bytes: []byte(on.Value),
})
} else {
valueBytes, err = asn1.Marshal(asn1.RawValue{
Tag: tag,
Class: asn1.ClassUniversal,
Bytes: []byte(on.Value),
})
}
if err != nil {
return nil, fmt.Errorf("marshaling othername value: %w", err)
}
explicitBytes, err := asn1.Marshal(asn1.RawValue{
Class: asn1.ClassContextSpecific,
Tag: 0,
IsCompound: true,
Bytes: valueBytes,
})
if err != nil {
return nil, fmt.Errorf("marshaling othername explicit wrapper: %w", err)
}
seqContent := slices.Concat(oidBytes, explicitBytes)
gnBytes, err := asn1.Marshal(asn1.RawValue{
Class: asn1.ClassContextSpecific,
Tag: 0,
IsCompound: true,
Bytes: seqContent,
})
if err != nil {
return nil, fmt.Errorf("marshaling othername GeneralName: %w", err)
}
return gnBytes, nil
}
// parseOtherNameSANEntries extracts structured OtherNameSAN entries from
// a list of extensions. Unlike ParseOtherNameSANs which returns formatted
// strings, this returns typed entries suitable for re-encoding.
func parseOtherNameSANEntries(extensions []pkix.Extension) []OtherNameSAN {
for _, ext := range extensions {
if !ext.Id.Equal(oidSubjectAltName) {
continue
}
return parseOtherNameEntriesFromSANBytes(ext.Value)
}
return nil
}
func parseOtherNameEntriesFromSANBytes(raw []byte) []OtherNameSAN {
var entries []OtherNameSAN
walkOtherNameSANs(raw, func(oid asn1.ObjectIdentifier, valueBytes []byte) {
var strVal string
if _, strErr := asn1.Unmarshal(valueBytes, &strVal); strErr != nil {
slog.Debug("skipping OtherName entry: string value parse failed", "oid", oid, "error", strErr)
return
}
entries = append(entries, OtherNameSAN{OID: oid, Value: strVal})
})
return entries
}
// walkOtherNameSANs iterates over the OtherName GeneralName entries in raw
// SAN extension bytes and calls fn for each successfully parsed entry. The
// valueBytes passed to fn are the inner bytes of the [0] EXPLICIT wrapper
// (i.e. the TLV-encoded string value). This shared walker is used by both
// parseOtherNameEntriesFromSANBytes (structured extraction) and
// parseOtherNamesFromSANBytes (display formatting).
func walkOtherNameSANs(raw []byte, fn func(oid asn1.ObjectIdentifier, valueBytes []byte)) {
var seq asn1.RawValue
rest, err := asn1.Unmarshal(raw, &seq)
if err != nil || len(rest) > 0 {
return
}
inner := seq.Bytes
for len(inner) > 0 {
var gn asn1.RawValue
inner, err = asn1.Unmarshal(inner, &gn)
if err != nil {
break
}
if gn.Class != asn1.ClassContextSpecific || gn.Tag != 0 {
continue
}
content := gn.Bytes
var probe asn1.RawValue
if _, probeErr := asn1.Unmarshal(gn.Bytes, &probe); probeErr == nil &&
probe.Tag == asn1.TagSequence && probe.Class == asn1.ClassUniversal {
content = probe.Bytes
}
var oid asn1.ObjectIdentifier
oidRest, oidErr := asn1.Unmarshal(content, &oid)
if oidErr != nil {
slog.Debug("skipping OtherName entry: OID parse failed", "error", oidErr)
continue
}
var explicit asn1.RawValue
if _, explErr := asn1.Unmarshal(oidRest, &explicit); explErr != nil {
slog.Debug("skipping OtherName entry: explicit tag parse failed", "oid", oid, "error", explErr)
continue
}
if explicit.Class != asn1.ClassContextSpecific || explicit.Tag != 0 || !explicit.IsCompound {
slog.Debug("skipping OtherName entry: explicit tag invalid",
"oid", oid,
"class", explicit.Class,
"tag", explicit.Tag,
"compound", explicit.IsCompound,
)
continue
}
fn(oid, explicit.Bytes)
}
}
// ParseOtherNameSANs extracts SAN entries that Go's x509 package silently
// drops: OtherName (tag 0), DirectoryName (tag 4), and RegisteredID (tag 8).
// Returns formatted strings like "UPN:user@example.com" or
// "OtherName(1.2.3.4):value". Pass the raw extensions list from a certificate
// or CSR.
func ParseOtherNameSANs(extensions []pkix.Extension) []string {
var sans []string
for _, ext := range extensions {
if !ext.Id.Equal(oidSubjectAltName) {
continue
}
sans = append(sans, parseOtherNamesFromSANBytes(ext.Value)...)
}
if len(sans) == 0 {
return nil
}
return sans
}
// ExtensionOIDName returns the human-readable name for a certificate
// extension OID, or the dotted-decimal OID string if it is not in the
// registry.
func ExtensionOIDName(oid string) string {
if name, ok := extensionOIDNames[oid]; ok {
return name
}
if suffix, ok := strings.CutPrefix(oid, "1.2.840.113635.100.6."); ok {
return "Apple Proprietary Extension " + suffix
}
if suffix, ok := strings.CutPrefix(oid, "1.3.6.1.4.1.311."); ok {
return "Microsoft Proprietary Extension " + suffix
}
if suffix, ok := strings.CutPrefix(oid, "2.16.840.1.113730."); ok {
return "Netscape Proprietary Extension " + suffix
}
return oid
}
// CollectCertificateExtensions returns a summary of every top-level X.509
// certificate extension on cert. Unhandled is sourced from Go's
// UnhandledCriticalExtensions slice.
func CollectCertificateExtensions(cert *x509.Certificate) []CertificateExtension {
if cert == nil || len(cert.Extensions) == 0 {
return nil
}
unhandled := make(map[string]struct{}, len(cert.UnhandledCriticalExtensions))
for _, oid := range cert.UnhandledCriticalExtensions {
unhandled[oid.String()] = struct{}{}
}
exts := make([]CertificateExtension, 0, len(cert.Extensions))
for _, ext := range cert.Extensions {
oid := ext.Id.String()
_, isUnhandled := unhandled[oid]
exts = append(exts, CertificateExtension{
OID: oid,
Name: ExtensionOIDName(oid),
Critical: ext.Critical,
Unhandled: isUnhandled,
})
}
return exts
}
// CollectCertificateSANs returns all Subject Alternative Names from a
// certificate: DNS names, IP addresses, email addresses, URIs, and OtherName
// extensions. This is the canonical SAN aggregation used across all CLI
// commands for CLI-4 consistency.
func CollectCertificateSANs(cert *x509.Certificate) []string {
sans := slices.Clone(cert.DNSNames)
for _, ip := range cert.IPAddresses {
sans = append(sans, ip.String())
}
sans = append(sans, cert.EmailAddresses...)
for _, uri := range cert.URIs {
sans = append(sans, uri.String())
}
sans = append(sans, ParseOtherNameSANs(cert.Extensions)...)
return sans
}
func parseOtherNamesFromSANBytes(raw []byte) []string {
// SAN extension value is: SEQUENCE OF GeneralName
var seq asn1.RawValue
rest, err := asn1.Unmarshal(raw, &seq)
if err != nil || len(rest) > 0 {
return nil
}
// Collect OtherName entries via shared walker.
var sans []string
walkOtherNameSANs(raw, func(oid asn1.ObjectIdentifier, valueBytes []byte) {
label := oid.String()
if name, ok := otherNameLabels[label]; ok {
label = name
}
var strVal string
if _, strErr := asn1.Unmarshal(valueBytes, &strVal); strErr == nil {
sans = append(sans, label+":"+strVal)
} else {
sans = append(sans, label+":"+hex.EncodeToString(valueBytes))
}
})
// Handle DirectoryName (tag 4) and RegisteredID (tag 8) which the
// OtherName walker does not cover.
inner := seq.Bytes
for len(inner) > 0 {
var gn asn1.RawValue
inner, err = asn1.Unmarshal(inner, &gn)
if err != nil {
break
}
if gn.Class != asn1.ClassContextSpecific {
continue
}
switch gn.Tag {
case 4: // directoryName [4]
var name pkix.RDNSequence
if _, err := asn1.Unmarshal(gn.Bytes, &name); err == nil {
var pn pkix.Name
pn.FillFromRDNSequence(&name)
sans = append(sans, "DirName:"+FormatDN(pn))
}
case 8: // registeredID [8] IMPLICIT OBJECT IDENTIFIER
// gn.Bytes contains the raw OID content but gn.FullBytes has a
// context-specific tag (0x88) instead of the universal OID tag
// (0x06). Re-wrap as a universal OID before unmarshaling.
rewrapped, rewrapErr := asn1.Marshal(asn1.RawValue{
Class: asn1.ClassUniversal,
Tag: asn1.TagOID,
Bytes: gn.Bytes,
})
if rewrapErr != nil {
slog.Debug("skipping registeredID SAN: re-wrap failed", "error", rewrapErr)
continue
}
var oid asn1.ObjectIdentifier
if _, err := asn1.Unmarshal(rewrapped, &oid); err == nil {
sans = append(sans, "RegisteredID:"+oid.String())
}
}
}
if len(sans) == 0 {
return nil
}
return sans
}
// oidLabel maps certificate subject OIDs to their standard human-readable
// labels. It includes both the standard X.500 attributes that Go's
// crypto/x509/pkix package handles natively and the additional OIDs that
// Go renders as raw dotted-decimal 1.2.3.4=#hex values.
//
// When name.Names is populated (always the case for parsed certificates),
// FormatDN iterates it in ASN.1 DER order and looks up each OID here,
// matching the display order that OpenSSL uses.
var oidLabel = map[string]string{
// Standard X.500 attributes rendered natively by Go's pkix package.
"2.5.4.3": "CN",
"2.5.4.5": "SERIALNUMBER",
"2.5.4.6": "C",
"2.5.4.7": "L",
"2.5.4.8": "ST",
"2.5.4.9": "STREET",
"2.5.4.10": "O",
"2.5.4.11": "OU",
"2.5.4.17": "POSTALCODE",
// X.500 personal name attributes (RFC 4519).
"2.5.4.4": "SN", // surname
"2.5.4.41": "name", // name
"2.5.4.42": "GN", // givenName
"2.5.4.43": "initials", // initials
"2.5.4.44": "generationQualifier",
"2.5.4.46": "dnQualifier",
"2.5.4.65": "pseudonym",
// X.500 organization attributes.
"2.5.4.15": "businessCategory",
"2.5.4.16": "postalAddress",
"2.5.4.20": "telephoneNumber",
"2.5.4.97": "organizationIdentifier", // eIDAS / QWAC
// Email (RFC 2985).
"1.2.840.113549.1.9.1": "emailAddress",
// EV certificate jurisdiction fields (CA/B Forum EV Guidelines).
// OpenSSL abbreviates these as jurisdictionL/ST/C, mirroring the base
// X.500 locality/state/country abbreviations.
"1.3.6.1.4.1.311.60.2.1.1": "jurisdictionL",
"1.3.6.1.4.1.311.60.2.1.2": "jurisdictionST",
"1.3.6.1.4.1.311.60.2.1.3": "jurisdictionC",
}
// FormatDN formats a pkix.Name as a Distinguished Name string in ASN.1 DER
// order, matching the display order used by OpenSSL. When name.Names is
// populated (always the case for certificates parsed from DER/PEM), attributes
// are emitted in their original encoded order with human-readable labels.
// Unknown OIDs are rendered as dotted-decimal 1.2.3.4=#hex values. Multi-valued RDNs are
// flattened because pkix.Name does not preserve SET boundaries; prefer
// FormatDNFromRaw when raw DER is available. When name.Names is empty (e.g. a
// pkix.Name constructed programmatically without setting Names), it falls back
// to pkix.Name.String().
func FormatDN(name pkix.Name) string {
if len(name.Names) == 0 {
return name.String()
}
parts := make([]string, 0, len(name.Names))
for _, atv := range name.Names {
parts = append(parts, formatDNAttribute(atv))
}
return strings.Join(parts, ",")
}
// FormatDNFromRaw formats a Distinguished Name from the raw DER-encoded
// RDNSequence (e.g. Certificate.RawSubject/RawIssuer). When raw is empty or
// unparsable, it falls back to FormatDN.
func FormatDNFromRaw(raw []byte, fallback pkix.Name) string {
if len(raw) == 0 {
return FormatDN(fallback)
}
formatted, err := formatDERRDN(raw)
if err != nil {
slog.Debug("formatting DN from raw DER failed", "error", err)
return FormatDN(fallback)
}
return formatted
}
func formatDERRDN(raw []byte) (string, error) {
var rdns pkix.RDNSequence
rest, err := asn1.Unmarshal(raw, &rdns)
if err != nil {
return "", fmt.Errorf("parse DN: %w", err)
}
if len(rest) != 0 {
return "", errParseDNTrailingData
}
return formatRDNSequence(rdns), nil
}
func formatRDNSequence(rdns pkix.RDNSequence) string {
if len(rdns) == 0 {
return ""
}
parts := make([]string, 0, len(rdns))
for _, rdn := range rdns {
if len(rdn) == 0 {
continue
}
attributes := make([]string, 0, len(rdn))
for _, atv := range rdn {
attributes = append(attributes, formatDNAttribute(atv))
}
if len(attributes) == 0 {
continue
}
parts = append(parts, strings.Join(attributes, "+"))
}
return strings.Join(parts, ",")
}
func formatDNAttribute(atv pkix.AttributeTypeAndValue) string {
oid := atv.Type.String()
label, hasLabel := oidLabel[oid]
if hasLabel {
if value, ok := stringFromASN1Value(atv.Value); ok {
return label + "=" + escapeDNValue(value)
}
}
// Unknown OID or non-string value: render as dotted-decimal 1.2.3.4=#hex.
derBytes, err := marshalDNValue(atv.Value)
if err != nil {
slog.Debug("failed to marshal DN attribute value",
"oid", oid,
"error", err,
)
if hasLabel {
return label + "=<unencodable>"
}
return oid + "=<unencodable>"
}
if hasLabel {
return label + "=#" + hex.EncodeToString(derBytes)
}
return oid + "=#" + hex.EncodeToString(derBytes)
}
func stringFromASN1Value(value any) (string, bool) {
switch typed := value.(type) {
case string:
return typed, true
case asn1.RawValue:
if len(typed.FullBytes) == 0 {
return "", false
}
var s string
rest, err := asn1.Unmarshal(typed.FullBytes, &s)
if err != nil || len(rest) != 0 {
return "", false
}
return s, true
default:
return "", false
}
}
func marshalDNValue(value any) ([]byte, error) {
if raw, ok := value.(asn1.RawValue); ok && len(raw.FullBytes) > 0 {
return raw.FullBytes, nil
}
data, err := asn1.Marshal(value)
if err != nil {
return nil, fmt.Errorf("marshaling DN value: %w", err)
}
return data, nil
}
// escapeDNValue escapes special characters in a DN attribute value per RFC 4514.
func escapeDNValue(s string) string {
if len(s) == 0 {
return s
}
var b strings.Builder
b.Grow(len(s))
for i, r := range s {
switch r {
case ',', '+', '"', '\\', '<', '>', ';', '=':
b.WriteByte('\\')
b.WriteRune(r)
case '#':
if i == 0 {
b.WriteByte('\\')
}
b.WriteRune(r)
case ' ':
if i == 0 || i == len(s)-1 {
b.WriteByte('\\')
}
b.WriteRune(r)
default:
if r < 0x20 || r == 0x7f {
fmt.Fprintf(&b, "\\%02X", r)
continue
}
b.WriteRune(r)
}
}
return b.String()
}