authority_test.go 17 KB

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