4
0

ssh_test.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. package api
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/ecdsa"
  6. "crypto/elliptic"
  7. "crypto/rand"
  8. "crypto/x509"
  9. "encoding/base64"
  10. "encoding/json"
  11. "fmt"
  12. "io"
  13. "net/http"
  14. "net/http/httptest"
  15. "reflect"
  16. "strings"
  17. "testing"
  18. "time"
  19. "golang.org/x/crypto/ssh"
  20. "github.com/smallstep/assert"
  21. "github.com/smallstep/certificates/authority"
  22. "github.com/smallstep/certificates/authority/provisioner"
  23. "github.com/smallstep/certificates/logging"
  24. "github.com/smallstep/certificates/templates"
  25. )
  26. var (
  27. sshSignerKey = mustKey()
  28. sshUserKey = mustKey()
  29. sshHostKey = mustKey()
  30. )
  31. func mustKey() *ecdsa.PrivateKey {
  32. priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  33. if err != nil {
  34. panic(err)
  35. }
  36. return priv
  37. }
  38. func signSSHCertificate(cert *ssh.Certificate) error {
  39. signerKey, err := ssh.NewPublicKey(sshSignerKey.Public())
  40. if err != nil {
  41. return err
  42. }
  43. signer, err := ssh.NewSignerFromSigner(sshSignerKey)
  44. if err != nil {
  45. return err
  46. }
  47. cert.SignatureKey = signerKey
  48. data := cert.Marshal()
  49. data = data[:len(data)-4]
  50. sig, err := signer.Sign(rand.Reader, data)
  51. if err != nil {
  52. return err
  53. }
  54. cert.Signature = sig
  55. return nil
  56. }
  57. func getSignedUserCertificate() (*ssh.Certificate, error) {
  58. key, err := ssh.NewPublicKey(sshUserKey.Public())
  59. if err != nil {
  60. return nil, err
  61. }
  62. t := time.Now()
  63. cert := &ssh.Certificate{
  64. Nonce: []byte("1234567890"),
  65. Key: key,
  66. Serial: 1234567890,
  67. CertType: ssh.UserCert,
  68. KeyId: "user@localhost",
  69. ValidPrincipals: []string{"user"},
  70. ValidAfter: uint64(t.Unix()),
  71. ValidBefore: uint64(t.Add(time.Hour).Unix()),
  72. Permissions: ssh.Permissions{
  73. CriticalOptions: map[string]string{},
  74. Extensions: map[string]string{
  75. "permit-X11-forwarding": "",
  76. "permit-agent-forwarding": "",
  77. "permit-port-forwarding": "",
  78. "permit-pty": "",
  79. "permit-user-rc": "",
  80. },
  81. },
  82. Reserved: []byte{},
  83. }
  84. if err := signSSHCertificate(cert); err != nil {
  85. return nil, err
  86. }
  87. return cert, nil
  88. }
  89. func getSignedHostCertificate() (*ssh.Certificate, error) {
  90. key, err := ssh.NewPublicKey(sshHostKey.Public())
  91. if err != nil {
  92. return nil, err
  93. }
  94. t := time.Now()
  95. cert := &ssh.Certificate{
  96. Nonce: []byte("1234567890"),
  97. Key: key,
  98. Serial: 1234567890,
  99. CertType: ssh.UserCert,
  100. KeyId: "internal.smallstep.com",
  101. ValidPrincipals: []string{"internal.smallstep.com"},
  102. ValidAfter: uint64(t.Unix()),
  103. ValidBefore: uint64(t.Add(time.Hour).Unix()),
  104. Permissions: ssh.Permissions{
  105. CriticalOptions: map[string]string{},
  106. Extensions: map[string]string{},
  107. },
  108. Reserved: []byte{},
  109. }
  110. if err := signSSHCertificate(cert); err != nil {
  111. return nil, err
  112. }
  113. return cert, nil
  114. }
  115. func TestSSHCertificate_MarshalJSON(t *testing.T) {
  116. user, err := getSignedUserCertificate()
  117. assert.FatalError(t, err)
  118. host, err := getSignedHostCertificate()
  119. assert.FatalError(t, err)
  120. userB64 := base64.StdEncoding.EncodeToString(user.Marshal())
  121. hostB64 := base64.StdEncoding.EncodeToString(host.Marshal())
  122. type fields struct {
  123. Certificate *ssh.Certificate
  124. }
  125. tests := []struct {
  126. name string
  127. fields fields
  128. want []byte
  129. wantErr bool
  130. }{
  131. {"nil", fields{Certificate: nil}, []byte("null"), false},
  132. {"user", fields{Certificate: user}, []byte(`"` + userB64 + `"`), false},
  133. {"user", fields{Certificate: host}, []byte(`"` + hostB64 + `"`), false},
  134. }
  135. for _, tt := range tests {
  136. t.Run(tt.name, func(t *testing.T) {
  137. c := SSHCertificate{
  138. Certificate: tt.fields.Certificate,
  139. }
  140. got, err := c.MarshalJSON()
  141. if (err != nil) != tt.wantErr {
  142. t.Errorf("SSHCertificate.MarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
  143. return
  144. }
  145. if !reflect.DeepEqual(got, tt.want) {
  146. t.Errorf("SSHCertificate.MarshalJSON() = %v, want %v", got, tt.want)
  147. }
  148. })
  149. }
  150. }
  151. func TestSSHCertificate_UnmarshalJSON(t *testing.T) {
  152. user, err := getSignedUserCertificate()
  153. assert.FatalError(t, err)
  154. host, err := getSignedHostCertificate()
  155. assert.FatalError(t, err)
  156. userB64 := base64.StdEncoding.EncodeToString(user.Marshal())
  157. hostB64 := base64.StdEncoding.EncodeToString(host.Marshal())
  158. keyB64 := base64.StdEncoding.EncodeToString(user.Key.Marshal())
  159. type args struct {
  160. data []byte
  161. }
  162. tests := []struct {
  163. name string
  164. args args
  165. want *ssh.Certificate
  166. wantErr bool
  167. }{
  168. {"null", args{[]byte(`null`)}, nil, false},
  169. {"empty", args{[]byte(`""`)}, nil, false},
  170. {"user", args{[]byte(`"` + userB64 + `"`)}, user, false},
  171. {"host", args{[]byte(`"` + hostB64 + `"`)}, host, false},
  172. {"bad-string", args{[]byte(userB64)}, nil, true},
  173. {"bad-base64", args{[]byte(`"this-is-not-base64"`)}, nil, true},
  174. {"bad-key", args{[]byte(`"bm90LWEta2V5"`)}, nil, true},
  175. {"bat-cert", args{[]byte(`"` + keyB64 + `"`)}, nil, true},
  176. }
  177. for _, tt := range tests {
  178. t.Run(tt.name, func(t *testing.T) {
  179. c := &SSHCertificate{}
  180. if err := c.UnmarshalJSON(tt.args.data); (err != nil) != tt.wantErr {
  181. t.Errorf("SSHCertificate.UnmarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
  182. }
  183. if !reflect.DeepEqual(tt.want, c.Certificate) {
  184. t.Errorf("SSHCertificate.UnmarshalJSON() got = %v, want %v\n", c.Certificate, tt.want)
  185. }
  186. })
  187. }
  188. }
  189. func TestSignSSHRequest_Validate(t *testing.T) {
  190. csr := parseCertificateRequest(csrPEM)
  191. badCSR := parseCertificateRequest(csrPEM)
  192. badCSR.SignatureAlgorithm = x509.SHA1WithRSA
  193. type fields struct {
  194. PublicKey []byte
  195. OTT string
  196. CertType string
  197. Principals []string
  198. ValidAfter TimeDuration
  199. ValidBefore TimeDuration
  200. AddUserPublicKey []byte
  201. KeyID string
  202. IdentityCSR CertificateRequest
  203. }
  204. tests := []struct {
  205. name string
  206. fields fields
  207. wantErr bool
  208. }{
  209. {"ok-empty", fields{[]byte("Zm9v"), "ott", "", []string{"user"}, TimeDuration{}, TimeDuration{}, nil, "", CertificateRequest{}}, false},
  210. {"ok-user", fields{[]byte("Zm9v"), "ott", "user", []string{"user"}, TimeDuration{}, TimeDuration{}, nil, "", CertificateRequest{}}, false},
  211. {"ok-host", fields{[]byte("Zm9v"), "ott", "host", []string{"user"}, TimeDuration{}, TimeDuration{}, nil, "", CertificateRequest{}}, false},
  212. {"ok-keyID", fields{[]byte("Zm9v"), "ott", "user", []string{"user"}, TimeDuration{}, TimeDuration{}, nil, "key-id", CertificateRequest{}}, false},
  213. {"ok-identityCSR", fields{[]byte("Zm9v"), "ott", "user", []string{"user"}, TimeDuration{}, TimeDuration{}, nil, "key-id", CertificateRequest{CertificateRequest: csr}}, false},
  214. {"key", fields{nil, "ott", "user", []string{"user"}, TimeDuration{}, TimeDuration{}, nil, "", CertificateRequest{}}, true},
  215. {"key", fields{[]byte(""), "ott", "user", []string{"user"}, TimeDuration{}, TimeDuration{}, nil, "", CertificateRequest{}}, true},
  216. {"type", fields{[]byte("Zm9v"), "ott", "foo", []string{"user"}, TimeDuration{}, TimeDuration{}, nil, "", CertificateRequest{}}, true},
  217. {"ott", fields{[]byte("Zm9v"), "", "user", []string{"user"}, TimeDuration{}, TimeDuration{}, nil, "", CertificateRequest{}}, true},
  218. {"identityCSR", fields{[]byte("Zm9v"), "ott", "user", []string{"user"}, TimeDuration{}, TimeDuration{}, nil, "key-id", CertificateRequest{CertificateRequest: badCSR}}, true},
  219. }
  220. for _, tt := range tests {
  221. t.Run(tt.name, func(t *testing.T) {
  222. s := &SSHSignRequest{
  223. PublicKey: tt.fields.PublicKey,
  224. OTT: tt.fields.OTT,
  225. CertType: tt.fields.CertType,
  226. Principals: tt.fields.Principals,
  227. ValidAfter: tt.fields.ValidAfter,
  228. ValidBefore: tt.fields.ValidBefore,
  229. AddUserPublicKey: tt.fields.AddUserPublicKey,
  230. KeyID: tt.fields.KeyID,
  231. IdentityCSR: tt.fields.IdentityCSR,
  232. }
  233. if err := s.Validate(); (err != nil) != tt.wantErr {
  234. t.Errorf("SignSSHRequest.Validate() error = %v, wantErr %v", err, tt.wantErr)
  235. }
  236. })
  237. }
  238. }
  239. func Test_caHandler_SSHSign(t *testing.T) {
  240. user, err := getSignedUserCertificate()
  241. assert.FatalError(t, err)
  242. host, err := getSignedHostCertificate()
  243. assert.FatalError(t, err)
  244. userB64 := base64.StdEncoding.EncodeToString(user.Marshal())
  245. hostB64 := base64.StdEncoding.EncodeToString(host.Marshal())
  246. userReq, err := json.Marshal(SSHSignRequest{
  247. PublicKey: user.Key.Marshal(),
  248. OTT: "ott",
  249. })
  250. assert.FatalError(t, err)
  251. hostReq, err := json.Marshal(SSHSignRequest{
  252. PublicKey: host.Key.Marshal(),
  253. OTT: "ott",
  254. })
  255. assert.FatalError(t, err)
  256. userAddReq, err := json.Marshal(SSHSignRequest{
  257. PublicKey: user.Key.Marshal(),
  258. OTT: "ott",
  259. AddUserPublicKey: user.Key.Marshal(),
  260. })
  261. assert.FatalError(t, err)
  262. userIdentityReq, err := json.Marshal(SSHSignRequest{
  263. PublicKey: user.Key.Marshal(),
  264. OTT: "ott",
  265. IdentityCSR: CertificateRequest{parseCertificateRequest(csrPEM)},
  266. })
  267. assert.FatalError(t, err)
  268. identityCerts := []*x509.Certificate{
  269. parseCertificate(certPEM),
  270. }
  271. identityCertsPEM := []byte(`"` + strings.ReplaceAll(certPEM, "\n", `\n`) + `\n"`)
  272. tests := []struct {
  273. name string
  274. req []byte
  275. authErr error
  276. signCert *ssh.Certificate
  277. signErr error
  278. addUserCert *ssh.Certificate
  279. addUserErr error
  280. tlsSignCerts []*x509.Certificate
  281. tlsSignErr error
  282. body []byte
  283. statusCode int
  284. }{
  285. {"ok-user", userReq, nil, user, nil, nil, nil, nil, nil, []byte(fmt.Sprintf(`{"crt":%q}`, userB64)), http.StatusCreated},
  286. {"ok-host", hostReq, nil, host, nil, nil, nil, nil, nil, []byte(fmt.Sprintf(`{"crt":%q}`, hostB64)), http.StatusCreated},
  287. {"ok-user-add", userAddReq, nil, user, nil, user, nil, nil, nil, []byte(fmt.Sprintf(`{"crt":%q,"addUserCrt":%q}`, userB64, userB64)), http.StatusCreated},
  288. {"ok-user-identity", userIdentityReq, nil, user, nil, user, nil, identityCerts, nil, []byte(fmt.Sprintf(`{"crt":%q,"identityCrt":[%s]}`, userB64, identityCertsPEM)), http.StatusCreated},
  289. {"fail-body", []byte("bad-json"), nil, nil, nil, nil, nil, nil, nil, nil, http.StatusBadRequest},
  290. {"fail-validate", []byte("{}"), nil, nil, nil, nil, nil, nil, nil, nil, http.StatusBadRequest},
  291. {"fail-publicKey", []byte(`{"publicKey":"Zm9v","ott":"ott"}`), nil, nil, nil, nil, nil, nil, nil, nil, http.StatusBadRequest},
  292. {"fail-publicKey", []byte(fmt.Sprintf(`{"publicKey":%q,"ott":"ott","addUserPublicKey":"Zm9v"}`, base64.StdEncoding.EncodeToString(user.Key.Marshal()))), nil, nil, nil, nil, nil, nil, nil, nil, http.StatusBadRequest},
  293. {"fail-authorize", userReq, fmt.Errorf("an-error"), nil, nil, nil, nil, nil, nil, nil, http.StatusUnauthorized},
  294. {"fail-signSSH", userReq, nil, nil, fmt.Errorf("an-error"), nil, nil, nil, nil, nil, http.StatusForbidden},
  295. {"fail-SignSSHAddUser", userAddReq, nil, user, nil, nil, fmt.Errorf("an-error"), nil, nil, nil, http.StatusForbidden},
  296. {"fail-user-identity", userIdentityReq, nil, user, nil, user, nil, nil, fmt.Errorf("an-error"), nil, http.StatusForbidden},
  297. }
  298. for _, tt := range tests {
  299. t.Run(tt.name, func(t *testing.T) {
  300. h := New(&mockAuthority{
  301. authorizeSign: func(ott string) ([]provisioner.SignOption, error) {
  302. return []provisioner.SignOption{}, tt.authErr
  303. },
  304. signSSH: func(ctx context.Context, key ssh.PublicKey, opts provisioner.SignSSHOptions, signOpts ...provisioner.SignOption) (*ssh.Certificate, error) {
  305. return tt.signCert, tt.signErr
  306. },
  307. signSSHAddUser: func(ctx context.Context, key ssh.PublicKey, cert *ssh.Certificate) (*ssh.Certificate, error) {
  308. return tt.addUserCert, tt.addUserErr
  309. },
  310. sign: func(cr *x509.CertificateRequest, opts provisioner.SignOptions, signOpts ...provisioner.SignOption) ([]*x509.Certificate, error) {
  311. return tt.tlsSignCerts, tt.tlsSignErr
  312. },
  313. }).(*caHandler)
  314. req := httptest.NewRequest("POST", "http://example.com/ssh/sign", bytes.NewReader(tt.req))
  315. w := httptest.NewRecorder()
  316. h.SSHSign(logging.NewResponseLogger(w), req)
  317. res := w.Result()
  318. if res.StatusCode != tt.statusCode {
  319. t.Errorf("caHandler.SignSSH StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  320. }
  321. body, err := io.ReadAll(res.Body)
  322. res.Body.Close()
  323. if err != nil {
  324. t.Errorf("caHandler.SignSSH unexpected error = %v", err)
  325. }
  326. if tt.statusCode < http.StatusBadRequest {
  327. if !bytes.Equal(bytes.TrimSpace(body), tt.body) {
  328. t.Errorf("caHandler.SignSSH Body = %s, wants %s", body, tt.body)
  329. }
  330. }
  331. })
  332. }
  333. }
  334. func Test_caHandler_SSHRoots(t *testing.T) {
  335. user, err := ssh.NewPublicKey(sshUserKey.Public())
  336. assert.FatalError(t, err)
  337. userB64 := base64.StdEncoding.EncodeToString(user.Marshal())
  338. host, err := ssh.NewPublicKey(sshHostKey.Public())
  339. assert.FatalError(t, err)
  340. hostB64 := base64.StdEncoding.EncodeToString(host.Marshal())
  341. tests := []struct {
  342. name string
  343. keys *authority.SSHKeys
  344. keysErr error
  345. body []byte
  346. statusCode int
  347. }{
  348. {"ok", &authority.SSHKeys{HostKeys: []ssh.PublicKey{host}, UserKeys: []ssh.PublicKey{user}}, nil, []byte(fmt.Sprintf(`{"userKey":[%q],"hostKey":[%q]}`, userB64, hostB64)), http.StatusOK},
  349. {"many", &authority.SSHKeys{HostKeys: []ssh.PublicKey{host, host}, UserKeys: []ssh.PublicKey{user, user}}, nil, []byte(fmt.Sprintf(`{"userKey":[%q,%q],"hostKey":[%q,%q]}`, userB64, userB64, hostB64, hostB64)), http.StatusOK},
  350. {"user", &authority.SSHKeys{UserKeys: []ssh.PublicKey{user}}, nil, []byte(fmt.Sprintf(`{"userKey":[%q]}`, userB64)), http.StatusOK},
  351. {"host", &authority.SSHKeys{HostKeys: []ssh.PublicKey{host}}, nil, []byte(fmt.Sprintf(`{"hostKey":[%q]}`, hostB64)), http.StatusOK},
  352. {"empty", &authority.SSHKeys{}, nil, nil, http.StatusNotFound},
  353. {"error", nil, fmt.Errorf("an error"), nil, http.StatusInternalServerError},
  354. }
  355. for _, tt := range tests {
  356. t.Run(tt.name, func(t *testing.T) {
  357. h := New(&mockAuthority{
  358. getSSHRoots: func(ctx context.Context) (*authority.SSHKeys, error) {
  359. return tt.keys, tt.keysErr
  360. },
  361. }).(*caHandler)
  362. req := httptest.NewRequest("GET", "http://example.com/ssh/roots", http.NoBody)
  363. w := httptest.NewRecorder()
  364. h.SSHRoots(logging.NewResponseLogger(w), req)
  365. res := w.Result()
  366. if res.StatusCode != tt.statusCode {
  367. t.Errorf("caHandler.SSHRoots StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  368. }
  369. body, err := io.ReadAll(res.Body)
  370. res.Body.Close()
  371. if err != nil {
  372. t.Errorf("caHandler.SSHRoots unexpected error = %v", err)
  373. }
  374. if tt.statusCode < http.StatusBadRequest {
  375. if !bytes.Equal(bytes.TrimSpace(body), tt.body) {
  376. t.Errorf("caHandler.SSHRoots Body = %s, wants %s", body, tt.body)
  377. }
  378. }
  379. })
  380. }
  381. }
  382. func Test_caHandler_SSHFederation(t *testing.T) {
  383. user, err := ssh.NewPublicKey(sshUserKey.Public())
  384. assert.FatalError(t, err)
  385. userB64 := base64.StdEncoding.EncodeToString(user.Marshal())
  386. host, err := ssh.NewPublicKey(sshHostKey.Public())
  387. assert.FatalError(t, err)
  388. hostB64 := base64.StdEncoding.EncodeToString(host.Marshal())
  389. tests := []struct {
  390. name string
  391. keys *authority.SSHKeys
  392. keysErr error
  393. body []byte
  394. statusCode int
  395. }{
  396. {"ok", &authority.SSHKeys{HostKeys: []ssh.PublicKey{host}, UserKeys: []ssh.PublicKey{user}}, nil, []byte(fmt.Sprintf(`{"userKey":[%q],"hostKey":[%q]}`, userB64, hostB64)), http.StatusOK},
  397. {"many", &authority.SSHKeys{HostKeys: []ssh.PublicKey{host, host}, UserKeys: []ssh.PublicKey{user, user}}, nil, []byte(fmt.Sprintf(`{"userKey":[%q,%q],"hostKey":[%q,%q]}`, userB64, userB64, hostB64, hostB64)), http.StatusOK},
  398. {"user", &authority.SSHKeys{UserKeys: []ssh.PublicKey{user}}, nil, []byte(fmt.Sprintf(`{"userKey":[%q]}`, userB64)), http.StatusOK},
  399. {"host", &authority.SSHKeys{HostKeys: []ssh.PublicKey{host}}, nil, []byte(fmt.Sprintf(`{"hostKey":[%q]}`, hostB64)), http.StatusOK},
  400. {"empty", &authority.SSHKeys{}, nil, nil, http.StatusNotFound},
  401. {"error", nil, fmt.Errorf("an error"), nil, http.StatusInternalServerError},
  402. }
  403. for _, tt := range tests {
  404. t.Run(tt.name, func(t *testing.T) {
  405. h := New(&mockAuthority{
  406. getSSHFederation: func(ctx context.Context) (*authority.SSHKeys, error) {
  407. return tt.keys, tt.keysErr
  408. },
  409. }).(*caHandler)
  410. req := httptest.NewRequest("GET", "http://example.com/ssh/federation", http.NoBody)
  411. w := httptest.NewRecorder()
  412. h.SSHFederation(logging.NewResponseLogger(w), req)
  413. res := w.Result()
  414. if res.StatusCode != tt.statusCode {
  415. t.Errorf("caHandler.SSHFederation StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  416. }
  417. body, err := io.ReadAll(res.Body)
  418. res.Body.Close()
  419. if err != nil {
  420. t.Errorf("caHandler.SSHFederation unexpected error = %v", err)
  421. }
  422. if tt.statusCode < http.StatusBadRequest {
  423. if !bytes.Equal(bytes.TrimSpace(body), tt.body) {
  424. t.Errorf("caHandler.SSHFederation Body = %s, wants %s", body, tt.body)
  425. }
  426. }
  427. })
  428. }
  429. }
  430. func Test_caHandler_SSHConfig(t *testing.T) {
  431. userOutput := []templates.Output{
  432. {Name: "config.tpl", Type: templates.File, Comment: "#", Path: "ssh/config", Content: []byte("UserKnownHostsFile /home/user/.step/ssh/known_hosts")},
  433. {Name: "known_host.tpl", Type: templates.File, Comment: "#", Path: "ssh/known_host", Content: []byte("@cert-authority * ecdsa-sha2-nistp256 AAAA...=")},
  434. }
  435. hostOutput := []templates.Output{
  436. {Name: "sshd_config.tpl", Type: templates.Snippet, Comment: "#", Path: "/etc/ssh/sshd_config", Content: []byte("TrustedUserCAKeys /etc/ssh/ca.pub")},
  437. {Name: "ca.tpl", Type: templates.File, Comment: "#", Path: "/etc/ssh/ca.pub", Content: []byte("ecdsa-sha2-nistp256 AAAA...=")},
  438. }
  439. userJSON, err := json.Marshal(userOutput)
  440. assert.FatalError(t, err)
  441. hostJSON, err := json.Marshal(hostOutput)
  442. assert.FatalError(t, err)
  443. tests := []struct {
  444. name string
  445. req string
  446. output []templates.Output
  447. err error
  448. body []byte
  449. statusCode int
  450. }{
  451. {"user", `{"type":"user"}`, userOutput, nil, []byte(fmt.Sprintf(`{"userTemplates":%s}`, userJSON)), http.StatusOK},
  452. {"host", `{"type":"host"}`, hostOutput, nil, []byte(fmt.Sprintf(`{"hostTemplates":%s}`, hostJSON)), http.StatusOK},
  453. {"noType", `{}`, userOutput, nil, []byte(fmt.Sprintf(`{"userTemplates":%s}`, userJSON)), http.StatusOK},
  454. {"badType", `{"type":"bad"}`, userOutput, nil, nil, http.StatusBadRequest},
  455. {"badData", `{"type":"user","data":{"bad"}}`, userOutput, nil, nil, http.StatusBadRequest},
  456. {"error", `{"type": "user"}`, nil, fmt.Errorf("an error"), nil, http.StatusInternalServerError},
  457. }
  458. for _, tt := range tests {
  459. t.Run(tt.name, func(t *testing.T) {
  460. h := New(&mockAuthority{
  461. getSSHConfig: func(ctx context.Context, typ string, data map[string]string) ([]templates.Output, error) {
  462. return tt.output, tt.err
  463. },
  464. }).(*caHandler)
  465. req := httptest.NewRequest("GET", "http://example.com/ssh/config", strings.NewReader(tt.req))
  466. w := httptest.NewRecorder()
  467. h.SSHConfig(logging.NewResponseLogger(w), req)
  468. res := w.Result()
  469. if res.StatusCode != tt.statusCode {
  470. t.Errorf("caHandler.SSHConfig StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  471. }
  472. body, err := io.ReadAll(res.Body)
  473. res.Body.Close()
  474. if err != nil {
  475. t.Errorf("caHandler.SSHConfig unexpected error = %v", err)
  476. }
  477. if tt.statusCode < http.StatusBadRequest {
  478. if !bytes.Equal(bytes.TrimSpace(body), tt.body) {
  479. t.Errorf("caHandler.SSHConfig Body = %s, wants %s", body, tt.body)
  480. }
  481. }
  482. })
  483. }
  484. }
  485. func Test_caHandler_SSHCheckHost(t *testing.T) {
  486. tests := []struct {
  487. name string
  488. req string
  489. exists bool
  490. err error
  491. body []byte
  492. statusCode int
  493. }{
  494. {"true", `{"type":"host","principal":"foo.example.com"}`, true, nil, []byte(`{"exists":true}`), http.StatusOK},
  495. {"false", `{"type":"host","principal":"bar.example.com"}`, false, nil, []byte(`{"exists":false}`), http.StatusOK},
  496. {"badType", `{"type":"user","principal":"bar.example.com"}`, false, nil, nil, http.StatusBadRequest},
  497. {"badPrincipal", `{"type":"host","principal":""}`, false, nil, nil, http.StatusBadRequest},
  498. {"badRequest", `{"foo"}`, false, nil, nil, http.StatusBadRequest},
  499. {"error", `{"type":"host","principal":"foo.example.com"}`, false, fmt.Errorf("an error"), nil, http.StatusInternalServerError},
  500. }
  501. for _, tt := range tests {
  502. t.Run(tt.name, func(t *testing.T) {
  503. h := New(&mockAuthority{
  504. checkSSHHost: func(ctx context.Context, principal, token string) (bool, error) {
  505. return tt.exists, tt.err
  506. },
  507. }).(*caHandler)
  508. req := httptest.NewRequest("GET", "http://example.com/ssh/check-host", strings.NewReader(tt.req))
  509. w := httptest.NewRecorder()
  510. h.SSHCheckHost(logging.NewResponseLogger(w), req)
  511. res := w.Result()
  512. if res.StatusCode != tt.statusCode {
  513. t.Errorf("caHandler.SSHCheckHost StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  514. }
  515. body, err := io.ReadAll(res.Body)
  516. res.Body.Close()
  517. if err != nil {
  518. t.Errorf("caHandler.SSHCheckHost unexpected error = %v", err)
  519. }
  520. if tt.statusCode < http.StatusBadRequest {
  521. if !bytes.Equal(bytes.TrimSpace(body), tt.body) {
  522. t.Errorf("caHandler.SSHCheckHost Body = %s, wants %s", body, tt.body)
  523. }
  524. }
  525. })
  526. }
  527. }
  528. func Test_caHandler_SSHGetHosts(t *testing.T) {
  529. hosts := []authority.Host{
  530. {HostID: "1", HostTags: []authority.HostTag{{ID: "1", Name: "group", Value: "1"}}, Hostname: "host1"},
  531. {HostID: "2", HostTags: []authority.HostTag{{ID: "1", Name: "group", Value: "1"}, {ID: "2", Name: "group", Value: "2"}}, Hostname: "host2"},
  532. }
  533. hostsJSON, err := json.Marshal(hosts)
  534. assert.FatalError(t, err)
  535. tests := []struct {
  536. name string
  537. hosts []authority.Host
  538. err error
  539. body []byte
  540. statusCode int
  541. }{
  542. {"ok", hosts, nil, []byte(fmt.Sprintf(`{"hosts":%s}`, hostsJSON)), http.StatusOK},
  543. {"empty (array)", []authority.Host{}, nil, []byte(`{"hosts":[]}`), http.StatusOK},
  544. {"empty (nil)", nil, nil, []byte(`{"hosts":null}`), http.StatusOK},
  545. {"error", nil, fmt.Errorf("an error"), nil, http.StatusInternalServerError},
  546. }
  547. for _, tt := range tests {
  548. t.Run(tt.name, func(t *testing.T) {
  549. h := New(&mockAuthority{
  550. getSSHHosts: func(context.Context, *x509.Certificate) ([]authority.Host, error) {
  551. return tt.hosts, tt.err
  552. },
  553. }).(*caHandler)
  554. req := httptest.NewRequest("GET", "http://example.com/ssh/host", http.NoBody)
  555. w := httptest.NewRecorder()
  556. h.SSHGetHosts(logging.NewResponseLogger(w), req)
  557. res := w.Result()
  558. if res.StatusCode != tt.statusCode {
  559. t.Errorf("caHandler.SSHGetHosts StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  560. }
  561. body, err := io.ReadAll(res.Body)
  562. res.Body.Close()
  563. if err != nil {
  564. t.Errorf("caHandler.SSHGetHosts unexpected error = %v", err)
  565. }
  566. if tt.statusCode < http.StatusBadRequest {
  567. if !bytes.Equal(bytes.TrimSpace(body), tt.body) {
  568. t.Errorf("caHandler.SSHGetHosts Body = %s, wants %s", body, tt.body)
  569. }
  570. }
  571. })
  572. }
  573. }
  574. func Test_caHandler_SSHBastion(t *testing.T) {
  575. bastion := &authority.Bastion{
  576. Hostname: "bastion.local",
  577. }
  578. bastionPort := &authority.Bastion{
  579. Hostname: "bastion.local",
  580. Port: "2222",
  581. }
  582. tests := []struct {
  583. name string
  584. bastion *authority.Bastion
  585. bastionErr error
  586. req []byte
  587. body []byte
  588. statusCode int
  589. }{
  590. {"ok", bastion, nil, []byte(`{"hostname":"host.local"}`), []byte(`{"hostname":"host.local","bastion":{"hostname":"bastion.local"}}`), http.StatusOK},
  591. {"ok", bastionPort, nil, []byte(`{"hostname":"host.local","user":"user"}`), []byte(`{"hostname":"host.local","bastion":{"hostname":"bastion.local","port":"2222"}}`), http.StatusOK},
  592. {"empty", nil, nil, []byte(`{"hostname":"host.local"}`), []byte(`{"hostname":"host.local"}`), http.StatusOK},
  593. {"bad json", bastion, nil, []byte(`bad json`), nil, http.StatusBadRequest},
  594. {"bad request", bastion, nil, []byte(`{"hostname": ""}`), nil, http.StatusBadRequest},
  595. {"error", nil, fmt.Errorf("an error"), []byte(`{"hostname":"host.local"}`), nil, http.StatusInternalServerError},
  596. }
  597. for _, tt := range tests {
  598. t.Run(tt.name, func(t *testing.T) {
  599. h := New(&mockAuthority{
  600. getSSHBastion: func(ctx context.Context, user, hostname string) (*authority.Bastion, error) {
  601. return tt.bastion, tt.bastionErr
  602. },
  603. }).(*caHandler)
  604. req := httptest.NewRequest("POST", "http://example.com/ssh/bastion", bytes.NewReader(tt.req))
  605. w := httptest.NewRecorder()
  606. h.SSHBastion(logging.NewResponseLogger(w), req)
  607. res := w.Result()
  608. if res.StatusCode != tt.statusCode {
  609. t.Errorf("caHandler.SSHBastion StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  610. }
  611. body, err := io.ReadAll(res.Body)
  612. res.Body.Close()
  613. if err != nil {
  614. t.Errorf("caHandler.SSHBastion unexpected error = %v", err)
  615. }
  616. if tt.statusCode < http.StatusBadRequest {
  617. if !bytes.Equal(bytes.TrimSpace(body), tt.body) {
  618. t.Errorf("caHandler.SSHBastion Body = %s, wants %s", body, tt.body)
  619. }
  620. }
  621. })
  622. }
  623. }
  624. func TestSSHPublicKey_MarshalJSON(t *testing.T) {
  625. key, err := ssh.NewPublicKey(sshUserKey.Public())
  626. assert.FatalError(t, err)
  627. keyB64 := base64.StdEncoding.EncodeToString(key.Marshal())
  628. tests := []struct {
  629. name string
  630. publicKey *SSHPublicKey
  631. want []byte
  632. wantErr bool
  633. }{
  634. {"ok", &SSHPublicKey{PublicKey: key}, []byte(`"` + keyB64 + `"`), false},
  635. {"null", nil, []byte("null"), false},
  636. {"null", &SSHPublicKey{PublicKey: nil}, []byte("null"), false},
  637. }
  638. for _, tt := range tests {
  639. t.Run(tt.name, func(t *testing.T) {
  640. got, err := tt.publicKey.MarshalJSON()
  641. if (err != nil) != tt.wantErr {
  642. t.Errorf("SSHPublicKey.MarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
  643. return
  644. }
  645. if !reflect.DeepEqual(got, tt.want) {
  646. t.Errorf("SSHPublicKey.MarshalJSON() = %s, want %s", got, tt.want)
  647. }
  648. })
  649. }
  650. }
  651. func TestSSHPublicKey_UnmarshalJSON(t *testing.T) {
  652. key, err := ssh.NewPublicKey(sshUserKey.Public())
  653. assert.FatalError(t, err)
  654. keyB64 := base64.StdEncoding.EncodeToString(key.Marshal())
  655. type args struct {
  656. data []byte
  657. }
  658. tests := []struct {
  659. name string
  660. args args
  661. want *SSHPublicKey
  662. wantErr bool
  663. }{
  664. {"ok", args{[]byte(`"` + keyB64 + `"`)}, &SSHPublicKey{PublicKey: key}, false},
  665. {"empty", args{[]byte(`""`)}, &SSHPublicKey{}, false},
  666. {"null", args{[]byte(`null`)}, &SSHPublicKey{}, false},
  667. {"noString", args{[]byte("123")}, &SSHPublicKey{}, true},
  668. {"badB64", args{[]byte(`"bad"`)}, &SSHPublicKey{}, true},
  669. {"badKey", args{[]byte(`"Zm9vYmFyCg=="`)}, &SSHPublicKey{}, true},
  670. }
  671. for _, tt := range tests {
  672. t.Run(tt.name, func(t *testing.T) {
  673. p := &SSHPublicKey{}
  674. if err := p.UnmarshalJSON(tt.args.data); (err != nil) != tt.wantErr {
  675. t.Errorf("SSHPublicKey.UnmarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
  676. }
  677. if !reflect.DeepEqual(p, tt.want) {
  678. t.Errorf("SSHPublicKey.UnmarshalJSON() = %v, want %v", p, tt.want)
  679. }
  680. })
  681. }
  682. }