api.go 10 KB

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