api.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. package api
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "encoding/json"
  6. "encoding/pem"
  7. "net/http"
  8. "strings"
  9. "time"
  10. "github.com/go-chi/chi"
  11. "github.com/pkg/errors"
  12. "github.com/smallstep/cli/crypto/tlsutil"
  13. "github.com/smallstep/cli/crypto/x509util"
  14. )
  15. // Minimum and maximum validity of an end-entity (not root or intermediate) certificate.
  16. // They will be overwritten with the values configured in the authority
  17. var (
  18. minCertDuration = 5 * time.Minute
  19. maxCertDuration = 24 * time.Hour
  20. )
  21. // Claim interface is implemented by types used to validate specific claims in a
  22. // certificate request.
  23. // TODO(mariano): Rename?
  24. type Claim interface {
  25. Valid(cr *x509.CertificateRequest) error
  26. }
  27. // SignOptions contains the options that can be passed to the Authority.Sign
  28. // method.
  29. type SignOptions struct {
  30. NotAfter time.Time `json:"notAfter"`
  31. NotBefore time.Time `json:"notBefore"`
  32. }
  33. // Authority is the interface implemented by a CA authority.
  34. type Authority interface {
  35. Authorize(ott string) ([]Claim, error)
  36. GetTLSOptions() *tlsutil.TLSOptions
  37. GetMinDuration() time.Duration
  38. GetMaxDuration() time.Duration
  39. Root(shasum string) (*x509.Certificate, error)
  40. Sign(cr *x509.CertificateRequest, opts SignOptions, claims ...Claim) (*x509.Certificate, *x509.Certificate, error)
  41. Renew(cert *x509.Certificate) (*x509.Certificate, *x509.Certificate, error)
  42. }
  43. // Certificate wraps a *x509.Certificate and adds the json.Marshaler interface.
  44. type Certificate struct {
  45. *x509.Certificate
  46. }
  47. // NewCertificate is a helper method that returns a Certificate from a
  48. // *x509.Certificate.
  49. func NewCertificate(cr *x509.Certificate) Certificate {
  50. return Certificate{
  51. Certificate: cr,
  52. }
  53. }
  54. // MarshalJSON implements the json.Marshaler interface. The certificate is
  55. // quoted string using the PEM encoding.
  56. func (c Certificate) MarshalJSON() ([]byte, error) {
  57. if c.Certificate == nil {
  58. return []byte("null"), nil
  59. }
  60. block := pem.EncodeToMemory(&pem.Block{
  61. Type: "CERTIFICATE",
  62. Bytes: c.Raw,
  63. })
  64. return json.Marshal(string(block))
  65. }
  66. // UnmarshalJSON implements the json.Unmarshaler interface. The certificate is
  67. // expected to be a quoted string using the PEM encoding.
  68. func (c *Certificate) UnmarshalJSON(data []byte) error {
  69. var s string
  70. if err := json.Unmarshal(data, &s); err != nil {
  71. return errors.Wrap(err, "error decoding certificate")
  72. }
  73. block, _ := pem.Decode([]byte(s))
  74. if block == nil {
  75. return errors.New("error decoding certificate")
  76. }
  77. cert, err := x509.ParseCertificate(block.Bytes)
  78. if err != nil {
  79. return errors.Wrap(err, "error decoding certificate")
  80. }
  81. c.Certificate = cert
  82. return nil
  83. }
  84. // CertificateRequest wraps a *x509.CertificateRequest and adds the
  85. // json.Unmarshaler interface.
  86. type CertificateRequest struct {
  87. *x509.CertificateRequest
  88. }
  89. // NewCertificateRequest is a helper method that returns a CertificateRequest
  90. // from a *x509.CertificateRequest.
  91. func NewCertificateRequest(cr *x509.CertificateRequest) CertificateRequest {
  92. return CertificateRequest{
  93. CertificateRequest: cr,
  94. }
  95. }
  96. // MarshalJSON implements the json.Marshaler interface. The certificate request
  97. // is a quoted string using the PEM encoding.
  98. func (c CertificateRequest) MarshalJSON() ([]byte, error) {
  99. if c.CertificateRequest == nil {
  100. return []byte("null"), nil
  101. }
  102. block := pem.EncodeToMemory(&pem.Block{
  103. Type: "CERTIFICATE REQUEST",
  104. Bytes: c.Raw,
  105. })
  106. return json.Marshal(string(block))
  107. }
  108. // UnmarshalJSON implements the json.Unmarshaler interface. The certificate
  109. // request is expected to be a quoted string using the PEM encoding.
  110. func (c *CertificateRequest) UnmarshalJSON(data []byte) error {
  111. var s string
  112. if err := json.Unmarshal(data, &s); err != nil {
  113. return errors.Wrap(err, "error decoding csr")
  114. }
  115. block, _ := pem.Decode([]byte(s))
  116. if block == nil {
  117. return errors.New("error decoding csr")
  118. }
  119. cr, err := x509.ParseCertificateRequest(block.Bytes)
  120. if err != nil {
  121. return errors.Wrap(err, "error decoding csr")
  122. }
  123. c.CertificateRequest = cr
  124. return nil
  125. }
  126. // Router defines a common router interface.
  127. type Router interface {
  128. // MethodFunc adds routes for `pattern` that matches
  129. // the `method` HTTP method.
  130. MethodFunc(method, pattern string, h http.HandlerFunc)
  131. }
  132. // RouterHandler is the interface that a HTTP handler that manages multiple
  133. // endpoints will implement.
  134. type RouterHandler interface {
  135. Route(r Router)
  136. }
  137. // HealthResponse is the response object that returns the health of the server.
  138. type HealthResponse struct {
  139. Status string `json:"status"`
  140. }
  141. // RootResponse is the response object that returns the PEM of a root certificate.
  142. type RootResponse struct {
  143. RootPEM Certificate `json:"ca"`
  144. }
  145. // SignRequest is the request body for a certificate signature request.
  146. type SignRequest struct {
  147. CsrPEM CertificateRequest `json:"csr"`
  148. OTT string `json:"ott"`
  149. NotAfter time.Time `json:"notAfter"`
  150. NotBefore time.Time `json:"notBefore"`
  151. }
  152. // Validate checks the fields of the SignRequest and returns nil if they are ok
  153. // or an error if something is wrong.
  154. func (s *SignRequest) Validate() error {
  155. if s.CsrPEM.CertificateRequest == nil {
  156. return BadRequest(errors.New("missing csr"))
  157. }
  158. if err := s.CsrPEM.CertificateRequest.CheckSignature(); err != nil {
  159. return BadRequest(errors.Wrap(err, "invalid csr"))
  160. }
  161. if s.OTT == "" {
  162. return BadRequest(errors.New("missing ott"))
  163. }
  164. now := time.Now()
  165. if s.NotBefore.IsZero() {
  166. s.NotBefore = now
  167. }
  168. if s.NotAfter.IsZero() {
  169. s.NotAfter = now.Add(x509util.DefaultCertValidity)
  170. }
  171. if s.NotAfter.Before(now) {
  172. return BadRequest(errors.New("notAfter < now"))
  173. }
  174. if s.NotAfter.Before(s.NotBefore) {
  175. return BadRequest(errors.New("notAfter < notBefore"))
  176. }
  177. requestedDuration := s.NotAfter.Sub(s.NotBefore)
  178. if requestedDuration < minCertDuration {
  179. return BadRequest(errors.New("requested certificate validity duration is too short"))
  180. }
  181. if requestedDuration > maxCertDuration {
  182. return BadRequest(errors.New("requested certificate validity duration is too long"))
  183. }
  184. return nil
  185. }
  186. // SignResponse is the response object of the certificate signature request.
  187. type SignResponse struct {
  188. ServerPEM Certificate `json:"crt"`
  189. CaPEM Certificate `json:"ca"`
  190. TLSOptions *tlsutil.TLSOptions `json:"tlsOptions,omitempty"`
  191. TLS *tls.ConnectionState `json:"-"`
  192. }
  193. // caHandler is the type used to implement the different CA HTTP endpoints.
  194. type caHandler struct {
  195. Authority Authority
  196. }
  197. // New creates a new RouterHandler with the CA endpoints.
  198. func New(authority Authority) RouterHandler {
  199. minCertDuration = authority.GetMinDuration()
  200. maxCertDuration = authority.GetMaxDuration()
  201. return &caHandler{
  202. Authority: authority,
  203. }
  204. }
  205. func (h *caHandler) Route(r Router) {
  206. r.MethodFunc("GET", "/health", h.Health)
  207. r.MethodFunc("GET", "/root/{sha}", h.Root)
  208. r.MethodFunc("POST", "/sign", h.Sign)
  209. r.MethodFunc("POST", "/renew", h.Renew)
  210. }
  211. // Health is an HTTP handler that returns the status of the server.
  212. func (h *caHandler) Health(w http.ResponseWriter, r *http.Request) {
  213. JSON(w, HealthResponse{Status: "ok"})
  214. }
  215. // Root is an HTTP handler that using the SHA256 from the URL, returns the root
  216. // certificate for the given SHA256.
  217. func (h *caHandler) Root(w http.ResponseWriter, r *http.Request) {
  218. sha := chi.URLParam(r, "sha")
  219. sum := strings.ToLower(strings.Replace(sha, "-", "", -1))
  220. // Load root certificate with the
  221. cert, err := h.Authority.Root(sum)
  222. if err != nil {
  223. WriteError(w, NotFound(errors.Wrapf(err, "%s was not found", r.RequestURI)))
  224. return
  225. }
  226. JSON(w, &RootResponse{RootPEM: Certificate{cert}})
  227. }
  228. // Sign is an HTTP handler that reads a certificate request and an
  229. // one-time-token (ott) from the body and creates a new certificate with the
  230. // information in the certificate request.
  231. func (h *caHandler) Sign(w http.ResponseWriter, r *http.Request) {
  232. var body SignRequest
  233. if err := ReadJSON(r.Body, &body); err != nil {
  234. WriteError(w, BadRequest(errors.Wrap(err, "error reading request body")))
  235. return
  236. }
  237. if err := body.Validate(); err != nil {
  238. WriteError(w, err)
  239. return
  240. }
  241. claims, err := h.Authority.Authorize(body.OTT)
  242. if err != nil {
  243. WriteError(w, Unauthorized(err))
  244. return
  245. }
  246. opts := SignOptions{
  247. NotBefore: body.NotBefore,
  248. NotAfter: body.NotAfter,
  249. }
  250. cert, root, err := h.Authority.Sign(body.CsrPEM.CertificateRequest, opts, claims...)
  251. if err != nil {
  252. WriteError(w, Forbidden(err))
  253. return
  254. }
  255. w.WriteHeader(http.StatusCreated)
  256. JSON(w, &SignResponse{
  257. ServerPEM: Certificate{cert},
  258. CaPEM: Certificate{root},
  259. TLSOptions: h.Authority.GetTLSOptions(),
  260. })
  261. }
  262. // Renew uses the information of certificate in the TLS connection to create a
  263. // new one.
  264. func (h *caHandler) Renew(w http.ResponseWriter, r *http.Request) {
  265. if r.TLS == nil || len(r.TLS.PeerCertificates) == 0 {
  266. WriteError(w, BadRequest(errors.New("missing peer certificate")))
  267. return
  268. }
  269. cert, root, err := h.Authority.Renew(r.TLS.PeerCertificates[0])
  270. if err != nil {
  271. WriteError(w, Forbidden(err))
  272. return
  273. }
  274. w.WriteHeader(http.StatusCreated)
  275. JSON(w, &SignResponse{
  276. ServerPEM: Certificate{cert},
  277. CaPEM: Certificate{root},
  278. TLSOptions: h.Authority.GetTLSOptions(),
  279. })
  280. }