ssh.go 14 KB

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