client.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. "strings"
  21. "github.com/pkg/errors"
  22. "github.com/smallstep/ca-component/api"
  23. "golang.org/x/net/http2"
  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. block, _ := pem.Decode(data)
  109. if block == nil {
  110. return nil, errors.Errorf("error decoding %s", filename)
  111. }
  112. root, err := x509.ParseCertificate(block.Bytes)
  113. if err != nil {
  114. return nil, errors.Wrapf(err, "error parsing %s", filename)
  115. }
  116. pool := x509.NewCertPool()
  117. pool.AddCert(root)
  118. return getDefaultTransport(&tls.Config{
  119. MinVersion: tls.VersionTLS12,
  120. PreferServerCipherSuites: true,
  121. RootCAs: pool,
  122. })
  123. }
  124. func getTransportFromSHA256(endpoint, sum string) (http.RoundTripper, error) {
  125. u, err := parseEndpoint(endpoint)
  126. if err != nil {
  127. return nil, err
  128. }
  129. client := &Client{endpoint: u}
  130. root, err := client.Root(sum)
  131. if err != nil {
  132. return nil, err
  133. }
  134. pool := x509.NewCertPool()
  135. pool.AddCert(root.RootPEM.Certificate)
  136. return getDefaultTransport(&tls.Config{
  137. MinVersion: tls.VersionTLS12,
  138. PreferServerCipherSuites: true,
  139. RootCAs: pool,
  140. })
  141. }
  142. // parseEndpoint parses and validates the given endpoint
  143. func parseEndpoint(endpoint string) (*url.URL, error) {
  144. u, err := url.Parse(endpoint)
  145. if err != nil {
  146. return nil, errors.Wrapf(err, "error parsing endpoint '%s'", endpoint)
  147. }
  148. if u.Scheme == "" || u.Host == "" {
  149. return nil, errors.Errorf("error parsing endpoint: url '%s' is not valid", endpoint)
  150. }
  151. return u, nil
  152. }
  153. // Client implements an HTTP client for the CA server.
  154. type Client struct {
  155. client *http.Client
  156. endpoint *url.URL
  157. certPool *x509.CertPool
  158. }
  159. // NewClient creates a new Client with the given endpoint and options.
  160. func NewClient(endpoint string, opts ...ClientOption) (*Client, error) {
  161. u, err := parseEndpoint(endpoint)
  162. if err != nil {
  163. return nil, err
  164. }
  165. // Retrieve transport from options.
  166. o := new(clientOptions)
  167. if err := o.apply(opts); err != nil {
  168. return nil, err
  169. }
  170. tr, err := o.getTransport(endpoint)
  171. if err != nil {
  172. return nil, err
  173. }
  174. var cp *x509.CertPool
  175. switch tr := tr.(type) {
  176. case *http.Transport:
  177. if tr.TLSClientConfig != nil && tr.TLSClientConfig.RootCAs != nil {
  178. cp = tr.TLSClientConfig.RootCAs
  179. }
  180. case *http2.Transport:
  181. if tr.TLSClientConfig != nil && tr.TLSClientConfig.RootCAs != nil {
  182. cp = tr.TLSClientConfig.RootCAs
  183. }
  184. }
  185. return &Client{
  186. client: &http.Client{
  187. Transport: tr,
  188. },
  189. endpoint: u,
  190. certPool: cp,
  191. }, nil
  192. }
  193. // Health performs the health request to the CA and returns the
  194. // api.HealthResponse struct.
  195. func (c *Client) Health() (*api.HealthResponse, error) {
  196. u := c.endpoint.ResolveReference(&url.URL{Path: "/health"})
  197. resp, err := c.client.Get(u.String())
  198. if err != nil {
  199. return nil, errors.Wrapf(err, "client GET %s failed", u)
  200. }
  201. if resp.StatusCode >= 400 {
  202. return nil, readError(resp.Body)
  203. }
  204. var health api.HealthResponse
  205. if err := readJSON(resp.Body, &health); err != nil {
  206. return nil, errors.Wrapf(err, "error reading %s", u)
  207. }
  208. return &health, nil
  209. }
  210. // Root performs the root request to the CA with the given SHA256 and returns
  211. // the api.RootResponse struct. It uses an insecure client, but it checks the
  212. // resulting root certificate with the given SHA256, returning an error if they
  213. // do not match.
  214. func (c *Client) Root(sha256Sum string) (*api.RootResponse, error) {
  215. sha256Sum = strings.ToLower(strings.Replace(sha256Sum, "-", "", -1))
  216. u := c.endpoint.ResolveReference(&url.URL{Path: "/root/" + sha256Sum})
  217. resp, err := getInsecureClient().Get(u.String())
  218. if err != nil {
  219. return nil, errors.Wrapf(err, "client GET %s failed", u)
  220. }
  221. if resp.StatusCode >= 400 {
  222. return nil, readError(resp.Body)
  223. }
  224. var root api.RootResponse
  225. if err := readJSON(resp.Body, &root); err != nil {
  226. return nil, errors.Wrapf(err, "error reading %s", u)
  227. }
  228. // verify the sha256
  229. sum := sha256.Sum256(root.RootPEM.Raw)
  230. if sha256Sum != strings.ToLower(hex.EncodeToString(sum[:])) {
  231. return nil, errors.New("root certificate SHA256 fingerprint do not match")
  232. }
  233. return &root, nil
  234. }
  235. // Sign performs the sign request to the CA and returns the api.SignResponse
  236. // struct.
  237. func (c *Client) Sign(req *api.SignRequest) (*api.SignResponse, error) {
  238. body, err := json.Marshal(req)
  239. if err != nil {
  240. return nil, errors.Wrap(err, "error marshaling request")
  241. }
  242. u := c.endpoint.ResolveReference(&url.URL{Path: "/sign"})
  243. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  244. if err != nil {
  245. return nil, errors.Wrapf(err, "client POST %s failed", u)
  246. }
  247. if resp.StatusCode >= 400 {
  248. return nil, readError(resp.Body)
  249. }
  250. var sign api.SignResponse
  251. if err := readJSON(resp.Body, &sign); err != nil {
  252. return nil, errors.Wrapf(err, "error reading %s", u)
  253. }
  254. // Add tls.ConnectionState:
  255. // We'll extract the root certificate from the verified chains
  256. sign.TLS = resp.TLS
  257. return &sign, nil
  258. }
  259. // Renew performs the renew request to the CA and returns the api.SignResponse
  260. // struct.
  261. func (c *Client) Renew(tr http.RoundTripper) (*api.SignResponse, error) {
  262. u := c.endpoint.ResolveReference(&url.URL{Path: "/renew"})
  263. client := &http.Client{Transport: tr}
  264. resp, err := client.Post(u.String(), "application/json", http.NoBody)
  265. if err != nil {
  266. return nil, errors.Wrapf(err, "client POST %s failed", u)
  267. }
  268. if resp.StatusCode >= 400 {
  269. return nil, readError(resp.Body)
  270. }
  271. var sign api.SignResponse
  272. if err := readJSON(resp.Body, &sign); err != nil {
  273. return nil, errors.Wrapf(err, "error reading %s", u)
  274. }
  275. return &sign, nil
  276. }
  277. // Provisioners performs the provisioners request to the CA and returns the
  278. // api.ProvisionersResponse struct with a map of provisioners.
  279. func (c *Client) Provisioners() (*api.ProvisionersResponse, error) {
  280. u := c.endpoint.ResolveReference(&url.URL{Path: "/provisioners"})
  281. resp, err := c.client.Get(u.String())
  282. if err != nil {
  283. return nil, errors.Wrapf(err, "client GET %s failed", u)
  284. }
  285. if resp.StatusCode >= 400 {
  286. return nil, readError(resp.Body)
  287. }
  288. var provisioners api.ProvisionersResponse
  289. if err := readJSON(resp.Body, &provisioners); err != nil {
  290. return nil, errors.Wrapf(err, "error reading %s", u)
  291. }
  292. return &provisioners, nil
  293. }
  294. // ProvisionerKey performs the request to the CA to get the encrypted key for
  295. // the given provisioner kid and returns the api.ProvisionerKeyResponse struct
  296. // with the encrypted key.
  297. func (c *Client) ProvisionerKey(kid string) (*api.ProvisionerKeyResponse, error) {
  298. u := c.endpoint.ResolveReference(&url.URL{Path: "/provisioners/" + kid + "/encrypted-key"})
  299. resp, err := c.client.Get(u.String())
  300. if err != nil {
  301. return nil, errors.Wrapf(err, "client GET %s failed", u)
  302. }
  303. if resp.StatusCode >= 400 {
  304. return nil, readError(resp.Body)
  305. }
  306. var key api.ProvisionerKeyResponse
  307. if err := readJSON(resp.Body, &key); err != nil {
  308. return nil, errors.Wrapf(err, "error reading %s", u)
  309. }
  310. return &key, nil
  311. }
  312. // CreateSignRequest is a helper function that given an x509 OTT returns a
  313. // simple but secure sign request as well as the private key used.
  314. func CreateSignRequest(ott string) (*api.SignRequest, crypto.PrivateKey, error) {
  315. token, err := jwt.ParseSigned(ott)
  316. if err != nil {
  317. return nil, nil, errors.Wrap(err, "error parsing ott")
  318. }
  319. var claims jwt.Claims
  320. if err := token.UnsafeClaimsWithoutVerification(&claims); err != nil {
  321. return nil, nil, errors.Wrap(err, "error parsing ott")
  322. }
  323. pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  324. if err != nil {
  325. return nil, nil, errors.Wrap(err, "error generating key")
  326. }
  327. template := &x509.CertificateRequest{
  328. Subject: pkix.Name{
  329. CommonName: claims.Subject,
  330. },
  331. SignatureAlgorithm: x509.ECDSAWithSHA256,
  332. }
  333. if ip := net.ParseIP(claims.Subject); ip != nil {
  334. template.IPAddresses = append(template.IPAddresses, ip)
  335. } else {
  336. template.DNSNames = append(template.DNSNames, claims.Subject)
  337. }
  338. csr, err := x509.CreateCertificateRequest(rand.Reader, template, pk)
  339. if err != nil {
  340. return nil, nil, errors.Wrap(err, "error creating certificate request")
  341. }
  342. cr, err := x509.ParseCertificateRequest(csr)
  343. if err != nil {
  344. return nil, nil, errors.Wrap(err, "error parsing certificate request")
  345. }
  346. if err := cr.CheckSignature(); err != nil {
  347. return nil, nil, errors.Wrap(err, "error signing certificate request")
  348. }
  349. return &api.SignRequest{
  350. CsrPEM: api.CertificateRequest{CertificateRequest: cr},
  351. OTT: ott,
  352. }, pk, nil
  353. }
  354. func getInsecureClient() *http.Client {
  355. return &http.Client{
  356. Transport: &http.Transport{
  357. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  358. },
  359. }
  360. }
  361. func readJSON(r io.ReadCloser, v interface{}) error {
  362. defer r.Close()
  363. return json.NewDecoder(r).Decode(v)
  364. }
  365. func readError(r io.ReadCloser) error {
  366. defer r.Close()
  367. apiErr := new(api.Error)
  368. if err := json.NewDecoder(r).Decode(apiErr); err != nil {
  369. return err
  370. }
  371. return apiErr
  372. }