dynamicproxy.go 10 KB

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