client.go 38 KB

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