api.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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. if err := body.Validate(); err != nil {
  233. WriteError(w, err)
  234. return
  235. }
  236. signOpts := authority.SignOptions{
  237. NotBefore: body.NotBefore,
  238. NotAfter: body.NotAfter,
  239. }
  240. extraOpts, err := h.Authority.Authorize(body.OTT)
  241. if err != nil {
  242. WriteError(w, Unauthorized(err))
  243. return
  244. }
  245. cert, root, err := h.Authority.Sign(body.CsrPEM.CertificateRequest, signOpts, extraOpts...)
  246. if err != nil {
  247. WriteError(w, Forbidden(err))
  248. return
  249. }
  250. w.WriteHeader(http.StatusCreated)
  251. logCertificate(w, cert, body.OTT)
  252. JSON(w, &SignResponse{
  253. ServerPEM: Certificate{cert},
  254. CaPEM: Certificate{root},
  255. TLSOptions: h.Authority.GetTLSOptions(),
  256. })
  257. }
  258. // Renew uses the information of certificate in the TLS connection to create a
  259. // new one.
  260. func (h *caHandler) Renew(w http.ResponseWriter, r *http.Request) {
  261. if r.TLS == nil || len(r.TLS.PeerCertificates) == 0 {
  262. WriteError(w, BadRequest(errors.New("missing peer certificate")))
  263. return
  264. }
  265. cert, root, err := h.Authority.Renew(r.TLS.PeerCertificates[0])
  266. if err != nil {
  267. WriteError(w, Forbidden(err))
  268. return
  269. }
  270. w.WriteHeader(http.StatusCreated)
  271. logCertificate(w, cert, "")
  272. JSON(w, &SignResponse{
  273. ServerPEM: Certificate{cert},
  274. CaPEM: Certificate{root},
  275. TLSOptions: h.Authority.GetTLSOptions(),
  276. })
  277. }
  278. // Provisioners returns the list of provisioners configured in the authority.
  279. func (h *caHandler) Provisioners(w http.ResponseWriter, r *http.Request) {
  280. cursor, limit, err := parseCursor(r)
  281. if err != nil {
  282. WriteError(w, BadRequest(err))
  283. return
  284. }
  285. p, next, err := h.Authority.GetProvisioners(cursor, limit)
  286. if err != nil {
  287. WriteError(w, InternalServerError(err))
  288. return
  289. }
  290. JSON(w, &ProvisionersResponse{
  291. Provisioners: p,
  292. NextCursor: next,
  293. })
  294. }
  295. // ProvisionerKey returns the encrypted key of a provisioner by it's key id.
  296. func (h *caHandler) ProvisionerKey(w http.ResponseWriter, r *http.Request) {
  297. kid := chi.URLParam(r, "kid")
  298. key, err := h.Authority.GetEncryptedKey(kid)
  299. if err != nil {
  300. WriteError(w, NotFound(err))
  301. return
  302. }
  303. JSON(w, &ProvisionerKeyResponse{key})
  304. }
  305. // Roots returns all the root certificates for the CA.
  306. func (h *caHandler) Roots(w http.ResponseWriter, r *http.Request) {
  307. roots, err := h.Authority.GetRoots()
  308. if err != nil {
  309. WriteError(w, Forbidden(err))
  310. return
  311. }
  312. certs := make([]Certificate, len(roots))
  313. for i := range roots {
  314. certs[i] = Certificate{roots[i]}
  315. }
  316. w.WriteHeader(http.StatusCreated)
  317. JSON(w, &RootsResponse{
  318. Certificates: certs,
  319. })
  320. }
  321. // Federation returns all the public certificates in the federation.
  322. func (h *caHandler) Federation(w http.ResponseWriter, r *http.Request) {
  323. federated, err := h.Authority.GetFederation()
  324. if err != nil {
  325. WriteError(w, Forbidden(err))
  326. return
  327. }
  328. certs := make([]Certificate, len(federated))
  329. for i := range federated {
  330. certs[i] = Certificate{federated[i]}
  331. }
  332. w.WriteHeader(http.StatusCreated)
  333. JSON(w, &FederationResponse{
  334. Certificates: certs,
  335. })
  336. }
  337. var oidStepProvisioner = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 37476, 9000, 64, 1}
  338. type stepProvisioner struct {
  339. Type int
  340. Name []byte
  341. CredentialID []byte
  342. }
  343. func logCertificate(w http.ResponseWriter, cert *x509.Certificate, token string) {
  344. if rl, ok := w.(logging.ResponseLogger); ok {
  345. m := map[string]interface{}{
  346. "serial": cert.SerialNumber,
  347. "subject": cert.Subject.CommonName,
  348. "issuer": cert.Issuer.CommonName,
  349. "valid-from": cert.NotBefore.Format(time.RFC3339),
  350. "valid-to": cert.NotAfter.Format(time.RFC3339),
  351. "public-key": fmtPublicKey(cert),
  352. "certificate": base64.StdEncoding.EncodeToString(cert.Raw),
  353. }
  354. if len(token) > 0 {
  355. m["ott"] = token
  356. }
  357. for _, ext := range cert.Extensions {
  358. if ext.Id.Equal(oidStepProvisioner) {
  359. val := &stepProvisioner{}
  360. rest, err := asn1.Unmarshal(ext.Value, val)
  361. if err != nil || len(rest) > 0 {
  362. break
  363. }
  364. m["provisioner"] = fmt.Sprintf("%s (%s)", val.Name, val.CredentialID)
  365. break
  366. }
  367. }
  368. rl.WithFields(m)
  369. }
  370. }
  371. func parseCursor(r *http.Request) (cursor string, limit int, err error) {
  372. q := r.URL.Query()
  373. cursor = q.Get("cursor")
  374. if v := q.Get("limit"); len(v) > 0 {
  375. limit, err = strconv.Atoi(v)
  376. if err != nil {
  377. return "", 0, errors.Wrapf(err, "error converting %s to integer", v)
  378. }
  379. }
  380. return
  381. }
  382. // TODO: add support for Ed25519 once it's supported
  383. func fmtPublicKey(cert *x509.Certificate) string {
  384. var params string
  385. switch pk := cert.PublicKey.(type) {
  386. case *ecdsa.PublicKey:
  387. params = pk.Curve.Params().Name
  388. case *rsa.PublicKey:
  389. params = strconv.Itoa(pk.Size() * 8)
  390. case *dsa.PublicKey:
  391. params = strconv.Itoa(pk.Q.BitLen() * 8)
  392. default:
  393. params = "unknown"
  394. }
  395. return fmt.Sprintf("%s %s", cert.PublicKeyAlgorithm, params)
  396. }