x509.go 98 KB

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