geodb.go 5.4 KB

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