authority_test.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. package authority
  2. import (
  3. "crypto"
  4. "crypto/rand"
  5. "crypto/sha256"
  6. "crypto/x509"
  7. "encoding/hex"
  8. "encoding/pem"
  9. "net"
  10. "os"
  11. "path/filepath"
  12. "reflect"
  13. "testing"
  14. "time"
  15. "github.com/pkg/errors"
  16. "github.com/smallstep/assert"
  17. "github.com/smallstep/certificates/authority/config"
  18. "github.com/smallstep/certificates/authority/provisioner"
  19. "github.com/smallstep/certificates/db"
  20. "go.step.sm/crypto/jose"
  21. "go.step.sm/crypto/minica"
  22. "go.step.sm/crypto/pemutil"
  23. )
  24. func testAuthority(t *testing.T, opts ...Option) *Authority {
  25. maxjwk, err := jose.ReadKey("testdata/secrets/max_pub.jwk")
  26. assert.FatalError(t, err)
  27. clijwk, err := jose.ReadKey("testdata/secrets/step_cli_key_pub.jwk")
  28. assert.FatalError(t, err)
  29. disableRenewal := true
  30. enableSSHCA := true
  31. p := provisioner.List{
  32. &provisioner.JWK{
  33. Name: "Max",
  34. Type: "JWK",
  35. Key: maxjwk,
  36. },
  37. &provisioner.JWK{
  38. Name: "step-cli",
  39. Type: "JWK",
  40. Key: clijwk,
  41. Claims: &provisioner.Claims{
  42. EnableSSHCA: &enableSSHCA,
  43. },
  44. },
  45. &provisioner.JWK{
  46. Name: "dev",
  47. Type: "JWK",
  48. Key: maxjwk,
  49. Claims: &provisioner.Claims{
  50. DisableRenewal: &disableRenewal,
  51. },
  52. },
  53. &provisioner.JWK{
  54. Name: "renew_disabled",
  55. Type: "JWK",
  56. Key: maxjwk,
  57. Claims: &provisioner.Claims{
  58. DisableRenewal: &disableRenewal,
  59. },
  60. },
  61. &provisioner.SSHPOP{
  62. Name: "sshpop",
  63. Type: "SSHPOP",
  64. Claims: &provisioner.Claims{
  65. EnableSSHCA: &enableSSHCA,
  66. },
  67. },
  68. }
  69. c := &Config{
  70. Address: "127.0.0.1:443",
  71. Root: []string{"testdata/certs/root_ca.crt"},
  72. IntermediateCert: "testdata/certs/intermediate_ca.crt",
  73. IntermediateKey: "testdata/secrets/intermediate_ca_key",
  74. SSH: &SSHConfig{
  75. HostKey: "testdata/secrets/ssh_host_ca_key",
  76. UserKey: "testdata/secrets/ssh_user_ca_key",
  77. },
  78. DNSNames: []string{"example.com"},
  79. Password: "pass",
  80. AuthorityConfig: &AuthConfig{
  81. Provisioners: p,
  82. },
  83. }
  84. a, err := New(c, opts...)
  85. assert.FatalError(t, err)
  86. // Avoid errors when test tokens are created before the test authority. This
  87. // happens in some tests where we re-create the same authority to test
  88. // special cases without re-creating the token.
  89. a.startTime = a.startTime.Add(-1 * time.Minute)
  90. return a
  91. }
  92. func TestAuthorityNew(t *testing.T) {
  93. type newTest struct {
  94. config *Config
  95. err error
  96. }
  97. tests := map[string]func(t *testing.T) *newTest{
  98. "ok": func(t *testing.T) *newTest {
  99. c, err := LoadConfiguration("../ca/testdata/ca.json")
  100. assert.FatalError(t, err)
  101. return &newTest{
  102. config: c,
  103. }
  104. },
  105. "fail bad root": func(t *testing.T) *newTest {
  106. c, err := LoadConfiguration("../ca/testdata/ca.json")
  107. assert.FatalError(t, err)
  108. c.Root = []string{"foo"}
  109. return &newTest{
  110. config: c,
  111. err: errors.New("error reading foo: no such file or directory"),
  112. }
  113. },
  114. "fail bad password": func(t *testing.T) *newTest {
  115. c, err := LoadConfiguration("../ca/testdata/ca.json")
  116. assert.FatalError(t, err)
  117. c.Password = "wrong"
  118. return &newTest{
  119. config: c,
  120. err: errors.New("error decrypting ../ca/testdata/secrets/intermediate_ca_key: x509: decryption password incorrect"),
  121. }
  122. },
  123. "fail loading CA cert": func(t *testing.T) *newTest {
  124. c, err := LoadConfiguration("../ca/testdata/ca.json")
  125. assert.FatalError(t, err)
  126. c.IntermediateCert = "wrong"
  127. return &newTest{
  128. config: c,
  129. err: errors.New("error reading wrong: no such file or directory"),
  130. }
  131. },
  132. }
  133. for name, genTestCase := range tests {
  134. t.Run(name, func(t *testing.T) {
  135. tc := genTestCase(t)
  136. auth, err := New(tc.config)
  137. if err != nil {
  138. if assert.NotNil(t, tc.err) {
  139. assert.HasPrefix(t, err.Error(), tc.err.Error())
  140. }
  141. } else {
  142. if assert.Nil(t, tc.err) {
  143. sum := sha256.Sum256(auth.rootX509Certs[0].Raw)
  144. root, ok := auth.certificates.Load(hex.EncodeToString(sum[:]))
  145. assert.Fatal(t, ok)
  146. assert.Equals(t, auth.rootX509Certs[0], root)
  147. assert.True(t, auth.initOnce)
  148. assert.NotNil(t, auth.x509CAService)
  149. for _, p := range tc.config.AuthorityConfig.Provisioners {
  150. var _p provisioner.Interface
  151. _p, ok = auth.provisioners.Load(p.GetID())
  152. assert.True(t, ok)
  153. assert.Equals(t, p, _p)
  154. var kid, encryptedKey string
  155. if kid, encryptedKey, ok = p.GetEncryptedKey(); ok {
  156. var key string
  157. key, ok = auth.provisioners.LoadEncryptedKey(kid)
  158. assert.True(t, ok)
  159. assert.Equals(t, encryptedKey, key)
  160. }
  161. }
  162. // sanity check
  163. _, ok = auth.provisioners.Load("fooo")
  164. assert.False(t, ok)
  165. }
  166. }
  167. })
  168. }
  169. }
  170. func TestAuthorityNew_bundles(t *testing.T) {
  171. ca0, err := minica.New()
  172. if err != nil {
  173. t.Fatal(err)
  174. }
  175. ca1, err := minica.New()
  176. if err != nil {
  177. t.Fatal(err)
  178. }
  179. ca2, err := minica.New()
  180. if err != nil {
  181. t.Fatal(err)
  182. }
  183. rootPath := t.TempDir()
  184. writeCert := func(fn string, certs ...*x509.Certificate) error {
  185. var b []byte
  186. for _, crt := range certs {
  187. b = append(b, pem.EncodeToMemory(&pem.Block{
  188. Type: "CERTIFICATE",
  189. Bytes: crt.Raw,
  190. })...)
  191. }
  192. return os.WriteFile(filepath.Join(rootPath, fn), b, 0600)
  193. }
  194. writeKey := func(fn string, signer crypto.Signer) error {
  195. _, err := pemutil.Serialize(signer, pemutil.ToFile(filepath.Join(rootPath, fn), 0600))
  196. return err
  197. }
  198. if err := writeCert("root0.crt", ca0.Root); err != nil {
  199. t.Fatal(err)
  200. }
  201. if err := writeCert("int0.crt", ca0.Intermediate); err != nil {
  202. t.Fatal(err)
  203. }
  204. if err := writeKey("int0.key", ca0.Signer); err != nil {
  205. t.Fatal(err)
  206. }
  207. if err := writeCert("root1.crt", ca1.Root); err != nil {
  208. t.Fatal(err)
  209. }
  210. if err := writeCert("int1.crt", ca1.Intermediate); err != nil {
  211. t.Fatal(err)
  212. }
  213. if err := writeKey("int1.key", ca1.Signer); err != nil {
  214. t.Fatal(err)
  215. }
  216. if err := writeCert("bundle0.crt", ca0.Root, ca1.Root); err != nil {
  217. t.Fatal(err)
  218. }
  219. if err := writeCert("bundle1.crt", ca1.Root, ca2.Root); err != nil {
  220. t.Fatal(err)
  221. }
  222. tests := []struct {
  223. name string
  224. config *config.Config
  225. wantErr bool
  226. }{
  227. {"ok ca0", &config.Config{
  228. Address: "127.0.0.1:443",
  229. Root: []string{filepath.Join(rootPath, "root0.crt")},
  230. IntermediateCert: filepath.Join(rootPath, "int0.crt"),
  231. IntermediateKey: filepath.Join(rootPath, "int0.key"),
  232. DNSNames: []string{"127.0.0.1"},
  233. AuthorityConfig: &AuthConfig{},
  234. }, false},
  235. {"ok bundle", &config.Config{
  236. Address: "127.0.0.1:443",
  237. Root: []string{filepath.Join(rootPath, "bundle0.crt")},
  238. IntermediateCert: filepath.Join(rootPath, "int0.crt"),
  239. IntermediateKey: filepath.Join(rootPath, "int0.key"),
  240. DNSNames: []string{"127.0.0.1"},
  241. AuthorityConfig: &AuthConfig{},
  242. }, false},
  243. {"ok federated ca1", &config.Config{
  244. Address: "127.0.0.1:443",
  245. Root: []string{filepath.Join(rootPath, "root0.crt")},
  246. FederatedRoots: []string{filepath.Join(rootPath, "root1.crt")},
  247. IntermediateCert: filepath.Join(rootPath, "int0.crt"),
  248. IntermediateKey: filepath.Join(rootPath, "int0.key"),
  249. DNSNames: []string{"127.0.0.1"},
  250. AuthorityConfig: &AuthConfig{},
  251. }, false},
  252. {"ok federated bundle", &config.Config{
  253. Address: "127.0.0.1:443",
  254. Root: []string{filepath.Join(rootPath, "root0.crt")},
  255. FederatedRoots: []string{filepath.Join(rootPath, "bundle1.crt")},
  256. IntermediateCert: filepath.Join(rootPath, "int0.crt"),
  257. IntermediateKey: filepath.Join(rootPath, "int0.key"),
  258. DNSNames: []string{"127.0.0.1"},
  259. AuthorityConfig: &AuthConfig{},
  260. }, false},
  261. {"fail root", &config.Config{
  262. Address: "127.0.0.1:443",
  263. Root: []string{filepath.Join(rootPath, "missing.crt")},
  264. IntermediateCert: filepath.Join(rootPath, "int0.crt"),
  265. IntermediateKey: filepath.Join(rootPath, "int0.key"),
  266. DNSNames: []string{"127.0.0.1"},
  267. AuthorityConfig: &AuthConfig{},
  268. }, true},
  269. {"fail federated", &config.Config{
  270. Address: "127.0.0.1:443",
  271. Root: []string{filepath.Join(rootPath, "root0.crt")},
  272. FederatedRoots: []string{filepath.Join(rootPath, "missing.crt")},
  273. IntermediateCert: filepath.Join(rootPath, "int0.crt"),
  274. IntermediateKey: filepath.Join(rootPath, "int0.key"),
  275. DNSNames: []string{"127.0.0.1"},
  276. AuthorityConfig: &AuthConfig{},
  277. }, true},
  278. }
  279. for _, tt := range tests {
  280. t.Run(tt.name, func(t *testing.T) {
  281. _, err := New(tt.config)
  282. if (err != nil) != tt.wantErr {
  283. t.Errorf("New() error = %v, wantErr %v", err, tt.wantErr)
  284. return
  285. }
  286. })
  287. }
  288. }
  289. func TestAuthority_GetDatabase(t *testing.T) {
  290. auth := testAuthority(t)
  291. authWithDatabase, err := New(auth.config, WithDatabase(auth.db))
  292. assert.FatalError(t, err)
  293. tests := []struct {
  294. name string
  295. auth *Authority
  296. want db.AuthDB
  297. }{
  298. {"ok", auth, auth.db},
  299. {"ok WithDatabase", authWithDatabase, auth.db},
  300. }
  301. for _, tt := range tests {
  302. t.Run(tt.name, func(t *testing.T) {
  303. if got := tt.auth.GetDatabase(); !reflect.DeepEqual(got, tt.want) {
  304. t.Errorf("Authority.GetDatabase() = %v, want %v", got, tt.want)
  305. }
  306. })
  307. }
  308. }
  309. func TestNewEmbedded(t *testing.T) {
  310. caPEM, err := os.ReadFile("testdata/certs/root_ca.crt")
  311. assert.FatalError(t, err)
  312. crt, err := pemutil.ReadCertificate("testdata/certs/intermediate_ca.crt")
  313. assert.FatalError(t, err)
  314. key, err := pemutil.Read("testdata/secrets/intermediate_ca_key", pemutil.WithPassword([]byte("pass")))
  315. assert.FatalError(t, err)
  316. type args struct {
  317. opts []Option
  318. }
  319. tests := []struct {
  320. name string
  321. args args
  322. wantErr bool
  323. }{
  324. {"ok", args{[]Option{WithX509RootBundle(caPEM), WithX509Signer(crt, key.(crypto.Signer))}}, false},
  325. {"ok empty config", args{[]Option{WithConfig(&Config{}), WithX509RootBundle(caPEM), WithX509Signer(crt, key.(crypto.Signer))}}, false},
  326. {"ok config file", args{[]Option{WithConfigFile("../ca/testdata/ca.json")}}, false},
  327. {"ok config", args{[]Option{WithConfig(&Config{
  328. Root: []string{"testdata/certs/root_ca.crt"},
  329. IntermediateCert: "testdata/certs/intermediate_ca.crt",
  330. IntermediateKey: "testdata/secrets/intermediate_ca_key",
  331. Password: "pass",
  332. AuthorityConfig: &AuthConfig{},
  333. })}}, false},
  334. {"fail options", args{[]Option{WithX509RootBundle([]byte("bad data"))}}, true},
  335. {"fail missing config", args{[]Option{WithConfig(nil), WithX509RootBundle(caPEM), WithX509Signer(crt, key.(crypto.Signer))}}, true},
  336. {"fail missing root", args{[]Option{WithX509Signer(crt, key.(crypto.Signer))}}, true},
  337. {"fail missing signer", args{[]Option{WithX509RootBundle(caPEM)}}, true},
  338. {"fail missing root file", args{[]Option{WithConfig(&Config{
  339. IntermediateCert: "testdata/certs/intermediate_ca.crt",
  340. IntermediateKey: "testdata/secrets/intermediate_ca_key",
  341. Password: "pass",
  342. AuthorityConfig: &AuthConfig{},
  343. })}}, true},
  344. {"fail missing issuer", args{[]Option{WithConfig(&Config{
  345. Root: []string{"testdata/certs/root_ca.crt"},
  346. IntermediateKey: "testdata/secrets/intermediate_ca_key",
  347. Password: "pass",
  348. AuthorityConfig: &AuthConfig{},
  349. })}}, true},
  350. {"fail missing signer", args{[]Option{WithConfig(&Config{
  351. Root: []string{"testdata/certs/root_ca.crt"},
  352. IntermediateCert: "testdata/certs/intermediate_ca.crt",
  353. Password: "pass",
  354. AuthorityConfig: &AuthConfig{},
  355. })}}, true},
  356. {"fail bad password", args{[]Option{WithConfig(&Config{
  357. Root: []string{"testdata/certs/root_ca.crt"},
  358. IntermediateCert: "testdata/certs/intermediate_ca.crt",
  359. IntermediateKey: "testdata/secrets/intermediate_ca_key",
  360. Password: "bad",
  361. AuthorityConfig: &AuthConfig{},
  362. })}}, true},
  363. }
  364. for _, tt := range tests {
  365. t.Run(tt.name, func(t *testing.T) {
  366. got, err := NewEmbedded(tt.args.opts...)
  367. if (err != nil) != tt.wantErr {
  368. t.Errorf("NewEmbedded() error = %v, wantErr %v", err, tt.wantErr)
  369. return
  370. }
  371. if err == nil {
  372. assert.True(t, got.initOnce)
  373. assert.NotNil(t, got.rootX509Certs)
  374. assert.NotNil(t, got.x509CAService)
  375. }
  376. })
  377. }
  378. }
  379. func TestNewEmbedded_Sign(t *testing.T) {
  380. caPEM, err := os.ReadFile("testdata/certs/root_ca.crt")
  381. assert.FatalError(t, err)
  382. crt, err := pemutil.ReadCertificate("testdata/certs/intermediate_ca.crt")
  383. assert.FatalError(t, err)
  384. key, err := pemutil.Read("testdata/secrets/intermediate_ca_key", pemutil.WithPassword([]byte("pass")))
  385. assert.FatalError(t, err)
  386. a, err := NewEmbedded(WithX509RootBundle(caPEM), WithX509Signer(crt, key.(crypto.Signer)))
  387. assert.FatalError(t, err)
  388. // Sign
  389. cr, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{
  390. DNSNames: []string{"foo.bar.zar"},
  391. }, key)
  392. assert.FatalError(t, err)
  393. csr, err := x509.ParseCertificateRequest(cr)
  394. assert.FatalError(t, err)
  395. cert, err := a.Sign(csr, provisioner.SignOptions{})
  396. assert.FatalError(t, err)
  397. assert.Equals(t, []string{"foo.bar.zar"}, cert[0].DNSNames)
  398. assert.Equals(t, crt, cert[1])
  399. }
  400. func TestNewEmbedded_GetTLSCertificate(t *testing.T) {
  401. caPEM, err := os.ReadFile("testdata/certs/root_ca.crt")
  402. assert.FatalError(t, err)
  403. crt, err := pemutil.ReadCertificate("testdata/certs/intermediate_ca.crt")
  404. assert.FatalError(t, err)
  405. key, err := pemutil.Read("testdata/secrets/intermediate_ca_key", pemutil.WithPassword([]byte("pass")))
  406. assert.FatalError(t, err)
  407. a, err := NewEmbedded(WithX509RootBundle(caPEM), WithX509Signer(crt, key.(crypto.Signer)))
  408. assert.FatalError(t, err)
  409. // GetTLSCertificate
  410. cert, err := a.GetTLSCertificate()
  411. assert.FatalError(t, err)
  412. assert.Equals(t, []string{"localhost"}, cert.Leaf.DNSNames)
  413. assert.True(t, cert.Leaf.IPAddresses[0].Equal(net.ParseIP("127.0.0.1")))
  414. assert.True(t, cert.Leaf.IPAddresses[1].Equal(net.ParseIP("::1")))
  415. }
  416. func TestAuthority_CloseForReload(t *testing.T) {
  417. tests := []struct {
  418. name string
  419. auth *Authority
  420. }{
  421. {"ok", testAuthority(t)},
  422. }
  423. for _, tt := range tests {
  424. t.Run(tt.name, func(t *testing.T) {
  425. tt.auth.CloseForReload()
  426. })
  427. }
  428. }
  429. func testScepAuthority(t *testing.T, opts ...Option) *Authority {
  430. p := provisioner.List{
  431. &provisioner.SCEP{
  432. Name: "scep1",
  433. Type: "SCEP",
  434. },
  435. }
  436. c := &Config{
  437. Address: "127.0.0.1:8443",
  438. InsecureAddress: "127.0.0.1:8080",
  439. Root: []string{"testdata/scep/root.crt"},
  440. IntermediateCert: "testdata/scep/intermediate.crt",
  441. IntermediateKey: "testdata/scep/intermediate.key",
  442. DNSNames: []string{"example.com"},
  443. Password: "pass",
  444. AuthorityConfig: &AuthConfig{
  445. Provisioners: p,
  446. },
  447. }
  448. a, err := New(c, opts...)
  449. assert.FatalError(t, err)
  450. return a
  451. }
  452. func TestAuthority_GetSCEPService(t *testing.T) {
  453. _ = testScepAuthority(t)
  454. p := provisioner.List{
  455. &provisioner.SCEP{
  456. Name: "scep1",
  457. Type: "SCEP",
  458. },
  459. }
  460. type fields struct {
  461. config *Config
  462. }
  463. tests := []struct {
  464. name string
  465. fields fields
  466. wantService bool
  467. wantErr bool
  468. }{
  469. {
  470. name: "ok",
  471. fields: fields{
  472. config: &Config{
  473. Address: "127.0.0.1:8443",
  474. InsecureAddress: "127.0.0.1:8080",
  475. Root: []string{"testdata/scep/root.crt"},
  476. IntermediateCert: "testdata/scep/intermediate.crt",
  477. IntermediateKey: "testdata/scep/intermediate.key",
  478. DNSNames: []string{"example.com"},
  479. Password: "pass",
  480. AuthorityConfig: &AuthConfig{
  481. Provisioners: p,
  482. },
  483. },
  484. },
  485. wantService: true,
  486. wantErr: false,
  487. },
  488. {
  489. name: "wrong password",
  490. fields: fields{
  491. config: &Config{
  492. Address: "127.0.0.1:8443",
  493. InsecureAddress: "127.0.0.1:8080",
  494. Root: []string{"testdata/scep/root.crt"},
  495. IntermediateCert: "testdata/scep/intermediate.crt",
  496. IntermediateKey: "testdata/scep/intermediate.key",
  497. DNSNames: []string{"example.com"},
  498. Password: "wrongpass",
  499. AuthorityConfig: &AuthConfig{
  500. Provisioners: p,
  501. },
  502. },
  503. },
  504. wantService: false,
  505. wantErr: true,
  506. },
  507. }
  508. for _, tt := range tests {
  509. t.Run(tt.name, func(t *testing.T) {
  510. a, err := New(tt.fields.config)
  511. if (err != nil) != tt.wantErr {
  512. t.Errorf("Authority.New(), error = %v, wantErr %v", err, tt.wantErr)
  513. return
  514. }
  515. if tt.wantService {
  516. if got := a.GetSCEPService(); (got != nil) != tt.wantService {
  517. t.Errorf("Authority.GetSCEPService() = %v, wantService %v", got, tt.wantService)
  518. }
  519. }
  520. })
  521. }
  522. }
  523. func TestAuthority_GetID(t *testing.T) {
  524. type fields struct {
  525. authorityID string
  526. }
  527. tests := []struct {
  528. name string
  529. fields fields
  530. want string
  531. }{
  532. {"ok", fields{""}, "00000000-0000-0000-0000-000000000000"},
  533. {"ok with id", fields{"10b9a431-ed3b-4a5f-abee-ec35119b65e7"}, "10b9a431-ed3b-4a5f-abee-ec35119b65e7"},
  534. }
  535. for _, tt := range tests {
  536. t.Run(tt.name, func(t *testing.T) {
  537. a := &Authority{
  538. config: &config.Config{
  539. AuthorityConfig: &config.AuthConfig{
  540. AuthorityID: tt.fields.authorityID,
  541. },
  542. },
  543. }
  544. if got := a.GetID(); got != tt.want {
  545. t.Errorf("Authority.GetID() = %v, want %v", got, tt.want)
  546. }
  547. })
  548. }
  549. }