access.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package dynamicproxy
  2. import (
  3. "net/http"
  4. "os"
  5. "path/filepath"
  6. "imuslab.com/zoraxy/mod/access"
  7. "imuslab.com/zoraxy/mod/netutils"
  8. )
  9. // Handle access check (blacklist / whitelist), return true if request is handled (aka blocked)
  10. // if the return value is false, you can continue process the response writer
  11. func (h *ProxyHandler) handleAccessRouting(ruleID string, w http.ResponseWriter, r *http.Request) bool {
  12. accessRule, err := h.Parent.Option.AccessController.GetAccessRuleByID(ruleID)
  13. if err != nil {
  14. //Unable to load access rule. Target rule not found?
  15. h.Parent.Option.Logger.PrintAndLog("proxy-access", "Unable to load access rule: "+ruleID, err)
  16. w.WriteHeader(http.StatusInternalServerError)
  17. w.Write([]byte("500 - Internal Server Error"))
  18. return true
  19. }
  20. isBlocked, blockedReason := accessRequestBlocked(accessRule, h.Parent.Option.WebDirectory, w, r)
  21. if isBlocked {
  22. h.Parent.logRequest(r, false, 403, blockedReason, "")
  23. }
  24. return isBlocked
  25. }
  26. // Return boolean, return true if access is blocked
  27. // For string, it will return the blocked reason (if any)
  28. func accessRequestBlocked(accessRule *access.AccessRule, templateDirectory string, w http.ResponseWriter, r *http.Request) (bool, string) {
  29. //Check if this ip is in blacklist
  30. clientIpAddr := netutils.GetRequesterIP(r)
  31. if accessRule.IsBlacklisted(clientIpAddr) {
  32. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  33. w.WriteHeader(http.StatusForbidden)
  34. template, err := os.ReadFile(filepath.Join(templateDirectory, "templates/blacklist.html"))
  35. if err != nil {
  36. w.Write(page_forbidden)
  37. } else {
  38. w.Write(template)
  39. }
  40. return true, "blacklist"
  41. }
  42. //Check if this ip is in whitelist
  43. if !accessRule.IsWhitelisted(clientIpAddr) {
  44. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  45. w.WriteHeader(http.StatusForbidden)
  46. template, err := os.ReadFile(filepath.Join(templateDirectory, "templates/whitelist.html"))
  47. if err != nil {
  48. w.Write(page_forbidden)
  49. } else {
  50. w.Write(template)
  51. }
  52. return true, "whitelist"
  53. }
  54. //Not blocked.
  55. return false, ""
  56. }