api.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  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"
  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. 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() ([]byte, 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. MinimumPublicKeyLength: p.MinimumPublicKeyLength,
  217. DecrypterCertificate: redacted,
  218. DecrypterKey: redacted,
  219. DecrypterKeyPassword: redacted,
  220. EncryptionAlgorithmIdentifier: p.EncryptionAlgorithmIdentifier,
  221. Options: p.Options,
  222. Claims: p.Claims,
  223. }
  224. }
  225. // MarshalJSON implements json.Marshaler. It marshals the ProvisionersResponse
  226. // into a byte slice.
  227. //
  228. // Special treatment is given to the SCEP provisioner, as it contains a
  229. // challenge secret that MUST NOT be leaked in (public) HTTP responses. The
  230. // challenge value is thus redacted in HTTP responses.
  231. func (p ProvisionersResponse) MarshalJSON() ([]byte, error) {
  232. var responseProvisioners provisioner.List
  233. for _, item := range p.Provisioners {
  234. scepProv, ok := item.(*provisioner.SCEP)
  235. if !ok {
  236. responseProvisioners = append(responseProvisioners, item)
  237. continue
  238. }
  239. responseProvisioners = append(responseProvisioners, scepFromProvisioner(scepProv))
  240. }
  241. var list = struct {
  242. Provisioners []provisioner.Interface `json:"provisioners"`
  243. NextCursor string `json:"nextCursor"`
  244. }{
  245. Provisioners: []provisioner.Interface(responseProvisioners),
  246. NextCursor: p.NextCursor,
  247. }
  248. return json.Marshal(list)
  249. }
  250. // ProvisionerKeyResponse is the response object that returns the encrypted key
  251. // of a provisioner.
  252. type ProvisionerKeyResponse struct {
  253. Key string `json:"key"`
  254. }
  255. // RootsResponse is the response object of the roots request.
  256. type RootsResponse struct {
  257. Certificates []Certificate `json:"crts"`
  258. }
  259. // FederationResponse is the response object of the federation request.
  260. type FederationResponse struct {
  261. Certificates []Certificate `json:"crts"`
  262. }
  263. // caHandler is the type used to implement the different CA HTTP endpoints.
  264. type caHandler struct {
  265. Authority Authority
  266. }
  267. // Route configures the http request router.
  268. func (h *caHandler) Route(r Router) {
  269. Route(r)
  270. }
  271. // New creates a new RouterHandler with the CA endpoints.
  272. //
  273. // Deprecated: Use api.Route(r Router)
  274. func New(Authority) RouterHandler {
  275. return &caHandler{}
  276. }
  277. func Route(r Router) {
  278. r.MethodFunc("GET", "/version", Version)
  279. r.MethodFunc("GET", "/health", Health)
  280. r.MethodFunc("GET", "/root/{sha}", Root)
  281. r.MethodFunc("POST", "/sign", Sign)
  282. r.MethodFunc("POST", "/renew", Renew)
  283. r.MethodFunc("POST", "/rekey", Rekey)
  284. r.MethodFunc("POST", "/revoke", Revoke)
  285. r.MethodFunc("GET", "/crl", CRL)
  286. r.MethodFunc("GET", "/provisioners", Provisioners)
  287. r.MethodFunc("GET", "/provisioners/{kid}/encrypted-key", ProvisionerKey)
  288. r.MethodFunc("GET", "/roots", Roots)
  289. r.MethodFunc("GET", "/roots.pem", RootsPEM)
  290. r.MethodFunc("GET", "/federation", Federation)
  291. // SSH CA
  292. r.MethodFunc("POST", "/ssh/sign", SSHSign)
  293. r.MethodFunc("POST", "/ssh/renew", SSHRenew)
  294. r.MethodFunc("POST", "/ssh/revoke", SSHRevoke)
  295. r.MethodFunc("POST", "/ssh/rekey", SSHRekey)
  296. r.MethodFunc("GET", "/ssh/roots", SSHRoots)
  297. r.MethodFunc("GET", "/ssh/federation", SSHFederation)
  298. r.MethodFunc("POST", "/ssh/config", SSHConfig)
  299. r.MethodFunc("POST", "/ssh/config/{type}", SSHConfig)
  300. r.MethodFunc("POST", "/ssh/check-host", SSHCheckHost)
  301. r.MethodFunc("GET", "/ssh/hosts", SSHGetHosts)
  302. r.MethodFunc("POST", "/ssh/bastion", SSHBastion)
  303. // For compatibility with old code:
  304. r.MethodFunc("POST", "/re-sign", Renew)
  305. r.MethodFunc("POST", "/sign-ssh", SSHSign)
  306. r.MethodFunc("GET", "/ssh/get-hosts", SSHGetHosts)
  307. }
  308. // Version is an HTTP handler that returns the version of the server.
  309. func Version(w http.ResponseWriter, r *http.Request) {
  310. v := mustAuthority(r.Context()).Version()
  311. render.JSON(w, VersionResponse{
  312. Version: v.Version,
  313. RequireClientAuthentication: v.RequireClientAuthentication,
  314. })
  315. }
  316. // Health is an HTTP handler that returns the status of the server.
  317. func Health(w http.ResponseWriter, _ *http.Request) {
  318. render.JSON(w, HealthResponse{Status: "ok"})
  319. }
  320. // Root is an HTTP handler that using the SHA256 from the URL, returns the root
  321. // certificate for the given SHA256.
  322. func Root(w http.ResponseWriter, r *http.Request) {
  323. sha := chi.URLParam(r, "sha")
  324. sum := strings.ToLower(strings.ReplaceAll(sha, "-", ""))
  325. // Load root certificate with the
  326. cert, err := mustAuthority(r.Context()).Root(sum)
  327. if err != nil {
  328. render.Error(w, errs.Wrapf(http.StatusNotFound, err, "%s was not found", r.RequestURI))
  329. return
  330. }
  331. render.JSON(w, &RootResponse{RootPEM: Certificate{cert}})
  332. }
  333. func certChainToPEM(certChain []*x509.Certificate) []Certificate {
  334. certChainPEM := make([]Certificate, 0, len(certChain))
  335. for _, c := range certChain {
  336. certChainPEM = append(certChainPEM, Certificate{c})
  337. }
  338. return certChainPEM
  339. }
  340. // Provisioners returns the list of provisioners configured in the authority.
  341. func Provisioners(w http.ResponseWriter, r *http.Request) {
  342. cursor, limit, err := ParseCursor(r)
  343. if err != nil {
  344. render.Error(w, err)
  345. return
  346. }
  347. p, next, err := mustAuthority(r.Context()).GetProvisioners(cursor, limit)
  348. if err != nil {
  349. render.Error(w, errs.InternalServerErr(err))
  350. return
  351. }
  352. render.JSON(w, &ProvisionersResponse{
  353. Provisioners: p,
  354. NextCursor: next,
  355. })
  356. }
  357. // ProvisionerKey returns the encrypted key of a provisioner by it's key id.
  358. func ProvisionerKey(w http.ResponseWriter, r *http.Request) {
  359. kid := chi.URLParam(r, "kid")
  360. key, err := mustAuthority(r.Context()).GetEncryptedKey(kid)
  361. if err != nil {
  362. render.Error(w, errs.NotFoundErr(err))
  363. return
  364. }
  365. render.JSON(w, &ProvisionerKeyResponse{key})
  366. }
  367. // Roots returns all the root certificates for the CA.
  368. func Roots(w http.ResponseWriter, r *http.Request) {
  369. roots, err := mustAuthority(r.Context()).GetRoots()
  370. if err != nil {
  371. render.Error(w, errs.ForbiddenErr(err, "error getting roots"))
  372. return
  373. }
  374. certs := make([]Certificate, len(roots))
  375. for i := range roots {
  376. certs[i] = Certificate{roots[i]}
  377. }
  378. render.JSONStatus(w, &RootsResponse{
  379. Certificates: certs,
  380. }, http.StatusCreated)
  381. }
  382. // RootsPEM returns all the root certificates for the CA in PEM format.
  383. func RootsPEM(w http.ResponseWriter, r *http.Request) {
  384. roots, err := mustAuthority(r.Context()).GetRoots()
  385. if err != nil {
  386. render.Error(w, errs.InternalServerErr(err))
  387. return
  388. }
  389. w.Header().Set("Content-Type", "application/x-pem-file")
  390. for _, root := range roots {
  391. block := pem.EncodeToMemory(&pem.Block{
  392. Type: "CERTIFICATE",
  393. Bytes: root.Raw,
  394. })
  395. if _, err := w.Write(block); err != nil {
  396. log.Error(w, err)
  397. return
  398. }
  399. }
  400. }
  401. // Federation returns all the public certificates in the federation.
  402. func Federation(w http.ResponseWriter, r *http.Request) {
  403. federated, err := mustAuthority(r.Context()).GetFederation()
  404. if err != nil {
  405. render.Error(w, errs.ForbiddenErr(err, "error getting federated roots"))
  406. return
  407. }
  408. certs := make([]Certificate, len(federated))
  409. for i := range federated {
  410. certs[i] = Certificate{federated[i]}
  411. }
  412. render.JSONStatus(w, &FederationResponse{
  413. Certificates: certs,
  414. }, http.StatusCreated)
  415. }
  416. var oidStepProvisioner = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 37476, 9000, 64, 1}
  417. type stepProvisioner struct {
  418. Type int
  419. Name []byte
  420. CredentialID []byte
  421. }
  422. func logOtt(w http.ResponseWriter, token string) {
  423. if rl, ok := w.(logging.ResponseLogger); ok {
  424. rl.WithFields(map[string]interface{}{
  425. "ott": token,
  426. })
  427. }
  428. }
  429. // LogCertificate adds certificate fields to the log message.
  430. func LogCertificate(w http.ResponseWriter, cert *x509.Certificate) {
  431. if rl, ok := w.(logging.ResponseLogger); ok {
  432. m := map[string]interface{}{
  433. "serial": cert.SerialNumber.String(),
  434. "subject": cert.Subject.CommonName,
  435. "issuer": cert.Issuer.CommonName,
  436. "valid-from": cert.NotBefore.Format(time.RFC3339),
  437. "valid-to": cert.NotAfter.Format(time.RFC3339),
  438. "public-key": fmtPublicKey(cert),
  439. "certificate": base64.StdEncoding.EncodeToString(cert.Raw),
  440. }
  441. for _, ext := range cert.Extensions {
  442. if !ext.Id.Equal(oidStepProvisioner) {
  443. continue
  444. }
  445. val := &stepProvisioner{}
  446. rest, err := asn1.Unmarshal(ext.Value, val)
  447. if err != nil || len(rest) > 0 {
  448. break
  449. }
  450. if len(val.CredentialID) > 0 {
  451. m["provisioner"] = fmt.Sprintf("%s (%s)", val.Name, val.CredentialID)
  452. } else {
  453. m["provisioner"] = string(val.Name)
  454. }
  455. break
  456. }
  457. rl.WithFields(m)
  458. }
  459. }
  460. // LogSSHCertificate adds SSH certificate fields to the log message.
  461. func LogSSHCertificate(w http.ResponseWriter, cert *ssh.Certificate) {
  462. if rl, ok := w.(logging.ResponseLogger); ok {
  463. mak := bytes.TrimSpace(ssh.MarshalAuthorizedKey(cert))
  464. var certificate string
  465. parts := strings.Split(string(mak), " ")
  466. if len(parts) > 1 {
  467. certificate = parts[1]
  468. }
  469. var userOrHost string
  470. if cert.CertType == ssh.HostCert {
  471. userOrHost = "host"
  472. } else {
  473. userOrHost = "user"
  474. }
  475. certificateType := fmt.Sprintf("%s %s certificate", parts[0], userOrHost) // e.g. ecdsa-sha2-nistp256-cert-v01@openssh.com user certificate
  476. m := map[string]interface{}{
  477. "serial": cert.Serial,
  478. "principals": cert.ValidPrincipals,
  479. "valid-from": time.Unix(int64(cert.ValidAfter), 0).Format(time.RFC3339),
  480. "valid-to": time.Unix(int64(cert.ValidBefore), 0).Format(time.RFC3339),
  481. "certificate": certificate,
  482. "certificate-type": certificateType,
  483. }
  484. fingerprint, err := sshutil.FormatFingerprint(mak, sshutil.DefaultFingerprint)
  485. if err == nil {
  486. fpParts := strings.Split(fingerprint, " ")
  487. if len(fpParts) > 3 {
  488. m["public-key"] = fmt.Sprintf("%s %s", fpParts[1], fpParts[len(fpParts)-1])
  489. }
  490. }
  491. rl.WithFields(m)
  492. }
  493. }
  494. // ParseCursor parses the cursor and limit from the request query params.
  495. func ParseCursor(r *http.Request) (cursor string, limit int, err error) {
  496. q := r.URL.Query()
  497. cursor = q.Get("cursor")
  498. if v := q.Get("limit"); len(v) > 0 {
  499. limit, err = strconv.Atoi(v)
  500. if err != nil {
  501. return "", 0, errs.BadRequestErr(err, "limit '%s' is not an integer", v)
  502. }
  503. }
  504. return
  505. }
  506. func fmtPublicKey(cert *x509.Certificate) string {
  507. var params string
  508. switch pk := cert.PublicKey.(type) {
  509. case *ecdsa.PublicKey:
  510. params = pk.Curve.Params().Name
  511. case *rsa.PublicKey:
  512. params = strconv.Itoa(pk.Size() * 8)
  513. case ed25519.PublicKey:
  514. return cert.PublicKeyAlgorithm.String()
  515. case *dsa.PublicKey:
  516. params = strconv.Itoa(pk.Q.BitLen() * 8)
  517. default:
  518. params = "unknown"
  519. }
  520. return fmt.Sprintf("%s %s", cert.PublicKeyAlgorithm, params)
  521. }