chiark / gitweb /
bus-proxy: make sure we have creds when two legacy clients talk to each other
[elogind.git] / src / bus-proxyd / bus-proxyd.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 Lennart Poettering
7   Copyright 2013 Daniel Mack
8   Copyright 2014 Kay Sievers
9
10   systemd is free software; you can redistribute it and/or modify it
11   under the terms of the GNU Lesser General Public License as published by
12   the Free Software Foundation; either version 2.1 of the License, or
13   (at your option) any later version.
14
15   systemd is distributed in the hope that it will be useful, but
16   WITHOUT ANY WARRANTY; without even the implied warranty of
17   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18   Lesser General Public License for more details.
19
20   You should have received a copy of the GNU Lesser General Public License
21   along with systemd; If not, see <http://www.gnu.org/licenses/>.
22 ***/
23
24 #include <sys/socket.h>
25 #include <sys/un.h>
26 #include <sys/types.h>
27 #include <fcntl.h>
28 #include <unistd.h>
29 #include <string.h>
30 #include <errno.h>
31 #include <sys/poll.h>
32 #include <stddef.h>
33 #include <getopt.h>
34
35 #include "log.h"
36 #include "util.h"
37 #include "socket-util.h"
38 #include "sd-daemon.h"
39 #include "sd-bus.h"
40 #include "bus-internal.h"
41 #include "bus-message.h"
42 #include "bus-util.h"
43 #include "build.h"
44 #include "strv.h"
45 #include "def.h"
46 #include "capability.h"
47 #include "bus-control.h"
48 #include "smack-util.h"
49 #include "set.h"
50 #include "bus-xml-policy.h"
51
52 static char *arg_address = NULL;
53 static char *arg_command_line_buffer = NULL;
54 static bool arg_drop_privileges = false;
55 static char **arg_configuration = NULL;
56
57 static int help(void) {
58
59         printf("%s [OPTIONS...]\n\n"
60                "Connect STDIO or a socket to a given bus address.\n\n"
61                "  -h --help               Show this help\n"
62                "     --version            Show package version\n"
63                "     --drop-privileges    Drop privileges\n"
64                "     --configuration=PATH Configuration file or directory\n"
65                "     --machine=MACHINE    Connect to specified machine\n"
66                "     --address=ADDRESS    Connect to the bus specified by ADDRESS\n"
67                "                          (default: " DEFAULT_SYSTEM_BUS_ADDRESS ")\n",
68                program_invocation_short_name);
69
70         return 0;
71 }
72
73 static int parse_argv(int argc, char *argv[]) {
74
75         enum {
76                 ARG_VERSION = 0x100,
77                 ARG_ADDRESS,
78                 ARG_DROP_PRIVILEGES,
79                 ARG_CONFIGURATION,
80                 ARG_MACHINE,
81         };
82
83         static const struct option options[] = {
84                 { "help",            no_argument,       NULL, 'h'                 },
85                 { "version",         no_argument,       NULL, ARG_VERSION         },
86                 { "address",         required_argument, NULL, ARG_ADDRESS         },
87                 { "drop-privileges", no_argument,       NULL, ARG_DROP_PRIVILEGES },
88                 { "configuration",   required_argument, NULL, ARG_CONFIGURATION   },
89                 { "machine",         required_argument, NULL, ARG_MACHINE         },
90                 {},
91         };
92
93         int c, r;
94
95         assert(argc >= 0);
96         assert(argv);
97
98         while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
99
100                 switch (c) {
101
102                 case 'h':
103                         help();
104                         return 0;
105
106                 case ARG_VERSION:
107                         puts(PACKAGE_STRING);
108                         puts(SYSTEMD_FEATURES);
109                         return 0;
110
111                 case ARG_ADDRESS: {
112                         char *a;
113
114                         a = strdup(optarg);
115                         if (!a)
116                                 return log_oom();
117
118                         free(arg_address);
119                         arg_address = a;
120                         break;
121                 }
122
123                 case ARG_DROP_PRIVILEGES:
124                         arg_drop_privileges = true;
125                         break;
126
127                 case ARG_CONFIGURATION:
128                         r = strv_extend(&arg_configuration, optarg);
129                         if (r < 0)
130                                 return log_oom();
131                         break;
132
133                 case ARG_MACHINE: {
134                         _cleanup_free_ char *e = NULL;
135                         char *a;
136
137                         e = bus_address_escape(optarg);
138                         if (!e)
139                                 return log_oom();
140
141 #ifdef ENABLE_KDBUS
142                         a = strjoin("x-machine-kernel:machine=", e, ";x-machine-unix:machine=", e, NULL);
143 #else
144                         a = strjoin("x-machine-unix:machine=", e, NULL);
145 #endif
146                         if (!a)
147                                 return log_oom();
148
149                         free(arg_address);
150                         arg_address = a;
151
152                         break;
153                 }
154
155                 case '?':
156                         return -EINVAL;
157
158                 default:
159                         assert_not_reached("Unhandled option");
160                 }
161
162         /* If the first command line argument is only "x" characters
163          * we'll write who we are talking to into it, so that "ps" is
164          * explanatory */
165         arg_command_line_buffer = argv[optind];
166         if (argc > optind + 1 || (arg_command_line_buffer && !in_charset(arg_command_line_buffer, "x"))) {
167                 log_error("Too many arguments");
168                 return -EINVAL;
169         }
170
171         if (!arg_address) {
172                 arg_address = strdup(DEFAULT_SYSTEM_BUS_ADDRESS);
173                 if (!arg_address)
174                         return log_oom();
175         }
176
177         return 1;
178 }
179
180 static int rename_service(sd_bus *a, sd_bus *b) {
181         _cleanup_bus_creds_unref_ sd_bus_creds *creds = NULL;
182         _cleanup_free_ char *p = NULL, *name = NULL;
183         const char *comm;
184         char **cmdline;
185         uid_t uid;
186         pid_t pid;
187         int r;
188
189         assert(a);
190         assert(b);
191
192         r = sd_bus_get_owner_creds(b, SD_BUS_CREDS_UID|SD_BUS_CREDS_PID|SD_BUS_CREDS_CMDLINE|SD_BUS_CREDS_COMM|SD_BUS_CREDS_AUGMENT, &creds);
193         if (r < 0)
194                 return r;
195
196         r = sd_bus_creds_get_uid(creds, &uid);
197         if (r < 0)
198                 return r;
199
200         r = sd_bus_creds_get_pid(creds, &pid);
201         if (r < 0)
202                 return r;
203
204         r = sd_bus_creds_get_cmdline(creds, &cmdline);
205         if (r < 0)
206                 return r;
207
208         r = sd_bus_creds_get_comm(creds, &comm);
209         if (r < 0)
210                 return r;
211
212         name = uid_to_name(uid);
213         if (!name)
214                 return -ENOMEM;
215
216         p = strv_join(cmdline, " ");
217         if (!p)
218                 return -ENOMEM;
219
220         /* The status string gets the full command line ... */
221         sd_notifyf(false,
222                    "STATUS=Processing requests from client PID "PID_FMT" (%s); UID "UID_FMT" (%s)",
223                    pid, p,
224                    uid, name);
225
226         /* ... and the argv line only the short comm */
227         if (arg_command_line_buffer) {
228                 size_t m, w;
229
230                 m = strlen(arg_command_line_buffer);
231                 w = snprintf(arg_command_line_buffer, m,
232                              "[PID "PID_FMT"/%s; UID "UID_FMT"/%s]",
233                              pid, comm,
234                              uid, name);
235
236                 if (m > w)
237                         memzero(arg_command_line_buffer + w, m - w);
238         }
239
240         log_debug("Running on behalf of PID "PID_FMT" (%s), UID "UID_FMT" (%s), %s",
241                   pid, p,
242                   uid, name,
243                   a->unique_name);
244
245         return 0;
246 }
247
248 static int synthesize_name_acquired(sd_bus *a, sd_bus *b, sd_bus_message *m) {
249         _cleanup_bus_message_unref_ sd_bus_message *n = NULL;
250         const char *name, *old_owner, *new_owner;
251         int r;
252
253         assert(a);
254         assert(b);
255         assert(m);
256
257         /* If we get NameOwnerChanged for our own name, we need to
258          * synthesize NameLost/NameAcquired, since socket clients need
259          * that, even though it is obsoleted on kdbus */
260
261         if (!a->is_kernel)
262                 return 0;
263
264         if (!sd_bus_message_is_signal(m, "org.freedesktop.DBus", "NameOwnerChanged") ||
265             !streq_ptr(m->path, "/org/freedesktop/DBus") ||
266             !streq_ptr(m->sender, "org.freedesktop.DBus"))
267                 return 0;
268
269         r = sd_bus_message_read(m, "sss", &name, &old_owner, &new_owner);
270         if (r < 0)
271                 return r;
272
273         r = sd_bus_message_rewind(m, true);
274         if (r < 0)
275                 return r;
276
277         if (streq(old_owner, a->unique_name)) {
278
279                 r = sd_bus_message_new_signal(
280                                 b,
281                                 &n,
282                                 "/org/freedesktop/DBus",
283                                 "org.freedesktop.DBus",
284                                 "NameLost");
285
286         } else if (streq(new_owner, a->unique_name)) {
287
288                 r = sd_bus_message_new_signal(
289                                 b,
290                                 &n,
291                                 "/org/freedesktop/DBus",
292                                 "org.freedesktop.DBus",
293                                 "NameAcquired");
294         } else
295                 return 0;
296
297         if (r < 0)
298                 return r;
299
300         r = sd_bus_message_append(n, "s", name);
301         if (r < 0)
302                 return r;
303
304         r = bus_message_append_sender(n, "org.freedesktop.DBus");
305         if (r < 0)
306                 return r;
307
308         r = bus_seal_synthetic_message(b, n);
309         if (r < 0)
310                 return r;
311
312         return sd_bus_send(b, n, NULL);
313 }
314
315 static int synthetic_driver_send(sd_bus *b, sd_bus_message *m) {
316         int r;
317
318         assert(b);
319         assert(m);
320
321         r = bus_message_append_sender(m, "org.freedesktop.DBus");
322         if (r < 0)
323                 return r;
324
325         r = bus_seal_synthetic_message(b, m);
326         if (r < 0)
327                 return r;
328
329         return sd_bus_send(b, m, NULL);
330 }
331
332 static int synthetic_reply_method_error(sd_bus_message *call, const sd_bus_error *e) {
333         _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
334         int r;
335
336         assert(call);
337
338         if (call->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED)
339                 return 0;
340
341         r = sd_bus_message_new_method_error(call, &m, e);
342         if (r < 0)
343                 return r;
344
345         return synthetic_driver_send(call->bus, m);
346 }
347
348 static int synthetic_reply_method_errorf(sd_bus_message *call, const char *name, const char *format, ...) {
349         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
350         va_list ap;
351
352         va_start(ap, format);
353         bus_error_setfv(&error, name, format, ap);
354         va_end(ap);
355
356         return synthetic_reply_method_error(call, &error);
357 }
358
359 static int synthetic_reply_method_errno(sd_bus_message *call, int error, const sd_bus_error *p) {
360
361         _cleanup_bus_error_free_ sd_bus_error berror = SD_BUS_ERROR_NULL;
362
363         assert(call);
364
365         if (call->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED)
366                 return 0;
367
368         if (sd_bus_error_is_set(p))
369                 return synthetic_reply_method_error(call, p);
370
371         sd_bus_error_set_errno(&berror, error);
372
373         return synthetic_reply_method_error(call, &berror);
374 }
375
376 static int synthetic_reply_method_return(sd_bus_message *call, const char *types, ...) {
377         _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
378         int r;
379
380         assert(call);
381
382         if (call->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED)
383                 return 0;
384
385         r = sd_bus_message_new_method_return(call, &m);
386         if (r < 0)
387                 return r;
388
389         if (!isempty(types)) {
390                 va_list ap;
391
392                 va_start(ap, types);
393                 r = bus_message_append_ap(m, types, ap);
394                 va_end(ap);
395                 if (r < 0)
396                         return r;
397         }
398
399         return synthetic_driver_send(call->bus, m);
400 }
401
402 static int synthetic_reply_return_strv(sd_bus_message *call, char **l) {
403         _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
404         int r;
405
406         assert(call);
407
408         if (call->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED)
409                 return 0;
410
411         r = sd_bus_message_new_method_return(call, &m);
412         if (r < 0)
413                 return synthetic_reply_method_errno(call, r, NULL);
414
415         r = sd_bus_message_append_strv(m, l);
416         if (r < 0)
417                 return synthetic_reply_method_errno(call, r, NULL);
418
419         return synthetic_driver_send(call->bus, m);
420 }
421
422 static int get_creds_by_name(sd_bus *bus, const char *name, uint64_t mask, sd_bus_creds **_creds, sd_bus_error *error) {
423         _cleanup_bus_creds_unref_ sd_bus_creds *c = NULL;
424         int r;
425
426         assert(bus);
427         assert(name);
428         assert(_creds);
429
430         r = sd_bus_get_name_creds(bus, name, mask, &c);
431         if (r == -ESRCH || r == -ENXIO)
432                 return sd_bus_error_setf(error, SD_BUS_ERROR_NAME_HAS_NO_OWNER, "Name %s is currently not owned by anyone.", name);
433         if (r < 0)
434                 return r;
435
436         if ((c->mask & mask) != mask)
437                 return -ENOTSUP;
438
439         *_creds = c;
440         c = NULL;
441
442         return 0;
443 }
444
445 static int get_creds_by_message(sd_bus *bus, sd_bus_message *m, uint64_t mask, sd_bus_creds **_creds, sd_bus_error *error) {
446         const char *name;
447         int r;
448
449         assert(bus);
450         assert(m);
451         assert(_creds);
452
453         r = sd_bus_message_read(m, "s", &name);
454         if (r < 0)
455                 return r;
456
457         return get_creds_by_name(bus, name, mask, _creds, error);
458 }
459
460 static int process_driver(sd_bus *a, sd_bus *b, sd_bus_message *m, Policy *policy, const struct ucred *ucred, Set *owned_names) {
461         int r;
462
463         assert(a);
464         assert(b);
465         assert(m);
466
467         if (!a->is_kernel)
468                 return 0;
469
470         if (!streq_ptr(sd_bus_message_get_destination(m), "org.freedesktop.DBus"))
471                 return 0;
472
473         /* The "Hello()" call is is handled in process_hello() */
474
475         if (sd_bus_message_is_method_call(m, "org.freedesktop.DBus.Introspectable", "Introspect")) {
476
477                 if (!sd_bus_message_has_signature(m, ""))
478                         return synthetic_reply_method_error(m, &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_INVALID_ARGS, "Invalid parameters"));
479
480                 return synthetic_reply_method_return(m, "s",
481                         "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\" "
482                           "\"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
483                         "<node>\n"
484                         " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
485                         "  <method name=\"Introspect\">\n"
486                         "   <arg name=\"data\" type=\"s\" direction=\"out\"/>\n"
487                         "  </method>\n"
488                         " </interface>\n"
489                         " <interface name=\"org.freedesktop.DBus\">\n"
490                         "  <method name=\"AddMatch\">\n"
491                         "   <arg type=\"s\" direction=\"in\"/>\n"
492                         "  </method>\n"
493                         "  <method name=\"RemoveMatch\">\n"
494                         "   <arg type=\"s\" direction=\"in\"/>\n"
495                         "  </method>\n"
496                         "  <method name=\"GetConnectionSELinuxSecurityContext\">\n"
497                         "   <arg type=\"s\" direction=\"in\"/>\n"
498                         "   <arg type=\"ay\" direction=\"out\"/>\n"
499                         "  </method>\n"
500                         "  <method name=\"GetConnectionUnixProcessID\">\n"
501                         "   <arg type=\"s\" direction=\"in\"/>\n"
502                         "   <arg type=\"u\" direction=\"out\"/>\n"
503                         "  </method>\n"
504                         "  <method name=\"GetConnectionUnixUser\">\n"
505                         "   <arg type=\"s\" direction=\"in\"/>\n"
506                         "   <arg type=\"u\" direction=\"out\"/>\n"
507                         "  </method>\n"
508                         "  <method name=\"GetId\">\n"
509                         "   <arg type=\"s\" direction=\"out\"/>\n"
510                         "  </method>\n"
511                         "  <method name=\"GetNameOwner\">\n"
512                         "   <arg type=\"s\" direction=\"in\"/>\n"
513                         "   <arg type=\"s\" direction=\"out\"/>\n"
514                         "  </method>\n"
515                         "  <method name=\"Hello\">\n"
516                         "   <arg type=\"s\" direction=\"out\"/>\n"
517                         "  </method>\n"
518                         "  <method name=\"ListActivatableNames\">\n"
519                         "   <arg type=\"as\" direction=\"out\"/>\n"
520                         "  </method>\n"
521                         "  <method name=\"ListNames\">\n"
522                         "   <arg type=\"as\" direction=\"out\"/>\n"
523                         "  </method>\n"
524                         "  <method name=\"ListQueuedOwners\">\n"
525                         "   <arg type=\"s\" direction=\"in\"/>\n"
526                         "   <arg type=\"as\" direction=\"out\"/>\n"
527                         "  </method>\n"
528                         "  <method name=\"NameHasOwner\">\n"
529                         "   <arg type=\"s\" direction=\"in\"/>\n"
530                         "   <arg type=\"b\" direction=\"out\"/>\n"
531                         "  </method>\n"
532                         "  <method name=\"ReleaseName\">\n"
533                         "   <arg type=\"s\" direction=\"in\"/>\n"
534                         "   <arg type=\"u\" direction=\"out\"/>\n"
535                         "  </method>\n"
536                         "  <method name=\"ReloadConfig\">\n"
537                         "  </method>\n"
538                         "  <method name=\"RequestName\">\n"
539                         "   <arg type=\"s\" direction=\"in\"/>\n"
540                         "   <arg type=\"u\" direction=\"in\"/>\n"
541                         "   <arg type=\"u\" direction=\"out\"/>\n"
542                         "  </method>\n"
543                         "  <method name=\"StartServiceByName\">\n"
544                         "   <arg type=\"s\" direction=\"in\"/>\n"
545                         "   <arg type=\"u\" direction=\"in\"/>\n"
546                         "   <arg type=\"u\" direction=\"out\"/>\n"
547                         "  </method>\n"
548                         "  <method name=\"UpdateActivationEnvironment\">\n"
549                         "   <arg type=\"a{ss}\" direction=\"in\"/>\n"
550                         "  </method>\n"
551                         "  <signal name=\"NameAcquired\">\n"
552                         "   <arg type=\"s\"/>\n"
553                         "  </signal>\n"
554                         "  <signal name=\"NameLost\">\n"
555                         "   <arg type=\"s\"/>\n"
556                         "  </signal>\n"
557                         "  <signal name=\"NameOwnerChanged\">\n"
558                         "   <arg type=\"s\"/>\n"
559                         "   <arg type=\"s\"/>\n"
560                         "   <arg type=\"s\"/>\n"
561                         "  </signal>\n"
562                         " </interface>\n"
563                         "</node>\n");
564
565         } else if (sd_bus_message_is_method_call(m, "org.freedesktop.DBus", "AddMatch")) {
566                 const char *match;
567
568                 if (!sd_bus_message_has_signature(m, "s"))
569                         return synthetic_reply_method_error(m, &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_INVALID_ARGS, "Invalid parameters"));
570
571                 r = sd_bus_message_read(m, "s", &match);
572                 if (r < 0)
573                         return synthetic_reply_method_errno(m, r, NULL);
574
575                 r = sd_bus_add_match(a, NULL, match, NULL, NULL);
576                 if (r < 0)
577                         return synthetic_reply_method_errno(m, r, NULL);
578
579                 return synthetic_reply_method_return(m, NULL);
580
581         } else if (sd_bus_message_is_method_call(m, "org.freedesktop.DBus", "RemoveMatch")) {
582                 const char *match;
583
584                 if (!sd_bus_message_has_signature(m, "s"))
585                         return synthetic_reply_method_error(m, &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_INVALID_ARGS, "Invalid parameters"));
586
587                 r = sd_bus_message_read(m, "s", &match);
588                 if (r < 0)
589                         return synthetic_reply_method_errno(m, r, NULL);
590
591                 r = bus_remove_match_by_string(a, match, NULL, NULL);
592                 if (r == 0)
593                         return synthetic_reply_method_error(m, &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_MATCH_RULE_NOT_FOUND, "Match rule not found"));
594                 if (r < 0)
595                         return synthetic_reply_method_errno(m, r, NULL);
596
597                 return synthetic_reply_method_return(m, NULL);
598
599         } else if (sd_bus_message_is_method_call(m, "org.freedesktop.DBus", "GetConnectionSELinuxSecurityContext")) {
600                 _cleanup_bus_creds_unref_ sd_bus_creds *creds = NULL;
601                 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
602
603                 if (!sd_bus_message_has_signature(m, "s"))
604                         return synthetic_reply_method_error(m, &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_INVALID_ARGS, "Invalid parameters"));
605
606                 r = get_creds_by_message(a, m, SD_BUS_CREDS_SELINUX_CONTEXT, &creds, &error);
607                 if (r < 0)
608                         return synthetic_reply_method_errno(m, r, &error);
609
610                 return synthetic_reply_method_return(m, "y", creds->label, strlen(creds->label));
611
612         } else if (sd_bus_message_is_method_call(m, "org.freedesktop.DBus", "GetConnectionUnixProcessID")) {
613                 _cleanup_bus_creds_unref_ sd_bus_creds *creds = NULL;
614                 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
615
616                 if (!sd_bus_message_has_signature(m, "s"))
617                         return synthetic_reply_method_error(m, &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_INVALID_ARGS, "Invalid parameters"));
618
619                 r = get_creds_by_message(a, m, SD_BUS_CREDS_PID, &creds, &error);
620                 if (r < 0)
621                         return synthetic_reply_method_errno(m, r, &error);
622
623                 return synthetic_reply_method_return(m, "u", (uint32_t) creds->pid);
624
625         } else if (sd_bus_message_is_method_call(m, "org.freedesktop.DBus", "GetConnectionUnixUser")) {
626                 _cleanup_bus_creds_unref_ sd_bus_creds *creds = NULL;
627                 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
628
629                 if (!sd_bus_message_has_signature(m, "s"))
630                         return synthetic_reply_method_error(m, &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_INVALID_ARGS, "Invalid parameters"));
631
632                 r = get_creds_by_message(a, m, SD_BUS_CREDS_UID, &creds, &error);
633                 if (r < 0)
634                         return synthetic_reply_method_errno(m, r, &error);
635
636                 return synthetic_reply_method_return(m, "u", (uint32_t) creds->uid);
637
638         } else if (sd_bus_message_is_method_call(m, "org.freedesktop.DBus", "GetId")) {
639                 sd_id128_t server_id;
640                 char buf[SD_ID128_STRING_MAX];
641
642                 if (!sd_bus_message_has_signature(m, ""))
643                         return synthetic_reply_method_error(m, &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_INVALID_ARGS, "Invalid parameters"));
644
645                 r = sd_bus_get_bus_id(a, &server_id);
646                 if (r < 0)
647                         return synthetic_reply_method_errno(m, r, NULL);
648
649                 return synthetic_reply_method_return(m, "s", sd_id128_to_string(server_id, buf));
650
651         } else if (sd_bus_message_is_method_call(m, "org.freedesktop.DBus", "GetNameOwner")) {
652                 const char *name;
653                 _cleanup_bus_creds_unref_ sd_bus_creds *creds = NULL;
654                 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
655
656                 if (!sd_bus_message_has_signature(m, "s"))
657                         return synthetic_reply_method_error(m, &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_INVALID_ARGS, "Invalid parameters"));
658
659                 r = sd_bus_message_read(m, "s", &name);
660                 if (r < 0)
661                         return synthetic_reply_method_errno(m, r, NULL);
662
663                 if (streq(name, "org.freedesktop.DBus"))
664                         return synthetic_reply_method_return(m, "s", "org.freedesktop.DBus");
665
666                 r = get_creds_by_name(a, name, SD_BUS_CREDS_UNIQUE_NAME, &creds, &error);
667                 if (r < 0)
668                         return synthetic_reply_method_errno(m, r, &error);
669
670                 return synthetic_reply_method_return(m, "s", creds->unique_name);
671
672         } else if (sd_bus_message_is_method_call(m, "org.freedesktop.DBus", "ListActivatableNames")) {
673                 _cleanup_strv_free_ char **names = NULL;
674
675                 if (!sd_bus_message_has_signature(m, ""))
676                         return synthetic_reply_method_error(m, &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_INVALID_ARGS, "Invalid parameters"));
677
678                 r = sd_bus_list_names(a, NULL, &names);
679                 if (r < 0)
680                         return synthetic_reply_method_errno(m, r, NULL);
681
682                 /* Let's sort the names list to make it stable */
683                 strv_sort(names);
684
685                 return synthetic_reply_return_strv(m, names);
686
687         } else if (sd_bus_message_is_method_call(m, "org.freedesktop.DBus", "ListNames")) {
688                 _cleanup_strv_free_ char **names = NULL;
689
690                 if (!sd_bus_message_has_signature(m, ""))
691                         return synthetic_reply_method_error(m, &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_INVALID_ARGS, "Invalid parameters"));
692
693                 r = sd_bus_list_names(a, &names, NULL);
694                 if (r < 0)
695                         return synthetic_reply_method_errno(m, r, NULL);
696
697                 r = strv_extend(&names, "org.freedesktop.DBus");
698                 if (r < 0)
699                         return synthetic_reply_method_errno(m, r, NULL);
700
701                 /* Let's sort the names list to make it stable */
702                 strv_sort(names);
703
704                 return synthetic_reply_return_strv(m, names);
705
706         } else if (sd_bus_message_is_method_call(m, "org.freedesktop.DBus", "ListQueuedOwners")) {
707                 struct kdbus_cmd_name_list cmd = {};
708                 struct kdbus_name_list *name_list;
709                 struct kdbus_name_info *name;
710                 _cleanup_strv_free_ char **owners = NULL;
711                 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
712                 char *arg0;
713                 int err = 0;
714
715                 if (!sd_bus_message_has_signature(m, "s"))
716                         return synthetic_reply_method_error(m, &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_INVALID_ARGS, "Invalid parameters"));
717
718                 r = sd_bus_message_read(m, "s", &arg0);
719                 if (r < 0)
720                         return synthetic_reply_method_errno(m, r, NULL);
721
722                 r = sd_bus_get_name_creds(a, arg0, 0, NULL);
723                 if (r == -ESRCH || r == -ENXIO) {
724                         sd_bus_error_setf(&error, SD_BUS_ERROR_NAME_HAS_NO_OWNER, "Could not get owners of name '%s': no such name.", arg0);
725                         return synthetic_reply_method_errno(m, r, &error);
726                 }
727                 if (r < 0)
728                         return synthetic_reply_method_errno(m, r, NULL);
729
730                 cmd.flags = KDBUS_NAME_LIST_QUEUED;
731                 r = ioctl(a->input_fd, KDBUS_CMD_NAME_LIST, &cmd);
732                 if (r < 0)
733                         return synthetic_reply_method_errno(m, -errno, NULL);
734
735                 name_list = (struct kdbus_name_list *) ((uint8_t *) a->kdbus_buffer + cmd.offset);
736
737                 KDBUS_ITEM_FOREACH(name, name_list, names) {
738                         const char *entry_name = NULL;
739                         struct kdbus_item *item;
740                         char *n;
741
742                         KDBUS_ITEM_FOREACH(item, name, items)
743                                 if (item->type == KDBUS_ITEM_OWNED_NAME)
744                                         entry_name = item->name.name;
745
746                         if (!streq_ptr(entry_name, arg0))
747                                 continue;
748
749                         if (asprintf(&n, ":1.%llu", (unsigned long long) name->owner_id) < 0) {
750                                 err  = -ENOMEM;
751                                 break;
752                         }
753
754                         r = strv_consume(&owners, n);
755                         if (r < 0) {
756                                 err = r;
757                                 break;
758                         }
759                 }
760
761                 r = bus_kernel_cmd_free(a, cmd.offset);
762                 if (r < 0)
763                         return synthetic_reply_method_errno(m, r, NULL);
764
765                 if (err < 0)
766                         return synthetic_reply_method_errno(m, err, NULL);
767
768                 return synthetic_reply_return_strv(m, owners);
769
770         } else if (sd_bus_message_is_method_call(m, "org.freedesktop.DBus", "NameHasOwner")) {
771                 const char *name;
772
773                 if (!sd_bus_message_has_signature(m, "s"))
774                         return synthetic_reply_method_error(m, &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_INVALID_ARGS, "Invalid parameters"));
775
776                 r = sd_bus_message_read(m, "s", &name);
777                 if (r < 0)
778                         return synthetic_reply_method_errno(m, r, NULL);
779
780                 if (streq(name, "org.freedesktop.DBus"))
781                         return synthetic_reply_method_return(m, "b", true);
782
783                 r = sd_bus_get_name_creds(a, name, 0, NULL);
784                 if (r < 0 && r != -ESRCH && r != -ENXIO)
785                         return synthetic_reply_method_errno(m, r, NULL);
786
787                 return synthetic_reply_method_return(m, "b", r >= 0);
788
789         } else if (sd_bus_message_is_method_call(m, "org.freedesktop.DBus", "ReleaseName")) {
790                 const char *name;
791
792                 if (!sd_bus_message_has_signature(m, "s"))
793                         return synthetic_reply_method_error(m, &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_INVALID_ARGS, "Invalid parameters"));
794
795                 r = sd_bus_message_read(m, "s", &name);
796                 if (r < 0)
797                         return synthetic_reply_method_errno(m, r, NULL);
798
799                 r = sd_bus_release_name(a, name);
800                 if (r < 0) {
801                         if (r == -ESRCH)
802                                 return synthetic_reply_method_return(m, "u", BUS_NAME_NON_EXISTENT);
803                         if (r == -EADDRINUSE)
804                                 return synthetic_reply_method_return(m, "u", BUS_NAME_NOT_OWNER);
805
806                         return synthetic_reply_method_errno(m, r, NULL);
807                 }
808
809                 set_remove(owned_names, (char*) name);
810
811                 return synthetic_reply_method_return(m, "u", BUS_NAME_RELEASED);
812
813         } else if (sd_bus_message_is_method_call(m, "org.freedesktop.DBus", "ReloadConfig")) {
814                 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
815
816                 if (!sd_bus_message_has_signature(m, ""))
817                         return synthetic_reply_method_error(m, &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_INVALID_ARGS, "Invalid parameters"));
818
819                 r = sd_bus_error_setf(&error, SD_BUS_ERROR_NOT_SUPPORTED, "%s() is not supported", sd_bus_message_get_member(m));
820
821                 return synthetic_reply_method_errno(m, r, &error);
822
823         } else if (sd_bus_message_is_method_call(m, "org.freedesktop.DBus", "RequestName")) {
824                 const char *name;
825                 uint32_t flags, param;
826                 bool in_queue;
827
828                 if (!sd_bus_message_has_signature(m, "su"))
829                         return synthetic_reply_method_error(m, &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_INVALID_ARGS, "Invalid parameters"));
830
831                 r = sd_bus_message_read(m, "su", &name, &flags);
832                 if (r < 0)
833                         return synthetic_reply_method_errno(m, r, NULL);
834
835                 if (policy && !policy_check_own(policy, ucred->uid, ucred->gid, name))
836                         return synthetic_reply_method_errno(m, -EPERM, NULL);
837
838                 if ((flags & ~(BUS_NAME_ALLOW_REPLACEMENT|BUS_NAME_REPLACE_EXISTING|BUS_NAME_DO_NOT_QUEUE)) != 0)
839                         return synthetic_reply_method_errno(m, -EINVAL, NULL);
840
841                 param = 0;
842                 if (flags & BUS_NAME_ALLOW_REPLACEMENT)
843                         param |= SD_BUS_NAME_ALLOW_REPLACEMENT;
844                 if (flags & BUS_NAME_REPLACE_EXISTING)
845                         param |= SD_BUS_NAME_REPLACE_EXISTING;
846                 if (!(flags & BUS_NAME_DO_NOT_QUEUE))
847                         param |= SD_BUS_NAME_QUEUE;
848
849                 r = set_put_strdup(owned_names, name);
850                 if (r < 0)
851                         return synthetic_reply_method_errno(m, r, NULL);
852
853                 r = sd_bus_request_name(a, name, param);
854                 if (r < 0) {
855                         if (r == -EALREADY)
856                                 return synthetic_reply_method_return(m, "u", BUS_NAME_ALREADY_OWNER);
857
858                         set_remove(owned_names, (char*) name);
859
860                         if (r == -EEXIST)
861                                 return synthetic_reply_method_return(m, "u", BUS_NAME_EXISTS);
862                         return synthetic_reply_method_errno(m, r, NULL);
863                 }
864
865                 in_queue = (r == 0);
866
867                 if (in_queue)
868                         return synthetic_reply_method_return(m, "u", BUS_NAME_IN_QUEUE);
869
870                 return synthetic_reply_method_return(m, "u", BUS_NAME_PRIMARY_OWNER);
871
872         } else if (sd_bus_message_is_method_call(m, "org.freedesktop.DBus", "StartServiceByName")) {
873                 _cleanup_bus_message_unref_ sd_bus_message *msg = NULL;
874                 const char *name;
875                 uint32_t flags;
876
877                 if (!sd_bus_message_has_signature(m, "su"))
878                         return synthetic_reply_method_error(m, &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_INVALID_ARGS, "Invalid parameters"));
879
880                 r = sd_bus_message_read(m, "su", &name, &flags);
881                 if (r < 0)
882                         return synthetic_reply_method_errno(m, r, NULL);
883
884                 if (flags != 0)
885                         return synthetic_reply_method_errno(m, -EINVAL, NULL);
886
887                 r = sd_bus_get_name_creds(a, name, 0, NULL);
888                 if (r >= 0 || streq(name, "org.freedesktop.DBus"))
889                         return synthetic_reply_method_return(m, "u", BUS_START_REPLY_ALREADY_RUNNING);
890                 if (r != -ESRCH)
891                         return synthetic_reply_method_errno(m, r, NULL);
892
893                 r = sd_bus_message_new_method_call(
894                                 a,
895                                 &msg,
896                                 name,
897                                 "/",
898                                 "org.freedesktop.DBus.Peer",
899                                 "Ping");
900                 if (r < 0)
901                         return synthetic_reply_method_errno(m, r, NULL);
902
903                 r = sd_bus_send(a, msg, NULL);
904                 if (r < 0)
905                         return synthetic_reply_method_errno(m, r, NULL);
906
907                 return synthetic_reply_method_return(m, "u", BUS_START_REPLY_SUCCESS);
908
909         } else if (sd_bus_message_is_method_call(m, "org.freedesktop.DBus", "UpdateActivationEnvironment")) {
910                 _cleanup_bus_message_unref_ sd_bus_message *msg = NULL;
911                 _cleanup_strv_free_ char **args = NULL;
912
913                 if (!sd_bus_message_has_signature(m, "a{ss}"))
914                         return synthetic_reply_method_error(m, &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_INVALID_ARGS, "Invalid parameters"));
915
916                 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "{ss}");
917                 if (r < 0)
918                         return synthetic_reply_method_errno(m, r, NULL);
919
920                 while ((r = sd_bus_message_enter_container(m, SD_BUS_TYPE_DICT_ENTRY, "ss")) > 0) {
921                         _cleanup_free_ char *s = NULL;
922                         const char *key;
923                         const char *value;
924
925                         r = sd_bus_message_read(m, "ss", &key, &value);
926                         if (r < 0)
927                                 return synthetic_reply_method_errno(m, r, NULL);
928
929                         s = strjoin(key, "=", value, NULL);
930                         if (!s)
931                                 return synthetic_reply_method_errno(m, -ENOMEM, NULL);
932
933                         r  = strv_extend(&args, s);
934                         if (r < 0)
935                                 return synthetic_reply_method_errno(m, r, NULL);
936
937                         r = sd_bus_message_exit_container(m);
938                         if (r < 0)
939                                 return synthetic_reply_method_errno(m, r, NULL);
940                 }
941
942                 r = sd_bus_message_exit_container(m);
943                 if (r < 0)
944                         return synthetic_reply_method_errno(m, r, NULL);
945
946                 if (!args)
947                         return synthetic_reply_method_errno(m, -EINVAL, NULL);
948
949                 r = sd_bus_message_new_method_call(
950                                 a,
951                                 &msg,
952                                 "org.freedesktop.systemd1",
953                                 "/org/freedesktop/systemd1",
954                                 "org.freedesktop.systemd1.Manager",
955                                 "SetEnvironment");
956                 if (r < 0)
957                         return synthetic_reply_method_errno(m, r, NULL);
958
959                 r = sd_bus_message_append_strv(msg, args);
960                 if (r < 0)
961                         return synthetic_reply_method_errno(m, r, NULL);
962
963                 r = sd_bus_call(a, msg, 0, NULL, NULL);
964                 if (r < 0)
965                         return synthetic_reply_method_errno(m, r, NULL);
966
967                return synthetic_reply_method_return(m, NULL);
968
969         } else {
970                 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
971
972                 r = sd_bus_error_setf(&error, SD_BUS_ERROR_UNKNOWN_METHOD, "Unknown method '%s'.", m->member);
973
974                 return synthetic_reply_method_errno(m, r, &error);
975         }
976 }
977
978 static int handle_policy_error(sd_bus_message *m, int r) {
979         if (r == -ESRCH || r == -ENXIO)
980                 return synthetic_reply_method_errorf(m, SD_BUS_ERROR_NAME_HAS_NO_OWNER, "Name %s is currently not owned by anyone.", m->destination);
981
982         return r;
983 }
984
985 static int process_policy(sd_bus *from, sd_bus *to, sd_bus_message *m, Policy *policy, const struct ucred *our_ucred, Set *owned_names) {
986         int r;
987
988         assert(from);
989         assert(to);
990         assert(m);
991
992         if (!policy)
993                 return 0;
994
995         if (from->is_kernel) {
996                 uid_t sender_uid = UID_INVALID;
997                 gid_t sender_gid = GID_INVALID;
998                 char **sender_names = NULL;
999                 bool granted = false;
1000
1001                 /* Driver messages are always OK */
1002                 if (streq_ptr(m->sender, "org.freedesktop.DBus"))
1003                         return 0;
1004
1005                 /* The message came from the kernel, and is sent to our legacy client. */
1006                 sd_bus_creds_get_well_known_names(&m->creds, &sender_names);
1007
1008                 (void) sd_bus_creds_get_uid(&m->creds, &sender_uid);
1009                 (void) sd_bus_creds_get_gid(&m->creds, &sender_gid);
1010
1011                 if (sender_uid == UID_INVALID || sender_gid == GID_INVALID) {
1012                         _cleanup_bus_creds_unref_ sd_bus_creds *sender_creds = NULL;
1013
1014                         /* If the message came from another legacy
1015                          * client, then the message creds will be
1016                          * missing, simply because on legacy clients
1017                          * per-message creds were unknown. In this
1018                          * case, query the creds of the peer
1019                          * instead. */
1020
1021                         r = bus_get_name_creds_kdbus(from, m->sender, SD_BUS_CREDS_UID|SD_BUS_CREDS_GID, true, &sender_creds);
1022                         if (r < 0)
1023                                 return handle_policy_error(m, r);
1024
1025                         (void) sd_bus_creds_get_uid(sender_creds, &sender_uid);
1026                         (void) sd_bus_creds_get_gid(sender_creds, &sender_gid);
1027                 }
1028
1029                 /* First check whether the sender can send the message to our name */
1030                 if (set_isempty(owned_names)) {
1031                         if (policy_check_send(policy, sender_uid, sender_gid, m->header->type, NULL, m->path, m->interface, m->member))
1032                                 granted = true;
1033                 } else {
1034                         Iterator i;
1035                         char *n;
1036
1037                         SET_FOREACH(n, owned_names, i)
1038                                 if (policy_check_send(policy, sender_uid, sender_gid, m->header->type, n, m->path, m->interface, m->member)) {
1039                                         granted = true;
1040                                         break;
1041                                 }
1042                 }
1043
1044                 if (granted) {
1045                         /* Then check whether us (the recipient) can receive from the sender's name */
1046                         if (strv_isempty(sender_names)) {
1047                                 if (policy_check_recv(policy, our_ucred->uid, our_ucred->gid, m->header->type, NULL, m->path, m->interface, m->member))
1048                                         return 0;
1049                         } else {
1050                                 char **n;
1051
1052                                 STRV_FOREACH(n, sender_names) {
1053                                         if (policy_check_recv(policy, our_ucred->uid, our_ucred->gid, m->header->type, *n, m->path, m->interface, m->member))
1054                                                 return 0;
1055                                 }
1056                         }
1057                 }
1058
1059                 /* Return an error back to the caller */
1060                 if (m->header->type == SD_BUS_MESSAGE_METHOD_CALL)
1061                         return synthetic_reply_method_errorf(m, SD_BUS_ERROR_ACCESS_DENIED, "Access prohibited by XML receiver policy.");
1062
1063                 /* Return 1, indicating that the message shall not be processed any further */
1064                 return 1;
1065         }
1066
1067         if (to->is_kernel) {
1068                 _cleanup_bus_creds_unref_ sd_bus_creds *destination_creds = NULL;
1069                 uid_t destination_uid = UID_INVALID;
1070                 gid_t destination_gid = GID_INVALID;
1071                 const char *destination_unique = NULL;
1072                 char **destination_names = NULL;
1073                 bool granted = false;
1074
1075                 /* Driver messages are always OK */
1076                 if (streq_ptr(m->destination, "org.freedesktop.DBus"))
1077                         return 0;
1078
1079                 /* The message came from the legacy client, and is sent to kdbus. */
1080                 if (m->destination) {
1081                         r = bus_get_name_creds_kdbus(to, m->destination,
1082                                                      SD_BUS_CREDS_WELL_KNOWN_NAMES|SD_BUS_CREDS_UNIQUE_NAME|
1083                                                      SD_BUS_CREDS_UID|SD_BUS_CREDS_GID|SD_BUS_CREDS_PID,
1084                                                      true, &destination_creds);
1085                         if (r < 0)
1086                                 return handle_policy_error(m, r);
1087
1088                         r = sd_bus_creds_get_unique_name(destination_creds, &destination_unique);
1089                         if (r < 0)
1090                                 return handle_policy_error(m, r);
1091
1092                         sd_bus_creds_get_well_known_names(destination_creds, &destination_names);
1093
1094                         (void) sd_bus_creds_get_uid(destination_creds, &destination_uid);
1095                         (void) sd_bus_creds_get_gid(destination_creds, &destination_gid);
1096                 }
1097
1098                 /* First check if we (the sender) can send to this name */
1099                 if (strv_isempty(destination_names)) {
1100                         if (policy_check_send(policy, our_ucred->uid, our_ucred->gid, m->header->type, NULL, m->path, m->interface, m->member))
1101                                 granted = true;
1102                 } else {
1103                         char **n;
1104
1105                         STRV_FOREACH(n, destination_names) {
1106                                 if (policy_check_send(policy, our_ucred->uid, our_ucred->gid, m->header->type, *n, m->path, m->interface, m->member)) {
1107
1108                                         /* If we made a receiver decision,
1109                                            then remember which name's policy
1110                                            we used, and to which unique ID it
1111                                            mapped when we made the
1112                                            decision. Then, let's pass this to
1113                                            the kernel when sending the
1114                                            message, so that it refuses the
1115                                            operation should the name and
1116                                            unique ID not map to each other
1117                                            anymore. */
1118
1119                                         r = free_and_strdup(&m->destination_ptr, *n);
1120                                         if (r < 0)
1121                                                 return r;
1122
1123                                         r = bus_kernel_parse_unique_name(destination_unique, &m->verify_destination_id);
1124                                         if (r < 0)
1125                                                 break;
1126
1127                                         granted = true;
1128                                         break;
1129                                 }
1130                         }
1131                 }
1132
1133                 /* Then check if the recipient can receive from our name */
1134                 if (granted) {
1135                         if (set_isempty(owned_names)) {
1136                                 if (policy_check_recv(policy, destination_uid, destination_gid, m->header->type, NULL, m->path, m->interface, m->member))
1137                                         return 0;
1138                         } else {
1139                                 Iterator i;
1140                                 char *n;
1141
1142                                 SET_FOREACH(n, owned_names, i)
1143                                         if (policy_check_recv(policy, destination_uid, destination_gid, m->header->type, n, m->path, m->interface, m->member))
1144                                                 return 0;
1145                         }
1146                 }
1147
1148                 /* Return an error back to the caller */
1149                 if (m->header->type == SD_BUS_MESSAGE_METHOD_CALL)
1150                         return synthetic_reply_method_errorf(m, SD_BUS_ERROR_ACCESS_DENIED, "Access prohibited by XML sender policy.");
1151
1152                 /* Return 1, indicating that the message shall not be processed any further */
1153                 return 1;
1154         }
1155
1156         return 0;
1157 }
1158
1159 static int process_hello(sd_bus *a, sd_bus *b, sd_bus_message *m, bool *got_hello) {
1160         _cleanup_bus_message_unref_ sd_bus_message *n = NULL;
1161         bool is_hello;
1162         int r;
1163
1164         assert(a);
1165         assert(b);
1166         assert(m);
1167         assert(got_hello);
1168
1169         /* As reaction to hello we need to respond with two messages:
1170          * the callback reply and the NameAcquired for the unique
1171          * name, since hello is otherwise obsolete on kdbus. */
1172
1173         is_hello =
1174                 sd_bus_message_is_method_call(m, "org.freedesktop.DBus", "Hello") &&
1175                 streq_ptr(m->destination, "org.freedesktop.DBus");
1176
1177         if (!is_hello) {
1178
1179                 if (*got_hello)
1180                         return 0;
1181
1182                 log_error("First packet isn't hello (it's %s.%s), aborting.", m->interface, m->member);
1183                 return -EIO;
1184         }
1185
1186         if (*got_hello) {
1187                 log_error("Got duplicate hello, aborting.");
1188                 return -EIO;
1189         }
1190
1191         *got_hello = true;
1192
1193         if (!a->is_kernel)
1194                 return 0;
1195
1196         r = sd_bus_message_new_method_return(m, &n);
1197         if (r < 0)
1198                 return log_error_errno(r, "Failed to generate HELLO reply: %m");
1199
1200         r = sd_bus_message_append(n, "s", a->unique_name);
1201         if (r < 0)
1202                 return log_error_errno(r, "Failed to append unique name to HELLO reply: %m");
1203
1204         r = bus_message_append_sender(n, "org.freedesktop.DBus");
1205         if (r < 0)
1206                 return log_error_errno(r, "Failed to append sender to HELLO reply: %m");
1207
1208         r = bus_seal_synthetic_message(b, n);
1209         if (r < 0)
1210                 return log_error_errno(r, "Failed to seal HELLO reply: %m");
1211
1212         r = sd_bus_send(b, n, NULL);
1213         if (r < 0)
1214                 return log_error_errno(r, "Failed to send HELLO reply: %m");
1215
1216         n = sd_bus_message_unref(n);
1217         r = sd_bus_message_new_signal(
1218                         b,
1219                         &n,
1220                         "/org/freedesktop/DBus",
1221                         "org.freedesktop.DBus",
1222                         "NameAcquired");
1223         if (r < 0)
1224                 return log_error_errno(r, "Failed to allocate initial NameAcquired message: %m");
1225
1226         r = sd_bus_message_append(n, "s", a->unique_name);
1227         if (r < 0)
1228                 return log_error_errno(r, "Failed to append unique name to NameAcquired message: %m");
1229
1230         r = bus_message_append_sender(n, "org.freedesktop.DBus");
1231         if (r < 0)
1232                 return log_error_errno(r, "Failed to append sender to NameAcquired message: %m");
1233
1234         r = bus_seal_synthetic_message(b, n);
1235         if (r < 0)
1236                 return log_error_errno(r, "Failed to seal NameAcquired message: %m");
1237
1238         r = sd_bus_send(b, n, NULL);
1239         if (r < 0)
1240                 return log_error_errno(r, "Failed to send NameAcquired message: %m");
1241
1242         return 1;
1243 }
1244
1245 static int patch_sender(sd_bus *a, sd_bus_message *m) {
1246         char **well_known = NULL;
1247         sd_bus_creds *c;
1248         int r;
1249
1250         assert(a);
1251         assert(m);
1252
1253         if (!a->is_kernel)
1254                 return 0;
1255
1256         /* We will change the sender of messages from the bus driver
1257          * so that they originate from the bus driver. This is a
1258          * speciality originating from dbus1, where the bus driver did
1259          * not have a unique id, but only the well-known name. */
1260
1261         c = sd_bus_message_get_creds(m);
1262         if (!c)
1263                 return 0;
1264
1265         r = sd_bus_creds_get_well_known_names(c, &well_known);
1266         if (r < 0)
1267                 return r;
1268
1269         if (strv_contains(well_known, "org.freedesktop.DBus"))
1270                 m->sender = "org.freedesktop.DBus";
1271
1272         return 0;
1273 }
1274
1275 static int mac_smack_apply_label_and_drop_cap_mac_admin(pid_t its_pid, const char *new_label) {
1276 #ifdef HAVE_SMACK
1277         int r = 0, k;
1278
1279         if (!mac_smack_use())
1280                 return 0;
1281
1282         if (new_label && its_pid > 0)
1283                 r = mac_smack_apply_pid(its_pid, new_label);
1284
1285         k = drop_capability(CAP_MAC_ADMIN);
1286         return r < 0 ? r : k;
1287 #else
1288         return 0;
1289 #endif
1290 }
1291
1292 int main(int argc, char *argv[]) {
1293
1294         _cleanup_bus_close_unref_ sd_bus *a = NULL, *b = NULL;
1295         sd_id128_t server_id;
1296         int r, in_fd, out_fd;
1297         bool got_hello = false;
1298         bool is_unix;
1299         struct ucred ucred = {};
1300         _cleanup_free_ char *peersec = NULL;
1301         Policy policy_buffer = {}, *policy = NULL;
1302         _cleanup_set_free_free_ Set *owned_names = NULL;
1303         uid_t original_uid;
1304
1305         log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
1306         log_parse_environment();
1307         log_open();
1308
1309         r = parse_argv(argc, argv);
1310         if (r <= 0)
1311                 goto finish;
1312
1313         r = sd_listen_fds(0);
1314         if (r == 0) {
1315                 in_fd = STDIN_FILENO;
1316                 out_fd = STDOUT_FILENO;
1317         } else if (r == 1) {
1318                 in_fd = SD_LISTEN_FDS_START;
1319                 out_fd = SD_LISTEN_FDS_START;
1320         } else {
1321                 log_error("Illegal number of file descriptors passed");
1322                 goto finish;
1323         }
1324
1325         original_uid = getuid();
1326
1327         is_unix =
1328                 sd_is_socket(in_fd, AF_UNIX, 0, 0) > 0 &&
1329                 sd_is_socket(out_fd, AF_UNIX, 0, 0) > 0;
1330
1331         if (is_unix) {
1332                 (void) getpeercred(in_fd, &ucred);
1333                 (void) getpeersec(in_fd, &peersec);
1334
1335                 r = mac_smack_apply_label_and_drop_cap_mac_admin(getpid(), peersec);
1336                 if (r < 0)
1337                         log_warning_errno(r, "Failed to set SMACK label (%s) and drop CAP_MAC_ADMIN: %m", peersec);
1338         }
1339
1340         if (arg_drop_privileges) {
1341                 const char *user = "systemd-bus-proxy";
1342                 uid_t uid;
1343                 gid_t gid;
1344
1345                 r = get_user_creds(&user, &uid, &gid, NULL, NULL);
1346                 if (r < 0) {
1347                         log_error_errno(r, "Cannot resolve user name %s: %m", user);
1348                         goto finish;
1349                 }
1350
1351                 r = drop_privileges(uid, gid, 1ULL << CAP_IPC_OWNER);
1352                 if (r < 0)
1353                         goto finish;
1354         }
1355
1356         owned_names = set_new(&string_hash_ops);
1357         if (!owned_names) {
1358                 log_oom();
1359                 goto finish;
1360         }
1361
1362         r = sd_bus_new(&a);
1363         if (r < 0) {
1364                 log_error_errno(r, "Failed to allocate bus: %m");
1365                 goto finish;
1366         }
1367
1368         r = sd_bus_set_description(a, "sd-proxy");
1369         if (r < 0) {
1370                 log_error_errno(r, "Failed to set bus name: %m");
1371                 goto finish;
1372         }
1373
1374         r = sd_bus_set_address(a, arg_address);
1375         if (r < 0) {
1376                 log_error_errno(r, "Failed to set address to connect to: %m");
1377                 goto finish;
1378         }
1379
1380         r = sd_bus_negotiate_fds(a, is_unix);
1381         if (r < 0) {
1382                 log_error_errno(r, "Failed to set FD negotiation: %m");
1383                 goto finish;
1384         }
1385
1386         r = sd_bus_negotiate_creds(a, true, SD_BUS_CREDS_UID|SD_BUS_CREDS_PID|SD_BUS_CREDS_GID|SD_BUS_CREDS_SELINUX_CONTEXT);
1387         if (r < 0) {
1388                 log_error_errno(r, "Failed to set credential negotiation: %m");
1389                 goto finish;
1390         }
1391
1392         if (ucred.pid > 0) {
1393                 a->fake_pids.pid = ucred.pid;
1394                 a->fake_pids_valid = true;
1395
1396                 a->fake_creds.uid = ucred.uid;
1397                 a->fake_creds.euid = UID_INVALID;
1398                 a->fake_creds.suid = UID_INVALID;
1399                 a->fake_creds.fsuid = UID_INVALID;
1400                 a->fake_creds.gid = ucred.gid;
1401                 a->fake_creds.egid = GID_INVALID;
1402                 a->fake_creds.sgid = GID_INVALID;
1403                 a->fake_creds.fsgid = GID_INVALID;
1404                 a->fake_creds_valid = true;
1405         }
1406
1407         if (peersec) {
1408                 a->fake_label = peersec;
1409                 peersec = NULL;
1410         }
1411
1412         a->manual_peer_interface = true;
1413
1414         r = sd_bus_start(a);
1415         if (r < 0) {
1416                 log_error_errno(r, "Failed to start bus client: %m");
1417                 goto finish;
1418         }
1419
1420         r = sd_bus_get_bus_id(a, &server_id);
1421         if (r < 0) {
1422                 log_error_errno(r, "Failed to get server ID: %m");
1423                 goto finish;
1424         }
1425
1426         if (a->is_kernel) {
1427                 if (!arg_configuration) {
1428                         const char *scope;
1429
1430                         r = sd_bus_get_scope(a, &scope);
1431                         if (r < 0) {
1432                                 log_error_errno(r, "Couldn't determine bus scope: %m");
1433                                 goto finish;
1434                         }
1435
1436                         if (streq(scope, "system"))
1437                                 arg_configuration = strv_new(
1438                                                 "/etc/dbus-1/system.conf",
1439                                                 "/etc/dbus-1/system.d/",
1440                                                 "/etc/dbus-1/system-local.conf",
1441                                                 NULL);
1442                         else if (streq(scope, "user"))
1443                                 arg_configuration = strv_new(
1444                                                 "/etc/dbus-1/session.conf",
1445                                                 "/etc/dbus-1/session.d/",
1446                                                 "/etc/dbus-1/session-local.conf",
1447                                                 NULL);
1448                         else {
1449                                 log_error("Unknown scope %s, don't know which policy to load. Refusing.", scope);
1450                                 goto finish;
1451                         }
1452
1453                         if (!arg_configuration) {
1454                                 r = log_oom();
1455                                 goto finish;
1456                         }
1457                 }
1458
1459                 r = policy_load(&policy_buffer, arg_configuration);
1460                 if (r < 0) {
1461                         log_error_errno(r, "Failed to load policy: %m");
1462                         goto finish;
1463                 }
1464
1465                 policy = &policy_buffer;
1466                 /* policy_dump(policy); */
1467
1468                 if (ucred.uid == original_uid)
1469                         log_debug("Permitting access, since bus owner matches bus client.");
1470                 else if (policy_check_hello(policy, ucred.uid, ucred.gid))
1471                         log_debug("Permitting access due to XML policy.");
1472                 else {
1473                         r = log_error_errno(EPERM, "Policy denied connection.");
1474                         goto finish;
1475                 }
1476         }
1477
1478         r = sd_bus_new(&b);
1479         if (r < 0) {
1480                 log_error_errno(r, "Failed to allocate bus: %m");
1481                 goto finish;
1482         }
1483
1484         r = sd_bus_set_fd(b, in_fd, out_fd);
1485         if (r < 0) {
1486                 log_error_errno(r, "Failed to set fds: %m");
1487                 goto finish;
1488         }
1489
1490         r = sd_bus_set_server(b, 1, server_id);
1491         if (r < 0) {
1492                 log_error_errno(r, "Failed to set server mode: %m");
1493                 goto finish;
1494         }
1495
1496         r = sd_bus_negotiate_fds(b, is_unix);
1497         if (r < 0) {
1498                 log_error_errno(r, "Failed to set FD negotiation: %m");
1499                 goto finish;
1500         }
1501
1502         r = sd_bus_negotiate_creds(b, true, SD_BUS_CREDS_UID|SD_BUS_CREDS_PID|SD_BUS_CREDS_GID|SD_BUS_CREDS_SELINUX_CONTEXT);
1503         if (r < 0) {
1504                 log_error_errno(r, "Failed to set credential negotiation: %m");
1505                 goto finish;
1506         }
1507
1508         r = sd_bus_set_anonymous(b, true);
1509         if (r < 0) {
1510                 log_error_errno(r, "Failed to set anonymous authentication: %m");
1511                 goto finish;
1512         }
1513
1514         b->manual_peer_interface = true;
1515
1516         r = sd_bus_start(b);
1517         if (r < 0) {
1518                 log_error_errno(r, "Failed to start bus client: %m");
1519                 goto finish;
1520         }
1521
1522         r = rename_service(a, b);
1523         if (r < 0)
1524                 log_debug_errno(r, "Failed to rename process: %m");
1525
1526         if (a->is_kernel) {
1527                 _cleanup_free_ char *match = NULL;
1528                 const char *unique;
1529
1530                 r = sd_bus_get_unique_name(a, &unique);
1531                 if (r < 0) {
1532                         log_error_errno(r, "Failed to get unique name: %m");
1533                         goto finish;
1534                 }
1535
1536                 match = strjoin("type='signal',"
1537                                 "sender='org.freedesktop.DBus',"
1538                                 "path='/org/freedesktop/DBus',"
1539                                 "interface='org.freedesktop.DBus',"
1540                                 "member='NameOwnerChanged',"
1541                                 "arg1='",
1542                                 unique,
1543                                 "'",
1544                                 NULL);
1545                 if (!match) {
1546                         log_oom();
1547                         goto finish;
1548                 }
1549
1550                 r = sd_bus_add_match(a, NULL, match, NULL, NULL);
1551                 if (r < 0) {
1552                         log_error_errno(r, "Failed to add match for NameLost: %m");
1553                         goto finish;
1554                 }
1555
1556                 free(match);
1557                 match = strjoin("type='signal',"
1558                                 "sender='org.freedesktop.DBus',"
1559                                 "path='/org/freedesktop/DBus',"
1560                                 "interface='org.freedesktop.DBus',"
1561                                 "member='NameOwnerChanged',"
1562                                 "arg2='",
1563                                 unique,
1564                                 "'",
1565                                 NULL);
1566                 if (!match) {
1567                         log_oom();
1568                         goto finish;
1569                 }
1570
1571                 r = sd_bus_add_match(a, NULL, match, NULL, NULL);
1572                 if (r < 0) {
1573                         log_error_errno(r, "Failed to add match for NameAcquired: %m");
1574                         goto finish;
1575                 }
1576         }
1577
1578         for (;;) {
1579                 _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
1580                 int events_a, events_b, fd;
1581                 uint64_t timeout_a, timeout_b, t;
1582                 struct timespec _ts, *ts;
1583                 struct pollfd *pollfd;
1584                 int k;
1585
1586                 if (got_hello) {
1587                         /* Read messages from bus, to pass them on to our client */
1588
1589                         r = sd_bus_process(a, &m);
1590                         if (r < 0) {
1591                                 /* treat 'connection reset by peer' as clean exit condition */
1592                                 if (r == -ECONNRESET)
1593                                         r = 0;
1594                                 else
1595                                         log_error_errno(r, "Failed to process bus a: %m");
1596
1597                                 goto finish;
1598                         }
1599
1600                         if (m) {
1601                                 bool processed = false;
1602
1603                                 /* We officially got EOF, let's quit */
1604                                 if (sd_bus_message_is_signal(m, "org.freedesktop.DBus.Local", "Disconnected")) {
1605                                         r = 0;
1606                                         goto finish;
1607                                 }
1608
1609                                 k = synthesize_name_acquired(a, b, m);
1610                                 if (k < 0) {
1611                                         r = k;
1612                                         log_error_errno(r, "Failed to synthesize message: %m");
1613                                         goto finish;
1614                                 }
1615
1616                                 patch_sender(a, m);
1617
1618                                 if (policy) {
1619                                         k = process_policy(a, b, m, policy, &ucred, owned_names);
1620                                         if (k < 0) {
1621                                                 r = k;
1622                                                 log_error_errno(r, "Failed to process policy: %m");
1623                                                 goto finish;
1624                                         } else if (k > 0) {
1625                                                 r = 1;
1626                                                 processed = true;
1627                                         }
1628                                 }
1629
1630                                 if (!processed) {
1631                                         k = sd_bus_send(b, m, NULL);
1632                                         if (k < 0) {
1633                                                 if (k == -ECONNRESET) {
1634                                                         r = 0;
1635                                                         goto finish;
1636                                                 } else if (k == -EPERM && m->reply_cookie > 0) {
1637                                                         /* If the peer tries to send a reply and it is rejected with EPERM
1638                                                          * by the kernel, we ignore the error. This catches cases where the
1639                                                          * original method-call didn't had EXPECT_REPLY set, but the proxy-peer
1640                                                          * still sends a reply. This is allowed in dbus1, but not in kdbus. We
1641                                                          * don't want to track reply-windows in the proxy, so we simply ignore
1642                                                          * EPERM for all replies. The only downside is, that callers are no
1643                                                          * longer notified if their replies are dropped. However, this is
1644                                                          * equivalent to the caller's timeout to expire, so this should be
1645                                                          * acceptable. Nobody sane sends replies without a matching method-call,
1646                                                          * so nobody should care. */
1647                                                         r = 1;
1648                                                 } else {
1649                                                         r = k;
1650                                                         log_error_errno(r, "Failed to send message to client: %m");
1651                                                         goto finish;
1652                                                 }
1653                                         } else
1654                                                 r = 1;
1655                                 }
1656                         }
1657
1658                         if (r > 0)
1659                                 continue;
1660                 }
1661
1662                 /* Read messages from our client, to pass them on to the bus */
1663                 r = sd_bus_process(b, &m);
1664                 if (r < 0) {
1665                         /* treat 'connection reset by peer' as clean exit condition */
1666                         if (r == -ECONNRESET)
1667                                 r = 0;
1668                         else
1669                                 log_error_errno(r, "Failed to process bus b: %m");
1670
1671                         goto finish;
1672                 }
1673
1674                 if (m) {
1675                         bool processed = false;
1676
1677                         /* We officially got EOF, let's quit */
1678                         if (sd_bus_message_is_signal(m, "org.freedesktop.DBus.Local", "Disconnected")) {
1679                                 r = 0;
1680                                 goto finish;
1681                         }
1682
1683                         k = process_hello(a, b, m, &got_hello);
1684                         if (k < 0) {
1685                                 r = k;
1686                                 log_error_errno(r, "Failed to process HELLO: %m");
1687                                 goto finish;
1688                         } else if (k > 0) {
1689                                 processed = true;
1690                                 r = 1;
1691                         }
1692
1693                         if (!processed) {
1694                                 k = process_driver(a, b, m, policy, &ucred, owned_names);
1695                                 if (k < 0) {
1696                                         r = k;
1697                                         log_error_errno(r, "Failed to process driver calls: %m");
1698                                         goto finish;
1699                                 } else if (k > 0) {
1700                                         processed = true;
1701                                         r = 1;
1702                                 }
1703
1704                                 if (!processed) {
1705
1706                                         for (;;) {
1707                                                 if (policy) {
1708                                                         k = process_policy(b, a, m, policy, &ucred, owned_names);
1709                                                         if (k < 0) {
1710                                                                 r = k;
1711                                                                 log_error_errno(r, "Failed to process policy: %m");
1712                                                                 goto finish;
1713                                                         } else if (k > 0) {
1714                                                                 processed = true;
1715                                                                 r = 1;
1716                                                                 break;
1717                                                         }
1718                                                 }
1719
1720                                                 k = sd_bus_send(a, m, NULL);
1721                                                 if (k < 0) {
1722                                                         if (k == -EREMCHG) {
1723                                                                 /* The name database changed since the policy check, hence let's check again */
1724                                                                 continue;
1725                                                         } else if (k == -ECONNRESET) {
1726                                                                 r = 0;
1727                                                                 goto finish;
1728                                                         } else if (k == -EPERM && m->reply_cookie > 0) {
1729                                                                 /* see above why EPERM is ignored for replies */
1730                                                                 r = 1;
1731                                                         } else {
1732                                                                 r = k;
1733                                                                 log_error_errno(r, "Failed to send message to bus: %m");
1734                                                                 goto finish;
1735                                                         }
1736                                                 } else
1737                                                         r = 1;
1738
1739                                                 break;
1740                                         }
1741                                 }
1742                         }
1743                 }
1744
1745                 if (r > 0)
1746                         continue;
1747
1748                 fd = sd_bus_get_fd(a);
1749                 if (fd < 0) {
1750                         log_error_errno(r, "Failed to get fd: %m");
1751                         goto finish;
1752                 }
1753
1754                 events_a = sd_bus_get_events(a);
1755                 if (events_a < 0) {
1756                         log_error_errno(r, "Failed to get events mask: %m");
1757                         goto finish;
1758                 }
1759
1760                 r = sd_bus_get_timeout(a, &timeout_a);
1761                 if (r < 0) {
1762                         log_error_errno(r, "Failed to get timeout: %m");
1763                         goto finish;
1764                 }
1765
1766                 events_b = sd_bus_get_events(b);
1767                 if (events_b < 0) {
1768                         log_error_errno(r, "Failed to get events mask: %m");
1769                         goto finish;
1770                 }
1771
1772                 r = sd_bus_get_timeout(b, &timeout_b);
1773                 if (r < 0) {
1774                         log_error_errno(r, "Failed to get timeout: %m");
1775                         goto finish;
1776                 }
1777
1778                 t = timeout_a;
1779                 if (t == (uint64_t) -1 || (timeout_b != (uint64_t) -1 && timeout_b < timeout_a))
1780                         t = timeout_b;
1781
1782                 if (t == (uint64_t) -1)
1783                         ts = NULL;
1784                 else {
1785                         usec_t nw;
1786
1787                         nw = now(CLOCK_MONOTONIC);
1788                         if (t > nw)
1789                                 t -= nw;
1790                         else
1791                                 t = 0;
1792
1793                         ts = timespec_store(&_ts, t);
1794                 }
1795
1796                 pollfd = (struct pollfd[3]) {
1797                         {.fd = fd,     .events = events_a,           },
1798                         {.fd = in_fd,  .events = events_b & POLLIN,  },
1799                         {.fd = out_fd, .events = events_b & POLLOUT, }
1800                 };
1801
1802                 r = ppoll(pollfd, 3, ts, NULL);
1803                 if (r < 0) {
1804                         log_error_errno(errno, "ppoll() failed: %m");
1805                         goto finish;
1806                 }
1807         }
1808
1809 finish:
1810         sd_notify(false,
1811                   "STOPPING=1\n"
1812                   "STATUS=Shutting down.");
1813
1814         policy_free(&policy_buffer);
1815         strv_free(arg_configuration);
1816         free(arg_address);
1817
1818         return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
1819 }