4
0

authority_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. package authority
  2. import (
  3. "crypto"
  4. "crypto/rand"
  5. "crypto/sha256"
  6. "crypto/x509"
  7. "encoding/hex"
  8. "fmt"
  9. "net"
  10. "os"
  11. "reflect"
  12. "testing"
  13. "time"
  14. "github.com/pkg/errors"
  15. "github.com/smallstep/assert"
  16. "github.com/smallstep/certificates/authority/provisioner"
  17. "github.com/smallstep/certificates/db"
  18. "go.step.sm/crypto/jose"
  19. "go.step.sm/crypto/pemutil"
  20. )
  21. func testAuthority(t *testing.T, opts ...Option) *Authority {
  22. maxjwk, err := jose.ReadKey("testdata/secrets/max_pub.jwk")
  23. assert.FatalError(t, err)
  24. clijwk, err := jose.ReadKey("testdata/secrets/step_cli_key_pub.jwk")
  25. assert.FatalError(t, err)
  26. disableRenewal := true
  27. enableSSHCA := true
  28. p := provisioner.List{
  29. &provisioner.JWK{
  30. Name: "Max",
  31. Type: "JWK",
  32. Key: maxjwk,
  33. },
  34. &provisioner.JWK{
  35. Name: "step-cli",
  36. Type: "JWK",
  37. Key: clijwk,
  38. Claims: &provisioner.Claims{
  39. EnableSSHCA: &enableSSHCA,
  40. },
  41. },
  42. &provisioner.JWK{
  43. Name: "dev",
  44. Type: "JWK",
  45. Key: maxjwk,
  46. Claims: &provisioner.Claims{
  47. DisableRenewal: &disableRenewal,
  48. },
  49. },
  50. &provisioner.JWK{
  51. Name: "renew_disabled",
  52. Type: "JWK",
  53. Key: maxjwk,
  54. Claims: &provisioner.Claims{
  55. DisableRenewal: &disableRenewal,
  56. },
  57. },
  58. &provisioner.SSHPOP{
  59. Name: "sshpop",
  60. Type: "SSHPOP",
  61. Claims: &provisioner.Claims{
  62. EnableSSHCA: &enableSSHCA,
  63. },
  64. },
  65. }
  66. c := &Config{
  67. Address: "127.0.0.1:443",
  68. Root: []string{"testdata/certs/root_ca.crt"},
  69. IntermediateCert: "testdata/certs/intermediate_ca.crt",
  70. IntermediateKey: "testdata/secrets/intermediate_ca_key",
  71. SSH: &SSHConfig{
  72. HostKey: "testdata/secrets/ssh_host_ca_key",
  73. UserKey: "testdata/secrets/ssh_user_ca_key",
  74. },
  75. DNSNames: []string{"example.com"},
  76. Password: "pass",
  77. AuthorityConfig: &AuthConfig{
  78. Provisioners: p,
  79. },
  80. }
  81. a, err := New(c, opts...)
  82. assert.FatalError(t, err)
  83. // Avoid errors when test tokens are created before the test authority. This
  84. // happens in some tests where we re-create the same authority to test
  85. // special cases without re-creating the token.
  86. a.startTime = a.startTime.Add(-1 * time.Minute)
  87. return a
  88. }
  89. func TestAuthorityNew(t *testing.T) {
  90. type newTest struct {
  91. config *Config
  92. err error
  93. }
  94. tests := map[string]func(t *testing.T) *newTest{
  95. "ok": func(t *testing.T) *newTest {
  96. c, err := LoadConfiguration("../ca/testdata/ca.json")
  97. assert.FatalError(t, err)
  98. return &newTest{
  99. config: c,
  100. }
  101. },
  102. "fail bad root": func(t *testing.T) *newTest {
  103. c, err := LoadConfiguration("../ca/testdata/ca.json")
  104. assert.FatalError(t, err)
  105. c.Root = []string{"foo"}
  106. return &newTest{
  107. config: c,
  108. err: errors.New("error reading foo: no such file or directory"),
  109. }
  110. },
  111. "fail bad password": func(t *testing.T) *newTest {
  112. c, err := LoadConfiguration("../ca/testdata/ca.json")
  113. assert.FatalError(t, err)
  114. c.Password = "wrong"
  115. return &newTest{
  116. config: c,
  117. err: errors.New("error decrypting ../ca/testdata/secrets/intermediate_ca_key: x509: decryption password incorrect"),
  118. }
  119. },
  120. "fail loading CA cert": func(t *testing.T) *newTest {
  121. c, err := LoadConfiguration("../ca/testdata/ca.json")
  122. assert.FatalError(t, err)
  123. c.IntermediateCert = "wrong"
  124. return &newTest{
  125. config: c,
  126. err: errors.New("error reading wrong: no such file or directory"),
  127. }
  128. },
  129. }
  130. for name, genTestCase := range tests {
  131. t.Run(name, func(t *testing.T) {
  132. tc := genTestCase(t)
  133. auth, err := New(tc.config)
  134. if err != nil {
  135. if assert.NotNil(t, tc.err) {
  136. assert.HasPrefix(t, err.Error(), tc.err.Error())
  137. }
  138. } else {
  139. if assert.Nil(t, tc.err) {
  140. sum := sha256.Sum256(auth.rootX509Certs[0].Raw)
  141. root, ok := auth.certificates.Load(hex.EncodeToString(sum[:]))
  142. assert.Fatal(t, ok)
  143. assert.Equals(t, auth.rootX509Certs[0], root)
  144. assert.True(t, auth.initOnce)
  145. assert.NotNil(t, auth.x509CAService)
  146. for _, p := range tc.config.AuthorityConfig.Provisioners {
  147. var _p provisioner.Interface
  148. _p, ok = auth.provisioners.Load(p.GetID())
  149. assert.True(t, ok)
  150. assert.Equals(t, p, _p)
  151. var kid, encryptedKey string
  152. if kid, encryptedKey, ok = p.GetEncryptedKey(); ok {
  153. var key string
  154. key, ok = auth.provisioners.LoadEncryptedKey(kid)
  155. assert.True(t, ok)
  156. assert.Equals(t, encryptedKey, key)
  157. }
  158. }
  159. // sanity check
  160. _, ok = auth.provisioners.Load("fooo")
  161. assert.False(t, ok)
  162. }
  163. }
  164. })
  165. }
  166. }
  167. func TestAuthority_GetDatabase(t *testing.T) {
  168. auth := testAuthority(t)
  169. authWithDatabase, err := New(auth.config, WithDatabase(auth.db))
  170. assert.FatalError(t, err)
  171. tests := []struct {
  172. name string
  173. auth *Authority
  174. want db.AuthDB
  175. }{
  176. {"ok", auth, auth.db},
  177. {"ok WithDatabase", authWithDatabase, auth.db},
  178. }
  179. for _, tt := range tests {
  180. t.Run(tt.name, func(t *testing.T) {
  181. if got := tt.auth.GetDatabase(); !reflect.DeepEqual(got, tt.want) {
  182. t.Errorf("Authority.GetDatabase() = %v, want %v", got, tt.want)
  183. }
  184. })
  185. }
  186. }
  187. func TestNewEmbedded(t *testing.T) {
  188. caPEM, err := os.ReadFile("testdata/certs/root_ca.crt")
  189. assert.FatalError(t, err)
  190. crt, err := pemutil.ReadCertificate("testdata/certs/intermediate_ca.crt")
  191. assert.FatalError(t, err)
  192. key, err := pemutil.Read("testdata/secrets/intermediate_ca_key", pemutil.WithPassword([]byte("pass")))
  193. assert.FatalError(t, err)
  194. type args struct {
  195. opts []Option
  196. }
  197. tests := []struct {
  198. name string
  199. args args
  200. wantErr bool
  201. }{
  202. {"ok", args{[]Option{WithX509RootBundle(caPEM), WithX509Signer(crt, key.(crypto.Signer))}}, false},
  203. {"ok empty config", args{[]Option{WithConfig(&Config{}), WithX509RootBundle(caPEM), WithX509Signer(crt, key.(crypto.Signer))}}, false},
  204. {"ok config file", args{[]Option{WithConfigFile("../ca/testdata/ca.json")}}, false},
  205. {"ok config", args{[]Option{WithConfig(&Config{
  206. Root: []string{"testdata/certs/root_ca.crt"},
  207. IntermediateCert: "testdata/certs/intermediate_ca.crt",
  208. IntermediateKey: "testdata/secrets/intermediate_ca_key",
  209. Password: "pass",
  210. AuthorityConfig: &AuthConfig{},
  211. })}}, false},
  212. {"fail options", args{[]Option{WithX509RootBundle([]byte("bad data"))}}, true},
  213. {"fail missing config", args{[]Option{WithConfig(nil), WithX509RootBundle(caPEM), WithX509Signer(crt, key.(crypto.Signer))}}, true},
  214. {"fail missing root", args{[]Option{WithX509Signer(crt, key.(crypto.Signer))}}, true},
  215. {"fail missing signer", args{[]Option{WithX509RootBundle(caPEM)}}, true},
  216. {"fail missing root file", args{[]Option{WithConfig(&Config{
  217. IntermediateCert: "testdata/certs/intermediate_ca.crt",
  218. IntermediateKey: "testdata/secrets/intermediate_ca_key",
  219. Password: "pass",
  220. AuthorityConfig: &AuthConfig{},
  221. })}}, true},
  222. {"fail missing issuer", args{[]Option{WithConfig(&Config{
  223. Root: []string{"testdata/certs/root_ca.crt"},
  224. IntermediateKey: "testdata/secrets/intermediate_ca_key",
  225. Password: "pass",
  226. AuthorityConfig: &AuthConfig{},
  227. })}}, true},
  228. {"fail missing signer", args{[]Option{WithConfig(&Config{
  229. Root: []string{"testdata/certs/root_ca.crt"},
  230. IntermediateCert: "testdata/certs/intermediate_ca.crt",
  231. Password: "pass",
  232. AuthorityConfig: &AuthConfig{},
  233. })}}, true},
  234. {"fail bad password", args{[]Option{WithConfig(&Config{
  235. Root: []string{"testdata/certs/root_ca.crt"},
  236. IntermediateCert: "testdata/certs/intermediate_ca.crt",
  237. IntermediateKey: "testdata/secrets/intermediate_ca_key",
  238. Password: "bad",
  239. AuthorityConfig: &AuthConfig{},
  240. })}}, true},
  241. }
  242. for _, tt := range tests {
  243. t.Run(tt.name, func(t *testing.T) {
  244. got, err := NewEmbedded(tt.args.opts...)
  245. if (err != nil) != tt.wantErr {
  246. t.Errorf("NewEmbedded() error = %v, wantErr %v", err, tt.wantErr)
  247. return
  248. }
  249. if err == nil {
  250. assert.True(t, got.initOnce)
  251. assert.NotNil(t, got.rootX509Certs)
  252. assert.NotNil(t, got.x509CAService)
  253. }
  254. })
  255. }
  256. }
  257. func TestNewEmbedded_Sign(t *testing.T) {
  258. caPEM, err := os.ReadFile("testdata/certs/root_ca.crt")
  259. assert.FatalError(t, err)
  260. crt, err := pemutil.ReadCertificate("testdata/certs/intermediate_ca.crt")
  261. assert.FatalError(t, err)
  262. key, err := pemutil.Read("testdata/secrets/intermediate_ca_key", pemutil.WithPassword([]byte("pass")))
  263. assert.FatalError(t, err)
  264. a, err := NewEmbedded(WithX509RootBundle(caPEM), WithX509Signer(crt, key.(crypto.Signer)))
  265. assert.FatalError(t, err)
  266. // Sign
  267. cr, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{
  268. DNSNames: []string{"foo.bar.zar"},
  269. }, key)
  270. assert.FatalError(t, err)
  271. csr, err := x509.ParseCertificateRequest(cr)
  272. assert.FatalError(t, err)
  273. cert, err := a.Sign(csr, provisioner.SignOptions{})
  274. assert.FatalError(t, err)
  275. assert.Equals(t, []string{"foo.bar.zar"}, cert[0].DNSNames)
  276. assert.Equals(t, crt, cert[1])
  277. }
  278. func TestNewEmbedded_GetTLSCertificate(t *testing.T) {
  279. caPEM, err := os.ReadFile("testdata/certs/root_ca.crt")
  280. assert.FatalError(t, err)
  281. crt, err := pemutil.ReadCertificate("testdata/certs/intermediate_ca.crt")
  282. assert.FatalError(t, err)
  283. key, err := pemutil.Read("testdata/secrets/intermediate_ca_key", pemutil.WithPassword([]byte("pass")))
  284. assert.FatalError(t, err)
  285. a, err := NewEmbedded(WithX509RootBundle(caPEM), WithX509Signer(crt, key.(crypto.Signer)))
  286. assert.FatalError(t, err)
  287. // GetTLSCertificate
  288. cert, err := a.GetTLSCertificate()
  289. assert.FatalError(t, err)
  290. assert.Equals(t, []string{"localhost"}, cert.Leaf.DNSNames)
  291. assert.True(t, cert.Leaf.IPAddresses[0].Equal(net.ParseIP("127.0.0.1")))
  292. assert.True(t, cert.Leaf.IPAddresses[1].Equal(net.ParseIP("::1")))
  293. }
  294. func TestAuthority_CloseForReload(t *testing.T) {
  295. tests := []struct {
  296. name string
  297. auth *Authority
  298. }{
  299. {"ok", testAuthority(t)},
  300. }
  301. for _, tt := range tests {
  302. t.Run(tt.name, func(t *testing.T) {
  303. tt.auth.CloseForReload()
  304. })
  305. }
  306. }
  307. func testScepAuthority(t *testing.T, opts ...Option) *Authority {
  308. p := provisioner.List{
  309. &provisioner.SCEP{
  310. Name: "scep1",
  311. Type: "SCEP",
  312. },
  313. }
  314. c := &Config{
  315. Address: "127.0.0.1:8443",
  316. InsecureAddress: "127.0.0.1:8080",
  317. Root: []string{"testdata/scep/root.crt"},
  318. IntermediateCert: "testdata/scep/intermediate.crt",
  319. IntermediateKey: "testdata/scep/intermediate.key",
  320. DNSNames: []string{"example.com"},
  321. Password: "pass",
  322. AuthorityConfig: &AuthConfig{
  323. Provisioners: p,
  324. },
  325. }
  326. a, err := New(c, opts...)
  327. assert.FatalError(t, err)
  328. return a
  329. }
  330. func TestAuthority_GetSCEPService(t *testing.T) {
  331. auth := testScepAuthority(t)
  332. fmt.Println(auth)
  333. p := provisioner.List{
  334. &provisioner.SCEP{
  335. Name: "scep1",
  336. Type: "SCEP",
  337. },
  338. }
  339. type fields struct {
  340. config *Config
  341. // keyManager kms.KeyManager
  342. // provisioners *provisioner.Collection
  343. // db db.AuthDB
  344. // templates *templates.Templates
  345. // x509CAService cas.CertificateAuthorityService
  346. // rootX509Certs []*x509.Certificate
  347. // federatedX509Certs []*x509.Certificate
  348. // certificates *sync.Map
  349. // scepService *scep.Service
  350. // sshCAUserCertSignKey ssh.Signer
  351. // sshCAHostCertSignKey ssh.Signer
  352. // sshCAUserCerts []ssh.PublicKey
  353. // sshCAHostCerts []ssh.PublicKey
  354. // sshCAUserFederatedCerts []ssh.PublicKey
  355. // sshCAHostFederatedCerts []ssh.PublicKey
  356. // initOnce bool
  357. // startTime time.Time
  358. // sshBastionFunc func(ctx context.Context, user, hostname string) (*Bastion, error)
  359. // sshCheckHostFunc func(ctx context.Context, principal string, tok string, roots []*x509.Certificate) (bool, error)
  360. // sshGetHostsFunc func(ctx context.Context, cert *x509.Certificate) ([]Host, error)
  361. // getIdentityFunc provisioner.GetIdentityFunc
  362. }
  363. tests := []struct {
  364. name string
  365. fields fields
  366. wantService bool
  367. wantErr bool
  368. }{
  369. {
  370. name: "ok",
  371. fields: fields{
  372. config: &Config{
  373. Address: "127.0.0.1:8443",
  374. InsecureAddress: "127.0.0.1:8080",
  375. Root: []string{"testdata/scep/root.crt"},
  376. IntermediateCert: "testdata/scep/intermediate.crt",
  377. IntermediateKey: "testdata/scep/intermediate.key",
  378. DNSNames: []string{"example.com"},
  379. Password: "pass",
  380. AuthorityConfig: &AuthConfig{
  381. Provisioners: p,
  382. },
  383. },
  384. },
  385. wantService: true,
  386. wantErr: false,
  387. },
  388. {
  389. name: "wrong password",
  390. fields: fields{
  391. config: &Config{
  392. Address: "127.0.0.1:8443",
  393. InsecureAddress: "127.0.0.1:8080",
  394. Root: []string{"testdata/scep/root.crt"},
  395. IntermediateCert: "testdata/scep/intermediate.crt",
  396. IntermediateKey: "testdata/scep/intermediate.key",
  397. DNSNames: []string{"example.com"},
  398. Password: "wrongpass",
  399. AuthorityConfig: &AuthConfig{
  400. Provisioners: p,
  401. },
  402. },
  403. },
  404. wantService: false,
  405. wantErr: true,
  406. },
  407. }
  408. for _, tt := range tests {
  409. t.Run(tt.name, func(t *testing.T) {
  410. // a := &Authority{
  411. // config: tt.fields.config,
  412. // keyManager: tt.fields.keyManager,
  413. // provisioners: tt.fields.provisioners,
  414. // db: tt.fields.db,
  415. // templates: tt.fields.templates,
  416. // x509CAService: tt.fields.x509CAService,
  417. // rootX509Certs: tt.fields.rootX509Certs,
  418. // federatedX509Certs: tt.fields.federatedX509Certs,
  419. // certificates: tt.fields.certificates,
  420. // scepService: tt.fields.scepService,
  421. // sshCAUserCertSignKey: tt.fields.sshCAUserCertSignKey,
  422. // sshCAHostCertSignKey: tt.fields.sshCAHostCertSignKey,
  423. // sshCAUserCerts: tt.fields.sshCAUserCerts,
  424. // sshCAHostCerts: tt.fields.sshCAHostCerts,
  425. // sshCAUserFederatedCerts: tt.fields.sshCAUserFederatedCerts,
  426. // sshCAHostFederatedCerts: tt.fields.sshCAHostFederatedCerts,
  427. // initOnce: tt.fields.initOnce,
  428. // startTime: tt.fields.startTime,
  429. // sshBastionFunc: tt.fields.sshBastionFunc,
  430. // sshCheckHostFunc: tt.fields.sshCheckHostFunc,
  431. // sshGetHostsFunc: tt.fields.sshGetHostsFunc,
  432. // getIdentityFunc: tt.fields.getIdentityFunc,
  433. // }
  434. a, err := New(tt.fields.config)
  435. if (err != nil) != tt.wantErr {
  436. t.Errorf("Authority.New(), error = %v, wantErr %v", err, tt.wantErr)
  437. return
  438. }
  439. if tt.wantService {
  440. if got := a.GetSCEPService(); (got != nil) != tt.wantService {
  441. t.Errorf("Authority.GetSCEPService() = %v, wantService %v", got, tt.wantService)
  442. }
  443. }
  444. })
  445. }
  446. }