ssh.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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. a := mustAuthority(ctx)
  265. signOpts, err := a.Authorize(ctx, body.OTT)
  266. if err != nil {
  267. render.Error(w, r, errs.UnauthorizedErr(err))
  268. return
  269. }
  270. cert, err := a.SignSSH(ctx, publicKey, opts, signOpts...)
  271. if err != nil {
  272. render.Error(w, r, errs.ForbiddenErr(err, "error signing ssh certificate"))
  273. return
  274. }
  275. var addUserCertificate *SSHCertificate
  276. if addUserPublicKey != nil && authority.IsValidForAddUser(cert) == nil {
  277. addUserCert, err := a.SignSSHAddUser(ctx, addUserPublicKey, cert)
  278. if err != nil {
  279. render.Error(w, r, errs.ForbiddenErr(err, "error signing ssh certificate"))
  280. return
  281. }
  282. addUserCertificate = &SSHCertificate{addUserCert}
  283. }
  284. // Sign identity certificate if available.
  285. var identityCertificate []Certificate
  286. if cr := body.IdentityCSR.CertificateRequest; cr != nil {
  287. ctx := authority.NewContextWithSkipTokenReuse(r.Context())
  288. ctx = provisioner.NewContextWithMethod(ctx, provisioner.SignIdentityMethod)
  289. signOpts, err := a.Authorize(ctx, body.OTT)
  290. if err != nil {
  291. render.Error(w, r, errs.UnauthorizedErr(err))
  292. return
  293. }
  294. // Enforce the same duration as ssh certificate.
  295. signOpts = append(signOpts, &identityModifier{
  296. Identity: getIdentityURI(cr),
  297. NotBefore: time.Unix(int64(cert.ValidAfter), 0),
  298. NotAfter: time.Unix(int64(cert.ValidBefore), 0),
  299. })
  300. certChain, err := a.SignWithContext(ctx, cr, provisioner.SignOptions{}, signOpts...)
  301. if err != nil {
  302. render.Error(w, r, errs.ForbiddenErr(err, "error signing identity certificate"))
  303. return
  304. }
  305. identityCertificate = certChainToPEM(certChain)
  306. }
  307. LogSSHCertificate(w, cert)
  308. render.JSONStatus(w, r, &SSHSignResponse{
  309. Certificate: SSHCertificate{cert},
  310. AddUserCertificate: addUserCertificate,
  311. IdentityCertificate: identityCertificate,
  312. }, http.StatusCreated)
  313. }
  314. // SSHRoots is an HTTP handler that returns the SSH public keys for user and host
  315. // certificates.
  316. func SSHRoots(w http.ResponseWriter, r *http.Request) {
  317. ctx := r.Context()
  318. keys, err := mustAuthority(ctx).GetSSHRoots(ctx)
  319. if err != nil {
  320. render.Error(w, r, errs.InternalServerErr(err))
  321. return
  322. }
  323. if len(keys.HostKeys) == 0 && len(keys.UserKeys) == 0 {
  324. render.Error(w, r, errs.NotFound("no keys found"))
  325. return
  326. }
  327. resp := new(SSHRootsResponse)
  328. for _, k := range keys.HostKeys {
  329. resp.HostKeys = append(resp.HostKeys, SSHPublicKey{PublicKey: k})
  330. }
  331. for _, k := range keys.UserKeys {
  332. resp.UserKeys = append(resp.UserKeys, SSHPublicKey{PublicKey: k})
  333. }
  334. render.JSON(w, r, resp)
  335. }
  336. // SSHFederation is an HTTP handler that returns the federated SSH public keys
  337. // for user and host certificates.
  338. func SSHFederation(w http.ResponseWriter, r *http.Request) {
  339. ctx := r.Context()
  340. keys, err := mustAuthority(ctx).GetSSHFederation(ctx)
  341. if err != nil {
  342. render.Error(w, r, errs.InternalServerErr(err))
  343. return
  344. }
  345. if len(keys.HostKeys) == 0 && len(keys.UserKeys) == 0 {
  346. render.Error(w, r, errs.NotFound("no keys found"))
  347. return
  348. }
  349. resp := new(SSHRootsResponse)
  350. for _, k := range keys.HostKeys {
  351. resp.HostKeys = append(resp.HostKeys, SSHPublicKey{PublicKey: k})
  352. }
  353. for _, k := range keys.UserKeys {
  354. resp.UserKeys = append(resp.UserKeys, SSHPublicKey{PublicKey: k})
  355. }
  356. render.JSON(w, r, resp)
  357. }
  358. // SSHConfig is an HTTP handler that returns rendered templates for ssh clients
  359. // and servers.
  360. func SSHConfig(w http.ResponseWriter, r *http.Request) {
  361. var body SSHConfigRequest
  362. if err := read.JSON(r.Body, &body); err != nil {
  363. render.Error(w, r, errs.BadRequestErr(err, "error reading request body"))
  364. return
  365. }
  366. if err := body.Validate(); err != nil {
  367. render.Error(w, r, err)
  368. return
  369. }
  370. ctx := r.Context()
  371. ts, err := mustAuthority(ctx).GetSSHConfig(ctx, body.Type, body.Data)
  372. if err != nil {
  373. render.Error(w, r, errs.InternalServerErr(err))
  374. return
  375. }
  376. var cfg SSHConfigResponse
  377. switch body.Type {
  378. case provisioner.SSHUserCert:
  379. cfg.UserTemplates = ts
  380. case provisioner.SSHHostCert:
  381. cfg.HostTemplates = ts
  382. default:
  383. render.Error(w, r, errs.InternalServer("it should hot get here"))
  384. return
  385. }
  386. render.JSON(w, r, cfg)
  387. }
  388. // SSHCheckHost is the HTTP handler that returns if a hosts certificate exists or not.
  389. func SSHCheckHost(w http.ResponseWriter, r *http.Request) {
  390. var body SSHCheckPrincipalRequest
  391. if err := read.JSON(r.Body, &body); err != nil {
  392. render.Error(w, r, errs.BadRequestErr(err, "error reading request body"))
  393. return
  394. }
  395. if err := body.Validate(); err != nil {
  396. render.Error(w, r, err)
  397. return
  398. }
  399. ctx := r.Context()
  400. exists, err := mustAuthority(ctx).CheckSSHHost(ctx, body.Principal, body.Token)
  401. if err != nil {
  402. render.Error(w, r, errs.InternalServerErr(err))
  403. return
  404. }
  405. render.JSON(w, r, &SSHCheckPrincipalResponse{
  406. Exists: exists,
  407. })
  408. }
  409. // SSHGetHosts is the HTTP handler that returns a list of valid ssh hosts.
  410. func SSHGetHosts(w http.ResponseWriter, r *http.Request) {
  411. var cert *x509.Certificate
  412. if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 {
  413. cert = r.TLS.PeerCertificates[0]
  414. }
  415. ctx := r.Context()
  416. hosts, err := mustAuthority(ctx).GetSSHHosts(ctx, cert)
  417. if err != nil {
  418. render.Error(w, r, errs.InternalServerErr(err))
  419. return
  420. }
  421. render.JSON(w, r, &SSHGetHostsResponse{
  422. Hosts: hosts,
  423. })
  424. }
  425. // SSHBastion provides returns the bastion configured if any.
  426. func SSHBastion(w http.ResponseWriter, r *http.Request) {
  427. var body SSHBastionRequest
  428. if err := read.JSON(r.Body, &body); err != nil {
  429. render.Error(w, r, errs.BadRequestErr(err, "error reading request body"))
  430. return
  431. }
  432. if err := body.Validate(); err != nil {
  433. render.Error(w, r, err)
  434. return
  435. }
  436. ctx := r.Context()
  437. bastion, err := mustAuthority(ctx).GetSSHBastion(ctx, body.User, body.Hostname)
  438. if err != nil {
  439. render.Error(w, r, errs.InternalServerErr(err))
  440. return
  441. }
  442. render.JSON(w, r, &SSHBastionResponse{
  443. Hostname: body.Hostname,
  444. Bastion: bastion,
  445. })
  446. }
  447. // identityModifier is a custom modifier used to force a fixed duration, and set
  448. // the identity URI.
  449. type identityModifier struct {
  450. Identity *url.URL
  451. NotBefore time.Time
  452. NotAfter time.Time
  453. }
  454. // Enforce implements the enforcer interface and sets the validity bounds and
  455. // the identity uri to the certificate.
  456. func (m *identityModifier) Enforce(cert *x509.Certificate) error {
  457. cert.NotBefore = m.NotBefore
  458. cert.NotAfter = m.NotAfter
  459. if m.Identity != nil {
  460. var identityURL = m.Identity.String()
  461. for _, u := range cert.URIs {
  462. if u.String() == identityURL {
  463. return nil
  464. }
  465. }
  466. cert.URIs = append(cert.URIs, m.Identity)
  467. }
  468. return nil
  469. }
  470. // getIdentityURI returns the first valid UUID URN from the given CSR.
  471. func getIdentityURI(cr *x509.CertificateRequest) *url.URL {
  472. for _, u := range cr.URIs {
  473. s := u.String()
  474. // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
  475. if len(s) == 9+36 && strings.EqualFold(s[:9], "urn:uuid:") {
  476. if _, err := uuid.Parse(s); err == nil {
  477. return u
  478. }
  479. }
  480. }
  481. return nil
  482. }