udev_device.c: fix TOCTOU race condition (#57)

Separately checking the state of a file before operating on it may allow
an attacker to modify the file between the two operations.

Reference: CWE-367.
This commit is contained in:
Mingjie Shen
2023-12-05 03:41:24 -05:00
committed by GitHub
parent 90480bf525
commit a2cc51bb14

View File

@@ -267,16 +267,17 @@ const char *udev_device_get_sysattr_value(struct udev_device *udev_device, const
snprintf(path, sizeof(path), "%s/%s", udev_device_get_syspath(udev_device), sysattr);
if (lstat(path, &st) != 0 || !S_ISREG(st.st_mode)) {
return NULL;
}
file = fopen(path, "r");
if (!file) {
return NULL;
}
if (fstat(fileno(file), &st) != 0 || !S_ISREG(st.st_mode)) {
fclose(file);
return NULL;
}
// TODO dynamic allocation of data
len = fread(data, 1, sizeof(data) - 1, file);
@@ -309,16 +310,17 @@ int udev_device_set_sysattr_value(struct udev_device *udev_device, const char *s
snprintf(path, sizeof(path), "%s/%s", udev_device_get_syspath(udev_device), sysattr);
if (lstat(path, &st) != 0 || !S_ISREG(st.st_mode)) {
return -1;
}
file = fopen(path, "w");
if (!file) {
return -1;
}
if (fstat(fileno(file), &st) != 0 || !S_ISREG(st.st_mode)) {
fclose(file);
return -1;
}
len = strlen(value);
if (fwrite(value, 1, len, file) != len) {