ssh.go 15 KB

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