client.go 35 KB

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