x509.go 82 KB

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