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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
//! Mesh peer admission (P3-K1, ADR-103, plan section 1.5).
//!
//! After the optional Noise handshake, a peer that wants a verified
//! identity sends [`AdmitHello`] as its first frame. The hello signs the
//! *session's* Noise handshake hash, so a captured hello cannot be
//! replayed on another session, and binds the node id to the Ed25519 key
//! that the id is derived from ([`node_id_from_pubkey`]).
//!
//! This module is policy-free plumbing: [`AdmitHello::verify`] is pure
//! cryptography; the policy (genesis pin, revocation, verdict, mode) lives
//! behind [`AdmissionGate`]. [`AllowAll`] is today's behaviour;
//! [`CryptoGate`] implements `off | observe | enforce`.
//!
//! # Trust of scopes
//!
//! A peer's `dest_scope` is a *request*; the kernel ignores it and the
//! [`LocalDelivery`](crate::mesh_delivery::LocalDelivery) implementor must
//! treat it as untrusted. A peer's `src_scope` is kept only when
//! admission verified the peer ([`Grant::trust_scope`]); for every other
//! peer `mesh_serve` strips it before delivery.
use async_trait::async_trait;
use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
use serde::{Deserialize, Serialize};
use crate::node_id::node_id_from_pubkey;
pub use crate::mesh_admit_gate::{
AdmissionRecord, CryptoGate, OpenVerdicts, Verdict, VerdictRequest, VerdictSource,
VERDICT_TTL,
};
#[cfg(feature = "exochain")]
pub use crate::mesh_admit_gate::GateVerdictSource;
/// Discriminator that tells a hello apart from a `MeshIpcEnvelope`.
pub const HELLO_KIND: &str = "mesh.admit.hello";
/// Domain-separation prefix of the signed bytes.
pub const HELLO_DOMAIN: &[u8] = b"weftos/mesh-admit/v1\0";
/// Allowed clock skew between hello `ts` and local time.
pub const MAX_SKEW_SECS: u64 = 60;
/// Capability string marking a leaf-class peer.
pub const CAP_LEAF: &str = "leaf";
/// Wire form of the first frame (JSON). Binary fields are lowercase hex.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AdmitHello {
/// Always [`HELLO_KIND`].
pub kind: String,
/// Protocol version, currently 1.
pub v: u32,
/// `node_id_from_pubkey(pubkey)`.
pub node_id: String,
/// Ed25519 public key (64 hex).
pub pubkey: String,
/// Free-form platform string.
#[serde(default)]
pub platform: String,
/// Capability tags; [`CAP_LEAF`] marks a leaf-class peer.
#[serde(default)]
pub capabilities: Vec<String>,
/// Cluster genesis hash the peer believes in (64 hex).
pub genesis_hash: String,
/// Unix seconds when signed.
pub ts: u64,
/// The peer's Noise static public key (64 hex), or empty.
#[serde(default)]
pub noise_static_pub: String,
/// Signature (128 hex) over [`signed_bytes`].
pub sig: String,
}
/// What the channel itself proves: the session hash and the remote static.
#[derive(Debug, Clone, Copy)]
pub struct ChannelBinding<'a> {
/// Noise handshake hash of this session.
pub handshake_hash: &'a [u8],
/// Remote Noise static key as seen by the handshake.
pub remote_static: Option<&'a [u8]>,
}
/// A hello whose node id, key, session binding and timestamp checked out.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerifiedHello {
/// The verified node id.
pub node_id: String,
/// The verified Ed25519 key.
pub pubkey: [u8; 32],
/// Platform string as sent.
pub platform: String,
/// Capabilities as sent.
pub capabilities: Vec<String>,
/// Genesis hash as signed (not yet compared to a pin).
pub genesis_hash: [u8; 32],
/// Signed timestamp.
pub ts: u64,
}
impl VerifiedHello {
/// Class implied by the capabilities. **Self-declared**: a node can
/// claim `leaf` (taking limits it does not need) or omit it. Under
/// `enforce` the verdict source may override it
/// ([`Verdict::PermitAs`](crate::mesh_admit::Verdict)); a full fix
/// (class bound to an issued credential) is a known open limit
/// (ADR-103, Phase 3).
pub fn class(&self) -> PeerClass {
if self.capabilities.iter().any(|c| c == CAP_LEAF) {
PeerClass::Leaf
} else {
PeerClass::Node
}
}
}
/// Why a hello did not verify, or that none was sent.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HelloFailure {
/// First frame was not a hello (legacy / ESP32 peers).
Missing,
/// Hello present but unparsable or wrong version.
Malformed(String),
/// `node_id` is not the id derived from `pubkey`.
NodeIdMismatch,
/// Channel has no handshake hash (plaintext passthrough).
NoHandshakeBinding,
/// `noise_static_pub` differs from the handshake's remote static.
StaticMismatch,
/// Signature does not verify over this session's hash.
BadSignature,
/// `ts` outside the allowed skew.
ClockSkew,
}
impl HelloFailure {
/// Stable machine-readable code for records and logs.
pub fn code(&self) -> &'static str {
match self {
Self::Missing => "hello_missing",
Self::Malformed(_) => "hello_malformed",
Self::NodeIdMismatch => "node_id_mismatch",
Self::NoHandshakeBinding => "no_handshake_binding",
Self::StaticMismatch => "static_mismatch",
Self::BadSignature => "bad_signature",
Self::ClockSkew => "clock_skew",
}
}
}
/// The exact bytes a hello signs.
///
/// Layout: domain || handshake hash || genesis || ts (BE) || node_id ||
/// platform || capability count (BE u32) || each capability, with every
/// variable-length string prefixed by its length (BE u32). Covering the
/// identity, platform and capabilities means none can be altered in
/// flight; the class a hello implies is therefore signed (but still
/// self-declared, see [`VerifiedHello::class`]).
pub fn signed_bytes(
handshake_hash: &[u8],
genesis: &[u8; 32],
ts: u64,
node_id: &str,
platform: &str,
capabilities: &[String],
) -> Vec<u8> {
fn put(b: &mut Vec<u8>, s: &str) {
b.extend_from_slice(&(s.len() as u32).to_be_bytes());
b.extend_from_slice(s.as_bytes());
}
let mut b = Vec::with_capacity(HELLO_DOMAIN.len() + handshake_hash.len() + 128);
b.extend_from_slice(HELLO_DOMAIN);
b.extend_from_slice(handshake_hash);
b.extend_from_slice(genesis);
b.extend_from_slice(&ts.to_be_bytes());
put(&mut b, node_id);
put(&mut b, platform);
b.extend_from_slice(&(capabilities.len() as u32).to_be_bytes());
for c in capabilities {
put(&mut b, c);
}
b
}
impl AdmitHello {
/// Build and sign a hello for the session identified by
/// `handshake_hash`. `noise_static_pub` is this side's Noise static
/// public key (what the peer sees as its remote static).
pub fn sign(
key: &SigningKey,
handshake_hash: &[u8],
noise_static_pub: &[u8],
genesis: &[u8; 32],
ts: u64,
platform: &str,
capabilities: Vec<String>,
) -> Self {
let pk = key.verifying_key().to_bytes();
let node_id = node_id_from_pubkey(&pk);
let sig = key.sign(&signed_bytes(
handshake_hash, genesis, ts, &node_id, platform, &capabilities,
));
Self {
kind: HELLO_KIND.to_owned(),
v: 1,
node_id,
pubkey: hex_encode(&pk),
platform: platform.to_owned(),
capabilities,
genesis_hash: hex_encode(genesis),
ts,
noise_static_pub: hex_encode(noise_static_pub),
sig: hex_encode(&sig.to_bytes()),
}
}
/// Serialize for the wire.
pub fn to_bytes(&self) -> Vec<u8> {
serde_json::to_vec(self).unwrap_or_default()
}
/// Classify a first frame: `None` when it is not a hello at all (the
/// legacy path), `Some(Err)` when it claims to be one but is broken.
pub fn parse_frame(data: &[u8]) -> Option<Result<Self, HelloFailure>> {
if data.first() != Some(&b'{') {
return None;
}
let v: serde_json::Value = serde_json::from_slice(data).ok()?;
if v.get("kind").and_then(|k| k.as_str()) != Some(HELLO_KIND) {
return None;
}
Some(serde_json::from_value(v).map_err(|e| HelloFailure::Malformed(e.to_string())))
}
/// Verify everything that needs no policy: id/key binding, session
/// binding, signature, timestamp. Order follows plan section 1.5.
pub fn verify(
&self,
binding: Option<&ChannelBinding<'_>>,
now: u64,
) -> Result<VerifiedHello, HelloFailure> {
if self.v != 1 {
return Err(HelloFailure::Malformed(format!("unsupported version {}", self.v)));
}
let pubkey: [u8; 32] = hex_decode_fixed(&self.pubkey)
.ok_or_else(|| HelloFailure::Malformed("pubkey".into()))?;
let genesis: [u8; 32] = hex_decode_fixed(&self.genesis_hash)
.ok_or_else(|| HelloFailure::Malformed("genesis_hash".into()))?;
let sig: [u8; 64] =
hex_decode_fixed(&self.sig).ok_or_else(|| HelloFailure::Malformed("sig".into()))?;
if node_id_from_pubkey(&pubkey) != self.node_id {
return Err(HelloFailure::NodeIdMismatch);
}
let binding = binding.ok_or(HelloFailure::NoHandshakeBinding)?;
let claimed_static = hex_decode(&self.noise_static_pub)
.ok_or_else(|| HelloFailure::Malformed("noise_static_pub".into()))?;
if binding.remote_static != Some(claimed_static.as_slice()) {
return Err(HelloFailure::StaticMismatch);
}
let vk = VerifyingKey::from_bytes(&pubkey)
.map_err(|_| HelloFailure::Malformed("pubkey not on curve".into()))?;
// Cheap check first: skew before the signature verification.
if now.abs_diff(self.ts) > MAX_SKEW_SECS {
return Err(HelloFailure::ClockSkew);
}
vk.verify_strict(
&signed_bytes(
binding.handshake_hash,
&genesis,
self.ts,
&self.node_id,
&self.platform,
&self.capabilities,
),
&Signature::from_bytes(&sig),
)
.map_err(|_| HelloFailure::BadSignature)?;
Ok(VerifiedHello {
node_id: self.node_id.clone(),
pubkey,
platform: self.platform.clone(),
capabilities: self.capabilities.clone(),
genesis_hash: genesis,
ts: self.ts,
})
}
}
/// What this node needs to introduce itself on an outbound connection.
#[derive(Clone)]
pub struct DialIdentity {
/// This node's Ed25519 key (its node id derives from it).
pub key: SigningKey,
/// Cluster genesis hash to present.
pub genesis: [u8; 32],
/// Platform string.
pub platform: String,
/// Capability tags.
pub capabilities: Vec<String>,
}
impl DialIdentity {
/// Hello for a session. `noise_static` is our own Noise static public
/// key (see [`noise_static_public`](crate::mesh_noise::noise_static_public)).
pub fn hello(&self, handshake_hash: &[u8], noise_static: &[u8], ts: u64) -> AdmitHello {
AdmitHello::sign(
&self.key,
handshake_hash,
noise_static,
&self.genesis,
ts,
&self.platform,
self.capabilities.clone(),
)
}
}
/// How the peer presented itself.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PeerClass {
/// Verified full node.
Node,
/// Verified leaf device (hello carried [`CAP_LEAF`]).
Leaf,
/// Sent no verifiable hello (old build, ESP32 firmware).
Legacy,
}
impl PeerClass {
/// Stable lowercase name (status output, `fleet.snapshot`).
pub fn as_str(self) -> &'static str {
match self {
Self::Node => "node",
Self::Leaf => "leaf",
Self::Legacy => "legacy",
}
}
}
/// Transport protection of the connection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChannelKind {
/// Noise session (has a handshake hash).
Noise,
/// Plaintext.
Passthrough,
}
/// Facts about the connection handed to the gate.
#[derive(Debug, Clone, Copy)]
pub struct AdmitContext {
/// Peer class as known so far.
pub class: PeerClass,
/// Transport protection.
pub channel: ChannelKind,
}
/// What a connection may do after admission.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PeerLimits {
/// No restriction beyond the kernel's own.
None,
/// Leaf: publish only under `substrate/<own-id>/`, subscribe freely.
Leaf,
}
/// A refusal reason (also used for would-be refusals under observe).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Refusal {
/// Stable code, e.g. `wrong_genesis`, `revoked`, `hello_missing`.
pub code: &'static str,
/// Human-readable detail.
pub detail: String,
}
/// Terms of an admission.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Grant {
/// Post-admission limits.
pub limits: PeerLimits,
/// Class the connection is served as (the gate may override the
/// declared class under `enforce`).
pub class: PeerClass,
/// True only when the hello verified AND the gate actually enforces
/// (`CryptoGate` in `enforce`) AND decided Admit. `AllowAll`, `off`
/// and `observe` never set it: a verified key there only binds
/// `source_node`, it is not membership.
pub admitted: bool,
/// Keep the peer's `src_scope` (only for admitted `Node` peers).
pub trust_scope: bool,
/// Set under `observe` when enforcement would have refused.
pub observed: Option<Refusal>,
}
impl Grant {
/// An unrestricted, non-admitted grant (no membership claimed).
pub fn open(class: PeerClass) -> Self {
Self { limits: PeerLimits::None, class, admitted: false, trust_scope: false, observed: None }
}
}
/// Gate decision.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Admission {
/// Serve the peer on the given terms.
Admit(Grant),
/// Close the connection.
Refuse(Refusal),
}
/// Admission policy for the mesh listener.
#[async_trait]
pub trait AdmissionGate: Send + Sync + 'static {
/// True when the listener should apply the idle limit and the live
/// revocation check (a gate that actually checks peers). The per-IP cap
/// and first-frame timeout apply under every gate. `AllowAll` is false so
/// quiet legacy leaves are not cut off once connected.
fn strict(&self) -> bool {
false
}
/// Whether an admitted peer has since been revoked and must be cut off
/// (re-checked on every frame). Only gates that refuse revoked peers at
/// admission say yes; the default never does.
fn is_revoked(&self, _node_id: &str) -> bool {
false
}
/// A hello verified; decide.
async fn admit(&self, hello: &VerifiedHello, ctx: &AdmitContext) -> Admission;
/// No hello, or it failed verification; decide.
async fn admit_unverified(&self, failure: &HelloFailure, ctx: &AdmitContext) -> Admission;
}
/// Admit everyone: the pre-K1 behaviour. Verified hellos still bind
/// `source_node`, but nothing is ever refused or limited.
#[derive(Debug, Default, Clone, Copy)]
pub struct AllowAll;
#[async_trait]
impl AdmissionGate for AllowAll {
async fn admit(&self, _: &VerifiedHello, ctx: &AdmitContext) -> Admission {
Admission::Admit(Grant::open(ctx.class))
}
async fn admit_unverified(&self, _: &HelloFailure, _: &AdmitContext) -> Admission {
Admission::Admit(Grant::open(PeerClass::Legacy))
}
}
/// Lowercase hex encode.
pub fn hex_encode(b: &[u8]) -> String {
use std::fmt::Write;
b.iter().fold(String::with_capacity(b.len() * 2), |mut s, x| {
let _ = write!(s, "{x:02x}");
s
})
}
/// Decode hex (empty string decodes to empty).
pub fn hex_decode(s: &str) -> Option<Vec<u8>> {
if !s.len().is_multiple_of(2) || !s.is_ascii() {
return None;
}
(0..s.len())
.step_by(2)
.map(|i| u8::from_str_radix(&s[i..i + 2], 16).ok())
.collect()
}
fn hex_decode_fixed<const N: usize>(s: &str) -> Option<[u8; N]> {
hex_decode(s)?.try_into().ok()
}
#[cfg(test)]
#[path = "mesh_admit_tests.rs"]
mod tests;
#[cfg(test)]
#[path = "mesh_admit_dial_tests.rs"]
mod dial_tests;
pub use crate::mesh_admit_gate::install_nested_peer_ceiling;