1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2013 Lennart Poettering
7 systemd is free software; you can redistribute it and/or modify it
8 under the terms of the GNU Lesser General Public License as published by
9 the Free Software Foundation; either version 2.1 of the License, or
10 (at your option) any later version.
12 systemd is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
17 You should have received a copy of the GNU Lesser General Public License
18 along with systemd; If not, see <http://www.gnu.org/licenses/>.
27 #include "sd-daemon.h"
29 #include "alloc-util.h"
30 #include "bus-internal.h"
31 #include "bus-message.h"
32 #include "bus-socket.h"
34 #include "format-util.h"
35 #include "hexdecoct.h"
38 #include "selinux-util.h"
39 #include "signal-util.h"
40 #include "stdio-util.h"
41 #include "string-util.h"
42 #include "user-util.h"
46 #define SNDBUF_SIZE (8*1024*1024)
48 static void iovec_advance(struct iovec iov[], unsigned *idx, size_t size) {
51 struct iovec *i = iov + *idx;
53 if (i->iov_len > size) {
54 i->iov_base = (uint8_t*) i->iov_base + size;
68 static int append_iovec(sd_bus_message *m, const void *p, size_t sz) {
73 m->iovec[m->n_iovec].iov_base = (void*) p;
74 m->iovec[m->n_iovec].iov_len = sz;
80 static int bus_message_setup_iovec(sd_bus_message *m) {
81 struct bus_body_part *part;
93 n = 1 + m->n_body_parts;
94 if (n < ELEMENTSOF(m->iovec_fixed))
95 m->iovec = m->iovec_fixed;
97 m->iovec = new(struct iovec, n);
104 r = append_iovec(m, m->header, BUS_MESSAGE_BODY_BEGIN(m));
108 MESSAGE_FOREACH_PART(part, i, m) {
109 r = bus_body_part_map(part);
113 r = append_iovec(m, part->data, part->size);
118 assert(n == m->n_iovec);
127 bool bus_socket_auth_needs_write(sd_bus *b) {
131 if (b->auth_index >= ELEMENTSOF(b->auth_iovec))
134 for (i = b->auth_index; i < ELEMENTSOF(b->auth_iovec); i++) {
135 struct iovec *j = b->auth_iovec + i;
144 static int bus_socket_write_auth(sd_bus *b) {
148 assert(b->state == BUS_AUTHENTICATING);
150 if (!bus_socket_auth_needs_write(b))
153 if (b->prefer_writev)
154 k = writev(b->output_fd, b->auth_iovec + b->auth_index, ELEMENTSOF(b->auth_iovec) - b->auth_index);
159 mh.msg_iov = b->auth_iovec + b->auth_index;
160 mh.msg_iovlen = ELEMENTSOF(b->auth_iovec) - b->auth_index;
162 k = sendmsg(b->output_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL);
163 if (k < 0 && errno == ENOTSOCK) {
164 b->prefer_writev = true;
165 k = writev(b->output_fd, b->auth_iovec + b->auth_index, ELEMENTSOF(b->auth_iovec) - b->auth_index);
170 return errno == EAGAIN ? 0 : -errno;
172 iovec_advance(b->auth_iovec, &b->auth_index, (size_t) k);
176 static int bus_socket_auth_verify_client(sd_bus *b) {
184 /* We expect two response lines: "OK" and possibly
187 e = memmem_safe(b->rbuffer, b->rbuffer_size, "\r\n", 2);
191 if (b->hello_flags & KDBUS_HELLO_ACCEPT_FD) {
192 f = memmem(e + 2, b->rbuffer_size - (e - (char*) b->rbuffer) - 2, "\r\n", 2);
202 /* Nice! We got all the lines we need. First check the OK
205 if (e - (char*) b->rbuffer != 3 + 32)
208 if (memcmp(b->rbuffer, "OK ", 3))
211 b->auth = b->anonymous_auth ? BUS_AUTH_ANONYMOUS : BUS_AUTH_EXTERNAL;
213 for (i = 0; i < 32; i += 2) {
216 x = unhexchar(((char*) b->rbuffer)[3 + i]);
217 y = unhexchar(((char*) b->rbuffer)[3 + i + 1]);
222 peer.bytes[i/2] = ((uint8_t) x << 4 | (uint8_t) y);
225 if (!sd_id128_is_null(b->server_id) &&
226 !sd_id128_equal(b->server_id, peer))
231 /* And possibly check the second line, too */
235 (f - e == STRLEN("\r\nAGREE_UNIX_FD")) &&
236 memcmp(e + 2, "AGREE_UNIX_FD",
237 STRLEN("AGREE_UNIX_FD")) == 0;
239 b->rbuffer_size -= (start - (char*) b->rbuffer);
240 memmove(b->rbuffer, start, b->rbuffer_size);
242 r = bus_start_running(b);
249 static bool line_equals(const char *s, size_t m, const char *line) {
256 return memcmp(s, line, l) == 0;
259 static bool line_begins(const char *s, size_t m, const char *word) {
266 if (memcmp(s, word, l) != 0)
269 return m == l || (m > l && s[l] == ' ');
272 static int verify_anonymous_token(sd_bus *b, const char *p, size_t l) {
273 _cleanup_free_ char *token = NULL;
277 if (!b->anonymous_auth)
289 r = unhexmem(p, l, (void **) &token, &len);
293 if (memchr(token, 0, len))
296 return !!utf8_is_valid(token);
299 static int verify_external_token(sd_bus *b, const char *p, size_t l) {
300 _cleanup_free_ char *token = NULL;
305 /* We don't do any real authentication here. Instead, we if
306 * the owner of this bus wanted authentication he should have
307 * checked SO_PEERCRED before even creating the bus object. */
309 if (!b->anonymous_auth && !b->ucred_valid)
321 r = unhexmem(p, l, (void**) &token, &len);
325 if (memchr(token, 0, len))
328 r = parse_uid(token, &u);
332 /* We ignore the passed value if anonymous authentication is
334 if (!b->anonymous_auth && u != b->ucred.uid)
340 static int bus_socket_auth_write(sd_bus *b, const char *t) {
347 /* We only make use of the first iovec */
348 assert(IN_SET(b->auth_index, 0, 1));
351 p = malloc(b->auth_iovec[0].iov_len + l);
355 memcpy_safe(p, b->auth_iovec[0].iov_base, b->auth_iovec[0].iov_len);
356 memcpy(p + b->auth_iovec[0].iov_len, t, l);
358 b->auth_iovec[0].iov_base = p;
359 b->auth_iovec[0].iov_len += l;
361 free(b->auth_buffer);
367 static int bus_socket_auth_write_ok(sd_bus *b) {
368 char t[3 + 32 + 2 + 1];
372 xsprintf(t, "OK " SD_ID128_FORMAT_STR "\r\n", SD_ID128_FORMAT_VAL(b->server_id));
374 return bus_socket_auth_write(b, t);
377 static int bus_socket_auth_verify_server(sd_bus *b) {
381 bool processed = false;
386 if (b->rbuffer_size < 1)
389 /* First char must be a NUL byte */
390 if (*(char*) b->rbuffer != 0)
393 if (b->rbuffer_size < 3)
396 /* Begin with the first line */
397 if (b->auth_rbegin <= 0)
401 /* Check if line is complete */
402 line = (char*) b->rbuffer + b->auth_rbegin;
403 e = memmem(line, b->rbuffer_size - b->auth_rbegin, "\r\n", 2);
409 if (line_begins(line, l, "AUTH ANONYMOUS")) {
411 r = verify_anonymous_token(b, line + 14, l - 14);
415 r = bus_socket_auth_write(b, "REJECTED\r\n");
417 b->auth = BUS_AUTH_ANONYMOUS;
418 r = bus_socket_auth_write_ok(b);
421 } else if (line_begins(line, l, "AUTH EXTERNAL")) {
423 r = verify_external_token(b, line + 13, l - 13);
427 r = bus_socket_auth_write(b, "REJECTED\r\n");
429 b->auth = BUS_AUTH_EXTERNAL;
430 r = bus_socket_auth_write_ok(b);
433 } else if (line_begins(line, l, "AUTH"))
434 r = bus_socket_auth_write(b, "REJECTED EXTERNAL ANONYMOUS\r\n");
435 else if (line_equals(line, l, "CANCEL") ||
436 line_begins(line, l, "ERROR")) {
438 b->auth = _BUS_AUTH_INVALID;
439 r = bus_socket_auth_write(b, "REJECTED\r\n");
441 } else if (line_equals(line, l, "BEGIN")) {
443 if (b->auth == _BUS_AUTH_INVALID)
444 r = bus_socket_auth_write(b, "ERROR\r\n");
446 /* We can't leave from the auth phase
447 * before we haven't written
448 * everything queued, so let's check
451 if (bus_socket_auth_needs_write(b))
454 b->rbuffer_size -= (e + 2 - (char*) b->rbuffer);
455 memmove(b->rbuffer, e + 2, b->rbuffer_size);
456 return bus_start_running(b);
459 } else if (line_begins(line, l, "DATA")) {
461 if (b->auth == _BUS_AUTH_INVALID)
462 r = bus_socket_auth_write(b, "ERROR\r\n");
464 if (b->auth == BUS_AUTH_ANONYMOUS)
465 r = verify_anonymous_token(b, line + 4, l - 4);
467 r = verify_external_token(b, line + 4, l - 4);
472 b->auth = _BUS_AUTH_INVALID;
473 r = bus_socket_auth_write(b, "REJECTED\r\n");
475 r = bus_socket_auth_write_ok(b);
477 } else if (line_equals(line, l, "NEGOTIATE_UNIX_FD")) {
478 if (b->auth == _BUS_AUTH_INVALID || !(b->hello_flags & KDBUS_HELLO_ACCEPT_FD))
479 r = bus_socket_auth_write(b, "ERROR\r\n");
482 r = bus_socket_auth_write(b, "AGREE_UNIX_FD\r\n");
485 r = bus_socket_auth_write(b, "ERROR\r\n");
490 b->auth_rbegin = e + 2 - (char*) b->rbuffer;
496 static int bus_socket_auth_verify(sd_bus *b) {
500 return bus_socket_auth_verify_server(b);
502 return bus_socket_auth_verify_client(b);
505 static int bus_socket_read_auth(sd_bus *b) {
507 struct iovec iov = {};
513 struct cmsghdr cmsghdr;
514 uint8_t buf[CMSG_SPACE(sizeof(int) * BUS_FDS_MAX)];
516 bool handle_cmsg = false;
519 assert(b->state == BUS_AUTHENTICATING);
521 r = bus_socket_auth_verify(b);
525 n = MAX(256u, b->rbuffer_size * 2);
527 if (n > BUS_AUTH_SIZE_MAX)
528 n = BUS_AUTH_SIZE_MAX;
530 if (b->rbuffer_size >= n)
533 p = realloc(b->rbuffer, n);
539 iov.iov_base = (uint8_t*) b->rbuffer + b->rbuffer_size;
540 iov.iov_len = n - b->rbuffer_size;
543 k = readv(b->input_fd, &iov, 1);
548 mh.msg_control = &control;
549 mh.msg_controllen = sizeof(control);
551 k = recvmsg(b->input_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL|MSG_CMSG_CLOEXEC);
552 if (k < 0 && errno == ENOTSOCK) {
553 b->prefer_readv = true;
554 k = readv(b->input_fd, &iov, 1);
559 return errno == EAGAIN ? 0 : -errno;
563 b->rbuffer_size += k;
566 struct cmsghdr *cmsg;
568 CMSG_FOREACH(cmsg, &mh)
569 if (cmsg->cmsg_level == SOL_SOCKET &&
570 cmsg->cmsg_type == SCM_RIGHTS) {
573 /* Whut? We received fds during the auth
574 * protocol? Somebody is playing games with
575 * us. Close them all, and fail */
576 j = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
577 close_many((int*) CMSG_DATA(cmsg), j);
580 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
581 cmsg->cmsg_level, cmsg->cmsg_type);
584 r = bus_socket_auth_verify(b);
591 void bus_socket_setup(sd_bus *b) {
594 /* Increase the buffers to 8 MB */
595 fd_inc_rcvbuf(b->input_fd, SNDBUF_SIZE);
596 fd_inc_sndbuf(b->output_fd, SNDBUF_SIZE);
598 b->message_version = 1;
599 b->message_endian = 0;
602 static void bus_get_peercred(sd_bus *b) {
606 assert(!b->ucred_valid);
608 assert(b->n_groups == (size_t) -1);
610 /* Get the peer for socketpair() sockets */
611 b->ucred_valid = getpeercred(b->input_fd, &b->ucred) >= 0;
613 /* Get the SELinux context of the peer */
614 r = getpeersec(b->input_fd, &b->label);
615 if (r < 0 && !IN_SET(r, -EOPNOTSUPP, -ENOPROTOOPT))
616 log_debug_errno(r, "Failed to determine peer security context: %m");
618 /* Get the list of auxiliary groups of the peer */
619 r = getpeergroups(b->input_fd, &b->groups);
621 if (!IN_SET(r, -EOPNOTSUPP, -ENOPROTOOPT))
622 log_debug_errno(r, "Failed to determine peer groups list: %m");
624 b->n_groups = (size_t) -1;
626 b->n_groups = (size_t) r;
629 static int bus_socket_start_auth_client(sd_bus *b) {
631 const char *auth_suffix, *auth_prefix;
635 if (b->anonymous_auth) {
636 auth_prefix = "\0AUTH ANONYMOUS ";
638 /* For ANONYMOUS auth we send some arbitrary "trace" string */
640 b->auth_buffer = hexmem("anonymous", l);
642 char text[DECIMAL_STR_MAX(uid_t) + 1];
644 auth_prefix = "\0AUTH EXTERNAL ";
646 xsprintf(text, UID_FMT, geteuid());
649 b->auth_buffer = hexmem(text, l);
655 if (b->hello_flags & KDBUS_HELLO_ACCEPT_FD)
656 auth_suffix = "\r\nNEGOTIATE_UNIX_FD\r\nBEGIN\r\n";
658 auth_suffix = "\r\nBEGIN\r\n";
660 b->auth_iovec[0].iov_base = (void*) auth_prefix;
661 b->auth_iovec[0].iov_len = 1 + strlen(auth_prefix + 1);
662 b->auth_iovec[1].iov_base = (void*) b->auth_buffer;
663 b->auth_iovec[1].iov_len = l * 2;
664 b->auth_iovec[2].iov_base = (void*) auth_suffix;
665 b->auth_iovec[2].iov_len = strlen(auth_suffix);
667 return bus_socket_write_auth(b);
670 int bus_socket_start_auth(sd_bus *b) {
675 b->state = BUS_AUTHENTICATING;
676 b->auth_timeout = now(CLOCK_MONOTONIC) + BUS_AUTH_TIMEOUT;
678 if (sd_is_socket(b->input_fd, AF_UNIX, 0, 0) <= 0)
679 b->hello_flags &= ~KDBUS_HELLO_ACCEPT_FD;
681 if (b->output_fd != b->input_fd)
682 if (sd_is_socket(b->output_fd, AF_UNIX, 0, 0) <= 0)
683 b->hello_flags &= ~KDBUS_HELLO_ACCEPT_FD;
686 return bus_socket_read_auth(b);
688 return bus_socket_start_auth_client(b);
691 int bus_socket_connect(sd_bus *b) {
695 assert(b->input_fd < 0);
696 assert(b->output_fd < 0);
697 assert(b->sockaddr.sa.sa_family != AF_UNSPEC);
699 b->input_fd = socket(b->sockaddr.sa.sa_family, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
703 b->output_fd = b->input_fd;
707 r = connect(b->input_fd, &b->sockaddr.sa, b->sockaddr_size);
709 if (errno == EINPROGRESS)
715 return bus_socket_start_auth(b);
718 int bus_socket_exec(sd_bus *b) {
723 assert(b->input_fd < 0);
724 assert(b->output_fd < 0);
725 assert(b->exec_path);
727 r = socketpair(AF_UNIX, SOCK_STREAM|SOCK_NONBLOCK|SOCK_CLOEXEC, 0, s);
731 r = safe_fork_full("(sd-busexec)", s+1, 1, FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS, &pid);
739 assert_se(dup3(s[1], STDIN_FILENO, 0) == STDIN_FILENO);
740 assert_se(dup3(s[1], STDOUT_FILENO, 0) == STDOUT_FILENO);
742 if (!IN_SET(s[1], STDIN_FILENO, STDOUT_FILENO))
745 fd_cloexec(STDIN_FILENO, false);
746 fd_cloexec(STDOUT_FILENO, false);
747 fd_nonblock(STDIN_FILENO, false);
748 fd_nonblock(STDOUT_FILENO, false);
751 execvp(b->exec_path, b->exec_argv);
753 const char *argv[] = { b->exec_path, NULL };
754 execvp(b->exec_path, (char**) argv);
761 b->output_fd = b->input_fd = s[0];
765 return bus_socket_start_auth(b);
768 int bus_socket_take_fd(sd_bus *b) {
773 return bus_socket_start_auth(b);
776 int bus_socket_write_message(sd_bus *bus, sd_bus_message *m, size_t *idx) {
786 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
788 if (*idx >= BUS_MESSAGE_SIZE(m))
791 r = bus_message_setup_iovec(m);
795 n = m->n_iovec * sizeof(struct iovec);
797 memcpy_safe(iov, m->iovec, n);
800 iovec_advance(iov, &j, *idx);
802 if (bus->prefer_writev)
803 k = writev(bus->output_fd, iov, m->n_iovec);
807 .msg_iovlen = m->n_iovec,
810 if (m->n_fds > 0 && *idx == 0) {
811 struct cmsghdr *control;
813 mh.msg_control = control = alloca(CMSG_SPACE(sizeof(int) * m->n_fds));
814 mh.msg_controllen = control->cmsg_len = CMSG_LEN(sizeof(int) * m->n_fds);
815 control->cmsg_level = SOL_SOCKET;
816 control->cmsg_type = SCM_RIGHTS;
817 memcpy(CMSG_DATA(control), m->fds, sizeof(int) * m->n_fds);
820 k = sendmsg(bus->output_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL);
821 if (k < 0 && errno == ENOTSOCK) {
822 bus->prefer_writev = true;
823 k = writev(bus->output_fd, iov, m->n_iovec);
828 return errno == EAGAIN ? 0 : -errno;
834 static int bus_socket_read_message_need(sd_bus *bus, size_t *need) {
841 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
843 if (bus->rbuffer_size < sizeof(struct bus_header)) {
844 *need = sizeof(struct bus_header) + 8;
846 /* Minimum message size:
850 * Method Call: +2 string headers
851 * Signal: +3 string headers
852 * Method Error: +1 string headers
854 * Method Reply: +1 uint32 headers
856 * A string header is at least 9 bytes
857 * A uint32 header is at least 8 bytes
859 * Hence the minimum message size of a valid message
860 * is header + 8 bytes */
865 a = ((const uint32_t*) bus->rbuffer)[1];
866 b = ((const uint32_t*) bus->rbuffer)[3];
868 e = ((const uint8_t*) bus->rbuffer)[0];
869 if (e == BUS_LITTLE_ENDIAN) {
872 } else if (e == BUS_BIG_ENDIAN) {
878 sum = (uint64_t) sizeof(struct bus_header) + (uint64_t) ALIGN_TO(b, 8) + (uint64_t) a;
879 if (sum >= BUS_MESSAGE_SIZE_MAX)
882 *need = (size_t) sum;
886 static int bus_socket_make_message(sd_bus *bus, size_t size) {
892 assert(bus->rbuffer_size >= size);
893 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
895 r = bus_rqueue_make_room(bus);
899 if (bus->rbuffer_size > size) {
900 b = memdup((const uint8_t*) bus->rbuffer + size,
901 bus->rbuffer_size - size);
907 r = bus_message_from_malloc(bus,
909 bus->fds, bus->n_fds,
918 bus->rbuffer_size -= size;
923 bus->rqueue[bus->rqueue_size++] = t;
928 int bus_socket_read_message(sd_bus *bus) {
930 struct iovec iov = {};
936 struct cmsghdr cmsghdr;
937 uint8_t buf[CMSG_SPACE(sizeof(int) * BUS_FDS_MAX)];
939 bool handle_cmsg = false;
942 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
944 r = bus_socket_read_message_need(bus, &need);
948 if (bus->rbuffer_size >= need)
949 return bus_socket_make_message(bus, need);
951 b = realloc(bus->rbuffer, need);
957 iov.iov_base = (uint8_t*) bus->rbuffer + bus->rbuffer_size;
958 iov.iov_len = need - bus->rbuffer_size;
960 if (bus->prefer_readv)
961 k = readv(bus->input_fd, &iov, 1);
966 mh.msg_control = &control;
967 mh.msg_controllen = sizeof(control);
969 k = recvmsg(bus->input_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL|MSG_CMSG_CLOEXEC);
970 if (k < 0 && errno == ENOTSOCK) {
971 bus->prefer_readv = true;
972 k = readv(bus->input_fd, &iov, 1);
977 return errno == EAGAIN ? 0 : -errno;
981 bus->rbuffer_size += k;
984 struct cmsghdr *cmsg;
986 CMSG_FOREACH(cmsg, &mh)
987 if (cmsg->cmsg_level == SOL_SOCKET &&
988 cmsg->cmsg_type == SCM_RIGHTS) {
991 n = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
994 /* Whut? We received fds but this
995 * isn't actually enabled? Close them,
998 close_many((int*) CMSG_DATA(cmsg), n);
1002 f = realloc(bus->fds, sizeof(int) * (bus->n_fds + n));
1004 close_many((int*) CMSG_DATA(cmsg), n);
1008 memcpy_safe(f + bus->n_fds, CMSG_DATA(cmsg), n * sizeof(int));
1012 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
1013 cmsg->cmsg_level, cmsg->cmsg_type);
1016 r = bus_socket_read_message_need(bus, &need);
1020 if (bus->rbuffer_size >= need)
1021 return bus_socket_make_message(bus, need);
1026 int bus_socket_process_opening(sd_bus *b) {
1028 socklen_t slen = sizeof(error);
1035 assert(b->state == BUS_OPENING);
1041 if (!(p.revents & (POLLOUT|POLLERR|POLLHUP)))
1044 r = getsockopt(b->output_fd, SOL_SOCKET, SO_ERROR, &error, &slen);
1046 b->last_connect_error = errno;
1047 else if (error != 0)
1048 b->last_connect_error = error;
1049 else if (p.revents & (POLLERR|POLLHUP))
1050 b->last_connect_error = ECONNREFUSED;
1052 return bus_socket_start_auth(b);
1054 return bus_next_address(b);
1057 int bus_socket_process_authenticating(sd_bus *b) {
1061 assert(b->state == BUS_AUTHENTICATING);
1063 if (now(CLOCK_MONOTONIC) >= b->auth_timeout)
1066 r = bus_socket_write_auth(b);
1070 return bus_socket_read_auth(b);