100 lines
3.2 KiB
Rust
100 lines
3.2 KiB
Rust
// 版权所有 (c) ling 保留所有权利。
|
||
// 除非另行说明,否则仅允许在LingTransmit中使用此文件中的代码。
|
||
//
|
||
// 由 ling 创建于 2025/1/19.
|
||
#![allow(non_snake_case)]
|
||
|
||
use crate::packet::code::*;
|
||
use crate::stream::{OwnedReadHalfAbstraction, OwnedWriteHalfAbstraction};
|
||
use log::trace;
|
||
use openssl::x509::{X509NameEntryRef, X509};
|
||
use std::io;
|
||
use std::sync::Arc;
|
||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||
use tokio::net::{TcpStream, ToSocketAddrs};
|
||
use tokio::sync::Mutex;
|
||
|
||
/// 客户端
|
||
pub struct Client {
|
||
read: Arc<Mutex<dyn OwnedReadHalfAbstraction>>,
|
||
write: Arc<Mutex<dyn OwnedWriteHalfAbstraction>>,
|
||
}
|
||
|
||
impl Client {
|
||
fn init(
|
||
read: Arc<Mutex<dyn OwnedReadHalfAbstraction>>,
|
||
write: Arc<Mutex<dyn OwnedWriteHalfAbstraction>>,
|
||
) -> Self {
|
||
Client { read, write }
|
||
}
|
||
|
||
pub async fn tcp_connect<A: ToSocketAddrs>(addr: A, ca: X509) -> io::Result<Self> {
|
||
let stream = TcpStream::connect(addr).await?;
|
||
let (read, write) = stream.into_split();
|
||
|
||
let read: Arc<Mutex<dyn OwnedReadHalfAbstraction>> = Arc::new(Mutex::new(read));
|
||
let write: Arc<Mutex<dyn OwnedWriteHalfAbstraction>> = Arc::new(Mutex::new(write));
|
||
|
||
let buffer = Self::protocol_connection(read.clone(), write.clone()).await?;
|
||
let cert = X509::from_pem(&*buffer)?;
|
||
//先验证证书签名
|
||
let ca_public = ca
|
||
.public_key()
|
||
.map_err(|_| io::Error::new(io::ErrorKind::NotFound, "无法提取CA公钥"))?;
|
||
|
||
if !cert.verify(&ca_public).map_err(|e| {
|
||
io::Error::new(
|
||
io::ErrorKind::NotFound,
|
||
format!("无法验证服务器证书签名:{}", e.to_string()),
|
||
)
|
||
})? {
|
||
return Err(io::Error::new(
|
||
io::ErrorKind::NotFound,
|
||
"服务器证书缺少信任的CA签名",
|
||
));
|
||
}
|
||
//在此实现中阻止私域证书
|
||
let subject_name = cert.subject_name();
|
||
let cn = match subject_name
|
||
.entries_by_nid(openssl::nid::Nid::COMMONNAME)
|
||
.next()
|
||
{
|
||
None => {
|
||
return Err(io::Error::new(
|
||
io::ErrorKind::NotFound,
|
||
"无法获得签发对象信息",
|
||
));
|
||
}
|
||
Some(cn) => cn,
|
||
};
|
||
|
||
todo!()
|
||
}
|
||
|
||
/// 执行协议握手,
|
||
async fn protocol_connection(
|
||
read: Arc<Mutex<dyn OwnedReadHalfAbstraction>>,
|
||
write: Arc<Mutex<dyn OwnedWriteHalfAbstraction>>,
|
||
) -> io::Result<Vec<u8>> {
|
||
let mut write = write.lock().await;
|
||
let mut read = read.lock().await;
|
||
//请求执行 Ling Transmit V1.1 握手
|
||
write.write_i32_le(LING_SYN_V1).await?;
|
||
//读取证书大小
|
||
let ca_size = read.read_i64_le().await?;
|
||
if ca_size <= 0 {
|
||
return Err(io::Error::new(
|
||
io::ErrorKind::NetworkDown,
|
||
format!("读取到异常数据包大小:{}", ca_size),
|
||
));
|
||
}
|
||
trace!("证书大小:{:X}", ca_size);
|
||
//读取服务器证书
|
||
let mut buffer = Vec::new();
|
||
buffer.resize(ca_size as usize, 0u8);
|
||
read.read_exact(&mut buffer).await?;
|
||
|
||
Ok(buffer)
|
||
}
|
||
}
|