api.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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/provisioner"
  20. "github.com/smallstep/certificates/logging"
  21. "github.com/smallstep/cli/crypto/tlsutil"
  22. )
  23. // Authority is the interface implemented by a CA authority.
  24. type Authority interface {
  25. Authorize(ott string) ([]provisioner.SignOption, error)
  26. GetTLSOptions() *tlsutil.TLSOptions
  27. Root(shasum string) (*x509.Certificate, error)
  28. Sign(cr *x509.CertificateRequest, opts provisioner.Options, signOpts ...provisioner.SignOption) (*x509.Certificate, *x509.Certificate, error)
  29. Renew(peer *x509.Certificate) (*x509.Certificate, *x509.Certificate, error)
  30. GetProvisioners(cursor string, limit int) (provisioner.List, string, error)
  31. GetEncryptedKey(kid string) (string, error)
  32. GetRoots() (federation []*x509.Certificate, err error)
  33. GetFederation() ([]*x509.Certificate, error)
  34. }
  35. // TimeDuration is an alias of provisioner.TimeDuration
  36. type TimeDuration = provisioner.TimeDuration
  37. // NewTimeDuration returns a TimeDuration with the defined time.
  38. func NewTimeDuration(t time.Time) TimeDuration {
  39. return provisioner.NewTimeDuration(t)
  40. }
  41. // ParseTimeDuration returns a new TimeDuration parsing the RFC 3339 time or
  42. // time.Duration string.
  43. func ParseTimeDuration(s string) (TimeDuration, error) {
  44. return provisioner.ParseTimeDuration(s)
  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 TimeDuration `json:"notAfter"`
  153. NotBefore TimeDuration `json:"notBefore"`
  154. }
  155. // ProvisionersResponse is the response object that returns the list of
  156. // provisioners.
  157. type ProvisionersResponse struct {
  158. Provisioners provisioner.List `json:"provisioners"`
  159. NextCursor string `json:"nextCursor"`
  160. }
  161. // ProvisionerKeyResponse is the response object that returns the encrypted key
  162. // of a provisioner.
  163. type ProvisionerKeyResponse struct {
  164. Key string `json:"key"`
  165. }
  166. // Validate checks the fields of the SignRequest and returns nil if they are ok
  167. // or an error if something is wrong.
  168. func (s *SignRequest) Validate() error {
  169. if s.CsrPEM.CertificateRequest == nil {
  170. return BadRequest(errors.New("missing csr"))
  171. }
  172. if err := s.CsrPEM.CertificateRequest.CheckSignature(); err != nil {
  173. return BadRequest(errors.Wrap(err, "invalid csr"))
  174. }
  175. if s.OTT == "" {
  176. return BadRequest(errors.New("missing ott"))
  177. }
  178. return nil
  179. }
  180. // SignResponse is the response object of the certificate signature request.
  181. type SignResponse struct {
  182. ServerPEM Certificate `json:"crt"`
  183. CaPEM Certificate `json:"ca"`
  184. TLSOptions *tlsutil.TLSOptions `json:"tlsOptions,omitempty"`
  185. TLS *tls.ConnectionState `json:"-"`
  186. }
  187. // RootsResponse is the response object of the roots request.
  188. type RootsResponse struct {
  189. Certificates []Certificate `json:"crts"`
  190. }
  191. // FederationResponse is the response object of the federation request.
  192. type FederationResponse struct {
  193. Certificates []Certificate `json:"crts"`
  194. }
  195. // caHandler is the type used to implement the different CA HTTP endpoints.
  196. type caHandler struct {
  197. Authority Authority
  198. }
  199. // New creates a new RouterHandler with the CA endpoints.
  200. func New(authority Authority) RouterHandler {
  201. return &caHandler{
  202. Authority: authority,
  203. }
  204. }
  205. func (h *caHandler) Route(r Router) {
  206. r.MethodFunc("GET", "/health", h.Health)
  207. r.MethodFunc("GET", "/root/{sha}", h.Root)
  208. r.MethodFunc("POST", "/sign", h.Sign)
  209. r.MethodFunc("POST", "/renew", h.Renew)
  210. r.MethodFunc("GET", "/provisioners", h.Provisioners)
  211. r.MethodFunc("GET", "/provisioners/{kid}/encrypted-key", h.ProvisionerKey)
  212. r.MethodFunc("GET", "/roots", h.Roots)
  213. r.MethodFunc("GET", "/federation", h.Federation)
  214. // For compatibility with old code:
  215. r.MethodFunc("POST", "/re-sign", h.Renew)
  216. }
  217. // Health is an HTTP handler that returns the status of the server.
  218. func (h *caHandler) Health(w http.ResponseWriter, r *http.Request) {
  219. JSON(w, HealthResponse{Status: "ok"})
  220. }
  221. // Root is an HTTP handler that using the SHA256 from the URL, returns the root
  222. // certificate for the given SHA256.
  223. func (h *caHandler) Root(w http.ResponseWriter, r *http.Request) {
  224. sha := chi.URLParam(r, "sha")
  225. sum := strings.ToLower(strings.Replace(sha, "-", "", -1))
  226. // Load root certificate with the
  227. cert, err := h.Authority.Root(sum)
  228. if err != nil {
  229. WriteError(w, NotFound(errors.Wrapf(err, "%s was not found", r.RequestURI)))
  230. return
  231. }
  232. JSON(w, &RootResponse{RootPEM: Certificate{cert}})
  233. }
  234. // Sign is an HTTP handler that reads a certificate request and an
  235. // one-time-token (ott) from the body and creates a new certificate with the
  236. // information in the certificate request.
  237. func (h *caHandler) Sign(w http.ResponseWriter, r *http.Request) {
  238. var body SignRequest
  239. if err := ReadJSON(r.Body, &body); err != nil {
  240. WriteError(w, BadRequest(errors.Wrap(err, "error reading request body")))
  241. return
  242. }
  243. logOtt(w, body.OTT)
  244. if err := body.Validate(); err != nil {
  245. WriteError(w, err)
  246. return
  247. }
  248. opts := provisioner.Options{
  249. NotBefore: body.NotBefore,
  250. NotAfter: body.NotAfter,
  251. }
  252. signOpts, err := h.Authority.Authorize(body.OTT)
  253. if err != nil {
  254. WriteError(w, Unauthorized(err))
  255. return
  256. }
  257. cert, root, err := h.Authority.Sign(body.CsrPEM.CertificateRequest, opts, signOpts...)
  258. if err != nil {
  259. WriteError(w, Forbidden(err))
  260. return
  261. }
  262. w.WriteHeader(http.StatusCreated)
  263. logCertificate(w, cert)
  264. JSON(w, &SignResponse{
  265. ServerPEM: Certificate{cert},
  266. CaPEM: Certificate{root},
  267. TLSOptions: h.Authority.GetTLSOptions(),
  268. })
  269. }
  270. // Renew uses the information of certificate in the TLS connection to create a
  271. // new one.
  272. func (h *caHandler) Renew(w http.ResponseWriter, r *http.Request) {
  273. if r.TLS == nil || len(r.TLS.PeerCertificates) == 0 {
  274. WriteError(w, BadRequest(errors.New("missing peer certificate")))
  275. return
  276. }
  277. cert, root, err := h.Authority.Renew(r.TLS.PeerCertificates[0])
  278. if err != nil {
  279. WriteError(w, Forbidden(err))
  280. return
  281. }
  282. w.WriteHeader(http.StatusCreated)
  283. logCertificate(w, cert)
  284. JSON(w, &SignResponse{
  285. ServerPEM: Certificate{cert},
  286. CaPEM: Certificate{root},
  287. TLSOptions: h.Authority.GetTLSOptions(),
  288. })
  289. }
  290. // Provisioners returns the list of provisioners configured in the authority.
  291. func (h *caHandler) Provisioners(w http.ResponseWriter, r *http.Request) {
  292. cursor, limit, err := parseCursor(r)
  293. if err != nil {
  294. WriteError(w, BadRequest(err))
  295. return
  296. }
  297. p, next, err := h.Authority.GetProvisioners(cursor, limit)
  298. if err != nil {
  299. WriteError(w, InternalServerError(err))
  300. return
  301. }
  302. JSON(w, &ProvisionersResponse{
  303. Provisioners: p,
  304. NextCursor: next,
  305. })
  306. }
  307. // ProvisionerKey returns the encrypted key of a provisioner by it's key id.
  308. func (h *caHandler) ProvisionerKey(w http.ResponseWriter, r *http.Request) {
  309. kid := chi.URLParam(r, "kid")
  310. key, err := h.Authority.GetEncryptedKey(kid)
  311. if err != nil {
  312. WriteError(w, NotFound(err))
  313. return
  314. }
  315. JSON(w, &ProvisionerKeyResponse{key})
  316. }
  317. // Roots returns all the root certificates for the CA.
  318. func (h *caHandler) Roots(w http.ResponseWriter, r *http.Request) {
  319. roots, err := h.Authority.GetRoots()
  320. if err != nil {
  321. WriteError(w, Forbidden(err))
  322. return
  323. }
  324. certs := make([]Certificate, len(roots))
  325. for i := range roots {
  326. certs[i] = Certificate{roots[i]}
  327. }
  328. w.WriteHeader(http.StatusCreated)
  329. JSON(w, &RootsResponse{
  330. Certificates: certs,
  331. })
  332. }
  333. // Federation returns all the public certificates in the federation.
  334. func (h *caHandler) Federation(w http.ResponseWriter, r *http.Request) {
  335. federated, err := h.Authority.GetFederation()
  336. if err != nil {
  337. WriteError(w, Forbidden(err))
  338. return
  339. }
  340. certs := make([]Certificate, len(federated))
  341. for i := range federated {
  342. certs[i] = Certificate{federated[i]}
  343. }
  344. w.WriteHeader(http.StatusCreated)
  345. JSON(w, &FederationResponse{
  346. Certificates: certs,
  347. })
  348. }
  349. var oidStepProvisioner = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 37476, 9000, 64, 1}
  350. type stepProvisioner struct {
  351. Type int
  352. Name []byte
  353. CredentialID []byte
  354. }
  355. func logOtt(w http.ResponseWriter, token string) {
  356. if rl, ok := w.(logging.ResponseLogger); ok {
  357. rl.WithFields(map[string]interface{}{
  358. "ott": token,
  359. })
  360. }
  361. }
  362. func logCertificate(w http.ResponseWriter, cert *x509.Certificate) {
  363. if rl, ok := w.(logging.ResponseLogger); ok {
  364. m := map[string]interface{}{
  365. "serial": cert.SerialNumber,
  366. "subject": cert.Subject.CommonName,
  367. "issuer": cert.Issuer.CommonName,
  368. "valid-from": cert.NotBefore.Format(time.RFC3339),
  369. "valid-to": cert.NotAfter.Format(time.RFC3339),
  370. "public-key": fmtPublicKey(cert),
  371. "certificate": base64.StdEncoding.EncodeToString(cert.Raw),
  372. }
  373. for _, ext := range cert.Extensions {
  374. if ext.Id.Equal(oidStepProvisioner) {
  375. val := &stepProvisioner{}
  376. rest, err := asn1.Unmarshal(ext.Value, val)
  377. if err != nil || len(rest) > 0 {
  378. break
  379. }
  380. m["provisioner"] = fmt.Sprintf("%s (%s)", val.Name, val.CredentialID)
  381. break
  382. }
  383. }
  384. rl.WithFields(m)
  385. }
  386. }
  387. func parseCursor(r *http.Request) (cursor string, limit int, err error) {
  388. q := r.URL.Query()
  389. cursor = q.Get("cursor")
  390. if v := q.Get("limit"); len(v) > 0 {
  391. limit, err = strconv.Atoi(v)
  392. if err != nil {
  393. return "", 0, errors.Wrapf(err, "error converting %s to integer", v)
  394. }
  395. }
  396. return
  397. }
  398. // TODO: add support for Ed25519 once it's supported
  399. func fmtPublicKey(cert *x509.Certificate) string {
  400. var params string
  401. switch pk := cert.PublicKey.(type) {
  402. case *ecdsa.PublicKey:
  403. params = pk.Curve.Params().Name
  404. case *rsa.PublicKey:
  405. params = strconv.Itoa(pk.Size() * 8)
  406. case *dsa.PublicKey:
  407. params = strconv.Itoa(pk.Q.BitLen() * 8)
  408. default:
  409. params = "unknown"
  410. }
  411. return fmt.Sprintf("%s %s", cert.PublicKeyAlgorithm, params)
  412. }