ssh.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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(ctx context.Context, principal string, token 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 identityCSR")
  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. Token string `json:"token,omitempty"`
  184. }
  185. // Validate checks the check principal request.
  186. func (r *SSHCheckPrincipalRequest) Validate() error {
  187. switch {
  188. case r.Type != provisioner.SSHHostCert:
  189. return errors.Errorf("unsupported type %s", r.Type)
  190. case r.Principal == "":
  191. return errors.New("missing or empty principal")
  192. default:
  193. return nil
  194. }
  195. }
  196. // SSHCheckPrincipalResponse is the response body used to check if a principal
  197. // exists.
  198. type SSHCheckPrincipalResponse struct {
  199. Exists bool `json:"exists"`
  200. }
  201. // SSHBastionRequest is the request body used to get the bastion for a given
  202. // host.
  203. type SSHBastionRequest struct {
  204. User string `json:"user"`
  205. Hostname string `json:"hostname"`
  206. }
  207. // Validate checks the values of the SSHBastionRequest.
  208. func (r *SSHBastionRequest) Validate() error {
  209. if r.Hostname == "" {
  210. return errors.New("missing or empty hostname")
  211. }
  212. return nil
  213. }
  214. // SSHBastionResponse is the response body used to return the bastion for a
  215. // given host.
  216. type SSHBastionResponse struct {
  217. Hostname string `json:"hostname"`
  218. Bastion *authority.Bastion `json:"bastion,omitempty"`
  219. }
  220. // SSHSign is an HTTP handler that reads an SignSSHRequest with a one-time-token
  221. // (ott) from the body and creates a new SSH certificate with the information in
  222. // the request.
  223. func (h *caHandler) SSHSign(w http.ResponseWriter, r *http.Request) {
  224. var body SSHSignRequest
  225. if err := ReadJSON(r.Body, &body); err != nil {
  226. WriteError(w, BadRequest(errors.Wrap(err, "error reading request body")))
  227. return
  228. }
  229. logOtt(w, body.OTT)
  230. if err := body.Validate(); err != nil {
  231. WriteError(w, BadRequest(err))
  232. return
  233. }
  234. publicKey, err := ssh.ParsePublicKey(body.PublicKey)
  235. if err != nil {
  236. WriteError(w, BadRequest(errors.Wrap(err, "error parsing publicKey")))
  237. return
  238. }
  239. var addUserPublicKey ssh.PublicKey
  240. if body.AddUserPublicKey != nil {
  241. addUserPublicKey, err = ssh.ParsePublicKey(body.AddUserPublicKey)
  242. if err != nil {
  243. WriteError(w, BadRequest(errors.Wrap(err, "error parsing addUserPublicKey")))
  244. return
  245. }
  246. }
  247. opts := provisioner.SSHOptions{
  248. CertType: body.CertType,
  249. KeyID: body.KeyID,
  250. Principals: body.Principals,
  251. ValidBefore: body.ValidBefore,
  252. ValidAfter: body.ValidAfter,
  253. }
  254. ctx := provisioner.NewContextWithMethod(context.Background(), provisioner.SignSSHMethod)
  255. signOpts, err := h.Authority.Authorize(ctx, body.OTT)
  256. if err != nil {
  257. WriteError(w, Unauthorized(err))
  258. return
  259. }
  260. cert, err := h.Authority.SignSSH(publicKey, opts, signOpts...)
  261. if err != nil {
  262. WriteError(w, Forbidden(err))
  263. return
  264. }
  265. var addUserCertificate *SSHCertificate
  266. if addUserPublicKey != nil && cert.CertType == ssh.UserCert && len(cert.ValidPrincipals) == 1 {
  267. addUserCert, err := h.Authority.SignSSHAddUser(addUserPublicKey, cert)
  268. if err != nil {
  269. WriteError(w, Forbidden(err))
  270. return
  271. }
  272. addUserCertificate = &SSHCertificate{addUserCert}
  273. }
  274. // Sign identity certificate if available.
  275. var identityCertificate []Certificate
  276. if cr := body.IdentityCSR.CertificateRequest; cr != nil {
  277. var opts provisioner.Options
  278. // Use same duration as ssh certificate for user certificates
  279. if cert.CertType == ssh.UserCert {
  280. opts = provisioner.Options{
  281. NotBefore: provisioner.NewTimeDuration(time.Unix(int64(cert.ValidAfter), 0)),
  282. NotAfter: provisioner.NewTimeDuration(time.Unix(int64(cert.ValidBefore), 0)),
  283. }
  284. }
  285. ctx := authority.NewContextWithSkipTokenReuse(context.Background())
  286. ctx = provisioner.NewContextWithMethod(ctx, provisioner.SignMethod)
  287. signOpts, err := h.Authority.Authorize(ctx, body.OTT)
  288. if err != nil {
  289. WriteError(w, Unauthorized(err))
  290. return
  291. }
  292. certChain, err := h.Authority.Sign(cr, opts, signOpts...)
  293. if err != nil {
  294. WriteError(w, Forbidden(err))
  295. return
  296. }
  297. identityCertificate = certChainToPEM(certChain)
  298. }
  299. JSONStatus(w, &SSHSignResponse{
  300. Certificate: SSHCertificate{cert},
  301. AddUserCertificate: addUserCertificate,
  302. IdentityCertificate: identityCertificate,
  303. }, http.StatusCreated)
  304. }
  305. // SSHRoots is an HTTP handler that returns the SSH public keys for user and host
  306. // certificates.
  307. func (h *caHandler) SSHRoots(w http.ResponseWriter, r *http.Request) {
  308. keys, err := h.Authority.GetSSHRoots()
  309. if err != nil {
  310. WriteError(w, InternalServerError(err))
  311. return
  312. }
  313. if len(keys.HostKeys) == 0 && len(keys.UserKeys) == 0 {
  314. WriteError(w, NotFound(errors.New("no keys found")))
  315. return
  316. }
  317. resp := new(SSHRootsResponse)
  318. for _, k := range keys.HostKeys {
  319. resp.HostKeys = append(resp.HostKeys, SSHPublicKey{PublicKey: k})
  320. }
  321. for _, k := range keys.UserKeys {
  322. resp.UserKeys = append(resp.UserKeys, SSHPublicKey{PublicKey: k})
  323. }
  324. JSON(w, resp)
  325. }
  326. // SSHFederation is an HTTP handler that returns the federated SSH public keys
  327. // for user and host certificates.
  328. func (h *caHandler) SSHFederation(w http.ResponseWriter, r *http.Request) {
  329. keys, err := h.Authority.GetSSHFederation()
  330. if err != nil {
  331. WriteError(w, InternalServerError(err))
  332. return
  333. }
  334. if len(keys.HostKeys) == 0 && len(keys.UserKeys) == 0 {
  335. WriteError(w, NotFound(errors.New("no keys found")))
  336. return
  337. }
  338. resp := new(SSHRootsResponse)
  339. for _, k := range keys.HostKeys {
  340. resp.HostKeys = append(resp.HostKeys, SSHPublicKey{PublicKey: k})
  341. }
  342. for _, k := range keys.UserKeys {
  343. resp.UserKeys = append(resp.UserKeys, SSHPublicKey{PublicKey: k})
  344. }
  345. JSON(w, resp)
  346. }
  347. // SSHConfig is an HTTP handler that returns rendered templates for ssh clients
  348. // and servers.
  349. func (h *caHandler) SSHConfig(w http.ResponseWriter, r *http.Request) {
  350. var body SSHConfigRequest
  351. if err := ReadJSON(r.Body, &body); err != nil {
  352. WriteError(w, BadRequest(errors.Wrap(err, "error reading request body")))
  353. return
  354. }
  355. if err := body.Validate(); err != nil {
  356. WriteError(w, BadRequest(err))
  357. return
  358. }
  359. ts, err := h.Authority.GetSSHConfig(body.Type, body.Data)
  360. if err != nil {
  361. WriteError(w, InternalServerError(err))
  362. return
  363. }
  364. var config SSHConfigResponse
  365. switch body.Type {
  366. case provisioner.SSHUserCert:
  367. config.UserTemplates = ts
  368. case provisioner.SSHHostCert:
  369. config.HostTemplates = ts
  370. default:
  371. WriteError(w, InternalServerError(errors.New("it should hot get here")))
  372. return
  373. }
  374. JSON(w, config)
  375. }
  376. // SSHCheckHost is the HTTP handler that returns if a hosts certificate exists or not.
  377. func (h *caHandler) SSHCheckHost(w http.ResponseWriter, r *http.Request) {
  378. var body SSHCheckPrincipalRequest
  379. if err := ReadJSON(r.Body, &body); err != nil {
  380. WriteError(w, BadRequest(errors.Wrap(err, "error reading request body")))
  381. return
  382. }
  383. if err := body.Validate(); err != nil {
  384. WriteError(w, BadRequest(err))
  385. return
  386. }
  387. exists, err := h.Authority.CheckSSHHost(r.Context(), body.Principal, body.Token)
  388. if err != nil {
  389. WriteError(w, InternalServerError(err))
  390. return
  391. }
  392. JSON(w, &SSHCheckPrincipalResponse{
  393. Exists: exists,
  394. })
  395. }
  396. // SSHGetHosts is the HTTP handler that returns a list of valid ssh hosts.
  397. func (h *caHandler) SSHGetHosts(w http.ResponseWriter, r *http.Request) {
  398. var cert *x509.Certificate
  399. if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 {
  400. cert = r.TLS.PeerCertificates[0]
  401. }
  402. hosts, err := h.Authority.GetSSHHosts(cert)
  403. if err != nil {
  404. WriteError(w, InternalServerError(err))
  405. return
  406. }
  407. JSON(w, &SSHGetHostsResponse{
  408. Hosts: hosts,
  409. })
  410. }
  411. // SSHBastion provides returns the bastion configured if any.
  412. func (h *caHandler) SSHBastion(w http.ResponseWriter, r *http.Request) {
  413. var body SSHBastionRequest
  414. if err := ReadJSON(r.Body, &body); err != nil {
  415. WriteError(w, BadRequest(errors.Wrap(err, "error reading request body")))
  416. return
  417. }
  418. if err := body.Validate(); err != nil {
  419. WriteError(w, BadRequest(err))
  420. return
  421. }
  422. bastion, err := h.Authority.GetSSHBastion(body.User, body.Hostname)
  423. if err != nil {
  424. WriteError(w, InternalServerError(err))
  425. return
  426. }
  427. JSON(w, &SSHBastionResponse{
  428. Hostname: body.Hostname,
  429. Bastion: bastion,
  430. })
  431. }