api.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. package api
  2. import (
  3. "crypto/dsa"
  4. "crypto/ecdsa"
  5. "crypto/rsa"
  6. "crypto/tls"
  7. "crypto/x509"
  8. "encoding/asn1"
  9. "encoding/base64"
  10. "encoding/json"
  11. "encoding/pem"
  12. "fmt"
  13. "net/http"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "github.com/go-chi/chi"
  18. "github.com/pkg/errors"
  19. "github.com/smallstep/certificates/authority"
  20. "github.com/smallstep/certificates/authority/provisioner"
  21. "github.com/smallstep/certificates/logging"
  22. "github.com/smallstep/cli/crypto/tlsutil"
  23. )
  24. // Authority is the interface implemented by a CA authority.
  25. type Authority interface {
  26. Authorize(ott string) ([]provisioner.SignOption, error)
  27. GetTLSOptions() *tlsutil.TLSOptions
  28. Root(shasum string) (*x509.Certificate, error)
  29. Sign(cr *x509.CertificateRequest, signOpts authority.SignOptions, extraOpts ...provisioner.SignOption) (*x509.Certificate, *x509.Certificate, error)
  30. Renew(peer *x509.Certificate) (*x509.Certificate, *x509.Certificate, error)
  31. GetProvisioners(cursor string, limit int) ([]*provisioner.Provisioner, string, error)
  32. GetEncryptedKey(kid string) (string, error)
  33. GetRoots() (federation []*x509.Certificate, err error)
  34. GetFederation() ([]*x509.Certificate, error)
  35. }
  36. // Certificate wraps a *x509.Certificate and adds the json.Marshaler interface.
  37. type Certificate struct {
  38. *x509.Certificate
  39. }
  40. // NewCertificate is a helper method that returns a Certificate from a
  41. // *x509.Certificate.
  42. func NewCertificate(cr *x509.Certificate) Certificate {
  43. return Certificate{
  44. Certificate: cr,
  45. }
  46. }
  47. // MarshalJSON implements the json.Marshaler interface. The certificate is
  48. // quoted string using the PEM encoding.
  49. func (c Certificate) MarshalJSON() ([]byte, error) {
  50. if c.Certificate == nil {
  51. return []byte("null"), nil
  52. }
  53. block := pem.EncodeToMemory(&pem.Block{
  54. Type: "CERTIFICATE",
  55. Bytes: c.Raw,
  56. })
  57. return json.Marshal(string(block))
  58. }
  59. // UnmarshalJSON implements the json.Unmarshaler interface. The certificate is
  60. // expected to be a quoted string using the PEM encoding.
  61. func (c *Certificate) UnmarshalJSON(data []byte) error {
  62. var s string
  63. if err := json.Unmarshal(data, &s); err != nil {
  64. return errors.Wrap(err, "error decoding certificate")
  65. }
  66. block, _ := pem.Decode([]byte(s))
  67. if block == nil {
  68. return errors.New("error decoding certificate")
  69. }
  70. cert, err := x509.ParseCertificate(block.Bytes)
  71. if err != nil {
  72. return errors.Wrap(err, "error decoding certificate")
  73. }
  74. c.Certificate = cert
  75. return nil
  76. }
  77. // CertificateRequest wraps a *x509.CertificateRequest and adds the
  78. // json.Unmarshaler interface.
  79. type CertificateRequest struct {
  80. *x509.CertificateRequest
  81. }
  82. // NewCertificateRequest is a helper method that returns a CertificateRequest
  83. // from a *x509.CertificateRequest.
  84. func NewCertificateRequest(cr *x509.CertificateRequest) CertificateRequest {
  85. return CertificateRequest{
  86. CertificateRequest: cr,
  87. }
  88. }
  89. // MarshalJSON implements the json.Marshaler interface. The certificate request
  90. // is a quoted string using the PEM encoding.
  91. func (c CertificateRequest) MarshalJSON() ([]byte, error) {
  92. if c.CertificateRequest == nil {
  93. return []byte("null"), nil
  94. }
  95. block := pem.EncodeToMemory(&pem.Block{
  96. Type: "CERTIFICATE REQUEST",
  97. Bytes: c.Raw,
  98. })
  99. return json.Marshal(string(block))
  100. }
  101. // UnmarshalJSON implements the json.Unmarshaler interface. The certificate
  102. // request is expected to be a quoted string using the PEM encoding.
  103. func (c *CertificateRequest) UnmarshalJSON(data []byte) error {
  104. var s string
  105. if err := json.Unmarshal(data, &s); err != nil {
  106. return errors.Wrap(err, "error decoding csr")
  107. }
  108. block, _ := pem.Decode([]byte(s))
  109. if block == nil {
  110. return errors.New("error decoding csr")
  111. }
  112. cr, err := x509.ParseCertificateRequest(block.Bytes)
  113. if err != nil {
  114. return errors.Wrap(err, "error decoding csr")
  115. }
  116. c.CertificateRequest = cr
  117. return nil
  118. }
  119. // Router defines a common router interface.
  120. type Router interface {
  121. // MethodFunc adds routes for `pattern` that matches
  122. // the `method` HTTP method.
  123. MethodFunc(method, pattern string, h http.HandlerFunc)
  124. }
  125. // RouterHandler is the interface that a HTTP handler that manages multiple
  126. // endpoints will implement.
  127. type RouterHandler interface {
  128. Route(r Router)
  129. }
  130. // HealthResponse is the response object that returns the health of the server.
  131. type HealthResponse struct {
  132. Status string `json:"status"`
  133. }
  134. // RootResponse is the response object that returns the PEM of a root certificate.
  135. type RootResponse struct {
  136. RootPEM Certificate `json:"ca"`
  137. }
  138. // SignRequest is the request body for a certificate signature request.
  139. type SignRequest struct {
  140. CsrPEM CertificateRequest `json:"csr"`
  141. OTT string `json:"ott"`
  142. NotAfter time.Time `json:"notAfter"`
  143. NotBefore time.Time `json:"notBefore"`
  144. }
  145. // ProvisionersResponse is the response object that returns the list of
  146. // provisioners.
  147. type ProvisionersResponse struct {
  148. Provisioners []*provisioner.Provisioner `json:"provisioners"`
  149. NextCursor string `json:"nextCursor"`
  150. }
  151. // ProvisionerKeyResponse is the response object that returns the encryptoed key
  152. // of a provisioner.
  153. type ProvisionerKeyResponse struct {
  154. Key string `json:"key"`
  155. }
  156. // Validate checks the fields of the SignRequest and returns nil if they are ok
  157. // or an error if something is wrong.
  158. func (s *SignRequest) Validate() error {
  159. if s.CsrPEM.CertificateRequest == nil {
  160. return BadRequest(errors.New("missing csr"))
  161. }
  162. if err := s.CsrPEM.CertificateRequest.CheckSignature(); err != nil {
  163. return BadRequest(errors.Wrap(err, "invalid csr"))
  164. }
  165. if s.OTT == "" {
  166. return BadRequest(errors.New("missing ott"))
  167. }
  168. return nil
  169. }
  170. // SignResponse is the response object of the certificate signature request.
  171. type SignResponse struct {
  172. ServerPEM Certificate `json:"crt"`
  173. CaPEM Certificate `json:"ca"`
  174. TLSOptions *tlsutil.TLSOptions `json:"tlsOptions,omitempty"`
  175. TLS *tls.ConnectionState `json:"-"`
  176. }
  177. // RootsResponse is the response object of the roots request.
  178. type RootsResponse struct {
  179. Certificates []Certificate `json:"crts"`
  180. }
  181. // FederationResponse is the response object of the federation request.
  182. type FederationResponse struct {
  183. Certificates []Certificate `json:"crts"`
  184. }
  185. // caHandler is the type used to implement the different CA HTTP endpoints.
  186. type caHandler struct {
  187. Authority Authority
  188. }
  189. // New creates a new RouterHandler with the CA endpoints.
  190. func New(authority Authority) RouterHandler {
  191. return &caHandler{
  192. Authority: authority,
  193. }
  194. }
  195. func (h *caHandler) Route(r Router) {
  196. r.MethodFunc("GET", "/health", h.Health)
  197. r.MethodFunc("GET", "/root/{sha}", h.Root)
  198. r.MethodFunc("POST", "/sign", h.Sign)
  199. r.MethodFunc("POST", "/renew", h.Renew)
  200. r.MethodFunc("GET", "/provisioners", h.Provisioners)
  201. r.MethodFunc("GET", "/provisioners/{kid}/encrypted-key", h.ProvisionerKey)
  202. r.MethodFunc("GET", "/roots", h.Roots)
  203. r.MethodFunc("GET", "/federation", h.Federation)
  204. // For compatibility with old code:
  205. r.MethodFunc("POST", "/re-sign", h.Renew)
  206. }
  207. // Health is an HTTP handler that returns the status of the server.
  208. func (h *caHandler) Health(w http.ResponseWriter, r *http.Request) {
  209. JSON(w, HealthResponse{Status: "ok"})
  210. }
  211. // Root is an HTTP handler that using the SHA256 from the URL, returns the root
  212. // certificate for the given SHA256.
  213. func (h *caHandler) Root(w http.ResponseWriter, r *http.Request) {
  214. sha := chi.URLParam(r, "sha")
  215. sum := strings.ToLower(strings.Replace(sha, "-", "", -1))
  216. // Load root certificate with the
  217. cert, err := h.Authority.Root(sum)
  218. if err != nil {
  219. WriteError(w, NotFound(errors.Wrapf(err, "%s was not found", r.RequestURI)))
  220. return
  221. }
  222. JSON(w, &RootResponse{RootPEM: Certificate{cert}})
  223. }
  224. // Sign is an HTTP handler that reads a certificate request and an
  225. // one-time-token (ott) from the body and creates a new certificate with the
  226. // information in the certificate request.
  227. func (h *caHandler) Sign(w http.ResponseWriter, r *http.Request) {
  228. var body SignRequest
  229. if err := ReadJSON(r.Body, &body); err != nil {
  230. WriteError(w, BadRequest(errors.Wrap(err, "error reading request body")))
  231. return
  232. }
  233. logOtt(w, body.OTT)
  234. if err := body.Validate(); err != nil {
  235. WriteError(w, err)
  236. return
  237. }
  238. signOpts := authority.SignOptions{
  239. NotBefore: body.NotBefore,
  240. NotAfter: body.NotAfter,
  241. }
  242. extraOpts, err := h.Authority.Authorize(body.OTT)
  243. if err != nil {
  244. WriteError(w, Unauthorized(err))
  245. return
  246. }
  247. cert, root, err := h.Authority.Sign(body.CsrPEM.CertificateRequest, signOpts, extraOpts...)
  248. if err != nil {
  249. WriteError(w, Forbidden(err))
  250. return
  251. }
  252. w.WriteHeader(http.StatusCreated)
  253. logCertificate(w, cert)
  254. JSON(w, &SignResponse{
  255. ServerPEM: Certificate{cert},
  256. CaPEM: Certificate{root},
  257. TLSOptions: h.Authority.GetTLSOptions(),
  258. })
  259. }
  260. // Renew uses the information of certificate in the TLS connection to create a
  261. // new one.
  262. func (h *caHandler) Renew(w http.ResponseWriter, r *http.Request) {
  263. if r.TLS == nil || len(r.TLS.PeerCertificates) == 0 {
  264. WriteError(w, BadRequest(errors.New("missing peer certificate")))
  265. return
  266. }
  267. cert, root, err := h.Authority.Renew(r.TLS.PeerCertificates[0])
  268. if err != nil {
  269. WriteError(w, Forbidden(err))
  270. return
  271. }
  272. w.WriteHeader(http.StatusCreated)
  273. logCertificate(w, cert)
  274. JSON(w, &SignResponse{
  275. ServerPEM: Certificate{cert},
  276. CaPEM: Certificate{root},
  277. TLSOptions: h.Authority.GetTLSOptions(),
  278. })
  279. }
  280. // Provisioners returns the list of provisioners configured in the authority.
  281. func (h *caHandler) Provisioners(w http.ResponseWriter, r *http.Request) {
  282. cursor, limit, err := parseCursor(r)
  283. if err != nil {
  284. WriteError(w, BadRequest(err))
  285. return
  286. }
  287. p, next, err := h.Authority.GetProvisioners(cursor, limit)
  288. if err != nil {
  289. WriteError(w, InternalServerError(err))
  290. return
  291. }
  292. JSON(w, &ProvisionersResponse{
  293. Provisioners: p,
  294. NextCursor: next,
  295. })
  296. }
  297. // ProvisionerKey returns the encrypted key of a provisioner by it's key id.
  298. func (h *caHandler) ProvisionerKey(w http.ResponseWriter, r *http.Request) {
  299. kid := chi.URLParam(r, "kid")
  300. key, err := h.Authority.GetEncryptedKey(kid)
  301. if err != nil {
  302. WriteError(w, NotFound(err))
  303. return
  304. }
  305. JSON(w, &ProvisionerKeyResponse{key})
  306. }
  307. // Roots returns all the root certificates for the CA.
  308. func (h *caHandler) Roots(w http.ResponseWriter, r *http.Request) {
  309. roots, err := h.Authority.GetRoots()
  310. if err != nil {
  311. WriteError(w, Forbidden(err))
  312. return
  313. }
  314. certs := make([]Certificate, len(roots))
  315. for i := range roots {
  316. certs[i] = Certificate{roots[i]}
  317. }
  318. w.WriteHeader(http.StatusCreated)
  319. JSON(w, &RootsResponse{
  320. Certificates: certs,
  321. })
  322. }
  323. // Federation returns all the public certificates in the federation.
  324. func (h *caHandler) Federation(w http.ResponseWriter, r *http.Request) {
  325. federated, err := h.Authority.GetFederation()
  326. if err != nil {
  327. WriteError(w, Forbidden(err))
  328. return
  329. }
  330. certs := make([]Certificate, len(federated))
  331. for i := range federated {
  332. certs[i] = Certificate{federated[i]}
  333. }
  334. w.WriteHeader(http.StatusCreated)
  335. JSON(w, &FederationResponse{
  336. Certificates: certs,
  337. })
  338. }
  339. var oidStepProvisioner = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 37476, 9000, 64, 1}
  340. type stepProvisioner struct {
  341. Type int
  342. Name []byte
  343. CredentialID []byte
  344. }
  345. func logOtt(w http.ResponseWriter, token string) {
  346. if rl, ok := w.(logging.ResponseLogger); ok {
  347. rl.WithFields(map[string]interface{}{
  348. "ott": token,
  349. })
  350. }
  351. }
  352. func logCertificate(w http.ResponseWriter, cert *x509.Certificate) {
  353. if rl, ok := w.(logging.ResponseLogger); ok {
  354. m := map[string]interface{}{
  355. "serial": cert.SerialNumber,
  356. "subject": cert.Subject.CommonName,
  357. "issuer": cert.Issuer.CommonName,
  358. "valid-from": cert.NotBefore.Format(time.RFC3339),
  359. "valid-to": cert.NotAfter.Format(time.RFC3339),
  360. "public-key": fmtPublicKey(cert),
  361. "certificate": base64.StdEncoding.EncodeToString(cert.Raw),
  362. }
  363. for _, ext := range cert.Extensions {
  364. if ext.Id.Equal(oidStepProvisioner) {
  365. val := &stepProvisioner{}
  366. rest, err := asn1.Unmarshal(ext.Value, val)
  367. if err != nil || len(rest) > 0 {
  368. break
  369. }
  370. m["provisioner"] = fmt.Sprintf("%s (%s)", val.Name, val.CredentialID)
  371. break
  372. }
  373. }
  374. rl.WithFields(m)
  375. }
  376. }
  377. func parseCursor(r *http.Request) (cursor string, limit int, err error) {
  378. q := r.URL.Query()
  379. cursor = q.Get("cursor")
  380. if v := q.Get("limit"); len(v) > 0 {
  381. limit, err = strconv.Atoi(v)
  382. if err != nil {
  383. return "", 0, errors.Wrapf(err, "error converting %s to integer", v)
  384. }
  385. }
  386. return
  387. }
  388. // TODO: add support for Ed25519 once it's supported
  389. func fmtPublicKey(cert *x509.Certificate) string {
  390. var params string
  391. switch pk := cert.PublicKey.(type) {
  392. case *ecdsa.PublicKey:
  393. params = pk.Curve.Params().Name
  394. case *rsa.PublicKey:
  395. params = strconv.Itoa(pk.Size() * 8)
  396. case *dsa.PublicKey:
  397. params = strconv.Itoa(pk.Q.BitLen() * 8)
  398. default:
  399. params = "unknown"
  400. }
  401. return fmt.Sprintf("%s %s", cert.PublicKeyAlgorithm, params)
  402. }