tor: fix launch onion server, wallet tor service, send over tor

This commit is contained in:
ardocrat
2024-04-30 18:15:03 +03:00
parent 1d9c8533ad
commit 12650c94fd
17 changed files with 1408 additions and 607 deletions
+14 -27
View File
@@ -12,31 +12,30 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use std::path::PathBuf;
use serde_derive::{Deserialize, Serialize};
use crate::Settings;
/// Tor SOCKS proxy server configuration.
/// Tor configuration.
#[derive(Serialize, Deserialize, Clone)]
pub struct TorServerConfig {
socks_port: u16
pub struct TorConfig {
// Flag to check if Tor bridges usage is needed.
pub(crate) use_bridges: Option<bool>
}
/// Default SOCKS port value.
const DEFAULT_SOCKS_PORT: u16 = 9060;
impl Default for TorServerConfig {
impl Default for TorConfig {
fn default() -> Self {
Self {
socks_port: DEFAULT_SOCKS_PORT,
use_bridges: Some(false)
}
}
}
impl TorServerConfig {
impl TorConfig {
/// Tor configuration file name.
pub const FILE_NAME: &'static str = "tor.toml";
/// Directory for config and Tor related files.
/// Directory for Tor data files.
const DIR_NAME: &'static str = "tor";
/// Subdirectory name for Tor state.
@@ -48,11 +47,10 @@ impl TorServerConfig {
/// Save application configuration to the file.
pub fn save(&self) {
Settings::write_to_file(self, Settings::get_config_path(Self::FILE_NAME,
Some(Self::DIR_NAME.to_string())));
Settings::write_to_file(self, Settings::get_config_path(Self::FILE_NAME, None));
}
/// Get subdirectory path from dir name.
/// Get path from subdirectory name.
fn sub_dir_path(name: &str) -> String {
let mut base = Settings::get_base_path(Some(Self::DIR_NAME.to_string()));
base.push(name);
@@ -71,19 +69,8 @@ impl TorServerConfig {
/// Get Tor keystore directory path.
pub fn keystore_path() -> String {
Self::sub_dir_path(Self::KEYSTORE_DIR)
}
/// Get SOCKS port value.
pub fn socks_port() -> u16 {
let r_config = Settings::tor_config_to_read();
r_config.socks_port
}
/// Save SOCKS port value.
pub fn save_socks_port(port: u16) {
let mut w_config = Settings::tor_config_to_update();
w_config.socks_port = port;
w_config.save();
let mut base = PathBuf::from(Self::state_path());
base.push(Self::KEYSTORE_DIR);
base.to_str().unwrap().to_string()
}
}
+2 -2
View File
@@ -13,7 +13,7 @@
// limitations under the License.
mod config;
pub use config::TorServerConfig;
pub use config::TorConfig;
mod tor;
pub use tor::TorServer;
pub use tor::Tor;
+173 -242
View File
@@ -12,203 +12,129 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashMap;
use std::net::SocketAddr;
use std::collections::{BTreeMap, BTreeSet};
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::sync::{Arc, RwLock};
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::time::Duration;
use futures::executor::block_on;
use lazy_static::lazy_static;
use futures::task::SpawnExt;
use tokio::task::JoinHandle;
use anyhow::Result;
use tokio::time::sleep;
use arti::socks::run_socks_proxy;
use arti_client::{TorClient, TorClientConfig};
use arti_client::config::pt::TransportConfigBuilder;
use arti_client::config::{BridgeConfigBuilder, TorClientConfigBuilder};
use arti_client::config::TorClientConfigBuilder;
use fs_mistrust::Mistrust;
use grin_util::secp::SecretKey;
use grin_wallet_util::OnionV3Address;
use ed25519_dalek::hazmat::ExpandedSecretKey;
use curve25519_dalek::digest::Digest;
use sha2::Sha512;
use tor_config::{CfgPath, Listen};
use tor_rtcompat::tokio::TokioNativeTlsRuntime;
use tor_rtcompat::{BlockOn, Runtime};
use tor_rtcompat::Runtime;
use tor_hsrproxy::OnionServiceReverseProxy;
use tor_hsrproxy::config::{Encapsulation, ProxyAction, ProxyPattern, ProxyRule, TargetAddr, ProxyConfigBuilder};
use tor_hsservice::config::OnionServiceConfigBuilder;
use tor_hsservice::{HsIdKeypairSpecifier, HsIdPublicKeySpecifier, HsNickname};
use tor_hsservice::{HsIdKeypairSpecifier, HsIdPublicKeySpecifier, HsNickname, RunningOnionService};
use tor_keymgr::{ArtiNativeKeystore, KeyMgrBuilder, KeystoreSelector};
use tor_llcrypto::pk::ed25519::ExpandedKeypair;
use tor_hscrypto::pk::{HsIdKey, HsIdKeypair};
use arti_hyper::ArtiHttpConnector;
use futures::TryFutureExt;
use hyper::Body;
use tls_api::{TlsConnector as TlsConnectorTrait, TlsConnectorBuilder};
use crate::tor::TorServerConfig;
// On aarch64-apple-darwin targets there is an issue with the native and rustls
// tls implementation so this makes it fall back to the openssl variant.
//
// https://gitlab.torproject.org/tpo/core/arti/-/issues/715
#[cfg(not(all(target_vendor = "apple", target_arch = "aarch64")))]
use tls_api_native_tls::TlsConnector;
#[cfg(all(target_vendor = "apple", target_arch = "aarch64"))]
use tls_api_openssl::TlsConnector;
use crate::tor::TorConfig;
lazy_static! {
/// Static thread-aware state of [`Node`] to be updated from separate thread.
static ref TOR_SERVER_STATE: Arc<TorServer> = Arc::new(TorServer::default());
static ref TOR_SERVER_STATE: Arc<Tor> = Arc::new(Tor::default());
}
/// Tor server to use as SOCKS proxy for requests and to launch Onion services.
pub struct TorServer {
/// Running Tor client.
client: Arc<RwLock<Option<TorClient<TokioNativeTlsRuntime>>>>,
/// Running Tor client configuration.
config: Arc<RwLock<Option<TorClientConfig>>>,
/// Flag to check if server is running.
running: AtomicBool,
/// Flag to check if server is starting.
starting: AtomicBool,
/// Flag to check if server needs to stop.
stopping: AtomicBool,
/// Flag to check if error happened.
error: AtomicBool,
pub struct Tor {
/// [`TorClient`] used for connections with configuration.
client: Arc<RwLock<(TorClient<TokioNativeTlsRuntime>, TorClientConfig)>>,
/// Mapping of running Onion services identifiers to proxy.
running_services: Arc<RwLock<HashMap<String, Arc<OnionServiceReverseProxy>>>>
running_services: Arc<RwLock<BTreeMap<String,
(Arc<RunningOnionService>, Arc<OnionServiceReverseProxy>)>>>,
/// Starting Onion services identifiers.
starting_services: Arc<RwLock<BTreeSet<String>>>,
/// Failed Onion services identifiers.
failed_services: Arc<RwLock<BTreeSet<String>>>
}
impl Default for TorServer {
impl Default for Tor {
fn default() -> Self {
// Create Tor client config.
let mut builder =
TorClientConfigBuilder::from_directories(TorConfig::state_path(),
TorConfig::cache_path());
builder.address_filter().allow_onion_addrs(true);
// Create connected Tor client from config.
let runtime = TokioNativeTlsRuntime::create().unwrap();
let config = builder.build().unwrap();
let client = TorClient::with_runtime(runtime)
.config(config.clone())
.create_unbootstrapped()
.unwrap();
Self {
running: AtomicBool::new(false),
starting: AtomicBool::new(false),
stopping: AtomicBool::new(false),
error: AtomicBool::new(false),
client: Arc::new(RwLock::new(None)),
running_services: Arc::new(RwLock::new(HashMap::new())),
config: Arc::new(RwLock::new(None)),
client: Arc::new(RwLock::new((client, config))),
running_services: Arc::new(RwLock::new(BTreeMap::new())),
starting_services: Arc::new(RwLock::new(BTreeSet::new())),
failed_services: Arc::new(RwLock::new(BTreeSet::new()))
}
}
}
impl TorServer {
/// Check if server is running.
pub fn is_running() -> bool {
TOR_SERVER_STATE.running.load(Ordering::Relaxed)
}
impl Tor {
/// Send post request using Tor.
pub async fn post(body: String, url: String) -> Option<String> {
// Bootstrap client.
let client_config = TOR_SERVER_STATE.client.read().unwrap();
let client = client_config.0.clone();
client.bootstrap().await.unwrap();
/// Check if server is running.
pub fn is_starting() -> bool {
TOR_SERVER_STATE.starting.load(Ordering::Relaxed)
}
// Create http tor-powered client to post data.
let tls_connector = TlsConnector::builder().unwrap().build().unwrap();
let tor_connector = ArtiHttpConnector::new(client, tls_connector);
let http = hyper::Client::builder().build::<_, Body>(tor_connector);
// Create request.
let req = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url)
.body(Body::from(body))
.unwrap();
/// Check if server is stopping.
pub fn is_stopping() -> bool {
TOR_SERVER_STATE.stopping.load(Ordering::Relaxed)
}
/// Check if server has error.
pub fn has_error() -> bool {
TOR_SERVER_STATE.error.load(Ordering::Relaxed)
}
/// Stop the server.
pub fn stop() {
TOR_SERVER_STATE.stopping.store(true, Ordering::Relaxed);
}
/// Start or restart the server if already running.
pub fn start() {
if Self::is_running() {
Self::stop();
}
thread::spawn(|| {
while Self::is_stopping() {
thread::sleep(Duration::from_millis(1000));
}
TOR_SERVER_STATE.starting.store(true, Ordering::Relaxed);
TOR_SERVER_STATE.error.store(false, Ordering::Relaxed);
// Check if Tor client is already running.
if TOR_SERVER_STATE.client.read().unwrap().is_some() {
let r_client = TOR_SERVER_STATE.client.read().unwrap();
let client = r_client.as_ref().unwrap().clone();
let runtime = client.runtime().clone();
let _ = runtime.clone().block_on(Self::launch_socks_proxy(runtime, client));
} else {
// Create Tor client config to connect.
let mut builder =
TorClientConfigBuilder::from_directories(TorServerConfig::state_path(),
TorServerConfig::cache_path());
builder.address_filter().allow_onion_addrs(true);
// Setup Snowflake bridges.
Self::setup_bridges(&mut builder);
// Create Tor client from config.
if let Ok(config) = builder.build() {
let mut w_config = TOR_SERVER_STATE.config.write().unwrap();
*w_config = Some(config.clone());
// Restart server on connection timeout.
thread::spawn(|| {
thread::sleep(Duration::from_millis(30000));
let r_client = TOR_SERVER_STATE.client.read().unwrap();
if r_client.is_none() {
Self::start();
}
});
// Create Tor client.
let runtime = TokioNativeTlsRuntime::create().unwrap();
match TorClient::with_runtime(runtime.clone())
.config(config)
.bootstrap_behavior(arti_client::BootstrapBehavior::OnDemand)
.create_unbootstrapped() {
Ok(tor_client) => {
let mut w_client = TOR_SERVER_STATE.client.write().unwrap();
if w_client.is_some() {
return;
}
*w_client = Some(tor_client.clone());
let _ = runtime.clone().block_on(
// Launch SOCKS proxy server.
Self::launch_socks_proxy(runtime, tor_client)
);
}
Err(e) => {
eprintln!("{}", e);
TOR_SERVER_STATE.starting.store(false, Ordering::Relaxed);
TOR_SERVER_STATE.error.store(true, Ordering::Relaxed);
}
}
} else {
TOR_SERVER_STATE.starting.store(false, Ordering::Relaxed);
TOR_SERVER_STATE.error.store(true, Ordering::Relaxed);
// Send request.
let mut resp = None;
match http.request(req).await {
Ok(r) => {
match hyper::body::to_bytes(r).await {
Ok(raw) => {
resp = Some(String::from_utf8_lossy(&raw).to_string())
},
Err(_) => {},
}
}
});
},
Err(_) => {},
}
resp
}
/// Launch SOCKS proxy server to send connections.
async fn launch_socks_proxy<R: Runtime>(runtime: R, tor_client: TorClient<R>) -> Result<()> {
let proxy_handle: JoinHandle<Result<()>> = tokio::spawn(
run_socks_proxy(
runtime,
tor_client,
Listen::new_localhost(TorServerConfig::socks_port()),
)
);
// Setup server state flags.
TOR_SERVER_STATE.starting.store(false, Ordering::Relaxed);
TOR_SERVER_STATE.running.store(true, Ordering::Relaxed);
loop {
if Self::is_stopping() || proxy_handle.is_finished() {
proxy_handle.abort();
TOR_SERVER_STATE.stopping.store(false, Ordering::Relaxed);
TOR_SERVER_STATE.running.store(false, Ordering::Relaxed);
return Ok(());
}
sleep(Duration::from_millis(3000)).await;
}
/// Check if Onion service is starting.
pub fn is_service_starting(id: &String) -> bool {
let r_services = TOR_SERVER_STATE.starting_services.read().unwrap();
r_services.contains(id)
}
/// Check if Onion service is running.
@@ -217,36 +143,80 @@ impl TorServer {
r_services.contains_key(id)
}
/// Check if Onion service failed on start.
pub fn is_service_failed(id: &String) -> bool {
let r_services = TOR_SERVER_STATE.failed_services.read().unwrap();
r_services.contains(id)
}
/// Stop running Onion service.
pub fn stop_service(id: &String) {
let mut w_services = TOR_SERVER_STATE.running_services.write().unwrap();
if let Some(proxy) = w_services.remove(id) {
if let Some((svc, proxy)) = w_services.remove(id) {
proxy.shutdown();
drop(svc);
}
}
/// Run Onion service from listening local address, secret key and identifier.
pub fn run_service(addr: SocketAddr, key: SecretKey, id: &String) {
/// Start Onion service from listening local port and [`SecretKey`].
pub fn start_service(port: u16, key: SecretKey, id: &String) {
// Check if service is already running.
if Self::is_service_running(id) {
return;
} else {
// Save starting service.
let mut w_services = TOR_SERVER_STATE.starting_services.write().unwrap();
w_services.insert(id.clone());
// Remove service from failed.
let mut w_services = TOR_SERVER_STATE.failed_services.write().unwrap();
w_services.remove(id);
}
let hs_nickname = HsNickname::new(id.clone()).unwrap();
let service_config = OnionServiceConfigBuilder::default()
.nickname(hs_nickname.clone())
.build()
.unwrap();
let r_client = TOR_SERVER_STATE.client.read().unwrap();
let client = r_client.clone().unwrap();
let service_id = id.clone();
let client_config = TOR_SERVER_STATE.client.read().unwrap();
let client = client_config.0.clone();
let config = client_config.1.clone();
client.clone().runtime().spawn(async move {
// Add service key to keystore.
let hs_nickname = HsNickname::new(service_id.clone()).unwrap();
Self::add_service_key(config.fs_mistrust(), &key, &hs_nickname);
// Add service key to keystore.
let r_config = TOR_SERVER_STATE.config.read().unwrap();
let config = r_config.clone().unwrap();
Self::add_service_key(config.fs_mistrust(), &key, &hs_nickname);
// Bootstrap client and launch Onion service.
client.bootstrap().await.unwrap();
let service_config = OnionServiceConfigBuilder::default()
.nickname(hs_nickname.clone())
.build()
.unwrap();
let (service, request) = client.launch_onion_service(service_config).unwrap();
// Launch Onion service.
let (_, request) = client.launch_onion_service(service_config).unwrap();
// Launch service proxy.
let addr = SocketAddr::new(IpAddr::from(Ipv4Addr::LOCALHOST), port);
tokio::spawn(
Self::run_service_proxy(addr, client, service.clone(), request, hs_nickname.clone())
).await.unwrap();
println!(
"Onion service {} launched at: {}",
hs_nickname,
service.onion_name().unwrap().to_string()
);
}).unwrap();
}
/// Launch Onion service proxy.
async fn run_service_proxy<R, S>(
addr: SocketAddr,
client: TorClient<R>,
service: Arc<RunningOnionService>,
request: S,
nickname: HsNickname
)
where
R: Runtime,
S: futures::Stream<Item = tor_hsservice::RendRequest> + Unpin + Send + 'static,
{
let id = nickname.to_string();
let runtime = client.runtime().clone();
// Setup proxy to forward request from Tor address to local address.
let proxy_rule = ProxyRule::new(
@@ -257,43 +227,49 @@ impl TorServer {
proxy_cfg_builder.set_proxy_ports(vec![proxy_rule]);
let proxy = OnionServiceReverseProxy::new(proxy_cfg_builder.build().unwrap());
// Launch proxy at client runtime.
let proxy_service = proxy.clone();
let runtime = client.runtime().clone();
let nickname = hs_nickname.clone();
// Save running service.
let mut w_services = TOR_SERVER_STATE.running_services.write().unwrap();
w_services.insert(id.clone(), (service.clone(), proxy.clone()));
// Remove service from starting.
let mut w_services = TOR_SERVER_STATE.starting_services.write().unwrap();
w_services.remove(&id);
// Start proxy for launched service.
client
.runtime()
.spawn(async move {
// Launch proxy for launched service.
match proxy_service.handle_requests(runtime, nickname.clone(), request).await {
match proxy
.handle_requests(runtime, nickname.clone(), request)
.await {
Ok(()) => {
eprintln!("Onion service {} stopped.", nickname);
// Remove service from running.
let mut w_services =
TOR_SERVER_STATE.running_services.write().unwrap();
w_services.remove(&id);
println!("Onion service {} stopped.", nickname);
}
Err(e) => {
// Remove service from running.
let mut w_services =
TOR_SERVER_STATE.running_services.write().unwrap();
w_services.remove(&id);
// Save failed service.
let mut w_services =
TOR_SERVER_STATE.failed_services.write().unwrap();
w_services.insert(id);
eprintln!("Onion service {} exited with an error: {}", nickname, e);
}
}
}).unwrap();
// Save running service.
let mut w_services = TOR_SERVER_STATE.running_services.write().unwrap();
w_services.insert(id.clone(), proxy);
let onion_addr = OnionV3Address::from_private(&key.0).unwrap();
eprintln!("Onion service {} launched at {}", hs_nickname, onion_addr.to_ov3_str());
}
/// Add Onion service key to keystore.
/// Save Onion service key to keystore.
fn add_service_key(mistrust: &Mistrust, key: &SecretKey, hs_nickname: &HsNickname) {
let mut client_config_builder = TorClientConfigBuilder::from_directories(
TorServerConfig::state_path(),
TorServerConfig::cache_path()
);
client_config_builder
.address_filter()
.allow_onion_addrs(true);
let arti_store =
ArtiNativeKeystore::from_path_and_mistrust(TorServerConfig::keystore_path(), &mistrust)
ArtiNativeKeystore::from_path_and_mistrust(TorConfig::keystore_path(), &mistrust)
.unwrap();
let key_manager = KeyMgrBuilder::default()
@@ -329,49 +305,4 @@ impl TorServer {
)
.unwrap();
}
/// Setup Tor Snowflake bridges.
fn setup_bridges(builder: &mut TorClientConfigBuilder) {
// Add a single bridge to the list of bridges, from a bridge line.
// This line comes from https://gitlab.torproject.org/tpo/applications/tor-browser-build/-/blob/main/projects/common/bridges_list.snowflake.txt
// this is a real bridge line you can use as-is, after making sure it's still up to date with
// above link.
const BRIDGE1_LINE: &str = "Bridge snowflake 192.0.2.3:80 2B280B23E1107BB62ABFC40DDCC8824814F80A72 fingerprint=2B280B23E1107BB62ABFC40DDCC8824814F80A72 url=https://snowflake-broker.torproject.net.global.prod.fastly.net/ front=cdn.sstatic.net ice=stun:stun.l.google.com:19302,stun:stun.antisip.com:3478,stun:stun.bluesip.net:3478,stun:stun.dus.net:3478,stun:stun.epygi.com:3478,stun:stun.sonetel.com:3478,stun:stun.uls.co.za:3478,stun:stun.voipgate.com:3478,stun:stun.voys.nl:3478 utls-imitate=hellorandomizedalpn";
let bridge_1: BridgeConfigBuilder = BRIDGE1_LINE.parse().unwrap();
builder.bridges().bridges().push(bridge_1);
// Add a second bridge, built by hand. We use the 2nd bridge line from above, but modify some
// parameters to use AMP Cache instead of Fastly as a signaling channel. The difference in
// configuration is detailed in
// https://gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/-/tree/main/client#amp-cache
let mut bridge2_builder = BridgeConfigBuilder::default();
bridge2_builder
.transport("snowflake")
.push_setting(
"fingerprint",
"8838024498816A039FCBBAB14E6F40A0843051FA"
)
.push_setting("url", "https://snowflake-broker.torproject.net/")
.push_setting("ampcache", "https://cdn.ampproject.org/")
.push_setting("front", "www.google.com")
.push_setting(
"ice",
"stun:stun.l.google.com:19302,stun:stun.antisip.com:3478,stun:stun.bluesip.net:3478,stun:stun.dus.net:3478,stun:stun.epygi.com:3478,stun:stun.sonetel.net:3478,stun:stun.uls.co.za:3478,stun:stun.voipgate.com:3478,stun:stun.voys.nl:3478",
)
.push_setting("utls-imitate", "hellorandomizedalpn");
bridge2_builder.set_addrs(vec!["192.0.2.4:80".parse().unwrap()]);
bridge2_builder.set_ids(vec!["8838024498816A039FCBBAB14E6F40A0843051FA".parse().unwrap()]);
// Now insert the second bridge into our config builder.
builder.bridges().bridges().push(bridge2_builder);
// Now configure an snowflake transport. (Requires the "pt-client" feature)
let mut transport = TransportConfigBuilder::default();
transport
.protocols(vec!["snowflake".parse().unwrap()])
// this might be named differently on some systems, this should work on Debian,
// but Archlinux is known to use `snowflake-pt-client` instead for instance.
.path(CfgPath::new("snowflake-client".into()))
.run_on_startup(true);
builder.bridges().transports().push(transport);
}
}