4
0

ssh_test.go 30 KB

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