Ensure errors are handled or logged
if err != nil {
1// Copyright 2009 The Go Authors. All rights reserved.2// Use of this source code is governed by a BSD-style3// license that can be found in the LICENSE file.45// Package x509 implements a subset of the X.509 standard.6//7// It allows parsing and generating certificates, certificate signing8// 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 (RFC12// 2459/3280/5280), and as further restricted by the CA/Browser Forum Baseline13// Requirements. There is minimal support for features outside of these14// profiles, as the primary goal of the package is to provide compatibility15// with the publicly trusted TLS certificate ecosystem and its policies and16// constraints.17//18// On macOS and Windows, certificate verification is handled by system APIs, but19// the package aims to apply consistent validation rules across operating20// systems.21package x5092223import (24 "bytes"25 "crypto"26 "crypto/ecdh"27 "crypto/ecdsa"28 "crypto/ed25519"29 "crypto/elliptic"30 "crypto/fips140"31 "crypto/mldsa"32 "crypto/mlkem"33 "crypto/rsa"34 "crypto/sha1"35 "crypto/sha256"36 "crypto/x509/pkix"37 "encoding/asn1"38 "encoding/pem"39 "errors"40 "fmt"41 "internal/godebug"42 "io"43 "math/big"44 "net"45 "net/url"46 "strconv"47 "time"48 "unicode"4950 // Explicitly import these for their crypto.RegisterHash init side-effects.51 // Keep these as blank imports, even if they're imported above.52 _ "crypto/sha1"53 _ "crypto/sha256"54 _ "crypto/sha512"5556 "golang.org/x/crypto/cryptobyte"57 cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1"58)5960// pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo61// in RFC 3280.62type pkixPublicKey struct {63 Algo pkix.AlgorithmIdentifier64 BitString asn1.BitString65}6667// ParsePKIXPublicKey parses a public key in PKIX, ASN.1 DER form. The encoded68// public key is a SubjectPublicKeyInfo structure (see RFC 5280, Section 4.1).69//70// It returns a *[rsa.PublicKey], *[dsa.PublicKey], *[ecdsa.PublicKey],71// [ed25519.PublicKey] (not a pointer), *[mldsa.PublicKey], *[ecdh.PublicKey]72// (for X25519), *[mlkem.EncapsulationKey768], or *[mlkem.EncapsulationKey1024].73// More types might be supported in the future.74//75// This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".76func ParsePKIXPublicKey(derBytes []byte) (pub any, err error) {77 var pki publicKeyInfo78 if rest, err := asn1.Unmarshal(derBytes, &pki); err != nil {79 if _, err := asn1.Unmarshal(derBytes, &pkcs1PublicKey{}); err == nil {80 return nil, errors.New("x509: failed to parse public key (use ParsePKCS1PublicKey instead for this key format)")81 }82 return nil, err83 } else if len(rest) != 0 {84 return nil, errors.New("x509: trailing data after ASN.1 of public-key")85 }86 return parsePublicKey(&pki)87}8889func marshalPublicKey(pub any) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) {90 switch pub := pub.(type) {91 case *rsa.PublicKey:92 publicKeyBytes, err = asn1.Marshal(pkcs1PublicKey{93 N: pub.N,94 E: pub.E,95 })96 if err != nil {97 return nil, pkix.AlgorithmIdentifier{}, err98 }99 publicKeyAlgorithm.Algorithm = oidPublicKeyRSA100 // This is a NULL parameters value which is required by101 // RFC 3279, Section 2.3.1.102 publicKeyAlgorithm.Parameters = asn1.NullRawValue103 case *ecdsa.PublicKey:104 oid, ok := oidFromNamedCurve(pub.Curve)105 if !ok {106 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")107 }108 publicKeyBytes, err = pub.Bytes()109 if err != nil {110 return nil, pkix.AlgorithmIdentifier{}, err111 }112 publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA113 var paramBytes []byte114 paramBytes, err = asn1.Marshal(oid)115 if err != nil {116 return117 }118 publicKeyAlgorithm.Parameters.FullBytes = paramBytes119 case ed25519.PublicKey:120 publicKeyBytes = pub121 publicKeyAlgorithm.Algorithm = oidPublicKeyEd25519122 case *mldsa.PublicKey:123 oid, ok := oidFromMLDSAParameters(pub.Parameters())124 if !ok {125 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported ML-DSA parameters")126 }127 publicKeyBytes = pub.Bytes()128 publicKeyAlgorithm.Algorithm = oid129 case *ecdh.PublicKey:130 publicKeyBytes = pub.Bytes()131 if pub.Curve() == ecdh.X25519() {132 publicKeyAlgorithm.Algorithm = oidPublicKeyX25519133 } else {134 oid, ok := oidFromECDHCurve(pub.Curve())135 if !ok {136 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")137 }138 publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA139 var paramBytes []byte140 paramBytes, err = asn1.Marshal(oid)141 if err != nil {142 return143 }144 publicKeyAlgorithm.Parameters.FullBytes = paramBytes145 }146 case *mlkem.EncapsulationKey768:147 publicKeyBytes = pub.Bytes()148 publicKeyAlgorithm.Algorithm = oidPublicKeyMLKEM768149 case *mlkem.EncapsulationKey1024:150 publicKeyBytes = pub.Bytes()151 publicKeyAlgorithm.Algorithm = oidPublicKeyMLKEM1024152 default:153 return nil, pkix.AlgorithmIdentifier{}, fmt.Errorf("x509: unsupported public key type: %T", pub)154 }155156 return publicKeyBytes, publicKeyAlgorithm, nil157}158159// MarshalPKIXPublicKey converts a public key to PKIX, ASN.1 DER form.160// The encoded public key is a SubjectPublicKeyInfo structure161// (see RFC 5280, Section 4.1).162//163// The following key types are currently supported: *[rsa.PublicKey],164// *[ecdsa.PublicKey], [ed25519.PublicKey] (not a pointer), *[mldsa.PublicKey],165// *[ecdh.PublicKey], *[mlkem.EncapsulationKey768], and166// *[mlkem.EncapsulationKey1024]. Unsupported key types result in an error.167//168// This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".169func MarshalPKIXPublicKey(pub any) ([]byte, error) {170 var publicKeyBytes []byte171 var publicKeyAlgorithm pkix.AlgorithmIdentifier172 var err error173174 if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {175 return nil, err176 }177178 pkix := pkixPublicKey{179 Algo: publicKeyAlgorithm,180 BitString: asn1.BitString{181 Bytes: publicKeyBytes,182 BitLength: 8 * len(publicKeyBytes),183 },184 }185186 ret, _ := asn1.Marshal(pkix)187 return ret, nil188}189190// These structures reflect the ASN.1 structure of X.509 certificates.:191192type certificate struct {193 TBSCertificate tbsCertificate194 SignatureAlgorithm pkix.AlgorithmIdentifier195 SignatureValue asn1.BitString196}197198type tbsCertificate struct {199 Raw asn1.RawContent200 Version int `asn1:"optional,explicit,default:0,tag:0"`201 SerialNumber *big.Int202 SignatureAlgorithm pkix.AlgorithmIdentifier203 Issuer asn1.RawValue204 Validity validity205 Subject asn1.RawValue206 PublicKey publicKeyInfo207 UniqueId asn1.BitString `asn1:"optional,tag:1"`208 SubjectUniqueId asn1.BitString `asn1:"optional,tag:2"`209 Extensions []pkix.Extension `asn1:"omitempty,optional,explicit,tag:3"`210}211212type dsaAlgorithmParameters struct {213 P, Q, G *big.Int214}215216type validity struct {217 NotBefore, NotAfter time.Time218}219220type publicKeyInfo struct {221 Raw asn1.RawContent222 Algorithm pkix.AlgorithmIdentifier223 PublicKey asn1.BitString224}225226// RFC 5280, 4.2.1.1227type authKeyId struct {228 Id []byte `asn1:"optional,tag:0"`229}230231type SignatureAlgorithm int232233const (234 UnknownSignatureAlgorithm SignatureAlgorithm = iota235236 MD2WithRSA // Unsupported.237 MD5WithRSA // Only supported for signing, not verification.238 SHA1WithRSA // Only supported for signing, and verification of CRLs, CSRs, and OCSP responses.239 SHA256WithRSA240 SHA384WithRSA241 SHA512WithRSA242 DSAWithSHA1 // Unsupported.243 DSAWithSHA256 // Unsupported.244 ECDSAWithSHA1 // Only supported for signing, and verification of CRLs, CSRs, and OCSP responses.245 ECDSAWithSHA256246 ECDSAWithSHA384247 ECDSAWithSHA512248 SHA256WithRSAPSS249 SHA384WithRSAPSS250 SHA512WithRSAPSS251 PureEd25519252 MLDSA44253 MLDSA65254 MLDSA87255)256257func (algo SignatureAlgorithm) isRSAPSS() bool {258 for _, details := range signatureAlgorithmDetails {259 if details.algo == algo {260 return details.isRSAPSS261 }262 }263 return false264}265266func (algo SignatureAlgorithm) hashFunc() crypto.Hash {267 for _, details := range signatureAlgorithmDetails {268 if details.algo == algo {269 return details.hash270 }271 }272 return crypto.Hash(0)273}274275func (algo SignatureAlgorithm) String() string {276 for _, details := range signatureAlgorithmDetails {277 if details.algo == algo {278 return details.name279 }280 }281 return strconv.Itoa(int(algo))282}283284type PublicKeyAlgorithm int285286const (287 UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota288 RSA289 DSA // Only supported for parsing.290 ECDSA291 Ed25519292 MLDSA293)294295var publicKeyAlgoName = [...]string{296 RSA: "RSA",297 DSA: "DSA",298 ECDSA: "ECDSA",299 Ed25519: "Ed25519",300 MLDSA: "ML-DSA",301}302303func (algo PublicKeyAlgorithm) String() string {304 if 0 < algo && int(algo) < len(publicKeyAlgoName) {305 return publicKeyAlgoName[algo]306 }307 return strconv.Itoa(int(algo))308}309310// OIDs for signature algorithms311//312// pkcs-1 OBJECT IDENTIFIER ::= {313// iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }314//315// RFC 3279 2.2.1 RSA Signature Algorithms316//317// md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }318//319// sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }320//321// dsaWithSha1 OBJECT IDENTIFIER ::= {322// iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 }323//324// RFC 3279 2.2.3 ECDSA Signature Algorithm325//326// ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {327// iso(1) member-body(2) us(840) ansi-x962(10045)328// signatures(4) ecdsa-with-SHA1(1)}329//330// RFC 4055 5 PKCS #1 Version 1.5331//332// sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }333//334// sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }335//336// sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }337//338// RFC 5758 3.1 DSA Signature Algorithms339//340// dsaWithSha256 OBJECT IDENTIFIER ::= {341// joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)342// csor(3) algorithms(4) id-dsa-with-sha2(3) 2}343//344// RFC 5758 3.2 ECDSA Signature Algorithm345//346// ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2)347// us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 }348//349// ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2)350// us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 }351//352// ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2)353// us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 }354//355// RFC 8410 3 Curve25519 and Curve448 Algorithm Identifiers356//357// id-Ed25519 OBJECT IDENTIFIER ::= { 1 3 101 112 }358var (359 oidSignatureMD5WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}360 oidSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}361 oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}362 oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}363 oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}364 oidSignatureRSAPSS = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 10}365 oidSignatureDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}366 oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 2}367 oidSignatureECDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1}368 oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2}369 oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3}370 oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4}371 oidSignatureEd25519 = asn1.ObjectIdentifier{1, 3, 101, 112}372373 oidSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1}374 oidSHA384 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2}375 oidSHA512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3}376377 oidMGF1 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 8}378379 // oidISOSignatureSHA1WithRSA means the same as oidSignatureSHA1WithRSA380 // but it's specified by ISO. Microsoft's makecert.exe has been known381 // to produce certificates with this OID.382 oidISOSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 29}383)384385var signatureAlgorithmDetails = []struct {386 algo SignatureAlgorithm387 name string388 oid asn1.ObjectIdentifier389 params asn1.RawValue390 pubKeyAlgo PublicKeyAlgorithm391 hash crypto.Hash392 isRSAPSS bool393}{394 {MD5WithRSA, "MD5-RSA", oidSignatureMD5WithRSA, asn1.NullRawValue, RSA, crypto.MD5, false},395 {SHA1WithRSA, "SHA1-RSA", oidSignatureSHA1WithRSA, asn1.NullRawValue, RSA, crypto.SHA1, false},396 {SHA1WithRSA, "SHA1-RSA", oidISOSignatureSHA1WithRSA, asn1.NullRawValue, RSA, crypto.SHA1, false},397 {SHA256WithRSA, "SHA256-RSA", oidSignatureSHA256WithRSA, asn1.NullRawValue, RSA, crypto.SHA256, false},398 {SHA384WithRSA, "SHA384-RSA", oidSignatureSHA384WithRSA, asn1.NullRawValue, RSA, crypto.SHA384, false},399 {SHA512WithRSA, "SHA512-RSA", oidSignatureSHA512WithRSA, asn1.NullRawValue, RSA, crypto.SHA512, false},400 {SHA256WithRSAPSS, "SHA256-RSAPSS", oidSignatureRSAPSS, pssParametersSHA256, RSA, crypto.SHA256, true},401 {SHA384WithRSAPSS, "SHA384-RSAPSS", oidSignatureRSAPSS, pssParametersSHA384, RSA, crypto.SHA384, true},402 {SHA512WithRSAPSS, "SHA512-RSAPSS", oidSignatureRSAPSS, pssParametersSHA512, RSA, crypto.SHA512, true},403 {DSAWithSHA1, "DSA-SHA1", oidSignatureDSAWithSHA1, emptyRawValue, DSA, crypto.SHA1, false},404 {DSAWithSHA256, "DSA-SHA256", oidSignatureDSAWithSHA256, emptyRawValue, DSA, crypto.SHA256, false},405 {ECDSAWithSHA1, "ECDSA-SHA1", oidSignatureECDSAWithSHA1, emptyRawValue, ECDSA, crypto.SHA1, false},406 {ECDSAWithSHA256, "ECDSA-SHA256", oidSignatureECDSAWithSHA256, emptyRawValue, ECDSA, crypto.SHA256, false},407 {ECDSAWithSHA384, "ECDSA-SHA384", oidSignatureECDSAWithSHA384, emptyRawValue, ECDSA, crypto.SHA384, false},408 {ECDSAWithSHA512, "ECDSA-SHA512", oidSignatureECDSAWithSHA512, emptyRawValue, ECDSA, crypto.SHA512, false},409 {PureEd25519, "Ed25519", oidSignatureEd25519, emptyRawValue, Ed25519, crypto.Hash(0) /* no pre-hashing */, false},410 {MLDSA44, "ML-DSA-44", oidPublicKeyMLDSA44, emptyRawValue, MLDSA, crypto.Hash(0) /* no pre-hashing */, false},411 {MLDSA65, "ML-DSA-65", oidPublicKeyMLDSA65, emptyRawValue, MLDSA, crypto.Hash(0) /* no pre-hashing */, false},412 {MLDSA87, "ML-DSA-87", oidPublicKeyMLDSA87, emptyRawValue, MLDSA, crypto.Hash(0) /* no pre-hashing */, false},413}414415var emptyRawValue = asn1.RawValue{}416417// DER encoded RSA PSS parameters for the418// SHA256, SHA384, and SHA512 hashes as defined in RFC 3447, Appendix A.2.3.419// The parameters contain the following values:420// - hashAlgorithm contains the associated hash identifier with NULL parameters421// - maskGenAlgorithm always contains the default mgf1SHA1 identifier422// - saltLength contains the length of the associated hash423// - trailerField always contains the default trailerFieldBC value424var (425 pssParametersSHA256 = 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}}426 pssParametersSHA384 = 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}}427 pssParametersSHA512 = 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}}428)429430// pssParameters reflects the parameters in an AlgorithmIdentifier that431// specifies RSA PSS. See RFC 3447, Appendix A.2.3.432type pssParameters struct {433 // The following three fields are not marked as434 // optional because the default values specify SHA-1,435 // which is no longer suitable for use in signatures.436 Hash pkix.AlgorithmIdentifier `asn1:"explicit,tag:0"`437 MGF pkix.AlgorithmIdentifier `asn1:"explicit,tag:1"`438 SaltLength int `asn1:"explicit,tag:2"`439 TrailerField int `asn1:"optional,explicit,tag:3,default:1"`440}441442func getSignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm {443 if ai.Algorithm.Equal(oidSignatureEd25519) ||444 ai.Algorithm.Equal(oidPublicKeyMLDSA44) ||445 ai.Algorithm.Equal(oidPublicKeyMLDSA65) ||446 ai.Algorithm.Equal(oidPublicKeyMLDSA87) {447 // RFC 8410, Section 3448 // > For all of the OIDs, the parameters MUST be absent.449 // RFC 9881, Section 2450 // > The contents of the parameters component for each algorithm MUST be absent.451 if len(ai.Parameters.FullBytes) != 0 {452 return UnknownSignatureAlgorithm453 }454 }455456 if !ai.Algorithm.Equal(oidSignatureRSAPSS) {457 for _, details := range signatureAlgorithmDetails {458 if ai.Algorithm.Equal(details.oid) {459 return details.algo460 }461 }462 return UnknownSignatureAlgorithm463 }464465 // RSA PSS is special because it encodes important parameters466 // in the Parameters.467468 var params pssParameters469 if _, err := asn1.Unmarshal(ai.Parameters.FullBytes, ¶ms); err != nil {470 return UnknownSignatureAlgorithm471 }472473 var mgf1HashFunc pkix.AlgorithmIdentifier474 if _, err := asn1.Unmarshal(params.MGF.Parameters.FullBytes, &mgf1HashFunc); err != nil {475 return UnknownSignatureAlgorithm476 }477478 // PSS is greatly overburdened with options. This code forces them into479 // three buckets by requiring that the MGF1 hash function always match the480 // message hash function (as recommended in RFC 3447, Section 8.1), that the481 // salt length matches the hash length, and that the trailer field has the482 // default value.483 if (len(params.Hash.Parameters.FullBytes) != 0 && !bytes.Equal(params.Hash.Parameters.FullBytes, asn1.NullBytes)) ||484 !params.MGF.Algorithm.Equal(oidMGF1) ||485 !mgf1HashFunc.Algorithm.Equal(params.Hash.Algorithm) ||486 (len(mgf1HashFunc.Parameters.FullBytes) != 0 && !bytes.Equal(mgf1HashFunc.Parameters.FullBytes, asn1.NullBytes)) ||487 params.TrailerField != 1 {488 return UnknownSignatureAlgorithm489 }490491 switch {492 case params.Hash.Algorithm.Equal(oidSHA256) && params.SaltLength == 32:493 return SHA256WithRSAPSS494 case params.Hash.Algorithm.Equal(oidSHA384) && params.SaltLength == 48:495 return SHA384WithRSAPSS496 case params.Hash.Algorithm.Equal(oidSHA512) && params.SaltLength == 64:497 return SHA512WithRSAPSS498 }499500 return UnknownSignatureAlgorithm501}502503var (504 // RFC 3279, 2.3 Public Key Algorithms505 //506 // pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)507 // rsadsi(113549) pkcs(1) 1 }508 //509 // rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }510 //511 // id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)512 // x9-57(10040) x9cm(4) 1 }513 oidPublicKeyRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}514 oidPublicKeyDSA = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}515 // RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters516 //517 // id-ecPublicKey OBJECT IDENTIFIER ::= {518 // iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }519 oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}520 // RFC 8410, Section 3521 //522 // id-X25519 OBJECT IDENTIFIER ::= { 1 3 101 110 }523 // id-Ed25519 OBJECT IDENTIFIER ::= { 1 3 101 112 }524 oidPublicKeyX25519 = asn1.ObjectIdentifier{1, 3, 101, 110}525 oidPublicKeyEd25519 = asn1.ObjectIdentifier{1, 3, 101, 112}526 // RFC 9881, Section 2527 //528 // id-ml-dsa-44 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2)529 // country(16) us(840) organization(1) gov(101) csor(3)530 // nistAlgorithm(4) sigAlgs(3) id-ml-dsa-44(17) }531 //532 // id-ml-dsa-65 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2)533 // country(16) us(840) organization(1) gov(101) csor(3)534 // nistAlgorithm(4) sigAlgs(3) id-ml-dsa-65(18) }535 //536 // id-ml-dsa-87 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2)537 // country(16) us(840) organization(1) gov(101) csor(3)538 // nistAlgorithm(4) sigAlgs(3) id-ml-dsa-87(19) }539 oidPublicKeyMLDSA44 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 17}540 oidPublicKeyMLDSA65 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 18}541 oidPublicKeyMLDSA87 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 19}542 // RFC 9935, Section 3543 //544 // id-alg-ml-kem-768 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2)545 // country(16) us(840) organization(1) gov(101) csor(3)546 // nistAlgorithm(4) kems(4) id-alg-ml-kem-768(2) }547 //548 // id-alg-ml-kem-1024 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2)549 // country(16) us(840) organization(1) gov(101) csor(3)550 // nistAlgorithm(4) kems(4) id-alg-ml-kem-1024(3) }551 oidPublicKeyMLKEM768 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 4, 2}552 oidPublicKeyMLKEM1024 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 4, 3}553)554555// getPublicKeyAlgorithmFromOID returns the exposed PublicKeyAlgorithm556// identifier for public key types supported in certificates and CSRs. Marshal557// and Parse functions may support a different set of public key types.558func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {559 switch {560 case oid.Equal(oidPublicKeyRSA):561 return RSA562 case oid.Equal(oidPublicKeyDSA):563 return DSA564 case oid.Equal(oidPublicKeyECDSA):565 return ECDSA566 case oid.Equal(oidPublicKeyEd25519):567 return Ed25519568 case oid.Equal(oidPublicKeyMLDSA44),569 oid.Equal(oidPublicKeyMLDSA65),570 oid.Equal(oidPublicKeyMLDSA87):571 // ML-DSA is not available in FIPS 140-3 module v1.0.0.572 if fips140.Version() == "v1.0.0" {573 return UnknownPublicKeyAlgorithm574 }575 return MLDSA576 }577 return UnknownPublicKeyAlgorithm578}579580// RFC 5480, 2.1.1.1. Named Curve581//582// secp224r1 OBJECT IDENTIFIER ::= {583// iso(1) identified-organization(3) certicom(132) curve(0) 33 }584//585// secp256r1 OBJECT IDENTIFIER ::= {586// iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)587// prime(1) 7 }588//589// secp384r1 OBJECT IDENTIFIER ::= {590// iso(1) identified-organization(3) certicom(132) curve(0) 34 }591//592// secp521r1 OBJECT IDENTIFIER ::= {593// iso(1) identified-organization(3) certicom(132) curve(0) 35 }594//595// NB: secp256r1 is equivalent to prime256v1596var (597 oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}598 oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}599 oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}600 oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}601)602603func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve {604 switch {605 case oid.Equal(oidNamedCurveP224):606 return elliptic.P224()607 case oid.Equal(oidNamedCurveP256):608 return elliptic.P256()609 case oid.Equal(oidNamedCurveP384):610 return elliptic.P384()611 case oid.Equal(oidNamedCurveP521):612 return elliptic.P521()613 }614 return nil615}616617func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) {618 switch curve {619 case elliptic.P224():620 return oidNamedCurveP224, true621 case elliptic.P256():622 return oidNamedCurveP256, true623 case elliptic.P384():624 return oidNamedCurveP384, true625 case elliptic.P521():626 return oidNamedCurveP521, true627 }628629 return nil, false630}631632func oidFromECDHCurve(curve ecdh.Curve) (asn1.ObjectIdentifier, bool) {633 switch curve {634 case ecdh.X25519():635 return oidPublicKeyX25519, true636 case ecdh.P256():637 return oidNamedCurveP256, true638 case ecdh.P384():639 return oidNamedCurveP384, true640 case ecdh.P521():641 return oidNamedCurveP521, true642 }643644 return nil, false645}646647func mldsaParametersFromOID(oid asn1.ObjectIdentifier) (mldsa.Parameters, bool) {648 switch {649 case oid.Equal(oidPublicKeyMLDSA44):650 return mldsa.MLDSA44(), true651 case oid.Equal(oidPublicKeyMLDSA65):652 return mldsa.MLDSA65(), true653 case oid.Equal(oidPublicKeyMLDSA87):654 return mldsa.MLDSA87(), true655 }656 return mldsa.Parameters{}, false657}658659func oidFromMLDSAParameters(params mldsa.Parameters) (asn1.ObjectIdentifier, bool) {660 switch {661 case params == mldsa.MLDSA44():662 return oidPublicKeyMLDSA44, true663 case params == mldsa.MLDSA65():664 return oidPublicKeyMLDSA65, true665 case params == mldsa.MLDSA87():666 return oidPublicKeyMLDSA87, true667 }668 return nil, false669}670671// KeyUsage represents the set of actions that are valid for a given key. It's672// a bitmap of the KeyUsage* constants.673type KeyUsage int674675//go:generate stringer -linecomment -type=KeyUsage,ExtKeyUsage -output=x509_string.go676677const (678 KeyUsageDigitalSignature KeyUsage = 1 << iota // digitalSignature679 KeyUsageContentCommitment // contentCommitment680 KeyUsageKeyEncipherment // keyEncipherment681 KeyUsageDataEncipherment // dataEncipherment682 KeyUsageKeyAgreement // keyAgreement683 KeyUsageCertSign // keyCertSign684 KeyUsageCRLSign // cRLSign685 KeyUsageEncipherOnly // encipherOnly686 KeyUsageDecipherOnly // decipherOnly687)688689// RFC 5280, 4.2.1.12 Extended Key Usage690//691// anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }692//693// id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }694//695// id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 }696// id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 }697// id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 }698// id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 }699// id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 }700// id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 }701//702// https://www.iana.org/assignments/smi-numbers/smi-numbers.xhtml#smi-numbers-1.3.6.1.5.5.7.3703var (704 oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0}705 oidExtKeyUsageServerAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}706 oidExtKeyUsageClientAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}707 oidExtKeyUsageCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}708 oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}709 oidExtKeyUsageIPSECEndSystem = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}710 oidExtKeyUsageIPSECTunnel = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}711 oidExtKeyUsageIPSECUser = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}712 oidExtKeyUsageTimeStamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}713 oidExtKeyUsageOCSPSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}714 oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}715 oidExtKeyUsageNetscapeServerGatedCrypto = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}716 oidExtKeyUsageMicrosoftCommercialCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 2, 1, 22}717 oidExtKeyUsageMicrosoftKernelCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 1, 1}718)719720// ExtKeyUsage represents an extended set of actions that are valid for a given key.721// Each of the ExtKeyUsage* constants define a unique action.722type ExtKeyUsage int723724const (725 ExtKeyUsageAny ExtKeyUsage = iota // anyExtendedKeyUsage726 ExtKeyUsageServerAuth // serverAuth727 ExtKeyUsageClientAuth // clientAuth728 ExtKeyUsageCodeSigning // codeSigning729 ExtKeyUsageEmailProtection // emailProtection730 ExtKeyUsageIPSECEndSystem // ipsecEndSystem731 ExtKeyUsageIPSECTunnel // ipsecTunnel732 ExtKeyUsageIPSECUser // ipsecUser733 ExtKeyUsageTimeStamping // timeStamping734 ExtKeyUsageOCSPSigning // OCSPSigning735 ExtKeyUsageMicrosoftServerGatedCrypto // msSGC736 ExtKeyUsageNetscapeServerGatedCrypto // nsSGC737 ExtKeyUsageMicrosoftCommercialCodeSigning // msCodeCom738 ExtKeyUsageMicrosoftKernelCodeSigning // msKernelCode739)740741// extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.742var extKeyUsageOIDs = []struct {743 extKeyUsage ExtKeyUsage744 oid asn1.ObjectIdentifier745}{746 {ExtKeyUsageAny, oidExtKeyUsageAny},747 {ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},748 {ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},749 {ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},750 {ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},751 {ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},752 {ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},753 {ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},754 {ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},755 {ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},756 {ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},757 {ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},758 {ExtKeyUsageMicrosoftCommercialCodeSigning, oidExtKeyUsageMicrosoftCommercialCodeSigning},759 {ExtKeyUsageMicrosoftKernelCodeSigning, oidExtKeyUsageMicrosoftKernelCodeSigning},760}761762func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) {763 for _, pair := range extKeyUsageOIDs {764 if oid.Equal(pair.oid) {765 return pair.extKeyUsage, true766 }767 }768 return769}770771func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {772 for _, pair := range extKeyUsageOIDs {773 if eku == pair.extKeyUsage {774 return pair.oid, true775 }776 }777 return778}779780// OID returns the ASN.1 object identifier of the EKU.781func (eku ExtKeyUsage) OID() OID {782 asn1OID, ok := oidFromExtKeyUsage(eku)783 if !ok {784 panic("x509: internal error: known ExtKeyUsage has no OID")785 }786 oid, err := OIDFromASN1OID(asn1OID)787 if err != nil {788 panic("x509: internal error: known ExtKeyUsage has invalid OID")789 }790 return oid791}792793// A Certificate represents an X.509 certificate.794type Certificate struct {795 Raw []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).796 RawTBSCertificate []byte // Certificate part of raw ASN.1 DER content.797 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.798 RawSubject []byte // DER encoded Subject799 RawIssuer []byte // DER encoded Issuer800 RawSignatureAlgorithm []byte // DER encoded AlgorithmIdentifier801802 Signature []byte803 SignatureAlgorithm SignatureAlgorithm804805 PublicKeyAlgorithm PublicKeyAlgorithm806 PublicKey any807808 Version int809 SerialNumber *big.Int810 Issuer pkix.Name811 Subject pkix.Name812 NotBefore, NotAfter time.Time // Validity bounds.813 KeyUsage KeyUsage814815 // Extensions contains raw X.509 extensions. When parsing certificates,816 // this can be used to extract non-critical extensions that are not817 // parsed by this package. When marshaling certificates, the Extensions818 // field is ignored, see ExtraExtensions.819 Extensions []pkix.Extension820821 // ExtraExtensions contains extensions to be copied, raw, into any822 // marshaled certificates. Values override any extensions that would823 // otherwise be produced based on the other fields. The ExtraExtensions824 // field is not populated when parsing certificates, see Extensions.825 ExtraExtensions []pkix.Extension826827 // UnhandledCriticalExtensions contains a list of extension IDs that828 // were not (fully) processed when parsing. Verify will fail if this829 // slice is non-empty, unless verification is delegated to an OS830 // library which understands all the critical extensions.831 //832 // Users can access these extensions using Extensions and can remove833 // elements from this slice if they believe that they have been834 // handled.835 UnhandledCriticalExtensions []asn1.ObjectIdentifier836837 ExtKeyUsage []ExtKeyUsage // Sequence of extended key usages.838 UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.839840 // BasicConstraintsValid indicates whether IsCA, MaxPathLen,841 // and MaxPathLenZero are valid.842 BasicConstraintsValid bool843 IsCA bool844845 // MaxPathLen and MaxPathLenZero indicate the presence and846 // value of the BasicConstraints' "pathLenConstraint".847 //848 // When parsing a certificate, a positive non-zero MaxPathLen849 // means that the field was specified, -1 means it was unset,850 // and MaxPathLenZero being true mean that the field was851 // explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false852 // should be treated equivalent to -1 (unset).853 //854 // When generating a certificate, an unset pathLenConstraint855 // can be requested with either MaxPathLen == -1 or using the856 // zero value for both MaxPathLen and MaxPathLenZero.857 MaxPathLen int858 // MaxPathLenZero indicates that BasicConstraintsValid==true859 // and MaxPathLen==0 should be interpreted as an actual860 // maximum path length of zero. Otherwise, that combination is861 // interpreted as MaxPathLen not being set.862 MaxPathLenZero bool863864 SubjectKeyId []byte865 AuthorityKeyId []byte866867 // RFC 5280, 4.2.2.1 (Authority Information Access)868 OCSPServer []string869 IssuingCertificateURL []string870871 // Subject Alternate Name values. (Note that these values may not be valid872 // if invalid values were contained within a parsed certificate. For873 // example, an element of DNSNames may not be a valid DNS domain name.)874 DNSNames []string875 EmailAddresses []string876 IPAddresses []net.IP877 URIs []*url.URL878879 // Name constraints880 PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.881 PermittedDNSDomains []string882 ExcludedDNSDomains []string883 PermittedIPRanges []*net.IPNet884 ExcludedIPRanges []*net.IPNet885 PermittedEmailAddresses []string886 ExcludedEmailAddresses []string887 PermittedURIDomains []string888 ExcludedURIDomains []string889890 // CRL Distribution Points891 CRLDistributionPoints []string892893 // PolicyIdentifiers contains asn1.ObjectIdentifiers, the components894 // of which are limited to int32. If a certificate contains a policy which895 // cannot be represented by asn1.ObjectIdentifier, it will not be included in896 // PolicyIdentifiers, but will be present in Policies, which contains all parsed897 // policy OIDs.898 // See CreateCertificate for context about how this field and the Policies field899 // interact.900 PolicyIdentifiers []asn1.ObjectIdentifier901902 // Policies contains all policy identifiers included in the certificate.903 // See CreateCertificate for context about how this field and the PolicyIdentifiers field904 // interact.905 // In Go 1.22, encoding/gob cannot handle and ignores this field.906 Policies []OID907908 // InhibitAnyPolicy and InhibitAnyPolicyZero indicate the presence and value909 // of the inhibitAnyPolicy extension.910 //911 // The value of InhibitAnyPolicy indicates the number of additional912 // certificates in the path after this certificate that may use the913 // anyPolicy policy OID to indicate a match with any other policy.914 //915 // When parsing a certificate, a positive non-zero InhibitAnyPolicy means916 // that the field was specified, -1 means it was unset, and917 // InhibitAnyPolicyZero being true mean that the field was explicitly set to918 // zero. The case of InhibitAnyPolicy==0 with InhibitAnyPolicyZero==false919 // should be treated equivalent to -1 (unset).920 InhibitAnyPolicy int921 // InhibitAnyPolicyZero indicates that InhibitAnyPolicy==0 should be922 // interpreted as an actual maximum path length of zero. Otherwise, that923 // combination is interpreted as InhibitAnyPolicy not being set.924 InhibitAnyPolicyZero bool925926 // InhibitPolicyMapping and InhibitPolicyMappingZero indicate the presence927 // and value of the inhibitPolicyMapping field of the policyConstraints928 // extension.929 //930 // The value of InhibitPolicyMapping indicates the number of additional931 // certificates in the path after this certificate that may use policy932 // mapping.933 //934 // When parsing a certificate, a positive non-zero InhibitPolicyMapping935 // means that the field was specified, -1 means it was unset, and936 // InhibitPolicyMappingZero being true mean that the field was explicitly937 // set to zero. The case of InhibitPolicyMapping==0 with938 // InhibitPolicyMappingZero==false should be treated equivalent to -1939 // (unset).940 InhibitPolicyMapping int941 // InhibitPolicyMappingZero indicates that InhibitPolicyMapping==0 should be942 // interpreted as an actual maximum path length of zero. Otherwise, that943 // combination is interpreted as InhibitAnyPolicy not being set.944 InhibitPolicyMappingZero bool945946 // RequireExplicitPolicy and RequireExplicitPolicyZero indicate the presence947 // and value of the requireExplicitPolicy field of the policyConstraints948 // extension.949 //950 // The value of RequireExplicitPolicy indicates the number of additional951 // certificates in the path after this certificate before an explicit policy952 // is required for the rest of the path. When an explicit policy is required,953 // each subsequent certificate in the path must contain a required policy OID,954 // or a policy OID which has been declared as equivalent through the policy955 // mapping extension.956 //957 // When parsing a certificate, a positive non-zero RequireExplicitPolicy958 // means that the field was specified, -1 means it was unset, and959 // RequireExplicitPolicyZero being true mean that the field was explicitly960 // set to zero. The case of RequireExplicitPolicy==0 with961 // RequireExplicitPolicyZero==false should be treated equivalent to -1962 // (unset).963 RequireExplicitPolicy int964 // RequireExplicitPolicyZero indicates that RequireExplicitPolicy==0 should be965 // interpreted as an actual maximum path length of zero. Otherwise, that966 // combination is interpreted as InhibitAnyPolicy not being set.967 RequireExplicitPolicyZero bool968969 // PolicyMappings contains a list of policy mappings included in the certificate.970 PolicyMappings []PolicyMapping971}972973// PolicyMapping represents a policy mapping entry in the policyMappings extension.974type PolicyMapping struct {975 // IssuerDomainPolicy contains a policy OID the issuing certificate considers976 // equivalent to SubjectDomainPolicy in the subject certificate.977 IssuerDomainPolicy OID978 // SubjectDomainPolicy contains a OID the issuing certificate considers979 // equivalent to IssuerDomainPolicy in the subject certificate.980 SubjectDomainPolicy OID981}982983// ErrUnsupportedAlgorithm results from attempting to perform an operation that984// involves algorithms that are not currently implemented.985var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")986987// An InsecureAlgorithmError indicates that the [SignatureAlgorithm] used to988// generate the signature is not secure, and the signature has been rejected.989type InsecureAlgorithmError SignatureAlgorithm990991func (e InsecureAlgorithmError) Error() string {992 return fmt.Sprintf("x509: cannot verify signature: insecure algorithm %v", SignatureAlgorithm(e))993}994995// ConstraintViolationError results when a requested usage is not permitted by996// a certificate. For example: checking a signature when the public key isn't a997// certificate signing key.998type ConstraintViolationError struct{}9991000func (ConstraintViolationError) Error() string {1001 return "x509: invalid signature: parent certificate cannot sign this kind of certificate"1002}10031004func (c *Certificate) Equal(other *Certificate) bool {1005 if c == nil || other == nil {1006 return c == other1007 }1008 return bytes.Equal(c.Raw, other.Raw)1009}10101011func (c *Certificate) hasSANExtension() bool {1012 return oidInExtensions(oidExtensionSubjectAltName, c.Extensions)1013}10141015// CheckSignatureFrom verifies that the signature on c is a valid signature from parent.1016//1017// This is a low-level API that performs very limited checks, and not a full1018// path verifier. Most users should use [Certificate.Verify] instead.1019func (c *Certificate) CheckSignatureFrom(parent *Certificate) error {1020 // RFC 5280, 4.2.1.9:1021 // "If the basic constraints extension is not present in a version 31022 // certificate, or the extension is present but the cA boolean is not1023 // asserted, then the certified public key MUST NOT be used to verify1024 // certificate signatures."1025 if parent.Version == 3 && !parent.BasicConstraintsValid ||1026 parent.BasicConstraintsValid && !parent.IsCA {1027 return ConstraintViolationError{}1028 }10291030 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {1031 return ConstraintViolationError{}1032 }10331034 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {1035 return ErrUnsupportedAlgorithm1036 }10371038 return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature, parent.PublicKey, false)1039}10401041// CheckSignature verifies that signature is a valid signature over signed from1042// c's public key.1043//1044// This is a low-level API that performs no validity checks on the certificate.1045//1046// [MD5WithRSA] signatures are rejected, while [SHA1WithRSA] and [ECDSAWithSHA1]1047// signatures are currently accepted.1048func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error {1049 return checkSignature(algo, signed, signature, c.PublicKey, true)1050}10511052func (c *Certificate) hasNameConstraints() bool {1053 return oidInExtensions(oidExtensionNameConstraints, c.Extensions)1054}10551056func (c *Certificate) getSANExtension() []byte {1057 for _, e := range c.Extensions {1058 if e.Id.Equal(oidExtensionSubjectAltName) {1059 return e.Value1060 }1061 }1062 return nil1063}10641065func signaturePublicKeyAlgoMismatchError(expectedPubKeyAlgo PublicKeyAlgorithm, pubKey any) error {1066 return fmt.Errorf("x509: signature algorithm specifies an %s public key, but have public key of type %T", expectedPubKeyAlgo.String(), pubKey)1067}10681069func signatureMLDSAParametersMismatchError(expectedSigAlgo SignatureAlgorithm, pubKey *mldsa.PublicKey) error {1070 return fmt.Errorf("x509: signature algorithm specifies an ML-DSA public key with %s parameters, but have a public key with %s parameters", expectedSigAlgo, pubKey.Parameters())1071}10721073// checkSignature verifies that signature is a valid signature over signed from1074// a crypto.PublicKey.1075func checkSignature(algo SignatureAlgorithm, signed, signature []byte, publicKey crypto.PublicKey, allowSHA1 bool) (err error) {1076 var hashType crypto.Hash1077 var pubKeyAlgo PublicKeyAlgorithm10781079 for _, details := range signatureAlgorithmDetails {1080 if details.algo == algo {1081 hashType = details.hash1082 pubKeyAlgo = details.pubKeyAlgo1083 break1084 }1085 }10861087 switch hashType {1088 case crypto.Hash(0):1089 if pubKeyAlgo != Ed25519 && pubKeyAlgo != MLDSA {1090 return ErrUnsupportedAlgorithm1091 }1092 case crypto.MD5:1093 return InsecureAlgorithmError(algo)1094 case crypto.SHA1:1095 // SHA-1 signatures are only allowed for CRLs and CSRs.1096 if !allowSHA1 {1097 return InsecureAlgorithmError(algo)1098 }1099 fallthrough1100 default:1101 if !hashType.Available() {1102 return ErrUnsupportedAlgorithm1103 }1104 h := hashType.New()1105 h.Write(signed)1106 signed = h.Sum(nil)1107 }11081109 switch pub := publicKey.(type) {1110 case *rsa.PublicKey:1111 if pubKeyAlgo != RSA {1112 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)1113 }1114 if algo.isRSAPSS() {1115 return rsa.VerifyPSS(pub, hashType, signed, signature, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})1116 } else {1117 return rsa.VerifyPKCS1v15(pub, hashType, signed, signature)1118 }1119 case *ecdsa.PublicKey:1120 if pubKeyAlgo != ECDSA {1121 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)1122 }1123 if !ecdsa.VerifyASN1(pub, signed, signature) {1124 return errors.New("x509: ECDSA verification failure")1125 }1126 return1127 case ed25519.PublicKey:1128 if pubKeyAlgo != Ed25519 {1129 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)1130 }1131 if !ed25519.Verify(pub, signed, signature) {1132 return errors.New("x509: Ed25519 verification failure")1133 }1134 return1135 case *mldsa.PublicKey:1136 if pubKeyAlgo != MLDSA {1137 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)1138 }1139 switch pub.Parameters() {1140 case mldsa.MLDSA44():1141 if algo != MLDSA44 {1142 return signatureMLDSAParametersMismatchError(algo, pub)1143 }1144 case mldsa.MLDSA65():1145 if algo != MLDSA65 {1146 return signatureMLDSAParametersMismatchError(algo, pub)1147 }1148 case mldsa.MLDSA87():1149 if algo != MLDSA87 {1150 return signatureMLDSAParametersMismatchError(algo, pub)1151 }1152 default:1153 return fmt.Errorf("x509: unknown ML-DSA parameters: %s", pub.Parameters())1154 }1155 if err := mldsa.Verify(pub, signed, signature, nil); err != nil {1156 return fmt.Errorf("x509: ML-DSA verification failure: %w", err)1157 }1158 return1159 }1160 return ErrUnsupportedAlgorithm1161}11621163// CheckCRLSignature checks that the signature in crl is from c.1164//1165// Deprecated: Use [RevocationList.CheckSignatureFrom] instead.1166func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error {1167 algo := getSignatureAlgorithmFromAI(crl.SignatureAlgorithm)1168 return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())1169}11701171type UnhandledCriticalExtension struct{}11721173func (h UnhandledCriticalExtension) Error() string {1174 return "x509: unhandled critical extension"1175}11761177type basicConstraints struct {1178 IsCA bool `asn1:"optional"`1179 MaxPathLen int `asn1:"optional,default:-1"`1180}11811182// RFC 5280 4.2.1.41183type policyInformation struct {1184 Policy asn1.ObjectIdentifier1185 // policyQualifiers omitted1186}11871188const (1189 nameTypeEmail = 11190 nameTypeDNS = 21191 nameTypeURI = 61192 nameTypeIP = 71193)11941195// RFC 5280, 4.2.2.11196type authorityInfoAccess struct {1197 Method asn1.ObjectIdentifier1198 Location asn1.RawValue1199}12001201// RFC 5280, 4.2.1.141202type distributionPoint struct {1203 DistributionPoint distributionPointName `asn1:"optional,tag:0"`1204 Reason asn1.BitString `asn1:"optional,tag:1"`1205 CRLIssuer asn1.RawValue `asn1:"optional,tag:2"`1206}12071208type distributionPointName struct {1209 FullName []asn1.RawValue `asn1:"optional,tag:0"`1210 RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`1211}12121213func reverseBitsInAByte(in byte) byte {1214 b1 := in>>4 | in<<41215 b2 := b1>>2&0x33 | b1<<2&0xcc1216 b3 := b2>>1&0x55 | b2<<1&0xaa1217 return b31218}12191220// asn1BitLength returns the bit-length of bitString by considering the1221// most-significant bit in a byte to be the "first" bit. This convention1222// matches ASN.1, but differs from almost everything else.1223func asn1BitLength(bitString []byte) int {1224 bitLen := len(bitString) * 812251226 for i := range bitString {1227 b := bitString[len(bitString)-i-1]12281229 for bit := uint(0); bit < 8; bit++ {1230 if (b>>bit)&1 == 1 {1231 return bitLen1232 }1233 bitLen--1234 }1235 }12361237 return 01238}12391240var (1241 oidExtensionSubjectKeyId = []int{2, 5, 29, 14}1242 oidExtensionKeyUsage = []int{2, 5, 29, 15}1243 oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37}1244 oidExtensionAuthorityKeyId = []int{2, 5, 29, 35}1245 oidExtensionBasicConstraints = []int{2, 5, 29, 19}1246 oidExtensionSubjectAltName = []int{2, 5, 29, 17}1247 oidExtensionCertificatePolicies = []int{2, 5, 29, 32}1248 oidExtensionNameConstraints = []int{2, 5, 29, 30}1249 oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31}1250 oidExtensionAuthorityInfoAccess = []int{1, 3, 6, 1, 5, 5, 7, 1, 1}1251 oidExtensionCRLNumber = []int{2, 5, 29, 20}1252 oidExtensionReasonCode = []int{2, 5, 29, 21}1253)12541255var (1256 oidAuthorityInfoAccessOcsp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}1257 oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}1258)12591260// oidInExtensions reports whether an extension with the given oid exists in1261// extensions.1262func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {1263 for _, e := range extensions {1264 if e.Id.Equal(oid) {1265 return true1266 }1267 }1268 return false1269}12701271// marshalSANs marshals a list of addresses into a the contents of an X.5091272// SubjectAlternativeName extension.1273func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL) (derBytes []byte, err error) {1274 var rawValues []asn1.RawValue1275 for _, name := range dnsNames {1276 if err := isIA5String(name); err != nil {1277 return nil, err1278 }1279 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeDNS, Class: 2, Bytes: []byte(name)})1280 }1281 for _, email := range emailAddresses {1282 if err := isIA5String(email); err != nil {1283 return nil, err1284 }1285 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeEmail, Class: 2, Bytes: []byte(email)})1286 }1287 for _, rawIP := range ipAddresses {1288 // If possible, we always want to encode IPv4 addresses in 4 bytes.1289 ip := rawIP.To4()1290 if ip == nil {1291 ip = rawIP1292 }1293 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeIP, Class: 2, Bytes: ip})1294 }1295 for _, uri := range uris {1296 uriStr := uri.String()1297 if err := isIA5String(uriStr); err != nil {1298 return nil, err1299 }1300 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeURI, Class: 2, Bytes: []byte(uriStr)})1301 }1302 return asn1.Marshal(rawValues)1303}13041305func isIA5String(s string) error {1306 for _, r := range s {1307 // Per RFC5280 "IA5String is limited to the set of ASCII characters"1308 if r > unicode.MaxASCII {1309 return fmt.Errorf("x509: %q cannot be encoded as an IA5String", s)1310 }1311 }13121313 return nil1314}13151316var x509usepolicies = godebug.New("x509usepolicies")13171318func buildCertExtensions(template *Certificate, subjectIsEmpty bool, authorityKeyId []byte, subjectKeyId []byte) (ret []pkix.Extension, err error) {1319 ret = make([]pkix.Extension, 10 /* maximum number of elements. */)1320 n := 013211322 if template.KeyUsage != 0 &&1323 !oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) {1324 ret[n], err = marshalKeyUsage(template.KeyUsage)1325 if err != nil {1326 return nil, err1327 }1328 n++1329 }13301331 if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) &&1332 !oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) {1333 ret[n], err = marshalExtKeyUsage(template.ExtKeyUsage, template.UnknownExtKeyUsage)1334 if err != nil {1335 return nil, err1336 }1337 n++1338 }13391340 if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) {1341 ret[n], err = marshalBasicConstraints(template.IsCA, template.MaxPathLen, template.MaxPathLenZero)1342 if err != nil {1343 return nil, err1344 }1345 n++1346 }13471348 if len(subjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) {1349 ret[n].Id = oidExtensionSubjectKeyId1350 ret[n].Value, err = asn1.Marshal(subjectKeyId)1351 if err != nil {1352 return1353 }1354 n++1355 }13561357 if len(authorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) {1358 ret[n].Id = oidExtensionAuthorityKeyId1359 ret[n].Value, err = asn1.Marshal(authKeyId{authorityKeyId})1360 if err != nil {1361 return1362 }1363 n++1364 }13651366 if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) &&1367 !oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) {1368 ret[n].Id = oidExtensionAuthorityInfoAccess1369 var aiaValues []authorityInfoAccess1370 for _, name := range template.OCSPServer {1371 aiaValues = append(aiaValues, authorityInfoAccess{1372 Method: oidAuthorityInfoAccessOcsp,1373 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},1374 })1375 }1376 for _, name := range template.IssuingCertificateURL {1377 aiaValues = append(aiaValues, authorityInfoAccess{1378 Method: oidAuthorityInfoAccessIssuers,1379 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},1380 })1381 }1382 ret[n].Value, err = asn1.Marshal(aiaValues)1383 if err != nil {1384 return1385 }1386 n++1387 }13881389 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&1390 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {1391 ret[n].Id = oidExtensionSubjectAltName1392 // From RFC 5280, Section 4.2.1.6:1393 // “If the subject field contains an empty sequence ... then1394 // subjectAltName extension ... is marked as critical”1395 ret[n].Critical = subjectIsEmpty1396 ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)1397 if err != nil {1398 return1399 }1400 n++1401 }14021403 usePolicies := x509usepolicies.Value() != "0"1404 if ((!usePolicies && len(template.PolicyIdentifiers) > 0) || (usePolicies && len(template.Policies) > 0)) &&1405 !oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) {1406 ret[n], err = marshalCertificatePolicies(template.Policies, template.PolicyIdentifiers)1407 if err != nil {1408 return nil, err1409 }1410 n++1411 }14121413 if (len(template.PermittedDNSDomains) > 0 || len(template.ExcludedDNSDomains) > 0 ||1414 len(template.PermittedIPRanges) > 0 || len(template.ExcludedIPRanges) > 0 ||1415 len(template.PermittedEmailAddresses) > 0 || len(template.ExcludedEmailAddresses) > 0 ||1416 len(template.PermittedURIDomains) > 0 || len(template.ExcludedURIDomains) > 0) &&1417 !oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) {1418 ret[n].Id = oidExtensionNameConstraints1419 ret[n].Critical = template.PermittedDNSDomainsCritical14201421 ipAndMask := func(ipNet *net.IPNet) ([]byte, error) {1422 maskedIP := ipNet.IP.Mask(ipNet.Mask)1423 // This is extremely unlikely to actually happen, but lets save people from doing something they1424 // probably shouldn't.1425 if len(maskedIP) == net.IPv6len && maskedIP.To4() != nil {1426 return nil, errors.New("x509: IP constraint contained IPv4-mapped IPv6 address with a IPv6 mask")1427 }1428 ipAndMask := make([]byte, 0, len(maskedIP)+len(ipNet.Mask))1429 ipAndMask = append(ipAndMask, maskedIP...)1430 ipAndMask = append(ipAndMask, ipNet.Mask...)1431 return ipAndMask, nil1432 }14331434 serialiseConstraints := func(dns []string, ips []*net.IPNet, emails []string, uriDomains []string) (der []byte, err error) {1435 var b cryptobyte.Builder14361437 for _, name := range dns {1438 if err = isIA5String(name); err != nil {1439 return nil, err1440 }14411442 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {1443 b.AddASN1(cryptobyte_asn1.Tag(2).ContextSpecific(), func(b *cryptobyte.Builder) {1444 b.AddBytes([]byte(name))1445 })1446 })1447 }14481449 for _, ipNet := range ips {1450 encodedIPNet, err := ipAndMask(ipNet)1451 if err != nil {1452 return nil, err1453 }1454 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {1455 b.AddASN1(cryptobyte_asn1.Tag(7).ContextSpecific(), func(b *cryptobyte.Builder) {1456 b.AddBytes(encodedIPNet)1457 })1458 })1459 }14601461 for _, email := range emails {1462 if err = isIA5String(email); err != nil {1463 return nil, err1464 }14651466 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {1467 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific(), func(b *cryptobyte.Builder) {1468 b.AddBytes([]byte(email))1469 })1470 })1471 }14721473 for _, uriDomain := range uriDomains {1474 if err = isIA5String(uriDomain); err != nil {1475 return nil, err1476 }14771478 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {1479 b.AddASN1(cryptobyte_asn1.Tag(6).ContextSpecific(), func(b *cryptobyte.Builder) {1480 b.AddBytes([]byte(uriDomain))1481 })1482 })1483 }14841485 return b.Bytes()1486 }14871488 permitted, err := serialiseConstraints(template.PermittedDNSDomains, template.PermittedIPRanges, template.PermittedEmailAddresses, template.PermittedURIDomains)1489 if err != nil {1490 return nil, err1491 }14921493 excluded, err := serialiseConstraints(template.ExcludedDNSDomains, template.ExcludedIPRanges, template.ExcludedEmailAddresses, template.ExcludedURIDomains)1494 if err != nil {1495 return nil, err1496 }14971498 var b cryptobyte.Builder1499 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {1500 if len(permitted) > 0 {1501 b.AddASN1(cryptobyte_asn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {1502 b.AddBytes(permitted)1503 })1504 }15051506 if len(excluded) > 0 {1507 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {1508 b.AddBytes(excluded)1509 })1510 }1511 })15121513 ret[n].Value, err = b.Bytes()1514 if err != nil {1515 return nil, err1516 }1517 n++1518 }15191520 if len(template.CRLDistributionPoints) > 0 &&1521 !oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) {1522 ret[n].Id = oidExtensionCRLDistributionPoints15231524 var crlDp []distributionPoint1525 for _, name := range template.CRLDistributionPoints {1526 dp := distributionPoint{1527 DistributionPoint: distributionPointName{1528 FullName: []asn1.RawValue{1529 {Tag: 6, Class: 2, Bytes: []byte(name)},1530 },1531 },1532 }1533 crlDp = append(crlDp, dp)1534 }15351536 ret[n].Value, err = asn1.Marshal(crlDp)1537 if err != nil {1538 return1539 }1540 n++1541 }15421543 // Adding another extension here? Remember to update the maximum number1544 // of elements in the make() at the top of the function and the list of1545 // template fields used in CreateCertificate documentation.15461547 return append(ret[:n], template.ExtraExtensions...), nil1548}15491550func marshalKeyUsage(ku KeyUsage) (pkix.Extension, error) {1551 ext := pkix.Extension{Id: oidExtensionKeyUsage, Critical: true}15521553 var a [2]byte1554 a[0] = reverseBitsInAByte(byte(ku))1555 a[1] = reverseBitsInAByte(byte(ku >> 8))15561557 l := 11558 if a[1] != 0 {1559 l = 21560 }15611562 bitString := a[:l]1563 var err error1564 ext.Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)})1565 return ext, err1566}15671568func marshalExtKeyUsage(extUsages []ExtKeyUsage, unknownUsages []asn1.ObjectIdentifier) (pkix.Extension, error) {1569 ext := pkix.Extension{Id: oidExtensionExtendedKeyUsage}15701571 oids := make([]asn1.ObjectIdentifier, len(extUsages)+len(unknownUsages))1572 for i, u := range extUsages {1573 if oid, ok := oidFromExtKeyUsage(u); ok {1574 oids[i] = oid1575 } else {1576 return ext, errors.New("x509: unknown extended key usage")1577 }1578 }15791580 copy(oids[len(extUsages):], unknownUsages)15811582 var err error1583 ext.Value, err = asn1.Marshal(oids)1584 return ext, err1585}15861587func marshalBasicConstraints(isCA bool, maxPathLen int, maxPathLenZero bool) (pkix.Extension, error) {1588 ext := pkix.Extension{Id: oidExtensionBasicConstraints, Critical: true}1589 // Leaving MaxPathLen as zero indicates that no maximum path1590 // length is desired, unless MaxPathLenZero is set. A value of1591 // -1 causes encoding/asn1 to omit the value as desired.1592 if maxPathLen == 0 && !maxPathLenZero {1593 maxPathLen = -11594 }1595 var err error1596 ext.Value, err = asn1.Marshal(basicConstraints{isCA, maxPathLen})1597 return ext, err1598}15991600func marshalCertificatePolicies(policies []OID, policyIdentifiers []asn1.ObjectIdentifier) (pkix.Extension, error) {1601 ext := pkix.Extension{Id: oidExtensionCertificatePolicies}16021603 b := cryptobyte.NewBuilder(make([]byte, 0, 128))1604 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(child *cryptobyte.Builder) {1605 if x509usepolicies.Value() != "0" {1606 x509usepolicies.IncNonDefault()1607 for _, v := range policies {1608 child.AddASN1(cryptobyte_asn1.SEQUENCE, func(child *cryptobyte.Builder) {1609 child.AddASN1(cryptobyte_asn1.OBJECT_IDENTIFIER, func(child *cryptobyte.Builder) {1610 if len(v.der) == 0 {1611 child.SetError(errors.New("invalid policy object identifier"))1612 return1613 }1614 child.AddBytes(v.der)1615 })1616 })1617 }1618 } else {1619 for _, v := range policyIdentifiers {1620 child.AddASN1(cryptobyte_asn1.SEQUENCE, func(child *cryptobyte.Builder) {1621 child.AddASN1ObjectIdentifier(v)1622 })1623 }1624 }1625 })16261627 var err error1628 ext.Value, err = b.Bytes()1629 return ext, err1630}16311632func buildCSRExtensions(template *CertificateRequest) ([]pkix.Extension, error) {1633 var ret []pkix.Extension16341635 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&1636 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {1637 sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)1638 if err != nil {1639 return nil, err1640 }16411642 ret = append(ret, pkix.Extension{1643 Id: oidExtensionSubjectAltName,1644 Value: sanBytes,1645 })1646 }16471648 return append(ret, template.ExtraExtensions...), nil1649}16501651func subjectBytes(cert *Certificate) ([]byte, error) {1652 if len(cert.RawSubject) > 0 {1653 return cert.RawSubject, nil1654 }16551656 return asn1.Marshal(cert.Subject.ToRDNSequence())1657}16581659// signingParamsForKey returns the signature algorithm and its Algorithm1660// Identifier to use for signing, based on the key type. If sigAlgo is not zero1661// then it overrides the default.1662func signingParamsForKey(key crypto.Signer, sigAlgo SignatureAlgorithm) (SignatureAlgorithm, pkix.AlgorithmIdentifier, error) {1663 var ai pkix.AlgorithmIdentifier1664 var pubType PublicKeyAlgorithm1665 var defaultAlgo SignatureAlgorithm16661667 switch pub := key.Public().(type) {1668 case *rsa.PublicKey:1669 pubType = RSA1670 defaultAlgo = SHA256WithRSA16711672 case *ecdsa.PublicKey:1673 pubType = ECDSA1674 switch pub.Curve {1675 case elliptic.P224(), elliptic.P256():1676 defaultAlgo = ECDSAWithSHA2561677 case elliptic.P384():1678 defaultAlgo = ECDSAWithSHA3841679 case elliptic.P521():1680 defaultAlgo = ECDSAWithSHA5121681 default:1682 return 0, ai, errors.New("x509: unsupported elliptic curve")1683 }16841685 case ed25519.PublicKey:1686 pubType = Ed255191687 defaultAlgo = PureEd2551916881689 case *mldsa.PublicKey:1690 pubType = MLDSA1691 switch pub.Parameters() {1692 case mldsa.MLDSA44():1693 defaultAlgo = MLDSA441694 case mldsa.MLDSA65():1695 defaultAlgo = MLDSA651696 case mldsa.MLDSA87():1697 defaultAlgo = MLDSA871698 default:1699 return 0, ai, fmt.Errorf("x509: unsupported ML-DSA parameters: %s", pub.Parameters())1700 }17011702 default:1703 return 0, ai, errors.New("x509: only RSA, ECDSA, ML-DSA and Ed25519 keys supported")1704 }17051706 if sigAlgo == 0 {1707 sigAlgo = defaultAlgo1708 }17091710 for _, details := range signatureAlgorithmDetails {1711 if details.algo == sigAlgo {1712 if details.pubKeyAlgo != pubType {1713 return 0, ai, errors.New("x509: requested SignatureAlgorithm does not match private key type")1714 }1715 if pubType == MLDSA && sigAlgo != defaultAlgo {1716 return 0, ai, errors.New("x509: requested SignatureAlgorithm does not match ML-DSA parameters")1717 }1718 if details.hash == crypto.MD5 {1719 return 0, ai, errors.New("x509: signing with MD5 is not supported")1720 }17211722 return sigAlgo, pkix.AlgorithmIdentifier{1723 Algorithm: details.oid,1724 Parameters: details.params,1725 }, nil1726 }1727 }17281729 return 0, ai, errors.New("x509: unknown SignatureAlgorithm")1730}17311732func signTBS(tbs []byte, key crypto.Signer, sigAlg SignatureAlgorithm, rand io.Reader) ([]byte, error) {1733 hashFunc := sigAlg.hashFunc()17341735 var signerOpts crypto.SignerOpts = hashFunc1736 if sigAlg.isRSAPSS() {1737 signerOpts = &rsa.PSSOptions{1738 SaltLength: rsa.PSSSaltLengthEqualsHash,1739 Hash: hashFunc,1740 }1741 }17421743 signature, err := crypto.SignMessage(key, rand, tbs, signerOpts)1744 if err != nil {1745 return nil, err1746 }17471748 // Check the signature to ensure the crypto.Signer behaved correctly.1749 if err := checkSignature(sigAlg, tbs, signature, key.Public(), true); err != nil {1750 return nil, fmt.Errorf("x509: signature returned by signer is invalid: %w", err)1751 }17521753 return signature, nil1754}17551756// emptyASN1Subject is the ASN.1 DER encoding of an empty Subject, which is1757// just an empty SEQUENCE.1758var emptyASN1Subject = []byte{0x30, 0}17591760// CreateCertificate creates a new X.509 v3 certificate based on a template.1761// The following members of template are currently used:1762//1763// - AuthorityKeyId1764// - BasicConstraintsValid1765// - CRLDistributionPoints1766// - DNSNames1767// - EmailAddresses1768// - ExcludedDNSDomains1769// - ExcludedEmailAddresses1770// - ExcludedIPRanges1771// - ExcludedURIDomains1772// - ExtKeyUsage1773// - ExtraExtensions1774// - IPAddresses1775// - IsCA1776// - IssuingCertificateURL1777// - KeyUsage1778// - MaxPathLen1779// - MaxPathLenZero1780// - NotAfter1781// - NotBefore1782// - OCSPServer1783// - PermittedDNSDomains1784// - PermittedDNSDomainsCritical1785// - PermittedEmailAddresses1786// - PermittedIPRanges1787// - PermittedURIDomains1788// - PolicyIdentifiers (see note below)1789// - Policies (see note below)1790// - SerialNumber1791// - SignatureAlgorithm1792// - Subject1793// - SubjectKeyId1794// - URIs1795// - UnknownExtKeyUsage1796//1797// The certificate is signed by parent. If parent is equal to template then the1798// certificate is self-signed. The parameter pub is the public key of the1799// certificate to be generated and priv is the private key of the signer.1800//1801// The returned slice is the certificate in DER encoding.1802//1803// The currently supported key types are *rsa.PublicKey, *ecdsa.PublicKey,1804// ed25519.PublicKey, and *mldsa.PublicKey. pub must be a supported key type,1805// and priv must be a crypto.Signer or crypto.MessageSigner with a supported1806// public key.1807//1808// The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any,1809// unless the resulting certificate is self-signed. Otherwise the value from1810// template will be used.1811//1812// If SubjectKeyId from template is empty and the template is a CA, SubjectKeyId1813// will be generated from the hash of the public key.1814//1815// If template.SerialNumber is nil, a serial number will be generated which1816// conforms to RFC 5280, Section 4.1.2.2 using entropy from rand.1817//1818// The PolicyIdentifier and Policies fields can both be used to marshal certificate1819// policy OIDs. By default, only the Policies is marshaled, but if the1820// GODEBUG setting "x509usepolicies" has the value "0", the PolicyIdentifiers field will1821// be marshaled instead of the Policies field. This changed in Go 1.24. The Policies field can1822// be used to marshal policy OIDs which have components that are larger than 311823// bits.1824//1825// IP addresses in IPAddresses which are in their IPv4-mapped IPv6 form will always be encoded1826// in their IPv4 form.1827func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv any) ([]byte, error) {1828 key, ok := priv.(crypto.Signer)1829 if !ok {1830 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")1831 }18321833 serialNumber := template.SerialNumber1834 if serialNumber == nil {1835 // Generate a serial number following RFC 5280, Section 4.1.2.2 if one1836 // is not provided. The serial number must be positive and at most 201837 // octets *when encoded*.1838 serialBytes := make([]byte, 20)1839 if _, err := io.ReadFull(rand, serialBytes); err != nil {1840 return nil, err1841 }1842 // If the top bit is set, the serial will be padded with a leading zero1843 // byte during encoding, so that it's not interpreted as a negative1844 // integer. This padding would make the serial 21 octets so we clear the1845 // top bit to ensure the correct length in all cases.1846 serialBytes[0] &= 0b0111_11111847 serialNumber = new(big.Int).SetBytes(serialBytes)1848 }18491850 // RFC 5280 Section 4.1.2.2: serial number must be positive1851 //1852 // We _should_ also restrict serials to <= 20 octets, but it turns out a lot of people1853 // get this wrong, in part because the encoding can itself alter the length of the1854 // serial. For now we accept these non-conformant serials.1855 if serialNumber.Sign() == -1 {1856 return nil, errors.New("x509: serial number must be positive")1857 }18581859 if template.BasicConstraintsValid && template.MaxPathLen < -1 {1860 return nil, errors.New("x509: invalid MaxPathLen, must be greater or equal to -1")1861 }18621863 if template.BasicConstraintsValid && !template.IsCA && template.MaxPathLen != -1 && (template.MaxPathLen != 0 || template.MaxPathLenZero) {1864 return nil, errors.New("x509: only CAs are allowed to specify MaxPathLen")1865 }18661867 signatureAlgorithm, algorithmIdentifier, err := signingParamsForKey(key, template.SignatureAlgorithm)1868 if err != nil {1869 return nil, err1870 }18711872 publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub)1873 if err != nil {1874 return nil, err1875 }1876 if getPublicKeyAlgorithmFromOID(publicKeyAlgorithm.Algorithm) == UnknownPublicKeyAlgorithm {1877 return nil, fmt.Errorf("x509: unsupported public key type: %T", pub)1878 }18791880 asn1Issuer, err := subjectBytes(parent)1881 if err != nil {1882 return nil, err1883 }18841885 asn1Subject, err := subjectBytes(template)1886 if err != nil {1887 return nil, err1888 }18891890 authorityKeyId := template.AuthorityKeyId1891 if !bytes.Equal(asn1Issuer, asn1Subject) && len(parent.SubjectKeyId) > 0 {1892 authorityKeyId = parent.SubjectKeyId1893 }18941895 subjectKeyId := template.SubjectKeyId1896 if len(subjectKeyId) == 0 && template.IsCA {1897 if x509sha256skid.Value() == "0" {1898 x509sha256skid.IncNonDefault()1899 // SubjectKeyId generated using method 1 in RFC 5280, Section 4.2.1.2:1900 // (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the1901 // value of the BIT STRING subjectPublicKey (excluding the tag,1902 // length, and number of unused bits).1903 h := sha1.Sum(publicKeyBytes)1904 subjectKeyId = h[:]1905 } else {1906 // SubjectKeyId generated using method 1 in RFC 7093, Section 2:1907 // 1) The keyIdentifier is composed of the leftmost 160-bits of the1908 // SHA-256 hash of the value of the BIT STRING subjectPublicKey1909 // (excluding the tag, length, and number of unused bits).1910 h := sha256.Sum256(publicKeyBytes)1911 subjectKeyId = h[:20]1912 }1913 }19141915 // Check that the signer's public key matches the private key, if available.1916 type privateKey interface {1917 Equal(crypto.PublicKey) bool1918 }1919 if privPub, ok := key.Public().(privateKey); !ok {1920 return nil, errors.New("x509: internal error: supported public key does not implement Equal")1921 } else if parent.PublicKey != nil && !privPub.Equal(parent.PublicKey) {1922 return nil, errors.New("x509: provided PrivateKey doesn't match parent's PublicKey")1923 }19241925 extensions, err := buildCertExtensions(template, bytes.Equal(asn1Subject, emptyASN1Subject), authorityKeyId, subjectKeyId)1926 if err != nil {1927 return nil, err1928 }19291930 encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}1931 c := tbsCertificate{1932 Version: 2,1933 SerialNumber: serialNumber,1934 SignatureAlgorithm: algorithmIdentifier,1935 Issuer: asn1.RawValue{FullBytes: asn1Issuer},1936 Validity: validity{template.NotBefore.UTC(), template.NotAfter.UTC()},1937 Subject: asn1.RawValue{FullBytes: asn1Subject},1938 PublicKey: publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},1939 Extensions: extensions,1940 }19411942 tbsCertContents, err := asn1.Marshal(c)1943 if err != nil {1944 return nil, err1945 }1946 c.Raw = tbsCertContents19471948 signature, err := signTBS(tbsCertContents, key, signatureAlgorithm, rand)1949 if err != nil {1950 return nil, err1951 }19521953 return asn1.Marshal(certificate{1954 TBSCertificate: c,1955 SignatureAlgorithm: algorithmIdentifier,1956 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},1957 })1958}19591960var x509sha256skid = godebug.New("x509sha256skid")19611962// pemCRLPrefix is the magic string that indicates that we have a PEM encoded1963// CRL.1964var pemCRLPrefix = []byte("-----BEGIN X509 CRL")19651966// pemType is the type of a PEM encoded CRL.1967var pemType = "X509 CRL"19681969// ParseCRL parses a CRL from the given bytes. It's often the case that PEM1970// encoded CRLs will appear where they should be DER encoded, so this function1971// will transparently handle PEM encoding as long as there isn't any leading1972// garbage.1973//1974// Deprecated: Use [ParseRevocationList] instead.1975func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) {1976 if bytes.HasPrefix(crlBytes, pemCRLPrefix) {1977 block, _ := pem.Decode(crlBytes)1978 if block != nil && block.Type == pemType {1979 crlBytes = block.Bytes1980 }1981 }1982 return ParseDERCRL(crlBytes)1983}19841985// ParseDERCRL parses a DER encoded CRL from the given bytes.1986//1987// Deprecated: Use [ParseRevocationList] instead.1988func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) {1989 certList := new(pkix.CertificateList)1990 if rest, err := asn1.Unmarshal(derBytes, certList); err != nil {1991 return nil, err1992 } else if len(rest) != 0 {1993 return nil, errors.New("x509: trailing data after CRL")1994 }1995 return certList, nil1996}19971998// CreateCRL returns a DER encoded CRL, signed by this Certificate, that1999// contains the given list of revoked certificates.2000//
Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.