discover/discover-server: Restrict clients based on uid
[petitboot] / discover / boot.c
1
2 #if defined(HAVE_CONFIG_H)
3 #include "config.h"
4 #endif
5
6 #include <stdbool.h>
7 #include <stdlib.h>
8 #include <assert.h>
9 #include <dirent.h>
10 #include <string.h>
11 #include <fcntl.h>
12 #include <sys/types.h>
13
14 #include <log/log.h>
15 #include <pb-protocol/pb-protocol.h>
16 #include <process/process.h>
17 #include <system/system.h>
18 #include <talloc/talloc.h>
19 #include <url/url.h>
20 #include <util/util.h>
21 #include <i18n/i18n.h>
22
23 #include "device-handler.h"
24 #include "boot.h"
25 #include "paths.h"
26 #include "resource.h"
27 #include "platform.h"
28
29 #include <security/security.h>
30
31 static const char *boot_hook_dir = PKG_SYSCONF_DIR "/boot.d";
32 enum {
33         BOOT_HOOK_EXIT_OK       = 0,
34         BOOT_HOOK_EXIT_UPDATE   = 2,
35 };
36
37 static void __attribute__((format(__printf__, 4, 5))) update_status(
38                 boot_status_fn fn, void *arg, int type, char *fmt, ...)
39 {
40         struct status status;
41         va_list ap;
42
43         va_start(ap, fmt);
44         status.message = talloc_vasprintf(NULL, fmt, ap);
45         va_end(ap);
46
47         status.type = type;
48         status.backlog = false;
49         status.boot_active = type == STATUS_INFO;
50
51         pb_debug("boot status: [%d] %s\n", type, status.message);
52
53         fn(arg, &status);
54
55         talloc_free(status.message);
56 }
57
58 /**
59  * kexec_load - kexec load helper.
60  */
61 static int kexec_load(struct boot_task *boot_task)
62 {
63         struct process *process;
64         char *s_initrd = NULL;
65         char *s_args = NULL;
66         const char *argv[8];
67         char *s_dtb = NULL;
68         const char **p;
69         int result;
70
71
72         boot_task->local_initrd_override = NULL;
73         boot_task->local_dtb_override = NULL;
74         boot_task->local_image_override = NULL;
75
76         if ((result = validate_boot_files(boot_task))) {
77                 if (result == KEXEC_LOAD_DECRYPTION_FALURE) {
78                         pb_log("%s: Aborting kexec due to"
79                                 " decryption failure\n", __func__);
80                 }
81                 if (result == KEXEC_LOAD_SIGNATURE_FAILURE) {
82                         pb_log("%s: Aborting kexec due to signature"
83                                 " verification failure\n", __func__);
84                 }
85
86                 goto abort_kexec;
87         }
88
89         const char* local_initrd = (boot_task->local_initrd_override) ?
90                 boot_task->local_initrd_override : boot_task->local_initrd;
91         const char* local_dtb = (boot_task->local_dtb_override) ?
92                 boot_task->local_dtb_override : boot_task->local_dtb;
93         const char* local_image = (boot_task->local_image_override) ?
94                 boot_task->local_image_override : boot_task->local_image;
95
96         process = process_create(boot_task);
97         if (!process) {
98                 pb_log_fn("failed to create process\n");
99                 return -1;
100         }
101
102         process->path = pb_system_apps.kexec;
103         process->argv = argv;
104         process->keep_stdout = true;
105         process->add_stderr = true;
106
107         p = argv;
108         *p++ = pb_system_apps.kexec;    /* 1 */
109         *p++ = "-l";                    /* 2 */
110
111         if (pb_log_get_debug()) {
112                 *p++ = "--debug";       /* 3 */
113         }
114
115         if (local_initrd) {
116                 s_initrd = talloc_asprintf(boot_task, "--initrd=%s",
117                                 local_initrd);
118                 assert(s_initrd);
119                 *p++ = s_initrd;         /* 4 */
120         }
121
122         if (local_dtb) {
123                 s_dtb = talloc_asprintf(boot_task, "--dtb=%s",
124                                                 local_dtb);
125                 assert(s_dtb);
126                 *p++ = s_dtb;            /* 5 */
127         }
128
129         s_args = talloc_asprintf(boot_task, "--append=%s",
130                                 boot_task->args ?: "\"\"");
131         assert(s_args);
132         *p++ = s_args;                  /* 6 */
133
134         *p++ = local_image;             /* 7 */
135         *p++ = NULL;                    /* 8 */
136
137         result = process_run_sync(process);
138         if (result) {
139                 pb_log_fn("failed to run process\n");
140                 goto abort_kexec;
141         }
142
143         result = process->exit_status;
144
145         if (result) {
146                 pb_log_fn("failed: (%d)\n", result);
147                 update_status(boot_task->status_fn, boot_task->status_arg,
148                                 STATUS_ERROR, "%s", process->stdout_buf);
149         }
150
151 abort_kexec:
152         validate_boot_files_cleanup(boot_task);
153
154         return result;
155 }
156
157 /**
158  * kexec_reboot - Helper to boot the new kernel.
159  *
160  * Must only be called after a successful call to kexec_load().
161  */
162
163 static int kexec_reboot(struct boot_task *task)
164 {
165         int result;
166
167         /* First try running shutdown.  Init scripts should run 'exec -e' */
168         result = process_run_simple(task, pb_system_apps.shutdown, "-r",
169                         "now", NULL);
170
171         /* On error, force a kexec with the -e option */
172         if (result) {
173                 result = process_run_simple(task, pb_system_apps.kexec,
174                                                 "-e", NULL);
175         }
176
177         if (result)
178                 pb_log_fn("failed: (%d)\n", result);
179
180         /* okay, kexec -e -f */
181         if (result) {
182                 result = process_run_simple(task, pb_system_apps.kexec,
183                                                 "-e", "-f", NULL);
184         }
185
186         if (result)
187                 pb_log_fn("failed: (%d)\n", result);
188
189
190         return result;
191 }
192
193 static void boot_hook_update_param(void *ctx, struct boot_task *task,
194                 const char *name, const char *value)
195 {
196         struct p {
197                 const char *name;
198                 const char **p;
199         } *param, params[] = {
200                 { "boot_image",         &task->local_image },
201                 { "boot_initrd",        &task->local_initrd },
202                 { "boot_dtb",           &task->local_dtb },
203                 { "boot_args",          &task->args },
204                 { NULL, NULL },
205         };
206
207         for (param = params; param->name; param++) {
208                 if (strcmp(param->name, name))
209                         continue;
210
211                 *param->p = talloc_strdup(ctx, value);
212                 return;
213         }
214 }
215
216 static void boot_hook_update(struct boot_task *task, const char *hookname,
217                 char *buf)
218 {
219         char *line, *name, *val, *sep;
220         char *saveptr = NULL;
221
222         for (;; buf = NULL) {
223
224                 line = strtok_r(buf, "\n", &saveptr);
225                 if (!line)
226                         break;
227
228                 sep = strchr(line, '=');
229                 if (!sep)
230                         continue;
231
232                 *sep = '\0';
233                 name = line;
234                 val = sep + 1;
235
236                 boot_hook_update_param(task, task, name, val);
237
238                 pb_log("boot hook %s specified %s=%s\n",
239                                 hookname, name, val);
240         }
241 }
242
243 static void boot_hook_setenv(struct boot_task *task)
244 {
245         unsetenv("boot_image");
246         unsetenv("boot_initrd");
247         unsetenv("boot_dtb");
248         unsetenv("boot_args");
249         unsetenv("boot_console");
250
251         setenv("boot_image", task->local_image, 1);
252         if (task->local_initrd)
253                 setenv("boot_initrd", task->local_initrd, 1);
254         if (task->local_dtb)
255                 setenv("boot_dtb", task->local_dtb, 1);
256         if (task->args)
257                 setenv("boot_args", task->args, 1);
258         if (task->boot_console)
259                 setenv("boot_console", task->boot_console, 1);
260 }
261
262 static int hook_filter(const struct dirent *dirent)
263 {
264         return dirent->d_type == DT_REG || dirent->d_type == DT_LNK;
265 }
266
267 static int hook_cmp(const struct dirent **a, const struct dirent **b)
268 {
269         return strcmp((*a)->d_name, (*b)->d_name);
270 }
271
272 static void run_boot_hooks(struct boot_task *task)
273 {
274         struct dirent **hooks;
275         int i, n;
276
277         n = scandir(boot_hook_dir, &hooks, hook_filter, hook_cmp);
278         if (n < 1)
279                 return;
280
281         update_status(task->status_fn, task->status_arg, STATUS_INFO,
282                         _("Running boot hooks"));
283
284         boot_hook_setenv(task);
285
286         for (i = 0; i < n; i++) {
287                 const char *argv[2] = { NULL, NULL };
288                 struct process *process;
289                 char *path;
290                 int rc;
291
292                 path = join_paths(task, boot_hook_dir, hooks[i]->d_name);
293
294                 if (access(path, X_OK)) {
295                         talloc_free(path);
296                         continue;
297                 }
298
299                 process = process_create(task);
300
301                 argv[0] = path;
302                 process->path = path;
303                 process->argv = argv;
304                 process->keep_stdout = true;
305
306                 pb_log("running boot hook %s\n", hooks[i]->d_name);
307
308                 rc = process_run_sync(process);
309                 if (rc) {
310                         pb_log("boot hook exec failed!\n");
311
312                 } else if (WIFEXITED(process->exit_status) &&
313                            WEXITSTATUS(process->exit_status)
314                                 == BOOT_HOOK_EXIT_UPDATE) {
315                         /* if the hook returned with BOOT_HOOK_EXIT_UPDATE,
316                          * then we process stdout to look for updated params
317                          */
318                         boot_hook_update(task, hooks[i]->d_name,
319                                         process->stdout_buf);
320                         boot_hook_setenv(task);
321                 }
322
323                 process_release(process);
324                 talloc_free(path);
325         }
326
327         free(hooks);
328 }
329
330 static bool load_pending(struct load_url_result *result)
331 {
332         return !result || result->status == LOAD_ASYNC;
333 }
334
335 static int check_load(struct boot_task *task, const char *name,
336                 struct load_url_result *result)
337 {
338         if (!result)
339                 return 0;
340
341         if (result->status != LOAD_ERROR) {
342                 update_status(task->status_fn, task->status_arg,
343                                 STATUS_ERROR,
344                                 _("Loaded %s from %s"), name,
345                                 pb_url_to_string(result->url));
346                 return 0;
347         }
348
349         pb_log("Failed to load %s from %s\n", name,
350                         pb_url_to_string(result->url));
351         update_status(task->status_fn, task->status_arg,
352                         STATUS_ERROR,
353                         _("Couldn't load %s from %s"), name,
354                         pb_url_to_string(result->url));
355         return -1;
356 }
357
358 static void cleanup_load(struct load_url_result *result)
359 {
360         if (!result)
361                 return;
362         if (result->status != LOAD_OK)
363                 return;
364         if (!result->cleanup_local)
365                 return;
366         unlink(result->local);
367 }
368
369 static void cleanup_cancellations(struct boot_task *task,
370                 struct load_url_result *cur_result)
371 {
372         struct boot_resource *resource;
373         struct load_url_result *result;
374         bool pending = false;
375
376         list_for_each_entry(&task->resources, resource, list) {
377                 result = resource->result;
378
379                 /* Nothing to do if a load hasn't actually started yet */
380                 if (!result)
381                         continue;
382
383                 /* We need to cleanup and free any completed loads */
384                 if (result == cur_result || result->status == LOAD_OK
385                                 || result->status == LOAD_ERROR) {
386                         cleanup_load(result);
387                 /* ... and cancel any pending loads, which we'll free in
388                  * the completion callback */
389                 } else if (result->status == LOAD_ASYNC) {
390                         load_url_async_cancel(result);
391                         pending = true;
392
393                 /* if we're waiting for a cancellation, we still need to
394                  * wait for the completion before freeing the boot task */
395                 } else if (result->status == LOAD_CANCELLED) {
396                         pending = true;
397                 }
398         }
399
400         if (!pending)
401                 talloc_free(task);
402 }
403
404 static void boot_process(struct load_url_result *result, void *data)
405 {
406         struct boot_task *task = data;
407         struct boot_resource *resource;
408         int rc = -1;
409
410         if (task->cancelled) {
411                 cleanup_cancellations(task, result);
412                 return;
413         }
414
415         list_for_each_entry(&task->resources, resource, list)
416                 if (load_pending(resource->result))
417                         return;
418
419         list_for_each_entry(&task->resources, resource, list) {
420                 if (check_load(task, resource->name, resource->result))
421                         goto no_load;
422                 *resource->local_path = resource->result->local;
423         }
424
425         run_boot_hooks(task);
426
427         update_status(task->status_fn, task->status_arg, STATUS_INFO,
428                         _("Performing kexec load"));
429
430         rc = kexec_load(task);
431         pb_log_fn("kexec_load returned %d\n", rc);
432         if (rc == KEXEC_LOAD_DECRYPTION_FALURE) {
433                 update_status(task->status_fn, task->status_arg,
434                                 STATUS_ERROR, _("Decryption failed"));
435         }
436         else if (rc == KEXEC_LOAD_SIGNATURE_FAILURE) {
437                 update_status(task->status_fn, task->status_arg,
438                                 STATUS_ERROR,
439                                 _("Signature verification failed"));
440         }
441         else if (rc == KEXEC_LOAD_SIG_SETUP_INVALID) {
442                 update_status(task->status_fn, task->status_arg,
443                                 STATUS_ERROR,
444                                 _("Invalid signature configuration"));
445         }
446
447 no_load:
448         list_for_each_entry(&task->resources, resource, list)
449                 cleanup_load(resource->result);
450
451         if (!rc) {
452                 update_status(task->status_fn, task->status_arg,
453                                 STATUS_INFO, _("Performing kexec reboot"));
454
455                 rc = kexec_reboot(task);
456                 if (rc) {
457                         update_status(task->status_fn, task->status_arg,
458                                         STATUS_ERROR,
459                                         _("kexec reboot failed"));
460                 }
461         } else {
462                 pb_log("Failed to load all boot resources\n");
463         }
464 }
465
466 static int start_url_load(struct boot_task *task, struct boot_resource *res)
467 {
468         if (!res)
469                 return 0;
470
471         res->result = load_url_async(task, res->url, boot_process,
472                                  task, NULL, task->status_arg);
473         if (!res->result) {
474                 pb_log("Error starting load for %s at %s\n",
475                                 res->name, pb_url_to_string(res->url));
476                 update_status(task->status_fn, task->status_arg,
477                                 STATUS_ERROR, _("Error loading %s"),
478                                 res->name);
479                 return -1;
480         }
481         return 0;
482 }
483
484 static struct boot_resource *add_boot_resource(struct boot_task *task,
485                 const char *name, struct pb_url *url,
486                 const char **local_path)
487 {
488         struct boot_resource *res;
489
490         if (!url)
491                 return NULL;
492
493         res = talloc_zero(task, struct boot_resource);
494         if (!res)
495                 return NULL;
496
497         res->name = talloc_strdup(res, name);
498         res->url = pb_url_copy(res, url);
499         res->local_path = local_path;
500
501         list_add(&task->resources, &res->list);
502         return res;
503 }
504
505 struct boot_task *boot(void *ctx, struct discover_boot_option *opt,
506                 struct boot_command *cmd, int dry_run,
507                 boot_status_fn status_fn, void *status_arg)
508 {
509         struct pb_url *image = NULL, *initrd = NULL, *dtb = NULL;
510         struct pb_url *image_sig = NULL, *initrd_sig = NULL, *dtb_sig = NULL,
511                 *cmdline_sig = NULL;
512         struct boot_resource *image_res, *initrd_res, *dtb_res, *tmp;
513         const struct config *config = config_get();
514         struct boot_task *boot_task;
515         const char *boot_desc;
516         int rc;
517         int lockdown_type;
518
519         if (opt && opt->option->name)
520                 boot_desc = opt->option->name;
521         else if (cmd && cmd->boot_image_file)
522                 boot_desc = cmd->boot_image_file;
523         else
524                 boot_desc = _("(unknown)");
525
526         update_status(status_fn, status_arg, STATUS_INFO,
527                         _("Booting %s"), boot_desc);
528
529         boot_task = talloc_zero(ctx, struct boot_task);
530         boot_task->dry_run = dry_run;
531         boot_task->status_fn = status_fn;
532         boot_task->status_arg = status_arg;
533
534         if (cmd && cmd->boot_image_file) {
535                 image = pb_url_parse(boot_task, cmd->boot_image_file);
536         } else if (opt && opt->boot_image) {
537                 image = opt->boot_image->url;
538         } else {
539                 pb_log_fn("no image specified\n");
540                 update_status(status_fn, status_arg, STATUS_ERROR,
541                                 _("Boot failed: no image specified"));
542                 talloc_free(boot_task);
543                 return NULL;
544         }
545
546         if (cmd && cmd->initrd_file) {
547                 initrd = pb_url_parse(boot_task, cmd->initrd_file);
548         } else if (opt && opt->initrd) {
549                 initrd = opt->initrd->url;
550         }
551
552         if (cmd && cmd->dtb_file) {
553                 dtb = pb_url_parse(boot_task, cmd->dtb_file);
554         } else if (opt && opt->dtb) {
555                 dtb = opt->dtb->url;
556         }
557
558         if (opt && opt->proxy) {
559                 setenv("http_proxy", opt->proxy, 1);
560                 setenv("https_proxy", opt->proxy, 1);
561         }
562
563         list_init(&boot_task->resources);
564
565         lockdown_type = lockdown_status();
566         boot_task->verify_signature = (lockdown_type == PB_LOCKDOWN_SIGN);
567         boot_task->decrypt_files = (lockdown_type == PB_LOCKDOWN_DECRYPT);
568
569         if (cmd && cmd->boot_args) {
570                 boot_task->args = talloc_strdup(boot_task, cmd->boot_args);
571         } else if (opt && opt->option->boot_args) {
572                 boot_task->args = talloc_strdup(boot_task,
573                                                 opt->option->boot_args);
574         } else {
575                 boot_task->args = NULL;
576         }
577
578         if (cmd && cmd->console && !config->manual_console)
579                 boot_task->boot_console = talloc_strdup(boot_task, cmd->console);
580         else
581                 boot_task->boot_console = config ? config->boot_console : NULL;
582
583         if (boot_task->verify_signature || boot_task->decrypt_files) {
584                 if (cmd && cmd->args_sig_file) {
585                         cmdline_sig = pb_url_parse(opt, cmd->args_sig_file);
586                 } else if (opt && opt->args_sig_file) {
587                         cmdline_sig = opt->args_sig_file->url;
588                 } else {
589                         pb_log("%s: no command line signature file"
590                                 " specified\n", __func__);
591                         update_status(status_fn, status_arg, STATUS_ERROR,
592                                         _("Boot failed: no command line"
593                                                 " signature file specified"));
594                         talloc_free(boot_task);
595                         return NULL;
596                 }
597         }
598
599         image_res = add_boot_resource(boot_task, _("kernel image"), image,
600                         &boot_task->local_image);
601         initrd_res = add_boot_resource(boot_task, _("initrd"), initrd,
602                         &boot_task->local_initrd);
603         dtb_res = add_boot_resource(boot_task, _("dtb"), dtb,
604                         &boot_task->local_dtb);
605
606         /* start async loads for boot resources */
607         rc = start_url_load(boot_task, image_res)
608           || start_url_load(boot_task, initrd_res)
609           || start_url_load(boot_task, dtb_res);
610
611         if (boot_task->verify_signature) {
612                 /* Generate names of associated signature files and load */
613                 if (image) {
614                         image_sig = get_signature_url(ctx, image);
615                         tmp = add_boot_resource(boot_task,
616                                         _("kernel image signature"), image_sig,
617                                         &boot_task->local_image_signature);
618                         rc |= start_url_load(boot_task, tmp);
619                 }
620                 if (initrd) {
621                         initrd_sig = get_signature_url(ctx, initrd);
622                         tmp = add_boot_resource(boot_task,
623                                         _("initrd signature"), initrd_sig,
624                                         &boot_task->local_initrd_signature);
625                         rc |= start_url_load(boot_task, tmp);
626                 }
627                 if (dtb) {
628                         dtb_sig = get_signature_url(ctx, dtb);
629                         tmp = add_boot_resource(boot_task,
630                                         _("dtb signature"), dtb_sig,
631                                         &boot_task->local_dtb_signature);
632                         rc |= start_url_load(boot_task, tmp);
633                 }
634         }
635
636         if (boot_task->verify_signature || boot_task->decrypt_files) {
637                 tmp = add_boot_resource(boot_task,
638                                 _("kernel command line signature"), cmdline_sig,
639                                 &boot_task->local_cmdline_signature);
640                 rc |= start_url_load(boot_task, tmp);
641         }
642
643         /* If all URLs are local, we may be done. */
644         if (rc) {
645                 /* Don't call boot_cancel() to preserve the status update */
646                 boot_task->cancelled = true;
647                 cleanup_cancellations(boot_task, NULL);
648                 return NULL;
649         }
650
651         boot_process(NULL, boot_task);
652
653         return boot_task;
654 }
655
656 void boot_cancel(struct boot_task *task)
657 {
658         task->cancelled = true;
659
660         update_status(task->status_fn, task->status_arg, STATUS_ERROR,
661                         _("Boot cancelled"));
662
663         cleanup_cancellations(task, NULL);
664 }