Package: fakeroot
Version: 2.1.4-1
Severity: normal
Tags: patch

Hi,

faked in TCP mode reads every request with a single read(). TCP is a
byte stream, so once faked falls behind its client under CPU
contention, read() can return only part of a message. faked processes
the fragment as a complete message and reads the following data at the
wrong offset. Depending on what it reads, a request is swallowed and
the client blocks forever waiting for the reply, or the function id
hits a NULL entry (5, 6) or the out-of-bounds entry (11, process_msg()
checks with <=) of func_arr and faked crashes. Its clients then fail
with errors like "libfakeroot: write: Connection reset by peer". faked
has closed stderr by then, so the crash leaves no trace.

libfakeroot reads and writes complete messages; get_fakem() and
faked_send_fakem() in faked.c do not. The same code is in 1.37.1.2,
2.1.3 and 2.1.4.

We hit this error in OpenWrt, which builds fakeroot with --with-ipc=tcp
and runs every package installation of its ImageBuilder under fakeroot:
building several images in parallel sporadically fails with it.

The attached patch makes faked read and write complete messages, checks
the func_arr bounds and NULL entries (this part also affects the SysV
build), and drops a client that reset its connection instead of
exiting.

The attached script shows both effects with fakeroot-tcp. In test 1 a
client floods faked with requests while faked is paused repeatedly
(SIGSTOP/SIGCONT) so that requests pile up; the script pins all
processes to one CPU. Without the patch 16 of 30 runs deadlocked here
(fakeroot 2.1.3 as built by OpenWrt), with the patch none. Test 2
sends faked a single message with function id 5, as can happen after a
misaligned read; without the patch faked dies and the client fails,
with the patch faked survives.

OpenWrt pull request: https://github.com/openwrt/openwrt/pull/27080

Regards,
Martin Schiller
From 5f4e7d887b2ce9df2522779005e6fb4643e6d514 Mon Sep 17 00:00:00 2001
From: Martin Schiller <[email protected]>
Date: Tue, 1 Dec 2026 08:29:54 +0100
Subject: [PATCH] faked: handle partial messages in TCP mode

faked reads every request with a single read() call. TCP is a byte
stream, so as soon as faked lags behind its client (e.g. under CPU
contention) read() can return only part of a message. faked then
processes the fragment as a complete message and reads the following
data at the wrong offset:

 - requests are misinterpreted and their replies never sent, the client
   blocks forever in read() (hang)
 - a garbage function id hits a NULL slot (5, 6) or the out-of-bounds
   slot (11, check uses <=) of func_arr, faked crashes and its clients
   fail with errors like "libfakeroot: write: Connection reset by peer"

Read and write complete messages, check func_arr bounds and NULL slots,
and drop a client that reset its connection instead of exiting.

Signed-off-by: Martin Schiller <[email protected]>
---
 faked.c | 33 ++++++++++++++++++++++++---------
 1 file changed, 24 insertions(+), 9 deletions(-)

diff --git a/faked.c b/faked.c
index cc82afc..f530b00 100644
--- a/faked.c
+++ b/faked.c
@@ -461,12 +461,16 @@ static void faked_send_fakem(const struct fake_msg *buf)
   fm.xattr.flags_rc = htonl(buf->xattr.flags_rc);
   memcpy(fm.xattr.buf, buf->xattr.buf, MAX_IPC_BUFFER_SIZE);
 
-  while (1) {
+  size_t done = 0;
+
+  while (done < sizeof (fm)) {
     ssize_t len;
 
-    len = write(comm_sd, &fm, sizeof (fm));
-    if (len > 0)
-      break;
+    len = write(comm_sd, (char *) &fm + done, sizeof (fm) - done);
+    if (len > 0) {
+      done += len;
+      continue;
+    }
 
     if (errno == EINTR)
       continue;
@@ -1084,7 +1088,7 @@ void process_msg(struct fake_msg *buf){
 
   func_id_t f;
   f= buf->id;
-  if (f <= highest_funcid)
+  if (f < highest_funcid && func_arr[f])
     func_arr[f]((struct fake_msg*)buf);
 }
 
@@ -1335,12 +1339,19 @@ static long int read_intarg(char **argv)
 #ifdef FAKEROOT_FAKENET
 static int get_fakem(struct fake_msg *buf)
 {
-  while (1) {
+  size_t done = 0;
+
+  /* TCP is a byte stream: a message can arrive in several pieces, e.g.
+     when faked lags behind and the sender coalesces data. Never act on
+     a partial message, that desynchronizes the whole stream. */
+  while (done < sizeof (struct fake_msg)) {
     ssize_t len;
 
-    len = read(comm_sd, buf, sizeof (struct fake_msg));
-    if (len > 0)
-      break;
+    len = read(comm_sd, (char *) buf + done, sizeof (struct fake_msg) - done);
+    if (len > 0) {
+      done += len;
+      continue;
+    }
 
     if (len == 0)
       return -1;
@@ -1348,6 +1359,10 @@ static int get_fakem(struct fake_msg *buf)
     if (errno == EINTR)
       continue;
 
+    /* a single broken client must not take down the daemon */
+    if (errno == ECONNRESET)
+      return -1;
+
     fail("read");
   }
 
-- 
2.43.0

#!/bin/bash
# Reproducer for faked (TCP mode) misparsing partial messages under load.
#
# Usage: ./fakeroot-tcp-repro.sh [runs]
#   FAKEROOT / FAKED select the binaries (default: fakeroot-tcp / faked-tcp),
#   N / EVERY / TIMEOUT tune the load (iterations, iterations per stat,
#   seconds per run).
#
# All processes are pinned to one CPU to create the CPU contention under
# which the bug shows up.
#
# Test 1 lets a client flood faked with chown/chmod requests and do a stat
#        round trip every 1000 iterations, while faked is paused for 20 ms
#        every 20 ms (SIGSTOP/SIGCONT) so that requests pile up. With the
#        bug, some runs deadlock: faked idles in select(), the client waits
#        in read(). A run only counts as a hang if neither process uses CPU
#        any more; runs that are merely slow are reported separately. The
#        rate depends on the machine; raise runs if nothing hangs.
# Test 2 sends faked one message with function id 5 (a NULL slot in
#        func_arr), as can happen when the stream is misaligned. With the
#        bug, faked crashes and the client fails with "libfakeroot: ...".
set -u
RUNS=${1:-20}; TIMEOUT=${TIMEOUT:-30}; N=${N:-60000}; EVERY=${EVERY:-1000}
FAKEROOT=${FAKEROOT:-fakeroot-tcp}; FAKED=${FAKED:-faked-tcp}
command -v taskset >/dev/null || { echo "taskset (util-linux) is required"; exit 1; }
CPU=$(taskset -pc $$ | sed 's/.*: *//; s/[,-].*//')	# first CPU we may use
taskset -pc "$CPU" $$ >/dev/null	# inherited by everything started below
W=$(mktemp -d); PAUSER=""
cleanup() {
	[ -n "$PAUSER" ] && kill $PAUSER 2>/dev/null
	pkill -KILL -f "^$W/client" 2>/dev/null
	[ -f "$W/faked.out" ] && kill -KILL "$(cut -d: -f2 "$W/faked.out")" 2>/dev/null
	rm -rf "$W"
}
trap cleanup EXIT
trap 'exit 130' INT TERM

cat > "$W/client.c" <<'C'
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char **argv)
{
	int n = atoi(argv[1]), every = atoi(argv[2]);
	char fn[4096];
	struct stat st;

	signal(SIGPIPE, SIG_IGN);	/* like apk */
	mkdir(argv[3], 0755);
	for (int i = 0; i < n; i++) {
		snprintf(fn, sizeof fn, "%s/f%d", argv[3], i % 500);
		int fd = open(fn, O_CREAT | O_WRONLY | O_TRUNC, 0600);
		if (fd < 0) { perror("open"); return 2; }
		if (fchown(fd, 0, 0) || fchmod(fd, 0644)) perror("fchown/fchmod");
		close(fd);
		if (chown(fn, 0, 0)) perror("chown");
		if (i % every == 0 && stat(fn, &st)) { perror("stat"); return 3; }
	}
	return 0;
}
C
gcc -O2 -o "$W/client" "$W/client.c" || exit 1

# faked wrapper: remember the daemon's pid (faked prints "port:pid")
cat > "$W/faked" <<SH
#!/bin/sh
out=\$("$FAKED" "\$@") || exit \$?
echo "\$out" > "$W/faked.out"
echo "\$out"
SH
chmod +x "$W/faked"

ticks() { [ -n "$1" ] && awk '{print $14 + $15}' "/proc/$1/stat" 2>/dev/null; }

hangs=0; slow=0; fails=0
for i in $(seq 1 "$RUNS"); do
	rm -rf "$W/root" "$W/faked.out"
	"$FAKEROOT" -f "$W/faked" "$W/client" "$N" "$EVERY" "$W/root" > "$W/log" 2>&1 &
	pid=$!
	while [ ! -s "$W/faked.out" ] && kill -0 $pid 2>/dev/null; do sleep 0.01; done
	fpid=$(cut -d: -f2 "$W/faked.out" 2>/dev/null)
	if [ -n "$fpid" ]; then
		( while kill -0 "$fpid"; do
			kill -STOP "$fpid"; sleep 0.02; kill -CONT "$fpid"; sleep 0.02
		  done ) 2>/dev/null &
		PAUSER=$!
	fi
	for t in $(seq 1 $((TIMEOUT * 10))); do kill -0 $pid 2>/dev/null || break; sleep 0.1; done
	[ -n "$PAUSER" ] && { kill $PAUSER; wait $PAUSER; } 2>/dev/null; PAUSER=""
	[ -n "$fpid" ] && kill -CONT "$fpid" 2>/dev/null
	if kill -0 $pid 2>/dev/null; then
		# still running after TIMEOUT: deadlocked, or just slow?
		cpid=$(pgrep -f "^$W/client" | head -1)
		a="$(ticks "$fpid") $(ticks "$cpid")"; sleep 3
		b="$(ticks "$fpid") $(ticks "$cpid")"
		if kill -0 $pid 2>/dev/null && [ "$a" = "$b" ]; then
			hangs=$((hangs + 1)); echo "run $i: HANG (faked and client idle)"
		else
			slow=$((slow + 1)); echo "run $i: still working after ${TIMEOUT}s (not a hang)"
		fi
		pkill -KILL -f "^$W/client" 2>/dev/null
		kill -KILL "$fpid" 2>/dev/null
		wait $pid 2>/dev/null
	elif ! wait $pid; then
		fails=$((fails + 1)); echo "run $i: FAILED: $(tr '\n' ' ' < "$W/log")"
	fi
	rm -f "$W/faked.out"
done
echo "Test 1: $hangs hangs, $slow too slow, $fails failures in $RUNS runs"

# Test 2: one message with function id 5 while a client is busy
rm -rf "$W/root"
"$FAKEROOT" -f "$FAKED" bash -c '
	"$1" 300000 1000000 "$2" & c=$!
	sleep 0.5
	# send it from a process that does not depend on faked itself
	env -u LD_PRELOAD bash -c "exec 3<>/dev/tcp/127.0.0.1/\$FAKEROOTKEY;
		printf \"\\000\\000\\000\\005%01076d\" 0 >&3"
	wait $c' _ "$W/client" "$W/root" > "$W/log" 2>&1
rc=$?
if [ $rc -eq 0 ]; then echo "Test 2: faked survived the message (OK)"
else echo "Test 2: client failed (rc=$rc): $(tr '\n' ' ' < "$W/log")"; fi

Reply via email to