client.go 39 KB

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