blob: e0d3c7fe7489143ab1971e15a4c492f5c1d025de [file] [log] [blame]
Chris Morgan61a96182021-08-25 11:22:57 -05001// SPDX-License-Identifier: GPL-2.0+
2/*
3 * The 'kaslrseed' command takes bytes from the hardware random number
4 * generator and uses them to set the kaslr-seed value in the chosen node.
5 *
6 * Copyright (c) 2021, Chris Morgan <macromorgan@hotmail.com>
7 */
8
Chris Morgan61a96182021-08-25 11:22:57 -05009#include <command.h>
10#include <dm.h>
11#include <hexdump.h>
12#include <malloc.h>
13#include <rng.h>
14#include <fdt_support.h>
15
16static int do_kaslr_seed(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[])
17{
18 size_t n = 0x8;
19 struct udevice *dev;
20 u64 *buf;
21 int nodeoffset;
22 int ret = CMD_RET_SUCCESS;
23
24 if (uclass_get_device(UCLASS_RNG, 0, &dev) || !dev) {
25 printf("No RNG device\n");
26 return CMD_RET_FAILURE;
27 }
28
29 buf = malloc(n);
30 if (!buf) {
31 printf("Out of memory\n");
32 return CMD_RET_FAILURE;
33 }
34
35 if (dm_rng_read(dev, buf, n)) {
36 printf("Reading RNG failed\n");
37 return CMD_RET_FAILURE;
38 }
39
40 if (!working_fdt) {
41 printf("No FDT memory address configured. Please configure\n"
42 "the FDT address via \"fdt addr <address>\" command.\n"
43 "Aborting!\n");
44 return CMD_RET_FAILURE;
45 }
46
47 ret = fdt_check_header(working_fdt);
48 if (ret < 0) {
49 printf("fdt_chosen: %s\n", fdt_strerror(ret));
50 return CMD_RET_FAILURE;
51 }
52
53 nodeoffset = fdt_find_or_add_subnode(working_fdt, 0, "chosen");
54 if (nodeoffset < 0) {
55 printf("Reading chosen node failed\n");
56 return CMD_RET_FAILURE;
57 }
58
59 ret = fdt_setprop(working_fdt, nodeoffset, "kaslr-seed", buf, sizeof(buf));
60 if (ret < 0) {
61 printf("Unable to set kaslr-seed on chosen node: %s\n", fdt_strerror(ret));
62 return CMD_RET_FAILURE;
63 }
64
65 free(buf);
66
67 return ret;
68}
69
Tom Rini03f146c2023-10-07 15:13:08 -040070U_BOOT_LONGHELP(kaslrseed,
Chris Morgan61a96182021-08-25 11:22:57 -050071 "[n]\n"
Tom Rini03f146c2023-10-07 15:13:08 -040072 " - append random bytes to chosen kaslr-seed node\n");
Chris Morgan61a96182021-08-25 11:22:57 -050073
74U_BOOT_CMD(
75 kaslrseed, 1, 0, do_kaslr_seed,
76 "feed bytes from the hardware random number generator to the kaslr-seed",
77 kaslrseed_help_text
78);