You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
110 lines
3.0 KiB
110 lines
3.0 KiB
#!/usr/bin/env python3
|
|
"""
|
|
示例Python项目 - 包含一些常见的代码漏洞
|
|
"""
|
|
|
|
import os
|
|
import sys
|
|
import hashlib
|
|
import subprocess
|
|
from urllib.request import urlopen
|
|
|
|
class UserManager:
|
|
def __init__(self):
|
|
self.users = {}
|
|
self.admin_password = "admin123" # 硬编码密码
|
|
|
|
def create_user(self, username, password):
|
|
"""创建用户 - 存在SQL注入风险"""
|
|
# 模拟SQL查询 - 未使用参数化查询
|
|
query = f"INSERT INTO users (username, password) VALUES ('{username}', '{password}')"
|
|
print(f"执行查询: {query}")
|
|
|
|
# 存储明文密码
|
|
self.users[username] = password
|
|
return True
|
|
|
|
def authenticate(self, username, password):
|
|
"""用户认证"""
|
|
if username in self.users:
|
|
# 明文密码比较
|
|
return self.users[username] == password
|
|
return False
|
|
|
|
def hash_password(self, password):
|
|
"""密码哈希 - 使用弱哈希算法"""
|
|
# 使用MD5 - 已被认为不安全
|
|
return hashlib.md5(password.encode()).hexdigest()
|
|
|
|
def read_file(filename):
|
|
"""读取文件 - 未处理异常"""
|
|
# 未检查文件是否存在
|
|
with open(filename, 'r') as f:
|
|
return f.read()
|
|
|
|
def download_file(url):
|
|
"""下载文件 - 存在安全风险"""
|
|
# 未验证URL格式
|
|
response = urlopen(url)
|
|
return response.read()
|
|
|
|
def execute_command(cmd):
|
|
"""执行系统命令 - 存在命令注入风险"""
|
|
# 直接执行用户输入的命令
|
|
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
|
|
return result.stdout
|
|
|
|
def process_user_input(data):
|
|
"""处理用户输入 - 未进行输入验证"""
|
|
# 未验证输入长度和内容
|
|
if len(data) > 1000: # 简单的长度检查
|
|
return "输入过长"
|
|
|
|
# 未过滤危险字符
|
|
return data.replace('<script>', '').replace('</script>', '')
|
|
|
|
def calculate_total(items):
|
|
"""计算总数 - 存在除零风险"""
|
|
total = 0
|
|
for item in items:
|
|
# 未检查除零
|
|
total += item['price'] / item['quantity']
|
|
return total
|
|
|
|
def main():
|
|
"""主函数"""
|
|
print("代码漏洞检测系统示例")
|
|
|
|
# 硬编码的敏感信息
|
|
api_key = "sk-1234567890abcdef"
|
|
database_url = "mysql://user:password@localhost/db"
|
|
|
|
# 未使用HTTPS
|
|
external_url = "http://api.example.com/data"
|
|
|
|
# 创建用户管理器
|
|
user_mgr = UserManager()
|
|
|
|
# 模拟用户操作
|
|
username = input("请输入用户名: ")
|
|
password = input("请输入密码: ")
|
|
|
|
# 未验证输入
|
|
if user_mgr.create_user(username, password):
|
|
print("用户创建成功")
|
|
|
|
# 尝试读取文件
|
|
try:
|
|
content = read_file("config.txt")
|
|
print("配置文件内容:", content)
|
|
except:
|
|
print("文件读取失败")
|
|
|
|
# 执行命令
|
|
command = input("请输入要执行的命令: ")
|
|
output = execute_command(command)
|
|
print("命令输出:", output)
|
|
|
|
if __name__ == "__main__":
|
|
main()
|