x509.go 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526
  1. /*
  2. Copyright Suzhou Tongji Fintech Research Institute 2017 All Rights Reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. // crypto/x509 add sm2 support
  14. package sm2
  15. import (
  16. "bytes"
  17. "crypto"
  18. "crypto/dsa"
  19. "crypto/ecdsa"
  20. "crypto/elliptic"
  21. "crypto/md5"
  22. "crypto/rand"
  23. "crypto/rsa"
  24. "crypto/sha1"
  25. "crypto/sha256"
  26. "crypto/sha512"
  27. "crypto/x509/pkix"
  28. "encoding/asn1"
  29. "encoding/pem"
  30. "errors"
  31. "fmt"
  32. "hash"
  33. "io"
  34. "io/ioutil"
  35. "math/big"
  36. "net"
  37. "os"
  38. "strconv"
  39. "time"
  40. "github.com/tjfoc/gmsm/sm3"
  41. "golang.org/x/crypto/ripemd160"
  42. "golang.org/x/crypto/sha3"
  43. )
  44. // pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
  45. // in RFC 3280.
  46. type pkixPublicKey struct {
  47. Algo pkix.AlgorithmIdentifier
  48. BitString asn1.BitString
  49. }
  50. // ParsePKIXPublicKey parses a DER encoded public key. These values are
  51. // typically found in PEM blocks with "BEGIN PUBLIC KEY".
  52. //
  53. // Supported key types include RSA, DSA, and ECDSA. Unknown key
  54. // types result in an error.
  55. //
  56. // On success, pub will be of type *rsa.PublicKey, *dsa.PublicKey,
  57. // or *ecdsa.PublicKey.
  58. func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) {
  59. var pki publicKeyInfo
  60. if rest, err := asn1.Unmarshal(derBytes, &pki); err != nil {
  61. return nil, err
  62. } else if len(rest) != 0 {
  63. return nil, errors.New("x509: trailing data after ASN.1 of public-key")
  64. }
  65. algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm)
  66. if algo == UnknownPublicKeyAlgorithm {
  67. return nil, errors.New("x509: unknown public key algorithm")
  68. }
  69. return parsePublicKey(algo, &pki)
  70. }
  71. func marshalPublicKey(pub interface{}) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) {
  72. switch pub := pub.(type) {
  73. case *rsa.PublicKey:
  74. publicKeyBytes, err = asn1.Marshal(rsaPublicKey{
  75. N: pub.N,
  76. E: pub.E,
  77. })
  78. if err != nil {
  79. return nil, pkix.AlgorithmIdentifier{}, err
  80. }
  81. publicKeyAlgorithm.Algorithm = oidPublicKeyRSA
  82. // This is a NULL parameters value which is required by
  83. // https://tools.ietf.org/html/rfc3279#section-2.3.1.
  84. publicKeyAlgorithm.Parameters = asn1.RawValue{
  85. Tag: 5,
  86. }
  87. case *ecdsa.PublicKey:
  88. publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
  89. oid, ok := oidFromNamedCurve(pub.Curve)
  90. if !ok {
  91. return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
  92. }
  93. publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
  94. var paramBytes []byte
  95. paramBytes, err = asn1.Marshal(oid)
  96. if err != nil {
  97. return
  98. }
  99. publicKeyAlgorithm.Parameters.FullBytes = paramBytes
  100. case *PublicKey:
  101. publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
  102. oid, ok := oidFromNamedCurve(pub.Curve)
  103. if !ok {
  104. return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported SM2 curve")
  105. }
  106. publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
  107. var paramBytes []byte
  108. paramBytes, err = asn1.Marshal(oid)
  109. if err != nil {
  110. return
  111. }
  112. publicKeyAlgorithm.Parameters.FullBytes = paramBytes
  113. default:
  114. return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: only RSA and ECDSA(SM2) public keys supported")
  115. }
  116. return publicKeyBytes, publicKeyAlgorithm, nil
  117. }
  118. // MarshalPKIXPublicKey serialises a public key to DER-encoded PKIX format.
  119. func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
  120. var publicKeyBytes []byte
  121. var publicKeyAlgorithm pkix.AlgorithmIdentifier
  122. var err error
  123. if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
  124. return nil, err
  125. }
  126. pkix := pkixPublicKey{
  127. Algo: publicKeyAlgorithm,
  128. BitString: asn1.BitString{
  129. Bytes: publicKeyBytes,
  130. BitLength: 8 * len(publicKeyBytes),
  131. },
  132. }
  133. ret, _ := asn1.Marshal(pkix)
  134. return ret, nil
  135. }
  136. // These structures reflect the ASN.1 structure of X.509 certificates.:
  137. type certificate struct {
  138. Raw asn1.RawContent
  139. TBSCertificate tbsCertificate
  140. SignatureAlgorithm pkix.AlgorithmIdentifier
  141. SignatureValue asn1.BitString
  142. }
  143. type tbsCertificate struct {
  144. Raw asn1.RawContent
  145. Version int `asn1:"optional,explicit,default:0,tag:0"`
  146. SerialNumber *big.Int
  147. SignatureAlgorithm pkix.AlgorithmIdentifier
  148. Issuer asn1.RawValue
  149. Validity validity
  150. Subject asn1.RawValue
  151. PublicKey publicKeyInfo
  152. UniqueId asn1.BitString `asn1:"optional,tag:1"`
  153. SubjectUniqueId asn1.BitString `asn1:"optional,tag:2"`
  154. Extensions []pkix.Extension `asn1:"optional,explicit,tag:3"`
  155. }
  156. type dsaAlgorithmParameters struct {
  157. P, Q, G *big.Int
  158. }
  159. type dsaSignature struct {
  160. R, S *big.Int
  161. }
  162. type ecdsaSignature dsaSignature
  163. type validity struct {
  164. NotBefore, NotAfter time.Time
  165. }
  166. type publicKeyInfo struct {
  167. Raw asn1.RawContent
  168. Algorithm pkix.AlgorithmIdentifier
  169. PublicKey asn1.BitString
  170. }
  171. // RFC 5280, 4.2.1.1
  172. type authKeyId struct {
  173. Id []byte `asn1:"optional,tag:0"`
  174. }
  175. type SignatureAlgorithm int
  176. type Hash uint
  177. func init() {
  178. RegisterHash(MD4, nil)
  179. RegisterHash(MD5, md5.New)
  180. RegisterHash(SHA1, sha1.New)
  181. RegisterHash(SHA224, sha256.New224)
  182. RegisterHash(SHA256, sha256.New)
  183. RegisterHash(SHA384, sha512.New384)
  184. RegisterHash(SHA512, sha512.New)
  185. RegisterHash(MD5SHA1, nil)
  186. RegisterHash(RIPEMD160, ripemd160.New)
  187. RegisterHash(SHA3_224, sha3.New224)
  188. RegisterHash(SHA3_256, sha3.New256)
  189. RegisterHash(SHA3_384, sha3.New384)
  190. RegisterHash(SHA3_512, sha3.New512)
  191. RegisterHash(SHA512_224, sha512.New512_224)
  192. RegisterHash(SHA512_256, sha512.New512_256)
  193. RegisterHash(SM3, sm3.New)
  194. }
  195. // HashFunc simply returns the value of h so that Hash implements SignerOpts.
  196. func (h Hash) HashFunc() crypto.Hash {
  197. return crypto.Hash(h)
  198. }
  199. const (
  200. MD4 Hash = 1 + iota // import golang.org/x/crypto/md4
  201. MD5 // import crypto/md5
  202. SHA1 // import crypto/sha1
  203. SHA224 // import crypto/sha256
  204. SHA256 // import crypto/sha256
  205. SHA384 // import crypto/sha512
  206. SHA512 // import crypto/sha512
  207. MD5SHA1 // no implementation; MD5+SHA1 used for TLS RSA
  208. RIPEMD160 // import golang.org/x/crypto/ripemd160
  209. SHA3_224 // import golang.org/x/crypto/sha3
  210. SHA3_256 // import golang.org/x/crypto/sha3
  211. SHA3_384 // import golang.org/x/crypto/sha3
  212. SHA3_512 // import golang.org/x/crypto/sha3
  213. SHA512_224 // import crypto/sha512
  214. SHA512_256 // import crypto/sha512
  215. SM3
  216. maxHash
  217. )
  218. var digestSizes = []uint8{
  219. MD4: 16,
  220. MD5: 16,
  221. SHA1: 20,
  222. SHA224: 28,
  223. SHA256: 32,
  224. SHA384: 48,
  225. SHA512: 64,
  226. SHA512_224: 28,
  227. SHA512_256: 32,
  228. SHA3_224: 28,
  229. SHA3_256: 32,
  230. SHA3_384: 48,
  231. SHA3_512: 64,
  232. MD5SHA1: 36,
  233. RIPEMD160: 20,
  234. SM3: 32,
  235. }
  236. // Size returns the length, in bytes, of a digest resulting from the given hash
  237. // function. It doesn't require that the hash function in question be linked
  238. // into the program.
  239. func (h Hash) Size() int {
  240. if h > 0 && h < maxHash {
  241. return int(digestSizes[h])
  242. }
  243. panic("crypto: Size of unknown hash function")
  244. }
  245. var hashes = make([]func() hash.Hash, maxHash)
  246. // New returns a new hash.Hash calculating the given hash function. New panics
  247. // if the hash function is not linked into the binary.
  248. func (h Hash) New() hash.Hash {
  249. if h > 0 && h < maxHash {
  250. f := hashes[h]
  251. if f != nil {
  252. return f()
  253. }
  254. }
  255. panic("crypto: requested hash function #" + strconv.Itoa(int(h)) + " is unavailable")
  256. }
  257. // Available reports whether the given hash function is linked into the binary.
  258. func (h Hash) Available() bool {
  259. return h < maxHash && hashes[h] != nil
  260. }
  261. // RegisterHash registers a function that returns a new instance of the given
  262. // hash function. This is intended to be called from the init function in
  263. // packages that implement hash functions.
  264. func RegisterHash(h Hash, f func() hash.Hash) {
  265. if h >= maxHash {
  266. panic("crypto: RegisterHash of unknown hash function")
  267. }
  268. hashes[h] = f
  269. }
  270. const (
  271. UnknownSignatureAlgorithm SignatureAlgorithm = iota
  272. MD2WithRSA
  273. MD5WithRSA
  274. // SM3WithRSA reserve
  275. SHA1WithRSA
  276. SHA256WithRSA
  277. SHA384WithRSA
  278. SHA512WithRSA
  279. DSAWithSHA1
  280. DSAWithSHA256
  281. ECDSAWithSHA1
  282. ECDSAWithSHA256
  283. ECDSAWithSHA384
  284. ECDSAWithSHA512
  285. SHA256WithRSAPSS
  286. SHA384WithRSAPSS
  287. SHA512WithRSAPSS
  288. SM2WithSM3
  289. SM2WithSHA1
  290. SM2WithSHA256
  291. )
  292. func (algo SignatureAlgorithm) isRSAPSS() bool {
  293. switch algo {
  294. case SHA256WithRSAPSS, SHA384WithRSAPSS, SHA512WithRSAPSS:
  295. return true
  296. default:
  297. return false
  298. }
  299. }
  300. var algoName = [...]string{
  301. MD2WithRSA: "MD2-RSA",
  302. MD5WithRSA: "MD5-RSA",
  303. SHA1WithRSA: "SHA1-RSA",
  304. // SM3WithRSA: "SM3-RSA", reserve
  305. SHA256WithRSA: "SHA256-RSA",
  306. SHA384WithRSA: "SHA384-RSA",
  307. SHA512WithRSA: "SHA512-RSA",
  308. SHA256WithRSAPSS: "SHA256-RSAPSS",
  309. SHA384WithRSAPSS: "SHA384-RSAPSS",
  310. SHA512WithRSAPSS: "SHA512-RSAPSS",
  311. DSAWithSHA1: "DSA-SHA1",
  312. DSAWithSHA256: "DSA-SHA256",
  313. ECDSAWithSHA1: "ECDSA-SHA1",
  314. ECDSAWithSHA256: "ECDSA-SHA256",
  315. ECDSAWithSHA384: "ECDSA-SHA384",
  316. ECDSAWithSHA512: "ECDSA-SHA512",
  317. SM2WithSM3: "SM2-SM3",
  318. SM2WithSHA1: "SM2-SHA1",
  319. SM2WithSHA256: "SM2-SHA256",
  320. }
  321. func (algo SignatureAlgorithm) String() string {
  322. if 0 < algo && int(algo) < len(algoName) {
  323. return algoName[algo]
  324. }
  325. return strconv.Itoa(int(algo))
  326. }
  327. type PublicKeyAlgorithm int
  328. const (
  329. UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
  330. RSA
  331. DSA
  332. ECDSA
  333. )
  334. // OIDs for signature algorithms
  335. //
  336. // pkcs-1 OBJECT IDENTIFIER ::= {
  337. // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
  338. //
  339. //
  340. // RFC 3279 2.2.1 RSA Signature Algorithms
  341. //
  342. // md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 }
  343. //
  344. // md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }
  345. //
  346. // sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }
  347. //
  348. // dsaWithSha1 OBJECT IDENTIFIER ::= {
  349. // iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 }
  350. //
  351. // RFC 3279 2.2.3 ECDSA Signature Algorithm
  352. //
  353. // ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {
  354. // iso(1) member-body(2) us(840) ansi-x962(10045)
  355. // signatures(4) ecdsa-with-SHA1(1)}
  356. //
  357. //
  358. // RFC 4055 5 PKCS #1 Version 1.5
  359. //
  360. // sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
  361. //
  362. // sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
  363. //
  364. // sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
  365. //
  366. //
  367. // RFC 5758 3.1 DSA Signature Algorithms
  368. //
  369. // dsaWithSha256 OBJECT IDENTIFIER ::= {
  370. // joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
  371. // csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
  372. //
  373. // RFC 5758 3.2 ECDSA Signature Algorithm
  374. //
  375. // ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
  376. // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 }
  377. //
  378. // ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
  379. // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 }
  380. //
  381. // ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
  382. // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 }
  383. var (
  384. oidSignatureMD2WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2}
  385. oidSignatureMD5WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
  386. oidSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
  387. oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
  388. oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
  389. oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
  390. oidSignatureRSAPSS = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 10}
  391. oidSignatureDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
  392. oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 2}
  393. oidSignatureECDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1}
  394. oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2}
  395. oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3}
  396. oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4}
  397. oidSignatureSM2WithSM3 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 501}
  398. oidSignatureSM2WithSHA1 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 502}
  399. oidSignatureSM2WithSHA256 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 503}
  400. // oidSignatureSM3WithRSA = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 504}
  401. oidSM3 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 401, 1}
  402. oidSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1}
  403. oidSHA384 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2}
  404. oidSHA512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3}
  405. oidMGF1 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 8}
  406. // oidISOSignatureSHA1WithRSA means the same as oidSignatureSHA1WithRSA
  407. // but it's specified by ISO. Microsoft's makecert.exe has been known
  408. // to produce certificates with this OID.
  409. oidISOSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 29}
  410. )
  411. var signatureAlgorithmDetails = []struct {
  412. algo SignatureAlgorithm
  413. oid asn1.ObjectIdentifier
  414. pubKeyAlgo PublicKeyAlgorithm
  415. hash Hash
  416. }{
  417. {MD2WithRSA, oidSignatureMD2WithRSA, RSA, Hash(0) /* no value for MD2 */},
  418. {MD5WithRSA, oidSignatureMD5WithRSA, RSA, MD5},
  419. {SHA1WithRSA, oidSignatureSHA1WithRSA, RSA, SHA1},
  420. {SHA1WithRSA, oidISOSignatureSHA1WithRSA, RSA, SHA1},
  421. {SHA256WithRSA, oidSignatureSHA256WithRSA, RSA, SHA256},
  422. {SHA384WithRSA, oidSignatureSHA384WithRSA, RSA, SHA384},
  423. {SHA512WithRSA, oidSignatureSHA512WithRSA, RSA, SHA512},
  424. {SHA256WithRSAPSS, oidSignatureRSAPSS, RSA, SHA256},
  425. {SHA384WithRSAPSS, oidSignatureRSAPSS, RSA, SHA384},
  426. {SHA512WithRSAPSS, oidSignatureRSAPSS, RSA, SHA512},
  427. {DSAWithSHA1, oidSignatureDSAWithSHA1, DSA, SHA1},
  428. {DSAWithSHA256, oidSignatureDSAWithSHA256, DSA, SHA256},
  429. {ECDSAWithSHA1, oidSignatureECDSAWithSHA1, ECDSA, SHA1},
  430. {ECDSAWithSHA256, oidSignatureECDSAWithSHA256, ECDSA, SHA256},
  431. {ECDSAWithSHA384, oidSignatureECDSAWithSHA384, ECDSA, SHA384},
  432. {ECDSAWithSHA512, oidSignatureECDSAWithSHA512, ECDSA, SHA512},
  433. {SM2WithSM3, oidSignatureSM2WithSM3, ECDSA, SM3},
  434. {SM2WithSHA1, oidSignatureSM2WithSHA1, ECDSA, SHA1},
  435. {SM2WithSHA256, oidSignatureSM2WithSHA256, ECDSA, SHA256},
  436. // {SM3WithRSA, oidSignatureSM3WithRSA, RSA, SM3},
  437. }
  438. // pssParameters reflects the parameters in an AlgorithmIdentifier that
  439. // specifies RSA PSS. See https://tools.ietf.org/html/rfc3447#appendix-A.2.3
  440. type pssParameters struct {
  441. // The following three fields are not marked as
  442. // optional because the default values specify SHA-1,
  443. // which is no longer suitable for use in signatures.
  444. Hash pkix.AlgorithmIdentifier `asn1:"explicit,tag:0"`
  445. MGF pkix.AlgorithmIdentifier `asn1:"explicit,tag:1"`
  446. SaltLength int `asn1:"explicit,tag:2"`
  447. TrailerField int `asn1:"optional,explicit,tag:3,default:1"`
  448. }
  449. // rsaPSSParameters returns an asn1.RawValue suitable for use as the Parameters
  450. // in an AlgorithmIdentifier that specifies RSA PSS.
  451. func rsaPSSParameters(hashFunc Hash) asn1.RawValue {
  452. var hashOID asn1.ObjectIdentifier
  453. switch hashFunc {
  454. case SHA256:
  455. hashOID = oidSHA256
  456. case SHA384:
  457. hashOID = oidSHA384
  458. case SHA512:
  459. hashOID = oidSHA512
  460. }
  461. params := pssParameters{
  462. Hash: pkix.AlgorithmIdentifier{
  463. Algorithm: hashOID,
  464. Parameters: asn1.RawValue{
  465. Tag: 5, /* ASN.1 NULL */
  466. },
  467. },
  468. MGF: pkix.AlgorithmIdentifier{
  469. Algorithm: oidMGF1,
  470. },
  471. SaltLength: hashFunc.Size(),
  472. TrailerField: 1,
  473. }
  474. mgf1Params := pkix.AlgorithmIdentifier{
  475. Algorithm: hashOID,
  476. Parameters: asn1.RawValue{
  477. Tag: 5, /* ASN.1 NULL */
  478. },
  479. }
  480. var err error
  481. params.MGF.Parameters.FullBytes, err = asn1.Marshal(mgf1Params)
  482. if err != nil {
  483. panic(err)
  484. }
  485. serialized, err := asn1.Marshal(params)
  486. if err != nil {
  487. panic(err)
  488. }
  489. return asn1.RawValue{FullBytes: serialized}
  490. }
  491. func getSignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm {
  492. if !ai.Algorithm.Equal(oidSignatureRSAPSS) {
  493. for _, details := range signatureAlgorithmDetails {
  494. if ai.Algorithm.Equal(details.oid) {
  495. return details.algo
  496. }
  497. }
  498. return UnknownSignatureAlgorithm
  499. }
  500. // RSA PSS is special because it encodes important parameters
  501. // in the Parameters.
  502. var params pssParameters
  503. if _, err := asn1.Unmarshal(ai.Parameters.FullBytes, &params); err != nil {
  504. return UnknownSignatureAlgorithm
  505. }
  506. var mgf1HashFunc pkix.AlgorithmIdentifier
  507. if _, err := asn1.Unmarshal(params.MGF.Parameters.FullBytes, &mgf1HashFunc); err != nil {
  508. return UnknownSignatureAlgorithm
  509. }
  510. // PSS is greatly overburdened with options. This code forces
  511. // them into three buckets by requiring that the MGF1 hash
  512. // function always match the message hash function (as
  513. // recommended in
  514. // https://tools.ietf.org/html/rfc3447#section-8.1), that the
  515. // salt length matches the hash length, and that the trailer
  516. // field has the default value.
  517. asn1NULL := []byte{0x05, 0x00}
  518. if !bytes.Equal(params.Hash.Parameters.FullBytes, asn1NULL) ||
  519. !params.MGF.Algorithm.Equal(oidMGF1) ||
  520. !mgf1HashFunc.Algorithm.Equal(params.Hash.Algorithm) ||
  521. !bytes.Equal(mgf1HashFunc.Parameters.FullBytes, asn1NULL) ||
  522. params.TrailerField != 1 {
  523. return UnknownSignatureAlgorithm
  524. }
  525. switch {
  526. case params.Hash.Algorithm.Equal(oidSHA256) && params.SaltLength == 32:
  527. return SHA256WithRSAPSS
  528. case params.Hash.Algorithm.Equal(oidSHA384) && params.SaltLength == 48:
  529. return SHA384WithRSAPSS
  530. case params.Hash.Algorithm.Equal(oidSHA512) && params.SaltLength == 64:
  531. return SHA512WithRSAPSS
  532. }
  533. return UnknownSignatureAlgorithm
  534. }
  535. // RFC 3279, 2.3 Public Key Algorithms
  536. //
  537. // pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
  538. // rsadsi(113549) pkcs(1) 1 }
  539. //
  540. // rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
  541. //
  542. // id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
  543. // x9-57(10040) x9cm(4) 1 }
  544. //
  545. // RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters
  546. //
  547. // id-ecPublicKey OBJECT IDENTIFIER ::= {
  548. // iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
  549. var (
  550. oidPublicKeyRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
  551. oidPublicKeyDSA = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
  552. oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
  553. )
  554. func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
  555. switch {
  556. case oid.Equal(oidPublicKeyRSA):
  557. return RSA
  558. case oid.Equal(oidPublicKeyDSA):
  559. return DSA
  560. case oid.Equal(oidPublicKeyECDSA):
  561. return ECDSA
  562. }
  563. return UnknownPublicKeyAlgorithm
  564. }
  565. // RFC 5480, 2.1.1.1. Named Curve
  566. //
  567. // secp224r1 OBJECT IDENTIFIER ::= {
  568. // iso(1) identified-organization(3) certicom(132) curve(0) 33 }
  569. //
  570. // secp256r1 OBJECT IDENTIFIER ::= {
  571. // iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
  572. // prime(1) 7 }
  573. //
  574. // secp384r1 OBJECT IDENTIFIER ::= {
  575. // iso(1) identified-organization(3) certicom(132) curve(0) 34 }
  576. //
  577. // secp521r1 OBJECT IDENTIFIER ::= {
  578. // iso(1) identified-organization(3) certicom(132) curve(0) 35 }
  579. //
  580. // NB: secp256r1 is equivalent to prime256v1
  581. var (
  582. oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
  583. oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
  584. oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
  585. oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
  586. oidNamedCurveP256SM2 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 301} // I get the SM2 ID through parsing the pem file generated by gmssl
  587. )
  588. func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve {
  589. switch {
  590. case oid.Equal(oidNamedCurveP224):
  591. return elliptic.P224()
  592. case oid.Equal(oidNamedCurveP256):
  593. return elliptic.P256()
  594. case oid.Equal(oidNamedCurveP384):
  595. return elliptic.P384()
  596. case oid.Equal(oidNamedCurveP521):
  597. return elliptic.P521()
  598. case oid.Equal(oidNamedCurveP256SM2):
  599. return P256Sm2()
  600. }
  601. return nil
  602. }
  603. func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) {
  604. switch curve {
  605. case elliptic.P224():
  606. return oidNamedCurveP224, true
  607. case elliptic.P256():
  608. return oidNamedCurveP256, true
  609. case elliptic.P384():
  610. return oidNamedCurveP384, true
  611. case elliptic.P521():
  612. return oidNamedCurveP521, true
  613. case P256Sm2():
  614. return oidNamedCurveP256SM2, true
  615. }
  616. return nil, false
  617. }
  618. // KeyUsage represents the set of actions that are valid for a given key. It's
  619. // a bitmap of the KeyUsage* constants.
  620. type KeyUsage int
  621. const (
  622. KeyUsageDigitalSignature KeyUsage = 1 << iota
  623. KeyUsageContentCommitment
  624. KeyUsageKeyEncipherment
  625. KeyUsageDataEncipherment
  626. KeyUsageKeyAgreement
  627. KeyUsageCertSign
  628. KeyUsageCRLSign
  629. KeyUsageEncipherOnly
  630. KeyUsageDecipherOnly
  631. )
  632. // RFC 5280, 4.2.1.12 Extended Key Usage
  633. //
  634. // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
  635. //
  636. // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
  637. //
  638. // id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 }
  639. // id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 }
  640. // id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 }
  641. // id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 }
  642. // id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 }
  643. // id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 }
  644. var (
  645. oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
  646. oidExtKeyUsageServerAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
  647. oidExtKeyUsageClientAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
  648. oidExtKeyUsageCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
  649. oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
  650. oidExtKeyUsageIPSECEndSystem = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
  651. oidExtKeyUsageIPSECTunnel = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
  652. oidExtKeyUsageIPSECUser = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
  653. oidExtKeyUsageTimeStamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
  654. oidExtKeyUsageOCSPSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
  655. oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
  656. oidExtKeyUsageNetscapeServerGatedCrypto = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
  657. )
  658. // ExtKeyUsage represents an extended set of actions that are valid for a given key.
  659. // Each of the ExtKeyUsage* constants define a unique action.
  660. type ExtKeyUsage int
  661. const (
  662. ExtKeyUsageAny ExtKeyUsage = iota
  663. ExtKeyUsageServerAuth
  664. ExtKeyUsageClientAuth
  665. ExtKeyUsageCodeSigning
  666. ExtKeyUsageEmailProtection
  667. ExtKeyUsageIPSECEndSystem
  668. ExtKeyUsageIPSECTunnel
  669. ExtKeyUsageIPSECUser
  670. ExtKeyUsageTimeStamping
  671. ExtKeyUsageOCSPSigning
  672. ExtKeyUsageMicrosoftServerGatedCrypto
  673. ExtKeyUsageNetscapeServerGatedCrypto
  674. )
  675. // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
  676. var extKeyUsageOIDs = []struct {
  677. extKeyUsage ExtKeyUsage
  678. oid asn1.ObjectIdentifier
  679. }{
  680. {ExtKeyUsageAny, oidExtKeyUsageAny},
  681. {ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
  682. {ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
  683. {ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
  684. {ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
  685. {ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
  686. {ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
  687. {ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
  688. {ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
  689. {ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
  690. {ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
  691. {ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
  692. }
  693. func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) {
  694. for _, pair := range extKeyUsageOIDs {
  695. if oid.Equal(pair.oid) {
  696. return pair.extKeyUsage, true
  697. }
  698. }
  699. return
  700. }
  701. func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
  702. for _, pair := range extKeyUsageOIDs {
  703. if eku == pair.extKeyUsage {
  704. return pair.oid, true
  705. }
  706. }
  707. return
  708. }
  709. // A Certificate represents an X.509 certificate.
  710. type Certificate struct {
  711. Raw []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
  712. RawTBSCertificate []byte // Certificate part of raw ASN.1 DER content.
  713. RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
  714. RawSubject []byte // DER encoded Subject
  715. RawIssuer []byte // DER encoded Issuer
  716. Signature []byte
  717. SignatureAlgorithm SignatureAlgorithm
  718. PublicKeyAlgorithm PublicKeyAlgorithm
  719. PublicKey interface{}
  720. Version int
  721. SerialNumber *big.Int
  722. Issuer pkix.Name
  723. Subject pkix.Name
  724. NotBefore, NotAfter time.Time // Validity bounds.
  725. KeyUsage KeyUsage
  726. // Extensions contains raw X.509 extensions. When parsing certificates,
  727. // this can be used to extract non-critical extensions that are not
  728. // parsed by this package. When marshaling certificates, the Extensions
  729. // field is ignored, see ExtraExtensions.
  730. Extensions []pkix.Extension
  731. // ExtraExtensions contains extensions to be copied, raw, into any
  732. // marshaled certificates. Values override any extensions that would
  733. // otherwise be produced based on the other fields. The ExtraExtensions
  734. // field is not populated when parsing certificates, see Extensions.
  735. ExtraExtensions []pkix.Extension
  736. // UnhandledCriticalExtensions contains a list of extension IDs that
  737. // were not (fully) processed when parsing. Verify will fail if this
  738. // slice is non-empty, unless verification is delegated to an OS
  739. // library which understands all the critical extensions.
  740. //
  741. // Users can access these extensions using Extensions and can remove
  742. // elements from this slice if they believe that they have been
  743. // handled.
  744. UnhandledCriticalExtensions []asn1.ObjectIdentifier
  745. ExtKeyUsage []ExtKeyUsage // Sequence of extended key usages.
  746. UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
  747. BasicConstraintsValid bool // if true then the next two fields are valid.
  748. IsCA bool
  749. MaxPathLen int
  750. // MaxPathLenZero indicates that BasicConstraintsValid==true and
  751. // MaxPathLen==0 should be interpreted as an actual maximum path length
  752. // of zero. Otherwise, that combination is interpreted as MaxPathLen
  753. // not being set.
  754. MaxPathLenZero bool
  755. SubjectKeyId []byte
  756. AuthorityKeyId []byte
  757. // RFC 5280, 4.2.2.1 (Authority Information Access)
  758. OCSPServer []string
  759. IssuingCertificateURL []string
  760. // Subject Alternate Name values
  761. DNSNames []string
  762. EmailAddresses []string
  763. IPAddresses []net.IP
  764. // Name constraints
  765. PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
  766. PermittedDNSDomains []string
  767. // CRL Distribution Points
  768. CRLDistributionPoints []string
  769. PolicyIdentifiers []asn1.ObjectIdentifier
  770. }
  771. // ErrUnsupportedAlgorithm results from attempting to perform an operation that
  772. // involves algorithms that are not currently implemented.
  773. var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
  774. // An InsecureAlgorithmError
  775. type InsecureAlgorithmError SignatureAlgorithm
  776. func (e InsecureAlgorithmError) Error() string {
  777. return fmt.Sprintf("x509: cannot verify signature: insecure algorithm %v", SignatureAlgorithm(e))
  778. }
  779. // ConstraintViolationError results when a requested usage is not permitted by
  780. // a certificate. For example: checking a signature when the public key isn't a
  781. // certificate signing key.
  782. type ConstraintViolationError struct{}
  783. func (ConstraintViolationError) Error() string {
  784. return "x509: invalid signature: parent certificate cannot sign this kind of certificate"
  785. }
  786. func (c *Certificate) Equal(other *Certificate) bool {
  787. return bytes.Equal(c.Raw, other.Raw)
  788. }
  789. // Entrust have a broken root certificate (CN=Entrust.net Certification
  790. // Authority (2048)) which isn't marked as a CA certificate and is thus invalid
  791. // according to PKIX.
  792. // We recognise this certificate by its SubjectPublicKeyInfo and exempt it
  793. // from the Basic Constraints requirement.
  794. // See http://www.entrust.net/knowledge-base/technote.cfm?tn=7869
  795. //
  796. // TODO(agl): remove this hack once their reissued root is sufficiently
  797. // widespread.
  798. var entrustBrokenSPKI = []byte{
  799. 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09,
  800. 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01,
  801. 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00,
  802. 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01,
  803. 0x00, 0x97, 0xa3, 0x2d, 0x3c, 0x9e, 0xde, 0x05,
  804. 0xda, 0x13, 0xc2, 0x11, 0x8d, 0x9d, 0x8e, 0xe3,
  805. 0x7f, 0xc7, 0x4b, 0x7e, 0x5a, 0x9f, 0xb3, 0xff,
  806. 0x62, 0xab, 0x73, 0xc8, 0x28, 0x6b, 0xba, 0x10,
  807. 0x64, 0x82, 0x87, 0x13, 0xcd, 0x57, 0x18, 0xff,
  808. 0x28, 0xce, 0xc0, 0xe6, 0x0e, 0x06, 0x91, 0x50,
  809. 0x29, 0x83, 0xd1, 0xf2, 0xc3, 0x2a, 0xdb, 0xd8,
  810. 0xdb, 0x4e, 0x04, 0xcc, 0x00, 0xeb, 0x8b, 0xb6,
  811. 0x96, 0xdc, 0xbc, 0xaa, 0xfa, 0x52, 0x77, 0x04,
  812. 0xc1, 0xdb, 0x19, 0xe4, 0xae, 0x9c, 0xfd, 0x3c,
  813. 0x8b, 0x03, 0xef, 0x4d, 0xbc, 0x1a, 0x03, 0x65,
  814. 0xf9, 0xc1, 0xb1, 0x3f, 0x72, 0x86, 0xf2, 0x38,
  815. 0xaa, 0x19, 0xae, 0x10, 0x88, 0x78, 0x28, 0xda,
  816. 0x75, 0xc3, 0x3d, 0x02, 0x82, 0x02, 0x9c, 0xb9,
  817. 0xc1, 0x65, 0x77, 0x76, 0x24, 0x4c, 0x98, 0xf7,
  818. 0x6d, 0x31, 0x38, 0xfb, 0xdb, 0xfe, 0xdb, 0x37,
  819. 0x02, 0x76, 0xa1, 0x18, 0x97, 0xa6, 0xcc, 0xde,
  820. 0x20, 0x09, 0x49, 0x36, 0x24, 0x69, 0x42, 0xf6,
  821. 0xe4, 0x37, 0x62, 0xf1, 0x59, 0x6d, 0xa9, 0x3c,
  822. 0xed, 0x34, 0x9c, 0xa3, 0x8e, 0xdb, 0xdc, 0x3a,
  823. 0xd7, 0xf7, 0x0a, 0x6f, 0xef, 0x2e, 0xd8, 0xd5,
  824. 0x93, 0x5a, 0x7a, 0xed, 0x08, 0x49, 0x68, 0xe2,
  825. 0x41, 0xe3, 0x5a, 0x90, 0xc1, 0x86, 0x55, 0xfc,
  826. 0x51, 0x43, 0x9d, 0xe0, 0xb2, 0xc4, 0x67, 0xb4,
  827. 0xcb, 0x32, 0x31, 0x25, 0xf0, 0x54, 0x9f, 0x4b,
  828. 0xd1, 0x6f, 0xdb, 0xd4, 0xdd, 0xfc, 0xaf, 0x5e,
  829. 0x6c, 0x78, 0x90, 0x95, 0xde, 0xca, 0x3a, 0x48,
  830. 0xb9, 0x79, 0x3c, 0x9b, 0x19, 0xd6, 0x75, 0x05,
  831. 0xa0, 0xf9, 0x88, 0xd7, 0xc1, 0xe8, 0xa5, 0x09,
  832. 0xe4, 0x1a, 0x15, 0xdc, 0x87, 0x23, 0xaa, 0xb2,
  833. 0x75, 0x8c, 0x63, 0x25, 0x87, 0xd8, 0xf8, 0x3d,
  834. 0xa6, 0xc2, 0xcc, 0x66, 0xff, 0xa5, 0x66, 0x68,
  835. 0x55, 0x02, 0x03, 0x01, 0x00, 0x01,
  836. }
  837. // CheckSignatureFrom verifies that the signature on c is a valid signature
  838. // from parent.
  839. func (c *Certificate) CheckSignatureFrom(parent *Certificate) error {
  840. // RFC 5280, 4.2.1.9:
  841. // "If the basic constraints extension is not present in a version 3
  842. // certificate, or the extension is present but the cA boolean is not
  843. // asserted, then the certified public key MUST NOT be used to verify
  844. // certificate signatures."
  845. // (except for Entrust, see comment above entrustBrokenSPKI)
  846. if (parent.Version == 3 && !parent.BasicConstraintsValid ||
  847. parent.BasicConstraintsValid && !parent.IsCA) &&
  848. !bytes.Equal(c.RawSubjectPublicKeyInfo, entrustBrokenSPKI) {
  849. return ConstraintViolationError{}
  850. }
  851. if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
  852. return ConstraintViolationError{}
  853. }
  854. if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
  855. return ErrUnsupportedAlgorithm
  856. }
  857. // TODO(agl): don't ignore the path length constraint.
  858. return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature)
  859. }
  860. // CheckSignature verifies that signature is a valid signature over signed from
  861. // c's public key.
  862. func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error {
  863. return checkSignature(algo, signed, signature, c.PublicKey)
  864. }
  865. // CheckSignature verifies that signature is a valid signature over signed from
  866. // a crypto.PublicKey.
  867. func checkSignature(algo SignatureAlgorithm, signed, signature []byte, publicKey crypto.PublicKey) (err error) {
  868. var hashType Hash
  869. switch algo {
  870. case SHA1WithRSA, DSAWithSHA1, ECDSAWithSHA1, SM2WithSHA1:
  871. hashType = SHA1
  872. case SHA256WithRSA, SHA256WithRSAPSS, DSAWithSHA256, ECDSAWithSHA256, SM2WithSHA256:
  873. hashType = SHA256
  874. case SHA384WithRSA, SHA384WithRSAPSS, ECDSAWithSHA384:
  875. hashType = SHA384
  876. case SHA512WithRSA, SHA512WithRSAPSS, ECDSAWithSHA512:
  877. hashType = SHA512
  878. case MD2WithRSA, MD5WithRSA:
  879. return InsecureAlgorithmError(algo)
  880. case SM2WithSM3: // SM3WithRSA reserve
  881. hashType = SM3
  882. default:
  883. return ErrUnsupportedAlgorithm
  884. }
  885. if !hashType.Available() {
  886. return ErrUnsupportedAlgorithm
  887. }
  888. h := hashType.New()
  889. h.Write(signed)
  890. digest := h.Sum(nil)
  891. switch pub := publicKey.(type) {
  892. case *rsa.PublicKey:
  893. if algo.isRSAPSS() {
  894. return rsa.VerifyPSS(pub, crypto.Hash(hashType), digest, signature, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
  895. } else {
  896. return rsa.VerifyPKCS1v15(pub, crypto.Hash(hashType), digest, signature)
  897. }
  898. case *dsa.PublicKey:
  899. dsaSig := new(dsaSignature)
  900. if rest, err := asn1.Unmarshal(signature, dsaSig); err != nil {
  901. return err
  902. } else if len(rest) != 0 {
  903. return errors.New("x509: trailing data after DSA signature")
  904. }
  905. if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 {
  906. return errors.New("x509: DSA signature contained zero or negative values")
  907. }
  908. if !dsa.Verify(pub, digest, dsaSig.R, dsaSig.S) {
  909. return errors.New("x509: DSA verification failure")
  910. }
  911. return
  912. case *ecdsa.PublicKey:
  913. ecdsaSig := new(ecdsaSignature)
  914. if rest, err := asn1.Unmarshal(signature, ecdsaSig); err != nil {
  915. return err
  916. } else if len(rest) != 0 {
  917. return errors.New("x509: trailing data after ECDSA signature")
  918. }
  919. if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
  920. return errors.New("x509: ECDSA signature contained zero or negative values")
  921. }
  922. switch pub.Curve {
  923. case P256Sm2():
  924. if !Verify(&PublicKey{
  925. Curve: pub.Curve,
  926. X: pub.X,
  927. Y: pub.Y,
  928. }, digest, ecdsaSig.R, ecdsaSig.S) {
  929. return errors.New("x509: SM2 verification failure")
  930. }
  931. default:
  932. if !ecdsa.Verify(pub, digest, ecdsaSig.R, ecdsaSig.S) {
  933. return errors.New("x509: ECDSA verification failure")
  934. }
  935. }
  936. return
  937. }
  938. return ErrUnsupportedAlgorithm
  939. }
  940. // CheckCRLSignature checks that the signature in crl is from c.
  941. func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error {
  942. algo := getSignatureAlgorithmFromAI(crl.SignatureAlgorithm)
  943. return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
  944. }
  945. type UnhandledCriticalExtension struct{}
  946. func (h UnhandledCriticalExtension) Error() string {
  947. return "x509: unhandled critical extension"
  948. }
  949. type basicConstraints struct {
  950. IsCA bool `asn1:"optional"`
  951. MaxPathLen int `asn1:"optional,default:-1"`
  952. }
  953. // RFC 5280 4.2.1.4
  954. type policyInformation struct {
  955. Policy asn1.ObjectIdentifier
  956. // policyQualifiers omitted
  957. }
  958. // RFC 5280, 4.2.1.10
  959. type nameConstraints struct {
  960. Permitted []generalSubtree `asn1:"optional,tag:0"`
  961. Excluded []generalSubtree `asn1:"optional,tag:1"`
  962. }
  963. type generalSubtree struct {
  964. Name string `asn1:"tag:2,optional,ia5"`
  965. }
  966. // RFC 5280, 4.2.2.1
  967. type authorityInfoAccess struct {
  968. Method asn1.ObjectIdentifier
  969. Location asn1.RawValue
  970. }
  971. // RFC 5280, 4.2.1.14
  972. type distributionPoint struct {
  973. DistributionPoint distributionPointName `asn1:"optional,tag:0"`
  974. Reason asn1.BitString `asn1:"optional,tag:1"`
  975. CRLIssuer asn1.RawValue `asn1:"optional,tag:2"`
  976. }
  977. type distributionPointName struct {
  978. FullName asn1.RawValue `asn1:"optional,tag:0"`
  979. RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
  980. }
  981. // asn1Null is the ASN.1 encoding of a NULL value.
  982. var asn1Null = []byte{5, 0}
  983. func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (interface{}, error) {
  984. asn1Data := keyData.PublicKey.RightAlign()
  985. switch algo {
  986. case RSA:
  987. // RSA public keys must have a NULL in the parameters
  988. // (https://tools.ietf.org/html/rfc3279#section-2.3.1).
  989. if !bytes.Equal(keyData.Algorithm.Parameters.FullBytes, asn1Null) {
  990. return nil, errors.New("x509: RSA key missing NULL parameters")
  991. }
  992. p := new(rsaPublicKey)
  993. rest, err := asn1.Unmarshal(asn1Data, p)
  994. if err != nil {
  995. return nil, err
  996. }
  997. if len(rest) != 0 {
  998. return nil, errors.New("x509: trailing data after RSA public key")
  999. }
  1000. if p.N.Sign() <= 0 {
  1001. return nil, errors.New("x509: RSA modulus is not a positive number")
  1002. }
  1003. if p.E <= 0 {
  1004. return nil, errors.New("x509: RSA public exponent is not a positive number")
  1005. }
  1006. pub := &rsa.PublicKey{
  1007. E: p.E,
  1008. N: p.N,
  1009. }
  1010. return pub, nil
  1011. case DSA:
  1012. var p *big.Int
  1013. rest, err := asn1.Unmarshal(asn1Data, &p)
  1014. if err != nil {
  1015. return nil, err
  1016. }
  1017. if len(rest) != 0 {
  1018. return nil, errors.New("x509: trailing data after DSA public key")
  1019. }
  1020. paramsData := keyData.Algorithm.Parameters.FullBytes
  1021. params := new(dsaAlgorithmParameters)
  1022. rest, err = asn1.Unmarshal(paramsData, params)
  1023. if err != nil {
  1024. return nil, err
  1025. }
  1026. if len(rest) != 0 {
  1027. return nil, errors.New("x509: trailing data after DSA parameters")
  1028. }
  1029. if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 {
  1030. return nil, errors.New("x509: zero or negative DSA parameter")
  1031. }
  1032. pub := &dsa.PublicKey{
  1033. Parameters: dsa.Parameters{
  1034. P: params.P,
  1035. Q: params.Q,
  1036. G: params.G,
  1037. },
  1038. Y: p,
  1039. }
  1040. return pub, nil
  1041. case ECDSA:
  1042. paramsData := keyData.Algorithm.Parameters.FullBytes
  1043. namedCurveOID := new(asn1.ObjectIdentifier)
  1044. rest, err := asn1.Unmarshal(paramsData, namedCurveOID)
  1045. if err != nil {
  1046. return nil, err
  1047. }
  1048. if len(rest) != 0 {
  1049. return nil, errors.New("x509: trailing data after ECDSA parameters")
  1050. }
  1051. namedCurve := namedCurveFromOID(*namedCurveOID)
  1052. if namedCurve == nil {
  1053. return nil, errors.New("x509: unsupported elliptic curve")
  1054. }
  1055. x, y := elliptic.Unmarshal(namedCurve, asn1Data)
  1056. if x == nil {
  1057. return nil, errors.New("x509: failed to unmarshal elliptic curve point")
  1058. }
  1059. pub := &ecdsa.PublicKey{
  1060. Curve: namedCurve,
  1061. X: x,
  1062. Y: y,
  1063. }
  1064. return pub, nil
  1065. default:
  1066. return nil, nil
  1067. }
  1068. }
  1069. func parseSANExtension(value []byte) (dnsNames, emailAddresses []string, ipAddresses []net.IP, err error) {
  1070. // RFC 5280, 4.2.1.6
  1071. // SubjectAltName ::= GeneralNames
  1072. //
  1073. // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
  1074. //
  1075. // GeneralName ::= CHOICE {
  1076. // otherName [0] OtherName,
  1077. // rfc822Name [1] IA5String,
  1078. // dNSName [2] IA5String,
  1079. // x400Address [3] ORAddress,
  1080. // directoryName [4] Name,
  1081. // ediPartyName [5] EDIPartyName,
  1082. // uniformResourceIdentifier [6] IA5String,
  1083. // iPAddress [7] OCTET STRING,
  1084. // registeredID [8] OBJECT IDENTIFIER }
  1085. var seq asn1.RawValue
  1086. var rest []byte
  1087. if rest, err = asn1.Unmarshal(value, &seq); err != nil {
  1088. return
  1089. } else if len(rest) != 0 {
  1090. err = errors.New("x509: trailing data after X.509 extension")
  1091. return
  1092. }
  1093. if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 {
  1094. err = asn1.StructuralError{Msg: "bad SAN sequence"}
  1095. return
  1096. }
  1097. rest = seq.Bytes
  1098. for len(rest) > 0 {
  1099. var v asn1.RawValue
  1100. rest, err = asn1.Unmarshal(rest, &v)
  1101. if err != nil {
  1102. return
  1103. }
  1104. switch v.Tag {
  1105. case 1:
  1106. emailAddresses = append(emailAddresses, string(v.Bytes))
  1107. case 2:
  1108. dnsNames = append(dnsNames, string(v.Bytes))
  1109. case 7:
  1110. switch len(v.Bytes) {
  1111. case net.IPv4len, net.IPv6len:
  1112. ipAddresses = append(ipAddresses, v.Bytes)
  1113. default:
  1114. err = errors.New("x509: certificate contained IP address of length " + strconv.Itoa(len(v.Bytes)))
  1115. return
  1116. }
  1117. }
  1118. }
  1119. return
  1120. }
  1121. func parseCertificate(in *certificate) (*Certificate, error) {
  1122. out := new(Certificate)
  1123. out.Raw = in.Raw
  1124. out.RawTBSCertificate = in.TBSCertificate.Raw
  1125. out.RawSubjectPublicKeyInfo = in.TBSCertificate.PublicKey.Raw
  1126. out.RawSubject = in.TBSCertificate.Subject.FullBytes
  1127. out.RawIssuer = in.TBSCertificate.Issuer.FullBytes
  1128. out.Signature = in.SignatureValue.RightAlign()
  1129. out.SignatureAlgorithm =
  1130. getSignatureAlgorithmFromAI(in.TBSCertificate.SignatureAlgorithm)
  1131. out.PublicKeyAlgorithm =
  1132. getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm)
  1133. var err error
  1134. out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCertificate.PublicKey)
  1135. if err != nil {
  1136. return nil, err
  1137. }
  1138. out.Version = in.TBSCertificate.Version + 1
  1139. out.SerialNumber = in.TBSCertificate.SerialNumber
  1140. var issuer, subject pkix.RDNSequence
  1141. if rest, err := asn1.Unmarshal(in.TBSCertificate.Subject.FullBytes, &subject); err != nil {
  1142. return nil, err
  1143. } else if len(rest) != 0 {
  1144. return nil, errors.New("x509: trailing data after X.509 subject")
  1145. }
  1146. if rest, err := asn1.Unmarshal(in.TBSCertificate.Issuer.FullBytes, &issuer); err != nil {
  1147. return nil, err
  1148. } else if len(rest) != 0 {
  1149. return nil, errors.New("x509: trailing data after X.509 subject")
  1150. }
  1151. out.Issuer.FillFromRDNSequence(&issuer)
  1152. out.Subject.FillFromRDNSequence(&subject)
  1153. out.NotBefore = in.TBSCertificate.Validity.NotBefore
  1154. out.NotAfter = in.TBSCertificate.Validity.NotAfter
  1155. for _, e := range in.TBSCertificate.Extensions {
  1156. out.Extensions = append(out.Extensions, e)
  1157. unhandled := false
  1158. if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 {
  1159. switch e.Id[3] {
  1160. case 15:
  1161. // RFC 5280, 4.2.1.3
  1162. var usageBits asn1.BitString
  1163. if rest, err := asn1.Unmarshal(e.Value, &usageBits); err != nil {
  1164. return nil, err
  1165. } else if len(rest) != 0 {
  1166. return nil, errors.New("x509: trailing data after X.509 KeyUsage")
  1167. }
  1168. var usage int
  1169. for i := 0; i < 9; i++ {
  1170. if usageBits.At(i) != 0 {
  1171. usage |= 1 << uint(i)
  1172. }
  1173. }
  1174. out.KeyUsage = KeyUsage(usage)
  1175. case 19:
  1176. // RFC 5280, 4.2.1.9
  1177. var constraints basicConstraints
  1178. if rest, err := asn1.Unmarshal(e.Value, &constraints); err != nil {
  1179. return nil, err
  1180. } else if len(rest) != 0 {
  1181. return nil, errors.New("x509: trailing data after X.509 BasicConstraints")
  1182. }
  1183. out.BasicConstraintsValid = true
  1184. out.IsCA = constraints.IsCA
  1185. out.MaxPathLen = constraints.MaxPathLen
  1186. out.MaxPathLenZero = out.MaxPathLen == 0
  1187. case 17:
  1188. out.DNSNames, out.EmailAddresses, out.IPAddresses, err = parseSANExtension(e.Value)
  1189. if err != nil {
  1190. return nil, err
  1191. }
  1192. if len(out.DNSNames) == 0 && len(out.EmailAddresses) == 0 && len(out.IPAddresses) == 0 {
  1193. // If we didn't parse anything then we do the critical check, below.
  1194. unhandled = true
  1195. }
  1196. case 30:
  1197. // RFC 5280, 4.2.1.10
  1198. // NameConstraints ::= SEQUENCE {
  1199. // permittedSubtrees [0] GeneralSubtrees OPTIONAL,
  1200. // excludedSubtrees [1] GeneralSubtrees OPTIONAL }
  1201. //
  1202. // GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
  1203. //
  1204. // GeneralSubtree ::= SEQUENCE {
  1205. // base GeneralName,
  1206. // minimum [0] BaseDistance DEFAULT 0,
  1207. // maximum [1] BaseDistance OPTIONAL }
  1208. //
  1209. // BaseDistance ::= INTEGER (0..MAX)
  1210. var constraints nameConstraints
  1211. if rest, err := asn1.Unmarshal(e.Value, &constraints); err != nil {
  1212. return nil, err
  1213. } else if len(rest) != 0 {
  1214. return nil, errors.New("x509: trailing data after X.509 NameConstraints")
  1215. }
  1216. if len(constraints.Excluded) > 0 && e.Critical {
  1217. return out, UnhandledCriticalExtension{}
  1218. }
  1219. for _, subtree := range constraints.Permitted {
  1220. if len(subtree.Name) == 0 {
  1221. if e.Critical {
  1222. return out, UnhandledCriticalExtension{}
  1223. }
  1224. continue
  1225. }
  1226. out.PermittedDNSDomains = append(out.PermittedDNSDomains, subtree.Name)
  1227. }
  1228. case 31:
  1229. // RFC 5280, 4.2.1.13
  1230. // CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
  1231. //
  1232. // DistributionPoint ::= SEQUENCE {
  1233. // distributionPoint [0] DistributionPointName OPTIONAL,
  1234. // reasons [1] ReasonFlags OPTIONAL,
  1235. // cRLIssuer [2] GeneralNames OPTIONAL }
  1236. //
  1237. // DistributionPointName ::= CHOICE {
  1238. // fullName [0] GeneralNames,
  1239. // nameRelativeToCRLIssuer [1] RelativeDistinguishedName }
  1240. var cdp []distributionPoint
  1241. if rest, err := asn1.Unmarshal(e.Value, &cdp); err != nil {
  1242. return nil, err
  1243. } else if len(rest) != 0 {
  1244. return nil, errors.New("x509: trailing data after X.509 CRL distribution point")
  1245. }
  1246. for _, dp := range cdp {
  1247. // Per RFC 5280, 4.2.1.13, one of distributionPoint or cRLIssuer may be empty.
  1248. if len(dp.DistributionPoint.FullName.Bytes) == 0 {
  1249. continue
  1250. }
  1251. var n asn1.RawValue
  1252. if _, err := asn1.Unmarshal(dp.DistributionPoint.FullName.Bytes, &n); err != nil {
  1253. return nil, err
  1254. }
  1255. // Trailing data after the fullName is
  1256. // allowed because other elements of
  1257. // the SEQUENCE can appear.
  1258. if n.Tag == 6 {
  1259. out.CRLDistributionPoints = append(out.CRLDistributionPoints, string(n.Bytes))
  1260. }
  1261. }
  1262. case 35:
  1263. // RFC 5280, 4.2.1.1
  1264. var a authKeyId
  1265. if rest, err := asn1.Unmarshal(e.Value, &a); err != nil {
  1266. return nil, err
  1267. } else if len(rest) != 0 {
  1268. return nil, errors.New("x509: trailing data after X.509 authority key-id")
  1269. }
  1270. out.AuthorityKeyId = a.Id
  1271. case 37:
  1272. // RFC 5280, 4.2.1.12. Extended Key Usage
  1273. // id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 }
  1274. //
  1275. // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
  1276. //
  1277. // KeyPurposeId ::= OBJECT IDENTIFIER
  1278. var keyUsage []asn1.ObjectIdentifier
  1279. if rest, err := asn1.Unmarshal(e.Value, &keyUsage); err != nil {
  1280. return nil, err
  1281. } else if len(rest) != 0 {
  1282. return nil, errors.New("x509: trailing data after X.509 ExtendedKeyUsage")
  1283. }
  1284. for _, u := range keyUsage {
  1285. if extKeyUsage, ok := extKeyUsageFromOID(u); ok {
  1286. out.ExtKeyUsage = append(out.ExtKeyUsage, extKeyUsage)
  1287. } else {
  1288. out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u)
  1289. }
  1290. }
  1291. case 14:
  1292. // RFC 5280, 4.2.1.2
  1293. var keyid []byte
  1294. if rest, err := asn1.Unmarshal(e.Value, &keyid); err != nil {
  1295. return nil, err
  1296. } else if len(rest) != 0 {
  1297. return nil, errors.New("x509: trailing data after X.509 key-id")
  1298. }
  1299. out.SubjectKeyId = keyid
  1300. case 32:
  1301. // RFC 5280 4.2.1.4: Certificate Policies
  1302. var policies []policyInformation
  1303. if rest, err := asn1.Unmarshal(e.Value, &policies); err != nil {
  1304. return nil, err
  1305. } else if len(rest) != 0 {
  1306. return nil, errors.New("x509: trailing data after X.509 certificate policies")
  1307. }
  1308. out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies))
  1309. for i, policy := range policies {
  1310. out.PolicyIdentifiers[i] = policy.Policy
  1311. }
  1312. default:
  1313. // Unknown extensions are recorded if critical.
  1314. unhandled = true
  1315. }
  1316. } else if e.Id.Equal(oidExtensionAuthorityInfoAccess) {
  1317. // RFC 5280 4.2.2.1: Authority Information Access
  1318. var aia []authorityInfoAccess
  1319. if rest, err := asn1.Unmarshal(e.Value, &aia); err != nil {
  1320. return nil, err
  1321. } else if len(rest) != 0 {
  1322. return nil, errors.New("x509: trailing data after X.509 authority information")
  1323. }
  1324. for _, v := range aia {
  1325. // GeneralName: uniformResourceIdentifier [6] IA5String
  1326. if v.Location.Tag != 6 {
  1327. continue
  1328. }
  1329. if v.Method.Equal(oidAuthorityInfoAccessOcsp) {
  1330. out.OCSPServer = append(out.OCSPServer, string(v.Location.Bytes))
  1331. } else if v.Method.Equal(oidAuthorityInfoAccessIssuers) {
  1332. out.IssuingCertificateURL = append(out.IssuingCertificateURL, string(v.Location.Bytes))
  1333. }
  1334. }
  1335. } else {
  1336. // Unknown extensions are recorded if critical.
  1337. unhandled = true
  1338. }
  1339. if e.Critical && unhandled {
  1340. out.UnhandledCriticalExtensions = append(out.UnhandledCriticalExtensions, e.Id)
  1341. }
  1342. }
  1343. return out, nil
  1344. }
  1345. // ParseCertificate parses a single certificate from the given ASN.1 DER data.
  1346. func ParseCertificate(asn1Data []byte) (*Certificate, error) {
  1347. var cert certificate
  1348. rest, err := asn1.Unmarshal(asn1Data, &cert)
  1349. if err != nil {
  1350. return nil, err
  1351. }
  1352. if len(rest) > 0 {
  1353. return nil, asn1.SyntaxError{Msg: "trailing data"}
  1354. }
  1355. return parseCertificate(&cert)
  1356. }
  1357. // ParseCertificates parses one or more certificates from the given ASN.1 DER
  1358. // data. The certificates must be concatenated with no intermediate padding.
  1359. func ParseCertificates(asn1Data []byte) ([]*Certificate, error) {
  1360. var v []*certificate
  1361. for len(asn1Data) > 0 {
  1362. cert := new(certificate)
  1363. var err error
  1364. asn1Data, err = asn1.Unmarshal(asn1Data, cert)
  1365. if err != nil {
  1366. return nil, err
  1367. }
  1368. v = append(v, cert)
  1369. }
  1370. ret := make([]*Certificate, len(v))
  1371. for i, ci := range v {
  1372. cert, err := parseCertificate(ci)
  1373. if err != nil {
  1374. return nil, err
  1375. }
  1376. ret[i] = cert
  1377. }
  1378. return ret, nil
  1379. }
  1380. func reverseBitsInAByte(in byte) byte {
  1381. b1 := in>>4 | in<<4
  1382. b2 := b1>>2&0x33 | b1<<2&0xcc
  1383. b3 := b2>>1&0x55 | b2<<1&0xaa
  1384. return b3
  1385. }
  1386. // asn1BitLength returns the bit-length of bitString by considering the
  1387. // most-significant bit in a byte to be the "first" bit. This convention
  1388. // matches ASN.1, but differs from almost everything else.
  1389. func asn1BitLength(bitString []byte) int {
  1390. bitLen := len(bitString) * 8
  1391. for i := range bitString {
  1392. b := bitString[len(bitString)-i-1]
  1393. for bit := uint(0); bit < 8; bit++ {
  1394. if (b>>bit)&1 == 1 {
  1395. return bitLen
  1396. }
  1397. bitLen--
  1398. }
  1399. }
  1400. return 0
  1401. }
  1402. var (
  1403. oidExtensionSubjectKeyId = []int{2, 5, 29, 14}
  1404. oidExtensionKeyUsage = []int{2, 5, 29, 15}
  1405. oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37}
  1406. oidExtensionAuthorityKeyId = []int{2, 5, 29, 35}
  1407. oidExtensionBasicConstraints = []int{2, 5, 29, 19}
  1408. oidExtensionSubjectAltName = []int{2, 5, 29, 17}
  1409. oidExtensionCertificatePolicies = []int{2, 5, 29, 32}
  1410. oidExtensionNameConstraints = []int{2, 5, 29, 30}
  1411. oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31}
  1412. oidExtensionAuthorityInfoAccess = []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
  1413. )
  1414. var (
  1415. oidAuthorityInfoAccessOcsp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
  1416. oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}
  1417. )
  1418. // oidNotInExtensions returns whether an extension with the given oid exists in
  1419. // extensions.
  1420. func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {
  1421. for _, e := range extensions {
  1422. if e.Id.Equal(oid) {
  1423. return true
  1424. }
  1425. }
  1426. return false
  1427. }
  1428. // marshalSANs marshals a list of addresses into a the contents of an X.509
  1429. // SubjectAlternativeName extension.
  1430. func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP) (derBytes []byte, err error) {
  1431. var rawValues []asn1.RawValue
  1432. for _, name := range dnsNames {
  1433. rawValues = append(rawValues, asn1.RawValue{Tag: 2, Class: 2, Bytes: []byte(name)})
  1434. }
  1435. for _, email := range emailAddresses {
  1436. rawValues = append(rawValues, asn1.RawValue{Tag: 1, Class: 2, Bytes: []byte(email)})
  1437. }
  1438. for _, rawIP := range ipAddresses {
  1439. // If possible, we always want to encode IPv4 addresses in 4 bytes.
  1440. ip := rawIP.To4()
  1441. if ip == nil {
  1442. ip = rawIP
  1443. }
  1444. rawValues = append(rawValues, asn1.RawValue{Tag: 7, Class: 2, Bytes: ip})
  1445. }
  1446. return asn1.Marshal(rawValues)
  1447. }
  1448. func buildExtensions(template *Certificate) (ret []pkix.Extension, err error) {
  1449. ret = make([]pkix.Extension, 10 /* maximum number of elements. */)
  1450. n := 0
  1451. if template.KeyUsage != 0 &&
  1452. !oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) {
  1453. ret[n].Id = oidExtensionKeyUsage
  1454. ret[n].Critical = true
  1455. var a [2]byte
  1456. a[0] = reverseBitsInAByte(byte(template.KeyUsage))
  1457. a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8))
  1458. l := 1
  1459. if a[1] != 0 {
  1460. l = 2
  1461. }
  1462. bitString := a[:l]
  1463. ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)})
  1464. if err != nil {
  1465. return
  1466. }
  1467. n++
  1468. }
  1469. if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) &&
  1470. !oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) {
  1471. ret[n].Id = oidExtensionExtendedKeyUsage
  1472. var oids []asn1.ObjectIdentifier
  1473. for _, u := range template.ExtKeyUsage {
  1474. if oid, ok := oidFromExtKeyUsage(u); ok {
  1475. oids = append(oids, oid)
  1476. } else {
  1477. panic("internal error")
  1478. }
  1479. }
  1480. oids = append(oids, template.UnknownExtKeyUsage...)
  1481. ret[n].Value, err = asn1.Marshal(oids)
  1482. if err != nil {
  1483. return
  1484. }
  1485. n++
  1486. }
  1487. if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) {
  1488. // Leaving MaxPathLen as zero indicates that no maximum path
  1489. // length is desired, unless MaxPathLenZero is set. A value of
  1490. // -1 causes encoding/asn1 to omit the value as desired.
  1491. maxPathLen := template.MaxPathLen
  1492. if maxPathLen == 0 && !template.MaxPathLenZero {
  1493. maxPathLen = -1
  1494. }
  1495. ret[n].Id = oidExtensionBasicConstraints
  1496. ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, maxPathLen})
  1497. ret[n].Critical = true
  1498. if err != nil {
  1499. return
  1500. }
  1501. n++
  1502. }
  1503. if len(template.SubjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) {
  1504. ret[n].Id = oidExtensionSubjectKeyId
  1505. ret[n].Value, err = asn1.Marshal(template.SubjectKeyId)
  1506. if err != nil {
  1507. return
  1508. }
  1509. n++
  1510. }
  1511. if len(template.AuthorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) {
  1512. ret[n].Id = oidExtensionAuthorityKeyId
  1513. ret[n].Value, err = asn1.Marshal(authKeyId{template.AuthorityKeyId})
  1514. if err != nil {
  1515. return
  1516. }
  1517. n++
  1518. }
  1519. if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) &&
  1520. !oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) {
  1521. ret[n].Id = oidExtensionAuthorityInfoAccess
  1522. var aiaValues []authorityInfoAccess
  1523. for _, name := range template.OCSPServer {
  1524. aiaValues = append(aiaValues, authorityInfoAccess{
  1525. Method: oidAuthorityInfoAccessOcsp,
  1526. Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
  1527. })
  1528. }
  1529. for _, name := range template.IssuingCertificateURL {
  1530. aiaValues = append(aiaValues, authorityInfoAccess{
  1531. Method: oidAuthorityInfoAccessIssuers,
  1532. Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
  1533. })
  1534. }
  1535. ret[n].Value, err = asn1.Marshal(aiaValues)
  1536. if err != nil {
  1537. return
  1538. }
  1539. n++
  1540. }
  1541. if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0) &&
  1542. !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
  1543. ret[n].Id = oidExtensionSubjectAltName
  1544. ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses)
  1545. if err != nil {
  1546. return
  1547. }
  1548. n++
  1549. }
  1550. if len(template.PolicyIdentifiers) > 0 &&
  1551. !oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) {
  1552. ret[n].Id = oidExtensionCertificatePolicies
  1553. policies := make([]policyInformation, len(template.PolicyIdentifiers))
  1554. for i, policy := range template.PolicyIdentifiers {
  1555. policies[i].Policy = policy
  1556. }
  1557. ret[n].Value, err = asn1.Marshal(policies)
  1558. if err != nil {
  1559. return
  1560. }
  1561. n++
  1562. }
  1563. if len(template.PermittedDNSDomains) > 0 &&
  1564. !oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) {
  1565. ret[n].Id = oidExtensionNameConstraints
  1566. ret[n].Critical = template.PermittedDNSDomainsCritical
  1567. var out nameConstraints
  1568. out.Permitted = make([]generalSubtree, len(template.PermittedDNSDomains))
  1569. for i, permitted := range template.PermittedDNSDomains {
  1570. out.Permitted[i] = generalSubtree{Name: permitted}
  1571. }
  1572. ret[n].Value, err = asn1.Marshal(out)
  1573. if err != nil {
  1574. return
  1575. }
  1576. n++
  1577. }
  1578. if len(template.CRLDistributionPoints) > 0 &&
  1579. !oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) {
  1580. ret[n].Id = oidExtensionCRLDistributionPoints
  1581. var crlDp []distributionPoint
  1582. for _, name := range template.CRLDistributionPoints {
  1583. rawFullName, _ := asn1.Marshal(asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)})
  1584. dp := distributionPoint{
  1585. DistributionPoint: distributionPointName{
  1586. FullName: asn1.RawValue{Tag: 0, Class: 2, IsCompound: true, Bytes: rawFullName},
  1587. },
  1588. }
  1589. crlDp = append(crlDp, dp)
  1590. }
  1591. ret[n].Value, err = asn1.Marshal(crlDp)
  1592. if err != nil {
  1593. return
  1594. }
  1595. n++
  1596. }
  1597. // Adding another extension here? Remember to update the maximum number
  1598. // of elements in the make() at the top of the function.
  1599. return append(ret[:n], template.ExtraExtensions...), nil
  1600. }
  1601. func subjectBytes(cert *Certificate) ([]byte, error) {
  1602. if len(cert.RawSubject) > 0 {
  1603. return cert.RawSubject, nil
  1604. }
  1605. return asn1.Marshal(cert.Subject.ToRDNSequence())
  1606. }
  1607. // signingParamsForPublicKey returns the parameters to use for signing with
  1608. // priv. If requestedSigAlgo is not zero then it overrides the default
  1609. // signature algorithm.
  1610. func signingParamsForPublicKey(pub interface{}, requestedSigAlgo SignatureAlgorithm) (hashFunc Hash, sigAlgo pkix.AlgorithmIdentifier, err error) {
  1611. var pubType PublicKeyAlgorithm
  1612. switch pub := pub.(type) {
  1613. case *rsa.PublicKey:
  1614. pubType = RSA
  1615. hashFunc = SHA256
  1616. sigAlgo.Algorithm = oidSignatureSHA256WithRSA
  1617. sigAlgo.Parameters = asn1.RawValue{
  1618. Tag: 5,
  1619. }
  1620. case *ecdsa.PublicKey:
  1621. pubType = ECDSA
  1622. switch pub.Curve {
  1623. case elliptic.P224(), elliptic.P256():
  1624. hashFunc = SHA256
  1625. sigAlgo.Algorithm = oidSignatureECDSAWithSHA256
  1626. case elliptic.P384():
  1627. hashFunc = SHA384
  1628. sigAlgo.Algorithm = oidSignatureECDSAWithSHA384
  1629. case elliptic.P521():
  1630. hashFunc = SHA512
  1631. sigAlgo.Algorithm = oidSignatureECDSAWithSHA512
  1632. default:
  1633. err = errors.New("x509: unknown elliptic curve")
  1634. }
  1635. case *PublicKey:
  1636. pubType = ECDSA
  1637. switch pub.Curve {
  1638. case P256Sm2():
  1639. hashFunc = SM3
  1640. sigAlgo.Algorithm = oidSignatureSM2WithSM3
  1641. default:
  1642. err = errors.New("x509: unknown SM2 curve")
  1643. }
  1644. default:
  1645. err = errors.New("x509: only RSA and ECDSA keys supported")
  1646. }
  1647. if err != nil {
  1648. return
  1649. }
  1650. if requestedSigAlgo == 0 {
  1651. return
  1652. }
  1653. found := false
  1654. for _, details := range signatureAlgorithmDetails {
  1655. if details.algo == requestedSigAlgo {
  1656. if details.pubKeyAlgo != pubType {
  1657. err = errors.New("x509: requested SignatureAlgorithm does not match private key type")
  1658. return
  1659. }
  1660. sigAlgo.Algorithm, hashFunc = details.oid, details.hash
  1661. if hashFunc == 0 {
  1662. err = errors.New("x509: cannot sign with hash function requested")
  1663. return
  1664. }
  1665. if requestedSigAlgo.isRSAPSS() {
  1666. sigAlgo.Parameters = rsaPSSParameters(hashFunc)
  1667. }
  1668. found = true
  1669. break
  1670. }
  1671. }
  1672. if !found {
  1673. err = errors.New("x509: unknown SignatureAlgorithm")
  1674. }
  1675. return
  1676. }
  1677. // CreateCertificate creates a new certificate based on a template. The
  1678. // following members of template are used: SerialNumber, Subject, NotBefore,
  1679. // NotAfter, KeyUsage, ExtKeyUsage, UnknownExtKeyUsage, BasicConstraintsValid,
  1680. // IsCA, MaxPathLen, SubjectKeyId, DNSNames, PermittedDNSDomainsCritical,
  1681. // PermittedDNSDomains, SignatureAlgorithm.
  1682. //
  1683. // The certificate is signed by parent. If parent is equal to template then the
  1684. // certificate is self-signed. The parameter pub is the public key of the
  1685. // signee and priv is the private key of the signer.
  1686. //
  1687. // The returned slice is the certificate in DER encoding.
  1688. //
  1689. // All keys types that are implemented via crypto.Signer are supported (This
  1690. // includes *rsa.PublicKey and *ecdsa.PublicKey.)
  1691. func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv interface{}) (cert []byte, err error) {
  1692. key, ok := priv.(crypto.Signer)
  1693. if !ok {
  1694. return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
  1695. }
  1696. if template.SerialNumber == nil {
  1697. return nil, errors.New("x509: no SerialNumber given")
  1698. }
  1699. hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
  1700. if err != nil {
  1701. return nil, err
  1702. }
  1703. publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub)
  1704. if err != nil {
  1705. return nil, err
  1706. }
  1707. asn1Issuer, err := subjectBytes(parent)
  1708. if err != nil {
  1709. return
  1710. }
  1711. asn1Subject, err := subjectBytes(template)
  1712. if err != nil {
  1713. return
  1714. }
  1715. if !bytes.Equal(asn1Issuer, asn1Subject) && len(parent.SubjectKeyId) > 0 {
  1716. template.AuthorityKeyId = parent.SubjectKeyId
  1717. }
  1718. extensions, err := buildExtensions(template)
  1719. if err != nil {
  1720. return
  1721. }
  1722. encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
  1723. c := tbsCertificate{
  1724. Version: 2,
  1725. SerialNumber: template.SerialNumber,
  1726. SignatureAlgorithm: signatureAlgorithm,
  1727. Issuer: asn1.RawValue{FullBytes: asn1Issuer},
  1728. Validity: validity{template.NotBefore.UTC(), template.NotAfter.UTC()},
  1729. Subject: asn1.RawValue{FullBytes: asn1Subject},
  1730. PublicKey: publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},
  1731. Extensions: extensions,
  1732. }
  1733. tbsCertContents, err := asn1.Marshal(c)
  1734. if err != nil {
  1735. return
  1736. }
  1737. c.Raw = tbsCertContents
  1738. h := hashFunc.New()
  1739. h.Write(tbsCertContents)
  1740. digest := h.Sum(nil)
  1741. var signerOpts crypto.SignerOpts
  1742. signerOpts = hashFunc
  1743. if template.SignatureAlgorithm != 0 && template.SignatureAlgorithm.isRSAPSS() {
  1744. signerOpts = &rsa.PSSOptions{
  1745. SaltLength: rsa.PSSSaltLengthEqualsHash,
  1746. Hash: crypto.Hash(hashFunc),
  1747. }
  1748. }
  1749. var signature []byte
  1750. signature, err = key.Sign(rand, digest, signerOpts)
  1751. if err != nil {
  1752. return
  1753. }
  1754. return asn1.Marshal(certificate{
  1755. nil,
  1756. c,
  1757. signatureAlgorithm,
  1758. asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
  1759. })
  1760. }
  1761. // pemCRLPrefix is the magic string that indicates that we have a PEM encoded
  1762. // CRL.
  1763. var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
  1764. // pemType is the type of a PEM encoded CRL.
  1765. var pemType = "X509 CRL"
  1766. // ParseCRL parses a CRL from the given bytes. It's often the case that PEM
  1767. // encoded CRLs will appear where they should be DER encoded, so this function
  1768. // will transparently handle PEM encoding as long as there isn't any leading
  1769. // garbage.
  1770. func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) {
  1771. if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
  1772. block, _ := pem.Decode(crlBytes)
  1773. if block != nil && block.Type == pemType {
  1774. crlBytes = block.Bytes
  1775. }
  1776. }
  1777. return ParseDERCRL(crlBytes)
  1778. }
  1779. // ParseDERCRL parses a DER encoded CRL from the given bytes.
  1780. func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) {
  1781. certList := new(pkix.CertificateList)
  1782. if rest, err := asn1.Unmarshal(derBytes, certList); err != nil {
  1783. return nil, err
  1784. } else if len(rest) != 0 {
  1785. return nil, errors.New("x509: trailing data after CRL")
  1786. }
  1787. return certList, nil
  1788. }
  1789. // CreateCRL returns a DER encoded CRL, signed by this Certificate, that
  1790. // contains the given list of revoked certificates.
  1791. func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
  1792. key, ok := priv.(crypto.Signer)
  1793. if !ok {
  1794. return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
  1795. }
  1796. hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), 0)
  1797. if err != nil {
  1798. return nil, err
  1799. }
  1800. // Force revocation times to UTC per RFC 5280.
  1801. revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts))
  1802. for i, rc := range revokedCerts {
  1803. rc.RevocationTime = rc.RevocationTime.UTC()
  1804. revokedCertsUTC[i] = rc
  1805. }
  1806. tbsCertList := pkix.TBSCertificateList{
  1807. Version: 1,
  1808. Signature: signatureAlgorithm,
  1809. Issuer: c.Subject.ToRDNSequence(),
  1810. ThisUpdate: now.UTC(),
  1811. NextUpdate: expiry.UTC(),
  1812. RevokedCertificates: revokedCertsUTC,
  1813. }
  1814. // Authority Key Id
  1815. if len(c.SubjectKeyId) > 0 {
  1816. var aki pkix.Extension
  1817. aki.Id = oidExtensionAuthorityKeyId
  1818. aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId})
  1819. if err != nil {
  1820. return
  1821. }
  1822. tbsCertList.Extensions = append(tbsCertList.Extensions, aki)
  1823. }
  1824. tbsCertListContents, err := asn1.Marshal(tbsCertList)
  1825. if err != nil {
  1826. return
  1827. }
  1828. h := hashFunc.New()
  1829. h.Write(tbsCertListContents)
  1830. digest := h.Sum(nil)
  1831. var signature []byte
  1832. signature, err = key.Sign(rand, digest, hashFunc)
  1833. if err != nil {
  1834. return
  1835. }
  1836. return asn1.Marshal(pkix.CertificateList{
  1837. TBSCertList: tbsCertList,
  1838. SignatureAlgorithm: signatureAlgorithm,
  1839. SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
  1840. })
  1841. }
  1842. // CertificateRequest represents a PKCS #10, certificate signature request.
  1843. type CertificateRequest struct {
  1844. Raw []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
  1845. RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content.
  1846. RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
  1847. RawSubject []byte // DER encoded Subject.
  1848. Version int
  1849. Signature []byte
  1850. SignatureAlgorithm SignatureAlgorithm
  1851. PublicKeyAlgorithm PublicKeyAlgorithm
  1852. PublicKey interface{}
  1853. Subject pkix.Name
  1854. // Attributes is the dried husk of a bug and shouldn't be used.
  1855. Attributes []pkix.AttributeTypeAndValueSET
  1856. // Extensions contains raw X.509 extensions. When parsing CSRs, this
  1857. // can be used to extract extensions that are not parsed by this
  1858. // package.
  1859. Extensions []pkix.Extension
  1860. // ExtraExtensions contains extensions to be copied, raw, into any
  1861. // marshaled CSR. Values override any extensions that would otherwise
  1862. // be produced based on the other fields but are overridden by any
  1863. // extensions specified in Attributes.
  1864. //
  1865. // The ExtraExtensions field is not populated when parsing CSRs, see
  1866. // Extensions.
  1867. ExtraExtensions []pkix.Extension
  1868. // Subject Alternate Name values.
  1869. DNSNames []string
  1870. EmailAddresses []string
  1871. IPAddresses []net.IP
  1872. }
  1873. // These structures reflect the ASN.1 structure of X.509 certificate
  1874. // signature requests (see RFC 2986):
  1875. type tbsCertificateRequest struct {
  1876. Raw asn1.RawContent
  1877. Version int
  1878. Subject asn1.RawValue
  1879. PublicKey publicKeyInfo
  1880. RawAttributes []asn1.RawValue `asn1:"tag:0"`
  1881. }
  1882. type certificateRequest struct {
  1883. Raw asn1.RawContent
  1884. TBSCSR tbsCertificateRequest
  1885. SignatureAlgorithm pkix.AlgorithmIdentifier
  1886. SignatureValue asn1.BitString
  1887. }
  1888. // oidExtensionRequest is a PKCS#9 OBJECT IDENTIFIER that indicates requested
  1889. // extensions in a CSR.
  1890. var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14}
  1891. // newRawAttributes converts AttributeTypeAndValueSETs from a template
  1892. // CertificateRequest's Attributes into tbsCertificateRequest RawAttributes.
  1893. func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) {
  1894. var rawAttributes []asn1.RawValue
  1895. b, err := asn1.Marshal(attributes)
  1896. if err != nil {
  1897. return nil, err
  1898. }
  1899. rest, err := asn1.Unmarshal(b, &rawAttributes)
  1900. if err != nil {
  1901. return nil, err
  1902. }
  1903. if len(rest) != 0 {
  1904. return nil, errors.New("x509: failed to unmarshal raw CSR Attributes")
  1905. }
  1906. return rawAttributes, nil
  1907. }
  1908. // parseRawAttributes Unmarshals RawAttributes intos AttributeTypeAndValueSETs.
  1909. func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET {
  1910. var attributes []pkix.AttributeTypeAndValueSET
  1911. for _, rawAttr := range rawAttributes {
  1912. var attr pkix.AttributeTypeAndValueSET
  1913. rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr)
  1914. // Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET
  1915. // (i.e.: challengePassword or unstructuredName).
  1916. if err == nil && len(rest) == 0 {
  1917. attributes = append(attributes, attr)
  1918. }
  1919. }
  1920. return attributes
  1921. }
  1922. // parseCSRExtensions parses the attributes from a CSR and extracts any
  1923. // requested extensions.
  1924. func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) {
  1925. // pkcs10Attribute reflects the Attribute structure from section 4.1 of
  1926. // https://tools.ietf.org/html/rfc2986.
  1927. type pkcs10Attribute struct {
  1928. Id asn1.ObjectIdentifier
  1929. Values []asn1.RawValue `asn1:"set"`
  1930. }
  1931. var ret []pkix.Extension
  1932. for _, rawAttr := range rawAttributes {
  1933. var attr pkcs10Attribute
  1934. if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 {
  1935. // Ignore attributes that don't parse.
  1936. continue
  1937. }
  1938. if !attr.Id.Equal(oidExtensionRequest) {
  1939. continue
  1940. }
  1941. var extensions []pkix.Extension
  1942. if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil {
  1943. return nil, err
  1944. }
  1945. ret = append(ret, extensions...)
  1946. }
  1947. return ret, nil
  1948. }
  1949. // CreateCertificateRequest creates a new certificate request based on a template.
  1950. // The following members of template are used: Subject, Attributes,
  1951. // SignatureAlgorithm, Extensions, DNSNames, EmailAddresses, and IPAddresses.
  1952. // The private key is the private key of the signer.
  1953. //
  1954. // The returned slice is the certificate request in DER encoding.
  1955. //
  1956. // All keys types that are implemented via crypto.Signer are supported (This
  1957. // includes *rsa.PublicKey and *ecdsa.PublicKey.)
  1958. func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv interface{}) (csr []byte, err error) {
  1959. key, ok := priv.(crypto.Signer)
  1960. if !ok {
  1961. return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
  1962. }
  1963. var hashFunc Hash
  1964. var sigAlgo pkix.AlgorithmIdentifier
  1965. hashFunc, sigAlgo, err = signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
  1966. if err != nil {
  1967. return nil, err
  1968. }
  1969. var publicKeyBytes []byte
  1970. var publicKeyAlgorithm pkix.AlgorithmIdentifier
  1971. publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(key.Public())
  1972. if err != nil {
  1973. return nil, err
  1974. }
  1975. var extensions []pkix.Extension
  1976. if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0) &&
  1977. !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
  1978. sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses)
  1979. if err != nil {
  1980. return nil, err
  1981. }
  1982. extensions = append(extensions, pkix.Extension{
  1983. Id: oidExtensionSubjectAltName,
  1984. Value: sanBytes,
  1985. })
  1986. }
  1987. extensions = append(extensions, template.ExtraExtensions...)
  1988. var attributes []pkix.AttributeTypeAndValueSET
  1989. attributes = append(attributes, template.Attributes...)
  1990. if len(extensions) > 0 {
  1991. // specifiedExtensions contains all the extensions that we
  1992. // found specified via template.Attributes.
  1993. specifiedExtensions := make(map[string]bool)
  1994. for _, atvSet := range template.Attributes {
  1995. if !atvSet.Type.Equal(oidExtensionRequest) {
  1996. continue
  1997. }
  1998. for _, atvs := range atvSet.Value {
  1999. for _, atv := range atvs {
  2000. specifiedExtensions[atv.Type.String()] = true
  2001. }
  2002. }
  2003. }
  2004. atvs := make([]pkix.AttributeTypeAndValue, 0, len(extensions))
  2005. for _, e := range extensions {
  2006. if specifiedExtensions[e.Id.String()] {
  2007. // Attributes already contained a value for
  2008. // this extension and it takes priority.
  2009. continue
  2010. }
  2011. atvs = append(atvs, pkix.AttributeTypeAndValue{
  2012. // There is no place for the critical flag in a CSR.
  2013. Type: e.Id,
  2014. Value: e.Value,
  2015. })
  2016. }
  2017. // Append the extensions to an existing attribute if possible.
  2018. appended := false
  2019. for _, atvSet := range attributes {
  2020. if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 {
  2021. continue
  2022. }
  2023. atvSet.Value[0] = append(atvSet.Value[0], atvs...)
  2024. appended = true
  2025. break
  2026. }
  2027. // Otherwise, add a new attribute for the extensions.
  2028. if !appended {
  2029. attributes = append(attributes, pkix.AttributeTypeAndValueSET{
  2030. Type: oidExtensionRequest,
  2031. Value: [][]pkix.AttributeTypeAndValue{
  2032. atvs,
  2033. },
  2034. })
  2035. }
  2036. }
  2037. asn1Subject := template.RawSubject
  2038. if len(asn1Subject) == 0 {
  2039. asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence())
  2040. if err != nil {
  2041. return
  2042. }
  2043. }
  2044. rawAttributes, err := newRawAttributes(attributes)
  2045. if err != nil {
  2046. return
  2047. }
  2048. tbsCSR := tbsCertificateRequest{
  2049. Version: 0, // PKCS #10, RFC 2986
  2050. Subject: asn1.RawValue{FullBytes: asn1Subject},
  2051. PublicKey: publicKeyInfo{
  2052. Algorithm: publicKeyAlgorithm,
  2053. PublicKey: asn1.BitString{
  2054. Bytes: publicKeyBytes,
  2055. BitLength: len(publicKeyBytes) * 8,
  2056. },
  2057. },
  2058. RawAttributes: rawAttributes,
  2059. }
  2060. tbsCSRContents, err := asn1.Marshal(tbsCSR)
  2061. if err != nil {
  2062. return
  2063. }
  2064. tbsCSR.Raw = tbsCSRContents
  2065. h := hashFunc.New()
  2066. h.Write(tbsCSRContents)
  2067. digest := h.Sum(nil)
  2068. var signature []byte
  2069. signature, err = key.Sign(rand, digest, hashFunc)
  2070. if err != nil {
  2071. return
  2072. }
  2073. return asn1.Marshal(certificateRequest{
  2074. TBSCSR: tbsCSR,
  2075. SignatureAlgorithm: sigAlgo,
  2076. SignatureValue: asn1.BitString{
  2077. Bytes: signature,
  2078. BitLength: len(signature) * 8,
  2079. },
  2080. })
  2081. }
  2082. // ParseCertificateRequest parses a single certificate request from the
  2083. // given ASN.1 DER data.
  2084. func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) {
  2085. var csr certificateRequest
  2086. rest, err := asn1.Unmarshal(asn1Data, &csr)
  2087. if err != nil {
  2088. return nil, err
  2089. } else if len(rest) != 0 {
  2090. return nil, asn1.SyntaxError{Msg: "trailing data"}
  2091. }
  2092. return parseCertificateRequest(&csr)
  2093. }
  2094. func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) {
  2095. out := &CertificateRequest{
  2096. Raw: in.Raw,
  2097. RawTBSCertificateRequest: in.TBSCSR.Raw,
  2098. RawSubjectPublicKeyInfo: in.TBSCSR.PublicKey.Raw,
  2099. RawSubject: in.TBSCSR.Subject.FullBytes,
  2100. Signature: in.SignatureValue.RightAlign(),
  2101. SignatureAlgorithm: getSignatureAlgorithmFromAI(in.SignatureAlgorithm),
  2102. PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm),
  2103. Version: in.TBSCSR.Version,
  2104. Attributes: parseRawAttributes(in.TBSCSR.RawAttributes),
  2105. }
  2106. var err error
  2107. out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCSR.PublicKey)
  2108. if err != nil {
  2109. return nil, err
  2110. }
  2111. var subject pkix.RDNSequence
  2112. if rest, err := asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil {
  2113. return nil, err
  2114. } else if len(rest) != 0 {
  2115. return nil, errors.New("x509: trailing data after X.509 Subject")
  2116. }
  2117. out.Subject.FillFromRDNSequence(&subject)
  2118. if out.Extensions, err = parseCSRExtensions(in.TBSCSR.RawAttributes); err != nil {
  2119. return nil, err
  2120. }
  2121. for _, extension := range out.Extensions {
  2122. if extension.Id.Equal(oidExtensionSubjectAltName) {
  2123. out.DNSNames, out.EmailAddresses, out.IPAddresses, err = parseSANExtension(extension.Value)
  2124. if err != nil {
  2125. return nil, err
  2126. }
  2127. }
  2128. }
  2129. return out, nil
  2130. }
  2131. // CheckSignature reports whether the signature on c is valid.
  2132. func (c *CertificateRequest) CheckSignature() error {
  2133. return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey)
  2134. }
  2135. func ReadCertificateRequestFromMem(data []byte) (*CertificateRequest, error) {
  2136. block, _ := pem.Decode(data)
  2137. if block == nil {
  2138. return nil, errors.New("failed to decode certificate request")
  2139. }
  2140. return ParseCertificateRequest(block.Bytes)
  2141. }
  2142. func ReadCertificateRequestFromPem(FileName string) (*CertificateRequest, error) {
  2143. data, err := ioutil.ReadFile(FileName)
  2144. if err != nil {
  2145. return nil, err
  2146. }
  2147. return ReadCertificateRequestFromMem(data)
  2148. }
  2149. func CreateCertificateRequestToMem(template *CertificateRequest, privKey *PrivateKey) ([]byte, error) {
  2150. der, err := CreateCertificateRequest(rand.Reader, template, privKey)
  2151. if err != nil {
  2152. return nil, err
  2153. }
  2154. block := &pem.Block{
  2155. Type: "CERTIFICATE REQUEST",
  2156. Bytes: der,
  2157. }
  2158. return pem.EncodeToMemory(block), nil
  2159. }
  2160. func CreateCertificateRequestToPem(FileName string, template *CertificateRequest,
  2161. privKey *PrivateKey) (bool, error) {
  2162. der, err := CreateCertificateRequest(rand.Reader, template, privKey)
  2163. if err != nil {
  2164. return false, err
  2165. }
  2166. block := &pem.Block{
  2167. Type: "CERTIFICATE REQUEST",
  2168. Bytes: der,
  2169. }
  2170. file, err := os.Create(FileName)
  2171. if err != nil {
  2172. return false, err
  2173. }
  2174. defer file.Close()
  2175. err = pem.Encode(file, block)
  2176. if err != nil {
  2177. return false, err
  2178. }
  2179. return true, nil
  2180. }
  2181. func ReadCertificateFromMem(data []byte) (*Certificate, error) {
  2182. block, _ := pem.Decode(data)
  2183. if block == nil {
  2184. return nil, errors.New("failed to decode certificate request")
  2185. }
  2186. return ParseCertificate(block.Bytes)
  2187. }
  2188. func ReadCertificateFromPem(FileName string) (*Certificate, error) {
  2189. data, err := ioutil.ReadFile(FileName)
  2190. if err != nil {
  2191. return nil, err
  2192. }
  2193. return ReadCertificateFromMem(data)
  2194. }
  2195. func CreateCertificateToMem(template, parent *Certificate, pubKey *PublicKey, privKey *PrivateKey) ([]byte, error) {
  2196. der, err := CreateCertificate(rand.Reader, template, parent, pubKey, privKey)
  2197. if err != nil {
  2198. return nil, err
  2199. }
  2200. block := &pem.Block{
  2201. Type: "CERTIFICATE",
  2202. Bytes: der,
  2203. }
  2204. return pem.EncodeToMemory(block), nil
  2205. }
  2206. func CreateCertificateToPem(FileName string, template, parent *Certificate, pubKey *PublicKey, privKey *PrivateKey) (bool, error) {
  2207. der, err := CreateCertificate(rand.Reader, template, parent, pubKey, privKey)
  2208. if err != nil {
  2209. return false, err
  2210. }
  2211. block := &pem.Block{
  2212. Type: "CERTIFICATE",
  2213. Bytes: der,
  2214. }
  2215. file, err := os.Create(FileName)
  2216. if err != nil {
  2217. return false, err
  2218. }
  2219. defer file.Close()
  2220. err = pem.Encode(file, block)
  2221. if err != nil {
  2222. return false, err
  2223. }
  2224. return true, nil
  2225. }