client.go 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357
  1. package ca
  2. import (
  3. "bytes"
  4. "crypto"
  5. "crypto/ecdsa"
  6. "crypto/elliptic"
  7. "crypto/rand"
  8. "crypto/sha256"
  9. "crypto/tls"
  10. "crypto/x509"
  11. "crypto/x509/pkix"
  12. "encoding/hex"
  13. "encoding/json"
  14. "encoding/pem"
  15. "io"
  16. "net/http"
  17. "net/url"
  18. "os"
  19. "path/filepath"
  20. "strconv"
  21. "strings"
  22. "github.com/pkg/errors"
  23. "github.com/smallstep/certificates/api"
  24. "github.com/smallstep/certificates/authority"
  25. "github.com/smallstep/certificates/authority/provisioner"
  26. "github.com/smallstep/certificates/ca/identity"
  27. "github.com/smallstep/certificates/errs"
  28. "go.step.sm/cli-utils/step"
  29. "go.step.sm/crypto/jose"
  30. "go.step.sm/crypto/keyutil"
  31. "go.step.sm/crypto/pemutil"
  32. "go.step.sm/crypto/x509util"
  33. "golang.org/x/net/http2"
  34. "google.golang.org/protobuf/encoding/protojson"
  35. "google.golang.org/protobuf/proto"
  36. "gopkg.in/square/go-jose.v2/jwt"
  37. )
  38. // DisableIdentity is a global variable to disable the identity.
  39. var DisableIdentity = false
  40. // UserAgent will set the User-Agent header in the client requests.
  41. var UserAgent = "step-http-client/1.0"
  42. type uaClient struct {
  43. Client *http.Client
  44. }
  45. func newClient(transport http.RoundTripper) *uaClient {
  46. return &uaClient{
  47. Client: &http.Client{
  48. Transport: transport,
  49. },
  50. }
  51. }
  52. // nolint:gosec // used in bootstrap protocol
  53. func newInsecureClient() *uaClient {
  54. return &uaClient{
  55. Client: &http.Client{
  56. Transport: getDefaultTransport(&tls.Config{InsecureSkipVerify: true}),
  57. },
  58. }
  59. }
  60. func (c *uaClient) GetTransport() http.RoundTripper {
  61. return c.Client.Transport
  62. }
  63. func (c *uaClient) SetTransport(tr http.RoundTripper) {
  64. c.Client.Transport = tr
  65. }
  66. func (c *uaClient) Get(u string) (*http.Response, error) {
  67. req, err := http.NewRequest("GET", u, http.NoBody)
  68. if err != nil {
  69. return nil, errors.Wrapf(err, "new request GET %s failed", u)
  70. }
  71. req.Header.Set("User-Agent", UserAgent)
  72. return c.Client.Do(req)
  73. }
  74. func (c *uaClient) Post(u, contentType string, body io.Reader) (*http.Response, error) {
  75. req, err := http.NewRequest("POST", u, body)
  76. if err != nil {
  77. return nil, err
  78. }
  79. req.Header.Set("Content-Type", contentType)
  80. req.Header.Set("User-Agent", UserAgent)
  81. return c.Client.Do(req)
  82. }
  83. func (c *uaClient) Do(req *http.Request) (*http.Response, error) {
  84. req.Header.Set("User-Agent", UserAgent)
  85. return c.Client.Do(req)
  86. }
  87. // RetryFunc defines the method used to retry a request. If it returns true, the
  88. // request will be retried once.
  89. type RetryFunc func(code int) bool
  90. // ClientOption is the type of options passed to the Client constructor.
  91. type ClientOption func(o *clientOptions) error
  92. type clientOptions struct {
  93. transport http.RoundTripper
  94. rootSHA256 string
  95. rootFilename string
  96. rootBundle []byte
  97. certificate tls.Certificate
  98. getClientCertificate func(*tls.CertificateRequestInfo) (*tls.Certificate, error)
  99. retryFunc RetryFunc
  100. x5cJWK *jose.JSONWebKey
  101. x5cCertFile string
  102. x5cCertStrs []string
  103. x5cCert *x509.Certificate
  104. x5cSubject string
  105. }
  106. func (o *clientOptions) apply(opts []ClientOption) (err error) {
  107. if err = o.applyDefaultIdentity(); err != nil {
  108. return
  109. }
  110. for _, fn := range opts {
  111. if err = fn(o); err != nil {
  112. return
  113. }
  114. }
  115. return
  116. }
  117. // applyDefaultIdentity sets the options for the default identity if the
  118. // identity file is present. The identity is enabled by default.
  119. func (o *clientOptions) applyDefaultIdentity() error {
  120. if DisableIdentity {
  121. return nil
  122. }
  123. // Do not load an identity if something fails
  124. i, err := identity.LoadDefaultIdentity()
  125. if err != nil {
  126. return nil
  127. }
  128. if err := i.Validate(); err != nil {
  129. return nil
  130. }
  131. crt, err := i.TLSCertificate()
  132. if err != nil {
  133. return nil
  134. }
  135. o.certificate = crt
  136. o.getClientCertificate = i.GetClientCertificateFunc()
  137. return nil
  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. // nolint:gosec // insecure option
  221. func WithInsecure() ClientOption {
  222. return func(o *clientOptions) error {
  223. o.transport = &http.Transport{
  224. Proxy: http.ProxyFromEnvironment,
  225. TLSClientConfig: &tls.Config{
  226. MinVersion: tls.VersionTLS12,
  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, errs.Wrapf(http.StatusInternalServerError, err, "client.Version; client GET %s failed", u)
  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. // Health performs the health request to the CA and returns the
  557. // api.HealthResponse struct.
  558. func (c *Client) Health() (*api.HealthResponse, error) {
  559. var retried bool
  560. u := c.endpoint.ResolveReference(&url.URL{Path: "/health"})
  561. retry:
  562. resp, err := c.client.Get(u.String())
  563. if err != nil {
  564. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Health; client GET %s failed", u)
  565. }
  566. if resp.StatusCode >= 400 {
  567. if !retried && c.retryOnError(resp) {
  568. retried = true
  569. goto retry
  570. }
  571. return nil, readError(resp.Body)
  572. }
  573. var health api.HealthResponse
  574. if err := readJSON(resp.Body, &health); err != nil {
  575. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Health; error reading %s", u)
  576. }
  577. return &health, nil
  578. }
  579. // Root performs the root request to the CA with the given SHA256 and returns
  580. // the api.RootResponse struct. It uses an insecure client, but it checks the
  581. // resulting root certificate with the given SHA256, returning an error if they
  582. // do not match.
  583. func (c *Client) Root(sha256Sum string) (*api.RootResponse, error) {
  584. var retried bool
  585. sha256Sum = strings.ToLower(strings.ReplaceAll(sha256Sum, "-", ""))
  586. u := c.endpoint.ResolveReference(&url.URL{Path: "/root/" + sha256Sum})
  587. retry:
  588. resp, err := newInsecureClient().Get(u.String())
  589. if err != nil {
  590. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Root; client GET %s failed", u)
  591. }
  592. if resp.StatusCode >= 400 {
  593. if !retried && c.retryOnError(resp) {
  594. retried = true
  595. goto retry
  596. }
  597. return nil, readError(resp.Body)
  598. }
  599. var root api.RootResponse
  600. if err := readJSON(resp.Body, &root); err != nil {
  601. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Root; error reading %s", u)
  602. }
  603. // verify the sha256
  604. sum := sha256.Sum256(root.RootPEM.Raw)
  605. if !strings.EqualFold(sha256Sum, strings.ToLower(hex.EncodeToString(sum[:]))) {
  606. return nil, errs.BadRequest("root certificate fingerprint does not match")
  607. }
  608. return &root, nil
  609. }
  610. // Sign performs the sign request to the CA and returns the api.SignResponse
  611. // struct.
  612. func (c *Client) Sign(req *api.SignRequest) (*api.SignResponse, error) {
  613. var retried bool
  614. body, err := json.Marshal(req)
  615. if err != nil {
  616. return nil, errs.Wrap(http.StatusInternalServerError, err, "client.Sign; error marshaling request")
  617. }
  618. u := c.endpoint.ResolveReference(&url.URL{Path: "/sign"})
  619. retry:
  620. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  621. if err != nil {
  622. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Sign; client POST %s failed", u)
  623. }
  624. if resp.StatusCode >= 400 {
  625. if !retried && c.retryOnError(resp) {
  626. retried = true
  627. goto retry
  628. }
  629. return nil, readError(resp.Body)
  630. }
  631. var sign api.SignResponse
  632. if err := readJSON(resp.Body, &sign); err != nil {
  633. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Sign; error reading %s", u)
  634. }
  635. // Add tls.ConnectionState:
  636. // We'll extract the root certificate from the verified chains
  637. sign.TLS = resp.TLS
  638. return &sign, nil
  639. }
  640. // Renew performs the renew request to the CA and returns the api.SignResponse
  641. // struct.
  642. func (c *Client) Renew(tr http.RoundTripper) (*api.SignResponse, error) {
  643. var retried bool
  644. u := c.endpoint.ResolveReference(&url.URL{Path: "/renew"})
  645. client := &http.Client{Transport: tr}
  646. retry:
  647. resp, err := client.Post(u.String(), "application/json", http.NoBody)
  648. if err != nil {
  649. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Renew; client POST %s failed", u)
  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.Renew; error reading %s", u)
  661. }
  662. return &sign, nil
  663. }
  664. // RenewWithToken performs the renew request to the CA with the given
  665. // authorization token and returns the api.SignResponse struct. This method is
  666. // generally used to renew an expired certificate.
  667. func (c *Client) RenewWithToken(token string) (*api.SignResponse, error) {
  668. var retried bool
  669. u := c.endpoint.ResolveReference(&url.URL{Path: "/renew"})
  670. req, err := http.NewRequest("POST", u.String(), http.NoBody)
  671. if err != nil {
  672. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.RenewWithToken; error creating request")
  673. }
  674. req.Header.Add("Authorization", "Bearer "+token)
  675. retry:
  676. resp, err := c.client.Do(req)
  677. if err != nil {
  678. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.RenewWithToken; client POST %s failed", u)
  679. }
  680. if resp.StatusCode >= 400 {
  681. if !retried && c.retryOnError(resp) {
  682. retried = true
  683. goto retry
  684. }
  685. return nil, readError(resp.Body)
  686. }
  687. var sign api.SignResponse
  688. if err := readJSON(resp.Body, &sign); err != nil {
  689. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.RenewWithToken; error reading %s", u)
  690. }
  691. return &sign, nil
  692. }
  693. // Rekey performs the rekey request to the CA and returns the api.SignResponse
  694. // struct.
  695. func (c *Client) Rekey(req *api.RekeyRequest, tr http.RoundTripper) (*api.SignResponse, error) {
  696. var retried bool
  697. body, err := json.Marshal(req)
  698. if err != nil {
  699. return nil, errors.Wrap(err, "error marshaling request")
  700. }
  701. u := c.endpoint.ResolveReference(&url.URL{Path: "/rekey"})
  702. client := &http.Client{Transport: tr}
  703. retry:
  704. resp, err := client.Post(u.String(), "application/json", bytes.NewReader(body))
  705. if err != nil {
  706. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Rekey; client POST %s failed", u)
  707. }
  708. if resp.StatusCode >= 400 {
  709. if !retried && c.retryOnError(resp) {
  710. retried = true
  711. goto retry
  712. }
  713. return nil, readError(resp.Body)
  714. }
  715. var sign api.SignResponse
  716. if err := readJSON(resp.Body, &sign); err != nil {
  717. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Rekey; error reading %s", u)
  718. }
  719. return &sign, nil
  720. }
  721. // Revoke performs the revoke request to the CA and returns the api.RevokeResponse
  722. // struct.
  723. func (c *Client) Revoke(req *api.RevokeRequest, tr http.RoundTripper) (*api.RevokeResponse, error) {
  724. var retried bool
  725. body, err := json.Marshal(req)
  726. if err != nil {
  727. return nil, errors.Wrap(err, "error marshaling request")
  728. }
  729. var client *uaClient
  730. retry:
  731. if tr != nil {
  732. client = newClient(tr)
  733. } else {
  734. client = c.client
  735. }
  736. u := c.endpoint.ResolveReference(&url.URL{Path: "/revoke"})
  737. resp, err := client.Post(u.String(), "application/json", bytes.NewReader(body))
  738. if err != nil {
  739. return nil, errors.Wrapf(err, "client POST %s failed", u)
  740. }
  741. if resp.StatusCode >= 400 {
  742. if !retried && c.retryOnError(resp) {
  743. retried = true
  744. goto retry
  745. }
  746. return nil, readError(resp.Body)
  747. }
  748. var revoke api.RevokeResponse
  749. if err := readJSON(resp.Body, &revoke); err != nil {
  750. return nil, errors.Wrapf(err, "error reading %s", u)
  751. }
  752. return &revoke, nil
  753. }
  754. // Provisioners performs the provisioners request to the CA and returns the
  755. // api.ProvisionersResponse struct with a map of provisioners.
  756. //
  757. // ProvisionerOption WithProvisionerCursor and WithProvisionLimit can be used to
  758. // paginate the provisioners.
  759. func (c *Client) Provisioners(opts ...ProvisionerOption) (*api.ProvisionersResponse, error) {
  760. var retried bool
  761. o := new(ProvisionerOptions)
  762. if err := o.Apply(opts); err != nil {
  763. return nil, err
  764. }
  765. u := c.endpoint.ResolveReference(&url.URL{
  766. Path: "/provisioners",
  767. RawQuery: o.rawQuery(),
  768. })
  769. retry:
  770. resp, err := c.client.Get(u.String())
  771. if err != nil {
  772. return nil, errors.Wrapf(err, "client GET %s failed", u)
  773. }
  774. if resp.StatusCode >= 400 {
  775. if !retried && c.retryOnError(resp) {
  776. retried = true
  777. goto retry
  778. }
  779. return nil, readError(resp.Body)
  780. }
  781. var provisioners api.ProvisionersResponse
  782. if err := readJSON(resp.Body, &provisioners); err != nil {
  783. return nil, errors.Wrapf(err, "error reading %s", u)
  784. }
  785. return &provisioners, nil
  786. }
  787. // ProvisionerKey performs the request to the CA to get the encrypted key for
  788. // the given provisioner kid and returns the api.ProvisionerKeyResponse struct
  789. // with the encrypted key.
  790. func (c *Client) ProvisionerKey(kid string) (*api.ProvisionerKeyResponse, error) {
  791. var retried bool
  792. u := c.endpoint.ResolveReference(&url.URL{Path: "/provisioners/" + kid + "/encrypted-key"})
  793. retry:
  794. resp, err := c.client.Get(u.String())
  795. if err != nil {
  796. return nil, errors.Wrapf(err, "client GET %s failed", u)
  797. }
  798. if resp.StatusCode >= 400 {
  799. if !retried && c.retryOnError(resp) {
  800. retried = true
  801. goto retry
  802. }
  803. return nil, readError(resp.Body)
  804. }
  805. var key api.ProvisionerKeyResponse
  806. if err := readJSON(resp.Body, &key); err != nil {
  807. return nil, errors.Wrapf(err, "error reading %s", u)
  808. }
  809. return &key, nil
  810. }
  811. // Roots performs the get roots request to the CA and returns the
  812. // api.RootsResponse struct.
  813. func (c *Client) Roots() (*api.RootsResponse, error) {
  814. var retried bool
  815. u := c.endpoint.ResolveReference(&url.URL{Path: "/roots"})
  816. retry:
  817. resp, err := c.client.Get(u.String())
  818. if err != nil {
  819. return nil, errors.Wrapf(err, "client GET %s failed", u)
  820. }
  821. if resp.StatusCode >= 400 {
  822. if !retried && c.retryOnError(resp) {
  823. retried = true
  824. goto retry
  825. }
  826. return nil, readError(resp.Body)
  827. }
  828. var roots api.RootsResponse
  829. if err := readJSON(resp.Body, &roots); err != nil {
  830. return nil, errors.Wrapf(err, "error reading %s", u)
  831. }
  832. return &roots, nil
  833. }
  834. // Federation performs the get federation request to the CA and returns the
  835. // api.FederationResponse struct.
  836. func (c *Client) Federation() (*api.FederationResponse, error) {
  837. var retried bool
  838. u := c.endpoint.ResolveReference(&url.URL{Path: "/federation"})
  839. retry:
  840. resp, err := c.client.Get(u.String())
  841. if err != nil {
  842. return nil, errors.Wrapf(err, "client GET %s failed", u)
  843. }
  844. if resp.StatusCode >= 400 {
  845. if !retried && c.retryOnError(resp) {
  846. retried = true
  847. goto retry
  848. }
  849. return nil, readError(resp.Body)
  850. }
  851. var federation api.FederationResponse
  852. if err := readJSON(resp.Body, &federation); err != nil {
  853. return nil, errors.Wrapf(err, "error reading %s", u)
  854. }
  855. return &federation, nil
  856. }
  857. // SSHSign performs the POST /ssh/sign request to the CA and returns the
  858. // api.SSHSignResponse struct.
  859. func (c *Client) SSHSign(req *api.SSHSignRequest) (*api.SSHSignResponse, error) {
  860. var retried bool
  861. body, err := json.Marshal(req)
  862. if err != nil {
  863. return nil, errors.Wrap(err, "error marshaling request")
  864. }
  865. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/sign"})
  866. retry:
  867. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  868. if err != nil {
  869. return nil, errors.Wrapf(err, "client POST %s failed", u)
  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 sign api.SSHSignResponse
  879. if err := readJSON(resp.Body, &sign); err != nil {
  880. return nil, errors.Wrapf(err, "error reading %s", u)
  881. }
  882. return &sign, nil
  883. }
  884. // SSHRenew performs the POST /ssh/renew request to the CA and returns the
  885. // api.SSHRenewResponse struct.
  886. func (c *Client) SSHRenew(req *api.SSHRenewRequest) (*api.SSHRenewResponse, 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/renew"})
  893. retry:
  894. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  895. if err != nil {
  896. return nil, errors.Wrapf(err, "client POST %s failed", u)
  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 renew api.SSHRenewResponse
  906. if err := readJSON(resp.Body, &renew); err != nil {
  907. return nil, errors.Wrapf(err, "error reading %s", u)
  908. }
  909. return &renew, nil
  910. }
  911. // SSHRekey performs the POST /ssh/rekey request to the CA and returns the
  912. // api.SSHRekeyResponse struct.
  913. func (c *Client) SSHRekey(req *api.SSHRekeyRequest) (*api.SSHRekeyResponse, 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/rekey"})
  920. retry:
  921. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  922. if err != nil {
  923. return nil, errors.Wrapf(err, "client POST %s failed", u)
  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 rekey api.SSHRekeyResponse
  933. if err := readJSON(resp.Body, &rekey); err != nil {
  934. return nil, errors.Wrapf(err, "error reading %s", u)
  935. }
  936. return &rekey, nil
  937. }
  938. // SSHRevoke performs the POST /ssh/revoke request to the CA and returns the
  939. // api.SSHRevokeResponse struct.
  940. func (c *Client) SSHRevoke(req *api.SSHRevokeRequest) (*api.SSHRevokeResponse, 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/revoke"})
  947. retry:
  948. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  949. if err != nil {
  950. return nil, errors.Wrapf(err, "client POST %s failed", u)
  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 revoke api.SSHRevokeResponse
  960. if err := readJSON(resp.Body, &revoke); err != nil {
  961. return nil, errors.Wrapf(err, "error reading %s", u)
  962. }
  963. return &revoke, nil
  964. }
  965. // SSHRoots performs the GET /ssh/roots request to the CA and returns the
  966. // api.SSHRootsResponse struct.
  967. func (c *Client) SSHRoots() (*api.SSHRootsResponse, error) {
  968. var retried bool
  969. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/roots"})
  970. retry:
  971. resp, err := c.client.Get(u.String())
  972. if err != nil {
  973. return nil, errors.Wrapf(err, "client GET %s failed", u)
  974. }
  975. if resp.StatusCode >= 400 {
  976. if !retried && c.retryOnError(resp) {
  977. retried = true
  978. goto retry
  979. }
  980. return nil, readError(resp.Body)
  981. }
  982. var keys api.SSHRootsResponse
  983. if err := readJSON(resp.Body, &keys); err != nil {
  984. return nil, errors.Wrapf(err, "error reading %s", u)
  985. }
  986. return &keys, nil
  987. }
  988. // SSHFederation performs the get /ssh/federation request to the CA and returns
  989. // the api.SSHRootsResponse struct.
  990. func (c *Client) SSHFederation() (*api.SSHRootsResponse, error) {
  991. var retried bool
  992. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/federation"})
  993. retry:
  994. resp, err := c.client.Get(u.String())
  995. if err != nil {
  996. return nil, errors.Wrapf(err, "client GET %s failed", u)
  997. }
  998. if resp.StatusCode >= 400 {
  999. if !retried && c.retryOnError(resp) {
  1000. retried = true
  1001. goto retry
  1002. }
  1003. return nil, readError(resp.Body)
  1004. }
  1005. var keys api.SSHRootsResponse
  1006. if err := readJSON(resp.Body, &keys); err != nil {
  1007. return nil, errors.Wrapf(err, "error reading %s", u)
  1008. }
  1009. return &keys, nil
  1010. }
  1011. // SSHConfig performs the POST /ssh/config request to the CA to get the ssh
  1012. // configuration templates.
  1013. func (c *Client) SSHConfig(req *api.SSHConfigRequest) (*api.SSHConfigResponse, error) {
  1014. var retried bool
  1015. body, err := json.Marshal(req)
  1016. if err != nil {
  1017. return nil, errors.Wrap(err, "error marshaling request")
  1018. }
  1019. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/config"})
  1020. retry:
  1021. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  1022. if err != nil {
  1023. return nil, errors.Wrapf(err, "client POST %s failed", u)
  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 cfg api.SSHConfigResponse
  1033. if err := readJSON(resp.Body, &cfg); err != nil {
  1034. return nil, errors.Wrapf(err, "error reading %s", u)
  1035. }
  1036. return &cfg, nil
  1037. }
  1038. // SSHCheckHost performs the POST /ssh/check-host request to the CA with the
  1039. // given principal.
  1040. func (c *Client) SSHCheckHost(principal, token string) (*api.SSHCheckPrincipalResponse, error) {
  1041. var retried bool
  1042. body, err := json.Marshal(&api.SSHCheckPrincipalRequest{
  1043. Type: provisioner.SSHHostCert,
  1044. Principal: principal,
  1045. Token: token,
  1046. })
  1047. if err != nil {
  1048. return nil, errs.Wrap(http.StatusInternalServerError, err, "error marshaling request",
  1049. errs.WithMessage("Failed to marshal the check-host request"))
  1050. }
  1051. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/check-host"})
  1052. retry:
  1053. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  1054. if err != nil {
  1055. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client POST %s failed",
  1056. []interface{}{u, errs.WithMessage("Failed to perform POST request to %s", u)}...)
  1057. }
  1058. if resp.StatusCode >= 400 {
  1059. if !retried && c.retryOnError(resp) {
  1060. retried = true
  1061. goto retry
  1062. }
  1063. return nil, readError(resp.Body)
  1064. }
  1065. var check api.SSHCheckPrincipalResponse
  1066. if err := readJSON(resp.Body, &check); err != nil {
  1067. return nil, errs.Wrapf(http.StatusInternalServerError, err, "error reading %s response",
  1068. []interface{}{u, errs.WithMessage("Failed to parse response from /ssh/check-host endpoint")})
  1069. }
  1070. return &check, nil
  1071. }
  1072. // SSHGetHosts performs the GET /ssh/get-hosts request to the CA.
  1073. func (c *Client) SSHGetHosts() (*api.SSHGetHostsResponse, error) {
  1074. var retried bool
  1075. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/hosts"})
  1076. retry:
  1077. resp, err := c.client.Get(u.String())
  1078. if err != nil {
  1079. return nil, errors.Wrapf(err, "client GET %s failed", u)
  1080. }
  1081. if resp.StatusCode >= 400 {
  1082. if !retried && c.retryOnError(resp) {
  1083. retried = true
  1084. goto retry
  1085. }
  1086. return nil, readError(resp.Body)
  1087. }
  1088. var hosts api.SSHGetHostsResponse
  1089. if err := readJSON(resp.Body, &hosts); err != nil {
  1090. return nil, errors.Wrapf(err, "error reading %s", u)
  1091. }
  1092. return &hosts, nil
  1093. }
  1094. // SSHBastion performs the POST /ssh/bastion request to the CA.
  1095. func (c *Client) SSHBastion(req *api.SSHBastionRequest) (*api.SSHBastionResponse, error) {
  1096. var retried bool
  1097. body, err := json.Marshal(req)
  1098. if err != nil {
  1099. return nil, errors.Wrap(err, "client.SSHBastion; error marshaling request")
  1100. }
  1101. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/bastion"})
  1102. retry:
  1103. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  1104. if err != nil {
  1105. return nil, errors.Wrapf(err, "client.SSHBastion; client POST %s failed", u)
  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 bastion api.SSHBastionResponse
  1115. if err := readJSON(resp.Body, &bastion); err != nil {
  1116. return nil, errors.Wrapf(err, "client.SSHBastion; error reading %s", u)
  1117. }
  1118. return &bastion, nil
  1119. }
  1120. // RootFingerprint is a helper method that returns the current root fingerprint.
  1121. // It does an health connection and gets the fingerprint from the TLS verified
  1122. // chains.
  1123. func (c *Client) RootFingerprint() (string, error) {
  1124. u := c.endpoint.ResolveReference(&url.URL{Path: "/health"})
  1125. resp, err := c.client.Get(u.String())
  1126. if err != nil {
  1127. return "", errors.Wrapf(err, "client GET %s failed", u)
  1128. }
  1129. if resp.TLS == nil || len(resp.TLS.VerifiedChains) == 0 {
  1130. return "", errors.New("missing verified chains")
  1131. }
  1132. lastChain := resp.TLS.VerifiedChains[len(resp.TLS.VerifiedChains)-1]
  1133. if len(lastChain) == 0 {
  1134. return "", errors.New("missing verified chains")
  1135. }
  1136. return x509util.Fingerprint(lastChain[len(lastChain)-1]), nil
  1137. }
  1138. // CreateSignRequest is a helper function that given an x509 OTT returns a
  1139. // simple but secure sign request as well as the private key used.
  1140. func CreateSignRequest(ott string) (*api.SignRequest, crypto.PrivateKey, error) {
  1141. token, err := jwt.ParseSigned(ott)
  1142. if err != nil {
  1143. return nil, nil, errors.Wrap(err, "error parsing ott")
  1144. }
  1145. var claims authority.Claims
  1146. if err := token.UnsafeClaimsWithoutVerification(&claims); err != nil {
  1147. return nil, nil, errors.Wrap(err, "error parsing ott")
  1148. }
  1149. pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  1150. if err != nil {
  1151. return nil, nil, errors.Wrap(err, "error generating key")
  1152. }
  1153. dnsNames, ips, emails, uris := x509util.SplitSANs(claims.SANs)
  1154. if claims.Email != "" {
  1155. emails = append(emails, claims.Email)
  1156. }
  1157. template := &x509.CertificateRequest{
  1158. Subject: pkix.Name{
  1159. CommonName: claims.Subject,
  1160. },
  1161. SignatureAlgorithm: x509.ECDSAWithSHA256,
  1162. DNSNames: dnsNames,
  1163. IPAddresses: ips,
  1164. EmailAddresses: emails,
  1165. URIs: uris,
  1166. }
  1167. csr, err := x509.CreateCertificateRequest(rand.Reader, template, pk)
  1168. if err != nil {
  1169. return nil, nil, errors.Wrap(err, "error creating certificate request")
  1170. }
  1171. cr, err := x509.ParseCertificateRequest(csr)
  1172. if err != nil {
  1173. return nil, nil, errors.Wrap(err, "error parsing certificate request")
  1174. }
  1175. if err := cr.CheckSignature(); err != nil {
  1176. return nil, nil, errors.Wrap(err, "error signing certificate request")
  1177. }
  1178. return &api.SignRequest{
  1179. CsrPEM: api.CertificateRequest{CertificateRequest: cr},
  1180. OTT: ott,
  1181. }, pk, nil
  1182. }
  1183. // CreateCertificateRequest creates a new CSR with the given common name and
  1184. // SANs. If no san is provided the commonName will set also a SAN.
  1185. func CreateCertificateRequest(commonName string, sans ...string) (*api.CertificateRequest, crypto.PrivateKey, error) {
  1186. key, err := keyutil.GenerateDefaultKey()
  1187. if err != nil {
  1188. return nil, nil, err
  1189. }
  1190. return createCertificateRequest(commonName, sans, key)
  1191. }
  1192. // CreateIdentityRequest returns a new CSR to create the identity. If an
  1193. // identity was already present it reuses the private key.
  1194. func CreateIdentityRequest(commonName string, sans ...string) (*api.CertificateRequest, crypto.PrivateKey, error) {
  1195. var identityKey crypto.PrivateKey
  1196. if i, err := identity.LoadDefaultIdentity(); err == nil && i.Key != "" {
  1197. if k, err := pemutil.Read(i.Key); err == nil {
  1198. identityKey = k
  1199. }
  1200. }
  1201. if identityKey == nil {
  1202. return CreateCertificateRequest(commonName, sans...)
  1203. }
  1204. return createCertificateRequest(commonName, sans, identityKey)
  1205. }
  1206. // LoadDefaultIdentity is a wrapper for identity.LoadDefaultIdentity.
  1207. func LoadDefaultIdentity() (*identity.Identity, error) {
  1208. return identity.LoadDefaultIdentity()
  1209. }
  1210. // WriteDefaultIdentity is a wrapper for identity.WriteDefaultIdentity.
  1211. func WriteDefaultIdentity(certChain []api.Certificate, key crypto.PrivateKey) error {
  1212. return identity.WriteDefaultIdentity(certChain, key)
  1213. }
  1214. func createCertificateRequest(commonName string, sans []string, key crypto.PrivateKey) (*api.CertificateRequest, crypto.PrivateKey, error) {
  1215. if len(sans) == 0 {
  1216. sans = []string{commonName}
  1217. }
  1218. dnsNames, ips, emails, uris := x509util.SplitSANs(sans)
  1219. template := &x509.CertificateRequest{
  1220. Subject: pkix.Name{
  1221. CommonName: commonName,
  1222. },
  1223. DNSNames: dnsNames,
  1224. IPAddresses: ips,
  1225. EmailAddresses: emails,
  1226. URIs: uris,
  1227. }
  1228. csr, err := x509.CreateCertificateRequest(rand.Reader, template, key)
  1229. if err != nil {
  1230. return nil, nil, err
  1231. }
  1232. cr, err := x509.ParseCertificateRequest(csr)
  1233. if err != nil {
  1234. return nil, nil, err
  1235. }
  1236. if err := cr.CheckSignature(); err != nil {
  1237. return nil, nil, err
  1238. }
  1239. return &api.CertificateRequest{CertificateRequest: cr}, key, nil
  1240. }
  1241. // getRootCAPath returns the path where the root CA is stored based on the
  1242. // STEPPATH environment variable.
  1243. func getRootCAPath() string {
  1244. return filepath.Join(step.Path(), "certs", "root_ca.crt")
  1245. }
  1246. func readJSON(r io.ReadCloser, v interface{}) error {
  1247. defer r.Close()
  1248. return json.NewDecoder(r).Decode(v)
  1249. }
  1250. func readProtoJSON(r io.ReadCloser, m proto.Message) error {
  1251. defer r.Close()
  1252. data, err := io.ReadAll(r)
  1253. if err != nil {
  1254. return err
  1255. }
  1256. return protojson.Unmarshal(data, m)
  1257. }
  1258. func readError(r io.ReadCloser) error {
  1259. defer r.Close()
  1260. apiErr := new(errs.Error)
  1261. if err := json.NewDecoder(r).Decode(apiErr); err != nil {
  1262. return err
  1263. }
  1264. return apiErr
  1265. }