Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add openssl support in transport module with some enhancement and bug fix #4

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 14 additions & 0 deletions examples/tls/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[package]
name = "tls"
edition.workspace = true
version.workspace = true
readme.workspace = true
license.workspace = true

[dependencies]
rats-rs = {path = "../../rats-rs", features = ["is-sync"]}
env_logger = {workspace = true}
clap = {version = "4.5.4", features = ["derive"]}
anyhow = {workspace = true}
log = {workspace = true}
rand = {version = "0.8.5", features = ["small_rng"]}
45 changes: 45 additions & 0 deletions examples/tls/src/echo/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
use crate::{
tls::{with_tls_tcp_client, with_tls_tcp_server},
CommonClientOptions, CommonServerOptions,
};
use anyhow::Result;
use log::info;
use rand::{rngs::SmallRng, RngCore, SeedableRng};
use rats_rs::transport::{GenericSecureTransPortRead, GenericSecureTransPortWrite};

pub fn echo_client(opts: CommonClientOptions) -> Result<()> {
with_tls_tcp_client(opts, |mut c| {
let mut rng = SmallRng::from_entropy();
for _i in 0..128 {
let mut expected = [0u8; 8];
let expected_len = expected.len();

rng.fill_bytes(&mut expected);
c.send(&expected)?;

let mut buffer = [0u8; 1024];
let recv_len = c.receive(&mut buffer[..expected_len])?;

assert_eq!(expected_len, recv_len);
assert_eq!(expected, buffer[..expected_len]);
info!("{}/128: passed", _i + 1);
}
c.shutdown()?;
Ok(())
})?;
Ok(())
}

pub fn echo_server(opts: CommonServerOptions) -> Result<()> {
with_tls_tcp_server(opts, |mut s| {
let mut buffer = [0u8; 1024];
let buffer_len = buffer.len();
for _i in 0..128 {
let recv_len = s.receive(&mut buffer[..buffer_len])?;
s.send(&mut buffer[..recv_len])?;
}
s.shutdown()?;
Ok(())
})?;
Ok(())
}
86 changes: 86 additions & 0 deletions examples/tls/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
mod echo;
mod tls;

use anyhow::Result;
use clap::{arg, ArgAction, Parser};
use echo::{echo_client, echo_server};

#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
enum TlsCommand {
#[command(name = "echo-client")]
EchoClient(CommonClientOptions),
#[command(name = "echo-server")]
EchoServer(CommonServerOptions),
}

#[derive(Parser, Debug)]
struct CommonServerOptions {
/// Whether to attest self to peer. Defaults to `true`.
#[arg(
long,
default_missing_value("true"),
default_value("true"),
num_args(0..=1),
require_equals(true),
action = ArgAction::Set,
)]
attest_self: bool,

/// Whether to verify peer. Defaults to `false`.
#[arg(
long,
default_missing_value("true"),
default_value("false"),
num_args(0..=1),
require_equals(true),
action = ArgAction::Set,
)]
verify_peer: bool,

/// The ip:port to listen on for TCP connections.
#[arg(long)]
listen_on_tcp: String,
}

#[derive(Parser, Debug, Clone)]
struct CommonClientOptions {
/// Whether to attest self to peer. Defaults to `false`.
#[arg(
long,
default_missing_value("true"),
default_value("false"),
num_args(0..=1),
require_equals(true),
action = ArgAction::Set,
)]
attest_self: bool,

/// Whether to verify peer. Defaults to `true`.
#[arg(
long,
default_missing_value("true"),
default_value("true"),
num_args(0..=1),
require_equals(true),
action = ArgAction::Set,
)]
verify_peer: bool,

/// The ip:port to connect to for TCP connection.
#[arg(long)]
connect_to_tcp: String,
}

fn main() -> Result<()> {
let env = env_logger::Env::default()
.filter_or("RATS_RS_LOG_LEVEL", "debug")
.write_style_or("RATS_RS_LOG_STYLE", "always");
env_logger::Builder::from_env(env).init();
let command = TlsCommand::parse();
match command {
TlsCommand::EchoClient(opts) => echo_client(opts)?,
TlsCommand::EchoServer(opts) => echo_server(opts)?,
}
Ok(())
}
78 changes: 78 additions & 0 deletions examples/tls/src/tls.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
use crate::{CommonClientOptions, CommonServerOptions};
use anyhow::{bail, Result};
use log::info;
use rats_rs::transport::{
tls::{Client, Server, TlsClientBuilder, TlsServerBuilder},
GenericSecureTransPort,
};
use std::net::{SocketAddr, TcpListener, TcpStream};

pub fn with_tls_tcp_client(
opts: CommonClientOptions,
func: impl FnOnce(Client) -> Result<()>,
) -> Result<()> {
let server_addr: SocketAddr = opts.connect_to_tcp.parse().expect("Invalid address");

// Connect to TCP server
let stream = TcpStream::connect(server_addr).expect("Failed to connect to server");

info!("Connected to server: {}", server_addr);

let mut client = TlsClientBuilder::new()
.with_attest_self(opts.attest_self)
.with_tcp_stream(stream)
.build()?;

client.negotiate()?;

info!(
"The tls session on connection {} (responder) is ready.",
server_addr
);

func(client)?;

info!("Everything is fine, exit now.");
Ok(())
}

pub fn with_tls_tcp_server(
opts: CommonServerOptions,
func: impl Fn(Server) -> Result<()>,
) -> Result<()> {
let listen_addr: SocketAddr = opts.listen_on_tcp.parse().expect("Invalid address");

let listener = TcpListener::bind(listen_addr).expect("Failed to bind to address");

info!("Server started, listening on {}", listen_addr);

for stream in listener.incoming() {
match stream {
Ok(stream) => {
let peer_addr = stream.peer_addr().unwrap();
info!("New connection: {}", peer_addr);
let mut server = TlsServerBuilder::new()
.with_verify_peer(opts.verify_peer)
.with_tcp_stream(stream)
.build()?;
server.negotiate()?;

info!(
"The tls session on connection {} (requester) is ready.",
peer_addr
);

func(server)?;

info!(
"The connection {} is shutdown, waiting for another now.",
peer_addr
);
}
Err(e) => {
bail!("Error accepting connection: {}", e);
}
}
}
Ok(())
}
8 changes: 6 additions & 2 deletions rats-rs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,20 +31,24 @@ spdmlib = {workspace = true, optional = true}
spin = {workspace = true}
thiserror = "1.0.56"
tokio = {version = "1.36.0", features = ["full"], optional = true}
x509-cert = {version = "0.2.5", features = ["builder"], optional = true}
x509-cert = {version = "0.2.5", features = ["builder", "hazmat"], optional = true}
zeroize = "1.7.0"
bstr = "1.9.1"
itertools = "0.12.1"
indexmap = {version = "2.2.6", features = ["std", "serde"]}
tdx-attest-rs = {git = "https://github.com/intel/SGXDataCenterAttestationPrimitives", tag = "DCAP_1.20", optional = true}
intel-dcap = {path = "../intel-dcap", optional = true}
openssl-sys = {version = "0.9", optional = true, features = ["bindgen"] }
libc = {version = "0.2", optional = true}
lazy_static = "1.5.0"

[features]
async-tokio = ["dep:tokio"]
crypto-rustcrypto = ["dep:x509-cert", "dep:sha2", "dep:p256", "dep:rsa", "dep:pkcs8", "dep:const-oid", "dep:signature"]
default = ["crypto-rustcrypto", "transport-spdm", "attester-sgx-dcap-occlum", "verifier-sgx-dcap", "attester-tdx", "verifier-tdx", "is-sync"]
default = ["crypto-rustcrypto", "transport-spdm", "attester-sgx-dcap-occlum", "verifier-sgx-dcap", "attester-tdx", "verifier-tdx", "is-sync", "transport-tls"]
is-sync = ["maybe-async/is_sync", "spdmlib/is_sync"]
transport-spdm = ["dep:spdmlib", "dep:codec", "dep:ring"]
transport-tls = ["dep:openssl-sys", "dep:libc"]
attester-sgx-dcap = ["dep:intel-dcap"]
attester-sgx-dcap-occlum = ["attester-sgx-dcap", "dep:occlum_dcap"]
attester-sgx-dcap-enclave = [] # TODO: plain enclave mode
Expand Down
Loading
Loading