ssh_test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. package api
  2. import (
  3. "bytes"
  4. "crypto/ecdsa"
  5. "crypto/elliptic"
  6. "crypto/rand"
  7. "encoding/base64"
  8. "encoding/json"
  9. "fmt"
  10. "io/ioutil"
  11. "net/http"
  12. "net/http/httptest"
  13. "reflect"
  14. "testing"
  15. "time"
  16. "github.com/smallstep/assert"
  17. "github.com/smallstep/certificates/authority/provisioner"
  18. "github.com/smallstep/certificates/logging"
  19. "golang.org/x/crypto/ssh"
  20. )
  21. var (
  22. sshSignerKey = mustKey()
  23. sshUserKey = mustKey()
  24. sshHostKey = mustKey()
  25. )
  26. func mustKey() *ecdsa.PrivateKey {
  27. priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  28. if err != nil {
  29. panic(err)
  30. }
  31. return priv
  32. }
  33. func signSSHCertificate(cert *ssh.Certificate) error {
  34. signerKey, err := ssh.NewPublicKey(sshSignerKey.Public())
  35. if err != nil {
  36. return err
  37. }
  38. signer, err := ssh.NewSignerFromSigner(sshSignerKey)
  39. if err != nil {
  40. return err
  41. }
  42. cert.SignatureKey = signerKey
  43. data := cert.Marshal()
  44. data = data[:len(data)-4]
  45. sig, err := signer.Sign(rand.Reader, data)
  46. if err != nil {
  47. return err
  48. }
  49. cert.Signature = sig
  50. return nil
  51. }
  52. func getSignedUserCertificate() (*ssh.Certificate, error) {
  53. key, err := ssh.NewPublicKey(sshUserKey.Public())
  54. if err != nil {
  55. return nil, err
  56. }
  57. t := time.Now()
  58. cert := &ssh.Certificate{
  59. Nonce: []byte("1234567890"),
  60. Key: key,
  61. Serial: 1234567890,
  62. CertType: ssh.UserCert,
  63. KeyId: "user@localhost",
  64. ValidPrincipals: []string{"user"},
  65. ValidAfter: uint64(t.Unix()),
  66. ValidBefore: uint64(t.Add(time.Hour).Unix()),
  67. Permissions: ssh.Permissions{
  68. CriticalOptions: map[string]string{},
  69. Extensions: map[string]string{
  70. "permit-X11-forwarding": "",
  71. "permit-agent-forwarding": "",
  72. "permit-port-forwarding": "",
  73. "permit-pty": "",
  74. "permit-user-rc": "",
  75. },
  76. },
  77. Reserved: []byte{},
  78. }
  79. if err := signSSHCertificate(cert); err != nil {
  80. return nil, err
  81. }
  82. return cert, nil
  83. }
  84. func getSignedHostCertificate() (*ssh.Certificate, error) {
  85. key, err := ssh.NewPublicKey(sshHostKey.Public())
  86. if err != nil {
  87. return nil, err
  88. }
  89. t := time.Now()
  90. cert := &ssh.Certificate{
  91. Nonce: []byte("1234567890"),
  92. Key: key,
  93. Serial: 1234567890,
  94. CertType: ssh.UserCert,
  95. KeyId: "internal.smallstep.com",
  96. ValidPrincipals: []string{"internal.smallstep.com"},
  97. ValidAfter: uint64(t.Unix()),
  98. ValidBefore: uint64(t.Add(time.Hour).Unix()),
  99. Permissions: ssh.Permissions{
  100. CriticalOptions: map[string]string{},
  101. Extensions: map[string]string{},
  102. },
  103. Reserved: []byte{},
  104. }
  105. if err := signSSHCertificate(cert); err != nil {
  106. return nil, err
  107. }
  108. return cert, nil
  109. }
  110. func TestSSHCertificate_MarshalJSON(t *testing.T) {
  111. user, err := getSignedUserCertificate()
  112. assert.FatalError(t, err)
  113. host, err := getSignedHostCertificate()
  114. assert.FatalError(t, err)
  115. userB64 := base64.StdEncoding.EncodeToString(user.Marshal())
  116. hostB64 := base64.StdEncoding.EncodeToString(host.Marshal())
  117. type fields struct {
  118. Certificate *ssh.Certificate
  119. }
  120. tests := []struct {
  121. name string
  122. fields fields
  123. want []byte
  124. wantErr bool
  125. }{
  126. {"nil", fields{Certificate: nil}, []byte("null"), false},
  127. {"user", fields{Certificate: user}, []byte(`"` + userB64 + `"`), false},
  128. {"user", fields{Certificate: host}, []byte(`"` + hostB64 + `"`), false},
  129. }
  130. for _, tt := range tests {
  131. t.Run(tt.name, func(t *testing.T) {
  132. c := SSHCertificate{
  133. Certificate: tt.fields.Certificate,
  134. }
  135. got, err := c.MarshalJSON()
  136. if (err != nil) != tt.wantErr {
  137. t.Errorf("SSHCertificate.MarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
  138. return
  139. }
  140. if !reflect.DeepEqual(got, tt.want) {
  141. t.Errorf("SSHCertificate.MarshalJSON() = %v, want %v", got, tt.want)
  142. }
  143. })
  144. }
  145. }
  146. func TestSSHCertificate_UnmarshalJSON(t *testing.T) {
  147. user, err := getSignedUserCertificate()
  148. assert.FatalError(t, err)
  149. host, err := getSignedHostCertificate()
  150. assert.FatalError(t, err)
  151. userB64 := base64.StdEncoding.EncodeToString(user.Marshal())
  152. hostB64 := base64.StdEncoding.EncodeToString(host.Marshal())
  153. keyB64 := base64.StdEncoding.EncodeToString(user.Key.Marshal())
  154. type args struct {
  155. data []byte
  156. }
  157. tests := []struct {
  158. name string
  159. args args
  160. want *ssh.Certificate
  161. wantErr bool
  162. }{
  163. {"null", args{[]byte(`null`)}, nil, false},
  164. {"empty", args{[]byte(`""`)}, nil, false},
  165. {"user", args{[]byte(`"` + userB64 + `"`)}, user, false},
  166. {"host", args{[]byte(`"` + hostB64 + `"`)}, host, false},
  167. {"bad-string", args{[]byte(userB64)}, nil, true},
  168. {"bad-base64", args{[]byte(`"this-is-not-base64"`)}, nil, true},
  169. {"bad-key", args{[]byte(`"bm90LWEta2V5"`)}, nil, true},
  170. {"bat-cert", args{[]byte(`"` + keyB64 + `"`)}, nil, true},
  171. }
  172. for _, tt := range tests {
  173. t.Run(tt.name, func(t *testing.T) {
  174. c := &SSHCertificate{}
  175. if err := c.UnmarshalJSON(tt.args.data); (err != nil) != tt.wantErr {
  176. t.Errorf("SSHCertificate.UnmarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
  177. }
  178. if !reflect.DeepEqual(tt.want, c.Certificate) {
  179. t.Errorf("SSHCertificate.UnmarshalJSON() got = %v, want %v\n", c.Certificate, tt.want)
  180. }
  181. })
  182. }
  183. }
  184. func TestSignSSHRequest_Validate(t *testing.T) {
  185. type fields struct {
  186. PublicKey []byte
  187. OTT string
  188. CertType string
  189. Principals []string
  190. ValidAfter TimeDuration
  191. ValidBefore TimeDuration
  192. AddUserPublicKey []byte
  193. }
  194. tests := []struct {
  195. name string
  196. fields fields
  197. wantErr bool
  198. }{
  199. {"ok-empty", fields{[]byte("Zm9v"), "ott", "", []string{"user"}, TimeDuration{}, TimeDuration{}, nil}, false},
  200. {"ok-user", fields{[]byte("Zm9v"), "ott", "user", []string{"user"}, TimeDuration{}, TimeDuration{}, nil}, false},
  201. {"ok-host", fields{[]byte("Zm9v"), "ott", "host", []string{"user"}, TimeDuration{}, TimeDuration{}, nil}, false},
  202. {"key", fields{nil, "ott", "user", []string{"user"}, TimeDuration{}, TimeDuration{}, nil}, true},
  203. {"key", fields{[]byte(""), "ott", "user", []string{"user"}, TimeDuration{}, TimeDuration{}, nil}, true},
  204. {"type", fields{[]byte("Zm9v"), "ott", "foo", []string{"user"}, TimeDuration{}, TimeDuration{}, nil}, true},
  205. {"ott", fields{[]byte("Zm9v"), "", "user", []string{"user"}, TimeDuration{}, TimeDuration{}, nil}, true},
  206. }
  207. for _, tt := range tests {
  208. t.Run(tt.name, func(t *testing.T) {
  209. s := &SignSSHRequest{
  210. PublicKey: tt.fields.PublicKey,
  211. OTT: tt.fields.OTT,
  212. CertType: tt.fields.CertType,
  213. Principals: tt.fields.Principals,
  214. ValidAfter: tt.fields.ValidAfter,
  215. ValidBefore: tt.fields.ValidBefore,
  216. AddUserPublicKey: tt.fields.AddUserPublicKey,
  217. }
  218. if err := s.Validate(); (err != nil) != tt.wantErr {
  219. t.Errorf("SignSSHRequest.Validate() error = %v, wantErr %v", err, tt.wantErr)
  220. }
  221. })
  222. }
  223. }
  224. func Test_caHandler_SignSSH(t *testing.T) {
  225. user, err := getSignedUserCertificate()
  226. assert.FatalError(t, err)
  227. host, err := getSignedHostCertificate()
  228. assert.FatalError(t, err)
  229. userB64 := base64.StdEncoding.EncodeToString(user.Marshal())
  230. hostB64 := base64.StdEncoding.EncodeToString(host.Marshal())
  231. userReq, err := json.Marshal(SignSSHRequest{
  232. PublicKey: user.Key.Marshal(),
  233. OTT: "ott",
  234. })
  235. assert.FatalError(t, err)
  236. hostReq, err := json.Marshal(SignSSHRequest{
  237. PublicKey: host.Key.Marshal(),
  238. OTT: "ott",
  239. })
  240. assert.FatalError(t, err)
  241. userAddReq, err := json.Marshal(SignSSHRequest{
  242. PublicKey: user.Key.Marshal(),
  243. OTT: "ott",
  244. AddUserPublicKey: user.Key.Marshal(),
  245. })
  246. assert.FatalError(t, err)
  247. tests := []struct {
  248. name string
  249. req []byte
  250. authErr error
  251. signCert *ssh.Certificate
  252. signErr error
  253. addUserCert *ssh.Certificate
  254. addUserErr error
  255. body []byte
  256. statusCode int
  257. }{
  258. {"ok-user", userReq, nil, user, nil, nil, nil, []byte(fmt.Sprintf(`{"crt":"%s"}`, userB64)), http.StatusCreated},
  259. {"ok-host", hostReq, nil, host, nil, nil, nil, []byte(fmt.Sprintf(`{"crt":"%s"}`, hostB64)), http.StatusCreated},
  260. {"ok-user-add", userAddReq, nil, user, nil, user, nil, []byte(fmt.Sprintf(`{"crt":"%s","addUserCrt":"%s"}`, userB64, userB64)), http.StatusCreated},
  261. {"fail-body", []byte("bad-json"), nil, nil, nil, nil, nil, nil, http.StatusBadRequest},
  262. {"fail-validate", []byte("{}"), nil, nil, nil, nil, nil, nil, http.StatusBadRequest},
  263. {"fail-publicKey", []byte(`{"publicKey":"Zm9v","ott":"ott"}`), nil, nil, nil, nil, nil, nil, http.StatusBadRequest},
  264. {"fail-publicKey", []byte(fmt.Sprintf(`{"publicKey":"%s","ott":"ott","addUserPublicKey":"Zm9v"}`, base64.StdEncoding.EncodeToString(user.Key.Marshal()))), nil, nil, nil, nil, nil, nil, http.StatusBadRequest},
  265. {"fail-authorize", userReq, fmt.Errorf("an-error"), nil, nil, nil, nil, nil, http.StatusUnauthorized},
  266. {"fail-signSSH", userReq, nil, nil, fmt.Errorf("an-error"), nil, nil, nil, http.StatusForbidden},
  267. {"fail-SignSSHAddUser", userAddReq, nil, user, nil, nil, fmt.Errorf("an-error"), nil, http.StatusForbidden},
  268. }
  269. for _, tt := range tests {
  270. t.Run(tt.name, func(t *testing.T) {
  271. h := New(&mockAuthority{
  272. authorizeSign: func(ott string) ([]provisioner.SignOption, error) {
  273. return []provisioner.SignOption{}, tt.authErr
  274. },
  275. signSSH: func(key ssh.PublicKey, opts provisioner.SSHOptions, signOpts ...provisioner.SignOption) (*ssh.Certificate, error) {
  276. return tt.signCert, tt.signErr
  277. },
  278. signSSHAddUser: func(key ssh.PublicKey, cert *ssh.Certificate) (*ssh.Certificate, error) {
  279. return tt.addUserCert, tt.addUserErr
  280. },
  281. }).(*caHandler)
  282. req := httptest.NewRequest("POST", "http://example.com/sign-ssh", bytes.NewReader(tt.req))
  283. w := httptest.NewRecorder()
  284. h.SignSSH(logging.NewResponseLogger(w), req)
  285. res := w.Result()
  286. if res.StatusCode != tt.statusCode {
  287. t.Errorf("caHandler.Root StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
  288. }
  289. body, err := ioutil.ReadAll(res.Body)
  290. res.Body.Close()
  291. if err != nil {
  292. t.Errorf("caHandler.Root unexpected error = %v", err)
  293. }
  294. if tt.statusCode < http.StatusBadRequest {
  295. if !bytes.Equal(bytes.TrimSpace(body), tt.body) {
  296. t.Errorf("caHandler.Root Body = %s, wants %s", body, tt.body)
  297. }
  298. }
  299. })
  300. }
  301. }