reverseproxy.go 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377
  1. package main
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "path/filepath"
  6. "sort"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "imuslab.com/zoraxy/mod/auth"
  11. "imuslab.com/zoraxy/mod/dynamicproxy"
  12. "imuslab.com/zoraxy/mod/dynamicproxy/loadbalance"
  13. "imuslab.com/zoraxy/mod/dynamicproxy/permissionpolicy"
  14. "imuslab.com/zoraxy/mod/uptime"
  15. "imuslab.com/zoraxy/mod/utils"
  16. )
  17. var (
  18. dynamicProxyRouter *dynamicproxy.Router
  19. )
  20. // Add user customizable reverse proxy
  21. func ReverseProxtInit() {
  22. /*
  23. Load Reverse Proxy Global Settings
  24. */
  25. inboundPort := 80
  26. if sysdb.KeyExists("settings", "inbound") {
  27. sysdb.Read("settings", "inbound", &inboundPort)
  28. SystemWideLogger.Println("Serving inbound port ", inboundPort)
  29. } else {
  30. SystemWideLogger.Println("Inbound port not set. Using default (80)")
  31. }
  32. useTls := false
  33. sysdb.Read("settings", "usetls", &useTls)
  34. if useTls {
  35. SystemWideLogger.Println("TLS mode enabled. Serving proxxy request with TLS")
  36. } else {
  37. SystemWideLogger.Println("TLS mode disabled. Serving proxy request with plain http")
  38. }
  39. forceLatestTLSVersion := false
  40. sysdb.Read("settings", "forceLatestTLS", &forceLatestTLSVersion)
  41. if forceLatestTLSVersion {
  42. SystemWideLogger.Println("Force latest TLS mode enabled. Minimum TLS LS version is set to v1.2")
  43. } else {
  44. SystemWideLogger.Println("Force latest TLS mode disabled. Minimum TLS version is set to v1.0")
  45. }
  46. developmentMode := false
  47. sysdb.Read("settings", "devMode", &developmentMode)
  48. if useTls {
  49. SystemWideLogger.Println("Development mode enabled. Using no-store Cache Control policy")
  50. } else {
  51. SystemWideLogger.Println("Development mode disabled. Proxying with default Cache Control policy")
  52. }
  53. listenOnPort80 := false
  54. sysdb.Read("settings", "listenP80", &listenOnPort80)
  55. if listenOnPort80 {
  56. SystemWideLogger.Println("Port 80 listener enabled")
  57. } else {
  58. SystemWideLogger.Println("Port 80 listener disabled")
  59. }
  60. forceHttpsRedirect := false
  61. sysdb.Read("settings", "redirect", &forceHttpsRedirect)
  62. if forceHttpsRedirect {
  63. SystemWideLogger.Println("Force HTTPS mode enabled")
  64. //Port 80 listener must be enabled to perform http -> https redirect
  65. listenOnPort80 = true
  66. } else {
  67. SystemWideLogger.Println("Force HTTPS mode disabled")
  68. }
  69. /*
  70. Create a new proxy object
  71. The DynamicProxy is the parent of all reverse proxy handlers,
  72. use for managemening and provide functions to access proxy handlers
  73. */
  74. dprouter, err := dynamicproxy.NewDynamicProxy(dynamicproxy.RouterOption{
  75. HostUUID: nodeUUID,
  76. HostVersion: version,
  77. Port: inboundPort,
  78. UseTls: useTls,
  79. ForceTLSLatest: forceLatestTLSVersion,
  80. NoCache: developmentMode,
  81. ListenOnPort80: listenOnPort80,
  82. ForceHttpsRedirect: forceHttpsRedirect,
  83. TlsManager: tlsCertManager,
  84. RedirectRuleTable: redirectTable,
  85. GeodbStore: geodbStore,
  86. StatisticCollector: statisticCollector,
  87. WebDirectory: *staticWebServerRoot,
  88. AccessController: accessController,
  89. LoadBalancer: loadBalancer,
  90. })
  91. if err != nil {
  92. SystemWideLogger.PrintAndLog("Proxy", "Unable to create dynamic proxy router", err)
  93. return
  94. }
  95. dynamicProxyRouter = dprouter
  96. /*
  97. Load all conf from files
  98. */
  99. confs, _ := filepath.Glob("./conf/proxy/*.config")
  100. for _, conf := range confs {
  101. err := LoadReverseProxyConfig(conf)
  102. if err != nil {
  103. SystemWideLogger.PrintAndLog("Proxy", "Failed to load config file: "+filepath.Base(conf), err)
  104. return
  105. }
  106. }
  107. if dynamicProxyRouter.Root == nil {
  108. //Root config not set (new deployment?), use internal static web server as root
  109. defaultRootRouter, err := GetDefaultRootConfig()
  110. if err != nil {
  111. SystemWideLogger.PrintAndLog("Proxy", "Failed to generate default root routing", err)
  112. return
  113. }
  114. dynamicProxyRouter.SetProxyRouteAsRoot(defaultRootRouter)
  115. }
  116. //Start Service
  117. //Not sure why but delay must be added if you have another
  118. //reverse proxy server in front of this service
  119. time.Sleep(300 * time.Millisecond)
  120. dynamicProxyRouter.StartProxyService()
  121. SystemWideLogger.Println("Dynamic Reverse Proxy service started")
  122. //Add all proxy services to uptime monitor
  123. //Create a uptime monitor service
  124. go func() {
  125. //This must be done in go routine to prevent blocking on system startup
  126. uptimeMonitor, _ = uptime.NewUptimeMonitor(&uptime.Config{
  127. Targets: GetUptimeTargetsFromReverseProxyRules(dynamicProxyRouter),
  128. Interval: 300, //5 minutes
  129. MaxRecordsStore: 288, //1 day
  130. })
  131. SystemWideLogger.Println("Uptime Monitor background service started")
  132. }()
  133. }
  134. func ReverseProxyHandleOnOff(w http.ResponseWriter, r *http.Request) {
  135. enable, _ := utils.PostPara(r, "enable") //Support root, vdir and subd
  136. if enable == "true" {
  137. err := dynamicProxyRouter.StartProxyService()
  138. if err != nil {
  139. utils.SendErrorResponse(w, err.Error())
  140. return
  141. }
  142. } else {
  143. //Check if it is loopback
  144. if dynamicProxyRouter.IsProxiedSubdomain(r) {
  145. //Loopback routing. Turning it off will make the user lost control
  146. //of the whole system. Do not allow shutdown
  147. utils.SendErrorResponse(w, "Unable to shutdown in loopback rp mode. Remove proxy rules for management interface and retry.")
  148. return
  149. }
  150. err := dynamicProxyRouter.StopProxyService()
  151. if err != nil {
  152. utils.SendErrorResponse(w, err.Error())
  153. return
  154. }
  155. }
  156. utils.SendOK(w)
  157. }
  158. func ReverseProxyHandleAddEndpoint(w http.ResponseWriter, r *http.Request) {
  159. eptype, err := utils.PostPara(r, "type") //Support root and host
  160. if err != nil {
  161. utils.SendErrorResponse(w, "type not defined")
  162. return
  163. }
  164. endpoint, err := utils.PostPara(r, "ep")
  165. if err != nil {
  166. utils.SendErrorResponse(w, "endpoint not defined")
  167. return
  168. }
  169. tls, _ := utils.PostPara(r, "tls")
  170. if tls == "" {
  171. tls = "false"
  172. }
  173. useTLS := (tls == "true")
  174. //Bypass global TLS value / allow direct access from port 80?
  175. bypassGlobalTLS, _ := utils.PostPara(r, "bypassGlobalTLS")
  176. if bypassGlobalTLS == "" {
  177. bypassGlobalTLS = "false"
  178. }
  179. useBypassGlobalTLS := bypassGlobalTLS == "true"
  180. //Enable TLS validation?
  181. stv, _ := utils.PostPara(r, "tlsval")
  182. if stv == "" {
  183. stv = "false"
  184. }
  185. skipTlsValidation := (stv == "true")
  186. //Get access rule ID
  187. accessRuleID, _ := utils.PostPara(r, "access")
  188. if accessRuleID == "" {
  189. accessRuleID = "default"
  190. }
  191. if !accessController.AccessRuleExists(accessRuleID) {
  192. utils.SendErrorResponse(w, "invalid access rule ID selected")
  193. return
  194. }
  195. // Require basic auth?
  196. rba, _ := utils.PostPara(r, "bauth")
  197. if rba == "" {
  198. rba = "false"
  199. }
  200. requireBasicAuth := (rba == "true")
  201. // Require Rate Limiting?
  202. requireRateLimit := false
  203. proxyRateLimit := 1000
  204. requireRateLimit, err = utils.PostBool(r, "rate")
  205. if err != nil {
  206. requireRateLimit = false
  207. }
  208. if requireRateLimit {
  209. proxyRateLimit, err = utils.PostInt(r, "ratenum")
  210. if err != nil {
  211. proxyRateLimit = 0
  212. }
  213. if err != nil {
  214. utils.SendErrorResponse(w, "invalid rate limit number")
  215. return
  216. }
  217. if proxyRateLimit <= 0 {
  218. utils.SendErrorResponse(w, "rate limit number must be greater than 0")
  219. return
  220. }
  221. }
  222. // Bypass WebSocket Origin Check
  223. strbpwsorg, _ := utils.PostPara(r, "bpwsorg")
  224. if strbpwsorg == "" {
  225. strbpwsorg = "false"
  226. }
  227. bypassWebsocketOriginCheck := (strbpwsorg == "true")
  228. //Prase the basic auth to correct structure
  229. cred, _ := utils.PostPara(r, "cred")
  230. basicAuthCredentials := []*dynamicproxy.BasicAuthCredentials{}
  231. if requireBasicAuth {
  232. preProcessCredentials := []*dynamicproxy.BasicAuthUnhashedCredentials{}
  233. err = json.Unmarshal([]byte(cred), &preProcessCredentials)
  234. if err != nil {
  235. utils.SendErrorResponse(w, "invalid user credentials")
  236. return
  237. }
  238. //Check if there are empty password credentials
  239. for _, credObj := range preProcessCredentials {
  240. if strings.TrimSpace(credObj.Password) == "" {
  241. utils.SendErrorResponse(w, credObj.Username+" has empty password")
  242. return
  243. }
  244. }
  245. //Convert and hash the passwords
  246. for _, credObj := range preProcessCredentials {
  247. basicAuthCredentials = append(basicAuthCredentials, &dynamicproxy.BasicAuthCredentials{
  248. Username: credObj.Username,
  249. PasswordHash: auth.Hash(credObj.Password),
  250. })
  251. }
  252. }
  253. var proxyEndpointCreated *dynamicproxy.ProxyEndpoint
  254. if eptype == "host" {
  255. rootOrMatchingDomain, err := utils.PostPara(r, "rootname")
  256. if err != nil {
  257. utils.SendErrorResponse(w, "hostname not defined")
  258. return
  259. }
  260. rootOrMatchingDomain = strings.TrimSpace(rootOrMatchingDomain)
  261. //Check if it contains ",", if yes, split the remainings as alias
  262. aliasHostnames := []string{}
  263. if strings.Contains(rootOrMatchingDomain, ",") {
  264. matchingDomains := strings.Split(rootOrMatchingDomain, ",")
  265. if len(matchingDomains) > 1 {
  266. rootOrMatchingDomain = matchingDomains[0]
  267. for _, aliasHostname := range matchingDomains[1:] {
  268. //Filter out any space
  269. aliasHostnames = append(aliasHostnames, strings.TrimSpace(aliasHostname))
  270. }
  271. }
  272. }
  273. //Generate a proxy endpoint object
  274. thisProxyEndpoint := dynamicproxy.ProxyEndpoint{
  275. //I/O
  276. ProxyType: dynamicproxy.ProxyType_Host,
  277. RootOrMatchingDomain: rootOrMatchingDomain,
  278. MatchingDomainAlias: aliasHostnames,
  279. ActiveOrigins: []*loadbalance.Upstream{
  280. {
  281. OriginIpOrDomain: endpoint,
  282. RequireTLS: useTLS,
  283. SkipCertValidations: skipTlsValidation,
  284. SkipWebSocketOriginCheck: bypassWebsocketOriginCheck,
  285. Priority: 0,
  286. },
  287. },
  288. InactiveOrigins: []*loadbalance.Upstream{},
  289. UseStickySession: false, //TODO: Move options to webform
  290. //TLS
  291. BypassGlobalTLS: useBypassGlobalTLS,
  292. AccessFilterUUID: accessRuleID,
  293. //VDir
  294. VirtualDirectories: []*dynamicproxy.VirtualDirectoryEndpoint{},
  295. //Custom headers
  296. UserDefinedHeaders: []*dynamicproxy.UserDefinedHeader{},
  297. //Auth
  298. RequireBasicAuth: requireBasicAuth,
  299. BasicAuthCredentials: basicAuthCredentials,
  300. BasicAuthExceptionRules: []*dynamicproxy.BasicAuthExceptionRule{},
  301. DefaultSiteOption: 0,
  302. DefaultSiteValue: "",
  303. // Rate Limit
  304. RequireRateLimit: requireRateLimit,
  305. RateLimit: int64(proxyRateLimit),
  306. }
  307. preparedEndpoint, err := dynamicProxyRouter.PrepareProxyRoute(&thisProxyEndpoint)
  308. if err != nil {
  309. utils.SendErrorResponse(w, "unable to prepare proxy route to target endpoint: "+err.Error())
  310. return
  311. }
  312. dynamicProxyRouter.AddProxyRouteToRuntime(preparedEndpoint)
  313. proxyEndpointCreated = &thisProxyEndpoint
  314. } else if eptype == "root" {
  315. //Get the default site options and target
  316. dsOptString, err := utils.PostPara(r, "defaultSiteOpt")
  317. if err != nil {
  318. utils.SendErrorResponse(w, "default site action not defined")
  319. return
  320. }
  321. var defaultSiteOption int = 1
  322. opt, err := strconv.Atoi(dsOptString)
  323. if err != nil {
  324. utils.SendErrorResponse(w, "invalid default site option")
  325. return
  326. }
  327. defaultSiteOption = opt
  328. dsVal, err := utils.PostPara(r, "defaultSiteVal")
  329. if err != nil && (defaultSiteOption == 1 || defaultSiteOption == 2) {
  330. //Reverse proxy or redirect, must require value to be set
  331. utils.SendErrorResponse(w, "target not defined")
  332. return
  333. }
  334. //Write the root options to file
  335. rootRoutingEndpoint := dynamicproxy.ProxyEndpoint{
  336. ProxyType: dynamicproxy.ProxyType_Root,
  337. RootOrMatchingDomain: "/",
  338. ActiveOrigins: []*loadbalance.Upstream{
  339. {
  340. OriginIpOrDomain: endpoint,
  341. RequireTLS: useTLS,
  342. SkipCertValidations: true,
  343. SkipWebSocketOriginCheck: true,
  344. Priority: 0,
  345. },
  346. },
  347. InactiveOrigins: []*loadbalance.Upstream{},
  348. BypassGlobalTLS: false,
  349. DefaultSiteOption: defaultSiteOption,
  350. DefaultSiteValue: dsVal,
  351. }
  352. preparedRootProxyRoute, err := dynamicProxyRouter.PrepareProxyRoute(&rootRoutingEndpoint)
  353. if err != nil {
  354. utils.SendErrorResponse(w, "unable to prepare root routing: "+err.Error())
  355. return
  356. }
  357. err = dynamicProxyRouter.SetProxyRouteAsRoot(preparedRootProxyRoute)
  358. if err != nil {
  359. utils.SendErrorResponse(w, "unable to update default site: "+err.Error())
  360. return
  361. }
  362. proxyEndpointCreated = &rootRoutingEndpoint
  363. } else {
  364. //Invalid eptype
  365. utils.SendErrorResponse(w, "invalid endpoint type")
  366. return
  367. }
  368. //Save the config to file
  369. err = SaveReverseProxyConfig(proxyEndpointCreated)
  370. if err != nil {
  371. SystemWideLogger.PrintAndLog("Proxy", "Unable to save new proxy rule to file", err)
  372. return
  373. }
  374. //Update utm if exists
  375. UpdateUptimeMonitorTargets()
  376. utils.SendOK(w)
  377. }
  378. /*
  379. ReverseProxyHandleEditEndpoint handles proxy endpoint edit
  380. (host only, for root use Default Site page to edit)
  381. This endpoint do not handle basic auth credential update.
  382. The credential will be loaded from old config and reused
  383. */
  384. func ReverseProxyHandleEditEndpoint(w http.ResponseWriter, r *http.Request) {
  385. rootNameOrMatchingDomain, err := utils.PostPara(r, "rootname")
  386. if err != nil {
  387. utils.SendErrorResponse(w, "Target proxy rule not defined")
  388. return
  389. }
  390. tls, _ := utils.PostPara(r, "tls")
  391. if tls == "" {
  392. tls = "false"
  393. }
  394. useStickySession, _ := utils.PostBool(r, "ss")
  395. //Load bypass TLS option
  396. bpgtls, _ := utils.PostPara(r, "bpgtls")
  397. if bpgtls == "" {
  398. bpgtls = "false"
  399. }
  400. bypassGlobalTLS := (bpgtls == "true")
  401. // Basic Auth
  402. rba, _ := utils.PostPara(r, "bauth")
  403. if rba == "" {
  404. rba = "false"
  405. }
  406. requireBasicAuth := (rba == "true")
  407. // Rate Limiting?
  408. rl, _ := utils.PostPara(r, "rate")
  409. if rl == "" {
  410. rl = "false"
  411. }
  412. requireRateLimit := (rl == "true")
  413. rlnum, _ := utils.PostPara(r, "ratenum")
  414. if rlnum == "" {
  415. rlnum = "0"
  416. }
  417. proxyRateLimit, err := strconv.ParseInt(rlnum, 10, 64)
  418. if err != nil {
  419. utils.SendErrorResponse(w, "invalid rate limit number")
  420. return
  421. }
  422. if requireRateLimit && proxyRateLimit <= 0 {
  423. utils.SendErrorResponse(w, "rate limit number must be greater than 0")
  424. return
  425. } else if proxyRateLimit < 0 {
  426. proxyRateLimit = 1000
  427. }
  428. // Bypass WebSocket Origin Check
  429. /*
  430. strbpwsorg, _ := utils.PostPara(r, "bpwsorg")
  431. if strbpwsorg == "" {
  432. strbpwsorg = "false"
  433. }
  434. bypassWebsocketOriginCheck := (strbpwsorg == "true")
  435. */
  436. //Load the previous basic auth credentials from current proxy rules
  437. targetProxyEntry, err := dynamicProxyRouter.LoadProxy(rootNameOrMatchingDomain)
  438. if err != nil {
  439. utils.SendErrorResponse(w, "Target proxy config not found or could not be loaded")
  440. return
  441. }
  442. //Generate a new proxyEndpoint from the new config
  443. newProxyEndpoint := dynamicproxy.CopyEndpoint(targetProxyEntry)
  444. //TODO: Move these into dedicated module
  445. //newProxyEndpoint.Domain = endpoint
  446. //newProxyEndpoint.RequireTLS = useTLS
  447. //newProxyEndpoint.SkipCertValidations = skipTlsValidation
  448. //newProxyEndpoint.SkipWebSocketOriginCheck = bypassWebsocketOriginCheck
  449. newProxyEndpoint.BypassGlobalTLS = bypassGlobalTLS
  450. newProxyEndpoint.RequireBasicAuth = requireBasicAuth
  451. newProxyEndpoint.RequireRateLimit = requireRateLimit
  452. newProxyEndpoint.RateLimit = proxyRateLimit
  453. newProxyEndpoint.UseStickySession = useStickySession
  454. //Prepare to replace the current routing rule
  455. readyRoutingRule, err := dynamicProxyRouter.PrepareProxyRoute(newProxyEndpoint)
  456. if err != nil {
  457. utils.SendErrorResponse(w, err.Error())
  458. return
  459. }
  460. targetProxyEntry.Remove()
  461. dynamicProxyRouter.AddProxyRouteToRuntime(readyRoutingRule)
  462. //Save it to file
  463. SaveReverseProxyConfig(newProxyEndpoint)
  464. //Update uptime monitor
  465. UpdateUptimeMonitorTargets()
  466. utils.SendOK(w)
  467. }
  468. func ReverseProxyHandleAlias(w http.ResponseWriter, r *http.Request) {
  469. rootNameOrMatchingDomain, err := utils.PostPara(r, "ep")
  470. if err != nil {
  471. utils.SendErrorResponse(w, "Invalid ep given")
  472. return
  473. }
  474. //No need to check for type as root (/) can be set to default route
  475. //and hence, you will not need alias
  476. //Load the previous alias from current proxy rules
  477. targetProxyEntry, err := dynamicProxyRouter.LoadProxy(rootNameOrMatchingDomain)
  478. if err != nil {
  479. utils.SendErrorResponse(w, "Target proxy config not found or could not be loaded")
  480. return
  481. }
  482. newAliasJSON, err := utils.PostPara(r, "alias")
  483. if err != nil {
  484. //No new set of alias given
  485. utils.SendErrorResponse(w, "new alias not given")
  486. return
  487. }
  488. //Write new alias to runtime and file
  489. newAlias := []string{}
  490. err = json.Unmarshal([]byte(newAliasJSON), &newAlias)
  491. if err != nil {
  492. SystemWideLogger.PrintAndLog("Proxy", "Unable to parse new alias list", err)
  493. utils.SendErrorResponse(w, "Invalid alias list given")
  494. return
  495. }
  496. //Set the current alias
  497. newProxyEndpoint := dynamicproxy.CopyEndpoint(targetProxyEntry)
  498. newProxyEndpoint.MatchingDomainAlias = newAlias
  499. // Prepare to replace the current routing rule
  500. readyRoutingRule, err := dynamicProxyRouter.PrepareProxyRoute(newProxyEndpoint)
  501. if err != nil {
  502. utils.SendErrorResponse(w, err.Error())
  503. return
  504. }
  505. targetProxyEntry.Remove()
  506. dynamicProxyRouter.AddProxyRouteToRuntime(readyRoutingRule)
  507. // Save it to file
  508. err = SaveReverseProxyConfig(newProxyEndpoint)
  509. if err != nil {
  510. utils.SendErrorResponse(w, "Alias update failed")
  511. SystemWideLogger.PrintAndLog("Proxy", "Unable to save alias update", err)
  512. }
  513. utils.SendOK(w)
  514. }
  515. func DeleteProxyEndpoint(w http.ResponseWriter, r *http.Request) {
  516. ep, err := utils.GetPara(r, "ep")
  517. if err != nil {
  518. utils.SendErrorResponse(w, "Invalid ep given")
  519. return
  520. }
  521. //Remove the config from runtime
  522. err = dynamicProxyRouter.RemoveProxyEndpointByRootname(ep)
  523. if err != nil {
  524. utils.SendErrorResponse(w, err.Error())
  525. return
  526. }
  527. //Remove the config from file
  528. err = RemoveReverseProxyConfig(ep)
  529. if err != nil {
  530. utils.SendErrorResponse(w, err.Error())
  531. return
  532. }
  533. //Update utm if exists
  534. if uptimeMonitor != nil {
  535. uptimeMonitor.Config.Targets = GetUptimeTargetsFromReverseProxyRules(dynamicProxyRouter)
  536. uptimeMonitor.CleanRecords()
  537. }
  538. //Update uptime monitor
  539. UpdateUptimeMonitorTargets()
  540. utils.SendOK(w)
  541. }
  542. /*
  543. Handle update request for basic auth credential
  544. Require paramter: ep (Endpoint) and pytype (proxy Type)
  545. if request with GET, the handler will return current credentials
  546. on this endpoint by its username
  547. if request is POST, the handler will write the results to proxy config
  548. */
  549. func UpdateProxyBasicAuthCredentials(w http.ResponseWriter, r *http.Request) {
  550. if r.Method == http.MethodGet {
  551. ep, err := utils.GetPara(r, "ep")
  552. if err != nil {
  553. utils.SendErrorResponse(w, "Invalid ep given")
  554. return
  555. }
  556. //Load the target proxy object from router
  557. targetProxy, err := dynamicProxyRouter.LoadProxy(ep)
  558. if err != nil {
  559. utils.SendErrorResponse(w, err.Error())
  560. return
  561. }
  562. usernames := []string{}
  563. for _, cred := range targetProxy.BasicAuthCredentials {
  564. usernames = append(usernames, cred.Username)
  565. }
  566. js, _ := json.Marshal(usernames)
  567. utils.SendJSONResponse(w, string(js))
  568. } else if r.Method == http.MethodPost {
  569. //Write to target
  570. ep, err := utils.PostPara(r, "ep")
  571. if err != nil {
  572. utils.SendErrorResponse(w, "Invalid ep given")
  573. return
  574. }
  575. creds, err := utils.PostPara(r, "creds")
  576. if err != nil {
  577. utils.SendErrorResponse(w, "Invalid ptype given")
  578. return
  579. }
  580. //Load the target proxy object from router
  581. targetProxy, err := dynamicProxyRouter.LoadProxy(ep)
  582. if err != nil {
  583. utils.SendErrorResponse(w, err.Error())
  584. return
  585. }
  586. //Try to marshal the content of creds into the suitable structure
  587. newCredentials := []*dynamicproxy.BasicAuthUnhashedCredentials{}
  588. err = json.Unmarshal([]byte(creds), &newCredentials)
  589. if err != nil {
  590. utils.SendErrorResponse(w, "Malformed credential data")
  591. return
  592. }
  593. //Merge the credentials into the original config
  594. //If a new username exists in old config with no pw given, keep the old pw hash
  595. //If a new username is found with new password, hash it and push to credential slice
  596. mergedCredentials := []*dynamicproxy.BasicAuthCredentials{}
  597. for _, credential := range newCredentials {
  598. if credential.Password == "" {
  599. //Check if exists in the old credential files
  600. keepUnchange := false
  601. for _, oldCredEntry := range targetProxy.BasicAuthCredentials {
  602. if oldCredEntry.Username == credential.Username {
  603. //Exists! Reuse the old hash
  604. mergedCredentials = append(mergedCredentials, &dynamicproxy.BasicAuthCredentials{
  605. Username: oldCredEntry.Username,
  606. PasswordHash: oldCredEntry.PasswordHash,
  607. })
  608. keepUnchange = true
  609. }
  610. }
  611. if !keepUnchange {
  612. //This is a new username with no pw given
  613. utils.SendErrorResponse(w, "Access password for "+credential.Username+" is empty!")
  614. return
  615. }
  616. } else {
  617. //This username have given password
  618. mergedCredentials = append(mergedCredentials, &dynamicproxy.BasicAuthCredentials{
  619. Username: credential.Username,
  620. PasswordHash: auth.Hash(credential.Password),
  621. })
  622. }
  623. }
  624. targetProxy.BasicAuthCredentials = mergedCredentials
  625. //Save it to file
  626. SaveReverseProxyConfig(targetProxy)
  627. //Replace runtime configuration
  628. targetProxy.UpdateToRuntime()
  629. utils.SendOK(w)
  630. } else {
  631. http.Error(w, "invalid usage", http.StatusMethodNotAllowed)
  632. }
  633. }
  634. // List, Update or Remove the exception paths for basic auth.
  635. func ListProxyBasicAuthExceptionPaths(w http.ResponseWriter, r *http.Request) {
  636. if r.Method != http.MethodGet {
  637. http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
  638. }
  639. ep, err := utils.GetPara(r, "ep")
  640. if err != nil {
  641. utils.SendErrorResponse(w, "Invalid ep given")
  642. return
  643. }
  644. //Load the target proxy object from router
  645. targetProxy, err := dynamicProxyRouter.LoadProxy(ep)
  646. if err != nil {
  647. utils.SendErrorResponse(w, err.Error())
  648. return
  649. }
  650. //List all the exception paths for this proxy
  651. results := targetProxy.BasicAuthExceptionRules
  652. if results == nil {
  653. //It is a config from a really old version of zoraxy. Overwrite it with empty array
  654. results = []*dynamicproxy.BasicAuthExceptionRule{}
  655. }
  656. js, _ := json.Marshal(results)
  657. utils.SendJSONResponse(w, string(js))
  658. return
  659. }
  660. func AddProxyBasicAuthExceptionPaths(w http.ResponseWriter, r *http.Request) {
  661. ep, err := utils.PostPara(r, "ep")
  662. if err != nil {
  663. utils.SendErrorResponse(w, "Invalid ep given")
  664. return
  665. }
  666. matchingPrefix, err := utils.PostPara(r, "prefix")
  667. if err != nil {
  668. utils.SendErrorResponse(w, "Invalid matching prefix given")
  669. return
  670. }
  671. //Load the target proxy object from router
  672. targetProxy, err := dynamicProxyRouter.LoadProxy(ep)
  673. if err != nil {
  674. utils.SendErrorResponse(w, err.Error())
  675. return
  676. }
  677. //Check if the prefix starts with /. If not, prepend it
  678. if !strings.HasPrefix(matchingPrefix, "/") {
  679. matchingPrefix = "/" + matchingPrefix
  680. }
  681. //Add a new exception rule if it is not already exists
  682. alreadyExists := false
  683. for _, thisExceptionRule := range targetProxy.BasicAuthExceptionRules {
  684. if thisExceptionRule.PathPrefix == matchingPrefix {
  685. alreadyExists = true
  686. break
  687. }
  688. }
  689. if alreadyExists {
  690. utils.SendErrorResponse(w, "This matching path already exists")
  691. return
  692. }
  693. targetProxy.BasicAuthExceptionRules = append(targetProxy.BasicAuthExceptionRules, &dynamicproxy.BasicAuthExceptionRule{
  694. PathPrefix: strings.TrimSpace(matchingPrefix),
  695. })
  696. //Save configs to runtime and file
  697. targetProxy.UpdateToRuntime()
  698. SaveReverseProxyConfig(targetProxy)
  699. utils.SendOK(w)
  700. }
  701. func RemoveProxyBasicAuthExceptionPaths(w http.ResponseWriter, r *http.Request) {
  702. // Delete a rule
  703. ep, err := utils.PostPara(r, "ep")
  704. if err != nil {
  705. utils.SendErrorResponse(w, "Invalid ep given")
  706. return
  707. }
  708. matchingPrefix, err := utils.PostPara(r, "prefix")
  709. if err != nil {
  710. utils.SendErrorResponse(w, "Invalid matching prefix given")
  711. return
  712. }
  713. // Load the target proxy object from router
  714. targetProxy, err := dynamicProxyRouter.LoadProxy(ep)
  715. if err != nil {
  716. utils.SendErrorResponse(w, err.Error())
  717. return
  718. }
  719. newExceptionRuleList := []*dynamicproxy.BasicAuthExceptionRule{}
  720. matchingExists := false
  721. for _, thisExceptionalRule := range targetProxy.BasicAuthExceptionRules {
  722. if thisExceptionalRule.PathPrefix != matchingPrefix {
  723. newExceptionRuleList = append(newExceptionRuleList, thisExceptionalRule)
  724. } else {
  725. matchingExists = true
  726. }
  727. }
  728. if !matchingExists {
  729. utils.SendErrorResponse(w, "target matching rule not exists")
  730. return
  731. }
  732. targetProxy.BasicAuthExceptionRules = newExceptionRuleList
  733. // Save configs to runtime and file
  734. targetProxy.UpdateToRuntime()
  735. SaveReverseProxyConfig(targetProxy)
  736. utils.SendOK(w)
  737. }
  738. // Report the current status of the reverse proxy server
  739. func ReverseProxyStatus(w http.ResponseWriter, r *http.Request) {
  740. js, _ := json.Marshal(dynamicProxyRouter)
  741. utils.SendJSONResponse(w, string(js))
  742. }
  743. // Toggle a certain rule on and off
  744. func ReverseProxyToggleRuleSet(w http.ResponseWriter, r *http.Request) {
  745. //No need to check for type as root cannot be turned off
  746. ep, err := utils.PostPara(r, "ep")
  747. if err != nil {
  748. utils.SendErrorResponse(w, "invalid ep given")
  749. return
  750. }
  751. targetProxyRule, err := dynamicProxyRouter.LoadProxy(ep)
  752. if err != nil {
  753. utils.SendErrorResponse(w, "invalid endpoint given")
  754. return
  755. }
  756. enableStr, err := utils.PostPara(r, "enable")
  757. if err != nil {
  758. enableStr = "true"
  759. }
  760. //Flip the enable and disabled tag state
  761. ruleDisabled := enableStr == "false"
  762. targetProxyRule.Disabled = ruleDisabled
  763. err = SaveReverseProxyConfig(targetProxyRule)
  764. if err != nil {
  765. utils.SendErrorResponse(w, "unable to save updated rule")
  766. return
  767. }
  768. utils.SendOK(w)
  769. }
  770. func ReverseProxyListDetail(w http.ResponseWriter, r *http.Request) {
  771. eptype, err := utils.PostPara(r, "type") //Support root and host
  772. if err != nil {
  773. utils.SendErrorResponse(w, "type not defined")
  774. return
  775. }
  776. if eptype == "host" {
  777. epname, err := utils.PostPara(r, "epname")
  778. if err != nil {
  779. utils.SendErrorResponse(w, "epname not defined")
  780. return
  781. }
  782. endpointRaw, ok := dynamicProxyRouter.ProxyEndpoints.Load(epname)
  783. if !ok {
  784. utils.SendErrorResponse(w, "proxy rule not found")
  785. return
  786. }
  787. targetEndpoint := dynamicproxy.CopyEndpoint(endpointRaw.(*dynamicproxy.ProxyEndpoint))
  788. js, _ := json.Marshal(targetEndpoint)
  789. utils.SendJSONResponse(w, string(js))
  790. } else if eptype == "root" {
  791. js, _ := json.Marshal(dynamicProxyRouter.Root)
  792. utils.SendJSONResponse(w, string(js))
  793. } else {
  794. utils.SendErrorResponse(w, "Invalid type given")
  795. }
  796. }
  797. func ReverseProxyList(w http.ResponseWriter, r *http.Request) {
  798. eptype, err := utils.PostPara(r, "type") //Support root and host
  799. if err != nil {
  800. utils.SendErrorResponse(w, "type not defined")
  801. return
  802. }
  803. if eptype == "host" {
  804. results := []*dynamicproxy.ProxyEndpoint{}
  805. dynamicProxyRouter.ProxyEndpoints.Range(func(key, value interface{}) bool {
  806. thisEndpoint := dynamicproxy.CopyEndpoint(value.(*dynamicproxy.ProxyEndpoint))
  807. //Clear the auth passwords before showing to front-end
  808. cleanedCredentials := []*dynamicproxy.BasicAuthCredentials{}
  809. for _, user := range thisEndpoint.BasicAuthCredentials {
  810. cleanedCredentials = append(cleanedCredentials, &dynamicproxy.BasicAuthCredentials{
  811. Username: user.Username,
  812. PasswordHash: "",
  813. })
  814. }
  815. thisEndpoint.BasicAuthCredentials = cleanedCredentials
  816. results = append(results, thisEndpoint)
  817. return true
  818. })
  819. sort.Slice(results, func(i, j int) bool {
  820. return results[i].RootOrMatchingDomain < results[j].RootOrMatchingDomain
  821. })
  822. js, _ := json.Marshal(results)
  823. utils.SendJSONResponse(w, string(js))
  824. } else if eptype == "root" {
  825. js, _ := json.Marshal(dynamicProxyRouter.Root)
  826. utils.SendJSONResponse(w, string(js))
  827. } else {
  828. utils.SendErrorResponse(w, "Invalid type given")
  829. }
  830. }
  831. // Handle port 80 incoming traffics
  832. func HandleUpdatePort80Listener(w http.ResponseWriter, r *http.Request) {
  833. enabled, err := utils.GetPara(r, "enable")
  834. if err != nil {
  835. //Load the current status
  836. currentEnabled := false
  837. err = sysdb.Read("settings", "listenP80", &currentEnabled)
  838. if err != nil {
  839. utils.SendErrorResponse(w, err.Error())
  840. return
  841. }
  842. js, _ := json.Marshal(currentEnabled)
  843. utils.SendJSONResponse(w, string(js))
  844. } else {
  845. if enabled == "true" {
  846. sysdb.Write("settings", "listenP80", true)
  847. SystemWideLogger.Println("Enabling port 80 listener")
  848. dynamicProxyRouter.UpdatePort80ListenerState(true)
  849. } else if enabled == "false" {
  850. sysdb.Write("settings", "listenP80", false)
  851. SystemWideLogger.Println("Disabling port 80 listener")
  852. dynamicProxyRouter.UpdatePort80ListenerState(false)
  853. } else {
  854. utils.SendErrorResponse(w, "invalid mode given: "+enabled)
  855. }
  856. utils.SendOK(w)
  857. }
  858. }
  859. // Handle https redirect
  860. func HandleUpdateHttpsRedirect(w http.ResponseWriter, r *http.Request) {
  861. useRedirect, err := utils.GetPara(r, "set")
  862. if err != nil {
  863. currentRedirectToHttps := false
  864. //Load the current status
  865. err = sysdb.Read("settings", "redirect", &currentRedirectToHttps)
  866. if err != nil {
  867. utils.SendErrorResponse(w, err.Error())
  868. return
  869. }
  870. js, _ := json.Marshal(currentRedirectToHttps)
  871. utils.SendJSONResponse(w, string(js))
  872. } else {
  873. if dynamicProxyRouter.Option.Port == 80 {
  874. utils.SendErrorResponse(w, "This option is not available when listening on port 80")
  875. return
  876. }
  877. if useRedirect == "true" {
  878. sysdb.Write("settings", "redirect", true)
  879. SystemWideLogger.Println("Updating force HTTPS redirection to true")
  880. dynamicProxyRouter.UpdateHttpToHttpsRedirectSetting(true)
  881. } else if useRedirect == "false" {
  882. sysdb.Write("settings", "redirect", false)
  883. SystemWideLogger.Println("Updating force HTTPS redirection to false")
  884. dynamicProxyRouter.UpdateHttpToHttpsRedirectSetting(false)
  885. }
  886. utils.SendOK(w)
  887. }
  888. }
  889. // Handle checking if the current user is accessing via the reverse proxied interface
  890. // Of the management interface.
  891. func HandleManagementProxyCheck(w http.ResponseWriter, r *http.Request) {
  892. isProxied := dynamicProxyRouter.IsProxiedSubdomain(r)
  893. js, _ := json.Marshal(isProxied)
  894. utils.SendJSONResponse(w, string(js))
  895. }
  896. func HandleDevelopmentModeChange(w http.ResponseWriter, r *http.Request) {
  897. enableDevelopmentModeStr, err := utils.GetPara(r, "enable")
  898. if err != nil {
  899. //Load the current development mode toggle state
  900. js, _ := json.Marshal(dynamicProxyRouter.Option.NoCache)
  901. utils.SendJSONResponse(w, string(js))
  902. } else {
  903. //Write changes to runtime
  904. enableDevelopmentMode := false
  905. if enableDevelopmentModeStr == "true" {
  906. enableDevelopmentMode = true
  907. }
  908. //Write changes to runtime
  909. dynamicProxyRouter.Option.NoCache = enableDevelopmentMode
  910. //Write changes to database
  911. sysdb.Write("settings", "devMode", enableDevelopmentMode)
  912. utils.SendOK(w)
  913. }
  914. }
  915. // Handle incoming port set. Change the current proxy incoming port
  916. func HandleIncomingPortSet(w http.ResponseWriter, r *http.Request) {
  917. newIncomingPort, err := utils.PostPara(r, "incoming")
  918. if err != nil {
  919. utils.SendErrorResponse(w, "invalid incoming port given")
  920. return
  921. }
  922. newIncomingPortInt, err := strconv.Atoi(newIncomingPort)
  923. if err != nil {
  924. utils.SendErrorResponse(w, "Invalid incoming port given")
  925. return
  926. }
  927. rootProxyTargetOrigin := ""
  928. if len(dynamicProxyRouter.Root.ActiveOrigins) > 0 {
  929. rootProxyTargetOrigin = dynamicProxyRouter.Root.ActiveOrigins[0].OriginIpOrDomain
  930. }
  931. //Check if it is identical as proxy root (recursion!)
  932. if dynamicProxyRouter.Root == nil || rootProxyTargetOrigin == "" {
  933. //Check if proxy root is set before checking recursive listen
  934. //Fixing issue #43
  935. utils.SendErrorResponse(w, "Set Proxy Root before changing inbound port")
  936. return
  937. }
  938. proxyRoot := strings.TrimSuffix(rootProxyTargetOrigin, "/")
  939. if strings.EqualFold(proxyRoot, "localhost:"+strconv.Itoa(newIncomingPortInt)) || strings.EqualFold(proxyRoot, "127.0.0.1:"+strconv.Itoa(newIncomingPortInt)) {
  940. //Listening port is same as proxy root
  941. //Not allow recursive settings
  942. utils.SendErrorResponse(w, "Recursive listening port! Check your proxy root settings.")
  943. return
  944. }
  945. //Stop and change the setting of the reverse proxy service
  946. if dynamicProxyRouter.Running {
  947. dynamicProxyRouter.StopProxyService()
  948. dynamicProxyRouter.Option.Port = newIncomingPortInt
  949. dynamicProxyRouter.StartProxyService()
  950. } else {
  951. //Only change setting but not starting the proxy service
  952. dynamicProxyRouter.Option.Port = newIncomingPortInt
  953. }
  954. sysdb.Write("settings", "inbound", newIncomingPortInt)
  955. utils.SendOK(w)
  956. }
  957. /* Handle Custom Header Rules */
  958. //List all the custom header defined in this proxy rule
  959. func HandleCustomHeaderList(w http.ResponseWriter, r *http.Request) {
  960. epType, err := utils.PostPara(r, "type")
  961. if err != nil {
  962. utils.SendErrorResponse(w, "endpoint type not defined")
  963. return
  964. }
  965. domain, err := utils.PostPara(r, "domain")
  966. if err != nil {
  967. utils.SendErrorResponse(w, "domain or matching rule not defined")
  968. return
  969. }
  970. var targetProxyEndpoint *dynamicproxy.ProxyEndpoint
  971. if epType == "root" {
  972. targetProxyEndpoint = dynamicProxyRouter.Root
  973. } else {
  974. ep, err := dynamicProxyRouter.LoadProxy(domain)
  975. if err != nil {
  976. utils.SendErrorResponse(w, "target endpoint not exists")
  977. return
  978. }
  979. targetProxyEndpoint = ep
  980. }
  981. //List all custom headers
  982. customHeaderList := targetProxyEndpoint.UserDefinedHeaders
  983. if customHeaderList == nil {
  984. customHeaderList = []*dynamicproxy.UserDefinedHeader{}
  985. }
  986. js, _ := json.Marshal(customHeaderList)
  987. utils.SendJSONResponse(w, string(js))
  988. }
  989. // Add a new header to the target endpoint
  990. func HandleCustomHeaderAdd(w http.ResponseWriter, r *http.Request) {
  991. rewriteType, err := utils.PostPara(r, "type")
  992. if err != nil {
  993. utils.SendErrorResponse(w, "rewriteType not defined")
  994. return
  995. }
  996. domain, err := utils.PostPara(r, "domain")
  997. if err != nil {
  998. utils.SendErrorResponse(w, "domain or matching rule not defined")
  999. return
  1000. }
  1001. direction, err := utils.PostPara(r, "direction")
  1002. if err != nil {
  1003. utils.SendErrorResponse(w, "HTTP modifiy direction not set")
  1004. return
  1005. }
  1006. name, err := utils.PostPara(r, "name")
  1007. if err != nil {
  1008. utils.SendErrorResponse(w, "HTTP header name not set")
  1009. return
  1010. }
  1011. value, err := utils.PostPara(r, "value")
  1012. if err != nil && rewriteType == "add" {
  1013. utils.SendErrorResponse(w, "HTTP header value not set")
  1014. return
  1015. }
  1016. targetProxyEndpoint, err := dynamicProxyRouter.LoadProxy(domain)
  1017. if err != nil {
  1018. utils.SendErrorResponse(w, "target endpoint not exists")
  1019. return
  1020. }
  1021. //Create a Custom Header Defination type
  1022. var rewriteDirection dynamicproxy.HeaderDirection
  1023. if direction == "toOrigin" {
  1024. rewriteDirection = dynamicproxy.HeaderDirection_ZoraxyToUpstream
  1025. } else if direction == "toClient" {
  1026. rewriteDirection = dynamicproxy.HeaderDirection_ZoraxyToDownstream
  1027. } else {
  1028. //Unknown direction
  1029. utils.SendErrorResponse(w, "header rewrite direction not supported")
  1030. return
  1031. }
  1032. isRemove := false
  1033. if rewriteType == "remove" {
  1034. isRemove = true
  1035. }
  1036. headerRewriteDefination := dynamicproxy.UserDefinedHeader{
  1037. Key: name,
  1038. Value: value,
  1039. Direction: rewriteDirection,
  1040. IsRemove: isRemove,
  1041. }
  1042. //Create a new custom header object
  1043. err = targetProxyEndpoint.AddUserDefinedHeader(&headerRewriteDefination)
  1044. if err != nil {
  1045. utils.SendErrorResponse(w, "unable to add header rewrite rule: "+err.Error())
  1046. return
  1047. }
  1048. //Save it (no need reload as header are not handled by dpcore)
  1049. err = SaveReverseProxyConfig(targetProxyEndpoint)
  1050. if err != nil {
  1051. utils.SendErrorResponse(w, "unable to save update")
  1052. return
  1053. }
  1054. utils.SendOK(w)
  1055. }
  1056. // Remove a header from the target endpoint
  1057. func HandleCustomHeaderRemove(w http.ResponseWriter, r *http.Request) {
  1058. domain, err := utils.PostPara(r, "domain")
  1059. if err != nil {
  1060. utils.SendErrorResponse(w, "domain or matching rule not defined")
  1061. return
  1062. }
  1063. name, err := utils.PostPara(r, "name")
  1064. if err != nil {
  1065. utils.SendErrorResponse(w, "HTTP header name not set")
  1066. return
  1067. }
  1068. targetProxyEndpoint, err := dynamicProxyRouter.LoadProxy(domain)
  1069. if err != nil {
  1070. utils.SendErrorResponse(w, "target endpoint not exists")
  1071. return
  1072. }
  1073. err = targetProxyEndpoint.RemoveUserDefinedHeader(name)
  1074. if err != nil {
  1075. utils.SendErrorResponse(w, "unable to remove header rewrite rule: "+err.Error())
  1076. return
  1077. }
  1078. err = SaveReverseProxyConfig(targetProxyEndpoint)
  1079. if err != nil {
  1080. utils.SendErrorResponse(w, "unable to save update")
  1081. return
  1082. }
  1083. utils.SendOK(w)
  1084. }
  1085. // Handle view or edit HSTS states
  1086. func HandleHSTSState(w http.ResponseWriter, r *http.Request) {
  1087. domain, err := utils.PostPara(r, "domain")
  1088. if err != nil {
  1089. domain, err = utils.GetPara(r, "domain")
  1090. if err != nil {
  1091. utils.SendErrorResponse(w, "domain or matching rule not defined")
  1092. return
  1093. }
  1094. }
  1095. targetProxyEndpoint, err := dynamicProxyRouter.LoadProxy(domain)
  1096. if err != nil {
  1097. utils.SendErrorResponse(w, "target endpoint not exists")
  1098. return
  1099. }
  1100. if r.Method == http.MethodGet {
  1101. //Return current HSTS enable state
  1102. hstsAge := targetProxyEndpoint.HSTSMaxAge
  1103. js, _ := json.Marshal(hstsAge)
  1104. utils.SendJSONResponse(w, string(js))
  1105. return
  1106. } else if r.Method == http.MethodPost {
  1107. newMaxAge, err := utils.PostInt(r, "maxage")
  1108. if err != nil {
  1109. utils.SendErrorResponse(w, "maxage not defeined")
  1110. return
  1111. }
  1112. if newMaxAge == 0 || newMaxAge >= 31536000 {
  1113. targetProxyEndpoint.HSTSMaxAge = int64(newMaxAge)
  1114. SaveReverseProxyConfig(targetProxyEndpoint)
  1115. targetProxyEndpoint.UpdateToRuntime()
  1116. } else {
  1117. utils.SendErrorResponse(w, "invalid max age given")
  1118. return
  1119. }
  1120. utils.SendOK(w)
  1121. return
  1122. }
  1123. http.Error(w, "405 - Method not allowed", http.StatusMethodNotAllowed)
  1124. }
  1125. // HandlePermissionPolicy handle read or write to permission policy
  1126. func HandlePermissionPolicy(w http.ResponseWriter, r *http.Request) {
  1127. domain, err := utils.PostPara(r, "domain")
  1128. if err != nil {
  1129. domain, err = utils.GetPara(r, "domain")
  1130. if err != nil {
  1131. utils.SendErrorResponse(w, "domain or matching rule not defined")
  1132. return
  1133. }
  1134. }
  1135. targetProxyEndpoint, err := dynamicProxyRouter.LoadProxy(domain)
  1136. if err != nil {
  1137. utils.SendErrorResponse(w, "target endpoint not exists")
  1138. return
  1139. }
  1140. if r.Method == http.MethodGet {
  1141. type CurrentPolicyState struct {
  1142. PPEnabled bool
  1143. CurrentPolicy *permissionpolicy.PermissionsPolicy
  1144. }
  1145. currentPolicy := permissionpolicy.GetDefaultPermissionPolicy()
  1146. if targetProxyEndpoint.PermissionPolicy != nil {
  1147. currentPolicy = targetProxyEndpoint.PermissionPolicy
  1148. }
  1149. result := CurrentPolicyState{
  1150. PPEnabled: targetProxyEndpoint.EnablePermissionPolicyHeader,
  1151. CurrentPolicy: currentPolicy,
  1152. }
  1153. js, _ := json.Marshal(result)
  1154. utils.SendJSONResponse(w, string(js))
  1155. return
  1156. } else if r.Method == http.MethodPost {
  1157. //Update the enable state of permission policy
  1158. enableState, err := utils.PostBool(r, "enable")
  1159. if err != nil {
  1160. utils.SendErrorResponse(w, "invalid enable state given")
  1161. return
  1162. }
  1163. targetProxyEndpoint.EnablePermissionPolicyHeader = enableState
  1164. SaveReverseProxyConfig(targetProxyEndpoint)
  1165. targetProxyEndpoint.UpdateToRuntime()
  1166. utils.SendOK(w)
  1167. return
  1168. } else if r.Method == http.MethodPut {
  1169. //Store the new permission policy
  1170. newPermissionPolicyJSONString, err := utils.PostPara(r, "pp")
  1171. if err != nil {
  1172. utils.SendErrorResponse(w, "missing pp (permission policy) paramter")
  1173. return
  1174. }
  1175. //Parse the permission policy from JSON string
  1176. newPermissionPolicy := permissionpolicy.GetDefaultPermissionPolicy()
  1177. err = json.Unmarshal([]byte(newPermissionPolicyJSONString), &newPermissionPolicy)
  1178. if err != nil {
  1179. utils.SendErrorResponse(w, "permission policy parse error: "+err.Error())
  1180. return
  1181. }
  1182. //Save it to file
  1183. targetProxyEndpoint.PermissionPolicy = newPermissionPolicy
  1184. SaveReverseProxyConfig(targetProxyEndpoint)
  1185. targetProxyEndpoint.UpdateToRuntime()
  1186. utils.SendOK(w)
  1187. return
  1188. }
  1189. http.Error(w, "405 - Method not allowed", http.StatusMethodNotAllowed)
  1190. }