Debian Codegraph @

internal/x509andr/x509.go

raw symbols SCIP
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package x509 parses X.509-encoded keys and certificates.
6 //
7 // On UNIX systems the environment variables SSL_CERT_FILE and SSL_CERT_DIR
8 // can be used to override the system default locations for the SSL certificate
9 // file and SSL certificate files directory, respectively.
10 package x509andr
11
12 import (
13 "bytes"
14 "crypto"
15 "crypto/dsa"
16 "crypto/ecdsa"
17 "crypto/elliptic"
18 "crypto/rsa"
19 _ "crypto/sha1"
20 _ "crypto/sha256"
21 _ "crypto/sha512"
22 "crypto/x509/pkix"
23 "encoding/asn1"
24 "encoding/pem"
25 "errors"
26 "fmt"
27 "io"
28 "math/big"
29 "net"
30 "strconv"
31 "time"
32 )
33
34 const tagNull = 5
35
36 var (
37 nullBytes = []byte{tagNull, 0}
38 nullRawValue = asn1.RawValue{Tag: tagNull}
39 )
40
41 // pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
42 // in RFC 3280.
43 type pkixPublicKey struct {
44 Algo pkix.AlgorithmIdentifier
45 BitString asn1.BitString
46 }
47
48 // ParsePKIXPublicKey parses a DER encoded public key. These values are
49 // typically found in PEM blocks with "BEGIN PUBLIC KEY".
50 //
51 // Supported key types include RSA, DSA, and ECDSA. Unknown key
52 // types result in an error.
53 //
54 // On success, pub will be of type *rsa.PublicKey, *dsa.PublicKey,
55 // or *ecdsa.PublicKey.
56 func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) {
57 var pki publicKeyInfo
58 if rest, err := asn1.Unmarshal(derBytes, &pki); err != nil {
59 return nil, err
60 } else if len(rest) != 0 {
61 return nil, errors.New("x509: trailing data after ASN.1 of public-key")
62 }
63 algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm)
64 if algo == UnknownPublicKeyAlgorithm {
65 return nil, errors.New("x509: unknown public key algorithm")
66 }
67 return parsePublicKey(algo, &pki)
68 }
69
70 func marshalPublicKey(pub interface{}) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) {
71 switch pub := pub.(type) {
72 case *rsa.PublicKey:
73 publicKeyBytes, err = asn1.Marshal(pkcs1PublicKey{
74 N: pub.N,
75 E: pub.E,
76 })
77 if err != nil {
78 return nil, pkix.AlgorithmIdentifier{}, err
79 }
80 publicKeyAlgorithm.Algorithm = oidPublicKeyRSA
81 // This is a NULL parameters value which is required by
82 // https://tools.ietf.org/html/rfc3279#section-2.3.1.
83 publicKeyAlgorithm.Parameters = nullRawValue
84 case *ecdsa.PublicKey:
85 publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
86 oid, ok := oidFromNamedCurve(pub.Curve)
87 if !ok {
88 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
89 }
90 publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
91 var paramBytes []byte
92 paramBytes, err = asn1.Marshal(oid)
93 if err != nil {
94 return
95 }
96 publicKeyAlgorithm.Parameters.FullBytes = paramBytes
97 default:
98 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: only RSA and ECDSA public keys supported")
99 }
100
101 return publicKeyBytes, publicKeyAlgorithm, nil
102 }
103
104 // MarshalPKIXPublicKey serialises a public key to DER-encoded PKIX format.
105 func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
106 var publicKeyBytes []byte
107 var publicKeyAlgorithm pkix.AlgorithmIdentifier
108 var err error
109
110 if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
111 return nil, err
112 }
113
114 pkix := pkixPublicKey{
115 Algo: publicKeyAlgorithm,
116 BitString: asn1.BitString{
117 Bytes: publicKeyBytes,
118 BitLength: 8 * len(publicKeyBytes),
119 },
120 }
121
122 ret, _ := asn1.Marshal(pkix)
123 return ret, nil
124 }
125
126 // These structures reflect the ASN.1 structure of X.509 certificates.:
127
128 type certificate struct {
129 Raw asn1.RawContent
130 TBSCertificate tbsCertificate
131 SignatureAlgorithm pkix.AlgorithmIdentifier
132 SignatureValue asn1.BitString
133 }
134
135 type tbsCertificate struct {
136 Raw asn1.RawContent
137 Version int `asn1:"optional,explicit,default:0,tag:0"`
138 SerialNumber *big.Int
139 SignatureAlgorithm pkix.AlgorithmIdentifier
140 Issuer asn1.RawValue
141 Validity validity
142 Subject asn1.RawValue
143 PublicKey publicKeyInfo
144 UniqueId asn1.BitString `asn1:"optional,tag:1"`
145 SubjectUniqueId asn1.BitString `asn1:"optional,tag:2"`
146 Extensions []pkix.Extension `asn1:"optional,explicit,tag:3"`
147 }
148
149 type dsaAlgorithmParameters struct {
150 P, Q, G *big.Int
151 }
152
153 type dsaSignature struct {
154 R, S *big.Int
155 }
156
157 type ecdsaSignature dsaSignature
158
159 type validity struct {
160 NotBefore, NotAfter time.Time
161 }
162
163 type publicKeyInfo struct {
164 Raw asn1.RawContent
165 Algorithm pkix.AlgorithmIdentifier
166 PublicKey asn1.BitString
167 }
168
169 // RFC 5280, 4.2.1.1
170 type authKeyId struct {
171 Id []byte `asn1:"optional,tag:0"`
172 }
173
174 type SignatureAlgorithm int
175
176 const (
177 UnknownSignatureAlgorithm SignatureAlgorithm = iota
178 MD2WithRSA
179 MD5WithRSA
180 SHA1WithRSA
181 SHA256WithRSA
182 SHA384WithRSA
183 SHA512WithRSA
184 DSAWithSHA1
185 DSAWithSHA256
186 ECDSAWithSHA1
187 ECDSAWithSHA256
188 ECDSAWithSHA384
189 ECDSAWithSHA512
190 SHA256WithRSAPSS
191 SHA384WithRSAPSS
192 SHA512WithRSAPSS
193 )
194
195 func (algo SignatureAlgorithm) isRSAPSS() bool {
196 switch algo {
197 case SHA256WithRSAPSS, SHA384WithRSAPSS, SHA512WithRSAPSS:
198 return true
199 default:
200 return false
201 }
202 }
203
204 var algoName = [...]string{
205 MD2WithRSA: "MD2-RSA",
206 MD5WithRSA: "MD5-RSA",
207 SHA1WithRSA: "SHA1-RSA",
208 SHA256WithRSA: "SHA256-RSA",
209 SHA384WithRSA: "SHA384-RSA",
210 SHA512WithRSA: "SHA512-RSA",
211 SHA256WithRSAPSS: "SHA256-RSAPSS",
212 SHA384WithRSAPSS: "SHA384-RSAPSS",
213 SHA512WithRSAPSS: "SHA512-RSAPSS",
214 DSAWithSHA1: "DSA-SHA1",
215 DSAWithSHA256: "DSA-SHA256",
216 ECDSAWithSHA1: "ECDSA-SHA1",
217 ECDSAWithSHA256: "ECDSA-SHA256",
218 ECDSAWithSHA384: "ECDSA-SHA384",
219 ECDSAWithSHA512: "ECDSA-SHA512",
220 }
221
222 func (algo SignatureAlgorithm) String() string {
223 if 0 < algo && int(algo) < len(algoName) {
224 return algoName[algo]
225 }
226 return strconv.Itoa(int(algo))
227 }
228
229 type PublicKeyAlgorithm int
230
231 const (
232 UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
233 RSA
234 DSA
235 ECDSA
236 )
237
238 // OIDs for signature algorithms
239 //
240 // pkcs-1 OBJECT IDENTIFIER ::= {
241 // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
242 //
243 //
244 // RFC 3279 2.2.1 RSA Signature Algorithms
245 //
246 // md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 }
247 //
248 // md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }
249 //
250 // sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }
251 //
252 // dsaWithSha1 OBJECT IDENTIFIER ::= {
253 // iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 }
254 //
255 // RFC 3279 2.2.3 ECDSA Signature Algorithm
256 //
257 // ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {
258 // iso(1) member-body(2) us(840) ansi-x962(10045)
259 // signatures(4) ecdsa-with-SHA1(1)}
260 //
261 //
262 // RFC 4055 5 PKCS #1 Version 1.5
263 //
264 // sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
265 //
266 // sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
267 //
268 // sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
269 //
270 //
271 // RFC 5758 3.1 DSA Signature Algorithms
272 //
273 // dsaWithSha256 OBJECT IDENTIFIER ::= {
274 // joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
275 // csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
276 //
277 // RFC 5758 3.2 ECDSA Signature Algorithm
278 //
279 // ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
280 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 }
281 //
282 // ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
283 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 }
284 //
285 // ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
286 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 }
287
288 var (
289 oidSignatureMD2WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2}
290 oidSignatureMD5WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
291 oidSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
292 oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
293 oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
294 oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
295 oidSignatureRSAPSS = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 10}
296 oidSignatureDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
297 oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 2}
298 oidSignatureECDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1}
299 oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2}
300 oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3}
301 oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4}
302
303 oidSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1}
304 oidSHA384 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2}
305 oidSHA512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3}
306
307 oidMGF1 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 8}
308
309 // oidISOSignatureSHA1WithRSA means the same as oidSignatureSHA1WithRSA
310 // but it's specified by ISO. Microsoft's makecert.exe has been known
311 // to produce certificates with this OID.
312 oidISOSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 29}
313 )
314
315 var signatureAlgorithmDetails = []struct {
316 algo SignatureAlgorithm
317 oid asn1.ObjectIdentifier
318 pubKeyAlgo PublicKeyAlgorithm
319 hash crypto.Hash
320 }{
321 {MD2WithRSA, oidSignatureMD2WithRSA, RSA, crypto.Hash(0) /* no value for MD2 */},
322 {MD5WithRSA, oidSignatureMD5WithRSA, RSA, crypto.MD5},
323 {SHA1WithRSA, oidSignatureSHA1WithRSA, RSA, crypto.SHA1},
324 {SHA1WithRSA, oidISOSignatureSHA1WithRSA, RSA, crypto.SHA1},
325 {SHA256WithRSA, oidSignatureSHA256WithRSA, RSA, crypto.SHA256},
326 {SHA384WithRSA, oidSignatureSHA384WithRSA, RSA, crypto.SHA384},
327 {SHA512WithRSA, oidSignatureSHA512WithRSA, RSA, crypto.SHA512},
328 {SHA256WithRSAPSS, oidSignatureRSAPSS, RSA, crypto.SHA256},
329 {SHA384WithRSAPSS, oidSignatureRSAPSS, RSA, crypto.SHA384},
330 {SHA512WithRSAPSS, oidSignatureRSAPSS, RSA, crypto.SHA512},
331 {DSAWithSHA1, oidSignatureDSAWithSHA1, DSA, crypto.SHA1},
332 {DSAWithSHA256, oidSignatureDSAWithSHA256, DSA, crypto.SHA256},
333 {ECDSAWithSHA1, oidSignatureECDSAWithSHA1, ECDSA, crypto.SHA1},
334 {ECDSAWithSHA256, oidSignatureECDSAWithSHA256, ECDSA, crypto.SHA256},
335 {ECDSAWithSHA384, oidSignatureECDSAWithSHA384, ECDSA, crypto.SHA384},
336 {ECDSAWithSHA512, oidSignatureECDSAWithSHA512, ECDSA, crypto.SHA512},
337 }
338
339 // pssParameters reflects the parameters in an AlgorithmIdentifier that
340 // specifies RSA PSS. See https://tools.ietf.org/html/rfc3447#appendix-A.2.3
341 type pssParameters struct {
342 // The following three fields are not marked as
343 // optional because the default values specify SHA-1,
344 // which is no longer suitable for use in signatures.
345 Hash pkix.AlgorithmIdentifier `asn1:"explicit,tag:0"`
346 MGF pkix.AlgorithmIdentifier `asn1:"explicit,tag:1"`
347 SaltLength int `asn1:"explicit,tag:2"`
348 TrailerField int `asn1:"optional,explicit,tag:3,default:1"`
349 }
350
351 // rsaPSSParameters returns an asn1.RawValue suitable for use as the Parameters
352 // in an AlgorithmIdentifier that specifies RSA PSS.
353 func rsaPSSParameters(hashFunc crypto.Hash) asn1.RawValue {
354 var hashOID asn1.ObjectIdentifier
355
356 switch hashFunc {
357 case crypto.SHA256:
358 hashOID = oidSHA256
359 case crypto.SHA384:
360 hashOID = oidSHA384
361 case crypto.SHA512:
362 hashOID = oidSHA512
363 }
364
365 params := pssParameters{
366 Hash: pkix.AlgorithmIdentifier{
367 Algorithm: hashOID,
368 Parameters: nullRawValue,
369 },
370 MGF: pkix.AlgorithmIdentifier{
371 Algorithm: oidMGF1,
372 },
373 SaltLength: hashFunc.Size(),
374 TrailerField: 1,
375 }
376
377 mgf1Params := pkix.AlgorithmIdentifier{
378 Algorithm: hashOID,
379 Parameters: nullRawValue,
380 }
381
382 var err error
383 params.MGF.Parameters.FullBytes, err = asn1.Marshal(mgf1Params)
384 if err != nil {
385 panic(err)
386 }
387
388 serialized, err := asn1.Marshal(params)
389 if err != nil {
390 panic(err)
391 }
392
393 return asn1.RawValue{FullBytes: serialized}
394 }
395
396 func getSignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm {
397 if !ai.Algorithm.Equal(oidSignatureRSAPSS) {
398 for _, details := range signatureAlgorithmDetails {
399 if ai.Algorithm.Equal(details.oid) {
400 return details.algo
401 }
402 }
403 return UnknownSignatureAlgorithm
404 }
405
406 // RSA PSS is special because it encodes important parameters
407 // in the Parameters.
408
409 var params pssParameters
410 if _, err := asn1.Unmarshal(ai.Parameters.FullBytes, &params); err != nil {
411 return UnknownSignatureAlgorithm
412 }
413
414 var mgf1HashFunc pkix.AlgorithmIdentifier
415 if _, err := asn1.Unmarshal(params.MGF.Parameters.FullBytes, &mgf1HashFunc); err != nil {
416 return UnknownSignatureAlgorithm
417 }
418
419 // PSS is greatly overburdened with options. This code forces
420 // them into three buckets by requiring that the MGF1 hash
421 // function always match the message hash function (as
422 // recommended in
423 // https://tools.ietf.org/html/rfc3447#section-8.1), that the
424 // salt length matches the hash length, and that the trailer
425 // field has the default value.
426 if !bytes.Equal(params.Hash.Parameters.FullBytes, nullBytes) ||
427 !params.MGF.Algorithm.Equal(oidMGF1) ||
428 !mgf1HashFunc.Algorithm.Equal(params.Hash.Algorithm) ||
429 !bytes.Equal(mgf1HashFunc.Parameters.FullBytes, nullBytes) ||
430 params.TrailerField != 1 {
431 return UnknownSignatureAlgorithm
432 }
433
434 switch {
435 case params.Hash.Algorithm.Equal(oidSHA256) && params.SaltLength == 32:
436 return SHA256WithRSAPSS
437 case params.Hash.Algorithm.Equal(oidSHA384) && params.SaltLength == 48:
438 return SHA384WithRSAPSS
439 case params.Hash.Algorithm.Equal(oidSHA512) && params.SaltLength == 64:
440 return SHA512WithRSAPSS
441 }
442
443 return UnknownSignatureAlgorithm
444 }
445
446 // RFC 3279, 2.3 Public Key Algorithms
447 //
448 // pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
449 // rsadsi(113549) pkcs(1) 1 }
450 //
451 // rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
452 //
453 // id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
454 // x9-57(10040) x9cm(4) 1 }
455 //
456 // RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters
457 //
458 // id-ecPublicKey OBJECT IDENTIFIER ::= {
459 // iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
460 var (
461 oidPublicKeyRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
462 oidPublicKeyDSA = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
463 oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
464 )
465
466 func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
467 switch {
468 case oid.Equal(oidPublicKeyRSA):
469 return RSA
470 case oid.Equal(oidPublicKeyDSA):
471 return DSA
472 case oid.Equal(oidPublicKeyECDSA):
473 return ECDSA
474 }
475 return UnknownPublicKeyAlgorithm
476 }
477
478 // RFC 5480, 2.1.1.1. Named Curve
479 //
480 // secp224r1 OBJECT IDENTIFIER ::= {
481 // iso(1) identified-organization(3) certicom(132) curve(0) 33 }
482 //
483 // secp256r1 OBJECT IDENTIFIER ::= {
484 // iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
485 // prime(1) 7 }
486 //
487 // secp384r1 OBJECT IDENTIFIER ::= {
488 // iso(1) identified-organization(3) certicom(132) curve(0) 34 }
489 //
490 // secp521r1 OBJECT IDENTIFIER ::= {
491 // iso(1) identified-organization(3) certicom(132) curve(0) 35 }
492 //
493 // NB: secp256r1 is equivalent to prime256v1
494 var (
495 oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
496 oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
497 oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
498 oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
499 )
500
501 func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve {
502 switch {
503 case oid.Equal(oidNamedCurveP224):
504 return elliptic.P224()
505 case oid.Equal(oidNamedCurveP256):
506 return elliptic.P256()
507 case oid.Equal(oidNamedCurveP384):
508 return elliptic.P384()
509 case oid.Equal(oidNamedCurveP521):
510 return elliptic.P521()
511 }
512 return nil
513 }
514
515 func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) {
516 switch curve {
517 case elliptic.P224():
518 return oidNamedCurveP224, true
519 case elliptic.P256():
520 return oidNamedCurveP256, true
521 case elliptic.P384():
522 return oidNamedCurveP384, true
523 case elliptic.P521():
524 return oidNamedCurveP521, true
525 }
526
527 return nil, false
528 }
529
530 // KeyUsage represents the set of actions that are valid for a given key. It's
531 // a bitmap of the KeyUsage* constants.
532 type KeyUsage int
533
534 const (
535 KeyUsageDigitalSignature KeyUsage = 1 << iota
536 KeyUsageContentCommitment
537 KeyUsageKeyEncipherment
538 KeyUsageDataEncipherment
539 KeyUsageKeyAgreement
540 KeyUsageCertSign
541 KeyUsageCRLSign
542 KeyUsageEncipherOnly
543 KeyUsageDecipherOnly
544 )
545
546 // RFC 5280, 4.2.1.12 Extended Key Usage
547 //
548 // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
549 //
550 // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
551 //
552 // id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 }
553 // id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 }
554 // id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 }
555 // id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 }
556 // id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 }
557 // id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 }
558 var (
559 oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
560 oidExtKeyUsageServerAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
561 oidExtKeyUsageClientAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
562 oidExtKeyUsageCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
563 oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
564 oidExtKeyUsageIPSECEndSystem = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
565 oidExtKeyUsageIPSECTunnel = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
566 oidExtKeyUsageIPSECUser = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
567 oidExtKeyUsageTimeStamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
568 oidExtKeyUsageOCSPSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
569 oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
570 oidExtKeyUsageNetscapeServerGatedCrypto = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
571 )
572
573 // ExtKeyUsage represents an extended set of actions that are valid for a given key.
574 // Each of the ExtKeyUsage* constants define a unique action.
575 type ExtKeyUsage int
576
577 const (
578 ExtKeyUsageAny ExtKeyUsage = iota
579 ExtKeyUsageServerAuth
580 ExtKeyUsageClientAuth
581 ExtKeyUsageCodeSigning
582 ExtKeyUsageEmailProtection
583 ExtKeyUsageIPSECEndSystem
584 ExtKeyUsageIPSECTunnel
585 ExtKeyUsageIPSECUser
586 ExtKeyUsageTimeStamping
587 ExtKeyUsageOCSPSigning
588 ExtKeyUsageMicrosoftServerGatedCrypto
589 ExtKeyUsageNetscapeServerGatedCrypto
590 )
591
592 // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
593 var extKeyUsageOIDs = []struct {
594 extKeyUsage ExtKeyUsage
595 oid asn1.ObjectIdentifier
596 }{
597 {ExtKeyUsageAny, oidExtKeyUsageAny},
598 {ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
599 {ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
600 {ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
601 {ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
602 {ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
603 {ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
604 {ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
605 {ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
606 {ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
607 {ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
608 {ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
609 }
610
611 func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) {
612 for _, pair := range extKeyUsageOIDs {
613 if oid.Equal(pair.oid) {
614 return pair.extKeyUsage, true
615 }
616 }
617 return
618 }
619
620 func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
621 for _, pair := range extKeyUsageOIDs {
622 if eku == pair.extKeyUsage {
623 return pair.oid, true
624 }
625 }
626 return
627 }
628
629 // A Certificate represents an X.509 certificate.
630 type Certificate struct {
631 Raw []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
632 RawTBSCertificate []byte // Certificate part of raw ASN.1 DER content.
633 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
634 RawSubject []byte // DER encoded Subject
635 RawIssuer []byte // DER encoded Issuer
636
637 Signature []byte
638 SignatureAlgorithm SignatureAlgorithm
639
640 PublicKeyAlgorithm PublicKeyAlgorithm
641 PublicKey interface{}
642
643 Version int
644 SerialNumber *big.Int
645 Issuer pkix.Name
646 Subject pkix.Name
647 NotBefore, NotAfter time.Time // Validity bounds.
648 KeyUsage KeyUsage
649
650 // Extensions contains raw X.509 extensions. When parsing certificates,
651 // this can be used to extract non-critical extensions that are not
652 // parsed by this package. When marshaling certificates, the Extensions
653 // field is ignored, see ExtraExtensions.
654 Extensions []pkix.Extension
655
656 // ExtraExtensions contains extensions to be copied, raw, into any
657 // marshaled certificates. Values override any extensions that would
658 // otherwise be produced based on the other fields. The ExtraExtensions
659 // field is not populated when parsing certificates, see Extensions.
660 ExtraExtensions []pkix.Extension
661
662 // UnhandledCriticalExtensions contains a list of extension IDs that
663 // were not (fully) processed when parsing. Verify will fail if this
664 // slice is non-empty, unless verification is delegated to an OS
665 // library which understands all the critical extensions.
666 //
667 // Users can access these extensions using Extensions and can remove
668 // elements from this slice if they believe that they have been
669 // handled.
670 UnhandledCriticalExtensions []asn1.ObjectIdentifier
671
672 ExtKeyUsage []ExtKeyUsage // Sequence of extended key usages.
673 UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
674
675 // BasicConstraintsValid indicates whether IsCA, MaxPathLen,
676 // and MaxPathLenZero are valid.
677 BasicConstraintsValid bool
678 IsCA bool
679
680 // MaxPathLen and MaxPathLenZero indicate the presence and
681 // value of the BasicConstraints' "pathLenConstraint".
682 //
683 // When parsing a certificate, a positive non-zero MaxPathLen
684 // means that the field was specified, -1 means it was unset,
685 // and MaxPathLenZero being true mean that the field was
686 // explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false
687 // should be treated equivalent to -1 (unset).
688 //
689 // When generating a certificate, an unset pathLenConstraint
690 // can be requested with either MaxPathLen == -1 or using the
691 // zero value for both MaxPathLen and MaxPathLenZero.
692 MaxPathLen int
693 // MaxPathLenZero indicates that BasicConstraintsValid==true
694 // and MaxPathLen==0 should be interpreted as an actual
695 // maximum path length of zero. Otherwise, that combination is
696 // interpreted as MaxPathLen not being set.
697 MaxPathLenZero bool
698
699 SubjectKeyId []byte
700 AuthorityKeyId []byte
701
702 // RFC 5280, 4.2.2.1 (Authority Information Access)
703 OCSPServer []string
704 IssuingCertificateURL []string
705
706 // Subject Alternate Name values
707 DNSNames []string
708 EmailAddresses []string
709 IPAddresses []net.IP
710
711 // Name constraints
712 PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
713 PermittedDNSDomains []string
714 ExcludedDNSDomains []string
715
716 // CRL Distribution Points
717 CRLDistributionPoints []string
718
719 PolicyIdentifiers []asn1.ObjectIdentifier
720 }
721
722 // ErrUnsupportedAlgorithm results from attempting to perform an operation that
723 // involves algorithms that are not currently implemented.
724 var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
725
726 // An InsecureAlgorithmError
727 type InsecureAlgorithmError SignatureAlgorithm
728
729 func (e InsecureAlgorithmError) Error() string {
730 return fmt.Sprintf("x509: cannot verify signature: insecure algorithm %v", SignatureAlgorithm(e))
731 }
732
733 // ConstraintViolationError results when a requested usage is not permitted by
734 // a certificate. For example: checking a signature when the public key isn't a
735 // certificate signing key.
736 type ConstraintViolationError struct{}
737
738 func (ConstraintViolationError) Error() string {
739 return "x509: invalid signature: parent certificate cannot sign this kind of certificate"
740 }
741
742 func (c *Certificate) Equal(other *Certificate) bool {
743 return bytes.Equal(c.Raw, other.Raw)
744 }
745
746 func (c *Certificate) hasSANExtension() bool {
747 return oidInExtensions(oidExtensionSubjectAltName, c.Extensions)
748 }
749
750 // Entrust have a broken root certificate (CN=Entrust.net Certification
751 // Authority (2048)) which isn't marked as a CA certificate and is thus invalid
752 // according to PKIX.
753 // We recognise this certificate by its SubjectPublicKeyInfo and exempt it
754 // from the Basic Constraints requirement.
755 // See http://www.entrust.net/knowledge-base/technote.cfm?tn=7869
756 //
757 // TODO(agl): remove this hack once their reissued root is sufficiently
758 // widespread.
759 var entrustBrokenSPKI = []byte{
760 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09,
761 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01,
762 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00,
763 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01,
764 0x00, 0x97, 0xa3, 0x2d, 0x3c, 0x9e, 0xde, 0x05,
765 0xda, 0x13, 0xc2, 0x11, 0x8d, 0x9d, 0x8e, 0xe3,
766 0x7f, 0xc7, 0x4b, 0x7e, 0x5a, 0x9f, 0xb3, 0xff,
767 0x62, 0xab, 0x73, 0xc8, 0x28, 0x6b, 0xba, 0x10,
768 0x64, 0x82, 0x87, 0x13, 0xcd, 0x57, 0x18, 0xff,
769 0x28, 0xce, 0xc0, 0xe6, 0x0e, 0x06, 0x91, 0x50,
770 0x29, 0x83, 0xd1, 0xf2, 0xc3, 0x2a, 0xdb, 0xd8,
771 0xdb, 0x4e, 0x04, 0xcc, 0x00, 0xeb, 0x8b, 0xb6,
772 0x96, 0xdc, 0xbc, 0xaa, 0xfa, 0x52, 0x77, 0x04,
773 0xc1, 0xdb, 0x19, 0xe4, 0xae, 0x9c, 0xfd, 0x3c,
774 0x8b, 0x03, 0xef, 0x4d, 0xbc, 0x1a, 0x03, 0x65,
775 0xf9, 0xc1, 0xb1, 0x3f, 0x72, 0x86, 0xf2, 0x38,
776 0xaa, 0x19, 0xae, 0x10, 0x88, 0x78, 0x28, 0xda,
777 0x75, 0xc3, 0x3d, 0x02, 0x82, 0x02, 0x9c, 0xb9,
778 0xc1, 0x65, 0x77, 0x76, 0x24, 0x4c, 0x98, 0xf7,
779 0x6d, 0x31, 0x38, 0xfb, 0xdb, 0xfe, 0xdb, 0x37,
780 0x02, 0x76, 0xa1, 0x18, 0x97, 0xa6, 0xcc, 0xde,
781 0x20, 0x09, 0x49, 0x36, 0x24, 0x69, 0x42, 0xf6,
782 0xe4, 0x37, 0x62, 0xf1, 0x59, 0x6d, 0xa9, 0x3c,
783 0xed, 0x34, 0x9c, 0xa3, 0x8e, 0xdb, 0xdc, 0x3a,
784 0xd7, 0xf7, 0x0a, 0x6f, 0xef, 0x2e, 0xd8, 0xd5,
785 0x93, 0x5a, 0x7a, 0xed, 0x08, 0x49, 0x68, 0xe2,
786 0x41, 0xe3, 0x5a, 0x90, 0xc1, 0x86, 0x55, 0xfc,
787 0x51, 0x43, 0x9d, 0xe0, 0xb2, 0xc4, 0x67, 0xb4,
788 0xcb, 0x32, 0x31, 0x25, 0xf0, 0x54, 0x9f, 0x4b,
789 0xd1, 0x6f, 0xdb, 0xd4, 0xdd, 0xfc, 0xaf, 0x5e,
790 0x6c, 0x78, 0x90, 0x95, 0xde, 0xca, 0x3a, 0x48,
791 0xb9, 0x79, 0x3c, 0x9b, 0x19, 0xd6, 0x75, 0x05,
792 0xa0, 0xf9, 0x88, 0xd7, 0xc1, 0xe8, 0xa5, 0x09,
793 0xe4, 0x1a, 0x15, 0xdc, 0x87, 0x23, 0xaa, 0xb2,
794 0x75, 0x8c, 0x63, 0x25, 0x87, 0xd8, 0xf8, 0x3d,
795 0xa6, 0xc2, 0xcc, 0x66, 0xff, 0xa5, 0x66, 0x68,
796 0x55, 0x02, 0x03, 0x01, 0x00, 0x01,
797 }
798
799 // CheckSignatureFrom verifies that the signature on c is a valid signature
800 // from parent.
801 func (c *Certificate) CheckSignatureFrom(parent *Certificate) error {
802 // RFC 5280, 4.2.1.9:
803 // "If the basic constraints extension is not present in a version 3
804 // certificate, or the extension is present but the cA boolean is not
805 // asserted, then the certified public key MUST NOT be used to verify
806 // certificate signatures."
807 // (except for Entrust, see comment above entrustBrokenSPKI)
808 if (parent.Version == 3 && !parent.BasicConstraintsValid ||
809 parent.BasicConstraintsValid && !parent.IsCA) &&
810 !bytes.Equal(c.RawSubjectPublicKeyInfo, entrustBrokenSPKI) {
811 return ConstraintViolationError{}
812 }
813
814 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
815 return ConstraintViolationError{}
816 }
817
818 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
819 return ErrUnsupportedAlgorithm
820 }
821
822 // TODO(agl): don't ignore the path length constraint.
823
824 return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature)
825 }
826
827 // CheckSignature verifies that signature is a valid signature over signed from
828 // c's public key.
829 func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error {
830 return checkSignature(algo, signed, signature, c.PublicKey)
831 }
832
833 // CheckSignature verifies that signature is a valid signature over signed from
834 // a crypto.PublicKey.
835 func checkSignature(algo SignatureAlgorithm, signed, signature []byte, publicKey crypto.PublicKey) (err error) {
836 var hashType crypto.Hash
837
838 switch algo {
839 case SHA1WithRSA, DSAWithSHA1, ECDSAWithSHA1:
840 hashType = crypto.SHA1
841 case SHA256WithRSA, SHA256WithRSAPSS, DSAWithSHA256, ECDSAWithSHA256:
842 hashType = crypto.SHA256
843 case SHA384WithRSA, SHA384WithRSAPSS, ECDSAWithSHA384:
844 hashType = crypto.SHA384
845 case SHA512WithRSA, SHA512WithRSAPSS, ECDSAWithSHA512:
846 hashType = crypto.SHA512
847 case MD2WithRSA, MD5WithRSA:
848 return InsecureAlgorithmError(algo)
849 default:
850 return ErrUnsupportedAlgorithm
851 }
852
853 if !hashType.Available() {
854 return ErrUnsupportedAlgorithm
855 }
856 h := hashType.New()
857
858 h.Write(signed)
859 digest := h.Sum(nil)
860
861 switch pub := publicKey.(type) {
862 case *rsa.PublicKey:
863 if algo.isRSAPSS() {
864 return rsa.VerifyPSS(pub, hashType, digest, signature, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
865 } else {
866 return rsa.VerifyPKCS1v15(pub, hashType, digest, signature)
867 }
868 case *dsa.PublicKey:
869 dsaSig := new(dsaSignature)
870 if rest, err := asn1.Unmarshal(signature, dsaSig); err != nil {
871 return err
872 } else if len(rest) != 0 {
873 return errors.New("x509: trailing data after DSA signature")
874 }
875 if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 {
876 return errors.New("x509: DSA signature contained zero or negative values")
877 }
878 if !dsa.Verify(pub, digest, dsaSig.R, dsaSig.S) {
879 return errors.New("x509: DSA verification failure")
880 }
881 return
882 case *ecdsa.PublicKey:
883 ecdsaSig := new(ecdsaSignature)
884 if rest, err := asn1.Unmarshal(signature, ecdsaSig); err != nil {
885 return err
886 } else if len(rest) != 0 {
887 return errors.New("x509: trailing data after ECDSA signature")
888 }
889 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
890 return errors.New("x509: ECDSA signature contained zero or negative values")
891 }
892 if !ecdsa.Verify(pub, digest, ecdsaSig.R, ecdsaSig.S) {
893 return errors.New("x509: ECDSA verification failure")
894 }
895 return
896 }
897 return ErrUnsupportedAlgorithm
898 }
899
900 // CheckCRLSignature checks that the signature in crl is from c.
901 func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error {
902 algo := getSignatureAlgorithmFromAI(crl.SignatureAlgorithm)
903 return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
904 }
905
906 type UnhandledCriticalExtension struct{}
907
908 func (h UnhandledCriticalExtension) Error() string {
909 return "x509: unhandled critical extension"
910 }
911
912 type basicConstraints struct {
913 IsCA bool `asn1:"optional"`
914 MaxPathLen int `asn1:"optional,default:-1"`
915 }
916
917 // RFC 5280 4.2.1.4
918 type policyInformation struct {
919 Policy asn1.ObjectIdentifier
920 // policyQualifiers omitted
921 }
922
923 // RFC 5280, 4.2.1.10
924 type nameConstraints struct {
925 Permitted []generalSubtree `asn1:"optional,tag:0"`
926 Excluded []generalSubtree `asn1:"optional,tag:1"`
927 }
928
929 type generalSubtree struct {
930 Name string `asn1:"tag:2,optional,ia5"`
931 }
932
933 // RFC 5280, 4.2.2.1
934 type authorityInfoAccess struct {
935 Method asn1.ObjectIdentifier
936 Location asn1.RawValue
937 }
938
939 // RFC 5280, 4.2.1.14
940 type distributionPoint struct {
941 DistributionPoint distributionPointName `asn1:"optional,tag:0"`
942 Reason asn1.BitString `asn1:"optional,tag:1"`
943 CRLIssuer asn1.RawValue `asn1:"optional,tag:2"`
944 }
945
946 type distributionPointName struct {
947 FullName asn1.RawValue `asn1:"optional,tag:0"`
948 RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
949 }
950
951 func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (interface{}, error) {
952 asn1Data := keyData.PublicKey.RightAlign()
953 switch algo {
954 case RSA:
955 // CHADRON: Android does not care, ignore.
956 // Sample: fcfbe912bc70e9c996c82cc25194908055734f7db4e81fd948fb7deb8bc7450f
957 //
958 // RSA public keys must have a NULL in the parameters
959 // (https://tools.ietf.org/html/rfc3279#section-2.3.1).
960 //if !bytes.Equal(keyData.Algorithm.Parameters.FullBytes, nullBytes) {
961 // return nil, errors.New("x509: RSA key missing NULL parameters")
962 //}
963
964 p := new(pkcs1PublicKey)
965 rest, err := asn1.Unmarshal(asn1Data, p)
966 if err != nil {
967 return nil, err
968 }
969 if len(rest) != 0 {
970 return nil, errors.New("x509: trailing data after RSA public key")
971 }
972
973 if p.N.Sign() <= 0 {
974 return nil, errors.New("x509: RSA modulus is not a positive number")
975 }
976 if p.E <= 0 {
977 return nil, errors.New("x509: RSA public exponent is not a positive number")
978 }
979
980 pub := &rsa.PublicKey{
981 E: p.E,
982 N: p.N,
983 }
984 return pub, nil
985 case DSA:
986 var p *big.Int
987 rest, err := asn1.Unmarshal(asn1Data, &p)
988 if err != nil {
989 return nil, err
990 }
991 if len(rest) != 0 {
992 return nil, errors.New("x509: trailing data after DSA public key")
993 }
994 paramsData := keyData.Algorithm.Parameters.FullBytes
995 params := new(dsaAlgorithmParameters)
996 rest, err = asn1.Unmarshal(paramsData, params)
997 if err != nil {
998 return nil, err
999 }
1000 if len(rest) != 0 {
1001 return nil, errors.New("x509: trailing data after DSA parameters")
1002 }
1003 if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 {
1004 return nil, errors.New("x509: zero or negative DSA parameter")
1005 }
1006 pub := &dsa.PublicKey{
1007 Parameters: dsa.Parameters{
1008 P: params.P,
1009 Q: params.Q,
1010 G: params.G,
1011 },
1012 Y: p,
1013 }
1014 return pub, nil
1015 case ECDSA:
1016 paramsData := keyData.Algorithm.Parameters.FullBytes
1017 namedCurveOID := new(asn1.ObjectIdentifier)
1018 rest, err := asn1.Unmarshal(paramsData, namedCurveOID)
1019 if err != nil {
1020 return nil, err
1021 }
1022 if len(rest) != 0 {
1023 return nil, errors.New("x509: trailing data after ECDSA parameters")
1024 }
1025 namedCurve := namedCurveFromOID(*namedCurveOID)
1026 if namedCurve == nil {
1027 return nil, errors.New("x509: unsupported elliptic curve")
1028 }
1029 x, y := elliptic.Unmarshal(namedCurve, asn1Data)
1030 if x == nil {
1031 return nil, errors.New("x509: failed to unmarshal elliptic curve point")
1032 }
1033 pub := &ecdsa.PublicKey{
1034 Curve: namedCurve,
1035 X: x,
1036 Y: y,
1037 }
1038 return pub, nil
1039 default:
1040 return nil, nil
1041 }
1042 }
1043
1044 func parseSANExtension(value []byte) (dnsNames, emailAddresses []string, ipAddresses []net.IP, err error) {
1045 // RFC 5280, 4.2.1.6
1046
1047 // SubjectAltName ::= GeneralNames
1048 //
1049 // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
1050 //
1051 // GeneralName ::= CHOICE {
1052 // otherName [0] OtherName,
1053 // rfc822Name [1] IA5String,
1054 // dNSName [2] IA5String,
1055 // x400Address [3] ORAddress,
1056 // directoryName [4] Name,
1057 // ediPartyName [5] EDIPartyName,
1058 // uniformResourceIdentifier [6] IA5String,
1059 // iPAddress [7] OCTET STRING,
1060 // registeredID [8] OBJECT IDENTIFIER }
1061 var seq asn1.RawValue
1062 var rest []byte
1063 if rest, err = asn1.Unmarshal(value, &seq); err != nil {
1064 return
1065 } else if len(rest) != 0 {
1066 err = errors.New("x509: trailing data after X.509 extension")
1067 return
1068 }
1069 if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 {
1070 err = asn1.StructuralError{Msg: "bad SAN sequence"}
1071 return
1072 }
1073
1074 rest = seq.Bytes
1075 for len(rest) > 0 {
1076 var v asn1.RawValue
1077 rest, err = asn1.Unmarshal(rest, &v)
1078 if err != nil {
1079 return
1080 }
1081 switch v.Tag {
1082 case 1:
1083 emailAddresses = append(emailAddresses, string(v.Bytes))
1084 case 2:
1085 dnsNames = append(dnsNames, string(v.Bytes))
1086 case 7:
1087 switch len(v.Bytes) {
1088 case net.IPv4len, net.IPv6len:
1089 ipAddresses = append(ipAddresses, v.Bytes)
1090 default:
1091 err = errors.New("x509: certificate contained IP address of length " + strconv.Itoa(len(v.Bytes)))
1092 return
1093 }
1094 }
1095 }
1096
1097 return
1098 }
1099
1100 func parseCertificate(in *certificate) (*Certificate, error) {
1101 out := new(Certificate)
1102 out.Raw = in.Raw
1103 out.RawTBSCertificate = in.TBSCertificate.Raw
1104 out.RawSubjectPublicKeyInfo = in.TBSCertificate.PublicKey.Raw
1105 out.RawSubject = in.TBSCertificate.Subject.FullBytes
1106 out.RawIssuer = in.TBSCertificate.Issuer.FullBytes
1107
1108 out.Signature = in.SignatureValue.RightAlign()
1109 out.SignatureAlgorithm =
1110 getSignatureAlgorithmFromAI(in.TBSCertificate.SignatureAlgorithm)
1111
1112 out.PublicKeyAlgorithm =
1113 getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm)
1114 var err error
1115 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCertificate.PublicKey)
1116 if err != nil {
1117 return nil, err
1118 }
1119
1120 out.Version = in.TBSCertificate.Version + 1
1121 out.SerialNumber = in.TBSCertificate.SerialNumber
1122
1123 var issuer, subject pkix.RDNSequence
1124 if rest, err := asn1.Unmarshal(in.TBSCertificate.Subject.FullBytes, &subject); err != nil {
1125 return nil, err
1126 } else if len(rest) != 0 {
1127 return nil, errors.New("x509: trailing data after X.509 subject")
1128 }
1129 if rest, err := asn1.Unmarshal(in.TBSCertificate.Issuer.FullBytes, &issuer); err != nil {
1130 return nil, err
1131 } else if len(rest) != 0 {
1132 return nil, errors.New("x509: trailing data after X.509 subject")
1133 }
1134
1135 out.Issuer.FillFromRDNSequence(&issuer)
1136 out.Subject.FillFromRDNSequence(&subject)
1137
1138 out.NotBefore = in.TBSCertificate.Validity.NotBefore
1139 out.NotAfter = in.TBSCertificate.Validity.NotAfter
1140
1141 for _, e := range in.TBSCertificate.Extensions {
1142 out.Extensions = append(out.Extensions, e)
1143 unhandled := false
1144
1145 if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 {
1146 switch e.Id[3] {
1147 case 15:
1148 // RFC 5280, 4.2.1.3
1149 var usageBits asn1.BitString
1150 if rest, err := asn1.Unmarshal(e.Value, &usageBits); err != nil {
1151 return nil, err
1152 } else if len(rest) != 0 {
1153 return nil, errors.New("x509: trailing data after X.509 KeyUsage")
1154 }
1155
1156 var usage int
1157 for i := 0; i < 9; i++ {
1158 if usageBits.At(i) != 0 {
1159 usage |= 1 << uint(i)
1160 }
1161 }
1162 out.KeyUsage = KeyUsage(usage)
1163
1164 case 19:
1165 // RFC 5280, 4.2.1.9
1166 var constraints basicConstraints
1167 if rest, err := asn1.Unmarshal(e.Value, &constraints); err != nil {
1168 return nil, err
1169 } else if len(rest) != 0 {
1170 return nil, errors.New("x509: trailing data after X.509 BasicConstraints")
1171 }
1172
1173 out.BasicConstraintsValid = true
1174 out.IsCA = constraints.IsCA
1175 out.MaxPathLen = constraints.MaxPathLen
1176 out.MaxPathLenZero = out.MaxPathLen == 0
1177 // TODO: map out.MaxPathLen to 0 if it has the -1 default value? (Issue 19285)
1178 case 17:
1179 out.DNSNames, out.EmailAddresses, out.IPAddresses, err = parseSANExtension(e.Value)
1180 if err != nil {
1181 return nil, err
1182 }
1183
1184 if len(out.DNSNames) == 0 && len(out.EmailAddresses) == 0 && len(out.IPAddresses) == 0 {
1185 // If we didn't parse anything then we do the critical check, below.
1186 unhandled = true
1187 }
1188
1189 case 30:
1190 // RFC 5280, 4.2.1.10
1191
1192 // NameConstraints ::= SEQUENCE {
1193 // permittedSubtrees [0] GeneralSubtrees OPTIONAL,
1194 // excludedSubtrees [1] GeneralSubtrees OPTIONAL }
1195 //
1196 // GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
1197 //
1198 // GeneralSubtree ::= SEQUENCE {
1199 // base GeneralName,
1200 // minimum [0] BaseDistance DEFAULT 0,
1201 // maximum [1] BaseDistance OPTIONAL }
1202 //
1203 // BaseDistance ::= INTEGER (0..MAX)
1204
1205 var constraints nameConstraints
1206 if rest, err := asn1.Unmarshal(e.Value, &constraints); err != nil {
1207 return nil, err
1208 } else if len(rest) != 0 {
1209 return nil, errors.New("x509: trailing data after X.509 NameConstraints")
1210 }
1211
1212 getDNSNames := func(subtrees []generalSubtree, isCritical bool) (dnsNames []string, err error) {
1213 for _, subtree := range subtrees {
1214 if len(subtree.Name) == 0 {
1215 if isCritical {
1216 return nil, UnhandledCriticalExtension{}
1217 }
1218 continue
1219 }
1220 dnsNames = append(dnsNames, subtree.Name)
1221 }
1222
1223 return dnsNames, nil
1224 }
1225
1226 if out.PermittedDNSDomains, err = getDNSNames(constraints.Permitted, e.Critical); err != nil {
1227 return out, err
1228 }
1229 if out.ExcludedDNSDomains, err = getDNSNames(constraints.Excluded, e.Critical); err != nil {
1230 return out, err
1231 }
1232 out.PermittedDNSDomainsCritical = e.Critical
1233
1234 case 31:
1235 // RFC 5280, 4.2.1.13
1236
1237 // CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
1238 //
1239 // DistributionPoint ::= SEQUENCE {
1240 // distributionPoint [0] DistributionPointName OPTIONAL,
1241 // reasons [1] ReasonFlags OPTIONAL,
1242 // cRLIssuer [2] GeneralNames OPTIONAL }
1243 //
1244 // DistributionPointName ::= CHOICE {
1245 // fullName [0] GeneralNames,
1246 // nameRelativeToCRLIssuer [1] RelativeDistinguishedName }
1247
1248 var cdp []distributionPoint
1249 if rest, err := asn1.Unmarshal(e.Value, &cdp); err != nil {
1250 return nil, err
1251 } else if len(rest) != 0 {
1252 return nil, errors.New("x509: trailing data after X.509 CRL distribution point")
1253 }
1254
1255 for _, dp := range cdp {
1256 // Per RFC 5280, 4.2.1.13, one of distributionPoint or cRLIssuer may be empty.
1257 if len(dp.DistributionPoint.FullName.Bytes) == 0 {
1258 continue
1259 }
1260
1261 var n asn1.RawValue
1262 if _, err := asn1.Unmarshal(dp.DistributionPoint.FullName.Bytes, &n); err != nil {
1263 return nil, err
1264 }
1265 // Trailing data after the fullName is
1266 // allowed because other elements of
1267 // the SEQUENCE can appear.
1268
1269 if n.Tag == 6 {
1270 out.CRLDistributionPoints = append(out.CRLDistributionPoints, string(n.Bytes))
1271 }
1272 }
1273
1274 case 35:
1275 // RFC 5280, 4.2.1.1
1276 var a authKeyId
1277 if rest, err := asn1.Unmarshal(e.Value, &a); err != nil {
1278 return nil, err
1279 } else if len(rest) != 0 {
1280 return nil, errors.New("x509: trailing data after X.509 authority key-id")
1281 }
1282 out.AuthorityKeyId = a.Id
1283
1284 case 37:
1285 // RFC 5280, 4.2.1.12. Extended Key Usage
1286
1287 // id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 }
1288 //
1289 // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
1290 //
1291 // KeyPurposeId ::= OBJECT IDENTIFIER
1292
1293 var keyUsage []asn1.ObjectIdentifier
1294 if rest, err := asn1.Unmarshal(e.Value, &keyUsage); err != nil {
1295 return nil, err
1296 } else if len(rest) != 0 {
1297 return nil, errors.New("x509: trailing data after X.509 ExtendedKeyUsage")
1298 }
1299
1300 for _, u := range keyUsage {
1301 if extKeyUsage, ok := extKeyUsageFromOID(u); ok {
1302 out.ExtKeyUsage = append(out.ExtKeyUsage, extKeyUsage)
1303 } else {
1304 out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u)
1305 }
1306 }
1307
1308 case 14:
1309 // RFC 5280, 4.2.1.2
1310 var keyid []byte
1311 if rest, err := asn1.Unmarshal(e.Value, &keyid); err != nil {
1312 return nil, err
1313 } else if len(rest) != 0 {
1314 return nil, errors.New("x509: trailing data after X.509 key-id")
1315 }
1316 out.SubjectKeyId = keyid
1317
1318 case 32:
1319 // RFC 5280 4.2.1.4: Certificate Policies
1320 var policies []policyInformation
1321 if rest, err := asn1.Unmarshal(e.Value, &policies); err != nil {
1322 return nil, err
1323 } else if len(rest) != 0 {
1324 return nil, errors.New("x509: trailing data after X.509 certificate policies")
1325 }
1326 out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies))
1327 for i, policy := range policies {
1328 out.PolicyIdentifiers[i] = policy.Policy
1329 }
1330
1331 default:
1332 // Unknown extensions are recorded if critical.
1333 unhandled = true
1334 }
1335 } else if e.Id.Equal(oidExtensionAuthorityInfoAccess) {
1336 // RFC 5280 4.2.2.1: Authority Information Access
1337 var aia []authorityInfoAccess
1338 if rest, err := asn1.Unmarshal(e.Value, &aia); err != nil {
1339 return nil, err
1340 } else if len(rest) != 0 {
1341 return nil, errors.New("x509: trailing data after X.509 authority information")
1342 }
1343
1344 for _, v := range aia {
1345 // GeneralName: uniformResourceIdentifier [6] IA5String
1346 if v.Location.Tag != 6 {
1347 continue
1348 }
1349 if v.Method.Equal(oidAuthorityInfoAccessOcsp) {
1350 out.OCSPServer = append(out.OCSPServer, string(v.Location.Bytes))
1351 } else if v.Method.Equal(oidAuthorityInfoAccessIssuers) {
1352 out.IssuingCertificateURL = append(out.IssuingCertificateURL, string(v.Location.Bytes))
1353 }
1354 }
1355 } else {
1356 // Unknown extensions are recorded if critical.
1357 unhandled = true
1358 }
1359
1360 if e.Critical && unhandled {
1361 out.UnhandledCriticalExtensions = append(out.UnhandledCriticalExtensions, e.Id)
1362 }
1363 }
1364
1365 return out, nil
1366 }
1367
1368 // ParseCertificate parses a single certificate from the given ASN.1 DER data.
1369 func ParseCertificate(asn1Data []byte) (*Certificate, error) {
1370 var cert certificate
1371 rest, err := asn1.Unmarshal(asn1Data, &cert)
1372 if err != nil {
1373 return nil, err
1374 }
1375 if len(rest) > 0 {
1376 return nil, asn1.SyntaxError{Msg: "trailing data"}
1377 }
1378
1379 return parseCertificate(&cert)
1380 }
1381
1382 // ParseCertificates parses one or more certificates from the given ASN.1 DER
1383 // data. The certificates must be concatenated with no intermediate padding.
1384 func ParseCertificates(asn1Data []byte) ([]*Certificate, error) {
1385 var v []*certificate
1386
1387 for len(asn1Data) > 0 {
1388 cert := new(certificate)
1389 var err error
1390 asn1Data, err = asn1.Unmarshal(asn1Data, cert)
1391 if err != nil {
1392 return nil, err
1393 }
1394 v = append(v, cert)
1395 }
1396
1397 ret := make([]*Certificate, len(v))
1398 for i, ci := range v {
1399 cert, err := parseCertificate(ci)
1400 if err != nil {
1401 return nil, err
1402 }
1403 ret[i] = cert
1404 }
1405
1406 return ret, nil
1407 }
1408
1409 func reverseBitsInAByte(in byte) byte {
1410 b1 := in>>4 | in<<4
1411 b2 := b1>>2&0x33 | b1<<2&0xcc
1412 b3 := b2>>1&0x55 | b2<<1&0xaa
1413 return b3
1414 }
1415
1416 // asn1BitLength returns the bit-length of bitString by considering the
1417 // most-significant bit in a byte to be the "first" bit. This convention
1418 // matches ASN.1, but differs from almost everything else.
1419 func asn1BitLength(bitString []byte) int {
1420 bitLen := len(bitString) * 8
1421
1422 for i := range bitString {
1423 b := bitString[len(bitString)-i-1]
1424
1425 for bit := uint(0); bit < 8; bit++ {
1426 if (b>>bit)&1 == 1 {
1427 return bitLen
1428 }
1429 bitLen--
1430 }
1431 }
1432
1433 return 0
1434 }
1435
1436 var (
1437 oidExtensionSubjectKeyId = []int{2, 5, 29, 14}
1438 oidExtensionKeyUsage = []int{2, 5, 29, 15}
1439 oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37}
1440 oidExtensionAuthorityKeyId = []int{2, 5, 29, 35}
1441 oidExtensionBasicConstraints = []int{2, 5, 29, 19}
1442 oidExtensionSubjectAltName = []int{2, 5, 29, 17}
1443 oidExtensionCertificatePolicies = []int{2, 5, 29, 32}
1444 oidExtensionNameConstraints = []int{2, 5, 29, 30}
1445 oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31}
1446 oidExtensionAuthorityInfoAccess = []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
1447 )
1448
1449 var (
1450 oidAuthorityInfoAccessOcsp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
1451 oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}
1452 )
1453
1454 // oidNotInExtensions returns whether an extension with the given oid exists in
1455 // extensions.
1456 func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {
1457 for _, e := range extensions {
1458 if e.Id.Equal(oid) {
1459 return true
1460 }
1461 }
1462 return false
1463 }
1464
1465 // marshalSANs marshals a list of addresses into a the contents of an X.509
1466 // SubjectAlternativeName extension.
1467 func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP) (derBytes []byte, err error) {
1468 var rawValues []asn1.RawValue
1469 for _, name := range dnsNames {
1470 rawValues = append(rawValues, asn1.RawValue{Tag: 2, Class: 2, Bytes: []byte(name)})
1471 }
1472 for _, email := range emailAddresses {
1473 rawValues = append(rawValues, asn1.RawValue{Tag: 1, Class: 2, Bytes: []byte(email)})
1474 }
1475 for _, rawIP := range ipAddresses {
1476 // If possible, we always want to encode IPv4 addresses in 4 bytes.
1477 ip := rawIP.To4()
1478 if ip == nil {
1479 ip = rawIP
1480 }
1481 rawValues = append(rawValues, asn1.RawValue{Tag: 7, Class: 2, Bytes: ip})
1482 }
1483 return asn1.Marshal(rawValues)
1484 }
1485
1486 func buildExtensions(template *Certificate, authorityKeyId []byte) (ret []pkix.Extension, err error) {
1487 ret = make([]pkix.Extension, 10 /* maximum number of elements. */)
1488 n := 0
1489
1490 if template.KeyUsage != 0 &&
1491 !oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) {
1492 ret[n].Id = oidExtensionKeyUsage
1493 ret[n].Critical = true
1494
1495 var a [2]byte
1496 a[0] = reverseBitsInAByte(byte(template.KeyUsage))
1497 a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8))
1498
1499 l := 1
1500 if a[1] != 0 {
1501 l = 2
1502 }
1503
1504 bitString := a[:l]
1505 ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)})
1506 if err != nil {
1507 return
1508 }
1509 n++
1510 }
1511
1512 if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) &&
1513 !oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) {
1514 ret[n].Id = oidExtensionExtendedKeyUsage
1515
1516 var oids []asn1.ObjectIdentifier
1517 for _, u := range template.ExtKeyUsage {
1518 if oid, ok := oidFromExtKeyUsage(u); ok {
1519 oids = append(oids, oid)
1520 } else {
1521 panic("internal error")
1522 }
1523 }
1524
1525 oids = append(oids, template.UnknownExtKeyUsage...)
1526
1527 ret[n].Value, err = asn1.Marshal(oids)
1528 if err != nil {
1529 return
1530 }
1531 n++
1532 }
1533
1534 if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) {
1535 // Leaving MaxPathLen as zero indicates that no maximum path
1536 // length is desired, unless MaxPathLenZero is set. A value of
1537 // -1 causes encoding/asn1 to omit the value as desired.
1538 maxPathLen := template.MaxPathLen
1539 if maxPathLen == 0 && !template.MaxPathLenZero {
1540 maxPathLen = -1
1541 }
1542 ret[n].Id = oidExtensionBasicConstraints
1543 ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, maxPathLen})
1544 ret[n].Critical = true
1545 if err != nil {
1546 return
1547 }
1548 n++
1549 }
1550
1551 if len(template.SubjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) {
1552 ret[n].Id = oidExtensionSubjectKeyId
1553 ret[n].Value, err = asn1.Marshal(template.SubjectKeyId)
1554 if err != nil {
1555 return
1556 }
1557 n++
1558 }
1559
1560 if len(authorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) {
1561 ret[n].Id = oidExtensionAuthorityKeyId
1562 ret[n].Value, err = asn1.Marshal(authKeyId{authorityKeyId})
1563 if err != nil {
1564 return
1565 }
1566 n++
1567 }
1568
1569 if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) &&
1570 !oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) {
1571 ret[n].Id = oidExtensionAuthorityInfoAccess
1572 var aiaValues []authorityInfoAccess
1573 for _, name := range template.OCSPServer {
1574 aiaValues = append(aiaValues, authorityInfoAccess{
1575 Method: oidAuthorityInfoAccessOcsp,
1576 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1577 })
1578 }
1579 for _, name := range template.IssuingCertificateURL {
1580 aiaValues = append(aiaValues, authorityInfoAccess{
1581 Method: oidAuthorityInfoAccessIssuers,
1582 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1583 })
1584 }
1585 ret[n].Value, err = asn1.Marshal(aiaValues)
1586 if err != nil {
1587 return
1588 }
1589 n++
1590 }
1591
1592 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0) &&
1593 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
1594 ret[n].Id = oidExtensionSubjectAltName
1595 ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses)
1596 if err != nil {
1597 return
1598 }
1599 n++
1600 }
1601
1602 if len(template.PolicyIdentifiers) > 0 &&
1603 !oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) {
1604 ret[n].Id = oidExtensionCertificatePolicies
1605 policies := make([]policyInformation, len(template.PolicyIdentifiers))
1606 for i, policy := range template.PolicyIdentifiers {
1607 policies[i].Policy = policy
1608 }
1609 ret[n].Value, err = asn1.Marshal(policies)
1610 if err != nil {
1611 return
1612 }
1613 n++
1614 }
1615
1616 if (len(template.PermittedDNSDomains) > 0 || len(template.ExcludedDNSDomains) > 0) &&
1617 !oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) {
1618 ret[n].Id = oidExtensionNameConstraints
1619 ret[n].Critical = template.PermittedDNSDomainsCritical
1620
1621 var out nameConstraints
1622
1623 out.Permitted = make([]generalSubtree, len(template.PermittedDNSDomains))
1624 for i, permitted := range template.PermittedDNSDomains {
1625 out.Permitted[i] = generalSubtree{Name: permitted}
1626 }
1627 out.Excluded = make([]generalSubtree, len(template.ExcludedDNSDomains))
1628 for i, excluded := range template.ExcludedDNSDomains {
1629 out.Excluded[i] = generalSubtree{Name: excluded}
1630 }
1631
1632 ret[n].Value, err = asn1.Marshal(out)
1633 if err != nil {
1634 return
1635 }
1636 n++
1637 }
1638
1639 if len(template.CRLDistributionPoints) > 0 &&
1640 !oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) {
1641 ret[n].Id = oidExtensionCRLDistributionPoints
1642
1643 var crlDp []distributionPoint
1644 for _, name := range template.CRLDistributionPoints {
1645 rawFullName, _ := asn1.Marshal(asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)})
1646
1647 dp := distributionPoint{
1648 DistributionPoint: distributionPointName{
1649 FullName: asn1.RawValue{Tag: 0, Class: 2, IsCompound: true, Bytes: rawFullName},
1650 },
1651 }
1652 crlDp = append(crlDp, dp)
1653 }
1654
1655 ret[n].Value, err = asn1.Marshal(crlDp)
1656 if err != nil {
1657 return
1658 }
1659 n++
1660 }
1661
1662 // Adding another extension here? Remember to update the maximum number
1663 // of elements in the make() at the top of the function.
1664
1665 return append(ret[:n], template.ExtraExtensions...), nil
1666 }
1667
1668 func subjectBytes(cert *Certificate) ([]byte, error) {
1669 if len(cert.RawSubject) > 0 {
1670 return cert.RawSubject, nil
1671 }
1672
1673 return asn1.Marshal(cert.Subject.ToRDNSequence())
1674 }
1675
1676 // signingParamsForPublicKey returns the parameters to use for signing with
1677 // priv. If requestedSigAlgo is not zero then it overrides the default
1678 // signature algorithm.
1679 func signingParamsForPublicKey(pub interface{}, requestedSigAlgo SignatureAlgorithm) (hashFunc crypto.Hash, sigAlgo pkix.AlgorithmIdentifier, err error) {
1680 var pubType PublicKeyAlgorithm
1681
1682 switch pub := pub.(type) {
1683 case *rsa.PublicKey:
1684 pubType = RSA
1685 hashFunc = crypto.SHA256
1686 sigAlgo.Algorithm = oidSignatureSHA256WithRSA
1687 sigAlgo.Parameters = nullRawValue
1688
1689 case *ecdsa.PublicKey:
1690 pubType = ECDSA
1691
1692 switch pub.Curve {
1693 case elliptic.P224(), elliptic.P256():
1694 hashFunc = crypto.SHA256
1695 sigAlgo.Algorithm = oidSignatureECDSAWithSHA256
1696 case elliptic.P384():
1697 hashFunc = crypto.SHA384
1698 sigAlgo.Algorithm = oidSignatureECDSAWithSHA384
1699 case elliptic.P521():
1700 hashFunc = crypto.SHA512
1701 sigAlgo.Algorithm = oidSignatureECDSAWithSHA512
1702 default:
1703 err = errors.New("x509: unknown elliptic curve")
1704 }
1705
1706 default:
1707 err = errors.New("x509: only RSA and ECDSA keys supported")
1708 }
1709
1710 if err != nil {
1711 return
1712 }
1713
1714 if requestedSigAlgo == 0 {
1715 return
1716 }
1717
1718 found := false
1719 for _, details := range signatureAlgorithmDetails {
1720 if details.algo == requestedSigAlgo {
1721 if details.pubKeyAlgo != pubType {
1722 err = errors.New("x509: requested SignatureAlgorithm does not match private key type")
1723 return
1724 }
1725 sigAlgo.Algorithm, hashFunc = details.oid, details.hash
1726 if hashFunc == 0 {
1727 err = errors.New("x509: cannot sign with hash function requested")
1728 return
1729 }
1730 if requestedSigAlgo.isRSAPSS() {
1731 sigAlgo.Parameters = rsaPSSParameters(hashFunc)
1732 }
1733 found = true
1734 break
1735 }
1736 }
1737
1738 if !found {
1739 err = errors.New("x509: unknown SignatureAlgorithm")
1740 }
1741
1742 return
1743 }
1744
1745 // CreateCertificate creates a new certificate based on a template.
1746 // The following members of template are used: AuthorityKeyId,
1747 // BasicConstraintsValid, DNSNames, ExcludedDNSDomains, ExtKeyUsage,
1748 // IsCA, KeyUsage, MaxPathLen, MaxPathLenZero, NotAfter, NotBefore,
1749 // PermittedDNSDomains, PermittedDNSDomainsCritical, SerialNumber,
1750 // SignatureAlgorithm, Subject, SubjectKeyId, and UnknownExtKeyUsage.
1751 //
1752 // The certificate is signed by parent. If parent is equal to template then the
1753 // certificate is self-signed. The parameter pub is the public key of the
1754 // signee and priv is the private key of the signer.
1755 //
1756 // The returned slice is the certificate in DER encoding.
1757 //
1758 // All keys types that are implemented via crypto.Signer are supported (This
1759 // includes *rsa.PublicKey and *ecdsa.PublicKey.)
1760 //
1761 // The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any,
1762 // unless the resulting certificate is self-signed. Otherwise the value from
1763 // template will be used.
1764 func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv interface{}) (cert []byte, err error) {
1765 key, ok := priv.(crypto.Signer)
1766 if !ok {
1767 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
1768 }
1769
1770 if template.SerialNumber == nil {
1771 return nil, errors.New("x509: no SerialNumber given")
1772 }
1773
1774 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
1775 if err != nil {
1776 return nil, err
1777 }
1778
1779 publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub)
1780 if err != nil {
1781 return nil, err
1782 }
1783
1784 asn1Issuer, err := subjectBytes(parent)
1785 if err != nil {
1786 return
1787 }
1788
1789 asn1Subject, err := subjectBytes(template)
1790 if err != nil {
1791 return
1792 }
1793
1794 authorityKeyId := template.AuthorityKeyId
1795 if !bytes.Equal(asn1Issuer, asn1Subject) && len(parent.SubjectKeyId) > 0 {
1796 authorityKeyId = parent.SubjectKeyId
1797 }
1798
1799 extensions, err := buildExtensions(template, authorityKeyId)
1800 if err != nil {
1801 return
1802 }
1803
1804 encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
1805 c := tbsCertificate{
1806 Version: 2,
1807 SerialNumber: template.SerialNumber,
1808 SignatureAlgorithm: signatureAlgorithm,
1809 Issuer: asn1.RawValue{FullBytes: asn1Issuer},
1810 Validity: validity{template.NotBefore.UTC(), template.NotAfter.UTC()},
1811 Subject: asn1.RawValue{FullBytes: asn1Subject},
1812 PublicKey: publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},
1813 Extensions: extensions,
1814 }
1815
1816 tbsCertContents, err := asn1.Marshal(c)
1817 if err != nil {
1818 return
1819 }
1820
1821 c.Raw = tbsCertContents
1822
1823 h := hashFunc.New()
1824 h.Write(tbsCertContents)
1825 digest := h.Sum(nil)
1826
1827 var signerOpts crypto.SignerOpts
1828 signerOpts = hashFunc
1829 if template.SignatureAlgorithm != 0 && template.SignatureAlgorithm.isRSAPSS() {
1830 signerOpts = &rsa.PSSOptions{
1831 SaltLength: rsa.PSSSaltLengthEqualsHash,
1832 Hash: hashFunc,
1833 }
1834 }
1835
1836 var signature []byte
1837 signature, err = key.Sign(rand, digest, signerOpts)
1838 if err != nil {
1839 return
1840 }
1841
1842 return asn1.Marshal(certificate{
1843 nil,
1844 c,
1845 signatureAlgorithm,
1846 asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
1847 })
1848 }
1849
1850 // pemCRLPrefix is the magic string that indicates that we have a PEM encoded
1851 // CRL.
1852 var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
1853
1854 // pemType is the type of a PEM encoded CRL.
1855 var pemType = "X509 CRL"
1856
1857 // ParseCRL parses a CRL from the given bytes. It's often the case that PEM
1858 // encoded CRLs will appear where they should be DER encoded, so this function
1859 // will transparently handle PEM encoding as long as there isn't any leading
1860 // garbage.
1861 func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) {
1862 if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
1863 block, _ := pem.Decode(crlBytes)
1864 if block != nil && block.Type == pemType {
1865 crlBytes = block.Bytes
1866 }
1867 }
1868 return ParseDERCRL(crlBytes)
1869 }
1870
1871 // ParseDERCRL parses a DER encoded CRL from the given bytes.
1872 func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) {
1873 certList := new(pkix.CertificateList)
1874 if rest, err := asn1.Unmarshal(derBytes, certList); err != nil {
1875 return nil, err
1876 } else if len(rest) != 0 {
1877 return nil, errors.New("x509: trailing data after CRL")
1878 }
1879 return certList, nil
1880 }
1881
1882 // CreateCRL returns a DER encoded CRL, signed by this Certificate, that
1883 // contains the given list of revoked certificates.
1884 func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
1885 key, ok := priv.(crypto.Signer)
1886 if !ok {
1887 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
1888 }
1889
1890 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), 0)
1891 if err != nil {
1892 return nil, err
1893 }
1894
1895 // Force revocation times to UTC per RFC 5280.
1896 revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts))
1897 for i, rc := range revokedCerts {
1898 rc.RevocationTime = rc.RevocationTime.UTC()
1899 revokedCertsUTC[i] = rc
1900 }
1901
1902 tbsCertList := pkix.TBSCertificateList{
1903 Version: 1,
1904 Signature: signatureAlgorithm,
1905 Issuer: c.Subject.ToRDNSequence(),
1906 ThisUpdate: now.UTC(),
1907 NextUpdate: expiry.UTC(),
1908 RevokedCertificates: revokedCertsUTC,
1909 }
1910
1911 // Authority Key Id
1912 if len(c.SubjectKeyId) > 0 {
1913 var aki pkix.Extension
1914 aki.Id = oidExtensionAuthorityKeyId
1915 aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId})
1916 if err != nil {
1917 return
1918 }
1919 tbsCertList.Extensions = append(tbsCertList.Extensions, aki)
1920 }
1921
1922 tbsCertListContents, err := asn1.Marshal(tbsCertList)
1923 if err != nil {
1924 return
1925 }
1926
1927 h := hashFunc.New()
1928 h.Write(tbsCertListContents)
1929 digest := h.Sum(nil)
1930
1931 var signature []byte
1932 signature, err = key.Sign(rand, digest, hashFunc)
1933 if err != nil {
1934 return
1935 }
1936
1937 return asn1.Marshal(pkix.CertificateList{
1938 TBSCertList: tbsCertList,
1939 SignatureAlgorithm: signatureAlgorithm,
1940 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
1941 })
1942 }
1943
1944 // CertificateRequest represents a PKCS #10, certificate signature request.
1945 type CertificateRequest struct {
1946 Raw []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
1947 RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content.
1948 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
1949 RawSubject []byte // DER encoded Subject.
1950
1951 Version int
1952 Signature []byte
1953 SignatureAlgorithm SignatureAlgorithm
1954
1955 PublicKeyAlgorithm PublicKeyAlgorithm
1956 PublicKey interface{}
1957
1958 Subject pkix.Name
1959
1960 // Attributes is the dried husk of a bug and shouldn't be used.
1961 Attributes []pkix.AttributeTypeAndValueSET
1962
1963 // Extensions contains raw X.509 extensions. When parsing CSRs, this
1964 // can be used to extract extensions that are not parsed by this
1965 // package.
1966 Extensions []pkix.Extension
1967
1968 // ExtraExtensions contains extensions to be copied, raw, into any
1969 // marshaled CSR. Values override any extensions that would otherwise
1970 // be produced based on the other fields but are overridden by any
1971 // extensions specified in Attributes.
1972 //
1973 // The ExtraExtensions field is not populated when parsing CSRs, see
1974 // Extensions.
1975 ExtraExtensions []pkix.Extension
1976
1977 // Subject Alternate Name values.
1978 DNSNames []string
1979 EmailAddresses []string
1980 IPAddresses []net.IP
1981 }
1982
1983 // These structures reflect the ASN.1 structure of X.509 certificate
1984 // signature requests (see RFC 2986):
1985
1986 type tbsCertificateRequest struct {
1987 Raw asn1.RawContent
1988 Version int
1989 Subject asn1.RawValue
1990 PublicKey publicKeyInfo
1991 RawAttributes []asn1.RawValue `asn1:"tag:0"`
1992 }
1993
1994 type certificateRequest struct {
1995 Raw asn1.RawContent
1996 TBSCSR tbsCertificateRequest
1997 SignatureAlgorithm pkix.AlgorithmIdentifier
1998 SignatureValue asn1.BitString
1999 }
2000
2001 // oidExtensionRequest is a PKCS#9 OBJECT IDENTIFIER that indicates requested
2002 // extensions in a CSR.
2003 var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14}
2004
2005 // newRawAttributes converts AttributeTypeAndValueSETs from a template
2006 // CertificateRequest's Attributes into tbsCertificateRequest RawAttributes.
2007 func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) {
2008 var rawAttributes []asn1.RawValue
2009 b, err := asn1.Marshal(attributes)
2010 if err != nil {
2011 return nil, err
2012 }
2013 rest, err := asn1.Unmarshal(b, &rawAttributes)
2014 if err != nil {
2015 return nil, err
2016 }
2017 if len(rest) != 0 {
2018 return nil, errors.New("x509: failed to unmarshal raw CSR Attributes")
2019 }
2020 return rawAttributes, nil
2021 }
2022
2023 // parseRawAttributes Unmarshals RawAttributes intos AttributeTypeAndValueSETs.
2024 func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET {
2025 var attributes []pkix.AttributeTypeAndValueSET
2026 for _, rawAttr := range rawAttributes {
2027 var attr pkix.AttributeTypeAndValueSET
2028 rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr)
2029 // Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET
2030 // (i.e.: challengePassword or unstructuredName).
2031 if err == nil && len(rest) == 0 {
2032 attributes = append(attributes, attr)
2033 }
2034 }
2035 return attributes
2036 }
2037
2038 // parseCSRExtensions parses the attributes from a CSR and extracts any
2039 // requested extensions.
2040 func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) {
2041 // pkcs10Attribute reflects the Attribute structure from section 4.1 of
2042 // https://tools.ietf.org/html/rfc2986.
2043 type pkcs10Attribute struct {
2044 Id asn1.ObjectIdentifier
2045 Values []asn1.RawValue `asn1:"set"`
2046 }
2047
2048 var ret []pkix.Extension
2049 for _, rawAttr := range rawAttributes {
2050 var attr pkcs10Attribute
2051 if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 {
2052 // Ignore attributes that don't parse.
2053 continue
2054 }
2055
2056 if !attr.Id.Equal(oidExtensionRequest) {
2057 continue
2058 }
2059
2060 var extensions []pkix.Extension
2061 if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil {
2062 return nil, err
2063 }
2064 ret = append(ret, extensions...)
2065 }
2066
2067 return ret, nil
2068 }
2069
2070 // CreateCertificateRequest creates a new certificate request based on a
2071 // template. The following members of template are used: Attributes, DNSNames,
2072 // EmailAddresses, ExtraExtensions, IPAddresses, SignatureAlgorithm, and
2073 // Subject. The private key is the private key of the signer.
2074 //
2075 // The returned slice is the certificate request in DER encoding.
2076 //
2077 // All keys types that are implemented via crypto.Signer are supported (This
2078 // includes *rsa.PublicKey and *ecdsa.PublicKey.)
2079 func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv interface{}) (csr []byte, err error) {
2080 key, ok := priv.(crypto.Signer)
2081 if !ok {
2082 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
2083 }
2084
2085 var hashFunc crypto.Hash
2086 var sigAlgo pkix.AlgorithmIdentifier
2087 hashFunc, sigAlgo, err = signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
2088 if err != nil {
2089 return nil, err
2090 }
2091
2092 var publicKeyBytes []byte
2093 var publicKeyAlgorithm pkix.AlgorithmIdentifier
2094 publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(key.Public())
2095 if err != nil {
2096 return nil, err
2097 }
2098
2099 var extensions []pkix.Extension
2100
2101 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0) &&
2102 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
2103 sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses)
2104 if err != nil {
2105 return nil, err
2106 }
2107
2108 extensions = append(extensions, pkix.Extension{
2109 Id: oidExtensionSubjectAltName,
2110 Value: sanBytes,
2111 })
2112 }
2113
2114 extensions = append(extensions, template.ExtraExtensions...)
2115
2116 var attributes []pkix.AttributeTypeAndValueSET
2117 attributes = append(attributes, template.Attributes...)
2118
2119 if len(extensions) > 0 {
2120 // specifiedExtensions contains all the extensions that we
2121 // found specified via template.Attributes.
2122 specifiedExtensions := make(map[string]bool)
2123
2124 for _, atvSet := range template.Attributes {
2125 if !atvSet.Type.Equal(oidExtensionRequest) {
2126 continue
2127 }
2128
2129 for _, atvs := range atvSet.Value {
2130 for _, atv := range atvs {
2131 specifiedExtensions[atv.Type.String()] = true
2132 }
2133 }
2134 }
2135
2136 atvs := make([]pkix.AttributeTypeAndValue, 0, len(extensions))
2137 for _, e := range extensions {
2138 if specifiedExtensions[e.Id.String()] {
2139 // Attributes already contained a value for
2140 // this extension and it takes priority.
2141 continue
2142 }
2143
2144 atvs = append(atvs, pkix.AttributeTypeAndValue{
2145 // There is no place for the critical flag in a CSR.
2146 Type: e.Id,
2147 Value: e.Value,
2148 })
2149 }
2150
2151 // Append the extensions to an existing attribute if possible.
2152 appended := false
2153 for _, atvSet := range attributes {
2154 if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 {
2155 continue
2156 }
2157
2158 atvSet.Value[0] = append(atvSet.Value[0], atvs...)
2159 appended = true
2160 break
2161 }
2162
2163 // Otherwise, add a new attribute for the extensions.
2164 if !appended {
2165 attributes = append(attributes, pkix.AttributeTypeAndValueSET{
2166 Type: oidExtensionRequest,
2167 Value: [][]pkix.AttributeTypeAndValue{
2168 atvs,
2169 },
2170 })
2171 }
2172 }
2173
2174 asn1Subject := template.RawSubject
2175 if len(asn1Subject) == 0 {
2176 asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence())
2177 if err != nil {
2178 return
2179 }
2180 }
2181
2182 rawAttributes, err := newRawAttributes(attributes)
2183 if err != nil {
2184 return
2185 }
2186
2187 tbsCSR := tbsCertificateRequest{
2188 Version: 0, // PKCS #10, RFC 2986
2189 Subject: asn1.RawValue{FullBytes: asn1Subject},
2190 PublicKey: publicKeyInfo{
2191 Algorithm: publicKeyAlgorithm,
2192 PublicKey: asn1.BitString{
2193 Bytes: publicKeyBytes,
2194 BitLength: len(publicKeyBytes) * 8,
2195 },
2196 },
2197 RawAttributes: rawAttributes,
2198 }
2199
2200 tbsCSRContents, err := asn1.Marshal(tbsCSR)
2201 if err != nil {
2202 return
2203 }
2204 tbsCSR.Raw = tbsCSRContents
2205
2206 h := hashFunc.New()
2207 h.Write(tbsCSRContents)
2208 digest := h.Sum(nil)
2209
2210 var signature []byte
2211 signature, err = key.Sign(rand, digest, hashFunc)
2212 if err != nil {
2213 return
2214 }
2215
2216 return asn1.Marshal(certificateRequest{
2217 TBSCSR: tbsCSR,
2218 SignatureAlgorithm: sigAlgo,
2219 SignatureValue: asn1.BitString{
2220 Bytes: signature,
2221 BitLength: len(signature) * 8,
2222 },
2223 })
2224 }
2225
2226 // ParseCertificateRequest parses a single certificate request from the
2227 // given ASN.1 DER data.
2228 func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) {
2229 var csr certificateRequest
2230
2231 rest, err := asn1.Unmarshal(asn1Data, &csr)
2232 if err != nil {
2233 return nil, err
2234 } else if len(rest) != 0 {
2235 return nil, asn1.SyntaxError{Msg: "trailing data"}
2236 }
2237
2238 return parseCertificateRequest(&csr)
2239 }
2240
2241 func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) {
2242 out := &CertificateRequest{
2243 Raw: in.Raw,
2244 RawTBSCertificateRequest: in.TBSCSR.Raw,
2245 RawSubjectPublicKeyInfo: in.TBSCSR.PublicKey.Raw,
2246 RawSubject: in.TBSCSR.Subject.FullBytes,
2247
2248 Signature: in.SignatureValue.RightAlign(),
2249 SignatureAlgorithm: getSignatureAlgorithmFromAI(in.SignatureAlgorithm),
2250
2251 PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm),
2252
2253 Version: in.TBSCSR.Version,
2254 Attributes: parseRawAttributes(in.TBSCSR.RawAttributes),
2255 }
2256
2257 var err error
2258 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCSR.PublicKey)
2259 if err != nil {
2260 return nil, err
2261 }
2262
2263 var subject pkix.RDNSequence
2264 if rest, err := asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil {
2265 return nil, err
2266 } else if len(rest) != 0 {
2267 return nil, errors.New("x509: trailing data after X.509 Subject")
2268 }
2269
2270 out.Subject.FillFromRDNSequence(&subject)
2271
2272 if out.Extensions, err = parseCSRExtensions(in.TBSCSR.RawAttributes); err != nil {
2273 return nil, err
2274 }
2275
2276 for _, extension := range out.Extensions {
2277 if extension.Id.Equal(oidExtensionSubjectAltName) {
2278 out.DNSNames, out.EmailAddresses, out.IPAddresses, err = parseSANExtension(extension.Value)
2279 if err != nil {
2280 return nil, err
2281 }
2282 }
2283 }
2284
2285 return out, nil
2286 }
2287
2288 // CheckSignature reports whether the signature on c is valid.
2289 func (c *CertificateRequest) CheckSignature() error {
2290 return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey)
2291 }