From ddb8297bc3c6b1f0a6e64d82ec8825c6c19d4f00 Mon Sep 17 00:00:00 2001 From: aixiao Date: Tue, 29 Oct 2024 10:44:13 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9MD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .vscode/settings.json | 3 ++- README.md | 12 +++++++++--- cap.c | 21 ++++++++++----------- 3 files changed, 21 insertions(+), 15 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 9e9a0f5..49964e7 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -4,6 +4,7 @@ "common.h": "c", "prctl.h": "c", "algorithm": "c", - "cstdlib": "c" + "cstdlib": "c", + "libipset.h": "c" } } \ No newline at end of file diff --git a/README.md b/README.md index 5c83295..60fea37 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,14 @@ # denyip -大陆服务器禁止国外IP访问 +针对非国际业务的Linux服务器构建防火墙策略: -## build +利用 libpcap 抓取网络包,从中提取源IP地址。 +使用 libipset 实现IP黑名单管理,将不符合访问条件的IP添加至黑名单集合。 +结合 ip2region 库进行初步的IP地域判定,筛选大陆以外的IP地址。 +通过 Go ipquery 进一步精准识别IP地理位置,将确认的非大陆IP加入到 ipset 集合,严格限制非大陆来源的访问。 +此方案能有效保护大陆服务器免受非本地业务访问,提高访问控制的精度与效率。 + +## Build ~~~bash # Debian System @@ -22,7 +28,7 @@ gcc -g -Wall -Iip2region -o a.out cap.o common.o ip2region/ip2region.o ip2region root@NIUYULING:/mnt/c/Users/root/Desktop/git.aixiao.me/DenyIP# ~~~ -### help +### Help ~~~bash diff --git a/cap.c b/cap.c index eef4296..5e8897e 100644 --- a/cap.c +++ b/cap.c @@ -2,22 +2,20 @@ #include "common.h" #include "libipset.h" -#define CACHE_TTL 600 // 设定缓存的存活时间为 600 秒 (10 分钟) -#define MAX_CACHE_SIZE 100 // 缓存最多存储 100 个 IP 地址 - -struct ip_cache_node *ip_cache_head = NULL; // 缓存链表的头节点 -int cache_size = 0; // 当前缓存中的 IP 数量 - -pid_t pid = -1; +pid_t pid = -1; // 子进程全局PID #define SHM_SIZE 1024 // 共享内存大小 #define SHM_KEY 1234 // 共享内存键值 int shmid = -1; -int RULE_NAME_NUMBER = 0; -char *RULE_NAME = NULL; +int RULE_NAME_NUMBER = 0; // ipset 集合集合数 +char *RULE_NAME = NULL; // 共享内存 +char *ip2region_area = NULL; // ip2region 解析结果 +char *command_result = NULL; // 执行命令的结果 -char *ip2region_area = NULL; // ip2region 解析结果 -char *command_result = NULL; // 执行命令的结果 +#define CACHE_TTL 600 // 设定缓存的存活时间为 600 秒 (10 分钟) +#define MAX_CACHE_SIZE 100 // 缓存最多存储 100 个 IP 地址 +struct ip_cache_node *ip_cache_head = NULL; // 缓存链表的头节点 +int cache_size = 0; // 当前缓存中的 IP 数量 // 定义链表结构,用于缓存 IP 地址 struct ip_cache_node { @@ -26,6 +24,7 @@ struct ip_cache_node { struct ip_cache_node *next; // 指向下一个节点 }; + // 检查 IP 是否已在缓存中并是否过期 int is_ip_in_cache(const char *ip) {