tunnet_core/direct/
auth.rs1use std::collections::{HashMap, HashSet};
11use std::sync::Arc;
12
13use anyhow::Context;
14use hmac::{Hmac, KeyInit, Mac};
15use iroh::EndpointAddr;
16use iroh::endpoint::{
17 AfterHandshakeOutcome, BeforeConnectOutcome, Connection, EndpointHooks, RecvStream, SendStream,
18 Side,
19};
20use parking_lot::Mutex;
21use sha2::Sha256;
22use uuid::Uuid;
23
24use crate::acl::AclEngine;
25
26pub const AUTH_ALPN: &[u8] = b"tunnet/direct-auth/2";
28
29type HmacSha256 = Hmac<Sha256>;
30
31#[derive(Clone, Default)]
33pub struct AuthCache {
34 inner: Arc<Mutex<HashMap<String, HashSet<Uuid>>>>,
36}
37
38impl AuthCache {
39 pub fn new() -> Self {
40 Self::default()
41 }
42
43 pub fn insert(&self, endpoint_hex: impl Into<String>, network_id: Uuid) {
44 self.inner
45 .lock()
46 .entry(endpoint_hex.into())
47 .or_default()
48 .insert(network_id);
49 }
50
51 pub fn contains(&self, endpoint_hex: &str) -> bool {
53 self.inner
54 .lock()
55 .get(endpoint_hex)
56 .is_some_and(|s| !s.is_empty())
57 }
58
59 pub fn contains_network(&self, endpoint_hex: &str, network_id: Uuid) -> bool {
60 self.inner
61 .lock()
62 .get(endpoint_hex)
63 .is_some_and(|s| s.contains(&network_id))
64 }
65
66 pub fn networks_for(&self, endpoint_hex: &str) -> Vec<Uuid> {
67 self.inner
68 .lock()
69 .get(endpoint_hex)
70 .map(|s| s.iter().copied().collect())
71 .unwrap_or_default()
72 }
73
74 pub fn remove(&self, endpoint_hex: &str) {
75 self.inner.lock().remove(endpoint_hex);
76 }
77
78 pub fn remove_network(&self, endpoint_hex: &str, network_id: Uuid) {
79 let mut g = self.inner.lock();
80 if let Some(set) = g.get_mut(endpoint_hex) {
81 set.remove(&network_id);
82 if set.is_empty() {
83 g.remove(endpoint_hex);
84 }
85 }
86 }
87}
88
89#[derive(Clone)]
91pub struct DirectAuthHook {
92 acl: AclEngine,
93 auth: AuthCache,
94}
95
96impl DirectAuthHook {
97 pub fn new(acl: AclEngine, auth: AuthCache) -> Self {
98 Self { acl, auth }
99 }
100}
101
102impl std::fmt::Debug for DirectAuthHook {
103 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104 f.debug_struct("DirectAuthHook").finish_non_exhaustive()
105 }
106}
107
108impl EndpointHooks for DirectAuthHook {
109 async fn before_connect<'a>(
110 &'a self,
111 remote_addr: &'a EndpointAddr,
112 alpn: &'a [u8],
113 ) -> BeforeConnectOutcome {
114 let peer_hex = format!("{}", remote_addr.id);
115 if alpn == AUTH_ALPN {
116 return BeforeConnectOutcome::Accept;
117 }
118 if self.auth.contains(&peer_hex) || self.acl.allow_outbound_peer(&peer_hex) {
119 BeforeConnectOutcome::Accept
120 } else {
121 tracing::warn!(%peer_hex, "outbound connect blocked (not authenticated)");
122 BeforeConnectOutcome::Reject
123 }
124 }
125
126 async fn after_handshake<'a>(&'a self, conn: &'a Connection) -> AfterHandshakeOutcome {
127 if conn.side() != Side::Server {
128 return AfterHandshakeOutcome::Accept;
129 }
130 let peer_hex = format!("{}", conn.remote_id());
131 let alpn = conn.alpn();
132 if alpn == AUTH_ALPN {
133 return AfterHandshakeOutcome::Accept;
134 }
135 if self.auth.contains(&peer_hex) || self.acl.allow_inbound_peer(&peer_hex) {
136 AfterHandshakeOutcome::Accept
137 } else {
138 tracing::warn!(%peer_hex, "inbound connection blocked (not authenticated)");
139 AfterHandshakeOutcome::Reject {
140 error_code: 401u32.into(),
141 reason: b"auth_required".to_vec(),
142 }
143 }
144 }
145}
146
147fn compute_proof(
148 secret_hex: &str,
149 local_hex: &str,
150 remote_hex: &str,
151 network_id: Uuid,
152 nonce: &[u8],
153) -> Vec<u8> {
154 let secret = hex::decode(secret_hex).unwrap_or_else(|_| secret_hex.as_bytes().to_vec());
155 let mut mac = HmacSha256::new_from_slice(&secret).expect("hmac accepts any key length");
156 mac.update(local_hex.as_bytes());
157 mac.update(b"|");
158 mac.update(remote_hex.as_bytes());
159 mac.update(b"|");
160 mac.update(network_id.as_bytes());
161 mac.update(b"|");
162 mac.update(nonce);
163 mac.finalize().into_bytes().to_vec()
164}
165
166async fn write_frame(send: &mut SendStream, data: &[u8]) -> anyhow::Result<()> {
167 let len = (data.len() as u32).to_be_bytes();
168 send.write_all(&len).await?;
169 send.write_all(data).await?;
170 Ok(())
171}
172
173async fn read_frame(recv: &mut RecvStream, max: usize) -> anyhow::Result<Vec<u8>> {
174 let mut len_buf = [0u8; 4];
175 recv.read_exact(&mut len_buf).await?;
176 let len = u32::from_be_bytes(len_buf) as usize;
177 if len > max {
178 anyhow::bail!("auth frame too large: {len}");
179 }
180 let mut buf = vec![0u8; len];
181 if len > 0 {
182 recv.read_exact(&mut buf).await?;
183 }
184 Ok(buf)
185}
186
187fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
188 if a.len() != b.len() {
189 return false;
190 }
191 let mut diff = 0u8;
192 for (x, y) in a.iter().zip(b.iter()) {
193 diff |= x ^ y;
194 }
195 diff == 0
196}
197
198pub async fn run_psk_handshake_client(
200 conn: &Connection,
201 network_id: Uuid,
202 network_secret_hex: &str,
203 local_endpoint_hex: &str,
204) -> anyhow::Result<()> {
205 let (mut send, mut recv) = conn.open_bi().await.context("open auth stream")?;
206 let remote_hex = format!("{}", conn.remote_id());
207 let nonce: [u8; 32] = rand::random();
208 write_frame(&mut send, local_endpoint_hex.as_bytes()).await?;
209 write_frame(&mut send, network_id.as_bytes()).await?;
210 write_frame(&mut send, &nonce).await?;
211 let proof = compute_proof(
212 network_secret_hex,
213 local_endpoint_hex,
214 &remote_hex,
215 network_id,
216 &nonce,
217 );
218 write_frame(&mut send, &proof).await?;
219 let resp = read_frame(&mut recv, 64).await?;
220 if resp.as_slice() != b"ok" {
221 anyhow::bail!("PSK auth rejected by peer");
222 }
223 Ok(())
224}
225
226pub type SecretResolver = Arc<dyn Fn(Uuid) -> Option<String> + Send + Sync>;
228
229pub async fn run_psk_handshake_server(
231 conn: &Connection,
232 resolve_secret: SecretResolver,
233 self_endpoint_hex: &str,
234 auth: &AuthCache,
235) -> anyhow::Result<(String, Uuid)> {
236 let (mut send, mut recv) = conn.accept_bi().await.context("accept auth stream")?;
237 let peer_claimed =
238 String::from_utf8(read_frame(&mut recv, 128).await?).context("peer id utf8")?;
239 let network_id_bytes = read_frame(&mut recv, 16).await?;
240 if network_id_bytes.len() != 16 {
241 write_frame(&mut send, b"no").await.ok();
242 anyhow::bail!("invalid network_id frame");
243 }
244 let mut uuid_bytes = [0u8; 16];
245 uuid_bytes.copy_from_slice(&network_id_bytes);
246 let network_id = Uuid::from_bytes(uuid_bytes);
247
248 let nonce = read_frame(&mut recv, 64).await?;
249 let proof = read_frame(&mut recv, 64).await?;
250 let remote_hex = format!("{}", conn.remote_id());
251 if peer_claimed != remote_hex {
252 anyhow::bail!("peer id mismatch in auth handshake");
253 }
254
255 let Some(secret) = resolve_secret(network_id) else {
256 write_frame(&mut send, b"no").await.ok();
257 anyhow::bail!("unknown network_id in PSK handshake");
258 };
259
260 let expected = compute_proof(
261 &secret,
262 &peer_claimed,
263 self_endpoint_hex,
264 network_id,
265 &nonce,
266 );
267 if !constant_time_eq(&expected, &proof) {
268 write_frame(&mut send, b"no").await.ok();
269 anyhow::bail!("invalid PSK proof");
270 }
271 write_frame(&mut send, b"ok").await?;
272 auth.insert(peer_claimed.clone(), network_id);
273 Ok((peer_claimed, network_id))
274}