reverseproxy.go 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371
  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. Origins: []*loadbalance.Upstream{
  280. {
  281. OriginIpOrDomain: endpoint,
  282. RequireTLS: useTLS,
  283. SkipCertValidations: skipTlsValidation,
  284. SkipWebSocketOriginCheck: bypassWebsocketOriginCheck,
  285. Priority: 0,
  286. },
  287. },
  288. UseStickySession: false, //TODO: Move options to webform
  289. //TLS
  290. BypassGlobalTLS: useBypassGlobalTLS,
  291. AccessFilterUUID: accessRuleID,
  292. //VDir
  293. VirtualDirectories: []*dynamicproxy.VirtualDirectoryEndpoint{},
  294. //Custom headers
  295. UserDefinedHeaders: []*dynamicproxy.UserDefinedHeader{},
  296. //Auth
  297. RequireBasicAuth: requireBasicAuth,
  298. BasicAuthCredentials: basicAuthCredentials,
  299. BasicAuthExceptionRules: []*dynamicproxy.BasicAuthExceptionRule{},
  300. DefaultSiteOption: 0,
  301. DefaultSiteValue: "",
  302. // Rate Limit
  303. RequireRateLimit: requireRateLimit,
  304. RateLimit: int64(proxyRateLimit),
  305. }
  306. preparedEndpoint, err := dynamicProxyRouter.PrepareProxyRoute(&thisProxyEndpoint)
  307. if err != nil {
  308. utils.SendErrorResponse(w, "unable to prepare proxy route to target endpoint: "+err.Error())
  309. return
  310. }
  311. dynamicProxyRouter.AddProxyRouteToRuntime(preparedEndpoint)
  312. proxyEndpointCreated = &thisProxyEndpoint
  313. } else if eptype == "root" {
  314. //Get the default site options and target
  315. dsOptString, err := utils.PostPara(r, "defaultSiteOpt")
  316. if err != nil {
  317. utils.SendErrorResponse(w, "default site action not defined")
  318. return
  319. }
  320. var defaultSiteOption int = 1
  321. opt, err := strconv.Atoi(dsOptString)
  322. if err != nil {
  323. utils.SendErrorResponse(w, "invalid default site option")
  324. return
  325. }
  326. defaultSiteOption = opt
  327. dsVal, err := utils.PostPara(r, "defaultSiteVal")
  328. if err != nil && (defaultSiteOption == 1 || defaultSiteOption == 2) {
  329. //Reverse proxy or redirect, must require value to be set
  330. utils.SendErrorResponse(w, "target not defined")
  331. return
  332. }
  333. //Write the root options to file
  334. rootRoutingEndpoint := dynamicproxy.ProxyEndpoint{
  335. ProxyType: dynamicproxy.ProxyType_Root,
  336. RootOrMatchingDomain: "/",
  337. Origins: []*loadbalance.Upstream{
  338. {
  339. OriginIpOrDomain: endpoint,
  340. RequireTLS: useTLS,
  341. SkipCertValidations: false,
  342. SkipWebSocketOriginCheck: true,
  343. Priority: 0,
  344. },
  345. },
  346. BypassGlobalTLS: false,
  347. DefaultSiteOption: defaultSiteOption,
  348. DefaultSiteValue: dsVal,
  349. }
  350. preparedRootProxyRoute, err := dynamicProxyRouter.PrepareProxyRoute(&rootRoutingEndpoint)
  351. if err != nil {
  352. utils.SendErrorResponse(w, "unable to prepare root routing: "+err.Error())
  353. return
  354. }
  355. dynamicProxyRouter.SetProxyRouteAsRoot(preparedRootProxyRoute)
  356. proxyEndpointCreated = &rootRoutingEndpoint
  357. } else {
  358. //Invalid eptype
  359. utils.SendErrorResponse(w, "invalid endpoint type")
  360. return
  361. }
  362. //Save the config to file
  363. err = SaveReverseProxyConfig(proxyEndpointCreated)
  364. if err != nil {
  365. SystemWideLogger.PrintAndLog("Proxy", "Unable to save new proxy rule to file", err)
  366. return
  367. }
  368. //Update utm if exists
  369. UpdateUptimeMonitorTargets()
  370. utils.SendOK(w)
  371. }
  372. /*
  373. ReverseProxyHandleEditEndpoint handles proxy endpoint edit
  374. (host only, for root use Default Site page to edit)
  375. This endpoint do not handle basic auth credential update.
  376. The credential will be loaded from old config and reused
  377. */
  378. func ReverseProxyHandleEditEndpoint(w http.ResponseWriter, r *http.Request) {
  379. rootNameOrMatchingDomain, err := utils.PostPara(r, "rootname")
  380. if err != nil {
  381. utils.SendErrorResponse(w, "Target proxy rule not defined")
  382. return
  383. }
  384. tls, _ := utils.PostPara(r, "tls")
  385. if tls == "" {
  386. tls = "false"
  387. }
  388. useStickySession, _ := utils.PostBool(r, "ss")
  389. //Load bypass TLS option
  390. bpgtls, _ := utils.PostPara(r, "bpgtls")
  391. if bpgtls == "" {
  392. bpgtls = "false"
  393. }
  394. bypassGlobalTLS := (bpgtls == "true")
  395. // Basic Auth
  396. rba, _ := utils.PostPara(r, "bauth")
  397. if rba == "" {
  398. rba = "false"
  399. }
  400. requireBasicAuth := (rba == "true")
  401. // Rate Limiting?
  402. rl, _ := utils.PostPara(r, "rate")
  403. if rl == "" {
  404. rl = "false"
  405. }
  406. requireRateLimit := (rl == "true")
  407. rlnum, _ := utils.PostPara(r, "ratenum")
  408. if rlnum == "" {
  409. rlnum = "0"
  410. }
  411. proxyRateLimit, err := strconv.ParseInt(rlnum, 10, 64)
  412. if err != nil {
  413. utils.SendErrorResponse(w, "invalid rate limit number")
  414. return
  415. }
  416. if requireRateLimit && proxyRateLimit <= 0 {
  417. utils.SendErrorResponse(w, "rate limit number must be greater than 0")
  418. return
  419. } else if proxyRateLimit < 0 {
  420. proxyRateLimit = 1000
  421. }
  422. // Bypass WebSocket Origin Check
  423. /*
  424. strbpwsorg, _ := utils.PostPara(r, "bpwsorg")
  425. if strbpwsorg == "" {
  426. strbpwsorg = "false"
  427. }
  428. bypassWebsocketOriginCheck := (strbpwsorg == "true")
  429. */
  430. //Load the previous basic auth credentials from current proxy rules
  431. targetProxyEntry, err := dynamicProxyRouter.LoadProxy(rootNameOrMatchingDomain)
  432. if err != nil {
  433. utils.SendErrorResponse(w, "Target proxy config not found or could not be loaded")
  434. return
  435. }
  436. //Generate a new proxyEndpoint from the new config
  437. newProxyEndpoint := dynamicproxy.CopyEndpoint(targetProxyEntry)
  438. //TODO: Move these into dedicated module
  439. //newProxyEndpoint.Domain = endpoint
  440. //newProxyEndpoint.RequireTLS = useTLS
  441. //newProxyEndpoint.SkipCertValidations = skipTlsValidation
  442. //newProxyEndpoint.SkipWebSocketOriginCheck = bypassWebsocketOriginCheck
  443. newProxyEndpoint.BypassGlobalTLS = bypassGlobalTLS
  444. newProxyEndpoint.RequireBasicAuth = requireBasicAuth
  445. newProxyEndpoint.RequireRateLimit = requireRateLimit
  446. newProxyEndpoint.RateLimit = proxyRateLimit
  447. newProxyEndpoint.UseStickySession = useStickySession
  448. //Prepare to replace the current routing rule
  449. readyRoutingRule, err := dynamicProxyRouter.PrepareProxyRoute(newProxyEndpoint)
  450. if err != nil {
  451. utils.SendErrorResponse(w, err.Error())
  452. return
  453. }
  454. targetProxyEntry.Remove()
  455. dynamicProxyRouter.AddProxyRouteToRuntime(readyRoutingRule)
  456. //Save it to file
  457. SaveReverseProxyConfig(newProxyEndpoint)
  458. //Update uptime monitor
  459. UpdateUptimeMonitorTargets()
  460. utils.SendOK(w)
  461. }
  462. func ReverseProxyHandleAlias(w http.ResponseWriter, r *http.Request) {
  463. rootNameOrMatchingDomain, err := utils.PostPara(r, "ep")
  464. if err != nil {
  465. utils.SendErrorResponse(w, "Invalid ep given")
  466. return
  467. }
  468. //No need to check for type as root (/) can be set to default route
  469. //and hence, you will not need alias
  470. //Load the previous alias from current proxy rules
  471. targetProxyEntry, err := dynamicProxyRouter.LoadProxy(rootNameOrMatchingDomain)
  472. if err != nil {
  473. utils.SendErrorResponse(w, "Target proxy config not found or could not be loaded")
  474. return
  475. }
  476. newAliasJSON, err := utils.PostPara(r, "alias")
  477. if err != nil {
  478. //No new set of alias given
  479. utils.SendErrorResponse(w, "new alias not given")
  480. return
  481. }
  482. //Write new alias to runtime and file
  483. newAlias := []string{}
  484. err = json.Unmarshal([]byte(newAliasJSON), &newAlias)
  485. if err != nil {
  486. SystemWideLogger.PrintAndLog("Proxy", "Unable to parse new alias list", err)
  487. utils.SendErrorResponse(w, "Invalid alias list given")
  488. return
  489. }
  490. //Set the current alias
  491. newProxyEndpoint := dynamicproxy.CopyEndpoint(targetProxyEntry)
  492. newProxyEndpoint.MatchingDomainAlias = newAlias
  493. // Prepare to replace the current routing rule
  494. readyRoutingRule, err := dynamicProxyRouter.PrepareProxyRoute(newProxyEndpoint)
  495. if err != nil {
  496. utils.SendErrorResponse(w, err.Error())
  497. return
  498. }
  499. targetProxyEntry.Remove()
  500. dynamicProxyRouter.AddProxyRouteToRuntime(readyRoutingRule)
  501. // Save it to file
  502. err = SaveReverseProxyConfig(newProxyEndpoint)
  503. if err != nil {
  504. utils.SendErrorResponse(w, "Alias update failed")
  505. SystemWideLogger.PrintAndLog("Proxy", "Unable to save alias update", err)
  506. }
  507. utils.SendOK(w)
  508. }
  509. func DeleteProxyEndpoint(w http.ResponseWriter, r *http.Request) {
  510. ep, err := utils.GetPara(r, "ep")
  511. if err != nil {
  512. utils.SendErrorResponse(w, "Invalid ep given")
  513. return
  514. }
  515. //Remove the config from runtime
  516. err = dynamicProxyRouter.RemoveProxyEndpointByRootname(ep)
  517. if err != nil {
  518. utils.SendErrorResponse(w, err.Error())
  519. return
  520. }
  521. //Remove the config from file
  522. err = RemoveReverseProxyConfig(ep)
  523. if err != nil {
  524. utils.SendErrorResponse(w, err.Error())
  525. return
  526. }
  527. //Update utm if exists
  528. if uptimeMonitor != nil {
  529. uptimeMonitor.Config.Targets = GetUptimeTargetsFromReverseProxyRules(dynamicProxyRouter)
  530. uptimeMonitor.CleanRecords()
  531. }
  532. //Update uptime monitor
  533. UpdateUptimeMonitorTargets()
  534. utils.SendOK(w)
  535. }
  536. /*
  537. Handle update request for basic auth credential
  538. Require paramter: ep (Endpoint) and pytype (proxy Type)
  539. if request with GET, the handler will return current credentials
  540. on this endpoint by its username
  541. if request is POST, the handler will write the results to proxy config
  542. */
  543. func UpdateProxyBasicAuthCredentials(w http.ResponseWriter, r *http.Request) {
  544. if r.Method == http.MethodGet {
  545. ep, err := utils.GetPara(r, "ep")
  546. if err != nil {
  547. utils.SendErrorResponse(w, "Invalid ep given")
  548. return
  549. }
  550. //Load the target proxy object from router
  551. targetProxy, err := dynamicProxyRouter.LoadProxy(ep)
  552. if err != nil {
  553. utils.SendErrorResponse(w, err.Error())
  554. return
  555. }
  556. usernames := []string{}
  557. for _, cred := range targetProxy.BasicAuthCredentials {
  558. usernames = append(usernames, cred.Username)
  559. }
  560. js, _ := json.Marshal(usernames)
  561. utils.SendJSONResponse(w, string(js))
  562. } else if r.Method == http.MethodPost {
  563. //Write to target
  564. ep, err := utils.PostPara(r, "ep")
  565. if err != nil {
  566. utils.SendErrorResponse(w, "Invalid ep given")
  567. return
  568. }
  569. creds, err := utils.PostPara(r, "creds")
  570. if err != nil {
  571. utils.SendErrorResponse(w, "Invalid ptype given")
  572. return
  573. }
  574. //Load the target proxy object from router
  575. targetProxy, err := dynamicProxyRouter.LoadProxy(ep)
  576. if err != nil {
  577. utils.SendErrorResponse(w, err.Error())
  578. return
  579. }
  580. //Try to marshal the content of creds into the suitable structure
  581. newCredentials := []*dynamicproxy.BasicAuthUnhashedCredentials{}
  582. err = json.Unmarshal([]byte(creds), &newCredentials)
  583. if err != nil {
  584. utils.SendErrorResponse(w, "Malformed credential data")
  585. return
  586. }
  587. //Merge the credentials into the original config
  588. //If a new username exists in old config with no pw given, keep the old pw hash
  589. //If a new username is found with new password, hash it and push to credential slice
  590. mergedCredentials := []*dynamicproxy.BasicAuthCredentials{}
  591. for _, credential := range newCredentials {
  592. if credential.Password == "" {
  593. //Check if exists in the old credential files
  594. keepUnchange := false
  595. for _, oldCredEntry := range targetProxy.BasicAuthCredentials {
  596. if oldCredEntry.Username == credential.Username {
  597. //Exists! Reuse the old hash
  598. mergedCredentials = append(mergedCredentials, &dynamicproxy.BasicAuthCredentials{
  599. Username: oldCredEntry.Username,
  600. PasswordHash: oldCredEntry.PasswordHash,
  601. })
  602. keepUnchange = true
  603. }
  604. }
  605. if !keepUnchange {
  606. //This is a new username with no pw given
  607. utils.SendErrorResponse(w, "Access password for "+credential.Username+" is empty!")
  608. return
  609. }
  610. } else {
  611. //This username have given password
  612. mergedCredentials = append(mergedCredentials, &dynamicproxy.BasicAuthCredentials{
  613. Username: credential.Username,
  614. PasswordHash: auth.Hash(credential.Password),
  615. })
  616. }
  617. }
  618. targetProxy.BasicAuthCredentials = mergedCredentials
  619. //Save it to file
  620. SaveReverseProxyConfig(targetProxy)
  621. //Replace runtime configuration
  622. targetProxy.UpdateToRuntime()
  623. utils.SendOK(w)
  624. } else {
  625. http.Error(w, "invalid usage", http.StatusMethodNotAllowed)
  626. }
  627. }
  628. // List, Update or Remove the exception paths for basic auth.
  629. func ListProxyBasicAuthExceptionPaths(w http.ResponseWriter, r *http.Request) {
  630. if r.Method != http.MethodGet {
  631. http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
  632. }
  633. ep, err := utils.GetPara(r, "ep")
  634. if err != nil {
  635. utils.SendErrorResponse(w, "Invalid ep given")
  636. return
  637. }
  638. //Load the target proxy object from router
  639. targetProxy, err := dynamicProxyRouter.LoadProxy(ep)
  640. if err != nil {
  641. utils.SendErrorResponse(w, err.Error())
  642. return
  643. }
  644. //List all the exception paths for this proxy
  645. results := targetProxy.BasicAuthExceptionRules
  646. if results == nil {
  647. //It is a config from a really old version of zoraxy. Overwrite it with empty array
  648. results = []*dynamicproxy.BasicAuthExceptionRule{}
  649. }
  650. js, _ := json.Marshal(results)
  651. utils.SendJSONResponse(w, string(js))
  652. return
  653. }
  654. func AddProxyBasicAuthExceptionPaths(w http.ResponseWriter, r *http.Request) {
  655. ep, err := utils.PostPara(r, "ep")
  656. if err != nil {
  657. utils.SendErrorResponse(w, "Invalid ep given")
  658. return
  659. }
  660. matchingPrefix, err := utils.PostPara(r, "prefix")
  661. if err != nil {
  662. utils.SendErrorResponse(w, "Invalid matching prefix given")
  663. return
  664. }
  665. //Load the target proxy object from router
  666. targetProxy, err := dynamicProxyRouter.LoadProxy(ep)
  667. if err != nil {
  668. utils.SendErrorResponse(w, err.Error())
  669. return
  670. }
  671. //Check if the prefix starts with /. If not, prepend it
  672. if !strings.HasPrefix(matchingPrefix, "/") {
  673. matchingPrefix = "/" + matchingPrefix
  674. }
  675. //Add a new exception rule if it is not already exists
  676. alreadyExists := false
  677. for _, thisExceptionRule := range targetProxy.BasicAuthExceptionRules {
  678. if thisExceptionRule.PathPrefix == matchingPrefix {
  679. alreadyExists = true
  680. break
  681. }
  682. }
  683. if alreadyExists {
  684. utils.SendErrorResponse(w, "This matching path already exists")
  685. return
  686. }
  687. targetProxy.BasicAuthExceptionRules = append(targetProxy.BasicAuthExceptionRules, &dynamicproxy.BasicAuthExceptionRule{
  688. PathPrefix: strings.TrimSpace(matchingPrefix),
  689. })
  690. //Save configs to runtime and file
  691. targetProxy.UpdateToRuntime()
  692. SaveReverseProxyConfig(targetProxy)
  693. utils.SendOK(w)
  694. }
  695. func RemoveProxyBasicAuthExceptionPaths(w http.ResponseWriter, r *http.Request) {
  696. // Delete a rule
  697. ep, err := utils.PostPara(r, "ep")
  698. if err != nil {
  699. utils.SendErrorResponse(w, "Invalid ep given")
  700. return
  701. }
  702. matchingPrefix, err := utils.PostPara(r, "prefix")
  703. if err != nil {
  704. utils.SendErrorResponse(w, "Invalid matching prefix given")
  705. return
  706. }
  707. // Load the target proxy object from router
  708. targetProxy, err := dynamicProxyRouter.LoadProxy(ep)
  709. if err != nil {
  710. utils.SendErrorResponse(w, err.Error())
  711. return
  712. }
  713. newExceptionRuleList := []*dynamicproxy.BasicAuthExceptionRule{}
  714. matchingExists := false
  715. for _, thisExceptionalRule := range targetProxy.BasicAuthExceptionRules {
  716. if thisExceptionalRule.PathPrefix != matchingPrefix {
  717. newExceptionRuleList = append(newExceptionRuleList, thisExceptionalRule)
  718. } else {
  719. matchingExists = true
  720. }
  721. }
  722. if !matchingExists {
  723. utils.SendErrorResponse(w, "target matching rule not exists")
  724. return
  725. }
  726. targetProxy.BasicAuthExceptionRules = newExceptionRuleList
  727. // Save configs to runtime and file
  728. targetProxy.UpdateToRuntime()
  729. SaveReverseProxyConfig(targetProxy)
  730. utils.SendOK(w)
  731. }
  732. // Report the current status of the reverse proxy server
  733. func ReverseProxyStatus(w http.ResponseWriter, r *http.Request) {
  734. js, _ := json.Marshal(dynamicProxyRouter)
  735. utils.SendJSONResponse(w, string(js))
  736. }
  737. // Toggle a certain rule on and off
  738. func ReverseProxyToggleRuleSet(w http.ResponseWriter, r *http.Request) {
  739. //No need to check for type as root cannot be turned off
  740. ep, err := utils.PostPara(r, "ep")
  741. if err != nil {
  742. utils.SendErrorResponse(w, "invalid ep given")
  743. return
  744. }
  745. targetProxyRule, err := dynamicProxyRouter.LoadProxy(ep)
  746. if err != nil {
  747. utils.SendErrorResponse(w, "invalid endpoint given")
  748. return
  749. }
  750. enableStr, err := utils.PostPara(r, "enable")
  751. if err != nil {
  752. enableStr = "true"
  753. }
  754. //Flip the enable and disabled tag state
  755. ruleDisabled := enableStr == "false"
  756. targetProxyRule.Disabled = ruleDisabled
  757. err = SaveReverseProxyConfig(targetProxyRule)
  758. if err != nil {
  759. utils.SendErrorResponse(w, "unable to save updated rule")
  760. return
  761. }
  762. utils.SendOK(w)
  763. }
  764. func ReverseProxyListDetail(w http.ResponseWriter, r *http.Request) {
  765. eptype, err := utils.PostPara(r, "type") //Support root and host
  766. if err != nil {
  767. utils.SendErrorResponse(w, "type not defined")
  768. return
  769. }
  770. if eptype == "host" {
  771. epname, err := utils.PostPara(r, "epname")
  772. if err != nil {
  773. utils.SendErrorResponse(w, "epname not defined")
  774. return
  775. }
  776. endpointRaw, ok := dynamicProxyRouter.ProxyEndpoints.Load(epname)
  777. if !ok {
  778. utils.SendErrorResponse(w, "proxy rule not found")
  779. return
  780. }
  781. targetEndpoint := dynamicproxy.CopyEndpoint(endpointRaw.(*dynamicproxy.ProxyEndpoint))
  782. js, _ := json.Marshal(targetEndpoint)
  783. utils.SendJSONResponse(w, string(js))
  784. } else if eptype == "root" {
  785. js, _ := json.Marshal(dynamicProxyRouter.Root)
  786. utils.SendJSONResponse(w, string(js))
  787. } else {
  788. utils.SendErrorResponse(w, "Invalid type given")
  789. }
  790. }
  791. func ReverseProxyList(w http.ResponseWriter, r *http.Request) {
  792. eptype, err := utils.PostPara(r, "type") //Support root and host
  793. if err != nil {
  794. utils.SendErrorResponse(w, "type not defined")
  795. return
  796. }
  797. if eptype == "host" {
  798. results := []*dynamicproxy.ProxyEndpoint{}
  799. dynamicProxyRouter.ProxyEndpoints.Range(func(key, value interface{}) bool {
  800. thisEndpoint := dynamicproxy.CopyEndpoint(value.(*dynamicproxy.ProxyEndpoint))
  801. //Clear the auth passwords before showing to front-end
  802. cleanedCredentials := []*dynamicproxy.BasicAuthCredentials{}
  803. for _, user := range thisEndpoint.BasicAuthCredentials {
  804. cleanedCredentials = append(cleanedCredentials, &dynamicproxy.BasicAuthCredentials{
  805. Username: user.Username,
  806. PasswordHash: "",
  807. })
  808. }
  809. thisEndpoint.BasicAuthCredentials = cleanedCredentials
  810. results = append(results, thisEndpoint)
  811. return true
  812. })
  813. sort.Slice(results, func(i, j int) bool {
  814. return results[i].RootOrMatchingDomain < results[j].RootOrMatchingDomain
  815. })
  816. js, _ := json.Marshal(results)
  817. utils.SendJSONResponse(w, string(js))
  818. } else if eptype == "root" {
  819. js, _ := json.Marshal(dynamicProxyRouter.Root)
  820. utils.SendJSONResponse(w, string(js))
  821. } else {
  822. utils.SendErrorResponse(w, "Invalid type given")
  823. }
  824. }
  825. // Handle port 80 incoming traffics
  826. func HandleUpdatePort80Listener(w http.ResponseWriter, r *http.Request) {
  827. enabled, err := utils.GetPara(r, "enable")
  828. if err != nil {
  829. //Load the current status
  830. currentEnabled := false
  831. err = sysdb.Read("settings", "listenP80", &currentEnabled)
  832. if err != nil {
  833. utils.SendErrorResponse(w, err.Error())
  834. return
  835. }
  836. js, _ := json.Marshal(currentEnabled)
  837. utils.SendJSONResponse(w, string(js))
  838. } else {
  839. if enabled == "true" {
  840. sysdb.Write("settings", "listenP80", true)
  841. SystemWideLogger.Println("Enabling port 80 listener")
  842. dynamicProxyRouter.UpdatePort80ListenerState(true)
  843. } else if enabled == "false" {
  844. sysdb.Write("settings", "listenP80", false)
  845. SystemWideLogger.Println("Disabling port 80 listener")
  846. dynamicProxyRouter.UpdatePort80ListenerState(false)
  847. } else {
  848. utils.SendErrorResponse(w, "invalid mode given: "+enabled)
  849. }
  850. utils.SendOK(w)
  851. }
  852. }
  853. // Handle https redirect
  854. func HandleUpdateHttpsRedirect(w http.ResponseWriter, r *http.Request) {
  855. useRedirect, err := utils.GetPara(r, "set")
  856. if err != nil {
  857. currentRedirectToHttps := false
  858. //Load the current status
  859. err = sysdb.Read("settings", "redirect", &currentRedirectToHttps)
  860. if err != nil {
  861. utils.SendErrorResponse(w, err.Error())
  862. return
  863. }
  864. js, _ := json.Marshal(currentRedirectToHttps)
  865. utils.SendJSONResponse(w, string(js))
  866. } else {
  867. if dynamicProxyRouter.Option.Port == 80 {
  868. utils.SendErrorResponse(w, "This option is not available when listening on port 80")
  869. return
  870. }
  871. if useRedirect == "true" {
  872. sysdb.Write("settings", "redirect", true)
  873. SystemWideLogger.Println("Updating force HTTPS redirection to true")
  874. dynamicProxyRouter.UpdateHttpToHttpsRedirectSetting(true)
  875. } else if useRedirect == "false" {
  876. sysdb.Write("settings", "redirect", false)
  877. SystemWideLogger.Println("Updating force HTTPS redirection to false")
  878. dynamicProxyRouter.UpdateHttpToHttpsRedirectSetting(false)
  879. }
  880. utils.SendOK(w)
  881. }
  882. }
  883. // Handle checking if the current user is accessing via the reverse proxied interface
  884. // Of the management interface.
  885. func HandleManagementProxyCheck(w http.ResponseWriter, r *http.Request) {
  886. isProxied := dynamicProxyRouter.IsProxiedSubdomain(r)
  887. js, _ := json.Marshal(isProxied)
  888. utils.SendJSONResponse(w, string(js))
  889. }
  890. func HandleDevelopmentModeChange(w http.ResponseWriter, r *http.Request) {
  891. enableDevelopmentModeStr, err := utils.GetPara(r, "enable")
  892. if err != nil {
  893. //Load the current development mode toggle state
  894. js, _ := json.Marshal(dynamicProxyRouter.Option.NoCache)
  895. utils.SendJSONResponse(w, string(js))
  896. } else {
  897. //Write changes to runtime
  898. enableDevelopmentMode := false
  899. if enableDevelopmentModeStr == "true" {
  900. enableDevelopmentMode = true
  901. }
  902. //Write changes to runtime
  903. dynamicProxyRouter.Option.NoCache = enableDevelopmentMode
  904. //Write changes to database
  905. sysdb.Write("settings", "devMode", enableDevelopmentMode)
  906. utils.SendOK(w)
  907. }
  908. }
  909. // Handle incoming port set. Change the current proxy incoming port
  910. func HandleIncomingPortSet(w http.ResponseWriter, r *http.Request) {
  911. newIncomingPort, err := utils.PostPara(r, "incoming")
  912. if err != nil {
  913. utils.SendErrorResponse(w, "invalid incoming port given")
  914. return
  915. }
  916. newIncomingPortInt, err := strconv.Atoi(newIncomingPort)
  917. if err != nil {
  918. utils.SendErrorResponse(w, "Invalid incoming port given")
  919. return
  920. }
  921. rootProxyTargetOrigin := ""
  922. if len(dynamicProxyRouter.Root.Origins) > 0 {
  923. rootProxyTargetOrigin = dynamicProxyRouter.Root.Origins[0].OriginIpOrDomain
  924. }
  925. //Check if it is identical as proxy root (recursion!)
  926. if dynamicProxyRouter.Root == nil || rootProxyTargetOrigin == "" {
  927. //Check if proxy root is set before checking recursive listen
  928. //Fixing issue #43
  929. utils.SendErrorResponse(w, "Set Proxy Root before changing inbound port")
  930. return
  931. }
  932. proxyRoot := strings.TrimSuffix(rootProxyTargetOrigin, "/")
  933. if strings.EqualFold(proxyRoot, "localhost:"+strconv.Itoa(newIncomingPortInt)) || strings.EqualFold(proxyRoot, "127.0.0.1:"+strconv.Itoa(newIncomingPortInt)) {
  934. //Listening port is same as proxy root
  935. //Not allow recursive settings
  936. utils.SendErrorResponse(w, "Recursive listening port! Check your proxy root settings.")
  937. return
  938. }
  939. //Stop and change the setting of the reverse proxy service
  940. if dynamicProxyRouter.Running {
  941. dynamicProxyRouter.StopProxyService()
  942. dynamicProxyRouter.Option.Port = newIncomingPortInt
  943. dynamicProxyRouter.StartProxyService()
  944. } else {
  945. //Only change setting but not starting the proxy service
  946. dynamicProxyRouter.Option.Port = newIncomingPortInt
  947. }
  948. sysdb.Write("settings", "inbound", newIncomingPortInt)
  949. utils.SendOK(w)
  950. }
  951. /* Handle Custom Header Rules */
  952. //List all the custom header defined in this proxy rule
  953. func HandleCustomHeaderList(w http.ResponseWriter, r *http.Request) {
  954. epType, err := utils.PostPara(r, "type")
  955. if err != nil {
  956. utils.SendErrorResponse(w, "endpoint type not defined")
  957. return
  958. }
  959. domain, err := utils.PostPara(r, "domain")
  960. if err != nil {
  961. utils.SendErrorResponse(w, "domain or matching rule not defined")
  962. return
  963. }
  964. var targetProxyEndpoint *dynamicproxy.ProxyEndpoint
  965. if epType == "root" {
  966. targetProxyEndpoint = dynamicProxyRouter.Root
  967. } else {
  968. ep, err := dynamicProxyRouter.LoadProxy(domain)
  969. if err != nil {
  970. utils.SendErrorResponse(w, "target endpoint not exists")
  971. return
  972. }
  973. targetProxyEndpoint = ep
  974. }
  975. //List all custom headers
  976. customHeaderList := targetProxyEndpoint.UserDefinedHeaders
  977. if customHeaderList == nil {
  978. customHeaderList = []*dynamicproxy.UserDefinedHeader{}
  979. }
  980. js, _ := json.Marshal(customHeaderList)
  981. utils.SendJSONResponse(w, string(js))
  982. }
  983. // Add a new header to the target endpoint
  984. func HandleCustomHeaderAdd(w http.ResponseWriter, r *http.Request) {
  985. rewriteType, err := utils.PostPara(r, "type")
  986. if err != nil {
  987. utils.SendErrorResponse(w, "rewriteType not defined")
  988. return
  989. }
  990. domain, err := utils.PostPara(r, "domain")
  991. if err != nil {
  992. utils.SendErrorResponse(w, "domain or matching rule not defined")
  993. return
  994. }
  995. direction, err := utils.PostPara(r, "direction")
  996. if err != nil {
  997. utils.SendErrorResponse(w, "HTTP modifiy direction not set")
  998. return
  999. }
  1000. name, err := utils.PostPara(r, "name")
  1001. if err != nil {
  1002. utils.SendErrorResponse(w, "HTTP header name not set")
  1003. return
  1004. }
  1005. value, err := utils.PostPara(r, "value")
  1006. if err != nil && rewriteType == "add" {
  1007. utils.SendErrorResponse(w, "HTTP header value not set")
  1008. return
  1009. }
  1010. targetProxyEndpoint, err := dynamicProxyRouter.LoadProxy(domain)
  1011. if err != nil {
  1012. utils.SendErrorResponse(w, "target endpoint not exists")
  1013. return
  1014. }
  1015. //Create a Custom Header Defination type
  1016. var rewriteDirection dynamicproxy.HeaderDirection
  1017. if direction == "toOrigin" {
  1018. rewriteDirection = dynamicproxy.HeaderDirection_ZoraxyToUpstream
  1019. } else if direction == "toClient" {
  1020. rewriteDirection = dynamicproxy.HeaderDirection_ZoraxyToDownstream
  1021. } else {
  1022. //Unknown direction
  1023. utils.SendErrorResponse(w, "header rewrite direction not supported")
  1024. return
  1025. }
  1026. isRemove := false
  1027. if rewriteType == "remove" {
  1028. isRemove = true
  1029. }
  1030. headerRewriteDefination := dynamicproxy.UserDefinedHeader{
  1031. Key: name,
  1032. Value: value,
  1033. Direction: rewriteDirection,
  1034. IsRemove: isRemove,
  1035. }
  1036. //Create a new custom header object
  1037. err = targetProxyEndpoint.AddUserDefinedHeader(&headerRewriteDefination)
  1038. if err != nil {
  1039. utils.SendErrorResponse(w, "unable to add header rewrite rule: "+err.Error())
  1040. return
  1041. }
  1042. //Save it (no need reload as header are not handled by dpcore)
  1043. err = SaveReverseProxyConfig(targetProxyEndpoint)
  1044. if err != nil {
  1045. utils.SendErrorResponse(w, "unable to save update")
  1046. return
  1047. }
  1048. utils.SendOK(w)
  1049. }
  1050. // Remove a header from the target endpoint
  1051. func HandleCustomHeaderRemove(w http.ResponseWriter, r *http.Request) {
  1052. domain, err := utils.PostPara(r, "domain")
  1053. if err != nil {
  1054. utils.SendErrorResponse(w, "domain or matching rule not defined")
  1055. return
  1056. }
  1057. name, err := utils.PostPara(r, "name")
  1058. if err != nil {
  1059. utils.SendErrorResponse(w, "HTTP header name not set")
  1060. return
  1061. }
  1062. targetProxyEndpoint, err := dynamicProxyRouter.LoadProxy(domain)
  1063. if err != nil {
  1064. utils.SendErrorResponse(w, "target endpoint not exists")
  1065. return
  1066. }
  1067. err = targetProxyEndpoint.RemoveUserDefinedHeader(name)
  1068. if err != nil {
  1069. utils.SendErrorResponse(w, "unable to remove header rewrite rule: "+err.Error())
  1070. return
  1071. }
  1072. err = SaveReverseProxyConfig(targetProxyEndpoint)
  1073. if err != nil {
  1074. utils.SendErrorResponse(w, "unable to save update")
  1075. return
  1076. }
  1077. utils.SendOK(w)
  1078. }
  1079. // Handle view or edit HSTS states
  1080. func HandleHSTSState(w http.ResponseWriter, r *http.Request) {
  1081. domain, err := utils.PostPara(r, "domain")
  1082. if err != nil {
  1083. domain, err = utils.GetPara(r, "domain")
  1084. if err != nil {
  1085. utils.SendErrorResponse(w, "domain or matching rule not defined")
  1086. return
  1087. }
  1088. }
  1089. targetProxyEndpoint, err := dynamicProxyRouter.LoadProxy(domain)
  1090. if err != nil {
  1091. utils.SendErrorResponse(w, "target endpoint not exists")
  1092. return
  1093. }
  1094. if r.Method == http.MethodGet {
  1095. //Return current HSTS enable state
  1096. hstsAge := targetProxyEndpoint.HSTSMaxAge
  1097. js, _ := json.Marshal(hstsAge)
  1098. utils.SendJSONResponse(w, string(js))
  1099. return
  1100. } else if r.Method == http.MethodPost {
  1101. newMaxAge, err := utils.PostInt(r, "maxage")
  1102. if err != nil {
  1103. utils.SendErrorResponse(w, "maxage not defeined")
  1104. return
  1105. }
  1106. if newMaxAge == 0 || newMaxAge >= 31536000 {
  1107. targetProxyEndpoint.HSTSMaxAge = int64(newMaxAge)
  1108. SaveReverseProxyConfig(targetProxyEndpoint)
  1109. targetProxyEndpoint.UpdateToRuntime()
  1110. } else {
  1111. utils.SendErrorResponse(w, "invalid max age given")
  1112. return
  1113. }
  1114. utils.SendOK(w)
  1115. return
  1116. }
  1117. http.Error(w, "405 - Method not allowed", http.StatusMethodNotAllowed)
  1118. }
  1119. // HandlePermissionPolicy handle read or write to permission policy
  1120. func HandlePermissionPolicy(w http.ResponseWriter, r *http.Request) {
  1121. domain, err := utils.PostPara(r, "domain")
  1122. if err != nil {
  1123. domain, err = utils.GetPara(r, "domain")
  1124. if err != nil {
  1125. utils.SendErrorResponse(w, "domain or matching rule not defined")
  1126. return
  1127. }
  1128. }
  1129. targetProxyEndpoint, err := dynamicProxyRouter.LoadProxy(domain)
  1130. if err != nil {
  1131. utils.SendErrorResponse(w, "target endpoint not exists")
  1132. return
  1133. }
  1134. if r.Method == http.MethodGet {
  1135. type CurrentPolicyState struct {
  1136. PPEnabled bool
  1137. CurrentPolicy *permissionpolicy.PermissionsPolicy
  1138. }
  1139. currentPolicy := permissionpolicy.GetDefaultPermissionPolicy()
  1140. if targetProxyEndpoint.PermissionPolicy != nil {
  1141. currentPolicy = targetProxyEndpoint.PermissionPolicy
  1142. }
  1143. result := CurrentPolicyState{
  1144. PPEnabled: targetProxyEndpoint.EnablePermissionPolicyHeader,
  1145. CurrentPolicy: currentPolicy,
  1146. }
  1147. js, _ := json.Marshal(result)
  1148. utils.SendJSONResponse(w, string(js))
  1149. return
  1150. } else if r.Method == http.MethodPost {
  1151. //Update the enable state of permission policy
  1152. enableState, err := utils.PostBool(r, "enable")
  1153. if err != nil {
  1154. utils.SendErrorResponse(w, "invalid enable state given")
  1155. return
  1156. }
  1157. targetProxyEndpoint.EnablePermissionPolicyHeader = enableState
  1158. SaveReverseProxyConfig(targetProxyEndpoint)
  1159. targetProxyEndpoint.UpdateToRuntime()
  1160. utils.SendOK(w)
  1161. return
  1162. } else if r.Method == http.MethodPut {
  1163. //Store the new permission policy
  1164. newPermissionPolicyJSONString, err := utils.PostPara(r, "pp")
  1165. if err != nil {
  1166. utils.SendErrorResponse(w, "missing pp (permission policy) paramter")
  1167. return
  1168. }
  1169. //Parse the permission policy from JSON string
  1170. newPermissionPolicy := permissionpolicy.GetDefaultPermissionPolicy()
  1171. err = json.Unmarshal([]byte(newPermissionPolicyJSONString), &newPermissionPolicy)
  1172. if err != nil {
  1173. utils.SendErrorResponse(w, "permission policy parse error: "+err.Error())
  1174. return
  1175. }
  1176. //Save it to file
  1177. targetProxyEndpoint.PermissionPolicy = newPermissionPolicy
  1178. SaveReverseProxyConfig(targetProxyEndpoint)
  1179. targetProxyEndpoint.UpdateToRuntime()
  1180. utils.SendOK(w)
  1181. return
  1182. }
  1183. http.Error(w, "405 - Method not allowed", http.StatusMethodNotAllowed)
  1184. }