api.go 11 KB

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