diff --git a/Cargo.toml b/Cargo.toml index 83c5de6..9a393b1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -75,5 +75,10 @@ name = "proxy_secure" path = "src/executables/proxy_secure.rs" [[bin]] -name = "backend_server" -path = "src/executables/backend_server.rs" \ No newline at end of file +name = "backend_server_insecure" +path = "src/executables/backend_server_insecure.rs" + + +[[bin]] +name = "backend_server_secure" +path = "src/executables/backend_server_secure.rs" \ No newline at end of file diff --git a/src/executables/backend_server.rs b/src/executables/backend_server.rs deleted file mode 100644 index 4dd5d71..0000000 --- a/src/executables/backend_server.rs +++ /dev/null @@ -1,58 +0,0 @@ -use log::error; -use once_cell::sync::Lazy; -use rustls::client::danger::HandshakeSignatureValid; -use rustls::pki_types::{CertificateDer, TrustAnchor, UnixTime}; -use rustls::server::danger::{ClientCertVerified, ClientCertVerifier}; -use rustls::server::{ClientCertVerifierBuilder, WebPkiClientVerifier}; -use rustls::{ - DigitallySignedStruct, DistinguishedName, Error, RootCertStore, ServerConfig, ServerConnection, - SignatureScheme, -}; -use rustls_pki_types::PrivateKeyDer; -use rust_nex::common::setup; -use rust_nex::reggie::{get_configured_tls_acceptor, TestStruct, ROOT_TRUST_ANCHOR, SELF_CERT, SELF_KEY}; -use std::borrow::ToOwned; -use std::fs; -use std::io::Cursor; -use std::net::{IpAddr, SocketAddr, SocketAddrV4}; -use std::sync::Arc; -use macros::{method_id, rmc_proto, rmc_struct}; -use tokio::io::AsyncReadExt; -use tokio::net::{TcpListener, TcpSocket}; -use tokio::task; -use tokio_rustls::TlsAcceptor; -use rust_nex::define_rmc_proto; -use rust_nex::rmc::protocols::new_rmc_gateway_connection; -use rust_nex::rmc::response::ErrorCode; -use rust_nex::rmc::structures::RmcSerialize; - - - - -#[tokio::main] -async fn main() { - setup(); - - let acceptor = get_configured_tls_acceptor().await; - - let listen = TcpListener::bind("192.168.178.120:2376").await.unwrap(); - - while let Ok((stream, addr)) = listen.accept().await { - let mut stream = match acceptor.accept(stream).await { - Ok(v) => v, - Err(e) => { - error!("an error ocurred whilest accepting tls connection: {:?}", e); - continue; - } - }; - - task::spawn(async move { - new_rmc_gateway_connection(stream.into(), |_| { - Arc::new(TestStruct) - }); - - println!("lost connection lol"); - }); - - } -} diff --git a/src/executables/backend_server_insecure.rs b/src/executables/backend_server_insecure.rs new file mode 100644 index 0000000..6e7f3a3 --- /dev/null +++ b/src/executables/backend_server_insecure.rs @@ -0,0 +1,100 @@ +use rust_nex::reggie::UnitPacketRead; +use log::{error, info}; +use once_cell::sync::Lazy; +use rustls::client::danger::HandshakeSignatureValid; +use rustls::pki_types::{CertificateDer, TrustAnchor, UnixTime}; +use rustls::server::danger::{ClientCertVerified, ClientCertVerifier}; +use rustls::server::{ClientCertVerifierBuilder, WebPkiClientVerifier}; +use rustls::{ + DigitallySignedStruct, DistinguishedName, Error, RootCertStore, ServerConfig, ServerConnection, + SignatureScheme, +}; +use rustls_pki_types::PrivateKeyDer; +use rust_nex::common::setup; +use rust_nex::reggie::{get_configured_tls_acceptor, TestStruct, ROOT_TRUST_ANCHOR, SELF_CERT, SELF_KEY}; +use std::borrow::ToOwned; +use std::{env, fs}; +use std::io::Cursor; +use std::net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4}; +use std::sync::Arc; +use macros::{method_id, rmc_proto, rmc_struct}; +use tokio::io::AsyncReadExt; +use tokio::net::{TcpListener, TcpSocket}; +use tokio::task; +use tokio_rustls::TlsAcceptor; +use rust_nex::define_rmc_proto; +use rust_nex::executables::common::{OWN_IP_PRIVATE, SECURE_SERVER_ACCOUNT, SERVER_PORT}; +use rust_nex::nex::auth_handler::AuthHandler; +use rust_nex::rmc::protocols::new_rmc_gateway_connection; +use rust_nex::rmc::response::ErrorCode; +use rust_nex::rmc::structures::RmcSerialize; +use rust_nex::rnex_proxy_common::ConnectionInitData; + +pub static SECURE_PROXY_ADDR: Lazy = Lazy::new(|| { + env::var("SECURE_PROXY_ADDR") + .ok() + .and_then(|s| s.parse().ok()) + .expect("no secure proxy ip specified") +}); + +pub static SECURE_PROXY_PORT: Lazy = Lazy::new(|| { + env::var("SECURE_PROXY_PORT") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(10000) +}); + +static SECURE_STATION_URL: Lazy = Lazy::new(|| { + format!( + "prudps:/PID=2;sid=1;stream=10;type=2;address={};port={};CID=1", + *SECURE_PROXY_ADDR, *SECURE_PROXY_PORT + ) +}); + +#[tokio::main] +async fn main() { + setup(); + + let acceptor = get_configured_tls_acceptor().await; + + let listen = TcpListener::bind(SocketAddrV4::new(*OWN_IP_PRIVATE, *SERVER_PORT)).await.unwrap(); + + while let Ok((stream, addr)) = listen.accept().await { + let mut stream = match acceptor.accept(stream).await { + Ok(v) => v, + Err(e) => { + error!("an error ocurred whilest accepting tls connection: {:?}", e); + continue; + } + }; + let buffer = match stream.read_buffer().await{ + Ok(v) => v, + Err(e) => { + error!("an error ocurred whilest reading connection data buffer: {:?}", e); + continue; + } + }; + + let user_connection_data = ConnectionInitData::deserialize(&mut Cursor::new(buffer)); + + let user_connection_data = match user_connection_data{ + Ok(v) => v, + Err(e) => { + error!("an error ocurred whilest reading connection data: {:?}", e); + continue; + } + }; + + task::spawn(async move { + info!("connection to secure backend established"); + new_rmc_gateway_connection(stream.into(), |_| { + Arc::new(AuthHandler { + destination_server_acct: &SECURE_SERVER_ACCOUNT, + build_name: "branch:origin/project/wup-agmj build:3_8_15_2004_0", + station_url: &SECURE_STATION_URL, + }) + }); + }); + + } +} diff --git a/src/executables/backend_server_secure.rs b/src/executables/backend_server_secure.rs new file mode 100644 index 0000000..5744e8c --- /dev/null +++ b/src/executables/backend_server_secure.rs @@ -0,0 +1,84 @@ +use std::io::Cursor; +use rust_nex::rmc::structures::RmcSerialize; +use rust_nex::reggie::UnitPacketRead; +use std::net::SocketAddrV4; +use std::sync::Arc; +use std::sync::atomic::AtomicU32; +use log::{error, info}; +use tokio::net::TcpListener; +use tokio::task; +use rust_nex::common::setup; +use rust_nex::executables::common::{OWN_IP_PRIVATE, SERVER_PORT}; +use rust_nex::nex::matchmake::MatchmakeManager; +use rust_nex::nex::remote_console::RemoteConsole; +use rust_nex::nex::user::User; +use rust_nex::reggie::get_configured_tls_acceptor; +use rust_nex::rmc::protocols::new_rmc_gateway_connection; +use rust_nex::rnex_proxy_common::ConnectionInitData; +use rust_nex::rmc::protocols::RemoteInstantiatable; + + +#[tokio::main] +async fn main() { + setup(); + + let acceptor = get_configured_tls_acceptor().await; + + let listen = TcpListener::bind(SocketAddrV4::new(*OWN_IP_PRIVATE, *SERVER_PORT)).await.unwrap(); + + let mmm = Arc::new(MatchmakeManager{ + gid_counter: AtomicU32::new(1), + sessions: Default::default(), + users: Default::default(), + rv_cid_counter: AtomicU32::new(1), + }); + + let weak_mmm = Arc::downgrade(&mmm); + + MatchmakeManager::initialize_garbage_collect_thread(weak_mmm).await; + + while let Ok((stream, addr)) = listen.accept().await { + let mut stream = match acceptor.accept(stream).await { + Ok(v) => v, + Err(e) => { + error!("an error ocurred whilest accepting tls connection: {:?}", e); + continue; + } + }; + + let buffer = match stream.read_buffer().await{ + Ok(v) => v, + Err(e) => { + error!("an error ocurred whilest reading connection data buffer: {:?}", e); + continue; + } + }; + + let user_connection_data = ConnectionInitData::deserialize(&mut Cursor::new(buffer)); + + let user_connection_data = match user_connection_data{ + Ok(v) => v, + Err(e) => { + error!("an error ocurred whilest reading connection data: {:?}", e); + continue; + } + }; + + + let mmm = mmm.clone(); + task::spawn(async move { + info!("connection to secure backend established"); + new_rmc_gateway_connection(stream.into(), |r| { + Arc::new_cyclic(|this| User{ + this: this.clone(), + ip: user_connection_data.prudpsock_addr, + pid: user_connection_data.pid, + remote: RemoteConsole::new(r), + matchmake_manager: mmm, + station_url: Default::default() + }) + }); + }); + + } +} \ No newline at end of file diff --git a/src/executables/common.rs b/src/executables/common.rs new file mode 100644 index 0000000..0b81da8 --- /dev/null +++ b/src/executables/common.rs @@ -0,0 +1,29 @@ +use std::env; +use std::net::Ipv4Addr; +use once_cell::sync::Lazy; +use crate::nex::account::Account; + +pub static OWN_IP_PRIVATE: Lazy = Lazy::new(|| { + env::var("SERVER_IP") + .ok() + .and_then(|s| s.parse().ok()) + .expect("no private ip specified") +}); + +pub static SERVER_PORT: Lazy = Lazy::new(|| { + env::var("SERVER_PORT") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(10000) +}); + +pub static KERBEROS_SERVER_PASSWORD: Lazy = Lazy::new(|| { + env::var("AUTH_SERVER_PASSWORD") + .ok() + .unwrap_or("password".to_owned()) +}); + +pub static AUTH_SERVER_ACCOUNT: Lazy = + Lazy::new(|| Account::new(1, "Quazal Authentication", &KERBEROS_SERVER_PASSWORD)); +pub static SECURE_SERVER_ACCOUNT: Lazy = + Lazy::new(|| Account::new(2, "Quazal Rendez-Vous", &KERBEROS_SERVER_PASSWORD)); diff --git a/src/executables/mod.rs b/src/executables/mod.rs new file mode 100644 index 0000000..ffac467 --- /dev/null +++ b/src/executables/mod.rs @@ -0,0 +1 @@ +pub mod common; \ No newline at end of file diff --git a/src/executables/proxy_insecure.rs b/src/executables/proxy_insecure.rs index 17454f2..5860f13 100644 --- a/src/executables/proxy_insecure.rs +++ b/src/executables/proxy_insecure.rs @@ -1,4 +1,4 @@ -mod proxy_secure; + use std::env; use std::ffi::CStr; @@ -18,6 +18,7 @@ use sha2::Sha256; use tokio::net::TcpSocket; use tokio::task; use rust_nex::common::setup; +use rust_nex::executables::common::{OWN_IP_PRIVATE, SERVER_PORT}; use rust_nex::prudp::packet::VirtualPort; use rust_nex::prudp::router::Router; use rust_nex::prudp::unsecure::Unsecure; @@ -25,25 +26,12 @@ use rust_nex::reggie::{establish_tls_connection_to, UnitPacketRead, UnitPacketWr use rust_nex::rmc::structures::RmcSerialize; use rust_nex::rnex_proxy_common::ConnectionInitData; -static OWN_IP_PRIVATE: Lazy = Lazy::new(|| { - env::var("SERVER_IP") - .ok() - .and_then(|s| s.parse().ok()) - .expect("no public ip specified") -}); -static OWN_IP_PUBLIC: Lazy = - Lazy::new(|| env::var("SERVER_IP_PUBLIC").unwrap_or(OWN_IP_PRIVATE.to_string())); - -static SERVER_PORT: Lazy = Lazy::new(|| { - env::var("AUTH_SERVER_PORT") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(10000) -}); static FORWARD_DESTINATION: Lazy = - Lazy::new(|| env::var("FORWARD_DESTINATION").unwrap_or(OWN_IP_PRIVATE.to_string())); + Lazy::new(|| env::var("FORWARD_DESTINATION").expect("no forward destination given")); +static FORWARD_DESTINATION_NAME: Lazy = + Lazy::new(|| env::var("FORWARD_DESTINATION_NAME").expect("no forward destination name given")); static RSA_PRIVKEY: Lazy = Lazy::new(|| { let path = env::var("RSA_PRIVKEY") @@ -90,10 +78,11 @@ async fn main() { task::spawn(async move { let mut stream - = establish_tls_connection_to("192.168.178.120:2376", "account.spfn.net").await; + = establish_tls_connection_to(FORWARD_DESTINATION.as_str(), FORWARD_DESTINATION_NAME.as_str()).await; if let Err(e) = stream.send_buffer(&ConnectionInitData{ - prudpsock_addr: conn.socket_addr + prudpsock_addr: conn.socket_addr, + pid: conn.user_id }.to_data()).await{ error!("error connecting to backend: {}", e); return; diff --git a/src/executables/proxy_secure.rs b/src/executables/proxy_secure.rs index dbbafe1..2fea0ac 100644 --- a/src/executables/proxy_secure.rs +++ b/src/executables/proxy_secure.rs @@ -1,26 +1,102 @@ -use rust_nex::reggie::RemoteRmcTestProto; -use std::fs; -use std::net::IpAddr; -use std::sync::Arc; -use rustls::ClientConfig; -use rustls_pki_types::ServerName; -use tokio::io::AsyncWriteExt; -use tokio::net::TcpStream; -use tokio_rustls::{TlsConnector, TlsStream}; -use rust_nex::common::setup; -use rust_nex::reggie::{establish_tls_connection_to, get_configured_tls_connector, RemoteTestProto, UnitPacketWrite}; -use rust_nex::rmc::protocols::{new_rmc_gateway_connection, OnlyRemote}; -use rust_nex::rmc::structures::RmcSerialize; +use std::env; +use std::ffi::CStr; +use std::io::{Read, Write}; +use std::net::{Ipv4Addr, SocketAddrV4, TcpListener, TcpStream}; +use bytemuck::{Pod, Zeroable}; +use chacha20::{ChaCha20, Key}; +use chacha20::cipher::{Iv, KeyIvInit, StreamCipher}; +use log::error; +use once_cell::sync::Lazy; +use rsa::pkcs8::{DecodePrivateKey, DecodePublicKey, Document}; +use rsa::{BigUint, Pkcs1v15Encrypt, RsaPrivateKey, RsaPublicKey}; +use rsa::pkcs1::EncodeRsaPublicKey; +use rsa::pss::BlindedSigningKey; +use rsa::signature::{RandomizedSigner, SignatureEncoding}; +use sha2::Sha256; +use tokio::net::TcpSocket; +use tokio::task; +use rust_nex::common::setup; +use rust_nex::executables::common::{OWN_IP_PRIVATE, SECURE_SERVER_ACCOUNT, SERVER_PORT}; +use rust_nex::prudp::packet::VirtualPort; +use rust_nex::prudp::router::Router; +use rust_nex::prudp::secure::Secure; +use rust_nex::prudp::unsecure::Unsecure; +use rust_nex::reggie::{establish_tls_connection_to, UnitPacketRead, UnitPacketWrite}; +use rust_nex::rmc::structures::RmcSerialize; +use rust_nex::rnex_proxy_common::ConnectionInitData; + + + +static FORWARD_DESTINATION: Lazy = + Lazy::new(|| env::var("FORWARD_DESTINATION").expect("no forward destination given")); +static FORWARD_DESTINATION_NAME: Lazy = + Lazy::new(|| env::var("FORWARD_DESTINATION_NAME").expect("no forward destination name given")); + #[tokio::main] -async fn main(){ +async fn main() { setup(); - let mut stream - = establish_tls_connection_to("192.168.178.120:2376", "account.spfn.net").await; + let (router_secure, _) = Router::new(SocketAddrV4::new(*OWN_IP_PRIVATE, *SERVER_PORT)) + .await + .expect("unable to start router"); - let remo = new_rmc_gateway_connection(stream.into(), |r| Arc::new(OnlyRemote::::new(r)) ); + let mut socket_secure = router_secure + .add_socket(VirtualPort::new(1, 10), Secure( + "6f599f81", + &SECURE_SERVER_ACCOUNT + )) + .await + .expect("unable to add socket"); - println!("{:?}", remo.test().await); + // let conn = socket_secure.connect(auth_sockaddr).await.unwrap(); + + loop { + let Some(mut conn) = socket_secure.accept().await else { + error!("server crashed"); + return; + }; + + task::spawn(async move { + let mut stream + = establish_tls_connection_to(FORWARD_DESTINATION.as_str(), FORWARD_DESTINATION_NAME.as_str()).await; + + if let Err(e) = stream.send_buffer(&ConnectionInitData{ + prudpsock_addr: conn.socket_addr, + pid: conn.user_id + }.to_data()).await{ + error!("error connecting to backend: {}", e); + return; + }; + + loop { + tokio::select! { + data = conn.recv() => { + let Some(data) = data else { + break; + }; + + if let Err(e) = stream.send_buffer(&data[..]).await{ + error!("error sending data to backend: {}", e); + break; + } + }, + data = stream.read_buffer() => { + let data = match data{ + Ok(d) => d, + Err(e) => { + error!("error reveiving data from backend: {}", e); + break; + } + }; + + if conn.send(data).await == None{ + return; + } + }, + } + } + }); + } } \ No newline at end of file diff --git a/src/grpc/account.rs b/src/grpc/account.rs index 0700a7c..4ec4752 100644 --- a/src/grpc/account.rs +++ b/src/grpc/account.rs @@ -20,7 +20,7 @@ use crate::grpc::protobufs::account::{GetNexPasswordRequest, GetUserDataRequest, static API_KEY: Lazy = Lazy::new(||{ let key = env::var("ACCOUNT_GQL_API_KEY") - .expect("no public ip specified"); + .expect("no graphql ip specified"); key }); @@ -29,7 +29,7 @@ static CLIENT_URI: Lazy = Lazy::new(||{ env::var("ACCOUNT_GQL_URL") .ok() .and_then(|s| s.parse().ok()) - .expect("no public ip specified") + .expect("no graphql ip specified") }); diff --git a/src/lib.rs b/src/lib.rs index 775b940..fb941c0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -15,3 +15,4 @@ pub mod common; pub mod reggie; pub mod rnex_proxy_common; pub mod util; +pub mod executables; diff --git a/src/main.rs b/src/main.rs index af9a3bd..34350ba 100644 --- a/src/main.rs +++ b/src/main.rs @@ -94,7 +94,7 @@ static OWN_IP_PRIVATE: Lazy = Lazy::new(|| { env::var("SERVER_IP") .ok() .and_then(|s| s.parse().ok()) - .expect("no public ip specified") + .expect("no private ip specified") }); static OWN_IP_PUBLIC: Lazy = diff --git a/src/reggie.rs b/src/reggie.rs index 449c7dd..9985ec9 100644 --- a/src/reggie.rs +++ b/src/reggie.rs @@ -1,4 +1,4 @@ -use std::{fs, io}; +use std::{env, fs, io}; use std::sync::Arc; use macros::{method_id, rmc_proto, rmc_struct}; use once_cell::sync::Lazy; @@ -16,9 +16,13 @@ use crate::endianness::IS_BIG_ENDIAN; use crate::rmc::response::ErrorCode; use crate::rmc::structures::RmcSerialize; -pub static SELF_CERT: Lazy> = Lazy::new(|| CertificateDer::from(fs::read("/opt/reggie/certs/SELF.crt").expect("failed to read self cpub ertificate"))); +pub static SERVER_NAME: Lazy = Lazy::new(|| { + env::var("REGGIE_SERVER_NAME").expect("no server name specified") +}); + +pub static SELF_CERT: Lazy> = Lazy::new(|| CertificateDer::from(fs::read(&format!("/opt/reggie/certs/{}.crt", SERVER_NAME.as_str())).expect("failed to read self cpub ertificate"))); pub static ROOT_CA: Lazy> = Lazy::new(|| CertificateDer::from(fs::read("/opt/reggie/certs/CA.crt").expect("failed to read root certipub ficate"))); -pub static SELF_KEY: Lazy> = Lazy::new(|| PrivateKeyDer::try_from(fs::read("/opt/reggie/certs/SELF.key").expect("failed to read self pub key")).expect("failed to read self key")); +pub static SELF_KEY: Lazy> = Lazy::new(|| PrivateKeyDer::try_from(fs::read(&format!("/opt/reggie/certs/{}.key", SERVER_NAME.as_str())).expect("failed to read self pub key")).expect("failed to read self key")); pub static ROOT_TRUST_ANCHOR: Lazy> = Lazy::new(|| anchor_from_trusted_cert(&*ROOT_CA).expect("unable to create root ca trust anchor")); @@ -134,6 +138,7 @@ define_rmc_proto!( RmcTestProto } ); + #[rmc_struct(TestProto)] pub struct TestStruct; diff --git a/src/rnex_proxy_common.rs b/src/rnex_proxy_common.rs index a4ee7e6..f04cf3e 100644 --- a/src/rnex_proxy_common.rs +++ b/src/rnex_proxy_common.rs @@ -6,5 +6,7 @@ use crate::prudp::sockaddr::PRUDPSockAddr; #[rmc_struct(0)] pub struct ConnectionInitData{ pub prudpsock_addr: PRUDPSockAddr, + pub pid: u32, + }