x509.go 92 KB

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