Skip to content

Commit b943517

Browse files
committed
Reduce code duplication in init_entropy()
Signed-off-by: DL6ER <[email protected]>
1 parent 778cc66 commit b943517

File tree

1 file changed

+31
-21
lines changed

1 file changed

+31
-21
lines changed

src/webserver/x509.c

+31-21
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,22 @@
2525
#define RSA_KEY_SIZE 4096
2626
#define BUFFER_SIZE 16000
2727

28+
static bool read_id_file(const char *filename, char *buffer, size_t buffer_size)
29+
{
30+
FILE *f = fopen(filename, "r");
31+
if(f == NULL)
32+
return false;
33+
34+
if(fread(buffer, 1, buffer_size, f) != buffer_size)
35+
{
36+
fclose(f);
37+
return false;
38+
}
39+
40+
fclose(f);
41+
return true;
42+
}
43+
2844
static mbedtls_entropy_context entropy = { 0 };
2945
static mbedtls_ctr_drbg_context ctr_drbg = { 0 };
3046
/**
@@ -47,28 +63,23 @@ bool init_entropy(void)
4763
mbedtls_ctr_drbg_init(&ctr_drbg);
4864
mbedtls_entropy_init(&entropy);
4965

50-
char machine_id[33] = { 0 };
51-
// Get machine-id
66+
// Get machine-id (this may fail in containers)
5267
// https://www.freedesktop.org/software/systemd/man/latest/machine-id.html
53-
FILE *f = fopen("/etc/machine-id", "r");
54-
if(f == NULL)
55-
{
56-
log_warn("Could not open /etc/machine-id, using fallback");
57-
strcpy(machine_id, "c7bde55876876987accc913546f3bcc");
58-
}
59-
else
68+
char machine_id[128] = { 0 };
69+
read_id_file("/etc/machine-id", machine_id, sizeof(machine_id));
70+
71+
// The boot_id random ID that is regenerated on each boot. As such it
72+
// can be used to identify the local machine’s current boot. It’s
73+
// universally available on any recent Linux kernel. It’s a good and
74+
// safe choice if you need to identify a specific boot on a specific
75+
// booted kernel.
76+
// Read /proc/sys/kernel/random/boot_id and append it to machine_id
77+
// The UUID is in format 8-4-4-4-12 and, hence, 36 characters long
78+
char boot_id[37] = { 0 };
79+
if(read_id_file("/proc/sys/kernel/random/boot_id", boot_id, sizeof(boot_id)))
6080
{
61-
if(fread(machine_id, 1, 32, f) != 32)
62-
{
63-
log_warn("Could not read /etc/machine-id, using fallback");
64-
strcpy(machine_id, "c7bde55876876987accc913546f3bcc");
65-
}
66-
else
67-
{
68-
// Ensure null-termination
69-
machine_id[32] = '\0';
70-
}
71-
fclose(f);
81+
boot_id[36] = '\0';
82+
strncat(machine_id, boot_id, sizeof(machine_id) - strlen(machine_id) - 1);
7283
}
7384

7485
// Initialize random number generator
@@ -79,7 +90,6 @@ bool init_entropy(void)
7990
return false;
8091
}
8192

82-
log_info("Random number generator initialized successfully");
8393
initialized = true;
8494
return true;
8595
}

0 commit comments

Comments
 (0)