forked from zmap/zcrypto
/
x509_modified.go
1568 lines (1397 loc) · 51.6 KB
/
x509_modified.go
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
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package x509 parses X.509-encoded keys and certificates.
package x509
import (
// all of the hash libraries need to be imported for side-effects,
// so that crypto.RegisterHash is called
_ "crypto/md5"
"crypto/sha256"
_ "crypto/sha512"
"strings"
"bytes"
"crypto"
"crypto/dsa"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rsa"
"encoding/asn1"
"errors"
"fmt"
"math/big"
"net"
"strconv"
"time"
"github.com/smallstep/zcrypto/x509/ct"
"github.com/smallstep/zcrypto/x509/pkix"
"github.com/weppos/publicsuffix-go/publicsuffix"
"golang.org/x/crypto/ed25519"
)
// ParsedDomainName is a structure holding a parsed domain name (CommonName or DNS SAN) and a parsing error.
type ParsedDomainName struct {
DomainString string
ParsedDomain *publicsuffix.DomainName
ParseError error
}
func marshalPublicKey(pub interface{}) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) {
switch pub := pub.(type) {
case *rsa.PublicKey:
publicKeyBytes, err = asn1.Marshal(pkcs1PublicKey{
N: pub.N,
E: pub.E,
})
if err != nil {
return nil, pkix.AlgorithmIdentifier{}, err
}
publicKeyAlgorithm.Algorithm = oidPublicKeyRSA
// This is a NULL parameters value which is required by
// https://tools.ietf.org/html/rfc3279#section-2.3.1.
publicKeyAlgorithm.Parameters = asn1.NullRawValue
case *ecdsa.PublicKey:
publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
oid, ok := oidFromNamedCurve(pub.Curve)
if !ok {
return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
}
publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
var paramBytes []byte
paramBytes, err = asn1.Marshal(oid)
if err != nil {
return
}
publicKeyAlgorithm.Parameters.FullBytes = paramBytes
case *AugmentedECDSA:
return marshalPublicKey(pub.Pub)
case ed25519.PublicKey:
publicKeyAlgorithm.Algorithm = oidKeyEd25519
return []byte(pub), publicKeyAlgorithm, nil
case X25519PublicKey:
publicKeyAlgorithm.Algorithm = oidKeyX25519
return []byte(pub), publicKeyAlgorithm, nil
default:
return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: only RSA, ECDSA, ed25519, or X25519 public keys supported")
}
return publicKeyBytes, publicKeyAlgorithm, nil
}
// These structures reflect the ASN.1 structure of X.509 certificates.:
type AugmentedECDSA struct {
Pub *ecdsa.PublicKey
Raw asn1.BitString
}
type SignatureAlgorithmOID asn1.ObjectIdentifier
const (
UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
RSA
DSA
ECDSA
ED25519
X25519
total_key_algorithms
)
var keyAlgorithmNames = []string{
"unknown_algorithm",
"RSA",
"DSA",
"ECDSA",
"Ed25519",
"X25519",
}
func maxValidationLevel(a, b CertValidationLevel) CertValidationLevel {
if a > b {
return a
}
return b
}
func getMaxCertValidationLevel(oids []asn1.ObjectIdentifier) CertValidationLevel {
maxOID := UnknownValidationLevel
for _, oid := range oids {
if _, ok := ExtendedValidationOIDs[oid.String()]; ok {
return EV
} else if _, ok := OrganizationValidationOIDs[oid.String()]; ok {
maxOID = maxValidationLevel(maxOID, OV)
} else if _, ok := DomainValidationOIDs[oid.String()]; ok {
maxOID = maxValidationLevel(maxOID, DV)
}
}
return maxOID
}
// TODO: slight differences in case in some names. Should be easy to align with stdlib.
// leaving for now to not break compatibility
// extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
var extKeyUsageOIDs = []struct {
extKeyUsage ExtKeyUsage
oid asn1.ObjectIdentifier
}{
{ExtKeyUsageAny, oidExtKeyUsageAny},
{ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
{ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
{ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
{ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
//{ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
{ExtKeyUsageIpsecUser, oidExtKeyUsageIpsecEndSystem},
//{ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
{ExtKeyUsageIpsecTunnel, oidExtKeyUsageIpsecTunnel},
//{ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
{ExtKeyUsageIpsecUser, oidExtKeyUsageIpsecUser},
{ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
//{ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
{ExtKeyUsageOcspSigning, oidExtKeyUsageOcspSigning},
{ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
{ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
}
// TODO: slight differences in case in some names. Should be easy to align with stdlib.
// leaving for now to not break compatibility
// extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
var nativeExtKeyUsageOIDs = []struct {
extKeyUsage ExtKeyUsage
oid asn1.ObjectIdentifier
}{
{ExtKeyUsageAny, oidExtKeyUsageAny},
{ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
{ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
{ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
{ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
{ExtKeyUsageIpsecEndSystem, oidExtKeyUsageIpsecEndSystem},
{ExtKeyUsageIpsecTunnel, oidExtKeyUsageIpsecTunnel},
{ExtKeyUsageIpsecUser, oidExtKeyUsageIpsecUser},
{ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
{ExtKeyUsageOcspSigning, oidExtKeyUsageOcspSigning},
{ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
{ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
}
func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) {
s := oid.String()
eku, ok = ekuConstants[s]
return
}
func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
for _, pair := range nativeExtKeyUsageOIDs {
if eku == pair.extKeyUsage {
return pair.oid, true
}
}
return
}
// A Certificate represents an X.509 certificate.
type Certificate struct {
Raw []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
RawTBSCertificate []byte // Certificate part of raw ASN.1 DER content.
RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
RawSubject []byte // DER encoded Subject
RawIssuer []byte // DER encoded Issuer
Signature []byte
SignatureAlgorithm SignatureAlgorithm
SelfSigned bool
SignatureAlgorithmOID asn1.ObjectIdentifier
PublicKeyAlgorithm PublicKeyAlgorithm
PublicKey interface{}
PublicKeyAlgorithmOID asn1.ObjectIdentifier
Version int
SerialNumber *big.Int
Issuer pkix.Name
Subject pkix.Name
NotBefore, NotAfter time.Time // Validity bounds.
ValidityPeriod int
KeyUsage KeyUsage
IssuerUniqueId asn1.BitString
SubjectUniqueId asn1.BitString
// Extensions contains raw X.509 extensions. When parsing certificates,
// this can be used to extract non-critical extensions that are not
// parsed by this package. When marshaling certificates, the Extensions
// field is ignored, see ExtraExtensions.
Extensions []pkix.Extension
// ExtraExtensions contains extensions to be copied, raw, into any
// marshaled certificates. Values override any extensions that would
// otherwise be produced based on the other fields. The ExtraExtensions
// field is not populated when parsing certificates, see Extensions.
ExtraExtensions []pkix.Extension
// UnhandledCriticalExtensions contains a list of extension IDs that
// were not (fully) processed when parsing. Verify will fail if this
// slice is non-empty, unless verification is delegated to an OS
// library which understands all the critical extensions.
//
// Users can access these extensions using Extensions and can remove
// elements from this slice if they believe that they have been
// handled.
UnhandledCriticalExtensions []asn1.ObjectIdentifier
ExtKeyUsage []ExtKeyUsage // Sequence of extended key usages.
UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
BasicConstraintsValid bool // if true then the next two fields are valid.
IsCA bool
// MaxPathLen and MaxPathLenZero indicate the presence and
// value of the BasicConstraints' "pathLenConstraint".
//
// When parsing a certificate, a positive non-zero MaxPathLen
// means that the field was specified, -1 means it was unset,
// and MaxPathLenZero being true mean that the field was
// explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false
// should be treated equivalent to -1 (unset).
//
// When generating a certificate, an unset pathLenConstraint
// can be requested with either MaxPathLen == -1 or using the
// zero value for both MaxPathLen and MaxPathLenZero.
MaxPathLen int
// MaxPathLenZero indicates that BasicConstraintsValid==true and
// MaxPathLen==0 should be interpreted as an actual Max path length
// of zero. Otherwise, that combination is interpreted as MaxPathLen
// not being set.
MaxPathLenZero bool
SubjectKeyId []byte
AuthorityKeyId []byte
// RFC 5280, 4.2.2.1 (Authority Information Access)
OCSPServer []string
IssuingCertificateURL []string
// Subject Alternate Name values
OtherNames []pkix.OtherName
DNSNames []string
EmailAddresses []string
DirectoryNames []pkix.Name
EDIPartyNames []pkix.EDIPartyName
URIs []string
IPAddresses []net.IP
RegisteredIDs []asn1.ObjectIdentifier
// Issuer Alternative Name values
IANOtherNames []pkix.OtherName
IANDNSNames []string
IANEmailAddresses []string
IANDirectoryNames []pkix.Name
IANEDIPartyNames []pkix.EDIPartyName
IANURIs []string
IANIPAddresses []net.IP
IANRegisteredIDs []asn1.ObjectIdentifier
// Certificate Policies values
QualifierId [][]asn1.ObjectIdentifier
CPSuri [][]string
ExplicitTexts [][]asn1.RawValue
NoticeRefOrgnization [][]asn1.RawValue
NoticeRefNumbers [][]NoticeNumber
ParsedExplicitTexts [][]string
ParsedNoticeRefOrganization [][]string
// Name constraints
NameConstraintsCritical bool // if true then the name constraints are marked critical.
PermittedDNSNames []GeneralSubtreeString
ExcludedDNSNames []GeneralSubtreeString
PermittedEmailAddresses []GeneralSubtreeString
ExcludedEmailAddresses []GeneralSubtreeString
PermittedIPAddresses []GeneralSubtreeIP
ExcludedIPAddresses []GeneralSubtreeIP
PermittedDirectoryNames []GeneralSubtreeName
ExcludedDirectoryNames []GeneralSubtreeName
PermittedEdiPartyNames []GeneralSubtreeEdi
ExcludedEdiPartyNames []GeneralSubtreeEdi
PermittedRegisteredIDs []GeneralSubtreeOid
ExcludedRegisteredIDs []GeneralSubtreeOid
PermittedX400Addresses []GeneralSubtreeRaw
ExcludedX400Addresses []GeneralSubtreeRaw
// CRL Distribution Points
CRLDistributionPoints []string
PolicyIdentifiers []asn1.ObjectIdentifier
ValidationLevel CertValidationLevel
// Fingerprints
FingerprintMD5 CertificateFingerprint
FingerprintSHA1 CertificateFingerprint
FingerprintSHA256 CertificateFingerprint
FingerprintNoCT CertificateFingerprint
// SPKI
SPKIFingerprint CertificateFingerprint
SPKISubjectFingerprint CertificateFingerprint
TBSCertificateFingerprint CertificateFingerprint
IsPrecert bool
// Internal
validSignature bool
// CT
SignedCertificateTimestampList []*ct.SignedCertificateTimestamp
// Used to speed up the zlint checks. Populated by the GetParsedDNSNames method.
parsedDNSNames []ParsedDomainName
// Used to speed up the zlint checks. Populated by the GetParsedCommonName method
parsedCommonName *ParsedDomainName
// Step Provisioner
StepProvisioner *StepProvisioner
}
// SubjectAndKey represents a (subjecty, subject public key info) tuple.
type SubjectAndKey struct {
RawSubject []byte
RawSubjectPublicKeyInfo []byte
Fingerprint CertificateFingerprint
PublicKey interface{}
PublicKeyAlgorithm PublicKeyAlgorithm
}
type NoticeNumber []int
type GeneralSubtreeString struct {
Data string
Max int
Min int
}
type GeneralSubtreeIP struct {
Data net.IPNet
Max int
Min int
}
type GeneralSubtreeName struct {
Data pkix.Name
Max int
Min int
}
type GeneralSubtreeEdi struct {
Data pkix.EDIPartyName
Max int
Min int
}
type GeneralSubtreeOid struct {
Data asn1.ObjectIdentifier
Max int
Min int
}
type GeneralSubtreeRaw struct {
Data asn1.RawValue
Max int
Min int
}
// SubjectAndKey returns a SubjectAndKey for this certificate.
func (c *Certificate) SubjectAndKey() *SubjectAndKey {
return &SubjectAndKey{
RawSubject: c.RawSubject,
RawSubjectPublicKeyInfo: c.RawSubjectPublicKeyInfo,
Fingerprint: c.SPKISubjectFingerprint,
PublicKey: c.PublicKey,
PublicKeyAlgorithm: c.PublicKeyAlgorithm,
}
}
// CheckSignatureFrom verifies that the signature on c is a valid signature
// from parent.
func (c *Certificate) CheckSignatureFrom(parent *Certificate) (err error) {
// RFC 5280, 4.2.1.9:
// "If the basic constraints extension is not present in a version 3
// certificate, or the extension is present but the cA boolean is not
// asserted, then the certified public key MUST NOT be used to verify
// certificate signatures."
// (except for Entrust, see comment above entrustBrokenSPKI)
if (parent.Version == 3 && !parent.BasicConstraintsValid ||
parent.BasicConstraintsValid && !parent.IsCA) &&
!bytes.Equal(c.RawSubjectPublicKeyInfo, entrustBrokenSPKI) {
return ConstraintViolationError{}
}
if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
return ConstraintViolationError{}
}
if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
return ErrUnsupportedAlgorithm
}
// TODO(agl): don't ignore the path length constraint.
if !bytes.Equal(parent.RawSubject, c.RawIssuer) {
return errors.New("Mis-match issuer/subject")
}
return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature)
}
func hash(hashFunc crypto.Hash, raw []byte) []byte {
digest := raw
if hashFunc != 0 {
h := hashFunc.New()
h.Write(raw)
digest = h.Sum(nil)
}
return digest
}
func CheckSignatureFromKey(publicKey interface{}, algo SignatureAlgorithm, signed, signature []byte) (err error) {
var hashType crypto.Hash
switch algo {
// NOTE: exception to stdlib, allow MD5 algorithm
case MD5WithRSA:
hashType = crypto.MD5
case SHA1WithRSA, DSAWithSHA1, ECDSAWithSHA1:
hashType = crypto.SHA1
case SHA256WithRSA, SHA256WithRSAPSS, DSAWithSHA256, ECDSAWithSHA256:
hashType = crypto.SHA256
case SHA384WithRSA, SHA384WithRSAPSS, ECDSAWithSHA384:
hashType = crypto.SHA384
case SHA512WithRSA, SHA512WithRSAPSS, ECDSAWithSHA512:
hashType = crypto.SHA512
//case MD2WithRSA, MD5WithRSA:
case MD2WithRSA:
return InsecureAlgorithmError(algo)
case ED25519SIG:
hashType = 0
default:
return ErrUnsupportedAlgorithm
}
if hashType != 0 && !hashType.Available() {
return ErrUnsupportedAlgorithm
}
digest := hash(hashType, signed)
switch pub := publicKey.(type) {
case *rsa.PublicKey:
if algo.isRSAPSS() {
return rsa.VerifyPSS(pub, hashType, digest, signature, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
} else {
return rsa.VerifyPKCS1v15(pub, hashType, digest, signature)
}
case *dsa.PublicKey:
dsaSig := new(dsaSignature)
if rest, err := asn1.Unmarshal(signature, dsaSig); err != nil {
return err
} else if len(rest) != 0 {
return errors.New("x509: trailing data after DSA signature")
}
if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 {
return errors.New("x509: DSA signature contained zero or negative values")
}
if !dsa.Verify(pub, digest, dsaSig.R, dsaSig.S) {
return errors.New("x509: DSA verification failure")
}
return
case *ecdsa.PublicKey:
ecdsaSig := new(ecdsaSignature)
if rest, err := asn1.Unmarshal(signature, ecdsaSig); err != nil {
return err
} else if len(rest) != 0 {
return errors.New("x509: trailing data after ECDSA signature")
}
if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
return errors.New("x509: ECDSA signature contained zero or negative values")
}
if !ecdsa.Verify(pub, digest, ecdsaSig.R, ecdsaSig.S) {
return errors.New("x509: ECDSA verification failure")
}
return
case *AugmentedECDSA:
ecdsaSig := new(ecdsaSignature)
if _, err := asn1.Unmarshal(signature, ecdsaSig); err != nil {
return err
}
if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
return errors.New("x509: ECDSA signature contained zero or negative values")
}
if !ecdsa.Verify(pub.Pub, digest, ecdsaSig.R, ecdsaSig.S) {
return errors.New("x509: ECDSA verification failure")
}
return
case ed25519.PublicKey:
if !ed25519.Verify(pub, digest, signature) {
return errors.New("x509: ED25519 verification failure")
}
return
}
return ErrUnsupportedAlgorithm
}
// CheckCRLSignature checks that the signature in crl is from c.
func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error {
algo := GetSignatureAlgorithmFromAI(crl.SignatureAlgorithm)
return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
}
// UnhandledCriticalExtension results when the certificate contains an
// unimplemented X.509 extension marked as critical.
type UnhandledCriticalExtension struct {
oid asn1.ObjectIdentifier
message string
}
func (h UnhandledCriticalExtension) Error() string {
return fmt.Sprintf("x509: unhandled critical extension: %s | %s", h.oid, h.message)
}
// CheckSignature verifies that signature is a valid signature over signed from
// c's public key.
func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) (err error) {
return CheckSignatureFromKey(c.PublicKey, algo, signed, signature)
}
// TimeInValidityPeriod returns true if NotBefore < t < NotAfter
func (c *Certificate) TimeInValidityPeriod(t time.Time) bool {
return c.NotBefore.Before(t) && c.NotAfter.After(t)
}
// RFC 5280 4.2.1.4
type policyInformation struct {
Policy asn1.ObjectIdentifier
Qualifiers []policyQualifierInfo `asn1:"optional"`
}
type policyQualifierInfo struct {
PolicyQualifierId asn1.ObjectIdentifier
Qualifier asn1.RawValue
}
type userNotice struct {
NoticeRef noticeReference `asn1:"optional"`
ExplicitText asn1.RawValue `asn1:"optional"`
}
type noticeReference struct {
Organization asn1.RawValue
NoticeNumbers []int
}
type generalSubtree struct {
Value asn1.RawValue `asn1:"optional"`
Min int `asn1:"tag:0,default:0,optional"`
Max int `asn1:"tag:1,optional"`
}
func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (interface{}, error) {
asn1Data := keyData.PublicKey.RightAlign()
switch algo {
case RSA:
// TODO: disabled since current behaviour does not expect it. Should be enabled though
// RSA public keys must have a NULL in the parameters
// (https://tools.ietf.org/html/rfc3279#section-2.3.1).
//if !bytes.Equal(keyData.Algorithm.Parameters.FullBytes, asn1.NullBytes) {
// return nil, errors.New("x509: RSA key missing NULL parameters")
//}
p := new(pkcs1PublicKey)
rest, err := asn1.Unmarshal(asn1Data, p)
if err != nil {
return nil, err
}
if len(rest) != 0 {
return nil, errors.New("x509: trailing data after RSA public key")
}
if p.N.Sign() <= 0 {
return nil, errors.New("x509: RSA modulus is not a positive number")
}
if p.E <= 0 {
return nil, errors.New("x509: RSA public exponent is not a positive number")
}
pub := &rsa.PublicKey{
E: p.E,
N: p.N,
}
return pub, nil
case DSA:
var p *big.Int
rest, err := asn1.Unmarshal(asn1Data, &p)
if err != nil {
return nil, err
}
if len(rest) != 0 {
return nil, errors.New("x509: trailing data after DSA public key")
}
paramsData := keyData.Algorithm.Parameters.FullBytes
params := new(dsaAlgorithmParameters)
rest, err = asn1.Unmarshal(paramsData, params)
if err != nil {
return nil, err
}
if len(rest) != 0 {
return nil, errors.New("x509: trailing data after DSA parameters")
}
if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 {
return nil, errors.New("x509: zero or negative DSA parameter")
}
pub := &dsa.PublicKey{
Parameters: dsa.Parameters{
P: params.P,
Q: params.Q,
G: params.G,
},
Y: p,
}
return pub, nil
case ECDSA:
paramsData := keyData.Algorithm.Parameters.FullBytes
namedCurveOID := new(asn1.ObjectIdentifier)
rest, err := asn1.Unmarshal(paramsData, namedCurveOID)
if err != nil {
return nil, err
}
if len(rest) != 0 {
return nil, errors.New("x509: trailing data after ECDSA parameters")
}
namedCurve := namedCurveFromOID(*namedCurveOID)
if namedCurve == nil {
return nil, errors.New("x509: unsupported elliptic curve")
}
x, y := elliptic.Unmarshal(namedCurve, asn1Data)
if x == nil {
return nil, errors.New("x509: failed to unmarshal elliptic curve point")
}
key := &ecdsa.PublicKey{
Curve: namedCurve,
X: x,
Y: y,
}
pub := &AugmentedECDSA{
Pub: key,
Raw: keyData.PublicKey,
}
return pub, nil
case ED25519:
p := ed25519.PublicKey(asn1Data)
if len(p) > ed25519.PublicKeySize {
return nil, errors.New("x509: trailing data after Ed25519 data")
}
return p, nil
case X25519:
p := X25519PublicKey(asn1Data)
if len(p) > 32 {
return nil, errors.New("x509: trailing data after X25519 public key")
}
return p, nil
default:
return nil, nil
}
}
func parseGeneralNames(value []byte) (otherNames []pkix.OtherName, dnsNames, emailAddresses, URIs []string, directoryNames []pkix.Name, ediPartyNames []pkix.EDIPartyName, ipAddresses []net.IP, registeredIDs []asn1.ObjectIdentifier, err error) {
// RFC 5280, 4.2.1.6
// SubjectAltName ::= GeneralNames
//
// GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
//
// GeneralName ::= CHOICE {
// otherName [0] OtherName,
// rfc822Name [1] IA5String,
// dNSName [2] IA5String,
// x400Address [3] ORAddress,
// directoryName [4] Name,
// ediPartyName [5] EDIPartyName,
// uniformResourceIdentifier [6] IA5String,
// iPAddress [7] OCTET STRING,
// registeredID [8] OBJECT IDENTIFIER }
var seq asn1.RawValue
if _, err = asn1.Unmarshal(value, &seq); err != nil {
return
}
if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 {
err = asn1.StructuralError{Msg: "bad SAN sequence"}
return
}
rest := seq.Bytes
for len(rest) > 0 {
var v asn1.RawValue
rest, err = asn1.Unmarshal(rest, &v)
if err != nil {
return
}
switch v.Tag {
case 0:
var oName pkix.OtherName
_, err = asn1.UnmarshalWithParams(v.FullBytes, &oName, "tag:0")
if err != nil {
return
}
otherNames = append(otherNames, oName)
case 1:
emailAddresses = append(emailAddresses, string(v.Bytes))
case 2:
dnsNames = append(dnsNames, string(v.Bytes))
case 4:
var rdn pkix.RDNSequence
_, err = asn1.Unmarshal(v.Bytes, &rdn)
if err != nil {
return
}
var dir pkix.Name
dir.FillFromRDNSequence(&rdn)
directoryNames = append(directoryNames, dir)
case 5:
var ediName pkix.EDIPartyName
_, err = asn1.UnmarshalWithParams(v.FullBytes, &ediName, "tag:5")
if err != nil {
return
}
ediPartyNames = append(ediPartyNames, ediName)
case 6:
URIs = append(URIs, string(v.Bytes))
case 7:
switch len(v.Bytes) {
case net.IPv4len, net.IPv6len:
ipAddresses = append(ipAddresses, v.Bytes)
default:
err = errors.New("x509: certificate contained IP address of length " + strconv.Itoa(len(v.Bytes)))
return
}
case 8:
var id asn1.ObjectIdentifier
_, err = asn1.UnmarshalWithParams(v.FullBytes, &id, "tag:8")
if err != nil {
return
}
registeredIDs = append(registeredIDs, id)
}
}
return
}
//TODO
func parseCertificate(in *certificate) (*Certificate, error) {
out := new(Certificate)
out.Raw = in.Raw
out.RawTBSCertificate = in.TBSCertificate.Raw
out.RawSubjectPublicKeyInfo = in.TBSCertificate.PublicKey.Raw
out.RawSubject = in.TBSCertificate.Subject.FullBytes
out.RawIssuer = in.TBSCertificate.Issuer.FullBytes
// Fingerprints
out.FingerprintMD5 = MD5Fingerprint(in.Raw)
out.FingerprintSHA1 = SHA1Fingerprint(in.Raw)
out.FingerprintSHA256 = SHA256Fingerprint(in.Raw)
out.SPKIFingerprint = SHA256Fingerprint(in.TBSCertificate.PublicKey.Raw)
out.TBSCertificateFingerprint = SHA256Fingerprint(in.TBSCertificate.Raw)
tbs := in.TBSCertificate
originalExtensions := in.TBSCertificate.Extensions
// Blow away the raw data since it also includes CT data
tbs.Raw = nil
// remove the CT extensions
extensions := make([]pkix.Extension, 0, len(originalExtensions))
for _, extension := range originalExtensions {
if extension.Id.Equal(oidExtensionCTPrecertificatePoison) {
continue
}
if extension.Id.Equal(oidExtensionSignedCertificateTimestampList) {
continue
}
extensions = append(extensions, extension)
}
tbs.Extensions = extensions
tbsbytes, err := asn1.Marshal(tbs)
if err != nil {
return nil, err
}
if tbsbytes == nil {
return nil, asn1.SyntaxError{Msg: "Trailing data"}
}
out.FingerprintNoCT = SHA256Fingerprint(tbsbytes[:])
// Hash both SPKI and Subject to create a fingerprint that we can use to describe a CA
hasher := sha256.New()
hasher.Write(in.TBSCertificate.PublicKey.Raw)
hasher.Write(in.TBSCertificate.Subject.FullBytes)
out.SPKISubjectFingerprint = hasher.Sum(nil)
out.Signature = in.SignatureValue.RightAlign()
out.SignatureAlgorithm =
GetSignatureAlgorithmFromAI(in.TBSCertificate.SignatureAlgorithm)
out.SignatureAlgorithmOID = in.TBSCertificate.SignatureAlgorithm.Algorithm
out.PublicKeyAlgorithm =
getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm)
out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCertificate.PublicKey)
if err != nil {
return nil, err
}
out.PublicKeyAlgorithmOID = in.TBSCertificate.PublicKey.Algorithm.Algorithm
out.Version = in.TBSCertificate.Version + 1
out.SerialNumber = in.TBSCertificate.SerialNumber
var issuer, subject pkix.RDNSequence
if _, err := asn1.Unmarshal(in.TBSCertificate.Subject.FullBytes, &subject); err != nil {
return nil, err
}
if _, err := asn1.Unmarshal(in.TBSCertificate.Issuer.FullBytes, &issuer); err != nil {
return nil, err
}
out.Issuer.FillFromRDNSequence(&issuer)
out.Subject.FillFromRDNSequence(&subject)
// Check if self-signed
if bytes.Equal(out.RawSubject, out.RawIssuer) {
// Possibly self-signed, check the signature against itself.
if err := out.CheckSignature(out.SignatureAlgorithm, out.RawTBSCertificate, out.Signature); err == nil {
out.SelfSigned = true
}
}
out.NotBefore = in.TBSCertificate.Validity.NotBefore
out.NotAfter = in.TBSCertificate.Validity.NotAfter
out.ValidityPeriod = int(out.NotAfter.Sub(out.NotBefore).Seconds())
out.IssuerUniqueId = in.TBSCertificate.UniqueId
out.SubjectUniqueId = in.TBSCertificate.SubjectUniqueId
for _, e := range in.TBSCertificate.Extensions {
out.Extensions = append(out.Extensions, e)
if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 {
switch e.Id[3] {
case 15:
// RFC 5280, 4.2.1.3
var usageBits asn1.BitString
_, err := asn1.Unmarshal(e.Value, &usageBits)
if err == nil {
var usage int
for i := 0; i < 9; i++ {
if usageBits.At(i) != 0 {
usage |= 1 << uint(i)
}
}
out.KeyUsage = KeyUsage(usage)
continue
}
case 19:
// RFC 5280, 4.2.1.9
var constraints basicConstraints
_, err := asn1.Unmarshal(e.Value, &constraints)
if err == nil {
out.BasicConstraintsValid = true
out.IsCA = constraints.IsCA
out.MaxPathLen = constraints.MaxPathLen
out.MaxPathLenZero = out.MaxPathLen == 0
continue
}
case 17:
out.OtherNames, out.DNSNames, out.EmailAddresses, out.URIs, out.DirectoryNames, out.EDIPartyNames, out.IPAddresses, out.RegisteredIDs, err = parseGeneralNames(e.Value)
if err != nil {
return nil, err
}
if len(out.DNSNames) > 0 || len(out.EmailAddresses) > 0 || len(out.IPAddresses) > 0 {
continue
}
// If we didn't parse any of the names then we
// fall through to the critical check below.
case 18:
out.IANOtherNames, out.IANDNSNames, out.IANEmailAddresses, out.IANURIs, out.IANDirectoryNames, out.IANEDIPartyNames, out.IANIPAddresses, out.IANRegisteredIDs, err = parseGeneralNames(e.Value)
if err != nil {
return nil, err
}
if len(out.IANDNSNames) > 0 || len(out.IANEmailAddresses) > 0 || len(out.IANIPAddresses) > 0 {
continue
}
case 30:
// RFC 5280, 4.2.1.10
// NameConstraints ::= SEQUENCE {
// permittedSubtrees [0] GeneralSubtrees OPTIONAL,
// excludedSubtrees [1] GeneralSubtrees OPTIONAL }
//
// GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
//
// GeneralSubtree ::= SEQUENCE {
// base GeneralName,
// Min [0] BaseDistance DEFAULT 0,
// Max [1] BaseDistance OPTIONAL }
//
// BaseDistance ::= INTEGER (0..MAX)
var constraints nameConstraints
_, err := asn1.Unmarshal(e.Value, &constraints)
if err != nil {
return nil, err
}
if e.Critical {
out.NameConstraintsCritical = true
}
for _, subtree := range constraints.Permitted {
switch subtree.Value.Tag {
case 1:
out.PermittedEmailAddresses = append(out.PermittedEmailAddresses, GeneralSubtreeString{Data: string(subtree.Value.Bytes), Max: subtree.Max, Min: subtree.Min})
case 2:
out.PermittedDNSNames = append(out.PermittedDNSNames, GeneralSubtreeString{Data: string(subtree.Value.Bytes), Max: subtree.Max, Min: subtree.Min})
case 3:
out.PermittedX400Addresses = append(out.PermittedX400Addresses, GeneralSubtreeRaw{Data: subtree.Value, Max: subtree.Max, Min: subtree.Min})
case 4:
var rawdn pkix.RDNSequence
if _, err := asn1.Unmarshal(subtree.Value.Bytes, &rawdn); err != nil {
return out, err
}
var dn pkix.Name
dn.FillFromRDNSequence(&rawdn)
out.PermittedDirectoryNames = append(out.PermittedDirectoryNames, GeneralSubtreeName{Data: dn, Max: subtree.Max, Min: subtree.Min})
case 5:
var ediName pkix.EDIPartyName
_, err = asn1.UnmarshalWithParams(subtree.Value.FullBytes, &ediName, "tag:5")
if err != nil {
return out, err
}
out.PermittedEdiPartyNames = append(out.PermittedEdiPartyNames, GeneralSubtreeEdi{Data: ediName, Max: subtree.Max, Min: subtree.Min})
case 7:
switch len(subtree.Value.Bytes) {
case net.IPv4len * 2:
ip := net.IPNet{IP: subtree.Value.Bytes[:net.IPv4len], Mask: subtree.Value.Bytes[net.IPv4len:]}
out.PermittedIPAddresses = append(out.PermittedIPAddresses, GeneralSubtreeIP{Data: ip, Max: subtree.Max, Min: subtree.Min})
case net.IPv6len * 2:
ip := net.IPNet{IP: subtree.Value.Bytes[:net.IPv6len], Mask: subtree.Value.Bytes[net.IPv6len:]}
out.PermittedIPAddresses = append(out.PermittedIPAddresses, GeneralSubtreeIP{Data: ip, Max: subtree.Max, Min: subtree.Min})