Skip to content

Commit 6fa12d5

Browse files
Telecaster2147Rbb666
authored andcommitted
fix(ramfs): harden entry name validation and termination
1 parent c167bbb commit 6fa12d5

File tree

1 file changed

+61
-5
lines changed

1 file changed

+61
-5
lines changed

components/dfs/dfs_v1/filesystems/ramfs/dfs_ramfs.c

Lines changed: 61 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,56 @@ int dfs_ramfs_ioctl(struct dfs_file *file, int cmd, void *args)
5959
return -EIO;
6060
}
6161

62+
63+
static int _ramfs_set_name(char *name, rt_size_t name_size, const char *path)
64+
{
65+
const char *name_ptr = path;
66+
const char *name_scan;
67+
rt_size_t name_len;
68+
69+
if (path == RT_NULL)
70+
{
71+
return -EINVAL;
72+
}
73+
74+
if (path[0] != '/')
75+
{
76+
return -EINVAL;
77+
}
78+
79+
while (*name_ptr == '/' && *name_ptr)
80+
{
81+
name_ptr ++;
82+
}
83+
84+
if (*name_ptr == '\0')
85+
{
86+
return -ENOENT;
87+
}
88+
89+
name_scan = name_ptr;
90+
while (*name_scan)
91+
{
92+
if (*name_scan == '/')
93+
{
94+
return -EINVAL;
95+
}
96+
97+
name_scan ++;
98+
}
99+
100+
name_len = rt_strlen(name_ptr);
101+
if (name_len >= name_size)
102+
{
103+
return -ENAMETOOLONG;
104+
}
105+
106+
rt_memcpy(name, name_ptr, name_len);
107+
name[name_len] = '\0';
108+
109+
return RT_EOK;
110+
}
111+
62112
struct ramfs_dirent *dfs_ramfs_lookup(struct dfs_ramfs *ramfs,
63113
const char *path,
64114
rt_size_t *size)
@@ -182,6 +232,7 @@ int dfs_ramfs_open(struct dfs_file *file)
182232
struct dfs_ramfs *ramfs;
183233
struct ramfs_dirent *dirent;
184234
struct dfs_filesystem *fs;
235+
int ret;
185236

186237
RT_ASSERT(file->vnode->ref_count > 0);
187238
if (file->vnode->ref_count > 1)
@@ -245,11 +296,12 @@ int dfs_ramfs_open(struct dfs_file *file)
245296

246297
/* remove '/' separator */
247298
name_ptr = file->vnode->path;
248-
while (*name_ptr == '/' && *name_ptr)
299+
ret = _ramfs_set_name(dirent->name, sizeof(dirent->name), name_ptr);
300+
if (ret != RT_EOK)
249301
{
250-
name_ptr++;
302+
rt_memheap_free(dirent);
303+
return ret;
251304
}
252-
strncpy(dirent->name, name_ptr, RAMFS_NAME_MAX);
253305

254306
rt_list_init(&(dirent->list));
255307
dirent->data = NULL;
@@ -390,6 +442,7 @@ int dfs_ramfs_rename(struct dfs_filesystem *fs,
390442
struct ramfs_dirent *dirent;
391443
struct dfs_ramfs *ramfs;
392444
rt_size_t size;
445+
int ret;
393446

394447
ramfs = (struct dfs_ramfs *)fs->data;
395448
RT_ASSERT(ramfs != NULL);
@@ -402,7 +455,11 @@ int dfs_ramfs_rename(struct dfs_filesystem *fs,
402455
if (dirent == NULL)
403456
return -ENOENT;
404457

405-
strncpy(dirent->name, newpath, RAMFS_NAME_MAX);
458+
ret = _ramfs_set_name(dirent->name, sizeof(dirent->name), newpath);
459+
if (ret != RT_EOK)
460+
{
461+
return ret;
462+
}
406463

407464
return RT_EOK;
408465
}
@@ -476,4 +533,3 @@ struct dfs_ramfs *dfs_ramfs_create(rt_uint8_t *pool, rt_size_t size)
476533

477534
return ramfs;
478535
}
479-

0 commit comments

Comments
 (0)