api.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. package api
  2. import (
  3. "context"
  4. "crypto"
  5. "crypto/dsa" //nolint
  6. "crypto/ecdsa"
  7. "crypto/ed25519"
  8. "crypto/rsa"
  9. "crypto/x509"
  10. "encoding/asn1"
  11. "encoding/base64"
  12. "encoding/json"
  13. "encoding/pem"
  14. "fmt"
  15. "net/http"
  16. "strconv"
  17. "strings"
  18. "time"
  19. "github.com/go-chi/chi"
  20. "github.com/pkg/errors"
  21. "github.com/smallstep/certificates/api/log"
  22. "github.com/smallstep/certificates/api/render"
  23. "github.com/smallstep/certificates/authority"
  24. "github.com/smallstep/certificates/authority/config"
  25. "github.com/smallstep/certificates/authority/provisioner"
  26. "github.com/smallstep/certificates/errs"
  27. "github.com/smallstep/certificates/logging"
  28. )
  29. // Authority is the interface implemented by a CA authority.
  30. type Authority interface {
  31. SSHAuthority
  32. // context specifies the Authorize[Sign|Revoke|etc.] method.
  33. Authorize(ctx context.Context, ott string) ([]provisioner.SignOption, error)
  34. AuthorizeSign(ott string) ([]provisioner.SignOption, error)
  35. AuthorizeRenewToken(ctx context.Context, ott string) (*x509.Certificate, error)
  36. GetTLSOptions() *config.TLSOptions
  37. Root(shasum string) (*x509.Certificate, error)
  38. Sign(cr *x509.CertificateRequest, opts provisioner.SignOptions, signOpts ...provisioner.SignOption) ([]*x509.Certificate, error)
  39. Renew(peer *x509.Certificate) ([]*x509.Certificate, error)
  40. Rekey(peer *x509.Certificate, pk crypto.PublicKey) ([]*x509.Certificate, error)
  41. LoadProvisionerByCertificate(*x509.Certificate) (provisioner.Interface, error)
  42. LoadProvisionerByName(string) (provisioner.Interface, error)
  43. GetProvisioners(cursor string, limit int) (provisioner.List, string, error)
  44. Revoke(context.Context, *authority.RevokeOptions) error
  45. GetEncryptedKey(kid string) (string, error)
  46. GetRoots() ([]*x509.Certificate, error)
  47. GetFederation() ([]*x509.Certificate, error)
  48. Version() authority.Version
  49. GenerateCertificateRevocationList() error
  50. GetCertificateRevocationList() ([]byte, error)
  51. }
  52. // TimeDuration is an alias of provisioner.TimeDuration
  53. type TimeDuration = provisioner.TimeDuration
  54. // NewTimeDuration returns a TimeDuration with the defined time.
  55. func NewTimeDuration(t time.Time) TimeDuration {
  56. return provisioner.NewTimeDuration(t)
  57. }
  58. // ParseTimeDuration returns a new TimeDuration parsing the RFC 3339 time or
  59. // time.Duration string.
  60. func ParseTimeDuration(s string) (TimeDuration, error) {
  61. return provisioner.ParseTimeDuration(s)
  62. }
  63. // Certificate wraps a *x509.Certificate and adds the json.Marshaler interface.
  64. type Certificate struct {
  65. *x509.Certificate
  66. }
  67. // NewCertificate is a helper method that returns a Certificate from a
  68. // *x509.Certificate.
  69. func NewCertificate(cr *x509.Certificate) Certificate {
  70. return Certificate{
  71. Certificate: cr,
  72. }
  73. }
  74. // reset sets the inner x509.CertificateRequest to nil
  75. func (c *Certificate) reset() {
  76. if c != nil {
  77. c.Certificate = nil
  78. }
  79. }
  80. // MarshalJSON implements the json.Marshaler interface. The certificate is
  81. // quoted string using the PEM encoding.
  82. func (c Certificate) MarshalJSON() ([]byte, error) {
  83. if c.Certificate == nil {
  84. return []byte("null"), nil
  85. }
  86. block := pem.EncodeToMemory(&pem.Block{
  87. Type: "CERTIFICATE",
  88. Bytes: c.Raw,
  89. })
  90. return json.Marshal(string(block))
  91. }
  92. // UnmarshalJSON implements the json.Unmarshaler interface. The certificate is
  93. // expected to be a quoted string using the PEM encoding.
  94. func (c *Certificate) UnmarshalJSON(data []byte) error {
  95. var s string
  96. if err := json.Unmarshal(data, &s); err != nil {
  97. return errors.Wrap(err, "error decoding certificate")
  98. }
  99. // Make sure the inner x509.Certificate is nil
  100. if s == "null" || s == "" {
  101. c.reset()
  102. return nil
  103. }
  104. block, _ := pem.Decode([]byte(s))
  105. if block == nil {
  106. return errors.New("error decoding certificate")
  107. }
  108. cert, err := x509.ParseCertificate(block.Bytes)
  109. if err != nil {
  110. return errors.Wrap(err, "error decoding certificate")
  111. }
  112. c.Certificate = cert
  113. return nil
  114. }
  115. // CertificateRequest wraps a *x509.CertificateRequest and adds the
  116. // json.Unmarshaler interface.
  117. type CertificateRequest struct {
  118. *x509.CertificateRequest
  119. }
  120. // NewCertificateRequest is a helper method that returns a CertificateRequest
  121. // from a *x509.CertificateRequest.
  122. func NewCertificateRequest(cr *x509.CertificateRequest) CertificateRequest {
  123. return CertificateRequest{
  124. CertificateRequest: cr,
  125. }
  126. }
  127. // reset sets the inner x509.CertificateRequest to nil
  128. func (c *CertificateRequest) reset() {
  129. if c != nil {
  130. c.CertificateRequest = nil
  131. }
  132. }
  133. // MarshalJSON implements the json.Marshaler interface. The certificate request
  134. // is a quoted string using the PEM encoding.
  135. func (c CertificateRequest) MarshalJSON() ([]byte, error) {
  136. if c.CertificateRequest == nil {
  137. return []byte("null"), nil
  138. }
  139. block := pem.EncodeToMemory(&pem.Block{
  140. Type: "CERTIFICATE REQUEST",
  141. Bytes: c.Raw,
  142. })
  143. return json.Marshal(string(block))
  144. }
  145. // UnmarshalJSON implements the json.Unmarshaler interface. The certificate
  146. // request is expected to be a quoted string using the PEM encoding.
  147. func (c *CertificateRequest) UnmarshalJSON(data []byte) error {
  148. var s string
  149. if err := json.Unmarshal(data, &s); err != nil {
  150. return errors.Wrap(err, "error decoding csr")
  151. }
  152. // Make sure the inner x509.CertificateRequest is nil
  153. if s == "null" || s == "" {
  154. c.reset()
  155. return nil
  156. }
  157. block, _ := pem.Decode([]byte(s))
  158. if block == nil {
  159. return errors.New("error decoding csr")
  160. }
  161. cr, err := x509.ParseCertificateRequest(block.Bytes)
  162. if err != nil {
  163. return errors.Wrap(err, "error decoding csr")
  164. }
  165. c.CertificateRequest = cr
  166. return nil
  167. }
  168. // Router defines a common router interface.
  169. type Router interface {
  170. // MethodFunc adds routes for `pattern` that matches
  171. // the `method` HTTP method.
  172. MethodFunc(method, pattern string, h http.HandlerFunc)
  173. }
  174. // RouterHandler is the interface that a HTTP handler that manages multiple
  175. // endpoints will implement.
  176. type RouterHandler interface {
  177. Route(r Router)
  178. }
  179. // VersionResponse is the response object that returns the version of the
  180. // server.
  181. type VersionResponse struct {
  182. Version string `json:"version"`
  183. RequireClientAuthentication bool `json:"requireClientAuthentication,omitempty"`
  184. }
  185. // HealthResponse is the response object that returns the health of the server.
  186. type HealthResponse struct {
  187. Status string `json:"status"`
  188. }
  189. // RootResponse is the response object that returns the PEM of a root certificate.
  190. type RootResponse struct {
  191. RootPEM Certificate `json:"ca"`
  192. }
  193. // ProvisionersResponse is the response object that returns the list of
  194. // provisioners.
  195. type ProvisionersResponse struct {
  196. Provisioners provisioner.List `json:"provisioners"`
  197. NextCursor string `json:"nextCursor"`
  198. }
  199. // ProvisionerKeyResponse is the response object that returns the encrypted key
  200. // of a provisioner.
  201. type ProvisionerKeyResponse struct {
  202. Key string `json:"key"`
  203. }
  204. // RootsResponse is the response object of the roots request.
  205. type RootsResponse struct {
  206. Certificates []Certificate `json:"crts"`
  207. }
  208. // FederationResponse is the response object of the federation request.
  209. type FederationResponse struct {
  210. Certificates []Certificate `json:"crts"`
  211. }
  212. // caHandler is the type used to implement the different CA HTTP endpoints.
  213. type caHandler struct {
  214. Authority Authority
  215. }
  216. // New creates a new RouterHandler with the CA endpoints.
  217. func New(auth Authority) RouterHandler {
  218. return &caHandler{
  219. Authority: auth,
  220. }
  221. }
  222. func (h *caHandler) Route(r Router) {
  223. r.MethodFunc("GET", "/version", h.Version)
  224. r.MethodFunc("GET", "/health", h.Health)
  225. r.MethodFunc("GET", "/root/{sha}", h.Root)
  226. r.MethodFunc("POST", "/sign", h.Sign)
  227. r.MethodFunc("POST", "/renew", h.Renew)
  228. r.MethodFunc("POST", "/rekey", h.Rekey)
  229. r.MethodFunc("POST", "/revoke", h.Revoke)
  230. r.MethodFunc("GET", "/crl", h.CRL)
  231. r.MethodFunc("GET", "/provisioners", h.Provisioners)
  232. r.MethodFunc("GET", "/provisioners/{kid}/encrypted-key", h.ProvisionerKey)
  233. r.MethodFunc("GET", "/roots", h.Roots)
  234. r.MethodFunc("GET", "/roots.pem", h.RootsPEM)
  235. r.MethodFunc("GET", "/federation", h.Federation)
  236. // SSH CA
  237. r.MethodFunc("POST", "/ssh/sign", h.SSHSign)
  238. r.MethodFunc("POST", "/ssh/renew", h.SSHRenew)
  239. r.MethodFunc("POST", "/ssh/revoke", h.SSHRevoke)
  240. r.MethodFunc("POST", "/ssh/rekey", h.SSHRekey)
  241. r.MethodFunc("GET", "/ssh/roots", h.SSHRoots)
  242. r.MethodFunc("GET", "/ssh/federation", h.SSHFederation)
  243. r.MethodFunc("POST", "/ssh/config", h.SSHConfig)
  244. r.MethodFunc("POST", "/ssh/config/{type}", h.SSHConfig)
  245. r.MethodFunc("POST", "/ssh/check-host", h.SSHCheckHost)
  246. r.MethodFunc("GET", "/ssh/hosts", h.SSHGetHosts)
  247. r.MethodFunc("POST", "/ssh/bastion", h.SSHBastion)
  248. // For compatibility with old code:
  249. r.MethodFunc("POST", "/re-sign", h.Renew)
  250. r.MethodFunc("POST", "/sign-ssh", h.SSHSign)
  251. r.MethodFunc("GET", "/ssh/get-hosts", h.SSHGetHosts)
  252. }
  253. // Version is an HTTP handler that returns the version of the server.
  254. func (h *caHandler) Version(w http.ResponseWriter, r *http.Request) {
  255. v := h.Authority.Version()
  256. render.JSON(w, VersionResponse{
  257. Version: v.Version,
  258. RequireClientAuthentication: v.RequireClientAuthentication,
  259. })
  260. }
  261. // Health is an HTTP handler that returns the status of the server.
  262. func (h *caHandler) Health(w http.ResponseWriter, r *http.Request) {
  263. render.JSON(w, HealthResponse{Status: "ok"})
  264. }
  265. // Root is an HTTP handler that using the SHA256 from the URL, returns the root
  266. // certificate for the given SHA256.
  267. func (h *caHandler) Root(w http.ResponseWriter, r *http.Request) {
  268. sha := chi.URLParam(r, "sha")
  269. sum := strings.ToLower(strings.ReplaceAll(sha, "-", ""))
  270. // Load root certificate with the
  271. cert, err := h.Authority.Root(sum)
  272. if err != nil {
  273. render.Error(w, errs.Wrapf(http.StatusNotFound, err, "%s was not found", r.RequestURI))
  274. return
  275. }
  276. render.JSON(w, &RootResponse{RootPEM: Certificate{cert}})
  277. }
  278. func certChainToPEM(certChain []*x509.Certificate) []Certificate {
  279. certChainPEM := make([]Certificate, 0, len(certChain))
  280. for _, c := range certChain {
  281. certChainPEM = append(certChainPEM, Certificate{c})
  282. }
  283. return certChainPEM
  284. }
  285. // Provisioners returns the list of provisioners configured in the authority.
  286. func (h *caHandler) Provisioners(w http.ResponseWriter, r *http.Request) {
  287. cursor, limit, err := ParseCursor(r)
  288. if err != nil {
  289. render.Error(w, err)
  290. return
  291. }
  292. p, next, err := h.Authority.GetProvisioners(cursor, limit)
  293. if err != nil {
  294. render.Error(w, errs.InternalServerErr(err))
  295. return
  296. }
  297. render.JSON(w, &ProvisionersResponse{
  298. Provisioners: p,
  299. NextCursor: next,
  300. })
  301. }
  302. // ProvisionerKey returns the encrypted key of a provisioner by it's key id.
  303. func (h *caHandler) ProvisionerKey(w http.ResponseWriter, r *http.Request) {
  304. kid := chi.URLParam(r, "kid")
  305. key, err := h.Authority.GetEncryptedKey(kid)
  306. if err != nil {
  307. render.Error(w, errs.NotFoundErr(err))
  308. return
  309. }
  310. render.JSON(w, &ProvisionerKeyResponse{key})
  311. }
  312. // Roots returns all the root certificates for the CA.
  313. func (h *caHandler) Roots(w http.ResponseWriter, r *http.Request) {
  314. roots, err := h.Authority.GetRoots()
  315. if err != nil {
  316. render.Error(w, errs.ForbiddenErr(err, "error getting roots"))
  317. return
  318. }
  319. certs := make([]Certificate, len(roots))
  320. for i := range roots {
  321. certs[i] = Certificate{roots[i]}
  322. }
  323. render.JSONStatus(w, &RootsResponse{
  324. Certificates: certs,
  325. }, http.StatusCreated)
  326. }
  327. // RootsPEM returns all the root certificates for the CA in PEM format.
  328. func (h *caHandler) RootsPEM(w http.ResponseWriter, r *http.Request) {
  329. roots, err := h.Authority.GetRoots()
  330. if err != nil {
  331. render.Error(w, errs.InternalServerErr(err))
  332. return
  333. }
  334. w.Header().Set("Content-Type", "application/x-pem-file")
  335. for _, root := range roots {
  336. block := pem.EncodeToMemory(&pem.Block{
  337. Type: "CERTIFICATE",
  338. Bytes: root.Raw,
  339. })
  340. if _, err := w.Write(block); err != nil {
  341. log.Error(w, err)
  342. return
  343. }
  344. }
  345. }
  346. // Federation returns all the public certificates in the federation.
  347. func (h *caHandler) Federation(w http.ResponseWriter, r *http.Request) {
  348. federated, err := h.Authority.GetFederation()
  349. if err != nil {
  350. render.Error(w, errs.ForbiddenErr(err, "error getting federated roots"))
  351. return
  352. }
  353. certs := make([]Certificate, len(federated))
  354. for i := range federated {
  355. certs[i] = Certificate{federated[i]}
  356. }
  357. render.JSONStatus(w, &FederationResponse{
  358. Certificates: certs,
  359. }, http.StatusCreated)
  360. }
  361. var oidStepProvisioner = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 37476, 9000, 64, 1}
  362. type stepProvisioner struct {
  363. Type int
  364. Name []byte
  365. CredentialID []byte
  366. }
  367. func logOtt(w http.ResponseWriter, token string) {
  368. if rl, ok := w.(logging.ResponseLogger); ok {
  369. rl.WithFields(map[string]interface{}{
  370. "ott": token,
  371. })
  372. }
  373. }
  374. // LogCertificate add certificate fields to the log message.
  375. func LogCertificate(w http.ResponseWriter, cert *x509.Certificate) {
  376. if rl, ok := w.(logging.ResponseLogger); ok {
  377. m := map[string]interface{}{
  378. "serial": cert.SerialNumber.String(),
  379. "subject": cert.Subject.CommonName,
  380. "issuer": cert.Issuer.CommonName,
  381. "valid-from": cert.NotBefore.Format(time.RFC3339),
  382. "valid-to": cert.NotAfter.Format(time.RFC3339),
  383. "public-key": fmtPublicKey(cert),
  384. "certificate": base64.StdEncoding.EncodeToString(cert.Raw),
  385. }
  386. for _, ext := range cert.Extensions {
  387. if !ext.Id.Equal(oidStepProvisioner) {
  388. continue
  389. }
  390. val := &stepProvisioner{}
  391. rest, err := asn1.Unmarshal(ext.Value, val)
  392. if err != nil || len(rest) > 0 {
  393. break
  394. }
  395. if len(val.CredentialID) > 0 {
  396. m["provisioner"] = fmt.Sprintf("%s (%s)", val.Name, val.CredentialID)
  397. } else {
  398. m["provisioner"] = string(val.Name)
  399. }
  400. break
  401. }
  402. rl.WithFields(m)
  403. }
  404. }
  405. // ParseCursor parses the cursor and limit from the request query params.
  406. func ParseCursor(r *http.Request) (cursor string, limit int, err error) {
  407. q := r.URL.Query()
  408. cursor = q.Get("cursor")
  409. if v := q.Get("limit"); len(v) > 0 {
  410. limit, err = strconv.Atoi(v)
  411. if err != nil {
  412. return "", 0, errs.BadRequestErr(err, "limit '%s' is not an integer", v)
  413. }
  414. }
  415. return
  416. }
  417. func fmtPublicKey(cert *x509.Certificate) string {
  418. var params string
  419. switch pk := cert.PublicKey.(type) {
  420. case *ecdsa.PublicKey:
  421. params = pk.Curve.Params().Name
  422. case *rsa.PublicKey:
  423. params = strconv.Itoa(pk.Size() * 8)
  424. case ed25519.PublicKey:
  425. return cert.PublicKeyAlgorithm.String()
  426. case *dsa.PublicKey:
  427. params = strconv.Itoa(pk.Q.BitLen() * 8)
  428. default:
  429. params = "unknown"
  430. }
  431. return fmt.Sprintf("%s %s", cert.PublicKeyAlgorithm, params)
  432. }