client.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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/certificates/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. It supports general
  144. // URLs like https://ca.smallstep.com[:port][/path], and incomplete URLs like
  145. // ca.smallstep.com[:port][/path].
  146. func parseEndpoint(endpoint string) (*url.URL, error) {
  147. u, err := url.Parse(endpoint)
  148. if err != nil {
  149. return nil, errors.Wrapf(err, "error parsing endpoint '%s'", endpoint)
  150. }
  151. // URLs are generally parsed as:
  152. // [scheme:][//[userinfo@]host][/]path[?query][#fragment]
  153. // But URLs that do not start with a slash after the scheme are interpreted as
  154. // scheme:opaque[?query][#fragment]
  155. if u.Opaque == "" {
  156. if u.Scheme == "" {
  157. u.Scheme = "https"
  158. }
  159. if u.Host == "" {
  160. // endpoint looks like ca.smallstep.com or ca.smallstep.com/1.0/sign
  161. if u.Path != "" {
  162. parts := strings.SplitN(u.Path, "/", 2)
  163. u.Host = parts[0]
  164. if len(parts) == 2 {
  165. u.Path = parts[1]
  166. } else {
  167. u.Path = ""
  168. }
  169. return parseEndpoint(u.String())
  170. }
  171. return nil, errors.Errorf("error parsing endpoint: url '%s' is not valid", endpoint)
  172. }
  173. return u, nil
  174. }
  175. // scheme:opaque[?query][#fragment]
  176. // endpoint looks like ca.smallstep.com:443 or ca.smallstep.com:443/1.0/sign
  177. return parseEndpoint("https://" + endpoint)
  178. }
  179. // ProvisionerOption is the type of options passed to the Provisioner method.
  180. type ProvisionerOption func(o *provisionerOptions) error
  181. type provisionerOptions struct {
  182. cursor string
  183. limit int
  184. }
  185. func (o *provisionerOptions) apply(opts []ProvisionerOption) (err error) {
  186. for _, fn := range opts {
  187. if err = fn(o); err != nil {
  188. return
  189. }
  190. }
  191. return
  192. }
  193. func (o *provisionerOptions) rawQuery() string {
  194. v := url.Values{}
  195. if len(o.cursor) > 0 {
  196. v.Set("cursor", o.cursor)
  197. }
  198. if o.limit > 0 {
  199. v.Set("limit", strconv.Itoa(o.limit))
  200. }
  201. return v.Encode()
  202. }
  203. // WithProvisionerCursor will request the provisioners starting with the given cursor.
  204. func WithProvisionerCursor(cursor string) ProvisionerOption {
  205. return func(o *provisionerOptions) error {
  206. o.cursor = cursor
  207. return nil
  208. }
  209. }
  210. // WithProvisionerLimit will request the given number of provisioners.
  211. func WithProvisionerLimit(limit int) ProvisionerOption {
  212. return func(o *provisionerOptions) error {
  213. o.limit = limit
  214. return nil
  215. }
  216. }
  217. // Client implements an HTTP client for the CA server.
  218. type Client struct {
  219. client *http.Client
  220. endpoint *url.URL
  221. certPool *x509.CertPool
  222. }
  223. // NewClient creates a new Client with the given endpoint and options.
  224. func NewClient(endpoint string, opts ...ClientOption) (*Client, error) {
  225. u, err := parseEndpoint(endpoint)
  226. if err != nil {
  227. return nil, err
  228. }
  229. // Retrieve transport from options.
  230. o := new(clientOptions)
  231. if err := o.apply(opts); err != nil {
  232. return nil, err
  233. }
  234. tr, err := o.getTransport(endpoint)
  235. if err != nil {
  236. return nil, err
  237. }
  238. var cp *x509.CertPool
  239. switch tr := tr.(type) {
  240. case *http.Transport:
  241. if tr.TLSClientConfig != nil && tr.TLSClientConfig.RootCAs != nil {
  242. cp = tr.TLSClientConfig.RootCAs
  243. }
  244. case *http2.Transport:
  245. if tr.TLSClientConfig != nil && tr.TLSClientConfig.RootCAs != nil {
  246. cp = tr.TLSClientConfig.RootCAs
  247. }
  248. }
  249. return &Client{
  250. client: &http.Client{
  251. Transport: tr,
  252. },
  253. endpoint: u,
  254. certPool: cp,
  255. }, nil
  256. }
  257. // Health performs the health request to the CA and returns the
  258. // api.HealthResponse struct.
  259. func (c *Client) Health() (*api.HealthResponse, error) {
  260. u := c.endpoint.ResolveReference(&url.URL{Path: "/health"})
  261. resp, err := c.client.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 health api.HealthResponse
  269. if err := readJSON(resp.Body, &health); err != nil {
  270. return nil, errors.Wrapf(err, "error reading %s", u)
  271. }
  272. return &health, nil
  273. }
  274. // Root performs the root request to the CA with the given SHA256 and returns
  275. // the api.RootResponse struct. It uses an insecure client, but it checks the
  276. // resulting root certificate with the given SHA256, returning an error if they
  277. // do not match.
  278. func (c *Client) Root(sha256Sum string) (*api.RootResponse, error) {
  279. sha256Sum = strings.ToLower(strings.Replace(sha256Sum, "-", "", -1))
  280. u := c.endpoint.ResolveReference(&url.URL{Path: "/root/" + sha256Sum})
  281. resp, err := getInsecureClient().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 root api.RootResponse
  289. if err := readJSON(resp.Body, &root); err != nil {
  290. return nil, errors.Wrapf(err, "error reading %s", u)
  291. }
  292. // verify the sha256
  293. sum := sha256.Sum256(root.RootPEM.Raw)
  294. if sha256Sum != strings.ToLower(hex.EncodeToString(sum[:])) {
  295. return nil, errors.New("root certificate SHA256 fingerprint do not match")
  296. }
  297. return &root, nil
  298. }
  299. // Sign performs the sign request to the CA and returns the api.SignResponse
  300. // struct.
  301. func (c *Client) Sign(req *api.SignRequest) (*api.SignResponse, error) {
  302. body, err := json.Marshal(req)
  303. if err != nil {
  304. return nil, errors.Wrap(err, "error marshaling request")
  305. }
  306. u := c.endpoint.ResolveReference(&url.URL{Path: "/sign"})
  307. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  308. if err != nil {
  309. return nil, errors.Wrapf(err, "client POST %s failed", u)
  310. }
  311. if resp.StatusCode >= 400 {
  312. return nil, readError(resp.Body)
  313. }
  314. var sign api.SignResponse
  315. if err := readJSON(resp.Body, &sign); err != nil {
  316. return nil, errors.Wrapf(err, "error reading %s", u)
  317. }
  318. // Add tls.ConnectionState:
  319. // We'll extract the root certificate from the verified chains
  320. sign.TLS = resp.TLS
  321. return &sign, nil
  322. }
  323. // Renew performs the renew request to the CA and returns the api.SignResponse
  324. // struct.
  325. func (c *Client) Renew(tr http.RoundTripper) (*api.SignResponse, error) {
  326. u := c.endpoint.ResolveReference(&url.URL{Path: "/renew"})
  327. client := &http.Client{Transport: tr}
  328. resp, err := client.Post(u.String(), "application/json", http.NoBody)
  329. if err != nil {
  330. return nil, errors.Wrapf(err, "client POST %s failed", u)
  331. }
  332. if resp.StatusCode >= 400 {
  333. return nil, readError(resp.Body)
  334. }
  335. var sign api.SignResponse
  336. if err := readJSON(resp.Body, &sign); err != nil {
  337. return nil, errors.Wrapf(err, "error reading %s", u)
  338. }
  339. return &sign, nil
  340. }
  341. // Provisioners performs the provisioners request to the CA and returns the
  342. // api.ProvisionersResponse struct with a map of provisioners.
  343. //
  344. // ProvisionerOption WithProvisionerCursor and WithProvisionLimit can be used to
  345. // paginate the provisioners.
  346. func (c *Client) Provisioners(opts ...ProvisionerOption) (*api.ProvisionersResponse, error) {
  347. o := new(provisionerOptions)
  348. if err := o.apply(opts); err != nil {
  349. return nil, err
  350. }
  351. u := c.endpoint.ResolveReference(&url.URL{
  352. Path: "/provisioners",
  353. RawQuery: o.rawQuery(),
  354. })
  355. resp, err := c.client.Get(u.String())
  356. if err != nil {
  357. return nil, errors.Wrapf(err, "client GET %s failed", u)
  358. }
  359. if resp.StatusCode >= 400 {
  360. return nil, readError(resp.Body)
  361. }
  362. var provisioners api.ProvisionersResponse
  363. if err := readJSON(resp.Body, &provisioners); err != nil {
  364. return nil, errors.Wrapf(err, "error reading %s", u)
  365. }
  366. return &provisioners, nil
  367. }
  368. // ProvisionerKey performs the request to the CA to get the encrypted key for
  369. // the given provisioner kid and returns the api.ProvisionerKeyResponse struct
  370. // with the encrypted key.
  371. func (c *Client) ProvisionerKey(kid string) (*api.ProvisionerKeyResponse, error) {
  372. u := c.endpoint.ResolveReference(&url.URL{Path: "/provisioners/" + kid + "/encrypted-key"})
  373. resp, err := c.client.Get(u.String())
  374. if err != nil {
  375. return nil, errors.Wrapf(err, "client GET %s failed", u)
  376. }
  377. if resp.StatusCode >= 400 {
  378. return nil, readError(resp.Body)
  379. }
  380. var key api.ProvisionerKeyResponse
  381. if err := readJSON(resp.Body, &key); err != nil {
  382. return nil, errors.Wrapf(err, "error reading %s", u)
  383. }
  384. return &key, nil
  385. }
  386. // Federation performs the get federation request to the CA and returns the
  387. // api.FederationResponse struct.
  388. func (c *Client) Federation(tr http.RoundTripper) (*api.FederationResponse, error) {
  389. u := c.endpoint.ResolveReference(&url.URL{Path: "/federation"})
  390. client := &http.Client{Transport: tr}
  391. resp, err := client.Get(u.String())
  392. if err != nil {
  393. return nil, errors.Wrapf(err, "client GET %s failed", u)
  394. }
  395. if resp.StatusCode >= 400 {
  396. return nil, readError(resp.Body)
  397. }
  398. var federation api.FederationResponse
  399. if err := readJSON(resp.Body, &federation); err != nil {
  400. return nil, errors.Wrapf(err, "error reading %s", u)
  401. }
  402. return &federation, nil
  403. }
  404. // CreateSignRequest is a helper function that given an x509 OTT returns a
  405. // simple but secure sign request as well as the private key used.
  406. func CreateSignRequest(ott string) (*api.SignRequest, crypto.PrivateKey, error) {
  407. token, err := jwt.ParseSigned(ott)
  408. if err != nil {
  409. return nil, nil, errors.Wrap(err, "error parsing ott")
  410. }
  411. var claims jwt.Claims
  412. if err := token.UnsafeClaimsWithoutVerification(&claims); err != nil {
  413. return nil, nil, errors.Wrap(err, "error parsing ott")
  414. }
  415. pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  416. if err != nil {
  417. return nil, nil, errors.Wrap(err, "error generating key")
  418. }
  419. template := &x509.CertificateRequest{
  420. Subject: pkix.Name{
  421. CommonName: claims.Subject,
  422. },
  423. SignatureAlgorithm: x509.ECDSAWithSHA256,
  424. }
  425. if ip := net.ParseIP(claims.Subject); ip != nil {
  426. template.IPAddresses = append(template.IPAddresses, ip)
  427. } else {
  428. template.DNSNames = append(template.DNSNames, claims.Subject)
  429. }
  430. csr, err := x509.CreateCertificateRequest(rand.Reader, template, pk)
  431. if err != nil {
  432. return nil, nil, errors.Wrap(err, "error creating certificate request")
  433. }
  434. cr, err := x509.ParseCertificateRequest(csr)
  435. if err != nil {
  436. return nil, nil, errors.Wrap(err, "error parsing certificate request")
  437. }
  438. if err := cr.CheckSignature(); err != nil {
  439. return nil, nil, errors.Wrap(err, "error signing certificate request")
  440. }
  441. return &api.SignRequest{
  442. CsrPEM: api.CertificateRequest{CertificateRequest: cr},
  443. OTT: ott,
  444. }, pk, nil
  445. }
  446. func getInsecureClient() *http.Client {
  447. return &http.Client{
  448. Transport: &http.Transport{
  449. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  450. },
  451. }
  452. }
  453. func readJSON(r io.ReadCloser, v interface{}) error {
  454. defer r.Close()
  455. return json.NewDecoder(r).Decode(v)
  456. }
  457. func readError(r io.ReadCloser) error {
  458. defer r.Close()
  459. apiErr := new(api.Error)
  460. if err := json.NewDecoder(r).Decode(apiErr); err != nil {
  461. return err
  462. }
  463. return apiErr
  464. }