sshRekey.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. IdentityCertificate []Certificate `json:"identityCrt,omitempty"`
  30. }
  31. // SSHRekey is an HTTP handler that reads an RekeySSHRequest with a one-time-token
  32. // (ott) from the body and creates a new SSH certificate with the information in
  33. // the request.
  34. func (h *caHandler) SSHRekey(w http.ResponseWriter, r *http.Request) {
  35. var body SSHRekeyRequest
  36. if err := ReadJSON(r.Body, &body); err != nil {
  37. WriteError(w, errs.Wrap(http.StatusBadRequest, err, "error reading request body"))
  38. return
  39. }
  40. logOtt(w, body.OTT)
  41. if err := body.Validate(); err != nil {
  42. WriteError(w, errs.BadRequestErr(err))
  43. return
  44. }
  45. publicKey, err := ssh.ParsePublicKey(body.PublicKey)
  46. if err != nil {
  47. WriteError(w, errs.Wrap(http.StatusBadRequest, err, "error parsing publicKey"))
  48. return
  49. }
  50. ctx := provisioner.NewContextWithMethod(context.Background(), provisioner.SSHRekeyMethod)
  51. signOpts, err := h.Authority.Authorize(ctx, body.OTT)
  52. if err != nil {
  53. WriteError(w, errs.UnauthorizedErr(err))
  54. return
  55. }
  56. oldCert, _, err := provisioner.ExtractSSHPOPCert(body.OTT)
  57. if err != nil {
  58. WriteError(w, errs.InternalServerErr(err))
  59. }
  60. newCert, err := h.Authority.RekeySSH(oldCert, publicKey, signOpts...)
  61. if err != nil {
  62. WriteError(w, errs.ForbiddenErr(err))
  63. return
  64. }
  65. identity, err := h.renewIdentityCertificate(r)
  66. if err != nil {
  67. WriteError(w, errs.ForbiddenErr(err))
  68. return
  69. }
  70. JSONStatus(w, &SSHRekeyResponse{
  71. Certificate: SSHCertificate{newCert},
  72. IdentityCertificate: identity,
  73. }, http.StatusCreated)
  74. }