apply suggestions from code review, and the examples to the test

This commit is contained in:
erik-krogh
2024-05-08 19:34:50 +02:00
parent 3989717878
commit a51d24cbab
5 changed files with 37 additions and 21 deletions

View File

@@ -2,11 +2,9 @@ int main(int argc, char** argv) {
char *userAndFile = argv[2];
{
char fileBuffer[FILENAME_MAX] = "/home/";
char *fileName = fileBuffer;
size_t len = strlen(fileName);
strncat(fileName+len, userAndFile, FILENAME_MAX-len-1);
char fileBuffer[PATH_MAX];
snprintf(fileBuffer, sizeof(fileBuffer), "/home/%s", userAndFile);
// BAD: a string from the user is used in a filename
fopen(fileName, "wb+");
fopen(fileBuffer, "wb+");
}
}

View File

@@ -3,7 +3,7 @@
int main(int argc, char** argv) {
char *userAndFile = argv[2];
char baseDir[PATH_MAX] = "/home/user/public/";
const char *baseDir = "/home/user/public/";
char fullPath[PATH_MAX];
// Attempt to concatenate the base directory and the user-supplied path

View File

@@ -2,13 +2,15 @@
#include <string.h>
int main(int argc, char** argv) {
char *userAndFile = argv[2];
char *fileName = argv[2];
// Check for invalid sequences in the user input
if (strstr(userAndFile, "..") || strchr(userAndFile, '/') || strchr(userAndFile, '\\')) {
if (strstr(fileName , "..") || strchr(fileName , '/') || strchr(fileName , '\\')) {
printf("Invalid filename.\n");
return 1;
}
// use `userAndFile` as a safe filename
char fileBuffer[PATH_MAX];
snprintf(fileBuffer, sizeof(fileBuffer), "/home/user/files/%s", fileName);
// GOOD: We know that the filename is safe and stays within the public folder
FILE *file = fopen(fileBuffer, "wb+");
}