ssh_test.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  1. package authority
  2. import (
  3. "context"
  4. "crypto/ecdsa"
  5. "crypto/elliptic"
  6. "crypto/rand"
  7. "crypto/x509"
  8. "encoding/base64"
  9. "fmt"
  10. "net/http"
  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. "github.com/smallstep/certificates/errs"
  19. "github.com/smallstep/certificates/sshutil"
  20. "github.com/smallstep/certificates/templates"
  21. "github.com/smallstep/cli/jose"
  22. "golang.org/x/crypto/ssh"
  23. )
  24. type sshTestModifier ssh.Certificate
  25. func (m sshTestModifier) Modify(cert *ssh.Certificate) error {
  26. if m.CertType != 0 {
  27. cert.CertType = m.CertType
  28. }
  29. if m.KeyId != "" {
  30. cert.KeyId = m.KeyId
  31. }
  32. if m.ValidAfter != 0 {
  33. cert.ValidAfter = m.ValidAfter
  34. }
  35. if m.ValidBefore != 0 {
  36. cert.ValidBefore = m.ValidBefore
  37. }
  38. if len(m.ValidPrincipals) != 0 {
  39. cert.ValidPrincipals = m.ValidPrincipals
  40. }
  41. if m.Permissions.CriticalOptions != nil {
  42. cert.Permissions.CriticalOptions = m.Permissions.CriticalOptions
  43. }
  44. if m.Permissions.Extensions != nil {
  45. cert.Permissions.Extensions = m.Permissions.Extensions
  46. }
  47. return nil
  48. }
  49. type sshTestCertModifier string
  50. func (m sshTestCertModifier) Modify(cert *ssh.Certificate) error {
  51. if m == "" {
  52. return nil
  53. }
  54. return fmt.Errorf(string(m))
  55. }
  56. type sshTestCertValidator string
  57. func (v sshTestCertValidator) Valid(crt *ssh.Certificate, opts provisioner.SSHOptions) error {
  58. if v == "" {
  59. return nil
  60. }
  61. return fmt.Errorf(string(v))
  62. }
  63. type sshTestOptionsValidator string
  64. func (v sshTestOptionsValidator) Valid(opts provisioner.SSHOptions) error {
  65. if v == "" {
  66. return nil
  67. }
  68. return fmt.Errorf(string(v))
  69. }
  70. type sshTestOptionsModifier string
  71. func (m sshTestOptionsModifier) Option(opts provisioner.SSHOptions) provisioner.SSHCertModifier {
  72. return sshTestCertModifier(string(m))
  73. }
  74. func TestAuthority_SignSSH(t *testing.T) {
  75. key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  76. assert.FatalError(t, err)
  77. pub, err := ssh.NewPublicKey(key.Public())
  78. assert.FatalError(t, err)
  79. signKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  80. assert.FatalError(t, err)
  81. signer, err := ssh.NewSignerFromKey(signKey)
  82. assert.FatalError(t, err)
  83. userOptions := sshTestModifier{
  84. CertType: ssh.UserCert,
  85. }
  86. hostOptions := sshTestModifier{
  87. CertType: ssh.HostCert,
  88. }
  89. now := time.Now()
  90. type fields struct {
  91. sshCAUserCertSignKey ssh.Signer
  92. sshCAHostCertSignKey ssh.Signer
  93. }
  94. type args struct {
  95. key ssh.PublicKey
  96. opts provisioner.SSHOptions
  97. signOpts []provisioner.SignOption
  98. }
  99. type want struct {
  100. CertType uint32
  101. Principals []string
  102. ValidAfter uint64
  103. ValidBefore uint64
  104. }
  105. tests := []struct {
  106. name string
  107. fields fields
  108. args args
  109. want want
  110. wantErr bool
  111. }{
  112. {"ok-user", fields{signer, signer}, args{pub, provisioner.SSHOptions{}, []provisioner.SignOption{userOptions}}, want{CertType: ssh.UserCert}, false},
  113. {"ok-host", fields{signer, signer}, args{pub, provisioner.SSHOptions{}, []provisioner.SignOption{hostOptions}}, want{CertType: ssh.HostCert}, false},
  114. {"ok-opts-type-user", fields{signer, signer}, args{pub, provisioner.SSHOptions{CertType: "user"}, []provisioner.SignOption{}}, want{CertType: ssh.UserCert}, false},
  115. {"ok-opts-type-host", fields{signer, signer}, args{pub, provisioner.SSHOptions{CertType: "host"}, []provisioner.SignOption{}}, want{CertType: ssh.HostCert}, false},
  116. {"ok-opts-principals", fields{signer, signer}, args{pub, provisioner.SSHOptions{CertType: "user", Principals: []string{"user"}}, []provisioner.SignOption{}}, want{CertType: ssh.UserCert, Principals: []string{"user"}}, false},
  117. {"ok-opts-principals", fields{signer, signer}, args{pub, provisioner.SSHOptions{CertType: "host", Principals: []string{"foo.test.com", "bar.test.com"}}, []provisioner.SignOption{}}, want{CertType: ssh.HostCert, Principals: []string{"foo.test.com", "bar.test.com"}}, false},
  118. {"ok-opts-valid-after", fields{signer, signer}, args{pub, provisioner.SSHOptions{CertType: "user", ValidAfter: provisioner.NewTimeDuration(now)}, []provisioner.SignOption{}}, want{CertType: ssh.UserCert, ValidAfter: uint64(now.Unix())}, false},
  119. {"ok-opts-valid-before", fields{signer, signer}, args{pub, provisioner.SSHOptions{CertType: "host", ValidBefore: provisioner.NewTimeDuration(now)}, []provisioner.SignOption{}}, want{CertType: ssh.HostCert, ValidBefore: uint64(now.Unix())}, false},
  120. {"ok-cert-validator", fields{signer, signer}, args{pub, provisioner.SSHOptions{}, []provisioner.SignOption{userOptions, sshTestCertValidator("")}}, want{CertType: ssh.UserCert}, false},
  121. {"ok-cert-modifier", fields{signer, signer}, args{pub, provisioner.SSHOptions{}, []provisioner.SignOption{userOptions, sshTestCertModifier("")}}, want{CertType: ssh.UserCert}, false},
  122. {"ok-opts-validator", fields{signer, signer}, args{pub, provisioner.SSHOptions{}, []provisioner.SignOption{userOptions, sshTestOptionsValidator("")}}, want{CertType: ssh.UserCert}, false},
  123. {"ok-opts-modifier", fields{signer, signer}, args{pub, provisioner.SSHOptions{}, []provisioner.SignOption{userOptions, sshTestOptionsModifier("")}}, want{CertType: ssh.UserCert}, false},
  124. {"fail-opts-type", fields{signer, signer}, args{pub, provisioner.SSHOptions{CertType: "foo"}, []provisioner.SignOption{}}, want{}, true},
  125. {"fail-cert-validator", fields{signer, signer}, args{pub, provisioner.SSHOptions{}, []provisioner.SignOption{userOptions, sshTestCertValidator("an error")}}, want{}, true},
  126. {"fail-cert-modifier", fields{signer, signer}, args{pub, provisioner.SSHOptions{}, []provisioner.SignOption{userOptions, sshTestCertModifier("an error")}}, want{}, true},
  127. {"fail-opts-validator", fields{signer, signer}, args{pub, provisioner.SSHOptions{}, []provisioner.SignOption{userOptions, sshTestOptionsValidator("an error")}}, want{}, true},
  128. {"fail-opts-modifier", fields{signer, signer}, args{pub, provisioner.SSHOptions{}, []provisioner.SignOption{userOptions, sshTestOptionsModifier("an error")}}, want{}, true},
  129. {"fail-bad-sign-options", fields{signer, signer}, args{pub, provisioner.SSHOptions{}, []provisioner.SignOption{userOptions, "wrong type"}}, want{}, true},
  130. {"fail-no-user-key", fields{nil, signer}, args{pub, provisioner.SSHOptions{CertType: "user"}, []provisioner.SignOption{}}, want{}, true},
  131. {"fail-no-host-key", fields{signer, nil}, args{pub, provisioner.SSHOptions{CertType: "host"}, []provisioner.SignOption{}}, want{}, true},
  132. {"fail-bad-type", fields{signer, nil}, args{pub, provisioner.SSHOptions{}, []provisioner.SignOption{sshTestModifier{CertType: 0}}}, want{}, true},
  133. }
  134. for _, tt := range tests {
  135. t.Run(tt.name, func(t *testing.T) {
  136. a := testAuthority(t)
  137. a.sshCAUserCertSignKey = tt.fields.sshCAUserCertSignKey
  138. a.sshCAHostCertSignKey = tt.fields.sshCAHostCertSignKey
  139. got, err := a.SignSSH(context.Background(), tt.args.key, tt.args.opts, tt.args.signOpts...)
  140. if (err != nil) != tt.wantErr {
  141. t.Errorf("Authority.SignSSH() error = %v, wantErr %v", err, tt.wantErr)
  142. return
  143. }
  144. if err == nil && assert.NotNil(t, got) {
  145. assert.Equals(t, tt.want.CertType, got.CertType)
  146. assert.Equals(t, tt.want.Principals, got.ValidPrincipals)
  147. assert.Equals(t, tt.want.ValidAfter, got.ValidAfter)
  148. assert.Equals(t, tt.want.ValidBefore, got.ValidBefore)
  149. assert.NotNil(t, got.Key)
  150. assert.NotNil(t, got.Nonce)
  151. assert.NotEquals(t, 0, got.Serial)
  152. assert.NotNil(t, got.Signature)
  153. assert.NotNil(t, got.SignatureKey)
  154. }
  155. })
  156. }
  157. }
  158. func TestAuthority_SignSSHAddUser(t *testing.T) {
  159. key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  160. assert.FatalError(t, err)
  161. pub, err := ssh.NewPublicKey(key.Public())
  162. assert.FatalError(t, err)
  163. signKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  164. assert.FatalError(t, err)
  165. signer, err := ssh.NewSignerFromKey(signKey)
  166. assert.FatalError(t, err)
  167. type fields struct {
  168. sshCAUserCertSignKey ssh.Signer
  169. sshCAHostCertSignKey ssh.Signer
  170. addUserPrincipal string
  171. addUserCommand string
  172. }
  173. type args struct {
  174. key ssh.PublicKey
  175. subject *ssh.Certificate
  176. }
  177. type want struct {
  178. CertType uint32
  179. Principals []string
  180. ValidAfter uint64
  181. ValidBefore uint64
  182. ForceCommand string
  183. }
  184. now := time.Now()
  185. validCert := &ssh.Certificate{
  186. CertType: ssh.UserCert,
  187. ValidPrincipals: []string{"user"},
  188. ValidAfter: uint64(now.Unix()),
  189. ValidBefore: uint64(now.Add(time.Hour).Unix()),
  190. }
  191. validWant := want{
  192. CertType: ssh.UserCert,
  193. Principals: []string{"provisioner"},
  194. ValidAfter: uint64(now.Unix()),
  195. ValidBefore: uint64(now.Add(time.Hour).Unix()),
  196. ForceCommand: "sudo useradd -m user; nc -q0 localhost 22",
  197. }
  198. tests := []struct {
  199. name string
  200. fields fields
  201. args args
  202. want want
  203. wantErr bool
  204. }{
  205. {"ok", fields{signer, signer, "", ""}, args{pub, validCert}, validWant, false},
  206. {"ok-no-host-key", fields{signer, nil, "", ""}, args{pub, validCert}, validWant, false},
  207. {"ok-custom-principal", fields{signer, signer, "my-principal", ""}, args{pub, &ssh.Certificate{CertType: ssh.UserCert, ValidPrincipals: []string{"user"}}}, want{CertType: ssh.UserCert, Principals: []string{"my-principal"}, ForceCommand: "sudo useradd -m user; nc -q0 localhost 22"}, false},
  208. {"ok-custom-command", fields{signer, signer, "", "foo <principal> <principal>"}, args{pub, &ssh.Certificate{CertType: ssh.UserCert, ValidPrincipals: []string{"user"}}}, want{CertType: ssh.UserCert, Principals: []string{"provisioner"}, ForceCommand: "foo user user"}, false},
  209. {"ok-custom-principal-and-command", fields{signer, signer, "my-principal", "foo <principal> <principal>"}, args{pub, &ssh.Certificate{CertType: ssh.UserCert, ValidPrincipals: []string{"user"}}}, want{CertType: ssh.UserCert, Principals: []string{"my-principal"}, ForceCommand: "foo user user"}, false},
  210. {"fail-no-user-key", fields{nil, signer, "", ""}, args{pub, validCert}, want{}, true},
  211. {"fail-no-user-cert", fields{signer, signer, "", ""}, args{pub, &ssh.Certificate{CertType: ssh.HostCert, ValidPrincipals: []string{"foo"}}}, want{}, true},
  212. {"fail-no-principals", fields{signer, signer, "", ""}, args{pub, &ssh.Certificate{CertType: ssh.UserCert, ValidPrincipals: []string{}}}, want{}, true},
  213. {"fail-many-principals", fields{signer, signer, "", ""}, args{pub, &ssh.Certificate{CertType: ssh.UserCert, ValidPrincipals: []string{"foo", "bar"}}}, want{}, true},
  214. }
  215. for _, tt := range tests {
  216. t.Run(tt.name, func(t *testing.T) {
  217. a := testAuthority(t)
  218. a.sshCAUserCertSignKey = tt.fields.sshCAUserCertSignKey
  219. a.sshCAHostCertSignKey = tt.fields.sshCAHostCertSignKey
  220. a.config.SSH = &SSHConfig{
  221. AddUserPrincipal: tt.fields.addUserPrincipal,
  222. AddUserCommand: tt.fields.addUserCommand,
  223. }
  224. got, err := a.SignSSHAddUser(context.Background(), tt.args.key, tt.args.subject)
  225. if (err != nil) != tt.wantErr {
  226. t.Errorf("Authority.SignSSHAddUser() error = %v, wantErr %v", err, tt.wantErr)
  227. return
  228. }
  229. if err == nil && assert.NotNil(t, got) {
  230. assert.Equals(t, tt.want.CertType, got.CertType)
  231. assert.Equals(t, tt.want.Principals, got.ValidPrincipals)
  232. assert.Equals(t, tt.args.subject.ValidPrincipals[0]+"-"+tt.want.Principals[0], got.KeyId)
  233. assert.Equals(t, tt.want.ValidAfter, got.ValidAfter)
  234. assert.Equals(t, tt.want.ValidBefore, got.ValidBefore)
  235. assert.Equals(t, map[string]string{"force-command": tt.want.ForceCommand}, got.CriticalOptions)
  236. assert.Equals(t, nil, got.Extensions)
  237. assert.NotNil(t, got.Key)
  238. assert.NotNil(t, got.Nonce)
  239. assert.NotEquals(t, 0, got.Serial)
  240. assert.NotNil(t, got.Signature)
  241. assert.NotNil(t, got.SignatureKey)
  242. }
  243. })
  244. }
  245. }
  246. func TestAuthority_GetSSHRoots(t *testing.T) {
  247. key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  248. assert.FatalError(t, err)
  249. user, err := ssh.NewPublicKey(key.Public())
  250. assert.FatalError(t, err)
  251. key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  252. assert.FatalError(t, err)
  253. host, err := ssh.NewPublicKey(key.Public())
  254. assert.FatalError(t, err)
  255. type fields struct {
  256. sshCAUserCerts []ssh.PublicKey
  257. sshCAHostCerts []ssh.PublicKey
  258. }
  259. tests := []struct {
  260. name string
  261. fields fields
  262. want *SSHKeys
  263. wantErr bool
  264. }{
  265. {"ok", fields{[]ssh.PublicKey{user}, []ssh.PublicKey{host}}, &SSHKeys{UserKeys: []ssh.PublicKey{user}, HostKeys: []ssh.PublicKey{host}}, false},
  266. {"nil", fields{}, &SSHKeys{}, false},
  267. }
  268. for _, tt := range tests {
  269. t.Run(tt.name, func(t *testing.T) {
  270. a := testAuthority(t)
  271. a.sshCAUserCerts = tt.fields.sshCAUserCerts
  272. a.sshCAHostCerts = tt.fields.sshCAHostCerts
  273. got, err := a.GetSSHRoots(context.Background())
  274. if (err != nil) != tt.wantErr {
  275. t.Errorf("Authority.GetSSHRoots() error = %v, wantErr %v", err, tt.wantErr)
  276. return
  277. }
  278. if !reflect.DeepEqual(got, tt.want) {
  279. t.Errorf("Authority.GetSSHRoots() = %v, want %v", got, tt.want)
  280. }
  281. })
  282. }
  283. }
  284. func TestAuthority_GetSSHFederation(t *testing.T) {
  285. key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  286. assert.FatalError(t, err)
  287. user, err := ssh.NewPublicKey(key.Public())
  288. assert.FatalError(t, err)
  289. key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  290. assert.FatalError(t, err)
  291. host, err := ssh.NewPublicKey(key.Public())
  292. assert.FatalError(t, err)
  293. type fields struct {
  294. sshCAUserFederatedCerts []ssh.PublicKey
  295. sshCAHostFederatedCerts []ssh.PublicKey
  296. }
  297. tests := []struct {
  298. name string
  299. fields fields
  300. want *SSHKeys
  301. wantErr bool
  302. }{
  303. {"ok", fields{[]ssh.PublicKey{user}, []ssh.PublicKey{host}}, &SSHKeys{UserKeys: []ssh.PublicKey{user}, HostKeys: []ssh.PublicKey{host}}, false},
  304. {"nil", fields{}, &SSHKeys{}, false},
  305. }
  306. for _, tt := range tests {
  307. t.Run(tt.name, func(t *testing.T) {
  308. a := testAuthority(t)
  309. a.sshCAUserFederatedCerts = tt.fields.sshCAUserFederatedCerts
  310. a.sshCAHostFederatedCerts = tt.fields.sshCAHostFederatedCerts
  311. got, err := a.GetSSHFederation(context.Background())
  312. if (err != nil) != tt.wantErr {
  313. t.Errorf("Authority.GetSSHFederation() error = %v, wantErr %v", err, tt.wantErr)
  314. return
  315. }
  316. if !reflect.DeepEqual(got, tt.want) {
  317. t.Errorf("Authority.GetSSHFederation() = %v, want %v", got, tt.want)
  318. }
  319. })
  320. }
  321. }
  322. func TestAuthority_GetSSHConfig(t *testing.T) {
  323. key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  324. assert.FatalError(t, err)
  325. user, err := ssh.NewPublicKey(key.Public())
  326. assert.FatalError(t, err)
  327. userSigner, err := ssh.NewSignerFromSigner(key)
  328. assert.FatalError(t, err)
  329. userB64 := base64.StdEncoding.EncodeToString(user.Marshal())
  330. key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  331. assert.FatalError(t, err)
  332. host, err := ssh.NewPublicKey(key.Public())
  333. assert.FatalError(t, err)
  334. hostSigner, err := ssh.NewSignerFromSigner(key)
  335. assert.FatalError(t, err)
  336. hostB64 := base64.StdEncoding.EncodeToString(host.Marshal())
  337. tmplConfig := &templates.Templates{
  338. SSH: &templates.SSHTemplates{
  339. User: []templates.Template{
  340. {Name: "known_host.tpl", Type: templates.File, TemplatePath: "./testdata/templates/known_hosts.tpl", Path: "ssh/known_host", Comment: "#"},
  341. },
  342. Host: []templates.Template{
  343. {Name: "ca.tpl", Type: templates.File, TemplatePath: "./testdata/templates/ca.tpl", Path: "/etc/ssh/ca.pub", Comment: "#"},
  344. },
  345. },
  346. Data: map[string]interface{}{
  347. "Step": &templates.Step{
  348. SSH: templates.StepSSH{
  349. UserKey: user,
  350. HostKey: host,
  351. },
  352. },
  353. },
  354. }
  355. userOutput := []templates.Output{
  356. {Name: "known_host.tpl", Type: templates.File, Comment: "#", Path: "ssh/known_host", Content: []byte(fmt.Sprintf("@cert-authority * %s %s", host.Type(), hostB64))},
  357. }
  358. hostOutput := []templates.Output{
  359. {Name: "ca.tpl", Type: templates.File, Comment: "#", Path: "/etc/ssh/ca.pub", Content: []byte(user.Type() + " " + userB64)},
  360. }
  361. tmplConfigWithUserData := &templates.Templates{
  362. SSH: &templates.SSHTemplates{
  363. User: []templates.Template{
  364. {Name: "include.tpl", Type: templates.File, TemplatePath: "./testdata/templates/include.tpl", Path: "ssh/include", Comment: "#"},
  365. {Name: "config.tpl", Type: templates.File, TemplatePath: "./testdata/templates/config.tpl", Path: "ssh/config", Comment: "#"},
  366. },
  367. Host: []templates.Template{
  368. {
  369. Name: "sshd_config.tpl",
  370. Type: templates.File,
  371. TemplatePath: "./testdata/templates/sshd_config.tpl",
  372. Path: "/etc/ssh/sshd_config",
  373. Comment: "#",
  374. RequiredData: []string{"Certificate", "Key"},
  375. },
  376. },
  377. },
  378. Data: map[string]interface{}{
  379. "Step": &templates.Step{
  380. SSH: templates.StepSSH{
  381. UserKey: user,
  382. HostKey: host,
  383. },
  384. },
  385. },
  386. }
  387. userOutputWithUserData := []templates.Output{
  388. {Name: "include.tpl", Type: templates.File, Comment: "#", Path: "ssh/include", Content: []byte("Host *\n\tInclude /home/user/.step/ssh/config")},
  389. {Name: "config.tpl", Type: templates.File, Comment: "#", Path: "ssh/config", Content: []byte("Match exec \"step ssh check-host %h\"\n\tUserKnownHostsFile /home/user/.step/ssh/known_hosts\n\tProxyCommand step ssh proxycommand %r %h %p\n")},
  390. }
  391. hostOutputWithUserData := []templates.Output{
  392. {Name: "sshd_config.tpl", Type: templates.File, Comment: "#", Path: "/etc/ssh/sshd_config", Content: []byte("TrustedUserCAKeys /etc/ssh/ca.pub\nHostCertificate /etc/ssh/ssh_host_ecdsa_key-cert.pub\nHostKey /etc/ssh/ssh_host_ecdsa_key")},
  393. }
  394. tmplConfigErr := &templates.Templates{
  395. SSH: &templates.SSHTemplates{
  396. User: []templates.Template{
  397. {Name: "error.tpl", Type: templates.File, TemplatePath: "./testdata/templates/error.tpl", Path: "ssh/error", Comment: "#"},
  398. },
  399. Host: []templates.Template{
  400. {Name: "error.tpl", Type: templates.File, TemplatePath: "./testdata/templates/error.tpl", Path: "ssh/error", Comment: "#"},
  401. },
  402. },
  403. }
  404. tmplConfigFail := &templates.Templates{
  405. SSH: &templates.SSHTemplates{
  406. User: []templates.Template{
  407. {Name: "fail.tpl", Type: templates.File, TemplatePath: "./testdata/templates/fail.tpl", Path: "ssh/fail", Comment: "#"},
  408. },
  409. },
  410. }
  411. type fields struct {
  412. templates *templates.Templates
  413. userSigner ssh.Signer
  414. hostSigner ssh.Signer
  415. }
  416. type args struct {
  417. typ string
  418. data map[string]string
  419. }
  420. tests := []struct {
  421. name string
  422. fields fields
  423. args args
  424. want []templates.Output
  425. wantErr bool
  426. }{
  427. {"user", fields{tmplConfig, userSigner, hostSigner}, args{"user", nil}, userOutput, false},
  428. {"user", fields{tmplConfig, userSigner, nil}, args{"user", nil}, userOutput, false},
  429. {"host", fields{tmplConfig, userSigner, hostSigner}, args{"host", nil}, hostOutput, false},
  430. {"host", fields{tmplConfig, nil, hostSigner}, args{"host", nil}, hostOutput, false},
  431. {"userWithData", fields{tmplConfigWithUserData, userSigner, hostSigner}, args{"user", map[string]string{"StepPath": "/home/user/.step"}}, userOutputWithUserData, false},
  432. {"hostWithData", fields{tmplConfigWithUserData, userSigner, hostSigner}, args{"host", map[string]string{"Certificate": "ssh_host_ecdsa_key-cert.pub", "Key": "ssh_host_ecdsa_key"}}, hostOutputWithUserData, false},
  433. {"disabled", fields{tmplConfig, nil, nil}, args{"host", nil}, nil, true},
  434. {"badType", fields{tmplConfig, userSigner, hostSigner}, args{"bad", nil}, nil, true},
  435. {"userError", fields{tmplConfigErr, userSigner, hostSigner}, args{"user", nil}, nil, true},
  436. {"hostError", fields{tmplConfigErr, userSigner, hostSigner}, args{"host", map[string]string{"Function": "foo"}}, nil, true},
  437. {"noTemplates", fields{nil, userSigner, hostSigner}, args{"user", nil}, nil, true},
  438. {"missingData", fields{tmplConfigWithUserData, userSigner, hostSigner}, args{"host", map[string]string{"Certificate": "ssh_host_ecdsa_key-cert.pub"}}, nil, true},
  439. {"failError", fields{tmplConfigFail, userSigner, hostSigner}, args{"user", nil}, nil, true},
  440. }
  441. for _, tt := range tests {
  442. t.Run(tt.name, func(t *testing.T) {
  443. a := testAuthority(t)
  444. a.templates = tt.fields.templates
  445. a.sshCAUserCertSignKey = tt.fields.userSigner
  446. a.sshCAHostCertSignKey = tt.fields.hostSigner
  447. got, err := a.GetSSHConfig(context.Background(), tt.args.typ, tt.args.data)
  448. if (err != nil) != tt.wantErr {
  449. t.Errorf("Authority.GetSSHConfig() error = %v, wantErr %v", err, tt.wantErr)
  450. return
  451. }
  452. if !reflect.DeepEqual(got, tt.want) {
  453. t.Errorf("Authority.GetSSHConfig() = %v, want %v", got, tt.want)
  454. }
  455. })
  456. }
  457. }
  458. func TestAuthority_CheckSSHHost(t *testing.T) {
  459. type fields struct {
  460. exists bool
  461. err error
  462. }
  463. type args struct {
  464. ctx context.Context
  465. principal string
  466. token string
  467. }
  468. tests := []struct {
  469. name string
  470. fields fields
  471. args args
  472. want bool
  473. wantErr bool
  474. }{
  475. {"true", fields{true, nil}, args{context.Background(), "foo.internal.com", ""}, true, false},
  476. {"false", fields{false, nil}, args{context.Background(), "foo.internal.com", ""}, false, false},
  477. {"notImplemented", fields{false, db.ErrNotImplemented}, args{context.Background(), "foo.internal.com", ""}, false, true},
  478. {"notImplemented", fields{true, db.ErrNotImplemented}, args{context.Background(), "foo.internal.com", ""}, false, true},
  479. {"internal", fields{false, fmt.Errorf("an error")}, args{context.Background(), "foo.internal.com", ""}, false, true},
  480. {"internal", fields{true, fmt.Errorf("an error")}, args{context.Background(), "foo.internal.com", ""}, false, true},
  481. }
  482. for _, tt := range tests {
  483. t.Run(tt.name, func(t *testing.T) {
  484. a := testAuthority(t)
  485. a.db = &db.MockAuthDB{
  486. MIsSSHHost: func(_ string) (bool, error) {
  487. return tt.fields.exists, tt.fields.err
  488. },
  489. }
  490. got, err := a.CheckSSHHost(tt.args.ctx, tt.args.principal, tt.args.token)
  491. if (err != nil) != tt.wantErr {
  492. t.Errorf("Authority.CheckSSHHost() error = %v, wantErr %v", err, tt.wantErr)
  493. return
  494. }
  495. if got != tt.want {
  496. t.Errorf("Authority.CheckSSHHost() = %v, want %v", got, tt.want)
  497. }
  498. })
  499. }
  500. }
  501. func TestSSHConfig_Validate(t *testing.T) {
  502. key, err := jose.GenerateJWK("EC", "P-256", "", "sig", "", 0)
  503. assert.FatalError(t, err)
  504. tests := []struct {
  505. name string
  506. sshConfig *SSHConfig
  507. wantErr bool
  508. }{
  509. {"nil", nil, false},
  510. {"ok", &SSHConfig{Keys: []*SSHPublicKey{{Type: "user", Key: key.Public()}}}, false},
  511. {"ok", &SSHConfig{Keys: []*SSHPublicKey{{Type: "host", Key: key.Public()}}}, false},
  512. {"badType", &SSHConfig{Keys: []*SSHPublicKey{{Type: "bad", Key: key.Public()}}}, true},
  513. {"badKey", &SSHConfig{Keys: []*SSHPublicKey{{Type: "user", Key: *key}}}, true},
  514. }
  515. for _, tt := range tests {
  516. t.Run(tt.name, func(t *testing.T) {
  517. if err := tt.sshConfig.Validate(); (err != nil) != tt.wantErr {
  518. t.Errorf("SSHConfig.Validate() error = %v, wantErr %v", err, tt.wantErr)
  519. }
  520. })
  521. }
  522. }
  523. func TestSSHPublicKey_Validate(t *testing.T) {
  524. key, err := jose.GenerateJWK("EC", "P-256", "", "sig", "", 0)
  525. assert.FatalError(t, err)
  526. type fields struct {
  527. Type string
  528. Federated bool
  529. Key jose.JSONWebKey
  530. }
  531. tests := []struct {
  532. name string
  533. fields fields
  534. wantErr bool
  535. }{
  536. {"user", fields{"user", true, key.Public()}, false},
  537. {"host", fields{"host", false, key.Public()}, false},
  538. {"empty", fields{"", true, key.Public()}, true},
  539. {"badType", fields{"bad", false, key.Public()}, true},
  540. {"badKey", fields{"user", false, *key}, true},
  541. }
  542. for _, tt := range tests {
  543. t.Run(tt.name, func(t *testing.T) {
  544. k := &SSHPublicKey{
  545. Type: tt.fields.Type,
  546. Federated: tt.fields.Federated,
  547. Key: tt.fields.Key,
  548. }
  549. if err := k.Validate(); (err != nil) != tt.wantErr {
  550. t.Errorf("SSHPublicKey.Validate() error = %v, wantErr %v", err, tt.wantErr)
  551. }
  552. })
  553. }
  554. }
  555. func TestSSHPublicKey_PublicKey(t *testing.T) {
  556. key, err := jose.GenerateJWK("EC", "P-256", "", "sig", "", 0)
  557. assert.FatalError(t, err)
  558. pub, err := ssh.NewPublicKey(key.Public().Key)
  559. assert.FatalError(t, err)
  560. type fields struct {
  561. publicKey ssh.PublicKey
  562. }
  563. tests := []struct {
  564. name string
  565. fields fields
  566. want ssh.PublicKey
  567. }{
  568. {"ok", fields{pub}, pub},
  569. {"nil", fields{nil}, nil},
  570. }
  571. for _, tt := range tests {
  572. t.Run(tt.name, func(t *testing.T) {
  573. k := &SSHPublicKey{
  574. publicKey: tt.fields.publicKey,
  575. }
  576. if got := k.PublicKey(); !reflect.DeepEqual(got, tt.want) {
  577. t.Errorf("SSHPublicKey.PublicKey() = %v, want %v", got, tt.want)
  578. }
  579. })
  580. }
  581. }
  582. func TestAuthority_GetSSHBastion(t *testing.T) {
  583. bastion := &Bastion{
  584. Hostname: "bastion.local",
  585. Port: "2222",
  586. }
  587. type fields struct {
  588. config *Config
  589. sshBastionFunc func(ctx context.Context, user, hostname string) (*Bastion, error)
  590. }
  591. type args struct {
  592. user string
  593. hostname string
  594. }
  595. tests := []struct {
  596. name string
  597. fields fields
  598. args args
  599. want *Bastion
  600. wantErr bool
  601. }{
  602. {"config", fields{&Config{SSH: &SSHConfig{Bastion: bastion}}, nil}, args{"user", "host.local"}, bastion, false},
  603. {"bastion", fields{&Config{SSH: &SSHConfig{Bastion: bastion}}, nil}, args{"user", "bastion.local"}, nil, false},
  604. {"nil", fields{&Config{SSH: &SSHConfig{Bastion: nil}}, nil}, args{"user", "host.local"}, nil, false},
  605. {"empty", fields{&Config{SSH: &SSHConfig{Bastion: &Bastion{}}}, nil}, args{"user", "host.local"}, nil, false},
  606. {"func", fields{&Config{}, func(_ context.Context, _, _ string) (*Bastion, error) { return bastion, nil }}, args{"user", "host.local"}, bastion, false},
  607. {"func err", fields{&Config{}, func(_ context.Context, _, _ string) (*Bastion, error) { return nil, errors.New("foo") }}, args{"user", "host.local"}, nil, true},
  608. {"error", fields{&Config{SSH: nil}, nil}, args{"user", "host.local"}, nil, true},
  609. }
  610. for _, tt := range tests {
  611. t.Run(tt.name, func(t *testing.T) {
  612. a := &Authority{
  613. config: tt.fields.config,
  614. sshBastionFunc: tt.fields.sshBastionFunc,
  615. }
  616. got, err := a.GetSSHBastion(context.Background(), tt.args.user, tt.args.hostname)
  617. if (err != nil) != tt.wantErr {
  618. t.Errorf("Authority.GetSSHBastion() error = %v, wantErr %v", err, tt.wantErr)
  619. return
  620. } else if err != nil {
  621. _, ok := err.(errs.StatusCoder)
  622. assert.Fatal(t, ok, "error does not implement StatusCoder interface")
  623. }
  624. if !reflect.DeepEqual(got, tt.want) {
  625. t.Errorf("Authority.GetSSHBastion() = %v, want %v", got, tt.want)
  626. }
  627. })
  628. }
  629. }
  630. func TestAuthority_GetSSHHosts(t *testing.T) {
  631. a := testAuthority(t)
  632. type test struct {
  633. getHostsFunc func(context.Context, *x509.Certificate) ([]sshutil.Host, error)
  634. auth *Authority
  635. cert *x509.Certificate
  636. cmp func(got []sshutil.Host)
  637. err error
  638. code int
  639. }
  640. tests := map[string]func(t *testing.T) *test{
  641. "fail/getHostsFunc-fail": func(t *testing.T) *test {
  642. return &test{
  643. getHostsFunc: func(ctx context.Context, cert *x509.Certificate) ([]sshutil.Host, error) {
  644. return nil, errors.New("force")
  645. },
  646. cert: &x509.Certificate{},
  647. err: errors.New("getSSHHosts: force"),
  648. code: http.StatusInternalServerError,
  649. }
  650. },
  651. "ok/getHostsFunc-defined": func(t *testing.T) *test {
  652. hosts := []sshutil.Host{
  653. {HostID: "1", Hostname: "foo"},
  654. {HostID: "2", Hostname: "bar"},
  655. }
  656. return &test{
  657. getHostsFunc: func(ctx context.Context, cert *x509.Certificate) ([]sshutil.Host, error) {
  658. return hosts, nil
  659. },
  660. cert: &x509.Certificate{},
  661. cmp: func(got []sshutil.Host) {
  662. assert.Equals(t, got, hosts)
  663. },
  664. }
  665. },
  666. "fail/db-get-fail": func(t *testing.T) *test {
  667. return &test{
  668. auth: testAuthority(t, WithDatabase(&db.MockAuthDB{
  669. MGetSSHHostPrincipals: func() ([]string, error) {
  670. return nil, errors.New("force")
  671. },
  672. })),
  673. cert: &x509.Certificate{},
  674. err: errors.New("getSSHHosts: force"),
  675. code: http.StatusInternalServerError,
  676. }
  677. },
  678. "ok": func(t *testing.T) *test {
  679. return &test{
  680. auth: testAuthority(t, WithDatabase(&db.MockAuthDB{
  681. MGetSSHHostPrincipals: func() ([]string, error) {
  682. return []string{"foo", "bar"}, nil
  683. },
  684. })),
  685. cert: &x509.Certificate{},
  686. cmp: func(got []sshutil.Host) {
  687. assert.Equals(t, got, []sshutil.Host{
  688. {Hostname: "foo"},
  689. {Hostname: "bar"},
  690. })
  691. },
  692. }
  693. },
  694. }
  695. for name, genTestCase := range tests {
  696. t.Run(name, func(t *testing.T) {
  697. tc := genTestCase(t)
  698. auth := tc.auth
  699. if auth == nil {
  700. auth = a
  701. }
  702. auth.sshGetHostsFunc = tc.getHostsFunc
  703. hosts, err := auth.GetSSHHosts(context.Background(), tc.cert)
  704. if err != nil {
  705. if assert.NotNil(t, tc.err) {
  706. sc, ok := err.(errs.StatusCoder)
  707. assert.Fatal(t, ok, "error does not implement StatusCoder interface")
  708. assert.Equals(t, sc.StatusCode(), tc.code)
  709. assert.HasPrefix(t, err.Error(), tc.err.Error())
  710. }
  711. } else {
  712. if assert.Nil(t, tc.err) {
  713. tc.cmp(hosts)
  714. }
  715. }
  716. })
  717. }
  718. }
  719. func TestAuthority_RekeySSH(t *testing.T) {
  720. key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  721. assert.FatalError(t, err)
  722. pub, err := ssh.NewPublicKey(key.Public())
  723. assert.FatalError(t, err)
  724. signKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  725. assert.FatalError(t, err)
  726. signer, err := ssh.NewSignerFromKey(signKey)
  727. assert.FatalError(t, err)
  728. userOptions := sshTestModifier{
  729. CertType: ssh.UserCert,
  730. }
  731. now := time.Now().UTC()
  732. a := testAuthority(t)
  733. type test struct {
  734. auth *Authority
  735. userSigner ssh.Signer
  736. hostSigner ssh.Signer
  737. cert *ssh.Certificate
  738. key ssh.PublicKey
  739. signOpts []provisioner.SignOption
  740. cmpResult func(old, n *ssh.Certificate)
  741. err error
  742. code int
  743. }
  744. tests := map[string]func(t *testing.T) *test{
  745. "fail/opts-type": func(t *testing.T) *test {
  746. return &test{
  747. userSigner: signer,
  748. hostSigner: signer,
  749. key: pub,
  750. signOpts: []provisioner.SignOption{userOptions},
  751. err: errors.New("rekeySSH; invalid extra option type"),
  752. code: http.StatusInternalServerError,
  753. }
  754. },
  755. "fail/old-cert-validAfter": func(t *testing.T) *test {
  756. return &test{
  757. userSigner: signer,
  758. hostSigner: signer,
  759. cert: &ssh.Certificate{},
  760. key: pub,
  761. signOpts: []provisioner.SignOption{},
  762. err: errors.New("rekeySSH; cannot rekey certificate without validity period"),
  763. code: http.StatusBadRequest,
  764. }
  765. },
  766. "fail/old-cert-validBefore": func(t *testing.T) *test {
  767. return &test{
  768. userSigner: signer,
  769. hostSigner: signer,
  770. cert: &ssh.Certificate{ValidAfter: uint64(now.Unix())},
  771. key: pub,
  772. signOpts: []provisioner.SignOption{},
  773. err: errors.New("rekeySSH; cannot rekey certificate without validity period"),
  774. code: http.StatusBadRequest,
  775. }
  776. },
  777. "fail/old-cert-no-user-key": func(t *testing.T) *test {
  778. return &test{
  779. userSigner: nil,
  780. hostSigner: signer,
  781. cert: &ssh.Certificate{ValidAfter: uint64(now.Unix()), ValidBefore: uint64(now.Add(10 * time.Minute).Unix()), CertType: ssh.UserCert},
  782. key: pub,
  783. signOpts: []provisioner.SignOption{},
  784. err: errors.New("rekeySSH; user certificate signing is not enabled"),
  785. code: http.StatusNotImplemented,
  786. }
  787. },
  788. "fail/old-cert-no-host-key": func(t *testing.T) *test {
  789. return &test{
  790. userSigner: signer,
  791. hostSigner: nil,
  792. cert: &ssh.Certificate{ValidAfter: uint64(now.Unix()), ValidBefore: uint64(now.Add(10 * time.Minute).Unix()), CertType: ssh.HostCert},
  793. key: pub,
  794. signOpts: []provisioner.SignOption{},
  795. err: errors.New("rekeySSH; host certificate signing is not enabled"),
  796. code: http.StatusNotImplemented,
  797. }
  798. },
  799. "fail/unexpected-old-cert-type": func(t *testing.T) *test {
  800. return &test{
  801. userSigner: signer,
  802. hostSigner: signer,
  803. cert: &ssh.Certificate{ValidAfter: uint64(now.Unix()), ValidBefore: uint64(now.Add(10 * time.Minute).Unix()), CertType: 0},
  804. key: pub,
  805. signOpts: []provisioner.SignOption{},
  806. err: errors.New("rekeySSH; unexpected ssh certificate type: 0"),
  807. code: http.StatusBadRequest,
  808. }
  809. },
  810. "fail/db-store": func(t *testing.T) *test {
  811. return &test{
  812. auth: testAuthority(t, WithDatabase(&db.MockAuthDB{
  813. MStoreSSHCertificate: func(cert *ssh.Certificate) error {
  814. return errors.New("force")
  815. },
  816. })),
  817. userSigner: signer,
  818. hostSigner: nil,
  819. cert: &ssh.Certificate{ValidAfter: uint64(now.Unix()), ValidBefore: uint64(now.Add(10 * time.Minute).Unix()), CertType: ssh.UserCert},
  820. key: pub,
  821. signOpts: []provisioner.SignOption{},
  822. err: errors.New("rekeySSH; error storing certificate in db: force"),
  823. code: http.StatusInternalServerError,
  824. }
  825. },
  826. "ok": func(t *testing.T) *test {
  827. va1 := now.Add(-24 * time.Hour)
  828. vb1 := now.Add(-23 * time.Hour)
  829. return &test{
  830. userSigner: signer,
  831. hostSigner: nil,
  832. cert: &ssh.Certificate{
  833. ValidAfter: uint64(va1.Unix()),
  834. ValidBefore: uint64(vb1.Unix()),
  835. CertType: ssh.UserCert,
  836. ValidPrincipals: []string{"foo", "bar"},
  837. KeyId: "foo",
  838. },
  839. key: pub,
  840. signOpts: []provisioner.SignOption{},
  841. cmpResult: func(old, n *ssh.Certificate) {
  842. assert.Equals(t, n.CertType, old.CertType)
  843. assert.Equals(t, n.ValidPrincipals, old.ValidPrincipals)
  844. assert.Equals(t, n.KeyId, old.KeyId)
  845. assert.True(t, n.ValidAfter > uint64(now.Add(-5*time.Minute).Unix()))
  846. assert.True(t, n.ValidAfter < uint64(now.Add(5*time.Minute).Unix()))
  847. l8r := now.Add(1 * time.Hour)
  848. assert.True(t, n.ValidBefore > uint64(l8r.Add(-5*time.Minute).Unix()))
  849. assert.True(t, n.ValidBefore < uint64(l8r.Add(5*time.Minute).Unix()))
  850. },
  851. }
  852. },
  853. }
  854. for name, genTestCase := range tests {
  855. t.Run(name, func(t *testing.T) {
  856. tc := genTestCase(t)
  857. auth := tc.auth
  858. if auth == nil {
  859. auth = a
  860. }
  861. a.sshCAUserCertSignKey = tc.userSigner
  862. a.sshCAHostCertSignKey = tc.hostSigner
  863. cert, err := auth.RekeySSH(context.Background(), tc.cert, tc.key, tc.signOpts...)
  864. if err != nil {
  865. if assert.NotNil(t, tc.err) {
  866. sc, ok := err.(errs.StatusCoder)
  867. assert.Fatal(t, ok, "error does not implement StatusCoder interface")
  868. assert.Equals(t, sc.StatusCode(), tc.code)
  869. assert.HasPrefix(t, err.Error(), tc.err.Error())
  870. }
  871. } else {
  872. if assert.Nil(t, tc.err) {
  873. tc.cmpResult(tc.cert, cert)
  874. }
  875. }
  876. })
  877. }
  878. }
  879. func TestIsValidForAddUser(t *testing.T) {
  880. type args struct {
  881. cert *ssh.Certificate
  882. }
  883. tests := []struct {
  884. name string
  885. args args
  886. wantErr bool
  887. }{
  888. {"ok", args{&ssh.Certificate{CertType: ssh.UserCert, ValidPrincipals: []string{"john"}}}, false},
  889. {"ok oidc", args{&ssh.Certificate{CertType: ssh.UserCert, ValidPrincipals: []string{"jane", "jane@smallstep.com"}}}, false},
  890. {"fail at", args{&ssh.Certificate{CertType: ssh.UserCert, ValidPrincipals: []string{"jane", "@smallstep.com"}}}, true},
  891. {"fail host", args{&ssh.Certificate{CertType: ssh.HostCert, ValidPrincipals: []string{"john"}}}, true},
  892. {"fail principals", args{&ssh.Certificate{CertType: ssh.UserCert, ValidPrincipals: []string{"john", "jane"}}}, true},
  893. {"fail no principals", args{&ssh.Certificate{CertType: ssh.UserCert, ValidPrincipals: []string{}}}, true},
  894. {"fail extra principals", args{&ssh.Certificate{CertType: ssh.UserCert, ValidPrincipals: []string{"john", "jane", "doe"}}}, true},
  895. }
  896. for _, tt := range tests {
  897. t.Run(tt.name, func(t *testing.T) {
  898. if err := IsValidForAddUser(tt.args.cert); (err != nil) != tt.wantErr {
  899. t.Errorf("IsValidForAddUser() error = %v, wantErr %v", err, tt.wantErr)
  900. }
  901. })
  902. }
  903. }