typedef.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. package dynamicproxy
  2. import (
  3. _ "embed"
  4. "net"
  5. "net/http"
  6. "sync"
  7. "imuslab.com/zoraxy/mod/access"
  8. "imuslab.com/zoraxy/mod/auth/sso/authelia"
  9. "imuslab.com/zoraxy/mod/dynamicproxy/dpcore"
  10. "imuslab.com/zoraxy/mod/dynamicproxy/loadbalance"
  11. "imuslab.com/zoraxy/mod/dynamicproxy/permissionpolicy"
  12. "imuslab.com/zoraxy/mod/dynamicproxy/redirection"
  13. "imuslab.com/zoraxy/mod/dynamicproxy/rewrite"
  14. "imuslab.com/zoraxy/mod/geodb"
  15. "imuslab.com/zoraxy/mod/info/logger"
  16. "imuslab.com/zoraxy/mod/statistic"
  17. "imuslab.com/zoraxy/mod/tlscert"
  18. )
  19. type ProxyType int
  20. const (
  21. ProxyTypeRoot ProxyType = iota //Root Proxy, everything not matching will be routed here
  22. ProxyTypeHost //Host Proxy, match by host (domain) name
  23. ProxyTypeVdir //Virtual Directory Proxy, match by path prefix
  24. )
  25. type ProxyHandler struct {
  26. Parent *Router
  27. }
  28. /* Router Object Options */
  29. type RouterOption struct {
  30. /* Basic Settings */
  31. HostUUID string //The UUID of Zoraxy, use for heading mod
  32. HostVersion string //The version of Zoraxy, use for heading mod
  33. Port int //Incoming port
  34. UseTls bool //Use TLS to serve incoming requsts
  35. ForceTLSLatest bool //Force TLS1.2 or above
  36. NoCache bool //Force set Cache-Control: no-store
  37. ListenOnPort80 bool //Enable port 80 http listener
  38. ForceHttpsRedirect bool //Force redirection of http to https endpoint
  39. /* Routing Service Managers */
  40. TlsManager *tlscert.Manager //TLS manager for serving SAN certificates
  41. RedirectRuleTable *redirection.RuleTable //Redirection rules handler and table
  42. GeodbStore *geodb.Store //GeoIP resolver
  43. AccessController *access.Controller //Blacklist / whitelist controller
  44. StatisticCollector *statistic.Collector //Statistic collector for storing stats on incoming visitors
  45. WebDirectory string //The static web server directory containing the templates folder
  46. LoadBalancer *loadbalance.RouteManager //Load balancer that handle load balancing of proxy target
  47. /* Authentication Providers */
  48. AutheliaRouter *authelia.AutheliaRouter //Authelia router for Authelia authentication
  49. /* Utilities */
  50. Logger *logger.Logger //Logger for reverse proxy requets
  51. }
  52. /* Router Object */
  53. type Router struct {
  54. Option *RouterOption
  55. ProxyEndpoints *sync.Map //Map of ProxyEndpoint objects, each ProxyEndpoint object is a routing rule that handle incoming requests
  56. Running bool //If the router is running
  57. Root *ProxyEndpoint //Root proxy endpoint, default site
  58. mux http.Handler //HTTP handler
  59. server *http.Server //HTTP server
  60. tlsListener net.Listener //TLS listener, handle SNI routing
  61. loadBalancer *loadbalance.RouteManager //Load balancer routing manager
  62. routingRules []*RoutingRule //Special routing rules, handle high priority routing like ACME request handling
  63. tlsRedirectStop chan bool //Stop channel for tls redirection server
  64. rateLimterStop chan bool //Stop channel for rate limiter
  65. rateLimitCounter RequestCountPerIpTable //Request counter for rate limter
  66. }
  67. /* Basic Auth Related Data structure*/
  68. // Auth credential for basic auth on certain endpoints
  69. type BasicAuthCredentials struct {
  70. Username string
  71. PasswordHash string
  72. }
  73. // Auth credential for basic auth on certain endpoints
  74. type BasicAuthUnhashedCredentials struct {
  75. Username string
  76. Password string
  77. }
  78. // Paths to exclude in basic auth enabled proxy handler
  79. type BasicAuthExceptionRule struct {
  80. PathPrefix string
  81. }
  82. /* Routing Rule Data Structures */
  83. // A Virtual Directory endpoint, provide a subset of ProxyEndpoint for better
  84. // program structure than directly using ProxyEndpoint
  85. type VirtualDirectoryEndpoint struct {
  86. MatchingPath string //Matching prefix of the request path, also act as key
  87. Domain string //Domain or IP to proxy to
  88. RequireTLS bool //Target domain require TLS
  89. SkipCertValidations bool //Set to true to accept self signed certs
  90. Disabled bool //If the rule is enabled
  91. proxy *dpcore.ReverseProxy `json:"-"`
  92. parent *ProxyEndpoint `json:"-"`
  93. }
  94. // Rules and settings for header rewriting
  95. type HeaderRewriteRules struct {
  96. UserDefinedHeaders []*rewrite.UserDefinedHeader //Custom headers to append when proxying requests from this endpoint
  97. RequestHostOverwrite string //If not empty, this domain will be used to overwrite the Host field in request header
  98. HSTSMaxAge int64 //HSTS max age, set to 0 for disable HSTS headers
  99. EnablePermissionPolicyHeader bool //Enable injection of permission policy header
  100. PermissionPolicy *permissionpolicy.PermissionsPolicy //Permission policy header
  101. DisableHopByHopHeaderRemoval bool //Do not remove hop-by-hop headers
  102. }
  103. /*
  104. Authentication Provider
  105. TODO: Move these into a dedicated module
  106. */
  107. type AuthMethod int
  108. const (
  109. AuthMethodNone AuthMethod = iota //No authentication required
  110. AuthMethodBasic //Basic Auth
  111. AuthMethodAuthelia //Authelia
  112. AuthMethodOauth2 //Oauth2
  113. )
  114. type AuthenticationProvider struct {
  115. AuthMethod AuthMethod //The authentication method to use
  116. /* Basic Auth Settings */
  117. BasicAuthCredentials []*BasicAuthCredentials //Basic auth credentials
  118. BasicAuthExceptionRules []*BasicAuthExceptionRule //Path to exclude in a basic auth enabled proxy target
  119. BasicAuthGroupIDs []string //Group IDs that are allowed to access this endpoint
  120. /* Authelia Settings */
  121. AutheliaURL string //URL of the Authelia server, leave empty to use global settings e.g. authelia.example.com
  122. UseHTTPS bool //Whether to use HTTPS for the Authelia server
  123. }
  124. // A proxy endpoint record, a general interface for handling inbound routing
  125. type ProxyEndpoint struct {
  126. ProxyType ProxyType //The type of this proxy, see const def
  127. RootOrMatchingDomain string //Matching domain for host, also act as key
  128. MatchingDomainAlias []string //A list of domains that alias to this rule
  129. ActiveOrigins []*loadbalance.Upstream //Activated Upstream or origin servers IP or domain to proxy to
  130. InactiveOrigins []*loadbalance.Upstream //Disabled Upstream or origin servers IP or domain to proxy to
  131. UseStickySession bool //Use stick session for load balancing
  132. UseActiveLoadBalance bool //Use active loadbalancing, default passive
  133. Disabled bool //If the rule is disabled
  134. //Inbound TLS/SSL Related
  135. BypassGlobalTLS bool //Bypass global TLS setting options if TLS Listener enabled (parent.tlsListener != nil)
  136. //Virtual Directories
  137. VirtualDirectories []*VirtualDirectoryEndpoint
  138. //Custom Headers
  139. HeaderRewriteRules *HeaderRewriteRules
  140. //Authentication
  141. AuthenticationProvider *AuthenticationProvider
  142. // Rate Limiting
  143. RequireRateLimit bool
  144. RateLimit int64 // Rate limit in requests per second
  145. //Uptime Monitor
  146. DisableUptimeMonitor bool //Disable uptime monitor for this endpoint
  147. //Access Control
  148. AccessFilterUUID string //Access filter ID
  149. //Fallback routing logic (Special Rule Sets Only)
  150. DefaultSiteOption int //Fallback routing logic options
  151. DefaultSiteValue string //Fallback routing target, optional
  152. //Internal Logic Elements
  153. parent *Router `json:"-"`
  154. }
  155. /*
  156. Routing type specific interface
  157. These are options that only avaible for a specific interface
  158. when running, these are converted into "ProxyEndpoint" objects
  159. for more generic routing logic
  160. */
  161. // Root options are those that are required for reverse proxy handler to work
  162. const (
  163. DefaultSite_InternalStaticWebServer = 0
  164. DefaultSite_ReverseProxy = 1
  165. DefaultSite_Redirect = 2
  166. DefaultSite_NotFoundPage = 3
  167. DefaultSite_NoResponse = 4
  168. DefaultSite_TeaPot = 418 //I'm a teapot
  169. )
  170. /*
  171. Web Templates
  172. */
  173. var (
  174. //go:embed templates/forbidden.html
  175. page_forbidden []byte
  176. //go:embed templates/hosterror.html
  177. page_hosterror []byte
  178. )