initca_test.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. package initca
  2. import (
  3. "bytes"
  4. "crypto/ecdsa"
  5. "crypto/rsa"
  6. "io/ioutil"
  7. "strings"
  8. "testing"
  9. "time"
  10. "github.com/cloudflare/cfssl/config"
  11. "github.com/cloudflare/cfssl/csr"
  12. "github.com/cloudflare/cfssl/helpers"
  13. "github.com/cloudflare/cfssl/signer"
  14. "github.com/cloudflare/cfssl/signer/local"
  15. )
  16. var validKeyParams = []csr.KeyRequest{
  17. {A: "rsa", S: 2048},
  18. {A: "rsa", S: 3072},
  19. {A: "rsa", S: 4096},
  20. {A: "ecdsa", S: 256},
  21. {A: "ecdsa", S: 384},
  22. {A: "ecdsa", S: 521},
  23. }
  24. var validCAConfigs = []csr.CAConfig{
  25. {PathLength: 0, PathLenZero: true},
  26. {PathLength: 0, PathLenZero: false},
  27. {PathLength: 2},
  28. {PathLength: 2, Expiry: "1h"},
  29. // invalid PathLenZero value will be ignored
  30. {PathLength: 2, PathLenZero: true},
  31. }
  32. var invalidCAConfig = csr.CAConfig{
  33. PathLength: 2,
  34. // Expiry must be a duration string
  35. Expiry: "2116/12/31",
  36. }
  37. var csrFiles = []string{
  38. "testdata/rsa2048.csr",
  39. "testdata/rsa3072.csr",
  40. "testdata/rsa4096.csr",
  41. "testdata/ecdsa256.csr",
  42. "testdata/ecdsa384.csr",
  43. "testdata/ecdsa521.csr",
  44. }
  45. var testRSACAFile = "testdata/5min-rsa.pem"
  46. var testRSACAKeyFile = "testdata/5min-rsa-key.pem"
  47. var testECDSACAFile = "testdata/5min-ecdsa.pem"
  48. var testECDSACAKeyFile = "testdata/5min-ecdsa-key.pem"
  49. var invalidCryptoParams = []csr.KeyRequest{
  50. // Weak Key
  51. {A: "rsa", S: 1024},
  52. // Bad param
  53. {A: "rsaCrypto", S: 2048},
  54. {A: "ecdsa", S: 2000},
  55. }
  56. func TestInitCA(t *testing.T) {
  57. var req *csr.CertificateRequest
  58. hostname := "cloudflare.com"
  59. crl := "http://crl.cloudflare.com/655c6a9b-01c6-4eea-bf21-be690cc315e0.crl" //cert_uuid.crl
  60. for _, param := range validKeyParams {
  61. for _, caconfig := range validCAConfigs {
  62. req = &csr.CertificateRequest{
  63. Names: []csr.Name{
  64. {
  65. C: "US",
  66. ST: "California",
  67. L: "San Francisco",
  68. O: "CloudFlare",
  69. OU: "Systems Engineering",
  70. },
  71. },
  72. CN: hostname,
  73. Hosts: []string{hostname, "www." + hostname},
  74. KeyRequest: &param,
  75. CA: &caconfig,
  76. CRL: crl,
  77. }
  78. certBytes, _, keyBytes, err := New(req)
  79. if err != nil {
  80. t.Fatal("InitCA failed:", err)
  81. }
  82. key, err := helpers.ParsePrivateKeyPEM(keyBytes)
  83. if err != nil {
  84. t.Fatal("InitCA private key parsing failed:", err)
  85. }
  86. cert, err := helpers.ParseCertificatePEM(certBytes)
  87. if err != nil {
  88. t.Fatal("InitCA cert parsing failed:", err)
  89. }
  90. // Verify if the CRL is set
  91. crlSet := false
  92. for _, certCrl := range cert.CRLDistributionPoints {
  93. if certCrl == crl {
  94. crlSet = true
  95. break
  96. }
  97. }
  98. if !crlSet {
  99. t.Fatal("Missing CRL on certificate")
  100. }
  101. // Verify key parameters.
  102. switch req.KeyRequest.Algo() {
  103. case "rsa":
  104. if cert.PublicKey.(*rsa.PublicKey).N.BitLen() != param.Size() {
  105. t.Fatal("Cert key length mismatch.")
  106. }
  107. if key.(*rsa.PrivateKey).N.BitLen() != param.Size() {
  108. t.Fatal("Private key length mismatch.")
  109. }
  110. case "ecdsa":
  111. if cert.PublicKey.(*ecdsa.PublicKey).Curve.Params().BitSize != param.Size() {
  112. t.Fatal("Cert key length mismatch.")
  113. }
  114. if key.(*ecdsa.PrivateKey).Curve.Params().BitSize != param.Size() {
  115. t.Fatal("Private key length mismatch.")
  116. }
  117. }
  118. // Verify CA MaxPathLen
  119. if caconfig.PathLength == 0 && cert.MaxPathLenZero != caconfig.PathLenZero {
  120. t.Fatalf("fail to init a CA cert with specified CA pathlen zero: expect %v, got %v", caconfig.PathLenZero, cert.MaxPathLenZero)
  121. }
  122. if caconfig.PathLength != 0 {
  123. if cert.MaxPathLen != caconfig.PathLength {
  124. t.Fatalf("fail to init a CA cert with specified CA pathlen: expect %d, got %d", caconfig.PathLength, cert.MaxPathLen)
  125. }
  126. if cert.MaxPathLenZero != false {
  127. t.Fatalf("fail to init a CA cert with specified CA pathlen zero: expect false, got %t", cert.MaxPathLenZero)
  128. }
  129. }
  130. // Replace the default CAPolicy with a test (short expiry) version and add a crl
  131. CAPolicy = func() *config.Signing {
  132. return &config.Signing{
  133. Default: &config.SigningProfile{
  134. Usage: []string{"cert sign", "crl sign"},
  135. ExpiryString: "300s",
  136. Expiry: 300 * time.Second,
  137. CAConstraint: config.CAConstraint{IsCA: true},
  138. CRL: crl,
  139. },
  140. }
  141. }
  142. // Start a signer
  143. s, err := local.NewSigner(key, cert, signer.DefaultSigAlgo(key), nil)
  144. if err != nil {
  145. t.Fatal("Signer Creation error:", err)
  146. }
  147. s.SetPolicy(CAPolicy())
  148. // Sign RSA and ECDSA customer CSRs.
  149. for _, csrFile := range csrFiles {
  150. csrBytes, err := ioutil.ReadFile(csrFile)
  151. if err != nil {
  152. t.Fatal("CSR loading error:", err)
  153. }
  154. req := signer.SignRequest{
  155. Request: string(csrBytes),
  156. Hosts: signer.SplitHosts(hostname),
  157. Profile: "",
  158. Label: "",
  159. }
  160. bytes, err := s.Sign(req)
  161. if err != nil {
  162. t.Fatal(err)
  163. }
  164. customerCert, _ := helpers.ParseCertificatePEM(bytes)
  165. if customerCert.SignatureAlgorithm != s.SigAlgo() {
  166. t.Fatal("Signature Algorithm mismatch")
  167. }
  168. err = customerCert.CheckSignatureFrom(cert)
  169. if err != nil {
  170. t.Fatal("Signing CSR failed.", err)
  171. }
  172. }
  173. }
  174. }
  175. }
  176. func TestInvalidCAConfig(t *testing.T) {
  177. hostname := "example.com"
  178. req := &csr.CertificateRequest{
  179. Names: []csr.Name{
  180. {
  181. C: "US",
  182. ST: "California",
  183. L: "San Francisco",
  184. O: "CloudFlare",
  185. OU: "Systems Engineering",
  186. },
  187. },
  188. CN: hostname,
  189. Hosts: []string{hostname, "www." + hostname},
  190. KeyRequest: &validKeyParams[0],
  191. CA: &invalidCAConfig,
  192. }
  193. _, _, _, err := New(req)
  194. if err == nil {
  195. t.Fatal("InitCA with bad CAConfig should fail:", err)
  196. }
  197. }
  198. func TestInvalidCryptoParams(t *testing.T) {
  199. var req *csr.CertificateRequest
  200. hostname := "cloudflare.com"
  201. for _, invalidParam := range invalidCryptoParams {
  202. req = &csr.CertificateRequest{
  203. Names: []csr.Name{
  204. {
  205. C: "US",
  206. ST: "California",
  207. L: "San Francisco",
  208. O: "CloudFlare",
  209. OU: "Systems Engineering",
  210. },
  211. },
  212. CN: hostname,
  213. Hosts: []string{hostname, "www." + hostname},
  214. KeyRequest: &invalidParam,
  215. }
  216. _, _, _, err := New(req)
  217. if err == nil {
  218. t.Fatal("InitCA with bad params should fail:", err)
  219. }
  220. if !strings.Contains(err.Error(), `"code":2400`) {
  221. t.Fatal(err)
  222. }
  223. }
  224. }
  225. type validation struct {
  226. r *csr.CertificateRequest
  227. v bool
  228. }
  229. var testValidations = []validation{
  230. {&csr.CertificateRequest{}, false},
  231. {&csr.CertificateRequest{
  232. CN: "test CA",
  233. }, true},
  234. {&csr.CertificateRequest{
  235. Names: []csr.Name{{}},
  236. }, false},
  237. {&csr.CertificateRequest{
  238. Names: []csr.Name{
  239. {O: "Example CA"},
  240. },
  241. }, true},
  242. }
  243. func TestValidations(t *testing.T) {
  244. for i, tv := range testValidations {
  245. err := validator(tv.r)
  246. if tv.v && err != nil {
  247. t.Fatalf("%v", err)
  248. }
  249. if !tv.v && err == nil {
  250. t.Fatalf("%d: expected error, but no error was reported", i)
  251. }
  252. }
  253. }
  254. func TestRenewRSA(t *testing.T) {
  255. certPEM, err := RenewFromPEM(testRSACAFile, testRSACAKeyFile)
  256. if err != nil {
  257. t.Fatal(err)
  258. }
  259. // must parse ok
  260. cert, err := helpers.ParseCertificatePEM(certPEM)
  261. if err != nil {
  262. t.Fatal(err)
  263. }
  264. if !cert.IsCA {
  265. t.Fatal("renewed CA certificate is not CA")
  266. }
  267. // cert expiry must be 5 minutes
  268. expiry := cert.NotAfter.Sub(cert.NotBefore).Seconds()
  269. if expiry >= 301 || expiry <= 299 {
  270. t.Fatal("expiry is not correct:", expiry)
  271. }
  272. // check subject
  273. if cert.Subject.CommonName != "" {
  274. t.Fatal("Bad CommonName")
  275. }
  276. if len(cert.Subject.Country) != 1 || cert.Subject.Country[0] != "US" {
  277. t.Fatal("Bad Subject")
  278. }
  279. if len(cert.Subject.Organization) != 1 || cert.Subject.Organization[0] != "CloudFlare, Inc." {
  280. t.Fatal("Bad Subject")
  281. }
  282. }
  283. func TestRenewECDSA(t *testing.T) {
  284. certPEM, err := RenewFromPEM(testECDSACAFile, testECDSACAKeyFile)
  285. if err != nil {
  286. t.Fatal(err)
  287. }
  288. // must parse ok
  289. cert, err := helpers.ParseCertificatePEM(certPEM)
  290. if err != nil {
  291. t.Fatal(err)
  292. }
  293. if !cert.IsCA {
  294. t.Fatal("renewed CA certificate is not CA")
  295. }
  296. // cert expiry must be 5 minutes
  297. expiry := cert.NotAfter.Sub(cert.NotBefore).Seconds()
  298. if expiry >= 301 || expiry <= 299 {
  299. t.Fatal("expiry is not correct:", expiry)
  300. }
  301. // check subject
  302. if cert.Subject.CommonName != "" {
  303. t.Fatal("Bad CommonName")
  304. }
  305. if len(cert.Subject.Country) != 1 || cert.Subject.Country[0] != "US" {
  306. t.Fatal("Bad Subject")
  307. }
  308. if len(cert.Subject.Organization) != 1 || cert.Subject.Organization[0] != "CloudFlare, Inc." {
  309. t.Fatal("Bad Subject")
  310. }
  311. }
  312. func TestRenewMismatch(t *testing.T) {
  313. _, err := RenewFromPEM(testECDSACAFile, testRSACAKeyFile)
  314. if err == nil {
  315. t.Fatal("Fail to detect cert/key mismatch")
  316. }
  317. }
  318. func TestRenew(t *testing.T) {
  319. in, err := ioutil.ReadFile(testECDSACAFile)
  320. if err != nil {
  321. t.Fatal(err)
  322. }
  323. cert, err := helpers.ParseCertificatePEM(in)
  324. if err != nil {
  325. t.Fatal(err)
  326. }
  327. in, err = ioutil.ReadFile(testECDSACAKeyFile)
  328. if err != nil {
  329. t.Fatal(err)
  330. }
  331. priv, err := helpers.ParsePrivateKeyPEM(in)
  332. if err != nil {
  333. t.Fatal(err)
  334. }
  335. renewed, err := Update(cert, priv)
  336. if err != nil {
  337. t.Fatal(err)
  338. }
  339. newCert, err := helpers.ParseCertificatePEM(renewed)
  340. if err != nil {
  341. t.Fatal(err)
  342. }
  343. if !bytes.Equal(newCert.RawSubjectPublicKeyInfo, cert.RawSubjectPublicKeyInfo) {
  344. t.Fatal("Update returned a certificate with different subject public key info")
  345. }
  346. if !bytes.Equal(newCert.RawSubject, cert.RawSubject) {
  347. t.Fatal("Update returned a certificate with different subject info")
  348. }
  349. if !bytes.Equal(newCert.RawIssuer, cert.RawIssuer) {
  350. t.Fatal("Update returned a certificate with different issuer info")
  351. }
  352. }