1
0

reverseproxy.go 40 KB

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