api.go 9.7 KB

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