diff --git a/Cargo.lock b/Cargo.lock index ad3b37ee1..d9bad0a6a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7173,7 +7173,6 @@ dependencies = [ "x11rb 0.12.0", "xkbcommon-dl", "xxhash-rust", - "zeroize", "zstd", ] diff --git a/Cargo.toml b/Cargo.toml index 31ae18934..238c07b59 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -61,7 +61,6 @@ serde_repr = "0.1" cfg-if = "1.0" lazy_static = "1.4" sha2 = "0.10" -zeroize = "1.8" repng = "0.2" zstd = "0.13" xxhash-rust = { version = "0.8", features = ["xxh3"] } diff --git a/src/auth_2fa.rs b/src/auth_2fa.rs index eab28a442..280f7da81 100644 --- a/src/auth_2fa.rs +++ b/src/auth_2fa.rs @@ -4,10 +4,11 @@ use hbb_common::{ config::Config, get_time, password_security::{decrypt_vec_or_original, encrypt_vec_or_original}, + tls::TlsType, ResultType, }; use serde_derive::{Deserialize, Serialize}; -use std::{fmt, sync::Mutex}; +use std::{fmt, sync::Mutex, time::Duration}; use totp_rs::{Algorithm, Secret, TOTP}; lazy_static::lazy_static! { @@ -164,18 +165,39 @@ impl TelegramBot { } } +// The URL carries the bot token: never fall back to accepting an invalid certificate, and drop +// the URL from errors so the token stays out of the log. +async fn post_telegram(url: String, body: String) -> ResultType { + let resp = crate::hbbs_http::create_http_client_async(TlsType::Rustls, false) + .post(url) + .header("Content-Type", "application/json") + .body(body) + .timeout(Duration::from_secs(12)) + .send() + .await + .map_err(|e| anyhow!("{:?}", e.without_url()))?; + resp.text() + .await + .map_err(|e| anyhow!("{:?}", e.without_url())) +} + // https://gist.github.com/dideler/85de4d64f66c1966788c1b2304b9caf1 pub async fn send_2fa_code_to_telegram(text: &str, bot: TelegramBot) -> ResultType<()> { let url = format!("https://api.telegram.org/bot{}/sendMessage", bot.token_str); let params = serde_json::json!({"chat_id": bot.chat_id, "text": text}); - crate::post_request(url, params.to_string(), "").await?; + post_telegram(url, params.to_string()).await?; Ok(()) } pub fn get_chatid_telegram(bot_token: &str) -> ResultType> { let url = format!("https://api.telegram.org/bot{}/getUpdates", bot_token); - // because caller is in tokio runtime, so we must call post_request_sync in new thread. - let handle = std::thread::spawn(move || crate::post_request_sync(url, "".to_owned(), "")); + // because caller is in tokio runtime, so we must run the request in a new thread. + let handle = std::thread::spawn(move || -> ResultType { + hbb_common::tokio::runtime::Builder::new_current_thread() + .enable_all() + .build()? + .block_on(post_telegram(url, String::new())) + }); let resp = handle.join().map_err(|_| anyhow!("Thread panicked"))??; let value = serde_json::from_str::(&resp).map_err(|e| anyhow!(e))?; @@ -215,7 +237,12 @@ pub fn get_chatid_telegram(bot_token: &str) -> ResultType> { #[cfg(test)] mod tests { - use super::TelegramBot; + use super::{post_telegram, TelegramBot}; + use hbb_common::tokio::{self, net::TcpListener}; + use std::sync::{ + atomic::{AtomicUsize, Ordering}, + Arc, + }; #[test] fn telegram_bot_debug_redacts_both_token_fields() { @@ -230,4 +257,25 @@ mod tests { assert!(!debug.contains(&format!("{:?}", bot.token))); assert!(debug.contains(&bot.chat_id)); } + + #[tokio::test] + async fn telegram_request_has_no_tls_fallback_and_hides_the_token() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let attempts = Arc::new(AtomicUsize::new(0)); + let counter = attempts.clone(); + tokio::spawn(async move { + while let Ok((stream, _)) = listener.accept().await { + counter.fetch_add(1, Ordering::SeqCst); + drop(stream); + } + }); + let token = "123456:test-telegram-token"; + let url = format!("https://127.0.0.1:{port}/bot{token}/sendMessage"); + + let err = post_telegram(url, String::new()).await.unwrap_err(); + + assert!(!err.to_string().contains(token), "{err}"); + assert_eq!(attempts.load(Ordering::SeqCst), 1); + } } diff --git a/src/client/io_loop.rs b/src/client/io_loop.rs index ed47e26e5..1b197a838 100644 --- a/src/client/io_loop.rs +++ b/src/client/io_loop.rs @@ -1732,7 +1732,7 @@ impl Remote { if !self .handler .handle_hash( - self.handler.password.as_str(), + &self.handler.password.clone(), hash, &mut self.trusted_device, peer, diff --git a/src/flutter.rs b/src/flutter.rs index ad8eae70f..31e6582e6 100644 --- a/src/flutter.rs +++ b/src/flutter.rs @@ -1345,15 +1345,17 @@ pub fn session_add( LocalConfig::set_remote_id(&id); - let (preset_password, shared_password) = if is_shared_password { + let mut preset_password = password.clone(); + let shared_password = if is_shared_password { // To achieve a flexible password application order, we don't treat shared password as a preset password. - (String::new(), Some(password)) + preset_password = Default::default(); + Some(password) } else { - (password, None) + None }; let session: Session = Session { - password: preset_password.into(), + password: preset_password, server_keyboard_enabled: Arc::new(RwLock::new(true)), server_file_transfer_enabled: Arc::new(RwLock::new(true)), server_clipboard_enabled: Arc::new(RwLock::new(true)), diff --git a/src/ui/remote.rs b/src/ui/remote.rs index cfdc5a605..f7a3ef68a 100644 --- a/src/ui/remote.rs +++ b/src/ui/remote.rs @@ -597,7 +597,7 @@ impl SciterSession { pub fn new(cmd: String, id: String, password: String, args: Vec) -> Self { let force_relay = args.contains(&"--relay".to_string()); let session: Session = Session { - password: password.into(), + password: password.clone(), args, server_keyboard_enabled: Arc::new(RwLock::new(true)), server_file_transfer_enabled: Arc::new(RwLock::new(true)), diff --git a/src/ui_session_interface.rs b/src/ui_session_interface.rs index cc6f715c1..d9146f2d4 100644 --- a/src/ui_session_interface.rs +++ b/src/ui_session_interface.rs @@ -40,7 +40,6 @@ use std::{ time::SystemTime, }; use uuid::Uuid; -use zeroize::Zeroizing; use crate::client::io_loop::Remote; use crate::client::{ @@ -61,7 +60,7 @@ const CHANGE_RESOLUTION_VALID_TIMEOUT_SECS: u64 = 15; #[derive(Clone, Default)] pub struct Session { - pub password: Zeroizing, + pub password: String, pub args: Vec, pub lc: Arc>, pub sender: Arc>>>, @@ -2092,7 +2091,7 @@ async fn start_one_port_forward( ) { if let Err(err) = crate::port_forward::listen( handler.get_id(), - handler.password.as_str().to_owned(), + handler.password.clone(), port, handler.clone(), receiver,