authority_test.go 14 KB

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