ssh.go 16 KB

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