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