server.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{
  19. collections::HashMap,
  20. fs::File,
  21. io::{BufReader, Cursor},
  22. path::PathBuf,
  23. sync::Arc,
  24. };
  25. use darkfi::{
  26. event_graph::Event,
  27. system::{StoppableTask, StoppableTaskPtr, Subscription},
  28. util::path::expand_path,
  29. zk::{empty_witnesses, ProvingKey, VerifyingKey, ZkCircuit},
  30. zkas::ZkBinary,
  31. Error, Result,
  32. };
  33. use darkfi_sdk::crypto::MerkleTree;
  34. use darkfi_serial::serialize_async;
  35. use futures_rustls::{
  36. rustls::{self, pki_types::PrivateKeyDer},
  37. TlsAcceptor,
  38. };
  39. use log::{debug, error, info, warn};
  40. use sled_overlay::sled;
  41. use smol::{
  42. fs,
  43. lock::{Mutex, RwLock},
  44. net::{SocketAddr, TcpListener},
  45. prelude::{AsyncRead, AsyncWrite},
  46. Executor,
  47. };
  48. use url::Url;
  49. use super::{client::Client, IrcChannel, IrcContact, Priv, Privmsg};
  50. use crate::{
  51. crypto::{
  52. rln::{RlnIdentity, RLN2_SIGNAL_ZKBIN, RLN2_SLASH_ZKBIN},
  53. saltbox,
  54. },
  55. settings::{
  56. parse_autojoin_channels, parse_configured_channels, parse_configured_contacts,
  57. parse_rln_identity,
  58. },
  59. DarkIrc,
  60. };
  61. /// Max channel/nick length
  62. pub const MAX_NICK_LEN: usize = 24;
  63. /// Max message length
  64. pub const MAX_MSG_LEN: usize = 512;
  65. /// IRC server instance
  66. pub struct IrcServer {
  67. /// DarkIrc instance
  68. pub darkirc: Arc<DarkIrc>,
  69. /// Path to the darkirc config file
  70. config_path: PathBuf,
  71. /// TCP listener
  72. listener: TcpListener,
  73. /// TLS acceptor
  74. acceptor: Option<TlsAcceptor>,
  75. /// Configured autojoin channels
  76. pub autojoin: RwLock<Vec<String>>,
  77. /// Configured IRC channels
  78. pub channels: RwLock<HashMap<String, IrcChannel>>,
  79. /// Configured IRC contacts
  80. pub contacts: RwLock<HashMap<String, IrcContact>>,
  81. /// Configured RLN identity
  82. pub rln_identity: RwLock<Option<RlnIdentity>>,
  83. /// Active client connections
  84. clients: Mutex<HashMap<u16, StoppableTaskPtr>>,
  85. /// IRC server Password
  86. pub password: String,
  87. /// Persistent server storage
  88. pub server_store: sled::Tree,
  89. /// RLN identity storage
  90. pub rln_identity_store: sled::Tree,
  91. /// RLN Signal VerifyingKey
  92. pub rln_signal_vk: VerifyingKey,
  93. }
  94. impl IrcServer {
  95. /// Instantiate a new IRC server. This function will try to bind a TCP socket,
  96. /// and optionally load a TLS certificate and key. To start the listening loop,
  97. /// call `IrcServer::listen()`.
  98. pub async fn new(
  99. darkirc: Arc<DarkIrc>,
  100. listen: Url,
  101. tls_cert: Option<String>,
  102. tls_secret: Option<String>,
  103. config_path: PathBuf,
  104. password: String,
  105. ) -> Result<Arc<Self>> {
  106. let scheme = listen.scheme();
  107. if scheme != "tcp" && scheme != "tcp+tls" {
  108. error!("IRC server supports listening only on tcp:// or tcp+tls://");
  109. return Err(Error::BindFailed(listen.to_string()))
  110. }
  111. if scheme == "tcp+tls" && (tls_cert.is_none() || tls_secret.is_none()) {
  112. error!("You must provide a TLS certificate and key if you want a TLS server");
  113. return Err(Error::BindFailed(listen.to_string()))
  114. }
  115. // Bind listener
  116. let listen_addr = listen.socket_addrs(|| None)?[0];
  117. let listener = TcpListener::bind(listen_addr).await?;
  118. let acceptor = match scheme {
  119. "tcp+tls" => {
  120. // openssl genpkey -algorithm ED25519 > example.com.key
  121. // openssl req -new -out example.com.csr -key example.com.key
  122. // openssl x509 -req -in example.com.csr -signkey example.com.key -out example.com.crt
  123. let f = File::open(expand_path(tls_secret.as_ref().unwrap())?)?;
  124. let mut reader = BufReader::new(f);
  125. let secret = PrivateKeyDer::Pkcs8(
  126. rustls_pemfile::pkcs8_private_keys(&mut reader).next().unwrap().unwrap(),
  127. );
  128. let f = File::open(expand_path(tls_cert.as_ref().unwrap())?)?;
  129. let mut reader = BufReader::new(f);
  130. let cert = rustls_pemfile::certs(&mut reader).next().unwrap().unwrap();
  131. let config = rustls::ServerConfig::builder()
  132. .with_no_client_auth()
  133. .with_single_cert(vec![cert], secret)
  134. .unwrap();
  135. let acceptor = TlsAcceptor::from(Arc::new(config));
  136. Some(acceptor)
  137. }
  138. _ => None,
  139. };
  140. // Open persistent dbs
  141. let server_store = darkirc.sled.open_tree("server_store")?;
  142. let rln_identity_store = darkirc.sled.open_tree("rln_identity_store")?;
  143. // Generate RLN proving and verifying keys, if needed
  144. let rln_signal_zkbin = ZkBinary::decode(RLN2_SIGNAL_ZKBIN)?;
  145. let rln_signal_circuit =
  146. ZkCircuit::new(empty_witnesses(&rln_signal_zkbin)?, &rln_signal_zkbin);
  147. if server_store.get("rlnv2-diff-signal-pk")?.is_none() {
  148. info!(target: "irc::server", "[RLN] Creating RlnV2_Diff_Signal ProvingKey");
  149. let provingkey = ProvingKey::build(rln_signal_zkbin.k, &rln_signal_circuit);
  150. let mut buf = vec![];
  151. provingkey.write(&mut buf)?;
  152. server_store.insert("rlnv2-diff-signal-pk", buf)?;
  153. }
  154. let rln_signal_vk = match server_store.get("rlnv2-diff-signal-vk")? {
  155. Some(vk) => {
  156. let mut reader = Cursor::new(vk);
  157. VerifyingKey::read(&mut reader, rln_signal_circuit)?
  158. }
  159. None => {
  160. info!(target: "irc::server", "[RLN] Creating RlnV2_Diff_Signal VerifyingKey");
  161. let verifyingkey = VerifyingKey::build(rln_signal_zkbin.k, &rln_signal_circuit);
  162. let mut buf = vec![];
  163. verifyingkey.write(&mut buf)?;
  164. server_store.insert("rlnv2-diff-signal-vk", buf)?;
  165. verifyingkey
  166. }
  167. };
  168. if server_store.get("rlnv2-diff-slash-pk")?.is_none() {
  169. info!(target: "irc::server", "[RLN] Creating RlnV2_Diff_Slash ProvingKey");
  170. let zkbin = ZkBinary::decode(RLN2_SLASH_ZKBIN)?;
  171. let circuit = ZkCircuit::new(empty_witnesses(&zkbin).unwrap(), &zkbin);
  172. let provingkey = ProvingKey::build(zkbin.k, &circuit);
  173. let mut buf = vec![];
  174. provingkey.write(&mut buf)?;
  175. server_store.insert("rlnv2-diff-slash-pk", buf)?;
  176. }
  177. if server_store.get("rlnv2-diff-slash-vk")?.is_none() {
  178. info!(target: "irc::server", "[RLN] Creating RlnV2_Diff_Slash VerifyingKey");
  179. let zkbin = ZkBinary::decode(RLN2_SIGNAL_ZKBIN)?;
  180. let circuit = ZkCircuit::new(empty_witnesses(&zkbin).unwrap(), &zkbin);
  181. let verifyingkey = VerifyingKey::build(zkbin.k, &circuit);
  182. let mut buf = vec![];
  183. verifyingkey.write(&mut buf)?;
  184. server_store.insert("rlnv2-diff-slash-vk", buf)?;
  185. }
  186. // Initialize RLN Incremental Merkle tree if necessary
  187. if server_store.get("rln_identity_tree")?.is_none() {
  188. let tree = MerkleTree::new(1);
  189. server_store.insert("rln_identity_tree", serialize_async(&tree).await)?;
  190. }
  191. let self_ = Arc::new(Self {
  192. darkirc,
  193. config_path,
  194. listener,
  195. acceptor,
  196. autojoin: RwLock::new(Vec::new()),
  197. channels: RwLock::new(HashMap::new()),
  198. contacts: RwLock::new(HashMap::new()),
  199. rln_identity: RwLock::new(None),
  200. clients: Mutex::new(HashMap::new()),
  201. password,
  202. server_store,
  203. rln_identity_store,
  204. rln_signal_vk,
  205. });
  206. // Load any channel/contact configuration.
  207. self_.rehash().await?;
  208. Ok(self_)
  209. }
  210. /// Reload the darkirc configuration file and reconfigure channels and contacts.
  211. pub async fn rehash(&self) -> Result<()> {
  212. let contents = fs::read_to_string(&self.config_path).await?;
  213. let contents = match toml::from_str(&contents) {
  214. Ok(v) => v,
  215. Err(e) => {
  216. error!("Failed parsing TOML config: {}", e);
  217. return Err(Error::ParseFailed("Failed parsing TOML config"))
  218. }
  219. };
  220. // Parse autojoin channels
  221. let autojoin = parse_autojoin_channels(&contents)?;
  222. // Parse configured channels
  223. let configured_channels = parse_configured_channels(&contents)?;
  224. // Parse configured contacts
  225. let contacts = parse_configured_contacts(&contents)?;
  226. // Parse RLN identity
  227. let rln_identity = parse_rln_identity(&contents)?;
  228. // Persist unconfigured channels (joined from client, or autojoined without config)
  229. let channels = {
  230. let old_channels = self.channels.read().await.clone();
  231. let unconfigured_channels: HashMap<String, IrcChannel> = old_channels
  232. .into_iter()
  233. .filter(|(chan_str, _)| !configured_channels.contains_key(chan_str))
  234. .collect();
  235. configured_channels.into_iter().chain(unconfigured_channels).collect()
  236. };
  237. // Only if everything is fine, replace.
  238. *self.autojoin.write().await = autojoin;
  239. *self.channels.write().await = channels;
  240. *self.contacts.write().await = contacts;
  241. *self.rln_identity.write().await = rln_identity;
  242. Ok(())
  243. }
  244. /// Start accepting new IRC connections.
  245. pub async fn listen(self: Arc<Self>, ex: Arc<Executor<'_>>) -> Result<()> {
  246. loop {
  247. let (stream, peer_addr) = match self.listener.accept().await {
  248. Ok((s, a)) => (s, a),
  249. // As per usual accept(2) recommendations
  250. Err(e) if e.raw_os_error().is_some() => match e.raw_os_error().unwrap() {
  251. libc::EAGAIN | libc::ECONNABORTED | libc::EPROTO | libc::EINTR => continue,
  252. _ => {
  253. error!("[IRC SERVER] Failed accepting connection: {}", e);
  254. return Err(e.into())
  255. }
  256. },
  257. Err(e) => {
  258. error!("[IRC SERVER] Failed accepting new connection: {}", e);
  259. continue
  260. }
  261. };
  262. match &self.acceptor {
  263. // Expecting encrypted TLS connection
  264. Some(acceptor) => {
  265. let stream = match acceptor.accept(stream).await {
  266. Ok(s) => s,
  267. Err(e) => {
  268. error!("[IRC SERVER] Failed accepting new TLS connection: {}", e);
  269. continue
  270. }
  271. };
  272. // Subscribe to incoming events and set up the connection.
  273. let incoming = self.darkirc.event_graph.event_pub.clone().subscribe().await;
  274. if let Err(e) = self
  275. .clone()
  276. .process_connection(stream, peer_addr, incoming, ex.clone())
  277. .await
  278. {
  279. error!("[IRC SERVER] Failed processing new connection: {}", e);
  280. continue
  281. };
  282. }
  283. // Expecting plain TCP connection
  284. None => {
  285. // Subscribe to incoming events and set up the connection.
  286. let incoming = self.darkirc.event_graph.event_pub.clone().subscribe().await;
  287. if let Err(e) = self
  288. .clone()
  289. .process_connection(stream, peer_addr, incoming, ex.clone())
  290. .await
  291. {
  292. error!("[IRC SERVER] Failed processing new connection: {}", e);
  293. continue
  294. };
  295. }
  296. }
  297. info!("[IRC SERVER] Accepted new client connection at: {}", peer_addr);
  298. }
  299. }
  300. /// IRC client connection process.
  301. /// Sets up multiplexing between the server and client.
  302. /// Detaches the connection as a `StoppableTask`.
  303. async fn process_connection<C: AsyncRead + AsyncWrite + Send + Unpin + 'static>(
  304. self: Arc<Self>,
  305. stream: C,
  306. peer_addr: SocketAddr,
  307. incoming: Subscription<Event>,
  308. ex: Arc<Executor<'_>>,
  309. ) -> Result<()> {
  310. let port = peer_addr.port();
  311. let client = Client::new(self.clone(), incoming, peer_addr).await?;
  312. let conn_task = StoppableTask::new();
  313. self.clients.lock().await.insert(port, conn_task.clone());
  314. conn_task.clone().start(
  315. async move { client.multiplex_connection(stream).await },
  316. move |res| async move {
  317. match res {
  318. Ok(()) => info!("[IRC SERVER] Disconnected client from {}", peer_addr),
  319. Err(e) => error!("[IRC SERVER] Disconnected client from {}: {}", peer_addr, e),
  320. }
  321. self.clone().clients.lock().await.remove(&port);
  322. },
  323. Error::ChannelStopped,
  324. ex,
  325. );
  326. Ok(())
  327. }
  328. fn pad(string: &str) -> Vec<u8> {
  329. let mut bytes = string.as_bytes().to_vec();
  330. bytes.resize(MAX_NICK_LEN, 0x00);
  331. bytes
  332. }
  333. fn unpad(vec: &mut Vec<u8>) {
  334. if let Some(i) = vec.iter().rposition(|x| *x != 0) {
  335. let new_len = i + 1;
  336. vec.truncate(new_len);
  337. }
  338. }
  339. /// Try encrypting a given `Privmsg` if there is such a channel/contact.
  340. pub async fn try_encrypt<T: Priv>(&self, privmsg: &mut T) {
  341. if let Some((name, channel)) = self.channels.read().await.get_key_value(privmsg.channel()) {
  342. if let Some(saltbox) = &channel.saltbox {
  343. // We will use a dummy channel value of MAX_NICK_LEN,
  344. // since its not used, so all encrypted messages look the same.
  345. *privmsg.channel() = saltbox::encrypt(saltbox, &[0x00; MAX_NICK_LEN]);
  346. // We will pad the name to MAX_NICK_LEN so they all look the same
  347. *privmsg.nick() = saltbox::encrypt(saltbox, &Self::pad(privmsg.nick()));
  348. *privmsg.msg() = saltbox::encrypt(saltbox, privmsg.msg().as_bytes());
  349. debug!("Successfully encrypted message for {}", name);
  350. return
  351. }
  352. };
  353. if let Some((name, contact)) = self.contacts.read().await.get_key_value(privmsg.channel()) {
  354. let (saltbox, self_saltbox) = &contact.saltboxes;
  355. // We will use dummy channel and nick values of MAX_NICK_LEN,
  356. // since they are not used, so all encrypted messages look the same.
  357. *privmsg.channel() = saltbox::encrypt(saltbox, &[0x00; MAX_NICK_LEN]);
  358. // We will encrypt the dummy nick value using our own self saltbox,
  359. // so we can identify our messages.
  360. *privmsg.nick() = saltbox::encrypt(self_saltbox, &[0x00; MAX_NICK_LEN]);
  361. *privmsg.msg() = saltbox::encrypt(saltbox, privmsg.msg().as_bytes());
  362. debug!("Successfully encrypted message for {}", name);
  363. };
  364. }
  365. /// Try decrypting a given potentially encrypted `Privmsg` object.
  366. pub async fn try_decrypt(&self, privmsg: &mut Privmsg, self_nickname: &str) {
  367. // If all fields have base58, then we can consider decrypting.
  368. let channel_ciphertext = match bs58::decode(&privmsg.channel).into_vec() {
  369. Ok(v) => v,
  370. Err(_) => return,
  371. };
  372. let nick_ciphertext = match bs58::decode(&privmsg.nick).into_vec() {
  373. Ok(v) => v,
  374. Err(_) => return,
  375. };
  376. let msg_ciphertext = match bs58::decode(&privmsg.msg).into_vec() {
  377. Ok(v) => v,
  378. Err(_) => return,
  379. };
  380. // Now go through all 3 ciphertexts. We'll use intermediate buffers
  381. // for decryption, iff all passes, we will return a modified
  382. // (i.e. decrypted) privmsg, otherwise we return the original.
  383. for (name, channel) in self.channels.read().await.iter() {
  384. let Some(saltbox) = &channel.saltbox else { continue };
  385. if saltbox::try_decrypt(saltbox, &channel_ciphertext).is_none() {
  386. continue
  387. };
  388. let Some(mut nick_dec) = saltbox::try_decrypt(saltbox, &nick_ciphertext) else {
  389. warn!(target: "darkirc::irc::server::try_decrypt", "Could not decrypt nick ciphertext for channel: {name}");
  390. continue
  391. };
  392. let Some(msg_dec) = saltbox::try_decrypt(saltbox, &msg_ciphertext) else {
  393. warn!(target: "darkirc::irc::server::try_decrypt", "Could not decrypt message ciphertext for channel: {name}");
  394. continue
  395. };
  396. Self::unpad(&mut nick_dec);
  397. privmsg.channel = name.to_string();
  398. privmsg.nick = String::from_utf8_lossy(&nick_dec).into();
  399. privmsg.msg = String::from_utf8_lossy(&msg_dec).into();
  400. debug!("Successfully decrypted message for {}", name);
  401. return
  402. }
  403. for (name, contact) in self.contacts.read().await.iter() {
  404. let (saltbox, self_saltbox) = &contact.saltboxes;
  405. if saltbox::try_decrypt(saltbox, &channel_ciphertext).is_none() {
  406. continue
  407. };
  408. // Since everyone encrypts the dummy nick value with their self saltbox,
  409. // we try to decrypt using our, to identify our messages.
  410. let nick = if saltbox::try_decrypt(self_saltbox, &nick_ciphertext).is_some() {
  411. String::from(self_nickname)
  412. } else {
  413. name.to_string()
  414. };
  415. let Some(msg_dec) = saltbox::try_decrypt(saltbox, &msg_ciphertext) else {
  416. warn!(target: "darkirc::irc::server::try_decrypt", "Could not decrypt message ciphertext for contact: {name}");
  417. continue
  418. };
  419. privmsg.channel = name.to_string();
  420. privmsg.nick = nick;
  421. privmsg.msg = String::from_utf8_lossy(&msg_dec).into();
  422. debug!("Successfully decrypted message from {}", name);
  423. return
  424. }
  425. }
  426. }