api.go 17 KB

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