client.go 39 KB

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