client.go 34 KB

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