client.go 32 KB

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