Compare commits

..
19 Commits
Author SHA1 Message Date
eichenseerni80900 b1a40554f9 clean up 2022-12-01 12:21:43 +01:00
Daniel Laptop 808af585c9 Merge branch 'master' of https://git.efi.th-nuernberg.de/gitea/hopfma/appsec 2022-12-01 11:46:28 +01:00
geigerfl81129 9ade9799f6 Merge branch 'master' of https://git.efi.th-nuernberg.de/gitea/hopfma/appsec 2022-12-01 11:45:11 +01:00
geigerfl81129 bb8f5fc0d4 Port als lokale Variable 2022-12-01 11:45:09 +01:00
Daniel Laptop eaac88c973 Merge branch 'master' of https://git.efi.th-nuernberg.de/gitea/hopfma/appsec 2022-12-01 11:44:15 +01:00
Daniel Laptop b1a6b69867 dependencie eingebunden 2022-12-01 11:44:09 +01:00
eichenseerni80900 7460cd314c install crypto_box & de-&encrypt messages in client.rs 2022-12-01 11:43:06 +01:00
Daniel Laptop 9f0f5d8a3d Merge branch 'master' of https://git.efi.th-nuernberg.de/gitea/hopfma/appsec 2022-12-01 10:59:10 +01:00
Daniel Laptop 09fd969a58 VsCode in gitignore hinzugefügt 2022-12-01 10:59:07 +01:00
geigerfl81129 64676bfd5c minor changes 2022-12-01 10:58:06 +01:00
geigerfl81129 a9ce9cc00b Hinzufügen Kommentar 2022-12-01 10:57:27 +01:00
geigerfl81129 2d9cd3eefe Anpassung IP 2022-12-01 10:55:59 +01:00
onuchowskian84364 a0808728ad thread pool 2022-11-17 23:45:29 +01:00
eichenseerni80900 ed06a50aa8 Merge remote-tracking branch 'origin/master'
# Conflicts:
#	src/bin/client.rs
2022-11-17 12:24:18 +01:00
eichenseerni80900 3691679be4 send input from client 2022-11-17 12:23:49 +01:00
Andrew Onuchowski 829db5445e Merge remote-tracking branch 'origin/master' 2022-11-17 12:22:36 +01:00
Andrew Onuchowski ac174d0f39 added JetBrains template to .gitignore 2022-11-17 12:22:30 +01:00
grafju78439 375afb4ae7 Merge branch 'master' of https://git.efi.th-nuernberg.de/gitea/hopfma/appsec 2022-11-17 12:20:39 +01:00
grafju78439 2546dd6ba1 input error behandlung 2022-11-17 12:20:24 +01:00
5 changed files with 295 additions and 22 deletions

No files matched your search

+75
View File
@@ -59,3 +59,78 @@ Icon
Network Trash Folder
Temporary Items
.apdisk
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
.vscode/launch.json
+1
View File
@@ -6,3 +6,4 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
crypto_box = "0.8.2"
+77 -18
View File
@@ -1,26 +1,85 @@
use std::io::Write;
use std::net::TcpStream;
use crypto_box::{
aead::{Aead, AeadCore, OsRng},
SalsaBox, PublicKey, SecretKey
};
fn main() {
let stream = TcpStream::connect("127.0.0.1:8080");
if stream.is_ok() {
println!("Connected to the server!");
} else {
println!("Couldn't connect to server...");
}
let port: u32 = 7878;
//let stream = TcpStream::connect("172.30.16.1:8080");
//let stream = TcpStream::connect("27.0.0.1:8080");
match TcpStream::connect(format!("localhost:{}", port)) {
Ok(mut stream) => {
println!("Successfully connected to server");
loop {
let mut buffer = String::new();
match std::io::stdin().read_line(&mut buffer) {
Ok(n) => {
if n == 0 {
break;
let bob_init_pub_key = PublicKey::from([
0xe8, 0x98, 0xc, 0x86, 0xe0, 0x32, 0xf1, 0xeb,
0x29, 0x75, 0x5, 0x2e, 0x8d, 0x65, 0xbd, 0xdd,
0x15, 0xc3, 0xb5, 0x96, 0x41, 0x17, 0x4e, 0xc9,
0x67, 0x8a, 0x53, 0x78, 0x9d, 0x92, 0xc7, 0x54,
]);
let (salsa_box, pub_key) = generate_box(bob_init_pub_key.clone());
loop {
let mut buffer = String::new();
match std::io::stdin().read_line(&mut buffer) {
Ok(n) => {
if n == 0 {
break; // Beenden bei EOF
}
//
// Encryption
//
// Get a random nonce to encrypt the message under
let nonce = SalsaBox::generate_nonce(&mut OsRng);
// Message to encrypt
let plaintext = buffer.trim().as_bytes();
// Encrypt the message using the box
let ciphertext = salsa_box.encrypt(&nonce, &plaintext[..]).expect("Fehler");
println!("Sending {0} as {1:?}", buffer.trim(), plaintext);
stream.write(buffer.as_bytes()).unwrap();
//
// Decryption
//
// Decrypt the message, using the same randomly generated nonce
let decrypted_plaintext = salsa_box.decrypt(&nonce, &ciphertext[..]).expect("Fehler");
let dec_plain_plaintext = std::str::from_utf8(&*decrypted_plaintext).expect("Nö");
assert_eq!(&plaintext[..], &decrypted_plaintext[..]);
println!("Sent {0:?} as cypher: {1:?}, decrypted: {2:?}, {3}", plaintext, ciphertext, decrypted_plaintext, dec_plain_plaintext);
}
Err(error) => {
println!("error: {error}");
break;
}
}
println!("{}", buffer);
}
Err(_error) => {
println!("Fehlerhafte Eingabe!");
break;
}
}
Err(e) => {
println!("Failed to connect: {}", e);
}
}
} // the stream is closed here
println!("Terminated.");
}
fn generate_box(partner_public_key: PublicKey) -> (SalsaBox, PublicKey) {
// Generate a random secret key.
// NOTE: The secret key bytes can be accessed by calling `secret_key.as_bytes()`
let own_secret_key = SecretKey::generate(&mut OsRng);
// Get the public key for the secret key we just generated
let own_public_key = own_secret_key.public_key().clone();
// Create a `SalsaBox` by performing Diffie-Hellman key agreement between
// the two keys.
let salsa_box = SalsaBox::new(&partner_public_key, &own_secret_key);
(salsa_box, own_public_key)
}
+26 -4
View File
@@ -1,31 +1,53 @@
use std::{
io::{prelude::*, BufReader},
io::{prelude::*, BufReader, Lines},
net::{TcpListener, TcpStream},
};
use std::io::Lines;
use std::thread::available_parallelism;
use crate::thread_pool::ThreadPool;
mod thread_pool;
fn main() {
// start server on localhost (for remote access use: 0.0.0.0)
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
// create thread pool (size = no. of cpu cores)
let pool = ThreadPool::new(available_parallelism().unwrap().get());
// handling function for incoming requests
for stream in listener.incoming() {
let stream = stream.unwrap();
handle_connection(stream);
// pass request to thread pool
pool.execute(|| {
handle_connection(stream);
});
}
println!("Shutting down.");
}
fn handle_connection(mut stream: TcpStream) {
// clone TcpStream for simultaneous receiving and sending
let mut stream2: TcpStream = stream.try_clone().unwrap();
// initialize reading buffer (for better performance!)
let buf_reader: BufReader<&mut TcpStream> = BufReader::new(&mut stream);
// request: read received text line by line (continuous until connection closed)
let request: Lines<BufReader<&mut TcpStream>> = buf_reader.lines();
println!("Request: {:#?}", request);
// processing function for every text line received by request (terminates when conn closed)
for elem in request
{
// store received line in variable s
let s = elem.unwrap();
println!("{:?}", s);
stream2.write(s.as_bytes()).unwrap();
// send received line back to sender (append LF)
stream2.write_all(s.as_bytes()).unwrap();
stream2.write_all(b"\n").unwrap();
}
}
+116
View File
@@ -0,0 +1,116 @@
use std::{
sync::{mpsc, Arc, Mutex},
thread
};
pub struct ThreadPool {
workers: Vec<Worker>,
sender: Option<mpsc::Sender<Job>>,
}
// Box: pointer for heap allocation (smart pointer); dyn: unknown type to compile time
type Job = Box<dyn FnOnce() + Send + 'static>;
impl ThreadPool {
/// Create a new ThreadPool.
///
/// The size is the number of threads in the pool.
///
/// # Panics
///
/// The `new` function will panic if the size is zero.
pub fn new(size: usize) -> ThreadPool {
assert!(size > 0);
// create asynchronous channel with sender/receiver pair (for jobs!)
let (sender, receiver) = mpsc::channel();
// protect receiver with thread-safe shared (Arc) mutex to avoid multiple access
let receiver = Arc::new(Mutex::new(receiver));
// pre(!)allocate space for workers
let mut workers = Vec::with_capacity(size);
// initialize all workers...
for id in 0..size {
// create worker with unique id and pointer to the shared mutex
workers.push(Worker::new(id, Arc::clone(&receiver)));
}
// set thread pool variables
ThreadPool {
workers,
// Some --> enum variant (Option): indicates that sender may not exist (=be null)
sender: Some(sender),
}
}
pub fn execute<F>(&self, f: F)
where
// FnOnce() --> only callable once; Send --> transfer to another thread; 'static --> lifetime
F: FnOnce() + Send + 'static,
{
let job = Box::new(f);
// commit job to sender object --> pass to threads for execution
self.sender.as_ref().unwrap().send(job).unwrap();
}
}
impl Drop for ThreadPool {
fn drop(&mut self) {
// drop sender first
drop(self.sender.take());
// then drop workers
for worker in &mut self.workers {
println!("Shutting down worker {}", worker.id);
// join worker thread
if let Some(thread) = worker.thread.take() {
thread.join().unwrap();
}
}
}
}
struct Worker {
id: usize,
thread: Option<thread::JoinHandle<()>>,
}
impl Worker {
/// Create a new Worker..
///
/// The id is a unique identifier.
/// The receiver is a shared pointer to a receiver protected by Mutex.
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
// spawn thread and enter infinite loop
let thread = thread::spawn(move || loop {
// lock mutex and wait for job
let message = receiver.lock().unwrap().recv();
match message {
// normal operation --> execute job
Ok(job) => {
println!("Worker {id} got a job; executing.");
job();
}
// exit gracefully when pool is closed --> recv will return error then
Err(_) => {
println!("Worker {id} disconnected; shutting down.");
break;
}
}
});
Worker {
id,
thread: Some(thread),
}
}
}