diff --git a/libs/tls/README.md b/libs/tls/README.md new file mode 100644 index 000000000..a0dda3812 --- /dev/null +++ b/libs/tls/README.md @@ -0,0 +1,41 @@ +== TLS == + +A tls library focused on explicitly trusting Certificate Authority Certificates (requires `--feature tls`). + +Typically, operating systems and browsers embed a list of implicitly trusted Root CA certificates. + +The tls handshake involves the host offering the client a Certificate signed for authenticity by a CA, with a chain of signatures back to a Root CA. If the client trusts at least one Certificate in this chain of trust, then the handshake may progress to an encrypted connection. + +It does not seem in keeping with the Precursor/Xous idea to ask users to trust any such list of Root CA Certificates. + +This tls library enables the user to obtain and save trusted CA certificates to the PDDB as a personalised set of trusted Root CA certificates on which to establish a tls connection. This can be as simple for the user as responding to a modal, when making a first connection to an as yet un-trusted host. Just a couple of clicks. The developer need only call `Tls::check_trust()`. + +Note that hosts with self-signed Certificates may be probed and trusted (e.g. [chat.signal.org](https://chat.signal.org)) + +A small set of shellchat commands are included to enact the base functionality: + +- `net tls probe ` will initiate a modified tls handshake with ``, obtain the certificate chain offered by ``, and immediately terminate the connection. A call to Tls::check_trust() will present the CA certificate chain in a modal to be individually selected and saved to PDDB if trusted. +- `net tls test ` will attempt a normal tls handshake with `` based on the trusted Root CA certificates in the PDDB. If the connection is successful, then a simple `get` is emitted, the response accepted, and the connection closed. +- `net tls mozilla` trusts and saves all Root CA's in the [webpki-roots crate](https://crates.io/crates/webpki-roots) - which contains Mozilla's root certificates. (requires `--feature rootCA`) +- `net list` lists all trusted certificates in the PDDB +- `net deleteall` deletes all trusted certificates in the PDDB + +These functions are gated by 2 feature flags: +- `tls` includes [der](https://crates.io/crates/der), [ring](https://crates.io/crates/ring) (local patch), [rustls](https://crates.io/crates/rustls), [webpki](https://crates.io/crates/webpki) & [x509-parser](https://crates.io/crates/x509-parser) +- `rootCA` includes the [webpki-roots crate](https://crates.io/crates/webpki-roots) + +In keeping with `rustls` & `webpki`, only the critical components of each x509-Certificate are stored in the PDDB under the `tls.trusted` dictionary - as a `rkyv` archive of a `tls::RustTlsOwnedTrustAuthority` object. + +The rustls [dangerous_configuration](https://github.com/betrusted-io/xous-core/pull/394/commits/4ea0c8457de8f855723af76546b6ecb7e54661f7) feature is required to modify the tls handshake during a `net tls probe `. This is because, by default, `rustls` drops the connection (and certificate chain) if there is no match to a trusted Root CA Certificate in the `RootStore`. During a `probe` we need to briefly trust all CA certificates in order to get hold of the CA certificate chain, and inspect it. + +The shellchat `net tls` commands are are called from `services/shellchat/src/cmds/net_cmd.rs`, but located in `libs/tls/src/cmd.rs` in order to contain the size of `services/shellchat/src/cmds/net_cmd.rs` and to keep the tls cmds close to the implementation. + +Native `pddb` calls are used throuought (`std::fs` free) + +Considerations: + +- there is an outstanding **issue** where the `checkbox` modal does not display options with multiple lines correctly. This impacts the display of fingerprints for some certificates with longer subjects. +- It may be worth considering rendering public `pddb::KEY_NAME_LEN` to allow developer to avoid sending overly long key's which will be rejected by the pddb. +- probably need a shellchat `net tls delete ` +- some broken code is included for a future fix if required [RustlsOwnedTrustAnchor::publik_key()](https://github.com/betrusted-io/xous-core/pull/394/commits/4e0298c17ad2c51aa220a88dc69bf2f56e51076f) +- some hosts (eg bunnyfoo.com) emit an `unexpected eof` error during tls handshake 🤷 diff --git a/libs/tls/src/cmd.rs b/libs/tls/src/cmd.rs index da877270f..ebc533cbe 100644 --- a/libs/tls/src/cmd.rs +++ b/libs/tls/src/cmd.rs @@ -1,4 +1,4 @@ -use crate::{danger, Tls}; +use crate::Tls; use locales::t; #[cfg(feature = "rootCA")] use modals::Modals; @@ -53,7 +53,7 @@ pub fn shellchat<'a>( ) }) .collect(); - let mut count:u32 = rotas.len().try_into().unwrap(); + let mut count: u32 = rotas.len().try_into().unwrap(); let xns = XousNames::new().unwrap(); let modals = Modals::new(&xns).unwrap(); modals @@ -75,60 +75,20 @@ pub fn shellchat<'a>( // 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 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", + None => "betrusted.io", }; - let server_name = target.try_into().unwrap_or_else(|e| { - log::warn!("failed to create sever_name from {target}: {e}"); - write!( + let tls = Tls::new(); + match tls.probe(target) { + Ok(count) => write!(ret, "{} {}", count, t!("tls.probe_done", locales::LANG)).ok(), + Err(_) => write!( ret, "{} {target}", t!("tls.probe_fail_servername", locales::LANG) ) - .ok(); - "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); - 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) => { - let tls = Tls::new(); - let count = tls.check_trust(certificates); - write!(ret, "{} {}", count, t!("tls.probe_done", locales::LANG)).ok(); - } - None => (), - }; - } - Err(e) => { - write!(ret, "{e}").ok(); - log::warn!("{e}") - } + .ok(), }; - log::set_max_level(log::LevelFilter::Info); } @@ -199,7 +159,12 @@ pub fn shellchat<'a>( } None | _ => { write!(ret, "{}\n", t!("tls.cmd", locales::LANG)).ok(); - write!(ret, "\tdeleteall\t{}\n", t!("tls.deleteall_cmd", locales::LANG)).ok(); + write!( + ret, + "\tdeleteall\t{}\n", + t!("tls.deleteall_cmd", locales::LANG) + ) + .ok(); write!(ret, "\thelp\n").ok(); write!(ret, "\tlist\t{}\n", t!("tls.list_cmd", locales::LANG)).ok(); #[cfg(feature = "rootCA")] diff --git a/libs/tls/src/lib.rs b/libs/tls/src/lib.rs index fdf7451ce..aa703f633 100644 --- a/libs/tls/src/lib.rs +++ b/libs/tls/src/lib.rs @@ -1,5 +1,5 @@ pub mod cmd; -pub mod danger; +mod danger; pub mod rota; use crate::rota::RustlsOwnedTrustAnchor; @@ -31,9 +31,17 @@ impl Tls { } } - // presents a modal to the user to select trusted tls certificates - // and saves the selected certificates to the pddb - // returns a count of trusted certificates + /// Presents a modal to the user to select trusted tls certificates + /// and saves the selected certificates to the pddb + /// + /// # Arguments + /// + /// * `certificates` - the certificates to be presented + /// + /// # Returns + /// + /// a count of trusted certificates + /// pub fn check_trust(&self, certificates: &[Certificate]) -> usize { let xns = XousNames::new().unwrap(); let modals = Modals::new(&xns).unwrap(); @@ -92,8 +100,12 @@ impl Tls { } } - // deletes ALL tls trust-anchors from the pddb - // returns the number of certs deleted + /// Deletes ALL tls trust-anchors from the pddb + /// + /// # Returns + /// + /// the number of trust-anchors deleted + /// pub fn del_all_cert(&self) -> Result { let count = match self.pddb.list_keys(TLS_TRUSTED_DICT, None) { Ok(list) => list.len(), @@ -116,7 +128,12 @@ impl Tls { Ok(count) } - // deletes a tls trust-anchor from the pddb + /// Deletes a tls trust-anchor from the pddb + /// + /// # Arguments + /// + /// * `key` - the pddb-key containing the unwanted trust-anchor + /// pub fn del_cert(&self, key: &str) -> Result<(), Error> { match self.pddb.delete_key(TLS_TRUSTED_DICT, key, None) { Ok(_) => { @@ -131,7 +148,12 @@ impl Tls { return Ok(()); } - // saves a tls trust-anchor to the pddb + /// Saves a tls trust-anchor to the pddb + /// + /// # Arguments + /// + /// * `ta` - a trusted trust-anchor + /// pub fn save_cert(&self, ta: &RustlsOwnedTrustAnchor) -> Result<(), Error> { let key = ta.pddb_key(); match self.pddb.get( @@ -175,8 +197,12 @@ impl Tls { Ok(()) } - - // retrieves a tls trust-anchor from the pddb + /// Returns a tls trust-anchor from the pddb + /// + /// # Arguments + /// + /// * `key` - pddb key holding the trust-anchor + /// pub fn get_cert(&self, key: &str) -> Option { match self.pddb.get( TLS_TRUSTED_DICT, @@ -195,9 +221,8 @@ impl Tls { let pos: u16 = u16::from_be_bytes([bytes[0], bytes[1]]); let pos: usize = pos.into(); // deserialize the trust-anchor - let archive = unsafe { - rkyv::archived_value::(&bytes, pos) - }; + let archive = + unsafe { rkyv::archived_value::(&bytes, pos) }; let ta = archive.deserialize(&mut AllocDeserializer {}).ok(); log::info!("get '{}' = '{:?}'", key, &ta); ta @@ -215,6 +240,8 @@ impl Tls { } } + /// Returns a Vec of all trusted trust-anchors + /// pub fn trusted(&self) -> Vec { match self.pddb.list_keys(TLS_TRUSTED_DICT, None) { Ok(list) => list @@ -229,6 +256,8 @@ impl Tls { } } + /// Returns a RootCertStore containing all trusted trust-anchors + /// pub fn root_store(&self) -> RootCertStore { let mut root_store = RootCertStore::empty(); match self.pddb.list_keys(TLS_TRUSTED_DICT, None) { @@ -244,6 +273,65 @@ impl Tls { } root_store } + + /// Probes the target and returns true is at least 1 certificate is trusted + /// + /// Establishes a tls connection to the target 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. + /// + /// By default, rustls only provides access to a trusted certificate chain. + /// Probe briefly stifles the certificate validation (ie trusts everything) + /// in order to grab the untrusted cetificate chain and present it to the + /// user for examination. + /// + /// # Arguments + /// + /// * `target` - the target tls site (i.e. betrusted.io) + /// + pub fn probe(&self, target: &str) -> Result { + log::info!("starting TLS probe"); + // Attempt to open the tls connection with an empty root_store + let 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(); + match target.try_into() { + Ok(server_name) => { + let mut conn = + rustls::ClientConnection::new(Arc::new(config), server_name).unwrap(); + log::info!("connect TCPstream to {}", target); + let url = format!("{}:443", target); + match TcpStream::connect(url) { + Ok(mut sock) => { + match conn.complete_io(&mut sock) { + Ok(_) => log::info!("handshake complete"), + Err(e) => log::warn!("{e}"), + } + conn.send_close_notify(); + match conn.peer_certificates() { + Some(certificates) => Ok(self.check_trust(certificates)), + None => Ok(0), + } + } + Err(e) => { + log::warn!("{e}"); + Err(e) + } + } + } + Err(e) => { + log::warn!("failed to create sever_name from {target}: {e}"); + Err(Error::from(ErrorKind::InvalidInput)) + } + } + } } // https://stackoverflow.com/questions/57029974/how-to-split-string-into-chunks-in-rust-to-insert-spaces