api.go 17 KB

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