1
0

reverseproxy.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  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/uptime"
  13. "imuslab.com/zoraxy/mod/utils"
  14. )
  15. var (
  16. dynamicProxyRouter *dynamicproxy.Router
  17. )
  18. // Add user customizable reverse proxy
  19. func ReverseProxtInit() {
  20. /*
  21. Load Reverse Proxy Global Settings
  22. */
  23. inboundPort := 80
  24. if sysdb.KeyExists("settings", "inbound") {
  25. sysdb.Read("settings", "inbound", &inboundPort)
  26. SystemWideLogger.Println("Serving inbound port ", inboundPort)
  27. } else {
  28. SystemWideLogger.Println("Inbound port not set. Using default (80)")
  29. }
  30. useTls := false
  31. sysdb.Read("settings", "usetls", &useTls)
  32. if useTls {
  33. SystemWideLogger.Println("TLS mode enabled. Serving proxxy request with TLS")
  34. } else {
  35. SystemWideLogger.Println("TLS mode disabled. Serving proxy request with plain http")
  36. }
  37. forceLatestTLSVersion := false
  38. sysdb.Read("settings", "forceLatestTLS", &forceLatestTLSVersion)
  39. if forceLatestTLSVersion {
  40. SystemWideLogger.Println("Force latest TLS mode enabled. Minimum TLS LS version is set to v1.2")
  41. } else {
  42. SystemWideLogger.Println("Force latest TLS mode disabled. Minimum TLS version is set to v1.0")
  43. }
  44. listenOnPort80 := false
  45. sysdb.Read("settings", "listenP80", &listenOnPort80)
  46. if listenOnPort80 {
  47. SystemWideLogger.Println("Port 80 listener enabled")
  48. } else {
  49. SystemWideLogger.Println("Port 80 listener disabled")
  50. }
  51. forceHttpsRedirect := false
  52. sysdb.Read("settings", "redirect", &forceHttpsRedirect)
  53. if forceHttpsRedirect {
  54. SystemWideLogger.Println("Force HTTPS mode enabled")
  55. //Port 80 listener must be enabled to perform http -> https redirect
  56. listenOnPort80 = true
  57. } else {
  58. SystemWideLogger.Println("Force HTTPS mode disabled")
  59. }
  60. /*
  61. Create a new proxy object
  62. The DynamicProxy is the parent of all reverse proxy handlers,
  63. use for managemening and provide functions to access proxy handlers
  64. */
  65. dprouter, err := dynamicproxy.NewDynamicProxy(dynamicproxy.RouterOption{
  66. HostUUID: nodeUUID,
  67. Port: inboundPort,
  68. UseTls: useTls,
  69. ForceTLSLatest: forceLatestTLSVersion,
  70. ListenOnPort80: listenOnPort80,
  71. ForceHttpsRedirect: forceHttpsRedirect,
  72. TlsManager: tlsCertManager,
  73. RedirectRuleTable: redirectTable,
  74. GeodbStore: geodbStore,
  75. StatisticCollector: statisticCollector,
  76. WebDirectory: *staticWebServerRoot,
  77. })
  78. if err != nil {
  79. SystemWideLogger.PrintAndLog("Proxy", "Unable to create dynamic proxy router", err)
  80. return
  81. }
  82. dynamicProxyRouter = dprouter
  83. /*
  84. Load all conf from files
  85. */
  86. confs, _ := filepath.Glob("./conf/proxy/*.config")
  87. for _, conf := range confs {
  88. err := LoadReverseProxyConfig(conf)
  89. if err != nil {
  90. SystemWideLogger.PrintAndLog("Proxy", "Failed to load config file: "+filepath.Base(conf), err)
  91. return
  92. }
  93. }
  94. if dynamicProxyRouter.Root == nil {
  95. //Root config not set (new deployment?), use internal static web server as root
  96. defaultRootRouter, err := GetDefaultRootConfig()
  97. if err != nil {
  98. SystemWideLogger.PrintAndLog("Proxy", "Failed to generate default root routing", err)
  99. return
  100. }
  101. dynamicProxyRouter.SetProxyRouteAsRoot(defaultRootRouter)
  102. }
  103. //Start Service
  104. //Not sure why but delay must be added if you have another
  105. //reverse proxy server in front of this service
  106. time.Sleep(300 * time.Millisecond)
  107. dynamicProxyRouter.StartProxyService()
  108. SystemWideLogger.Println("Dynamic Reverse Proxy service started")
  109. //Add all proxy services to uptime monitor
  110. //Create a uptime monitor service
  111. go func() {
  112. //This must be done in go routine to prevent blocking on system startup
  113. uptimeMonitor, _ = uptime.NewUptimeMonitor(&uptime.Config{
  114. Targets: GetUptimeTargetsFromReverseProxyRules(dynamicProxyRouter),
  115. Interval: 300, //5 minutes
  116. MaxRecordsStore: 288, //1 day
  117. })
  118. SystemWideLogger.Println("Uptime Monitor background service started")
  119. }()
  120. }
  121. func ReverseProxyHandleOnOff(w http.ResponseWriter, r *http.Request) {
  122. enable, _ := utils.PostPara(r, "enable") //Support root, vdir and subd
  123. if enable == "true" {
  124. err := dynamicProxyRouter.StartProxyService()
  125. if err != nil {
  126. utils.SendErrorResponse(w, err.Error())
  127. return
  128. }
  129. } else {
  130. //Check if it is loopback
  131. if dynamicProxyRouter.IsProxiedSubdomain(r) {
  132. //Loopback routing. Turning it off will make the user lost control
  133. //of the whole system. Do not allow shutdown
  134. utils.SendErrorResponse(w, "Unable to shutdown in loopback rp mode. Remove proxy rules for management interface and retry.")
  135. return
  136. }
  137. err := dynamicProxyRouter.StopProxyService()
  138. if err != nil {
  139. utils.SendErrorResponse(w, err.Error())
  140. return
  141. }
  142. }
  143. utils.SendOK(w)
  144. }
  145. func ReverseProxyHandleAddEndpoint(w http.ResponseWriter, r *http.Request) {
  146. eptype, err := utils.PostPara(r, "type") //Support root and host
  147. if err != nil {
  148. utils.SendErrorResponse(w, "type not defined")
  149. return
  150. }
  151. endpoint, err := utils.PostPara(r, "ep")
  152. if err != nil {
  153. utils.SendErrorResponse(w, "endpoint not defined")
  154. return
  155. }
  156. tls, _ := utils.PostPara(r, "tls")
  157. if tls == "" {
  158. tls = "false"
  159. }
  160. useTLS := (tls == "true")
  161. bypassGlobalTLS, _ := utils.PostPara(r, "bypassGlobalTLS")
  162. if bypassGlobalTLS == "" {
  163. bypassGlobalTLS = "false"
  164. }
  165. useBypassGlobalTLS := bypassGlobalTLS == "true"
  166. stv, _ := utils.PostPara(r, "tlsval")
  167. if stv == "" {
  168. stv = "false"
  169. }
  170. skipTlsValidation := (stv == "true")
  171. rba, _ := utils.PostPara(r, "bauth")
  172. if rba == "" {
  173. rba = "false"
  174. }
  175. requireBasicAuth := (rba == "true")
  176. //Prase the basic auth to correct structure
  177. cred, _ := utils.PostPara(r, "cred")
  178. basicAuthCredentials := []*dynamicproxy.BasicAuthCredentials{}
  179. if requireBasicAuth {
  180. preProcessCredentials := []*dynamicproxy.BasicAuthUnhashedCredentials{}
  181. err = json.Unmarshal([]byte(cred), &preProcessCredentials)
  182. if err != nil {
  183. utils.SendErrorResponse(w, "invalid user credentials")
  184. return
  185. }
  186. //Check if there are empty password credentials
  187. for _, credObj := range preProcessCredentials {
  188. if strings.TrimSpace(credObj.Password) == "" {
  189. utils.SendErrorResponse(w, credObj.Username+" has empty password")
  190. return
  191. }
  192. }
  193. //Convert and hash the passwords
  194. for _, credObj := range preProcessCredentials {
  195. basicAuthCredentials = append(basicAuthCredentials, &dynamicproxy.BasicAuthCredentials{
  196. Username: credObj.Username,
  197. PasswordHash: auth.Hash(credObj.Password),
  198. })
  199. }
  200. }
  201. var proxyEndpointCreated *dynamicproxy.ProxyEndpoint
  202. if eptype == "host" {
  203. rootOrMatchingDomain, err := utils.PostPara(r, "rootname")
  204. if err != nil {
  205. utils.SendErrorResponse(w, "subdomain not defined")
  206. return
  207. }
  208. thisProxyEndpoint := dynamicproxy.ProxyEndpoint{
  209. //I/O
  210. ProxyType: dynamicproxy.ProxyType_Host,
  211. RootOrMatchingDomain: rootOrMatchingDomain,
  212. Domain: endpoint,
  213. //TLS
  214. RequireTLS: useTLS,
  215. BypassGlobalTLS: useBypassGlobalTLS,
  216. SkipCertValidations: skipTlsValidation,
  217. //VDir
  218. VirtualDirectories: []*dynamicproxy.ProxyEndpoint{},
  219. //Auth
  220. RequireBasicAuth: requireBasicAuth,
  221. BasicAuthCredentials: basicAuthCredentials,
  222. BasicAuthExceptionRules: []*dynamicproxy.BasicAuthExceptionRule{},
  223. DefaultSiteOption: 0,
  224. DefaultSiteValue: "",
  225. }
  226. preparedEndpoint, err := dynamicProxyRouter.PrepareProxyRoute(&thisProxyEndpoint)
  227. if err != nil {
  228. utils.SendErrorResponse(w, "unable to prepare proxy route to target endpoint: "+err.Error())
  229. return
  230. }
  231. dynamicProxyRouter.AddProxyRouteToRuntime(preparedEndpoint)
  232. proxyEndpointCreated = &thisProxyEndpoint
  233. } else if eptype == "root" {
  234. //Get the default site options and target
  235. dsOptString, err := utils.PostPara(r, "defaultSiteOpt")
  236. if err != nil {
  237. utils.SendErrorResponse(w, "default site action not defined")
  238. return
  239. }
  240. var defaultSiteOption int = 1
  241. opt, err := strconv.Atoi(dsOptString)
  242. if err != nil {
  243. utils.SendErrorResponse(w, "invalid default site option")
  244. return
  245. }
  246. defaultSiteOption = opt
  247. dsVal, err := utils.PostPara(r, "defaultSiteVal")
  248. if err != nil && (defaultSiteOption == 2 || defaultSiteOption == 3) {
  249. //Reverse proxy or redirect, must require value to be set
  250. utils.SendErrorResponse(w, "subdomain not defined")
  251. return
  252. }
  253. //Write the root options to file
  254. rootRoutingEndpoint := dynamicproxy.ProxyEndpoint{
  255. ProxyType: dynamicproxy.ProxyType_Root,
  256. RootOrMatchingDomain: "/",
  257. Domain: endpoint,
  258. RequireTLS: useTLS,
  259. BypassGlobalTLS: false,
  260. SkipCertValidations: false,
  261. DefaultSiteOption: defaultSiteOption,
  262. DefaultSiteValue: dsVal,
  263. }
  264. preparedRootProxyRoute, err := dynamicProxyRouter.PrepareProxyRoute(&rootRoutingEndpoint)
  265. if err != nil {
  266. utils.SendErrorResponse(w, "unable to prepare root routing: "+err.Error())
  267. return
  268. }
  269. dynamicProxyRouter.SetProxyRouteAsRoot(preparedRootProxyRoute)
  270. proxyEndpointCreated = &rootRoutingEndpoint
  271. } else {
  272. //Invalid eptype
  273. utils.SendErrorResponse(w, "invalid endpoint type")
  274. return
  275. }
  276. //Save the config to file
  277. err = SaveReverseProxyConfig(proxyEndpointCreated)
  278. if err != nil {
  279. SystemWideLogger.PrintAndLog("Proxy", "Unable to save new proxy rule to file", err)
  280. return
  281. }
  282. //Update utm if exists
  283. if uptimeMonitor != nil {
  284. uptimeMonitor.Config.Targets = GetUptimeTargetsFromReverseProxyRules(dynamicProxyRouter)
  285. uptimeMonitor.CleanRecords()
  286. }
  287. utils.SendOK(w)
  288. }
  289. /*
  290. ReverseProxyHandleEditEndpoint handles proxy endpoint edit
  291. (host only, for root use Default Site page to edit)
  292. This endpoint do not handle basic auth credential update.
  293. The credential will be loaded from old config and reused
  294. */
  295. func ReverseProxyHandleEditEndpoint(w http.ResponseWriter, r *http.Request) {
  296. rootNameOrMatchingDomain, err := utils.PostPara(r, "rootname")
  297. if err != nil {
  298. utils.SendErrorResponse(w, "Target proxy rule not defined")
  299. return
  300. }
  301. endpoint, err := utils.PostPara(r, "ep")
  302. if err != nil {
  303. utils.SendErrorResponse(w, "endpoint not defined")
  304. return
  305. }
  306. tls, _ := utils.PostPara(r, "tls")
  307. if tls == "" {
  308. tls = "false"
  309. }
  310. useTLS := (tls == "true")
  311. stv, _ := utils.PostPara(r, "tlsval")
  312. if stv == "" {
  313. stv = "false"
  314. }
  315. skipTlsValidation := (stv == "true")
  316. //Load bypass TLS option
  317. bpgtls, _ := utils.PostPara(r, "bpgtls")
  318. if bpgtls == "" {
  319. bpgtls = "false"
  320. }
  321. bypassGlobalTLS := (bpgtls == "true")
  322. rba, _ := utils.PostPara(r, "bauth")
  323. if rba == "" {
  324. rba = "false"
  325. }
  326. requireBasicAuth := (rba == "true")
  327. //Load the previous basic auth credentials from current proxy rules
  328. targetProxyEntry, err := dynamicProxyRouter.LoadProxy(rootNameOrMatchingDomain)
  329. if err != nil {
  330. utils.SendErrorResponse(w, "Target proxy config not found or could not be loaded")
  331. return
  332. }
  333. //Generate a new proxyEndpoint from the new config
  334. newProxyEndpoint := dynamicproxy.CopyEndpoint(targetProxyEntry)
  335. newProxyEndpoint.Domain = endpoint
  336. newProxyEndpoint.RequireTLS = useTLS
  337. newProxyEndpoint.BypassGlobalTLS = bypassGlobalTLS
  338. newProxyEndpoint.SkipCertValidations = skipTlsValidation
  339. newProxyEndpoint.RequireBasicAuth = requireBasicAuth
  340. //Prepare to replace the current routing rule
  341. readyRoutingRule, err := dynamicProxyRouter.PrepareProxyRoute(newProxyEndpoint)
  342. if err != nil {
  343. utils.SendErrorResponse(w, err.Error())
  344. return
  345. }
  346. targetProxyEntry.Remove()
  347. dynamicProxyRouter.AddProxyRouteToRuntime(readyRoutingRule)
  348. //Save it to file
  349. SaveReverseProxyConfig(newProxyEndpoint)
  350. //Update uptime monitor
  351. UpdateUptimeMonitorTargets()
  352. utils.SendOK(w)
  353. }
  354. func DeleteProxyEndpoint(w http.ResponseWriter, r *http.Request) {
  355. ep, err := utils.GetPara(r, "ep")
  356. if err != nil {
  357. utils.SendErrorResponse(w, "Invalid ep given")
  358. return
  359. }
  360. ptype, err := utils.PostPara(r, "ptype")
  361. if err != nil {
  362. utils.SendErrorResponse(w, "Invalid ptype given")
  363. return
  364. }
  365. //Remove the config from runtime
  366. err = dynamicProxyRouter.RemoveProxyEndpointByRootname(ptype, ep)
  367. if err != nil {
  368. utils.SendErrorResponse(w, err.Error())
  369. return
  370. }
  371. //Remove the config from file
  372. RemoveReverseProxyConfig(ep)
  373. //Update utm if exists
  374. if uptimeMonitor != nil {
  375. uptimeMonitor.Config.Targets = GetUptimeTargetsFromReverseProxyRules(dynamicProxyRouter)
  376. uptimeMonitor.CleanRecords()
  377. }
  378. //Update uptime monitor
  379. UpdateUptimeMonitorTargets()
  380. utils.SendOK(w)
  381. }
  382. /*
  383. Handle update request for basic auth credential
  384. Require paramter: ep (Endpoint) and pytype (proxy Type)
  385. if request with GET, the handler will return current credentials
  386. on this endpoint by its username
  387. if request is POST, the handler will write the results to proxy config
  388. */
  389. func UpdateProxyBasicAuthCredentials(w http.ResponseWriter, r *http.Request) {
  390. if r.Method == http.MethodGet {
  391. ep, err := utils.GetPara(r, "ep")
  392. if err != nil {
  393. utils.SendErrorResponse(w, "Invalid ep given")
  394. return
  395. }
  396. //Load the target proxy object from router
  397. targetProxy, err := dynamicProxyRouter.LoadProxy(ep)
  398. if err != nil {
  399. utils.SendErrorResponse(w, err.Error())
  400. return
  401. }
  402. usernames := []string{}
  403. for _, cred := range targetProxy.BasicAuthCredentials {
  404. usernames = append(usernames, cred.Username)
  405. }
  406. js, _ := json.Marshal(usernames)
  407. utils.SendJSONResponse(w, string(js))
  408. } else if r.Method == http.MethodPost {
  409. //Write to target
  410. ep, err := utils.PostPara(r, "ep")
  411. if err != nil {
  412. utils.SendErrorResponse(w, "Invalid ep given")
  413. return
  414. }
  415. creds, err := utils.PostPara(r, "creds")
  416. if err != nil {
  417. utils.SendErrorResponse(w, "Invalid ptype given")
  418. return
  419. }
  420. //Load the target proxy object from router
  421. targetProxy, err := dynamicProxyRouter.LoadProxy(ep)
  422. if err != nil {
  423. utils.SendErrorResponse(w, err.Error())
  424. return
  425. }
  426. //Try to marshal the content of creds into the suitable structure
  427. newCredentials := []*dynamicproxy.BasicAuthUnhashedCredentials{}
  428. err = json.Unmarshal([]byte(creds), &newCredentials)
  429. if err != nil {
  430. utils.SendErrorResponse(w, "Malformed credential data")
  431. return
  432. }
  433. //Merge the credentials into the original config
  434. //If a new username exists in old config with no pw given, keep the old pw hash
  435. //If a new username is found with new password, hash it and push to credential slice
  436. mergedCredentials := []*dynamicproxy.BasicAuthCredentials{}
  437. for _, credential := range newCredentials {
  438. if credential.Password == "" {
  439. //Check if exists in the old credential files
  440. keepUnchange := false
  441. for _, oldCredEntry := range targetProxy.BasicAuthCredentials {
  442. if oldCredEntry.Username == credential.Username {
  443. //Exists! Reuse the old hash
  444. mergedCredentials = append(mergedCredentials, &dynamicproxy.BasicAuthCredentials{
  445. Username: oldCredEntry.Username,
  446. PasswordHash: oldCredEntry.PasswordHash,
  447. })
  448. keepUnchange = true
  449. }
  450. }
  451. if !keepUnchange {
  452. //This is a new username with no pw given
  453. utils.SendErrorResponse(w, "Access password for "+credential.Username+" is empty!")
  454. return
  455. }
  456. } else {
  457. //This username have given password
  458. mergedCredentials = append(mergedCredentials, &dynamicproxy.BasicAuthCredentials{
  459. Username: credential.Username,
  460. PasswordHash: auth.Hash(credential.Password),
  461. })
  462. }
  463. }
  464. targetProxy.BasicAuthCredentials = mergedCredentials
  465. //Save it to file
  466. SaveReverseProxyConfig(targetProxy)
  467. //Replace runtime configuration
  468. targetProxy.UpdateToRuntime()
  469. utils.SendOK(w)
  470. } else {
  471. http.Error(w, "invalid usage", http.StatusMethodNotAllowed)
  472. }
  473. }
  474. // List, Update or Remove the exception paths for basic auth.
  475. func ListProxyBasicAuthExceptionPaths(w http.ResponseWriter, r *http.Request) {
  476. if r.Method != http.MethodGet {
  477. http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
  478. }
  479. ep, err := utils.GetPara(r, "ep")
  480. if err != nil {
  481. utils.SendErrorResponse(w, "Invalid ep given")
  482. return
  483. }
  484. //Load the target proxy object from router
  485. targetProxy, err := dynamicProxyRouter.LoadProxy(ep)
  486. if err != nil {
  487. utils.SendErrorResponse(w, err.Error())
  488. return
  489. }
  490. //List all the exception paths for this proxy
  491. results := targetProxy.BasicAuthExceptionRules
  492. if results == nil {
  493. //It is a config from a really old version of zoraxy. Overwrite it with empty array
  494. results = []*dynamicproxy.BasicAuthExceptionRule{}
  495. }
  496. js, _ := json.Marshal(results)
  497. utils.SendJSONResponse(w, string(js))
  498. return
  499. }
  500. func AddProxyBasicAuthExceptionPaths(w http.ResponseWriter, r *http.Request) {
  501. ep, err := utils.PostPara(r, "ep")
  502. if err != nil {
  503. utils.SendErrorResponse(w, "Invalid ep given")
  504. return
  505. }
  506. matchingPrefix, err := utils.PostPara(r, "prefix")
  507. if err != nil {
  508. utils.SendErrorResponse(w, "Invalid matching prefix given")
  509. return
  510. }
  511. //Load the target proxy object from router
  512. targetProxy, err := dynamicProxyRouter.LoadProxy(ep)
  513. if err != nil {
  514. utils.SendErrorResponse(w, err.Error())
  515. return
  516. }
  517. //Check if the prefix starts with /. If not, prepend it
  518. if !strings.HasPrefix(matchingPrefix, "/") {
  519. matchingPrefix = "/" + matchingPrefix
  520. }
  521. //Add a new exception rule if it is not already exists
  522. alreadyExists := false
  523. for _, thisExceptionRule := range targetProxy.BasicAuthExceptionRules {
  524. if thisExceptionRule.PathPrefix == matchingPrefix {
  525. alreadyExists = true
  526. break
  527. }
  528. }
  529. if alreadyExists {
  530. utils.SendErrorResponse(w, "This matching path already exists")
  531. return
  532. }
  533. targetProxy.BasicAuthExceptionRules = append(targetProxy.BasicAuthExceptionRules, &dynamicproxy.BasicAuthExceptionRule{
  534. PathPrefix: strings.TrimSpace(matchingPrefix),
  535. })
  536. //Save configs to runtime and file
  537. targetProxy.UpdateToRuntime()
  538. SaveReverseProxyConfig(targetProxy)
  539. utils.SendOK(w)
  540. }
  541. func RemoveProxyBasicAuthExceptionPaths(w http.ResponseWriter, r *http.Request) {
  542. // Delete a rule
  543. ep, err := utils.PostPara(r, "ep")
  544. if err != nil {
  545. utils.SendErrorResponse(w, "Invalid ep given")
  546. return
  547. }
  548. matchingPrefix, err := utils.PostPara(r, "prefix")
  549. if err != nil {
  550. utils.SendErrorResponse(w, "Invalid matching prefix given")
  551. return
  552. }
  553. // Load the target proxy object from router
  554. targetProxy, err := dynamicProxyRouter.LoadProxy(ep)
  555. if err != nil {
  556. utils.SendErrorResponse(w, err.Error())
  557. return
  558. }
  559. newExceptionRuleList := []*dynamicproxy.BasicAuthExceptionRule{}
  560. matchingExists := false
  561. for _, thisExceptionalRule := range targetProxy.BasicAuthExceptionRules {
  562. if thisExceptionalRule.PathPrefix != matchingPrefix {
  563. newExceptionRuleList = append(newExceptionRuleList, thisExceptionalRule)
  564. } else {
  565. matchingExists = true
  566. }
  567. }
  568. if !matchingExists {
  569. utils.SendErrorResponse(w, "target matching rule not exists")
  570. return
  571. }
  572. targetProxy.BasicAuthExceptionRules = newExceptionRuleList
  573. // Save configs to runtime and file
  574. targetProxy.UpdateToRuntime()
  575. SaveReverseProxyConfig(targetProxy)
  576. utils.SendOK(w)
  577. }
  578. func ReverseProxyStatus(w http.ResponseWriter, r *http.Request) {
  579. js, _ := json.Marshal(dynamicProxyRouter)
  580. utils.SendJSONResponse(w, string(js))
  581. }
  582. func ReverseProxyList(w http.ResponseWriter, r *http.Request) {
  583. eptype, err := utils.PostPara(r, "type") //Support root and host
  584. if err != nil {
  585. utils.SendErrorResponse(w, "type not defined")
  586. return
  587. }
  588. if eptype == "host" {
  589. results := []*dynamicproxy.ProxyEndpoint{}
  590. dynamicProxyRouter.ProxyEndpoints.Range(func(key, value interface{}) bool {
  591. thisEndpoint := value.(*dynamicproxy.ProxyEndpoint)
  592. //Clear the auth credentials before showing to front-end
  593. thisEndpoint.BasicAuthCredentials = []*dynamicproxy.BasicAuthCredentials{}
  594. results = append(results, thisEndpoint)
  595. return true
  596. })
  597. sort.Slice(results, func(i, j int) bool {
  598. return results[i].Domain < results[j].Domain
  599. })
  600. js, _ := json.Marshal(results)
  601. utils.SendJSONResponse(w, string(js))
  602. } else if eptype == "root" {
  603. js, _ := json.Marshal(dynamicProxyRouter.Root)
  604. utils.SendJSONResponse(w, string(js))
  605. } else {
  606. utils.SendErrorResponse(w, "Invalid type given")
  607. }
  608. }
  609. // Handle port 80 incoming traffics
  610. func HandleUpdatePort80Listener(w http.ResponseWriter, r *http.Request) {
  611. enabled, err := utils.GetPara(r, "enable")
  612. if err != nil {
  613. //Load the current status
  614. currentEnabled := false
  615. err = sysdb.Read("settings", "listenP80", &currentEnabled)
  616. if err != nil {
  617. utils.SendErrorResponse(w, err.Error())
  618. return
  619. }
  620. js, _ := json.Marshal(currentEnabled)
  621. utils.SendJSONResponse(w, string(js))
  622. } else {
  623. if enabled == "true" {
  624. sysdb.Write("settings", "listenP80", true)
  625. SystemWideLogger.Println("Enabling port 80 listener")
  626. dynamicProxyRouter.UpdatePort80ListenerState(true)
  627. } else if enabled == "false" {
  628. sysdb.Write("settings", "listenP80", false)
  629. SystemWideLogger.Println("Disabling port 80 listener")
  630. dynamicProxyRouter.UpdatePort80ListenerState(true)
  631. } else {
  632. utils.SendErrorResponse(w, "invalid mode given: "+enabled)
  633. }
  634. utils.SendOK(w)
  635. }
  636. }
  637. // Handle https redirect
  638. func HandleUpdateHttpsRedirect(w http.ResponseWriter, r *http.Request) {
  639. useRedirect, err := utils.GetPara(r, "set")
  640. if err != nil {
  641. currentRedirectToHttps := false
  642. //Load the current status
  643. err = sysdb.Read("settings", "redirect", &currentRedirectToHttps)
  644. if err != nil {
  645. utils.SendErrorResponse(w, err.Error())
  646. return
  647. }
  648. js, _ := json.Marshal(currentRedirectToHttps)
  649. utils.SendJSONResponse(w, string(js))
  650. } else {
  651. if dynamicProxyRouter.Option.Port == 80 {
  652. utils.SendErrorResponse(w, "This option is not available when listening on port 80")
  653. return
  654. }
  655. if useRedirect == "true" {
  656. sysdb.Write("settings", "redirect", true)
  657. SystemWideLogger.Println("Updating force HTTPS redirection to true")
  658. dynamicProxyRouter.UpdateHttpToHttpsRedirectSetting(true)
  659. } else if useRedirect == "false" {
  660. sysdb.Write("settings", "redirect", false)
  661. SystemWideLogger.Println("Updating force HTTPS redirection to false")
  662. dynamicProxyRouter.UpdateHttpToHttpsRedirectSetting(false)
  663. }
  664. utils.SendOK(w)
  665. }
  666. }
  667. // Handle checking if the current user is accessing via the reverse proxied interface
  668. // Of the management interface.
  669. func HandleManagementProxyCheck(w http.ResponseWriter, r *http.Request) {
  670. isProxied := dynamicProxyRouter.IsProxiedSubdomain(r)
  671. js, _ := json.Marshal(isProxied)
  672. utils.SendJSONResponse(w, string(js))
  673. }
  674. // Handle incoming port set. Change the current proxy incoming port
  675. func HandleIncomingPortSet(w http.ResponseWriter, r *http.Request) {
  676. newIncomingPort, err := utils.PostPara(r, "incoming")
  677. if err != nil {
  678. utils.SendErrorResponse(w, "invalid incoming port given")
  679. return
  680. }
  681. newIncomingPortInt, err := strconv.Atoi(newIncomingPort)
  682. if err != nil {
  683. utils.SendErrorResponse(w, "Invalid incoming port given")
  684. return
  685. }
  686. //Check if it is identical as proxy root (recursion!)
  687. if dynamicProxyRouter.Root == nil || dynamicProxyRouter.Root.Domain == "" {
  688. //Check if proxy root is set before checking recursive listen
  689. //Fixing issue #43
  690. utils.SendErrorResponse(w, "Set Proxy Root before changing inbound port")
  691. return
  692. }
  693. proxyRoot := strings.TrimSuffix(dynamicProxyRouter.Root.Domain, "/")
  694. if strings.HasPrefix(proxyRoot, "localhost:"+strconv.Itoa(newIncomingPortInt)) || strings.HasPrefix(proxyRoot, "127.0.0.1:"+strconv.Itoa(newIncomingPortInt)) {
  695. //Listening port is same as proxy root
  696. //Not allow recursive settings
  697. utils.SendErrorResponse(w, "Recursive listening port! Check your proxy root settings.")
  698. return
  699. }
  700. //Stop and change the setting of the reverse proxy service
  701. if dynamicProxyRouter.Running {
  702. dynamicProxyRouter.StopProxyService()
  703. dynamicProxyRouter.Option.Port = newIncomingPortInt
  704. dynamicProxyRouter.StartProxyService()
  705. } else {
  706. //Only change setting but not starting the proxy service
  707. dynamicProxyRouter.Option.Port = newIncomingPortInt
  708. }
  709. sysdb.Write("settings", "inbound", newIncomingPortInt)
  710. utils.SendOK(w)
  711. }