api.go 10 KB

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