forked from kai4711x/rustdesk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth_2fa.rs
204 lines (184 loc) · 6.35 KB
/
auth_2fa.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
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)
}