From c94b65f677875140b019bec1f7dc07bd2e14d45b Mon Sep 17 00:00:00 2001
From: Noah Misch <noah@leadboat.com>
Date: Sun, 20 Sep 2015 20:42:27 -0400
Subject: [PATCH] Restrict file mode creation mask during tmpfile().

Per Coverity.  Back-patch to 9.0 (all supported versions).

Michael Paquier, reviewed (in earlier versions) by Heikki Linnakangas.
---
 src/bin/pg_dump/pg_backup_tar.c | 12 ++++++++++++
 1 file changed, 12 insertions(+)

diff --git a/src/bin/pg_dump/pg_backup_tar.c b/src/bin/pg_dump/pg_backup_tar.c
index 650338e646e..54ca16600c5 100644
--- a/src/bin/pg_dump/pg_backup_tar.c
+++ b/src/bin/pg_dump/pg_backup_tar.c
@@ -371,8 +371,18 @@ tarOpen(ArchiveHandle *AH, const char *filename, char mode)
 	}
 	else
 	{
+		int			old_umask;
+
 		tm = pg_calloc(1, sizeof(TAR_MEMBER));
 
+		/*
+		 * POSIX does not require, but permits, tmpfile() to restrict file
+		 * permissions.  Given an OS crash after we write data, the filesystem
+		 * might retain the data but forget tmpfile()'s unlink().  If so, the
+		 * file mode protects confidentiality of the data written.
+		 */
+		old_umask = umask(S_IRWXG | S_IRWXO);
+
 #ifndef WIN32
 		tm->tmpFH = tmpfile();
 #else
@@ -407,6 +417,8 @@ tarOpen(ArchiveHandle *AH, const char *filename, char mode)
 		if (tm->tmpFH == NULL)
 			exit_horribly(modulename, "could not generate temporary file name: %s\n", strerror(errno));
 
+		umask(old_umask);
+
 #ifdef HAVE_LIBZ
 
 		if (AH->compression != 0)
-- 
GitLab