rusty_time-daemon 0.3.2

rtimed, the rusty_time daemon: a pure-Rust NTPv4 and NTS (RFC 8915) client and server with interleaved mode (RFC 9769), rate limiting, Kiss-o'-Death, batched send/receive and an NTP-over-HTTP gateway. The chronyd analog.
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
//! Tests for the NTP server: admission, interleaved mode, NTS, and the
//! adversarial cases (reflection, amplification, forgery, garbage).

use super::*;
use crate::nts_session::NtsSession;

fn peer(n: u8) -> SocketAddr {
    format!("192.0.2.{n}:123").parse().expect("addr")
}

/// The same host, a different ephemeral source port.
fn peer_port(n: u8, port: u16) -> SocketAddr {
    format!("192.0.2.{n}:{port}").parse().expect("addr")
}

fn state_with(rate_limit: RateLimitConfig) -> Arc<Mutex<ServerState>> {
    let mut ring = KeyRing::new(3);
    ring.rotate_in(MasterKey {
        id: 7,
        key: [0x5A; 32],
    });
    Arc::new(Mutex::new(ServerState {
        clients: ClientTable::new(64, rate_limit),
        ring,
        stratum: 2,
        upstream: Upstream::REFERENCE,
        started_unix: 0,
    }))
}

/// Rate limiting effectively off, for tests about protocol behavior rather
/// than admission.
fn test_state() -> Arc<Mutex<ServerState>> {
    state_with(RateLimitConfig {
        interval_log2: -20,
        burst: 1_000_000,
        leak_shift: 0,
        global_rate_hz: 0.0,
        global_burst: 0.0,
    })
}

#[test]
fn answers_plain_client_requests() {
    let state = test_state();
    let req = NtpPacket::client_request(4, NtpTimestamp(0x1234_5678_9ABC_DEF0)).to_bytes();
    let recv = NtpTimestamp::from_unix(1_756_224_000, 0);
    let reply = build_reply(&req, peer(1), recv, &state, &SystemClock).expect("reply");
    let p = NtpPacket::parse(&reply).expect("parse");
    assert_eq!(p.mode, Mode::Server);
    assert_eq!(p.stratum, 2);
    // The origin timestamp must echo the client transmit: that is the client's
    // only anti-spoofing binding.
    assert_eq!(p.origin_ts, NtpTimestamp(0x1234_5678_9ABC_DEF0));
}

#[test]
fn a_following_server_is_unselectable_until_its_clock_is_steered() {
    // A router serving its LAN from `rtimed sync --serve`: before the first
    // correction, RFC 5905's unsynchronised answer (leap 3, stratum 16), which
    // every client refuses; afterwards, the selected source's view.
    let state = test_state();
    {
        let mut s = state.lock().expect("lock");
        s.stratum = STRATUM_UNSYNCHRONIZED;
        s.upstream = Upstream::UNSYNCHRONIZED;
    }
    let req = NtpPacket::client_request(4, NtpTimestamp(0x1234_5678_9ABC_DEF0)).to_bytes();
    let recv = NtpTimestamp::from_unix(1_756_224_000, 0);
    let reply = build_reply(&req, peer(1), recv, &state, &SystemClock).expect("reply");
    let p = NtpPacket::parse(&reply).expect("parse");
    assert_eq!(p.leap, LeapIndicator::Unsynchronized);
    assert_eq!(p.stratum, 16);
    assert_eq!(&p.reference_id, b"INIT");

    {
        let mut s = state.lock().expect("lock");
        s.stratum = 3;
        s.upstream = Upstream {
            leap: LeapIndicator::NoWarning,
            reference_id: [203, 0, 113, 2],
            root_delay_s: 0.0,
            root_dispersion_s: 0.25,
        };
    }
    let reply = build_reply(&req, peer(2), recv, &state, &SystemClock).expect("reply");
    let p = NtpPacket::parse(&reply).expect("parse");
    assert_eq!(p.leap, LeapIndicator::NoWarning);
    assert_eq!(p.stratum, 3);
    assert_eq!(p.reference_id, [203, 0, 113, 2]);
    assert!((p.root_dispersion.to_seconds() - 0.25).abs() < 0.001);
}

#[test]
fn refuses_to_reflect_server_mode_packets() {
    // A server-mode datagram must never be answered, or the server becomes a
    // reflection amplifier between two victims.
    let state = test_state();
    let mut p = NtpPacket::client_request(4, NtpTimestamp(1));
    p.mode = Mode::Server;
    let recv = NtpTimestamp::from_unix(1_756_224_000, 0);
    assert!(build_reply(&p.to_bytes(), peer(1), recv, &state, &SystemClock).is_none());
    assert_eq!(state.lock().expect("lock").clients.stats.refused, 1);
}

#[test]
fn a_flood_is_rate_limited_and_kissed_off_sparingly() {
    let state = state_with(RateLimitConfig {
        interval_log2: 3,
        burst: 2,
        leak_shift: 2,
        global_rate_hz: 0.0,
        global_burst: 0.0,
    });
    let recv = NtpTimestamp::from_unix(1_756_224_000, 0);
    let mut answers = 0;
    let mut kods = 0;
    for i in 0..40u64 {
        let req = NtpPacket::client_request(4, NtpTimestamp(i)).to_bytes();
        if let Some(reply) = build_reply(&req, peer(9), recv, &state, &SystemClock) {
            let p = NtpPacket::parse(&reply).expect("parse");
            if p.stratum == 0 && &p.reference_id == b"RATE" {
                kods += 1;
            } else {
                answers += 1;
            }
        }
    }
    // The whole point: a flood must cost the attacker far more packets than it
    // costs us.
    assert!(
        answers <= 3,
        "rate limiter let {answers} full answers through"
    );
    assert!(kods > 0, "no Kiss-o'-Death emitted at all");
    assert!(
        answers + kods < 20,
        "server replied to {}/40 of a flood, which is an amplifier",
        answers + kods
    );
}

#[test]
fn changing_source_port_does_not_reset_the_rate_limit() {
    // The source port is chosen by the sender. If it were part of the client
    // key, anyone could refill their bucket by picking a new ephemeral port
    // and the limiter would be decorative.
    let state = state_with(RateLimitConfig {
        interval_log2: 3,
        burst: 4,
        leak_shift: 8, // rarely kiss, so we count real answers
        global_rate_hz: 0.0,
        global_burst: 0.0,
    });
    let recv = NtpTimestamp::from_unix(1_756_224_000, 0);
    let mut answers = 0;
    for port in 40_000u16..40_040 {
        let req = NtpPacket::client_request(4, NtpTimestamp(port as u64)).to_bytes();
        if let Some(reply) = build_reply(&req, peer_port(9, port), recv, &state, &SystemClock) {
            let p = NtpPacket::parse(&reply).expect("parse");
            if p.stratum != 0 {
                answers += 1;
            }
        }
    }
    assert!(
        answers <= 5,
        "40 requests from 40 source ports on ONE address got {answers} answers with a burst of 4 \
         — the limiter is keyed on the port and can be bypassed"
    );
    assert_eq!(
        state.lock().expect("lock").clients.len(),
        1,
        "one address must be one client, whatever port it uses"
    );
}

#[test]
fn one_clients_flood_does_not_deny_service_to_another() {
    let state = state_with(RateLimitConfig {
        interval_log2: 3,
        burst: 2,
        leak_shift: 2,
        global_rate_hz: 0.0,
        global_burst: 0.0,
    });
    let recv = NtpTimestamp::from_unix(1_756_224_000, 0);
    for i in 0..100u64 {
        let req = NtpPacket::client_request(4, NtpTimestamp(i)).to_bytes();
        let _ = build_reply(&req, peer(9), recv, &state, &SystemClock);
    }
    // An innocent client still gets a real answer.
    let req = NtpPacket::client_request(4, NtpTimestamp(999)).to_bytes();
    let reply = build_reply(&req, peer(10), recv, &state, &SystemClock).expect("reply");
    let p = NtpPacket::parse(&reply).expect("parse");
    assert_ne!(p.stratum, 0, "innocent client received a Kiss-o-Death");
    assert_eq!(p.stratum, 2);
}

#[test]
fn interleaved_mode_reports_the_previous_exchanges_timestamps() {
    let state = test_state();
    let clock = SystemClock;
    let client = peer(3);

    // Exchange 1: basic, and the server learns this client.
    let recv1 = NtpTimestamp::from_unix(1_756_224_000, 0);
    let req1 = NtpPacket::client_request(4, NtpTimestamp(0xAAAA)).to_bytes();
    let reply1 = build_reply(&req1, client, recv1, &state, &clock).expect("reply 1");
    let p1 = NtpPacket::parse(&reply1).expect("parse 1");
    // Bit 0 is the server marking, so compare the rest.
    assert_eq!(p1.receive_ts.0 & !1, recv1.0 & !1);

    // The driver reports the true transmit timestamp after sending.
    let true_tx = NtpTimestamp::from_unix(1_756_224_000, 123_456);
    state
        .lock()
        .expect("lock")
        .clients
        .note_transmit(&client_key(client), true_tx);

    // Exchange 2: the client echoes the receive timestamp it was given (that is
    // how it asks for interleaved) and puts its own T4 in the request's
    // receive field, which the reply must echo back as origin.
    let recv2 = NtpTimestamp::from_unix(1_756_224_064, 0);
    let client_t4 = NtpTimestamp(0xC0FF_EE00_1234_5678);
    let mut req2 = NtpPacket::client_request(4, NtpTimestamp(0xBBBB));
    req2.origin_ts = p1.receive_ts;
    req2.receive_ts = client_t4;
    let reply2 = build_reply(&req2.to_bytes(), client, recv2, &state, &clock).expect("reply 2");
    let p2 = NtpPacket::parse(&reply2).expect("parse 2");

    // Receive is THIS exchange's (so the client can interleave again); only
    // transmit looks back. Bit 0 is the server marking.
    assert_eq!(
        p2.receive_ts.0 & !1,
        recv2.0 & !1,
        "interleaved reply must report the CURRENT receive timestamp"
    );
    assert_eq!(
        p2.transmit_ts.0 & !1,
        true_tx.0 & !1,
        "should report the true transmit of the previous response"
    );
    // THE rule chrony checks: an interleaved reply echoes the request's
    // RECEIVE field into origin. Echoing transmit instead makes the client
    // classify the reply as basic and silently misread stale timestamps —
    // observed live as a 146 ms offset error against chrony's `xleave`.
    assert_eq!(
        p2.origin_ts, client_t4,
        "interleaved reply must echo the request's receive field as origin"
    );
    assert_eq!(
        state
            .lock()
            .expect("lock")
            .clients
            .stats
            .interleaved_responses,
        1
    );
}

#[test]
fn a_client_not_asking_for_interleaved_gets_this_exchanges_timestamps() {
    let state = test_state();
    let clock = SystemClock;
    let client = peer(4);
    let recv1 = NtpTimestamp::from_unix(1_756_224_000, 0);
    let req1 = NtpPacket::client_request(4, NtpTimestamp(0xAAAA)).to_bytes();
    let _ = build_reply(&req1, client, recv1, &state, &clock).expect("reply 1");
    state.lock().expect("lock").clients.note_transmit(
        &client_key(client),
        NtpTimestamp::from_unix(1_756_224_000, 1),
    );

    // Origin left at zero (a plain client): basic mode.
    let recv2 = NtpTimestamp::from_unix(1_756_224_064, 0);
    let req2 = NtpPacket::client_request(4, NtpTimestamp(0xBBBB)).to_bytes();
    let reply2 = build_reply(&req2, client, recv2, &state, &clock).expect("reply 2");
    let p2 = NtpPacket::parse(&reply2).expect("parse 2");
    assert_eq!(
        p2.receive_ts.0 & !1,
        recv2.0 & !1,
        "basic mode must use this exchange"
    );
    // A basic reply echoes the request's TRANSMIT field as origin.
    assert_eq!(p2.origin_ts, NtpTimestamp(0xBBBB));
    // And the server marking must hold in both modes.
    assert_eq!(p2.receive_ts.0 & 1, 1, "receive must have bit 0 set");
    assert_eq!(p2.transmit_ts.0 & 1, 0, "transmit must have bit 0 clear");
    assert_eq!(
        state
            .lock()
            .expect("lock")
            .clients
            .stats
            .interleaved_responses,
        0
    );
}

#[test]
fn nts_round_trip_client_to_server() {
    let state = test_state();
    let keys = NtsKeys {
        c2s: [0x11; 32],
        s2c: [0x22; 32],
    };
    let cookie = {
        let guard = state.lock().expect("lock");
        rusty_time_nts::cookie::mint(&guard.ring, &keys, &[3; COOKIE_NONCE_LEN]).expect("mint")
    };

    let mut session = NtsSession::for_test(keys.clone(), vec![cookie]);
    let header = NtpPacket::client_request(4, NtpTimestamp(0xAABB_CCDD_1122_3344)).to_bytes();
    let request = session.protect(&header).expect("protect");

    let recv = NtpTimestamp::from_unix(1_756_224_000, 0);
    let reply = build_reply(&request, peer(5), recv, &state, &SystemClock).expect("reply");

    assert_eq!(session.cookies_held(), 0, "cookie spent");
    session
        .verify(&reply)
        .expect("client verifies server reply");
    assert!(
        session.cookies_held() >= 1,
        "server must replenish the spent cookie"
    );
}

#[test]
fn forged_authenticator_gets_no_answer() {
    let state = test_state();
    let keys = NtsKeys {
        c2s: [0x11; 32],
        s2c: [0x22; 32],
    };
    let cookie = {
        let guard = state.lock().expect("lock");
        rusty_time_nts::cookie::mint(&guard.ring, &keys, &[3; COOKIE_NONCE_LEN]).expect("mint")
    };
    let mut session = NtsSession::for_test(keys, vec![cookie]);
    let header = NtpPacket::client_request(4, NtpTimestamp(1)).to_bytes();
    let mut request = session.protect(&header).expect("protect");
    let last = request.len() - 1;
    request[last] ^= 0xFF;
    let recv = NtpTimestamp::from_unix(1_756_224_000, 0);
    assert!(
        build_reply(&request, peer(6), recv, &state, &SystemClock).is_none(),
        "server answered a forged NTS request"
    );
}

#[test]
fn unknown_cookie_gets_an_nts_nak() {
    // RFC 8915 §5.7: a cookie the server cannot redeem (its master keys have
    // changed, as after a restart without --state) is answered with an NTS NAK
    // so the client renews at once. The NAK says nothing about the time,
    // carries no authenticator and is never larger than the request.
    let state = test_state();
    let keys = NtsKeys {
        c2s: [0x11; 32],
        s2c: [0x22; 32],
    };
    let mut foreign = KeyRing::new(3);
    foreign.rotate_in(MasterKey {
        id: 7, // same id, different key
        key: [0xEE; 32],
    });
    let cookie =
        rusty_time_nts::cookie::mint(&foreign, &keys, &[3; COOKIE_NONCE_LEN]).expect("mint");
    let mut session = NtsSession::for_test(keys, vec![cookie]);
    let header = NtpPacket::client_request(4, NtpTimestamp(1)).to_bytes();
    let request = session.protect(&header).expect("protect");
    let recv = NtpTimestamp::from_unix(1_756_224_000, 0);
    let reply = build_reply(&request, peer(7), recv, &state, &SystemClock).expect("a NAK");
    let p = NtpPacket::parse(&reply).expect("parse");
    assert_eq!(p.stratum, 0, "a kiss, not a time source");
    assert_eq!(&p.reference_id, b"NTSN");
    assert_eq!(p.origin_ts, NtpTimestamp(1), "tied to the request");
    assert!(reply.len() <= request.len(), "never an amplifier");
    let uid = |packet: &[u8]| {
        ef::fields(packet)
            .find(|f| f.field_type == ef::field_type::UNIQUE_IDENTIFIER)
            .map(|f| f.body.to_vec())
    };
    assert_eq!(uid(&reply), uid(&request), "echoes the unique identifier");
    assert!(
        session.verify(&reply).is_err(),
        "a NAK is unauthenticated and must never verify"
    );
}

#[test]
fn placeholder_count_cannot_amplify_without_bound() {
    let state = test_state();
    let keys = NtsKeys {
        c2s: [0x11; 32],
        s2c: [0x22; 32],
    };
    let cookie = {
        let guard = state.lock().expect("lock");
        rusty_time_nts::cookie::mint(&guard.ring, &keys, &[3; COOKIE_NONCE_LEN]).expect("mint")
    };
    let header = NtpPacket::client_request(4, NtpTimestamp(1)).to_bytes();
    let uid = [9u8; UNIQUE_ID_LEN];
    let nonce = [4u8; NONCE_LEN];
    let request =
        ef::protect_request(&header, &uid, &cookie, 60, &keys.c2s, &nonce).expect("protect");

    let recv = NtpTimestamp::from_unix(1_756_224_000, 0);
    let reply = build_reply(&request, peer(8), recv, &state, &SystemClock).expect("reply");
    assert!(
        reply.len() <= request.len(),
        "reply ({}) exceeded request ({}): amplification",
        reply.len(),
        request.len()
    );
}

#[test]
fn malformed_datagrams_never_panic() {
    let state = test_state();
    let recv = NtpTimestamp::from_unix(1_756_224_000, 0);
    let mut rng = 0xACE1_2345_6789_BEEFu64;
    for _ in 0..20_000 {
        rng ^= rng << 13;
        rng ^= rng >> 7;
        rng ^= rng << 17;
        let len = (rng % 200) as usize;
        let mut p = vec![0u8; len];
        for b in p.iter_mut() {
            rng ^= rng << 13;
            rng ^= rng >> 7;
            rng ^= rng << 17;
            *b = rng as u8;
        }
        if len > 0 {
            p[0] = (4 << 3) | 3; // bias toward "looks like a client request"
        }
        let _ = build_reply(&p, peer(11), recv, &state, &SystemClock);
    }
}