client.go 29 KB

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