api.go 15 KB

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