initca_test.go 8.0 KB

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