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