api.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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/certificates/authority"
  14. "github.com/smallstep/cli/crypto/tlsutil"
  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(cursor string, limit int) ([]*authority.Provisioner, string, error)
  24. GetEncryptedKey(kid string) (string, error)
  25. GetFederation(cert *x509.Certificate) ([]*x509.Certificate, 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. // ProvisionerKeyResponse is the response object that returns the encryptoed key
  143. // of a provisioner.
  144. type ProvisionerKeyResponse struct {
  145. Key string `json:"key"`
  146. }
  147. // Validate checks the fields of the SignRequest and returns nil if they are ok
  148. // or an error if something is wrong.
  149. func (s *SignRequest) Validate() error {
  150. if s.CsrPEM.CertificateRequest == nil {
  151. return BadRequest(errors.New("missing csr"))
  152. }
  153. if err := s.CsrPEM.CertificateRequest.CheckSignature(); err != nil {
  154. return BadRequest(errors.Wrap(err, "invalid csr"))
  155. }
  156. if s.OTT == "" {
  157. return BadRequest(errors.New("missing ott"))
  158. }
  159. return nil
  160. }
  161. // SignResponse is the response object of the certificate signature request.
  162. type SignResponse struct {
  163. ServerPEM Certificate `json:"crt"`
  164. CaPEM Certificate `json:"ca"`
  165. TLSOptions *tlsutil.TLSOptions `json:"tlsOptions,omitempty"`
  166. TLS *tls.ConnectionState `json:"-"`
  167. }
  168. // FederationResponse is the response object of the federation request.
  169. type FederationResponse struct {
  170. Certificates []Certificate `json:"crts"`
  171. }
  172. // caHandler is the type used to implement the different CA HTTP endpoints.
  173. type caHandler struct {
  174. Authority Authority
  175. }
  176. // New creates a new RouterHandler with the CA endpoints.
  177. func New(authority Authority) RouterHandler {
  178. return &caHandler{
  179. Authority: authority,
  180. }
  181. }
  182. func (h *caHandler) Route(r Router) {
  183. r.MethodFunc("GET", "/health", h.Health)
  184. r.MethodFunc("GET", "/root/{sha}", h.Root)
  185. r.MethodFunc("POST", "/sign", h.Sign)
  186. r.MethodFunc("POST", "/renew", h.Renew)
  187. r.MethodFunc("GET", "/provisioners", h.Provisioners)
  188. r.MethodFunc("GET", "/provisioners/{kid}/encrypted-key", h.ProvisionerKey)
  189. r.MethodFunc("GET", "/federation", h.Federation)
  190. // For compatibility with old code:
  191. r.MethodFunc("POST", "/re-sign", h.Renew)
  192. }
  193. // Health is an HTTP handler that returns the status of the server.
  194. func (h *caHandler) Health(w http.ResponseWriter, r *http.Request) {
  195. JSON(w, HealthResponse{Status: "ok"})
  196. }
  197. // Root is an HTTP handler that using the SHA256 from the URL, returns the root
  198. // certificate for the given SHA256.
  199. func (h *caHandler) Root(w http.ResponseWriter, r *http.Request) {
  200. sha := chi.URLParam(r, "sha")
  201. sum := strings.ToLower(strings.Replace(sha, "-", "", -1))
  202. // Load root certificate with the
  203. cert, err := h.Authority.Root(sum)
  204. if err != nil {
  205. WriteError(w, NotFound(errors.Wrapf(err, "%s was not found", r.RequestURI)))
  206. return
  207. }
  208. JSON(w, &RootResponse{RootPEM: Certificate{cert}})
  209. }
  210. // Sign is an HTTP handler that reads a certificate request and an
  211. // one-time-token (ott) from the body and creates a new certificate with the
  212. // information in the certificate request.
  213. func (h *caHandler) Sign(w http.ResponseWriter, r *http.Request) {
  214. var body SignRequest
  215. if err := ReadJSON(r.Body, &body); err != nil {
  216. WriteError(w, BadRequest(errors.Wrap(err, "error reading request body")))
  217. return
  218. }
  219. if err := body.Validate(); err != nil {
  220. WriteError(w, err)
  221. return
  222. }
  223. signOpts := authority.SignOptions{
  224. NotBefore: body.NotBefore,
  225. NotAfter: body.NotAfter,
  226. }
  227. extraOpts, err := h.Authority.Authorize(body.OTT)
  228. if err != nil {
  229. WriteError(w, Unauthorized(err))
  230. return
  231. }
  232. cert, root, err := h.Authority.Sign(body.CsrPEM.CertificateRequest, signOpts, extraOpts...)
  233. if err != nil {
  234. WriteError(w, Forbidden(err))
  235. return
  236. }
  237. w.WriteHeader(http.StatusCreated)
  238. JSON(w, &SignResponse{
  239. ServerPEM: Certificate{cert},
  240. CaPEM: Certificate{root},
  241. TLSOptions: h.Authority.GetTLSOptions(),
  242. })
  243. }
  244. // Renew uses the information of certificate in the TLS connection to create a
  245. // new one.
  246. func (h *caHandler) Renew(w http.ResponseWriter, r *http.Request) {
  247. if r.TLS == nil || len(r.TLS.PeerCertificates) == 0 {
  248. WriteError(w, BadRequest(errors.New("missing peer certificate")))
  249. return
  250. }
  251. cert, root, err := h.Authority.Renew(r.TLS.PeerCertificates[0])
  252. if err != nil {
  253. WriteError(w, Forbidden(err))
  254. return
  255. }
  256. w.WriteHeader(http.StatusCreated)
  257. JSON(w, &SignResponse{
  258. ServerPEM: Certificate{cert},
  259. CaPEM: Certificate{root},
  260. TLSOptions: h.Authority.GetTLSOptions(),
  261. })
  262. }
  263. // Provisioners returns the list of provisioners configured in the authority.
  264. func (h *caHandler) Provisioners(w http.ResponseWriter, r *http.Request) {
  265. cursor, limit, err := parseCursor(r)
  266. if err != nil {
  267. WriteError(w, BadRequest(err))
  268. return
  269. }
  270. p, next, err := h.Authority.GetProvisioners(cursor, limit)
  271. if err != nil {
  272. WriteError(w, InternalServerError(err))
  273. return
  274. }
  275. JSON(w, &ProvisionersResponse{
  276. Provisioners: p,
  277. NextCursor: next,
  278. })
  279. }
  280. // ProvisionerKey returns the encrypted key of a provisioner by it's key id.
  281. func (h *caHandler) ProvisionerKey(w http.ResponseWriter, r *http.Request) {
  282. kid := chi.URLParam(r, "kid")
  283. key, err := h.Authority.GetEncryptedKey(kid)
  284. if err != nil {
  285. WriteError(w, NotFound(err))
  286. return
  287. }
  288. JSON(w, &ProvisionerKeyResponse{key})
  289. }
  290. // Federation returns all the public certificates in the federation.
  291. func (h *caHandler) Federation(w http.ResponseWriter, r *http.Request) {
  292. if r.TLS == nil || len(r.TLS.PeerCertificates) == 0 {
  293. WriteError(w, BadRequest(errors.New("missing peer certificate")))
  294. return
  295. }
  296. federated, err := h.Authority.GetFederation(r.TLS.PeerCertificates[0])
  297. if err != nil {
  298. WriteError(w, Forbidden(err))
  299. return
  300. }
  301. certs := make([]Certificate, len(federated))
  302. for i := range federated {
  303. certs[i] = Certificate{federated[i]}
  304. }
  305. w.WriteHeader(http.StatusCreated)
  306. JSON(w, &FederationResponse{
  307. Certificates: certs,
  308. })
  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. }