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