client.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  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/cli/config"
  26. "github.com/smallstep/cli/crypto/x509util"
  27. "gopkg.in/square/go-jose.v2/jwt"
  28. )
  29. // ClientOption is the type of options passed to the Client constructor.
  30. type ClientOption func(o *clientOptions) error
  31. type clientOptions struct {
  32. transport http.RoundTripper
  33. rootSHA256 string
  34. rootFilename string
  35. rootBundle []byte
  36. }
  37. func (o *clientOptions) apply(opts []ClientOption) (err error) {
  38. for _, fn := range opts {
  39. if err = fn(o); err != nil {
  40. return
  41. }
  42. }
  43. return
  44. }
  45. // checkTransport checks if other ways to set up a transport have been provided.
  46. // If they have it returns an error.
  47. func (o *clientOptions) checkTransport() error {
  48. if o.transport != nil || o.rootFilename != "" || o.rootSHA256 != "" || o.rootBundle != nil {
  49. return errors.New("multiple transport methods have been configured")
  50. }
  51. return nil
  52. }
  53. // getTransport returns the transport configured in the clientOptions.
  54. func (o *clientOptions) getTransport(endpoint string) (tr http.RoundTripper, err error) {
  55. if o.transport != nil {
  56. tr = o.transport
  57. }
  58. if o.rootFilename != "" {
  59. if tr, err = getTransportFromFile(o.rootFilename); err != nil {
  60. return nil, err
  61. }
  62. }
  63. if o.rootSHA256 != "" {
  64. if tr, err = getTransportFromSHA256(endpoint, o.rootSHA256); err != nil {
  65. return nil, err
  66. }
  67. }
  68. if o.rootBundle != nil {
  69. if tr, err = getTransportFromCABundle(o.rootBundle); err != nil {
  70. return nil, err
  71. }
  72. }
  73. // As the last option attempt to load the default root ca
  74. if tr == nil {
  75. rootFile := getRootCAPath()
  76. if _, err := os.Stat(rootFile); err == nil {
  77. if tr, err = getTransportFromFile(rootFile); err != nil {
  78. return nil, err
  79. }
  80. return tr, nil
  81. }
  82. return nil, errors.New("a transport, a root cert, or a root sha256 must be used")
  83. }
  84. return tr, nil
  85. }
  86. // WithTransport adds a custom transport to the Client. It will fail if a
  87. // previous option to create the transport has been configured.
  88. func WithTransport(tr http.RoundTripper) ClientOption {
  89. return func(o *clientOptions) error {
  90. if err := o.checkTransport(); err != nil {
  91. return err
  92. }
  93. o.transport = tr
  94. return nil
  95. }
  96. }
  97. // WithRootFile will create the transport using the given root certificate. It
  98. // will fail if a previous option to create the transport has been configured.
  99. func WithRootFile(filename string) ClientOption {
  100. return func(o *clientOptions) error {
  101. if err := o.checkTransport(); err != nil {
  102. return err
  103. }
  104. o.rootFilename = filename
  105. return nil
  106. }
  107. }
  108. // WithRootSHA256 will create the transport using an insecure client to retrieve
  109. // the root certificate using its fingerprint. It will fail if a previous option
  110. // to create the transport has been configured.
  111. func WithRootSHA256(sum string) ClientOption {
  112. return func(o *clientOptions) error {
  113. if err := o.checkTransport(); err != nil {
  114. return err
  115. }
  116. o.rootSHA256 = sum
  117. return nil
  118. }
  119. }
  120. // WithCABundle will create the transport using the given root certificates. It
  121. // will fail if a previous option to create the transport has been configured.
  122. func WithCABundle(bundle []byte) ClientOption {
  123. return func(o *clientOptions) error {
  124. if err := o.checkTransport(); err != nil {
  125. return err
  126. }
  127. o.rootBundle = bundle
  128. return nil
  129. }
  130. }
  131. func getTransportFromFile(filename string) (http.RoundTripper, error) {
  132. data, err := ioutil.ReadFile(filename)
  133. if err != nil {
  134. return nil, errors.Wrapf(err, "error reading %s", filename)
  135. }
  136. pool := x509.NewCertPool()
  137. if !pool.AppendCertsFromPEM(data) {
  138. return nil, errors.Errorf("error parsing %s: no certificates found", filename)
  139. }
  140. return getDefaultTransport(&tls.Config{
  141. MinVersion: tls.VersionTLS12,
  142. PreferServerCipherSuites: true,
  143. RootCAs: pool,
  144. })
  145. }
  146. func getTransportFromSHA256(endpoint, sum string) (http.RoundTripper, error) {
  147. u, err := parseEndpoint(endpoint)
  148. if err != nil {
  149. return nil, err
  150. }
  151. client := &Client{endpoint: u}
  152. root, err := client.Root(sum)
  153. if err != nil {
  154. return nil, err
  155. }
  156. pool := x509.NewCertPool()
  157. pool.AddCert(root.RootPEM.Certificate)
  158. return getDefaultTransport(&tls.Config{
  159. MinVersion: tls.VersionTLS12,
  160. PreferServerCipherSuites: true,
  161. RootCAs: pool,
  162. })
  163. }
  164. func getTransportFromCABundle(bundle []byte) (http.RoundTripper, error) {
  165. pool := x509.NewCertPool()
  166. if !pool.AppendCertsFromPEM(bundle) {
  167. return nil, errors.New("error parsing ca bundle: no certificates found")
  168. }
  169. return getDefaultTransport(&tls.Config{
  170. MinVersion: tls.VersionTLS12,
  171. PreferServerCipherSuites: true,
  172. RootCAs: pool,
  173. })
  174. }
  175. // parseEndpoint parses and validates the given endpoint. It supports general
  176. // URLs like https://ca.smallstep.com[:port][/path], and incomplete URLs like
  177. // ca.smallstep.com[:port][/path].
  178. func parseEndpoint(endpoint string) (*url.URL, error) {
  179. u, err := url.Parse(endpoint)
  180. if err != nil {
  181. return nil, errors.Wrapf(err, "error parsing endpoint '%s'", endpoint)
  182. }
  183. // URLs are generally parsed as:
  184. // [scheme:][//[userinfo@]host][/]path[?query][#fragment]
  185. // But URLs that do not start with a slash after the scheme are interpreted as
  186. // scheme:opaque[?query][#fragment]
  187. if u.Opaque == "" {
  188. if u.Scheme == "" {
  189. u.Scheme = "https"
  190. }
  191. if u.Host == "" {
  192. // endpoint looks like ca.smallstep.com or ca.smallstep.com/1.0/sign
  193. if u.Path != "" {
  194. parts := strings.SplitN(u.Path, "/", 2)
  195. u.Host = parts[0]
  196. if len(parts) == 2 {
  197. u.Path = parts[1]
  198. } else {
  199. u.Path = ""
  200. }
  201. return parseEndpoint(u.String())
  202. }
  203. return nil, errors.Errorf("error parsing endpoint: url '%s' is not valid", endpoint)
  204. }
  205. return u, nil
  206. }
  207. // scheme:opaque[?query][#fragment]
  208. // endpoint looks like ca.smallstep.com:443 or ca.smallstep.com:443/1.0/sign
  209. return parseEndpoint("https://" + endpoint)
  210. }
  211. // ProvisionerOption is the type of options passed to the Provisioner method.
  212. type ProvisionerOption func(o *provisionerOptions) error
  213. type provisionerOptions struct {
  214. cursor string
  215. limit int
  216. }
  217. func (o *provisionerOptions) apply(opts []ProvisionerOption) (err error) {
  218. for _, fn := range opts {
  219. if err = fn(o); err != nil {
  220. return
  221. }
  222. }
  223. return
  224. }
  225. func (o *provisionerOptions) rawQuery() string {
  226. v := url.Values{}
  227. if len(o.cursor) > 0 {
  228. v.Set("cursor", o.cursor)
  229. }
  230. if o.limit > 0 {
  231. v.Set("limit", strconv.Itoa(o.limit))
  232. }
  233. return v.Encode()
  234. }
  235. // WithProvisionerCursor will request the provisioners starting with the given cursor.
  236. func WithProvisionerCursor(cursor string) ProvisionerOption {
  237. return func(o *provisionerOptions) error {
  238. o.cursor = cursor
  239. return nil
  240. }
  241. }
  242. // WithProvisionerLimit will request the given number of provisioners.
  243. func WithProvisionerLimit(limit int) ProvisionerOption {
  244. return func(o *provisionerOptions) error {
  245. o.limit = limit
  246. return nil
  247. }
  248. }
  249. // Client implements an HTTP client for the CA server.
  250. type Client struct {
  251. client *http.Client
  252. endpoint *url.URL
  253. }
  254. // NewClient creates a new Client with the given endpoint and options.
  255. func NewClient(endpoint string, opts ...ClientOption) (*Client, error) {
  256. u, err := parseEndpoint(endpoint)
  257. if err != nil {
  258. return nil, err
  259. }
  260. // Retrieve transport from options.
  261. o := new(clientOptions)
  262. if err := o.apply(opts); err != nil {
  263. return nil, err
  264. }
  265. tr, err := o.getTransport(endpoint)
  266. if err != nil {
  267. return nil, err
  268. }
  269. return &Client{
  270. client: &http.Client{
  271. Transport: tr,
  272. },
  273. endpoint: u,
  274. }, nil
  275. }
  276. // SetTransport updates the transport of the internal HTTP client.
  277. func (c *Client) SetTransport(tr http.RoundTripper) {
  278. c.client.Transport = tr
  279. }
  280. // Health performs the health request to the CA and returns the
  281. // api.HealthResponse struct.
  282. func (c *Client) Health() (*api.HealthResponse, error) {
  283. u := c.endpoint.ResolveReference(&url.URL{Path: "/health"})
  284. resp, err := c.client.Get(u.String())
  285. if err != nil {
  286. return nil, errors.Wrapf(err, "client GET %s failed", u)
  287. }
  288. if resp.StatusCode >= 400 {
  289. return nil, readError(resp.Body)
  290. }
  291. var health api.HealthResponse
  292. if err := readJSON(resp.Body, &health); err != nil {
  293. return nil, errors.Wrapf(err, "error reading %s", u)
  294. }
  295. return &health, nil
  296. }
  297. // Root performs the root request to the CA with the given SHA256 and returns
  298. // the api.RootResponse struct. It uses an insecure client, but it checks the
  299. // resulting root certificate with the given SHA256, returning an error if they
  300. // do not match.
  301. func (c *Client) Root(sha256Sum string) (*api.RootResponse, error) {
  302. sha256Sum = strings.ToLower(strings.Replace(sha256Sum, "-", "", -1))
  303. u := c.endpoint.ResolveReference(&url.URL{Path: "/root/" + sha256Sum})
  304. resp, err := getInsecureClient().Get(u.String())
  305. if err != nil {
  306. return nil, errors.Wrapf(err, "client GET %s failed", u)
  307. }
  308. if resp.StatusCode >= 400 {
  309. return nil, readError(resp.Body)
  310. }
  311. var root api.RootResponse
  312. if err := readJSON(resp.Body, &root); err != nil {
  313. return nil, errors.Wrapf(err, "error reading %s", u)
  314. }
  315. // verify the sha256
  316. sum := sha256.Sum256(root.RootPEM.Raw)
  317. if sha256Sum != strings.ToLower(hex.EncodeToString(sum[:])) {
  318. return nil, errors.New("root certificate SHA256 fingerprint do not match")
  319. }
  320. return &root, nil
  321. }
  322. // Sign performs the sign request to the CA and returns the api.SignResponse
  323. // struct.
  324. func (c *Client) Sign(req *api.SignRequest) (*api.SignResponse, error) {
  325. body, err := json.Marshal(req)
  326. if err != nil {
  327. return nil, errors.Wrap(err, "error marshaling request")
  328. }
  329. u := c.endpoint.ResolveReference(&url.URL{Path: "/sign"})
  330. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  331. if err != nil {
  332. return nil, errors.Wrapf(err, "client POST %s failed", u)
  333. }
  334. if resp.StatusCode >= 400 {
  335. return nil, readError(resp.Body)
  336. }
  337. var sign api.SignResponse
  338. if err := readJSON(resp.Body, &sign); err != nil {
  339. return nil, errors.Wrapf(err, "error reading %s", u)
  340. }
  341. // Add tls.ConnectionState:
  342. // We'll extract the root certificate from the verified chains
  343. sign.TLS = resp.TLS
  344. return &sign, nil
  345. }
  346. // SignSSH performs the SSH certificate sign request to the CA and returns the
  347. // api.SignSSHResponse struct.
  348. func (c *Client) SignSSH(req *api.SignSSHRequest) (*api.SignSSHResponse, error) {
  349. body, err := json.Marshal(req)
  350. if err != nil {
  351. return nil, errors.Wrap(err, "error marshaling request")
  352. }
  353. u := c.endpoint.ResolveReference(&url.URL{Path: "/sign-ssh"})
  354. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  355. if err != nil {
  356. return nil, errors.Wrapf(err, "client POST %s failed", u)
  357. }
  358. if resp.StatusCode >= 400 {
  359. return nil, readError(resp.Body)
  360. }
  361. var sign api.SignSSHResponse
  362. if err := readJSON(resp.Body, &sign); err != nil {
  363. return nil, errors.Wrapf(err, "error reading %s", u)
  364. }
  365. return &sign, nil
  366. }
  367. // Renew performs the renew request to the CA and returns the api.SignResponse
  368. // struct.
  369. func (c *Client) Renew(tr http.RoundTripper) (*api.SignResponse, error) {
  370. u := c.endpoint.ResolveReference(&url.URL{Path: "/renew"})
  371. client := &http.Client{Transport: tr}
  372. resp, err := client.Post(u.String(), "application/json", http.NoBody)
  373. if err != nil {
  374. return nil, errors.Wrapf(err, "client POST %s failed", u)
  375. }
  376. if resp.StatusCode >= 400 {
  377. return nil, readError(resp.Body)
  378. }
  379. var sign api.SignResponse
  380. if err := readJSON(resp.Body, &sign); err != nil {
  381. return nil, errors.Wrapf(err, "error reading %s", u)
  382. }
  383. return &sign, nil
  384. }
  385. // Revoke performs the revoke request to the CA and returns the api.RevokeResponse
  386. // struct.
  387. func (c *Client) Revoke(req *api.RevokeRequest, tr http.RoundTripper) (*api.RevokeResponse, error) {
  388. body, err := json.Marshal(req)
  389. if err != nil {
  390. return nil, errors.Wrap(err, "error marshaling request")
  391. }
  392. var client *http.Client
  393. if tr != nil {
  394. client = &http.Client{Transport: tr}
  395. } else {
  396. client = c.client
  397. }
  398. u := c.endpoint.ResolveReference(&url.URL{Path: "/revoke"})
  399. resp, err := client.Post(u.String(), "application/json", bytes.NewReader(body))
  400. if err != nil {
  401. return nil, errors.Wrapf(err, "client POST %s failed", u)
  402. }
  403. if resp.StatusCode >= 400 {
  404. return nil, readError(resp.Body)
  405. }
  406. var revoke api.RevokeResponse
  407. if err := readJSON(resp.Body, &revoke); err != nil {
  408. return nil, errors.Wrapf(err, "error reading %s", u)
  409. }
  410. return &revoke, nil
  411. }
  412. // Provisioners performs the provisioners request to the CA and returns the
  413. // api.ProvisionersResponse struct with a map of provisioners.
  414. //
  415. // ProvisionerOption WithProvisionerCursor and WithProvisionLimit can be used to
  416. // paginate the provisioners.
  417. func (c *Client) Provisioners(opts ...ProvisionerOption) (*api.ProvisionersResponse, error) {
  418. o := new(provisionerOptions)
  419. if err := o.apply(opts); err != nil {
  420. return nil, err
  421. }
  422. u := c.endpoint.ResolveReference(&url.URL{
  423. Path: "/provisioners",
  424. RawQuery: o.rawQuery(),
  425. })
  426. resp, err := c.client.Get(u.String())
  427. if err != nil {
  428. return nil, errors.Wrapf(err, "client GET %s failed", u)
  429. }
  430. if resp.StatusCode >= 400 {
  431. return nil, readError(resp.Body)
  432. }
  433. var provisioners api.ProvisionersResponse
  434. if err := readJSON(resp.Body, &provisioners); err != nil {
  435. return nil, errors.Wrapf(err, "error reading %s", u)
  436. }
  437. return &provisioners, nil
  438. }
  439. // ProvisionerKey performs the request to the CA to get the encrypted key for
  440. // the given provisioner kid and returns the api.ProvisionerKeyResponse struct
  441. // with the encrypted key.
  442. func (c *Client) ProvisionerKey(kid string) (*api.ProvisionerKeyResponse, error) {
  443. u := c.endpoint.ResolveReference(&url.URL{Path: "/provisioners/" + kid + "/encrypted-key"})
  444. resp, err := c.client.Get(u.String())
  445. if err != nil {
  446. return nil, errors.Wrapf(err, "client GET %s failed", u)
  447. }
  448. if resp.StatusCode >= 400 {
  449. return nil, readError(resp.Body)
  450. }
  451. var key api.ProvisionerKeyResponse
  452. if err := readJSON(resp.Body, &key); err != nil {
  453. return nil, errors.Wrapf(err, "error reading %s", u)
  454. }
  455. return &key, nil
  456. }
  457. // Roots performs the get roots request to the CA and returns the
  458. // api.RootsResponse struct.
  459. func (c *Client) Roots() (*api.RootsResponse, error) {
  460. u := c.endpoint.ResolveReference(&url.URL{Path: "/roots"})
  461. resp, err := c.client.Get(u.String())
  462. if err != nil {
  463. return nil, errors.Wrapf(err, "client GET %s failed", u)
  464. }
  465. if resp.StatusCode >= 400 {
  466. return nil, readError(resp.Body)
  467. }
  468. var roots api.RootsResponse
  469. if err := readJSON(resp.Body, &roots); err != nil {
  470. return nil, errors.Wrapf(err, "error reading %s", u)
  471. }
  472. return &roots, nil
  473. }
  474. // Federation performs the get federation request to the CA and returns the
  475. // api.FederationResponse struct.
  476. func (c *Client) Federation() (*api.FederationResponse, error) {
  477. u := c.endpoint.ResolveReference(&url.URL{Path: "/federation"})
  478. resp, err := c.client.Get(u.String())
  479. if err != nil {
  480. return nil, errors.Wrapf(err, "client GET %s failed", u)
  481. }
  482. if resp.StatusCode >= 400 {
  483. return nil, readError(resp.Body)
  484. }
  485. var federation api.FederationResponse
  486. if err := readJSON(resp.Body, &federation); err != nil {
  487. return nil, errors.Wrapf(err, "error reading %s", u)
  488. }
  489. return &federation, nil
  490. }
  491. // RootFingerprint is a helper method that returns the current root fingerprint.
  492. // It does an health connection and gets the fingerprint from the TLS verified
  493. // chains.
  494. func (c *Client) RootFingerprint() (string, error) {
  495. u := c.endpoint.ResolveReference(&url.URL{Path: "/health"})
  496. resp, err := c.client.Get(u.String())
  497. if err != nil {
  498. return "", errors.Wrapf(err, "client GET %s failed", u)
  499. }
  500. if resp.TLS == nil || len(resp.TLS.VerifiedChains) == 0 {
  501. return "", errors.New("missing verified chains")
  502. }
  503. lastChain := resp.TLS.VerifiedChains[len(resp.TLS.VerifiedChains)-1]
  504. if len(lastChain) == 0 {
  505. return "", errors.New("missing verified chains")
  506. }
  507. return x509util.Fingerprint(lastChain[len(lastChain)-1]), nil
  508. }
  509. // CreateSignRequest is a helper function that given an x509 OTT returns a
  510. // simple but secure sign request as well as the private key used.
  511. func CreateSignRequest(ott string) (*api.SignRequest, crypto.PrivateKey, error) {
  512. token, err := jwt.ParseSigned(ott)
  513. if err != nil {
  514. return nil, nil, errors.Wrap(err, "error parsing ott")
  515. }
  516. var claims authority.Claims
  517. if err := token.UnsafeClaimsWithoutVerification(&claims); err != nil {
  518. return nil, nil, errors.Wrap(err, "error parsing ott")
  519. }
  520. pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  521. if err != nil {
  522. return nil, nil, errors.Wrap(err, "error generating key")
  523. }
  524. dnsNames, ips, emails := x509util.SplitSANs(claims.SANs)
  525. if claims.Email != "" {
  526. emails = append(emails, claims.Email)
  527. }
  528. template := &x509.CertificateRequest{
  529. Subject: pkix.Name{
  530. CommonName: claims.Subject,
  531. },
  532. SignatureAlgorithm: x509.ECDSAWithSHA256,
  533. DNSNames: dnsNames,
  534. IPAddresses: ips,
  535. EmailAddresses: emails,
  536. }
  537. csr, err := x509.CreateCertificateRequest(rand.Reader, template, pk)
  538. if err != nil {
  539. return nil, nil, errors.Wrap(err, "error creating certificate request")
  540. }
  541. cr, err := x509.ParseCertificateRequest(csr)
  542. if err != nil {
  543. return nil, nil, errors.Wrap(err, "error parsing certificate request")
  544. }
  545. if err := cr.CheckSignature(); err != nil {
  546. return nil, nil, errors.Wrap(err, "error signing certificate request")
  547. }
  548. return &api.SignRequest{
  549. CsrPEM: api.CertificateRequest{CertificateRequest: cr},
  550. OTT: ott,
  551. }, pk, nil
  552. }
  553. func getInsecureClient() *http.Client {
  554. return &http.Client{
  555. Transport: &http.Transport{
  556. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  557. },
  558. }
  559. }
  560. // getRootCAPath returns the path where the root CA is stored based on the
  561. // STEPPATH environment variable.
  562. func getRootCAPath() string {
  563. return filepath.Join(config.StepPath(), "certs", "root_ca.crt")
  564. }
  565. func readJSON(r io.ReadCloser, v interface{}) error {
  566. defer r.Close()
  567. return json.NewDecoder(r).Decode(v)
  568. }
  569. func readError(r io.ReadCloser) error {
  570. defer r.Close()
  571. apiErr := new(api.Error)
  572. if err := json.NewDecoder(r).Decode(apiErr); err != nil {
  573. return err
  574. }
  575. return apiErr
  576. }