创建时间: 2025-08-18 08:35:39
更新时间: 2025-08-18 08:55:53
import hmac
import os
import json
import base64
import hashlib
import requests
import time
import uuid
import platform
import subprocess
import ctypes
import sys
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
BASE_URL = "http://lifey.icu"
BLOCK_SIZE = 16
SESSION_TIMEOUT = 100
class SecureClient:
def __init__(self, app_id, secret):
# 敏感信息采用下划线前缀标识私有性,防止外部直接访问
self._session_id = None
self._session_key = None
self._expire_time = 0
self._secret = secret # 核心密钥,用于所有加密/解密操作
self.app_id = app_id
self._token = None
self._session_hmac = None
self._salt_session_id = None
self._salt_session_key = None
self._salt_token = None
def _get_device_fingerprint(self):
"""改进的设备指纹生成方法,兼容多种环境"""
device_info_parts = []
# 基础系统信息
system_info = f"{platform.system()}-{platform.release()}-{platform.machine()}-{platform.version()}"
device_info_parts.append(system_info)
# 获取CPU信息 - 尝试多种方法
cpu_info = self._get_cpu_info()
if cpu_info is None:
return "hwid失败 请联系管理员"
device_info_parts.append(f"cpu:{cpu_info}")
# 获取MAC地址 - 尝试多种方法
mac_addr = self._get_mac_address()
if mac_addr is None:
return "hwid失败 请联系管理员"
device_info_parts.append(f"mac:{mac_addr}")
# 添加磁盘信息作为补充标识
disk_info = self._get_disk_info()
if disk_info:
device_info_parts.append(f"disk:{disk_info}")
else:
# 磁盘信息不是必须的,不作为失败条件
device_info_parts.append("disk:unknown")
# 添加主板信息作为补充标识(Windows)
if platform.system() == "Windows":
board_info = self._get_motherboard_info()
if board_info:
device_info_parts.append(f"board:{board_info}")
else:
device_info_parts.append("board:unknown")
# 组合所有信息并生成哈希
device_string = "-".join(device_info_parts)
return hashlib.sha256(device_string.encode()).hexdigest()
def _get_cpu_info(self):
"""获取CPU信息的多种方法"""
try:
if platform.system() == "Windows":
# 尝试wmic获取CPU信息
try:
output = subprocess.check_output(
'wmic cpu get ProcessorId,Name',
shell=True,
stderr=subprocess.DEVNULL
).decode(errors='ignore')
lines = [line.strip() for line in output.split('\n') if line.strip()]
if len(lines) > 1:
return hashlib.md5(lines[1].encode()).hexdigest()[:16]
except:
pass
# 尝试通过注册表获取CPU信息
try:
import winreg
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
r"HARDWARE\DESCRIPTION\System\CentralProcessor\0")
processor_name = winreg.QueryValueEx(key, "ProcessorNameString")[0]
winreg.CloseKey(key)
return hashlib.md5(processor_name.encode()).hexdigest()[:16]
except:
pass
elif platform.system() == "Linux":
# Linux系统尝试从/proc/cpuinfo获取
try:
with open('/proc/cpuinfo', 'r') as f:
for line in f:
if line.startswith('processor'):
continue
if line.startswith('model name') or line.startswith('cpu family'):
return hashlib.md5(line.strip().encode()).hexdigest()[:16]
except:
pass
elif platform.system() == "Darwin": # macOS
try:
output = subprocess.check_output(
'sysctl -n machdep.cpu.brand_string',
shell=True,
stderr=subprocess.DEVNULL
).decode(errors='ignore').strip()
return hashlib.md5(output.encode()).hexdigest()[:16]
except:
pass
except Exception as e:
pass
# 所有方法都失败时返回None
return None
def _get_mac_address(self):
"""获取MAC地址的多种方法"""
try:
# 尝试通过uuid获取
mac_num = hex(uuid.getnode()).replace('0x', '').upper()
mac_addr = '-'.join(mac_num[i:i + 2] for i in range(0, 11, 2))
if mac_addr and not mac_addr.startswith('00-00-00'):
return mac_addr
# 不同系统尝试不同命令
if platform.system() == "Windows":
output = subprocess.check_output(
'ipconfig /all',
shell=True,
stderr=subprocess.DEVNULL
).decode(errors='ignore').lower()
for line in output.split('\n'):
if '物理地址' in line or 'mac address' in line:
parts = line.split(':')
if len(parts) > 1:
mac = parts[1].strip().upper()
if mac and not mac.startswith('00-00-00'):
return mac
elif platform.system() in ["Linux", "Darwin"]:
output = subprocess.check_output(
'ifconfig || ip addr',
shell=True,
stderr=subprocess.DEVNULL
).decode(errors='ignore').lower()
for line in output.split('\n'):
if 'ether' in line or 'hwaddr' in line:
parts = line.strip().split()
if len(parts) > 1:
mac = parts[1].upper()
if mac and not mac.startswith('00:00:00'):
return mac.replace(':', '-')
except Exception as e:
pass
# 所有方法都失败时返回None
return None
def _get_disk_info(self):
"""获取磁盘信息作为补充标识"""
try:
if platform.system() == "Windows":
# 获取系统盘信息
output = subprocess.check_output(
'wmic diskdrive get SerialNumber',
shell=True,
stderr=subprocess.DEVNULL
).decode(errors='ignore')
lines = [line.strip() for line in output.split('\n') if line.strip() and line.strip() != 'SerialNumber']
if lines:
return hashlib.md5(lines[0].encode()).hexdigest()[:16]
elif platform.system() == "Linux":
try:
with open('/proc/diskstats', 'r') as f:
first_line = f.readline().strip()
return hashlib.md5(first_line.encode()).hexdigest()[:16]
except:
pass
elif platform.system() == "Darwin":
output = subprocess.check_output(
'diskutil info / | grep "Volume UUID"',
shell=True,
stderr=subprocess.DEVNULL
).decode(errors='ignore').strip()
if output:
return hashlib.md5(output.encode()).hexdigest()[:16]
except Exception as e:
pass
return None
def _get_motherboard_info(self):
"""获取主板信息(仅Windows)"""
try:
output = subprocess.check_output(
'wmic baseboard get SerialNumber',
shell=True,
stderr=subprocess.DEVNULL
).decode(errors='ignore')
lines = [line.strip() for line in output.split('\n') if line.strip() and line.strip() != 'SerialNumber']
if lines:
return hashlib.md5(lines[0].encode()).hexdigest()[:16]
except:
pass
return None
def _cipher(self, data, key=None, encrypt=True):
key = key or self._secret
if isinstance(key, str):
try:
key = base64.b64decode(key)
except:
key = key.encode()[:32]
key = key.ljust(32, b'\0')[:32]
if encrypt:
if isinstance(data, str):
data = data.encode()
iv = os.urandom(BLOCK_SIZE) # 随机生成初始化向量,增强加密安全性
cipher = AES.new(key, AES.MODE_CBC, iv)
return base64.b64encode(iv + cipher.encrypt(pad(data, BLOCK_SIZE)))
else:
raw = base64.b64decode(data)
iv, ciphertext = raw[:BLOCK_SIZE], raw[BLOCK_SIZE:]
cipher = AES.new(key, AES.MODE_CBC, iv)
return unpad(cipher.decrypt(ciphertext), BLOCK_SIZE).decode()
def _build_secure_request(self, path, payload):
payload.update({
'timestamp': int(time.time() * 1000), # 时间戳防止重放攻击
'nonce': str(uuid.uuid4())
})
encrypted = self._cipher(json.dumps(payload)).decode()
return {
"encrypted_data": encrypted,
"appid": self.app_id,
"encryption_key": self._secret
}
def _send_secure_request(self, path, payload):
req_data = self._build_secure_request(path, payload)
try:
resp = requests.post(
f"{BASE_URL}{path}",
json=req_data,
headers={"Content-Type": "application/json"},
timeout=5
)
if resp.status_code == 200:
res = resp.json()
if 'encrypted_response' in res:
return json.loads(self._cipher(res['encrypted_response'], encrypt=False))
except Exception as e:
print(f"请求错误: {str(e)}")
return None
def _check_debugger(self):
try:
if sys.platform == 'win32':
kernel32 = ctypes.windll.kernel32
if kernel32.IsDebuggerPresent():
return True
elif 'linux' in sys.platform:
try:
with open('/proc/self/status', 'r') as status:
for line in status:
if line.startswith('TracerPid:'):
tracer_pid = int(line.split(':')[1].strip())
if tracer_pid != 0:
return True
return False
except:
pass
# 检测常见调试工具进程名,防止调试分析
debuggers = ['ollydbg', 'ida', 'ghidra', 'x64dbg', 'windbg']
if sys.platform == 'win32':
processes = subprocess.check_output(['tasklist'], stderr=subprocess.DEVNULL).decode(
errors='ignore').lower()
else:
processes = subprocess.check_output(['ps', 'aux'], stderr=subprocess.DEVNULL).decode(
errors='ignore').lower()
return any(debugger in processes for debugger in debuggers)
except:
return False
def _obfuscate_data(self, data):
if data is None:
return None, None
salt = os.urandom(16)
return hmac.new(salt, data.encode(), 'sha256').digest(), salt
def _deobfuscate_data(self, data, salt):
if data is None or salt is None:
return None
return hmac.new(salt, data, 'sha256').digest()
def _create_session_hmac(self):
if not self._session_id or not self._session_key:
return None
data = f"{self._session_id}{self._session_key}{self._expire_time}"
key = self._secret.encode() if isinstance(self._secret, str) else self._secret
return hmac.new(key, data.encode(), 'sha256').digest()
def _verify_session_hmac(self):
if not self._session_hmac:
return False
current_hmac = self._create_session_hmac()
# 使用compare_digest防止时序攻击
return hmac.compare_digest(self._session_hmac, current_hmac)
def login(self, user, pwd):
if self._check_debugger():
print("安全警告:检测到调试环境")
return False
# 获取设备指纹
device_fingerprint = self._get_device_fingerprint()
# 检查是否获取失败
if device_fingerprint == "hwid失败 请联系管理员":
print(device_fingerprint)
return False
print(f"设备指纹: {device_fingerprint}")
payload = {
"action": "login",
"username": user,
"password": pwd,
"device_id": device_fingerprint,
"appid": self.app_id
}
res = self._send_secure_request("/api/user/encrypted-login", payload)
if res and res.get("success"):
session_id = res.get('session_id')
session_key = res.get('session_key')
token = res.get('encrypted_token')
if not all([session_id, session_key, token]):
return False
self._session_id, self._salt_session_id = self._obfuscate_data(session_id)
self._session_key, self._salt_session_key = self._obfuscate_data(session_key)
self._token, self._salt_token = self._obfuscate_data(token)
self._expire_time = res.get('expire_time')
self._session_hmac = self._create_session_hmac()
start_time = time.time()
self._perform_sensitive_operation()
if time.time() - start_time > 0.5:
self._clear_session()
return False
return True
return False
def _perform_sensitive_operation(self):
for _ in range(100):
_ = hashlib.sha256(os.urandom(16)).hexdigest()
def _clear_session(self):
self._session_id = None
self._session_key = None
self._expire_time = 0
self._token = None
self._session_hmac = None
self._salt_session_id = None
self._salt_session_key = None
self._salt_token = None
def get_session_info(self):
if not self._verify_session_hmac():
return "会话无效或已被篡改"
try:
session_id = self._deobfuscate_data(
self._session_id,
self._salt_session_id
)
if session_id is None:
return "会话数据损坏"
return {
"session_id": session_id.hex(),
"expire_time": time.ctime(self._expire_time)
}
except Exception as e:
return f"会话数据错误: {str(e)}"
if __name__ == "__main__":
client = SecureClient(
app_id="c8cb18875d4e42cf",
secret="mtWrARdvhQgY4kT0oXDRTLaCt/hdTefkjCEYbwB+IeY="
)
print()
username = str(input("请输入用户名: "))
password = str(input("请输入密码: "))
if client.login(username, password):
print("登录成功")
session_info = client.get_session_info()
if isinstance(session_info, dict):
print(f"会话ID: {session_info['session_id']}")
print(f"过期时间: {session_info['expire_time']}")
else:
print(session_info)
else:
print("登录失败")