FRP内网穿透如何避免SSH暴力破解(二)——指定地区允许访问

背景

上篇文章说到,出现了试图反复通过FRP的隧道,建立外网端口到内网服务器TCP链路的机器人,同时试图暴力破解ssh。这些连接造成了流量的浪费和不必要的通信开销。考虑到服务器使用者主要分布在A、B、C地区和国家,我打算对上一篇文章获取的建立连接的ip再过滤一遍,把其他地区的ip加以封禁,确保服务器不被恶意访问骚扰。

思路

在FRP服务端写一个python程序,每个小时查询一次已连接ip的清单,只允许指定区域的ip访问内网的指定端口。本文国家/地区列表我设置为中国大陆、香港、新加坡、马来西亚、美国。

获取地区&检查是否是目标区域

# 设置允许访问地区列表
target_countries = ('China', 'Hong Kong', 'Singapore', 'Malaysia', 'United States')def get_ip_location(ip_address):response = requests.get(f'https://ipapi.co/{ip_address}/json/').json()country_name = response.get("country_name")# print(country_name)return country_namedef check_ip_location(ip_address):country_name = get_ip_location(ip_address)if country_name in target_countries:# print('ok')return 'ok'else:return 'no'

封禁服务区域外的ip

def ban_ip(ip_address):# 检查IP是否已经被封禁if is_ip_banned(ip_address):print(f"IP {ip_address} is already banned.")returntry:# 封禁IP地址subprocess.run(['sudo', 'iptables', '-A', 'INPUT', '-s', ip_address, '-j', 'DROP'], check=True)# 记录到文件with open('/home/user/ban_ip_no_cn.txt', 'a') as file:ban_time = datetime.datetime.now()unban_time = ban_time + datetime.timedelta(days=1)file.write(f"{ban_time}, {ip_address}, {unban_time}\n")print(f"IP {ip_address} has been banned.")except Exception as e:print(f"Error banning IP {ip_address}: {e}")

封禁时间限制

每天运行一次脚本ban_ip_no_cn.sh,检查是否到了解封时间。

BAN_FILE="/home/user/ban_ip_no_cn.txt"
TEMP_FILE="/tmp/temp_ban_ip_no_cn.txt"while IFS=, read -r ban_time ip_address unban_time; docurrent_time=$(date +%Y-%m-%d' '%H:%M:%S)if [[ "$current_time" > "$unban_time" ]]; thensudo iptables -D INPUT -s $ip_address -j DROPelseecho "$line" >> $TEMP_FILEfi
done < $BAN_FILEmv $TEMP_FILE $BAN_FILE

定期清理连接建立记录(ip_ban_delete_old.py)

# 已建立连接ip的清单‘establishment_ip.txt’,每三天释放一次from datetime import datetime, timedelta
import osdef delete_old_entries(file_path):cutoff_date = datetime.now().date() - timedelta(days=1)temp_file_path = file_path + ".tmp"with open(file_path, 'r') as read_file, open(temp_file_path, 'w') as write_file:for line in read_file:line_date_str = line.split(' ')[0]  # Extract only the date partline_date = datetime.strptime(line_date_str, '%Y-%m-%d').date()if line_date >= cutoff_date:write_file.write(line)os.replace(temp_file_path, file_path)# Path to the establishment_ip.txt file
file_path = '/home/peter/establishment_ip.txt'
delete_old_entries(file_path)

注意

establishment_ip.txt文件的格式如下,通过ss -anp | grep ":port"(port切换为你的frps开放的port)命令获取。

2024-02-06 07:36:52.541687: Established connection from IP 203.145.18.60 on port 23
2024-02-06 07:36:52.578422: Established connection from IP 203.145.18.60 on port 23
2024-02-06 07:40:01.597133: Established connection from IP 56.101.207.179 on port 24
2024-02-06 07:40:01.597341: Established connection from IP 203.145.18.60 on port 24
2024-02-06 07:40:01.633414: Established connection from IP 203.145.18.60 on port 24
2024-02-06 07:40:36.380221: Established connection from IP 203.145.18.60 on port 24

效果:

  1. ip_ban_no_cn.log输出打印
    ip_ban_no_cn.log输出
  2. ban_ip_no_cn.txt的被封禁ip记录
    在这里插入图片描述

完整Python代码ip_ban_no_cn.py (注意修改路径)

# 每小时运行一次,从已建立连接ip的清单查询,封禁所有不欢迎ip
# 已建立连接ip的清单‘establishment_ip.txt’,每三天释放一次import re
import requests
import subprocess
import datetime# 更新国家列表
target_countries = ('China', 'Hong Kong', 'Singapore', 'Malaysia', 'United States')def get_ip_location(ip_address):response = requests.get(f'https://ipapi.co/{ip_address}/json/').json()country_name = response.get("country_name")# print(country_name)return country_namedef check_ip_location(ip_address):country_name = get_ip_location(ip_address)if country_name in target_countries:# print('ok')return 'ok'else:return 'no'def is_ip_banned(ip_address):try:with open('/home/{user}/ban_ip_no_cn.txt', 'r') as file:for line in file:if ip_address in line:return Trueexcept FileNotFoundError:# 如果文件不存在,意味着没有IP被封禁return Falsereturn Falsedef ban_ip(ip_address):# 检查IP是否已经被封禁if is_ip_banned(ip_address):print(f"IP {ip_address} is already banned.")returntry:# 封禁IP地址subprocess.run(['sudo', 'iptables', '-A', 'INPUT', '-s', ip_address, '-j', 'DROP'], check=True)# 记录到文件with open('/home/{user}/ban_ip_no_cn.txt', 'a') as file:ban_time = datetime.datetime.now()unban_time = ban_time + datetime.timedelta(days=1)file.write(f"{ban_time}, {ip_address}, {unban_time}\n")print(f"IP {ip_address} has been banned.")except Exception as e:print(f"Error banning IP {ip_address}: {e}")def main():log_file_path = '/home/{user}/establishment_ip.txt'ip_pattern = re.compile(r'\b(?:\d{1,3}\.){3}\d{1,3}\b')current_time = datetime.datetime.now()try:with open(log_file_path, 'r') as file:for line in file:# 尝试解析每行的时间戳parts = line.split(": Established connection from IP ")if len(parts) > 1:timestamp_str = parts[0].strip()# print(timestamp_str)try:timestamp = datetime.datetime.strptime(timestamp_str, '%Y-%m-%d %H:%M:%S.%f')# 检查时间是否在最近2小时内# print(timestamp)if (current_time - timestamp) <= datetime.timedelta(hours=2):search_result = ip_pattern.search(line)# print((current_time - timestamp))if search_result:ip_address = search_result.group(0)if check_ip_location(ip_address) == 'no':ban_ip(ip_address)except ValueError:# 如果时间戳格式不正确,跳过这一行continueexcept FileNotFoundError:print(f"File {log_file_path} not found.")except Exception as e:print(f"An error occurred: {e}")if __name__ == '__main__':main()

Crontab运行的脚本

# Run ban_ip_no_cn.sh every 24 hours and log output
0 0 * * * /home/user/ban_ip_no_cn.sh > /home/user/log_temp/ban_ip_no_cn.log 2>&1# Run ip_ban_no_cn.py every hour and log output
0 * * * * python3 /home/user/ip_ban_no_cn.py > /home/user/log_temp/ip_ban_no_cn.log 2>&1# Run ip_ban_delete_old.py every 24 hours and log output
0 0 * * * python3 /home/user/ip_ban_delete_old.py > /home/user/log_temp/ip_ban_delete_old.log 2>&1

总结

  • 代码写完才发现,早就有大神写了个复杂版本。呜呼哀哉,就好像论文idea被抢发了一样:https://github.com/zngw/frptables
  • ip归属地查询返回的是JSON格式,不光能查国家,还能获取到城市、语言、首都等信息。
get_location() function
As per the API documentation of ipapi, we need to make a GET request on https://ipapi.co/{ip}/{format}/ to get location information for a particular IP address. {ip} is replaced by the IP address and {format} can be replaced with any of these – json, jsonp, xml, csv, yaml.This function internally calls the get_ip() function to get the IP address and then makes a GET request on the URL with the IP address. This API returns a JSON response that looks like this:{"ip": "117.214.109.137","version": "IPv4","city": "Gaya","region": "Bihar","region_code": "BR","country": "IN","country_name": "India","country_code": "IN","country_code_iso3": "IND","country_capital": "New Delhi","country_tld": ".in","continent_code": "AS","in_eu": false,"postal": "823002","latitude": 24.7935,"longitude": 85.012,"timezone": "Asia/Kolkata","utc_offset": "+0530","country_calling_code": "+91","currency": "INR","currency_name": "Rupee","languages": "en-IN,hi,bn,te,mr,ta,ur,gu,kn,ml,or,pa,as,bh,sat,ks,ne,sd,kok,doi,mni,sit,sa,fr,lus,inc","country_area": 3287590,"country_population": 1352617328,"asn": "AS9829","org": "National Internet Backbone"
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/460474.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

LC 993. 二叉树的堂兄弟节点

993. 二叉树的堂兄弟节点 难度&#xff1a; 简单 题目&#xff1a; 在二叉树中&#xff0c;根节点位于深度 0 处&#xff0c;每个深度为 k 的节点的子节点位于深度 k1 处。 如果二叉树的两个节点深度相同&#xff0c;但 父节点不同 &#xff0c;则它们是一对堂兄弟节点。 我…

【调试】pstore原理和使用方法总结

什么是pstore pstore最初是用于系统发生oops或panic时&#xff0c;自动保存内核log buffer中的日志。不过在当前内核版本中&#xff0c;其已经支持了更多的功能&#xff0c;如保存console日志、ftrace消息和用户空间日志。同时&#xff0c;它还支持将这些消息保存在不同的存储…

C#用Array类的FindAll方法和List<T>类的Add方法按关键词在数组中检索元素并输出

目录 一、使用的方法 1. Array.FindAll(T[], Predicate) 方法 &#xff08;1&#xff09;定义 &#xff08;2&#xff09;示例 2.List类的常用方法 &#xff08;1&#xff09;List.Add(T) 方法 &#xff08;2&#xff09;List.RemoveAt(Int32) 方法 &#xff08;3&…

stable_diffusion提示词编写笔记(1)

stable_diffusion提示词编写笔记(1) start 总结一下AI绘画学到的知识。 一.提示词分两种&#xff1a; 1.正向提示词&#xff1b; 2.反向提示词&#xff1b; 一个对应你希望图形包含的内容提示词&#xff0c;一个对应你不希望图形出现的内容提示词。 二.如何书写提示词 1.内…

gh0st远程控制——客户端界面编写(三)

◉ 主控端界面添加右键弹出菜单的功能 为Onlie_List区域添加右键弹出菜单项的功能&#xff1a; 3个视图&#xff1a;类视图、解决方案视图、资源视图 在资源视图下添加一个Menu&#xff1a; 更改Menu的ID为IDR_MENU_ONLINE&#xff1a; 为各控件添加便于区分的ID&#xff1a…

C语言函数栈帧的创建和销毁(逐步分析)

什么是函数栈帧 我们在写C语言代码的时候&#xff0c;经常会把一个独立的功能抽象为函数&#xff0c;所以C程序是以函数为基本单位的。 那函数是如何调用的&#xff1f;函数的返回值又是如何返回的&#xff1f;函数参数是如何传递的&#xff1f;这些问题都和函数栈帧有关系。 …

数据结构(C语言)代码实现(八)——顺序栈实现数值转换行编辑程序汉诺塔

目录 参考资料 顺序栈的实现 头文件SqStack.h&#xff08;顺序栈函数声明&#xff09; 源文件SqStack.cpp&#xff08;顺序栈函数实现&#xff09; 顺序栈的三个应用 数值转换 行编辑程序 顺序栈的实现测试 栈与递归的实现&#xff08;以汉诺塔为例&#xff09; 参考资…

Stable Diffusion 模型下载:Samaritan 3d Cartoon(撒玛利亚人 3d 卡通)

文章目录 模型介绍生成案例案例一案例二案例三案例四案例五案例六案例七案例八案例九案例十 下载地址 模型介绍 由“PromptSharingSamaritan”创作的撒玛利亚人 3d 卡通类型的大模型&#xff0c;该模型的基础模型为 SD 1.5。 条目内容类型大模型基础模型SD 1.5来源CIVITAI作者…

编译原理实验1——词法分析(python实现)

文章目录 实验目的实现定义单词对应的种别码定义输出形式&#xff1a;三元式python代码实现运行结果检错处理 总结 实验目的 输入一个C语言代码串&#xff0c;输出单词流&#xff0c;识别对象包含关键字、标识符、整型浮点型字符串型常数、科学计数法、操作符和标点、注释等等。…

飞天使-linux操作的一些技巧与知识点8-zabbix6.0 容器搭建

文章目录 安装docker安装步骤mysql下载镜像安装zabbix 测试效果 安装docker 1. 配置官方 yum 源$ sudo yum install -y yum-utils $ sudo yum-config-manager \--add-repo \https://download.docker.com/linux/centos/docker-ce.repo2. 安装 Docker$ sudo yum install docker-c…

Docker的镜像和容器的区别

1 Docker镜像 假设Linux内核是第0层&#xff0c;那么无论怎么运行Docker&#xff0c;它都是运行于内核层之上的。这个Docker镜像&#xff0c;是一个只读的镜像&#xff0c;位于第1层&#xff0c;它不能被修改或不能保存状态。 一个Docker镜像可以构建于另一个Docker镜像之上&…

go语言进阶篇——面向对象(一)

什么是面向对象 在我们设计代码时&#xff0c;比如写一个算法题或者写一个问题结局办法时&#xff0c;我们常常会使用面向过程的方式来书写代码&#xff0c;面向过程主要指的是以解决问题为中心&#xff0c;按照一步步具体的步骤来编写代码或者调用函数&#xff0c;他在问题规…