sshRekey.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package api
  2. import (
  3. "net/http"
  4. "github.com/pkg/errors"
  5. "github.com/smallstep/certificates/authority/provisioner"
  6. "github.com/smallstep/certificates/errs"
  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. IdentityCertificate []Certificate `json:"identityCrt,omitempty"`
  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.Wrap(http.StatusBadRequest, err, "error reading request body"))
  37. return
  38. }
  39. logOtt(w, body.OTT)
  40. if err := body.Validate(); err != nil {
  41. WriteError(w, errs.BadRequestErr(err))
  42. return
  43. }
  44. publicKey, err := ssh.ParsePublicKey(body.PublicKey)
  45. if err != nil {
  46. WriteError(w, errs.Wrap(http.StatusBadRequest, err, "error parsing publicKey"))
  47. return
  48. }
  49. ctx := provisioner.NewContextWithMethod(r.Context(), provisioner.SSHRekeyMethod)
  50. signOpts, err := h.Authority.Authorize(ctx, body.OTT)
  51. if err != nil {
  52. WriteError(w, errs.UnauthorizedErr(err))
  53. return
  54. }
  55. oldCert, _, err := provisioner.ExtractSSHPOPCert(body.OTT)
  56. if err != nil {
  57. WriteError(w, errs.InternalServerErr(err))
  58. }
  59. newCert, err := h.Authority.RekeySSH(ctx, oldCert, publicKey, signOpts...)
  60. if err != nil {
  61. WriteError(w, errs.ForbiddenErr(err))
  62. return
  63. }
  64. identity, err := h.renewIdentityCertificate(r)
  65. if err != nil {
  66. WriteError(w, errs.ForbiddenErr(err))
  67. return
  68. }
  69. JSONStatus(w, &SSHRekeyResponse{
  70. Certificate: SSHCertificate{newCert},
  71. IdentityCertificate: identity,
  72. }, http.StatusCreated)
  73. }