ssh.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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 SSHSign(w http.ResponseWriter, r *http.Request) {
  228. var body SSHSignRequest
  229. if err := read.JSON(r.Body, &body); err != nil {
  230. render.Error(w, errs.BadRequestErr(err, "error reading request body"))
  231. return
  232. }
  233. logOtt(w, body.OTT)
  234. if err := body.Validate(); err != nil {
  235. render.Error(w, err)
  236. return
  237. }
  238. publicKey, err := ssh.ParsePublicKey(body.PublicKey)
  239. if err != nil {
  240. render.Error(w, errs.BadRequestErr(err, "error parsing publicKey"))
  241. return
  242. }
  243. var addUserPublicKey ssh.PublicKey
  244. if body.AddUserPublicKey != nil {
  245. addUserPublicKey, err = ssh.ParsePublicKey(body.AddUserPublicKey)
  246. if err != nil {
  247. render.Error(w, errs.BadRequestErr(err, "error parsing addUserPublicKey"))
  248. return
  249. }
  250. }
  251. opts := provisioner.SignSSHOptions{
  252. CertType: body.CertType,
  253. KeyID: body.KeyID,
  254. Principals: body.Principals,
  255. ValidBefore: body.ValidBefore,
  256. ValidAfter: body.ValidAfter,
  257. TemplateData: body.TemplateData,
  258. }
  259. ctx := provisioner.NewContextWithMethod(r.Context(), provisioner.SSHSignMethod)
  260. ctx = provisioner.NewContextWithToken(ctx, body.OTT)
  261. a := mustAuthority(ctx)
  262. signOpts, err := a.Authorize(ctx, body.OTT)
  263. if err != nil {
  264. render.Error(w, errs.UnauthorizedErr(err))
  265. return
  266. }
  267. cert, err := a.SignSSH(ctx, publicKey, opts, signOpts...)
  268. if err != nil {
  269. render.Error(w, errs.ForbiddenErr(err, "error signing ssh certificate"))
  270. return
  271. }
  272. var addUserCertificate *SSHCertificate
  273. if addUserPublicKey != nil && authority.IsValidForAddUser(cert) == nil {
  274. addUserCert, err := a.SignSSHAddUser(ctx, addUserPublicKey, cert)
  275. if err != nil {
  276. render.Error(w, errs.ForbiddenErr(err, "error signing ssh certificate"))
  277. return
  278. }
  279. addUserCertificate = &SSHCertificate{addUserCert}
  280. }
  281. // Sign identity certificate if available.
  282. var identityCertificate []Certificate
  283. if cr := body.IdentityCSR.CertificateRequest; cr != nil {
  284. ctx := authority.NewContextWithSkipTokenReuse(r.Context())
  285. ctx = provisioner.NewContextWithMethod(ctx, provisioner.SignIdentityMethod)
  286. signOpts, err := a.Authorize(ctx, body.OTT)
  287. if err != nil {
  288. render.Error(w, errs.UnauthorizedErr(err))
  289. return
  290. }
  291. // Enforce the same duration as ssh certificate.
  292. signOpts = append(signOpts, &identityModifier{
  293. NotBefore: time.Unix(int64(cert.ValidAfter), 0),
  294. NotAfter: time.Unix(int64(cert.ValidBefore), 0),
  295. })
  296. certChain, err := a.Sign(cr, provisioner.SignOptions{}, signOpts...)
  297. if err != nil {
  298. render.Error(w, errs.ForbiddenErr(err, "error signing identity certificate"))
  299. return
  300. }
  301. identityCertificate = certChainToPEM(certChain)
  302. }
  303. LogSSHCertificate(w, cert)
  304. render.JSONStatus(w, &SSHSignResponse{
  305. Certificate: SSHCertificate{cert},
  306. AddUserCertificate: addUserCertificate,
  307. IdentityCertificate: identityCertificate,
  308. }, http.StatusCreated)
  309. }
  310. // SSHRoots is an HTTP handler that returns the SSH public keys for user and host
  311. // certificates.
  312. func SSHRoots(w http.ResponseWriter, r *http.Request) {
  313. ctx := r.Context()
  314. keys, err := mustAuthority(ctx).GetSSHRoots(ctx)
  315. if err != nil {
  316. render.Error(w, errs.InternalServerErr(err))
  317. return
  318. }
  319. if len(keys.HostKeys) == 0 && len(keys.UserKeys) == 0 {
  320. render.Error(w, errs.NotFound("no keys found"))
  321. return
  322. }
  323. resp := new(SSHRootsResponse)
  324. for _, k := range keys.HostKeys {
  325. resp.HostKeys = append(resp.HostKeys, SSHPublicKey{PublicKey: k})
  326. }
  327. for _, k := range keys.UserKeys {
  328. resp.UserKeys = append(resp.UserKeys, SSHPublicKey{PublicKey: k})
  329. }
  330. render.JSON(w, resp)
  331. }
  332. // SSHFederation is an HTTP handler that returns the federated SSH public keys
  333. // for user and host certificates.
  334. func SSHFederation(w http.ResponseWriter, r *http.Request) {
  335. ctx := r.Context()
  336. keys, err := mustAuthority(ctx).GetSSHFederation(ctx)
  337. if err != nil {
  338. render.Error(w, errs.InternalServerErr(err))
  339. return
  340. }
  341. if len(keys.HostKeys) == 0 && len(keys.UserKeys) == 0 {
  342. render.Error(w, errs.NotFound("no keys found"))
  343. return
  344. }
  345. resp := new(SSHRootsResponse)
  346. for _, k := range keys.HostKeys {
  347. resp.HostKeys = append(resp.HostKeys, SSHPublicKey{PublicKey: k})
  348. }
  349. for _, k := range keys.UserKeys {
  350. resp.UserKeys = append(resp.UserKeys, SSHPublicKey{PublicKey: k})
  351. }
  352. render.JSON(w, resp)
  353. }
  354. // SSHConfig is an HTTP handler that returns rendered templates for ssh clients
  355. // and servers.
  356. func SSHConfig(w http.ResponseWriter, r *http.Request) {
  357. var body SSHConfigRequest
  358. if err := read.JSON(r.Body, &body); err != nil {
  359. render.Error(w, errs.BadRequestErr(err, "error reading request body"))
  360. return
  361. }
  362. if err := body.Validate(); err != nil {
  363. render.Error(w, err)
  364. return
  365. }
  366. ctx := r.Context()
  367. ts, err := mustAuthority(ctx).GetSSHConfig(ctx, body.Type, body.Data)
  368. if err != nil {
  369. render.Error(w, errs.InternalServerErr(err))
  370. return
  371. }
  372. var cfg SSHConfigResponse
  373. switch body.Type {
  374. case provisioner.SSHUserCert:
  375. cfg.UserTemplates = ts
  376. case provisioner.SSHHostCert:
  377. cfg.HostTemplates = ts
  378. default:
  379. render.Error(w, errs.InternalServer("it should hot get here"))
  380. return
  381. }
  382. render.JSON(w, cfg)
  383. }
  384. // SSHCheckHost is the HTTP handler that returns if a hosts certificate exists or not.
  385. func SSHCheckHost(w http.ResponseWriter, r *http.Request) {
  386. var body SSHCheckPrincipalRequest
  387. if err := read.JSON(r.Body, &body); err != nil {
  388. render.Error(w, errs.BadRequestErr(err, "error reading request body"))
  389. return
  390. }
  391. if err := body.Validate(); err != nil {
  392. render.Error(w, err)
  393. return
  394. }
  395. ctx := r.Context()
  396. exists, err := mustAuthority(ctx).CheckSSHHost(ctx, body.Principal, body.Token)
  397. if err != nil {
  398. render.Error(w, errs.InternalServerErr(err))
  399. return
  400. }
  401. render.JSON(w, &SSHCheckPrincipalResponse{
  402. Exists: exists,
  403. })
  404. }
  405. // SSHGetHosts is the HTTP handler that returns a list of valid ssh hosts.
  406. func SSHGetHosts(w http.ResponseWriter, r *http.Request) {
  407. var cert *x509.Certificate
  408. if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 {
  409. cert = r.TLS.PeerCertificates[0]
  410. }
  411. ctx := r.Context()
  412. hosts, err := mustAuthority(ctx).GetSSHHosts(ctx, cert)
  413. if err != nil {
  414. render.Error(w, errs.InternalServerErr(err))
  415. return
  416. }
  417. render.JSON(w, &SSHGetHostsResponse{
  418. Hosts: hosts,
  419. })
  420. }
  421. // SSHBastion provides returns the bastion configured if any.
  422. func SSHBastion(w http.ResponseWriter, r *http.Request) {
  423. var body SSHBastionRequest
  424. if err := read.JSON(r.Body, &body); err != nil {
  425. render.Error(w, errs.BadRequestErr(err, "error reading request body"))
  426. return
  427. }
  428. if err := body.Validate(); err != nil {
  429. render.Error(w, err)
  430. return
  431. }
  432. ctx := r.Context()
  433. bastion, err := mustAuthority(ctx).GetSSHBastion(ctx, body.User, body.Hostname)
  434. if err != nil {
  435. render.Error(w, errs.InternalServerErr(err))
  436. return
  437. }
  438. render.JSON(w, &SSHBastionResponse{
  439. Hostname: body.Hostname,
  440. Bastion: bastion,
  441. })
  442. }
  443. // identityModifier is a custom modifier used to force a fixed duration.
  444. type identityModifier struct {
  445. NotBefore time.Time
  446. NotAfter time.Time
  447. }
  448. func (m *identityModifier) Enforce(cert *x509.Certificate) error {
  449. cert.NotBefore = m.NotBefore
  450. cert.NotAfter = m.NotAfter
  451. return nil
  452. }