client.go 14 KB

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