client.go 14 KB

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