client.go 39 KB

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