1
0
mirror of https://passt.top/passt synced 2024-12-22 05:35:23 +00:00

tap: Correctly handle frames of odd length

The Qemu socket protocol consists of a 32-bit frame length in network (BE)
order, followed by the Ethernet frame itself.  As far as I can tell,
frames can be any length, with no particular alignment requirement.  This
means that although pkt_buf itself is aligned, if we have a frame of odd
length, frames after it will have their frame length at an unaligned
address.

Currently we load the frame length by just casting a char pointer to
(uint32_t *) and loading.  Some platforms will generate a fatal trap on
such an unaligned load.  Even if they don't casting an incorrectly aligned
pointer to (uint32_t *) is undefined behaviour, strictly speaking.

Introduce a new helper to safely load a possibly unaligned value here.  We
assume that the compiler is smart enough to optimize this into nothing on
platforms that provide performant unaligned loads.  If that turns out not
to be the case, we can look at improvements then.

Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
Signed-off-by: Stefano Brivio <sbrivio@redhat.com>
This commit is contained in:
David Gibson 2024-07-26 17:20:30 +10:00 committed by Stefano Brivio
parent 4684f60344
commit 37e3b24d90
2 changed files with 17 additions and 1 deletions

2
tap.c
View File

@ -1011,7 +1011,7 @@ void tap_handler_passt(struct ctx *c, uint32_t events,
}
while (n > (ssize_t)sizeof(uint32_t)) {
uint32_t l2len = ntohl(*(uint32_t *)p);
uint32_t l2len = ntohl_unaligned(p);
if (l2len < sizeof(struct ethhdr) || l2len > ETH_MAX_MTU) {
err("Bad frame size from guest, resetting connection");

16
util.h
View File

@ -10,8 +10,10 @@
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include <signal.h>
#include <arpa/inet.h>
#include "log.h"
@ -116,6 +118,20 @@
#define htonl_constant(x) (__bswap_constant_32(x))
#endif
/**
* ntohl_unaligned() - Read 32-bit BE value from a possibly unaligned address
* @p: Pointer to the BE value in memory
*
* Returns: Host-order value of 32-bit BE quantity at @p
*/
static inline uint32_t ntohl_unaligned(const void *p)
{
uint32_t val;
memcpy(&val, p, sizeof(val));
return ntohl(val);
}
#define NS_FN_STACK_SIZE (RLIMIT_STACK_VAL * 1024 / 8)
int do_clone(int (*fn)(void *), char *stack_area, size_t stack_size, int flags,
void *arg);