如何为Telegram Python机器人实现参数关键词过滤功能?
Telegram Python机器人参数过滤与命令注入防护
你的代码目前存在严重的命令注入风险——直接将用户输入的host拼接进os.popen的命令字符串里,攻击者可以通过输入类似example.com{IFS};rm -rf /的内容,让机器人执行任意系统命令。下面是具体的解决方法:
1. 实现恶意内容拦截
先定义需要拦截的恶意特征列表,检查用户传入的参数是否包含这些内容,若包含则直接跳过响应:
if sender in authorized_senders: args = text.split() command = args[0] # 定义需要拦截的恶意字符串,可根据需求扩展 forbidden_patterns = ['{IFS}', ';', '|', '&', '`', '$', '(', ')'] if command == '/ping': if len(args) < 2: bot.sendMessage(chat_id, "请提供要ping的主机地址") return host = str(args[1]) # 检查是否包含恶意内容 for pattern in forbidden_patterns: if pattern in host: bot.sendMessage(chat_id, "输入包含非法内容,拒绝执行") return # 原执行逻辑(后续建议替换为更安全的方式) output = os.popen(f"ping -c1 {host}").read() bot.sendMessage(chat_id, output)
2. 替换为更安全的命令执行方式
os.popen本质是调用shell解析命令,容易被注入。推荐使用subprocess模块,通过分离命令和参数的方式执行,彻底避免命令注入风险:
import subprocess if sender in authorized_senders: args = text.split() command = args[0] forbidden_patterns = ['{IFS}', ';', '|', '&', '`', '$', '(', ')'] if command == '/ping': if len(args) < 2: bot.sendMessage(chat_id, "请提供要ping的主机地址") return host = str(args[1]) # 恶意内容检查 for pattern in forbidden_patterns: if pattern in host: bot.sendMessage(chat_id, "输入包含非法内容,拒绝执行") return # 使用subprocess安全执行命令 try: # 分离命令与参数,避免shell解析 cmd = ['ping', '-c1', host] # 捕获输出和错误,设置超时防止阻塞 result = subprocess.run(cmd, capture_output=True, text=True, timeout=5) output = result.stdout if result.returncode == 0 else result.stderr bot.sendMessage(chat_id, output) except subprocess.TimeoutExpired: bot.sendMessage(chat_id, "ping请求超时") except Exception as e: bot.sendMessage(chat_id, f"执行出错:{str(e)}")
说明:
- 恶意特征列表可根据实际攻击场景扩展,比如添加
<、>等重定向符号 subprocess.run通过分离参数的方式,完全避免了shell解析命令的风险,即使过滤出现遗漏,也能从根源上阻止命令注入
内容的提问来源于stack exchange,提问作者will
相关产品推荐
相关产品推荐

