aboutsummaryrefslogtreecommitdiff
path: root/libbb/validate_filename.c
diff options
context:
space:
mode:
Diffstat (limited to 'libbb/validate_filename.c')
-rw-r--r--libbb/validate_filename.c33
1 files changed, 33 insertions, 0 deletions
diff --git a/libbb/validate_filename.c b/libbb/validate_filename.c
new file mode 100644
index 0000000..2b9b80a
--- /dev/null
+++ b/libbb/validate_filename.c
@@ -0,0 +1,33 @@
+#include "libbb.h"
+
+int validate_filename(const char *path, const char *prefix)
+{
+ size_t path_len, prefix_len;
+
+ /* Check for the following properties:
+ * 1) path start with prefix
+ * 2) the next character after prefix is a '/'
+ * 3) path does not contain '/../'
+ * 4) path does not end in '/..'
+ * return 0 if any of the properties does not hold
+ * return 1 if all properties hold
+ */
+ path_len= strlen(path);
+ prefix_len= strlen(prefix);
+ if (path_len < prefix_len)
+ return 0;
+
+ if (memcmp(path, prefix, prefix_len) != 0)
+ return 0; /* property 1 */
+
+ if (path[prefix_len] != '/')
+ return 0; /* property 2 */
+
+ if (strstr(path, "/../") != NULL)
+ return 0; /* property 3 */
+
+ if (path_len >= 3 && strcmp(&path[path_len-3], "/..") == 0)
+ return 0; /* property 4 */
+
+ return 1;
+}