client.go 39 KB

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