Implement SSH Phase 13.1: Enterprise-level security configuration
Some checks failed
Test / test (push) Has been cancelled
Test / build (push) Has been cancelled

- Add ssh_security_config.rs module (150 lines)
- Define SshSecurityConfig structure (GatewayPorts, PermitOpen, etc.)
- Implement enterprise_default() and development_default()
- Add validate_tcpip_forward_request() security validation
- Add validate_direct_tcpip_channel() security validation
- Integrate SshSecurityConfig into server.rs
- Add SSH_MSG_GLOBAL_REQUEST handling in service loop
- Initialize PortForwardManager for port forwarding
- Create data/ssh_config.json example file
- Support session counting (increment/decrement)
- All compilation tests passed successfully
This commit is contained in:
Warren
2026-06-15 16:56:38 +08:00
parent 4b4d9c3805
commit a771a30e66
5 changed files with 392 additions and 16 deletions

View File

@@ -1,5 +1,5 @@
// SSH服务器完整实现Phase 1-7集成版
// 参考OpenSSH sshd.c: complete SSH/SFTP flow
// SSH服务器完整实现Phase 1-7集成版 + Phase 13端口转发
// 参考OpenSSH sshd.c: complete SSH/SFTP flow + port forwarding
use crate::ssh_server::version::VersionExchange;
use crate::ssh_server::packet::{SshPacket, PacketType};
@@ -8,16 +8,20 @@ use crate::ssh_server::kex_complete::{KexState};
use crate::ssh_server::auth::{AuthHandler, AuthResult};
use crate::ssh_server::channel::{ChannelManager};
use crate::ssh_server::cipher::{EncryptionContext, EncryptedPacket};
use crate::ssh_server::ssh_security_config::SshSecurityConfig; // Phase 13.1
use crate::ssh_server::port_forward::PortForwardManager; // Phase 13
use anyhow::{Result, anyhow};
use log::{info, warn, error, debug};
use std::net::{TcpListener, TcpStream};
use std::thread;
use std::io::{Read, Write};
use std::sync::{Arc, Mutex}; // Phase 13: 端口转发线程同步
/// SSH服务器配置
/// SSH服务器配置Phase 13.1企业级安全配置)
pub struct SshServerConfig {
pub port: u16,
pub bind_address: String,
pub security_config: SshSecurityConfig, // Phase 13.1: 企业级安全配置
}
impl Default for SshServerConfig {
@@ -25,18 +29,36 @@ impl Default for SshServerConfig {
Self {
port: 2024,
bind_address: "127.0.0.1".to_string(),
security_config: SshSecurityConfig::enterprise_default(), // Phase 13.1
}
}
}
/// SSH服务器主结构Phase 1-7完整版
impl SshServerConfig {
/// 从配置文件加载Phase 13.1
pub fn load_from_file(path: &str) -> Result<Self> {
let config = SshSecurityConfig::load_from_file(path)?;
Ok(Self {
port: 2024,
bind_address: "127.0.0.1".to_string(),
security_config: config,
})
}
}
/// SSH服务器主结构Phase 1-13完整版
pub struct SshServer {
config: SshServerConfig,
security_config: Arc<Mutex<SshSecurityConfig>>, // Phase 13.1: 共享安全配置
}
impl SshServer {
pub fn new(config: SshServerConfig) -> Self {
Self { config }
let security_config = Arc::new(Mutex::new(config.security_config.clone())); // Phase 13.1: 先clone
Self {
config,
security_config, // Phase 13.1
}
}
pub fn run(&self) -> Result<()> {
@@ -44,7 +66,13 @@ impl SshServer {
let listener = TcpListener::bind(&bind_addr)?;
info!("MarkBaseSSH server listening on {}", bind_addr);
info!("Implementation: Complete SSH/SFTP (Phase 1-7)");
info!("Implementation: Complete SSH/SFTP + Port Forwarding (Phase 1-13)");
info!("Security config: GatewayPorts={}, PermitOpen={:?}, MaxSessions={}",
self.config.security_config.gateway_ports,
self.config.security_config.permit_open,
self.config.security_config.max_sessions);
let security_config = self.security_config.clone(); // Phase 13.1: 共享安全配置
for stream in listener.incoming() {
match stream {
@@ -52,8 +80,10 @@ impl SshServer {
let client_addr = stream.peer_addr()?;
info!("New SSH connection from {}", client_addr);
let security_config_clone = security_config.clone(); // Phase 13.1
thread::spawn(move || {
if let Err(e) = handle_connection_complete(stream) {
if let Err(e) = handle_connection_complete(stream, security_config_clone) { // Phase 13.1
error!("Connection error: {}", e);
}
});
@@ -68,9 +98,15 @@ impl SshServer {
}
}
/// 处理完整SSH连接Phase 1-7完整流程)
fn handle_connection_complete(stream: TcpStream) -> Result<()> {
info!("Handling client connection (Phase 1-7 complete flow)");
/// 处理完整SSH连接Phase 1-13完整流程)
fn handle_connection_complete(stream: TcpStream, security_config: Arc<Mutex<SshSecurityConfig>>) -> Result<()> {
info!("Handling client connection (Phase 1-13 complete flow with port forwarding)");
// Phase 13.1: 增加活动会话数
{
let mut security = security_config.lock().unwrap();
security.increment_sessions()?;
}
let mut stream = stream;
@@ -78,7 +114,7 @@ fn handle_connection_complete(stream: TcpStream) -> Result<()> {
let client_version = VersionExchange::exchange(&mut stream)?;
info!("Version exchange: client={}, server=SSH-2.0-MarkBaseSSH_1.0", client_version);
// Phase 2: 法协商
// Phase 2: 法协商
let (kex_result, server_kexinit, client_kexinit) = perform_kex_negotiation_complete(&mut stream)?;
info!("KEX negotiation: KEX={}, Cipher={}", kex_result.kex_algorithm, kex_result.encryption_ctos);
@@ -94,10 +130,21 @@ fn handle_connection_complete(stream: TcpStream) -> Result<()> {
// Phase 6: SSH Channel管理参考OpenSSH channel.c
let mut channel_manager = ChannelManager::new();
// Phase 6-7: SSH服务循环处理channel请求
handle_ssh_service_loop(&mut stream, &mut channel_manager, &mut encryption_ctx)?;
// Phase 13: PortForwardManager初始化
let mut port_forward_manager = PortForwardManager::new();
// Phase 6-13: SSH服务循环处理channel请求 + 端口转发)
let security_config_clone = security_config.clone(); // Phase 13.1: clone for service loop
handle_ssh_service_loop(&mut stream, &mut channel_manager, &mut encryption_ctx, &mut port_forward_manager, security_config_clone)?;
info!("SSH session completed successfully");
// Phase 13.1: 减少活动会话数
{
let mut security = security_config.lock().unwrap();
security.decrement_sessions();
}
Ok(())
}
@@ -299,13 +346,15 @@ AuthResult::Failure(message) => {
}
}
/// SSH服务循环Phase 6
/// SSH服务循环Phase 6-13完整版
fn handle_ssh_service_loop(
stream: &mut TcpStream,
channel_manager: &mut ChannelManager,
encryption_ctx: &mut EncryptionContext,
port_forward_manager: &mut PortForwardManager, // Phase 13
security_config: Arc<Mutex<SshSecurityConfig>>, // Phase 13.1
) -> Result<()> {
info!("Starting SSH service loop (channel management)");
info!("Starting SSH service loop (channel management + port forwarding)");
loop {
// 使用EncryptedPacket读取加密packetPhase 6
@@ -313,6 +362,45 @@ fn handle_ssh_service_loop(
let packet = SshPacket::new(encrypted_packet.payload().to_vec());
match packet.payload.first() {
// Phase 13: SSH_MSG_GLOBAL_REQUEST处理端口转发
Some(&pt) if pt == PacketType::SSH_MSG_GLOBAL_REQUEST as u8 => {
info!("Received SSH_MSG_GLOBAL_REQUEST (port forwarding)");
// Phase 13.1: 安全配置验证
let security = security_config.lock().unwrap();
if !security.allow_tcp_forwarding {
warn!("TCP forwarding disabled by security config");
let failure_packet = vec![PacketType::SSH_MSG_REQUEST_FAILURE as u8];
let encrypted_failure = EncryptedPacket::new(&failure_packet, encryption_ctx, true)?;
encrypted_failure.write(stream)?;
info!("Sent SSH_MSG_REQUEST_FAILURE (TCP forwarding disabled)");
continue;
}
drop(security); // 释放锁
// Phase 13: 调用PortForwardManager处理
let (success, response) = port_forward_manager.handle_global_request(&packet.payload)?;
if success {
if let Some(response_data) = response {
let encrypted_response = EncryptedPacket::new(&response_data, encryption_ctx, true)?;
encrypted_response.write(stream)?;
info!("Sent SSH_MSG_REQUEST_SUCCESS (tcpip-forward accepted)");
} else {
// 无响应数据时发送简单的SUCCESS
let success_packet = vec![PacketType::SSH_MSG_REQUEST_SUCCESS as u8];
let encrypted_success = EncryptedPacket::new(&success_packet, encryption_ctx, true)?;
encrypted_success.write(stream)?;
info!("Sent SSH_MSG_REQUEST_SUCCESS");
}
} else {
let failure_packet = vec![PacketType::SSH_MSG_REQUEST_FAILURE as u8];
let encrypted_failure = EncryptedPacket::new(&failure_packet, encryption_ctx, true)?;
encrypted_failure.write(stream)?;
info!("Sent SSH_MSG_REQUEST_FAILURE (tcpip-forward rejected)");
}
}
Some(&pt) if pt == PacketType::SSH_MSG_CHANNEL_OPEN as u8 => {
info!("Received SSH_MSG_CHANNEL_OPEN");
let response = channel_manager.handle_channel_open(&packet)?;
@@ -392,6 +480,7 @@ pub fn run_ssh_server(port: Option<u16>) -> Result<()> {
let config = SshServerConfig {
port: port.unwrap_or(2024),
bind_address: "127.0.0.1".to_string(),
security_config: SshSecurityConfig::enterprise_default(), // Phase 13.1: 添加安全配置
};
let server = SshServer::new(config);