api.go 18 KB

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