From 0c1a3da8b8e185967acca0537e9652cc154ad7be Mon Sep 17 00:00:00 2001 From: Alyssa Ross Date: Fri, 19 Mar 2021 02:56:45 +0000 Subject: vsock: check socket family before reading sockaddr Extracting a helper function for this has the nice side effect of making the `cid' and `port' parameters to vsock_accept nullable, which is nice for consistency with vsock_get_cid_and_port. Message-Id: <20210319025648.17925-2-hi@alyssa.is> Reviewed-by: Cole Helbling --- vsock.c | 31 +++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) (limited to 'vsock.c') diff --git a/vsock.c b/vsock.c index 99945c3..6f1f466 100644 --- a/vsock.c +++ b/vsock.c @@ -5,6 +5,7 @@ #include "vsock.h" +#include #include #include @@ -17,6 +18,25 @@ static void fill_sockaddr(struct sockaddr_vm *addr, uint32_t cid, uint32_t port) addr->svm_port = port; } +static int fill_cid_and_port(const struct sockaddr_vm *addr, + uint32_t *cid, uint32_t *port) +{ + // Check that this sockaddr info is actually for the socket + // type we think it is, or we could get some very confusing + // data out of it. + if (addr->svm_family != AF_VSOCK) { + errno = EPROTOTYPE; + return -1; + } + + if (cid) + *cid = addr->svm_cid; + if (port) + *port = addr->svm_port; + + return 0; +} + int vsock_bind(int fd, uint32_t cid, uint32_t port) { struct sockaddr_vm addr = { 0 }; @@ -37,8 +57,8 @@ int vsock_accept(int sockfd, uint32_t *cid, uint32_t *port) if ((fd = accept(sockfd, (struct sockaddr *)&addr, &addr_size)) == -1) return -1; - *cid = addr.svm_cid; - *port = addr.svm_port; + if (fill_cid_and_port(&addr, cid, port) == -1) + return -1; return fd; } @@ -70,10 +90,5 @@ int vsock_get_cid_and_port(int fd, uint32_t *cid, uint32_t *port) if (getsockname(fd, (struct sockaddr *)&addr, &addrlen) == -1) return -1; - if (cid) - *cid = addr.svm_cid; - if (port) - *port = addr.svm_port; - - return 0; + return fill_cid_and_port(&addr, cid, port); } -- cgit 1.4.1