x509.go 105 KB

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