ssh.go 14 KB

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