Browse code

retry_realpath: check before possibly writing out of bounds

Sigrid Solveig Haflínudóttir authored on 10/07/2023 17:21:36
Showing 1 changed files
... ...
@@ -126,10 +126,11 @@ static char *
126 126
 retry_realpath(const char *file_name)
127 127
 {
128 128
 	char *r, p[PATH_MAX] = {'\0'}, *x;
129
+	int fnlen;
129 130
 	if(file_name == NULL) {
130 131
 		errno = EINVAL;
131 132
 		return NULL;
132
-	} else if(strlen(file_name) >= PATH_MAX) {
133
+	} else if((fnlen = strlen(file_name)) >= PATH_MAX) {
133 134
 		errno = ENAMETOOLONG;
134 135
 		return NULL;
135 136
 	}
... ...
@@ -137,6 +138,10 @@ retry_realpath(const char *file_name)
137 138
 		/* TODO: use a macro instead of '/' for absolute path first character so that other systems can work */
138 139
 		/* if a relative path, prepend cwd */
139 140
 		getcwd(p, sizeof(p));
141
+		if(strlen(p) + strlen(DIR_SEP_STR) + fnlen >= PATH_MAX) {
142
+			errno = ENAMETOOLONG;
143
+			return NULL;
144
+		}
140 145
 		strcat(p, DIR_SEP_STR); /* TODO: use a macro instead of '/' for the path delimiter */
141 146
 	}
142 147
 	strcat(p, file_name);