api.go 13 KB

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