summaryrefslogtreecommitdiffstats
path: root/libs/libudev-zero/patches/0001-udev_device.c-fix-TOCTOU-race-condition-57.patch
blob: 4d3528d62de017c51d7d4f5056f15a8f0c6f8303 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
From a2cc51bb142c16eac5598237d2edb46f095607be Mon Sep 17 00:00:00 2001
From: Mingjie Shen <mjshen137@gmail.com>
Date: Tue, 5 Dec 2023 03:41:24 -0500
Subject: [PATCH] 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.
---
 udev_device.c | 18 ++++++++++--------
 1 file changed, 10 insertions(+), 8 deletions(-)

--- a/udev_device.c
+++ b/udev_device.c
@@ -267,16 +267,17 @@ const char *udev_device_get_sysattr_valu
 
     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
 
     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) {