Lab 1: Linux Workbench udev, dup2 Redirection & PATH Security Auditor
Provision hardware-virtualized Linux network bridges, deterministic udev USB device permissions, POSIX file-descriptor redirection pipelines, sudo-safe cross-compiler PATH environments, and modal tree-search workflows verified by an ISO C11 workbench auditor.
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
Onboarding scripts for embedded Linux teams routinely break because one typo in /etc/udev/rules.d/ grants world-writable 0666 permissions or fails to match 15a2:0080, inverted 2>&1 >log redirection loses compiler errors, and an unguarded PATH append introduces an implicit . current-directory vulnerability. In this studio you repair a deterministic ISO C11 workbench auditor that enforces all three contracts before a host machine touches target hardware.
learner@ksa:~/gl-e00/lab-m01ls -lastarter/Makefilestarter/cli.cstarter/core.cstarter/core.hlearner@ksa:~/gl-e00/lab-m01starter: starter/Makefile
learner@ksa:~/gl-e00/lab-m01$ 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-m01$ bat starter/cli.c File: starter/cli.c #define _POSIX_C_SOURCE 200809L #include "core.h" #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> 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) { const char *rule = "SUBSYSTEM==\"tty\", ATTRS{idVendor}==\"1a86\", ATTRS{idProduct}==\"7523\", " "MODE=\"0660\", GROUP=\"dialout\", SYMLINK+=\"ttyBENCH0\""; const char *path_ok = "/opt/toolchains/arm/bin:/usr/local/bin:/usr/bin:/bin"; const unsigned int modes[4] = {0755U, 0755U, 0755U, 0755U}; uint64_t samples[40]; volatile int sink = 0; for (int w = 0; w < 5; ++w) { udev_audit_t ua; path_audit_t pa; fd_target_t f1, f2; sink += ksa_audit_udev_rule(rule, &ua); sink += ksa_simulate_redir(1, &f1, &f2); sink += ksa_audit_path_env(path_ok, modes, 4, &pa); } for (int s = 0; s < 40; ++s) { uint64_t t0 = now_ns(); for (int it = 0; it < 250; ++it) { udev_audit_t ua; path_audit_t pa; fd_target_t f1, f2; sink += ksa_audit_udev_rule(rule, &ua); sink += ksa_simulate_redir(1, &f1, &f2); sink += ksa_audit_path_env(path_ok, modes, 4, &pa); } samples[s] = (now_ns() - t0) / 250ULL; } qsort(samples, 40, sizeof(samples[0]), cmp_u64); printf("BENCH lab_m01_shell_env_audit 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(); } udev_audit_t ua; int rc_udev = ksa_audit_udev_rule( "SUBSYSTEM==\"tty\", ATTRS{idVendor}==\"1a86\", ATTRS{idProduct}==\"7523\", " "MODE=\"0660\", GROUP=\"dialout\", SYMLINK+=\"ttyBENCH0\"", &ua); fd_target_t ok1, ok2, bad1, bad2; ksa_simulate_redir(1, &ok1, &ok2); ksa_simulate_redir(0, &bad1, &bad2); const unsigned int modes[3] = {0755U, 0755U, 0755U}; path_audit_t pa_ok, pa_empty; int rc_p_ok = ksa_audit_path_env("/opt/arm/bin:/usr/bin:/bin", modes, 3, &pa_ok); int rc_p_bad = ksa_audit_path_env("/opt/arm/bin::/usr/bin", modes, 3, &pa_empty); printf("udev_ch340: rc=%d mode=0%03o\n", rc_udev, ua.mode); printf("redir_order: gt_log_2gt1=(%d,%d) 2gt1_gt_log=(%d,%d)\n", (int)ok1, (int)ok2, (int)bad1, (int)bad2); printf("path_audit: clean_rc=%d(segs=%zu) double_colon_rc=%d(empty_idx=%d)\n", rc_p_ok, pa_ok.segments, rc_p_bad, pa_empty.empty_seg_index); return (rc_udev == 0 && ok1 == FD_TARGET_LOG && ok2 == FD_TARGET_LOG && bad2 == FD_TARGET_PTS && rc_p_ok == 0 && rc_p_bad == -2) ? 0 : 1; }starter: starter/core.c
learner@ksa:~/gl-e00/lab-m01$ bat starter/core.c File: starter/core.c #define _POSIX_C_SOURCE 200809L #include "core.h" #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> static int is_hex4_str(const char *s) { if (strlen(s) != 4) return 0; for (int i = 0; i < 4; ++i) { if (!isxdigit((unsigned char)s[i])) return 0; } return 1; } int ksa_audit_udev_rule(const char *rule_line, udev_audit_t *out) { if (!rule_line || !out) return -1; memset(out, 0, sizeof(*out)); char buf[512]; snprintf(buf, sizeof(buf), "%s", rule_line); int has_mode = 0; char *save = NULL; for (char *tok = strtok_r(buf, ",", &save); tok; tok = strtok_r(NULL, ",", &save)) { while (*tok == ' ' || *tok == '\t') tok++; int has_eq2 = (strstr(tok, "==") != NULL); if (strncmp(tok, "SUBSYSTEM", 9) == 0 || strncmp(tok, "ATTR", 4) == 0) { if (!has_eq2) return -2; /* Single '=' on predicate key */ } const char *q1 = strchr(tok, '"'); const char *q2 = q1 ? strchr(q1 + 1, '"') : NULL; if (!q1 || !q2 || (size_t)(q2 - q1 - 1) >= 48) return -3; char val[48]; memcpy(val, q1 + 1, (size_t)(q2 - q1 - 1)); val[q2 - q1 - 1] = '\0'; if (strncmp(tok, "SUBSYSTEM==", 11) == 0) { out->has_subsys = (strcmp(val, "tty") == 0 || strcmp(val, "usb") == 0); } else if (strstr(tok, "{idVendor}==")) { out->has_vid = is_hex4_str(val); } else if (strstr(tok, "{idProduct}==")) { out->has_pid = is_hex4_str(val); } else if (strncmp(tok, "GROUP=", 6) == 0 && tok[6] == '"') { out->has_group = (val[0] != '\0'); } else if (strncmp(tok, "MODE=", 5) == 0 && tok[5] == '"') { char *end = NULL; unsigned long m = strtoul(val, &end, 8); if (*end != '\0' || m > 0777UL) return -4; if ((m & 0000UL) != 0) return -5; /* BUG: fails to reject world-writable 0666 */ out->mode = (unsigned int)m; has_mode = 1; } } if (!out->has_subsys || !out->has_vid || !out->has_pid || !out->has_group || !has_mode) { return -6; } return 0; } int ksa_simulate_redir(int log_first, fd_target_t *fd1_out, fd_target_t *fd2_out) { if (!fd1_out || !fd2_out) return -1; fd_target_t fd1 = FD_TARGET_PTS; fd_target_t fd2 = FD_TARGET_PTS; if (log_first) { fd1 = FD_TARGET_LOG; fd2 = fd1; /* 2>&1 after >log */ } else { fd1 = FD_TARGET_LOG; fd2 = fd1; /* BUG: ignores left-to-right dup2 order */ } *fd1_out = fd1; *fd2_out = fd2; return 0; } int ksa_audit_path_env(const char *path_str, const unsigned int *dir_modes, size_t mode_count, path_audit_t *out) { if (!path_str || !out || path_str[0] == '\0') return -1; out->segments = 0; out->empty_seg_index = -1; out->bad_mode_index = -1; const char *p = path_str; size_t idx = 0; for (;;) { const char *colon = strchr(p, ':'); size_t len = colon ? (size_t)(colon - p) : strlen(p); out->segments++; if (len == 9999) { out->empty_seg_index = (int)idx; return -2; /* BUG: misses empty '::' and trailing ':' segments */ } if (p[0] != '/') { return -3; /* Non-absolute segment */ } if (dir_modes && idx < mode_count) { if ((dir_modes[idx] & 0002U) != 0) { out->bad_mode_index = (int)idx; return -4; /* World-writable directory in PATH */ } } if (!colon) break; p = colon + 1; idx++; } return 0; }starter: starter/core.h
learner@ksa:~/gl-e00/lab-m01$ bat starter/core.h File: starter/core.h #ifndef KSA_M01_AUDIT_CORE_H #define KSA_M01_AUDIT_CORE_H #include <stddef.h> #ifdef __cplusplus extern "C" { #endif typedef enum { FD_TARGET_PTS = 0, FD_TARGET_LOG = 1 } fd_target_t; typedef struct { unsigned int mode; int has_subsys; int has_vid; int has_pid; int has_group; } udev_audit_t; typedef struct { size_t segments; int empty_seg_index; int bad_mode_index; } path_audit_t; /* Returns 0 on valid non-world-writable udev rule with == matchers; < 0 on defect. */ int ksa_audit_udev_rule(const char *rule_line, udev_audit_t *out); /* Simulates left-to-right fd 1 & fd 2 routing: * log_first != 0 -> cmd >build.log 2>&1 * log_first == 0 -> cmd 2>&1 >build.log */ int ksa_simulate_redir(int log_first, fd_target_t *fd1_out, fd_target_t *fd2_out); /* Scans colon-delimited PATH without strtok(), rejecting empty ('::', leading/trailing ':'), * relative (non-'/'), and world-writable (mode & 0002) segments. Returns 0 when clean. */ int ksa_audit_path_env(const char *path_str, const unsigned int *dir_modes, size_t mode_count, path_audit_t *out); #ifdef __cplusplus } #endif #endifstep 2/15 · 2. learning objectives
- Enforce udev
==predicate syntax, 4-digit hexidVendor/idProductbounds, and non-world-writable!(mode & 0002)rules. - Model left-to-right POSIX
dup2(oldfd, newfd)descriptor routing across>build.log 2>&1and2>&1 >build.log. - Scan colon-delimited
PATHstrings via pointer arithmetic (strchr) to reject leading:, interior::, trailing:, and world-writable (0002) directories.
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):
ARMv7-ACortex-A7board connected viaCH340(1a86:7523) USB-UART console and USB OTGSDP(15a2:0080) recovery cable to verify/dev/ttyBENCH0symlink creation underudevadm.
step 5/15 · 5. complete executable commands
learner@ksa:~/gl-e00/lab-m01$ 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-m01$ bat example.c File: example.c if ((m & 0002UL) != 0) return -5; /* Reject world-writable 0666 */ ... const char *colon = strchr(p, ':'); size_t len = colon ? (size_t)(colon - p) : strlen(p); if (len == 0) { out->empty_seg_index = (int)idx; return -2; /* Empty segment -> implicit '.' CWD hazard */ }starter/core.c contains three realistic defects: (1) ksa_audit_udev_rule() masks m & 0000UL and lets MODE="0666" slip through; (2) ksa_simulate_redir() ignores left-to-right dup2() order when log_first == 0; and (3) ksa_audit_path_env() fails to reject len == 0 empty :: or trailing : segments.
step 7/15 · 7. expected output
Passing files/ run (sh check.sh, exit code 0):
learner@ksa:~/gl-e00/lab-m01$ 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 - validates udev == predicates, hex4 VID:PID, and rejects world-writable MODE 0666 ok 4 - models left-to-right dup2 order distinguishing >log 2>&1 from 2>&1 >log ok 5 - audits colon-delimited PATH rejecting empty ::/trailing : and 0002 world-writable dirs # pass 5/5CLI verification output (./files/lab_cli):
learner@ksa:~/gl-e00/lab-m01$ bat listing.txt File: listing.txt udev_ch340: rc=0 mode=0660 redir_order: gt_log_2gt1=(1,1) 2gt1_gt_log=(1,0) path_audit: clean_rc=0(segs=3) double_colon_rc=-2(empty_idx=1)Defective starter/ run (exit code 1): emits FAIL: diagnostics on the broken contract assertions.
step 8/15 · 8. explanation of observed behavior
When all three invariants are restored in files/core.c, sh check.sh compiles libcore.a cleanly under -std=c11 -Wall -Wextra -Werror, links the independent tests.c harness, and verifies all 5 TAP version 13 assertions (CH340 + 15a2:0080 udev rules, dup2 redirection order, and colon-exact PATH auditing).
step 9/15 · 9. experiment variations
- Near transfer: Extend
ksa_audit_udev_rule()to rejectSYMLINK="..."(overwrite=) and requireSYMLINK+="..."(append+=) so custom bench aliases never wipe out/dev/serial/by-id/links. - Far transfer: Write a companion shell/C11 preflight tool that reads live
/etc/udev/rules.d/*.rulesandgetenv("PATH")+stat(2)on your workstation, failing CI if any directory inPATHis writable by group or other (st_mode & 0022).
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-m01$ bat listing.txt File: listing.txt BENCH lab_m01_shell_env_audit clock=CLOCK_MONOTONIC warmup=5 samples=40 p50_ns=468 p95_ns=484 p99_ns=497 sink=0The CLOCK_MONOTONIC numbers above measure pure in-memory C11 rule and PATH parsing cost on the host CPU (p50 typically sub-microsecond per 3-call batch). Never extrapolate these host numbers to physical USB 2.0 enumeration (~tens of milliseconds) or systemd-udevd netlink worker fork latency.
step 11/15 · 11. troubleshooting
| Symptom | Root cause | Fix |
|---|---|---|
not ok 3 - validates udev == predicates... | ksa_audit_udev_rule() still permits (m & 0002UL) != 0 (MODE="0666"). | Check (m & 0002UL) != 0 after strtoul(val, &end, 8) and return -5. |
not ok 4 - models left-to-right dup2 order... | log_first == 0 updates fd1 before copying fd1 into fd2. | In the else branch (2>&1 >log), set fd2 = fd1 (FD_TARGET_PTS) first, then fd1 = FD_TARGET_LOG. |
not ok 5 - audits colon-delimited PATH... | strtok() was used or len == 0 check is disabled, missing :: and trailing :. | Keep the strchr(p, ':') loop and return -2 whenever len == 0. |
step 12/15 · 12. guided questions
- Why does
ksa_audit_path_env()reject/tmp(01777) when(dir_modes[idx] & 0002U) != 0even though/tmphas the sticky bit (01000) set?
- *Hint 1:* What does the sticky bit (
01000) prevent (unlink/renameof existing files), and what does0002(o+w) still allow any local user to create? - *Hint 2:* Any unprivileged user can still create a brand-new executable (such as a fake
arm-linux-gnueabihf-gccorsltypo binary) inside/tmpif it does not yet exist!
- Why does
strtoul(val, &end, 8)explicitly pass base8instead of base0when parsingMODE="0660"?
- *Hint 1:* What happens under base
0if someone writesMODE="660"without a leading'0'? - *Hint 2:* Base
0parses"660"as decimal660(01224octal!) instead of octal0660, whereasudevalways interpretsMODEstrings in base8.
step 13/15 · 13. independent challenges
Add a ksa_audit_sudo_secure_path() function to core.c that compares a developer's cross-build PATH against /etc/sudoers secure_path, returning the exact list of stripped toolchain directories so an onboarding doctor CLI can explain why sudo make failed.
step 14/15 · 14. solutions and explanations
The reference files/core.c validates == predicates and !(m & 0002UL) octal permissions in ksa_audit_udev_rule(), preserves strict left-to-right fd2 = fd1; fd1 = FD_TARGET_LOG; ordering in ksa_simulate_redir(0, ...), and scans raw : boundaries with strchr() in ksa_audit_path_env() to reject empty segments and world-writable directories.
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-m01./files/lab_clilearner@ksa:~/gl-e00/lab-m01udev_ch340: rc=0 mode=0660redir_order: gt_log_2gt1=(1,1) 2gt1_gt_log=(1,0)path_audit: clean_rc=0(segs=3) double_colon_rc=-2(empty_idx=1)Progressive 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-m01$ 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-m01$ bat files/cli.c File: files/cli.c #define _POSIX_C_SOURCE 200809L #include "core.h" #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> 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) { const char *rule = "SUBSYSTEM==\"tty\", ATTRS{idVendor}==\"1a86\", ATTRS{idProduct}==\"7523\", " "MODE=\"0660\", GROUP=\"dialout\", SYMLINK+=\"ttyBENCH0\""; const char *path_ok = "/opt/toolchains/arm/bin:/usr/local/bin:/usr/bin:/bin"; const unsigned int modes[4] = {0755U, 0755U, 0755U, 0755U}; uint64_t samples[40]; volatile int sink = 0; for (int w = 0; w < 5; ++w) { udev_audit_t ua; path_audit_t pa; fd_target_t f1, f2; sink += ksa_audit_udev_rule(rule, &ua); sink += ksa_simulate_redir(1, &f1, &f2); sink += ksa_audit_path_env(path_ok, modes, 4, &pa); } for (int s = 0; s < 40; ++s) { uint64_t t0 = now_ns(); for (int it = 0; it < 250; ++it) { udev_audit_t ua; path_audit_t pa; fd_target_t f1, f2; sink += ksa_audit_udev_rule(rule, &ua); sink += ksa_simulate_redir(1, &f1, &f2); sink += ksa_audit_path_env(path_ok, modes, 4, &pa); } samples[s] = (now_ns() - t0) / 250ULL; } qsort(samples, 40, sizeof(samples[0]), cmp_u64); printf("BENCH lab_m01_shell_env_audit 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(); } udev_audit_t ua; int rc_udev = ksa_audit_udev_rule( "SUBSYSTEM==\"tty\", ATTRS{idVendor}==\"1a86\", ATTRS{idProduct}==\"7523\", " "MODE=\"0660\", GROUP=\"dialout\", SYMLINK+=\"ttyBENCH0\"", &ua); fd_target_t ok1, ok2, bad1, bad2; ksa_simulate_redir(1, &ok1, &ok2); ksa_simulate_redir(0, &bad1, &bad2); const unsigned int modes[3] = {0755U, 0755U, 0755U}; path_audit_t pa_ok, pa_empty; int rc_p_ok = ksa_audit_path_env("/opt/arm/bin:/usr/bin:/bin", modes, 3, &pa_ok); int rc_p_bad = ksa_audit_path_env("/opt/arm/bin::/usr/bin", modes, 3, &pa_empty); printf("udev_ch340: rc=%d mode=0%03o\n", rc_udev, ua.mode); printf("redir_order: gt_log_2gt1=(%d,%d) 2gt1_gt_log=(%d,%d)\n", (int)ok1, (int)ok2, (int)bad1, (int)bad2); printf("path_audit: clean_rc=%d(segs=%zu) double_colon_rc=%d(empty_idx=%d)\n", rc_p_ok, pa_ok.segments, rc_p_bad, pa_empty.empty_seg_index); return (rc_udev == 0 && ok1 == FD_TARGET_LOG && ok2 == FD_TARGET_LOG && bad2 == FD_TARGET_PTS && rc_p_ok == 0 && rc_p_bad == -2) ? 0 : 1; }solution: files/core.c
learner@ksa:~/gl-e00/lab-m01$ bat files/core.c File: files/core.c #define _POSIX_C_SOURCE 200809L #include "core.h" #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> static int is_hex4_str(const char *s) { if (strlen(s) != 4) return 0; for (int i = 0; i < 4; ++i) { if (!isxdigit((unsigned char)s[i])) return 0; } return 1; } int ksa_audit_udev_rule(const char *rule_line, udev_audit_t *out) { if (!rule_line || !out) return -1; memset(out, 0, sizeof(*out)); char buf[512]; snprintf(buf, sizeof(buf), "%s", rule_line); int has_mode = 0; char *save = NULL; for (char *tok = strtok_r(buf, ",", &save); tok; tok = strtok_r(NULL, ",", &save)) { while (*tok == ' ' || *tok == '\t') tok++; int has_eq2 = (strstr(tok, "==") != NULL); if (strncmp(tok, "SUBSYSTEM", 9) == 0 || strncmp(tok, "ATTR", 4) == 0) { if (!has_eq2) return -2; /* Single '=' on predicate key */ } const char *q1 = strchr(tok, '"'); const char *q2 = q1 ? strchr(q1 + 1, '"') : NULL; if (!q1 || !q2 || (size_t)(q2 - q1 - 1) >= 48) return -3; char val[48]; memcpy(val, q1 + 1, (size_t)(q2 - q1 - 1)); val[q2 - q1 - 1] = '\0'; if (strncmp(tok, "SUBSYSTEM==", 11) == 0) { out->has_subsys = (strcmp(val, "tty") == 0 || strcmp(val, "usb") == 0); } else if (strstr(tok, "{idVendor}==")) { out->has_vid = is_hex4_str(val); } else if (strstr(tok, "{idProduct}==")) { out->has_pid = is_hex4_str(val); } else if (strncmp(tok, "GROUP=", 6) == 0 && tok[6] == '"') { out->has_group = (val[0] != '\0'); } else if (strncmp(tok, "MODE=", 5) == 0 && tok[5] == '"') { char *end = NULL; unsigned long m = strtoul(val, &end, 8); if (*end != '\0' || m > 0777UL) return -4; if ((m & 0002UL) != 0) return -5; /* Reject world-writable 0666 */ out->mode = (unsigned int)m; has_mode = 1; } } if (!out->has_subsys || !out->has_vid || !out->has_pid || !out->has_group || !has_mode) { return -6; } return 0; } int ksa_simulate_redir(int log_first, fd_target_t *fd1_out, fd_target_t *fd2_out) { if (!fd1_out || !fd2_out) return -1; fd_target_t fd1 = FD_TARGET_PTS; fd_target_t fd2 = FD_TARGET_PTS; if (log_first) { fd1 = FD_TARGET_LOG; fd2 = fd1; /* 2>&1 after >log */ } else { fd2 = fd1; /* 2>&1 while fd1 is still PTS */ fd1 = FD_TARGET_LOG; } *fd1_out = fd1; *fd2_out = fd2; return 0; } int ksa_audit_path_env(const char *path_str, const unsigned int *dir_modes, size_t mode_count, path_audit_t *out) { if (!path_str || !out || path_str[0] == '\0') return -1; out->segments = 0; out->empty_seg_index = -1; out->bad_mode_index = -1; const char *p = path_str; size_t idx = 0; for (;;) { const char *colon = strchr(p, ':'); size_t len = colon ? (size_t)(colon - p) : strlen(p); out->segments++; if (len == 0) { out->empty_seg_index = (int)idx; return -2; /* Empty segment -> implicit '.' CWD hazard */ } if (p[0] != '/') { return -3; /* Non-absolute segment */ } if (dir_modes && idx < mode_count) { if ((dir_modes[idx] & 0002U) != 0) { out->bad_mode_index = (int)idx; return -4; /* World-writable directory in PATH */ } } if (!colon) break; p = colon + 1; idx++; } return 0; }solution: files/core.h
learner@ksa:~/gl-e00/lab-m01$ bat files/core.h File: files/core.h #ifndef KSA_M01_AUDIT_CORE_H #define KSA_M01_AUDIT_CORE_H #include <stddef.h> #ifdef __cplusplus extern "C" { #endif typedef enum { FD_TARGET_PTS = 0, FD_TARGET_LOG = 1 } fd_target_t; typedef struct { unsigned int mode; int has_subsys; int has_vid; int has_pid; int has_group; } udev_audit_t; typedef struct { size_t segments; int empty_seg_index; int bad_mode_index; } path_audit_t; /* Returns 0 on valid non-world-writable udev rule with == matchers; < 0 on defect. */ int ksa_audit_udev_rule(const char *rule_line, udev_audit_t *out); /* Simulates left-to-right fd 1 & fd 2 routing: * log_first != 0 -> cmd >build.log 2>&1 * log_first == 0 -> cmd 2>&1 >build.log */ int ksa_simulate_redir(int log_first, fd_target_t *fd1_out, fd_target_t *fd2_out); /* Scans colon-delimited PATH without strtok(), rejecting empty ('::', leading/trailing ':'), * relative (non-'/'), and world-writable (mode & 0002) segments. Returns 0 when clean. */ int ksa_audit_path_env(const char *path_str, const unsigned int *dir_modes, size_t mode_count, path_audit_t *out); #ifdef __cplusplus } #endif #endifRun the check
From labs/lab_m01_shell_env_audit/, run ./check.sh. A complete solution emits TAP version 13 with every test point marked ok and exits 0:
learner@ksa:~/gl-e00/lab-m01./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 - validates udev == predicates, hex4 VID:PID, and rejects world-writable MODE 0666ok 4 - models left-to-right dup2 order distinguishing >log 2>&1 from 2>&1 >logok 5 - audits colon-delimited PATH rejecting empty ::/trailing : and 0002 world-writable dirs# 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-m01./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 - validates udev == predicates, hex4 VID:PID, and rejects world-writable MODE 0666FAIL: reject single = on SUBSYSTEM/ATTR keys and return < 0 when (mode & 0002) != 0 in ksa_audit_udev_rule --- message: 'got udev_audit mismatch: ok_uart=0 ok_sdp=0 bad_eq=-2 bad_0666=0' hint: 'reject single = on SUBSYSTEM/ATTR keys and return < 0 when (mode & 0002) != 0 in ksa_audit_udev_rule' ...not ok 4 - models left-to-right dup2 order distinguishing >log 2>&1 from 2>&1 >logFAIL: when log_first == 0 (2>&1 >log), assign fd2 = fd1 before updating fd1 to FD_TARGET_LOG --- message: 'got redir mismatch: ok=(1,1) inv=(1,1)' hint: 'when log_first == 0 (2>&1 >log), assign fd2 = fd1 before updating fd1 to FD_TARGET_LOG' ...not ok 5 - audits colon-delimited PATH rejecting empty ::/trailing : and 0002 world-writable dirsFAIL: reject len == 0 colon segments (-2) and (dir_modes[idx] & 0002) != 0 (-4) in ksa_audit_path_env --- message: 'got path_audit mismatch: clean=0 mid=-3 trail=-3 ww=-4' hint: 'reject len == 0 colon segments (-2) and (dir_modes[idx] & 0002) != 0 (-4) in ksa_audit_path_env' ...# 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-m01$ 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 - validates udev == predicates, hex4 VID:PID, and rejects world-writable MODE 0666\n' PASS=$((PASS + 1)) else printf 'not ok 3 - validates udev == predicates, hex4 VID:PID, and rejects world-writable MODE 0666\n' printf 'FAIL: reject single = on SUBSYSTEM/ATTR keys and return < 0 when (mode & 0002) != 0 in ksa_audit_udev_rule\n' printf " ---\n message: 'got %s'\n hint: 'reject single = on SUBSYSTEM/ATTR keys and return < 0 when (mode & 0002) != 0 in ksa_audit_udev_rule'\n ...\n" "${OUT:-build_failed}" fi if [ -x "$WORK/verify" ] && OUT=$("$WORK/verify" 2 2>&1); then printf 'ok 4 - models left-to-right dup2 order distinguishing >log 2>&1 from 2>&1 >log\n' PASS=$((PASS + 1)) else printf 'not ok 4 - models left-to-right dup2 order distinguishing >log 2>&1 from 2>&1 >log\n' printf 'FAIL: when log_first == 0 (2>&1 >log), assign fd2 = fd1 before updating fd1 to FD_TARGET_LOG\n' printf " ---\n message: 'got %s'\n hint: 'when log_first == 0 (2>&1 >log), assign fd2 = fd1 before updating fd1 to FD_TARGET_LOG'\n ...\n" "${OUT:-build_failed}" fi if [ -x "$WORK/verify" ] && OUT=$("$WORK/verify" 3 2>&1); then printf 'ok 5 - audits colon-delimited PATH rejecting empty ::/trailing : and 0002 world-writable dirs\n' PASS=$((PASS + 1)) else printf 'not ok 5 - audits colon-delimited PATH rejecting empty ::/trailing : and 0002 world-writable dirs\n' printf 'FAIL: reject len == 0 colon segments (-2) and (dir_modes[idx] & 0002) != 0 (-4) in ksa_audit_path_env\n' printf " ---\n message: 'got %s'\n hint: 'reject len == 0 colon segments (-2) and (dir_modes[idx] & 0002) != 0 (-4) in ksa_audit_path_env'\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_m01_shell_env_audit/ so relative paths to files/ resolve directly.