commit 99185f6cb5f6465d11adf3131d079209049f432c
parent ad20518bf7b7f5d4bf9238f7e87fe633a76adb74
Author: Santtu Lakkala <inz@inz.fi>
Date: Fri, 31 Jan 2025 14:05:05 +0200
Fix potential UB in unix sockets
Diffstat:
1 file changed, 16 insertions(+), 7 deletions(-)
diff --git a/xs_unix_socket.h b/xs_unix_socket.h
@@ -18,17 +18,21 @@ int xs_unix_socket_server(const char *path, const char *grp)
/* opens a unix-type server socket */
{
int rs = -1;
+ struct sockaddr_un su = {0};
+ socklen_t plen = strlen(path);
+
+ if (plen >= sizeof(su.sun_path)) return -1;
if ((rs = socket(AF_UNIX, SOCK_STREAM, 0)) != -1) {
- struct sockaddr_un su = {0};
mode_t mode = 0666;
su.sun_family = AF_UNIX;
- strncpy(su.sun_path, path, sizeof(su.sun_path));
+ memcpy(su.sun_path, path, plen + 1);
+ plen += offsetof(struct sockaddr_un, sun_path) + 1;
unlink(path);
- if (bind(rs, (struct sockaddr *)&su, sizeof(su)) == -1) {
+ if (bind(rs, (struct sockaddr *)&su, plen) == -1) {
close(rs);
return -1;
}
@@ -55,15 +59,20 @@ int xs_unix_socket_server(const char *path, const char *grp)
int xs_unix_socket_connect(const char *path)
/* connects to a unix-type socket */
{
+ struct sockaddr_un su = {0};
int d = -1;
- if ((d = socket(AF_UNIX, SOCK_STREAM, 0)) != -1) {
- struct sockaddr_un su = {0};
+ socklen_t plen = strlen(path);
+
+ if (plen >= sizeof(su.sun_path)) return -1;
+ if ((d = socket(AF_UNIX, SOCK_STREAM, 0)) != -1) {
su.sun_family = AF_UNIX;
- strncpy(su.sun_path, path, sizeof(su.sun_path));
+ memcpy(su.sun_path, path, plen + 1);
+
+ plen += offsetof(struct sockaddr_un, sun_path) + 1;
- if (connect(d, (struct sockaddr *)&su, sizeof(su)) == -1) {
+ if (connect(d, (struct sockaddr *)&su, plen) == -1) {
close(d);
d = -1;
}