client.go 14 KB

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