relocate shellchat net tls sub-commands to libs/tls/src/cmd.rs

This commit is contained in:
nworbnhoj 2023-06-27 14:24:11 +10:00
parent d6fe702278
commit aeeff17a6a
4 changed files with 15 additions and 180 deletions

View file

@ -20,5 +20,9 @@ net = { path = "../../services/net" }
pddb = { path = "../../services/pddb" }
rkyv = "0.4.3"
rustls = { version = "0.21.2", features = ["dangerous_configuration"]}
# note requirement for patch to xous-ring in workspace Cargo.toml
rustls = { version = "0.21.2", features = ["dangerous_configuration"] }
webpki = { package = "rustls-webpki", version = "0.100.1" }
webpki-roots = {version = "0.23.1" }
x509-parser = "0.15.0"

View file

@ -1,3 +1,4 @@
pub mod cmd;
pub mod danger;
use modals::Modals;

View file

@ -76,13 +76,7 @@ tracing-subscriber = {version = "0.3.11", optional = true}
# for rustls testing
tls = {path="../../libs/tls"}
# note requirement for patch to xous-ring in workspace Cargo.toml
rustls = {version = "0.21.2", optional = true}
webpki-roots = {version = "0.22.4", optional = true}
url = {version = "2.2.2", optional = true}
x509-parser = "0.15.0"
# for testing ring math functions
# note requirement for patch to xous-ring in workspace Cargo.toml
ring = {version = "0.16.20", optional = true}
@ -132,7 +126,7 @@ dbg-ecupdate = [] # for issuing manual commands to initiate an EC update (vs UX)
test-rekey = []
no-codec = []
nettest = [] # batch network tests
tls = ["rustls", "webpki-roots", "ring", "tungstenite", "url"]
tls = ["ring", "tungstenite", "url"]
shellperf = ["ring", "perflib", "xous/v2p", "random-pick"] # this also needs the project-wide "perfcounter" feature to be selected. shellchat is the exclusive manager of the performance counter, do not use with e.g. "vaultperf" feature
extra-tests = []
mass-storage = []

View file

@ -24,12 +24,7 @@ use net::XousServerId;
use perflib::*;
#[cfg(feature = "tls")]
use {
rustls::{Certificate, OwnedTrustAnchor},
std::convert::TryInto,
tls::{danger, Trusted},
tungstenite::{stream::MaybeTlsStream, WebSocket},
};
use tungstenite::{stream::MaybeTlsStream, WebSocket};
pub struct NetCmd {
callback_id: Option<u32>,
@ -459,173 +454,14 @@ impl<'a> ShellCmdApi<'a> for NetCmd {
write!(ret, "\nWeb socket session closed.").ok();
}
}
// net tls <sub-command>
// mozilla trust all Root CA's in webpki-roots
// probe <host> save host CA'a if trusted
// test <host> make tls connection to host
// trusted list trusted CA certificates
#[cfg(feature = "tls")]
"tls" => {
match tokens.next() {
// save/trust all Root CA's in webpki-roots en-masse
Some("mozilla") => {
let mut rotas: Vec<tls::RustlsOwnedTrustAnchor> = webpki_roots::TLS_SERVER_ROOTS
.0
.iter()
.map(|ta| tls::RustlsOwnedTrustAnchor::from_subject_spki_name_constraints(
ta.subject,
ta.spki,
ta.name_constraints,
))
.collect();
let mut i = 0;
for rota in rotas {
tls::save_cert(format!("webpki-root-{i}").as_str(), &rota).unwrap();
i += 1;
}
}
// probe establishes a tls connection to the supplied host, extracts the
// certificates offered and immediately closes the connection.
// The certificates are presented by modal to the user, and saved to the
// pddb if trusted.
Some("probe") => {
log::set_max_level(log::LevelFilter::Info);
log::info!("starting TLS probe");
// Attempt to open the tls connection with an empty root_store
let mut root_store = rustls::RootCertStore::empty();
// Stifle the default rustls certificate verification's complaint about an
// unknown/untrusted CA root certificate so that we get to see the certificate chain
let stifled_verifier =
Arc::new(danger::StifledCertificateVerification {
roots: root_store,
});
let config = rustls::ClientConfig::builder()
.with_safe_defaults()
.with_custom_certificate_verifier(stifled_verifier)
.with_no_client_auth();
let target = match tokens.next() {
Some(target) => target,
None => "bunnyfoo.com",
};
let server_name = target.try_into().unwrap_or_else(|e| {
log::warn!("failed to create sever_name from {target}: {e}");
write!(ret, "failed to create sever_name from {target}");
"bunnyfoo.com".try_into().unwrap()
});
let mut conn =
rustls::ClientConnection::new(Arc::new(config), server_name)
.unwrap();
log::info!("connect TCPstream to {}", target);
let url = format!("{}:443", target);
let mut sock = match TcpStream::connect(url) {
Ok(mut sock) => {
match conn.complete_io(&mut sock) {
Ok(_) => log::info!("handshake complete"),
Err(e) => {
write!(ret, "{e}").ok();
log::warn!("{e}");
}
}
conn.send_close_notify();
match conn.peer_certificates() {
Some(certificates) => tls::check_trust(certificates),
None => false,
};
}
Err(e) => {
write!(ret, "{e}").ok();
log::warn!("{e}")
}
};
log::set_max_level(log::LevelFilter::Info);
}
Some("test") => {
log::set_max_level(log::LevelFilter::Info);
log::info!("starting TLS run");
log::info!("build TLS client config");
let trusted = Trusted::new().unwrap();
let config = rustls::ClientConfig::builder()
.with_safe_defaults()
.with_root_certificates(trusted.into())
.with_no_client_auth();
let target = match tokens.next() {
Some(target) => target,
None => "bunnyfoo.com",
};
log::info!("point TLS to {}", target);
let mut conn = rustls::ClientConnection::new(
Arc::new(config),
target.try_into().unwrap(),
)
.unwrap();
log::info!("connect TCPstream to {}", target);
let url = format!("{}:443", target);
match TcpStream::connect(url) {
Ok(mut sock) => {
log::info!("tcp connected");
write!(ret, "tcp connected\n").ok();
let mut tls = rustls::Stream::new(&mut conn, &mut sock);
log::info!("create http headers and write to server");
let msg = format!("GET / HTTP/1.1\r\nHost: {}\r\nConnection: close\r\nAccept-Encoding: identity\r\n\r\n", target);
match tls.write_all(msg.as_bytes()) {
Ok(()) => {
log::info!("tls accepted GET");
write!(ret, "tls accepted GET\n").ok();
let mut plaintext = Vec::new();
log::info!("read TLS response");
match tls.read_to_end(&mut plaintext) {
Ok(n) => {
log::info!("tls received {} bytes", n);
write!(ret, "tls received {} bytes\n", n).ok();
log::info!(
"{}",
std::str::from_utf8(&plaintext)
.unwrap_or("utf-error")
);
}
Err(e) => {
log::warn!("failed to read tls response: {e}");
write!(ret, "{e}\n").ok();
}
};
}
Err(e) => {
log::warn!("failed to GET on tls connection: {e}");
write!(ret, "{e}\n").ok();
}
};
}
Err(e) => {
log::warn!("failed to connect tcp: {e}");
write!(ret, "{e}\n").ok();
}
};
log::set_max_level(log::LevelFilter::Info);
}
// list trusted Certificate Authority certificates
Some("trusted") => {
log::set_max_level(log::LevelFilter::Info);
log::info!("starting TLS trusted listing");
let trusted =
Trusted::new().expect("failed to initiate trusted iterator");
for rota in trusted {
write!(ret, "🏛 {}\n", rota.subject()).ok();
}
log::info!("finished TLS trusted listing");
}
_ | None => {
write!(ret, "net tls <sub-command>\n").ok();
write!(
ret,
"\tmozilla\ttrust all Root CA's in webpki-roots\n"
)
.ok();
write!(ret, "\tprobe <host>\tsave host CA'a if trusted\n").ok();
write!(ret, "\ttest <host>\tmake tls connection to host\n")
.ok();
write!(ret, "\ttrusted\tlist trusted CA certificates\n").ok();
}
}
"tls" => if let Ok(Some(r)) = tls::cmd::shellchat(&mut tokens) {
write!(ret, "{r}").unwrap();
}
// note: to use the `shellperf` option, you need to load a version of the SOC that has the performance counters built in.
// this can be generated using the command `python3 .\betrusted_soc.py -e .\dummy.nky --perfcounter` in the betrusted-soc repo.