Compare commits

..

15 commits
v1.0.1 ... main

Author SHA1 Message Date
vanten-s e4fd3224cf Merge pull request 'Changed docs' (#8) from dev-laptop into main
Reviewed-on: #8
2023-10-21 12:07:05 +02:00
vanten-s 5c24ae5f96
Changed docs 2023-10-21 12:06:28 +02:00
vanten-s c895210cea Merge pull request 'Got ready for publication' (#7) from dev-laptop into main
Reviewed-on: #7
2023-10-21 12:05:05 +02:00
vanten-s 4aed403c97
Got ready for publication 2023-10-21 12:04:50 +02:00
vanten-s 247f35994b Merge pull request 'Version 3.0.0' (#6) from dev-laptop into main
Reviewed-on: #6
2023-10-21 11:46:12 +02:00
vanten-s 6eeeb4a2e8
Version 3.0.0 2023-10-21 11:10:44 +02:00
vanten-s 2783cc9ca8 Merge pull request 'Added an internal bot that can remove encryption for specific nicks' (#5) from dev-laptop into main
Reviewed-on: #5
2023-10-21 11:07:36 +02:00
vanten-s bdb14a5b6d
Added an internal bot that can remove encryption for specific nicks 2023-10-21 11:05:17 +02:00
vanten-s 805caebe35 Merge pull request 'Version 2' (#4) from dev-laptop into main
Reviewed-on: #4
2023-10-19 22:14:20 +02:00
vanten-s b9af753fc7
Version 2 2023-10-19 22:08:13 +02:00
vanten-s e26db6d68b
Merge branch 'dev-laptop' 2023-10-19 22:04:46 +02:00
vanten-s 7c5bc94ade
You can now reconnect to the server 2023-10-19 22:03:18 +02:00
vanten-s d38da05d05
Fixed docs, version number and made server required 2023-10-19 17:23:38 +02:00
vanten-s 83b10eb3d5
Changed from a .env to config file 2023-10-19 17:08:05 +02:00
vanten-s b480ce09e5
Added cargo.lock to gitignore 2023-10-16 11:29:08 +02:00
11 changed files with 251 additions and 1526 deletions

4
.gitignore vendored
View file

@ -1,4 +1,2 @@
/target /target
secret.gpg Cargo.lock
public.gpg
.env

1406
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,15 +1,21 @@
[package] [package]
name = "e2e-irc" name = "e2e-irc"
version = "0.1.0" version = "3.0.0"
edition = "2021" edition = "2021"
license = "GPL-3.0"
keywords = ["irc", "encryption"]
description = "An IRC bouncer that can send encrypted messages"
repository = "https://forgejo.vanten-s.com/vanten-s/e2e-irc/"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
argparse = "0.2.2"
base64 = "0.21.4" base64 = "0.21.4"
dotenv = "0.15.0" dirs = "5.0.1"
eyre = "0.6.8" eyre = "0.6.8"
ircparser = "0.2.1" ircparser-vanten = "0.2.1"
openssl = "0.10" openssl = "0.10"
pgp = "0.10.2" pgp = "0.10.2"
rand = "0.8.5" rand = "0.8.5"
toml = "0.8.2"

View file

@ -1,25 +1,35 @@
# e2e-irc # e2e-irc
This is an IRC bouncer that supports end-to-end encryption and is horribly written. This is an IRC bouncer that supports end-to-end encryption and is horribly written.
# Setup CWD # Configuration
To use this you need to build it and in your CWD you need to add two files. One called `secret.gpg` and one called `public.gpg` that are just pgp keys. e2e-irc uses a config file in `~/.config/e2e-irc/config.toml` on linux.
You also need a .env file in your CWD like this: The configuration file is a toml file with two or three fields:
- public_key the location of the public pgp key
- secret_key the location of the secret pgp key
- passwd the password of the pgp key
# Usage
```
e2e-irc [OPTIONS] SERVER
Encrypted IRC Bouncer
Positional arguments:
server The Address Of The Server The Bouncer Connects To
Optional arguments:
-h,--help Show this help message and exit
-p,--port PORT The Port The Bouncer Binds To
--sp,--server-port SERVER_PORT
The TLS Enabled Port Of The Server
```
# Install
```bash ```bash
SERVER={address of the server you want to connect to (has to support tls)} cargo install e2e-irc
PORT={the port you want the program to bind to and the port that the IRC client should connect to}
PASSWD={password of your pgp key} # Optional
``` ```
# Run # Run
Then you just run the binary with:
`cargo run --release`
or build the project to get a binary
```bash ```bash
cargo build --release e2e-irc [OPTIONS] SERVER
cp target/release/e2e-irc ~/.local/bin/
``` ```
and after running that once you can run the program with
```bash
e2e-irc
```
but you have to have the .env in the CWD

View file

@ -1,10 +1,41 @@
use crate::helpers::bytes_to_privmsg_base64; use crate::helpers::bytes_to_privmsg_base64;
use crate::{encryption, helpers}; use crate::{encryption, helpers, State};
use eyre::Result; use eyre::Result;
use pgp::{Deserializable, SignedPublicKey}; use pgp::{Deserializable, SignedPublicKey};
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::mpsc::{Receiver, Sender}; use std::sync::mpsc::{Receiver, Sender};
#[derive(Debug)]
struct InvalidCommand;
impl std::fmt::Display for InvalidCommand {
fn fmt(&self, _f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Ok(())
}
}
impl std::error::Error for InvalidCommand {}
fn parse_bouncer_command(message: String, state: &mut State) -> Result<()> {
macro_rules! unwrap_option {
($t:expr) => {
match $t {
Some(val) => val,
None => return Err(InvalidCommand.into()),
}
};
}
let mut splitted = message.split(' ');
match unwrap_option!(splitted.next()) {
"ALLOW_UNENCRYPTED" => state
.nicks_without_encryption
.push(unwrap_option!(splitted.next()).to_string().to_lowercase()),
_ => return Err(InvalidCommand.into()),
};
Ok(())
}
pub fn handle_message_from_client( pub fn handle_message_from_client(
recieved: &str, recieved: &str,
public_key: &Vec<u8>, public_key: &Vec<u8>,
@ -14,10 +45,34 @@ pub fn handle_message_from_client(
writer_channel_rx: &Receiver<String>, writer_channel_rx: &Receiver<String>,
listener_channel_tx: &Sender<String>, listener_channel_tx: &Sender<String>,
_listener_channel_rx: &Receiver<String>, _listener_channel_rx: &Receiver<String>,
state: &mut State,
) -> Result<()> { ) -> Result<()> {
let command = &ircparser::parse(recieved).expect("Got an invalid IRC instruction")[0]; let mut recieved = recieved.to_string();
if command.command == "PRIVMSG" && !command.params[0].starts_with("#") { if recieved.split(' ').count() == 1 {
recieved += " ";
}
let parsed = ircparser::parse(&recieved);
let command = match parsed {
Ok(val) => val[0].clone(),
Err(_) => {
writer_channel_tx.send(recieved)?;
return Ok(());
}
};
if command.command == "PRIVMSG" && !command.params[0].starts_with('#') {
if command.params[0] == "BOUNCER" {
return parse_bouncer_command(command.params[1].clone(), state);
}
if state
.nicks_without_encryption
.contains(&command.params[0].to_lowercase())
{
writer_channel_tx.send(recieved)?;
return Ok(());
}
let other = &command.params[0]; let other = &command.params[0];
if !keys.contains_key(other) { if !keys.contains_key(other) {
@ -27,7 +82,7 @@ pub fn handle_message_from_client(
listener_channel_tx, listener_channel_tx,
"127.0.0.1", "127.0.0.1",
server, server,
&other, other,
"END_KEY", "END_KEY",
)?; )?;
let key = SignedPublicKey::from_bytes(key.as_slice())?; let key = SignedPublicKey::from_bytes(key.as_slice())?;
@ -38,12 +93,12 @@ pub fn handle_message_from_client(
writer_channel_tx.send(format!("PRIVMSG {other} START_MESSAGE\r\n"))?; writer_channel_tx.send(format!("PRIVMSG {other} START_MESSAGE\r\n"))?;
writer_channel_tx.send(bytes_to_privmsg_base64( writer_channel_tx.send(bytes_to_privmsg_base64(
&encryption::encrypt(&foreign_key, &command.params[1])?, &encryption::encrypt(foreign_key, &command.params[1])?,
other, other,
))?; ))?;
writer_channel_tx.send(format!("PRIVMSG {other} END_MESSAGE\r\n"))?; writer_channel_tx.send(format!("PRIVMSG {other} END_MESSAGE\r\n"))?;
} else { } else {
writer_channel_tx.send(recieved.replace("127.0.0.1", &server))?; writer_channel_tx.send(recieved.replace("127.0.0.1", server))?;
} }
Ok(()) Ok(())
} }

View file

@ -10,7 +10,7 @@ pub fn encrypt(key: &SignedPublicKey, message: &str) -> Result<Vec<u8>, pgp::err
let message = message.encrypt_to_keys(&mut rng, SymmetricKeyAlgorithm::AES128, &[key])?; let message = message.encrypt_to_keys(&mut rng, SymmetricKeyAlgorithm::AES128, &[key])?;
Ok(message.to_bytes()?) message.to_bytes()
} }
pub fn decrypt<'a>( pub fn decrypt<'a>(

View file

@ -1,10 +1,9 @@
use base64::{engine::general_purpose, Engine as _}; use base64::{engine::general_purpose, Engine as _};
use eyre::Result; use eyre::Result;
use ircparser;
use std::sync::mpsc::{self, Receiver, Sender}; use std::sync::mpsc::{self, Receiver, Sender};
#[derive(Debug)] #[derive(Debug)]
struct IrcParseError; pub struct IrcParseError;
impl std::fmt::Display for IrcParseError { impl std::fmt::Display for IrcParseError {
fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
@ -36,6 +35,22 @@ macro_rules! unwrap_or_return_option {
}; };
} }
pub struct State {
pub nicks_without_encryption: Vec<String>,
}
impl State {
pub fn new() -> Self {
State {
nicks_without_encryption: vec![
"nickserv".to_string(),
"chanserv".to_string(),
"hostserv".to_string(),
],
}
}
}
fn forward( fn forward(
message: String, message: String,
stream: &Sender<String>, stream: &Sender<String>,
@ -45,7 +60,7 @@ fn forward(
match ircparser::parse(&message) { match ircparser::parse(&message) {
Ok(val) => match val[0].command.as_str() { Ok(val) => match val[0].command.as_str() {
"PRIVMSG" => stream.send(message), "PRIVMSG" => stream.send(message),
_ => stream.send(message.replace(&server_local, server_forward)), _ => stream.send(message.replace(server_local, server_forward)),
}, },
Err(_) => stream.send(message.replace(server_local, server_forward)), Err(_) => stream.send(message.replace(server_local, server_forward)),
} }
@ -113,7 +128,7 @@ pub fn recieve_message_base64(
.clone() .clone()
.unwrap_or("".to_string()) .unwrap_or("".to_string())
.starts_with(&begin_source_reciever) .starts_with(&begin_source_reciever)
|| recieved.params[0].starts_with("#") || recieved.params[0].starts_with('#')
{ {
forward(recieved_raw, forward_stream, server_local, server_forward)?; forward(recieved_raw, forward_stream, server_local, server_forward)?;
continue; continue;

View file

@ -31,13 +31,13 @@ fn stream_handler(tx: &mpsc::Sender<String>, rx: &mpsc::Receiver<String>, mut st
} }
}; };
} }
Err(TryRecvError::Empty) => {}, Err(TryRecvError::Empty) => {}
Err(TryRecvError::Disconnected) => return, Err(TryRecvError::Disconnected) => return,
} }
thread::sleep(Duration::from_micros(100)); thread::sleep(Duration::from_micros(100));
} }
let _ = tx.send(String::from_utf8_lossy(&buffer).to_string()); let _ = tx.send(dbg!(String::from_utf8_lossy(&buffer).to_string()));
} }
} }
@ -54,5 +54,6 @@ pub fn listen_to_client(tx: mpsc::Sender<String>, rx: mpsc::Receiver<String>, po
stream_handler(&tx, &rx, stream); stream_handler(&tx, &rx, stream);
println!("Closed connection with {ip}"); println!("Closed connection with {ip}");
let _ = tx.send("DUMMY CLOSE_CONNECTION".to_string());
} }
} }

View file

@ -1,12 +1,14 @@
use dotenv::{dotenv, vars}; use argparse::{ArgumentParser, Store};
use dirs::config_local_dir;
use eyre::Result; use eyre::Result;
use helpers::State;
use pgp::{Deserializable, SignedPublicKey, SignedSecretKey}; use pgp::{Deserializable, SignedPublicKey, SignedSecretKey};
use std::collections::HashMap; use std::collections::HashMap;
use std::fs; use std::fs;
use std::net::{Shutdown, TcpStream};
use std::sync::mpsc; use std::sync::mpsc;
use std::thread; use std::thread;
use std::time::Duration; use std::time::Duration;
use toml::Table;
mod client_handler; mod client_handler;
mod encryption; mod encryption;
@ -16,46 +18,61 @@ mod server_handler;
mod writer_client; mod writer_client;
fn main() -> Result<()> { fn main() -> Result<()> {
dotenv().expect("Couldn't load .env. It probably doesn't exist"); let config_file = config_local_dir()
let mut vars_hashmap = HashMap::new(); .expect("Couldn't get config directory")
.join("e2e-irc/config.toml");
for var in vars() { if !config_file.exists() {
vars_hashmap.insert(var.0, var.1); panic!("Create a config file at {}", config_file.display());
} }
let server = &vars_hashmap["SERVER"]; let parsed_config = String::from_utf8_lossy(&fs::read(config_file)?).parse::<Table>()?;
let default_passwd = String::new(); let public_key_location = parsed_config
.get("public_key")
.expect("Coudln't get public_key. Try creating it in the config")
.as_str()
.expect("Couldn't convert public_key to str");
let secret_key_location = parsed_config
.get("secret_key")
.expect("Coudln't get secret_key. Try creating it in the config")
.as_str()
.expect("Couldn't convert secret_key to str");
let port = match vars_hashmap.get("PORT") { let default_password = toml::Value::String(String::new());
Some(val) => val,
None => "6666", let passwd = parsed_config
.get("passwd")
.unwrap_or(&default_password)
.as_str()
.expect("Coudln't convert passwd to str");
let mut server = "irc.vanten-s.com".to_string();
let mut port = "6666".to_string();
let mut server_port = "6697".to_string();
{
let mut ap = ArgumentParser::new();
ap.set_description("Encrypted IRC Bouncer");
ap.refer(&mut server)
.add_argument(
"server",
Store,
"The Address Of The Server The Bouncer Connects To",
)
.required();
ap.refer(&mut port)
.add_option(&["-p", "--port"], Store, "The Port The Bouncer Binds To");
ap.refer(&mut server_port).add_option(
&["--sp", "--server-port"],
Store,
"The TLS Enabled Port Of The Server",
);
ap.parse_args_or_exit();
} }
.to_string();
let passwd = vars_hashmap.get("PASSWD").unwrap_or(&default_passwd); let public_key = fs::read(public_key_location)?;
let secret_key = SignedSecretKey::from_bytes(fs::read(secret_key_location)?.as_slice())?;
let stream = TcpStream::connect(format!("{server}:6697"))?;
let public_key = fs::read("public.gpg")?;
let secret_key = SignedSecretKey::from_bytes(fs::read("secret.gpg")?.as_slice())?;
let reader_stream = match stream.try_clone() {
Ok(stream) => stream,
Err(_error) => {
let _ = stream.shutdown(Shutdown::Both);
panic!("Failed to create the reader stream")
}
};
let writer_stream = match stream.try_clone() {
Ok(stream) => stream,
Err(_error) => {
let _ = stream.shutdown(Shutdown::Both);
let _ = reader_stream.shutdown(Shutdown::Both);
panic!("Failed to create the writer stream")
}
};
let (listener_channel_send_tx, listener_channel_rx) = mpsc::channel(); let (listener_channel_send_tx, listener_channel_rx) = mpsc::channel();
let (listener_channel_tx, listener_channel_recv_rx) = mpsc::channel(); let (listener_channel_tx, listener_channel_recv_rx) = mpsc::channel();
@ -63,20 +80,27 @@ fn main() -> Result<()> {
let (writer_channel_tx, writer_channel_send_rx) = mpsc::channel(); let (writer_channel_tx, writer_channel_send_rx) = mpsc::channel();
let (writer_channel_recv_tx, writer_channel_rx) = mpsc::channel(); let (writer_channel_recv_tx, writer_channel_rx) = mpsc::channel();
let tmp_port = port.clone();
thread::spawn(move || { thread::spawn(move || {
listener_server::listen_to_client(listener_channel_send_tx, listener_channel_recv_rx, port) listener_server::listen_to_client(
listener_channel_send_tx,
listener_channel_recv_rx,
tmp_port,
)
}); });
let tmp_port = server_port.clone();
let tmp_server = server.clone(); let tmp_server = server.clone();
thread::spawn(|| { thread::spawn(move || {
writer_client::write_to_server( writer_client::write_to_server(
writer_stream, &tmp_server,
tmp_server, &tmp_port,
writer_channel_send_rx, writer_channel_send_rx,
writer_channel_recv_tx, writer_channel_recv_tx,
) )
}); });
let mut keys: HashMap<String, SignedPublicKey> = HashMap::new(); let mut keys: HashMap<String, SignedPublicKey> = HashMap::new();
let mut state = State::new();
loop { loop {
match listener_channel_rx.try_recv() { match listener_channel_rx.try_recv() {
@ -84,12 +108,13 @@ fn main() -> Result<()> {
let _ = client_handler::handle_message_from_client( let _ = client_handler::handle_message_from_client(
&message, &message,
&public_key, &public_key,
server, &server,
&mut keys, &mut keys,
&writer_channel_tx, &writer_channel_tx,
&writer_channel_rx, &writer_channel_rx,
&listener_channel_tx, &listener_channel_tx,
&listener_channel_rx, &listener_channel_rx,
&mut state,
); );
} }
Err(error) => match error { Err(error) => match error {
@ -104,13 +129,14 @@ fn main() -> Result<()> {
&message, &message,
&public_key, &public_key,
&secret_key, &secret_key,
server, &server,
passwd, passwd,
&mut keys, &mut keys,
&writer_channel_tx, &writer_channel_tx,
&writer_channel_rx, &writer_channel_rx,
&listener_channel_tx, &listener_channel_tx,
&listener_channel_rx, &listener_channel_rx,
&state,
); );
} }
Err(error) => match error { Err(error) => match error {

View file

@ -1,5 +1,6 @@
use crate::unwrap_or_return_option; use crate::unwrap_or_return_option;
use crate::unwrap_or_return_result; use crate::unwrap_or_return_result;
use crate::State;
use crate::{encryption, helpers}; use crate::{encryption, helpers};
use eyre::Result; use eyre::Result;
use pgp::{Deserializable, SignedPublicKey, SignedSecretKey}; use pgp::{Deserializable, SignedPublicKey, SignedSecretKey};
@ -25,15 +26,20 @@ pub fn handle_message_from_server(
writer_channel_rx: &Receiver<String>, writer_channel_rx: &Receiver<String>,
listener_channel_tx: &Sender<String>, listener_channel_tx: &Sender<String>,
_listener_channel_rx: &Receiver<String>, _listener_channel_rx: &Receiver<String>,
state: &State,
) -> Result<()> { ) -> Result<()> {
let recieved_parsed = &unwrap_or_return_result!(ircparser::parse(recieved))[0]; let recieved_parsed = &unwrap_or_return_result!(ircparser::parse(recieved))[0];
let default_reciever = String::new();
let reciever = match recieved_parsed.params.get(0) {
Some(val) => val,
None => &default_reciever,
};
if recieved_parsed.command != "PRIVMSG" if recieved_parsed.command != "PRIVMSG"
|| recieved_parsed || reciever.starts_with('#')
.params || state.nicks_without_encryption.contains(reciever)
.get(0)
.unwrap_or(&String::new())
.starts_with('#')
{ {
forward(recieved, listener_channel_tx, server)?; forward(recieved, listener_channel_tx, server)?;
return Ok(()); return Ok(());

View file

@ -6,54 +6,68 @@ use std::thread;
use std::time::Duration; use std::time::Duration;
pub fn write_to_server( pub fn write_to_server(
tcp_stream: TcpStream, server: &str,
server: String, port: &str,
rx: mpsc::Receiver<String>, rx: mpsc::Receiver<String>,
tx: mpsc::Sender<String>, tx: mpsc::Sender<String>,
) { ) {
let connector = SslConnector::builder(SslMethod::tls()).unwrap().build(); 'big: loop {
let mut stream = connector println!("Connecting to {server}:{port}");
.connect(&server, tcp_stream) let tcp_stream =
.expect("Couldn't start TLS"); TcpStream::connect(format!("{server}:{port}")).expect("Couldn't connect to server");
stream let connector = SslConnector::builder(SslMethod::tls()).unwrap().build();
.get_mut() let mut stream = connector
.set_nonblocking(true) .connect(server, &tcp_stream)
.expect("Failed to set nonblocking"); .expect("Couldn't start TLS");
loop { stream
let mut buffer: Vec<u8> = Vec::new(); .get_mut()
let mut buf: [u8; 1] = [0]; .set_nonblocking(true)
let newline: u8 = b'\n'; .expect("Failed to set nonblocking");
while buf[0] != newline { loop {
match stream.ssl_read(&mut buf) { let mut buffer: Vec<u8> = Vec::new();
Ok(_length) => { let mut buf: [u8; 1] = [0];
if _length > 0 { let newline: u8 = b'\n';
buffer.push(buf[0]);
} while buf[0] != newline {
} match stream.ssl_read(&mut buf) {
Err(_error) => match _error.io_error() { Ok(_length) => {
None => { if _length > 0 {
dbg!(_error.ssl_error()); buffer.push(buf[0]);
}
Some(error) => match error.kind() {
ErrorKind::WouldBlock => {}
_ => {
dbg!(error.kind());
println!("Couldn't read the stream");
} }
}
Err(_error) => match _error.io_error() {
None => {
dbg!(_error.ssl_error());
continue 'big;
}
Some(error) => match error.kind() {
ErrorKind::WouldBlock => {}
_ => {
dbg!(error.kind());
println!("Couldn't read the stream");
continue 'big;
}
},
}, },
}, }
let value = rx.try_recv().unwrap_or("".to_string());
match value.as_str() {
"DUMMY CLOSE_CONNECTION" => {
continue 'big;
}
_ => {}
}
match stream.write_all(value.as_bytes()) {
Ok(_) => {}
Err(_e) => println!("Couldn't send {value}"),
};
thread::sleep(Duration::from_micros(100));
} }
let value = rx.try_recv().unwrap_or("".to_string());
match stream.write_all(value.as_bytes()) {
Ok(_) => {}
Err(_e) => println!("Couldn't send {value}"),
};
thread::sleep(Duration::from_micros(100));
}
let _ = tx.send(dbg!(String::from_utf8_lossy(&buffer).to_string())); let _ = tx.send(dbg!(String::from_utf8_lossy(&buffer).to_string()));
}
} }
} }