4
0

client.go 50 KB

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