kshana 0.37.0

Open, reproducible PNT-resilience simulator with quantum-sensor performance models
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
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
// SPDX-License-Identifier: AGPL-3.0-only
//! `kshana osnma verify <input>`: run the verifier over a file of I/NAV pages and print
//! the authentication status per satellite and epoch, as text or JSON.

use super::input;
use super::signature::PublicKey;
use super::tables::KeyType;
use super::verifier::{Config, Event, TagResult, TagStatus, Verifier};
use super::{OsnmaStatus, ADVISORY};
use serde::Serialize;
use std::collections::BTreeMap;

const USAGE: &str = "usage: kshana osnma verify <input> [options]

  <input>                    I/NAV pages: the plain format (see docs/OSNMA.md) or the
                             CSV layout of the published test vectors
  --format pages|vector-csv|ubx
                             input layout (default: by file content). ubx is a u-blox
                             byte stream with UBX-RXM-SFRBX messages (Galileo E1-B)
  --start-gst SECONDS        start time of a vector CSV in GST seconds
                             (default: read from a file name like 16_AUG_2023_GST_05_00_01.csv)
  --merkle-root HEX          trusted Merkle root (64 hex digits) for DSM-PKR checks
  --public-key ID:TYPE:HEX   trusted public key, TYPE p256 or p521, compressed point
  --reference-time SECONDS   present time in GST seconds from an independent source. A single
                             instant: sub-frames further from it than the tolerance are set
                             aside, so use it for live or just-recorded data
  --max-time-error SECONDS   largest distance of a sub-frame from the reference time, below
                             30 (default 29); needs --reference-time
  --epochs                   also print every tag result
  --json                     print JSON instead of text

Exit status: 0 done, 2 usage or input error, 3 a check on some satellite's data failed.";

struct Options {
    input: String,
    format: Option<String>,
    start_gst: Option<u32>,
    merkle_root: Option<[u8; 32]>,
    keys: Vec<PublicKey>,
    reference: Option<u32>,
    max_err: Option<u32>,
    epochs: bool,
    json: bool,
}

fn parse_args(args: &[String]) -> Result<Options, String> {
    let mut o = Options {
        input: String::new(),
        format: None,
        start_gst: None,
        merkle_root: None,
        keys: Vec::new(),
        reference: None,
        max_err: None,
        epochs: false,
        json: false,
    };
    let mut it = args.iter();
    while let Some(a) = it.next() {
        let mut val = |name: &str| it.next().cloned().ok_or(format!("{name} needs a value"));
        match a.as_str() {
            "--format" => o.format = Some(val("--format")?),
            "--start-gst" => o.start_gst = Some(num(&val("--start-gst")?)?),
            "--reference-time" => o.reference = Some(num(&val("--reference-time")?)?),
            "--max-time-error" => o.max_err = Some(num(&val("--max-time-error")?)?),
            "--merkle-root" => {
                let b = hex::decode(val("--merkle-root")?).map_err(|_| "bad Merkle root hex")?;
                o.merkle_root = Some(b.try_into().map_err(|_| "Merkle root must be 32 bytes")?);
            }
            "--public-key" => o.keys.push(parse_key(&val("--public-key")?)?),
            "--epochs" => o.epochs = true,
            "--json" => o.json = true,
            s if s.starts_with("--") => return Err(format!("unknown option {s}")),
            s if o.input.is_empty() => o.input = s.to_string(),
            s => return Err(format!("unexpected argument {s}")),
        }
    }
    if o.input.is_empty() {
        return Err("missing input file".into());
    }
    if o.max_err.is_some() && o.reference.is_none() {
        return Err("--max-time-error has no effect without --reference-time".into());
    }
    let cfg = Config {
        max_time_error_s: o.max_err,
        ..Config::default()
    };
    cfg.validate()?;
    Ok(o)
}

fn num(s: &str) -> Result<u32, String> {
    s.parse().map_err(|_| format!("not a number: {s}"))
}

fn parse_key(s: &str) -> Result<PublicKey, String> {
    let p: Vec<&str> = s.split(':').collect();
    let [id, ty, hx] = p[..] else {
        return Err("public key must be ID:TYPE:HEX".into());
    };
    let key_type = match ty {
        "p256" => KeyType::P256,
        "p521" => KeyType::P521,
        _ => return Err("public key type must be p256 or p521".into()),
    };
    Ok(PublicKey {
        pkid: id.parse().map_err(|_| "bad public key id")?,
        key_type,
        bytes: hex::decode(hx).map_err(|_| "bad public key hex")?,
    })
}

/// Names of a serde value for text output.
fn name<T: Serialize>(t: &T) -> String {
    match serde_json::to_value(t) {
        Ok(serde_json::Value::String(s)) => s,
        Ok(serde_json::Value::Object(m)) => {
            let state = m.get("state").and_then(|v| v.as_str()).unwrap_or("?");
            match m.get("reason").and_then(|v| v.as_str()) {
                Some(r) => format!("{state} ({r})"),
                None => state.to_string(),
            }
        }
        _ => String::new(),
    }
}

fn status_word(s: OsnmaStatus) -> &'static str {
    match s {
        OsnmaStatus::Authenticated => "authenticated",
        OsnmaStatus::Failed => "failed",
        OsnmaStatus::Unavailable => "unavailable",
    }
}

fn event_json(e: &Event) -> serde_json::Value {
    use serde_json::json;
    match e {
        Event::PublicKeyVerified { pkid } => json!({"kind":"public_key_verified","pkid":pkid}),
        Event::PublicKeyRejected(r) => {
            json!({"kind":"public_key_rejected","reason":format!("{r:?}")})
        }
        Event::AlertMessage { verified } => json!({"kind":"alert_message","verified":verified}),
        Event::KrootVerified {
            cid,
            pkid,
            hash,
            mac,
            key_bits,
            tag_bits,
            maclt,
        } => json!({"kind":"kroot_verified","cid":cid,"pkid":pkid,
            "hash":format!("{hash:?}"),"mac":format!("{mac:?}"),
            "key_bits":key_bits,"tag_bits":tag_bits,"maclt":maclt}),
        Event::KeyStall {
            reference,
            latest_key,
        } => json!({"kind":"key_stall","reference":reference,"latest_key":latest_key}),
        Event::ChainRevoked { cid } => json!({"kind":"chain_revoked","cid":cid}),
        Event::PublicKeyRevoked { pkid } => json!({"kind":"public_key_revoked","pkid":pkid}),
        Event::KrootRejected(r) => json!({"kind":"kroot_rejected","reason":format!("{r:?}")}),
        Event::KeyVerified { gst } => json!({"kind":"key_verified","gst":gst}),
        Event::KeyRejected { gst, reason } => {
            json!({"kind":"key_rejected","gst":gst,"reason":name(reason)})
        }
        Event::TimeRejected { gst_sf } => json!({"kind":"time_rejected","gst":gst_sf}),
        Event::BadCrc { .. } => json!({"kind":"bad_crc"}),
        Event::Tag(_) => json!(null),
    }
}

/// Identical events collapsed with a count, in order of first appearance.
fn grouped_events(events: &[Event]) -> Vec<serde_json::Value> {
    let mut order: Vec<String> = Vec::new();
    let mut seen: BTreeMap<String, (serde_json::Value, u32)> = BTreeMap::new();
    for e in events {
        let j = event_json(e);
        let key = j.to_string();
        if !seen.contains_key(&key) {
            order.push(key.clone());
        }
        seen.entry(key).or_insert((j, 0)).1 += 1;
    }
    order
        .into_iter()
        .filter_map(|k| seen.remove(&k))
        .map(|(mut j, n)| {
            j["count"] = n.into();
            j
        })
        .collect()
}

#[derive(Default, Serialize)]
struct Counts {
    authenticated: u32,
    failed: u32,
    pending: u32,
    discarded: u32,
}

/// What one verification run needs besides the input bytes; the command line and the in-memory
/// surfaces (Python, WebAssembly) fill the same fields.
pub struct VerifyParams<'a> {
    /// Name shown for the input (a path, or `(in memory)`).
    pub label: &'a str,
    /// `pages`, `vector-csv` or `ubx`; `None` picks by content.
    pub format: Option<&'a str>,
    /// Start of a vector CSV in GST seconds; `None` reads it from a dated file name.
    pub start_gst: Option<u32>,
    /// Trusted Merkle root for DSM-PKR checks.
    pub merkle_root: Option<[u8; 32]>,
    /// Trusted public keys.
    pub keys: Vec<PublicKey>,
    /// Present time in GST seconds from an independent source.
    pub reference: Option<u32>,
    /// Largest distance of a sub-frame from the reference time (needs `reference`).
    pub max_err: Option<u32>,
}

/// Everything a run produced, before it is written as text or JSON.
struct Analysis {
    pages: usize,
    ubx_stats: Option<super::ubx::UbxStats>,
    events: Vec<Event>,
    tags: Vec<TagResult>,
    sats: Vec<(String, OsnmaStatus)>,
    overall: OsnmaStatus,
    nma_status: u8,
    alert: bool,
    counts: BTreeMap<u8, Counts>,
    last_ok: BTreeMap<u8, u32>,
}

impl Analysis {
    fn any_failed(&self) -> bool {
        self.sats.iter().any(|(_, s)| *s == OsnmaStatus::Failed)
    }
}

fn analyse(raw: Vec<u8>, p: &VerifyParams) -> Result<Analysis, String> {
    let layout = match p.format {
        Some(f @ ("vector-csv" | "pages" | "ubx")) => f,
        Some(f) => return Err(format!("unknown format {f}")),
        None if raw.starts_with(&[0xB5, 0x62]) || std::str::from_utf8(&raw).is_err() => "ubx",
        None if raw
            .iter()
            .skip_while(|b| b.is_ascii_whitespace())
            .take(4)
            .eq(b"SVID".iter()) =>
        {
            "vector-csv"
        }
        None => "pages",
    };
    let mut ubx_stats = None;
    let pages = if layout == "ubx" {
        let (pg, st) = super::ubx::pages_from_ubx(&raw);
        ubx_stats = Some(st);
        pg
    } else {
        let Ok(text) = String::from_utf8(raw) else {
            return Err(format!(
                "{} is not text; use --format ubx for a UBX stream",
                p.label
            ));
        };
        if layout == "vector-csv" {
            let Some(start) = p.start_gst.or_else(|| input::start_from_filename(p.label)) else {
                return Err("a vector CSV needs --start-gst or a dated file name".into());
            };
            input::parse_vector_csv(&text, start)?
        } else {
            input::parse_pages(&text)?
        }
    };
    if p.max_err.is_some() && p.reference.is_none() {
        return Err("--max-time-error has no effect without --reference-time".into());
    }
    let mut v = Verifier::new(Config {
        merkle_root: p.merkle_root,
        public_keys: p.keys.clone(),
        // A reference time brings a tolerance with it, the widest allowed by default.
        max_time_error_s: p.reference.map(|_| p.max_err.unwrap_or(29)),
        ..Config::default()
    });
    if let Some(r) = p.reference {
        v.set_reference_time(r);
    }
    let mut events = Vec::new();
    let mut tags: Vec<TagResult> = Vec::new();
    for pg in &pages {
        for e in v.push_page(pg) {
            match e {
                Event::Tag(t) => tags.push(t),
                other => events.push(other),
            }
        }
    }
    let mut counts: BTreeMap<u8, Counts> = BTreeMap::new();
    let mut last_ok: BTreeMap<u8, u32> = BTreeMap::new();
    for t in &tags {
        let c = counts.entry(t.prnd).or_default();
        match t.status {
            TagStatus::Authenticated => {
                c.authenticated += 1;
                let e = last_ok.entry(t.prnd).or_insert(0);
                *e = (*e).max(t.tag_gst);
            }
            TagStatus::Failed(_) => c.failed += 1,
            TagStatus::Pending(_) => c.pending += 1,
            TagStatus::Discarded(_) => c.discarded += 1,
        }
    }
    Ok(Analysis {
        pages: pages.len(),
        ubx_stats,
        events,
        tags,
        sats: v.sat_status(),
        overall: v.overall(),
        nma_status: v.nma_status(),
        alert: v.alert(),
        counts,
        last_ok,
    })
}

fn report_json(a: &Analysis, p: &VerifyParams) -> serde_json::Value {
    let sat_json: Vec<_> = a
        .sats
        .iter()
        .map(|(s, st)| {
            let prn: u8 = s[1..].parse().unwrap_or(0);
            serde_json::json!({
                "sat": s,
                "status": status_word(*st),
                "tags": a.counts.get(&prn),
                "last_authenticated_tag_gst": a.last_ok.get(&prn),
            })
        })
        .collect();
    serde_json::json!({
        "advisory": ADVISORY,
        "input": {"path": p.label, "pages": a.pages},
        "overall": status_word(a.overall),
        "nma_status": a.nma_status,
        "alert": a.alert,
        "freshness_enforced": p.reference.is_some(),
        "reference_time": p.reference,
        "satellites": sat_json,
        "events": grouped_events(&a.events),
        "tags": a.tags,
        "pksos": super::pksos_sentence(a.overall, &a.sats),
        "ubx": a.ubx_stats.as_ref().map(|u| serde_json::json!({
            "frames": u.frames, "skipped_bytes": u.skipped_bytes,
            "inav_pages": u.inav_pages, "ignored_sfrbx": u.ignored_sfrbx,
            "bad_crc": u.bad_crc, "unstamped": u.unstamped,
            "time_conflicts": u.time_conflicts,
        })),
    })
}

/// The JSON report `kshana osnma verify --json` prints, for input held in memory, and whether
/// any satellite's data failed a check (the command line's exit status 3). Nothing is read from
/// or written to disk. The report states the advisory in its `advisory` field.
pub fn verify_report(raw: Vec<u8>, p: &VerifyParams) -> Result<(serde_json::Value, bool), String> {
    let a = analyse(raw, p)?;
    Ok((report_json(&a, p), a.any_failed()))
}

/// Parse a `ID:TYPE:HEX` trusted public key, as `--public-key` takes it.
pub fn parse_public_key(s: &str) -> Result<PublicKey, String> {
    parse_key(s)
}

/// Run the subcommand; returns the process exit code.
pub fn run(args: &[String]) -> i32 {
    // The advisory goes first on every path, errors included.
    if matches!(args.first().map(String::as_str), Some("--help" | "-h")) {
        println!("{ADVISORY}\n\n{USAGE}");
        return 0;
    }
    if args.first().map(String::as_str) != Some("verify") {
        eprintln!("{ADVISORY}\n\n{USAGE}");
        return 2;
    }
    let o = match parse_args(&args[1..]) {
        Ok(o) => o,
        Err(e) => {
            eprintln!("{ADVISORY}\n\nerror: {e}\n\n{USAGE}");
            return 2;
        }
    };
    let raw = match std::fs::read(&o.input) {
        Ok(t) => t,
        Err(e) => {
            eprintln!("{ADVISORY}\n\nerror: cannot read {}: {e}", o.input);
            return 2;
        }
    };
    let params = VerifyParams {
        label: &o.input,
        format: o.format.as_deref(),
        start_gst: o.start_gst,
        merkle_root: o.merkle_root,
        keys: o.keys.clone(),
        reference: o.reference,
        max_err: o.max_err,
    };
    let a = match analyse(raw, &params) {
        Ok(a) => a,
        Err(e) => {
            eprintln!("{ADVISORY}\n\nerror: {e}");
            return 2;
        }
    };
    if o.json {
        match serde_json::to_string_pretty(&report_json(&a, &params)) {
            Ok(s) => println!("{s}"),
            Err(e) => {
                eprintln!("{ADVISORY}\n\nerror: {e}");
                return 2;
            }
        }
    } else {
        print_text(&a, &o);
    }
    if a.any_failed() {
        3
    } else {
        0
    }
}

fn print_text(a: &Analysis, o: &Options) {
    let Analysis {
        pages,
        ubx_stats,
        events,
        tags,
        sats,
        overall,
        nma_status,
        alert,
        counts,
        last_ok,
    } = a;
    let overall = *overall;
    {
        println!("Galileo OSNMA verification\n{ADVISORY}\n");
        println!("input: {} ({} pages)", o.input, pages);
        if let Some(u) = ubx_stats {
            println!(
                "ubx: {} frames; {} I/NAV pages decoded, {} placed in time ({} bad CRC, {} unplaceable, {} time conflicts)",
                u.frames, u.inav_pages, pages, u.bad_crc, u.unstamped, u.time_conflicts
            );
        }
        println!(
            "overall: {}   NMA status: {}",
            status_word(overall),
            nma_status
        );
        if *alert {
            println!("ALERT: a verified OSNMA alert message was received. Stop using OSNMA data; nothing is reported as authenticated.");
        }
        match o.reference {
            None => println!(
                "freshness: NOT enforced. No reference time was given, so sub-frame times are taken from the input and a replay of old data would authenticate."
            ),
            Some(r) => {
                let set_aside = events
                    .iter()
                    .filter(|e| matches!(e, Event::TimeRejected { .. }))
                    .count();
                println!(
                    "freshness: sub-frames within {} s of the reference time {} are used; {set_aside} were set aside. A reference time is a single instant.",
                    o.max_err.unwrap_or(29),
                    input::label(r)
                );
            }
        }
        let mut kinds: BTreeMap<String, u32> = BTreeMap::new();
        for e in events {
            let j = event_json(e);
            *kinds
                .entry(j["kind"].as_str().unwrap_or("?").to_string())
                .or_default() += 1;
        }
        for (k, n) in &kinds {
            println!("  {k}: {n}");
        }
        println!("\nsatellite  status          authenticated  failed  pending  discarded  last authenticated");
        for (s, st) in sats {
            let prn: u8 = s[1..].parse().unwrap_or(0);
            let c = counts.get(&prn);
            let last = last_ok
                .get(&prn)
                .map(|g| input::label(*g))
                .unwrap_or_else(|| "-".into());
            println!(
                "{s:<10} {:<15} {:>13}  {:>6}  {:>7}  {:>9}  {last}",
                status_word(*st),
                c.map_or(0, |c| c.authenticated),
                c.map_or(0, |c| c.failed),
                c.map_or(0, |c| c.pending),
                c.map_or(0, |c| c.discarded),
            );
        }
        if o.epochs {
            println!("\nepoch (tag sub-frame)      tx   data  adkd  ctr  result");
            for t in tags {
                println!(
                    "{:<26} E{:02}  E{:02}  {:>4}  {:>3}  {}",
                    input::label(t.tag_gst),
                    t.prna,
                    t.prnd,
                    t.adkd,
                    t.ctr,
                    name(&t.status)
                );
            }
        }
        println!("\n{}", super::pksos_sentence(overall, sats));
    }
}