client.go 39 KB

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