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