linux-sysprog · intermediate · ~15 min
Validate Unix-socket peer credentials before processing the protocol.
Decide whether to accept a Unix-socket peer based on its UID against an explicit allow-list — the in-protocol check you'd run after SO_PEERCRED. This is a pure membership test on an int array.
Implement int allow_peer(int peer_uid, const int *allow, int n_allow) that returns whether peer_uid is permitted.
peer_uid: the connecting peer's user id (as SO_PEERCRED would report).allow, n_allow: the allow-list array and its length.Returns 1 if peer_uid appears in allow[0..n_allow-1], otherwise 0. Root (uid 0) is allowed only when 0 is explicitly listed — there is no implicit root bypass. A negative uid or an empty/NULL list always denies.
allow = {1000, 1001}
allow_peer(1000, allow, 2) -> 1
allow_peer(2000, allow, 2) -> 0
allow_peer(0, allow, 2) -> 0 (root not implicitly allowed)
allow_peer(0, {0,1000}, 2) -> 1 (root explicitly listed)
allow_peer(1000, NULL, 0) -> 0 (empty list denies all)
allow_peer(-1, allow, 2) -> 0 (invalid uid)
peer_uid is invalid and denied.Unix socket connections carry the peer's real uid via SO_PEERCRED. Refusing connections by uid is the cheapest in-protocol authentication.
The peer's uid plus an allow-list array allow of length n_allow.
1 if peer_uid is in the list, else 0.
No implicit root: 0 must be explicitly listed. Empty/NULL list or negative uid denies.
int allow_peer(int peer_uid, const int *allow, int n_allow) { /* TODO */ (void)peer_uid; (void)allow; (void)n_allow; return 0; }
Special-casing uid==0 as 'always allow' — root must be explicitly listed.
Empty allow-list (deny all). Negative uid (invalid; deny).
O(n_allow).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.