client.go 29 KB

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