From 9cba9c8585bc5ebf19bafece118fb2362090547c Mon Sep 17 00:00:00 2001 From: Miroslav Lichvar Date: Thu, 19 Jan 2023 16:09:40 +0100 Subject: [PATCH] keys+nts: warn if loading world-readable/writable key Log a warning message if the file specified by the keyfile or ntsserverkey directive is world-readable or writable, which is likely an insecure misconfiguration. There is no check of directories containing the file. --- keys.c | 3 +++ nts_ke_session.c | 2 ++ util.c | 23 +++++++++++++++++++++++ util.h | 4 ++++ 4 files changed, 32 insertions(+) diff --git a/keys.c b/keys.c index 11f8b76..9225e6c 100644 --- a/keys.c +++ b/keys.c @@ -182,6 +182,9 @@ KEY_Reload(void) if (!key_file) return; + if (!UTI_CheckFilePermissions(key_file, 0771)) + ; + in = UTI_OpenFile(NULL, key_file, NULL, 'r', 0); if (!in) { LOG(LOGS_WARN, "Could not open keyfile %s", key_file); diff --git a/nts_ke_session.c b/nts_ke_session.c index dfcd18a..2ae1e91 100644 --- a/nts_ke_session.c +++ b/nts_ke_session.c @@ -667,6 +667,8 @@ create_credentials(const char **certs, const char **keys, int n_certs_keys, assert(0); for (i = 0; i < n_certs_keys; i++) { + if (!UTI_CheckFilePermissions(keys[i], 0771)) + ; r = gnutls_certificate_set_x509_key_file(credentials, certs[i], keys[i], GNUTLS_X509_FMT_PEM); if (r < 0) diff --git a/util.c b/util.c index 064292c..4b9d30e 100644 --- a/util.c +++ b/util.c @@ -1248,6 +1248,29 @@ UTI_CheckDirPermissions(const char *path, mode_t perm, uid_t uid, gid_t gid) /* ================================================== */ +int +UTI_CheckFilePermissions(const char *path, mode_t perm) +{ + mode_t extra_perm; + struct stat buf; + + if (stat(path, &buf) < 0 || !S_ISREG(buf.st_mode)) { + /* Not considered an error */ + return 1; + } + + extra_perm = (buf.st_mode & 0777) & ~perm; + if (extra_perm != 0) { + LOG(LOGS_WARN, "%s permissions on %s", extra_perm & 0006 ? + (extra_perm & 0004 ? "World-readable" : "World-writable") : "Wrong", path); + return 0; + } + + return 1; +} + +/* ================================================== */ + static int join_path(const char *basedir, const char *name, const char *suffix, char *buffer, size_t length, LOG_Severity severity) diff --git a/util.h b/util.h index 4655e53..6844798 100644 --- a/util.h +++ b/util.h @@ -196,6 +196,10 @@ extern int UTI_CreateDirAndParents(const char *path, mode_t mode, uid_t uid, gid permissions and its uid/gid must match the specified values. */ extern int UTI_CheckDirPermissions(const char *path, mode_t perm, uid_t uid, gid_t gid); +/* Check and log a warning message if a file has more permissions than + specified. It does not return error if it is not an accessible file. */ +extern int UTI_CheckFilePermissions(const char *path, mode_t perm); + /* Open a file. The full path of the file is constructed from the basedir (may be NULL), '/' (if basedir is not NULL), name, and suffix (may be NULL). Created files have specified permissions (umasked). Returns NULL on error.