api.go 9.5 KB

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