client.go 38 KB

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