2 Commits

Author SHA1 Message Date
6ac06ccfe5 wip registering ip addresses 2025-12-18 00:34:57 +01:00
e902070c82 wip structures and message signature 2025-12-17 14:09:51 +01:00
5 changed files with 284 additions and 54 deletions

View File

@@ -1,8 +1,16 @@
use crate::messages_structure::HandshakeMessage;
use p256::ecdsa::{
Signature, SigningKey, VerifyingKey,
signature::{Signer, Verifier},
};
use rand_core::OsRng;
use sha2::{Digest, Sha256};
pub enum MathError {
DivisionByZero,
NonPositiveLogarithm,
NegativeSquareRoot,
}
///
/// contains the ecdsa private key, the ecdsa public key and the username
@@ -40,16 +48,61 @@ pub fn formatPubKey(crypto_pair: CryptographicSignature) -> String {
hex::encode(pubkey_bytes)
}
pub fn sign_message(crypto_pair: CryptographicSignature, message: Vec<u8>) -> Vec<u8> {
let length_bytes: [u8; 2] = message[5..7]
.try_into()
.expect("slice with incorrect length");
let msg_length = u16::from_be_bytes(length_bytes);
println!("{}", msg_length);
let digest = Sha256::digest(&message[..8 + msg_length as usize]);
let signature = crypto_pair.priv_key.sign_prehash_recoverable(&digest);
let message_length = 12 + msg_length as usize + 32;
let mut signed_message = Vec::with_capacity(message_length);
println!("{}", message_length);
signed_message.extend_from_slice(&message[..8 + msg_length as usize]);
signed_message.pop();
println!("signed_tmp:{:?}", signed_message);
match signature {
Ok(signature) => {
//println!("Signature: {:?}", signature);
let r = signature.0.r();
let r_bytes = r.to_bytes(); // Returns a GenericArray/bytes object
signed_message.extend_from_slice(&r_bytes[..32]);
println!("signed:{:?}", signed_message);
println!("rbytes:{:?}", &r_bytes[..32]);
signed_message
}
Err(e) => {
panic!("error");
}
}
}
#[cfg(test)]
mod tests {
// Note this useful idiom: importing names from outer (for mod tests) scope.
use super::*;
#[test]
/*#[test]
fn creating_cryptographic_signature() {
let username = String::from("quoicoubeh");
let crypto_pair = CryptographicSignature::new(username);
let formatted_pubkey =formatPubKey(crypto_pair);
println!("pubkey : {}",formatted_pubkey);
}
}*/
/*#[test]
fn signing_message() {
let username = String::from("quoicoubeh");
let crypto_pair = CryptographicSignature::new(username);
let username_b = String::from("quoicoubeh");
let handshake = HandshakeMessage::hello(0, 12, username_b);
let ser = handshake.serialize();
let signed_message = sign_message(crypto_pair, ser);
println!("unsigned_message: {:?}", ser);
println!("signed_message: {:?}", signed_message);
}*/
}

View File

View File

@@ -1,50 +1,174 @@
struct UDPMessage {
id: [u8; 4],
pub struct UDPMessage {
id: u32,
msg_type: u8,
length: [u8; 2],
length: u16,
body: [u8; 985],
signature: [u8; 32],
}
struct HandshakeMessage {
id: [u8; 4],
pub struct HandshakeMessage {
id: u32,
msg_type: u8,
length: [u8; 2],
extensions: [u8; 4],
name: [u8; 981],
signature: [u8; 32],
length: u16,
extensions: u32,
name: Vec<u8>,
signature: Vec<u8>,
}
impl UDPMessage {
pub fn ping(id: i32) -> UDPMessage {
UDPMessage { id: id.to_ne_bytes(), msg_type: 0, length: [0; 2], body: [0; 985], signature: [0; 32]}
}
pub fn error(id: i32) -> UDPMessage {
UDPMessage { id: id.to_ne_bytes(), msg_type: 129, length: [0; 2], body: [0; 985], signature: [0; 32]}
}
pub fn hello(id: i32, length: i16, username: String) -> HandshakeMessage {
let username_bytes = username.as_bytes();
let mut body: [u8; 981] = [0; 981];
let length_to_copy = username_bytes.len().min(981);
body[..length_to_copy].copy_from_slice(&username_bytes[..length_to_copy]);
HandshakeMessage {id: id.to_ne_bytes(), msg_type: 1, length: length.to_ne_bytes(), extensions: [0;4], name: body, signature: [0;32]}
}
pub fn helloReply(id: i32, length: i16, username: String) -> HandshakeMessage {
let username_bytes = username.as_bytes();
let mut body: [u8; 981] = [0; 981];
let length_to_copy = username_bytes.len().min(981);
body[..length_to_copy].copy_from_slice(&username_bytes[..length_to_copy]);
HandshakeMessage {id: id.to_ne_bytes(), msg_type: 130, length: length.to_ne_bytes(), extensions: [0;4], name: body, signature: [0;32]}
pub fn ping(id: u32) -> UDPMessage {
UDPMessage {
id: id,
msg_type: 0,
length: 0,
body: [0; 985],
signature: [0; 32],
}
}
pub fn error(id: u32) -> UDPMessage {
UDPMessage {
id: id,
msg_type: 129,
length: 0,
body: [0; 985],
signature: [0; 32],
}
}
pub fn parse(received_message: [u8; 1024]) -> UDPMessage {
let id_bytes: [u8; 4] = received_message[0..4]
.try_into()
.expect("Taille incorrecte");
let length_bytes: [u8; 2] = received_message[5..7]
.try_into()
.expect("Taille incorrecte");
let name_bytes: [u8; 985] = received_message[7..992]
.try_into()
.expect("Taille incorrecte");
let signature_bytes: [u8; 32] = received_message[992..1024]
.try_into()
.expect("Taille incorrecte");
UDPMessage {
id: u32::from_be_bytes(id_bytes),
msg_type: received_message[4],
length: u16::from_be_bytes(length_bytes),
body: name_bytes,
signature: signature_bytes,
}
}
pub fn display(&self) {
println!("ID: {:?}", self.id);
println!("Message Type: {}", self.msg_type);
println!("Length: {:?}", self.length);
let good_length = usize::min(self.length as usize, 985);
println!("name: {:?}", &self.body[..good_length]);
println!("Signature: {:?}", self.signature);
}
}
impl HandshakeMessage {
pub fn display(&self) {
println!("ID: {:?}", self.id);
println!("Message Type: {}", self.msg_type);
println!("Length: {:?}", self.length);
println!("extensions: {:?}", self.extensions);
println!("name: {:?}", &self.name[..(self.length - 4) as usize]);
println!("Signature: {:?}", self.signature);
}
pub fn hello(id: u32, length: u16, username: String) -> HandshakeMessage {
let name_vec = username.trim_end_matches(char::from(0)).as_bytes().to_vec();
HandshakeMessage {
id: id,
msg_type: 1,
length: length,
extensions: 0,
name: name_vec,
signature: vec![0; 64],
}
}
pub fn helloReply(id: u32, length: u16, username: String) -> HandshakeMessage {
let name_vec = username.trim_end_matches(char::from(0)).as_bytes().to_vec();
HandshakeMessage {
id: id,
msg_type: 130,
length: length,
extensions: 0,
name: name_vec,
signature: vec![0; 64],
}
}
pub fn serialize(&self) -> Vec<u8> {
let mut out = Vec::with_capacity(4 + 1 + 2 + 4 + self.name.len() + self.signature.len());
// id: u32 little-endian
out.extend_from_slice(&self.id.to_be_bytes());
// msg_type: u8
out.push(self.msg_type);
out.extend_from_slice(&self.length.to_be_bytes());
out.extend_from_slice(&self.extensions.to_be_bytes());
out.extend_from_slice(&self.name);
out.extend_from_slice(&self.signature);
out
}
pub fn parse(received_message: Vec<u8>) -> HandshakeMessage {
let id_bytes: [u8; 4] = received_message[0..4]
.try_into()
.expect("Taille incorrecte");
let length_bytes: [u8; 2] = received_message[5..7]
.try_into()
.expect("Taille incorrecte");
let msg_length = u16::from_be_bytes(length_bytes);
let extensions_bytes: [u8; 4] = received_message[7..11]
.try_into()
.expect("Taille incorrecte");
let name_bytes = &received_message[11..12 + msg_length as usize];
let signature_bytes =
&received_message[12 + msg_length as usize..(13 + msg_length + 32) as usize];
HandshakeMessage {
id: u32::from_be_bytes(id_bytes),
msg_type: received_message[4],
length: u16::from_be_bytes(length_bytes),
extensions: u32::from_be_bytes(extensions_bytes),
name: name_bytes.to_vec(),
signature: signature_bytes.to_vec(),
}
}
}
fn convert_to_u16(bytes: [u8; 2]) -> u16 {
((bytes[0] as u16) << 8) | (bytes[1] as u16)
}
#[cfg(test)]
mod tests {
// Note this useful idiom: importing names from outer (for mod tests) scope.
use super::*;
/*#[tokio::test]
async fn creating_cryptographic_signature() {
let username = String::from("charlie_kirk");
let handshake = HandshakeMessage::hello(0, 12, username);
handshake.display();
}*/
/*#[tokio::test]
async fn parse_handshakemessage() {
let username = String::from("charlie_kirk");
let handshake = HandshakeMessage::hello(0, 12, username);
let ser = handshake.serialize();
let parsed = HandshakeMessage::parse(ser);
handshake.display();
parsed.display();
}*/
}

View File

@@ -1,37 +1,75 @@
use crate::cryptographic_signature::{CryptographicSignature, formatPubKey};
use bytes::Bytes;
use crate::cryptographic_signature::{CryptographicSignature, formatPubKey, sign_message};
use crate::messages_structure::{HandshakeMessage, UDPMessage};
use std::net::UdpSocket;
///
/// Registration with the server happens in two steps: first, the client
/// sends its cryptographic signature to the server using a PUT request over the HTTP API.
async fn register_with_the_server(crypto_pair: CryptographicSignature) -> Result<(), reqwest::Error>{
async fn register_with_the_server(
crypto_pair: CryptographicSignature,
) -> Result<(), reqwest::Error> {
let client = reqwest::Client::new();
let uri = format!("https://jch.irif.fr:8443/peers/{}/key", crypto_pair.username);
let uri = format!(
"https://jch.irif.fr:8443/peers/{}/key",
crypto_pair.username
);
let encoded_point = crypto_pair.pub_key.to_encoded_point(false);
let pubkey_bytes = encoded_point.as_ref().to_vec();
let pubkey_bytes_minus = pubkey_bytes[1..].to_vec();
// In order to register with the server, a peer ϕ makes a PUT request to the URL /peers/ϕ/key with its 64-byte public key in the body
let res = client.put(uri)
.body(pubkey_bytes_minus)
.send()
.await?;
let res = client.put(uri).body(pubkey_bytes_minus).send().await?;
if res.status().is_success() {
println!("Successfully registered with the server.");
} else {
eprintln!("Failed to register with the server. Status: {}", res.status());
eprintln!(
"Failed to register with the server. Status: {}",
res.status()
);
let str = hex::encode(res.bytes().await?);
eprintln!("erreur : {}", str);
}
println!("register ip adresses");
register_ip_addresses(crypto_pair);
Ok(())
}
async fn get_socket_address(username: String) -> Result<Bytes, reqwest::Error> {
let client = reqwest::Client::new();
let uri = format!("https://jch.irif.fr:8443/peers/{}/addresses", username);
let res = client.get(uri).send().await?;
if res.status().is_success() {
println!("Successfully retreived the addresses.");
} else {
eprintln!(
"Failed to register with the server. Status: {}",
res.status()
);
}
let body: Bytes = res.bytes().await?;
Ok(body)
}
/// It then
/// registers each of its IP addresses by sending a Hello request to the server.
/// After the client sends a Hello request to the server, the server will verify that the client is able
/// to receive requests by sending a Hello request to the client. If the client doesnt reply to the Hello
/// request with a properly signed message, its address will not be published by the server.
fn register_ip_addresses(crypto_pair: CryptographicSignature) {
let socket = UdpSocket::bind("127.0.0.1:4242");
//TODO
let socket = UdpSocket::bind("0.0.0.0:0").expect("bind failed");
let username_size = crypto_pair.username.len();
let hello_handshake =
HandshakeMessage::hello(545, username_size as u16 + 4, crypto_pair.username.clone());
//HandshakeMessage::display(&hello_handshake);
let hello_handshake_serialized = hello_handshake.serialize();
let message_signed = sign_message(crypto_pair, hello_handshake_serialized.to_vec());
socket
.send_to(&message_signed, "81.194.30.229:8443")
.expect("send failed");
let mut buf = [0u8; 1024];
socket.recv_from(&mut buf).expect("receive failed");
let hello_handshake_received = UDPMessage::parse(buf);
hello_handshake_received.display();
}
#[cfg(test)]
@@ -40,11 +78,24 @@ mod tests {
use super::*;
#[tokio::test]
async fn creating_cryptographic_signature() {
let username = String::from("charlie_kirk");
async fn registering_with_server() {
let username = String::from("gamemixtreize");
let crypto_pair = CryptographicSignature::new(username);
if let Err(e) = register_with_the_server(crypto_pair).await {
eprintln!("Error during registration: {}", e);
}
}
/*#[tokio::test]
async fn retreive_socket_addr() {
let username = String::from("ipjkndqfshjldfsjlbsdfjhhj");
match get_socket_address(username).await {
Ok(body) => {
println!("{:?}",body);
}
Err(e) => {
eprintln!("Erreur HTTP: {}", e);
}
}
}*/
}

View File

@@ -31,3 +31,5 @@ rechercher les fichiers d'un pair
telechargement des fichiers
choisir un dossier à partager
se deconnecter du réseau
2 channels -> un pour envoyer et un pour recevoir