From e7fac7a15ed0eda6516e7fa0917c06e005341b00 Mon Sep 17 00:00:00 2001 From: Thomas Munro Date: Wed, 7 Sep 2022 07:35:11 +1200 Subject: [PATCH v3 1/2] Make mkdtemp() more secure on Windows. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Our POSIX mkdtemp() implementation in src/port/mkdtemp.c code would create directories with default permissions on Windows. Fix, using the native Windows API instead of mkdir(). This function is currently used by pg_regress's make_temp_sockdir(). Reviewed-by: Juan José Santamaría Flecha Discussion: https://postgr.es/m/CA%2BhUKGK30uLx9dpgkYwomgH0WVLUHytkChDgf3iUM2zp0pf_nA%40mail.gmail.com --- src/port/mkdtemp.c | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/port/mkdtemp.c b/src/port/mkdtemp.c index 4578e8384c..9d3c4fce71 100644 --- a/src/port/mkdtemp.c +++ b/src/port/mkdtemp.c @@ -187,8 +187,35 @@ GETTEMP(char *path, int *doopen, int domkdir) } else if (domkdir) { +#ifdef WIN32 + /* + * Plain mkdir(path, 0700) would ignore the mode argument, so + * we'll use the native Windows API to create the directory. By + * setting lpSecurityDescriptor to NULL, we get "the default + * security descriptor associated with the access token of the + * calling process. [...] By default, the default DACL in the + * access token of a process allows access only to the user + * represented by the access token." + * + * Note that a NULL lpSecurityDescriptor is not the same as a NULL + * lpSecurityAttributes argument. The latter would mean that the + * ACL is inherited from the parent directory, which would + * probably work out the same if it's the TMP directory, but by a + * different route. + */ + SECURITY_ATTRIBUTES sa = { + .nLength = sizeof(SECURITY_ATTRIBUTES), + .lpSecurityDescriptor = NULL, + .bInheritHandle = false + }; + + if (CreateDirectory(path, &sa)) + return 1; + _dosmaperr(GetLastError()); +#else if (mkdir(path, 0700) >= 0) return 1; +#endif if (errno != EEXIST) return 0; } -- 2.39.2