Skip to content
Open
56 changes: 54 additions & 2 deletions src/flb_utils.c
Original file line number Diff line number Diff line change
Expand Up @@ -2043,13 +2043,40 @@ static int machine_id_read_and_sanitize(char *path,
return 0;
}

static int write_uuid_to_file(const char* filename, char* uuid)
{
int fd;
size_t uuid_len;

if (filename == NULL || uuid == NULL) {
return FLB_FALSE;
}

/* write uuid to file */
fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC, 0600);
if (fd == -1) {
return FLB_FALSE;
}

uuid_len = strlen(uuid);

if (write(fd, uuid, uuid_len) != uuid_len) {
close(fd);
return FLB_FALSE;
}

close(fd);
return FLB_TRUE;
}

int flb_utils_get_machine_id(char **out_id, size_t *out_size)
{
int ret;
char *id;
size_t bytes;
char *uuid;
int fallback = FLB_FALSE;
char *fallback_id_file = "/tmp/flb-machine-id"; /*should reside in current working directory*/

#ifdef __linux__
char *dbus_var = "/var/lib/dbus/machine-id";
Expand Down Expand Up @@ -2084,6 +2111,22 @@ int flb_utils_get_machine_id(char **out_id, size_t *out_size)
return 0;
}
}

if (access(fallback_id_file, F_OK) == 0){
ret = machine_id_read_and_sanitize(fallback_id_file, &id, &bytes);
if (ret == 0){
if (bytes == 0) {
/* guid is somewhat corrupted */
fallback = FLB_TRUE;
goto fallback;
}
}

*out_id = id;
*out_size = bytes;
return 0;
Comment on lines +2123 to +2127

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Return uninitialized fallback ID on read failure

If a fallback machine-id file exists but machine_id_read_and_sanitize fails (e.g., unreadable or malformed), ret remains non‑zero yet the code still assigns id/bytes to the outputs and returns success because the return block sits outside the ret == 0 guard. In that scenario id and bytes are uninitialized, so callers can receive a garbage pointer/size or crash instead of regenerating an ID. The return should stay within the successful read path or jump to the fallback path when the read fails.

Useful? React with 👍 / 👎.

}

#elif defined(__FreeBSD__) || defined(__NetBSD__) || \
defined(__OpenBSD__) || defined(__DragonFly__)

Expand Down Expand Up @@ -2175,7 +2218,7 @@ int flb_utils_get_machine_id(char **out_id, size_t *out_size)
#endif

fallback:

flb_warn("falling back on random machine UUID");

/* generate a random uuid */
Expand All @@ -2185,15 +2228,24 @@ int flb_utils_get_machine_id(char **out_id, size_t *out_size)
return -1;
}
ret = flb_utils_uuid_v4_gen(uuid);

if (ret == 0) {

ret = write_uuid_to_file(fallback_id_file, uuid);
if (ret == FLB_FALSE){
/*
* writing failed, next uuid generation will be random again
* log a warning message and return
*/
flb_warn("failed to write machine-id to file %s", fallback_id_file);
}
*out_id = uuid;
*out_size = strlen(uuid);
if (fallback == FLB_TRUE) {
return 2;
}
return 0;
}

return -1;
}

Expand Down