4
0

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