This commit is contained in:
2024-10-29 10:44:13 +08:00
parent 6569e7e577
commit ddb8297bc3
3 changed files with 21 additions and 15 deletions

View File

@@ -4,6 +4,7 @@
"common.h": "c",
"prctl.h": "c",
"algorithm": "c",
"cstdlib": "c"
"cstdlib": "c",
"libipset.h": "c"
}
}

View File

@@ -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

21
cap.c
View File

@@ -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)
{