api.go 14 KB

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