Skip to content

Commit

Permalink
When opening files for write, ensure files can only be read by root
Browse files Browse the repository at this point in the history
Issue acassen#1048 referred to CVE-2018-19046 regarding files used for
debugging purposes could potentially be read by non root users.

This commit ensures that such log files cannot be opened by non root
users.

Signed-off-by: Quentin Armitage <quentin@armitage.org.uk>
  • Loading branch information
pqarmitage committed Nov 11, 2018
1 parent cf605b9 commit ac8e2ef
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 8 deletions.
2 changes: 1 addition & 1 deletion lib/memory.c
Expand Up @@ -622,7 +622,7 @@ mem_log_init(const char* prog_name, const char *banner)
}

snprintf(log_name, log_name_len, "/tmp/%s_mem.%d.log", prog_name, getpid());
log_op = fopen_safe(log_name, "a");
log_op = fopen_safe(log_name, "w");
if (log_op == NULL) {
log_message(LOG_INFO, "Unable to open %s for appending", log_name);
log_op = stderr;
Expand Down
35 changes: 28 additions & 7 deletions lib/utils.c
Expand Up @@ -30,6 +30,7 @@
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/utsname.h>
#include <sys/stat.h>
#include <stdint.h>
#include <errno.h>
#ifdef _WITH_PERF_
Expand Down Expand Up @@ -58,9 +59,7 @@
#include "signals.h"
#include "bitops.h"
#include "parser.h"
#if !defined _HAVE_LIBIPTC_ || defined _LIBIPTC_DYNAMIC_ || defined _WITH_STACKTRACE_ || defined _WITH_PERF_
#include "logger.h"
#endif
#if !defined _HAVE_LIBIPTC_ || defined _LIBIPTC_DYNAMIC_
#include "process.h"
#endif
Expand Down Expand Up @@ -795,16 +794,17 @@ FILE *fopen_safe(const char *path, const char *mode)
int fd;
FILE *file;
int flags = O_NOFOLLOW | O_CREAT;
int sav_errno;

if (mode[0] == 'r')
return fopen(path, mode);

if (mode[0] != 'a' && mode[0] != 'w')
return NULL;

if (mode[1] &&
(mode[1] != '+' || mode[2]))
if ((mode[0] != 'a' && mode[0] != 'w') ||
(mode[1] &&
(mode[1] != '+' || mode[2]))) {
errno = EINVAL;
return NULL;
}

if (mode[0] == 'w')
flags |= O_TRUNC;
Expand All @@ -820,9 +820,30 @@ FILE *fopen_safe(const char *path, const char *mode)
if (fd == -1)
return NULL;

/* Change file ownership to root */
if (fchown(fd, 0, 0)) {
sav_errno = errno;
log_message(LOG_INFO, "Unable to change file ownership of %s- errno %d (%m)", path, errno);
close(fd);
errno = sav_errno;
return NULL;
}

/* Set file mode to rw------- */
if (fchmod(fd, S_IRUSR | S_IWUSR)) {
sav_errno = errno;
log_message(LOG_INFO, "Unable to change file permission of %s - errno %d (%m)", path, errno);
close(fd);
errno = sav_errno;
return NULL;
}

file = fdopen (fd, "w");
if (!file) {
sav_errno = errno;
log_message(LOG_INFO, "fdopen(\"%s\") failed - errno %d (%m)", path, errno);
close(fd);
errno = sav_errno;
return NULL;
}

Expand Down

0 comments on commit ac8e2ef

Please sign in to comment.