dynamicproxy.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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. http.NotFound(w, r)
  172. }
  173. }
  174. }),
  175. ReadTimeout: 3 * time.Second,
  176. WriteTimeout: 3 * time.Second,
  177. IdleTimeout: 120 * time.Second,
  178. }
  179. router.Option.Logger.PrintAndLog("dprouter", "Starting HTTP-to-HTTPS redirector (port 80)", nil)
  180. //Create a redirection stop channel
  181. stopChan := make(chan bool)
  182. //Start a blocking wait for shutting down the http to https redirection server
  183. go func() {
  184. <-stopChan
  185. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  186. defer cancel()
  187. httpServer.Shutdown(ctx)
  188. router.Option.Logger.PrintAndLog("dprouter", "HTTP to HTTPS redirection listener stopped", nil)
  189. }()
  190. //Start the http server that listens to port 80 and redirect to 443
  191. go func() {
  192. if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  193. //Unable to startup port 80 listener. Handle shutdown process gracefully
  194. stopChan <- true
  195. log.Fatalf("Could not start redirection server: %v\n", err)
  196. }
  197. }()
  198. router.tlsRedirectStop = stopChan
  199. }
  200. //Start the TLS server
  201. router.Option.Logger.PrintAndLog("dprouter", "Reverse proxy service started in the background (TLS mode)", nil)
  202. go func() {
  203. if err := router.server.ListenAndServeTLS("", ""); err != nil && err != http.ErrServerClosed {
  204. router.Option.Logger.PrintAndLog("dprouter", "Could not start proxy server", err)
  205. }
  206. }()
  207. } else {
  208. //Serve with non TLS mode
  209. router.tlsListener = nil
  210. router.server = &http.Server{Addr: ":" + strconv.Itoa(router.Option.Port), Handler: router.mux}
  211. router.Running = true
  212. router.Option.Logger.PrintAndLog("dprouter", "Reverse proxy service started in the background (Plain HTTP mode)", nil)
  213. go func() {
  214. router.server.ListenAndServe()
  215. }()
  216. }
  217. return nil
  218. }
  219. func (router *Router) StopProxyService() error {
  220. if router.server == nil {
  221. return errors.New("reverse proxy server already stopped")
  222. }
  223. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  224. defer cancel()
  225. err := router.server.Shutdown(ctx)
  226. if err != nil {
  227. return err
  228. }
  229. //Stop TLS listener
  230. if router.tlsListener != nil {
  231. router.tlsListener.Close()
  232. }
  233. //Stop rate limiter
  234. if router.rateLimterStop != nil {
  235. go func() {
  236. // As the rate timer loop has a 1 sec ticker
  237. // stop the rate limiter in go routine can prevent
  238. // front end from freezing for 1 sec
  239. router.rateLimterStop <- true
  240. }()
  241. }
  242. //Stop TLS redirection (from port 80)
  243. if router.tlsRedirectStop != nil {
  244. router.tlsRedirectStop <- true
  245. }
  246. //Discard the server object
  247. router.tlsListener = nil
  248. router.server = nil
  249. router.Running = false
  250. router.tlsRedirectStop = nil
  251. return nil
  252. }
  253. // Restart the current router if it is running.
  254. func (router *Router) Restart() error {
  255. //Stop the router if it is already running
  256. if router.Running {
  257. err := router.StopProxyService()
  258. if err != nil {
  259. return err
  260. }
  261. time.Sleep(800 * time.Millisecond)
  262. // Start the server
  263. err = router.StartProxyService()
  264. if err != nil {
  265. return err
  266. }
  267. }
  268. return nil
  269. }
  270. /*
  271. Check if a given request is accessed via a proxied subdomain
  272. */
  273. func (router *Router) IsProxiedSubdomain(r *http.Request) bool {
  274. hostname := r.Header.Get("X-Forwarded-Host")
  275. if hostname == "" {
  276. hostname = r.Host
  277. }
  278. hostname = strings.Split(hostname, ":")[0]
  279. subdEndpoint := router.getProxyEndpointFromHostname(hostname)
  280. return subdEndpoint != nil
  281. }
  282. /*
  283. Load routing from RP
  284. */
  285. func (router *Router) LoadProxy(matchingDomain string) (*ProxyEndpoint, error) {
  286. var targetProxyEndpoint *ProxyEndpoint
  287. router.ProxyEndpoints.Range(func(key, value interface{}) bool {
  288. key, ok := key.(string)
  289. if !ok {
  290. return true
  291. }
  292. v, ok := value.(*ProxyEndpoint)
  293. if !ok {
  294. return true
  295. }
  296. if key == matchingDomain {
  297. targetProxyEndpoint = v
  298. }
  299. return true
  300. })
  301. if targetProxyEndpoint == nil {
  302. return nil, errors.New("target routing rule not found")
  303. }
  304. return targetProxyEndpoint, nil
  305. }
  306. // Deep copy a proxy endpoint, excluding runtime paramters
  307. func CopyEndpoint(endpoint *ProxyEndpoint) *ProxyEndpoint {
  308. js, _ := json.Marshal(endpoint)
  309. newProxyEndpoint := ProxyEndpoint{}
  310. err := json.Unmarshal(js, &newProxyEndpoint)
  311. if err != nil {
  312. return nil
  313. }
  314. return &newProxyEndpoint
  315. }
  316. func (r *Router) GetProxyEndpointsAsMap() map[string]*ProxyEndpoint {
  317. m := make(map[string]*ProxyEndpoint)
  318. r.ProxyEndpoints.Range(func(key, value interface{}) bool {
  319. k, ok := key.(string)
  320. if !ok {
  321. return true
  322. }
  323. v, ok := value.(*ProxyEndpoint)
  324. if !ok {
  325. return true
  326. }
  327. m[k] = v
  328. return true
  329. })
  330. return m
  331. }