geodb.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. package geodb
  2. import (
  3. _ "embed"
  4. "log"
  5. "net"
  6. "net/http"
  7. "strings"
  8. "imuslab.com/zoraxy/mod/database"
  9. )
  10. //go:embed geoipv4.csv
  11. var geoipv4 []byte //Original embedded csv file
  12. type Store struct {
  13. Enabled bool
  14. geodb [][]string //Parsed geodb list
  15. //geoipCache sync.Map
  16. geotrie *trie
  17. sysdb *database.Database
  18. }
  19. type CountryInfo struct {
  20. CountryIsoCode string
  21. ContinetCode string
  22. }
  23. func NewGeoDb(sysdb *database.Database) (*Store, error) {
  24. parsedGeoData, err := parseCSV(geoipv4)
  25. if err != nil {
  26. return nil, err
  27. }
  28. blacklistEnabled := false
  29. if sysdb != nil {
  30. err = sysdb.NewTable("blacklist-cn")
  31. if err != nil {
  32. return nil, err
  33. }
  34. err = sysdb.NewTable("blacklist-ip")
  35. if err != nil {
  36. return nil, err
  37. }
  38. err = sysdb.NewTable("blacklist")
  39. if err != nil {
  40. return nil, err
  41. }
  42. sysdb.Read("blacklist", "enabled", &blacklistEnabled)
  43. } else {
  44. log.Println("Database pointer set to nil: Entering debug mode")
  45. }
  46. return &Store{
  47. Enabled: blacklistEnabled,
  48. geodb: parsedGeoData,
  49. //geoipCache: sync.Map{},
  50. geotrie: constrctTrieTree(parsedGeoData),
  51. sysdb: sysdb,
  52. }, nil
  53. }
  54. func (s *Store) ToggleBlacklist(enabled bool) {
  55. s.sysdb.Write("blacklist", "enabled", enabled)
  56. s.Enabled = enabled
  57. }
  58. func (s *Store) ResolveCountryCodeFromIP(ipstring string) (*CountryInfo, error) {
  59. cc := s.search(ipstring)
  60. return &CountryInfo{
  61. CountryIsoCode: cc,
  62. ContinetCode: "",
  63. }, nil
  64. }
  65. func (s *Store) Close() {
  66. }
  67. func (s *Store) AddCountryCodeToBlackList(countryCode string) {
  68. countryCode = strings.ToLower(countryCode)
  69. s.sysdb.Write("blacklist-cn", countryCode, true)
  70. }
  71. func (s *Store) RemoveCountryCodeFromBlackList(countryCode string) {
  72. countryCode = strings.ToLower(countryCode)
  73. s.sysdb.Delete("blacklist-cn", countryCode)
  74. }
  75. func (s *Store) IsCountryCodeBlacklisted(countryCode string) bool {
  76. countryCode = strings.ToLower(countryCode)
  77. var isBlacklisted bool = false
  78. s.sysdb.Read("blacklist-cn", countryCode, &isBlacklisted)
  79. return isBlacklisted
  80. }
  81. func (s *Store) GetAllBlacklistedCountryCode() []string {
  82. bannedCountryCodes := []string{}
  83. entries, err := s.sysdb.ListTable("blacklist-cn")
  84. if err != nil {
  85. return bannedCountryCodes
  86. }
  87. for _, keypairs := range entries {
  88. ip := string(keypairs[0])
  89. bannedCountryCodes = append(bannedCountryCodes, ip)
  90. }
  91. return bannedCountryCodes
  92. }
  93. func (s *Store) AddIPToBlackList(ipAddr string) {
  94. s.sysdb.Write("blacklist-ip", ipAddr, true)
  95. }
  96. func (s *Store) RemoveIPFromBlackList(ipAddr string) {
  97. s.sysdb.Delete("blacklist-ip", ipAddr)
  98. }
  99. func (s *Store) IsIPBlacklisted(ipAddr string) bool {
  100. var isBlacklisted bool = false
  101. s.sysdb.Read("blacklist-ip", ipAddr, &isBlacklisted)
  102. if isBlacklisted {
  103. return true
  104. }
  105. //Check for IP wildcard and CIRD rules
  106. AllBlacklistedIps := s.GetAllBlacklistedIp()
  107. for _, blacklistRule := range AllBlacklistedIps {
  108. wildcardMatch := MatchIpWildcard(ipAddr, blacklistRule)
  109. if wildcardMatch {
  110. return true
  111. }
  112. cidrMatch := MatchIpCIDR(ipAddr, blacklistRule)
  113. if cidrMatch {
  114. return true
  115. }
  116. }
  117. return false
  118. }
  119. func (s *Store) GetAllBlacklistedIp() []string {
  120. bannedIps := []string{}
  121. entries, err := s.sysdb.ListTable("blacklist-ip")
  122. if err != nil {
  123. return bannedIps
  124. }
  125. for _, keypairs := range entries {
  126. ip := string(keypairs[0])
  127. bannedIps = append(bannedIps, ip)
  128. }
  129. return bannedIps
  130. }
  131. // Check if a IP address is blacklisted, in either country or IP blacklist
  132. func (s *Store) IsBlacklisted(ipAddr string) bool {
  133. if !s.Enabled {
  134. //Blacklist not enabled. Always return false
  135. return false
  136. }
  137. if ipAddr == "" {
  138. //Unable to get the target IP address
  139. return false
  140. }
  141. countryCode, err := s.ResolveCountryCodeFromIP(ipAddr)
  142. if err != nil {
  143. return false
  144. }
  145. if s.IsCountryCodeBlacklisted(countryCode.CountryIsoCode) {
  146. return true
  147. }
  148. if s.IsIPBlacklisted(ipAddr) {
  149. return true
  150. }
  151. return false
  152. }
  153. func (s *Store) GetRequesterCountryISOCode(r *http.Request) string {
  154. ipAddr := GetRequesterIP(r)
  155. if ipAddr == "" {
  156. return ""
  157. }
  158. countryCode, err := s.ResolveCountryCodeFromIP(ipAddr)
  159. if err != nil {
  160. return ""
  161. }
  162. return countryCode.CountryIsoCode
  163. }
  164. // Utilities function
  165. func GetRequesterIP(r *http.Request) string {
  166. ip := r.Header.Get("X-Forwarded-For")
  167. if ip == "" {
  168. ip = r.Header.Get("X-Real-IP")
  169. if ip == "" {
  170. ip = strings.Split(r.RemoteAddr, ":")[0]
  171. }
  172. }
  173. return ip
  174. }
  175. // Match the IP address with a wildcard string
  176. func MatchIpWildcard(ipAddress, wildcard string) bool {
  177. // Split IP address and wildcard into octets
  178. ipOctets := strings.Split(ipAddress, ".")
  179. wildcardOctets := strings.Split(wildcard, ".")
  180. // Check that both have 4 octets
  181. if len(ipOctets) != 4 || len(wildcardOctets) != 4 {
  182. return false
  183. }
  184. // Check each octet to see if it matches the wildcard or is an exact match
  185. for i := 0; i < 4; i++ {
  186. if wildcardOctets[i] == "*" {
  187. continue
  188. }
  189. if ipOctets[i] != wildcardOctets[i] {
  190. return false
  191. }
  192. }
  193. return true
  194. }
  195. // Match ip address with CIDR
  196. func MatchIpCIDR(ip string, cidr string) bool {
  197. // parse the CIDR string
  198. _, cidrnet, err := net.ParseCIDR(cidr)
  199. if err != nil {
  200. return false
  201. }
  202. // parse the IP address
  203. ipAddr := net.ParseIP(ip)
  204. // check if the IP address is within the CIDR range
  205. return cidrnet.Contains(ipAddr)
  206. }