api.go 13 KB

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