client.go 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585
  1. package ca
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto"
  6. "crypto/ecdsa"
  7. "crypto/elliptic"
  8. "crypto/rand"
  9. "crypto/sha256"
  10. "crypto/tls"
  11. "crypto/x509"
  12. "crypto/x509/pkix"
  13. "encoding/hex"
  14. "encoding/json"
  15. "encoding/pem"
  16. "fmt"
  17. "io"
  18. "net/http"
  19. "net/url"
  20. "os"
  21. "path/filepath"
  22. "strconv"
  23. "strings"
  24. "time"
  25. "github.com/pkg/errors"
  26. "golang.org/x/net/http2"
  27. "google.golang.org/protobuf/encoding/protojson"
  28. "google.golang.org/protobuf/proto"
  29. "github.com/smallstep/cli-utils/step"
  30. "go.step.sm/crypto/jose"
  31. "go.step.sm/crypto/keyutil"
  32. "go.step.sm/crypto/pemutil"
  33. "go.step.sm/crypto/randutil"
  34. "go.step.sm/crypto/x509util"
  35. "github.com/smallstep/certificates/api"
  36. "github.com/smallstep/certificates/authority"
  37. "github.com/smallstep/certificates/authority/provisioner"
  38. "github.com/smallstep/certificates/ca/client"
  39. "github.com/smallstep/certificates/ca/identity"
  40. "github.com/smallstep/certificates/errs"
  41. )
  42. // DisableIdentity is a global variable to disable the identity.
  43. var DisableIdentity = false
  44. // UserAgent will set the User-Agent header in the client requests.
  45. var UserAgent = "step-http-client/1.0"
  46. type uaClient struct {
  47. Client *http.Client
  48. }
  49. func newClient(transport http.RoundTripper, timeout time.Duration) *uaClient {
  50. return &uaClient{
  51. Client: &http.Client{
  52. Transport: transport,
  53. Timeout: timeout,
  54. },
  55. }
  56. }
  57. //nolint:gosec // used in bootstrap protocol
  58. func newInsecureClient() *uaClient {
  59. return &uaClient{
  60. Client: &http.Client{
  61. Transport: getDefaultTransport(&tls.Config{InsecureSkipVerify: true}),
  62. },
  63. }
  64. }
  65. func (c *uaClient) GetTransport() http.RoundTripper {
  66. return c.Client.Transport
  67. }
  68. func (c *uaClient) SetTransport(tr http.RoundTripper) {
  69. c.Client.Transport = tr
  70. }
  71. func (c *uaClient) CloseIdleConnections() {
  72. c.Client.CloseIdleConnections()
  73. }
  74. func (c *uaClient) Get(u string) (*http.Response, error) {
  75. return c.GetWithContext(context.Background(), u)
  76. }
  77. func (c *uaClient) GetWithContext(ctx context.Context, u string) (*http.Response, error) {
  78. req, err := http.NewRequestWithContext(ctx, "GET", u, http.NoBody)
  79. if err != nil {
  80. return nil, errors.Wrapf(err, "create GET %s request failed", u)
  81. }
  82. return c.Do(req)
  83. }
  84. func (c *uaClient) Post(u, contentType string, body io.Reader) (*http.Response, error) {
  85. return c.PostWithContext(context.Background(), u, contentType, body)
  86. }
  87. func (c *uaClient) PostWithContext(ctx context.Context, u, contentType string, body io.Reader) (*http.Response, error) {
  88. req, err := http.NewRequestWithContext(ctx, "POST", u, body)
  89. if err != nil {
  90. return nil, errors.Wrapf(err, "create POST %s request failed", u)
  91. }
  92. req.Header.Set("Content-Type", contentType)
  93. return c.Do(req)
  94. }
  95. // requestIDHeader is the header name used for propagating request IDs from
  96. // the CA client to the CA and back again.
  97. const requestIDHeader = "X-Request-Id"
  98. // newRequestID generates a new random UUIDv4 request ID. If it fails,
  99. // the request ID will be the empty string.
  100. func newRequestID() string {
  101. requestID, err := randutil.UUIDv4()
  102. if err != nil {
  103. return ""
  104. }
  105. return requestID
  106. }
  107. // enforceRequestID checks if the X-Request-Id HTTP header is filled. If it's
  108. // empty, the context is searched for a request ID. If that's also empty, a new
  109. // request ID is generated.
  110. func enforceRequestID(r *http.Request) {
  111. if requestID := r.Header.Get(requestIDHeader); requestID == "" {
  112. if reqID, ok := client.RequestIDFromContext(r.Context()); ok {
  113. // TODO(hs): ensure the request ID from the context is fresh, and thus hasn't been
  114. // used before by the client (unless it's a retry for the same request)?
  115. requestID = reqID
  116. } else {
  117. requestID = newRequestID()
  118. }
  119. r.Header.Set(requestIDHeader, requestID)
  120. }
  121. }
  122. func (c *uaClient) Do(req *http.Request) (*http.Response, error) {
  123. req.Header.Set("User-Agent", UserAgent)
  124. enforceRequestID(req)
  125. return c.Client.Do(req)
  126. }
  127. // RetryFunc defines the method used to retry a request. If it returns true, the
  128. // request will be retried once.
  129. type RetryFunc func(code int) bool
  130. // ClientOption is the type of options passed to the Client constructor.
  131. type ClientOption func(o *clientOptions) error
  132. type clientOptions struct {
  133. transport http.RoundTripper
  134. timeout time.Duration
  135. rootSHA256 string
  136. rootFilename string
  137. rootBundle []byte
  138. certificate tls.Certificate
  139. getClientCertificate func(*tls.CertificateRequestInfo) (*tls.Certificate, error)
  140. retryFunc RetryFunc
  141. x5cJWK *jose.JSONWebKey
  142. x5cCertFile string
  143. x5cCertStrs []string
  144. x5cCert *x509.Certificate
  145. x5cSubject string
  146. }
  147. func (o *clientOptions) apply(opts []ClientOption) (err error) {
  148. o.applyDefaultIdentity()
  149. for _, fn := range opts {
  150. if err = fn(o); err != nil {
  151. return
  152. }
  153. }
  154. return
  155. }
  156. // applyDefaultIdentity sets the options for the default identity if the
  157. // identity file is present. The identity is enabled by default.
  158. func (o *clientOptions) applyDefaultIdentity() {
  159. if DisableIdentity {
  160. return
  161. }
  162. // Do not load an identity if something fails
  163. i, err := identity.LoadDefaultIdentity()
  164. if err != nil {
  165. return
  166. }
  167. if err := i.Validate(); err != nil {
  168. return
  169. }
  170. crt, err := i.TLSCertificate()
  171. if err != nil {
  172. return
  173. }
  174. o.certificate = crt
  175. o.getClientCertificate = i.GetClientCertificateFunc()
  176. }
  177. // checkTransport checks if other ways to set up a transport have been provided.
  178. // If they have it returns an error.
  179. func (o *clientOptions) checkTransport() error {
  180. if o.transport != nil || o.rootFilename != "" || o.rootSHA256 != "" || o.rootBundle != nil {
  181. return errors.New("multiple transport methods have been configured")
  182. }
  183. return nil
  184. }
  185. // getTransport returns the transport configured in the clientOptions.
  186. func (o *clientOptions) getTransport(endpoint string) (tr http.RoundTripper, err error) {
  187. if o.transport != nil {
  188. tr = o.transport
  189. }
  190. if o.rootFilename != "" {
  191. if tr, err = getTransportFromFile(o.rootFilename); err != nil {
  192. return nil, err
  193. }
  194. }
  195. if o.rootSHA256 != "" {
  196. if tr, err = getTransportFromSHA256(endpoint, o.rootSHA256); err != nil {
  197. return nil, err
  198. }
  199. }
  200. if o.rootBundle != nil {
  201. if tr, err = getTransportFromCABundle(o.rootBundle); err != nil {
  202. return nil, err
  203. }
  204. }
  205. // As the last option attempt to load the default root ca
  206. if tr == nil {
  207. rootFile := getRootCAPath()
  208. if _, err := os.Stat(rootFile); err == nil {
  209. if tr, err = getTransportFromFile(rootFile); err != nil {
  210. return nil, err
  211. }
  212. }
  213. if tr == nil {
  214. return nil, errors.New("a transport, a root cert, or a root sha256 must be used")
  215. }
  216. }
  217. // Add client certificate if available
  218. if o.certificate.Certificate != nil {
  219. switch tr := tr.(type) {
  220. case *http.Transport:
  221. if tr.TLSClientConfig == nil {
  222. tr.TLSClientConfig = &tls.Config{
  223. MinVersion: tls.VersionTLS12,
  224. }
  225. }
  226. if len(tr.TLSClientConfig.Certificates) == 0 && tr.TLSClientConfig.GetClientCertificate == nil {
  227. tr.TLSClientConfig.Certificates = []tls.Certificate{o.certificate}
  228. tr.TLSClientConfig.GetClientCertificate = o.getClientCertificate
  229. }
  230. case *http2.Transport:
  231. if tr.TLSClientConfig == nil {
  232. tr.TLSClientConfig = &tls.Config{
  233. MinVersion: tls.VersionTLS12,
  234. }
  235. }
  236. if len(tr.TLSClientConfig.Certificates) == 0 && tr.TLSClientConfig.GetClientCertificate == nil {
  237. tr.TLSClientConfig.Certificates = []tls.Certificate{o.certificate}
  238. tr.TLSClientConfig.GetClientCertificate = o.getClientCertificate
  239. }
  240. default:
  241. return nil, errors.Errorf("unsupported transport type %T", tr)
  242. }
  243. }
  244. return tr, nil
  245. }
  246. // WithTransport adds a custom transport to the Client. It will fail if a
  247. // previous option to create the transport has been configured.
  248. func WithTransport(tr http.RoundTripper) ClientOption {
  249. return func(o *clientOptions) error {
  250. if err := o.checkTransport(); err != nil {
  251. return err
  252. }
  253. o.transport = tr
  254. return nil
  255. }
  256. }
  257. // WithInsecure adds a insecure transport that bypasses TLS verification.
  258. func WithInsecure() ClientOption {
  259. return func(o *clientOptions) error {
  260. o.transport = &http.Transport{
  261. Proxy: http.ProxyFromEnvironment,
  262. TLSClientConfig: &tls.Config{
  263. MinVersion: tls.VersionTLS12,
  264. //nolint:gosec // insecure option
  265. InsecureSkipVerify: true,
  266. },
  267. }
  268. return nil
  269. }
  270. }
  271. // WithRootFile will create the transport using the given root certificate. It
  272. // will fail if a previous option to create the transport has been configured.
  273. func WithRootFile(filename string) ClientOption {
  274. return func(o *clientOptions) error {
  275. if err := o.checkTransport(); err != nil {
  276. return err
  277. }
  278. o.rootFilename = filename
  279. return nil
  280. }
  281. }
  282. // WithRootSHA256 will create the transport using an insecure client to retrieve
  283. // the root certificate using its fingerprint. It will fail if a previous option
  284. // to create the transport has been configured.
  285. func WithRootSHA256(sum string) ClientOption {
  286. return func(o *clientOptions) error {
  287. if err := o.checkTransport(); err != nil {
  288. return err
  289. }
  290. o.rootSHA256 = sum
  291. return nil
  292. }
  293. }
  294. // WithCABundle will create the transport using the given root certificates. It
  295. // will fail if a previous option to create the transport has been configured.
  296. func WithCABundle(bundle []byte) ClientOption {
  297. return func(o *clientOptions) error {
  298. if err := o.checkTransport(); err != nil {
  299. return err
  300. }
  301. o.rootBundle = bundle
  302. return nil
  303. }
  304. }
  305. // WithCertificate will set the given certificate as the TLS client certificate
  306. // in the client.
  307. func WithCertificate(cert tls.Certificate) ClientOption {
  308. return func(o *clientOptions) error {
  309. o.certificate = cert
  310. return nil
  311. }
  312. }
  313. // WithAdminX5C will set the given file as the X5C certificate for use
  314. // by the client.
  315. func WithAdminX5C(certs []*x509.Certificate, key interface{}, passwordFile string) ClientOption {
  316. return func(o *clientOptions) error {
  317. // Get private key from given key file
  318. var (
  319. err error
  320. opts []jose.Option
  321. )
  322. if passwordFile != "" {
  323. opts = append(opts, jose.WithPasswordFile(passwordFile))
  324. }
  325. blk, err := pemutil.Serialize(key)
  326. if err != nil {
  327. return errors.Wrap(err, "error serializing private key")
  328. }
  329. o.x5cJWK, err = jose.ParseKey(pem.EncodeToMemory(blk), opts...)
  330. if err != nil {
  331. return err
  332. }
  333. o.x5cCertStrs, err = jose.ValidateX5C(certs, o.x5cJWK.Key)
  334. if err != nil {
  335. return errors.Wrap(err, "error validating x5c certificate chain and key for use in x5c header")
  336. }
  337. o.x5cCert = certs[0]
  338. switch leaf := certs[0]; {
  339. case leaf.Subject.CommonName != "":
  340. o.x5cSubject = leaf.Subject.CommonName
  341. case len(leaf.DNSNames) > 0:
  342. o.x5cSubject = leaf.DNSNames[0]
  343. case len(leaf.EmailAddresses) > 0:
  344. o.x5cSubject = leaf.EmailAddresses[0]
  345. }
  346. return nil
  347. }
  348. }
  349. // WithRetryFunc defines a method used to retry a request.
  350. func WithRetryFunc(fn RetryFunc) ClientOption {
  351. return func(o *clientOptions) error {
  352. o.retryFunc = fn
  353. return nil
  354. }
  355. }
  356. // WithTimeout defines the time limit for requests made by this client. The
  357. // timeout includes connection time, any redirects, and reading the response
  358. // body.
  359. func WithTimeout(d time.Duration) ClientOption {
  360. return func(o *clientOptions) error {
  361. o.timeout = d
  362. return nil
  363. }
  364. }
  365. func getTransportFromFile(filename string) (http.RoundTripper, error) {
  366. data, err := os.ReadFile(filename)
  367. if err != nil {
  368. return nil, errors.Wrapf(err, "error reading %s", filename)
  369. }
  370. pool := x509.NewCertPool()
  371. if !pool.AppendCertsFromPEM(data) {
  372. return nil, errors.Errorf("error parsing %s: no certificates found", filename)
  373. }
  374. return getDefaultTransport(&tls.Config{
  375. MinVersion: tls.VersionTLS12,
  376. PreferServerCipherSuites: true,
  377. RootCAs: pool,
  378. }), nil
  379. }
  380. func getTransportFromSHA256(endpoint, sum string) (http.RoundTripper, error) {
  381. u, err := parseEndpoint(endpoint)
  382. if err != nil {
  383. return nil, err
  384. }
  385. caClient := &Client{endpoint: u}
  386. root, err := caClient.Root(sum)
  387. if err != nil {
  388. return nil, err
  389. }
  390. pool := x509.NewCertPool()
  391. pool.AddCert(root.RootPEM.Certificate)
  392. return getDefaultTransport(&tls.Config{
  393. MinVersion: tls.VersionTLS12,
  394. PreferServerCipherSuites: true,
  395. RootCAs: pool,
  396. }), nil
  397. }
  398. func getTransportFromCABundle(bundle []byte) (http.RoundTripper, error) {
  399. pool := x509.NewCertPool()
  400. if !pool.AppendCertsFromPEM(bundle) {
  401. return nil, errors.New("error parsing ca bundle: no certificates found")
  402. }
  403. return getDefaultTransport(&tls.Config{
  404. MinVersion: tls.VersionTLS12,
  405. PreferServerCipherSuites: true,
  406. RootCAs: pool,
  407. }), nil
  408. }
  409. // parseEndpoint parses and validates the given endpoint. It supports general
  410. // URLs like https://ca.smallstep.com[:port][/path], and incomplete URLs like
  411. // ca.smallstep.com[:port][/path].
  412. func parseEndpoint(endpoint string) (*url.URL, error) {
  413. u, err := url.Parse(endpoint)
  414. if err != nil {
  415. return nil, errors.Wrapf(err, "error parsing endpoint '%s'", endpoint)
  416. }
  417. // URLs are generally parsed as:
  418. // [scheme:][//[userinfo@]host][/]path[?query][#fragment]
  419. // But URLs that do not start with a slash after the scheme are interpreted as
  420. // scheme:opaque[?query][#fragment]
  421. if u.Opaque == "" {
  422. if u.Scheme == "" {
  423. u.Scheme = "https"
  424. }
  425. if u.Host == "" {
  426. // endpoint looks like ca.smallstep.com or ca.smallstep.com/1.0/sign
  427. if u.Path != "" {
  428. parts := strings.SplitN(u.Path, "/", 2)
  429. u.Host = parts[0]
  430. if len(parts) == 2 {
  431. u.Path = parts[1]
  432. } else {
  433. u.Path = ""
  434. }
  435. return parseEndpoint(u.String())
  436. }
  437. return nil, errors.Errorf("error parsing endpoint: url '%s' is not valid", endpoint)
  438. }
  439. return u, nil
  440. }
  441. // scheme:opaque[?query][#fragment]
  442. // endpoint looks like ca.smallstep.com:443 or ca.smallstep.com:443/1.0/sign
  443. return parseEndpoint("https://" + endpoint)
  444. }
  445. // ProvisionerOption is the type of options passed to the Provisioner method.
  446. type ProvisionerOption func(o *ProvisionerOptions) error
  447. // ProvisionerOptions stores options for the provisioner CRUD API.
  448. type ProvisionerOptions struct {
  449. Cursor string
  450. Limit int
  451. ID string
  452. Name string
  453. }
  454. // Apply caches provisioner options on a struct for later use.
  455. func (o *ProvisionerOptions) Apply(opts []ProvisionerOption) (err error) {
  456. for _, fn := range opts {
  457. if err = fn(o); err != nil {
  458. return
  459. }
  460. }
  461. return
  462. }
  463. func (o *ProvisionerOptions) rawQuery() string {
  464. v := url.Values{}
  465. if o.Cursor != "" {
  466. v.Set("cursor", o.Cursor)
  467. }
  468. if o.Limit > 0 {
  469. v.Set("limit", strconv.Itoa(o.Limit))
  470. }
  471. if o.ID != "" {
  472. v.Set("id", o.ID)
  473. }
  474. if o.Name != "" {
  475. v.Set("name", o.Name)
  476. }
  477. return v.Encode()
  478. }
  479. // WithProvisionerCursor will request the provisioners starting with the given cursor.
  480. func WithProvisionerCursor(cursor string) ProvisionerOption {
  481. return func(o *ProvisionerOptions) error {
  482. o.Cursor = cursor
  483. return nil
  484. }
  485. }
  486. // WithProvisionerLimit will request the given number of provisioners.
  487. func WithProvisionerLimit(limit int) ProvisionerOption {
  488. return func(o *ProvisionerOptions) error {
  489. o.Limit = limit
  490. return nil
  491. }
  492. }
  493. // WithProvisionerID will request the given provisioner.
  494. func WithProvisionerID(id string) ProvisionerOption {
  495. return func(o *ProvisionerOptions) error {
  496. o.ID = id
  497. return nil
  498. }
  499. }
  500. // WithProvisionerName will request the given provisioner.
  501. func WithProvisionerName(name string) ProvisionerOption {
  502. return func(o *ProvisionerOptions) error {
  503. o.Name = name
  504. return nil
  505. }
  506. }
  507. // Client implements an HTTP client for the CA server.
  508. type Client struct {
  509. client *uaClient
  510. endpoint *url.URL
  511. retryFunc RetryFunc
  512. timeout time.Duration
  513. opts []ClientOption
  514. }
  515. // NewClient creates a new Client with the given endpoint and options.
  516. func NewClient(endpoint string, opts ...ClientOption) (*Client, error) {
  517. u, err := parseEndpoint(endpoint)
  518. if err != nil {
  519. return nil, err
  520. }
  521. // Retrieve transport from options.
  522. o := defaultClientOptions()
  523. if err := o.apply(opts); err != nil {
  524. return nil, err
  525. }
  526. tr, err := o.getTransport(endpoint)
  527. if err != nil {
  528. return nil, err
  529. }
  530. return &Client{
  531. client: newClient(tr, o.timeout),
  532. endpoint: u,
  533. retryFunc: o.retryFunc,
  534. timeout: o.timeout,
  535. opts: opts,
  536. }, nil
  537. }
  538. func (c *Client) retryOnError(r *http.Response) bool {
  539. if c.retryFunc != nil {
  540. if c.retryFunc(r.StatusCode) {
  541. o := defaultClientOptions()
  542. if err := o.apply(c.opts); err != nil {
  543. return false
  544. }
  545. tr, err := o.getTransport(c.endpoint.String())
  546. if err != nil {
  547. return false
  548. }
  549. r.Body.Close()
  550. c.client.SetTransport(tr)
  551. return true
  552. }
  553. }
  554. return false
  555. }
  556. // GetCaURL returns the configured CA url.
  557. func (c *Client) GetCaURL() string {
  558. return c.endpoint.String()
  559. }
  560. // GetRootCAs returns the RootCAs certificate pool from the configured
  561. // transport.
  562. func (c *Client) GetRootCAs() *x509.CertPool {
  563. switch t := c.client.GetTransport().(type) {
  564. case *http.Transport:
  565. if t.TLSClientConfig != nil {
  566. return t.TLSClientConfig.RootCAs
  567. }
  568. return nil
  569. case *http2.Transport:
  570. if t.TLSClientConfig != nil {
  571. return t.TLSClientConfig.RootCAs
  572. }
  573. return nil
  574. default:
  575. return nil
  576. }
  577. }
  578. // SetTransport updates the transport of the internal HTTP client.
  579. func (c *Client) SetTransport(tr http.RoundTripper) {
  580. c.client.SetTransport(tr)
  581. }
  582. // CloseIdleConnections closes any connections on its Transport which were
  583. // previously connected from previous requests but are now sitting idle in a
  584. // "keep-alive" state. It does not interrupt any connections currently in use.
  585. func (c *Client) CloseIdleConnections() {
  586. c.client.CloseIdleConnections()
  587. }
  588. // Version performs the version request to the CA with an empty context and returns the
  589. // api.VersionResponse struct.
  590. func (c *Client) Version() (*api.VersionResponse, error) {
  591. return c.VersionWithContext(context.Background())
  592. }
  593. // VersionWithContext performs the version request to the CA with the provided context
  594. // and returns the api.VersionResponse struct.
  595. func (c *Client) VersionWithContext(ctx context.Context) (*api.VersionResponse, error) {
  596. var retried bool
  597. u := c.endpoint.ResolveReference(&url.URL{Path: "/version"})
  598. retry:
  599. resp, err := c.client.GetWithContext(ctx, u.String())
  600. if err != nil {
  601. return nil, clientError(err)
  602. }
  603. if resp.StatusCode >= 400 {
  604. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  605. retried = true
  606. goto retry
  607. }
  608. return nil, readError(resp)
  609. }
  610. var version api.VersionResponse
  611. if err := readJSON(resp.Body, &version); err != nil {
  612. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Version; error reading %s", u)
  613. }
  614. return &version, nil
  615. }
  616. // Health performs the health request to the CA with an empty context
  617. // and returns the api.HealthResponse struct.
  618. func (c *Client) Health() (*api.HealthResponse, error) {
  619. return c.HealthWithContext(context.Background())
  620. }
  621. // HealthWithContext performs the health request to the CA with the provided context
  622. // and returns the api.HealthResponse struct.
  623. func (c *Client) HealthWithContext(ctx context.Context) (*api.HealthResponse, error) {
  624. var retried bool
  625. u := c.endpoint.ResolveReference(&url.URL{Path: "/health"})
  626. retry:
  627. resp, err := c.client.GetWithContext(ctx, u.String())
  628. if err != nil {
  629. return nil, clientError(err)
  630. }
  631. if resp.StatusCode >= 400 {
  632. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  633. retried = true
  634. goto retry
  635. }
  636. return nil, readError(resp)
  637. }
  638. var health api.HealthResponse
  639. if err := readJSON(resp.Body, &health); err != nil {
  640. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Health; error reading %s", u)
  641. }
  642. return &health, nil
  643. }
  644. // Root performs the root request to the CA with an empty context and the provided
  645. // SHA256 and returns the api.RootResponse struct. It uses an insecure client, but
  646. // it checks the resulting root certificate with the given SHA256, returning an error
  647. // if they do not match.
  648. func (c *Client) Root(sha256Sum string) (*api.RootResponse, error) {
  649. return c.RootWithContext(context.Background(), sha256Sum)
  650. }
  651. // RootWithContext performs the root request to the CA with an empty context and the provided
  652. // SHA256 and returns the api.RootResponse struct. It uses an insecure client, but
  653. // it checks the resulting root certificate with the given SHA256, returning an error
  654. // if they do not match.
  655. func (c *Client) RootWithContext(ctx context.Context, sha256Sum string) (*api.RootResponse, error) {
  656. var retried bool
  657. sha256Sum = strings.ToLower(strings.ReplaceAll(sha256Sum, "-", ""))
  658. u := c.endpoint.ResolveReference(&url.URL{Path: "/root/" + sha256Sum})
  659. retry:
  660. resp, err := newInsecureClient().GetWithContext(ctx, u.String())
  661. if err != nil {
  662. return nil, clientError(err)
  663. }
  664. if resp.StatusCode >= 400 {
  665. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  666. retried = true
  667. goto retry
  668. }
  669. return nil, readError(resp)
  670. }
  671. var root api.RootResponse
  672. if err := readJSON(resp.Body, &root); err != nil {
  673. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Root; error reading %s", u)
  674. }
  675. // verify the sha256
  676. sum := sha256.Sum256(root.RootPEM.Raw)
  677. if !strings.EqualFold(sha256Sum, strings.ToLower(hex.EncodeToString(sum[:]))) {
  678. return nil, errs.BadRequest("root certificate fingerprint does not match")
  679. }
  680. return &root, nil
  681. }
  682. // Sign performs the sign request to the CA with an empty context and returns
  683. // the api.SignResponse struct.
  684. func (c *Client) Sign(req *api.SignRequest) (*api.SignResponse, error) {
  685. return c.SignWithContext(context.Background(), req)
  686. }
  687. // SignWithContext performs the sign request to the CA with the provided context
  688. // and returns the api.SignResponse struct.
  689. func (c *Client) SignWithContext(ctx context.Context, req *api.SignRequest) (*api.SignResponse, error) {
  690. var retried bool
  691. body, err := json.Marshal(req)
  692. if err != nil {
  693. return nil, errs.Wrap(http.StatusInternalServerError, err, "client.Sign; error marshaling request")
  694. }
  695. u := c.endpoint.ResolveReference(&url.URL{Path: "/sign"})
  696. retry:
  697. resp, err := c.client.PostWithContext(ctx, u.String(), "application/json", bytes.NewReader(body))
  698. if err != nil {
  699. return nil, clientError(err)
  700. }
  701. if resp.StatusCode >= 400 {
  702. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  703. retried = true
  704. goto retry
  705. }
  706. return nil, readError(resp)
  707. }
  708. var sign api.SignResponse
  709. if err := readJSON(resp.Body, &sign); err != nil {
  710. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Sign; error reading %s", u)
  711. }
  712. // Add tls.ConnectionState:
  713. // We'll extract the root certificate from the verified chains
  714. sign.TLS = resp.TLS
  715. return &sign, nil
  716. }
  717. // Renew performs the renew request to the CA with an empty context and
  718. // returns the api.SignResponse struct.
  719. func (c *Client) Renew(tr http.RoundTripper) (*api.SignResponse, error) {
  720. return c.RenewWithContext(context.Background(), tr)
  721. }
  722. // RenewWithContext performs the renew request to the CA with the provided context
  723. // and returns the api.SignResponse struct.
  724. func (c *Client) RenewWithContext(ctx context.Context, tr http.RoundTripper) (*api.SignResponse, error) {
  725. var retried bool
  726. u := c.endpoint.ResolveReference(&url.URL{Path: "/renew"})
  727. httpClient := &http.Client{Transport: tr}
  728. retry:
  729. req, err := http.NewRequestWithContext(ctx, "POST", u.String(), http.NoBody)
  730. if err != nil {
  731. return nil, err
  732. }
  733. req.Header.Set("Content-Type", "application/json")
  734. resp, err := httpClient.Do(req)
  735. if err != nil {
  736. return nil, clientError(err)
  737. }
  738. if resp.StatusCode >= 400 {
  739. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  740. retried = true
  741. goto retry
  742. }
  743. return nil, readError(resp)
  744. }
  745. var sign api.SignResponse
  746. if err := readJSON(resp.Body, &sign); err != nil {
  747. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Renew; error reading %s", u)
  748. }
  749. return &sign, nil
  750. }
  751. // RenewWithToken performs the renew request to the CA with the given
  752. // authorization token and and empty context and returns the api.SignResponse struct.
  753. // This method is generally used to renew an expired certificate.
  754. func (c *Client) RenewWithToken(token string) (*api.SignResponse, error) {
  755. return c.RenewWithTokenAndContext(context.Background(), token)
  756. }
  757. // RenewWithTokenAndContext performs the renew request to the CA with the given
  758. // authorization token and context and returns the api.SignResponse struct.
  759. // This method is generally used to renew an expired certificate.
  760. func (c *Client) RenewWithTokenAndContext(ctx context.Context, token string) (*api.SignResponse, error) {
  761. var retried bool
  762. u := c.endpoint.ResolveReference(&url.URL{Path: "/renew"})
  763. req, err := http.NewRequestWithContext(ctx, "POST", u.String(), http.NoBody)
  764. if err != nil {
  765. return nil, errors.Wrapf(err, "create POST %s request failed", u)
  766. }
  767. req.Header.Add("Authorization", "Bearer "+token)
  768. retry:
  769. resp, err := c.client.Do(req)
  770. if err != nil {
  771. return nil, clientError(err)
  772. }
  773. if resp.StatusCode >= 400 {
  774. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  775. retried = true
  776. goto retry
  777. }
  778. return nil, readError(resp)
  779. }
  780. var sign api.SignResponse
  781. if err := readJSON(resp.Body, &sign); err != nil {
  782. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.RenewWithToken; error reading %s", u)
  783. }
  784. return &sign, nil
  785. }
  786. // Rekey performs the rekey request to the CA with an empty context and
  787. // returns the api.SignResponse struct.
  788. func (c *Client) Rekey(req *api.RekeyRequest, tr http.RoundTripper) (*api.SignResponse, error) {
  789. return c.RekeyWithContext(context.Background(), req, tr)
  790. }
  791. // RekeyWithContext performs the rekey request to the CA with the provided context
  792. // and returns the api.SignResponse struct.
  793. func (c *Client) RekeyWithContext(ctx context.Context, req *api.RekeyRequest, tr http.RoundTripper) (*api.SignResponse, error) {
  794. var retried bool
  795. body, err := json.Marshal(req)
  796. if err != nil {
  797. return nil, errors.Wrap(err, "error marshaling request")
  798. }
  799. u := c.endpoint.ResolveReference(&url.URL{Path: "/rekey"})
  800. httpClient := &http.Client{Transport: tr}
  801. retry:
  802. httpReq, err := http.NewRequestWithContext(ctx, "POST", u.String(), bytes.NewReader(body))
  803. if err != nil {
  804. return nil, err
  805. }
  806. httpReq.Header.Set("Content-Type", "application/json")
  807. resp, err := httpClient.Do(httpReq)
  808. if err != nil {
  809. return nil, clientError(err)
  810. }
  811. if resp.StatusCode >= 400 {
  812. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  813. retried = true
  814. goto retry
  815. }
  816. return nil, readError(resp)
  817. }
  818. var sign api.SignResponse
  819. if err := readJSON(resp.Body, &sign); err != nil {
  820. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Rekey; error reading %s", u)
  821. }
  822. return &sign, nil
  823. }
  824. // Revoke performs the revoke request to the CA with an empty context and returns
  825. // the api.RevokeResponse struct.
  826. func (c *Client) Revoke(req *api.RevokeRequest, tr http.RoundTripper) (*api.RevokeResponse, error) {
  827. return c.RevokeWithContext(context.Background(), req, tr)
  828. }
  829. // RevokeWithContext performs the revoke request to the CA with the provided context and
  830. // returns the api.RevokeResponse struct.
  831. func (c *Client) RevokeWithContext(ctx context.Context, req *api.RevokeRequest, tr http.RoundTripper) (*api.RevokeResponse, error) {
  832. var retried bool
  833. body, err := json.Marshal(req)
  834. if err != nil {
  835. return nil, errors.Wrap(err, "error marshaling request")
  836. }
  837. var uaClient *uaClient
  838. retry:
  839. if tr != nil {
  840. uaClient = newClient(tr, c.timeout)
  841. } else {
  842. uaClient = c.client
  843. }
  844. u := c.endpoint.ResolveReference(&url.URL{Path: "/revoke"})
  845. resp, err := uaClient.PostWithContext(ctx, u.String(), "application/json", bytes.NewReader(body))
  846. if err != nil {
  847. return nil, clientError(err)
  848. }
  849. if resp.StatusCode >= 400 {
  850. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  851. retried = true
  852. goto retry
  853. }
  854. return nil, readError(resp)
  855. }
  856. var revoke api.RevokeResponse
  857. if err := readJSON(resp.Body, &revoke); err != nil {
  858. return nil, errors.Wrapf(err, "error reading %s", u)
  859. }
  860. return &revoke, nil
  861. }
  862. // Provisioners performs the provisioners request to the CA with an empty context
  863. // and returns the api.ProvisionersResponse struct with a map of provisioners.
  864. //
  865. // ProvisionerOption WithProvisionerCursor and WithProvisionLimit can be used to
  866. // paginate the provisioners.
  867. func (c *Client) Provisioners(opts ...ProvisionerOption) (*api.ProvisionersResponse, error) {
  868. return c.ProvisionersWithContext(context.Background(), opts...)
  869. }
  870. // ProvisionersWithContext performs the provisioners request to the CA with the provided context
  871. // and returns the api.ProvisionersResponse struct with a map of provisioners.
  872. //
  873. // ProvisionerOption WithProvisionerCursor and WithProvisionLimit can be used to
  874. // paginate the provisioners.
  875. func (c *Client) ProvisionersWithContext(ctx context.Context, opts ...ProvisionerOption) (*api.ProvisionersResponse, error) {
  876. var retried bool
  877. o := new(ProvisionerOptions)
  878. if err := o.Apply(opts); err != nil {
  879. return nil, err
  880. }
  881. u := c.endpoint.ResolveReference(&url.URL{
  882. Path: "/provisioners",
  883. RawQuery: o.rawQuery(),
  884. })
  885. retry:
  886. resp, err := c.client.GetWithContext(ctx, u.String())
  887. if err != nil {
  888. return nil, clientError(err)
  889. }
  890. if resp.StatusCode >= 400 {
  891. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  892. retried = true
  893. goto retry
  894. }
  895. return nil, readError(resp)
  896. }
  897. var provisioners api.ProvisionersResponse
  898. if err := readJSON(resp.Body, &provisioners); err != nil {
  899. return nil, errors.Wrapf(err, "error reading %s", u)
  900. }
  901. return &provisioners, nil
  902. }
  903. // ProvisionerKey performs the request to the CA with an empty context to get
  904. // the encrypted key for the given provisioner kid and returns the api.ProvisionerKeyResponse
  905. // struct with the encrypted key.
  906. func (c *Client) ProvisionerKey(kid string) (*api.ProvisionerKeyResponse, error) {
  907. return c.ProvisionerKeyWithContext(context.Background(), kid)
  908. }
  909. // ProvisionerKeyWithContext performs the request to the CA with the provided context to get
  910. // the encrypted key for the given provisioner kid and returns the api.ProvisionerKeyResponse
  911. // struct with the encrypted key.
  912. func (c *Client) ProvisionerKeyWithContext(ctx context.Context, kid string) (*api.ProvisionerKeyResponse, error) {
  913. var retried bool
  914. u := c.endpoint.ResolveReference(&url.URL{Path: "/provisioners/" + kid + "/encrypted-key"})
  915. retry:
  916. resp, err := c.client.GetWithContext(ctx, u.String())
  917. if err != nil {
  918. return nil, clientError(err)
  919. }
  920. if resp.StatusCode >= 400 {
  921. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  922. retried = true
  923. goto retry
  924. }
  925. return nil, readError(resp)
  926. }
  927. var key api.ProvisionerKeyResponse
  928. if err := readJSON(resp.Body, &key); err != nil {
  929. return nil, errors.Wrapf(err, "error reading %s", u)
  930. }
  931. return &key, nil
  932. }
  933. // Roots performs the get roots request to the CA with an empty context
  934. // and returns the api.RootsResponse struct.
  935. func (c *Client) Roots() (*api.RootsResponse, error) {
  936. return c.RootsWithContext(context.Background())
  937. }
  938. // RootsWithContext performs the get roots request to the CA with the provided context
  939. // and returns the api.RootsResponse struct.
  940. func (c *Client) RootsWithContext(ctx context.Context) (*api.RootsResponse, error) {
  941. var retried bool
  942. u := c.endpoint.ResolveReference(&url.URL{Path: "/roots"})
  943. retry:
  944. resp, err := c.client.GetWithContext(ctx, u.String())
  945. if err != nil {
  946. return nil, clientError(err)
  947. }
  948. if resp.StatusCode >= 400 {
  949. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  950. retried = true
  951. goto retry
  952. }
  953. return nil, readError(resp)
  954. }
  955. var roots api.RootsResponse
  956. if err := readJSON(resp.Body, &roots); err != nil {
  957. return nil, errors.Wrapf(err, "error reading %s", u)
  958. }
  959. return &roots, nil
  960. }
  961. // Federation performs the get federation request to the CA with an empty context
  962. // and returns the api.FederationResponse struct.
  963. func (c *Client) Federation() (*api.FederationResponse, error) {
  964. return c.FederationWithContext(context.Background())
  965. }
  966. // FederationWithContext performs the get federation request to the CA with the provided context
  967. // and returns the api.FederationResponse struct.
  968. func (c *Client) FederationWithContext(ctx context.Context) (*api.FederationResponse, error) {
  969. var retried bool
  970. u := c.endpoint.ResolveReference(&url.URL{Path: "/federation"})
  971. retry:
  972. resp, err := c.client.GetWithContext(ctx, u.String())
  973. if err != nil {
  974. return nil, clientError(err)
  975. }
  976. if resp.StatusCode >= 400 {
  977. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  978. retried = true
  979. goto retry
  980. }
  981. return nil, readError(resp)
  982. }
  983. var federation api.FederationResponse
  984. if err := readJSON(resp.Body, &federation); err != nil {
  985. return nil, errors.Wrapf(err, "error reading %s", u)
  986. }
  987. return &federation, nil
  988. }
  989. // SSHSign performs the POST /ssh/sign request to the CA with an empty context
  990. // and returns the api.SSHSignResponse struct.
  991. func (c *Client) SSHSign(req *api.SSHSignRequest) (*api.SSHSignResponse, error) {
  992. return c.SSHSignWithContext(context.Background(), req)
  993. }
  994. // SSHSignWithContext performs the POST /ssh/sign request to the CA with the provided context
  995. // and returns the api.SSHSignResponse struct.
  996. func (c *Client) SSHSignWithContext(ctx context.Context, req *api.SSHSignRequest) (*api.SSHSignResponse, error) {
  997. var retried bool
  998. body, err := json.Marshal(req)
  999. if err != nil {
  1000. return nil, errors.Wrap(err, "error marshaling request")
  1001. }
  1002. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/sign"})
  1003. retry:
  1004. resp, err := c.client.PostWithContext(ctx, u.String(), "application/json", bytes.NewReader(body))
  1005. if err != nil {
  1006. return nil, clientError(err)
  1007. }
  1008. if resp.StatusCode >= 400 {
  1009. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  1010. retried = true
  1011. goto retry
  1012. }
  1013. return nil, readError(resp)
  1014. }
  1015. var sign api.SSHSignResponse
  1016. if err := readJSON(resp.Body, &sign); err != nil {
  1017. return nil, errors.Wrapf(err, "error reading %s", u)
  1018. }
  1019. return &sign, nil
  1020. }
  1021. // SSHRenew performs the POST /ssh/renew request to the CA with an empty context
  1022. // and returns the api.SSHRenewResponse struct.
  1023. func (c *Client) SSHRenew(req *api.SSHRenewRequest) (*api.SSHRenewResponse, error) {
  1024. return c.SSHRenewWithContext(context.Background(), req)
  1025. }
  1026. // SSHRenewWithContext performs the POST /ssh/renew request to the CA with the provided context
  1027. // and returns the api.SSHRenewResponse struct.
  1028. func (c *Client) SSHRenewWithContext(ctx context.Context, req *api.SSHRenewRequest) (*api.SSHRenewResponse, error) {
  1029. var retried bool
  1030. body, err := json.Marshal(req)
  1031. if err != nil {
  1032. return nil, errors.Wrap(err, "error marshaling request")
  1033. }
  1034. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/renew"})
  1035. retry:
  1036. resp, err := c.client.PostWithContext(ctx, u.String(), "application/json", bytes.NewReader(body))
  1037. if err != nil {
  1038. return nil, clientError(err)
  1039. }
  1040. if resp.StatusCode >= 400 {
  1041. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  1042. retried = true
  1043. goto retry
  1044. }
  1045. return nil, readError(resp)
  1046. }
  1047. var renew api.SSHRenewResponse
  1048. if err := readJSON(resp.Body, &renew); err != nil {
  1049. return nil, errors.Wrapf(err, "error reading %s", u)
  1050. }
  1051. return &renew, nil
  1052. }
  1053. // SSHRekey performs the POST /ssh/rekey request to the CA with an empty context
  1054. // and returns the api.SSHRekeyResponse struct.
  1055. func (c *Client) SSHRekey(req *api.SSHRekeyRequest) (*api.SSHRekeyResponse, error) {
  1056. return c.SSHRekeyWithContext(context.Background(), req)
  1057. }
  1058. // SSHRekeyWithContext performs the POST /ssh/rekey request to the CA with the provided context
  1059. // and returns the api.SSHRekeyResponse struct.
  1060. func (c *Client) SSHRekeyWithContext(ctx context.Context, req *api.SSHRekeyRequest) (*api.SSHRekeyResponse, error) {
  1061. var retried bool
  1062. body, err := json.Marshal(req)
  1063. if err != nil {
  1064. return nil, errors.Wrap(err, "error marshaling request")
  1065. }
  1066. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/rekey"})
  1067. retry:
  1068. resp, err := c.client.PostWithContext(ctx, u.String(), "application/json", bytes.NewReader(body))
  1069. if err != nil {
  1070. return nil, clientError(err)
  1071. }
  1072. if resp.StatusCode >= 400 {
  1073. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  1074. retried = true
  1075. goto retry
  1076. }
  1077. return nil, readError(resp)
  1078. }
  1079. var rekey api.SSHRekeyResponse
  1080. if err := readJSON(resp.Body, &rekey); err != nil {
  1081. return nil, errors.Wrapf(err, "error reading %s", u)
  1082. }
  1083. return &rekey, nil
  1084. }
  1085. // SSHRevoke performs the POST /ssh/revoke request to the CA with an empty context
  1086. // and returns the api.SSHRevokeResponse struct.
  1087. func (c *Client) SSHRevoke(req *api.SSHRevokeRequest) (*api.SSHRevokeResponse, error) {
  1088. return c.SSHRevokeWithContext(context.Background(), req)
  1089. }
  1090. // SSHRevokeWithContext performs the POST /ssh/revoke request to the CA with the provided context
  1091. // and returns the api.SSHRevokeResponse struct.
  1092. func (c *Client) SSHRevokeWithContext(ctx context.Context, req *api.SSHRevokeRequest) (*api.SSHRevokeResponse, error) {
  1093. var retried bool
  1094. body, err := json.Marshal(req)
  1095. if err != nil {
  1096. return nil, errors.Wrap(err, "error marshaling request")
  1097. }
  1098. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/revoke"})
  1099. retry:
  1100. resp, err := c.client.PostWithContext(ctx, u.String(), "application/json", bytes.NewReader(body))
  1101. if err != nil {
  1102. return nil, clientError(err)
  1103. }
  1104. if resp.StatusCode >= 400 {
  1105. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  1106. retried = true
  1107. goto retry
  1108. }
  1109. return nil, readError(resp)
  1110. }
  1111. var revoke api.SSHRevokeResponse
  1112. if err := readJSON(resp.Body, &revoke); err != nil {
  1113. return nil, errors.Wrapf(err, "error reading %s", u)
  1114. }
  1115. return &revoke, nil
  1116. }
  1117. // SSHRoots performs the GET /ssh/roots request to the CA with an empty context
  1118. // and returns the api.SSHRootsResponse struct.
  1119. func (c *Client) SSHRoots() (*api.SSHRootsResponse, error) {
  1120. return c.SSHRootsWithContext(context.Background())
  1121. }
  1122. // SSHRootsWithContext performs the GET /ssh/roots request to the CA with the provided context
  1123. // and returns the api.SSHRootsResponse struct.
  1124. func (c *Client) SSHRootsWithContext(ctx context.Context) (*api.SSHRootsResponse, error) {
  1125. var retried bool
  1126. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/roots"})
  1127. retry:
  1128. resp, err := c.client.GetWithContext(ctx, u.String())
  1129. if err != nil {
  1130. return nil, clientError(err)
  1131. }
  1132. if resp.StatusCode >= 400 {
  1133. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  1134. retried = true
  1135. goto retry
  1136. }
  1137. return nil, readError(resp)
  1138. }
  1139. var keys api.SSHRootsResponse
  1140. if err := readJSON(resp.Body, &keys); err != nil {
  1141. return nil, errors.Wrapf(err, "error reading %s", u)
  1142. }
  1143. return &keys, nil
  1144. }
  1145. // SSHFederation performs the get /ssh/federation request to the CA with an empty context
  1146. // and returns the api.SSHRootsResponse struct.
  1147. func (c *Client) SSHFederation() (*api.SSHRootsResponse, error) {
  1148. return c.SSHFederationWithContext(context.Background())
  1149. }
  1150. // SSHFederationWithContext performs the get /ssh/federation request to the CA with the provided context
  1151. // and returns the api.SSHRootsResponse struct.
  1152. func (c *Client) SSHFederationWithContext(ctx context.Context) (*api.SSHRootsResponse, error) {
  1153. var retried bool
  1154. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/federation"})
  1155. retry:
  1156. resp, err := c.client.GetWithContext(ctx, u.String())
  1157. if err != nil {
  1158. return nil, clientError(err)
  1159. }
  1160. if resp.StatusCode >= 400 {
  1161. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  1162. retried = true
  1163. goto retry
  1164. }
  1165. return nil, readError(resp)
  1166. }
  1167. var keys api.SSHRootsResponse
  1168. if err := readJSON(resp.Body, &keys); err != nil {
  1169. return nil, errors.Wrapf(err, "error reading %s", u)
  1170. }
  1171. return &keys, nil
  1172. }
  1173. // SSHConfig performs the POST /ssh/config request to the CA with an empty context
  1174. // to get the ssh configuration templates.
  1175. func (c *Client) SSHConfig(req *api.SSHConfigRequest) (*api.SSHConfigResponse, error) {
  1176. return c.SSHConfigWithContext(context.Background(), req)
  1177. }
  1178. // SSHConfigWithContext performs the POST /ssh/config request to the CA with the provided context
  1179. // to get the ssh configuration templates.
  1180. func (c *Client) SSHConfigWithContext(ctx context.Context, req *api.SSHConfigRequest) (*api.SSHConfigResponse, error) {
  1181. var retried bool
  1182. body, err := json.Marshal(req)
  1183. if err != nil {
  1184. return nil, errors.Wrap(err, "error marshaling request")
  1185. }
  1186. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/config"})
  1187. retry:
  1188. resp, err := c.client.PostWithContext(ctx, u.String(), "application/json", bytes.NewReader(body))
  1189. if err != nil {
  1190. return nil, clientError(err)
  1191. }
  1192. if resp.StatusCode >= 400 {
  1193. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  1194. retried = true
  1195. goto retry
  1196. }
  1197. return nil, readError(resp)
  1198. }
  1199. var cfg api.SSHConfigResponse
  1200. if err := readJSON(resp.Body, &cfg); err != nil {
  1201. return nil, errors.Wrapf(err, "error reading %s", u)
  1202. }
  1203. return &cfg, nil
  1204. }
  1205. // SSHCheckHost performs the POST /ssh/check-host request to the CA with an empty context,
  1206. // the principal and a token and returns the api.SSHCheckPrincipalResponse.
  1207. func (c *Client) SSHCheckHost(principal, token string) (*api.SSHCheckPrincipalResponse, error) {
  1208. return c.SSHCheckHostWithContext(context.Background(), principal, token)
  1209. }
  1210. // SSHCheckHostWithContext performs the POST /ssh/check-host request to the CA with the provided context,
  1211. // principal and token and returns the api.SSHCheckPrincipalResponse.
  1212. func (c *Client) SSHCheckHostWithContext(ctx context.Context, principal, token string) (*api.SSHCheckPrincipalResponse, error) {
  1213. var retried bool
  1214. body, err := json.Marshal(&api.SSHCheckPrincipalRequest{
  1215. Type: provisioner.SSHHostCert,
  1216. Principal: principal,
  1217. Token: token,
  1218. })
  1219. if err != nil {
  1220. return nil, errs.Wrap(http.StatusInternalServerError, err, "error marshaling request",
  1221. errs.WithMessage("Failed to marshal the check-host request"))
  1222. }
  1223. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/check-host"})
  1224. retry:
  1225. resp, err := c.client.PostWithContext(ctx, u.String(), "application/json", bytes.NewReader(body))
  1226. if err != nil {
  1227. return nil, clientError(err)
  1228. }
  1229. if resp.StatusCode >= 400 {
  1230. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  1231. retried = true
  1232. goto retry
  1233. }
  1234. return nil, readError(resp)
  1235. }
  1236. var check api.SSHCheckPrincipalResponse
  1237. if err := readJSON(resp.Body, &check); err != nil {
  1238. return nil, errs.Wrapf(http.StatusInternalServerError, err, "error reading %s response",
  1239. []any{u, errs.WithMessage("Failed to parse response from /ssh/check-host endpoint")}...)
  1240. }
  1241. return &check, nil
  1242. }
  1243. // SSHGetHosts performs the GET /ssh/get-hosts request to the CA with an empty context.
  1244. func (c *Client) SSHGetHosts() (*api.SSHGetHostsResponse, error) {
  1245. return c.SSHGetHostsWithContext(context.Background())
  1246. }
  1247. // SSHGetHostsWithContext performs the GET /ssh/get-hosts request to the CA with the provided context.
  1248. func (c *Client) SSHGetHostsWithContext(ctx context.Context) (*api.SSHGetHostsResponse, error) {
  1249. var retried bool
  1250. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/hosts"})
  1251. retry:
  1252. resp, err := c.client.GetWithContext(ctx, u.String())
  1253. if err != nil {
  1254. return nil, clientError(err)
  1255. }
  1256. if resp.StatusCode >= 400 {
  1257. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  1258. retried = true
  1259. goto retry
  1260. }
  1261. return nil, readError(resp)
  1262. }
  1263. var hosts api.SSHGetHostsResponse
  1264. if err := readJSON(resp.Body, &hosts); err != nil {
  1265. return nil, errors.Wrapf(err, "error reading %s", u)
  1266. }
  1267. return &hosts, nil
  1268. }
  1269. // SSHBastion performs the POST /ssh/bastion request to the CA with an empty context.
  1270. func (c *Client) SSHBastion(req *api.SSHBastionRequest) (*api.SSHBastionResponse, error) {
  1271. return c.SSHBastionWithContext(context.Background(), req)
  1272. }
  1273. // SSHBastionWithContext performs the POST /ssh/bastion request to the CA with the provided context.
  1274. func (c *Client) SSHBastionWithContext(ctx context.Context, req *api.SSHBastionRequest) (*api.SSHBastionResponse, error) {
  1275. var retried bool
  1276. body, err := json.Marshal(req)
  1277. if err != nil {
  1278. return nil, errors.Wrap(err, "client.SSHBastion; error marshaling request")
  1279. }
  1280. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/bastion"})
  1281. retry:
  1282. resp, err := c.client.PostWithContext(ctx, u.String(), "application/json", bytes.NewReader(body))
  1283. if err != nil {
  1284. return nil, clientError(err)
  1285. }
  1286. if resp.StatusCode >= 400 {
  1287. if !retried && c.retryOnError(resp) { //nolint:contextcheck // deeply nested context; retry using the same context
  1288. retried = true
  1289. goto retry
  1290. }
  1291. return nil, readError(resp)
  1292. }
  1293. var bastion api.SSHBastionResponse
  1294. if err := readJSON(resp.Body, &bastion); err != nil {
  1295. return nil, errors.Wrapf(err, "client.SSHBastion; error reading %s", u)
  1296. }
  1297. return &bastion, nil
  1298. }
  1299. // RootFingerprint is a helper method that returns the current root fingerprint.
  1300. // It does an health connection and gets the fingerprint from the TLS verified chains.
  1301. func (c *Client) RootFingerprint() (string, error) {
  1302. return c.RootFingerprintWithContext(context.Background())
  1303. }
  1304. // RootFingerprintWithContext is a helper method that returns the current root fingerprint.
  1305. // It does an health connection and gets the fingerprint from the TLS verified chains.
  1306. func (c *Client) RootFingerprintWithContext(ctx context.Context) (string, error) {
  1307. u := c.endpoint.ResolveReference(&url.URL{Path: "/health"})
  1308. resp, err := c.client.GetWithContext(ctx, u.String())
  1309. if err != nil {
  1310. return "", clientError(err)
  1311. }
  1312. defer resp.Body.Close()
  1313. if resp.TLS == nil || len(resp.TLS.VerifiedChains) == 0 {
  1314. return "", errors.New("missing verified chains")
  1315. }
  1316. lastChain := resp.TLS.VerifiedChains[len(resp.TLS.VerifiedChains)-1]
  1317. if len(lastChain) == 0 {
  1318. return "", errors.New("missing verified chains")
  1319. }
  1320. return x509util.Fingerprint(lastChain[len(lastChain)-1]), nil
  1321. }
  1322. // CreateSignRequest is a helper function that given an x509 OTT returns a
  1323. // simple but secure sign request as well as the private key used.
  1324. func CreateSignRequest(ott string) (*api.SignRequest, crypto.PrivateKey, error) {
  1325. token, err := jose.ParseSigned(ott)
  1326. if err != nil {
  1327. return nil, nil, errors.Wrap(err, "error parsing ott")
  1328. }
  1329. var claims authority.Claims
  1330. if err := token.UnsafeClaimsWithoutVerification(&claims); err != nil {
  1331. return nil, nil, errors.Wrap(err, "error parsing ott")
  1332. }
  1333. pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  1334. if err != nil {
  1335. return nil, nil, errors.Wrap(err, "error generating key")
  1336. }
  1337. dnsNames, ips, emails, uris := x509util.SplitSANs(claims.SANs)
  1338. if claims.Email != "" {
  1339. emails = append(emails, claims.Email)
  1340. }
  1341. template := &x509.CertificateRequest{
  1342. Subject: pkix.Name{
  1343. CommonName: claims.Subject,
  1344. },
  1345. SignatureAlgorithm: x509.ECDSAWithSHA256,
  1346. DNSNames: dnsNames,
  1347. IPAddresses: ips,
  1348. EmailAddresses: emails,
  1349. URIs: uris,
  1350. }
  1351. csr, err := x509.CreateCertificateRequest(rand.Reader, template, pk)
  1352. if err != nil {
  1353. return nil, nil, errors.Wrap(err, "error creating certificate request")
  1354. }
  1355. cr, err := x509.ParseCertificateRequest(csr)
  1356. if err != nil {
  1357. return nil, nil, errors.Wrap(err, "error parsing certificate request")
  1358. }
  1359. if err := cr.CheckSignature(); err != nil {
  1360. return nil, nil, errors.Wrap(err, "error signing certificate request")
  1361. }
  1362. return &api.SignRequest{
  1363. CsrPEM: api.CertificateRequest{CertificateRequest: cr},
  1364. OTT: ott,
  1365. }, pk, nil
  1366. }
  1367. // CreateCertificateRequest creates a new CSR with the given common name and
  1368. // SANs. If no san is provided the commonName will set also a SAN.
  1369. func CreateCertificateRequest(commonName string, sans ...string) (*api.CertificateRequest, crypto.PrivateKey, error) {
  1370. key, err := keyutil.GenerateDefaultKey()
  1371. if err != nil {
  1372. return nil, nil, err
  1373. }
  1374. return createCertificateRequest(commonName, sans, key)
  1375. }
  1376. // CreateIdentityRequest returns a new CSR to create the identity. If an
  1377. // identity was already present it reuses the private key.
  1378. func CreateIdentityRequest(commonName string, sans ...string) (*api.CertificateRequest, crypto.PrivateKey, error) {
  1379. var identityKey crypto.PrivateKey
  1380. if i, err := identity.LoadDefaultIdentity(); err == nil && i.Key != "" {
  1381. if k, err := pemutil.Read(i.Key); err == nil {
  1382. identityKey = k
  1383. }
  1384. }
  1385. if identityKey == nil {
  1386. return CreateCertificateRequest(commonName, sans...)
  1387. }
  1388. return createCertificateRequest(commonName, sans, identityKey)
  1389. }
  1390. // LoadDefaultIdentity is a wrapper for identity.LoadDefaultIdentity.
  1391. func LoadDefaultIdentity() (*identity.Identity, error) {
  1392. return identity.LoadDefaultIdentity()
  1393. }
  1394. // WriteDefaultIdentity is a wrapper for identity.WriteDefaultIdentity.
  1395. func WriteDefaultIdentity(certChain []api.Certificate, key crypto.PrivateKey) error {
  1396. return identity.WriteDefaultIdentity(certChain, key)
  1397. }
  1398. func createCertificateRequest(commonName string, sans []string, key crypto.PrivateKey) (*api.CertificateRequest, crypto.PrivateKey, error) {
  1399. if len(sans) == 0 {
  1400. sans = []string{commonName}
  1401. }
  1402. dnsNames, ips, emails, uris := x509util.SplitSANs(sans)
  1403. template := &x509.CertificateRequest{
  1404. Subject: pkix.Name{
  1405. CommonName: commonName,
  1406. },
  1407. DNSNames: dnsNames,
  1408. IPAddresses: ips,
  1409. EmailAddresses: emails,
  1410. URIs: uris,
  1411. }
  1412. csr, err := x509.CreateCertificateRequest(rand.Reader, template, key)
  1413. if err != nil {
  1414. return nil, nil, err
  1415. }
  1416. cr, err := x509.ParseCertificateRequest(csr)
  1417. if err != nil {
  1418. return nil, nil, err
  1419. }
  1420. if err := cr.CheckSignature(); err != nil {
  1421. return nil, nil, err
  1422. }
  1423. return &api.CertificateRequest{CertificateRequest: cr}, key, nil
  1424. }
  1425. // getRootCAPath returns the path where the root CA is stored based on the
  1426. // STEPPATH environment variable.
  1427. func getRootCAPath() string {
  1428. return filepath.Join(step.Path(), "certs", "root_ca.crt")
  1429. }
  1430. func readJSON(r io.ReadCloser, v interface{}) error {
  1431. defer r.Close()
  1432. return json.NewDecoder(r).Decode(v)
  1433. }
  1434. func readProtoJSON(r io.ReadCloser, m proto.Message) error {
  1435. defer r.Close()
  1436. data, err := io.ReadAll(r)
  1437. if err != nil {
  1438. return err
  1439. }
  1440. return protojson.Unmarshal(data, m)
  1441. }
  1442. func readError(r *http.Response) error {
  1443. defer r.Body.Close()
  1444. apiErr := new(errs.Error)
  1445. if err := json.NewDecoder(r.Body).Decode(apiErr); err != nil {
  1446. return fmt.Errorf("failed decoding CA error response: %w", err)
  1447. }
  1448. apiErr.RequestID = r.Header.Get("X-Request-Id")
  1449. return apiErr
  1450. }
  1451. func clientError(err error) error {
  1452. var uerr *url.Error
  1453. if errors.As(err, &uerr) {
  1454. return fmt.Errorf("client %s %s failed: %w",
  1455. strings.ToUpper(uerr.Op), uerr.URL, uerr.Err)
  1456. }
  1457. return fmt.Errorf("client request failed: %w", err)
  1458. }