client.go 13 KB

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