4
0

sshRenew.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. )
  8. // SSHRenewRequest is the request body of an SSH certificate request.
  9. type SSHRenewRequest struct {
  10. OTT string `json:"ott"`
  11. }
  12. // Validate validates the SSHSignRequest.
  13. func (s *SSHRenewRequest) Validate() error {
  14. switch {
  15. case len(s.OTT) == 0:
  16. return errors.New("missing or empty ott")
  17. default:
  18. return nil
  19. }
  20. }
  21. // SSHRenewResponse is the response object that returns the SSH certificate.
  22. type SSHRenewResponse struct {
  23. Certificate SSHCertificate `json:"crt"`
  24. IdentityCertificate []Certificate `json:"identityCrt,omitempty"`
  25. }
  26. // SSHRenew is an HTTP handler that reads an RenewSSHRequest with a one-time-token
  27. // (ott) from the body and creates a new SSH certificate with the information in
  28. // the request.
  29. func (h *caHandler) SSHRenew(w http.ResponseWriter, r *http.Request) {
  30. var body SSHRenewRequest
  31. if err := ReadJSON(r.Body, &body); err != nil {
  32. WriteError(w, errs.Wrap(http.StatusBadRequest, err, "error reading request body"))
  33. return
  34. }
  35. logOtt(w, body.OTT)
  36. if err := body.Validate(); err != nil {
  37. WriteError(w, errs.BadRequestErr(err))
  38. return
  39. }
  40. ctx := provisioner.NewContextWithMethod(r.Context(), provisioner.SSHRenewMethod)
  41. _, err := h.Authority.Authorize(ctx, body.OTT)
  42. if err != nil {
  43. WriteError(w, errs.UnauthorizedErr(err))
  44. return
  45. }
  46. oldCert, _, err := provisioner.ExtractSSHPOPCert(body.OTT)
  47. if err != nil {
  48. WriteError(w, errs.InternalServerErr(err))
  49. }
  50. newCert, err := h.Authority.RenewSSH(ctx, oldCert)
  51. if err != nil {
  52. WriteError(w, errs.ForbiddenErr(err))
  53. return
  54. }
  55. identity, err := h.renewIdentityCertificate(r)
  56. if err != nil {
  57. WriteError(w, errs.ForbiddenErr(err))
  58. return
  59. }
  60. JSONStatus(w, &SSHSignResponse{
  61. Certificate: SSHCertificate{newCert},
  62. IdentityCertificate: identity,
  63. }, http.StatusCreated)
  64. }
  65. // renewIdentityCertificate request the client TLS certificate if present.
  66. func (h *caHandler) renewIdentityCertificate(r *http.Request) ([]Certificate, error) {
  67. if r.TLS == nil || len(r.TLS.PeerCertificates) == 0 {
  68. return nil, nil
  69. }
  70. certChain, err := h.Authority.Renew(r.TLS.PeerCertificates[0])
  71. if err != nil {
  72. return nil, err
  73. }
  74. return certChainToPEM(certChain), nil
  75. }