Skip to content

Commit 2a715f7

Browse files
committed
Implement connections to TCP-based services
Both IPv4 and IPv6 are supported. The port or both host and port can be taken from the service argument instead of the symbolic link name. Of course, there are full unit tests. Fixes: QubesOS/qubes-issues#9037
1 parent 8dfd4b0 commit 2a715f7

File tree

5 files changed

+232
-11
lines changed

5 files changed

+232
-11
lines changed

libqrexec/exec.c

+131-8
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,12 @@
2727
#include <stddef.h>
2828
#include <limits.h>
2929

30-
#include <sys/socket.h>
3130
#include <sys/types.h>
31+
#include <sys/socket.h>
3232
#include <sys/stat.h>
3333
#include <sys/un.h>
3434
#include <sys/wait.h>
35+
#include <netdb.h>
3536
#include <unistd.h>
3637
#include <fcntl.h>
3738
#include "qrexec.h"
@@ -206,7 +207,7 @@ static int qubes_connect(int s, const char *connect_path, const size_t total_pat
206207
}
207208

208209
static int execute_qrexec_service(
209-
const struct qrexec_parsed_command *cmd,
210+
struct qrexec_parsed_command *cmd,
210211
int *pid, int *stdin_fd, int *stdout_fd, int *stderr_fd,
211212
struct buffer *stdin_buffer);
212213

@@ -418,7 +419,7 @@ struct qrexec_parsed_command *parse_qubes_rpc_command(
418419
/* Parse service name ("qubes.Service") */
419420

420421
const char *const plus = memchr(start, '+', descriptor_len);
421-
size_t const name_len = plus != NULL ? (size_t)(plus - start) : descriptor_len;
422+
size_t name_len = plus != NULL ? (size_t)(plus - start) : descriptor_len;
422423
if (name_len > NAME_MAX) {
423424
LOG(ERROR, "Service name too long to execute (length %zu)", name_len);
424425
goto err;
@@ -430,6 +431,7 @@ struct qrexec_parsed_command *parse_qubes_rpc_command(
430431
cmd->service_name = memdupnul(start, name_len);
431432
if (!cmd->service_name)
432433
goto err;
434+
cmd->arg = plus != NULL ? plus + 1 : NULL;
433435

434436
/* If there is no service argument, add a trailing "+" to the descriptor */
435437
cmd->service_descriptor = memdupnul(start, descriptor_len + (plus == NULL));
@@ -487,7 +489,7 @@ int execute_qubes_rpc_command(const char *cmdline, int *pid, int *stdin_fd,
487489
}
488490

489491
int execute_parsed_qubes_rpc_command(
490-
const struct qrexec_parsed_command *cmd, int *pid, int *stdin_fd,
492+
struct qrexec_parsed_command *cmd, int *pid, int *stdin_fd,
491493
int *stdout_fd, int *stderr_fd, struct buffer *stdin_buffer) {
492494
if (cmd->service_descriptor) {
493495
// Proper Qubes RPC call
@@ -499,9 +501,81 @@ int execute_parsed_qubes_rpc_command(
499501
pid, stdin_fd, stdout_fd, stderr_fd);
500502
}
501503
}
504+
static bool validate_port(const char *port) {
505+
#define MAXPORT "65535"
506+
#define MAXPORTLEN (sizeof MAXPORT - 1)
507+
if (*port < '1' || *port > '9')
508+
return false;
509+
const char *p = port + 1;
510+
for (; *p != 0; ++p) {
511+
if (*p < '0' || *p > '9')
512+
return false;
513+
}
514+
if (p - port > (ptrdiff_t)MAXPORTLEN)
515+
return false;
516+
if (p - port < (ptrdiff_t)MAXPORTLEN)
517+
return true;
518+
return memcmp(port, MAXPORT, MAXPORTLEN) <= 0;
519+
#undef MAXPORT
520+
#undef MAXPORTLEN
521+
}
522+
523+
static int qubes_tcp_connect(const char *host, const char *port)
524+
{
525+
// Work around a glibc bug: overly-large port numbers not rejected
526+
if (!validate_port(port)) {
527+
LOG(ERROR, "Invalid port number %s", port);
528+
return -1;
529+
}
530+
/* If there is ':' or '%' in the host, then this must be an IPv6 address, not IPv4. */
531+
bool const must_be_ipv6_addr = strchr(host, ':') != NULL || strchr(host, '%') != NULL;
532+
LOG(DEBUG, "Connecting to %s%s%s:%s",
533+
must_be_ipv6_addr ? "[" : "",
534+
host,
535+
must_be_ipv6_addr ? "]" : "",
536+
port);
537+
struct addrinfo hints = {
538+
.ai_flags = AI_NUMERICSERV | AI_NUMERICHOST,
539+
.ai_family = must_be_ipv6_addr ? AF_INET6 : AF_UNSPEC,
540+
.ai_socktype = SOCK_STREAM,
541+
.ai_protocol = IPPROTO_TCP,
542+
}, *addrs;
543+
int rc = getaddrinfo(host, port, &hints, &addrs);
544+
if (rc != 0) {
545+
/* data comes from symlink or from qrexec service argument, which has already
546+
* been sanitized */
547+
LOG(ERROR, "getaddrinfo(%s, %s) failed: %s", host, port, gai_strerror(rc));
548+
return -1;
549+
}
550+
rc = -1;
551+
assert(addrs != NULL && "getaddrinfo() returned zero addresses");
552+
assert(addrs->ai_next == NULL &&
553+
"getaddrinfo() returned multiple addresses despite AI_NUMERICHOST | AI_NUMERICSERV");
554+
int sockfd = socket(addrs->ai_family,
555+
addrs->ai_socktype | SOCK_CLOEXEC,
556+
addrs->ai_protocol);
557+
if (sockfd < 0)
558+
goto freeaddrs;
559+
{
560+
int one = 1;
561+
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one) != 0)
562+
abort();
563+
}
564+
int res = connect(sockfd, addrs->ai_addr, addrs->ai_addrlen);
565+
if (res != 0) {
566+
PERROR("connect");
567+
close(sockfd);
568+
} else {
569+
rc = sockfd;
570+
LOG(DEBUG, "Connection succeeded");
571+
}
572+
freeaddrs:
573+
freeaddrinfo(addrs);
574+
return rc;
575+
}
502576

503577
static int execute_qrexec_service(
504-
const struct qrexec_parsed_command *cmd,
578+
struct qrexec_parsed_command *cmd,
505579
int *pid, int *stdin_fd, int *stdout_fd, int *stderr_fd,
506580
struct buffer *stdin_buffer) {
507581

@@ -527,10 +601,11 @@ static int execute_qrexec_service(
527601
return -1;
528602
}
529603

604+
const char *desc = cmd->command + RPC_REQUEST_COMMAND_LEN + 1;
530605
if (S_ISSOCK(statbuf.st_mode)) {
531606
/* Socket-based service. */
532607
int s;
533-
if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
608+
if ((s = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)) == -1) {
534609
PERROR("socket");
535610
return -1;
536611
}
@@ -544,14 +619,62 @@ static int execute_qrexec_service(
544619
if (stderr_fd)
545620
*stderr_fd = -1;
546621
*pid = 0;
547-
set_nonblock(s);
548622

549623
if (cmd->send_service_descriptor) {
550624
/* send part after "QUBESRPC ", including trailing NUL */
551-
const char *desc = cmd->command + RPC_REQUEST_COMMAND_LEN + 1;
552625
buffer_append(stdin_buffer, desc, strlen(desc) + 1);
553626
}
554627
return 0;
628+
} else if (S_ISLNK(statbuf.st_mode)) {
629+
if (stderr_fd)
630+
*stderr_fd = -1;
631+
*pid = 0;
632+
/* TCP-based service */
633+
assert(memcmp(service_full_path, "/dev/tcp/", sizeof "/dev/tcp") == 0);
634+
char *address = service_full_path + sizeof "/dev/tcp";
635+
char *slash = strchr(address, '/');
636+
char *host, *port;
637+
if (slash == NULL) {
638+
if (cmd->arg == NULL || *cmd->arg == ' ') {
639+
LOG(ERROR, "No or empty argument provided, cannot connect to %s",
640+
service_full_path);
641+
return -1;
642+
}
643+
char *ptr = cmd->service_descriptor + (cmd->arg - desc);
644+
if (*address == '\0') {
645+
/* Get both host and port from service arguments */
646+
host = ptr;
647+
port = strrchr(ptr, '+');
648+
if (port == NULL) {
649+
LOG(ERROR, "No host provided, cannot connect at %s", service_full_path);
650+
return -1;
651+
}
652+
*port = '\0';
653+
for (char *p = host; p < port; ++p) {
654+
if (*p == '_') {
655+
LOG(ERROR, "Underscore not allowed in hostname %s", host);
656+
return -1;
657+
}
658+
if (*p == '+')
659+
*p = ':';
660+
}
661+
port++;
662+
} else {
663+
/* Get just port from service arguments */
664+
host = address;
665+
port = ptr;
666+
}
667+
} else {
668+
*slash = '\0';
669+
host = address;
670+
port = slash + 1;
671+
}
672+
int res = qubes_tcp_connect(host, port);
673+
if (res == -1)
674+
return -1;
675+
*stdin_fd = *stdout_fd = res;
676+
cmd->send_service_descriptor = false;
677+
return 0;
555678
}
556679

557680
if (euidaccess(service_full_path, X_OK) == 0) {

libqrexec/libqrexec-utils.h

+11-2
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,9 @@ struct buffer {
4848
#define WRITE_STDIN_BUFFERED 1 /* something still in the buffer */
4949
#define WRITE_STDIN_ERROR 2 /* write error, errno set */
5050

51-
/* Parsed Qubes RPC or legacy command. */
51+
/* Parsed Qubes RPC or legacy command.
52+
* The size of this structure is not part of the public API or ABI.
53+
* Only use instances allocated by libqrexec-utils. */
5254
struct qrexec_parsed_command {
5355
const char *cmdline;
5456

@@ -82,6 +84,13 @@ struct qrexec_parsed_command {
8284

8385
/* For socket-based services: Should the service descriptor be sent? */
8486
bool send_service_descriptor;
87+
88+
/* Remaining fields are private to libqrexec-utils. Do not access them
89+
* directly - they may change in any update. */
90+
91+
/* Pointer to the argument, or NULL if there is no argument.
92+
* Same buffer as "command" and "cmdline". */
93+
const char *arg;
8594
};
8695

8796
/* Parse a command, return NULL on failure. Uses cmd->cmdline
@@ -142,7 +151,7 @@ int fork_and_flush_stdin(int fd, struct buffer *buffer);
142151
* nonzero on failure.
143152
*/
144153
int execute_parsed_qubes_rpc_command(
145-
const struct qrexec_parsed_command *cmd, int *pid, int *stdin_fd,
154+
struct qrexec_parsed_command *cmd, int *pid, int *stdin_fd,
146155
int *stdout_fd, int *stderr_fd, struct buffer *stdin_buffer);
147156

148157
/**

libqrexec/process_io.c

+1-1
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ static void close_stdout(int fd, bool restore_block) {
7676
} else if (shutdown(fd, SHUT_RD) == -1) {
7777
if (errno == ENOTSOCK)
7878
close(fd);
79-
else
79+
else if (errno != ENOTCONN) /* can happen with TCP, harmless */
8080
PERROR("shutdown close_stdout");
8181
}
8282
}

qrexec/tests/socket/agent.py

+88
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
import os.path
2323
import os
2424
import tempfile
25+
import socket
2526
import shutil
2627
import struct
2728
import getpass
@@ -702,6 +703,93 @@ def test_connect_socket_no_metadata(self):
702703
)
703704
self.check_dom0(dom0)
704705

706+
def test_connect_socket_tcp(self):
707+
socket_path = os.path.join(
708+
self.tempdir, "rpc", "qubes.SocketService+arg"
709+
)
710+
port = 65534
711+
host = "127.0.0.1"
712+
os.symlink(f"/dev/tcp/{host}/{port}", socket_path)
713+
self._test_tcp(socket.AF_INET, "qubes.SocketService+arg", host, port)
714+
715+
def _test_tcp_raw(self, family: int, service: str, host: str, port: int, accept=True):
716+
server = socket.socket(family, socket.SOCK_STREAM, socket.IPPROTO_TCP)
717+
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
718+
server.bind((host, port))
719+
server.listen(1)
720+
server = qrexec.QrexecServer(server)
721+
self.addCleanup(server.close)
722+
723+
target, dom0 = self.execute_qubesrpc(service, "domX")
724+
if accept:
725+
server.accept()
726+
message = b"stdin data"
727+
target.send_message(qrexec.MSG_DATA_STDIN, message)
728+
target.send_message(qrexec.MSG_DATA_STDIN, b"")
729+
if accept:
730+
self.assertEqual(server.recvall(len(message)), message)
731+
server.sendall(b"stdout data")
732+
server.close()
733+
messages = target.recv_all_messages()
734+
self.check_dom0(dom0)
735+
return util.sort_messages(messages)
736+
737+
def _test_tcp(self, family: int, service: str, host: str, port: int) -> None:
738+
# No stderr
739+
self.assertListEqual(
740+
self._test_tcp_raw(family, service, host, port),
741+
[
742+
(qrexec.MSG_DATA_STDOUT, b"stdout data"),
743+
(qrexec.MSG_DATA_STDOUT, b""),
744+
(qrexec.MSG_DATA_EXIT_CODE, b"\0\0\0\0"),
745+
],
746+
)
747+
748+
def test_connect_socket_tcp_port_from_arg(self):
749+
socket_path = os.path.join(
750+
self.tempdir, "rpc", "qubes.SocketService"
751+
)
752+
port = 65533
753+
host = "127.0.0.1"
754+
os.symlink(f"/dev/tcp/{host}", socket_path)
755+
self._test_tcp(socket.AF_INET, f"qubes.SocketService+{port}", host, port)
756+
757+
def test_connect_socket_tcp_host_and_port_from_arg(self):
758+
socket_path = os.path.join(
759+
self.tempdir, "rpc", "qubes.SocketService"
760+
)
761+
port = 65535
762+
host = "127.0.0.1"
763+
os.symlink(f"/dev/tcp/", socket_path)
764+
self._test_tcp(socket.AF_INET, f"qubes.SocketService+{host}+{port}", host, port)
765+
766+
def test_connect_socket_tcp_ipv6(self):
767+
socket_path = os.path.join(
768+
self.tempdir, "rpc", "qubes.SocketService"
769+
)
770+
port = 65532
771+
host = "::1"
772+
os.symlink(f"/dev/tcp/", socket_path)
773+
self._test_tcp(socket.AF_INET6, f"qubes.SocketService+{host.replace(':', '+')}+{port}", host, port)
774+
775+
def test_connect_socket_tcp_unexpected_host(self):
776+
socket_path = os.path.join(
777+
self.tempdir, "rpc", "qubes.SocketService"
778+
)
779+
port = 65535
780+
host = "127.0.0.1"
781+
os.symlink(f"/dev/tcp/{host}", socket_path)
782+
messages = self._test_tcp_raw(socket.AF_INET, f"qubes.SocketService+{host}+{port}",
783+
host, port, accept=False)
784+
self.assertListEqual(
785+
messages,
786+
[
787+
(qrexec.MSG_DATA_STDOUT, b""),
788+
(qrexec.MSG_DATA_STDERR, b""),
789+
(qrexec.MSG_DATA_EXIT_CODE, b"\177\0\0\0"),
790+
],
791+
)
792+
705793
def test_connect_socket(self):
706794
socket_path = os.path.join(
707795
self.tempdir, "rpc", "qubes.SocketService+arg"

qrexec/tests/socket/qrexec.py

+1
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,7 @@ def socket_server(socket_path):
141141
except FileNotFoundError:
142142
pass
143143
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
144+
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
144145
server.bind(socket_path)
145146
server.listen(1)
146147
return QrexecServer(server)

0 commit comments

Comments
 (0)