sshRenew.go 2.3 KB

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