ssh.go 14 KB

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