| Crates.io | psi_detector |
| lib.rs | psi_detector |
| version | 0.1.3 |
| created_at | 2025-09-26 06:15:48.778069+00 |
| updated_at | 2025-09-26 06:15:48.778069+00 |
| description | Protocol detection and upgrade framework inspired by Yuri's PSI Detector |
| homepage | https://github.com/0ldm0s/psi_detector |
| repository | https://github.com/0ldm0s/psi_detector.git |
| max_upload_size | |
| id | 1855475 |
| size | 647,190 |
PSI-Detector (Protocol Stream Identifier Detector) 是一个高性能的协议检测和升级框架,专为现代网络应用设计。通过智能的协议识别、魔法包特征检测和严格的过滤机制,为您的网络服务提供企业级的性能和安全保障。
[dependencies]
psi_detector = "0.1.1"
use psi_detector::{DetectorBuilder, ProtocolType};
// 创建HTTP服务器检测器
let detector = DetectorBuilder::new()
.enable_http()
.enable_websocket()
.enable_tls()
.high_performance()
.build()?;
// 检测协议
let data = b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n";
let result = detector.detect(data)?;
println!("检测到协议: {} (置信度: {:.1}%)",
result.protocol_type(),
result.confidence() * 100.0);
适用于:Web应用、API服务、微服务网关
let detector = DetectorBuilder::new()
.enable_http() // HTTP/1.1 支持
.enable_http2() // HTTP/2 支持
.enable_websocket() // WebSocket 支持
.enable_tls() // HTTPS 支持
.high_performance() // 性能优化
.build()?;
效果:
适用于:游戏后端、实时应用、IoT设备
// 定义自定义游戏协议
let game_probe = create_game_protocol_probe(); // 您的实现
let detector = DetectorBuilder::new()
.enable_custom() // 启用自定义协议
.add_custom_probe(Box::new(game_probe))
.high_performance()
.build()?;
效果:
适用于:堡垒机、远程管理、安全隧道
let detector = DetectorBuilder::new()
.enable_ssh() // SSH协议支持
.enable_tls() // 安全隧道支持
.high_accuracy() // 高精度模式
.build()?;
效果:
适用于:API网关、代理服务、协议转换
let detector = DetectorBuilder::new()
.enable_http()
.enable_http2()
.enable_grpc() // gRPC支持
.enable_quic() // QUIC/HTTP3支持
.enable_tls()
.balanced() // 平衡性能和精度
.build()?;
效果:
PSI-Detector支持服务器和客户端双向检测:
use psi_detector::core::detector::{Role, Agent};
let server_agent = DetectorBuilder::new()
.enable_http()
.enable_tls()
.with_role(Role::Server) // 服务器角色
.with_instance_id("web-server-01") // 实例标识
.build_agent()?;
// 被动检测传入连接
let result = server_agent.detect(incoming_data)?;
let client_agent = DetectorBuilder::new()
.enable_http2()
.enable_quic()
.with_role(Role::Client) // 客户端角色
.build_agent()?;
// 主动探测服务器能力
let supported_protocols = client_agent.probe_capabilities(&mut transport)?;
let lb_agent = DetectorBuilder::new()
.enable_http()
.with_role(Role::Server)
.with_load_balancer(
LoadBalanceStrategy::RoundRobin,
vec!["backend-1".to_string(), "backend-2".to_string()]
)
.build_agent()?;
PSI-Detector内置超高速魔法包检测,可在前几个字节内识别协议:
| 协议 | 魔法字节 | 置信度 | 检测速度 |
|---|---|---|---|
| HTTP/1.1 | GET , POST , HTTP/ |
95%-98% | ~1800 ns |
| HTTP/2 | PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n |
100% | ~1700 ns |
| TLS | 0x16, 0x03 |
90% | ~3400 ns |
| SSH | SSH- |
99% | ~1500 ns |
| QUIC | 0x80 (长头部) |
70% | ~1600 ns |
use psi_detector::core::magic::{MagicDetector, CustomSignatureBuilder};
let mut detector = MagicDetector::new();
// 添加自定义协议特征
let custom_sig = CustomSignatureBuilder::new(ProtocolType::Custom, "My Game Protocol")
.with_magic_string("GAME") // 魔法字符串
.with_confidence(0.95) // 置信度
.with_offset(0) // 偏移位置
.case_insensitive() // 不区分大小写
.build();
detector.add_signature(custom_sig);
// 快速检测
let result = detector.quick_detect(b"GAME v1.0 login request");
适用于:高并发场景、实时应用
let detector = DetectorBuilder::new()
.enable_http()
.high_performance() // 性能优先配置
.build()?;
特点:
适用于:安全要求高、误判成本大的场景
let detector = DetectorBuilder::new()
.enable_all()
.high_accuracy() // 精度优先配置
.build()?;
特点:
适用于:一般应用场景
let detector = DetectorBuilder::new()
.enable_http()
.enable_tls()
.balanced() // 平衡配置
.build()?;
特点:
let detector = DetectorBuilder::new()
.enable_http()
.with_strategy(ProbeStrategy::Passive)
.with_timeout(Duration::from_millis(50))
.with_min_confidence(0.85)
.enable_simd()
.enable_heuristic()
.with_buffer_size(4096)
.build()?;
致敬经典,PSI-Detector提供特殊的"心灵"检测模式:
let detector = DetectorBuilder::new()
.enable_http()
.psychic_detection() // 高精度被动探测
.build()?;
let detector = DetectorBuilder::new()
.enable_all()
.mind_control() // 高性能被动探测
.build()?;
let detector = DetectorBuilder::new()
.psychic_storm() // 全面被动探测
.build()?;
运行性能测试:
# 基础性能测试
cargo run --example magic_bytes_performance
# 协议过滤性能对比
cargo run --example protocol_filtering_performance
# 实际场景模拟
cargo run --example real_world_scenarios
| 测试场景 | 检测时间 | 吞吐量 | 性能提升 |
|---|---|---|---|
| 魔法包检测 | 1,108 ns | 902K/秒 | 2.08x |
| 游戏服务器 | 4,420 ns | 226K/秒 | 2.30x |
| HTTP服务器 | 7,880 ns | 127K/秒 | 1.29x |
| 标准检测 | 2,303 ns | 434K/秒 | 1.00x |
#[cfg(feature = "runtime-tokio")]
use psi_detector::core::detector::AsyncProtocolDetector;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let detector = DetectorBuilder::new()
.enable_http()
.build()?;
let result = detector.detect_async(data).await?;
Ok(())
}
let data_chunks = vec![
http_request.as_slice(),
tls_handshake.as_slice(),
ssh_banner.as_slice(),
];
let results = detector.detect_batch(&data_chunks)?;
for result in results {
println!("协议: {}", result.protocol_type());
}
use psi_detector::core::detector::DetectionStats;
let mut stats = DetectionStats::new();
// 检测并记录统计
let result = detector.detect(data)?;
stats.record_success(result.protocol_type(), result.detection_time);
// 查看统计
println!("成功率: {:.1}%", stats.success_rate() * 100.0);
println!("最常见协议: {:?}", stats.most_common_protocol());
println!("平均检测时间: {:?}", stats.avg_detection_time);
use tokio::net::TcpListener;
use psi_detector::{DetectorBuilder, ProtocolType};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let detector = DetectorBuilder::new()
.enable_http()
.enable_tls()
.high_performance()
.build()?;
let listener = TcpListener::bind("127.0.0.1:8080").await?;
loop {
let (mut socket, _) = listener.accept().await?;
let detector = detector.clone(); // 需要实现Clone
tokio::spawn(async move {
let mut buf = [0; 1024];
if let Ok(n) = socket.read(&mut buf).await {
if let Ok(result) = detector.detect(&buf[..n]) {
match result.protocol_type() {
ProtocolType::HTTP1_1 => {
// 处理HTTP请求
}
ProtocolType::TLS => {
// 处理HTTPS请求
}
_ => {
// 其他协议或拒绝连接
}
}
}
}
});
}
}
use mammoth_transport::{TransportBuilder, ProtocolRouter};
use psi_detector::DetectorBuilder;
let detector = DetectorBuilder::new()
.enable_http()
.enable_quic()
.enable_tls()
.build()?;
let transport = TransportBuilder::new()
.with_protocol_detector(detector)
.with_auto_routing()
.build()?;
// ❌ 错误:启用所有协议
let detector = DetectorBuilder::new().enable_all().build()?;
// ✅ 正确:只启用需要的协议
let detector = DetectorBuilder::new()
.enable_http()
.enable_tls()
.build()?;
// PSI-Detector 强制配置验证
let result = DetectorBuilder::new().build(); // 将失败
match result {
Err(e) => {
// 会收到详细的配置指导
println!("配置错误: {}", e);
}
Ok(_) => unreachable!(),
}
use psi_detector::utils::logger;
// 启用详细日志
logger::init_logger(log::LevelFilter::Debug);
let result = detector.detect(data)?;
// 自动记录检测过程和结果
match detector.detect(suspicious_data) {
Ok(result) => {
if result.confidence() < 0.5 {
// 低置信度,可能是攻击
log::warn!("检测到可疑流量: {:?}", result);
}
}
Err(e) => {
// 检测失败,记录并拒绝连接
log::error!("协议检测失败: {}", e);
// 静默拒绝连接
}
}
// ❌ 问题代码
let detector = DetectorBuilder::new().build()?;
// ✅ 解决方案
let detector = DetectorBuilder::new()
.enable_http() // 至少启用一个协议
.build()?;
// ✅ 使用高性能配置
let detector = DetectorBuilder::new()
.enable_http()
.high_performance() // 关键!
.build()?;
// ✅ 避免启用过多协议
// ❌ 不要: .enable_all()
// ✅ 推荐: 只启用需要的协议
// ✅ 使用高精度模式
let detector = DetectorBuilder::new()
.enable_http()
.enable_tls()
.high_accuracy() // 提高精度
.build()?;
// ✅ 确保启用自定义协议
let detector = DetectorBuilder::new()
.enable_custom() // 必须启用!
.add_custom_probe(your_probe)
.build()?;
// 在main函数开始添加
env_logger::init();
std::env::set_var("RUST_LOG", "psi_detector=debug");
use std::time::Instant;
let start = Instant::now();
let result = detector.detect(data)?;
let duration = start.elapsed();
if duration.as_millis() > 10 {
println!("检测耗时过长: {:?}", duration);
}
DetectorBuilder构建器模式配置探测器
enable_*() - 启用特定协议with_*() - 设置配置参数high_performance() - 性能优化预设build() - 构建探测器实例ProtocolDetector协议检测核心接口
detect(&self, data: &[u8]) -> Result<DetectionResult> - 检测协议confidence(&self, data: &[u8]) -> Result<f32> - 获取置信度supported_protocols(&self) -> Vec<ProtocolType> - 支持的协议DetectionResult检测结果
protocol_type(&self) -> ProtocolType - 协议类型confidence(&self) -> f32 - 置信度(0.0-1.0)detection_time(&self) -> Duration - 检测耗时is_high_confidence(&self) -> bool - 是否高置信度ProtocolType支持的协议类型
HTTP1_1, HTTP2, HTTP3 - HTTP协议族TLS, QUIC - 安全协议SSH, FTP, SMTP - 传统协议WebSocket, GRPC - 现代协议Custom - 自定义协议我们欢迎各种形式的贡献!
git checkout -b feature/AmazingFeature)git commit -m 'Add some AmazingFeature')git push origin feature/AmazingFeature)# 克隆项目
git clone https://github.com/your-org/psi-detector.git
cd psi-detector
# 运行测试
cargo test
# 运行示例
cargo run --example magic_bytes_performance
# 代码格式化
cargo fmt
# 代码检查
cargo clippy
本项目采用 MIT 许可证 - 查看 LICENSE 文件了解详情。
让我们一起构建更快、更安全的网络应用! 🚀