dynamicproxy.go 9.4 KB

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