4
0

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