sshRekey.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package api
  2. import (
  3. "context"
  4. "net/http"
  5. "github.com/pkg/errors"
  6. "github.com/smallstep/certificates/authority/provisioner"
  7. "github.com/smallstep/certificates/errs"
  8. "golang.org/x/crypto/ssh"
  9. )
  10. // SSHRekeyRequest is the request body of an SSH certificate request.
  11. type SSHRekeyRequest struct {
  12. OTT string `json:"ott"`
  13. PublicKey []byte `json:"publicKey"` //base64 encoded
  14. }
  15. // Validate validates the SSHSignRekey.
  16. func (s *SSHRekeyRequest) Validate() error {
  17. switch {
  18. case len(s.OTT) == 0:
  19. return errors.New("missing or empty ott")
  20. case len(s.PublicKey) == 0:
  21. return errors.New("missing or empty public key")
  22. default:
  23. return nil
  24. }
  25. }
  26. // SSHRekeyResponse is the response object that returns the SSH certificate.
  27. type SSHRekeyResponse struct {
  28. Certificate SSHCertificate `json:"crt"`
  29. }
  30. // SSHRekey is an HTTP handler that reads an RekeySSHRequest with a one-time-token
  31. // (ott) from the body and creates a new SSH certificate with the information in
  32. // the request.
  33. func (h *caHandler) SSHRekey(w http.ResponseWriter, r *http.Request) {
  34. var body SSHRekeyRequest
  35. if err := ReadJSON(r.Body, &body); err != nil {
  36. WriteError(w, errs.BadRequest(errors.Wrap(err, "error reading request body")))
  37. return
  38. }
  39. logOtt(w, body.OTT)
  40. if err := body.Validate(); err != nil {
  41. WriteError(w, errs.BadRequest(err))
  42. return
  43. }
  44. publicKey, err := ssh.ParsePublicKey(body.PublicKey)
  45. if err != nil {
  46. WriteError(w, errs.BadRequest(errors.Wrap(err, "error parsing publicKey")))
  47. return
  48. }
  49. ctx := provisioner.NewContextWithMethod(context.Background(), provisioner.RekeySSHMethod)
  50. signOpts, err := h.Authority.Authorize(ctx, body.OTT)
  51. if err != nil {
  52. WriteError(w, errs.Unauthorized(err))
  53. return
  54. }
  55. oldCert, err := provisioner.ExtractSSHPOPCert(body.OTT)
  56. if err != nil {
  57. WriteError(w, errs.InternalServerError(err))
  58. }
  59. newCert, err := h.Authority.RekeySSH(oldCert, publicKey, signOpts...)
  60. if err != nil {
  61. WriteError(w, errs.Forbidden(err))
  62. return
  63. }
  64. JSONStatus(w, &SSHSignResponse{
  65. Certificate: SSHCertificate{newCert},
  66. }, http.StatusCreated)
  67. }