client.go 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346
  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. type provisionerOptions struct {
  392. cursor string
  393. limit int
  394. id string
  395. name string
  396. }
  397. func (o *provisionerOptions) apply(opts []ProvisionerOption) (err error) {
  398. for _, fn := range opts {
  399. if err = fn(o); err != nil {
  400. return
  401. }
  402. }
  403. return
  404. }
  405. func (o *provisionerOptions) rawQuery() string {
  406. v := url.Values{}
  407. if len(o.cursor) > 0 {
  408. v.Set("cursor", o.cursor)
  409. }
  410. if o.limit > 0 {
  411. v.Set("limit", strconv.Itoa(o.limit))
  412. }
  413. if len(o.id) > 0 {
  414. v.Set("id", o.id)
  415. }
  416. if len(o.name) > 0 {
  417. v.Set("name", o.name)
  418. }
  419. return v.Encode()
  420. }
  421. // WithProvisionerCursor will request the provisioners starting with the given cursor.
  422. func WithProvisionerCursor(cursor string) ProvisionerOption {
  423. return func(o *provisionerOptions) error {
  424. o.cursor = cursor
  425. return nil
  426. }
  427. }
  428. // WithProvisionerLimit will request the given number of provisioners.
  429. func WithProvisionerLimit(limit int) ProvisionerOption {
  430. return func(o *provisionerOptions) error {
  431. o.limit = limit
  432. return nil
  433. }
  434. }
  435. // WithProvisionerID will request the given provisioner.
  436. func WithProvisionerID(id string) ProvisionerOption {
  437. return func(o *provisionerOptions) error {
  438. o.id = id
  439. return nil
  440. }
  441. }
  442. // WithProvisionerName will request the given provisioner.
  443. func WithProvisionerName(name string) ProvisionerOption {
  444. return func(o *provisionerOptions) error {
  445. o.name = name
  446. return nil
  447. }
  448. }
  449. // Client implements an HTTP client for the CA server.
  450. type Client struct {
  451. client *uaClient
  452. endpoint *url.URL
  453. retryFunc RetryFunc
  454. opts []ClientOption
  455. }
  456. // NewClient creates a new Client with the given endpoint and options.
  457. func NewClient(endpoint string, opts ...ClientOption) (*Client, error) {
  458. u, err := parseEndpoint(endpoint)
  459. if err != nil {
  460. return nil, err
  461. }
  462. // Retrieve transport from options.
  463. o := new(clientOptions)
  464. if err := o.apply(opts); err != nil {
  465. return nil, err
  466. }
  467. tr, err := o.getTransport(endpoint)
  468. if err != nil {
  469. return nil, err
  470. }
  471. return &Client{
  472. client: newClient(tr),
  473. endpoint: u,
  474. retryFunc: o.retryFunc,
  475. opts: opts,
  476. }, nil
  477. }
  478. func (c *Client) retryOnError(r *http.Response) bool {
  479. if c.retryFunc != nil {
  480. if c.retryFunc(r.StatusCode) {
  481. o := new(clientOptions)
  482. if err := o.apply(c.opts); err != nil {
  483. return false
  484. }
  485. tr, err := o.getTransport(c.endpoint.String())
  486. if err != nil {
  487. return false
  488. }
  489. r.Body.Close()
  490. c.client.SetTransport(tr)
  491. return true
  492. }
  493. }
  494. return false
  495. }
  496. // GetCaURL returns the configured CA url.
  497. func (c *Client) GetCaURL() string {
  498. return c.endpoint.String()
  499. }
  500. // GetRootCAs returns the RootCAs certificate pool from the configured
  501. // transport.
  502. func (c *Client) GetRootCAs() *x509.CertPool {
  503. switch t := c.client.GetTransport().(type) {
  504. case *http.Transport:
  505. if t.TLSClientConfig != nil {
  506. return t.TLSClientConfig.RootCAs
  507. }
  508. return nil
  509. case *http2.Transport:
  510. if t.TLSClientConfig != nil {
  511. return t.TLSClientConfig.RootCAs
  512. }
  513. return nil
  514. default:
  515. return nil
  516. }
  517. }
  518. // SetTransport updates the transport of the internal HTTP client.
  519. func (c *Client) SetTransport(tr http.RoundTripper) {
  520. c.client.SetTransport(tr)
  521. }
  522. // Version performs the version request to the CA and returns the
  523. // api.VersionResponse struct.
  524. func (c *Client) Version() (*api.VersionResponse, error) {
  525. var retried bool
  526. u := c.endpoint.ResolveReference(&url.URL{Path: "/version"})
  527. retry:
  528. resp, err := c.client.Get(u.String())
  529. if err != nil {
  530. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Version; client GET %s failed", u)
  531. }
  532. if resp.StatusCode >= 400 {
  533. if !retried && c.retryOnError(resp) {
  534. retried = true
  535. goto retry
  536. }
  537. return nil, readError(resp.Body)
  538. }
  539. var version api.VersionResponse
  540. if err := readJSON(resp.Body, &version); err != nil {
  541. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Version; error reading %s", u)
  542. }
  543. return &version, nil
  544. }
  545. // Health performs the health request to the CA and returns the
  546. // api.HealthResponse struct.
  547. func (c *Client) Health() (*api.HealthResponse, error) {
  548. var retried bool
  549. u := c.endpoint.ResolveReference(&url.URL{Path: "/health"})
  550. retry:
  551. resp, err := c.client.Get(u.String())
  552. if err != nil {
  553. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Health; client GET %s failed", u)
  554. }
  555. if resp.StatusCode >= 400 {
  556. if !retried && c.retryOnError(resp) {
  557. retried = true
  558. goto retry
  559. }
  560. return nil, readError(resp.Body)
  561. }
  562. var health api.HealthResponse
  563. if err := readJSON(resp.Body, &health); err != nil {
  564. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Health; error reading %s", u)
  565. }
  566. return &health, nil
  567. }
  568. // Root performs the root request to the CA with the given SHA256 and returns
  569. // the api.RootResponse struct. It uses an insecure client, but it checks the
  570. // resulting root certificate with the given SHA256, returning an error if they
  571. // do not match.
  572. func (c *Client) Root(sha256Sum string) (*api.RootResponse, error) {
  573. var retried bool
  574. sha256Sum = strings.ToLower(strings.ReplaceAll(sha256Sum, "-", ""))
  575. u := c.endpoint.ResolveReference(&url.URL{Path: "/root/" + sha256Sum})
  576. retry:
  577. resp, err := newInsecureClient().Get(u.String())
  578. if err != nil {
  579. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Root; client GET %s failed", u)
  580. }
  581. if resp.StatusCode >= 400 {
  582. if !retried && c.retryOnError(resp) {
  583. retried = true
  584. goto retry
  585. }
  586. return nil, readError(resp.Body)
  587. }
  588. var root api.RootResponse
  589. if err := readJSON(resp.Body, &root); err != nil {
  590. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Root; error reading %s", u)
  591. }
  592. // verify the sha256
  593. sum := sha256.Sum256(root.RootPEM.Raw)
  594. if !strings.EqualFold(sha256Sum, strings.ToLower(hex.EncodeToString(sum[:]))) {
  595. return nil, errs.BadRequest("root certificate fingerprint does not match")
  596. }
  597. return &root, nil
  598. }
  599. // Sign performs the sign request to the CA and returns the api.SignResponse
  600. // struct.
  601. func (c *Client) Sign(req *api.SignRequest) (*api.SignResponse, error) {
  602. var retried bool
  603. body, err := json.Marshal(req)
  604. if err != nil {
  605. return nil, errs.Wrap(http.StatusInternalServerError, err, "client.Sign; error marshaling request")
  606. }
  607. u := c.endpoint.ResolveReference(&url.URL{Path: "/sign"})
  608. retry:
  609. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  610. if err != nil {
  611. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Sign; client POST %s failed", u)
  612. }
  613. if resp.StatusCode >= 400 {
  614. if !retried && c.retryOnError(resp) {
  615. retried = true
  616. goto retry
  617. }
  618. return nil, readError(resp.Body)
  619. }
  620. var sign api.SignResponse
  621. if err := readJSON(resp.Body, &sign); err != nil {
  622. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Sign; error reading %s", u)
  623. }
  624. // Add tls.ConnectionState:
  625. // We'll extract the root certificate from the verified chains
  626. sign.TLS = resp.TLS
  627. return &sign, nil
  628. }
  629. // Renew performs the renew request to the CA and returns the api.SignResponse
  630. // struct.
  631. func (c *Client) Renew(tr http.RoundTripper) (*api.SignResponse, error) {
  632. var retried bool
  633. u := c.endpoint.ResolveReference(&url.URL{Path: "/renew"})
  634. client := &http.Client{Transport: tr}
  635. retry:
  636. resp, err := client.Post(u.String(), "application/json", http.NoBody)
  637. if err != nil {
  638. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Renew; client POST %s failed", u)
  639. }
  640. if resp.StatusCode >= 400 {
  641. if !retried && c.retryOnError(resp) {
  642. retried = true
  643. goto retry
  644. }
  645. return nil, readError(resp.Body)
  646. }
  647. var sign api.SignResponse
  648. if err := readJSON(resp.Body, &sign); err != nil {
  649. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Renew; error reading %s", u)
  650. }
  651. return &sign, nil
  652. }
  653. // RenewWithToken performs the renew request to the CA with the given
  654. // authorization token and returns the api.SignResponse struct. This method is
  655. // generally used to renew an expired certificate.
  656. func (c *Client) RenewWithToken(token string) (*api.SignResponse, error) {
  657. var retried bool
  658. u := c.endpoint.ResolveReference(&url.URL{Path: "/renew"})
  659. req, err := http.NewRequest("POST", u.String(), http.NoBody)
  660. if err != nil {
  661. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.RenewWithToken; error creating request")
  662. }
  663. req.Header.Add("Authorization", "Bearer "+token)
  664. retry:
  665. resp, err := c.client.Do(req)
  666. if err != nil {
  667. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.RenewWithToken; client POST %s failed", u)
  668. }
  669. if resp.StatusCode >= 400 {
  670. if !retried && c.retryOnError(resp) {
  671. retried = true
  672. goto retry
  673. }
  674. return nil, readError(resp.Body)
  675. }
  676. var sign api.SignResponse
  677. if err := readJSON(resp.Body, &sign); err != nil {
  678. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.RenewWithToken; error reading %s", u)
  679. }
  680. return &sign, nil
  681. }
  682. // Rekey performs the rekey request to the CA and returns the api.SignResponse
  683. // struct.
  684. func (c *Client) Rekey(req *api.RekeyRequest, tr http.RoundTripper) (*api.SignResponse, error) {
  685. var retried bool
  686. body, err := json.Marshal(req)
  687. if err != nil {
  688. return nil, errors.Wrap(err, "error marshaling request")
  689. }
  690. u := c.endpoint.ResolveReference(&url.URL{Path: "/rekey"})
  691. client := &http.Client{Transport: tr}
  692. retry:
  693. resp, err := client.Post(u.String(), "application/json", bytes.NewReader(body))
  694. if err != nil {
  695. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Rekey; client POST %s failed", u)
  696. }
  697. if resp.StatusCode >= 400 {
  698. if !retried && c.retryOnError(resp) {
  699. retried = true
  700. goto retry
  701. }
  702. return nil, readError(resp.Body)
  703. }
  704. var sign api.SignResponse
  705. if err := readJSON(resp.Body, &sign); err != nil {
  706. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Rekey; error reading %s", u)
  707. }
  708. return &sign, nil
  709. }
  710. // Revoke performs the revoke request to the CA and returns the api.RevokeResponse
  711. // struct.
  712. func (c *Client) Revoke(req *api.RevokeRequest, tr http.RoundTripper) (*api.RevokeResponse, error) {
  713. var retried bool
  714. body, err := json.Marshal(req)
  715. if err != nil {
  716. return nil, errors.Wrap(err, "error marshaling request")
  717. }
  718. var client *uaClient
  719. retry:
  720. if tr != nil {
  721. client = newClient(tr)
  722. } else {
  723. client = c.client
  724. }
  725. u := c.endpoint.ResolveReference(&url.URL{Path: "/revoke"})
  726. resp, err := client.Post(u.String(), "application/json", bytes.NewReader(body))
  727. if err != nil {
  728. return nil, errors.Wrapf(err, "client POST %s failed", u)
  729. }
  730. if resp.StatusCode >= 400 {
  731. if !retried && c.retryOnError(resp) {
  732. retried = true
  733. goto retry
  734. }
  735. return nil, readError(resp.Body)
  736. }
  737. var revoke api.RevokeResponse
  738. if err := readJSON(resp.Body, &revoke); err != nil {
  739. return nil, errors.Wrapf(err, "error reading %s", u)
  740. }
  741. return &revoke, nil
  742. }
  743. // Provisioners performs the provisioners request to the CA and returns the
  744. // api.ProvisionersResponse struct with a map of provisioners.
  745. //
  746. // ProvisionerOption WithProvisionerCursor and WithProvisionLimit can be used to
  747. // paginate the provisioners.
  748. func (c *Client) Provisioners(opts ...ProvisionerOption) (*api.ProvisionersResponse, error) {
  749. var retried bool
  750. o := new(provisionerOptions)
  751. if err := o.apply(opts); err != nil {
  752. return nil, err
  753. }
  754. u := c.endpoint.ResolveReference(&url.URL{
  755. Path: "/provisioners",
  756. RawQuery: o.rawQuery(),
  757. })
  758. retry:
  759. resp, err := c.client.Get(u.String())
  760. if err != nil {
  761. return nil, errors.Wrapf(err, "client GET %s failed", u)
  762. }
  763. if resp.StatusCode >= 400 {
  764. if !retried && c.retryOnError(resp) {
  765. retried = true
  766. goto retry
  767. }
  768. return nil, readError(resp.Body)
  769. }
  770. var provisioners api.ProvisionersResponse
  771. if err := readJSON(resp.Body, &provisioners); err != nil {
  772. return nil, errors.Wrapf(err, "error reading %s", u)
  773. }
  774. return &provisioners, nil
  775. }
  776. // ProvisionerKey performs the request to the CA to get the encrypted key for
  777. // the given provisioner kid and returns the api.ProvisionerKeyResponse struct
  778. // with the encrypted key.
  779. func (c *Client) ProvisionerKey(kid string) (*api.ProvisionerKeyResponse, error) {
  780. var retried bool
  781. u := c.endpoint.ResolveReference(&url.URL{Path: "/provisioners/" + kid + "/encrypted-key"})
  782. retry:
  783. resp, err := c.client.Get(u.String())
  784. if err != nil {
  785. return nil, errors.Wrapf(err, "client GET %s failed", u)
  786. }
  787. if resp.StatusCode >= 400 {
  788. if !retried && c.retryOnError(resp) {
  789. retried = true
  790. goto retry
  791. }
  792. return nil, readError(resp.Body)
  793. }
  794. var key api.ProvisionerKeyResponse
  795. if err := readJSON(resp.Body, &key); err != nil {
  796. return nil, errors.Wrapf(err, "error reading %s", u)
  797. }
  798. return &key, nil
  799. }
  800. // Roots performs the get roots request to the CA and returns the
  801. // api.RootsResponse struct.
  802. func (c *Client) Roots() (*api.RootsResponse, error) {
  803. var retried bool
  804. u := c.endpoint.ResolveReference(&url.URL{Path: "/roots"})
  805. retry:
  806. resp, err := c.client.Get(u.String())
  807. if err != nil {
  808. return nil, errors.Wrapf(err, "client GET %s failed", u)
  809. }
  810. if resp.StatusCode >= 400 {
  811. if !retried && c.retryOnError(resp) {
  812. retried = true
  813. goto retry
  814. }
  815. return nil, readError(resp.Body)
  816. }
  817. var roots api.RootsResponse
  818. if err := readJSON(resp.Body, &roots); err != nil {
  819. return nil, errors.Wrapf(err, "error reading %s", u)
  820. }
  821. return &roots, nil
  822. }
  823. // Federation performs the get federation request to the CA and returns the
  824. // api.FederationResponse struct.
  825. func (c *Client) Federation() (*api.FederationResponse, error) {
  826. var retried bool
  827. u := c.endpoint.ResolveReference(&url.URL{Path: "/federation"})
  828. retry:
  829. resp, err := c.client.Get(u.String())
  830. if err != nil {
  831. return nil, errors.Wrapf(err, "client GET %s failed", u)
  832. }
  833. if resp.StatusCode >= 400 {
  834. if !retried && c.retryOnError(resp) {
  835. retried = true
  836. goto retry
  837. }
  838. return nil, readError(resp.Body)
  839. }
  840. var federation api.FederationResponse
  841. if err := readJSON(resp.Body, &federation); err != nil {
  842. return nil, errors.Wrapf(err, "error reading %s", u)
  843. }
  844. return &federation, nil
  845. }
  846. // SSHSign performs the POST /ssh/sign request to the CA and returns the
  847. // api.SSHSignResponse struct.
  848. func (c *Client) SSHSign(req *api.SSHSignRequest) (*api.SSHSignResponse, error) {
  849. var retried bool
  850. body, err := json.Marshal(req)
  851. if err != nil {
  852. return nil, errors.Wrap(err, "error marshaling request")
  853. }
  854. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/sign"})
  855. retry:
  856. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  857. if err != nil {
  858. return nil, errors.Wrapf(err, "client POST %s failed", u)
  859. }
  860. if resp.StatusCode >= 400 {
  861. if !retried && c.retryOnError(resp) {
  862. retried = true
  863. goto retry
  864. }
  865. return nil, readError(resp.Body)
  866. }
  867. var sign api.SSHSignResponse
  868. if err := readJSON(resp.Body, &sign); err != nil {
  869. return nil, errors.Wrapf(err, "error reading %s", u)
  870. }
  871. return &sign, nil
  872. }
  873. // SSHRenew performs the POST /ssh/renew request to the CA and returns the
  874. // api.SSHRenewResponse struct.
  875. func (c *Client) SSHRenew(req *api.SSHRenewRequest) (*api.SSHRenewResponse, error) {
  876. var retried bool
  877. body, err := json.Marshal(req)
  878. if err != nil {
  879. return nil, errors.Wrap(err, "error marshaling request")
  880. }
  881. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/renew"})
  882. retry:
  883. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  884. if err != nil {
  885. return nil, errors.Wrapf(err, "client POST %s failed", u)
  886. }
  887. if resp.StatusCode >= 400 {
  888. if !retried && c.retryOnError(resp) {
  889. retried = true
  890. goto retry
  891. }
  892. return nil, readError(resp.Body)
  893. }
  894. var renew api.SSHRenewResponse
  895. if err := readJSON(resp.Body, &renew); err != nil {
  896. return nil, errors.Wrapf(err, "error reading %s", u)
  897. }
  898. return &renew, nil
  899. }
  900. // SSHRekey performs the POST /ssh/rekey request to the CA and returns the
  901. // api.SSHRekeyResponse struct.
  902. func (c *Client) SSHRekey(req *api.SSHRekeyRequest) (*api.SSHRekeyResponse, error) {
  903. var retried bool
  904. body, err := json.Marshal(req)
  905. if err != nil {
  906. return nil, errors.Wrap(err, "error marshaling request")
  907. }
  908. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/rekey"})
  909. retry:
  910. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  911. if err != nil {
  912. return nil, errors.Wrapf(err, "client POST %s failed", u)
  913. }
  914. if resp.StatusCode >= 400 {
  915. if !retried && c.retryOnError(resp) {
  916. retried = true
  917. goto retry
  918. }
  919. return nil, readError(resp.Body)
  920. }
  921. var rekey api.SSHRekeyResponse
  922. if err := readJSON(resp.Body, &rekey); err != nil {
  923. return nil, errors.Wrapf(err, "error reading %s", u)
  924. }
  925. return &rekey, nil
  926. }
  927. // SSHRevoke performs the POST /ssh/revoke request to the CA and returns the
  928. // api.SSHRevokeResponse struct.
  929. func (c *Client) SSHRevoke(req *api.SSHRevokeRequest) (*api.SSHRevokeResponse, error) {
  930. var retried bool
  931. body, err := json.Marshal(req)
  932. if err != nil {
  933. return nil, errors.Wrap(err, "error marshaling request")
  934. }
  935. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/revoke"})
  936. retry:
  937. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  938. if err != nil {
  939. return nil, errors.Wrapf(err, "client POST %s failed", u)
  940. }
  941. if resp.StatusCode >= 400 {
  942. if !retried && c.retryOnError(resp) {
  943. retried = true
  944. goto retry
  945. }
  946. return nil, readError(resp.Body)
  947. }
  948. var revoke api.SSHRevokeResponse
  949. if err := readJSON(resp.Body, &revoke); err != nil {
  950. return nil, errors.Wrapf(err, "error reading %s", u)
  951. }
  952. return &revoke, nil
  953. }
  954. // SSHRoots performs the GET /ssh/roots request to the CA and returns the
  955. // api.SSHRootsResponse struct.
  956. func (c *Client) SSHRoots() (*api.SSHRootsResponse, error) {
  957. var retried bool
  958. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/roots"})
  959. retry:
  960. resp, err := c.client.Get(u.String())
  961. if err != nil {
  962. return nil, errors.Wrapf(err, "client GET %s failed", u)
  963. }
  964. if resp.StatusCode >= 400 {
  965. if !retried && c.retryOnError(resp) {
  966. retried = true
  967. goto retry
  968. }
  969. return nil, readError(resp.Body)
  970. }
  971. var keys api.SSHRootsResponse
  972. if err := readJSON(resp.Body, &keys); err != nil {
  973. return nil, errors.Wrapf(err, "error reading %s", u)
  974. }
  975. return &keys, nil
  976. }
  977. // SSHFederation performs the get /ssh/federation request to the CA and returns
  978. // the api.SSHRootsResponse struct.
  979. func (c *Client) SSHFederation() (*api.SSHRootsResponse, error) {
  980. var retried bool
  981. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/federation"})
  982. retry:
  983. resp, err := c.client.Get(u.String())
  984. if err != nil {
  985. return nil, errors.Wrapf(err, "client GET %s failed", u)
  986. }
  987. if resp.StatusCode >= 400 {
  988. if !retried && c.retryOnError(resp) {
  989. retried = true
  990. goto retry
  991. }
  992. return nil, readError(resp.Body)
  993. }
  994. var keys api.SSHRootsResponse
  995. if err := readJSON(resp.Body, &keys); err != nil {
  996. return nil, errors.Wrapf(err, "error reading %s", u)
  997. }
  998. return &keys, nil
  999. }
  1000. // SSHConfig performs the POST /ssh/config request to the CA to get the ssh
  1001. // configuration templates.
  1002. func (c *Client) SSHConfig(req *api.SSHConfigRequest) (*api.SSHConfigResponse, error) {
  1003. var retried bool
  1004. body, err := json.Marshal(req)
  1005. if err != nil {
  1006. return nil, errors.Wrap(err, "error marshaling request")
  1007. }
  1008. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/config"})
  1009. retry:
  1010. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  1011. if err != nil {
  1012. return nil, errors.Wrapf(err, "client POST %s failed", u)
  1013. }
  1014. if resp.StatusCode >= 400 {
  1015. if !retried && c.retryOnError(resp) {
  1016. retried = true
  1017. goto retry
  1018. }
  1019. return nil, readError(resp.Body)
  1020. }
  1021. var cfg api.SSHConfigResponse
  1022. if err := readJSON(resp.Body, &cfg); err != nil {
  1023. return nil, errors.Wrapf(err, "error reading %s", u)
  1024. }
  1025. return &cfg, nil
  1026. }
  1027. // SSHCheckHost performs the POST /ssh/check-host request to the CA with the
  1028. // given principal.
  1029. func (c *Client) SSHCheckHost(principal, token string) (*api.SSHCheckPrincipalResponse, error) {
  1030. var retried bool
  1031. body, err := json.Marshal(&api.SSHCheckPrincipalRequest{
  1032. Type: provisioner.SSHHostCert,
  1033. Principal: principal,
  1034. Token: token,
  1035. })
  1036. if err != nil {
  1037. return nil, errs.Wrap(http.StatusInternalServerError, err, "error marshaling request",
  1038. errs.WithMessage("Failed to marshal the check-host request"))
  1039. }
  1040. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/check-host"})
  1041. retry:
  1042. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  1043. if err != nil {
  1044. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client POST %s failed",
  1045. []interface{}{u, errs.WithMessage("Failed to perform POST request to %s", u)}...)
  1046. }
  1047. if resp.StatusCode >= 400 {
  1048. if !retried && c.retryOnError(resp) {
  1049. retried = true
  1050. goto retry
  1051. }
  1052. return nil, readError(resp.Body)
  1053. }
  1054. var check api.SSHCheckPrincipalResponse
  1055. if err := readJSON(resp.Body, &check); err != nil {
  1056. return nil, errs.Wrapf(http.StatusInternalServerError, err, "error reading %s response",
  1057. []interface{}{u, errs.WithMessage("Failed to parse response from /ssh/check-host endpoint")})
  1058. }
  1059. return &check, nil
  1060. }
  1061. // SSHGetHosts performs the GET /ssh/get-hosts request to the CA.
  1062. func (c *Client) SSHGetHosts() (*api.SSHGetHostsResponse, error) {
  1063. var retried bool
  1064. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/hosts"})
  1065. retry:
  1066. resp, err := c.client.Get(u.String())
  1067. if err != nil {
  1068. return nil, errors.Wrapf(err, "client GET %s failed", u)
  1069. }
  1070. if resp.StatusCode >= 400 {
  1071. if !retried && c.retryOnError(resp) {
  1072. retried = true
  1073. goto retry
  1074. }
  1075. return nil, readError(resp.Body)
  1076. }
  1077. var hosts api.SSHGetHostsResponse
  1078. if err := readJSON(resp.Body, &hosts); err != nil {
  1079. return nil, errors.Wrapf(err, "error reading %s", u)
  1080. }
  1081. return &hosts, nil
  1082. }
  1083. // SSHBastion performs the POST /ssh/bastion request to the CA.
  1084. func (c *Client) SSHBastion(req *api.SSHBastionRequest) (*api.SSHBastionResponse, error) {
  1085. var retried bool
  1086. body, err := json.Marshal(req)
  1087. if err != nil {
  1088. return nil, errors.Wrap(err, "client.SSHBastion; error marshaling request")
  1089. }
  1090. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/bastion"})
  1091. retry:
  1092. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  1093. if err != nil {
  1094. return nil, errors.Wrapf(err, "client.SSHBastion; client POST %s failed", u)
  1095. }
  1096. if resp.StatusCode >= 400 {
  1097. if !retried && c.retryOnError(resp) {
  1098. retried = true
  1099. goto retry
  1100. }
  1101. return nil, readError(resp.Body)
  1102. }
  1103. var bastion api.SSHBastionResponse
  1104. if err := readJSON(resp.Body, &bastion); err != nil {
  1105. return nil, errors.Wrapf(err, "client.SSHBastion; error reading %s", u)
  1106. }
  1107. return &bastion, nil
  1108. }
  1109. // RootFingerprint is a helper method that returns the current root fingerprint.
  1110. // It does an health connection and gets the fingerprint from the TLS verified
  1111. // chains.
  1112. func (c *Client) RootFingerprint() (string, error) {
  1113. u := c.endpoint.ResolveReference(&url.URL{Path: "/health"})
  1114. resp, err := c.client.Get(u.String())
  1115. if err != nil {
  1116. return "", errors.Wrapf(err, "client GET %s failed", u)
  1117. }
  1118. if resp.TLS == nil || len(resp.TLS.VerifiedChains) == 0 {
  1119. return "", errors.New("missing verified chains")
  1120. }
  1121. lastChain := resp.TLS.VerifiedChains[len(resp.TLS.VerifiedChains)-1]
  1122. if len(lastChain) == 0 {
  1123. return "", errors.New("missing verified chains")
  1124. }
  1125. return x509util.Fingerprint(lastChain[len(lastChain)-1]), nil
  1126. }
  1127. // CreateSignRequest is a helper function that given an x509 OTT returns a
  1128. // simple but secure sign request as well as the private key used.
  1129. func CreateSignRequest(ott string) (*api.SignRequest, crypto.PrivateKey, error) {
  1130. token, err := jwt.ParseSigned(ott)
  1131. if err != nil {
  1132. return nil, nil, errors.Wrap(err, "error parsing ott")
  1133. }
  1134. var claims authority.Claims
  1135. if err := token.UnsafeClaimsWithoutVerification(&claims); err != nil {
  1136. return nil, nil, errors.Wrap(err, "error parsing ott")
  1137. }
  1138. pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  1139. if err != nil {
  1140. return nil, nil, errors.Wrap(err, "error generating key")
  1141. }
  1142. dnsNames, ips, emails, uris := x509util.SplitSANs(claims.SANs)
  1143. if claims.Email != "" {
  1144. emails = append(emails, claims.Email)
  1145. }
  1146. template := &x509.CertificateRequest{
  1147. Subject: pkix.Name{
  1148. CommonName: claims.Subject,
  1149. },
  1150. SignatureAlgorithm: x509.ECDSAWithSHA256,
  1151. DNSNames: dnsNames,
  1152. IPAddresses: ips,
  1153. EmailAddresses: emails,
  1154. URIs: uris,
  1155. }
  1156. csr, err := x509.CreateCertificateRequest(rand.Reader, template, pk)
  1157. if err != nil {
  1158. return nil, nil, errors.Wrap(err, "error creating certificate request")
  1159. }
  1160. cr, err := x509.ParseCertificateRequest(csr)
  1161. if err != nil {
  1162. return nil, nil, errors.Wrap(err, "error parsing certificate request")
  1163. }
  1164. if err := cr.CheckSignature(); err != nil {
  1165. return nil, nil, errors.Wrap(err, "error signing certificate request")
  1166. }
  1167. return &api.SignRequest{
  1168. CsrPEM: api.CertificateRequest{CertificateRequest: cr},
  1169. OTT: ott,
  1170. }, pk, nil
  1171. }
  1172. // CreateCertificateRequest creates a new CSR with the given common name and
  1173. // SANs. If no san is provided the commonName will set also a SAN.
  1174. func CreateCertificateRequest(commonName string, sans ...string) (*api.CertificateRequest, crypto.PrivateKey, error) {
  1175. key, err := keyutil.GenerateDefaultKey()
  1176. if err != nil {
  1177. return nil, nil, err
  1178. }
  1179. return createCertificateRequest(commonName, sans, key)
  1180. }
  1181. // CreateIdentityRequest returns a new CSR to create the identity. If an
  1182. // identity was already present it reuses the private key.
  1183. func CreateIdentityRequest(commonName string, sans ...string) (*api.CertificateRequest, crypto.PrivateKey, error) {
  1184. var identityKey crypto.PrivateKey
  1185. if i, err := identity.LoadDefaultIdentity(); err == nil && i.Key != "" {
  1186. if k, err := pemutil.Read(i.Key); err == nil {
  1187. identityKey = k
  1188. }
  1189. }
  1190. if identityKey == nil {
  1191. return CreateCertificateRequest(commonName, sans...)
  1192. }
  1193. return createCertificateRequest(commonName, sans, identityKey)
  1194. }
  1195. // LoadDefaultIdentity is a wrapper for identity.LoadDefaultIdentity.
  1196. func LoadDefaultIdentity() (*identity.Identity, error) {
  1197. return identity.LoadDefaultIdentity()
  1198. }
  1199. // WriteDefaultIdentity is a wrapper for identity.WriteDefaultIdentity.
  1200. func WriteDefaultIdentity(certChain []api.Certificate, key crypto.PrivateKey) error {
  1201. return identity.WriteDefaultIdentity(certChain, key)
  1202. }
  1203. func createCertificateRequest(commonName string, sans []string, key crypto.PrivateKey) (*api.CertificateRequest, crypto.PrivateKey, error) {
  1204. if len(sans) == 0 {
  1205. sans = []string{commonName}
  1206. }
  1207. dnsNames, ips, emails, uris := x509util.SplitSANs(sans)
  1208. template := &x509.CertificateRequest{
  1209. Subject: pkix.Name{
  1210. CommonName: commonName,
  1211. },
  1212. DNSNames: dnsNames,
  1213. IPAddresses: ips,
  1214. EmailAddresses: emails,
  1215. URIs: uris,
  1216. }
  1217. csr, err := x509.CreateCertificateRequest(rand.Reader, template, key)
  1218. if err != nil {
  1219. return nil, nil, err
  1220. }
  1221. cr, err := x509.ParseCertificateRequest(csr)
  1222. if err != nil {
  1223. return nil, nil, err
  1224. }
  1225. if err := cr.CheckSignature(); err != nil {
  1226. return nil, nil, err
  1227. }
  1228. return &api.CertificateRequest{CertificateRequest: cr}, key, nil
  1229. }
  1230. // getRootCAPath returns the path where the root CA is stored based on the
  1231. // STEPPATH environment variable.
  1232. func getRootCAPath() string {
  1233. return filepath.Join(step.Path(), "certs", "root_ca.crt")
  1234. }
  1235. func readJSON(r io.ReadCloser, v interface{}) error {
  1236. defer r.Close()
  1237. return json.NewDecoder(r).Decode(v)
  1238. }
  1239. func readProtoJSON(r io.ReadCloser, m proto.Message) error {
  1240. defer r.Close()
  1241. data, err := io.ReadAll(r)
  1242. if err != nil {
  1243. return err
  1244. }
  1245. return protojson.Unmarshal(data, m)
  1246. }
  1247. func readError(r io.ReadCloser) error {
  1248. defer r.Close()
  1249. apiErr := new(errs.Error)
  1250. if err := json.NewDecoder(r).Decode(apiErr); err != nil {
  1251. return err
  1252. }
  1253. return apiErr
  1254. }