api.go 17 KB

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