Files
hello-agent/vendor/rustdesk/src/auth_2fa.rs
T
mike f8ead215d8
build-windows / build-hello-agent-x64 (push) Successful in 5m41s
Initial commit: hello-agent — headless RustDesk-protocol-compatible Windows agent
A single-binary, Flutter-free remote-support agent that speaks the stock
RustDesk wire protocol. Designed for one-line MDM deployment against a
self-hosted rustdesk-server: a supporter using the unmodified rustdesk.exe
client connects, the controlled-side user gets a native Win32 approval
prompt, click Yes / No.

CLI surface

    hello-agent.exe --install                # register + start service
    hello-agent.exe --uninstall              # stop, delete, clean up
    hello-agent.exe --config <BLOB>          # admin-UI deploy string
    hello-agent.exe --install --config <BLOB>   # MDM one-liner

--config accepts both forms emitted by the rustdesk-server admin UI: the
reversed-base64 deploy string and the host=,key=,api=,relay= filename
form. Decoded via the upstream custom_server module, persisted via
hbb_common::config::Config::set_option.

Architecture

    --service runs as a Session 0 LocalSystem service. It polls
    WTSGetActiveConsoleSessionId and (re)spawns hello-agent.exe --server
    into the active console session via librustdesk::platform::run_as_user,
    handling the Session 0 → user-session token impersonation.

    --server is the worker. It boots three concurrent components:
      1. cm_popup: an IPC listener on the rustdesk `_cm` named pipe
      2. librustdesk::start_server(true, false): the upstream protocol
         stack — rendezvous mediator, NAT punch, IPC server, screen
         capture, login validation, hbbs_http heartbeat / sysinfo sync
      3. (implicit) ApproveMode::Click is pinned in config, so every
         incoming connection routes through cm_popup

The popup mechanism reuses an existing upstream contract without any
patches to the protocol code: when a peer connects with no password,
Connection::start in the upstream code calls try_start_cm_ipc, which
ipc::connect-s the `_cm` pipe before falling back to spawning a Flutter
CM child. Since cm_popup is up first, step 1 succeeds; we read the
Data::Login{authorized:false} frame, show MessageBoxTimeoutW (Yes/No,
60s, top-most, system-modal), and reply Data::Authorize or Data::Close.

Source tree

    src/main.rs             CLI dispatcher + run_server() composition
    src/cli.rs              hand-rolled argv parser + unit tests
    src/service.rs          windows-service install/uninstall/dispatcher
    src/config_import.rs    --config blob decoding + persistence
    src/cm_popup.rs         _cm IPC listener + Win32 approval dialog

Vendoring

The upstream RustDesk crate is vendored under vendor/rustdesk/ — full
workspace including libs/{hbb_common, scrap, enigo, clipboard,
virtual_display, remote_printer}. This makes the build self-contained
(no submodules, no sibling-repo checkout in CI) and gives us freedom to
fork in a different direction later. Excluded from the vendor: .git,
target/, flutter/, appimage/, flatpak/, fastlane/, docs/, examples/,
ci/, build.py, Dockerfile, upstream README/CLAUDE/AGENTS/GEMINI.

One local divergence vs. upstream: vendor/rustdesk/src/lib.rs flips
`mod custom_server` → `pub mod custom_server` so config_import.rs can
call get_custom_server_from_string without going through the
ui_interface shim. Documented in README.md → "Re-syncing the vendored
copy".

CI

.gitea/workflows/build-windows.yml builds on a self-hosted Windows
runner with Rust 1.75, LLVM 15.0.6 (libclang for bindgen via libvpx-sys),
and a vcpkg cache. The vendored vcpkg.json drives x64-windows-static
deps. The workflow stages the resulting hello-agent.exe into
SignOutput\, reports authenticode signing status (warns on unsigned),
and uploads as artifact. ~15 min full build, faster on incremental.

Out of scope for this commit: Linux/macOS builds, code signing, MSI
packaging, coexistence with stock rustdesk on the same box (currently
shares the RustDesk APP_NAME and config dir).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 16:29:31 +02:00

205 lines
6.3 KiB
Rust

use hbb_common::{
anyhow::anyhow,
bail,
config::Config,
get_time,
password_security::{decrypt_vec_or_original, encrypt_vec_or_original},
ResultType,
};
use serde_derive::{Deserialize, Serialize};
use std::sync::Mutex;
use totp_rs::{Algorithm, Secret, TOTP};
lazy_static::lazy_static! {
static ref CURRENT_2FA: Mutex<Option<(TOTPInfo, TOTP)>> = Mutex::new(None);
}
const ISSUER: &str = "RustDesk";
const TAG_LOGIN: &str = "Connection";
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TOTPInfo {
pub name: String,
pub secret: Vec<u8>,
pub digits: usize,
pub created_at: i64,
}
impl TOTPInfo {
fn new_totp(&self) -> ResultType<TOTP> {
let totp = TOTP::new(
Algorithm::SHA1,
self.digits,
1,
30,
self.secret.clone(),
Some(format!("{} {}", ISSUER, TAG_LOGIN)),
self.name.clone(),
)?;
Ok(totp)
}
fn gen_totp_info(name: String, digits: usize) -> ResultType<TOTPInfo> {
let secret = Secret::generate_secret();
let totp = TOTPInfo {
secret: secret.to_bytes()?,
name,
digits,
created_at: get_time(),
..Default::default()
};
Ok(totp)
}
pub fn into_string(&self) -> ResultType<String> {
let secret = encrypt_vec_or_original(self.secret.as_slice(), "00", 1024);
let totp_info = TOTPInfo {
secret,
..self.clone()
};
let s = serde_json::to_string(&totp_info)?;
Ok(s)
}
pub fn from_str(data: &str) -> ResultType<TOTP> {
let mut totp_info = serde_json::from_str::<TOTPInfo>(data)?;
let (secret, success, _) = decrypt_vec_or_original(&totp_info.secret, "00");
if success {
totp_info.secret = secret;
return Ok(totp_info.new_totp()?);
} else {
bail!("decrypt_vec_or_original 2fa secret failed")
}
}
}
pub fn generate2fa() -> String {
#[cfg(not(any(target_os = "android", target_os = "ios")))]
let id = crate::ipc::get_id();
#[cfg(any(target_os = "android", target_os = "ios"))]
let id = Config::get_id();
if let Ok(info) = TOTPInfo::gen_totp_info(id, 6) {
if let Ok(totp) = info.new_totp() {
let code = totp.get_url();
*CURRENT_2FA.lock().unwrap() = Some((info, totp));
return code;
}
}
"".to_owned()
}
pub fn verify2fa(code: String) -> bool {
if let Some((info, totp)) = CURRENT_2FA.lock().unwrap().as_ref() {
if let Ok(res) = totp.check_current(&code) {
if res {
if let Ok(v) = info.into_string() {
#[cfg(not(any(target_os = "android", target_os = "ios")))]
crate::ipc::set_option("2fa", &v);
#[cfg(any(target_os = "android", target_os = "ios"))]
Config::set_option("2fa".to_owned(), v);
return res;
}
}
}
}
false
}
pub fn get_2fa(raw: Option<String>) -> Option<TOTP> {
TOTPInfo::from_str(&raw.unwrap_or(Config::get_option("2fa")))
.map(|x| Some(x))
.unwrap_or_default()
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TelegramBot {
#[serde(skip)]
pub token_str: String,
pub token: Vec<u8>,
pub chat_id: String,
}
impl TelegramBot {
fn into_string(&self) -> ResultType<String> {
let token = encrypt_vec_or_original(self.token_str.as_bytes(), "00", 1024);
let bot = TelegramBot {
token,
..self.clone()
};
let s = serde_json::to_string(&bot)?;
Ok(s)
}
fn save(&self) -> ResultType<()> {
let s = self.into_string()?;
#[cfg(not(any(target_os = "android", target_os = "ios")))]
crate::ipc::set_option("bot", &s);
#[cfg(any(target_os = "android", target_os = "ios"))]
Config::set_option("bot".to_owned(), s);
Ok(())
}
pub fn get() -> ResultType<Option<TelegramBot>> {
let data = Config::get_option("bot");
if data.is_empty() {
return Ok(None);
}
let mut bot = serde_json::from_str::<TelegramBot>(&data)?;
let (token, success, _) = decrypt_vec_or_original(&bot.token, "00");
if success {
bot.token_str = String::from_utf8(token)?;
return Ok(Some(bot));
}
bail!("decrypt_vec_or_original telegram bot token failed")
}
}
// 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?;
Ok(())
}
pub fn get_chatid_telegram(bot_token: &str) -> ResultType<Option<String>> {
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(), ""));
let resp = handle.join().map_err(|_| anyhow!("Thread panicked"))??;
let value = serde_json::from_str::<serde_json::Value>(&resp).map_err(|e| anyhow!(e))?;
// Check for an error_code in the response
if let Some(error_code) = value.get("error_code").and_then(|code| code.as_i64()) {
// If there's an error_code, try to use the description for the error message
let description = value["description"]
.as_str()
.unwrap_or("Unknown error occurred");
return Err(anyhow!(
"Telegram API error: {} (error_code: {})",
description,
error_code
));
}
let chat_id = &value["result"][0]["message"]["chat"]["id"];
let chat_id = if let Some(id) = chat_id.as_i64() {
Some(id.to_string())
} else if let Some(id) = chat_id.as_str() {
Some(id.to_owned())
} else {
None
};
if let Some(chat_id) = chat_id.as_ref() {
let bot = TelegramBot {
token_str: bot_token.to_owned(),
chat_id: chat_id.to_owned(),
..Default::default()
};
bot.save()?;
}
Ok(chat_id)
}