4
0

ssh.go 15 KB

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