4
0

client.go 33 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/cli/config"
  28. "github.com/smallstep/cli/crypto/keys"
  29. "github.com/smallstep/cli/crypto/pemutil"
  30. "github.com/smallstep/cli/crypto/x509util"
  31. "golang.org/x/net/http2"
  32. "gopkg.in/square/go-jose.v2/jwt"
  33. )
  34. // DisableIdentity is a global variable to disable the identity.
  35. var DisableIdentity = false
  36. // UserAgent will set the User-Agent header in the client requests.
  37. var UserAgent = "step-http-client/1.0"
  38. type uaClient struct {
  39. Client *http.Client
  40. }
  41. func newClient(transport http.RoundTripper) *uaClient {
  42. return &uaClient{
  43. Client: &http.Client{
  44. Transport: transport,
  45. },
  46. }
  47. }
  48. func newInsecureClient() *uaClient {
  49. return &uaClient{
  50. Client: &http.Client{
  51. Transport: &http.Transport{
  52. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  53. },
  54. },
  55. }
  56. }
  57. func (c *uaClient) GetTransport() http.RoundTripper {
  58. return c.Client.Transport
  59. }
  60. func (c *uaClient) SetTransport(tr http.RoundTripper) {
  61. c.Client.Transport = tr
  62. }
  63. func (c *uaClient) Get(url string) (*http.Response, error) {
  64. req, err := http.NewRequest("GET", url, nil)
  65. if err != nil {
  66. return nil, errors.Wrapf(err, "new request GET %s failed", url)
  67. }
  68. req.Header.Set("User-Agent", UserAgent)
  69. return c.Client.Do(req)
  70. }
  71. func (c *uaClient) Post(url, contentType string, body io.Reader) (*http.Response, error) {
  72. req, err := http.NewRequest("POST", url, body)
  73. if err != nil {
  74. return nil, err
  75. }
  76. req.Header.Set("Content-Type", contentType)
  77. req.Header.Set("User-Agent", UserAgent)
  78. return c.Client.Do(req)
  79. }
  80. // RetryFunc defines the method used to retry a request. If it returns true, the
  81. // request will be retried once.
  82. type RetryFunc func(code int) bool
  83. // ClientOption is the type of options passed to the Client constructor.
  84. type ClientOption func(o *clientOptions) error
  85. type clientOptions struct {
  86. transport http.RoundTripper
  87. rootSHA256 string
  88. rootFilename string
  89. rootBundle []byte
  90. certificate tls.Certificate
  91. retryFunc RetryFunc
  92. }
  93. func (o *clientOptions) apply(opts []ClientOption) (err error) {
  94. if err = o.applyDefaultIdentity(); err != nil {
  95. return
  96. }
  97. for _, fn := range opts {
  98. if err = fn(o); err != nil {
  99. return
  100. }
  101. }
  102. return
  103. }
  104. // applyDefaultIdentity sets the options for the default identity if the
  105. // identity file is present. The identity is enabled by default.
  106. func (o *clientOptions) applyDefaultIdentity() error {
  107. if DisableIdentity {
  108. return nil
  109. }
  110. // Do not load an identity if something fails
  111. i, err := identity.LoadDefaultIdentity()
  112. if err != nil {
  113. return nil
  114. }
  115. if err := i.Validate(); err != nil {
  116. return nil
  117. }
  118. crt, err := i.TLSCertificate()
  119. if err != nil {
  120. return nil
  121. }
  122. o.certificate = crt
  123. return nil
  124. }
  125. // checkTransport checks if other ways to set up a transport have been provided.
  126. // If they have it returns an error.
  127. func (o *clientOptions) checkTransport() error {
  128. if o.transport != nil || o.rootFilename != "" || o.rootSHA256 != "" || o.rootBundle != nil {
  129. return errors.New("multiple transport methods have been configured")
  130. }
  131. return nil
  132. }
  133. // getTransport returns the transport configured in the clientOptions.
  134. func (o *clientOptions) getTransport(endpoint string) (tr http.RoundTripper, err error) {
  135. if o.transport != nil {
  136. tr = o.transport
  137. }
  138. if o.rootFilename != "" {
  139. if tr, err = getTransportFromFile(o.rootFilename); err != nil {
  140. return nil, err
  141. }
  142. }
  143. if o.rootSHA256 != "" {
  144. if tr, err = getTransportFromSHA256(endpoint, o.rootSHA256); err != nil {
  145. return nil, err
  146. }
  147. }
  148. if o.rootBundle != nil {
  149. if tr, err = getTransportFromCABundle(o.rootBundle); err != nil {
  150. return nil, err
  151. }
  152. }
  153. // As the last option attempt to load the default root ca
  154. if tr == nil {
  155. rootFile := getRootCAPath()
  156. if _, err := os.Stat(rootFile); err == nil {
  157. if tr, err = getTransportFromFile(rootFile); err != nil {
  158. return nil, err
  159. }
  160. }
  161. if tr == nil {
  162. return nil, errors.New("a transport, a root cert, or a root sha256 must be used")
  163. }
  164. }
  165. // Add client certificate if available
  166. if o.certificate.Certificate != nil {
  167. switch tr := tr.(type) {
  168. case *http.Transport:
  169. if tr.TLSClientConfig == nil {
  170. tr.TLSClientConfig = &tls.Config{}
  171. }
  172. if len(tr.TLSClientConfig.Certificates) == 0 && tr.TLSClientConfig.GetClientCertificate == nil {
  173. tr.TLSClientConfig.Certificates = []tls.Certificate{o.certificate}
  174. }
  175. case *http2.Transport:
  176. if tr.TLSClientConfig == nil {
  177. tr.TLSClientConfig = &tls.Config{}
  178. }
  179. if len(tr.TLSClientConfig.Certificates) == 0 && tr.TLSClientConfig.GetClientCertificate == nil {
  180. tr.TLSClientConfig.Certificates = []tls.Certificate{o.certificate}
  181. }
  182. default:
  183. return nil, errors.Errorf("unsupported transport type %T", tr)
  184. }
  185. }
  186. return tr, nil
  187. }
  188. // WithTransport adds a custom transport to the Client. It will fail if a
  189. // previous option to create the transport has been configured.
  190. func WithTransport(tr http.RoundTripper) ClientOption {
  191. return func(o *clientOptions) error {
  192. if err := o.checkTransport(); err != nil {
  193. return err
  194. }
  195. o.transport = tr
  196. return nil
  197. }
  198. }
  199. // WithRootFile will create the transport using the given root certificate. It
  200. // will fail if a previous option to create the transport has been configured.
  201. func WithRootFile(filename string) ClientOption {
  202. return func(o *clientOptions) error {
  203. if err := o.checkTransport(); err != nil {
  204. return err
  205. }
  206. o.rootFilename = filename
  207. return nil
  208. }
  209. }
  210. // WithRootSHA256 will create the transport using an insecure client to retrieve
  211. // the root certificate using its fingerprint. It will fail if a previous option
  212. // to create the transport has been configured.
  213. func WithRootSHA256(sum string) ClientOption {
  214. return func(o *clientOptions) error {
  215. if err := o.checkTransport(); err != nil {
  216. return err
  217. }
  218. o.rootSHA256 = sum
  219. return nil
  220. }
  221. }
  222. // WithCABundle will create the transport using the given root certificates. It
  223. // will fail if a previous option to create the transport has been configured.
  224. func WithCABundle(bundle []byte) ClientOption {
  225. return func(o *clientOptions) error {
  226. if err := o.checkTransport(); err != nil {
  227. return err
  228. }
  229. o.rootBundle = bundle
  230. return nil
  231. }
  232. }
  233. // WithCertificate will set the given certificate as the TLS client certificate
  234. // in the client.
  235. func WithCertificate(crt tls.Certificate) ClientOption {
  236. return func(o *clientOptions) error {
  237. o.certificate = crt
  238. return nil
  239. }
  240. }
  241. // WithRetryFunc defines a method used to retry a request.
  242. func WithRetryFunc(fn RetryFunc) ClientOption {
  243. return func(o *clientOptions) error {
  244. o.retryFunc = fn
  245. return nil
  246. }
  247. }
  248. func getTransportFromFile(filename string) (http.RoundTripper, error) {
  249. data, err := ioutil.ReadFile(filename)
  250. if err != nil {
  251. return nil, errors.Wrapf(err, "error reading %s", filename)
  252. }
  253. pool := x509.NewCertPool()
  254. if !pool.AppendCertsFromPEM(data) {
  255. return nil, errors.Errorf("error parsing %s: no certificates found", filename)
  256. }
  257. return getDefaultTransport(&tls.Config{
  258. MinVersion: tls.VersionTLS12,
  259. PreferServerCipherSuites: true,
  260. RootCAs: pool,
  261. })
  262. }
  263. func getTransportFromSHA256(endpoint, sum string) (http.RoundTripper, error) {
  264. u, err := parseEndpoint(endpoint)
  265. if err != nil {
  266. return nil, err
  267. }
  268. client := &Client{endpoint: u}
  269. root, err := client.Root(sum)
  270. if err != nil {
  271. return nil, err
  272. }
  273. pool := x509.NewCertPool()
  274. pool.AddCert(root.RootPEM.Certificate)
  275. return getDefaultTransport(&tls.Config{
  276. MinVersion: tls.VersionTLS12,
  277. PreferServerCipherSuites: true,
  278. RootCAs: pool,
  279. })
  280. }
  281. func getTransportFromCABundle(bundle []byte) (http.RoundTripper, error) {
  282. pool := x509.NewCertPool()
  283. if !pool.AppendCertsFromPEM(bundle) {
  284. return nil, errors.New("error parsing ca bundle: no certificates found")
  285. }
  286. return getDefaultTransport(&tls.Config{
  287. MinVersion: tls.VersionTLS12,
  288. PreferServerCipherSuites: true,
  289. RootCAs: pool,
  290. })
  291. }
  292. // parseEndpoint parses and validates the given endpoint. It supports general
  293. // URLs like https://ca.smallstep.com[:port][/path], and incomplete URLs like
  294. // ca.smallstep.com[:port][/path].
  295. func parseEndpoint(endpoint string) (*url.URL, error) {
  296. u, err := url.Parse(endpoint)
  297. if err != nil {
  298. return nil, errors.Wrapf(err, "error parsing endpoint '%s'", endpoint)
  299. }
  300. // URLs are generally parsed as:
  301. // [scheme:][//[userinfo@]host][/]path[?query][#fragment]
  302. // But URLs that do not start with a slash after the scheme are interpreted as
  303. // scheme:opaque[?query][#fragment]
  304. if u.Opaque == "" {
  305. if u.Scheme == "" {
  306. u.Scheme = "https"
  307. }
  308. if u.Host == "" {
  309. // endpoint looks like ca.smallstep.com or ca.smallstep.com/1.0/sign
  310. if u.Path != "" {
  311. parts := strings.SplitN(u.Path, "/", 2)
  312. u.Host = parts[0]
  313. if len(parts) == 2 {
  314. u.Path = parts[1]
  315. } else {
  316. u.Path = ""
  317. }
  318. return parseEndpoint(u.String())
  319. }
  320. return nil, errors.Errorf("error parsing endpoint: url '%s' is not valid", endpoint)
  321. }
  322. return u, nil
  323. }
  324. // scheme:opaque[?query][#fragment]
  325. // endpoint looks like ca.smallstep.com:443 or ca.smallstep.com:443/1.0/sign
  326. return parseEndpoint("https://" + endpoint)
  327. }
  328. // ProvisionerOption is the type of options passed to the Provisioner method.
  329. type ProvisionerOption func(o *provisionerOptions) error
  330. type provisionerOptions struct {
  331. cursor string
  332. limit int
  333. }
  334. func (o *provisionerOptions) apply(opts []ProvisionerOption) (err error) {
  335. for _, fn := range opts {
  336. if err = fn(o); err != nil {
  337. return
  338. }
  339. }
  340. return
  341. }
  342. func (o *provisionerOptions) rawQuery() string {
  343. v := url.Values{}
  344. if len(o.cursor) > 0 {
  345. v.Set("cursor", o.cursor)
  346. }
  347. if o.limit > 0 {
  348. v.Set("limit", strconv.Itoa(o.limit))
  349. }
  350. return v.Encode()
  351. }
  352. // WithProvisionerCursor will request the provisioners starting with the given cursor.
  353. func WithProvisionerCursor(cursor string) ProvisionerOption {
  354. return func(o *provisionerOptions) error {
  355. o.cursor = cursor
  356. return nil
  357. }
  358. }
  359. // WithProvisionerLimit will request the given number of provisioners.
  360. func WithProvisionerLimit(limit int) ProvisionerOption {
  361. return func(o *provisionerOptions) error {
  362. o.limit = limit
  363. return nil
  364. }
  365. }
  366. // Client implements an HTTP client for the CA server.
  367. type Client struct {
  368. client *uaClient
  369. endpoint *url.URL
  370. retryFunc RetryFunc
  371. opts []ClientOption
  372. }
  373. // NewClient creates a new Client with the given endpoint and options.
  374. func NewClient(endpoint string, opts ...ClientOption) (*Client, error) {
  375. u, err := parseEndpoint(endpoint)
  376. if err != nil {
  377. return nil, err
  378. }
  379. // Retrieve transport from options.
  380. o := new(clientOptions)
  381. if err := o.apply(opts); err != nil {
  382. return nil, err
  383. }
  384. tr, err := o.getTransport(endpoint)
  385. if err != nil {
  386. return nil, err
  387. }
  388. return &Client{
  389. client: newClient(tr),
  390. endpoint: u,
  391. retryFunc: o.retryFunc,
  392. opts: opts,
  393. }, nil
  394. }
  395. func (c *Client) retryOnError(r *http.Response) bool {
  396. if c.retryFunc != nil {
  397. if c.retryFunc(r.StatusCode) {
  398. o := new(clientOptions)
  399. if err := o.apply(c.opts); err != nil {
  400. return false
  401. }
  402. tr, err := o.getTransport(c.endpoint.String())
  403. if err != nil {
  404. return false
  405. }
  406. r.Body.Close()
  407. c.client.SetTransport(tr)
  408. return true
  409. }
  410. }
  411. return false
  412. }
  413. // GetRootCAs returns the RootCAs certificate pool from the configured
  414. // transport.
  415. func (c *Client) GetRootCAs() *x509.CertPool {
  416. switch t := c.client.GetTransport().(type) {
  417. case *http.Transport:
  418. if t.TLSClientConfig != nil {
  419. return t.TLSClientConfig.RootCAs
  420. }
  421. return nil
  422. case *http2.Transport:
  423. if t.TLSClientConfig != nil {
  424. return t.TLSClientConfig.RootCAs
  425. }
  426. return nil
  427. default:
  428. return nil
  429. }
  430. }
  431. // GetTransport returns the transport of the internal HTTP client.
  432. func (c *Client) GetTransport() http.RoundTripper {
  433. return c.client.GetTransport()
  434. }
  435. // SetTransport updates the transport of the internal HTTP client.
  436. func (c *Client) SetTransport(tr http.RoundTripper) {
  437. c.client.SetTransport(tr)
  438. }
  439. // Version performs the version request to the CA and returns the
  440. // api.VersionResponse struct.
  441. func (c *Client) Version() (*api.VersionResponse, error) {
  442. var retried bool
  443. u := c.endpoint.ResolveReference(&url.URL{Path: "/version"})
  444. retry:
  445. resp, err := c.client.Get(u.String())
  446. if err != nil {
  447. return nil, errors.Wrapf(err, "client GET %s failed", u)
  448. }
  449. if resp.StatusCode >= 400 {
  450. if !retried && c.retryOnError(resp) {
  451. retried = true
  452. goto retry
  453. }
  454. return nil, readError(resp.Body)
  455. }
  456. var version api.VersionResponse
  457. if err := readJSON(resp.Body, &version); err != nil {
  458. return nil, errors.Wrapf(err, "error reading %s", u)
  459. }
  460. return &version, nil
  461. }
  462. // Health performs the health request to the CA and returns the
  463. // api.HealthResponse struct.
  464. func (c *Client) Health() (*api.HealthResponse, error) {
  465. var retried bool
  466. u := c.endpoint.ResolveReference(&url.URL{Path: "/health"})
  467. retry:
  468. resp, err := c.client.Get(u.String())
  469. if err != nil {
  470. return nil, errors.Wrapf(err, "client GET %s failed", u)
  471. }
  472. if resp.StatusCode >= 400 {
  473. if !retried && c.retryOnError(resp) {
  474. retried = true
  475. goto retry
  476. }
  477. return nil, readError(resp.Body)
  478. }
  479. var health api.HealthResponse
  480. if err := readJSON(resp.Body, &health); err != nil {
  481. return nil, errors.Wrapf(err, "error reading %s", u)
  482. }
  483. return &health, nil
  484. }
  485. // Root performs the root request to the CA with the given SHA256 and returns
  486. // the api.RootResponse struct. It uses an insecure client, but it checks the
  487. // resulting root certificate with the given SHA256, returning an error if they
  488. // do not match.
  489. func (c *Client) Root(sha256Sum string) (*api.RootResponse, error) {
  490. var retried bool
  491. sha256Sum = strings.ToLower(strings.Replace(sha256Sum, "-", "", -1))
  492. u := c.endpoint.ResolveReference(&url.URL{Path: "/root/" + sha256Sum})
  493. retry:
  494. resp, err := newInsecureClient().Get(u.String())
  495. if err != nil {
  496. return nil, errors.Wrapf(err, "client GET %s failed", u)
  497. }
  498. if resp.StatusCode >= 400 {
  499. if !retried && c.retryOnError(resp) {
  500. retried = true
  501. goto retry
  502. }
  503. return nil, readError(resp.Body)
  504. }
  505. var root api.RootResponse
  506. if err := readJSON(resp.Body, &root); err != nil {
  507. return nil, errors.Wrapf(err, "error reading %s", u)
  508. }
  509. // verify the sha256
  510. sum := sha256.Sum256(root.RootPEM.Raw)
  511. if sha256Sum != strings.ToLower(hex.EncodeToString(sum[:])) {
  512. return nil, errors.New("root certificate SHA256 fingerprint do not match")
  513. }
  514. return &root, nil
  515. }
  516. // Sign performs the sign request to the CA and returns the api.SignResponse
  517. // struct.
  518. func (c *Client) Sign(req *api.SignRequest) (*api.SignResponse, error) {
  519. var retried bool
  520. body, err := json.Marshal(req)
  521. if err != nil {
  522. return nil, errors.Wrap(err, "error marshaling request")
  523. }
  524. u := c.endpoint.ResolveReference(&url.URL{Path: "/sign"})
  525. retry:
  526. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  527. if err != nil {
  528. return nil, errors.Wrapf(err, "client POST %s failed", u)
  529. }
  530. if resp.StatusCode >= 400 {
  531. if !retried && c.retryOnError(resp) {
  532. retried = true
  533. goto retry
  534. }
  535. return nil, readError(resp.Body)
  536. }
  537. var sign api.SignResponse
  538. if err := readJSON(resp.Body, &sign); err != nil {
  539. return nil, errors.Wrapf(err, "error reading %s", u)
  540. }
  541. // Add tls.ConnectionState:
  542. // We'll extract the root certificate from the verified chains
  543. sign.TLS = resp.TLS
  544. return &sign, nil
  545. }
  546. // Renew performs the renew request to the CA and returns the api.SignResponse
  547. // struct.
  548. func (c *Client) Renew(tr http.RoundTripper) (*api.SignResponse, error) {
  549. var retried bool
  550. u := c.endpoint.ResolveReference(&url.URL{Path: "/renew"})
  551. client := &http.Client{Transport: tr}
  552. retry:
  553. resp, err := client.Post(u.String(), "application/json", http.NoBody)
  554. if err != nil {
  555. return nil, errors.Wrapf(err, "client POST %s failed", u)
  556. }
  557. if resp.StatusCode >= 400 {
  558. if !retried && c.retryOnError(resp) {
  559. retried = true
  560. goto retry
  561. }
  562. return nil, readError(resp.Body)
  563. }
  564. var sign api.SignResponse
  565. if err := readJSON(resp.Body, &sign); err != nil {
  566. return nil, errors.Wrapf(err, "error reading %s", u)
  567. }
  568. return &sign, nil
  569. }
  570. // Revoke performs the revoke request to the CA and returns the api.RevokeResponse
  571. // struct.
  572. func (c *Client) Revoke(req *api.RevokeRequest, tr http.RoundTripper) (*api.RevokeResponse, error) {
  573. var retried bool
  574. body, err := json.Marshal(req)
  575. if err != nil {
  576. return nil, errors.Wrap(err, "error marshaling request")
  577. }
  578. var client *uaClient
  579. retry:
  580. if tr != nil {
  581. client = newClient(tr)
  582. } else {
  583. client = c.client
  584. }
  585. u := c.endpoint.ResolveReference(&url.URL{Path: "/revoke"})
  586. resp, err := client.Post(u.String(), "application/json", bytes.NewReader(body))
  587. if err != nil {
  588. return nil, errors.Wrapf(err, "client POST %s failed", u)
  589. }
  590. if resp.StatusCode >= 400 {
  591. if !retried && c.retryOnError(resp) {
  592. retried = true
  593. goto retry
  594. }
  595. return nil, readError(resp.Body)
  596. }
  597. var revoke api.RevokeResponse
  598. if err := readJSON(resp.Body, &revoke); err != nil {
  599. return nil, errors.Wrapf(err, "error reading %s", u)
  600. }
  601. return &revoke, nil
  602. }
  603. // Provisioners performs the provisioners request to the CA and returns the
  604. // api.ProvisionersResponse struct with a map of provisioners.
  605. //
  606. // ProvisionerOption WithProvisionerCursor and WithProvisionLimit can be used to
  607. // paginate the provisioners.
  608. func (c *Client) Provisioners(opts ...ProvisionerOption) (*api.ProvisionersResponse, error) {
  609. var retried bool
  610. o := new(provisionerOptions)
  611. if err := o.apply(opts); err != nil {
  612. return nil, err
  613. }
  614. u := c.endpoint.ResolveReference(&url.URL{
  615. Path: "/provisioners",
  616. RawQuery: o.rawQuery(),
  617. })
  618. retry:
  619. resp, err := c.client.Get(u.String())
  620. if err != nil {
  621. return nil, errors.Wrapf(err, "client GET %s failed", u)
  622. }
  623. if resp.StatusCode >= 400 {
  624. if !retried && c.retryOnError(resp) {
  625. retried = true
  626. goto retry
  627. }
  628. return nil, readError(resp.Body)
  629. }
  630. var provisioners api.ProvisionersResponse
  631. if err := readJSON(resp.Body, &provisioners); err != nil {
  632. return nil, errors.Wrapf(err, "error reading %s", u)
  633. }
  634. return &provisioners, nil
  635. }
  636. // ProvisionerKey performs the request to the CA to get the encrypted key for
  637. // the given provisioner kid and returns the api.ProvisionerKeyResponse struct
  638. // with the encrypted key.
  639. func (c *Client) ProvisionerKey(kid string) (*api.ProvisionerKeyResponse, error) {
  640. var retried bool
  641. u := c.endpoint.ResolveReference(&url.URL{Path: "/provisioners/" + kid + "/encrypted-key"})
  642. retry:
  643. resp, err := c.client.Get(u.String())
  644. if err != nil {
  645. return nil, errors.Wrapf(err, "client GET %s failed", u)
  646. }
  647. if resp.StatusCode >= 400 {
  648. if !retried && c.retryOnError(resp) {
  649. retried = true
  650. goto retry
  651. }
  652. return nil, readError(resp.Body)
  653. }
  654. var key api.ProvisionerKeyResponse
  655. if err := readJSON(resp.Body, &key); err != nil {
  656. return nil, errors.Wrapf(err, "error reading %s", u)
  657. }
  658. return &key, nil
  659. }
  660. // Roots performs the get roots request to the CA and returns the
  661. // api.RootsResponse struct.
  662. func (c *Client) Roots() (*api.RootsResponse, error) {
  663. var retried bool
  664. u := c.endpoint.ResolveReference(&url.URL{Path: "/roots"})
  665. retry:
  666. resp, err := c.client.Get(u.String())
  667. if err != nil {
  668. return nil, errors.Wrapf(err, "client GET %s failed", u)
  669. }
  670. if resp.StatusCode >= 400 {
  671. if !retried && c.retryOnError(resp) {
  672. retried = true
  673. goto retry
  674. }
  675. return nil, readError(resp.Body)
  676. }
  677. var roots api.RootsResponse
  678. if err := readJSON(resp.Body, &roots); err != nil {
  679. return nil, errors.Wrapf(err, "error reading %s", u)
  680. }
  681. return &roots, nil
  682. }
  683. // Federation performs the get federation request to the CA and returns the
  684. // api.FederationResponse struct.
  685. func (c *Client) Federation() (*api.FederationResponse, error) {
  686. var retried bool
  687. u := c.endpoint.ResolveReference(&url.URL{Path: "/federation"})
  688. retry:
  689. resp, err := c.client.Get(u.String())
  690. if err != nil {
  691. return nil, errors.Wrapf(err, "client GET %s failed", u)
  692. }
  693. if resp.StatusCode >= 400 {
  694. if !retried && c.retryOnError(resp) {
  695. retried = true
  696. goto retry
  697. }
  698. return nil, readError(resp.Body)
  699. }
  700. var federation api.FederationResponse
  701. if err := readJSON(resp.Body, &federation); err != nil {
  702. return nil, errors.Wrapf(err, "error reading %s", u)
  703. }
  704. return &federation, nil
  705. }
  706. // SSHSign performs the POST /ssh/sign request to the CA and returns the
  707. // api.SSHSignResponse struct.
  708. func (c *Client) SSHSign(req *api.SSHSignRequest) (*api.SSHSignResponse, error) {
  709. var retried bool
  710. body, err := json.Marshal(req)
  711. if err != nil {
  712. return nil, errors.Wrap(err, "error marshaling request")
  713. }
  714. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/sign"})
  715. retry:
  716. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  717. if err != nil {
  718. return nil, errors.Wrapf(err, "client POST %s failed", u)
  719. }
  720. if resp.StatusCode >= 400 {
  721. if !retried && c.retryOnError(resp) {
  722. retried = true
  723. goto retry
  724. }
  725. return nil, readError(resp.Body)
  726. }
  727. var sign api.SSHSignResponse
  728. if err := readJSON(resp.Body, &sign); err != nil {
  729. return nil, errors.Wrapf(err, "error reading %s", u)
  730. }
  731. return &sign, nil
  732. }
  733. // SSHRenew performs the POST /ssh/renew request to the CA and returns the
  734. // api.SSHRenewResponse struct.
  735. func (c *Client) SSHRenew(req *api.SSHRenewRequest) (*api.SSHRenewResponse, error) {
  736. var retried bool
  737. body, err := json.Marshal(req)
  738. if err != nil {
  739. return nil, errors.Wrap(err, "error marshaling request")
  740. }
  741. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/renew"})
  742. retry:
  743. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  744. if err != nil {
  745. return nil, errors.Wrapf(err, "client POST %s failed", u)
  746. }
  747. if resp.StatusCode >= 400 {
  748. if !retried && c.retryOnError(resp) {
  749. retried = true
  750. goto retry
  751. }
  752. return nil, readError(resp.Body)
  753. }
  754. var renew api.SSHRenewResponse
  755. if err := readJSON(resp.Body, &renew); err != nil {
  756. return nil, errors.Wrapf(err, "error reading %s", u)
  757. }
  758. return &renew, nil
  759. }
  760. // SSHRekey performs the POST /ssh/rekey request to the CA and returns the
  761. // api.SSHRekeyResponse struct.
  762. func (c *Client) SSHRekey(req *api.SSHRekeyRequest) (*api.SSHRekeyResponse, error) {
  763. var retried bool
  764. body, err := json.Marshal(req)
  765. if err != nil {
  766. return nil, errors.Wrap(err, "error marshaling request")
  767. }
  768. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/rekey"})
  769. retry:
  770. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  771. if err != nil {
  772. return nil, errors.Wrapf(err, "client POST %s failed", u)
  773. }
  774. if resp.StatusCode >= 400 {
  775. if !retried && c.retryOnError(resp) {
  776. retried = true
  777. goto retry
  778. }
  779. return nil, readError(resp.Body)
  780. }
  781. var rekey api.SSHRekeyResponse
  782. if err := readJSON(resp.Body, &rekey); err != nil {
  783. return nil, errors.Wrapf(err, "error reading %s", u)
  784. }
  785. return &rekey, nil
  786. }
  787. // SSHRevoke performs the POST /ssh/revoke request to the CA and returns the
  788. // api.SSHRevokeResponse struct.
  789. func (c *Client) SSHRevoke(req *api.SSHRevokeRequest) (*api.SSHRevokeResponse, error) {
  790. var retried bool
  791. body, err := json.Marshal(req)
  792. if err != nil {
  793. return nil, errors.Wrap(err, "error marshaling request")
  794. }
  795. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/revoke"})
  796. retry:
  797. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  798. if err != nil {
  799. return nil, errors.Wrapf(err, "client POST %s failed", u)
  800. }
  801. if resp.StatusCode >= 400 {
  802. if !retried && c.retryOnError(resp) {
  803. retried = true
  804. goto retry
  805. }
  806. return nil, readError(resp.Body)
  807. }
  808. var revoke api.SSHRevokeResponse
  809. if err := readJSON(resp.Body, &revoke); err != nil {
  810. return nil, errors.Wrapf(err, "error reading %s", u)
  811. }
  812. return &revoke, nil
  813. }
  814. // SSHRoots performs the GET /ssh/roots request to the CA and returns the
  815. // api.SSHRootsResponse struct.
  816. func (c *Client) SSHRoots() (*api.SSHRootsResponse, error) {
  817. var retried bool
  818. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/roots"})
  819. retry:
  820. resp, err := c.client.Get(u.String())
  821. if err != nil {
  822. return nil, errors.Wrapf(err, "client GET %s failed", u)
  823. }
  824. if resp.StatusCode >= 400 {
  825. if !retried && c.retryOnError(resp) {
  826. retried = true
  827. goto retry
  828. }
  829. return nil, readError(resp.Body)
  830. }
  831. var keys api.SSHRootsResponse
  832. if err := readJSON(resp.Body, &keys); err != nil {
  833. return nil, errors.Wrapf(err, "error reading %s", u)
  834. }
  835. return &keys, nil
  836. }
  837. // SSHFederation performs the get /ssh/federation request to the CA and returns
  838. // the api.SSHRootsResponse struct.
  839. func (c *Client) SSHFederation() (*api.SSHRootsResponse, error) {
  840. var retried bool
  841. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/federation"})
  842. retry:
  843. resp, err := c.client.Get(u.String())
  844. if err != nil {
  845. return nil, errors.Wrapf(err, "client GET %s failed", u)
  846. }
  847. if resp.StatusCode >= 400 {
  848. if !retried && c.retryOnError(resp) {
  849. retried = true
  850. goto retry
  851. }
  852. return nil, readError(resp.Body)
  853. }
  854. var keys api.SSHRootsResponse
  855. if err := readJSON(resp.Body, &keys); err != nil {
  856. return nil, errors.Wrapf(err, "error reading %s", u)
  857. }
  858. return &keys, nil
  859. }
  860. // SSHConfig performs the POST /ssh/config request to the CA to get the ssh
  861. // configuration templates.
  862. func (c *Client) SSHConfig(req *api.SSHConfigRequest) (*api.SSHConfigResponse, error) {
  863. var retried bool
  864. body, err := json.Marshal(req)
  865. if err != nil {
  866. return nil, errors.Wrap(err, "error marshaling request")
  867. }
  868. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/config"})
  869. retry:
  870. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  871. if err != nil {
  872. return nil, errors.Wrapf(err, "client POST %s failed", u)
  873. }
  874. if resp.StatusCode >= 400 {
  875. if !retried && c.retryOnError(resp) {
  876. retried = true
  877. goto retry
  878. }
  879. return nil, readError(resp.Body)
  880. }
  881. var config api.SSHConfigResponse
  882. if err := readJSON(resp.Body, &config); err != nil {
  883. return nil, errors.Wrapf(err, "error reading %s", u)
  884. }
  885. return &config, nil
  886. }
  887. // SSHCheckHost performs the POST /ssh/check-host request to the CA with the
  888. // given principal.
  889. func (c *Client) SSHCheckHost(principal string, token string) (*api.SSHCheckPrincipalResponse, error) {
  890. var retried bool
  891. body, err := json.Marshal(&api.SSHCheckPrincipalRequest{
  892. Type: provisioner.SSHHostCert,
  893. Principal: principal,
  894. Token: token,
  895. })
  896. if err != nil {
  897. return nil, errors.Wrap(err, "error marshaling request")
  898. }
  899. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/check-host"})
  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 check api.SSHCheckPrincipalResponse
  913. if err := readJSON(resp.Body, &check); err != nil {
  914. return nil, errors.Wrapf(err, "error reading %s", u)
  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, "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 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, "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(api.Error)
  1097. if err := json.NewDecoder(r).Decode(apiErr); err != nil {
  1098. return err
  1099. }
  1100. return apiErr
  1101. }