dataproxy.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. package api
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "net"
  6. "net/http"
  7. "net/http/httputil"
  8. "net/url"
  9. "time"
  10. "github.com/grafana/grafana/pkg/api/cloudwatch"
  11. "github.com/grafana/grafana/pkg/bus"
  12. "github.com/grafana/grafana/pkg/metrics"
  13. "github.com/grafana/grafana/pkg/middleware"
  14. m "github.com/grafana/grafana/pkg/models"
  15. "github.com/grafana/grafana/pkg/setting"
  16. "github.com/grafana/grafana/pkg/util"
  17. )
  18. func DataProxyTransport(ds *m.DataSource) (*http.Transport, error) {
  19. transport := &http.Transport{
  20. TLSClientConfig: &tls.Config{
  21. InsecureSkipVerify: true,
  22. },
  23. Proxy: http.ProxyFromEnvironment,
  24. Dial: (&net.Dialer{
  25. Timeout: 30 * time.Second,
  26. KeepAlive: 30 * time.Second,
  27. }).Dial,
  28. TLSHandshakeTimeout: 10 * time.Second,
  29. }
  30. var tlsAuth, tlsAuthWithCACert bool
  31. if ds.JsonData != nil {
  32. tlsAuth = ds.JsonData.Get("tlsAuth").MustBool(false)
  33. tlsAuthWithCACert = ds.JsonData.Get("tlsAuthWithCACert").MustBool(false)
  34. }
  35. if tlsAuth {
  36. transport.TLSClientConfig.InsecureSkipVerify = false
  37. decrypted := ds.SecureJsonData.Decrypt()
  38. if tlsAuthWithCACert && len(decrypted["tlsCACert"]) > 0 {
  39. caPool := x509.NewCertPool()
  40. ok := caPool.AppendCertsFromPEM([]byte(decrypted["tlsCACert"]))
  41. if ok {
  42. transport.TLSClientConfig.RootCAs = caPool
  43. }
  44. }
  45. cert, err := tls.X509KeyPair([]byte(decrypted["tlsClientCert"]), []byte(decrypted["tlsClientKey"]))
  46. if err != nil {
  47. return nil, err
  48. }
  49. transport.TLSClientConfig.Certificates = []tls.Certificate{cert}
  50. }
  51. return transport, nil
  52. }
  53. func NewReverseProxy(ds *m.DataSource, proxyPath string, targetUrl *url.URL) *httputil.ReverseProxy {
  54. director := func(req *http.Request) {
  55. req.URL.Scheme = targetUrl.Scheme
  56. req.URL.Host = targetUrl.Host
  57. req.Host = targetUrl.Host
  58. reqQueryVals := req.URL.Query()
  59. if ds.Type == m.DS_INFLUXDB_08 {
  60. req.URL.Path = util.JoinUrlFragments(targetUrl.Path, "db/"+ds.Database+"/"+proxyPath)
  61. reqQueryVals.Add("u", ds.User)
  62. reqQueryVals.Add("p", ds.Password)
  63. req.URL.RawQuery = reqQueryVals.Encode()
  64. } else if ds.Type == m.DS_INFLUXDB {
  65. req.URL.Path = util.JoinUrlFragments(targetUrl.Path, proxyPath)
  66. req.URL.RawQuery = reqQueryVals.Encode()
  67. if !ds.BasicAuth {
  68. req.Header.Del("Authorization")
  69. req.Header.Add("Authorization", util.GetBasicAuthHeader(ds.User, ds.Password))
  70. }
  71. } else {
  72. req.URL.Path = util.JoinUrlFragments(targetUrl.Path, proxyPath)
  73. }
  74. if ds.BasicAuth {
  75. req.Header.Del("Authorization")
  76. req.Header.Add("Authorization", util.GetBasicAuthHeader(ds.BasicAuthUser, ds.BasicAuthPassword))
  77. }
  78. dsAuth := req.Header.Get("X-DS-Authorization")
  79. if len(dsAuth) > 0 {
  80. req.Header.Del("X-DS-Authorization")
  81. req.Header.Del("Authorization")
  82. req.Header.Add("Authorization", dsAuth)
  83. }
  84. // clear cookie headers
  85. req.Header.Del("Cookie")
  86. req.Header.Del("Set-Cookie")
  87. }
  88. return &httputil.ReverseProxy{Director: director, FlushInterval: time.Millisecond * 200}
  89. }
  90. func getDatasource(id int64, orgId int64) (*m.DataSource, error) {
  91. query := m.GetDataSourceByIdQuery{Id: id, OrgId: orgId}
  92. if err := bus.Dispatch(&query); err != nil {
  93. return nil, err
  94. }
  95. return query.Result, nil
  96. }
  97. func ProxyDataSourceRequest(c *middleware.Context) {
  98. c.TimeRequest(metrics.M_DataSource_ProxyReq_Timer)
  99. ds, err := getDatasource(c.ParamsInt64(":id"), c.OrgId)
  100. if err != nil {
  101. c.JsonApiErr(500, "Unable to load datasource meta data", err)
  102. return
  103. }
  104. if ds.Type == m.DS_CLOUDWATCH {
  105. cloudwatch.HandleRequest(c, ds)
  106. return
  107. }
  108. if ds.Type == m.DS_INFLUXDB {
  109. if c.Query("db") != ds.Database {
  110. c.JsonApiErr(403, "Datasource is not configured to allow this database", nil)
  111. return
  112. }
  113. }
  114. targetUrl, _ := url.Parse(ds.Url)
  115. if len(setting.DataProxyWhiteList) > 0 {
  116. if _, exists := setting.DataProxyWhiteList[targetUrl.Host]; !exists {
  117. c.JsonApiErr(403, "Data proxy hostname and ip are not included in whitelist", nil)
  118. return
  119. }
  120. }
  121. proxyPath := c.Params("*")
  122. if ds.Type == m.DS_ES {
  123. if c.Req.Request.Method == "DELETE" {
  124. c.JsonApiErr(403, "Deletes not allowed on proxied Elasticsearch datasource", nil)
  125. return
  126. }
  127. if c.Req.Request.Method == "PUT" {
  128. c.JsonApiErr(403, "Puts not allowed on proxied Elasticsearch datasource", nil)
  129. return
  130. }
  131. if c.Req.Request.Method == "POST" && proxyPath != "_msearch" {
  132. c.JsonApiErr(403, "Posts not allowed on proxied Elasticsearch datasource except on /_msearch", nil)
  133. return
  134. }
  135. }
  136. proxy := NewReverseProxy(ds, proxyPath, targetUrl)
  137. proxy.Transport, err = DataProxyTransport(ds)
  138. if err != nil {
  139. c.JsonApiErr(400, "Unable to load TLS certificate", err)
  140. return
  141. }
  142. proxy.ServeHTTP(c.Resp, c.Req.Request)
  143. c.Resp.Header().Del("Set-Cookie")
  144. }