client.go 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153
  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. // SetTransport updates the transport of the internal HTTP client.
  435. func (c *Client) SetTransport(tr http.RoundTripper) {
  436. c.client.SetTransport(tr)
  437. }
  438. // Version performs the version request to the CA and returns the
  439. // api.VersionResponse struct.
  440. func (c *Client) Version() (*api.VersionResponse, error) {
  441. var retried bool
  442. u := c.endpoint.ResolveReference(&url.URL{Path: "/version"})
  443. retry:
  444. resp, err := c.client.Get(u.String())
  445. if err != nil {
  446. return nil, errors.Wrapf(err, "client GET %s failed", u)
  447. }
  448. if resp.StatusCode >= 400 {
  449. if !retried && c.retryOnError(resp) {
  450. retried = true
  451. goto retry
  452. }
  453. return nil, readError(resp.Body)
  454. }
  455. var version api.VersionResponse
  456. if err := readJSON(resp.Body, &version); err != nil {
  457. return nil, errors.Wrapf(err, "error reading %s", u)
  458. }
  459. return &version, nil
  460. }
  461. // Health performs the health request to the CA and returns the
  462. // api.HealthResponse struct.
  463. func (c *Client) Health() (*api.HealthResponse, error) {
  464. var retried bool
  465. u := c.endpoint.ResolveReference(&url.URL{Path: "/health"})
  466. retry:
  467. resp, err := c.client.Get(u.String())
  468. if err != nil {
  469. return nil, errors.Wrapf(err, "client GET %s failed", u)
  470. }
  471. if resp.StatusCode >= 400 {
  472. if !retried && c.retryOnError(resp) {
  473. retried = true
  474. goto retry
  475. }
  476. return nil, readError(resp.Body)
  477. }
  478. var health api.HealthResponse
  479. if err := readJSON(resp.Body, &health); err != nil {
  480. return nil, errors.Wrapf(err, "error reading %s", u)
  481. }
  482. return &health, nil
  483. }
  484. // Root performs the root request to the CA with the given SHA256 and returns
  485. // the api.RootResponse struct. It uses an insecure client, but it checks the
  486. // resulting root certificate with the given SHA256, returning an error if they
  487. // do not match.
  488. func (c *Client) Root(sha256Sum string) (*api.RootResponse, error) {
  489. var retried bool
  490. sha256Sum = strings.ToLower(strings.Replace(sha256Sum, "-", "", -1))
  491. u := c.endpoint.ResolveReference(&url.URL{Path: "/root/" + sha256Sum})
  492. retry:
  493. resp, err := newInsecureClient().Get(u.String())
  494. if err != nil {
  495. return nil, errors.Wrapf(err, "client GET %s failed", u)
  496. }
  497. if resp.StatusCode >= 400 {
  498. if !retried && c.retryOnError(resp) {
  499. retried = true
  500. goto retry
  501. }
  502. return nil, readError(resp.Body)
  503. }
  504. var root api.RootResponse
  505. if err := readJSON(resp.Body, &root); err != nil {
  506. return nil, errors.Wrapf(err, "error reading %s", u)
  507. }
  508. // verify the sha256
  509. sum := sha256.Sum256(root.RootPEM.Raw)
  510. if sha256Sum != strings.ToLower(hex.EncodeToString(sum[:])) {
  511. return nil, errors.New("root certificate SHA256 fingerprint do not match")
  512. }
  513. return &root, nil
  514. }
  515. // Sign performs the sign request to the CA and returns the api.SignResponse
  516. // struct.
  517. func (c *Client) Sign(req *api.SignRequest) (*api.SignResponse, error) {
  518. var retried bool
  519. body, err := json.Marshal(req)
  520. if err != nil {
  521. return nil, errors.Wrap(err, "error marshaling request")
  522. }
  523. u := c.endpoint.ResolveReference(&url.URL{Path: "/sign"})
  524. retry:
  525. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  526. if err != nil {
  527. return nil, errors.Wrapf(err, "client POST %s failed", u)
  528. }
  529. if resp.StatusCode >= 400 {
  530. if !retried && c.retryOnError(resp) {
  531. retried = true
  532. goto retry
  533. }
  534. return nil, readError(resp.Body)
  535. }
  536. var sign api.SignResponse
  537. if err := readJSON(resp.Body, &sign); err != nil {
  538. return nil, errors.Wrapf(err, "error reading %s", u)
  539. }
  540. // Add tls.ConnectionState:
  541. // We'll extract the root certificate from the verified chains
  542. sign.TLS = resp.TLS
  543. return &sign, nil
  544. }
  545. // Renew performs the renew request to the CA and returns the api.SignResponse
  546. // struct.
  547. func (c *Client) Renew(tr http.RoundTripper) (*api.SignResponse, error) {
  548. var retried bool
  549. u := c.endpoint.ResolveReference(&url.URL{Path: "/renew"})
  550. client := &http.Client{Transport: tr}
  551. retry:
  552. resp, err := client.Post(u.String(), "application/json", http.NoBody)
  553. if err != nil {
  554. return nil, errors.Wrapf(err, "client POST %s failed", u)
  555. }
  556. if resp.StatusCode >= 400 {
  557. if !retried && c.retryOnError(resp) {
  558. retried = true
  559. goto retry
  560. }
  561. return nil, readError(resp.Body)
  562. }
  563. var sign api.SignResponse
  564. if err := readJSON(resp.Body, &sign); err != nil {
  565. return nil, errors.Wrapf(err, "error reading %s", u)
  566. }
  567. return &sign, nil
  568. }
  569. // Revoke performs the revoke request to the CA and returns the api.RevokeResponse
  570. // struct.
  571. func (c *Client) Revoke(req *api.RevokeRequest, tr http.RoundTripper) (*api.RevokeResponse, error) {
  572. var retried bool
  573. body, err := json.Marshal(req)
  574. if err != nil {
  575. return nil, errors.Wrap(err, "error marshaling request")
  576. }
  577. var client *uaClient
  578. retry:
  579. if tr != nil {
  580. client = newClient(tr)
  581. } else {
  582. client = c.client
  583. }
  584. u := c.endpoint.ResolveReference(&url.URL{Path: "/revoke"})
  585. resp, err := client.Post(u.String(), "application/json", bytes.NewReader(body))
  586. if err != nil {
  587. return nil, errors.Wrapf(err, "client POST %s failed", u)
  588. }
  589. if resp.StatusCode >= 400 {
  590. if !retried && c.retryOnError(resp) {
  591. retried = true
  592. goto retry
  593. }
  594. return nil, readError(resp.Body)
  595. }
  596. var revoke api.RevokeResponse
  597. if err := readJSON(resp.Body, &revoke); err != nil {
  598. return nil, errors.Wrapf(err, "error reading %s", u)
  599. }
  600. return &revoke, nil
  601. }
  602. // Provisioners performs the provisioners request to the CA and returns the
  603. // api.ProvisionersResponse struct with a map of provisioners.
  604. //
  605. // ProvisionerOption WithProvisionerCursor and WithProvisionLimit can be used to
  606. // paginate the provisioners.
  607. func (c *Client) Provisioners(opts ...ProvisionerOption) (*api.ProvisionersResponse, error) {
  608. var retried bool
  609. o := new(provisionerOptions)
  610. if err := o.apply(opts); err != nil {
  611. return nil, err
  612. }
  613. u := c.endpoint.ResolveReference(&url.URL{
  614. Path: "/provisioners",
  615. RawQuery: o.rawQuery(),
  616. })
  617. retry:
  618. resp, err := c.client.Get(u.String())
  619. if err != nil {
  620. return nil, errors.Wrapf(err, "client GET %s failed", u)
  621. }
  622. if resp.StatusCode >= 400 {
  623. if !retried && c.retryOnError(resp) {
  624. retried = true
  625. goto retry
  626. }
  627. return nil, readError(resp.Body)
  628. }
  629. var provisioners api.ProvisionersResponse
  630. if err := readJSON(resp.Body, &provisioners); err != nil {
  631. return nil, errors.Wrapf(err, "error reading %s", u)
  632. }
  633. return &provisioners, nil
  634. }
  635. // ProvisionerKey performs the request to the CA to get the encrypted key for
  636. // the given provisioner kid and returns the api.ProvisionerKeyResponse struct
  637. // with the encrypted key.
  638. func (c *Client) ProvisionerKey(kid string) (*api.ProvisionerKeyResponse, error) {
  639. var retried bool
  640. u := c.endpoint.ResolveReference(&url.URL{Path: "/provisioners/" + kid + "/encrypted-key"})
  641. retry:
  642. resp, err := c.client.Get(u.String())
  643. if err != nil {
  644. return nil, errors.Wrapf(err, "client GET %s failed", u)
  645. }
  646. if resp.StatusCode >= 400 {
  647. if !retried && c.retryOnError(resp) {
  648. retried = true
  649. goto retry
  650. }
  651. return nil, readError(resp.Body)
  652. }
  653. var key api.ProvisionerKeyResponse
  654. if err := readJSON(resp.Body, &key); err != nil {
  655. return nil, errors.Wrapf(err, "error reading %s", u)
  656. }
  657. return &key, nil
  658. }
  659. // Roots performs the get roots request to the CA and returns the
  660. // api.RootsResponse struct.
  661. func (c *Client) Roots() (*api.RootsResponse, error) {
  662. var retried bool
  663. u := c.endpoint.ResolveReference(&url.URL{Path: "/roots"})
  664. retry:
  665. resp, err := c.client.Get(u.String())
  666. if err != nil {
  667. return nil, errors.Wrapf(err, "client GET %s failed", u)
  668. }
  669. if resp.StatusCode >= 400 {
  670. if !retried && c.retryOnError(resp) {
  671. retried = true
  672. goto retry
  673. }
  674. return nil, readError(resp.Body)
  675. }
  676. var roots api.RootsResponse
  677. if err := readJSON(resp.Body, &roots); err != nil {
  678. return nil, errors.Wrapf(err, "error reading %s", u)
  679. }
  680. return &roots, nil
  681. }
  682. // Federation performs the get federation request to the CA and returns the
  683. // api.FederationResponse struct.
  684. func (c *Client) Federation() (*api.FederationResponse, error) {
  685. var retried bool
  686. u := c.endpoint.ResolveReference(&url.URL{Path: "/federation"})
  687. retry:
  688. resp, err := c.client.Get(u.String())
  689. if err != nil {
  690. return nil, errors.Wrapf(err, "client GET %s failed", u)
  691. }
  692. if resp.StatusCode >= 400 {
  693. if !retried && c.retryOnError(resp) {
  694. retried = true
  695. goto retry
  696. }
  697. return nil, readError(resp.Body)
  698. }
  699. var federation api.FederationResponse
  700. if err := readJSON(resp.Body, &federation); err != nil {
  701. return nil, errors.Wrapf(err, "error reading %s", u)
  702. }
  703. return &federation, nil
  704. }
  705. // SSHSign performs the POST /ssh/sign request to the CA and returns the
  706. // api.SSHSignResponse struct.
  707. func (c *Client) SSHSign(req *api.SSHSignRequest) (*api.SSHSignResponse, error) {
  708. var retried bool
  709. body, err := json.Marshal(req)
  710. if err != nil {
  711. return nil, errors.Wrap(err, "error marshaling request")
  712. }
  713. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/sign"})
  714. retry:
  715. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  716. if err != nil {
  717. return nil, errors.Wrapf(err, "client POST %s failed", u)
  718. }
  719. if resp.StatusCode >= 400 {
  720. if !retried && c.retryOnError(resp) {
  721. retried = true
  722. goto retry
  723. }
  724. return nil, readError(resp.Body)
  725. }
  726. var sign api.SSHSignResponse
  727. if err := readJSON(resp.Body, &sign); err != nil {
  728. return nil, errors.Wrapf(err, "error reading %s", u)
  729. }
  730. return &sign, nil
  731. }
  732. // SSHRenew performs the POST /ssh/renew request to the CA and returns the
  733. // api.SSHRenewResponse struct.
  734. func (c *Client) SSHRenew(req *api.SSHRenewRequest) (*api.SSHRenewResponse, error) {
  735. var retried bool
  736. body, err := json.Marshal(req)
  737. if err != nil {
  738. return nil, errors.Wrap(err, "error marshaling request")
  739. }
  740. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/renew"})
  741. retry:
  742. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  743. if err != nil {
  744. return nil, errors.Wrapf(err, "client POST %s failed", u)
  745. }
  746. if resp.StatusCode >= 400 {
  747. if !retried && c.retryOnError(resp) {
  748. retried = true
  749. goto retry
  750. }
  751. return nil, readError(resp.Body)
  752. }
  753. var renew api.SSHRenewResponse
  754. if err := readJSON(resp.Body, &renew); err != nil {
  755. return nil, errors.Wrapf(err, "error reading %s", u)
  756. }
  757. return &renew, nil
  758. }
  759. // SSHRekey performs the POST /ssh/rekey request to the CA and returns the
  760. // api.SSHRekeyResponse struct.
  761. func (c *Client) SSHRekey(req *api.SSHRekeyRequest) (*api.SSHRekeyResponse, error) {
  762. var retried bool
  763. body, err := json.Marshal(req)
  764. if err != nil {
  765. return nil, errors.Wrap(err, "error marshaling request")
  766. }
  767. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/rekey"})
  768. retry:
  769. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  770. if err != nil {
  771. return nil, errors.Wrapf(err, "client POST %s failed", u)
  772. }
  773. if resp.StatusCode >= 400 {
  774. if !retried && c.retryOnError(resp) {
  775. retried = true
  776. goto retry
  777. }
  778. return nil, readError(resp.Body)
  779. }
  780. var rekey api.SSHRekeyResponse
  781. if err := readJSON(resp.Body, &rekey); err != nil {
  782. return nil, errors.Wrapf(err, "error reading %s", u)
  783. }
  784. return &rekey, nil
  785. }
  786. // SSHRevoke performs the POST /ssh/revoke request to the CA and returns the
  787. // api.SSHRevokeResponse struct.
  788. func (c *Client) SSHRevoke(req *api.SSHRevokeRequest) (*api.SSHRevokeResponse, error) {
  789. var retried bool
  790. body, err := json.Marshal(req)
  791. if err != nil {
  792. return nil, errors.Wrap(err, "error marshaling request")
  793. }
  794. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/revoke"})
  795. retry:
  796. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  797. if err != nil {
  798. return nil, errors.Wrapf(err, "client POST %s failed", u)
  799. }
  800. if resp.StatusCode >= 400 {
  801. if !retried && c.retryOnError(resp) {
  802. retried = true
  803. goto retry
  804. }
  805. return nil, readError(resp.Body)
  806. }
  807. var revoke api.SSHRevokeResponse
  808. if err := readJSON(resp.Body, &revoke); err != nil {
  809. return nil, errors.Wrapf(err, "error reading %s", u)
  810. }
  811. return &revoke, nil
  812. }
  813. // SSHRoots performs the GET /ssh/roots request to the CA and returns the
  814. // api.SSHRootsResponse struct.
  815. func (c *Client) SSHRoots() (*api.SSHRootsResponse, error) {
  816. var retried bool
  817. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/roots"})
  818. retry:
  819. resp, err := c.client.Get(u.String())
  820. if err != nil {
  821. return nil, errors.Wrapf(err, "client GET %s failed", u)
  822. }
  823. if resp.StatusCode >= 400 {
  824. if !retried && c.retryOnError(resp) {
  825. retried = true
  826. goto retry
  827. }
  828. return nil, readError(resp.Body)
  829. }
  830. var keys api.SSHRootsResponse
  831. if err := readJSON(resp.Body, &keys); err != nil {
  832. return nil, errors.Wrapf(err, "error reading %s", u)
  833. }
  834. return &keys, nil
  835. }
  836. // SSHFederation performs the get /ssh/federation request to the CA and returns
  837. // the api.SSHRootsResponse struct.
  838. func (c *Client) SSHFederation() (*api.SSHRootsResponse, error) {
  839. var retried bool
  840. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/federation"})
  841. retry:
  842. resp, err := c.client.Get(u.String())
  843. if err != nil {
  844. return nil, errors.Wrapf(err, "client GET %s failed", u)
  845. }
  846. if resp.StatusCode >= 400 {
  847. if !retried && c.retryOnError(resp) {
  848. retried = true
  849. goto retry
  850. }
  851. return nil, readError(resp.Body)
  852. }
  853. var keys api.SSHRootsResponse
  854. if err := readJSON(resp.Body, &keys); err != nil {
  855. return nil, errors.Wrapf(err, "error reading %s", u)
  856. }
  857. return &keys, nil
  858. }
  859. // SSHConfig performs the POST /ssh/config request to the CA to get the ssh
  860. // configuration templates.
  861. func (c *Client) SSHConfig(req *api.SSHConfigRequest) (*api.SSHConfigResponse, error) {
  862. var retried bool
  863. body, err := json.Marshal(req)
  864. if err != nil {
  865. return nil, errors.Wrap(err, "error marshaling request")
  866. }
  867. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/config"})
  868. retry:
  869. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  870. if err != nil {
  871. return nil, errors.Wrapf(err, "client POST %s failed", u)
  872. }
  873. if resp.StatusCode >= 400 {
  874. if !retried && c.retryOnError(resp) {
  875. retried = true
  876. goto retry
  877. }
  878. return nil, readError(resp.Body)
  879. }
  880. var config api.SSHConfigResponse
  881. if err := readJSON(resp.Body, &config); err != nil {
  882. return nil, errors.Wrapf(err, "error reading %s", u)
  883. }
  884. return &config, nil
  885. }
  886. // SSHCheckHost performs the POST /ssh/check-host request to the CA with the
  887. // given principal.
  888. func (c *Client) SSHCheckHost(principal string) (*api.SSHCheckPrincipalResponse, error) {
  889. var retried bool
  890. body, err := json.Marshal(&api.SSHCheckPrincipalRequest{
  891. Type: provisioner.SSHHostCert,
  892. Principal: principal,
  893. })
  894. if err != nil {
  895. return nil, errors.Wrap(err, "error marshaling 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, errors.Wrapf(err, "client POST %s failed", u)
  902. }
  903. if resp.StatusCode >= 400 {
  904. if !retried && c.retryOnError(resp) {
  905. retried = true
  906. goto retry
  907. }
  908. return nil, readError(resp.Body)
  909. }
  910. var check api.SSHCheckPrincipalResponse
  911. if err := readJSON(resp.Body, &check); err != nil {
  912. return nil, errors.Wrapf(err, "error reading %s", u)
  913. }
  914. return &check, nil
  915. }
  916. // SSHGetHosts performs the GET /ssh/get-hosts request to the CA.
  917. func (c *Client) SSHGetHosts() (*api.SSHGetHostsResponse, error) {
  918. var retried bool
  919. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/hosts"})
  920. retry:
  921. resp, err := c.client.Get(u.String())
  922. if err != nil {
  923. return nil, errors.Wrapf(err, "client GET %s failed", u)
  924. }
  925. if resp.StatusCode >= 400 {
  926. if !retried && c.retryOnError(resp) {
  927. retried = true
  928. goto retry
  929. }
  930. return nil, readError(resp.Body)
  931. }
  932. var hosts api.SSHGetHostsResponse
  933. if err := readJSON(resp.Body, &hosts); err != nil {
  934. return nil, errors.Wrapf(err, "error reading %s", u)
  935. }
  936. return &hosts, nil
  937. }
  938. // SSHBastion performs the POST /ssh/bastion request to the CA.
  939. func (c *Client) SSHBastion(req *api.SSHBastionRequest) (*api.SSHBastionResponse, error) {
  940. var retried bool
  941. body, err := json.Marshal(req)
  942. if err != nil {
  943. return nil, errors.Wrap(err, "error marshaling request")
  944. }
  945. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/bastion"})
  946. retry:
  947. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  948. if err != nil {
  949. return nil, errors.Wrapf(err, "client POST %s failed", u)
  950. }
  951. if resp.StatusCode >= 400 {
  952. if !retried && c.retryOnError(resp) {
  953. retried = true
  954. goto retry
  955. }
  956. return nil, readError(resp.Body)
  957. }
  958. var bastion api.SSHBastionResponse
  959. if err := readJSON(resp.Body, &bastion); err != nil {
  960. return nil, errors.Wrapf(err, "error reading %s", u)
  961. }
  962. return &bastion, nil
  963. }
  964. // RootFingerprint is a helper method that returns the current root fingerprint.
  965. // It does an health connection and gets the fingerprint from the TLS verified
  966. // chains.
  967. func (c *Client) RootFingerprint() (string, error) {
  968. u := c.endpoint.ResolveReference(&url.URL{Path: "/health"})
  969. resp, err := c.client.Get(u.String())
  970. if err != nil {
  971. return "", errors.Wrapf(err, "client GET %s failed", u)
  972. }
  973. if resp.TLS == nil || len(resp.TLS.VerifiedChains) == 0 {
  974. return "", errors.New("missing verified chains")
  975. }
  976. lastChain := resp.TLS.VerifiedChains[len(resp.TLS.VerifiedChains)-1]
  977. if len(lastChain) == 0 {
  978. return "", errors.New("missing verified chains")
  979. }
  980. return x509util.Fingerprint(lastChain[len(lastChain)-1]), nil
  981. }
  982. // CreateSignRequest is a helper function that given an x509 OTT returns a
  983. // simple but secure sign request as well as the private key used.
  984. func CreateSignRequest(ott string) (*api.SignRequest, crypto.PrivateKey, error) {
  985. token, err := jwt.ParseSigned(ott)
  986. if err != nil {
  987. return nil, nil, errors.Wrap(err, "error parsing ott")
  988. }
  989. var claims authority.Claims
  990. if err := token.UnsafeClaimsWithoutVerification(&claims); err != nil {
  991. return nil, nil, errors.Wrap(err, "error parsing ott")
  992. }
  993. pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  994. if err != nil {
  995. return nil, nil, errors.Wrap(err, "error generating key")
  996. }
  997. dnsNames, ips, emails := x509util.SplitSANs(claims.SANs)
  998. if claims.Email != "" {
  999. emails = append(emails, claims.Email)
  1000. }
  1001. template := &x509.CertificateRequest{
  1002. Subject: pkix.Name{
  1003. CommonName: claims.Subject,
  1004. },
  1005. SignatureAlgorithm: x509.ECDSAWithSHA256,
  1006. DNSNames: dnsNames,
  1007. IPAddresses: ips,
  1008. EmailAddresses: emails,
  1009. }
  1010. csr, err := x509.CreateCertificateRequest(rand.Reader, template, pk)
  1011. if err != nil {
  1012. return nil, nil, errors.Wrap(err, "error creating certificate request")
  1013. }
  1014. cr, err := x509.ParseCertificateRequest(csr)
  1015. if err != nil {
  1016. return nil, nil, errors.Wrap(err, "error parsing certificate request")
  1017. }
  1018. if err := cr.CheckSignature(); err != nil {
  1019. return nil, nil, errors.Wrap(err, "error signing certificate request")
  1020. }
  1021. return &api.SignRequest{
  1022. CsrPEM: api.CertificateRequest{CertificateRequest: cr},
  1023. OTT: ott,
  1024. }, pk, nil
  1025. }
  1026. // CreateCertificateRequest creates a new CSR with the given common name and
  1027. // SANs. If no san is provided the commonName will set also a SAN.
  1028. func CreateCertificateRequest(commonName string, sans ...string) (*api.CertificateRequest, crypto.PrivateKey, error) {
  1029. key, err := keys.GenerateDefaultKey()
  1030. if err != nil {
  1031. return nil, nil, err
  1032. }
  1033. return createCertificateRequest(commonName, sans, key)
  1034. }
  1035. func createCertificateRequest(commonName string, sans []string, key crypto.PrivateKey) (*api.CertificateRequest, crypto.PrivateKey, error) {
  1036. if len(sans) == 0 {
  1037. sans = []string{commonName}
  1038. }
  1039. dnsNames, ips, emails := x509util.SplitSANs(sans)
  1040. template := &x509.CertificateRequest{
  1041. Subject: pkix.Name{
  1042. CommonName: commonName,
  1043. },
  1044. DNSNames: dnsNames,
  1045. IPAddresses: ips,
  1046. EmailAddresses: emails,
  1047. }
  1048. csr, err := x509.CreateCertificateRequest(rand.Reader, template, key)
  1049. if err != nil {
  1050. return nil, nil, err
  1051. }
  1052. cr, err := x509.ParseCertificateRequest(csr)
  1053. if err != nil {
  1054. return nil, nil, err
  1055. }
  1056. if err := cr.CheckSignature(); err != nil {
  1057. return nil, nil, err
  1058. }
  1059. return &api.CertificateRequest{CertificateRequest: cr}, key, nil
  1060. }
  1061. // getRootCAPath returns the path where the root CA is stored based on the
  1062. // STEPPATH environment variable.
  1063. func getRootCAPath() string {
  1064. return filepath.Join(config.StepPath(), "certs", "root_ca.crt")
  1065. }
  1066. func readJSON(r io.ReadCloser, v interface{}) error {
  1067. defer r.Close()
  1068. return json.NewDecoder(r).Decode(v)
  1069. }
  1070. func readError(r io.ReadCloser) error {
  1071. defer r.Close()
  1072. apiErr := new(api.Error)
  1073. if err := json.NewDecoder(r).Decode(apiErr); err != nil {
  1074. return err
  1075. }
  1076. return apiErr
  1077. }