1
0

geodb.go 5.6 KB

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