client.go 50 KB

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