ssh.go 15 KB

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