geodb.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. 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. sysdb: sysdb,
  51. }, nil
  52. }
  53. func (s *Store) ToggleBlacklist(enabled bool) {
  54. s.sysdb.Write("blacklist", "enabled", enabled)
  55. s.Enabled = enabled
  56. }
  57. func (s *Store) ResolveCountryCodeFromIP(ipstring string) (*CountryInfo, error) {
  58. cc := s.search(ipstring)
  59. return &CountryInfo{
  60. CountryIsoCode: cc,
  61. ContinetCode: "",
  62. }, nil
  63. }
  64. func (s *Store) Close() {
  65. }
  66. func (s *Store) AddCountryCodeToBlackList(countryCode string) {
  67. countryCode = strings.ToLower(countryCode)
  68. s.sysdb.Write("blacklist-cn", countryCode, true)
  69. }
  70. func (s *Store) RemoveCountryCodeFromBlackList(countryCode string) {
  71. countryCode = strings.ToLower(countryCode)
  72. s.sysdb.Delete("blacklist-cn", countryCode)
  73. }
  74. func (s *Store) IsCountryCodeBlacklisted(countryCode string) bool {
  75. countryCode = strings.ToLower(countryCode)
  76. var isBlacklisted bool = false
  77. s.sysdb.Read("blacklist-cn", countryCode, &isBlacklisted)
  78. return isBlacklisted
  79. }
  80. func (s *Store) GetAllBlacklistedCountryCode() []string {
  81. bannedCountryCodes := []string{}
  82. entries, err := s.sysdb.ListTable("blacklist-cn")
  83. if err != nil {
  84. return bannedCountryCodes
  85. }
  86. for _, keypairs := range entries {
  87. ip := string(keypairs[0])
  88. bannedCountryCodes = append(bannedCountryCodes, ip)
  89. }
  90. return bannedCountryCodes
  91. }
  92. func (s *Store) AddIPToBlackList(ipAddr string) {
  93. s.sysdb.Write("blacklist-ip", ipAddr, true)
  94. }
  95. func (s *Store) RemoveIPFromBlackList(ipAddr string) {
  96. s.sysdb.Delete("blacklist-ip", ipAddr)
  97. }
  98. func (s *Store) IsIPBlacklisted(ipAddr string) bool {
  99. var isBlacklisted bool = false
  100. s.sysdb.Read("blacklist-ip", ipAddr, &isBlacklisted)
  101. if isBlacklisted {
  102. return true
  103. }
  104. //Check for IP wildcard and CIRD rules
  105. AllBlacklistedIps := s.GetAllBlacklistedIp()
  106. for _, blacklistRule := range AllBlacklistedIps {
  107. wildcardMatch := MatchIpWildcard(ipAddr, blacklistRule)
  108. if wildcardMatch {
  109. return true
  110. }
  111. cidrMatch := MatchIpCIDR(ipAddr, blacklistRule)
  112. if cidrMatch {
  113. return true
  114. }
  115. }
  116. return false
  117. }
  118. func (s *Store) GetAllBlacklistedIp() []string {
  119. bannedIps := []string{}
  120. entries, err := s.sysdb.ListTable("blacklist-ip")
  121. if err != nil {
  122. return bannedIps
  123. }
  124. for _, keypairs := range entries {
  125. ip := string(keypairs[0])
  126. bannedIps = append(bannedIps, ip)
  127. }
  128. return bannedIps
  129. }
  130. // Check if a IP address is blacklisted, in either country or IP blacklist
  131. func (s *Store) IsBlacklisted(ipAddr string) bool {
  132. if !s.Enabled {
  133. //Blacklist not enabled. Always return false
  134. return false
  135. }
  136. if ipAddr == "" {
  137. //Unable to get the target IP address
  138. return false
  139. }
  140. countryCode, err := s.ResolveCountryCodeFromIP(ipAddr)
  141. if err != nil {
  142. return false
  143. }
  144. if s.IsCountryCodeBlacklisted(countryCode.CountryIsoCode) {
  145. return true
  146. }
  147. if s.IsIPBlacklisted(ipAddr) {
  148. return true
  149. }
  150. return false
  151. }
  152. func (s *Store) GetRequesterCountryISOCode(r *http.Request) string {
  153. ipAddr := GetRequesterIP(r)
  154. if ipAddr == "" {
  155. return ""
  156. }
  157. countryCode, err := s.ResolveCountryCodeFromIP(ipAddr)
  158. if err != nil {
  159. return ""
  160. }
  161. return countryCode.CountryIsoCode
  162. }
  163. // Utilities function
  164. func GetRequesterIP(r *http.Request) string {
  165. ip := r.Header.Get("X-Forwarded-For")
  166. if ip == "" {
  167. ip = r.Header.Get("X-Real-IP")
  168. if ip == "" {
  169. ip = strings.Split(r.RemoteAddr, ":")[0]
  170. }
  171. }
  172. return ip
  173. }
  174. // Match the IP address with a wildcard string
  175. func MatchIpWildcard(ipAddress, wildcard string) bool {
  176. // Split IP address and wildcard into octets
  177. ipOctets := strings.Split(ipAddress, ".")
  178. wildcardOctets := strings.Split(wildcard, ".")
  179. // Check that both have 4 octets
  180. if len(ipOctets) != 4 || len(wildcardOctets) != 4 {
  181. return false
  182. }
  183. // Check each octet to see if it matches the wildcard or is an exact match
  184. for i := 0; i < 4; i++ {
  185. if wildcardOctets[i] == "*" {
  186. continue
  187. }
  188. if ipOctets[i] != wildcardOctets[i] {
  189. return false
  190. }
  191. }
  192. return true
  193. }
  194. // Match ip address with CIDR
  195. func MatchIpCIDR(ip string, cidr string) bool {
  196. // parse the CIDR string
  197. _, cidrnet, err := net.ParseCIDR(cidr)
  198. if err != nil {
  199. return false
  200. }
  201. // parse the IP address
  202. ipAddr := net.ParseIP(ip)
  203. // check if the IP address is within the CIDR range
  204. return cidrnet.Contains(ipAddr)
  205. }