x509.go 109 KB

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