Lab 2: SD/eMMC Partition-Offset, Sticky Unlink & ustar Rootfs Verifier
Master FHS 3.0 directory roles, VFS hard vs symbolic link semantics, character and block device major:minor nodes, octal permission/umask/sticky invariants, MBR 1 KiB raw IVT boot offsets, removable-disk safety guards, and numeric-owner rootfs tar archives.
Prerequisites in this module
What ./check.sh verifies
- Builds libcore.a and lab_cli cleanly with -std=c11 -Wall -Wextra -Werror.
- Fix compiler warnings or errors in files/core.c.
- Archives core.o into libcore.a and links independent TAP verifier.
- Preserve public declarations in files/core.h so tests.c links.
step 1/15 · inspect starter files and specification
Automated BSP image-creation pipelines must guarantee three non-negotiable safety invariants: never write raw bootloaders onto non-removable host disks or across Partition 1's FAT32 boundary (0x400 + sizeof(u-boot.imx) <= p1_lba * 512), enforce VFS sticky/triad permissions accurately, and ensure staged rootfs tarballs carry clean UID 0:0 --numeric-owner headers.
learner@ksa:~/gl-e00/lab-m02ls -lastarter/Makefilestarter/cli.cstarter/core.cstarter/core.hlearner@ksa:~/gl-e00/lab-m02starter: starter/Makefile
learner@ksa:~/gl-e00/lab-m02$ bat starter/Makefile File: starter/Makefile CC_BIN = gcc AR = ar CFLAGS_ALL = -std=c11 -Wall -Wextra -Werror -O2 LDLIBS = all: libcore.a lab_cli libcore.a: core.o $(AR) rcs $@ $^ lab_cli: cli.o libcore.a $(CC_BIN) $(CFLAGS_ALL) cli.o libcore.a $(LDLIBS) -o $@ %.o: %.c core.h $(CC_BIN) $(CFLAGS_ALL) -c $< -o $@ .PHONY: all clean clean: rm -f core.o cli.o libcore.a lab_clistarter: starter/cli.c
learner@ksa:~/gl-e00/lab-m02$ bat starter/cli.c File: starter/cli.c #define _POSIX_C_SOURCE 200809L #include "core.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> static void make_hdr(unsigned char h[512], unsigned int uid, const char *uname_str) { memset(h, 0, 512); snprintf((char *)(h + 0), 100, "sbin/init"); snprintf((char *)(h + 100), 8, "%07o", 0755U); snprintf((char *)(h + 108), 8, "%07o", uid); snprintf((char *)(h + 116), 8, "%07o", 0U); snprintf((char *)(h + 124), 12, "%011o", 0U); h[156] = '0'; memcpy(h + 257, "ustar", 6); memcpy(h + 263, "00", 2); snprintf((char *)(h + 265), 32, "%s", uname_str); memset(h + 148, ' ', 8); unsigned int sum = 0; for (int i = 0; i < 512; ++i) sum += h[i]; snprintf((char *)(h + 148), 7, "%06o", sum); h[154] = '\0'; h[155] = ' '; } static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a; uint64_t y = *(const uint64_t *)b; return (x > y) - (x < y); } static uint64_t now_ns(void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (uint64_t)ts.tv_sec * 1000000000ULL + (uint64_t)ts.tv_nsec; } static int run_bench(void) { block_dev_info_t sd = {"sdb", 1, 0, 0, 16U}; unsigned char hdr[512]; make_hdr(hdr, 0U, ""); uint64_t samples[40]; volatile int sink = 0; for (int w = 0; w < 5; ++w) { sink += ksa_guard_sdcard_layout(&sd, 650U * 1024U, 2048U); sink += ksa_check_sticky_unlink(01777U, 0U, 0U, 1000U, 1001U, 1001U); sink += ksa_verify_ustar_root(hdr); } for (int s = 0; s < 40; ++s) { uint64_t t0 = now_ns(); for (int it = 0; it < 250; ++it) { sink += ksa_guard_sdcard_layout(&sd, 650U * 1024U, 2048U); sink += ksa_check_sticky_unlink(01777U, 0U, 0U, 1000U, 1001U, 1001U); sink += ksa_verify_ustar_root(hdr); } samples[s] = (now_ns() - t0) / 250ULL; } qsort(samples, 40, sizeof(samples[0]), cmp_u64); printf("BENCH lab_m02_perm_partition_guard clock=CLOCK_MONOTONIC warmup=5 samples=40 " "p50_ns=%llu p95_ns=%llu p99_ns=%llu sink=%d\n", (unsigned long long)samples[20], (unsigned long long)samples[38], (unsigned long long)samples[39], sink); return 0; } int main(int argc, char **argv) { if (argc > 1 && strcmp(argv[1], "--bench") == 0) { return run_bench(); } block_dev_info_t sda = {"sda", 0, 0, 2, 512U}; block_dev_info_t sdb = {"sdb", 1, 0, 0, 16U}; int rc_sda = ksa_guard_sdcard_layout(&sda, 600U * 1024U, 2048U); int rc_sdb = ksa_guard_sdcard_layout(&sdb, 600U * 1024U, 2048U); int rc_ovl = ksa_guard_sdcard_layout(&sdb, 1200U * 1024U, 2048U); int ul_deny = ksa_check_sticky_unlink(01777U, 0U, 0U, 1000U, 1001U, 1001U); int ul_ok = ksa_check_sticky_unlink(01777U, 0U, 0U, 1001U, 1001U, 1001U); unsigned char h_ok[512], h_bad[512]; make_hdr(h_ok, 0U, ""); make_hdr(h_bad, 1000U, "builder"); int t_ok = ksa_verify_ustar_root(h_ok); int t_bad = ksa_verify_ustar_root(h_bad); printf("sdcard_guard: sda_fixed=%d sdb_ok=%d sdb_1200k_overlap=%d\n", rc_sda, rc_sdb, rc_ovl); printf("sticky_unlink: stranger=%d file_owner=%d\n", ul_deny, ul_ok); printf("ustar_verify: numeric_root=%d leaked_uid1000=%d\n", t_ok, t_bad); return (rc_sda == -2 && rc_sdb == 0 && rc_ovl == -7 && ul_deny == 0 && ul_ok == 1 && t_ok == 0 && t_bad == -4) ? 0 : 1; }starter: starter/core.c
learner@ksa:~/gl-e00/lab-m02$ bat starter/core.c File: starter/core.c #define _POSIX_C_SOURCE 200809L #include "core.h" #include <stdlib.h> #include <string.h> int ksa_guard_sdcard_layout(const block_dev_info_t *dev, uint32_t uboot_bytes, uint32_t p1_lba_start) { if (!dev) return -1; if (dev->removable != 1) return -2; /* Reject fixed NVMe/SATA host OS disk */ if (dev->read_only != 0) return -3; /* Hardware write-protect tab active */ if (dev->mounted_partitions > 0) return -4; /* Mounted partition corruption hazard */ if (dev->size_gib == 0U || dev->size_gib > 128U) return -5; if (uboot_bytes == 0U || p1_lba_start < 2048U) return -6; uint64_t uboot_end_byte = (uint64_t)uboot_bytes; /* BUG: forgets 0x400 (1 KiB) IVT offset! */ uint64_t p1_start_byte = (uint64_t)p1_lba_start * 512ULL; if (uboot_end_byte > p1_start_byte) { return -7; /* Raw U-Boot image overlaps Partition 1 FAT32 superblock */ } return 0; } int ksa_check_sticky_unlink(uint32_t dir_mode, uint32_t dir_uid, uint32_t dir_gid, uint32_t file_uid, uint32_t actor_uid, uint32_t actor_gid) { if (actor_uid == 0U) return 1; uint32_t triad = 0U; if (actor_uid == dir_uid) { triad = (dir_mode >> 6) & 7U; } else if (actor_gid == dir_gid) { triad = (dir_mode >> 3) & 7U; } else { triad = dir_mode & 7U; } if ((triad & 03U) != 03U) { return 0; /* Requires both write (02) and search/exec (01) on directory */ } if ((dir_mode & 04000U) != 0U) { /* BUG: checks setuid 04000 instead of sticky 01000! */ if (actor_uid != dir_uid && actor_uid != file_uid) { return 0; } } return 1; } int ksa_verify_ustar_root(const unsigned char hdr[512]) { if (!hdr) return -1; if (memcmp(hdr + 257, "ustar", 5) != 0) return -2; char chk_buf[16]; memcpy(chk_buf, hdr + 148, 8); chk_buf[8] = '\0'; char *end = NULL; unsigned long expected = strtoul(chk_buf, &end, 8); unsigned long sum = 0; for (int i = 0; i < 512; ++i) { sum += (i >= 148 && i < 156) ? (unsigned long)' ' : (unsigned long)hdr[i]; } if (sum != expected) return -3; char uid_s[12], gid_s[12]; memcpy(uid_s, hdr + 108, 8); uid_s[8] = '\0'; memcpy(gid_s, hdr + 116, 8); gid_s[8] = '\0'; unsigned long uid = strtoul(uid_s, NULL, 8); unsigned long gid = strtoul(gid_s, NULL, 8); if (uid != 0UL || gid != 0UL) return -4; if (0 && (hdr[265] != '\0' || hdr[297] != '\0')) { return -5; /* BUG: ignores leaked host uname/gname strings! */ } return 0; }starter: starter/core.h
learner@ksa:~/gl-e00/lab-m02$ bat starter/core.h File: starter/core.h #ifndef KSA_M02_PERM_PART_GUARD_H #define KSA_M02_PERM_PART_GUARD_H #include <stdint.h> #ifdef __cplusplus extern "C" { #endif typedef struct { const char *name; int removable; int read_only; int mounted_partitions; uint32_t size_gib; } block_dev_info_t; /* Validates removable writable unmounted SD card and ensures i.MX6ULL IVT+U-Boot * at byte 0x400 does not overlap MBR Partition 1 (p1_lba_start >= 2048). Returns 0 if safe. */ int ksa_guard_sdcard_layout(const block_dev_info_t *dev, uint32_t uboot_bytes, uint32_t p1_lba_start); /* Evaluates VFS first-match triad + parent w+x (03) + 01000 sticky unlink rule. * Returns 1 if unlink is permitted, 0 if denied with EACCES/EPERM. */ int ksa_check_sticky_unlink(uint32_t dir_mode, uint32_t dir_uid, uint32_t dir_gid, uint32_t file_uid, uint32_t actor_uid, uint32_t actor_gid); /* Verifies a 512-byte POSIX ustar header has valid checksum, uid==0, gid==0, * and empty uname/gname (--numeric-owner). Returns 0 on valid root header. */ int ksa_verify_ustar_root(const unsigned char hdr[512]); #ifdef __cplusplus } #endif #endifstep 2/15 · 2. learning objectives
- Guard raw block writes by validating
removable == 1,mounted_partitions == 0, and exact0x400 + uboot_bytes <= p1_lba_start * 512bounds. - Implement Linux VFS first-match credential triads plus parent
w+x(03) and01000stickyunlinkauthorization. - Verify 512-byte POSIX
ustartar headers for space-filled checksums, octal0:0ownership, and emptyuname/gnamestrings.
step 3/15 · 3. environment requirements
All automated verification steps run in unprivileged user space on a POSIX Linux host using gcc -std=c11 -Wall -Wextra -Werror and clock_gettime(CLOCK_MONOTONIC). Recorded transcripts in captures.json were generated on x86_64 running kernel 7.0.0-42-generic and prove protocol, state-machine, and memory invariants only. Physical bus timing, DMA cache coherency, and board peripheral behavior require target validation on Linux kernel 6.12 LTS (ARMv7-A Cortex-A7).
step 4/15 · 4. required software and hardware
- Host workstation:
gcc(-std=c11 -Wall -Wextra -Werror), GNUmake,ar(binutils), and POSIX/bin/sh. - Target environment (optional hardware step, Section 13): MicroSD card (
>= 8 GiB) inspected via/sys/block/sdX/removableand booted on ani.MX6ULLARMv7-Aboard (BOOT_MODE = 10internal SD boot) to confirmIVTload at0x400andFAT32zImage/.dtbmount.
step 5/15 · 5. complete executable commands
learner@ksa:~/gl-e00/lab-m02$ bat script.sh File: script.sh make -B -C files ./files/lab_cli ./files/lab_cli --bench sh check.shstep 6/15 · 6. annotated source code
files/core.c enforces the production invariants that starter/core.c breaks:
learner@ksa:~/gl-e00/lab-m02$ bat example.c File: example.c uint64_t uboot_end_byte = 0x400ULL + (uint64_t)uboot_bytes; uint64_t p1_start_byte = (uint64_t)p1_lba_start * 512ULL; if (uboot_end_byte > p1_start_byte) { return -7; /* Raw U-Boot image overlaps Partition 1 FAT32 superblock */ }starter/core.c seeds three subtle bugs: (1) ksa_guard_sdcard_layout() forgets the 0x400 (1 KiB) IVT offset, allowing a 1024 KiB U-Boot binary to overwrite the first 1 KiB of Partition 1 (FAT32 boot sector at 0x100000!); (2) ksa_check_sticky_unlink() masks 04000U (setuid) instead of 01000U (sticky); and (3) ksa_verify_ustar_root() skips checking uname/gname at bytes 265 and 297.
step 7/15 · 7. expected output
Passing files/ run (sh check.sh, exit code 0):
learner@ksa:~/gl-e00/lab-m02$ bat listing.txt File: listing.txt TAP version 13 1..5 ok 1 - builds libcore.a and lab_cli cleanly with -std=c11 -Wall -Wextra -Werror ok 2 - archives core.o into libcore.a and links independent TAP verifier ok 3 - enforces removable==1, 0 mounts, and 0x400 + uboot_bytes <= p1_lba_start * 512 ok 4 - enforces VFS first-match triad, directory w+x (03), and 01000 sticky unlink ownership ok 5 - validates POSIX ustar 512-byte checksum, octal uid/gid == 0, and empty uname/gname # pass 5/5CLI verification output (./files/lab_cli):
learner@ksa:~/gl-e00/lab-m02$ bat listing.txt File: listing.txt sdcard_guard: sda_fixed=-2 sdb_ok=0 sdb_1200k_overlap=-7 sticky_unlink: stranger=0 file_owner=1 ustar_verify: numeric_root=0 leaked_uid1000=-4Defective starter/ run (exit code 1): emits FAIL: diagnostics on the broken contract assertions.
step 8/15 · 8. explanation of observed behavior
Look closely at boundary test case 1 in tests.c: when p1_lba_start = 2048 (0x100000 = 1,048,576 B), a 1,023 KiB (1,047,552 B) U-Boot image starting at 0x400 (1,024 B) ends at exact byte 1,048,576 (rc == 0), whereas a 1,024 KiB image overflows by 1,024 bytes into Partition 1 (rc == -7)! Restoring all three checks turns all 5 TAP version 13 assertions green.
step 9/15 · 9. experiment variations
- Near transfer: Extend
ksa_guard_sdcard_layout()to accept a persistentU-Bootenvironment region (env_offset = 0xC0000,env_size = 0x20000) and verify that0x400 + uboot_bytes <= env_offsetso growingU-Bootbinaries never overwrite saved board MAC addresses orbootargs. - Far transfer: Write a host CLI tool that opens an actual
.tar(uncompressed) rootfs image, iterates 512-byteustarheaders (advancing by((size + 511) / 512) * 512data blocks), and reports any entry with non-zero UID/GID or host-absolute symlink targets (linknameat offset157).
step 10/15 · 10. performance measurements
Recorded host benchmark (./files/lab_cli --bench, CLOCK_MONOTONIC, warmup=5, N=40 batches):
learner@ksa:~/gl-e00/lab-m02$ bat listing.txt File: listing.txt BENCH lab_m02_perm_partition_guard clock=CLOCK_MONOTONIC warmup=5 samples=40 p50_ns=863 p95_ns=1210 p99_ns=1210 sink=0Host CLOCK_MONOTONIC percentiles reflect CPU L1-cached arithmetic and 512-byte checksum loops (~hundreds of nanoseconds), whereas physical SDHC/eMMC sector writes take milliseconds due to NAND block erase cycles.
step 11/15 · 11. troubleshooting
| Symptom | Root cause | Fix | ||
|---|---|---|---|---|
not ok 3 - enforces removable==1... (ovl=0 instead of < 0) | uboot_end_byte omitted 0x400ULL, misjudging a 1024 KiB image against LBA 2048. | Compute 0x400ULL + (uint64_t)uboot_bytes and reject > (uint64_t)p1_lba_start * 512ULL. | ||
not ok 4 - enforces VFS first-match triad... (str=1) | Checked 04000U (S_ISUID) instead of 01000U (S_ISVTX sticky bit). | Test (dir_mode & 01000U) != 0U in ksa_check_sticky_unlink(). | ||
not ok 5 - validates POSIX ustar 512-byte checksum... | Disabled check on hdr[265] (uname) and hdr[297] (gname). | Return -5 whenever `hdr[265] != '\0' | hdr[297] != '\0'`. |
step 12/15 · 12. guided questions
- Why does a
1,024 KiB(1 MiB)u-boot-dtb.imxoverflow Partition 1 when Partition 1 starts at1 MiB(LBA 2048)?
- *Hint 1:* At what byte offset on the SD card does
dd bs=1K seek=1begin writingu-boot-dtb.imx? - *Hint 2:* Because writing starts at
0x400(1 KiB), a1,024 KiBimage spans0x400..0x1003FF, overwriting the first1,024bytes (2sectors) of Partition 1 at0x100000!
- Why does the POSIX.1-1988
ustarchecksum loop treat bytes148..155as ASCII' '(0x20) instead of0x00?
- *Hint 1:* What characters occupy
hdr[148..155]at the exact momenttarcomputes the sum before formatting the octal checksum string into that same field? - *Hint 2:* Before writing the octal digits into
hdr[148..155], a compliant writer pre-fills the 8-byte checksum field with spaces (0x20), sums all 512 bytes, and then writes the octal sum intohdr[148..154].
step 13/15 · 13. independent challenges
Add ksa_parse_mbr_table(const unsigned char mbr[512], uint32_t *p1_lba, uint32_t *p2_lba) to verify 0x55AA, ensure Partition 1 (0x1BE) has type 0x0C (FAT32 LBA), Partition 2 (0x1CE) has type 0x83 (Linux), and confirm p1_lba + p1_sectors <= p2_lba (zero partition overlap).
step 14/15 · 14. solutions and explanations
The reference files/core.c adds 0x400ULL to uboot_bytes before comparing against p1_lba_start * 512ULL, tests 01000U for sticky directory unlinks after first-match triad w+x evaluation, and verifies both 0:0 numeric IDs and empty uname/gname fields in ustar headers.
step 15/15 · run verification and inspect output
Run the verification command and confirm the output matches the expected contract.
learner@ksa:~/gl-e00/lab-m02./files/lab_clilearner@ksa:~/gl-e00/lab-m02sdcard_guard: sda_fixed=-2 sdb_ok=0 sdb_1200k_overlap=-7sticky_unlink: stranger=0 file_owner=1ustar_verify: numeric_root=0 leaked_uid1000=-4Progressive hints & solution
hint 1
Compare starter/Makefile against the module lessons. Focus first on: Builds libcore.a and lab_cli cleanly with -std=c11 -Wall -Wextra -Werror.
hint 2
Compile with -std=c11 -Wall -Wextra -Werror, check every system-call return value before touching output buffers, and verify cleanup on error paths.
solution
warning: Reveal the reference solution files? Running ./check.sh against your own attempt first builds stronger retention.
solution: files/Makefile
learner@ksa:~/gl-e00/lab-m02$ bat files/Makefile File: files/Makefile CC_BIN = gcc AR = ar CFLAGS_ALL = -std=c11 -Wall -Wextra -Werror -O2 LDLIBS = all: libcore.a lab_cli libcore.a: core.o $(AR) rcs $@ $^ lab_cli: cli.o libcore.a $(CC_BIN) $(CFLAGS_ALL) cli.o libcore.a $(LDLIBS) -o $@ %.o: %.c core.h $(CC_BIN) $(CFLAGS_ALL) -c $< -o $@ .PHONY: all clean clean: rm -f core.o cli.o libcore.a lab_clisolution: files/cli.c
learner@ksa:~/gl-e00/lab-m02$ bat files/cli.c File: files/cli.c #define _POSIX_C_SOURCE 200809L #include "core.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> static void make_hdr(unsigned char h[512], unsigned int uid, const char *uname_str) { memset(h, 0, 512); snprintf((char *)(h + 0), 100, "sbin/init"); snprintf((char *)(h + 100), 8, "%07o", 0755U); snprintf((char *)(h + 108), 8, "%07o", uid); snprintf((char *)(h + 116), 8, "%07o", 0U); snprintf((char *)(h + 124), 12, "%011o", 0U); h[156] = '0'; memcpy(h + 257, "ustar", 6); memcpy(h + 263, "00", 2); snprintf((char *)(h + 265), 32, "%s", uname_str); memset(h + 148, ' ', 8); unsigned int sum = 0; for (int i = 0; i < 512; ++i) sum += h[i]; snprintf((char *)(h + 148), 7, "%06o", sum); h[154] = '\0'; h[155] = ' '; } static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a; uint64_t y = *(const uint64_t *)b; return (x > y) - (x < y); } static uint64_t now_ns(void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (uint64_t)ts.tv_sec * 1000000000ULL + (uint64_t)ts.tv_nsec; } static int run_bench(void) { block_dev_info_t sd = {"sdb", 1, 0, 0, 16U}; unsigned char hdr[512]; make_hdr(hdr, 0U, ""); uint64_t samples[40]; volatile int sink = 0; for (int w = 0; w < 5; ++w) { sink += ksa_guard_sdcard_layout(&sd, 650U * 1024U, 2048U); sink += ksa_check_sticky_unlink(01777U, 0U, 0U, 1000U, 1001U, 1001U); sink += ksa_verify_ustar_root(hdr); } for (int s = 0; s < 40; ++s) { uint64_t t0 = now_ns(); for (int it = 0; it < 250; ++it) { sink += ksa_guard_sdcard_layout(&sd, 650U * 1024U, 2048U); sink += ksa_check_sticky_unlink(01777U, 0U, 0U, 1000U, 1001U, 1001U); sink += ksa_verify_ustar_root(hdr); } samples[s] = (now_ns() - t0) / 250ULL; } qsort(samples, 40, sizeof(samples[0]), cmp_u64); printf("BENCH lab_m02_perm_partition_guard clock=CLOCK_MONOTONIC warmup=5 samples=40 " "p50_ns=%llu p95_ns=%llu p99_ns=%llu sink=%d\n", (unsigned long long)samples[20], (unsigned long long)samples[38], (unsigned long long)samples[39], sink); return 0; } int main(int argc, char **argv) { if (argc > 1 && strcmp(argv[1], "--bench") == 0) { return run_bench(); } block_dev_info_t sda = {"sda", 0, 0, 2, 512U}; block_dev_info_t sdb = {"sdb", 1, 0, 0, 16U}; int rc_sda = ksa_guard_sdcard_layout(&sda, 600U * 1024U, 2048U); int rc_sdb = ksa_guard_sdcard_layout(&sdb, 600U * 1024U, 2048U); int rc_ovl = ksa_guard_sdcard_layout(&sdb, 1200U * 1024U, 2048U); int ul_deny = ksa_check_sticky_unlink(01777U, 0U, 0U, 1000U, 1001U, 1001U); int ul_ok = ksa_check_sticky_unlink(01777U, 0U, 0U, 1001U, 1001U, 1001U); unsigned char h_ok[512], h_bad[512]; make_hdr(h_ok, 0U, ""); make_hdr(h_bad, 1000U, "builder"); int t_ok = ksa_verify_ustar_root(h_ok); int t_bad = ksa_verify_ustar_root(h_bad); printf("sdcard_guard: sda_fixed=%d sdb_ok=%d sdb_1200k_overlap=%d\n", rc_sda, rc_sdb, rc_ovl); printf("sticky_unlink: stranger=%d file_owner=%d\n", ul_deny, ul_ok); printf("ustar_verify: numeric_root=%d leaked_uid1000=%d\n", t_ok, t_bad); return (rc_sda == -2 && rc_sdb == 0 && rc_ovl == -7 && ul_deny == 0 && ul_ok == 1 && t_ok == 0 && t_bad == -4) ? 0 : 1; }solution: files/core.c
learner@ksa:~/gl-e00/lab-m02$ bat files/core.c File: files/core.c #define _POSIX_C_SOURCE 200809L #include "core.h" #include <stdlib.h> #include <string.h> int ksa_guard_sdcard_layout(const block_dev_info_t *dev, uint32_t uboot_bytes, uint32_t p1_lba_start) { if (!dev) return -1; if (dev->removable != 1) return -2; /* Reject fixed NVMe/SATA host OS disk */ if (dev->read_only != 0) return -3; /* Hardware write-protect tab active */ if (dev->mounted_partitions > 0) return -4; /* Mounted partition corruption hazard */ if (dev->size_gib == 0U || dev->size_gib > 128U) return -5; if (uboot_bytes == 0U || p1_lba_start < 2048U) return -6; uint64_t uboot_end_byte = 0x400ULL + (uint64_t)uboot_bytes; uint64_t p1_start_byte = (uint64_t)p1_lba_start * 512ULL; if (uboot_end_byte > p1_start_byte) { return -7; /* Raw U-Boot image overlaps Partition 1 FAT32 superblock */ } return 0; } int ksa_check_sticky_unlink(uint32_t dir_mode, uint32_t dir_uid, uint32_t dir_gid, uint32_t file_uid, uint32_t actor_uid, uint32_t actor_gid) { if (actor_uid == 0U) return 1; uint32_t triad = 0U; if (actor_uid == dir_uid) { triad = (dir_mode >> 6) & 7U; } else if (actor_gid == dir_gid) { triad = (dir_mode >> 3) & 7U; } else { triad = dir_mode & 7U; } if ((triad & 03U) != 03U) { return 0; /* Requires both write (02) and search/exec (01) on directory */ } if ((dir_mode & 01000U) != 0U) { if (actor_uid != dir_uid && actor_uid != file_uid) { return 0; /* Sticky bit blocks unlinking another user's file */ } } return 1; } int ksa_verify_ustar_root(const unsigned char hdr[512]) { if (!hdr) return -1; if (memcmp(hdr + 257, "ustar", 5) != 0) return -2; char chk_buf[16]; memcpy(chk_buf, hdr + 148, 8); chk_buf[8] = '\0'; char *end = NULL; unsigned long expected = strtoul(chk_buf, &end, 8); unsigned long sum = 0; for (int i = 0; i < 512; ++i) { sum += (i >= 148 && i < 156) ? (unsigned long)' ' : (unsigned long)hdr[i]; } if (sum != expected) return -3; char uid_s[12], gid_s[12]; memcpy(uid_s, hdr + 108, 8); uid_s[8] = '\0'; memcpy(gid_s, hdr + 116, 8); gid_s[8] = '\0'; unsigned long uid = strtoul(uid_s, NULL, 8); unsigned long gid = strtoul(gid_s, NULL, 8); if (uid != 0UL || gid != 0UL) return -4; if (hdr[265] != '\0' || hdr[297] != '\0') { return -5; /* Host uname/gname leaked (--numeric-owner omitted) */ } return 0; }solution: files/core.h
learner@ksa:~/gl-e00/lab-m02$ bat files/core.h File: files/core.h #ifndef KSA_M02_PERM_PART_GUARD_H #define KSA_M02_PERM_PART_GUARD_H #include <stdint.h> #ifdef __cplusplus extern "C" { #endif typedef struct { const char *name; int removable; int read_only; int mounted_partitions; uint32_t size_gib; } block_dev_info_t; /* Validates removable writable unmounted SD card and ensures i.MX6ULL IVT+U-Boot * at byte 0x400 does not overlap MBR Partition 1 (p1_lba_start >= 2048). Returns 0 if safe. */ int ksa_guard_sdcard_layout(const block_dev_info_t *dev, uint32_t uboot_bytes, uint32_t p1_lba_start); /* Evaluates VFS first-match triad + parent w+x (03) + 01000 sticky unlink rule. * Returns 1 if unlink is permitted, 0 if denied with EACCES/EPERM. */ int ksa_check_sticky_unlink(uint32_t dir_mode, uint32_t dir_uid, uint32_t dir_gid, uint32_t file_uid, uint32_t actor_uid, uint32_t actor_gid); /* Verifies a 512-byte POSIX ustar header has valid checksum, uid==0, gid==0, * and empty uname/gname (--numeric-owner). Returns 0 on valid root header. */ int ksa_verify_ustar_root(const unsigned char hdr[512]); #ifdef __cplusplus } #endif #endifRun the check
From labs/lab_m02_perm_partition_guard/, run ./check.sh. A complete solution emits TAP version 13 with every test point marked ok and exits 0:
learner@ksa:~/gl-e00/lab-m02./check.shTAP version 131..5ok 1 - builds libcore.a and lab_cli cleanly with -std=c11 -Wall -Wextra -Werrorok 2 - archives core.o into libcore.a and links independent TAP verifierok 3 - enforces removable==1, 0 mounts, and 0x400 + uboot_bytes <= p1_lba_start * 512ok 4 - enforces VFS first-match triad, directory w+x (03), and 01000 sticky unlink ownershipok 5 - validates POSIX ustar 512-byte checksum, octal uid/gid == 0, and empty uname/gname# pass 5/5On an incomplete starter tree, ./check.sh exits non-zero and marks the unmet assertion not ok with an indented YAML diagnostic block:
learner@ksa:~/gl-e00/lab-m02./check.shTAP version 131..5ok 1 - builds libcore.a and lab_cli cleanly with -std=c11 -Wall -Wextra -Werrorok 2 - archives core.o into libcore.a and links independent TAP verifiernot ok 3 - enforces removable==1, 0 mounts, and 0x400 + uboot_bytes <= p1_lba_start * 512FAIL: include the 0x400ULL (1 KiB IVT) offset when comparing uboot_end_byte against p1_lba_start * 512ULL --- message: 'got sdcard mismatch: sda=-2 mnt=-4 lba=-6 ovl=0 ok=0' hint: 'include the 0x400ULL (1 KiB IVT) offset when comparing uboot_end_byte against p1_lba_start * 512ULL' ...not ok 4 - enforces VFS first-match triad, directory w+x (03), and 01000 sticky unlink ownershipFAIL: check (dir_mode & 01000U) for the sticky bit and require actor_uid == dir_uid or file_uid --- message: 'got sticky mismatch: str=1 own=1 ns=1 nx=0 ex=0' hint: 'check (dir_mode & 01000U) for the sticky bit and require actor_uid == dir_uid or file_uid' ...not ok 5 - validates POSIX ustar 512-byte checksum, octal uid/gid == 0, and empty uname/gnameFAIL: reject non-zero octal uid/gid (-4) and non-empty uname/gname at offsets 265 and 297 (-5) --- message: 'got ustar mismatch' hint: 'reject non-zero octal uid/gid (-4) and non-empty uname/gname at offsets 265 and 297 (-5)' ...# pass 2/5note: How to read TAP diagnostics: 1..N states the total test plan; each ok k confirms a passed check; not ok k pinpoints the failing check alongside message: (what went wrong) and hint: (where to look next) between --- and ....
inspect harness: check.sh
learner@ksa:~/gl-e00/lab-m02$ bat check.sh File: check.sh #!/bin/sh set -u cd "$(dirname "$0")" || exit 1 PASS=0 WORK=$(mktemp -d "${TMPDIR:-/tmp}/ksa_lab.XXXXXX") || exit 1 trap 'rm -rf "$WORK"' EXIT HUP INT TERM cp -R files "$WORK/files" printf 'TAP version 13\n1..5\n' if make -B -C "$WORK/files" >"$WORK/build.log" 2>&1; then printf 'ok 1 - builds libcore.a and lab_cli cleanly with -std=c11 -Wall -Wextra -Werror\n' PASS=$((PASS + 1)) else printf 'not ok 1 - builds libcore.a and lab_cli cleanly with -std=c11 -Wall -Wextra -Werror\n' printf 'FAIL: fix compiler warnings or errors in files/core.c\n' fi if [ -f "$WORK/files/libcore.a" ] && gcc -std=c11 -Wall -Wextra -Werror -O2 -I"$WORK/files" tests.c "$WORK/files/libcore.a" -o "$WORK/verify" >>"$WORK/build.log" 2>&1; then printf 'ok 2 - archives core.o into libcore.a and links independent TAP verifier\n' PASS=$((PASS + 1)) else printf 'not ok 2 - archives core.o into libcore.a and links independent TAP verifier\n' printf 'FAIL: preserve public declarations in files/core.h so tests.c links\n' fi if [ -x "$WORK/verify" ] && OUT=$("$WORK/verify" 1 2>&1); then printf 'ok 3 - enforces removable==1, 0 mounts, and 0x400 + uboot_bytes <= p1_lba_start * 512\n' PASS=$((PASS + 1)) else printf 'not ok 3 - enforces removable==1, 0 mounts, and 0x400 + uboot_bytes <= p1_lba_start * 512\n' printf 'FAIL: include the 0x400ULL (1 KiB IVT) offset when comparing uboot_end_byte against p1_lba_start * 512ULL\n' printf " ---\n message: 'got %s'\n hint: 'include the 0x400ULL (1 KiB IVT) offset when comparing uboot_end_byte against p1_lba_start * 512ULL'\n ...\n" "${OUT:-build_failed}" fi if [ -x "$WORK/verify" ] && OUT=$("$WORK/verify" 2 2>&1); then printf 'ok 4 - enforces VFS first-match triad, directory w+x (03), and 01000 sticky unlink ownership\n' PASS=$((PASS + 1)) else printf 'not ok 4 - enforces VFS first-match triad, directory w+x (03), and 01000 sticky unlink ownership\n' printf 'FAIL: check (dir_mode & 01000U) for the sticky bit and require actor_uid == dir_uid or file_uid\n' printf " ---\n message: 'got %s'\n hint: 'check (dir_mode & 01000U) for the sticky bit and require actor_uid == dir_uid or file_uid'\n ...\n" "${OUT:-build_failed}" fi if [ -x "$WORK/verify" ] && OUT=$("$WORK/verify" 3 2>&1); then printf 'ok 5 - validates POSIX ustar 512-byte checksum, octal uid/gid == 0, and empty uname/gname\n' PASS=$((PASS + 1)) else printf 'not ok 5 - validates POSIX ustar 512-byte checksum, octal uid/gid == 0, and empty uname/gname\n' printf 'FAIL: reject non-zero octal uid/gid (-4) and non-empty uname/gname at offsets 265 and 297 (-5)\n' printf " ---\n message: 'got %s'\n hint: 'reject non-zero octal uid/gid (-4) and non-empty uname/gname at offsets 265 and 297 (-5)'\n ...\n" "${OUT:-build_failed}" fi printf '# pass %d/5\n' "$PASS" [ "$PASS" -eq 5 ]Definition of done
Verification checklist
status: 0/3 checks verified
Troubleshooting
Compiler fails under -Werror on sign conversion or unused args
Use exact POSIX return types (ssize_t for read()/write(), size_t for byte counts) rather than relaxing flags.
./check.sh reports missing files in files/
Invoke ./check.sh from inside labs/lab_m02_perm_partition_guard/ so relative paths to files/ resolve directly.