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

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.

Task

Implement int allow_peer(int peer_uid, const int *allow, int n_allow) that returns whether peer_uid is permitted.

Input

  • peer_uid: the connecting peer's user id (as SO_PEERCRED would report).
  • allow, n_allow: the allow-list array and its length.

Output

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.

Example

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)

Edge cases

  • Empty or NULL allow-list denies everyone.
  • A negative peer_uid is invalid and denied.
  • Root is allowed only when 0 is 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

The peer's uid plus an allow-list array allow of length n_allow.

Output format

1 if peer_uid is in the list, else 0.

Constraints

No implicit root: 0 must be explicitly listed. Empty/NULL list or negative uid denies.

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.