fix(prodtest): buffer emulator responses
What changed, and why it matters
This commit fixes a bug in the Trezor firmware emulator's USB-over-UDP test path where long responses could lose trailing bytes. The fix adds a small transmit buffer and a periodic flush thread so the emulator splits large replies into small UDP datagrams instead of sending one oversized packet that the host silently truncates. The affected code is only used in emulator/production-test builds, not on real Trezor hardware, so it does not directly endanger user funds or device security.
Treat as a reliability/functional bug fix rather than a security vulnerability. Review the new flush thread for correct shutdown ordering and mutex lifetime; confirm no use-after-free or deadlock can occur if usb_stop() is called while usb_emulated_write() holds the lock. No urgent user action is required because the change only affects emulator builds.
Security signals we found
Buffer sizing mismatch between sender and receiver causing silent truncation
Addition of concurrency control (pthread mutex) around socket send/receive
New periodic flush thread changes timing/atomicity of network output
Test updated to assert complete delivery of long responses
Evidence from the diff
The emulator’s VCP (virtual COM port) implementation previously called sock_sendto() directly for every write, which for large replies produced datagrams larger than the host’s 4096-byte receive buffer. The patch introduces a 128-byte TX buffer and a 10 ms flush thread for VCP interfaces, coalescing/breaking writes into small datagrams. It also adds a pthread mutex around sock_recvfrom() and sock_sendto() to satisfy the documented thread-safety contract. A const-correctness fix in cli_ok_hexdata() and an updated prodtest ping test (now asserting full echo of a >4096 byte response) accompany the change.
Changed components
core/embed/io/usb/unix/usb.c (emulator USB VCP/UDP stack)core/embed/io/usb/inc/io/unix/sock.h (thread-safety contract documentation)core/embed/rtl/cli.c (const-correctness in hex formatter)tests/prodtest_tests/test_ping.py (prodtest ping regression test)Inspect captured patch +130 / −25
### core/embed/io/usb/inc/io/unix/sock.h
@@ -11,6 +11,10 @@
/// Emulator datagram socket, for USB and BLE. Currently uses UDP but can be
/// possibly switched to unix datagram sockets.
+///
+/// Thread-safety: `sock_sendto()`, `sock_can_send()` and `sock_can_recv()`
+/// may be called concurrently with each other. Any other use requires
+/// exclusive access to the socket.
typedef struct {
/// Port number.
uint16_t port;
### core/embed/io/usb/unix/usb.c
@@ -21,10 +21,12 @@
#include <arpa/inet.h>
#include <fcntl.h>
+#include <pthread.h>
#include <stdlib.h>
#include <sys/poll.h>
#include <sys/socket.h>
#include <sys/sysevent_source.h>
+#include <sys/systick.h>
#include <time.h>
#include <unistd.h>
@@ -39,6 +41,12 @@
#define USBD_MAX_NUM_INTERFACES 8
+#define USB_RX_BUFFER_SIZE 64
+
+// These apply only to the USB VCP interface
+#define USB_TX_BUFFER_SIZE 128
+#define USB_FLUSH_INTERVAL_MS 10
+
typedef enum {
USB_IFACE_TYPE_DISABLED = 0,
USB_IFACE_TYPE_VCP = 1,
@@ -51,14 +59,23 @@ typedef struct {
usb_iface_type_t type;
uint16_t port;
emu_sock_t sock;
- uint8_t msg[64];
- int msg_len;
+ uint8_t rx_buf[USB_RX_BUFFER_SIZE];
+ int rx_len;
+ // Guards `tx_buf`, `tx_len` and `flush_thread_running`, and serializes
+ // `sock_recvfrom()` with the flush thread's `sock_sendto()` (see `sock.h`).
+ pthread_mutex_t sock_lock;
+ uint8_t tx_buf[USB_TX_BUFFER_SIZE];
+ size_t tx_len;
+ pthread_t flush_thread;
+ bool flush_thread_running;
} usb_iface_t;
static usb_iface_t usb_ifaces[USBD_MAX_NUM_INTERFACES];
// forward declaration
static const syshandle_vmt_t usb_iface_handle_vmt;
+static void *usb_flush_thread(void *arg);
+static void usb_flush(usb_iface_t *iface);
secbool usb_init(const usb_dev_info_t *dev_info) {
UNUSED(dev_info);
@@ -68,13 +85,21 @@ secbool usb_init(const usb_dev_info_t *dev_info) {
iface->type = USB_IFACE_TYPE_DISABLED;
iface->port = 0;
sock_init(&iface->sock);
- memzero(&iface->msg, sizeof(usb_ifaces[i].msg));
- iface->msg_len = 0;
+ memzero(&iface->rx_buf, sizeof(usb_ifaces[i].rx_buf));
+ iface->rx_len = 0;
+ pthread_mutex_init(&iface->sock_lock, NULL);
+ iface->tx_len = 0;
+ iface->flush_thread_running = false;
}
return sectrue;
}
-void usb_deinit(void) { usb_stop(); }
+void usb_deinit(void) {
+ usb_stop();
+ for (int i = 0; i < USBD_MAX_NUM_INTERFACES; i++) {
+ pthread_mutex_destroy(&usb_ifaces[i].sock_lock);
+ }
+}
secbool usb_start(const usb_start_params_t *params) {
const char *ip = getenv("TREZOR_UDP_IP");
@@ -94,6 +119,13 @@ secbool usb_start(const usb_start_params_t *params) {
ensure(sectrue *
syshandle_register(iface->handle, &usb_iface_handle_vmt, iface),
NULL);
+
+ if (iface->type == USB_IFACE_TYPE_VCP) {
+ iface->flush_thread_running = true;
+ ensure(sectrue * (0 == pthread_create(&iface->flush_thread, NULL,
+ usb_flush_thread, iface)),
+ NULL);
+ }
}
return sectrue;
@@ -102,6 +134,15 @@ secbool usb_start(const usb_start_params_t *params) {
void usb_stop(void) {
for (int i = 0; i < USBD_MAX_NUM_INTERFACES; i++) {
usb_iface_t *iface = &usb_ifaces[i];
+
+ if (iface->flush_thread_running) {
+ pthread_mutex_lock(&iface->sock_lock);
+ iface->flush_thread_running = false;
+ pthread_mutex_unlock(&iface->sock_lock);
+
+ pthread_join(iface->flush_thread, NULL);
+ }
+
sock_stop(&iface->sock);
syshandle_unregister(iface->handle);
}
@@ -147,29 +188,34 @@ secbool usb_vcp_add(const usb_vcp_info_t *info) {
}
static secbool usb_emulated_poll_read(usb_iface_t *iface) {
- if (iface->msg_len > 0) {
+ if (iface->rx_len > 0) {
return sectrue;
}
if (!sock_can_recv(&iface->sock)) {
return secfalse;
}
- size_t len = sock_recvfrom(&iface->sock, iface->msg, sizeof(iface->msg));
+ pthread_mutex_lock(&iface->sock_lock);
+ // Flush buffered bytes before `sock_recvfrom()` changes `si_other`.
+ usb_flush(iface);
+ size_t len =
+ sock_recvfrom(&iface->sock, iface->rx_buf, sizeof(iface->rx_buf));
+ pthread_mutex_unlock(&iface->sock_lock);
if (!len) {
return secfalse;
}
static const char *ping_req = "PINGPING";
static const char *ping_resp = "PONGPONG";
if (len == strlen(ping_req) &&
- 0 == memcmp(ping_req, iface->msg, strlen(ping_req))) {
+ 0 == memcmp(ping_req, iface->rx_buf, strlen(ping_req))) {
sock_sendto(&iface->sock, (const uint8_t *)ping_resp, strlen(ping_resp));
- memzero(iface->msg, sizeof(iface->msg));
+ memzero(iface->rx_buf, sizeof(iface->rx_buf));
return secfalse;
}
- iface->msg_len = len;
+ iface->rx_len = len;
return sectrue;
}
@@ -179,28 +225,79 @@ static secbool usb_emulated_poll_write(usb_iface_t *iface) {
}
static int usb_emulated_read(usb_iface_t *iface, uint8_t *buf, size_t len) {
- if (iface->msg_len > 0) {
- if ((size_t)iface->msg_len < len) {
- len = iface->msg_len;
+ if (iface->rx_len > 0) {
+ if ((size_t)iface->rx_len < len) {
+ len = iface->rx_len;
}
- memcpy(buf, iface->msg, len);
+ memcpy(buf, iface->rx_buf, len);
if (iface->type == USB_IFACE_TYPE_VCP) {
- iface->msg_len -= len;
- memmove(iface->msg, iface->msg + len, iface->msg_len);
+ iface->rx_len -= len;
+ memmove(iface->rx_buf, iface->rx_buf + len, iface->rx_len);
} else {
- iface->msg_len = 0;
- memzero(iface->msg, sizeof(iface->msg));
+ iface->rx_len = 0;
+ memzero(iface->rx_buf, sizeof(iface->rx_buf));
}
return len;
}
return 0;
}
+static void usb_flush(usb_iface_t *iface) {
+ if (iface->tx_len > 0) {
+ // Best effort - a failed datagram send cannot be retried meaningfully.
+ sock_sendto(&iface->sock, iface->tx_buf, iface->tx_len);
+ iface->tx_len = 0;
+ }
+}
+
+static void *usb_flush_thread(void *arg) {
+ usb_iface_t *iface = (usb_iface_t *)arg;
+ bool running = true;
+
+ while (running) {
+ systick_delay_ms(USB_FLUSH_INTERVAL_MS);
+
+ pthread_mutex_lock(&iface->sock_lock);
+ usb_flush(iface);
+ running = iface->flush_thread_running;
+ pthread_mutex_unlock(&iface->sock_lock);
+ }
+
+ return NULL;
+}
+
static ssize_t usb_emulated_write(usb_iface_t *iface, const uint8_t *buf,
uint32_t len) {
- return sock_sendto(&iface->sock, buf, len);
+ if (iface->type != USB_IFACE_TYPE_VCP) {
+ return sock_sendto(&iface->sock, buf, len);
+ }
+
+ pthread_mutex_lock(&iface->sock_lock);
+
+ if (!iface->flush_thread_running) {
+ pthread_mutex_unlock(&iface->sock_lock);
+ return -1;
+ }
+
+ size_t written = 0;
+ while (written < len) {
+ size_t space = sizeof(iface->tx_buf) - iface->tx_len;
+ size_t chunk = MIN(space, (size_t)len - written);
+
+ memcpy(&iface->tx_buf[iface->tx_len], buf + written, chunk);
+ iface->tx_len += chunk;
+ written += chunk;
+
+ if (iface->tx_len == sizeof(iface->tx_buf)) {
+ usb_flush(iface);
+ }
+ }
+
+ pthread_mutex_unlock(&iface->sock_lock);
+
+ return (ssize_t)written;
}
secbool usb_configured(void) {
### core/embed/rtl/cli.c
@@ -150,7 +150,7 @@ void cli_ok_hexdata(cli_t* cli, const void* data, size_t size) {
if (size > 0) {
cli_printf(cli, " ");
for (size_t i = 0; i < size; i++) {
- cli_printf(cli, "%02X", ((uint8_t*)data)[i]);
+ cli_printf(cli, "%02X", ((const uint8_t*)data)[i]);
}
}
cli_printf_newline(cli);
### tests/prodtest_tests/test_ping.py
@@ -32,10 +32,14 @@ def test_ping_with_text(client: ProdtestClient) -> None:
def test_ping_with_long_text(client: ProdtestClient) -> None:
- """ping echoes text up to the CLI line buffer, truncating anything beyond."""
- long_text = 512 * "longtext"
+ """ping should echo back long text without dropping bytes.
+
+ The text length is chosen so that the response exceeds the 4096-byte
+ buffer the host reads datagrams into (see ``VcpUdpTransport.readline``).
+ The full echo thus verifies that the emulator splits responses into
+ small datagrams. A single oversized datagram would get silently
+ truncated by the host and the trailing bytes would be lost.
+ """
+ long_text = 512 * "longtext" + "A"
resp = client.command_ok(ProdtestCommand(Cmd.PING, long_text))
assert resp.args == long_text
- too_long_text = long_text + "A"
- resp = client.command_ok(ProdtestCommand(Cmd.PING, too_long_text))
- assert resp.args == long_textWhy this scored 19/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.