client.go 34 KB

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