api.go 13 KB

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