client.go 39 KB

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