use std::net::SocketAddr;
use std::sync::Arc;
use rustls::pki_types::CertificateDer;
use tokio_rustls::server::TlsStream as ServerTlsStream;
use tokio_rustls::client::TlsStream as ClientTlsStream;
use tokio::net::TcpStream;
use crate::error::Result;
use crate::secure::credentials::{CredentialBundle, CredentialMode};
#[derive(Debug, Clone)]
pub struct Identity {
pub label: String,
pub bytes: Vec<u8>,
}
impl Identity {
pub fn new(label: impl Into<String>, bytes: impl Into<Vec<u8>>) -> Self {
Self {
label: label.into(),
bytes: bytes.into(),
}
}
pub fn dht_key(&self) -> [u8; 20] {
use sha1::{Digest, Sha1};
let digest = Sha1::digest(&self.bytes);
let mut out = [0u8; 20];
out.copy_from_slice(&digest);
out
}
}
#[derive(Debug, Clone)]
pub struct HandshakeOffer {
pub payload: Vec<u8>,
}
#[derive(Debug, Clone)]
pub struct Approval {
pub peer_label: String,
pub notes: Vec<u8>,
}
#[derive(Debug, Clone)]
pub struct RatchetContext {
pub local_identity: Identity,
pub peer_addr: SocketAddr,
pub peer_offer: Vec<u8>,
pub network_dht_key: [u8; 20],
pub peer_certificate_der: Vec<Vec<u8>>,
}
pub struct Handoff {
pub peer_addr: SocketAddr,
pub peer_label: String,
pub local_identity: Identity,
pub approval: Approval,
pub credentials: CredentialBundle,
pub transport: SecureTransport,
}
#[derive(Debug, Clone)]
pub struct HandoffNotice {
pub peer_addr: SocketAddr,
pub peer_label: String,
pub local_identity_label: String,
}
impl Handoff {
pub fn notice(&self) -> HandoffNotice {
HandoffNotice {
peer_addr: self.peer_addr,
peer_label: self.peer_label.clone(),
local_identity_label: self.local_identity.label.clone(),
}
}
}
pub enum SecureTransport {
Client(ClientTlsStream<TcpStream>),
Server(ServerTlsStream<TcpStream>),
}
impl SecureTransport {
pub fn into_client(self) -> Option<ClientTlsStream<TcpStream>> {
match self {
Self::Client(s) => Some(s),
Self::Server(_) => None,
}
}
pub fn into_server(self) -> Option<ServerTlsStream<TcpStream>> {
match self {
Self::Server(s) => Some(s),
Self::Client(_) => None,
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct SessionBroken {
pub peer_addr: SocketAddr,
pub prefer_addr_only: bool,
}
pub trait SecurePolicy: Send + Sync {
fn identity(&self) -> Identity;
fn network_dht_key(&self) -> [u8; 20] {
self.identity().dht_key()
}
fn handshake_offer(&self) -> Result<HandshakeOffer>;
fn approve_peer(
&self,
peer_offer: &HandshakeOffer,
peer_certs: &[CertificateDer<'static>],
) -> Result<Approval>;
fn ratchet(&self, _ctx: &RatchetContext) -> Result<()> {
Ok(())
}
fn credential_mode(&self) -> CredentialMode {
CredentialMode::SealedChannel
}
fn local_credentials(&self) -> Result<CredentialBundle> {
Ok(CredentialBundle::empty())
}
fn accept_remote_credentials(&self, remote: &[u8]) -> Result<CredentialBundle> {
Ok(CredentialBundle::new(remote.to_vec()))
}
fn on_handoff(&self, _handoff: &Handoff) {}
}
pub type PolicyHandle = Arc<dyn SecurePolicy>;