Skip to content

Commit 189ca35

Browse files
committed
Ensure /dev/mem is a character device file
While option --dev-mem can be convenient for testing purposes, it could be abused by attackers to force dmidecode to read a malicious file. Add a safety check on the type of the mem device file we are asked to read from. If we are root and this isn't a character device file, then something is fishy and we better stop. For non-root users, reading from a regular file is OK and accepted. Signed-off-by: Jean Delvare <jdelvare@suse.de>
1 parent 8427888 commit 189ca35

File tree

1 file changed

+13
-12
lines changed

1 file changed

+13
-12
lines changed

util.c

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -173,18 +173,26 @@ static void safe_memcpy(void *dest, const void *src, size_t n)
173173
*/
174174
void *mem_chunk(off_t base, size_t len, const char *devmem)
175175
{
176-
void *p;
176+
struct stat statbuf;
177+
void *p = NULL;
177178
int fd;
178179
#ifdef USE_MMAP
179-
struct stat statbuf;
180180
off_t mmoffset;
181181
void *mmp;
182182
#endif
183183

184-
if ((fd = open(devmem, O_RDONLY)) == -1)
184+
/*
185+
* Safety check: if running as root, devmem is expected to be a
186+
* character device file.
187+
*/
188+
if ((fd = open(devmem, O_RDONLY)) == -1
189+
|| fstat(fd, &statbuf) == -1
190+
|| (geteuid() == 0 && !S_ISCHR(statbuf.st_mode)))
185191
{
186-
perror(devmem);
187-
return NULL;
192+
fprintf(stderr, "Can't read memory from %s\n", devmem);
193+
if (fd == -1)
194+
return NULL;
195+
goto out;
188196
}
189197

190198
if ((p = malloc(len)) == NULL)
@@ -194,13 +202,6 @@ void *mem_chunk(off_t base, size_t len, const char *devmem)
194202
}
195203

196204
#ifdef USE_MMAP
197-
if (fstat(fd, &statbuf) == -1)
198-
{
199-
fprintf(stderr, "%s: ", devmem);
200-
perror("stat");
201-
goto err_free;
202-
}
203-
204205
/*
205206
* mmap() will fail with SIGBUS if trying to map beyond the end of
206207
* the file.

0 commit comments

Comments
 (0)