lib.rs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. /*
  2. * Copyright (c)2021 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2025-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. pub mod error;
  13. pub mod ext;
  14. extern crate base64;
  15. extern crate bytes;
  16. extern crate openidconnect;
  17. extern crate time;
  18. extern crate url;
  19. use crate::error::ZeroIDCError;
  20. use bytes::Bytes;
  21. use jwt::{Token};
  22. use openidconnect::core::{CoreClient, CoreProviderMetadata, CoreResponseType};
  23. use openidconnect::reqwest::http_client;
  24. use openidconnect::{AccessToken, AccessTokenHash, AuthorizationCode, AuthenticationFlow, ClientId, CsrfToken, IssuerUrl, Nonce, OAuth2TokenResponse, PkceCodeChallenge, PkceCodeVerifier, RedirectUrl, RefreshToken, Scope, TokenResponse};
  25. use std::str::from_utf8;
  26. use std::sync::{Arc, Mutex};
  27. use std::thread::{sleep, spawn, JoinHandle};
  28. use std::time::{SystemTime, UNIX_EPOCH, Duration};
  29. use time::{OffsetDateTime, format_description};
  30. use url::Url;
  31. #[cfg(
  32. any(
  33. all(target_os = "linux", target_arch = "x86"),
  34. all(target_os = "linux", target_arch = "x86_64"),
  35. all(target_os = "linux", target_arch = "aarch64"),
  36. target_os = "windows",
  37. target_os = "macos",
  38. )
  39. )]
  40. pub struct ZeroIDC {
  41. inner: Arc<Mutex<Inner>>,
  42. }
  43. #[cfg(
  44. any(
  45. all(target_os = "linux", target_arch = "x86"),
  46. all(target_os = "linux", target_arch = "x86_64"),
  47. all(target_os = "linux", target_arch = "aarch64"),
  48. target_os = "windows",
  49. target_os = "macos",
  50. )
  51. )]
  52. struct Inner {
  53. running: bool,
  54. auth_endpoint: String,
  55. oidc_thread: Option<JoinHandle<()>>,
  56. oidc_client: Option<openidconnect::core::CoreClient>,
  57. access_token: Option<AccessToken>,
  58. refresh_token: Option<RefreshToken>,
  59. exp_time: u64,
  60. kick: bool,
  61. url: Option<Url>,
  62. csrf_token: Option<CsrfToken>,
  63. nonce: Option<Nonce>,
  64. pkce_verifier: Option<PkceCodeVerifier>,
  65. }
  66. impl Inner {
  67. #[inline]
  68. fn as_opt(&mut self) -> Option<&mut Inner> {
  69. Some(self)
  70. }
  71. }
  72. fn csrf_func(csrf_token: String) -> Box<dyn Fn() -> CsrfToken> {
  73. return Box::new(move || CsrfToken::new(csrf_token.to_string()));
  74. }
  75. fn nonce_func(nonce: String) -> Box<dyn Fn() -> Nonce> {
  76. return Box::new(move || Nonce::new(nonce.to_string()));
  77. }
  78. #[cfg(debug_assertions)]
  79. fn systemtime_strftime<T>(dt: T, format: &str) -> String
  80. where T: Into<OffsetDateTime>
  81. {
  82. let f = format_description::parse(format);
  83. match f {
  84. Ok(f) => {
  85. match dt.into().format(&f) {
  86. Ok(s) => s,
  87. Err(_e) => "".to_string(),
  88. }
  89. },
  90. Err(_e) => {
  91. "".to_string()
  92. },
  93. }
  94. }
  95. #[cfg(
  96. any(
  97. all(target_os = "linux", target_arch = "x86"),
  98. all(target_os = "linux", target_arch = "x86_64"),
  99. all(target_os = "linux", target_arch = "aarch64"),
  100. target_os = "windows",
  101. target_os = "macos",
  102. )
  103. )]
  104. impl ZeroIDC {
  105. pub fn new(
  106. issuer: &str,
  107. client_id: &str,
  108. auth_ep: &str,
  109. local_web_port: u16,
  110. ) -> Result<ZeroIDC, ZeroIDCError> {
  111. let idc = ZeroIDC {
  112. inner: Arc::new(Mutex::new(Inner {
  113. running: false,
  114. auth_endpoint: auth_ep.to_string(),
  115. oidc_thread: None,
  116. oidc_client: None,
  117. access_token: None,
  118. refresh_token: None,
  119. exp_time: 0,
  120. kick: false,
  121. url: None,
  122. csrf_token: None,
  123. nonce: None,
  124. pkce_verifier: None,
  125. })),
  126. };
  127. let iss = IssuerUrl::new(issuer.to_string())?;
  128. let provider_meta = CoreProviderMetadata::discover(&iss, http_client)?;
  129. let r = format!("http://localhost:{}/sso", local_web_port);
  130. let redir_url = Url::parse(&r)?;
  131. let redirect = RedirectUrl::new(redir_url.to_string())?;
  132. (*idc.inner.lock().unwrap()).oidc_client = Some(
  133. CoreClient::from_provider_metadata(
  134. provider_meta,
  135. ClientId::new(client_id.to_string()),
  136. None,
  137. )
  138. .set_redirect_uri(redirect),
  139. );
  140. Ok(idc)
  141. }
  142. fn kick_refresh_thread(&mut self) {
  143. let local = Arc::clone(&self.inner);
  144. (*local.lock().unwrap()).kick = true;
  145. }
  146. fn start(&mut self) {
  147. let local = Arc::clone(&self.inner);
  148. if !(*local.lock().unwrap()).running {
  149. let inner_local = Arc::clone(&self.inner);
  150. (*local.lock().unwrap()).oidc_thread = Some(spawn(move || {
  151. (*inner_local.lock().unwrap()).running = true;
  152. let mut running = true;
  153. // Keep a copy of the initial nonce used to get the tokens
  154. // Will be needed later when verifying the responses from refresh tokens
  155. let nonce = (*inner_local.lock().unwrap()).nonce.clone();
  156. while running {
  157. let exp = UNIX_EPOCH + Duration::from_secs((*inner_local.lock().unwrap()).exp_time);
  158. let now = SystemTime::now();
  159. #[cfg(debug_assertions)] {
  160. println!("refresh token thread tick, now: {}, exp: {}", systemtime_strftime(now, "[year]-[month]-[day] [hour]:[minute]:[second]"), systemtime_strftime(exp, "[year]-[month]-[day] [hour]:[minute]:[second]"));
  161. }
  162. let refresh_token = (*inner_local.lock().unwrap()).refresh_token.clone();
  163. if let Some(refresh_token) = refresh_token {
  164. let should_kick = (*inner_local.lock().unwrap()).kick;
  165. if now >= (exp - Duration::from_secs(30)) || should_kick {
  166. if should_kick {
  167. #[cfg(debug_assertions)] {
  168. println!("refresh thread kicked");
  169. }
  170. (*inner_local.lock().unwrap()).kick = false;
  171. }
  172. let token_response = (*inner_local.lock().unwrap()).oidc_client.as_ref().map(|c| {
  173. let res = c.exchange_refresh_token(&refresh_token)
  174. .request(http_client);
  175. res
  176. });
  177. if let Some(res) = token_response {
  178. match res {
  179. Ok(res) => {
  180. let n = match nonce.clone() {
  181. Some(n) => n,
  182. None => {
  183. println!("err: no nonce");
  184. continue;
  185. }
  186. };
  187. let id = match res.id_token() {
  188. Some(t) => t,
  189. None => {
  190. println!("err: no id_token");
  191. continue;
  192. }
  193. };
  194. // verify & validate claims
  195. let verified = (*inner_local.lock().unwrap()).oidc_client.as_ref().map(|c| {
  196. let claims = match id.claims(&c.id_token_verifier(), &n) {
  197. Ok(c) => c,
  198. Err(e) => {
  199. println!("claims err: {}", e);
  200. return false;
  201. }
  202. };
  203. let signing_algo = match id.signing_alg() {
  204. Ok(s) => s,
  205. Err(e) => {
  206. println!("alg err: {}", e);
  207. return false;
  208. }
  209. };
  210. if let Some(expected_hash) = claims.access_token_hash() {
  211. let actual_hash = match AccessTokenHash::from_token(res.access_token(), &signing_algo) {
  212. Ok(h) => h,
  213. Err(e) => {
  214. println!("Error hashing access token: {}", e);
  215. return false;
  216. }
  217. };
  218. if actual_hash != *expected_hash {
  219. println!("token hash error");
  220. return false;
  221. }
  222. }
  223. return true;
  224. });
  225. let v = match verified {
  226. Some(verified) => {
  227. if !verified {
  228. println!("not verified.");
  229. (*inner_local.lock().unwrap()).running = false;
  230. false
  231. } else {
  232. true
  233. }
  234. },
  235. None => {
  236. println!("no verification performed?");
  237. (*inner_local.lock().unwrap()).running = false;
  238. false
  239. }
  240. };
  241. if v {
  242. match res.id_token() {
  243. Some(id_token) => {
  244. let params = [("id_token", id_token.to_string()),("state", "refresh".to_string())];
  245. #[cfg(debug_assertions)] {
  246. println!("New ID token: {}", id_token.to_string());
  247. }
  248. let client = reqwest::blocking::Client::new();
  249. let r = client.post((*inner_local.lock().unwrap()).auth_endpoint.clone())
  250. .form(&params)
  251. .send();
  252. match r {
  253. Ok(r) => {
  254. if r.status().is_success() {
  255. #[cfg(debug_assertions)] {
  256. println!("hit url: {}", r.url().as_str());
  257. println!("status: {}", r.status());
  258. }
  259. let access_token = res.access_token();
  260. let at = access_token.secret();
  261. let t: Result<Token<jwt::Header, jwt::Claims, jwt::Unverified<'_>>, jwt::Error>= Token::parse_unverified(at);
  262. if let Ok(t) = t {
  263. let claims = t.claims().registered.clone();
  264. match claims.expiration {
  265. Some(exp) => {
  266. (*inner_local.lock().unwrap()).exp_time = exp;
  267. },
  268. None => {
  269. panic!("expiration is None. This shouldn't happen")
  270. }
  271. }
  272. }
  273. (*inner_local.lock().unwrap()).access_token = Some(access_token.clone());
  274. if let Some(t) = res.refresh_token() {
  275. // println!("New Refresh Token: {}", t.secret());
  276. (*inner_local.lock().unwrap()).refresh_token = Some(t.clone());
  277. }
  278. #[cfg(debug_assertions)] {
  279. println!("Central post succeeded");
  280. }
  281. } else {
  282. println!("Central post failed: {}", r.status().to_string());
  283. println!("hit url: {}", r.url().as_str());
  284. println!("Status: {}", r.status());
  285. (*inner_local.lock().unwrap()).exp_time = 0;
  286. (*inner_local.lock().unwrap()).running = false;
  287. }
  288. },
  289. Err(e) => {
  290. println!("Central post failed: {}", e.to_string());
  291. println!("hit url: {}", e.url().unwrap().as_str());
  292. println!("Status: {}", e.status().unwrap());
  293. (*inner_local.lock().unwrap()).exp_time = 0;
  294. (*inner_local.lock().unwrap()).running = false;
  295. }
  296. }
  297. },
  298. None => {
  299. println!("no id token?!?");
  300. }
  301. }
  302. } else {
  303. println!("claims not verified");
  304. }
  305. },
  306. Err(e) => {
  307. println!("token error: {}", e);
  308. }
  309. }
  310. } else {
  311. println!("token response??");
  312. }
  313. } else {
  314. #[cfg(debug_assertions)]
  315. println!("waiting to refresh");
  316. }
  317. } else {
  318. println!("no refresh token?");
  319. }
  320. sleep(Duration::from_secs(1));
  321. running = (*inner_local.lock().unwrap()).running;
  322. }
  323. println!("thread done!")
  324. }));
  325. }
  326. }
  327. pub fn stop(&mut self) {
  328. let local = self.inner.clone();
  329. if (*local.lock().unwrap()).running {
  330. if let Some(u) = (*local.lock().unwrap()).oidc_thread.take() {
  331. u.join().expect("join failed");
  332. }
  333. }
  334. }
  335. pub fn is_running(&mut self) -> bool {
  336. let local = Arc::clone(&self.inner);
  337. if (*local.lock().unwrap()).running {
  338. true
  339. } else {
  340. false
  341. }
  342. }
  343. pub fn get_exp_time(&mut self) -> u64 {
  344. return (*self.inner.lock().unwrap()).exp_time;
  345. }
  346. pub fn set_nonce_and_csrf(&mut self, csrf_token: String, nonce: String) {
  347. let local = Arc::clone(&self.inner);
  348. (*local.lock().expect("can't lock inner")).as_opt().map(|i| {
  349. if i.running {
  350. println!("refresh thread running. not setting new nonce or csrf");
  351. return
  352. }
  353. let need_verifier = match i.pkce_verifier {
  354. None => true,
  355. _ => false,
  356. };
  357. let csrf_diff = if let Some(csrf) = i.csrf_token.clone() {
  358. if *csrf.secret() != csrf_token {
  359. true
  360. } else {
  361. false
  362. }
  363. } else {
  364. false
  365. };
  366. let nonce_diff = if let Some(n) = i.nonce.clone() {
  367. if *n.secret() != nonce {
  368. true
  369. } else {
  370. false
  371. }
  372. } else {
  373. false
  374. };
  375. if need_verifier || csrf_diff || nonce_diff {
  376. let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
  377. let r = i.oidc_client.as_ref().map(|c| {
  378. let (auth_url, csrf_token, nonce) = c
  379. .authorize_url(
  380. AuthenticationFlow::<CoreResponseType>::AuthorizationCode,
  381. csrf_func(csrf_token),
  382. nonce_func(nonce),
  383. )
  384. .add_scope(Scope::new("profile".to_string()))
  385. .add_scope(Scope::new("email".to_string()))
  386. .add_scope(Scope::new("offline_access".to_string()))
  387. .add_scope(Scope::new("openid".to_string()))
  388. .set_pkce_challenge(pkce_challenge)
  389. .url();
  390. (auth_url, csrf_token, nonce)
  391. });
  392. if let Some(r) = r {
  393. i.url = Some(r.0);
  394. i.csrf_token = Some(r.1);
  395. i.nonce = Some(r.2);
  396. i.pkce_verifier = Some(pkce_verifier);
  397. }
  398. }
  399. });
  400. }
  401. pub fn auth_url(&self) -> String {
  402. let url = (*self.inner.lock().expect("can't lock inner")).as_opt().map(|i| {
  403. match i.url.clone() {
  404. Some(u) => u.to_string(),
  405. _ => "".to_string(),
  406. }
  407. });
  408. match url {
  409. Some(url) => url.to_string(),
  410. None => "".to_string(),
  411. }
  412. }
  413. pub fn do_token_exchange(&mut self, code: &str) -> String {
  414. let local = Arc::clone(&self.inner);
  415. let mut should_start = false;
  416. let res = (*local.lock().unwrap()).as_opt().map(|i| {
  417. if let Some(verifier) = i.pkce_verifier.take() {
  418. let token_response = i.oidc_client.as_ref().map(|c| {
  419. let r = c.exchange_code(AuthorizationCode::new(code.to_string()))
  420. .set_pkce_verifier(verifier)
  421. .request(http_client);
  422. // validate the token hashes
  423. match r {
  424. Ok(res) =>{
  425. let n = match i.nonce.clone() {
  426. Some(n) => n,
  427. None => {
  428. return None;
  429. }
  430. };
  431. let id = match res.id_token() {
  432. Some(t) => t,
  433. None => {
  434. return None;
  435. }
  436. };
  437. let claims = match id.claims(&c.id_token_verifier(), &n) {
  438. Ok(c) => c,
  439. Err(_e) => {
  440. return None;
  441. }
  442. };
  443. let signing_algo = match id.signing_alg() {
  444. Ok(s) => s,
  445. Err(_) => {
  446. return None;
  447. }
  448. };
  449. if let Some(expected_hash) = claims.access_token_hash() {
  450. let actual_hash = match AccessTokenHash::from_token(res.access_token(), &signing_algo) {
  451. Ok(h) => h,
  452. Err(e) => {
  453. println!("Error hashing access token: {}", e);
  454. return None;
  455. }
  456. };
  457. if actual_hash != *expected_hash {
  458. println!("token hash error");
  459. return None;
  460. }
  461. }
  462. Some(res)
  463. },
  464. Err(_e) => {
  465. #[cfg(debug_assertions)] {
  466. println!("token response error: {}", _e.to_string());
  467. }
  468. return None;
  469. },
  470. }
  471. });
  472. if let Some(Some(tok)) = token_response {
  473. let id_token = tok.id_token().unwrap();
  474. #[cfg(debug_assertions)] {
  475. println!("ID token: {}", id_token.to_string());
  476. }
  477. let mut split = "".to_string();
  478. match i.csrf_token.clone() {
  479. Some(csrf_token) => {
  480. split = csrf_token.secret().to_owned();
  481. },
  482. _ => (),
  483. }
  484. let split = split.split("_").collect::<Vec<&str>>();
  485. if split.len() == 2 {
  486. let params = [("id_token", id_token.to_string()),("state", split[0].to_string())];
  487. let client = reqwest::blocking::Client::new();
  488. let res = client.post(i.auth_endpoint.clone())
  489. .form(&params)
  490. .send();
  491. match res {
  492. Ok(res) => {
  493. #[cfg(debug_assertions)] {
  494. println!("hit url: {}", res.url().as_str());
  495. println!("Status: {}", res.status());
  496. }
  497. let at = tok.access_token().secret();
  498. let t: Result<Token<jwt::Header, jwt::Claims, jwt::Unverified<'_>>, jwt::Error>= Token::parse_unverified(at);
  499. if let Ok(t) = t {
  500. let claims = t.claims().registered.clone();
  501. match claims.expiration {
  502. Some(exp) => {
  503. i.exp_time = exp;
  504. },
  505. None => {
  506. panic!("expiration is None. This shouldn't happen")
  507. }
  508. }
  509. }
  510. i.access_token = Some(tok.access_token().clone());
  511. if let Some(t) = tok.refresh_token() {
  512. i.refresh_token = Some(t.clone());
  513. should_start = true;
  514. }
  515. #[cfg(debug_assertions)] {
  516. let access_token = tok.access_token();
  517. println!("Access Token: {}", access_token.secret());
  518. let refresh_token = tok.refresh_token();
  519. println!("Refresh Token: {}", refresh_token.unwrap().secret());
  520. }
  521. let bytes = match res.bytes() {
  522. Ok(bytes) => bytes,
  523. Err(_) => Bytes::from(""),
  524. };
  525. let bytes = match from_utf8(bytes.as_ref()) {
  526. Ok(bytes) => bytes.to_string(),
  527. Err(_) => "".to_string(),
  528. };
  529. return bytes;
  530. },
  531. Err(res) => {
  532. println!("hit url: {}", res.url().unwrap().as_str());
  533. println!("Status: {}", res.status().unwrap());
  534. println!("Post error: {}", res.to_string());
  535. i.exp_time = 0;
  536. }
  537. }
  538. } else {
  539. println!("invalid split length?!?");
  540. }
  541. }
  542. }
  543. "".to_string()
  544. });
  545. if should_start {
  546. self.start();
  547. }
  548. return match res {
  549. Some(res) => res,
  550. _ => "".to_string(),
  551. };
  552. }
  553. }