linux-sysprog · intermediate · ~15 min

Refuse a Unix-socket peer unless their UID is on the allow-list

Validate Unix-socket peer credentials before processing the protocol.

Challenge

You've just accepted a Unix-socket connection. SO_PEERCRED gave you the peer's (pid, uid, gid). Implement int allow_peer(int peer_uid, const int *allow, int n_allow) returning 1 if peer_uid is in the allow-list array, else 0. Allow uid 0 (root) ONLY when 0 is explicitly in the list.

Why this matters

Unix socket connections carry the peer's real uid via SO_PEERCRED. Refusing connections by uid is the cheapest in-protocol authentication.

Input format

Peer uid + allow-list.

Output format

0/1.

Constraints

Allow only when uid is in list. No implicit root.

Starter code

int allow_peer(int peer_uid, const int *allow, int n_allow) { /* TODO */ (void)peer_uid; (void)allow; (void)n_allow; return 0; }

Common mistakes

Special-casing uid==0 as 'always allow' — root must be explicitly listed.

Edge cases to handle

Empty allow-list (deny all). Negative uid (invalid; deny).

Complexity

O(n_allow).

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.