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) {
607 /* Get the peer for socketpair() sockets */
608 b->ucred_valid = getpeercred(b->input_fd, &b->ucred) >= 0;
610 /* Get the SELinux context of the peer */
611 r = getpeersec(b->input_fd, &b->label);
612 if (r < 0 && r != -EOPNOTSUPP)
613 log_debug_errno(r, "Failed to determine peer security context: %m");
616 static int bus_socket_start_auth_client(sd_bus *b) {
618 const char *auth_suffix, *auth_prefix;
622 if (b->anonymous_auth) {
623 auth_prefix = "\0AUTH ANONYMOUS ";
625 /* For ANONYMOUS auth we send some arbitrary "trace" string */
627 b->auth_buffer = hexmem("anonymous", l);
629 char text[DECIMAL_STR_MAX(uid_t) + 1];
631 auth_prefix = "\0AUTH EXTERNAL ";
633 xsprintf(text, UID_FMT, geteuid());
636 b->auth_buffer = hexmem(text, l);
642 if (b->hello_flags & KDBUS_HELLO_ACCEPT_FD)
643 auth_suffix = "\r\nNEGOTIATE_UNIX_FD\r\nBEGIN\r\n";
645 auth_suffix = "\r\nBEGIN\r\n";
647 b->auth_iovec[0].iov_base = (void*) auth_prefix;
648 b->auth_iovec[0].iov_len = 1 + strlen(auth_prefix + 1);
649 b->auth_iovec[1].iov_base = (void*) b->auth_buffer;
650 b->auth_iovec[1].iov_len = l * 2;
651 b->auth_iovec[2].iov_base = (void*) auth_suffix;
652 b->auth_iovec[2].iov_len = strlen(auth_suffix);
654 return bus_socket_write_auth(b);
657 int bus_socket_start_auth(sd_bus *b) {
662 b->state = BUS_AUTHENTICATING;
663 b->auth_timeout = now(CLOCK_MONOTONIC) + BUS_AUTH_TIMEOUT;
665 if (sd_is_socket(b->input_fd, AF_UNIX, 0, 0) <= 0)
666 b->hello_flags &= ~KDBUS_HELLO_ACCEPT_FD;
668 if (b->output_fd != b->input_fd)
669 if (sd_is_socket(b->output_fd, AF_UNIX, 0, 0) <= 0)
670 b->hello_flags &= ~KDBUS_HELLO_ACCEPT_FD;
673 return bus_socket_read_auth(b);
675 return bus_socket_start_auth_client(b);
678 int bus_socket_connect(sd_bus *b) {
682 assert(b->input_fd < 0);
683 assert(b->output_fd < 0);
684 assert(b->sockaddr.sa.sa_family != AF_UNSPEC);
686 b->input_fd = socket(b->sockaddr.sa.sa_family, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
690 b->output_fd = b->input_fd;
694 r = connect(b->input_fd, &b->sockaddr.sa, b->sockaddr_size);
696 if (errno == EINPROGRESS)
702 return bus_socket_start_auth(b);
705 int bus_socket_exec(sd_bus *b) {
710 assert(b->input_fd < 0);
711 assert(b->output_fd < 0);
712 assert(b->exec_path);
714 r = socketpair(AF_UNIX, SOCK_STREAM|SOCK_NONBLOCK|SOCK_CLOEXEC, 0, s);
718 r = safe_fork_full("(sd-busexec)", s+1, 1, FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS, &pid);
726 assert_se(dup3(s[1], STDIN_FILENO, 0) == STDIN_FILENO);
727 assert_se(dup3(s[1], STDOUT_FILENO, 0) == STDOUT_FILENO);
729 if (!IN_SET(s[1], STDIN_FILENO, STDOUT_FILENO))
732 fd_cloexec(STDIN_FILENO, false);
733 fd_cloexec(STDOUT_FILENO, false);
734 fd_nonblock(STDIN_FILENO, false);
735 fd_nonblock(STDOUT_FILENO, false);
738 execvp(b->exec_path, b->exec_argv);
740 const char *argv[] = { b->exec_path, NULL };
741 execvp(b->exec_path, (char**) argv);
748 b->output_fd = b->input_fd = s[0];
752 return bus_socket_start_auth(b);
755 int bus_socket_take_fd(sd_bus *b) {
760 return bus_socket_start_auth(b);
763 int bus_socket_write_message(sd_bus *bus, sd_bus_message *m, size_t *idx) {
773 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
775 if (*idx >= BUS_MESSAGE_SIZE(m))
778 r = bus_message_setup_iovec(m);
782 n = m->n_iovec * sizeof(struct iovec);
784 memcpy_safe(iov, m->iovec, n);
787 iovec_advance(iov, &j, *idx);
789 if (bus->prefer_writev)
790 k = writev(bus->output_fd, iov, m->n_iovec);
794 .msg_iovlen = m->n_iovec,
797 if (m->n_fds > 0 && *idx == 0) {
798 struct cmsghdr *control;
800 mh.msg_control = control = alloca(CMSG_SPACE(sizeof(int) * m->n_fds));
801 mh.msg_controllen = control->cmsg_len = CMSG_LEN(sizeof(int) * m->n_fds);
802 control->cmsg_level = SOL_SOCKET;
803 control->cmsg_type = SCM_RIGHTS;
804 memcpy(CMSG_DATA(control), m->fds, sizeof(int) * m->n_fds);
807 k = sendmsg(bus->output_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL);
808 if (k < 0 && errno == ENOTSOCK) {
809 bus->prefer_writev = true;
810 k = writev(bus->output_fd, iov, m->n_iovec);
815 return errno == EAGAIN ? 0 : -errno;
821 static int bus_socket_read_message_need(sd_bus *bus, size_t *need) {
828 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
830 if (bus->rbuffer_size < sizeof(struct bus_header)) {
831 *need = sizeof(struct bus_header) + 8;
833 /* Minimum message size:
837 * Method Call: +2 string headers
838 * Signal: +3 string headers
839 * Method Error: +1 string headers
841 * Method Reply: +1 uint32 headers
843 * A string header is at least 9 bytes
844 * A uint32 header is at least 8 bytes
846 * Hence the minimum message size of a valid message
847 * is header + 8 bytes */
852 a = ((const uint32_t*) bus->rbuffer)[1];
853 b = ((const uint32_t*) bus->rbuffer)[3];
855 e = ((const uint8_t*) bus->rbuffer)[0];
856 if (e == BUS_LITTLE_ENDIAN) {
859 } else if (e == BUS_BIG_ENDIAN) {
865 sum = (uint64_t) sizeof(struct bus_header) + (uint64_t) ALIGN_TO(b, 8) + (uint64_t) a;
866 if (sum >= BUS_MESSAGE_SIZE_MAX)
869 *need = (size_t) sum;
873 static int bus_socket_make_message(sd_bus *bus, size_t size) {
879 assert(bus->rbuffer_size >= size);
880 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
882 r = bus_rqueue_make_room(bus);
886 if (bus->rbuffer_size > size) {
887 b = memdup((const uint8_t*) bus->rbuffer + size,
888 bus->rbuffer_size - size);
894 r = bus_message_from_malloc(bus,
896 bus->fds, bus->n_fds,
905 bus->rbuffer_size -= size;
910 bus->rqueue[bus->rqueue_size++] = t;
915 int bus_socket_read_message(sd_bus *bus) {
917 struct iovec iov = {};
923 struct cmsghdr cmsghdr;
924 uint8_t buf[CMSG_SPACE(sizeof(int) * BUS_FDS_MAX)];
926 bool handle_cmsg = false;
929 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
931 r = bus_socket_read_message_need(bus, &need);
935 if (bus->rbuffer_size >= need)
936 return bus_socket_make_message(bus, need);
938 b = realloc(bus->rbuffer, need);
944 iov.iov_base = (uint8_t*) bus->rbuffer + bus->rbuffer_size;
945 iov.iov_len = need - bus->rbuffer_size;
947 if (bus->prefer_readv)
948 k = readv(bus->input_fd, &iov, 1);
953 mh.msg_control = &control;
954 mh.msg_controllen = sizeof(control);
956 k = recvmsg(bus->input_fd, &mh, MSG_DONTWAIT|MSG_NOSIGNAL|MSG_CMSG_CLOEXEC);
957 if (k < 0 && errno == ENOTSOCK) {
958 bus->prefer_readv = true;
959 k = readv(bus->input_fd, &iov, 1);
964 return errno == EAGAIN ? 0 : -errno;
968 bus->rbuffer_size += k;
971 struct cmsghdr *cmsg;
973 CMSG_FOREACH(cmsg, &mh)
974 if (cmsg->cmsg_level == SOL_SOCKET &&
975 cmsg->cmsg_type == SCM_RIGHTS) {
978 n = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
981 /* Whut? We received fds but this
982 * isn't actually enabled? Close them,
985 close_many((int*) CMSG_DATA(cmsg), n);
989 f = realloc(bus->fds, sizeof(int) * (bus->n_fds + n));
991 close_many((int*) CMSG_DATA(cmsg), n);
995 memcpy_safe(f + bus->n_fds, CMSG_DATA(cmsg), n * sizeof(int));
999 log_debug("Got unexpected auxiliary data with level=%d and type=%d",
1000 cmsg->cmsg_level, cmsg->cmsg_type);
1003 r = bus_socket_read_message_need(bus, &need);
1007 if (bus->rbuffer_size >= need)
1008 return bus_socket_make_message(bus, need);
1013 int bus_socket_process_opening(sd_bus *b) {
1015 socklen_t slen = sizeof(error);
1022 assert(b->state == BUS_OPENING);
1028 if (!(p.revents & (POLLOUT|POLLERR|POLLHUP)))
1031 r = getsockopt(b->output_fd, SOL_SOCKET, SO_ERROR, &error, &slen);
1033 b->last_connect_error = errno;
1034 else if (error != 0)
1035 b->last_connect_error = error;
1036 else if (p.revents & (POLLERR|POLLHUP))
1037 b->last_connect_error = ECONNREFUSED;
1039 return bus_socket_start_auth(b);
1041 return bus_next_address(b);
1044 int bus_socket_process_authenticating(sd_bus *b) {
1048 assert(b->state == BUS_AUTHENTICATING);
1050 if (now(CLOCK_MONOTONIC) >= b->auth_timeout)
1053 r = bus_socket_write_auth(b);
1057 return bus_socket_read_auth(b);