-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathcheck-results
More file actions
executable file
·923 lines (863 loc) · 40.5 KB
/
Copy pathcheck-results
File metadata and controls
executable file
·923 lines (863 loc) · 40.5 KB
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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
#!/bin/sh
# This file is part of KASLD - https://github.com/bcoles/kasld
#
# Validate KASLD results against ground truth available to root.
#
# Reads tagged lines from a file or standard input and compares each result
# against /proc/kallsyms, /proc/iomem, /proc/modules, and /proc/kcore
# (direct-map base / page_offset_base).
#
# It never runs kasld. Only this script needs root, for the unmasked ground
# truth; kasld itself runs unprivileged and its output is piped or saved. That
# separation is the point -- nothing here elevates the analysis, so the
# KASLD_* environment (see kasld(1) ENVIRONMENT) is never read at root.
#
# Wire format (see src/include/kasld/api.h):
# <type> <region>[:<name>] pos=<pos> conf=<conf> \
# [lo=<hex>] [hi=<hex>|sz=<hex>] [sample=<hex>] [base_align=<hex>]
#
# type: P (physical), V (virtual), S (scalar-fact), R (disposition)
# region: closed enum (kernel_text, kernel_data, kernel_bss,
# kernel_image, module, module_band, ram, dma, dma32,
# initrd, cmdline, cmdline_memmap, reserved_mem, swiotlb,
# vmcoreinfo, crashkernel, pmem, acpi_table, acpi_nvs,
# efi_memmap, numa_node, mmio, pci_mmio, directmap,
# virt_page_offset, vmalloc, vmemmap).
#
# Usage:
# validate saved tagged lines from file:
# sudo ./extra/check-results results.txt
# validate from stdin pipe:
# ./build/*/kasld -v 2>&1 | sudo ./extra/check-results
# ./build/*/components/proc_kallsyms 2>&1 | sudo ./extra/check-results -
#
# Requires: root (for unhashed /proc/kallsyms and /proc/iomem)
# ---
# <bcoles@gmail.com>
set -e
# -------------------------------------------------------------------------
# Colors (disable if not a terminal)
# -------------------------------------------------------------------------
if [ -t 1 ]; then
GREEN=$(printf '\033[0;32m')
RED=$(printf '\033[0;31m')
YELLOW=$(printf '\033[0;33m')
BOLD=$(printf '\033[1m')
RESET=$(printf '\033[0m')
else
GREEN='' RED='' YELLOW='' BOLD='' RESET=''
fi
# Counters — written to a temp file so the subshell pipeline can update them
tmp_counts=$(mktemp)
printf '0 0 0\n' > "$tmp_counts"
trap 'rm -f "$tmp_counts"' EXIT INT TERM
update_counts() {
read -r p f s < "$tmp_counts"
case "$1" in
pass) p=$((p + 1)) ;;
fail) f=$((f + 1)) ;;
skip) s=$((s + 1)) ;;
esac
printf '%d %d %d\n' "$p" "$f" "$s" > "$tmp_counts"
}
pass() { update_counts pass; printf " ${GREEN}PASS${RESET} %s\n" "$1"; }
fail() { update_counts fail; printf " ${RED}FAIL${RESET} %s\n" "$1"; }
skip() { update_counts skip; printf " ${YELLOW}SKIP${RESET} %s\n" "$1"; }
# -------------------------------------------------------------------------
# Hex address comparison helpers (POSIX-safe, unsigned 64-bit)
#
# All addresses are normalized to 16-char zero-padded lowercase hex.
# Comparisons force a string compare by prefixing both operands with "x", so
# awk does not parse hex containing 'e'/'d' as scientific notation (e.g.
# "000000002e133000"). With equal-length lowercase hex, lexicographic order is
# unsigned numeric order ('0'..'9' < 'a'..'f' in ASCII).
# -------------------------------------------------------------------------
# Normalize a hex string (with or without 0x prefix) to 16-char lowercase
#
# @arith-validator — one of four guarding the same property across two scripts:
# numeric() and hex16() here, is_hex() and is_dec() in extra/ksymoff. They are
# duplicated because neither script can source a library (ksymoff installs to
# $PREFIX/bin; this one is copied to a target), so a correction to one does NOT
# reach the others -- review all four together. They accept different sets on
# purpose; what none of them may do is accept a shell metacharacter, which
# tests/check-validators asserts against a shared adversarial corpus.
hex16() {
# SECURITY: reject non-hex input up front so the reformatted value can never
# carry shell/arithmetic metacharacters into a later `$(( 0x... ))` — the same
# class numeric() guards. Callers today pass only /proc-sourced hex; this keeps
# hex16 self-contained. A rejected value yields empty output (treated as absent).
printf '%s' "$1" | grep -qiE '^(0x)?[0-9a-f]+$' || return 0
printf '%s' "$1" | tr 'A-F' 'a-f' | sed 's/^0x//; s/^0*//' | \
awk '{ printf "%016s\n", $0 }' | tr ' ' '0'
}
# hex_le A B → return 0 (true) if A <= B
hex_le() { awk -v a="x$1" -v b="x$2" 'BEGIN { exit !(a <= b) }'; }
# hex_ge A B → return 0 (true) if A >= B
hex_ge() { awk -v a="x$1" -v b="x$2" 'BEGIN { exit !(a >= b) }'; }
# hex_in_range ADDR LO HI → return 0 (true) if LO <= ADDR <= HI
hex_in_range() { hex_ge "$1" "$2" && hex_le "$1" "$3"; }
# covered_by_merged RLO RHI (merged disjoint runs "lo hi\n..." on stdin)
# → return 0 (true) if some single run contains [RLO, RHI]. Inputs are decimal
# integers; addresses fit in awk's exact-integer range (< 2^53). Because the
# runs are merged-maximal and disjoint, [RLO,RHI] lies in the union if one run
# contains it — a span crossing two runs has a real gap between them.
covered_by_merged() {
awk -v rlo="$1" -v rhi="$2" '$1 <= rlo && $2 >= rhi { f = 1 } END { exit !f }'
}
# Extract the value of a `key=value` token from a tagged line.
# Usage: get_field LINE KEY → echoes VALUE (without 0x), empty if absent.
get_field() {
printf '%s' "$1" | tr ' ' '\n' | \
awk -F= -v k="$2" '$1 == k { print $2; exit }'
}
# Echo $1 if it is an integer literal — hex (optional 0x prefix) or decimal —
# else echo nothing. SECURITY: this tool can run as root over untrusted input
# (`sudo check-results results.txt`, `<component> | sudo check-results -`), and
# bash arithmetic `$(( x ))` evaluates embedded command substitutions / array
# subscripts. A value like `a[$(cmd)]` from a `lo=`/`hi=`/`value=` field would
# run `cmd` as root. So EVERY value that reaches `$(( ))` must pass through
# numeric() first; anything with a non-[0-9a-fx] character is rejected to empty
# (treated as an absent field by the callers' existing `[ -n ]` checks).
# @arith-validator — see the note on hex16() above; all four are reviewed
# together.
numeric() {
printf '%s' "$1" | grep -qiE '^(0x)?[0-9a-f]+$' && printf '%s' "$1"
return 0 # never fail the substitution (a rejected value is just empty output)
}
# Validate a resolved image-base window (the rendered "guaranteed" row) against
# ground truth: the real _text base must fall inside it. Catches over-narrowing
# in the engine's resolution that no single leaked result reveals -- including
# resolution over the live-only leaks (perf, prefetch, side channels) that an
# offline replay cannot exercise.
# Usage: validate_inferred LABEL TRUTH16 RENDERED_LINE
validate_inferred() {
_label="$1"; _truth="$2"; _line="$3"
# No window to check: the base was leaked or pinned outright, so nothing was
# rendered to validate. Reported as a skip like every other inapplicable
# check, and with an explicit status -- a bare `return` here carries the
# status of the failed test above it, which under `set -e` ends the run at the
# call site and takes the remaining checks and the summary with it.
[ -n "$_line" ] || {
skip "$_label — window not rendered (base leaked/pinned)"
return 0
}
if [ -z "$_truth" ]; then
skip "$_label — no ground truth"
return
fi
_rlo=$(printf '%s' "$_line" | grep -oE '0x[0-9a-fA-F]+' | sed -n '1p')
_rhi=$(printf '%s' "$_line" | grep -oE '0x[0-9a-fA-F]+' | sed -n '2p')
if [ -z "$_rlo" ] || [ -z "$_rhi" ]; then
skip "$_label — unparsable range"
return
fi
_rlo=$(hex16 "$_rlo"); _rhi=$(hex16 "$_rhi")
if hex_in_range "$_truth" "$_rlo" "$_rhi"; then
pass "$_label — real base 0x$_truth within inferred [0x$_rlo - 0x$_rhi]"
else
fail "$_label — real base 0x$_truth NOT in inferred [0x$_rlo - 0x$_rhi]"
fi
}
# -------------------------------------------------------------------------
# Root check
# -------------------------------------------------------------------------
if [ "$(id -u)" -ne 0 ]; then
echo "error: must be run as root for ground truth from /proc/kallsyms and /proc/iomem" >&2
exit 1
fi
# -------------------------------------------------------------------------
# Collect tagged lines
# -------------------------------------------------------------------------
if [ "$1" = "-" ] || { [ -z "$1" ] && [ ! -t 0 ]; }; then
# Read from stdin (explicit '-' or piped input with no argument)
tagged_lines=$(cat)
elif [ -n "$1" ] && [ -f "$1" ]; then
# Read from file
tagged_lines=$(cat "$1")
else
echo "usage: $0 [results.txt|-]" >&2
echo " pipe kasld output: ./build/*/kasld -v 2>&1 | sudo $0" >&2
exit 1
fi
# SECURITY: strip C0 control characters and DEL before any value is extracted.
# Every field printed below comes from this input; the input is untrusted (its
# natural source is the machine under assessment); and this script runs as root.
# An escape sequence reaching the terminal can move the cursor, erase the line
# just written and redraw it, so a FAIL can be made to read as a PASS by the
# very report meant to expose it. Newline and tab are kept -- they separate
# records and fields. Bytes >= 0x80 are kept too: they carry UTF-8, and deleting
# them would corrupt text rather than protect anything.
# @ctrl-filter -- the same property is asserted for extra/ksymoff, which strips
# control characters from its file-derived fields; review the two together.
raw_input=$(printf '%s\n' "$tagged_lines" | tr -d '\000-\010\013-\037\177')
# Filter to tagged lines only (drops `[infer]`, `[parser]`, banner, etc.)
# raw_input is the full input, incl. the rendered summary lines.
tagged_lines=$(printf '%s\n' "$raw_input" | grep '^[VPS] ' || true)
if [ -z "$tagged_lines" ]; then
echo "error: no tagged lines found" >&2
exit 1
fi
num_lines=$(printf '%s\n' "$tagged_lines" | wc -l)
printf '%sValidating %d tagged results...%s\n' "$BOLD" "$num_lines" "$RESET"
echo
# -------------------------------------------------------------------------
# Extract ground truth from /proc/kallsyms
# -------------------------------------------------------------------------
truth_text=$(awk '$3 == "_text" { print $1 }' /proc/kallsyms 2>/dev/null)
truth_stext=$(awk '$3 == "_stext" { print $1 }' /proc/kallsyms 2>/dev/null)
truth_etext=$(awk '$3 == "_etext" { print $1 }' /proc/kallsyms 2>/dev/null)
truth_sdata=$(awk '$3 == "_sdata" { print $1 }' /proc/kallsyms 2>/dev/null)
# Check for zeroed-out symbols (kptr_restrict=2 or similar)
case "$truth_stext" in
0000000000000000|00000000)
echo "warning: /proc/kallsyms symbols are zeroed (kptr_restrict?)" >&2
truth_text="" truth_stext="" ;;
esac
# Normalize to 16-char hex
if [ -n "$truth_text" ]; then truth_text=$(hex16 "$truth_text"); fi
if [ -n "$truth_stext" ]; then truth_stext=$(hex16 "$truth_stext"); fi
if [ -n "$truth_etext" ]; then truth_etext=$(hex16 "$truth_etext"); fi
if [ -n "$truth_sdata" ]; then truth_sdata=$(hex16 "$truth_sdata"); fi
# BSS boundaries
truth_bss_start=$(awk '$3 == "__bss_start" { print $1 }' /proc/kallsyms 2>/dev/null)
truth_end=$(awk '$3 == "_end" { print $1 }' /proc/kallsyms 2>/dev/null)
case "$truth_bss_start" in
0000000000000000|00000000) truth_bss_start="" ;;
esac
if [ -n "$truth_bss_start" ]; then truth_bss_start=$(hex16 "$truth_bss_start"); fi
if [ -n "$truth_end" ]; then truth_end=$(hex16 "$truth_end"); fi
# Module address range from /proc/modules
truth_mod_lo=""
truth_mod_hi=""
if [ -r /proc/modules ]; then
# Format: name size refcount deps state addr [taint]
# Field 6 is the address; $NF may be taint flags like (OE)
mod_addrs=$(awk '$6 ~ /^0x/ { print $6 }' /proc/modules 2>/dev/null | \
sed 's/^0x//' | tr 'A-F' 'a-f' | sort)
if [ -n "$mod_addrs" ]; then
truth_mod_lo=$(hex16 "$(printf '%s\n' "$mod_addrs" | head -1)")
truth_mod_hi=$(hex16 "$(printf '%s\n' "$mod_addrs" | tail -1)")
fi
fi
# -------------------------------------------------------------------------
# Extract ground truth from /proc/iomem
# -------------------------------------------------------------------------
extract_iomem_range() {
# Usage: extract_iomem_range "pattern" → sets _range_lo and _range_hi
_line=$(grep "$1" /proc/iomem 2>/dev/null | head -1)
if [ -n "$_line" ]; then
_range_lo=$(hex16 "$(printf '%s' "$_line" | sed 's/^ *//' | cut -d'-' -f1 | tr -d ' ')")
_range_hi=$(hex16 "$(printf '%s' "$_line" | sed 's/^ *//' | cut -d'-' -f2 | cut -d' ' -f1 | tr -d ' ')")
else
_range_lo=""
_range_hi=""
fi
}
# Kernel code physical range
extract_iomem_range 'Kernel code'
truth_ptext_lo="$_range_lo"
truth_ptext_hi="$_range_hi"
# Kernel data / bss physical ranges (from /proc/iomem, when present)
extract_iomem_range 'Kernel data'
truth_pdata_lo="$_range_lo"
truth_pdata_hi="$_range_hi"
extract_iomem_range 'Kernel bss'
truth_pbss_lo="$_range_lo"
truth_pbss_hi="$_range_hi"
# Direct-map base (page_offset_base) from /proc/kcore. Each direct-map LOAD
# segment maps physical RAM at a fixed virtual offset, so VirtAddr - PhysAddr ==
# page_offset_base for all of them. Take that offset (the value >= 2 direct-map
# segments agree on) as ground truth. Portable 64-bit hex subtract via 32-bit
# hi/lo halves (no gawk strtonum); the band excludes kernel text and vmalloc/
# vmemmap. Empty when readelf or /proc/kcore is unavailable.
truth_page_offset=""
if command -v readelf >/dev/null 2>&1 && [ -r /proc/kcore ]; then
truth_page_offset=$(readelf -lW /proc/kcore 2>/dev/null | awk '
function h2n(s, n,i){ n=0; s=tolower(s); sub(/^0x/,"",s);
for(i=1;i<=length(s);i++) n=n*16+index("0123456789abcdef",substr(s,i,1))-1;
return n }
$1=="LOAD" {
v=$3; p=$4; sub(/^0x/,"",v); sub(/^0x/,"",p);
while(length(v)<16) v="0" v; while(length(p)<16) p="0" p;
ph=h2n(substr(p,1,8)); pl=h2n(substr(p,9,8));
if (ph==0 && pl==0) next; # not physical-backed
vh=h2n(substr(v,1,8)); vl=h2n(substr(v,9,8));
if (vh < h2n("ffff8880") || vh >= h2n("ffffc880")) next; # direct-map band only
lo=vl-pl; hi=vh-ph; if(lo<0){lo+=4294967296; hi-=1}
off=sprintf("%08x%08x", hi, lo);
cnt[off]++; if(cnt[off]>best){best=cnt[off]; mode=off}
}
END{ if(best>=2) print mode }')
fi
# System RAM: first range start, last range end
truth_ram_lo=""
truth_ram_hi=""
iomem_ram=$(grep 'System RAM' /proc/iomem 2>/dev/null || true)
if [ -n "$iomem_ram" ]; then
first_ram=$(printf '%s\n' "$iomem_ram" | head -1)
last_ram=$(printf '%s\n' "$iomem_ram" | tail -1)
truth_ram_lo=$(hex16 "$(printf '%s' "$first_ram" | sed 's/^ *//' | cut -d'-' -f1 | tr -d ' ')")
truth_ram_hi=$(hex16 "$(printf '%s' "$last_ram" | sed 's/^ *//' | cut -d'-' -f2 | cut -d' ' -f1 | tr -d ' ')")
fi
# Hotplug memory-block size. sysfs_memory_blocks reports RAM at this
# granularity, so its highest online block legitimately rounds the RAM top up to
# the next block boundary — which sits above the fine-grained /proc/iomem top.
# block_ram_ceiling is that boundary; a P ram address between truth_ram_hi and
# it is block-rounded (sound), anything beyond is a genuine out-of-RAM leak.
block_ram_ceiling=""
if [ -n "$truth_ram_hi" ]; then
_bs=$(numeric "$(tr -d ' \n' < /sys/devices/system/memory/block_size_bytes 2>/dev/null || true)")
if [ -n "$_bs" ] && [ "0x$_bs" != "0x0" ]; then
_bc=$(( ( (0x$truth_ram_hi / 0x$_bs) + 1 ) * 0x$_bs - 1 ))
block_ram_ceiling=$(hex16 "$(printf '%x' "$_bc")")
fi
fi
# -------------------------------------------------------------------------
# Scalar-fact ground truth (for the S <fact> validators below). Each source is
# root-cheap and arch-portable: absent fields leave the truth empty, and the
# validator SKIPs rather than fails. These facts now drive the inference
# (phys_addr_bits -> phys_bits_ceiling, phys_memtotal -> ceiling, virt_addr_bits
# / page_size -> paging level), so a wrong leak silently mis-bounds the window.
# -------------------------------------------------------------------------
# CPU address sizes (x86: "address sizes : N bits physical, M bits virtual").
gt_phys_bits=""
gt_virt_bits=""
_as=$(grep -m1 'address sizes' /proc/cpuinfo 2>/dev/null || true)
if [ -n "$_as" ]; then
gt_phys_bits=$(printf '%s' "$_as" | sed -n 's/.*: *\([0-9]\{1,\}\) bits physical.*/\1/p')
gt_virt_bits=$(printf '%s' "$_as" | sed -n 's/.*physical, *\([0-9]\{1,\}\) bits virtual.*/\1/p')
fi
# Page size (universal).
gt_page_size=$(getconf PAGESIZE 2>/dev/null || getconf PAGE_SIZE 2>/dev/null || true)
# EFI presence.
if [ -d /sys/firmware/efi ]; then gt_efi=1; else gt_efi=0; fi
# -------------------------------------------------------------------------
# Print ground truth
# -------------------------------------------------------------------------
printf '%sGround truth:%s\n' "$BOLD" "$RESET"
# 29-char left column = longest label (__bss_start (V kernel_bss):, 27 chars)
# + 2 trailing spaces of breathing room. Keeps the address column aligned.
gt_label_w=29
if [ -n "$truth_stext" ]; then
printf " %-*s 0x%s\n" "$gt_label_w" "_stext (V kernel_text):" "$truth_stext"
else
printf " %-*s (unavailable)\n" "$gt_label_w" "_stext (V kernel_text):"
fi
if [ -n "$truth_etext" ]; then
printf " %-*s 0x%s\n" "$gt_label_w" "_etext (V text end):" "$truth_etext"
fi
if [ -n "$truth_sdata" ]; then
printf " %-*s 0x%s\n" "$gt_label_w" "_sdata (V kernel_data):" "$truth_sdata"
fi
if [ -n "$truth_bss_start" ]; then
printf " %-*s 0x%s\n" "$gt_label_w" "__bss_start (V kernel_bss):" "$truth_bss_start"
fi
if [ -n "$truth_end" ]; then
printf " %-*s 0x%s\n" "$gt_label_w" "_end:" "$truth_end"
fi
if [ -n "$truth_mod_lo" ]; then
printf " %-*s 0x%s\n" "$gt_label_w" "module lo:" "$truth_mod_lo"
printf " %-*s 0x%s\n" "$gt_label_w" "module hi:" "$truth_mod_hi"
fi
if [ -n "$truth_ptext_lo" ]; then
printf " %-*s 0x%s - 0x%s\n" "$gt_label_w" "Kernel code (P):" "$truth_ptext_lo" "$truth_ptext_hi"
fi
if [ -n "$truth_page_offset" ]; then
printf " %-*s 0x%s\n" "$gt_label_w" "page_offset_base:" "$truth_page_offset"
fi
if [ -n "$truth_pdata_lo" ]; then
printf " %-*s 0x%s - 0x%s\n" "$gt_label_w" "Kernel data (P):" "$truth_pdata_lo" "$truth_pdata_hi"
fi
if [ -n "$truth_pbss_lo" ]; then
printf " %-*s 0x%s - 0x%s\n" "$gt_label_w" "Kernel bss (P):" "$truth_pbss_lo" "$truth_pbss_hi"
fi
if [ -n "$truth_ram_lo" ]; then
printf " %-*s 0x%s - 0x%s\n" "$gt_label_w" "System RAM (P):" "$truth_ram_lo" "$truth_ram_hi"
fi
echo
# -------------------------------------------------------------------------
# Validate each tagged line
# -------------------------------------------------------------------------
printf '%sResults:%s\n' "$BOLD" "$RESET"
printf '%s\n' "$tagged_lines" | while IFS= read -r line; do
type=$(printf '%s' "$line" | awk '{ print $1 }')
region_name=$(printf '%s' "$line" | awk '{ print $2 }')
# Scalar facts (S <fact> ... value=<hex>): validate where ground truth exists.
# A kernel image cannot exceed the RAM it lives in, so /proc/iomem's RAM
# ceiling is a reliable plausibility bound for image_size.
if [ "$type" = "S" ]; then
# numeric() both validates (a non-numeric value would make $(( value ))
# error under set -e — or inject, as this can run as root) and gates the
# arithmetic below; a malformed or absent value collapses to empty here.
value=$(numeric "$(get_field "$line" value)")
if [ -z "$value" ]; then
skip "S $region_name — no/invalid value field"
continue
fi
case "$region_name" in
image_size_min|image_size_max)
# A kernel image (or its init region) cannot exceed the RAM it lives in.
if [ "$value" = "0x0" ] || [ "$value" = "0" ]; then
skip "S $region_name — zero"
elif [ -z "$truth_ram_hi" ]; then
skip "S $region_name=$value — no /proc/iomem System RAM ground truth"
elif hex_le "$(hex16 "$value")" "$truth_ram_hi"; then
pass "S $region_name=$value — within RAM (top 0x$truth_ram_hi)"
else
fail "S $region_name=$value — exceeds all RAM (top 0x$truth_ram_hi); bogus"
fi
;;
phys_addr_bits)
if [ -z "$gt_phys_bits" ]; then
skip "S phys_addr_bits=$value — no cpuinfo 'address sizes' ground truth"
elif [ "$(( value ))" = "$gt_phys_bits" ]; then
pass "S phys_addr_bits=$value — matches cpuinfo ($gt_phys_bits bits physical)"
else
fail "S phys_addr_bits=$value ($(( value ))) — cpuinfo says $gt_phys_bits bits physical"
fi
;;
virt_addr_bits)
if [ -z "$gt_virt_bits" ]; then
skip "S virt_addr_bits=$value — no cpuinfo 'address sizes' ground truth"
elif [ "$(( value ))" = "$gt_virt_bits" ]; then
pass "S virt_addr_bits=$value — matches cpuinfo ($gt_virt_bits bits virtual)"
else
fail "S virt_addr_bits=$value ($(( value ))) — cpuinfo says $gt_virt_bits bits virtual"
fi
;;
page_size)
if [ -z "$gt_page_size" ]; then
skip "S page_size=$value — getconf unavailable"
elif [ "$(( value ))" = "$gt_page_size" ]; then
pass "S page_size=$value — matches getconf PAGESIZE ($gt_page_size)"
else
fail "S page_size=$value ($(( value ))) — getconf PAGESIZE is $gt_page_size"
fi
;;
efi_present)
if [ "$(( value ))" = "$gt_efi" ]; then
pass "S efi_present=$value — matches /sys/firmware/efi presence ($gt_efi)"
else
fail "S efi_present=$value — /sys/firmware/efi presence is $gt_efi"
fi
;;
phys_max_pfn)
if [ -z "$truth_ram_hi" ]; then
skip "S phys_max_pfn=$value — no /proc/iomem System RAM"
else
_pfn_ram=$(( (0x$truth_ram_hi + 1) >> 12 ))
if [ "$(( value ))" = "$_pfn_ram" ]; then
pass "S phys_max_pfn=$value — matches RAM-top PFN"
elif [ "$(( value ))" -ge "$_pfn_ram" ]; then
pass "S phys_max_pfn=$value — at/above RAM-top PFN (reserved above RAM)"
else
fail "S phys_max_pfn=$value — below RAM-top PFN (0x$(printf '%x' "$_pfn_ram")); under-counts RAM"
fi
fi
;;
phys_memtotal)
if [ -z "$truth_ram_lo" ]; then
skip "S phys_memtotal=$value — no /proc/iomem System RAM"
else
# Usable RAM cannot exceed the physical RAM span (a too-LOW value only
# under-bounds the ceiling, which is conservative — so bound above only).
_ramspan=$(( 0x$truth_ram_hi - 0x$truth_ram_lo + 1 ))
if [ "$(( value ))" -le "$_ramspan" ]; then
pass "S phys_memtotal=$value — within physical RAM span"
else
fail "S phys_memtotal=$value — exceeds physical RAM span (0x$(printf '%x' "$_ramspan"))"
fi
fi
;;
virt_page_offset)
# The exact left edge of the linear map. Whatever emits this pins
# PAGE_OFFSET outright rather than bounding it, so a wrong value
# mis-places the direct map and, on the architectures where text rides
# in it, kernel text with it. Ground truth is the same page_offset_base,
# derived here from /proc/kcore by this script's own reader — so the
# comparison is between two independent parses of the same bytes.
if [ -z "$truth_page_offset" ]; then
skip "S virt_page_offset=$value — no /proc/kcore page_offset_base"
elif [ "$(hex16 "$value")" = "$truth_page_offset" ]; then
pass "S virt_page_offset=$value — matches /proc/kcore page_offset_base"
else
fail "S virt_page_offset=$value — != page_offset_base 0x$truth_page_offset (/proc/kcore)"
fi
;;
physical_start)
# The real phys base sits at physical_start + KASLR offset, so the
# configured minimum start can never exceed the real base.
if [ -z "$truth_ptext_lo" ]; then
skip "S physical_start=$value — no /proc/iomem Kernel code base"
elif hex_le "$(hex16 "$value")" "$truth_ptext_lo"; then
pass "S physical_start=$value — at/below real phys base (0x$truth_ptext_lo)"
else
fail "S physical_start=$value — above real phys base (0x$truth_ptext_lo)"
fi
;;
phys_kernel_align)
# The real phys base must be a multiple of the KASLR physical alignment.
if [ -z "$truth_ptext_lo" ]; then
skip "S phys_kernel_align=$value — no /proc/iomem Kernel code base"
elif [ "$(( value ))" -eq 0 ]; then
skip "S phys_kernel_align=$value — zero"
elif [ "$(( 0x$truth_ptext_lo % value ))" -eq 0 ]; then
pass "S phys_kernel_align=$value — real phys base is $value-aligned"
else
fail "S phys_kernel_align=$value — real phys base 0x$truth_ptext_lo not $value-aligned"
fi
;;
*)
skip "S $region_name=$value — no scalar validator"
;;
esac
continue
fi
# Split region[:name] on the FIRST colon only — names can contain `:`
# (e.g. PCI BDF "0000:00:14.0"). The parser convention is documented in
# src/include/kasld/api.h.
region=${region_name%%:*}
case "$region_name" in
*:*) name=${region_name#*:} ;;
*) name="" ;;
esac
pos=$(get_field "$line" pos)
# numeric() on every extracted field: these feed $(( )) (the sz→hi path) and
# hex16; a non-numeric field collapses to empty (treated as absent below).
lo=$(numeric "$(get_field "$line" lo)")
hi=$(numeric "$(get_field "$line" hi)")
sz=$(numeric "$(get_field "$line" sz)")
sample=$(numeric "$(get_field "$line" sample)")
# Derive hi from sz if hi absent (parser does this too, but the wire form
# may carry either spelling). sz arithmetic kept simple: we mostly care
# about hi as a comparison key, not the exact byte.
if [ -n "$sz" ] && [ -z "$hi" ] && [ -n "$lo" ]; then
# printf supports unsigned hex arithmetic via $(( )) on most shells
hi_dec=$(( 0x$lo + 0x$sz - 1 ))
hi=$(printf '%x' "$hi_dec")
fi
# Normalize to 16-char hex
[ -n "$lo" ] && lo=$(hex16 "$lo")
[ -n "$hi" ] && hi=$(hex16 "$hi")
[ -n "$sample" ] && sample=$(hex16 "$sample")
# Pick a representative anchor address. Mirrors anchor_addr() in
# src/include/kasld/internal.h: prefer lo when pos=base, else sample,
# else any set bound.
addr=""
if [ "$pos" = "base" ] && [ -n "$lo" ]; then
addr="$lo"
elif [ -n "$sample" ]; then
addr="$sample"
elif [ -n "$lo" ]; then
addr="$lo"
elif [ -n "$hi" ]; then
addr="$hi"
fi
if [ -z "$addr" ]; then
skip "${type} ${region_name} pos=${pos} — no address fields"
continue
fi
if [ -n "$name" ]; then
desc="${type} ${region}:${name} (anchor 0x${addr})"
else
desc="${type} ${region} (anchor 0x${addr})"
fi
case "${type} ${region}" in
# ---- Virtual: kernel image regions ---------------------------------
"V kernel_text"|"V kernel_image")
if [ -z "$truth_stext" ]; then
skip "$desc — no _stext ground truth"
continue
fi
if [ "$addr" = "$truth_stext" ]; then
pass "$desc — exact _stext match"
elif [ -n "$truth_end" ] && hex_in_range "$addr" "$truth_stext" "$truth_end"; then
pass "$desc — within kernel image"
elif [ -n "$truth_etext" ] && hex_in_range "$addr" "$truth_stext" "$truth_etext"; then
pass "$desc — within text section"
else
fail "$desc — expected near 0x${truth_stext}"
fi
;;
"V kernel_data")
if [ -z "$truth_sdata" ]; then
skip "$desc — no _sdata ground truth"
continue
fi
if hex_ge "$addr" "$truth_sdata"; then
pass "$desc — at or above _sdata"
elif [ -n "$truth_stext" ] && hex_ge "$addr" "$truth_stext"; then
pass "$desc — within kernel image"
else
fail "$desc — below _stext"
fi
;;
"V kernel_bss")
if [ -z "$truth_bss_start" ]; then
skip "$desc — no __bss_start ground truth"
continue
fi
if [ -n "$truth_end" ] && hex_in_range "$addr" "$truth_bss_start" "$truth_end"; then
pass "$desc — within BSS section"
elif hex_ge "$addr" "$truth_bss_start"; then
pass "$desc — at or above __bss_start"
else
fail "$desc — expected >= 0x${truth_bss_start}"
fi
;;
# ---- Virtual: modules ----------------------------------------------
"V module"|"V module_band")
if [ -z "$truth_mod_lo" ]; then
skip "$desc — no modules loaded"
continue
fi
if hex_in_range "$addr" "$truth_mod_lo" "$truth_mod_hi"; then
pass "$desc — within module range"
else
fail "$desc — outside module range [0x${truth_mod_lo}, 0x${truth_mod_hi}]"
fi
;;
# ---- Virtual: direct map (page_offset_base + interior leaks) --------
"V directmap")
# Ground truth: page_offset_base from /proc/kcore direct-map segments.
# pos matters: a pos=base result IS page_offset_base and must match it
# exactly (catches a confident-but-wrong base like a mitigated CPU's sparse
# edge that a non-zero check passes); an interior/top/extent result is a
# leaked address INSIDE the direct map, which cannot be below the map's
# floor (page_offset_base) but is not expected to equal it.
if [ -z "$truth_page_offset" ]; then
if [ "$addr" != "0000000000000000" ]; then
skip "$desc — non-zero, but no /proc/kcore ground truth (readelf/kcore?)"
else
fail "$desc — zero address"
fi
elif [ "$pos" = "base" ]; then
if [ "$addr" = "$truth_page_offset" ]; then
pass "$desc — matches /proc/kcore page_offset_base"
else
fail "$desc — base 0x$addr != page_offset_base 0x$truth_page_offset (/proc/kcore)"
fi
elif hex_ge "$addr" "$truth_page_offset"; then
pass "$desc — within direct map (>= page_offset_base 0x$truth_page_offset)"
else
fail "$desc — 0x$addr below page_offset_base 0x$truth_page_offset (/proc/kcore)"
fi
;;
# ---- Virtual: vmalloc / vmemmap -----------------------------------
"V vmalloc"|"V vmemmap")
# Just sanity-check it's a non-zero kernel-space address. /proc/vmallocinfo
# could give a tighter ground truth for vmalloc but it's gated by
# kptr_restrict and not always populated.
if [ "$addr" != "0000000000000000" ]; then
pass "$desc — non-zero kernel address"
else
fail "$desc — zero address"
fi
;;
"V virt_page_offset")
# The region names PAGE_OFFSET itself, so page_offset_base is the value
# to compare against. What the record claims varies by form, and the
# check follows it rather than assuming the tightest one:
# both edges a window PAGE_OFFSET lies in -> truth must fall inside it
# base only the base itself -> exact match
# otherwise an address in the linear map -> truth is at or below it,
# which also holds if the record turns out to be the base
if [ -z "$truth_page_offset" ]; then
skip "$desc — no /proc/kcore page_offset_base"
elif [ -n "$hi" ]; then
if hex_in_range "$truth_page_offset" "$addr" "$hi"; then
pass "$desc — page_offset_base 0x$truth_page_offset within [0x$addr - 0x$hi]"
else
fail "$desc — page_offset_base 0x$truth_page_offset outside [0x$addr - 0x$hi]"
fi
elif [ "$pos" = "base" ]; then
if [ "$addr" = "$truth_page_offset" ]; then
pass "$desc — matches /proc/kcore page_offset_base"
else
fail "$desc — 0x$addr != page_offset_base 0x$truth_page_offset (/proc/kcore)"
fi
elif hex_le "$truth_page_offset" "$addr"; then
pass "$desc — at/above page_offset_base 0x$truth_page_offset"
else
fail "$desc — 0x$addr below page_offset_base 0x$truth_page_offset (/proc/kcore)"
fi
;;
# ---- Physical: kernel image regions --------------------------------
"P kernel_text"|"P kernel_image")
if [ -z "$truth_ptext_lo" ]; then
skip "$desc — no /proc/iomem Kernel code"
continue
fi
if hex_in_range "$addr" "$truth_ptext_lo" "$truth_ptext_hi"; then
pass "$desc — within Kernel code phys range"
elif [ -n "$truth_ram_lo" ] && hex_le "$addr" "$truth_ptext_lo" && \
hex_ge "$addr" "$truth_ram_lo"; then
# Address below Kernel code but within RAM — likely the slot-aligned
# base (text base sits a few bytes below _stext after KASLR alignment).
pass "$desc — aligned base below Kernel code start"
else
fail "$desc — expected range [0x${truth_ptext_lo}, 0x${truth_ptext_hi}]"
fi
;;
"P kernel_data")
if [ -n "$truth_pdata_lo" ] && hex_in_range "$addr" "$truth_pdata_lo" "$truth_pdata_hi"; then
pass "$desc — within Kernel data phys range"
elif [ -n "$truth_ram_lo" ] && hex_in_range "$addr" "$truth_ram_lo" "$truth_ram_hi"; then
pass "$desc — within System RAM"
else
skip "$desc — no Kernel data phys ground truth"
fi
;;
"P kernel_bss")
if [ -n "$truth_pbss_lo" ] && hex_in_range "$addr" "$truth_pbss_lo" "$truth_pbss_hi"; then
pass "$desc — within Kernel bss phys range"
elif [ -n "$truth_ram_lo" ] && hex_in_range "$addr" "$truth_ram_lo" "$truth_ram_hi"; then
pass "$desc — within System RAM"
else
skip "$desc — no Kernel bss phys ground truth"
fi
;;
# ---- Physical: DRAM-resident regions -------------------------------
"P ram"|"P dma"|"P dma32"|"P initrd"|"P cmdline"|"P cmdline_memmap"|\
"P reserved_mem"|"P swiotlb"|"P vmcoreinfo"|"P crashkernel"|"P pmem"|\
"P acpi_table"|"P acpi_nvs"|"P numa_node"|"P efi_memmap")
if [ -z "$truth_ram_lo" ]; then
skip "$desc — no /proc/iomem System RAM"
continue
fi
if hex_in_range "$addr" "$truth_ram_lo" "$truth_ram_hi"; then
pass "$desc — within System RAM"
elif [ "$region" = "ram" ] && [ -n "$block_ram_ceiling" ] && \
hex_ge "$addr" "$truth_ram_hi" && \
hex_le "$addr" "$block_ram_ceiling"; then
# The hotplug-block map (sysfs_memory_blocks) is block-coarse: its top
# online block rounds the RAM top up to the next block boundary, above
# the fine /proc/iomem top. Sound — the extra slice carries no real RAM
# and is never excluded — so accept up to the block boundary.
pass "$desc — block-rounded RAM top (hotplug-block granularity)"
else
# Some regions (efi_memmap, acpi_*) may sit in reserved holes
# outside the System RAM extents. Don't fail those — skip with a
# note so the operator can spot-check.
#
# cmdline_memmap is not a hole but a carve-out: the component emits a
# region only for the memmap= forms that REMOVE address space from RAM
# ($ reserved, ! persistent memory, # ACPI NVS), never for the @ form
# that adds usable RAM. Those intervals name whatever the operator
# asked to reserve, which is routinely outside the RAM extents
# entirely — a ramoops or pmem region above the top of memory.
case "$region" in
efi_memmap|acpi_table|acpi_nvs|reserved_mem|pmem|cmdline_memmap)
skip "$desc — outside System RAM (region may be in reserved hole)"
;;
*)
fail "$desc — outside RAM [0x${truth_ram_lo}, 0x${truth_ram_hi}]"
;;
esac
fi
;;
# ---- Physical: MMIO ------------------------------------------------
"P mmio"|"P pci_mmio")
# No direct ground truth: /proc/iomem entries for PCI BARs need name
# matching against `name` field. We can at least confirm the address
# is NOT within System RAM (MMIO and RAM are disjoint by design).
if [ -z "$truth_ram_lo" ]; then
skip "$desc — no /proc/iomem ground truth"
continue
fi
if hex_in_range "$addr" "$truth_ram_lo" "$truth_ram_hi"; then
# An MMIO address inside System RAM is suspicious — but UIO maps
# can legitimately expose reserved DRAM via sysfs_uio_map, which
# the new classifier should now tag as reserved_mem instead. Skip
# rather than fail to avoid flagging genuine driver-exposed DRAM.
skip "$desc — within RAM (UIO-mapped DRAM exposed as MMIO?)"
else
pass "$desc — outside System RAM (consistent with MMIO)"
fi
;;
# ---- Unmatched -----------------------------------------------------
*)
skip "$desc — no validator for ${type} ${region}"
;;
esac
done
# -------------------------------------------------------------------------
# Validate the engine's RESOLVED image-base windows (rendered summary), not just
# the per-component leaks: the real _text base must fall inside the guaranteed
# window. The window is the image base (_text), so both sides compare _text to
# _text -- virt _text from /proc/kallsyms, phys _text from /proc/iomem "Kernel
# code" (whose start the kernel sets to __pa_symbol(_text)). Comparing _stext
# here would false-fail on arches whose _text->_stext head gap is non-zero.
# The guaranteed row is always rendered by `kasld -v`; piping a single
# component's output has no window, and validate_inferred skips it.
# -------------------------------------------------------------------------
virt_win=$(printf '%s\n' "$raw_input" | grep 'Virtual Image Base' | grep 'guaranteed' | head -1)
phys_win=$(printf '%s\n' "$raw_input" | grep 'Physical Image Base' | grep 'guaranteed' | head -1)
validate_inferred "Resolved virt image-base window" "$truth_text" "$virt_win"
validate_inferred "Resolved phys image-base window" "$truth_ptext_lo" "$phys_win"
# -------------------------------------------------------------------------
# RAM-map coverage. A `pos=extent` line is one member of a COMPLETE single-source
# RAM map (a covering); the gaps between a source's extents are what
# ram_map_phys_exclude carves as non-RAM. So every /proc/iomem System RAM extent
# MUST lie within the union of the coverings — a hole here means a covering map
# is incomplete, which would carve a false non-RAM gap (the failure this whole
# mechanism guards against).
#
# Coverage is one-directional (RAM ⊆ union): coverings may extend ABOVE real RAM
# (the block-coarse hotplug map rounds up) — that only adds slack.
#
# The wire carries no origin, so a full `kasld -v` validates the AGGREGATE map.
# To validate ONE source's completeness, pipe that component alone, e.g.:
# ./build/*/components/firmware_memmap | sudo ./extra/check-results -
# then every pos=extent line belongs to that single origin.
# -------------------------------------------------------------------------
coverings=$(printf '%s\n' "$tagged_lines" | awk '$1 == "P" && $2 == "ram"' \
| grep 'pos=extent' || true)
if [ -z "$coverings" ]; then
: # no covering sources in this input — nothing to check
elif [ -z "$truth_ram_lo" ]; then
skip "RAM coverage — no /proc/iomem System RAM ground truth"
else
# Covering extents as decimal "lo hi", sorted by lo.
cov_intervals=$(printf '%s\n' "$coverings" | while IFS= read -r cl; do
clo=$(numeric "$(get_field "$cl" lo)")
chi=$(numeric "$(get_field "$cl" hi)")
csz=$(numeric "$(get_field "$cl" sz)")
# numeric()-validated and 0x-prefixed, so safe to use directly in $(( )).
[ -n "$clo" ] || continue
if [ -z "$chi" ] && [ -n "$csz" ]; then chi=$(printf '0x%x' $(( clo + csz - 1 ))); fi
[ -n "$chi" ] || continue
printf '%d %d\n' "$(( clo ))" "$(( chi ))"
done | sort -n)
# Merge into disjoint maximal runs (touching/overlapping coalesced).
merged=$(printf '%s\n' "$cov_intervals" | awk '
NR == 1 { lo = $1; hi = $2; next }
{ if ($1 <= hi + 1) { if ($2 > hi) hi = $2 }
else { print lo, hi; lo = $1; hi = $2 } }
END { if (NR > 0) print lo, hi }')
# Each System RAM extent must sit inside one merged covering run.
printf '%s\n' "$iomem_ram" | while IFS= read -r row; do
[ -n "$row" ] || continue
range=$(printf '%s' "$row" | sed 's/^ *//' | awk '{ print $1 }')
rlo_h=$(numeric "$(printf '%s' "$range" | cut -d- -f1)")
rhi_h=$(numeric "$(printf '%s' "$range" | cut -d- -f2)")
if [ -z "$rlo_h" ] || [ -z "$rhi_h" ]; then continue; fi
if printf '%s\n' "$merged" | covered_by_merged "$(( 0x$rlo_h ))" "$(( 0x$rhi_h ))"; then
pass "RAM coverage — System RAM [0x$rlo_h-0x$rhi_h] within covering map"
else
fail "RAM coverage — System RAM [0x$rlo_h-0x$rhi_h] NOT covered (covering map incomplete)"
fi
done
fi
# -------------------------------------------------------------------------
# Summary
# -------------------------------------------------------------------------
echo
read -r pass_count fail_count skip_count < "$tmp_counts"
total=$((pass_count + fail_count + skip_count))
printf '%sSummary: %d passed, %d failed, %d skipped (of %d)%s\n' \
"$BOLD" "$pass_count" "$fail_count" "$skip_count" "$total" "$RESET"
if [ "$fail_count" -gt 0 ]; then
exit 1
fi
exit 0