x509.go 94 KB

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