4
0

ssh.go 16 KB

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