From 5bb82a2ad0475e3d949c99d0147c5e21da520b76 Mon Sep 17 00:00:00 2001 From: dmiller Date: Wed, 3 Sep 2025 17:04:46 +0000 Subject: [PATCH] Fix crash in socket_bindtodevice: NULL device is permissible --- libnetutil/netutil.cc | 4 +++- nbase/nbase_misc.c | 28 +++++++++++++++------------- 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/libnetutil/netutil.cc b/libnetutil/netutil.cc index b13928d5c..7819de50c 100644 --- a/libnetutil/netutil.cc +++ b/libnetutil/netutil.cc @@ -1120,7 +1120,9 @@ int netutil_raw_socket(const char *device) { netutil_perror("setsockopt(SO_BROADCAST) failed"); } sethdrinclude(rawsd); - socket_bindtodevice(rawsd, device); + if (device) { + socket_bindtodevice(rawsd, device); + } return rawsd; #endif diff --git a/nbase/nbase_misc.c b/nbase/nbase_misc.c index 4ecee7c62..43d846a1f 100644 --- a/nbase/nbase_misc.c +++ b/nbase/nbase_misc.c @@ -266,20 +266,22 @@ int block_socket(int sd) { int socket_bindtodevice(int sd, const char *device) { #ifdef SO_BINDTODEVICE char padded[sizeof(int)]; - size_t len; + size_t len = 0; - len = strlen(device) + 1; - /* In Linux 2.6.20 and earlier, there is a bug in SO_BINDTODEVICE that causes - EINVAL to be returned if the optlen < sizeof(int); this happens for example - with the interface names "" and "lo". Pad the string with null characters - so it is above this limit if necessary. - http://article.gmane.org/gmane.linux.network/71887 - http://article.gmane.org/gmane.linux.network/72216 */ - if (len < sizeof(padded)) { - /* We rely on strncpy padding with nulls here. */ - strncpy(padded, device, sizeof(padded)); - device = padded; - len = sizeof(padded); + if (device) { + len = strlen(device) + 1; + /* In Linux 2.6.20 and earlier, there is a bug in SO_BINDTODEVICE that causes + EINVAL to be returned if the optlen < sizeof(int); this happens for example + with the interface names "" and "lo". Pad the string with null characters + so it is above this limit if necessary. + http://article.gmane.org/gmane.linux.network/71887 + http://article.gmane.org/gmane.linux.network/72216 */ + if (len < sizeof(padded)) { + /* We rely on strncpy padding with nulls here. */ + strncpy(padded, device, sizeof(padded)); + device = padded; + len = sizeof(padded); + } } /* Linux-specific sockopt asking to use a specific interface. See socket(7). */