slither 0.3.0

Encrypted peer-to-peer UDP transport: reliable messages, streams and datagrams, authenticated by raw public keys - no certificates, no TLS. WireGuard-shaped handshake, QUIC-shaped frames.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//! §6.2's staged accept — the [`Intro`], [`Claimed`] and [`Proven`] types.
//!
//! The reader-facing account of the ladder — what each rung costs, why
//! dropping one *is* the rejection, and why a staged object is not a handle
//! — is in [the shell module docs](super).
//!
//! What is here is the round-trip mechanics: each verb sends a [`Command`]
//! and awaits a [`oneshot`] reply, because §6.2 requires the DH cost to land
//! on the driver task, and each stage consumes its predecessor so a parked
//! chain cannot be forked.

use std::net::SocketAddr;

use tokio::sync::oneshot;

use crate::core::{IntroId, Timestamp};
use crate::error::{AcceptError, AuthError, IntroError};
use crate::identity::{Identity, PublicKeyOf};

use super::connection::Connection;
use super::shared::{Command, Shell};

/// A parked introduction — §6.1's **stage 0**, at **0 DH**.
///
/// Nothing has been spent on it: it is msg1's bytes plus the address they
/// came from, and it has passed §3.1's length gate and mac1 and nothing
/// else. Drop is a silent reject.
///
/// **S8** — `#[must_use]` because dropping this *is* the reject, and a
/// silent one. The attribute is S8's acceptance criterion verbatim —
/// *"it is `#[must_use]` and not `Clone`, so a parked chain cannot be
/// forked"* — and it guards the one mistake this type's own docs describe:
/// an unused staged object is not a no-op, it declines an inbound peer.
#[must_use = "dropping a staged accept object silently rejects the inbound \
              connection; call read_identity(), or drop it deliberately"]
pub struct Intro<I: Identity> {
    shell: Shell<I>,
    id: IntroId,
    /// The value at hand-over, used only if the parked entry is gone.
    source: SocketAddr,
    sender_index: u32,
    consumed: bool,
}

impl<I: Identity> Intro<I> {
    pub(crate) fn new(shell: Shell<I>, id: IntroId, source: SocketAddr, sender_index: u32) -> Self {
        Self {
            shell,
            id,
            source,
            sender_index,
            consumed: false,
        }
    }

    /// Where this initiation came from.
    ///
    /// **Attacker-chosen, at 0 DH, with no return-routability proof — do
    /// not key durable state on it.** §6.1 forbids that in terms, and it
    /// names **three** quantities, not one: *"Nothing durable may be keyed
    /// on the claimed static, the source address, or `sender_index` — no
    /// map insertion, no rate-limit bucket, no unbounded logging."* This is
    /// documentation obligation #2 (see the [crate docs](crate)) at the
    /// rung *below* the claimed static, and the address is the **cheaper**
    /// of the two to abuse, not the safer: a claimed static costs an
    /// attacker one DH and requires knowing some real public key, while a
    /// source address costs nothing and can name any host on the internet.
    /// Nothing has answered from this address at stage 0 — the ladder's
    /// first reply is msg2, which `accept()` sends — so a spoofed source is
    /// free, and a denylist or a rate-limit bucket keyed here bans whoever
    /// the attacker wrote in the packet. Under the flood §6.3 describes,
    /// that is precisely the reflex to expect.
    ///
    /// Use it to **route, log at bounded volume, and decide** — an address
    /// is legitimate input to an authorisation policy. Never use it to
    /// punish, and never let it grow a map.
    ///
    /// Read **live** from the parked entry (ruling 71): §6.3 requires a
    /// refreshed entry's accessors to reflect the newest bytes at call
    /// time. For the source address that happens to be invariant under
    /// replacement — the address *is* §6.3's dedup key — but reading it
    /// live is what makes that a property of the code rather than of a
    /// comment. If the entry has expired since hand-over, the value it had
    /// then is returned; an expired introduction still came from somewhere.
    pub fn source(&self) -> SocketAddr {
        self.shell
            .state
            .borrow()
            .endpoint
            .intro_source(self.id)
            .unwrap_or(self.source)
    }

    /// The `sender_index` on the initiation currently parked here.
    ///
    /// **The third of §6.1's three attacker-chosen quantities — do not key
    /// durable state on it either**, and see [`source`](Self::source) for
    /// the rule and the reason. This one carries its own trap: §5.5 mints a
    /// fresh random index on **every retransmit**, so it is not stable even
    /// for a genuine peer, and a map keyed on it grows one entry per
    /// retransmit of one honest initiation.
    ///
    /// Read **live**, and here it is load-bearing (ruling 71): §5.5 mints a
    /// **new random index on every retransmit**, and §6.3's dedup replaces
    /// a same-source entry *without re-surfacing it*, so a value cached
    /// when this handle was created is no longer the one on the wire the
    /// moment the peer retransmits.
    pub fn sender_index(&self) -> u32 {
        self.shell
            .state
            .borrow()
            .endpoint
            .intro_sender_index(self.id)
            .unwrap_or(self.sender_index)
    }

    /// §6.1's stage 1 — **1 DH** (`es`), 0 on a pre-read entry.
    ///
    /// Reveals the peer's **claimed** static: an unauthenticated assertion,
    /// made before any DH proves possession. This is documentation
    /// obligation #2 — **authorise on it, never punish on it**. Denylisting
    /// on a claimed static lets an attacker claim any public key in order
    /// to get its owner banned.
    ///
    /// On any error the chain is discarded. §6.2's typestate consumes the
    /// handle, so there is no retry to preserve it for — and leaving it
    /// parked would be worse than discarding it: §6.3's dedup replaces a
    /// same-source entry **without re-surfacing it**, so the peer's next
    /// retransmit would find the slot occupied by a chain no application
    /// can reach, and would go unanswered until `INTRO_TTL`.
    /// # The key this returns is **claimed**, not authenticated — S7
    ///
    /// **Do not denylist on it.** This is stage 0: the peer has asserted a
    /// static public key and *nothing has verified that it holds the
    /// matching private key*. Only [`Claimed::authenticate`] does that.
    ///
    /// An attacker can therefore claim **any** public key it likes. If a
    /// host bans the key this returns, an attacker bans a third party by
    /// naming them: one unauthenticated packet per victim, no key material,
    /// no session. A denylist keyed here is a denial-of-service primitive
    /// pointed at your own users.
    ///
    /// Rate-limiting, logging and routing on a claimed key are fine — they
    /// cost the claimant something or cost the victim nothing. Anything
    /// that **persists a penalty against the named identity** belongs after
    /// [`authenticate`](Claimed::authenticate), which is the first point at
    /// which the key is the peer's.
    ///
    /// # Cancel-safety
    ///
    /// The `Intro` stays alive across the round-trip and is only marked
    /// consumed once the reply is in hand, so **dropping this future
    /// rejects the chain** — §6.2's silent reject, freeing the stage-0 slot
    /// at once. Marking it consumed up front would instead orphan the
    /// chain until `INTRO_TTL`, holding one of §6.3's four per-source slots
    /// against a peer for 15 s.
    pub async fn read_identity(mut self) -> Result<Claimed<I>, IntroError> {
        let shell = self.shell.clone();
        let id = self.id;
        let result = round_trip(&shell, |reply| Command::ReadIdentity(id, reply)).await;
        // Reached only if the future was not dropped during the await.
        self.consumed = true;
        match result {
            Some(Ok(claimed)) => Ok(Claimed {
                shell,
                id,
                claimed_static: claimed,
                consumed: false,
            }),
            Some(Err(error)) => {
                shell.send(Command::Reject(id));
                Err(error)
            }
            None => Err(IntroError::EndpointDropped),
        }
    }
}

impl<I: Identity> Drop for Intro<I> {
    fn drop(&mut self) {
        if !self.consumed {
            self.shell.send(Command::Reject(self.id));
        }
    }
}

impl<I: Identity> std::fmt::Debug for Intro<I> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Both fields printed here are §6.1 attacker-chosen quantities, and
        // `Claimed`'s `Debug` below suppresses its one for that reason —
        // so whether this should suppress too is a live question and is
        // **deliberately not answered here**. It stays as it is: an
        // `Intro`'s `Debug` is an operator's only view of a stage-0
        // arrival, and the two values are diagnostics rather than a
        // secret-ish assertion of identity. What §6.1 forbids is *unbounded
        // logging* and durable keying, which is a property of the caller's
        // loop and not of this impl — see `source()` for the warning.
        f.debug_struct("Intro")
            .field("source", &self.source())
            .field("sender_index", &self.sender_index())
            .finish_non_exhaustive()
    }
}

/// A chain whose peer has **claimed** a static — §6.1's stage 1, at 1 DH
/// cumulative.
///
/// The claim is not proof. Drop is a silent reject.
///
/// **S8** — `#[must_use]`, see [`Intro`]. This is the stage S8 names
/// explicitly, the one parked across turns while a human is asked.
#[must_use = "dropping a staged accept object silently rejects the inbound \
              connection; call authenticate(), or drop it deliberately"]
pub struct Claimed<I: Identity> {
    shell: Shell<I>,
    id: IntroId,
    claimed_static: PublicKeyOf<I>,
    consumed: bool,
}

impl<I: Identity> Claimed<I> {
    /// The static the peer **claims**.
    ///
    /// Named `claimed_static`, never `remote_static`, and the name is the
    /// documentation: at this stage possession has not been proven. §6.1's
    /// `ss` in [`authenticate`](Self::authenticate) is what proves it.
    pub fn claimed_static(&self) -> &PublicKeyOf<I> {
        &self.claimed_static
    }

    /// §6.1's stage 2 — **+1 DH** (`ss`), 2 cumulative.
    ///
    /// Possession is proven here, and §17.1's timestamp guard admits the
    /// initiation here. On any error the chain is discarded, for the reason
    /// given on [`Intro::read_identity`].
    ///
    /// Cancel-safe on the same terms as
    /// [`Intro::read_identity`](Intro::read_identity): a dropped future
    /// rejects the chain rather than orphaning it.
    ///
    /// Defined only where the suite's pattern has no pre-shared key; a
    /// [`channel_psk!`](crate::channel_psk) suite has
    /// [`authenticate_with`](Claimed::authenticate_with) instead.
    pub async fn authenticate(self) -> Result<Proven<I>, AuthError>
    where
        I::Suite: crate::packet::Handshake<Psk = ()>,
    {
        self.authenticate_with(()).await
    }

    /// [`authenticate`](Claimed::authenticate), naming the pre-shared key.
    ///
    /// # This is the stage the PSK belongs at, and the reason is the cost
    ///
    /// [`claimed_static`](Claimed::claimed_static) is already in your hand
    /// — one `es`, and nothing else, has been spent — so the key is
    /// selected **with the peer named**. That ordering is the whole reason
    /// the pattern is `IKpsk1` and not a psk0 shape: its `psk` token sits
    /// after msg1's `s`, so a stranger you have no key for is rejected by
    /// *dropping this object*, at **1 DH**. Choosing inside the handshake
    /// instead — hiss's `read_message_1_with` lookup closure, which fires
    /// at the `psk` token and therefore after the proving `ss` — would cost
    /// **2** (ruling 280).
    ///
    /// This is also why the key is not held by the endpoint: an endpoint
    /// that already knew which PSK to use would have no use for the
    /// identity this stage exists to reveal.
    ///
    /// # A wrong key is [`AuthError::HandshakeFailed`]
    ///
    /// The same undetailed verdict a forged identity gets, and the same
    /// 2 DH. "You are not who you claim" and "you do not hold the pairing
    /// secret" are one answer to one question, and §18.1 gives an
    /// unauthenticated peer no oracle for telling them apart.
    ///
    /// Cancel-safe on the same terms as
    /// [`authenticate`](Claimed::authenticate).
    pub async fn authenticate_with(
        mut self,
        psk: crate::identity::PskOf<I>,
    ) -> Result<Proven<I>, AuthError> {
        let shell = self.shell.clone();
        let id = self.id;
        let result = round_trip(&shell, move |reply| Command::Authenticate(id, psk, reply)).await;
        self.consumed = true;
        match result {
            Some(Ok((peer_static, timestamp))) => Ok(Proven {
                shell,
                id,
                peer_static,
                timestamp,
                consumed: false,
            }),
            Some(Err(error)) => {
                shell.send(Command::Reject(id));
                Err(error)
            }
            None => Err(AuthError::EndpointDropped),
        }
    }
}

impl<I: Identity> Drop for Claimed<I> {
    fn drop(&mut self) {
        if !self.consumed {
            self.shell.send(Command::Reject(self.id));
        }
    }
}

impl<I: Identity> std::fmt::Debug for Claimed<I> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // The claimed static is deliberately not printed: it is an
        // unauthenticated assertion, and a `Debug` that showed it invites
        // exactly the logging that documentation obligation #2 warns about.
        f.debug_struct("Claimed").finish_non_exhaustive()
    }
}

/// A chain whose peer has **proven** possession — §6.1's stage 2, at 2 DH
/// cumulative.
///
/// Drop is a silent reject.
///
/// **S8** — `#[must_use]`, see [`Intro`]. S9 is the story that makes this
/// stage's drop meaningful: *prove an identity, then still decline*.
#[must_use = "dropping a staged accept object silently rejects the inbound \
              connection; call accept(), or drop it deliberately"]
pub struct Proven<I: Identity> {
    shell: Shell<I>,
    id: IntroId,
    peer_static: PublicKeyOf<I>,
    timestamp: Timestamp,
    consumed: bool,
}

impl<I: Identity> Proven<I> {
    /// The peer's static — **proven**, and safe to authorise or deny on.
    pub fn peer_static(&self) -> &PublicKeyOf<I> {
        &self.peer_static
    }

    /// §5.2's initiation timestamp, as the peer sent it.
    ///
    /// The one wall-clock reading in the protocol (§5.3), carried verbatim:
    /// it is **not** range-checked, because §5.3 specifies no validation and
    /// a slither that rejected an out-of-range value would have added a wire
    /// behaviour the spec does not have.
    pub fn timestamp(&self) -> Timestamp {
        self.timestamp
    }

    /// §6.1's stage 3 — **+2 DH** (`ee`, `se`), 4 cumulative.
    ///
    /// Writes msg2 and installs the session, returning the established
    /// [`Connection`].
    ///
    /// # Cancel-safety
    ///
    /// Dropping the future before the reply arrives rejects the chain (a
    /// no-op if the driver has already consumed it). Dropping it *after*
    /// the driver has built the connection drops that `Connection` — the
    /// last handle to it — which performs §16.2's `close(NO_ERROR, "")`.
    /// That is the right answer for a session nobody claimed: the peer is
    /// told at once rather than waiting out `DEAD_TIMEOUT`.
    pub async fn accept(mut self) -> Result<Connection<I::Suite>, AcceptError> {
        let shell = self.shell.clone();
        let id = self.id;
        let peer_static = self.peer_static.clone();
        let result = round_trip(&shell, move |reply| {
            Command::AcceptChain(id, peer_static, reply)
        })
        .await;
        self.consumed = true;
        match result {
            Some(result) => result,
            None => Err(AcceptError::EndpointDropped),
        }
    }
}

impl<I: Identity> Drop for Proven<I> {
    fn drop(&mut self) {
        if !self.consumed {
            self.shell.send(Command::Reject(self.id));
        }
    }
}

impl<I: Identity> std::fmt::Debug for Proven<I> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Proven")
            .field("timestamp", &self.timestamp)
            .finish_non_exhaustive()
    }
}

/// One driver round-trip: send the command, await the reply.
///
/// `None` means the driver stopped under the verb — the state each staged
/// error type's `EndpointDropped` describes (ruling 62).
///
/// **Cancel-safety** is the *caller's*: dropping the returned future drops
/// the `oneshot` receiver, and each verb above keeps its staged object alive
/// across this await so the drop rejects the chain. The DH the driver may
/// already have spent is not refunded, which is unavoidable and is why §6.1
/// prices the ladder cumulatively.
async fn round_trip<I: Identity, T>(
    shell: &Shell<I>,
    command: impl FnOnce(oneshot::Sender<T>) -> Command<I>,
) -> Option<T> {
    if shell.driver_stopped() {
        return None;
    }
    let (tx, rx) = oneshot::channel();
    shell.send(command(tx));
    rx.await.ok()
}