client.go 30 KB

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