ssh.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. package api
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "encoding/json"
  6. "net/http"
  7. "github.com/pkg/errors"
  8. "github.com/smallstep/certificates/authority"
  9. "github.com/smallstep/certificates/authority/provisioner"
  10. "github.com/smallstep/certificates/templates"
  11. "golang.org/x/crypto/ssh"
  12. )
  13. // SSHAuthority is the interface implemented by a SSH CA authority.
  14. type SSHAuthority interface {
  15. SignSSH(key ssh.PublicKey, opts provisioner.SSHOptions, signOpts ...provisioner.SignOption) (*ssh.Certificate, error)
  16. SignSSHAddUser(key ssh.PublicKey, cert *ssh.Certificate) (*ssh.Certificate, error)
  17. GetSSHRoots() (*authority.SSHKeys, error)
  18. GetSSHFederation() (*authority.SSHKeys, error)
  19. GetSSHConfig(typ string, data map[string]string) ([]templates.Output, error)
  20. CheckSSHHost(principal string) (bool, error)
  21. GetSSHHosts() ([]string, error)
  22. }
  23. // SSHSignRequest is the request body of an SSH certificate request.
  24. type SSHSignRequest struct {
  25. PublicKey []byte `json:"publicKey"` //base64 encoded
  26. OTT string `json:"ott"`
  27. CertType string `json:"certType,omitempty"`
  28. Principals []string `json:"principals,omitempty"`
  29. ValidAfter TimeDuration `json:"validAfter,omitempty"`
  30. ValidBefore TimeDuration `json:"validBefore,omitempty"`
  31. AddUserPublicKey []byte `json:"addUserPublicKey,omitempty"`
  32. }
  33. // Validate validates the SSHSignRequest.
  34. func (s *SSHSignRequest) Validate() error {
  35. switch {
  36. case s.CertType != "" && s.CertType != provisioner.SSHUserCert && s.CertType != provisioner.SSHHostCert:
  37. return errors.Errorf("unknown certType %s", s.CertType)
  38. case len(s.PublicKey) == 0:
  39. return errors.New("missing or empty publicKey")
  40. case len(s.OTT) == 0:
  41. return errors.New("missing or empty ott")
  42. default:
  43. return nil
  44. }
  45. }
  46. // SSHSignResponse is the response object that returns the SSH certificate.
  47. type SSHSignResponse struct {
  48. Certificate SSHCertificate `json:"crt"`
  49. AddUserCertificate *SSHCertificate `json:"addUserCrt,omitempty"`
  50. }
  51. // SSHRootsResponse represents the response object that returns the SSH user and
  52. // host keys.
  53. type SSHRootsResponse struct {
  54. UserKeys []SSHPublicKey `json:"userKey,omitempty"`
  55. HostKeys []SSHPublicKey `json:"hostKey,omitempty"`
  56. }
  57. // SSHCertificate represents the response SSH certificate.
  58. type SSHCertificate struct {
  59. *ssh.Certificate `json:"omitempty"`
  60. }
  61. // SSHGetHostsResponse
  62. type SSHGetHostsResponse struct {
  63. Hosts []string `json:"hosts"`
  64. }
  65. // MarshalJSON implements the json.Marshaler interface. Returns a quoted,
  66. // base64 encoded, openssh wire format version of the certificate.
  67. func (c SSHCertificate) MarshalJSON() ([]byte, error) {
  68. if c.Certificate == nil {
  69. return []byte("null"), nil
  70. }
  71. s := base64.StdEncoding.EncodeToString(c.Certificate.Marshal())
  72. return []byte(`"` + s + `"`), nil
  73. }
  74. // UnmarshalJSON implements the json.Unmarshaler interface. The certificate is
  75. // expected to be a quoted, base64 encoded, openssh wire formatted block of bytes.
  76. func (c *SSHCertificate) UnmarshalJSON(data []byte) error {
  77. var s string
  78. if err := json.Unmarshal(data, &s); err != nil {
  79. return errors.Wrap(err, "error decoding certificate")
  80. }
  81. if s == "" {
  82. c.Certificate = nil
  83. return nil
  84. }
  85. certData, err := base64.StdEncoding.DecodeString(s)
  86. if err != nil {
  87. return errors.Wrap(err, "error decoding ssh certificate")
  88. }
  89. pub, err := ssh.ParsePublicKey(certData)
  90. if err != nil {
  91. return errors.Wrap(err, "error parsing ssh certificate")
  92. }
  93. cert, ok := pub.(*ssh.Certificate)
  94. if !ok {
  95. return errors.Errorf("error decoding ssh certificate: %T is not an *ssh.Certificate", pub)
  96. }
  97. c.Certificate = cert
  98. return nil
  99. }
  100. // SSHPublicKey represents a public key in a response object.
  101. type SSHPublicKey struct {
  102. ssh.PublicKey
  103. }
  104. // MarshalJSON implements the json.Marshaler interface. Returns a quoted,
  105. // base64 encoded, openssh wire format version of the public key.
  106. func (p *SSHPublicKey) MarshalJSON() ([]byte, error) {
  107. if p == nil || p.PublicKey == nil {
  108. return []byte("null"), nil
  109. }
  110. s := base64.StdEncoding.EncodeToString(p.PublicKey.Marshal())
  111. return []byte(`"` + s + `"`), nil
  112. }
  113. // UnmarshalJSON implements the json.Unmarshaler interface. The public key is
  114. // expected to be a quoted, base64 encoded, openssh wire formatted block of
  115. // bytes.
  116. func (p *SSHPublicKey) UnmarshalJSON(data []byte) error {
  117. var s string
  118. if err := json.Unmarshal(data, &s); err != nil {
  119. return errors.Wrap(err, "error decoding ssh public key")
  120. }
  121. if s == "" {
  122. p.PublicKey = nil
  123. return nil
  124. }
  125. data, err := base64.StdEncoding.DecodeString(s)
  126. if err != nil {
  127. return errors.Wrap(err, "error decoding ssh public key")
  128. }
  129. pub, err := ssh.ParsePublicKey(data)
  130. if err != nil {
  131. return errors.Wrap(err, "error parsing ssh public key")
  132. }
  133. p.PublicKey = pub
  134. return nil
  135. }
  136. // Template represents the output of a template.
  137. type Template = templates.Output
  138. // SSHConfigRequest is the request body used to get the SSH configuration
  139. // templates.
  140. type SSHConfigRequest struct {
  141. Type string `json:"type"`
  142. Data map[string]string `json:"data"`
  143. }
  144. // Validate checks the values of the SSHConfigurationRequest.
  145. func (r *SSHConfigRequest) Validate() error {
  146. switch r.Type {
  147. case "":
  148. r.Type = provisioner.SSHUserCert
  149. return nil
  150. case provisioner.SSHUserCert, provisioner.SSHHostCert:
  151. return nil
  152. default:
  153. return errors.Errorf("unsupported type %s", r.Type)
  154. }
  155. }
  156. // SSHConfigResponse is the response that returns the rendered templates.
  157. type SSHConfigResponse struct {
  158. UserTemplates []Template `json:"userTemplates,omitempty"`
  159. HostTemplates []Template `json:"hostTemplates,omitempty"`
  160. }
  161. // SSHCheckPrincipalRequest is the request body used to check if a principal
  162. // certificate has been created. Right now it only supported for hosts
  163. // certificates.
  164. type SSHCheckPrincipalRequest struct {
  165. Type string `json:"type"`
  166. Principal string `json:"principal"`
  167. }
  168. // Validate checks the check principal request.
  169. func (r *SSHCheckPrincipalRequest) Validate() error {
  170. switch {
  171. case r.Type != provisioner.SSHHostCert:
  172. return errors.Errorf("unsupported type %s", r.Type)
  173. case r.Principal == "":
  174. return errors.New("missing or empty principal")
  175. default:
  176. return nil
  177. }
  178. }
  179. // SSHCheckPrincipalResponse is the response body used to check if a principal
  180. // exists.
  181. type SSHCheckPrincipalResponse struct {
  182. Exists bool `json:"exists"`
  183. }
  184. // SSHSign is an HTTP handler that reads an SignSSHRequest with a one-time-token
  185. // (ott) from the body and creates a new SSH certificate with the information in
  186. // the request.
  187. func (h *caHandler) SSHSign(w http.ResponseWriter, r *http.Request) {
  188. var body SSHSignRequest
  189. if err := ReadJSON(r.Body, &body); err != nil {
  190. WriteError(w, BadRequest(errors.Wrap(err, "error reading request body")))
  191. return
  192. }
  193. logOtt(w, body.OTT)
  194. if err := body.Validate(); err != nil {
  195. WriteError(w, BadRequest(err))
  196. return
  197. }
  198. publicKey, err := ssh.ParsePublicKey(body.PublicKey)
  199. if err != nil {
  200. WriteError(w, BadRequest(errors.Wrap(err, "error parsing publicKey")))
  201. return
  202. }
  203. var addUserPublicKey ssh.PublicKey
  204. if body.AddUserPublicKey != nil {
  205. addUserPublicKey, err = ssh.ParsePublicKey(body.AddUserPublicKey)
  206. if err != nil {
  207. WriteError(w, BadRequest(errors.Wrap(err, "error parsing addUserPublicKey")))
  208. return
  209. }
  210. }
  211. opts := provisioner.SSHOptions{
  212. CertType: body.CertType,
  213. Principals: body.Principals,
  214. ValidBefore: body.ValidBefore,
  215. ValidAfter: body.ValidAfter,
  216. }
  217. ctx := provisioner.NewContextWithMethod(context.Background(), provisioner.SignSSHMethod)
  218. signOpts, err := h.Authority.Authorize(ctx, body.OTT)
  219. if err != nil {
  220. WriteError(w, Unauthorized(err))
  221. return
  222. }
  223. cert, err := h.Authority.SignSSH(publicKey, opts, signOpts...)
  224. if err != nil {
  225. WriteError(w, Forbidden(err))
  226. return
  227. }
  228. var addUserCertificate *SSHCertificate
  229. if addUserPublicKey != nil && cert.CertType == ssh.UserCert && len(cert.ValidPrincipals) == 1 {
  230. addUserCert, err := h.Authority.SignSSHAddUser(addUserPublicKey, cert)
  231. if err != nil {
  232. WriteError(w, Forbidden(err))
  233. return
  234. }
  235. addUserCertificate = &SSHCertificate{addUserCert}
  236. }
  237. w.WriteHeader(http.StatusCreated)
  238. JSON(w, &SSHSignResponse{
  239. Certificate: SSHCertificate{cert},
  240. AddUserCertificate: addUserCertificate,
  241. })
  242. }
  243. // SSHRoots is an HTTP handler that returns the SSH public keys for user and host
  244. // certificates.
  245. func (h *caHandler) SSHRoots(w http.ResponseWriter, r *http.Request) {
  246. keys, err := h.Authority.GetSSHRoots()
  247. if err != nil {
  248. WriteError(w, InternalServerError(err))
  249. return
  250. }
  251. if len(keys.HostKeys) == 0 && len(keys.UserKeys) == 0 {
  252. WriteError(w, NotFound(errors.New("no keys found")))
  253. return
  254. }
  255. resp := new(SSHRootsResponse)
  256. for _, k := range keys.HostKeys {
  257. resp.HostKeys = append(resp.HostKeys, SSHPublicKey{PublicKey: k})
  258. }
  259. for _, k := range keys.UserKeys {
  260. resp.UserKeys = append(resp.UserKeys, SSHPublicKey{PublicKey: k})
  261. }
  262. JSON(w, resp)
  263. }
  264. // SSHFederation is an HTTP handler that returns the federated SSH public keys
  265. // for user and host certificates.
  266. func (h *caHandler) SSHFederation(w http.ResponseWriter, r *http.Request) {
  267. keys, err := h.Authority.GetSSHFederation()
  268. if err != nil {
  269. WriteError(w, InternalServerError(err))
  270. return
  271. }
  272. if len(keys.HostKeys) == 0 && len(keys.UserKeys) == 0 {
  273. WriteError(w, NotFound(errors.New("no keys found")))
  274. return
  275. }
  276. resp := new(SSHRootsResponse)
  277. for _, k := range keys.HostKeys {
  278. resp.HostKeys = append(resp.HostKeys, SSHPublicKey{PublicKey: k})
  279. }
  280. for _, k := range keys.UserKeys {
  281. resp.UserKeys = append(resp.UserKeys, SSHPublicKey{PublicKey: k})
  282. }
  283. JSON(w, resp)
  284. }
  285. // SSHConfig is an HTTP handler that returns rendered templates for ssh clients
  286. // and servers.
  287. func (h *caHandler) SSHConfig(w http.ResponseWriter, r *http.Request) {
  288. var body SSHConfigRequest
  289. if err := ReadJSON(r.Body, &body); err != nil {
  290. WriteError(w, BadRequest(errors.Wrap(err, "error reading request body")))
  291. return
  292. }
  293. if err := body.Validate(); err != nil {
  294. WriteError(w, BadRequest(err))
  295. return
  296. }
  297. ts, err := h.Authority.GetSSHConfig(body.Type, body.Data)
  298. if err != nil {
  299. WriteError(w, InternalServerError(err))
  300. return
  301. }
  302. var config SSHConfigResponse
  303. switch body.Type {
  304. case provisioner.SSHUserCert:
  305. config.UserTemplates = ts
  306. case provisioner.SSHHostCert:
  307. config.HostTemplates = ts
  308. default:
  309. WriteError(w, InternalServerError(errors.New("it should hot get here")))
  310. return
  311. }
  312. JSON(w, config)
  313. }
  314. // SSHCheckHost is the HTTP handler that returns if a hosts certificate exists or not.
  315. func (h *caHandler) SSHCheckHost(w http.ResponseWriter, r *http.Request) {
  316. var body SSHCheckPrincipalRequest
  317. if err := ReadJSON(r.Body, &body); err != nil {
  318. WriteError(w, BadRequest(errors.Wrap(err, "error reading request body")))
  319. return
  320. }
  321. if err := body.Validate(); err != nil {
  322. WriteError(w, BadRequest(err))
  323. return
  324. }
  325. exists, err := h.Authority.CheckSSHHost(body.Principal)
  326. if err != nil {
  327. WriteError(w, InternalServerError(err))
  328. return
  329. }
  330. JSON(w, &SSHCheckPrincipalResponse{
  331. Exists: exists,
  332. })
  333. }
  334. // SSHGetHosts is the HTTP handler that returns a list of valid ssh hosts.
  335. func (h *caHandler) SSHGetHosts(w http.ResponseWriter, r *http.Request) {
  336. hosts, err := h.Authority.GetSSHHosts()
  337. if err != nil {
  338. WriteError(w, InternalServerError(err))
  339. return
  340. }
  341. JSON(w, &SSHGetHostsResponse{
  342. Hosts: hosts,
  343. })
  344. }