api.go 18 KB

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