This commit is contained in:
2025-02-18 16:21:47 +08:00
commit 4af69eb3dd
7 changed files with 2599 additions and 0 deletions

2
.env.sample Normal file
View File

@@ -0,0 +1,2 @@
PORT=8001
USER_ID=1

3
.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
/target
database*.json
.env

1764
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

17
Cargo.toml Normal file
View File

@@ -0,0 +1,17 @@
[package]
name = "dske_poc_client"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
actix-web = "4.3.1"
dotenv = "0.15.0"
reqwest = { version = "0.11.17", features = ["json"] }
serde = { version = "1.0.160", features = ["derive"] }
serde_json = "1.0.96"
tokio = { version = "1.28.0", features = ["full"] }
async-trait = "0.1.68"
actix-cors = "0.6.4"
rand = "0.8.5"

419
README.md Normal file
View File

@@ -0,0 +1,419 @@
# DSKE POC (Client)
## Introduction
This is a proof of concept for the DSKE system. The main goal is to demonstrate the algorithm in DSKE. There are a few assumptions and limitations in this proof-of-concept project:
1. This is not a working protocol, this project is just to prove the algorithm concept.
2. This project is demonstrating a simple DSKE protocol, which means n = k. It is a (n, n) secret sharing scheme.
3. The code assumes that the final key sender chooses all common security hubs with the receiver that they both register.
This project is separated into two parts: the client and the security hub server.
- [client](https://gitea.devchristam.com/devchristam/dske_poc_client)
- [server](https://gitea.devchristam.com/devchristam/dske_poc_server)
You need to host multiple clients and servers to make this proof-of-concept DSKE system work.
## DSKE Main Phases
1. PSKM Generation and Distribution
The security hub's `POST /register_client` endpoint will generate random bits and record the client on the server side. This endpoint will return the generated random bits. The client's `POST /register_securityhub` endpoint will store these random bits so that both the security hub and the client have a copy. Note that the distribution process needs to be done manually because real PSKM distribution is done physically.
2. Peer Identity Establishment
When a client wants to share a key with another client using `POST /make_connection`, the sender client will send a request to the receiver client's `POST /agree_connection` endpoint with a list of security hubs to use in the key exchange. The receiver client will check if both the sender and receiver are registered in those security hubs using the security hub's `POST /user_list` endpoint. This endpoint will display every client ID registered in the security hub, allowing the client to identify common security hubs.
3. Key Agreement
The sender will use the `POST /make_connection` endpoint to exchange keys with the receiver.
1. Share Generation
The proof-of-concept project will use an (n, n) secret sharing scheme in a simple DSKE protocol. For simplicity, the sender will choose all the common security hubs with the receiver.
2. Share Distribution
The sender will send a request to the security hub's `POST /generate_key_instruction` endpoint to generate a key instruction A (sender's random bits) XOR B (receiver's random bits).
3. Key Reconstruction
After the security hub sends a request to the client's `POST /receive_key_instruction` endpoint, the client will calculate A ^ B ^ B to retrieve A in each request and store the calculated A in a key-value pair using the final key hash as the key. The receiver can reconstruct the final key S by executing XOR on every share in the simple DSKE protocol (n, n) secret sharing scheme.
4. Key Validation
The receiver will only reconstruct the final key if the number of received shares equals the total number of shares. The exchange process will abort if the numbers do not match.
## Step-by-Step Setup Guide
This guide will walk you through the steps to set up and run the DSKE POC server and client.
### Steps
#### 1. Clone the Repository
Clone the repository to your local machine using the following commands:
```bash
# Clone the DSKE POC server
git clone https://gitea.devchristam.com/devchristam/dske_poc_server.git
# Clone the DSKE POC client
git clone https://gitea.devchristam.com/devchristam/dske_poc_client.git
```
#### 2. Build the Project
Navigate to the project directory and build the project using Cargo:
```sh
cargo build
```
#### 3. Run the Server and Client
Run the server and client using the following commands. You need to use Tmux or open multiple terminal applications to host multiple servers and clients on the same machine.
For server:
```sh
# The code supports .env for port and security hub ID settings.
# Even if not using the .env file, please copy the .env because missing variables will show a runtime error.
cp .env.sample .env
# set the environment variables in .env if needed
# cargo run -- <port> <security hub id>
# e.g.
cargo run -- 8081 1
cargo run -- 8082 2
cargo run -- 8083 3
```
For client:
```sh
# The code supports .env for port and security hub ID settings.
# Even if not using the .env file, please copy the .env because missing variables will show a runtime error.
cp .env.sample .env
# set the environment variables in .env if needed
# cargo run -- <port> <user id>
# e.g.
cargo run -- 8001 1
cargo run -- 8002 2
```
## 4. Exchange Key
### Steps
All API calls use `content-type: "application/json"`.
#### 1. Register Client in Security Hub
Use the security hub endpoint `POST /register_client` to record the client.
- Example (record a client running on `cargo run -- 8001 1`):
```json
{
"id": 1,
"username": "alice",
"url": "http://localhost:8001"
}
```
- This request will return a payload. You need to copy the `random_bits` array for step 2:
```json
{
"id": 1,
"username": "alice",
"url": "http://localhost:8001",
"random_bits": [
false,
false,
true,
true,
true,
...
]
}
```
#### 2. Register Security Hub in the Client
Copy the `random_bits` array and input the same content into the client endpoint `POST /register_securityhub`.
- Example (record a security hub running on `cargo run -- 8081 1`):
```json
{
"securityhub_id": 1,
"securityhub_url": "http://localhost:8081",
"random_bits": [
false,
false,
true,
true,
true,
...
]
}
```
After repeating steps 1 and 2, you can create a proof-of-concept DSKE system network. Then the client can exchange keys within the network.
#### 3. Exchange Key
In the client endpoint `POST /make_connection`, you can exchange the final key with another client.
- Example (from client `cargo run -- 8001 1` exchanging key with `cargo run -- 8002 2`):
```json
{
"client_id": 2,
"client_url": "http://localhost:8002",
"keysize": 5
}
```
![screenshot](./Screenshot.png)
## API Documentation
### Server
#### `POST /register_client`
Registers a client in the security hub.
- **Input:**
`content-type: "application/json"`
```json
{
"id": Integer,
"username": String,
"url": String
}
```
Example:
```json
{
"id": 999,
"username": "test",
"url": "http://localhost:8888"
}
```
- **Output:**
```json
{
"id": Integer,
"username": String,
"url": String,
"random_bits": Boolean[]
}
```
Example:
```json
{
"id": 999,
"username": "test",
"url": "http://localhost:8888",
"random_bits": [true, false, true, ...]
}
```
#### `POST /user_list`
Retrieves the list of registered user IDs from the security hub.
- **Input:**
No input required.
- **Output:**
```json
Integer[]
```
Example:
```json
[1, 2, 3, ...]
```
#### `POST /generate_key_instruction`
Generates a key instruction for the key exchange process.
- **Input:**
`content-type: "application/json"`
```json
{
"sender_id": Integer,
"receiver_id": Integer,
"hash": Integer,
"keysize": Integer
}
```
Example:
```json
{
"sender_id": 1,
"receiver_id": 2,
"hash": 12345,
"keysize": 5
}
```
- **Output:**
```json
Boolean[]
```
Example:
```json
[true, false, true, ...]
```
### Client
#### `POST /register_securityhub`
Registers a security hub in the client.
- **Input:**
`content-type: "application/json"`
```json
{
"securityhub_id": Integer,
"securityhub_url": String,
"random_bits": Boolean[]
}
```
Example:
```json
{
"securityhub_id": 1,
"securityhub_url": "http://localhost:8081",
"random_bits": [true, false, true, ...]
}
```
- **Output:**
Null
#### `POST /make_connection`
Initiates a key exchange with another client.
- **Input:**
`content-type: "application/json"`
```json
{
"client_id": Integer,
"client_url": String,
"keysize": Integer
}
```
Example:
```json
{
"client_id": 2,
"client_url": "http://localhost:8002",
"keysize": 5
}
```
- **Output:**
Null
#### `POST /agree_connection`
Agrees to a key exchange initiated by another client. Check the `securityhub_list` are both registered or not.
- **Input:**
`content-type: "application/json"`
```json
{
"client_id": Integer,
"securityhub_list": Integer[],
"keysize": Integer
}
```
Example:
```json
{
"client_id": 1,
"securityhub_list": [1, 2],
"keysize": 5
}
```
- **Output:**
Null
If the exchange cannot process, the API will not return `200 OK`.
#### `POST /receive_key_instruction`
Receives a key instruction from the security hub.
- **Input:**
`content-type: "application/json"`
```json
{
"sender_id": Integer,
"hash": Integer,
"key_instruction": Boolean[],
"total": Integer,
"securityhub_id": Integer
}
```
Example:
```json
{
"sender_id": 1,
"hash": 1234,
"key_instruction": [true, false, ...],
"total": 2,
"securityhub_id": 1
}
```
- **Output:**
Null

BIN
Screenshot.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

394
src/main.rs Normal file
View File

@@ -0,0 +1,394 @@
use actix_cors::Cors;
use actix_web::{ http::header, web, App, HttpServer, Responder, HttpResponse };
use serde::{ Deserialize, Serialize };
use reqwest::Client as HttpClient;
use std::collections::hash_map::DefaultHasher;
use std::sync::Mutex;
use std::collections::HashMap;
use std::fs;
use std::env;
use std::io::Write;
use dotenv::dotenv;
use std::hash::{Hash, Hasher};
#[derive(Serialize, Deserialize, Debug, Clone)]
struct PSKM {
securityhub_id: u64,
securityhub_url: String,
random_bits: Vec<bool>
}
#[derive(Serialize, Deserialize, Debug, Clone)]
struct MakeConnection {
client_id: u64,
client_url: String,
keysize: u64
}
#[derive(Serialize, Deserialize, Debug, Clone)]
struct KeyInstruction{
sender_id: u64,
securityhub_id: u64,
hash: u64,
total: u64,
key_instruction: Vec<bool>
}
#[derive(Serialize, Deserialize, Debug, Clone)]
struct AgreeConnection {
client_id: u64,
securityhub_list: Vec<u64>,
keysize: u64
}
#[derive(Serialize, Deserialize, Debug, Clone)]
struct ReceiveInstruction {
sender_id: u64,
securityhub_id: u64,
calculated: Vec<bool>,
total: u64
}
#[derive(Serialize, Deserialize, Debug, Clone)]
struct Database {
received: HashMap<u64, Vec<ReceiveInstruction>>,
pskm_list: HashMap<u64, PSKM>,
}
impl Database {
fn new() -> Self {
Self {
received: HashMap::new(),
pskm_list: HashMap::new()
}
}
fn get_pskm(&self, id: &u64) -> Option<&PSKM> {
self.pskm_list.get(id)
}
fn insert_pskm(&mut self, pskm: PSKM) {
self.pskm_list.insert(pskm.securityhub_id, pskm);
}
fn insert_received(&mut self, hash: u64,received: ReceiveInstruction) {
let received_list = self.received.entry(hash).or_insert(Vec::new());
received_list.push(received);
}
fn get_received(&self, hash: &u64) -> Option<&Vec<ReceiveInstruction>> {
self.received.get(hash)
}
// remove the first n elements from the random_bits array
fn remove_random_bits(&mut self, id: &u64, n: usize) {
let pskm = self.pskm_list.get_mut(id).unwrap();
pskm.random_bits = pskm.random_bits.split_off(n);
}
fn save_to_file(&self) -> std::io::Result<()> {
let data: String = serde_json::to_string(&self)?;
let args: Vec<String> = env::args().collect();
let file_name = format!("database-{}.json", args.get(2).unwrap_or(&env::var("USER_ID").unwrap()));
let mut file: fs::File = fs::File::create(file_name)?;
file.write_all(data.as_bytes())?;
Ok(())
}
fn load_from_file() -> std::io::Result<Self> {
let args: Vec<String> = env::args().collect();
let file_name = format!("database-{}.json", args.get(2).unwrap_or(&env::var("USER_ID").unwrap()));
let file_content: String = fs::read_to_string(file_name)?;
let db: Database = serde_json::from_str(&file_content)?;
Ok(db)
}
}
struct AppState {
db: Mutex<Database>
}
async fn register_securityhub(app_state: web::Data<AppState>, pskm: web::Json<PSKM>) -> impl Responder {
let mut db: std::sync::MutexGuard<Database> = app_state.db.lock().unwrap();
db.insert_pskm(pskm.into_inner());
let _ = db.save_to_file();
HttpResponse::Ok().finish()
}
async fn make_connection(app_state: web::Data<AppState>, make_connection: web::Json<MakeConnection>) -> impl Responder {
let mut db: std::sync::MutexGuard<Database> = app_state.db.lock().unwrap();
let common_securityhubs = check_common_securityhub(make_connection.client_id).await;
//loop through the common_securityhubs and check if the keysize is bigger than the random_bits array size
for id in common_securityhubs.iter() {
let pskm = db.get_pskm(id).unwrap();
if pskm.random_bits.len() < make_connection.keysize as usize {
return HttpResponse::BadRequest().body("Keysize bigger than random bits array size");
}
}
println!("Common securityhubs: {:?}", common_securityhubs);
// if there is no common securityhub, abort the key exchange process
if common_securityhubs.len() == 0 {
return HttpResponse::BadRequest().body("No common securityhub found");
}
// send request to another client `/agree_connection` with the common_securityhubs list
let client = HttpClient::new();
let res = client.post(&format!("{}/agree_connection", make_connection.client_url))
.json(&AgreeConnection {
client_id: make_connection.client_id,
securityhub_list: common_securityhubs.clone(),
keysize: make_connection.keysize,
})
.send()
.await;
match res {
Ok(response) => {
if response.status().is_client_error() {
return HttpResponse::BadRequest().body("Receiver disagree connection");
}
},
Err(err) => {
println!("Error connecting to receiver: {:?}", err);
return HttpResponse::BadRequest().body("Error connecting to receiver");
}
};
// print the final key by the common_securityhubs
let final_key = generate_final_key(make_connection.keysize, common_securityhubs.clone());
let final_key_string = get_final_key_string(final_key.clone());
println!{"Final key: {}", final_key_string};
// hash the final key
let mut hasher = DefaultHasher::new();
final_key.hash(&mut hasher);
let hashed_value = hasher.finish();
println!("Hashed final key: {:?}", hashed_value);
//send a request to all common_securityhubs `generate_key_instruction`
let args: Vec<String> = env::args().collect();
for id in common_securityhubs.iter() {
let pskm = db.get_pskm(id).unwrap();
let client = HttpClient::new();
let user_id_env = env::var("USER_ID").unwrap();
let user_id: u64 = args.get(2).unwrap_or(&user_id_env).parse().unwrap();
let res = client.post(&format!("{}/generate_key_instruction", pskm.securityhub_url))
.json(&serde_json::json!({
"sender_id": user_id,
"receiver_id": make_connection.client_id,
"hash": hashed_value,
"total": common_securityhubs.len(),
"keysize": make_connection.keysize
}))
.send()
.await;
match res {
Ok(response) => {
println!("Request sent to securityhub {}", id);
// remove random bits after sending the request
db.remove_random_bits(id, make_connection.keysize as usize);
let _ = db.save_to_file();
if response.status().is_client_error() {
println!("securityhub {} error", id);
}
},
Err(err) => {
println!("Error sending request to securityhub {}: {:?}", id, err);
}
}
}
HttpResponse::Ok().finish()
}
fn get_final_key_string(final_key: Vec<bool>) -> std::string::String {
let mut final_key_string: String = String::new();
for bit in final_key {
final_key_string.push_str(if bit { "1" } else { "0" });
}
final_key_string
}
fn generate_final_key(key_size: u64, securityhub_list: Vec<u64>) -> Vec<bool> {
let db: Database = Database::load_from_file().unwrap();
let mut final_key: Vec<bool> = Vec::new();
for i in 0..key_size {
let xor_result = db.pskm_list.iter()
.filter(|(_, pskm)| securityhub_list.contains(&pskm.securityhub_id))
.map(|(_, pskm)| pskm.random_bits[i as usize])
.fold(false, |acc, bit| acc ^ bit);
final_key.push(xor_result);
}
final_key
}
async fn check_common_securityhub(client_id: u64) -> Vec<u64> {
let db: Database = Database::load_from_file().unwrap();
// get every registered securityhub
let pskm_list = db.pskm_list.clone();
// for every securityhub, send a request to the securityhub `/user_list`
// store the securityhub id if the response contains the target client id
let mut found_in: Vec<u64> = Vec::new();
for (id, pskm) in pskm_list {
let client = HttpClient::new();
let res = client.post(&format!("{}/user_list", pskm.securityhub_url))
.send()
.await;
if let Err(err) = res {
println!("Error connecting to securityhub {}: {:?}", id, err);
continue;
}
let res = res.unwrap();
let payload = res.json::<serde_json::Value>().await;
if let Err(err) = payload {
println!("Error parsing JSON: {:?}", err);
continue;
}
let payload = payload.unwrap();
// check if the client id is in the array
for user in payload.as_array().unwrap() {
if user == &client_id {
found_in.push(id);
}
}
}
found_in
}
// process to exchnage key if the input securityhub in securityhub_list are all found in the common securityhub
async fn agree_connection(app_state: web::Data<AppState>, agree_connection: web::Json<AgreeConnection>) -> impl Responder {
let db: std::sync::MutexGuard<Database> = app_state.db.lock().unwrap();
let common_securityhubs = check_common_securityhub(agree_connection.client_id).await;
// get every registered securityhub
let pskm_list = db.pskm_list.clone();
// check agree_connection.securityhub_list, if the id is not in the common_list, or the keysize is bigger than the random_bits array size, return an error
for id in agree_connection.securityhub_list.iter() {
if !common_securityhubs.contains(id) {
return HttpResponse::BadRequest().body("Securityhub not in common list");
}
// check remaining random bits
let pskm = pskm_list.get(id).unwrap();
if pskm.random_bits.len() < agree_connection.keysize as usize {
return HttpResponse::BadRequest().body("Keysize bigger than random bits array size");
}
}
HttpResponse::Ok().finish()
}
async fn receive_key_instruction(app_state: web::Data<AppState>, key_instruction: web::Json<KeyInstruction>) -> impl Responder {
let mut db: std::sync::MutexGuard<Database> = app_state.db.lock().unwrap();
// println!("Key instruction received: {:?}", key_instruction);
// calculate A ^ B ^ B
let mut calculated = Vec::new();
let securiyhub_random_bits = db.get_pskm(&key_instruction.securityhub_id).unwrap().random_bits.clone();
for (index, bit) in key_instruction.key_instruction.iter().enumerate() {
calculated.push(bit ^ securiyhub_random_bits.get(index).unwrap());
}
// println!("Calculated random bit A: {:?}", calculated);
// store the calculated key in the db received
db.insert_received(key_instruction.hash, ReceiveInstruction {
sender_id: key_instruction.sender_id,
securityhub_id: key_instruction.securityhub_id,
calculated,
total: key_instruction.total
});
// remove the used random bits
db.remove_random_bits(&key_instruction.securityhub_id, key_instruction.key_instruction.len());
// if the received list is equal to the total, calculate the final key
let received_list = db.get_received(&key_instruction.hash).unwrap();
if received_list.len() == key_instruction.total as usize {
let final_key: Vec<bool> = (0..key_instruction.key_instruction.len())
.map(|i| {
received_list.iter()
.map(|received| received.calculated[i])
.fold(false, |acc, bit| acc ^ bit)
})
.collect();
// remove the received list from the db
db.received.remove(&key_instruction.hash);
let final_key_string = get_final_key_string(final_key.clone());
println!{"Received final key: {}", final_key_string};
}
else if received_list.len() > key_instruction.total as usize {
return HttpResponse::BadRequest().body("Received list is bigger than the total");
}
let _ = db.save_to_file();
HttpResponse::Ok().finish()
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
dotenv().ok();
let args: Vec<String> = env::args().collect();
let db: Database = match Database::load_from_file() {
Ok(db) => db,
Err(_) => Database::new()
};
let data: web::Data<AppState> = web::Data::new(AppState {
db: Mutex::new(db)
});
// if args[1] is set, use the port from the args
// else use the port from the .env
let port_env = env::var("PORT").unwrap();
let port = args.get(1).unwrap_or(&port_env);
println!("Starting client on port {}", port);
// if args[2] is set, use the user id from the args
// else use the user id from the .env
let client_id_env = env::var("USER_ID").unwrap();
let client_id = args.get(2).unwrap_or(&client_id_env);
println!("Client ID: {}", client_id);
HttpServer::new(move || {
App::new()
.wrap(
Cors::permissive()
.allowed_origin_fn(|origin, _req_head| {
origin.as_bytes().starts_with(b"http://localhost") || origin == "null"
})
.allowed_methods(vec!["GET", "POST", "PUT", "DELETE"])
.allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT])
.allowed_header(header::CONTENT_TYPE)
.supports_credentials()
.max_age(3600)
)
.app_data(data.clone())
.route("/register_securityhub", web::post().to(register_securityhub))
.route("/make_connection", web::post().to(make_connection))
.route("/agree_connection", web::post().to(agree_connection))
.route("/receive_key_instruction", web::post().to(receive_key_instruction))
})
.bind(format!("127.0.0.1:{}", port))?
.run()
.await
}