x509.go 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622
  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. // START CT CHANGES
  7. // This is a fork of the go library crypto/x509 package, it's more relaxed
  8. // about certificates that it'll accept, and exports the TBSCertificate
  9. // structure.
  10. // END CT CHANGES
  11. package x509
  12. import (
  13. "bytes"
  14. "crypto"
  15. "crypto/dsa"
  16. "crypto/ecdsa"
  17. "crypto/elliptic"
  18. "crypto/rsa"
  19. "crypto/sha1"
  20. // START CT CHANGES
  21. "github.com/google/certificate-transparency/go/asn1"
  22. "github.com/google/certificate-transparency/go/x509/pkix"
  23. // END CT CHANGES
  24. "encoding/pem"
  25. "errors"
  26. // START CT CHANGES
  27. "fmt"
  28. // END CT CHANGES
  29. "io"
  30. "math/big"
  31. "net"
  32. "time"
  33. )
  34. // pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
  35. // in RFC 3280.
  36. type pkixPublicKey struct {
  37. Algo pkix.AlgorithmIdentifier
  38. BitString asn1.BitString
  39. }
  40. // ParsePKIXPublicKey parses a DER encoded public key. These values are
  41. // typically found in PEM blocks with "BEGIN PUBLIC KEY".
  42. func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) {
  43. var pki publicKeyInfo
  44. if _, err = asn1.Unmarshal(derBytes, &pki); err != nil {
  45. return
  46. }
  47. algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm)
  48. if algo == UnknownPublicKeyAlgorithm {
  49. return nil, errors.New("x509: unknown public key algorithm")
  50. }
  51. return parsePublicKey(algo, &pki)
  52. }
  53. func marshalPublicKey(pub interface{}) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) {
  54. switch pub := pub.(type) {
  55. case *rsa.PublicKey:
  56. publicKeyBytes, err = asn1.Marshal(rsaPublicKey{
  57. N: pub.N,
  58. E: pub.E,
  59. })
  60. publicKeyAlgorithm.Algorithm = oidPublicKeyRSA
  61. // This is a NULL parameters value which is technically
  62. // superfluous, but most other code includes it and, by
  63. // doing this, we match their public key hashes.
  64. publicKeyAlgorithm.Parameters = asn1.RawValue{
  65. Tag: 5,
  66. }
  67. case *ecdsa.PublicKey:
  68. publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
  69. oid, ok := oidFromNamedCurve(pub.Curve)
  70. if !ok {
  71. return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
  72. }
  73. publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
  74. var paramBytes []byte
  75. paramBytes, err = asn1.Marshal(oid)
  76. if err != nil {
  77. return
  78. }
  79. publicKeyAlgorithm.Parameters.FullBytes = paramBytes
  80. default:
  81. return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: only RSA and ECDSA public keys supported")
  82. }
  83. return publicKeyBytes, publicKeyAlgorithm, nil
  84. }
  85. // MarshalPKIXPublicKey serialises a public key to DER-encoded PKIX format.
  86. func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
  87. var publicKeyBytes []byte
  88. var publicKeyAlgorithm pkix.AlgorithmIdentifier
  89. var err error
  90. if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
  91. return nil, err
  92. }
  93. pkix := pkixPublicKey{
  94. Algo: publicKeyAlgorithm,
  95. BitString: asn1.BitString{
  96. Bytes: publicKeyBytes,
  97. BitLength: 8 * len(publicKeyBytes),
  98. },
  99. }
  100. ret, _ := asn1.Marshal(pkix)
  101. return ret, nil
  102. }
  103. // These structures reflect the ASN.1 structure of X.509 certificates.:
  104. type certificate struct {
  105. Raw asn1.RawContent
  106. TBSCertificate tbsCertificate
  107. SignatureAlgorithm pkix.AlgorithmIdentifier
  108. SignatureValue asn1.BitString
  109. }
  110. type tbsCertificate struct {
  111. Raw asn1.RawContent
  112. Version int `asn1:"optional,explicit,default:1,tag:0"`
  113. SerialNumber *big.Int
  114. SignatureAlgorithm pkix.AlgorithmIdentifier
  115. Issuer asn1.RawValue
  116. Validity validity
  117. Subject asn1.RawValue
  118. PublicKey publicKeyInfo
  119. UniqueId asn1.BitString `asn1:"optional,tag:1"`
  120. SubjectUniqueId asn1.BitString `asn1:"optional,tag:2"`
  121. Extensions []pkix.Extension `asn1:"optional,explicit,tag:3"`
  122. }
  123. type dsaAlgorithmParameters struct {
  124. P, Q, G *big.Int
  125. }
  126. type dsaSignature struct {
  127. R, S *big.Int
  128. }
  129. type ecdsaSignature dsaSignature
  130. type validity struct {
  131. NotBefore, NotAfter time.Time
  132. }
  133. type publicKeyInfo struct {
  134. Raw asn1.RawContent
  135. Algorithm pkix.AlgorithmIdentifier
  136. PublicKey asn1.BitString
  137. }
  138. // RFC 5280, 4.2.1.1
  139. type authKeyId struct {
  140. Id []byte `asn1:"optional,tag:0"`
  141. }
  142. type SignatureAlgorithm int
  143. const (
  144. UnknownSignatureAlgorithm SignatureAlgorithm = iota
  145. MD2WithRSA
  146. MD5WithRSA
  147. SHA1WithRSA
  148. SHA256WithRSA
  149. SHA384WithRSA
  150. SHA512WithRSA
  151. DSAWithSHA1
  152. DSAWithSHA256
  153. ECDSAWithSHA1
  154. ECDSAWithSHA256
  155. ECDSAWithSHA384
  156. ECDSAWithSHA512
  157. )
  158. type PublicKeyAlgorithm int
  159. const (
  160. UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
  161. RSA
  162. DSA
  163. ECDSA
  164. )
  165. // OIDs for signature algorithms
  166. //
  167. // pkcs-1 OBJECT IDENTIFIER ::= {
  168. // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
  169. //
  170. //
  171. // RFC 3279 2.2.1 RSA Signature Algorithms
  172. //
  173. // md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 }
  174. //
  175. // md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }
  176. //
  177. // sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }
  178. //
  179. // dsaWithSha1 OBJECT IDENTIFIER ::= {
  180. // iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 }
  181. //
  182. // RFC 3279 2.2.3 ECDSA Signature Algorithm
  183. //
  184. // ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {
  185. // iso(1) member-body(2) us(840) ansi-x962(10045)
  186. // signatures(4) ecdsa-with-SHA1(1)}
  187. //
  188. //
  189. // RFC 4055 5 PKCS #1 Version 1.5
  190. //
  191. // sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
  192. //
  193. // sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
  194. //
  195. // sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
  196. //
  197. //
  198. // RFC 5758 3.1 DSA Signature Algorithms
  199. //
  200. // dsaWithSha256 OBJECT IDENTIFIER ::= {
  201. // joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
  202. // csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
  203. //
  204. // RFC 5758 3.2 ECDSA Signature Algorithm
  205. //
  206. // ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
  207. // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 }
  208. //
  209. // ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
  210. // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 }
  211. //
  212. // ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
  213. // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 }
  214. var (
  215. oidSignatureMD2WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2}
  216. oidSignatureMD5WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
  217. oidSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
  218. oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
  219. oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
  220. oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
  221. oidSignatureDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
  222. oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 4, 3, 2}
  223. oidSignatureECDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1}
  224. oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2}
  225. oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3}
  226. oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4}
  227. )
  228. func getSignatureAlgorithmFromOID(oid asn1.ObjectIdentifier) SignatureAlgorithm {
  229. switch {
  230. case oid.Equal(oidSignatureMD2WithRSA):
  231. return MD2WithRSA
  232. case oid.Equal(oidSignatureMD5WithRSA):
  233. return MD5WithRSA
  234. case oid.Equal(oidSignatureSHA1WithRSA):
  235. return SHA1WithRSA
  236. case oid.Equal(oidSignatureSHA256WithRSA):
  237. return SHA256WithRSA
  238. case oid.Equal(oidSignatureSHA384WithRSA):
  239. return SHA384WithRSA
  240. case oid.Equal(oidSignatureSHA512WithRSA):
  241. return SHA512WithRSA
  242. case oid.Equal(oidSignatureDSAWithSHA1):
  243. return DSAWithSHA1
  244. case oid.Equal(oidSignatureDSAWithSHA256):
  245. return DSAWithSHA256
  246. case oid.Equal(oidSignatureECDSAWithSHA1):
  247. return ECDSAWithSHA1
  248. case oid.Equal(oidSignatureECDSAWithSHA256):
  249. return ECDSAWithSHA256
  250. case oid.Equal(oidSignatureECDSAWithSHA384):
  251. return ECDSAWithSHA384
  252. case oid.Equal(oidSignatureECDSAWithSHA512):
  253. return ECDSAWithSHA512
  254. }
  255. return UnknownSignatureAlgorithm
  256. }
  257. // RFC 3279, 2.3 Public Key Algorithms
  258. //
  259. // pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
  260. // rsadsi(113549) pkcs(1) 1 }
  261. //
  262. // rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
  263. //
  264. // id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
  265. // x9-57(10040) x9cm(4) 1 }
  266. //
  267. // RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters
  268. //
  269. // id-ecPublicKey OBJECT IDENTIFIER ::= {
  270. // iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
  271. var (
  272. oidPublicKeyRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
  273. oidPublicKeyDSA = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
  274. oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
  275. )
  276. func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
  277. switch {
  278. case oid.Equal(oidPublicKeyRSA):
  279. return RSA
  280. case oid.Equal(oidPublicKeyDSA):
  281. return DSA
  282. case oid.Equal(oidPublicKeyECDSA):
  283. return ECDSA
  284. }
  285. return UnknownPublicKeyAlgorithm
  286. }
  287. // RFC 5480, 2.1.1.1. Named Curve
  288. //
  289. // secp224r1 OBJECT IDENTIFIER ::= {
  290. // iso(1) identified-organization(3) certicom(132) curve(0) 33 }
  291. //
  292. // secp256r1 OBJECT IDENTIFIER ::= {
  293. // iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
  294. // prime(1) 7 }
  295. //
  296. // secp384r1 OBJECT IDENTIFIER ::= {
  297. // iso(1) identified-organization(3) certicom(132) curve(0) 34 }
  298. //
  299. // secp521r1 OBJECT IDENTIFIER ::= {
  300. // iso(1) identified-organization(3) certicom(132) curve(0) 35 }
  301. //
  302. // NB: secp256r1 is equivalent to prime256v1
  303. var (
  304. oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
  305. oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
  306. oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
  307. oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
  308. )
  309. func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve {
  310. switch {
  311. case oid.Equal(oidNamedCurveP224):
  312. return elliptic.P224()
  313. case oid.Equal(oidNamedCurveP256):
  314. return elliptic.P256()
  315. case oid.Equal(oidNamedCurveP384):
  316. return elliptic.P384()
  317. case oid.Equal(oidNamedCurveP521):
  318. return elliptic.P521()
  319. }
  320. return nil
  321. }
  322. func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) {
  323. switch curve {
  324. case elliptic.P224():
  325. return oidNamedCurveP224, true
  326. case elliptic.P256():
  327. return oidNamedCurveP256, true
  328. case elliptic.P384():
  329. return oidNamedCurveP384, true
  330. case elliptic.P521():
  331. return oidNamedCurveP521, true
  332. }
  333. return nil, false
  334. }
  335. // KeyUsage represents the set of actions that are valid for a given key. It's
  336. // a bitmap of the KeyUsage* constants.
  337. type KeyUsage int
  338. const (
  339. KeyUsageDigitalSignature KeyUsage = 1 << iota
  340. KeyUsageContentCommitment
  341. KeyUsageKeyEncipherment
  342. KeyUsageDataEncipherment
  343. KeyUsageKeyAgreement
  344. KeyUsageCertSign
  345. KeyUsageCRLSign
  346. KeyUsageEncipherOnly
  347. KeyUsageDecipherOnly
  348. )
  349. // RFC 5280, 4.2.1.12 Extended Key Usage
  350. //
  351. // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
  352. //
  353. // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
  354. //
  355. // id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 }
  356. // id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 }
  357. // id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 }
  358. // id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 }
  359. // id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 }
  360. // id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 }
  361. var (
  362. oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
  363. oidExtKeyUsageServerAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
  364. oidExtKeyUsageClientAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
  365. oidExtKeyUsageCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
  366. oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
  367. oidExtKeyUsageIPSECEndSystem = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
  368. oidExtKeyUsageIPSECTunnel = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
  369. oidExtKeyUsageIPSECUser = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
  370. oidExtKeyUsageTimeStamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
  371. oidExtKeyUsageOCSPSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
  372. oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
  373. oidExtKeyUsageNetscapeServerGatedCrypto = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
  374. )
  375. // ExtKeyUsage represents an extended set of actions that are valid for a given key.
  376. // Each of the ExtKeyUsage* constants define a unique action.
  377. type ExtKeyUsage int
  378. const (
  379. ExtKeyUsageAny ExtKeyUsage = iota
  380. ExtKeyUsageServerAuth
  381. ExtKeyUsageClientAuth
  382. ExtKeyUsageCodeSigning
  383. ExtKeyUsageEmailProtection
  384. ExtKeyUsageIPSECEndSystem
  385. ExtKeyUsageIPSECTunnel
  386. ExtKeyUsageIPSECUser
  387. ExtKeyUsageTimeStamping
  388. ExtKeyUsageOCSPSigning
  389. ExtKeyUsageMicrosoftServerGatedCrypto
  390. ExtKeyUsageNetscapeServerGatedCrypto
  391. )
  392. // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
  393. var extKeyUsageOIDs = []struct {
  394. extKeyUsage ExtKeyUsage
  395. oid asn1.ObjectIdentifier
  396. }{
  397. {ExtKeyUsageAny, oidExtKeyUsageAny},
  398. {ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
  399. {ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
  400. {ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
  401. {ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
  402. {ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
  403. {ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
  404. {ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
  405. {ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
  406. {ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
  407. {ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
  408. {ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
  409. }
  410. func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) {
  411. for _, pair := range extKeyUsageOIDs {
  412. if oid.Equal(pair.oid) {
  413. return pair.extKeyUsage, true
  414. }
  415. }
  416. return
  417. }
  418. func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
  419. for _, pair := range extKeyUsageOIDs {
  420. if eku == pair.extKeyUsage {
  421. return pair.oid, true
  422. }
  423. }
  424. return
  425. }
  426. // A Certificate represents an X.509 certificate.
  427. type Certificate struct {
  428. Raw []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
  429. RawTBSCertificate []byte // Certificate part of raw ASN.1 DER content.
  430. RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
  431. RawSubject []byte // DER encoded Subject
  432. RawIssuer []byte // DER encoded Issuer
  433. Signature []byte
  434. SignatureAlgorithm SignatureAlgorithm
  435. PublicKeyAlgorithm PublicKeyAlgorithm
  436. PublicKey interface{}
  437. Version int
  438. SerialNumber *big.Int
  439. Issuer pkix.Name
  440. Subject pkix.Name
  441. NotBefore, NotAfter time.Time // Validity bounds.
  442. KeyUsage KeyUsage
  443. // Extensions contains raw X.509 extensions. When parsing certificates,
  444. // this can be used to extract non-critical extensions that are not
  445. // parsed by this package. When marshaling certificates, the Extensions
  446. // field is ignored, see ExtraExtensions.
  447. Extensions []pkix.Extension
  448. // ExtraExtensions contains extensions to be copied, raw, into any
  449. // marshaled certificates. Values override any extensions that would
  450. // otherwise be produced based on the other fields. The ExtraExtensions
  451. // field is not populated when parsing certificates, see Extensions.
  452. ExtraExtensions []pkix.Extension
  453. ExtKeyUsage []ExtKeyUsage // Sequence of extended key usages.
  454. UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
  455. BasicConstraintsValid bool // if true then the next two fields are valid.
  456. IsCA bool
  457. MaxPathLen int
  458. SubjectKeyId []byte
  459. AuthorityKeyId []byte
  460. // RFC 5280, 4.2.2.1 (Authority Information Access)
  461. OCSPServer []string
  462. IssuingCertificateURL []string
  463. // Subject Alternate Name values
  464. DNSNames []string
  465. EmailAddresses []string
  466. IPAddresses []net.IP
  467. // Name constraints
  468. PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
  469. PermittedDNSDomains []string
  470. // CRL Distribution Points
  471. CRLDistributionPoints []string
  472. PolicyIdentifiers []asn1.ObjectIdentifier
  473. }
  474. // ErrUnsupportedAlgorithm results from attempting to perform an operation that
  475. // involves algorithms that are not currently implemented.
  476. var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
  477. // ConstraintViolationError results when a requested usage is not permitted by
  478. // a certificate. For example: checking a signature when the public key isn't a
  479. // certificate signing key.
  480. type ConstraintViolationError struct{}
  481. func (ConstraintViolationError) Error() string {
  482. return "x509: invalid signature: parent certificate cannot sign this kind of certificate"
  483. }
  484. func (c *Certificate) Equal(other *Certificate) bool {
  485. return bytes.Equal(c.Raw, other.Raw)
  486. }
  487. // Entrust have a broken root certificate (CN=Entrust.net Certification
  488. // Authority (2048)) which isn't marked as a CA certificate and is thus invalid
  489. // according to PKIX.
  490. // We recognise this certificate by its SubjectPublicKeyInfo and exempt it
  491. // from the Basic Constraints requirement.
  492. // See http://www.entrust.net/knowledge-base/technote.cfm?tn=7869
  493. //
  494. // TODO(agl): remove this hack once their reissued root is sufficiently
  495. // widespread.
  496. var entrustBrokenSPKI = []byte{
  497. 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09,
  498. 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01,
  499. 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00,
  500. 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01,
  501. 0x00, 0x97, 0xa3, 0x2d, 0x3c, 0x9e, 0xde, 0x05,
  502. 0xda, 0x13, 0xc2, 0x11, 0x8d, 0x9d, 0x8e, 0xe3,
  503. 0x7f, 0xc7, 0x4b, 0x7e, 0x5a, 0x9f, 0xb3, 0xff,
  504. 0x62, 0xab, 0x73, 0xc8, 0x28, 0x6b, 0xba, 0x10,
  505. 0x64, 0x82, 0x87, 0x13, 0xcd, 0x57, 0x18, 0xff,
  506. 0x28, 0xce, 0xc0, 0xe6, 0x0e, 0x06, 0x91, 0x50,
  507. 0x29, 0x83, 0xd1, 0xf2, 0xc3, 0x2a, 0xdb, 0xd8,
  508. 0xdb, 0x4e, 0x04, 0xcc, 0x00, 0xeb, 0x8b, 0xb6,
  509. 0x96, 0xdc, 0xbc, 0xaa, 0xfa, 0x52, 0x77, 0x04,
  510. 0xc1, 0xdb, 0x19, 0xe4, 0xae, 0x9c, 0xfd, 0x3c,
  511. 0x8b, 0x03, 0xef, 0x4d, 0xbc, 0x1a, 0x03, 0x65,
  512. 0xf9, 0xc1, 0xb1, 0x3f, 0x72, 0x86, 0xf2, 0x38,
  513. 0xaa, 0x19, 0xae, 0x10, 0x88, 0x78, 0x28, 0xda,
  514. 0x75, 0xc3, 0x3d, 0x02, 0x82, 0x02, 0x9c, 0xb9,
  515. 0xc1, 0x65, 0x77, 0x76, 0x24, 0x4c, 0x98, 0xf7,
  516. 0x6d, 0x31, 0x38, 0xfb, 0xdb, 0xfe, 0xdb, 0x37,
  517. 0x02, 0x76, 0xa1, 0x18, 0x97, 0xa6, 0xcc, 0xde,
  518. 0x20, 0x09, 0x49, 0x36, 0x24, 0x69, 0x42, 0xf6,
  519. 0xe4, 0x37, 0x62, 0xf1, 0x59, 0x6d, 0xa9, 0x3c,
  520. 0xed, 0x34, 0x9c, 0xa3, 0x8e, 0xdb, 0xdc, 0x3a,
  521. 0xd7, 0xf7, 0x0a, 0x6f, 0xef, 0x2e, 0xd8, 0xd5,
  522. 0x93, 0x5a, 0x7a, 0xed, 0x08, 0x49, 0x68, 0xe2,
  523. 0x41, 0xe3, 0x5a, 0x90, 0xc1, 0x86, 0x55, 0xfc,
  524. 0x51, 0x43, 0x9d, 0xe0, 0xb2, 0xc4, 0x67, 0xb4,
  525. 0xcb, 0x32, 0x31, 0x25, 0xf0, 0x54, 0x9f, 0x4b,
  526. 0xd1, 0x6f, 0xdb, 0xd4, 0xdd, 0xfc, 0xaf, 0x5e,
  527. 0x6c, 0x78, 0x90, 0x95, 0xde, 0xca, 0x3a, 0x48,
  528. 0xb9, 0x79, 0x3c, 0x9b, 0x19, 0xd6, 0x75, 0x05,
  529. 0xa0, 0xf9, 0x88, 0xd7, 0xc1, 0xe8, 0xa5, 0x09,
  530. 0xe4, 0x1a, 0x15, 0xdc, 0x87, 0x23, 0xaa, 0xb2,
  531. 0x75, 0x8c, 0x63, 0x25, 0x87, 0xd8, 0xf8, 0x3d,
  532. 0xa6, 0xc2, 0xcc, 0x66, 0xff, 0xa5, 0x66, 0x68,
  533. 0x55, 0x02, 0x03, 0x01, 0x00, 0x01,
  534. }
  535. // CheckSignatureFrom verifies that the signature on c is a valid signature
  536. // from parent.
  537. func (c *Certificate) CheckSignatureFrom(parent *Certificate) (err error) {
  538. // RFC 5280, 4.2.1.9:
  539. // "If the basic constraints extension is not present in a version 3
  540. // certificate, or the extension is present but the cA boolean is not
  541. // asserted, then the certified public key MUST NOT be used to verify
  542. // certificate signatures."
  543. // (except for Entrust, see comment above entrustBrokenSPKI)
  544. if (parent.Version == 3 && !parent.BasicConstraintsValid ||
  545. parent.BasicConstraintsValid && !parent.IsCA) &&
  546. !bytes.Equal(c.RawSubjectPublicKeyInfo, entrustBrokenSPKI) {
  547. return ConstraintViolationError{}
  548. }
  549. if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
  550. return ConstraintViolationError{}
  551. }
  552. if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
  553. return ErrUnsupportedAlgorithm
  554. }
  555. // TODO(agl): don't ignore the path length constraint.
  556. return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature)
  557. }
  558. // CheckSignature verifies that signature is a valid signature over signed from
  559. // c's public key.
  560. func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) (err error) {
  561. var hashType crypto.Hash
  562. switch algo {
  563. case SHA1WithRSA, DSAWithSHA1, ECDSAWithSHA1:
  564. hashType = crypto.SHA1
  565. case SHA256WithRSA, DSAWithSHA256, ECDSAWithSHA256:
  566. hashType = crypto.SHA256
  567. case SHA384WithRSA, ECDSAWithSHA384:
  568. hashType = crypto.SHA384
  569. case SHA512WithRSA, ECDSAWithSHA512:
  570. hashType = crypto.SHA512
  571. default:
  572. return ErrUnsupportedAlgorithm
  573. }
  574. if !hashType.Available() {
  575. return ErrUnsupportedAlgorithm
  576. }
  577. h := hashType.New()
  578. h.Write(signed)
  579. digest := h.Sum(nil)
  580. switch pub := c.PublicKey.(type) {
  581. case *rsa.PublicKey:
  582. return rsa.VerifyPKCS1v15(pub, hashType, digest, signature)
  583. case *dsa.PublicKey:
  584. dsaSig := new(dsaSignature)
  585. if _, err := asn1.Unmarshal(signature, dsaSig); err != nil {
  586. return err
  587. }
  588. if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 {
  589. return errors.New("x509: DSA signature contained zero or negative values")
  590. }
  591. if !dsa.Verify(pub, digest, dsaSig.R, dsaSig.S) {
  592. return errors.New("x509: DSA verification failure")
  593. }
  594. return
  595. case *ecdsa.PublicKey:
  596. ecdsaSig := new(ecdsaSignature)
  597. if _, err := asn1.Unmarshal(signature, ecdsaSig); err != nil {
  598. return err
  599. }
  600. if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
  601. return errors.New("x509: ECDSA signature contained zero or negative values")
  602. }
  603. if !ecdsa.Verify(pub, digest, ecdsaSig.R, ecdsaSig.S) {
  604. return errors.New("x509: ECDSA verification failure")
  605. }
  606. return
  607. }
  608. return ErrUnsupportedAlgorithm
  609. }
  610. // CheckCRLSignature checks that the signature in crl is from c.
  611. func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) (err error) {
  612. algo := getSignatureAlgorithmFromOID(crl.SignatureAlgorithm.Algorithm)
  613. return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
  614. }
  615. // START CT CHANGES
  616. type UnhandledCriticalExtension struct {
  617. ID asn1.ObjectIdentifier
  618. }
  619. func (h UnhandledCriticalExtension) Error() string {
  620. return fmt.Sprintf("x509: unhandled critical extension (%v)", h.ID)
  621. }
  622. // END CT CHANGES
  623. type basicConstraints struct {
  624. IsCA bool `asn1:"optional"`
  625. MaxPathLen int `asn1:"optional,default:-1"`
  626. }
  627. // RFC 5280 4.2.1.4
  628. type policyInformation struct {
  629. Policy asn1.ObjectIdentifier
  630. // policyQualifiers omitted
  631. }
  632. // RFC 5280, 4.2.1.10
  633. type nameConstraints struct {
  634. Permitted []generalSubtree `asn1:"optional,tag:0"`
  635. Excluded []generalSubtree `asn1:"optional,tag:1"`
  636. }
  637. type generalSubtree struct {
  638. Name string `asn1:"tag:2,optional,ia5"`
  639. }
  640. // RFC 5280, 4.2.2.1
  641. type authorityInfoAccess struct {
  642. Method asn1.ObjectIdentifier
  643. Location asn1.RawValue
  644. }
  645. // RFC 5280, 4.2.1.14
  646. type distributionPoint struct {
  647. DistributionPoint distributionPointName `asn1:"optional,tag:0"`
  648. Reason asn1.BitString `asn1:"optional,tag:1"`
  649. CRLIssuer asn1.RawValue `asn1:"optional,tag:2"`
  650. }
  651. type distributionPointName struct {
  652. FullName asn1.RawValue `asn1:"optional,tag:0"`
  653. RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
  654. }
  655. func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (interface{}, error) {
  656. asn1Data := keyData.PublicKey.RightAlign()
  657. switch algo {
  658. case RSA:
  659. p := new(rsaPublicKey)
  660. _, err := asn1.Unmarshal(asn1Data, p)
  661. if err != nil {
  662. return nil, err
  663. }
  664. if p.N.Sign() <= 0 {
  665. return nil, errors.New("x509: RSA modulus is not a positive number")
  666. }
  667. if p.E <= 0 {
  668. return nil, errors.New("x509: RSA public exponent is not a positive number")
  669. }
  670. pub := &rsa.PublicKey{
  671. E: p.E,
  672. N: p.N,
  673. }
  674. return pub, nil
  675. case DSA:
  676. var p *big.Int
  677. _, err := asn1.Unmarshal(asn1Data, &p)
  678. if err != nil {
  679. return nil, err
  680. }
  681. paramsData := keyData.Algorithm.Parameters.FullBytes
  682. params := new(dsaAlgorithmParameters)
  683. _, err = asn1.Unmarshal(paramsData, params)
  684. if err != nil {
  685. return nil, err
  686. }
  687. if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 {
  688. return nil, errors.New("x509: zero or negative DSA parameter")
  689. }
  690. pub := &dsa.PublicKey{
  691. Parameters: dsa.Parameters{
  692. P: params.P,
  693. Q: params.Q,
  694. G: params.G,
  695. },
  696. Y: p,
  697. }
  698. return pub, nil
  699. case ECDSA:
  700. paramsData := keyData.Algorithm.Parameters.FullBytes
  701. namedCurveOID := new(asn1.ObjectIdentifier)
  702. _, err := asn1.Unmarshal(paramsData, namedCurveOID)
  703. if err != nil {
  704. return nil, err
  705. }
  706. namedCurve := namedCurveFromOID(*namedCurveOID)
  707. if namedCurve == nil {
  708. return nil, errors.New("x509: unsupported elliptic curve")
  709. }
  710. x, y := elliptic.Unmarshal(namedCurve, asn1Data)
  711. if x == nil {
  712. return nil, errors.New("x509: failed to unmarshal elliptic curve point")
  713. }
  714. pub := &ecdsa.PublicKey{
  715. Curve: namedCurve,
  716. X: x,
  717. Y: y,
  718. }
  719. return pub, nil
  720. default:
  721. return nil, nil
  722. }
  723. }
  724. // START CT CHANGES
  725. // NonFatalErrors is an error type which can hold a number of other errors.
  726. // It's used to collect a range of non-fatal errors which occur while parsing
  727. // a certificate, that way we can still match on certs which technically are
  728. // invalid.
  729. type NonFatalErrors struct {
  730. Errors []error
  731. }
  732. // Adds an error to the list of errors contained by NonFatalErrors.
  733. func (e *NonFatalErrors) AddError(err error) {
  734. e.Errors = append(e.Errors, err)
  735. }
  736. // Returns a string consisting of the values of Error() from all of the errors
  737. // contained in |e|
  738. func (e NonFatalErrors) Error() string {
  739. r := "NonFatalErrors: "
  740. for _, err := range e.Errors {
  741. r += err.Error() + "; "
  742. }
  743. return r
  744. }
  745. // Returns true if |e| contains at least one error
  746. func (e *NonFatalErrors) HasError() bool {
  747. return len(e.Errors) > 0
  748. }
  749. // END CT CHANGES
  750. func parseCertificate(in *certificate) (*Certificate, error) {
  751. // START CT CHANGES
  752. var nfe NonFatalErrors
  753. // END CT CHANGES
  754. out := new(Certificate)
  755. out.Raw = in.Raw
  756. out.RawTBSCertificate = in.TBSCertificate.Raw
  757. out.RawSubjectPublicKeyInfo = in.TBSCertificate.PublicKey.Raw
  758. out.RawSubject = in.TBSCertificate.Subject.FullBytes
  759. out.RawIssuer = in.TBSCertificate.Issuer.FullBytes
  760. out.Signature = in.SignatureValue.RightAlign()
  761. out.SignatureAlgorithm =
  762. getSignatureAlgorithmFromOID(in.TBSCertificate.SignatureAlgorithm.Algorithm)
  763. out.PublicKeyAlgorithm =
  764. getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm)
  765. var err error
  766. out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCertificate.PublicKey)
  767. if err != nil {
  768. return nil, err
  769. }
  770. if in.TBSCertificate.SerialNumber.Sign() < 0 {
  771. // START CT CHANGES
  772. nfe.AddError(errors.New("x509: negative serial number"))
  773. // END CT CHANGES
  774. }
  775. out.Version = in.TBSCertificate.Version + 1
  776. out.SerialNumber = in.TBSCertificate.SerialNumber
  777. var issuer, subject pkix.RDNSequence
  778. if _, err := asn1.Unmarshal(in.TBSCertificate.Subject.FullBytes, &subject); err != nil {
  779. return nil, err
  780. }
  781. if _, err := asn1.Unmarshal(in.TBSCertificate.Issuer.FullBytes, &issuer); err != nil {
  782. return nil, err
  783. }
  784. out.Issuer.FillFromRDNSequence(&issuer)
  785. out.Subject.FillFromRDNSequence(&subject)
  786. out.NotBefore = in.TBSCertificate.Validity.NotBefore
  787. out.NotAfter = in.TBSCertificate.Validity.NotAfter
  788. for _, e := range in.TBSCertificate.Extensions {
  789. out.Extensions = append(out.Extensions, e)
  790. if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 {
  791. switch e.Id[3] {
  792. case 15:
  793. // RFC 5280, 4.2.1.3
  794. var usageBits asn1.BitString
  795. _, err := asn1.Unmarshal(e.Value, &usageBits)
  796. if err == nil {
  797. var usage int
  798. for i := 0; i < 9; i++ {
  799. if usageBits.At(i) != 0 {
  800. usage |= 1 << uint(i)
  801. }
  802. }
  803. out.KeyUsage = KeyUsage(usage)
  804. continue
  805. }
  806. case 19:
  807. // RFC 5280, 4.2.1.9
  808. var constraints basicConstraints
  809. _, err := asn1.Unmarshal(e.Value, &constraints)
  810. if err == nil {
  811. out.BasicConstraintsValid = true
  812. out.IsCA = constraints.IsCA
  813. out.MaxPathLen = constraints.MaxPathLen
  814. continue
  815. }
  816. case 17:
  817. // RFC 5280, 4.2.1.6
  818. // SubjectAltName ::= GeneralNames
  819. //
  820. // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
  821. //
  822. // GeneralName ::= CHOICE {
  823. // otherName [0] OtherName,
  824. // rfc822Name [1] IA5String,
  825. // dNSName [2] IA5String,
  826. // x400Address [3] ORAddress,
  827. // directoryName [4] Name,
  828. // ediPartyName [5] EDIPartyName,
  829. // uniformResourceIdentifier [6] IA5String,
  830. // iPAddress [7] OCTET STRING,
  831. // registeredID [8] OBJECT IDENTIFIER }
  832. var seq asn1.RawValue
  833. _, err := asn1.Unmarshal(e.Value, &seq)
  834. if err != nil {
  835. return nil, err
  836. }
  837. if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 {
  838. return nil, asn1.StructuralError{Msg: "bad SAN sequence"}
  839. }
  840. parsedName := false
  841. rest := seq.Bytes
  842. for len(rest) > 0 {
  843. var v asn1.RawValue
  844. rest, err = asn1.Unmarshal(rest, &v)
  845. if err != nil {
  846. return nil, err
  847. }
  848. switch v.Tag {
  849. case 1:
  850. out.EmailAddresses = append(out.EmailAddresses, string(v.Bytes))
  851. parsedName = true
  852. case 2:
  853. out.DNSNames = append(out.DNSNames, string(v.Bytes))
  854. parsedName = true
  855. case 7:
  856. switch len(v.Bytes) {
  857. case net.IPv4len, net.IPv6len:
  858. out.IPAddresses = append(out.IPAddresses, v.Bytes)
  859. default:
  860. // START CT CHANGES
  861. nfe.AddError(fmt.Errorf("x509: certificate contained IP address of length %d : %v", len(v.Bytes), v.Bytes))
  862. // END CT CHANGES
  863. }
  864. }
  865. }
  866. if parsedName {
  867. continue
  868. }
  869. // If we didn't parse any of the names then we
  870. // fall through to the critical check below.
  871. case 30:
  872. // RFC 5280, 4.2.1.10
  873. // NameConstraints ::= SEQUENCE {
  874. // permittedSubtrees [0] GeneralSubtrees OPTIONAL,
  875. // excludedSubtrees [1] GeneralSubtrees OPTIONAL }
  876. //
  877. // GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
  878. //
  879. // GeneralSubtree ::= SEQUENCE {
  880. // base GeneralName,
  881. // minimum [0] BaseDistance DEFAULT 0,
  882. // maximum [1] BaseDistance OPTIONAL }
  883. //
  884. // BaseDistance ::= INTEGER (0..MAX)
  885. var constraints nameConstraints
  886. _, err := asn1.Unmarshal(e.Value, &constraints)
  887. if err != nil {
  888. return nil, err
  889. }
  890. if len(constraints.Excluded) > 0 && e.Critical {
  891. // START CT CHANGES
  892. nfe.AddError(UnhandledCriticalExtension{e.Id})
  893. // END CT CHANGES
  894. }
  895. for _, subtree := range constraints.Permitted {
  896. if len(subtree.Name) == 0 {
  897. if e.Critical {
  898. // START CT CHANGES
  899. nfe.AddError(UnhandledCriticalExtension{e.Id})
  900. // END CT CHANGES
  901. }
  902. continue
  903. }
  904. out.PermittedDNSDomains = append(out.PermittedDNSDomains, subtree.Name)
  905. }
  906. continue
  907. case 31:
  908. // RFC 5280, 4.2.1.14
  909. // CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
  910. //
  911. // DistributionPoint ::= SEQUENCE {
  912. // distributionPoint [0] DistributionPointName OPTIONAL,
  913. // reasons [1] ReasonFlags OPTIONAL,
  914. // cRLIssuer [2] GeneralNames OPTIONAL }
  915. //
  916. // DistributionPointName ::= CHOICE {
  917. // fullName [0] GeneralNames,
  918. // nameRelativeToCRLIssuer [1] RelativeDistinguishedName }
  919. var cdp []distributionPoint
  920. _, err := asn1.Unmarshal(e.Value, &cdp)
  921. if err != nil {
  922. return nil, err
  923. }
  924. for _, dp := range cdp {
  925. var n asn1.RawValue
  926. _, err = asn1.Unmarshal(dp.DistributionPoint.FullName.Bytes, &n)
  927. if err != nil {
  928. return nil, err
  929. }
  930. if n.Tag == 6 {
  931. out.CRLDistributionPoints = append(out.CRLDistributionPoints, string(n.Bytes))
  932. }
  933. }
  934. continue
  935. case 35:
  936. // RFC 5280, 4.2.1.1
  937. var a authKeyId
  938. _, err = asn1.Unmarshal(e.Value, &a)
  939. if err != nil {
  940. return nil, err
  941. }
  942. out.AuthorityKeyId = a.Id
  943. continue
  944. case 37:
  945. // RFC 5280, 4.2.1.12. Extended Key Usage
  946. // id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 }
  947. //
  948. // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
  949. //
  950. // KeyPurposeId ::= OBJECT IDENTIFIER
  951. var keyUsage []asn1.ObjectIdentifier
  952. _, err = asn1.Unmarshal(e.Value, &keyUsage)
  953. if err != nil {
  954. return nil, err
  955. }
  956. for _, u := range keyUsage {
  957. if extKeyUsage, ok := extKeyUsageFromOID(u); ok {
  958. out.ExtKeyUsage = append(out.ExtKeyUsage, extKeyUsage)
  959. } else {
  960. out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u)
  961. }
  962. }
  963. continue
  964. case 14:
  965. // RFC 5280, 4.2.1.2
  966. var keyid []byte
  967. _, err = asn1.Unmarshal(e.Value, &keyid)
  968. if err != nil {
  969. return nil, err
  970. }
  971. out.SubjectKeyId = keyid
  972. continue
  973. case 32:
  974. // RFC 5280 4.2.1.4: Certificate Policies
  975. var policies []policyInformation
  976. if _, err = asn1.Unmarshal(e.Value, &policies); err != nil {
  977. return nil, err
  978. }
  979. out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies))
  980. for i, policy := range policies {
  981. out.PolicyIdentifiers[i] = policy.Policy
  982. }
  983. }
  984. } else if e.Id.Equal(oidExtensionAuthorityInfoAccess) {
  985. // RFC 5280 4.2.2.1: Authority Information Access
  986. var aia []authorityInfoAccess
  987. if _, err = asn1.Unmarshal(e.Value, &aia); err != nil {
  988. return nil, err
  989. }
  990. for _, v := range aia {
  991. // GeneralName: uniformResourceIdentifier [6] IA5String
  992. if v.Location.Tag != 6 {
  993. continue
  994. }
  995. if v.Method.Equal(oidAuthorityInfoAccessOcsp) {
  996. out.OCSPServer = append(out.OCSPServer, string(v.Location.Bytes))
  997. } else if v.Method.Equal(oidAuthorityInfoAccessIssuers) {
  998. out.IssuingCertificateURL = append(out.IssuingCertificateURL, string(v.Location.Bytes))
  999. }
  1000. }
  1001. }
  1002. if e.Critical {
  1003. // START CT CHANGES
  1004. nfe.AddError(UnhandledCriticalExtension{e.Id})
  1005. // END CT CHANGES
  1006. }
  1007. }
  1008. // START CT CHANGES
  1009. if nfe.HasError() {
  1010. return out, nfe
  1011. }
  1012. // END CT CHANGES
  1013. return out, nil
  1014. }
  1015. // START CT CHANGES
  1016. // ParseTBSCertificate parses a single TBSCertificate from the given ASN.1 DER data.
  1017. // The parsed data is returned in a Certificate struct for ease of access.
  1018. func ParseTBSCertificate(asn1Data []byte) (*Certificate, error) {
  1019. var tbsCert tbsCertificate
  1020. rest, err := asn1.Unmarshal(asn1Data, &tbsCert)
  1021. if err != nil {
  1022. return nil, err
  1023. }
  1024. if len(rest) > 0 {
  1025. return nil, asn1.SyntaxError{Msg: "trailing data"}
  1026. }
  1027. return parseCertificate(&certificate{
  1028. Raw: tbsCert.Raw,
  1029. TBSCertificate: tbsCert})
  1030. }
  1031. // END CT CHANGES
  1032. // ParseCertificate parses a single certificate from the given ASN.1 DER data.
  1033. func ParseCertificate(asn1Data []byte) (*Certificate, error) {
  1034. var cert certificate
  1035. rest, err := asn1.Unmarshal(asn1Data, &cert)
  1036. if err != nil {
  1037. return nil, err
  1038. }
  1039. if len(rest) > 0 {
  1040. return nil, asn1.SyntaxError{Msg: "trailing data"}
  1041. }
  1042. return parseCertificate(&cert)
  1043. }
  1044. // ParseCertificates parses one or more certificates from the given ASN.1 DER
  1045. // data. The certificates must be concatenated with no intermediate padding.
  1046. func ParseCertificates(asn1Data []byte) ([]*Certificate, error) {
  1047. var v []*certificate
  1048. for len(asn1Data) > 0 {
  1049. cert := new(certificate)
  1050. var err error
  1051. asn1Data, err = asn1.Unmarshal(asn1Data, cert)
  1052. if err != nil {
  1053. return nil, err
  1054. }
  1055. v = append(v, cert)
  1056. }
  1057. ret := make([]*Certificate, len(v))
  1058. for i, ci := range v {
  1059. cert, err := parseCertificate(ci)
  1060. if err != nil {
  1061. return nil, err
  1062. }
  1063. ret[i] = cert
  1064. }
  1065. return ret, nil
  1066. }
  1067. func reverseBitsInAByte(in byte) byte {
  1068. b1 := in>>4 | in<<4
  1069. b2 := b1>>2&0x33 | b1<<2&0xcc
  1070. b3 := b2>>1&0x55 | b2<<1&0xaa
  1071. return b3
  1072. }
  1073. var (
  1074. oidExtensionSubjectKeyId = []int{2, 5, 29, 14}
  1075. oidExtensionKeyUsage = []int{2, 5, 29, 15}
  1076. oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37}
  1077. oidExtensionAuthorityKeyId = []int{2, 5, 29, 35}
  1078. oidExtensionBasicConstraints = []int{2, 5, 29, 19}
  1079. oidExtensionSubjectAltName = []int{2, 5, 29, 17}
  1080. oidExtensionCertificatePolicies = []int{2, 5, 29, 32}
  1081. oidExtensionNameConstraints = []int{2, 5, 29, 30}
  1082. oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31}
  1083. oidExtensionAuthorityInfoAccess = []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
  1084. )
  1085. var (
  1086. oidAuthorityInfoAccessOcsp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
  1087. oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}
  1088. )
  1089. // oidNotInExtensions returns whether an extension with the given oid exists in
  1090. // extensions.
  1091. func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {
  1092. for _, e := range extensions {
  1093. if e.Id.Equal(oid) {
  1094. return true
  1095. }
  1096. }
  1097. return false
  1098. }
  1099. func buildExtensions(template *Certificate) (ret []pkix.Extension, err error) {
  1100. ret = make([]pkix.Extension, 10 /* maximum number of elements. */)
  1101. n := 0
  1102. if template.KeyUsage != 0 &&
  1103. !oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) {
  1104. ret[n].Id = oidExtensionKeyUsage
  1105. ret[n].Critical = true
  1106. var a [2]byte
  1107. a[0] = reverseBitsInAByte(byte(template.KeyUsage))
  1108. a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8))
  1109. l := 1
  1110. if a[1] != 0 {
  1111. l = 2
  1112. }
  1113. ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: a[0:l], BitLength: l * 8})
  1114. if err != nil {
  1115. return
  1116. }
  1117. n++
  1118. }
  1119. if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) &&
  1120. !oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) {
  1121. ret[n].Id = oidExtensionExtendedKeyUsage
  1122. var oids []asn1.ObjectIdentifier
  1123. for _, u := range template.ExtKeyUsage {
  1124. if oid, ok := oidFromExtKeyUsage(u); ok {
  1125. oids = append(oids, oid)
  1126. } else {
  1127. panic("internal error")
  1128. }
  1129. }
  1130. oids = append(oids, template.UnknownExtKeyUsage...)
  1131. ret[n].Value, err = asn1.Marshal(oids)
  1132. if err != nil {
  1133. return
  1134. }
  1135. n++
  1136. }
  1137. if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) {
  1138. ret[n].Id = oidExtensionBasicConstraints
  1139. ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, template.MaxPathLen})
  1140. ret[n].Critical = true
  1141. if err != nil {
  1142. return
  1143. }
  1144. n++
  1145. }
  1146. if len(template.SubjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) {
  1147. ret[n].Id = oidExtensionSubjectKeyId
  1148. ret[n].Value, err = asn1.Marshal(template.SubjectKeyId)
  1149. if err != nil {
  1150. return
  1151. }
  1152. n++
  1153. }
  1154. if len(template.AuthorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) {
  1155. ret[n].Id = oidExtensionAuthorityKeyId
  1156. ret[n].Value, err = asn1.Marshal(authKeyId{template.AuthorityKeyId})
  1157. if err != nil {
  1158. return
  1159. }
  1160. n++
  1161. }
  1162. if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) &&
  1163. !oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) {
  1164. ret[n].Id = oidExtensionAuthorityInfoAccess
  1165. var aiaValues []authorityInfoAccess
  1166. for _, name := range template.OCSPServer {
  1167. aiaValues = append(aiaValues, authorityInfoAccess{
  1168. Method: oidAuthorityInfoAccessOcsp,
  1169. Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
  1170. })
  1171. }
  1172. for _, name := range template.IssuingCertificateURL {
  1173. aiaValues = append(aiaValues, authorityInfoAccess{
  1174. Method: oidAuthorityInfoAccessIssuers,
  1175. Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
  1176. })
  1177. }
  1178. ret[n].Value, err = asn1.Marshal(aiaValues)
  1179. if err != nil {
  1180. return
  1181. }
  1182. n++
  1183. }
  1184. if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0) &&
  1185. !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
  1186. ret[n].Id = oidExtensionSubjectAltName
  1187. var rawValues []asn1.RawValue
  1188. for _, name := range template.DNSNames {
  1189. rawValues = append(rawValues, asn1.RawValue{Tag: 2, Class: 2, Bytes: []byte(name)})
  1190. }
  1191. for _, email := range template.EmailAddresses {
  1192. rawValues = append(rawValues, asn1.RawValue{Tag: 1, Class: 2, Bytes: []byte(email)})
  1193. }
  1194. for _, rawIP := range template.IPAddresses {
  1195. // If possible, we always want to encode IPv4 addresses in 4 bytes.
  1196. ip := rawIP.To4()
  1197. if ip == nil {
  1198. ip = rawIP
  1199. }
  1200. rawValues = append(rawValues, asn1.RawValue{Tag: 7, Class: 2, Bytes: ip})
  1201. }
  1202. ret[n].Value, err = asn1.Marshal(rawValues)
  1203. if err != nil {
  1204. return
  1205. }
  1206. n++
  1207. }
  1208. if len(template.PolicyIdentifiers) > 0 &&
  1209. !oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) {
  1210. ret[n].Id = oidExtensionCertificatePolicies
  1211. policies := make([]policyInformation, len(template.PolicyIdentifiers))
  1212. for i, policy := range template.PolicyIdentifiers {
  1213. policies[i].Policy = policy
  1214. }
  1215. ret[n].Value, err = asn1.Marshal(policies)
  1216. if err != nil {
  1217. return
  1218. }
  1219. n++
  1220. }
  1221. if len(template.PermittedDNSDomains) > 0 &&
  1222. !oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) {
  1223. ret[n].Id = oidExtensionNameConstraints
  1224. ret[n].Critical = template.PermittedDNSDomainsCritical
  1225. var out nameConstraints
  1226. out.Permitted = make([]generalSubtree, len(template.PermittedDNSDomains))
  1227. for i, permitted := range template.PermittedDNSDomains {
  1228. out.Permitted[i] = generalSubtree{Name: permitted}
  1229. }
  1230. ret[n].Value, err = asn1.Marshal(out)
  1231. if err != nil {
  1232. return
  1233. }
  1234. n++
  1235. }
  1236. if len(template.CRLDistributionPoints) > 0 &&
  1237. !oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) {
  1238. ret[n].Id = oidExtensionCRLDistributionPoints
  1239. var crlDp []distributionPoint
  1240. for _, name := range template.CRLDistributionPoints {
  1241. rawFullName, _ := asn1.Marshal(asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)})
  1242. dp := distributionPoint{
  1243. DistributionPoint: distributionPointName{
  1244. FullName: asn1.RawValue{Tag: 0, Class: 2, Bytes: rawFullName},
  1245. },
  1246. }
  1247. crlDp = append(crlDp, dp)
  1248. }
  1249. ret[n].Value, err = asn1.Marshal(crlDp)
  1250. if err != nil {
  1251. return
  1252. }
  1253. n++
  1254. }
  1255. // Adding another extension here? Remember to update the maximum number
  1256. // of elements in the make() at the top of the function.
  1257. return append(ret[:n], template.ExtraExtensions...), nil
  1258. }
  1259. func subjectBytes(cert *Certificate) ([]byte, error) {
  1260. if len(cert.RawSubject) > 0 {
  1261. return cert.RawSubject, nil
  1262. }
  1263. return asn1.Marshal(cert.Subject.ToRDNSequence())
  1264. }
  1265. // CreateCertificate creates a new certificate based on a template. The
  1266. // following members of template are used: SerialNumber, Subject, NotBefore,
  1267. // NotAfter, KeyUsage, ExtKeyUsage, UnknownExtKeyUsage, BasicConstraintsValid,
  1268. // IsCA, MaxPathLen, SubjectKeyId, DNSNames, PermittedDNSDomainsCritical,
  1269. // PermittedDNSDomains.
  1270. //
  1271. // The certificate is signed by parent. If parent is equal to template then the
  1272. // certificate is self-signed. The parameter pub is the public key of the
  1273. // signee and priv is the private key of the signer.
  1274. //
  1275. // The returned slice is the certificate in DER encoding.
  1276. //
  1277. // The only supported key types are RSA and ECDSA (*rsa.PublicKey or
  1278. // *ecdsa.PublicKey for pub, *rsa.PrivateKey or *ecdsa.PublicKey for priv).
  1279. func CreateCertificate(rand io.Reader, template, parent *Certificate, pub interface{}, priv interface{}) (cert []byte, err error) {
  1280. var publicKeyBytes []byte
  1281. var publicKeyAlgorithm pkix.AlgorithmIdentifier
  1282. if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
  1283. return nil, err
  1284. }
  1285. var signatureAlgorithm pkix.AlgorithmIdentifier
  1286. var hashFunc crypto.Hash
  1287. switch priv := priv.(type) {
  1288. case *rsa.PrivateKey:
  1289. signatureAlgorithm.Algorithm = oidSignatureSHA1WithRSA
  1290. hashFunc = crypto.SHA1
  1291. case *ecdsa.PrivateKey:
  1292. switch priv.Curve {
  1293. case elliptic.P224(), elliptic.P256():
  1294. hashFunc = crypto.SHA256
  1295. signatureAlgorithm.Algorithm = oidSignatureECDSAWithSHA256
  1296. case elliptic.P384():
  1297. hashFunc = crypto.SHA384
  1298. signatureAlgorithm.Algorithm = oidSignatureECDSAWithSHA384
  1299. case elliptic.P521():
  1300. hashFunc = crypto.SHA512
  1301. signatureAlgorithm.Algorithm = oidSignatureECDSAWithSHA512
  1302. default:
  1303. return nil, errors.New("x509: unknown elliptic curve")
  1304. }
  1305. default:
  1306. return nil, errors.New("x509: only RSA and ECDSA private keys supported")
  1307. }
  1308. if err != nil {
  1309. return
  1310. }
  1311. if len(parent.SubjectKeyId) > 0 {
  1312. template.AuthorityKeyId = parent.SubjectKeyId
  1313. }
  1314. extensions, err := buildExtensions(template)
  1315. if err != nil {
  1316. return
  1317. }
  1318. asn1Issuer, err := subjectBytes(parent)
  1319. if err != nil {
  1320. return
  1321. }
  1322. asn1Subject, err := subjectBytes(template)
  1323. if err != nil {
  1324. return
  1325. }
  1326. encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
  1327. c := tbsCertificate{
  1328. Version: 2,
  1329. SerialNumber: template.SerialNumber,
  1330. SignatureAlgorithm: signatureAlgorithm,
  1331. Issuer: asn1.RawValue{FullBytes: asn1Issuer},
  1332. Validity: validity{template.NotBefore.UTC(), template.NotAfter.UTC()},
  1333. Subject: asn1.RawValue{FullBytes: asn1Subject},
  1334. PublicKey: publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},
  1335. Extensions: extensions,
  1336. }
  1337. tbsCertContents, err := asn1.Marshal(c)
  1338. if err != nil {
  1339. return
  1340. }
  1341. c.Raw = tbsCertContents
  1342. h := hashFunc.New()
  1343. h.Write(tbsCertContents)
  1344. digest := h.Sum(nil)
  1345. var signature []byte
  1346. switch priv := priv.(type) {
  1347. case *rsa.PrivateKey:
  1348. signature, err = rsa.SignPKCS1v15(rand, priv, hashFunc, digest)
  1349. case *ecdsa.PrivateKey:
  1350. var r, s *big.Int
  1351. if r, s, err = ecdsa.Sign(rand, priv, digest); err == nil {
  1352. signature, err = asn1.Marshal(ecdsaSignature{r, s})
  1353. }
  1354. default:
  1355. panic("internal error")
  1356. }
  1357. if err != nil {
  1358. return
  1359. }
  1360. cert, err = asn1.Marshal(certificate{
  1361. nil,
  1362. c,
  1363. signatureAlgorithm,
  1364. asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
  1365. })
  1366. return
  1367. }
  1368. // pemCRLPrefix is the magic string that indicates that we have a PEM encoded
  1369. // CRL.
  1370. var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
  1371. // pemType is the type of a PEM encoded CRL.
  1372. var pemType = "X509 CRL"
  1373. // ParseCRL parses a CRL from the given bytes. It's often the case that PEM
  1374. // encoded CRLs will appear where they should be DER encoded, so this function
  1375. // will transparently handle PEM encoding as long as there isn't any leading
  1376. // garbage.
  1377. func ParseCRL(crlBytes []byte) (certList *pkix.CertificateList, err error) {
  1378. if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
  1379. block, _ := pem.Decode(crlBytes)
  1380. if block != nil && block.Type == pemType {
  1381. crlBytes = block.Bytes
  1382. }
  1383. }
  1384. return ParseDERCRL(crlBytes)
  1385. }
  1386. // ParseDERCRL parses a DER encoded CRL from the given bytes.
  1387. func ParseDERCRL(derBytes []byte) (certList *pkix.CertificateList, err error) {
  1388. certList = new(pkix.CertificateList)
  1389. _, err = asn1.Unmarshal(derBytes, certList)
  1390. if err != nil {
  1391. certList = nil
  1392. }
  1393. return
  1394. }
  1395. // CreateCRL returns a DER encoded CRL, signed by this Certificate, that
  1396. // contains the given list of revoked certificates.
  1397. //
  1398. // The only supported key type is RSA (*rsa.PrivateKey for priv).
  1399. func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
  1400. rsaPriv, ok := priv.(*rsa.PrivateKey)
  1401. if !ok {
  1402. return nil, errors.New("x509: non-RSA private keys not supported")
  1403. }
  1404. tbsCertList := pkix.TBSCertificateList{
  1405. Version: 2,
  1406. Signature: pkix.AlgorithmIdentifier{
  1407. Algorithm: oidSignatureSHA1WithRSA,
  1408. },
  1409. Issuer: c.Subject.ToRDNSequence(),
  1410. ThisUpdate: now.UTC(),
  1411. NextUpdate: expiry.UTC(),
  1412. RevokedCertificates: revokedCerts,
  1413. }
  1414. tbsCertListContents, err := asn1.Marshal(tbsCertList)
  1415. if err != nil {
  1416. return
  1417. }
  1418. h := sha1.New()
  1419. h.Write(tbsCertListContents)
  1420. digest := h.Sum(nil)
  1421. signature, err := rsa.SignPKCS1v15(rand, rsaPriv, crypto.SHA1, digest)
  1422. if err != nil {
  1423. return
  1424. }
  1425. return asn1.Marshal(pkix.CertificateList{
  1426. TBSCertList: tbsCertList,
  1427. SignatureAlgorithm: pkix.AlgorithmIdentifier{
  1428. Algorithm: oidSignatureSHA1WithRSA,
  1429. },
  1430. SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
  1431. })
  1432. }