disable auth for now

This commit is contained in:
2025-11-16 16:50:34 -05:00
parent 7d73a8344a
commit 8fe403b94d
6 changed files with 170 additions and 83 deletions

View File

@@ -1,5 +1,9 @@
use openworm::server::run_server; use openworm::server::run_server;
fn main() { fn main() {
quinn::rustls::crypto::aws_lc_rs::default_provider()
.install_default()
.unwrap();
run_server(); run_server();
} }

View File

@@ -1,14 +1,18 @@
use crate::client::{AppHandle, ClientEvent}; use crate::{
use quinn::{crypto::rustls::QuicClientConfig, rustls::pki_types::CertificateDer}; client::{AppHandle, ClientEvent},
net::{SERVER_NAME, no_cert::SkipServerVerification},
};
use quinn::{ClientConfig, Connection, Endpoint, crypto::rustls::QuicClientConfig};
use std::{ use std::{
fs, net::{Ipv6Addr, SocketAddr, SocketAddrV6},
io::ErrorKind,
net::{IpAddr, Ipv6Addr, SocketAddr},
str::FromStr, str::FromStr,
sync::Arc, sync::Arc,
}; };
use tokio::sync::mpsc::UnboundedSender; use tokio::sync::mpsc::UnboundedSender;
pub const CLIENT_SOCKET: SocketAddr =
SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, 0, 0, 0));
pub fn connect(handle: AppHandle, ip: String) { pub fn connect(handle: AppHandle, ip: String) {
std::thread::spawn(|| { std::thread::spawn(|| {
connect_the(handle, ip).unwrap(); connect_the(handle, ip).unwrap();
@@ -21,39 +25,57 @@ pub enum NetCmd {
pub type NetSender = UnboundedSender<NetCmd>; pub type NetSender = UnboundedSender<NetCmd>;
// async fn connection_cert(addr: SocketAddr) -> anyhow::Result<Connection> {
// let dirs = directories_next::ProjectDirs::from("", "", "openworm").unwrap();
// let mut roots = quinn::rustls::RootCertStore::empty();
// match fs::read(dirs.data_local_dir().join("cert.der")) {
// Ok(cert) => {
// roots.add(CertificateDer::from(cert))?;
// }
// Err(ref e) if e.kind() == ErrorKind::NotFound => {
// eprintln!("local server certificate not found");
// }
// Err(e) => {
// eprintln!("failed to open local server certificate: {}", e);
// }
// }
// let client_crypto = quinn::rustls::ClientConfig::builder()
// .with_root_certificates(roots)
// .with_no_client_auth();
// let client_config = ClientConfig::new(Arc::new(QuicClientConfig::try_from(client_crypto)?));
// let mut endpoint = quinn::Endpoint::client(SocketAddr::from_str("[::]:0").unwrap())?;
// endpoint.set_default_client_config(client_config);
// endpoint
// .connect(addr, SERVER_NAME)?
// .await
// .map_err(|e| anyhow::anyhow!("failed to connect: {}", e))
// }
async fn connection_no_cert(addr: SocketAddr) -> anyhow::Result<Connection> {
let mut endpoint = Endpoint::client(CLIENT_SOCKET)?;
endpoint.set_default_client_config(ClientConfig::new(Arc::new(QuicClientConfig::try_from(
quinn::rustls::ClientConfig::builder()
.dangerous()
.with_custom_certificate_verifier(SkipServerVerification::new())
.with_no_client_auth(),
)?)));
// connect to server
endpoint
.connect(addr, SERVER_NAME)
.unwrap()
.await
.map_err(|e| anyhow::anyhow!("failed to connect: {e}"))
}
#[tokio::main] #[tokio::main]
async fn connect_the(handle: AppHandle, ip: String) -> anyhow::Result<()> { async fn connect_the(handle: AppHandle, ip: String) -> anyhow::Result<()> {
let dirs = directories_next::ProjectDirs::from("", "", "openworm").unwrap();
let mut roots = quinn::rustls::RootCertStore::empty();
match fs::read(dirs.data_local_dir().join("cert.der")) {
Ok(cert) => {
roots.add(CertificateDer::from(cert))?;
}
Err(ref e) if e.kind() == ErrorKind::NotFound => {
eprintln!("local server certificate not found");
}
Err(e) => {
eprintln!("failed to open local server certificate: {}", e);
}
}
let client_crypto = quinn::rustls::ClientConfig::builder()
.with_root_certificates(roots)
.with_no_client_auth();
let client_config =
quinn::ClientConfig::new(Arc::new(QuicClientConfig::try_from(client_crypto)?));
let mut endpoint = quinn::Endpoint::client(SocketAddr::from_str("[::]:0").unwrap())?;
endpoint.set_default_client_config(client_config);
let remote = SocketAddr::from_str(&ip).unwrap();
// let remote = SocketAddr::new(IpAddr::V6(Ipv6Addr::LOCALHOST), 4433);
let host = "localhost";
let conn = endpoint
.connect(remote, host)?
.await
.map_err(|e| anyhow::anyhow!("failed to connect: {}", e))?;
let (client_send, mut client_recv) = tokio::sync::mpsc::unbounded_channel::<NetCmd>(); let (client_send, mut client_recv) = tokio::sync::mpsc::unbounded_channel::<NetCmd>();
handle.send(ClientEvent::Connect(client_send)); handle.send(ClientEvent::Connect(client_send));
let addr = SocketAddr::from_str(&ip).unwrap();
let conn = connection_no_cert(addr).await?;
while let Some(msg) = client_recv.recv().await { while let Some(msg) = client_recv.recv().await {
match msg { match msg {
@@ -61,7 +83,7 @@ async fn connect_the(handle: AppHandle, ip: String) -> anyhow::Result<()> {
let (mut send, recv) = conn let (mut send, recv) = conn
.open_bi() .open_bi()
.await .await
.map_err(|e| anyhow::anyhow!("failed to open stream: {}", e))?; .map_err(|e| anyhow::anyhow!("failed to open stream: {e}"))?;
drop(recv); drop(recv);

View File

@@ -1,4 +1,8 @@
pub mod client; pub mod client;
mod no_cert;
pub mod server;
pub const SERVER_NAME: &str = "openworm";
pub enum ClientMsg { pub enum ClientMsg {
SendMsg { content: String }, SendMsg { content: String },

56
src/net/no_cert.rs Normal file
View File

@@ -0,0 +1,56 @@
use quinn::rustls::{self, pki_types::*};
use std::sync::Arc;
#[derive(Debug)]
pub struct SkipServerVerification(Arc<rustls::crypto::CryptoProvider>);
impl SkipServerVerification {
pub fn new() -> Arc<Self> {
Arc::new(Self(Arc::new(rustls::crypto::ring::default_provider())))
}
}
impl rustls::client::danger::ServerCertVerifier for SkipServerVerification {
fn verify_server_cert(
&self,
_end_entity: &CertificateDer<'_>,
_intermediates: &[CertificateDer<'_>],
_server_name: &ServerName<'_>,
_ocsp: &[u8],
_now: UnixTime,
) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
Ok(rustls::client::danger::ServerCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &rustls::DigitallySignedStruct,
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
rustls::crypto::verify_tls12_signature(
message,
cert,
dss,
&self.0.signature_verification_algorithms,
)
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &rustls::DigitallySignedStruct,
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
rustls::crypto::verify_tls13_signature(
message,
cert,
dss,
&self.0.signature_verification_algorithms,
)
}
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
self.0.signature_verification_algorithms.supported_schemes()
}
}

49
src/net/server.rs Normal file
View File

@@ -0,0 +1,49 @@
use crate::net::SERVER_NAME;
use quinn::{
Endpoint, ServerConfig,
rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer},
};
use std::net::{Ipv6Addr, SocketAddr, SocketAddrV6};
use std::{fs, path::Path};
pub const DEFAULT_PORT: u16 = 16839;
pub const SERVER_HOST: Ipv6Addr = Ipv6Addr::UNSPECIFIED;
pub const SERVER_SOCKET: SocketAddr =
SocketAddr::V6(SocketAddrV6::new(SERVER_HOST, DEFAULT_PORT, 0, 0));
pub fn listen(data_path: &Path) -> Endpoint {
let cert_path = data_path.join("cert.der");
let key_path = data_path.join("key.der");
let (cert, key) = match fs::read(&cert_path).and_then(|x| Ok((x, fs::read(&key_path)?))) {
Ok((cert, key)) => (
CertificateDer::from(cert),
PrivateKeyDer::try_from(key).unwrap(),
),
Err(ref e) if e.kind() == std::io::ErrorKind::NotFound => {
let cert = rcgen::generate_simple_self_signed([SERVER_NAME.into()]).unwrap();
let key = PrivatePkcs8KeyDer::from(cert.signing_key.serialize_der());
let cert = cert.cert.into();
fs::create_dir_all(data_path).expect("failed to create certificate directory");
fs::write(&cert_path, &cert).expect("failed to write certificate");
fs::write(&key_path, key.secret_pkcs8_der()).expect("failed to write private key");
(cert, key.into())
}
Err(e) => {
panic!("failed to read certificate: {}", e);
}
};
// let server_crypto = quinn::rustls::ServerConfig::builder()
// .with_no_client_auth()
// .with_single_cert(vec![cert], key)
// .unwrap();
//
// let server_config = quinn::ServerConfig::with_crypto(Arc::new(
// QuicServerConfig::try_from(server_crypto).unwrap(),
// ));
let server_config = ServerConfig::with_single_cert(vec![cert], key).unwrap();
// let transport_config = Arc::get_mut(&mut server_config.transport).unwrap();
// transport_config.max_concurrent_uni_streams(0_u8.into());
quinn::Endpoint::server(server_config, SERVER_SOCKET).unwrap()
}

View File

@@ -1,19 +1,8 @@
use quinn::{ use crate::net::{ClientMsg, server::listen};
Endpoint,
crypto::rustls::QuicServerConfig,
rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer},
};
use std::{fs, net::SocketAddr, path::Path, str::FromStr, sync::Arc};
use tracing::Instrument; use tracing::Instrument;
use crate::net::ClientMsg;
#[tokio::main] #[tokio::main]
pub async fn run_server() { pub async fn run_server() {
quinn::rustls::crypto::aws_lc_rs::default_provider()
.install_default()
.unwrap();
let dirs = directories_next::ProjectDirs::from("", "", "openworm").unwrap(); let dirs = directories_next::ProjectDirs::from("", "", "openworm").unwrap();
let path = dirs.data_local_dir(); let path = dirs.data_local_dir();
let endpoint = listen(path); let endpoint = listen(path);
@@ -27,43 +16,6 @@ pub async fn run_server() {
} }
}); });
} }
println!("hello world!");
}
pub fn listen(data_path: &Path) -> Endpoint {
let cert_path = data_path.join("cert.der");
let key_path = data_path.join("key.der");
let (cert, key) = match fs::read(&cert_path).and_then(|x| Ok((x, fs::read(&key_path)?))) {
Ok((cert, key)) => (
CertificateDer::from(cert),
PrivateKeyDer::try_from(key).unwrap(),
),
Err(ref e) if e.kind() == std::io::ErrorKind::NotFound => {
let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap();
let key = PrivatePkcs8KeyDer::from(cert.signing_key.serialize_der());
let cert = cert.cert.into();
fs::create_dir_all(data_path).expect("failed to create certificate directory");
fs::write(&cert_path, &cert).expect("failed to write certificate");
fs::write(&key_path, key.secret_pkcs8_der()).expect("failed to write private key");
(cert, key.into())
}
Err(e) => {
panic!("failed to read certificate: {}", e);
}
};
let server_crypto = quinn::rustls::ServerConfig::builder()
.with_no_client_auth()
.with_single_cert(vec![cert], key)
.unwrap();
let mut server_config = quinn::ServerConfig::with_crypto(Arc::new(
QuicServerConfig::try_from(server_crypto).unwrap(),
));
let transport_config = Arc::get_mut(&mut server_config.transport).unwrap();
transport_config.max_concurrent_uni_streams(0_u8.into());
quinn::Endpoint::server(server_config, SocketAddr::from_str("[::1]:4433").unwrap()).unwrap()
} }
async fn handle_connection(conn: quinn::Incoming) -> std::io::Result<()> { async fn handle_connection(conn: quinn::Incoming) -> std::io::Result<()> {