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

2024-02-06 16:20

本文主要是介绍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的清单‘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的清单查询,封禁所有不欢迎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

这篇关于FRP内网穿透如何避免SSH暴力破解(二)——指定地区允许访问的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/684879

相关文章

豆包 MarsCode 不允许你还没有女朋友

在这个喧嚣的世界里,爱意需要被温柔地唤醒。为心爱的她制作每日一句小工具,就像是一场永不落幕的浪漫仪式,每天都在她的心田播撒爱的种子,让她的每一天都充满甜蜜与期待。 背景 在这个瞬息万变的时代,我们都在寻找那些能让我们慢下来,感受生活美好的瞬间。为了让这份浪漫持久而深刻,我们决定为女朋友定制一个每日一句小工具。这个工具会在她意想不到的时刻,为她呈现一句充满爱意的话语,让她的每一天都充满惊喜和感动

安卓链接正常显示,ios#符被转义%23导致链接访问404

原因分析: url中含有特殊字符 中文未编码 都有可能导致URL转换失败,所以需要对url编码处理  如下: guard let allowUrl = webUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {return} 后面发现当url中有#号时,会被误伤转义为%23,导致链接无法访问

两个月冲刺软考——访问位与修改位的题型(淘汰哪一页);内聚的类型;关于码制的知识点;地址映射的相关内容

1.访问位与修改位的题型(淘汰哪一页) 访问位:为1时表示在内存期间被访问过,为0时表示未被访问;修改位:为1时表示该页面自从被装入内存后被修改过,为0时表示未修改过。 置换页面时,最先置换访问位和修改位为00的,其次是01(没被访问但被修改过)的,之后是10(被访问了但没被修改过),最后是11。 2.内聚的类型 功能内聚:完成一个单一功能,各个部分协同工作,缺一不可。 顺序内聚:

git ssh key相关

step1、进入.ssh文件夹   (windows下 下载git客户端)   cd ~/.ssh(windows mkdir ~/.ssh) step2、配置name和email git config --global user.name "你的名称"git config --global user.email "你的邮箱" step3、生成key ssh-keygen

遮罩,在指定元素上进行遮罩

废话不多说,直接上代码: ps:依赖 jquer.js 1.首先,定义一个 Overlay.js  代码如下: /*遮罩 Overlay js 对象*/function Overlay(options){//{targetId:'',viewHtml:'',viewWidth:'',viewHeight:''}try{this.state=false;//遮罩状态 true 激活,f

Jenkins构建Maven聚合工程,指定构建子模块

一、设置单独编译构建子模块 配置: 1、Root POM指向父pom.xml 2、Goals and options指定构建模块的参数: mvn -pl project1/project1-son -am clean package 单独构建project1-son项目以及它所依赖的其它项目。 说明: mvn clean package -pl 父级模块名/子模块名 -am参数

如何来避免FOUC

FOUC(Flash of Unstyled Content)是指在网页加载过程中,由于CSS样式加载延迟或加载顺序不当,导致页面出现短暂的无样式内容闪烁现象。为了避免FOUC,可以采取以下几种方法: 1. 优化CSS加载 内联CSS:将关键的CSS样式直接嵌入到HTML文档的<head>部分,这样可以确保在页面渲染之前样式就已经加载和应用。提前引入CSS:将CSS文件放在HTML文档的<he

Redis中使用布隆过滤器解决缓存穿透问题

一、缓存穿透(失效)问题 缓存穿透是指查询一个一定不存在的数据,由于缓存中没有命中,会去数据库中查询,而数据库中也没有该数据,并且每次查询都不会命中缓存,从而每次请求都直接打到了数据库上,这会给数据库带来巨大压力。 二、布隆过滤器原理 布隆过滤器(Bloom Filter)是一种空间效率很高的随机数据结构,它利用多个不同的哈希函数将一个元素映射到一个位数组中的多个位置,并将这些位置的值置

C#关闭指定时间段的Excel进程的方法

private DateTime beforeTime;            //Excel启动之前时间          private DateTime afterTime;               //Excel启动之后时间          //举例          beforeTime = DateTime.Now;          Excel.Applicat

防止缓存击穿、缓存穿透和缓存雪崩

使用Redis缓存防止缓存击穿、缓存穿透和缓存雪崩 在高并发系统中,缓存击穿、缓存穿透和缓存雪崩是三种常见的缓存问题。本文将介绍如何使用Redis、分布式锁和布隆过滤器有效解决这些问题,并且会通过Java代码详细说明实现的思路和原因。 1. 背景 缓存穿透:指的是大量请求缓存中不存在且数据库中也不存在的数据,导致大量请求直接打到数据库上,形成数据库压力。 缓存击穿:指的是某个热点数据在