dynamicproxy.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. package dynamicproxy
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "encoding/json"
  6. "errors"
  7. "log"
  8. "net/http"
  9. "net/url"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "time"
  14. "imuslab.com/zoraxy/mod/dynamicproxy/dpcore"
  15. )
  16. /*
  17. Zoraxy Dynamic Proxy
  18. */
  19. func NewDynamicProxy(option RouterOption) (*Router, error) {
  20. proxyMap := sync.Map{}
  21. thisRouter := Router{
  22. Option: &option,
  23. ProxyEndpoints: &proxyMap,
  24. Running: false,
  25. server: nil,
  26. routingRules: []*RoutingRule{},
  27. loadBalancer: option.LoadBalancer,
  28. rateLimitCounter: RequestCountPerIpTable{},
  29. }
  30. thisRouter.mux = &ProxyHandler{
  31. Parent: &thisRouter,
  32. }
  33. return &thisRouter, nil
  34. }
  35. // Update TLS setting in runtime. Will restart the proxy server
  36. // if it is already running in the background
  37. func (router *Router) UpdateTLSSetting(tlsEnabled bool) {
  38. router.Option.UseTls = tlsEnabled
  39. router.Restart()
  40. }
  41. // Update TLS Version in runtime. Will restart proxy server if running.
  42. // Set this to true to force TLS 1.2 or above
  43. func (router *Router) UpdateTLSVersion(requireLatest bool) {
  44. router.Option.ForceTLSLatest = requireLatest
  45. router.Restart()
  46. }
  47. // Update port 80 listener state
  48. func (router *Router) UpdatePort80ListenerState(useRedirect bool) {
  49. router.Option.ListenOnPort80 = useRedirect
  50. router.Restart()
  51. }
  52. // Update https redirect, which will require updates
  53. func (router *Router) UpdateHttpToHttpsRedirectSetting(useRedirect bool) {
  54. router.Option.ForceHttpsRedirect = useRedirect
  55. router.Restart()
  56. }
  57. // Start the dynamic routing
  58. func (router *Router) StartProxyService() error {
  59. //Create a new server object
  60. if router.server != nil {
  61. return errors.New("reverse proxy server already running")
  62. }
  63. //Check if root route is set
  64. if router.Root == nil {
  65. return errors.New("reverse proxy router root not set")
  66. }
  67. minVersion := tls.VersionTLS10
  68. if router.Option.ForceTLSLatest {
  69. minVersion = tls.VersionTLS12
  70. }
  71. config := &tls.Config{
  72. GetCertificate: router.Option.TlsManager.GetCert,
  73. MinVersion: uint16(minVersion),
  74. }
  75. //Start rate limitor
  76. err := router.startRateLimterCounterResetTicker()
  77. if err != nil {
  78. return err
  79. }
  80. if router.Option.UseTls {
  81. router.server = &http.Server{
  82. Addr: ":" + strconv.Itoa(router.Option.Port),
  83. Handler: router.mux,
  84. TLSConfig: config,
  85. }
  86. router.Running = true
  87. if router.Option.Port != 80 && router.Option.ListenOnPort80 {
  88. //Add a 80 to 443 redirector
  89. httpServer := &http.Server{
  90. Addr: ":80",
  91. Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  92. //Check if the domain requesting allow non TLS mode
  93. domainOnly := r.Host
  94. if strings.Contains(r.Host, ":") {
  95. hostPath := strings.Split(r.Host, ":")
  96. domainOnly = hostPath[0]
  97. }
  98. sep := router.getProxyEndpointFromHostname(domainOnly)
  99. if sep != nil && sep.BypassGlobalTLS {
  100. //Allow routing via non-TLS handler
  101. originalHostHeader := r.Host
  102. if r.URL != nil {
  103. r.Host = r.URL.Host
  104. } else {
  105. //Fallback when the upstream proxy screw something up in the header
  106. r.URL, _ = url.Parse(originalHostHeader)
  107. }
  108. //Access Check (blacklist / whitelist)
  109. ruleID := sep.AccessFilterUUID
  110. if sep.AccessFilterUUID == "" {
  111. //Use default rule
  112. ruleID = "default"
  113. }
  114. accessRule, err := router.Option.AccessController.GetAccessRuleByID(ruleID)
  115. if err == nil {
  116. isBlocked, _ := accessRequestBlocked(accessRule, router.Option.WebDirectory, w, r)
  117. if isBlocked {
  118. return
  119. }
  120. }
  121. // Rate Limit
  122. if sep.RequireRateLimit {
  123. if err := router.handleRateLimit(w, r, sep); err != nil {
  124. return
  125. }
  126. }
  127. //Validate basic auth
  128. if sep.AuthenticationProvider.AuthMethod == AuthMethodBasic {
  129. err := handleBasicAuth(w, r, sep)
  130. if err != nil {
  131. return
  132. }
  133. }
  134. selectedUpstream, err := router.loadBalancer.GetRequestUpstreamTarget(w, r, sep.ActiveOrigins, sep.UseStickySession)
  135. if err != nil {
  136. http.ServeFile(w, r, "./web/hosterror.html")
  137. router.Option.Logger.PrintAndLog("dprouter", "failed to get upstream for hostname", err)
  138. router.logRequest(r, false, 404, "vdir-http", r.Host)
  139. }
  140. endpointProxyRewriteRules := GetDefaultHeaderRewriteRules()
  141. if sep.HeaderRewriteRules != nil {
  142. endpointProxyRewriteRules = sep.HeaderRewriteRules
  143. }
  144. selectedUpstream.ServeHTTP(w, r, &dpcore.ResponseRewriteRuleSet{
  145. ProxyDomain: selectedUpstream.OriginIpOrDomain,
  146. OriginalHost: originalHostHeader,
  147. UseTLS: selectedUpstream.RequireTLS,
  148. HostHeaderOverwrite: endpointProxyRewriteRules.RequestHostOverwrite,
  149. NoRemoveHopByHop: endpointProxyRewriteRules.DisableHopByHopHeaderRemoval,
  150. PathPrefix: "",
  151. Version: sep.parent.Option.HostVersion,
  152. })
  153. return
  154. }
  155. if router.Option.ForceHttpsRedirect {
  156. //Redirect to https is enabled
  157. protocol := "https://"
  158. if router.Option.Port == 443 {
  159. http.Redirect(w, r, protocol+r.Host+r.RequestURI, http.StatusTemporaryRedirect)
  160. } else {
  161. http.Redirect(w, r, protocol+r.Host+":"+strconv.Itoa(router.Option.Port)+r.RequestURI, http.StatusTemporaryRedirect)
  162. }
  163. } else {
  164. //Do not do redirection
  165. if sep != nil {
  166. //Sub-domain exists but not allow non-TLS access
  167. w.WriteHeader(http.StatusBadRequest)
  168. w.Write([]byte("400 - Bad Request"))
  169. } else {
  170. //No defined sub-domain
  171. if router.Root.DefaultSiteOption == DefaultSite_NoResponse {
  172. //No response. Just close the connection
  173. hijacker, ok := w.(http.Hijacker)
  174. if !ok {
  175. w.Header().Set("Connection", "close")
  176. return
  177. }
  178. conn, _, err := hijacker.Hijack()
  179. if err != nil {
  180. w.Header().Set("Connection", "close")
  181. return
  182. }
  183. conn.Close()
  184. } else {
  185. //Default behavior
  186. http.NotFound(w, r)
  187. }
  188. }
  189. }
  190. }),
  191. ReadTimeout: 3 * time.Second,
  192. WriteTimeout: 3 * time.Second,
  193. IdleTimeout: 120 * time.Second,
  194. }
  195. router.Option.Logger.PrintAndLog("dprouter", "Starting HTTP-to-HTTPS redirector (port 80)", nil)
  196. //Create a redirection stop channel
  197. stopChan := make(chan bool)
  198. //Start a blocking wait for shutting down the http to https redirection server
  199. go func() {
  200. <-stopChan
  201. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  202. defer cancel()
  203. httpServer.Shutdown(ctx)
  204. router.Option.Logger.PrintAndLog("dprouter", "HTTP to HTTPS redirection listener stopped", nil)
  205. }()
  206. //Start the http server that listens to port 80 and redirect to 443
  207. go func() {
  208. if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  209. //Unable to startup port 80 listener. Handle shutdown process gracefully
  210. stopChan <- true
  211. log.Fatalf("Could not start redirection server: %v\n", err)
  212. }
  213. }()
  214. router.tlsRedirectStop = stopChan
  215. }
  216. //Start the TLS server
  217. router.Option.Logger.PrintAndLog("dprouter", "Reverse proxy service started in the background (TLS mode)", nil)
  218. go func() {
  219. if err := router.server.ListenAndServeTLS("", ""); err != nil && err != http.ErrServerClosed {
  220. router.Option.Logger.PrintAndLog("dprouter", "Could not start proxy server", err)
  221. }
  222. }()
  223. } else {
  224. //Serve with non TLS mode
  225. router.tlsListener = nil
  226. router.server = &http.Server{Addr: ":" + strconv.Itoa(router.Option.Port), Handler: router.mux}
  227. router.Running = true
  228. router.Option.Logger.PrintAndLog("dprouter", "Reverse proxy service started in the background (Plain HTTP mode)", nil)
  229. go func() {
  230. router.server.ListenAndServe()
  231. }()
  232. }
  233. return nil
  234. }
  235. func (router *Router) StopProxyService() error {
  236. if router.server == nil {
  237. return errors.New("reverse proxy server already stopped")
  238. }
  239. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  240. defer cancel()
  241. err := router.server.Shutdown(ctx)
  242. if err != nil {
  243. return err
  244. }
  245. //Stop TLS listener
  246. if router.tlsListener != nil {
  247. router.tlsListener.Close()
  248. }
  249. //Stop rate limiter
  250. if router.rateLimterStop != nil {
  251. go func() {
  252. // As the rate timer loop has a 1 sec ticker
  253. // stop the rate limiter in go routine can prevent
  254. // front end from freezing for 1 sec
  255. router.rateLimterStop <- true
  256. }()
  257. }
  258. //Stop TLS redirection (from port 80)
  259. if router.tlsRedirectStop != nil {
  260. router.tlsRedirectStop <- true
  261. }
  262. //Discard the server object
  263. router.tlsListener = nil
  264. router.server = nil
  265. router.Running = false
  266. router.tlsRedirectStop = nil
  267. return nil
  268. }
  269. // Restart the current router if it is running.
  270. func (router *Router) Restart() error {
  271. //Stop the router if it is already running
  272. if router.Running {
  273. err := router.StopProxyService()
  274. if err != nil {
  275. return err
  276. }
  277. time.Sleep(100 * time.Millisecond)
  278. // Start the server
  279. err = router.StartProxyService()
  280. if err != nil {
  281. return err
  282. }
  283. }
  284. return nil
  285. }
  286. /*
  287. Check if a given request is accessed via a proxied subdomain
  288. */
  289. func (router *Router) IsProxiedSubdomain(r *http.Request) bool {
  290. hostname := r.Header.Get("X-Forwarded-Host")
  291. if hostname == "" {
  292. hostname = r.Host
  293. }
  294. hostname = strings.Split(hostname, ":")[0]
  295. subdEndpoint := router.getProxyEndpointFromHostname(hostname)
  296. return subdEndpoint != nil
  297. }
  298. /*
  299. Load routing from RP
  300. */
  301. func (router *Router) LoadProxy(matchingDomain string) (*ProxyEndpoint, error) {
  302. var targetProxyEndpoint *ProxyEndpoint
  303. router.ProxyEndpoints.Range(func(key, value interface{}) bool {
  304. key, ok := key.(string)
  305. if !ok {
  306. return true
  307. }
  308. v, ok := value.(*ProxyEndpoint)
  309. if !ok {
  310. return true
  311. }
  312. if key == strings.ToLower(matchingDomain) {
  313. targetProxyEndpoint = v
  314. }
  315. return true
  316. })
  317. if targetProxyEndpoint == nil {
  318. return nil, errors.New("target routing rule not found")
  319. }
  320. return targetProxyEndpoint, nil
  321. }
  322. // Deep copy a proxy endpoint, excluding runtime paramters
  323. func CopyEndpoint(endpoint *ProxyEndpoint) *ProxyEndpoint {
  324. js, _ := json.Marshal(endpoint)
  325. newProxyEndpoint := ProxyEndpoint{}
  326. err := json.Unmarshal(js, &newProxyEndpoint)
  327. if err != nil {
  328. return nil
  329. }
  330. return &newProxyEndpoint
  331. }
  332. func (r *Router) GetProxyEndpointsAsMap() map[string]*ProxyEndpoint {
  333. m := make(map[string]*ProxyEndpoint)
  334. r.ProxyEndpoints.Range(func(key, value interface{}) bool {
  335. k, ok := key.(string)
  336. if !ok {
  337. return true
  338. }
  339. v, ok := value.(*ProxyEndpoint)
  340. if !ok {
  341. return true
  342. }
  343. m[k] = v
  344. return true
  345. })
  346. return m
  347. }