pg.ddx.io  pgsql-bugs@postgresql.org mailing list archive  
help / color / mirror / Atom feed
pg_upgrade failure on Windows Server
35+ messages / 6 participants
[nested] [flat]

* pg_upgrade failure on Windows Server
@ 2015-01-05 00:34  Asif Naeem <anaeem.it@gmail.com>
  0 siblings, 1 reply; 35+ messages in thread

From: Asif Naeem @ 2015-01-05 00:34 UTC (permalink / raw)
  To: pgsql-bugs

Hi,

It is been observed that pg_upgrade fail to upgrade on Windows Server
machine if being run as Administrator user (other local users works fine),
It fail with the following error message i.e.

> ""c:\pg93\bin/pg_ctl" -w -l "pg_upgrade_server.log" -D "c:\pgdata93" -o
> "-p 3333 -b -c autovacuum_multixact_freeze_max_age=2000000000  -c
> synchronous_commit=off -c fsync=off -c full_page_writes=off" start >>
> "pg_upgrade_server_start.log" 2>&1"
> *failure*
> There were problems executing """c:\pg93\bin/pg_ctl" -w -l
> "pg_upgrade_server.log" -D "c:\pgdata93" -o "-p 3333 -b -c
> autovacuum_multixact_freeze_max_age=2000000000  -c synchronous_commit=off
> -c fsync=off -c full_page_writes=off" start >>
> "pg_upgrade_server_start.log" 2>&1""
> Consult the last few lines of "pg_upgrade_server_start.log" or
> "pg_upgrade_server.log" for
> the probable cause of the failure.
> connection to database failed: could not connect to server: Connection
> refused (0x0000274D/10061)
>         Is the server running on host "localhost" (127.0.0.1) and accepting
>         TCP/IP connections on port 3333?
>
> could not connect to new postmaster started with the command:
> "c:\pg93\bin/pg_ctl" -w -l "pg_upgrade_server.log" -D "c:\pgdata93" -o "-p
> 3333 -b -c autovacuum_multixact_freeze_max_age=2000000000  -c
> synchronous_commit=off -c fsync=off -c full_page_writes=off" start
> Failure, exiting


pg_upgrade_server.log

> PANIC:  could not open control file "global/pg_control": Permission denied


"global/pg_control” file in data directory owned by
"BUILTIN\Administrators” that was owned by “Administrator” user before
pg_upgrade. I have verified it on Windows Server 2003/2008 R2/2012.

Steps to reproduce the issue :

> 1. Login as Administrator on Windows Server 2012 or Windows Server 2008
> 2. On command prompt run "c:\pg92\bin\initdb -D c:\pgdata92"
> 3. On command prompt run "c:\pg93\bin\initdb -D c:\pgdata93"
> 4. On command prompt run  "c:\pg93\bin\pg_upgrade -d c:\pgdata92 -D
> c:\pgdata93 -b c:\pg92\bin -B c:\pg93\bin -p 2222 -P 3333 -v"


Issue is reproducible with PG 9.2, 9.3 and 9.4. It is caused by
pg_resetxlog utility (It is internally used by pg_upgrade) that fail to
keep correct file permissions/ownership (as required by dbserver process)
while rewriting "global/pg_control” in data directory. pg_resetxlog utility
don’t sandbox and make changes in data directory, when it is being run as
Administrator ; it create files that are owned by "BUILTIN\Administrators”
group. pg_ctl fails because it is using CreateRestrictedProcess() to
sandbox and give up administrator privileges that make it fail to open
"global/pg_control” file (that is now owned by "BUILTIN\Administrators”
group) in write mode i.e.

2014-12-19 03:19:34 PST PANIC: 42501: could not open control file
> "global/pg_control": Permission denied
> 2014-12-19 03:19:34 PST LOCATION: ReadControlFile,
> src\backend\access\transam\xlog.c:4458


I think Domain users that are members of Administrators group suffer from
same problem. On Windows Server 2003, changing Group Policy “System
objects: Default owner for objects created by members of the Administrators
group” to “Object Creator” fixes the problem. Microsoft obsolete this Group
Policy in later version of Windows Server. I have tried a workaround (
http://support.microsoft.com/kb/947721) on Windows Server 2008 R2 but it
seems did not worked for me. As it is default behavior for Windows Server,
I would suggest to use CreateRestrictedProcess function (sandbox or
restricted tokens approach) in pg_resetxlog utility or explicitly change
ownership to current user instead of "BUILTIN\Administrators” group if
required (If you agree with the approach I can submit patch for this).
Please do let me know if I missed something or more information is
required. Thanks.

Regards,
Muhammad Asif Naeem

^ permalink  raw  reply  [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-01-20 17:41  Asif Naeem <anaeem.it@gmail.com>
  parent: Asif Naeem <anaeem.it@gmail.com>
  0 siblings, 1 reply; 35+ messages in thread

From: Asif Naeem @ 2015-01-20 17:41 UTC (permalink / raw)
  To: pgsql-bugs

Hi,

When pg_upgrade is being run by Administrator user to upgrade database from
Windows Server (2003/2008/2012), pg_upgrade fail with permission denied
error. When an application (run by Administrator) create files, the default
ownership for the newly created file/folder goes to administrators group
rather than Administrator user.

https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/634.mspx?mfr=true

> System objects: Default owner for objects created by members of the
> administrators group
> Description
> Determines whether the Administrators group or an object creator is the
> default owner of any system objects that are created.
> Default: Administrators group (on servers).


Above setting is available in Windows Server 2003, If I change this policy
setting from “Administrators group" to "object creator", pg_upgrade work
without issue. Unfortunately it got obsolete in later version of Windows
Server. On Windows Server 2008, there seems workaround available i.e.
http://support.microsoft.com/kb/947721 but it did not worked for me.

PFA patch. To run pg_upgrade (and its child processes) without
administrative privileges (when available), I have copied restricted token
logic from src/bin/initdb/initdb.c, that enables pg_upgrade to rerun itself
with removed Administrators group privileges, this way it create files with
the ownership of user running pg_upgrade. With the patch applied,
pg_upgrade (or its child process) don’t create files with administrators
group owner and works fine without issue.

As pg_resetxlog change file in data directory, it do suffer from same
permission issue, it also require similar changes. PFA for pg_resetxlog
fix. Please do let me know if I missed something or more information is
required. Thanks.

Regards,
Muhammad Asif Naeem


On Mon, Jan 5, 2015 at 5:34 AM, Asif Naeem <anaeem.it@gmail.com> wrote:

> Hi,
>
> It is been observed that pg_upgrade fail to upgrade on Windows Server
> machine if being run as Administrator user (other local users works fine),
> It fail with the following error message i.e.
>
>> ""c:\pg93\bin/pg_ctl" -w -l "pg_upgrade_server.log" -D "c:\pgdata93" -o
>> "-p 3333 -b -c autovacuum_multixact_freeze_max_age=2000000000  -c
>> synchronous_commit=off -c fsync=off -c full_page_writes=off" start >>
>> "pg_upgrade_server_start.log" 2>&1"
>> *failure*
>> There were problems executing """c:\pg93\bin/pg_ctl" -w -l
>> "pg_upgrade_server.log" -D "c:\pgdata93" -o "-p 3333 -b -c
>> autovacuum_multixact_freeze_max_age=2000000000  -c synchronous_commit=off
>> -c fsync=off -c full_page_writes=off" start >>
>> "pg_upgrade_server_start.log" 2>&1""
>> Consult the last few lines of "pg_upgrade_server_start.log" or
>> "pg_upgrade_server.log" for
>> the probable cause of the failure.
>> connection to database failed: could not connect to server: Connection
>> refused (0x0000274D/10061)
>>         Is the server running on host "localhost" (127.0.0.1) and
>> accepting
>>         TCP/IP connections on port 3333?
>>
>> could not connect to new postmaster started with the command:
>> "c:\pg93\bin/pg_ctl" -w -l "pg_upgrade_server.log" -D "c:\pgdata93" -o
>> "-p 3333 -b -c autovacuum_multixact_freeze_max_age=2000000000  -c
>> synchronous_commit=off -c fsync=off -c full_page_writes=off" start
>> Failure, exiting
>
>
> pg_upgrade_server.log
>
>> PANIC:  could not open control file "global/pg_control": Permission denied
>
>
> "global/pg_control” file in data directory owned by
> "BUILTIN\Administrators” that was owned by “Administrator” user before
> pg_upgrade. I have verified it on Windows Server 2003/2008 R2/2012.
>
> Steps to reproduce the issue :
>
>> 1. Login as Administrator on Windows Server 2012 or Windows Server 2008
>> 2. On command prompt run "c:\pg92\bin\initdb -D c:\pgdata92"
>> 3. On command prompt run "c:\pg93\bin\initdb -D c:\pgdata93"
>> 4. On command prompt run  "c:\pg93\bin\pg_upgrade -d c:\pgdata92 -D
>> c:\pgdata93 -b c:\pg92\bin -B c:\pg93\bin -p 2222 -P 3333 -v"
>
>
> Issue is reproducible with PG 9.2, 9.3 and 9.4. It is caused by
> pg_resetxlog utility (It is internally used by pg_upgrade) that fail to
> keep correct file permissions/ownership (as required by dbserver process)
> while rewriting "global/pg_control” in data directory. pg_resetxlog utility
> don’t sandbox and make changes in data directory, when it is being run as
> Administrator ; it create files that are owned by "BUILTIN\Administrators”
> group. pg_ctl fails because it is using CreateRestrictedProcess() to
> sandbox and give up administrator privileges that make it fail to open
> "global/pg_control” file (that is now owned by "BUILTIN\Administrators”
> group) in write mode i.e.
>
> 2014-12-19 03:19:34 PST PANIC: 42501: could not open control file
>> "global/pg_control": Permission denied
>> 2014-12-19 03:19:34 PST LOCATION: ReadControlFile,
>> src\backend\access\transam\xlog.c:4458
>
>
> I think Domain users that are members of Administrators group suffer from
> same problem. On Windows Server 2003, changing Group Policy “System
> objects: Default owner for objects created by members of the Administrators
> group” to “Object Creator” fixes the problem. Microsoft obsolete this Group
> Policy in later version of Windows Server. I have tried a workaround (
> http://support.microsoft.com/kb/947721) on Windows Server 2008 R2 but it
> seems did not worked for me. As it is default behavior for Windows Server,
> I would suggest to use CreateRestrictedProcess function (sandbox or
> restricted tokens approach) in pg_resetxlog utility or explicitly change
> ownership to current user instead of "BUILTIN\Administrators” group if
> required (If you agree with the approach I can submit patch for this).
> Please do let me know if I missed something or more information is
> required. Thanks.
>
> Regards,
> Muhammad Asif Naeem
>

-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs

Attachments: download all (2 files, .tar.gz)

pg_resetxlog_PG94.v1.patch (application/octet-stream, 5.1K) download diff --git a/src/bin/pg_resetxlog/pg_resetxlog.c b/src/bin/pg_resetxlog/pg_resetxlog.c index 302d005..55ffcd7 100644 --- a/src/bin/pg_resetxlog/pg_resetxlog.c +++ b/src/bin/pg_resetxlog/pg_resetxlog.c @@ -68,6 +68,10 @@ static MultiXactOffset set_mxoff = (MultiXactOffset) -1; static uint32 minXlogTli = 0; static XLogSegNo minXlogSegNo = 0; +#ifdef WIN32 +static char *restrict_env; +#endif + static bool ReadControlFile(void); static void GuessControlValues(void); static void PrintControlValues(bool guessed); @@ -78,6 +82,11 @@ static void KillExistingXLOG(void); static void KillExistingArchiveStatus(void); static void WriteEmptyXLOG(void); static void usage(void); +static void get_restricted_token(void); + +#ifdef WIN32 +static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo); +#endif int @@ -257,6 +266,7 @@ main(int argc, char *argv[]) } #endif + get_restricted_token(); DataDir = argv[optind]; if (chdir(DataDir) < 0) @@ -1072,6 +1082,162 @@ WriteEmptyXLOG(void) close(fd); } +#ifdef WIN32 +typedef BOOL(WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); + +/* Windows API define missing from some versions of MingW headers */ +#ifndef DISABLE_MAX_PRIVILEGE +#define DISABLE_MAX_PRIVILEGE 0x1 +#endif + +/* +* Create a restricted token and execute the specified process with it. +* +* Returns 0 on failure, non-zero on success, same as CreateProcess(). +* +* On NT4, or any other system not containing the required functions, will +* NOT execute anything. +*/ +static int +CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo) +{ + BOOL b; + STARTUPINFO si; + HANDLE origToken; + HANDLE restrictedToken; + SID_IDENTIFIER_AUTHORITY NtAuthority = { SECURITY_NT_AUTHORITY }; + SID_AND_ATTRIBUTES dropSids[2]; + __CreateRestrictedToken _CreateRestrictedToken = NULL; + HANDLE Advapi32Handle; + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + + Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); + if (Advapi32Handle != NULL) + { + _CreateRestrictedToken = (__CreateRestrictedToken)GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); + } + + if (_CreateRestrictedToken == NULL) + { + fprintf(stderr, _("%s: WARNING: cannot create restricted tokens on this platform\n"), progname); + if (Advapi32Handle != NULL) + FreeLibrary(Advapi32Handle); + return 0; + } + + /* Open the current token to use as a base for the restricted one */ + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) + { + fprintf(stderr, _("%s: could not open process token: error code %lu\n"), progname, GetLastError()); + return 0; + } + + /* Allocate list of SIDs to remove */ + ZeroMemory(&dropSids, sizeof(dropSids)); + if (!AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, + 0, &dropSids[0].Sid) || + !AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, + 0, &dropSids[1].Sid)) + { + fprintf(stderr, _("%s: could not to allocate SIDs: error code %lu\n"), progname, GetLastError()); + return 0; + } + + b = _CreateRestrictedToken(origToken, + DISABLE_MAX_PRIVILEGE, + sizeof(dropSids) / sizeof(dropSids[0]), + dropSids, + 0, NULL, + 0, NULL, + &restrictedToken); + + FreeSid(dropSids[1].Sid); + FreeSid(dropSids[0].Sid); + CloseHandle(origToken); + FreeLibrary(Advapi32Handle); + + if (!b) + { + fprintf(stderr, _("%s: could not create restricted token: error code %lu\n"), progname, GetLastError()); + return 0; + } + +#ifndef __CYGWIN__ + AddUserToTokenDacl(restrictedToken); +#endif + + if (!CreateProcessAsUser(restrictedToken, + NULL, + cmd, + NULL, + NULL, + TRUE, + CREATE_SUSPENDED, + NULL, + NULL, + &si, + processInfo)) + + { + fprintf(stderr, _("%s: could not start process for command \"%s\": error code %lu\n"), progname, cmd, GetLastError()); + return 0; + } + + return ResumeThread(processInfo->hThread); +} +#endif + +void +get_restricted_token(void) +{ +#ifdef WIN32 + + /* + * Before we execute another program, make sure that we are running with a + * restricted token. If not, re-execute ourselves with one. + */ + + if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL + || strcmp(restrict_env, "1") != 0) + { + PROCESS_INFORMATION pi; + char *cmdline; + + ZeroMemory(&pi, sizeof(pi)); + + cmdline = pg_strdup(GetCommandLine()); + + putenv("PG_RESTRICT_EXEC=1"); + + if (!CreateRestrictedProcess(cmdline, &pi)) + { + fprintf(stderr, _("%s: could not re-execute with restricted token: error code %lu\n"), progname, GetLastError()); + } + else + { + /* + * Successfully re-execed. Now wait for child process to capture + * exitcode. + */ + DWORD x; + + CloseHandle(pi.hThread); + WaitForSingleObject(pi.hProcess, INFINITE); + + if (!GetExitCodeProcess(pi.hProcess, &x)) + { + fprintf(stderr, _("%s: could not get exit code from subprocess: error code %lu\n"), progname, GetLastError()); + exit(1); + } + exit(x); + } + } +#endif +} static void usage(void)
pg_upgrade_PG94.v1.patch (application/octet-stream, 5.0K) download diff --git a/contrib/pg_upgrade/pg_upgrade.c b/contrib/pg_upgrade/pg_upgrade.c index 7a18e4e..169e7eb 100644 --- a/contrib/pg_upgrade/pg_upgrade.c +++ b/contrib/pg_upgrade/pg_upgrade.c @@ -49,6 +49,11 @@ static void copy_clog_xlog_xid(void); static void set_frozenxids(bool minmxid_only); static void setup(char *argv0, bool *live_check); static void cleanup(void); +static void get_restricted_token(void); + +#ifdef WIN32 +static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo); +#endif ClusterInfo old_cluster, new_cluster; @@ -65,6 +70,9 @@ char *output_files[] = { NULL }; +#ifdef WIN32 +static char *restrict_env; +#endif int main(int argc, char **argv) @@ -76,6 +84,8 @@ main(int argc, char **argv) parseCommandLine(argc, argv); + get_restricted_token(); + adjust_data_dir(&old_cluster); adjust_data_dir(&new_cluster); @@ -174,6 +184,162 @@ main(int argc, char **argv) return 0; } +#ifdef WIN32 +typedef BOOL(WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); + +/* Windows API define missing from some versions of MingW headers */ +#ifndef DISABLE_MAX_PRIVILEGE +#define DISABLE_MAX_PRIVILEGE 0x1 +#endif + +/* +* Create a restricted token and execute the specified process with it. +* +* Returns 0 on failure, non-zero on success, same as CreateProcess(). +* +* On NT4, or any other system not containing the required functions, will +* NOT execute anything. +*/ +static int +CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo) +{ + BOOL b; + STARTUPINFO si; + HANDLE origToken; + HANDLE restrictedToken; + SID_IDENTIFIER_AUTHORITY NtAuthority = { SECURITY_NT_AUTHORITY }; + SID_AND_ATTRIBUTES dropSids[2]; + __CreateRestrictedToken _CreateRestrictedToken = NULL; + HANDLE Advapi32Handle; + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + + Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); + if (Advapi32Handle != NULL) + { + _CreateRestrictedToken = (__CreateRestrictedToken)GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); + } + + if (_CreateRestrictedToken == NULL) + { + fprintf(stderr, _("WARNING: cannot create restricted tokens on this platform\n")); + if (Advapi32Handle != NULL) + FreeLibrary(Advapi32Handle); + return 0; + } + + /* Open the current token to use as a base for the restricted one */ + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) + { + fprintf(stderr, _("could not open process token: error code %lu\n"), GetLastError()); + return 0; + } + + /* Allocate list of SIDs to remove */ + ZeroMemory(&dropSids, sizeof(dropSids)); + if (!AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, + 0, &dropSids[0].Sid) || + !AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, + 0, &dropSids[1].Sid)) + { + fprintf(stderr, _("could not to allocate SIDs: error code %lu\n"), GetLastError()); + return 0; + } + + b = _CreateRestrictedToken(origToken, + DISABLE_MAX_PRIVILEGE, + sizeof(dropSids) / sizeof(dropSids[0]), + dropSids, + 0, NULL, + 0, NULL, + &restrictedToken); + + FreeSid(dropSids[1].Sid); + FreeSid(dropSids[0].Sid); + CloseHandle(origToken); + FreeLibrary(Advapi32Handle); + + if (!b) + { + fprintf(stderr, _("could not create restricted token: error code %lu\n"), GetLastError()); + return 0; + } + +#ifndef __CYGWIN__ + AddUserToTokenDacl(restrictedToken); +#endif + + if (!CreateProcessAsUser(restrictedToken, + NULL, + cmd, + NULL, + NULL, + TRUE, + CREATE_SUSPENDED, + NULL, + NULL, + &si, + processInfo)) + + { + fprintf(stderr, _("could not start process for command \"%s\": error code %lu\n"), cmd, GetLastError()); + return 0; + } + + return ResumeThread(processInfo->hThread); +} +#endif + +void +get_restricted_token(void) +{ +#ifdef WIN32 + + /* + * Before we execute another program, make sure that we are running with a + * restricted token. If not, re-execute ourselves with one. + */ + + if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL + || strcmp(restrict_env, "1") != 0) + { + PROCESS_INFORMATION pi; + char *cmdline; + + ZeroMemory(&pi, sizeof(pi)); + + cmdline = pg_strdup(GetCommandLine()); + + putenv("PG_RESTRICT_EXEC=1"); + + if (!CreateRestrictedProcess(cmdline, &pi)) + { + fprintf(stderr, _("could not re-execute with restricted token: error code %lu\n"), GetLastError()); + } + else + { + /* + * Successfully re-execed. Now wait for child process to capture + * exitcode. + */ + DWORD x; + + CloseHandle(pi.hThread); + WaitForSingleObject(pi.hProcess, INFINITE); + + if (!GetExitCodeProcess(pi.hProcess, &x)) + { + fprintf(stderr, _("could not get exit code from subprocess: error code %lu\n"), GetLastError()); + exit(1); + } + exit(x); + } + } +#endif +} static void setup(char *argv0, bool *live_check)
^ permalink raw reply [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-01-21 18:14  Bruce Momjian <bruce@momjian.us>
  parent: Asif Naeem <anaeem.it@gmail.com>
  0 siblings, 1 reply; 35+ messages in thread

From: Bruce Momjian @ 2015-01-21 18:14 UTC (permalink / raw)
  To: Asif Naeem <anaeem.it@gmail.com>; +Cc: pgsql-bugs

On Tue, Jan 20, 2015 at 10:41:41PM +0500, Asif Naeem wrote:
> Above setting is available in Windows Server 2003, If I change this policy
> setting from “Administrators group" to "object creator", pg_upgrade work
> without issue. Unfortunately it got obsolete in later version of Windows
> Server. On Windows Server 2008, there seems workaround available i.e. http://
> support.microsoft.com/kb/947721 but it did not worked for me.
> 
> PFA patch. To run pg_upgrade (and its child processes) without administrative
> privileges (when available), I have copied restricted token logic from src/bin/
> initdb/initdb.c, that enables pg_upgrade to rerun itself with removed
> Administrators group privileges, this way it create files with the ownership of
> user running pg_upgrade. With the patch applied, pg_upgrade (or its child
> process) don’t create files with administrators group owner and works fine
> without issue.
> 
> As pg_resetxlog change file in data directory, it do suffer from same
> permission issue, it also require similar changes. PFA for pg_resetxlog fix.
> Please do let me know if I missed something or more information is required.
> Thanks.

This sounds like the exact right patch.  However, since it has a lot of
Windows-specific code, and we don't have any Windows experts, I am not
sure how this can be applied.

-- 
  Bruce Momjian  <bruce@momjian.us>        http://momjian.us
  EnterpriseDB                             http://enterprisedb.com

  + Everyone has their own god. +


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-01-21 18:31  Alvaro Herrera <alvherre@2ndquadrant.com>
  parent: Bruce Momjian <bruce@momjian.us>
  0 siblings, 1 reply; 35+ messages in thread

From: Alvaro Herrera @ 2015-01-21 18:31 UTC (permalink / raw)
  To: Bruce Momjian <bruce@momjian.us>; +Cc: Asif Naeem <anaeem.it@gmail.com>; pgsql-bugs

Bruce Momjian wrote:

> This sounds like the exact right patch.  However, since it has a lot of
> Windows-specific code, and we don't have any Windows experts, I am not
> sure how this can be applied.

Are you saying we will remove the Windows port?  That sounds awesome,
thanks!  If you need help, I will volunteer on the spot, just LMK.

-- 
Álvaro Herrera                http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-01-21 18:36  Bruce Momjian <bruce@momjian.us>
  parent: Alvaro Herrera <alvherre@2ndquadrant.com>
  0 siblings, 1 reply; 35+ messages in thread

From: Bruce Momjian @ 2015-01-21 18:36 UTC (permalink / raw)
  To: Alvaro Herrera <alvherre@2ndquadrant.com>; +Cc: Asif Naeem <anaeem.it@gmail.com>; pgsql-bugs

On Wed, Jan 21, 2015 at 03:31:42PM -0300, Alvaro Herrera wrote:
> Bruce Momjian wrote:
> 
> > This sounds like the exact right patch.  However, since it has a lot of
> > Windows-specific code, and we don't have any Windows experts, I am not
> > sure how this can be applied.
> 
> Are you saying we will remove the Windows port?  That sounds awesome,
> thanks!  If you need help, I will volunteer on the spot, just LMK.

:-)

Well, I _am_ saying that historically patches that touch the innards of
the Windows API are rarely applied as we can't evaluate or maintain the
code.  I can probably come up with an example if you want.  The
Windows-specif code we do carry is required and was developed by people
that are no longer as involved.

-- 
  Bruce Momjian  <bruce@momjian.us>        http://momjian.us
  EnterpriseDB                             http://enterprisedb.com

  + Everyone has their own god. +


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-01-22 03:31  Amit Kapila <amit.kapila16@gmail.com>
  parent: Bruce Momjian <bruce@momjian.us>
  0 siblings, 2 replies; 35+ messages in thread

From: Amit Kapila @ 2015-01-22 03:31 UTC (permalink / raw)
  To: Bruce Momjian <bruce@momjian.us>; +Cc: Alvaro Herrera <alvherre@2ndquadrant.com>; Asif Naeem <anaeem.it@gmail.com>; pgsql-bugs

On Thu, Jan 22, 2015 at 12:06 AM, Bruce Momjian <bruce@momjian.us> wrote:
>
> On Wed, Jan 21, 2015 at 03:31:42PM -0300, Alvaro Herrera wrote:
> > Bruce Momjian wrote:
> >
> > > This sounds like the exact right patch.  However, since it has a lot
of
> > > Windows-specific code, and we don't have any Windows experts, I am not
> > > sure how this can be applied.
> >
> > Are you saying we will remove the Windows port?  That sounds awesome,
> > thanks!  If you need help, I will volunteer on the spot, just LMK.
>
> :-)
>
> Well, I _am_ saying that historically patches that touch the innards of
> the Windows API are rarely applied as we can't evaluate or maintain the
> code.  I can probably come up with an example if you want.

I think it is true to a great extent that Windows patches receive less
attention, however in many cases the patch finally do get committed.
I think the right thing for this patch is that Author should submit it to
next CF, so that it could be tracked and reviewed, once it is reviewed
by some one having Windows access, it should be taken care by
Committer.


> The
> Windows-specif code we do carry is required and was developed by people
> that are no longer as involved.
>

I have seen many a times that once committer's (those who are not generally
involved in Windows development) get reasonable confidence about patch
and the review done for the same, they commit the patch.  It happens both
for the patches where I was Author and where I was Reviewer, although I
agree that it takes more time.


With Regards,
Amit Kapila.
EnterpriseDB: http://www.enterprisedb.com

^ permalink  raw  reply  [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-01-22 04:38  Michael Paquier <michael.paquier@gmail.com>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  1 sibling, 1 reply; 35+ messages in thread

From: Michael Paquier @ 2015-01-22 04:38 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Bruce Momjian <bruce@momjian.us>; Alvaro Herrera <alvherre@2ndquadrant.com>; Asif Naeem <anaeem.it@gmail.com>; pgsql-bugs

On Thu, Jan 22, 2015 at 12:31 PM, Amit Kapila <amit.kapila16@gmail.com> wrote:
> On Thu, Jan 22, 2015 at 12:06 AM, Bruce Momjian <bruce@momjian.us> wrote:
>>
>> On Wed, Jan 21, 2015 at 03:31:42PM -0300, Alvaro Herrera wrote:
>> > Bruce Momjian wrote:
>> >
>> > > This sounds like the exact right patch.  However, since it has a lot
>> > > of
>> > > Windows-specific code, and we don't have any Windows experts, I am not
>> > > sure how this can be applied.
>> >
>> > Are you saying we will remove the Windows port?  That sounds awesome,
>> > thanks!  If you need help, I will volunteer on the spot, just LMK.
>>
>> :-)
>>
>> Well, I _am_ saying that historically patches that touch the innards of
>> the Windows API are rarely applied as we can't evaluate or maintain the
>> code.  I can probably come up with an example if you want.
>
> I think it is true to a great extent that Windows patches receive less
> attention, however in many cases the patch finally do get committed.
> I think the right thing for this patch is that Author should submit it to
> next CF, so that it could be tracked and reviewed, once it is reviewed
> by some one having Windows access, it should be taken care by
> Committer.
Adding it to the next CF would be a good first step. I got some access
to some 2k3 and 2k8 boxes, so I think that I could give it a shot.
-- 
Michael


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-01-22 07:07  Asif Naeem <anaeem.it@gmail.com>
  parent: Michael Paquier <michael.paquier@gmail.com>
  0 siblings, 1 reply; 35+ messages in thread

From: Asif Naeem @ 2015-01-22 07:07 UTC (permalink / raw)
  To: Michael Paquier <michael.paquier@gmail.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Bruce Momjian <bruce@momjian.us>; Alvaro Herrera <alvherre@2ndquadrant.com>; pgsql-bugs

Thank you. I have added it to next commitfest
<https://commitfest.postgresql.org/4/114/;.

On Thu, Jan 22, 2015 at 9:38 AM, Michael Paquier <michael.paquier@gmail.com>
wrote:

> On Thu, Jan 22, 2015 at 12:31 PM, Amit Kapila <amit.kapila16@gmail.com>
> wrote:
> > On Thu, Jan 22, 2015 at 12:06 AM, Bruce Momjian <bruce@momjian.us>
> wrote:
> >>
> >> On Wed, Jan 21, 2015 at 03:31:42PM -0300, Alvaro Herrera wrote:
> >> > Bruce Momjian wrote:
> >> >
> >> > > This sounds like the exact right patch.  However, since it has a lot
> >> > > of
> >> > > Windows-specific code, and we don't have any Windows experts, I am
> not
> >> > > sure how this can be applied.
> >> >
> >> > Are you saying we will remove the Windows port?  That sounds awesome,
> >> > thanks!  If you need help, I will volunteer on the spot, just LMK.
> >>
> >> :-)
> >>
> >> Well, I _am_ saying that historically patches that touch the innards of
> >> the Windows API are rarely applied as we can't evaluate or maintain the
> >> code.  I can probably come up with an example if you want.
> >
> > I think it is true to a great extent that Windows patches receive less
> > attention, however in many cases the patch finally do get committed.
> > I think the right thing for this patch is that Author should submit it to
> > next CF, so that it could be tracked and reviewed, once it is reviewed
> > by some one having Windows access, it should be taken care by
> > Committer.
> Adding it to the next CF would be a good first step. I got some access
> to some 2k3 and 2k8 boxes, so I think that I could give it a shot.
> --
> Michael
>

^ permalink  raw  reply  [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-01-22 16:24  Bruce Momjian <bruce@momjian.us>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  1 sibling, 1 reply; 35+ messages in thread

From: Bruce Momjian @ 2015-01-22 16:24 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Alvaro Herrera <alvherre@2ndquadrant.com>; Asif Naeem <anaeem.it@gmail.com>; pgsql-bugs

On Thu, Jan 22, 2015 at 09:01:39AM +0530, Amit Kapila wrote:
> > The
> > Windows-specif code we do carry is required and was developed by people
> > that are no longer as involved.
> >
> 
> I have seen many a times that once committer's (those who are not generally
> involved in Windows development) get reasonable confidence about patch
> and the review done for the same, they commit the patch.  It happens both
> for the patches where I was Author and where I was Reviewer, although I
> agree that it takes more time.

Here is Windows change to properly detach the server process that never
got implemented as no Windows expert developed or tested a patch, but
test code was posted:

	http://www.postgresql.org/message-id/flat/53759381.4000205@cubiclesoft.com#53759381.4000205@cubicles...

Here is another unapplied Windows patch for preventing Control-C from
closing the server:

	http://www.postgresql.org/message-id/flat/20140410214426.GI6917@momjian.us#20140410214426.GI6917@mom...

Again, I would love to say we handle Windows patches well, but we don't.

-- 
  Bruce Momjian  <bruce@momjian.us>        http://momjian.us
  EnterpriseDB                             http://enterprisedb.com

  + Everyone has their own god. +


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-01-22 16:26  Andres Freund <andres@2ndquadrant.com>
  parent: Bruce Momjian <bruce@momjian.us>
  0 siblings, 2 replies; 35+ messages in thread

From: Andres Freund @ 2015-01-22 16:26 UTC (permalink / raw)
  To: Bruce Momjian <bruce@momjian.us>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Alvaro Herrera <alvherre@2ndquadrant.com>; Asif Naeem <anaeem.it@gmail.com>; pgsql-bugs

On 2015-01-22 11:24:31 -0500, Bruce Momjian wrote:
> On Thu, Jan 22, 2015 at 09:01:39AM +0530, Amit Kapila wrote:
> > > The
> > > Windows-specif code we do carry is required and was developed by people
> > > that are no longer as involved.
> > >
> > 
> > I have seen many a times that once committer's (those who are not generally
> > involved in Windows development) get reasonable confidence about patch
> > and the review done for the same, they commit the patch.  It happens both
> > for the patches where I was Author and where I was Reviewer, although I
> > agree that it takes more time.
> 
> Here is Windows change to properly detach the server process that never
> got implemented as no Windows expert developed or tested a patch, but
> test code was posted:
> 
> 	http://www.postgresql.org/message-id/flat/53759381.4000205@cubiclesoft.com#53759381.4000205@cubicles...
> 
> Here is another unapplied Windows patch for preventing Control-C from
> closing the server:
> 
> 	http://www.postgresql.org/message-id/flat/20140410214426.GI6917@momjian.us#20140410214426.GI6917@mom...
> 
> Again, I would love to say we handle Windows patches well, but we don't.

I unfortunately don't the issue is that specific to windows.

Greetings,

Andres Freund

-- 
 Andres Freund	                   http://www.2ndQuadrant.com/
 PostgreSQL Development, 24x7 Support, Training & Services


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-01-22 16:32  Bruce Momjian <bruce@momjian.us>
  parent: Andres Freund <andres@2ndquadrant.com>
  1 sibling, 0 replies; 35+ messages in thread

From: Bruce Momjian @ 2015-01-22 16:32 UTC (permalink / raw)
  To: Andres Freund <andres@2ndquadrant.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Alvaro Herrera <alvherre@2ndquadrant.com>; Asif Naeem <anaeem.it@gmail.com>; pgsql-bugs

On Thu, Jan 22, 2015 at 05:26:57PM +0100, Andres Freund wrote:
> > Again, I would love to say we handle Windows patches well, but we don't.
> 
> I unfortunately don't the issue is that specific to windows.

Yes, any case where small number of people understand the problem is an
issue.

-- 
  Bruce Momjian  <bruce@momjian.us>        http://momjian.us
  EnterpriseDB                             http://enterprisedb.com

  + Everyone has their own god. +


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-03-02 04:42  Michael Paquier <michael.paquier@gmail.com>
  parent: Asif Naeem <anaeem.it@gmail.com>
  0 siblings, 1 reply; 35+ messages in thread

From: Michael Paquier @ 2015-03-02 04:42 UTC (permalink / raw)
  To: Asif Naeem <anaeem.it@gmail.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Bruce Momjian <bruce@momjian.us>; Alvaro Herrera <alvherre@2ndquadrant.com>; pgsql-bugs

On Thu, Jan 22, 2015 at 4:07 PM, Asif Naeem <anaeem.it@gmail.com> wrote:
> Thank you. I have added it to next commitfest.

Sorry for the late reply.

So I have been looking at both patches, and I would definitely be
useful to authorize the use of restricted tokens for both pg_upgrade
and pg_resetxlog. The patch for pg_resetxlog should be rebased on
latest HEAD because there is a small diff with get_restricted_token()
though.

The portion for initdb to make it use restricted tokens has been added
some time ago with fc9c20e, and the one of pg_ctl with a25cd81, both
of them in 2006, so instead of duplicating again the logic for
pg_upgrade and pg_resetxlog, shouldn't we create a common routine in
src/common and link to it all the frontend binaries that need it?
Hence, Asif, could you refactor first the existing code and make it
use a new API in libpqcommon? Let's say in
src/common/restricted_token.c or a better name than the one I just
gave out. Then, you could plug-in this new common routine with
pg_upgrade and pg_resetxlog in a second patch.
Regards,
-- 
Michael


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-03-02 04:44  Michael Paquier <michael.paquier@gmail.com>
  parent: Andres Freund <andres@2ndquadrant.com>
  1 sibling, 0 replies; 35+ messages in thread

From: Michael Paquier @ 2015-03-02 04:44 UTC (permalink / raw)
  To: Andres Freund <andres@2ndquadrant.com>; +Cc: Bruce Momjian <bruce@momjian.us>; Amit Kapila <amit.kapila16@gmail.com>; Alvaro Herrera <alvherre@2ndquadrant.com>; Asif Naeem <anaeem.it@gmail.com>; pgsql-bugs

On Fri, Jan 23, 2015 at 1:26 AM, Andres Freund <andres@2ndquadrant.com> wrote:
> On 2015-01-22 11:24:31 -0500, Bruce Momjian wrote:
>> On Thu, Jan 22, 2015 at 09:01:39AM +0530, Amit Kapila wrote:
>> > > The
>> > > Windows-specif code we do carry is required and was developed by people
>> > > that are no longer as involved.
>> > >
>> >
>> > I have seen many a times that once committer's (those who are not generally
>> > involved in Windows development) get reasonable confidence about patch
>> > and the review done for the same, they commit the patch.  It happens both
>> > for the patches where I was Author and where I was Reviewer, although I
>> > agree that it takes more time.
>>
>> Here is Windows change to properly detach the server process that never
>> got implemented as no Windows expert developed or tested a patch, but
>> test code was posted:
>>
>>       http://www.postgresql.org/message-id/flat/53759381.4000205@cubiclesoft.com#53759381.4000205@cubicles...
>>
>> Here is another unapplied Windows patch for preventing Control-C from
>> closing the server:
>>
>>       http://www.postgresql.org/message-id/flat/20140410214426.GI6917@momjian.us#20140410214426.GI6917@mom...
>>
>> Again, I would love to say we handle Windows patches well, but we don't.
>
> I unfortunately don't the issue is that specific to windows.

FWIW, I am putting those things in my never-ending TODO list. Thanks
for the reminder, Bruce.
-- 
Michael


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-03-04 13:53  Asif Naeem <anaeem.it@gmail.com>
  parent: Michael Paquier <michael.paquier@gmail.com>
  0 siblings, 1 reply; 35+ messages in thread

From: Asif Naeem @ 2015-03-04 13:53 UTC (permalink / raw)
  To: Michael Paquier <michael.paquier@gmail.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Bruce Momjian <bruce@momjian.us>; Alvaro Herrera <alvherre@2ndquadrant.com>; pgsql-bugs

On Mon, Mar 2, 2015 at 9:42 AM, Michael Paquier <michael.paquier@gmail.com>
wrote:

> On Thu, Jan 22, 2015 at 4:07 PM, Asif Naeem <anaeem.it@gmail.com> wrote:
> > Thank you. I have added it to next commitfest.
>
> Sorry for the late reply.
>
> So I have been looking at both patches, and I would definitely be
> useful to authorize the use of restricted tokens for both pg_upgrade
> and pg_resetxlog. The patch for pg_resetxlog should be rebased on
> latest HEAD because there is a small diff with get_restricted_token()
> though.
>
> The portion for initdb to make it use restricted tokens has been added
> some time ago with fc9c20e, and the one of pg_ctl with a25cd81, both
> of them in 2006, so instead of duplicating again the logic for
> pg_upgrade and pg_resetxlog, shouldn't we create a common routine in
> src/common and link to it all the frontend binaries that need it?
> Hence, Asif, could you refactor first the existing code and make it
> use a new API in libpqcommon? Let's say in
> src/common/restricted_token.c or a better name than the one I just
> gave out. Then, you could plug-in this new common routine with
> pg_upgrade and pg_resetxlog in a second patch.
>

Sure. PFA patch, restricted token code is moved to
src/common/restricted_token.c, Now it uses common routine for initdb,
pg_upgrade and pg_resetxlog. Please do let me know if I missed something or
more information is required. Thanks.

Regards,
Muhammad Asif Naeem


> Regards,
> --
> Michael
>

-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs

Attachments:

restricted_token.v1.patch (application/octet-stream, 14.9K) download diff --git a/contrib/pg_upgrade/pg_upgrade.c b/contrib/pg_upgrade/pg_upgrade.c index ed7de80..37e23ef 100644 --- a/contrib/pg_upgrade/pg_upgrade.c +++ b/contrib/pg_upgrade/pg_upgrade.c @@ -37,6 +37,7 @@ #include "postgres_fe.h" #include "pg_upgrade.h" +#include "common/restricted_token.h" #ifdef HAVE_LANGINFO_H #include <langinfo.h> @@ -65,6 +66,9 @@ char *output_files[] = { NULL }; +#ifdef WIN32 +const char *progname; +#endif int main(int argc, char **argv) @@ -75,6 +79,12 @@ main(int argc, char **argv) parseCommandLine(argc, argv); +#ifdef WIN32 + progname = os_info.progname; +#endif + + get_restricted_token(); + adjust_data_dir(&old_cluster); adjust_data_dir(&new_cluster); diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c index 18614e7..b69b5f4 100644 --- a/src/bin/initdb/initdb.c +++ b/src/bin/initdb/initdb.c @@ -62,6 +62,7 @@ #include "catalog/catalog.h" #include "common/username.h" +#include "common/restricted_token.h" #include "mb/pg_wchar.h" #include "getaddrinfo.h" #include "getopt_long.h" @@ -70,6 +71,8 @@ /* Ideally this would be in a .h file, but it hardly seems worth the trouble */ extern const char *select_default_timezone(const char *share_path); +const char *progname; + static const char *auth_methods_host[] = {"trust", "reject", "md5", "password", "ident", "radius", #ifdef ENABLE_GSS "gss", @@ -127,7 +130,6 @@ static char *xlog_dir = ""; /* internal vars */ -static const char *progname; static char *encodingid = "0"; static char *bki_file; static char *desc_file; @@ -178,9 +180,6 @@ static char *authwarning = NULL; static const char *boot_options = "-F"; static const char *backend_options = "--single -F -O -c search_path=pg_catalog -c exit_on_error=true"; -#ifdef WIN32 -char *restrict_env; -#endif static const char *subdirs[] = { "global", "pg_xlog", @@ -260,7 +259,6 @@ static void check_locale_name(int category, const char *locale, static bool check_locale_encoding(const char *locale, int encoding); static void setlocales(void); static void usage(const char *progname); -void get_restricted_token(void); void setup_pgdata(void); void setup_bin_paths(const char *argv0); void setup_data_file_paths(void); @@ -272,12 +270,6 @@ void create_xlog_symlink(void); void warn_on_mount_point(int error); void initialize_data_directory(void); - -#ifdef WIN32 -static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo); -#endif - - /* * macros for running pipes to postgres */ @@ -2754,116 +2746,6 @@ setlocales(void) #endif } -#ifdef WIN32 -typedef BOOL (WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); - -/* Windows API define missing from some versions of MingW headers */ -#ifndef DISABLE_MAX_PRIVILEGE -#define DISABLE_MAX_PRIVILEGE 0x1 -#endif - -/* - * Create a restricted token and execute the specified process with it. - * - * Returns 0 on failure, non-zero on success, same as CreateProcess(). - * - * On NT4, or any other system not containing the required functions, will - * NOT execute anything. - */ -static int -CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo) -{ - BOOL b; - STARTUPINFO si; - HANDLE origToken; - HANDLE restrictedToken; - SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY}; - SID_AND_ATTRIBUTES dropSids[2]; - __CreateRestrictedToken _CreateRestrictedToken = NULL; - HANDLE Advapi32Handle; - - ZeroMemory(&si, sizeof(si)); - si.cb = sizeof(si); - - Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); - if (Advapi32Handle != NULL) - { - _CreateRestrictedToken = (__CreateRestrictedToken) GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); - } - - if (_CreateRestrictedToken == NULL) - { - fprintf(stderr, _("%s: WARNING: cannot create restricted tokens on this platform\n"), progname); - if (Advapi32Handle != NULL) - FreeLibrary(Advapi32Handle); - return 0; - } - - /* Open the current token to use as a base for the restricted one */ - if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) - { - fprintf(stderr, _("%s: could not open process token: error code %lu\n"), progname, GetLastError()); - return 0; - } - - /* Allocate list of SIDs to remove */ - ZeroMemory(&dropSids, sizeof(dropSids)); - if (!AllocateAndInitializeSid(&NtAuthority, 2, - SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, - 0, &dropSids[0].Sid) || - !AllocateAndInitializeSid(&NtAuthority, 2, - SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, - 0, &dropSids[1].Sid)) - { - fprintf(stderr, _("%s: could not allocate SIDs: error code %lu\n"), - progname, GetLastError()); - return 0; - } - - b = _CreateRestrictedToken(origToken, - DISABLE_MAX_PRIVILEGE, - sizeof(dropSids) / sizeof(dropSids[0]), - dropSids, - 0, NULL, - 0, NULL, - &restrictedToken); - - FreeSid(dropSids[1].Sid); - FreeSid(dropSids[0].Sid); - CloseHandle(origToken); - FreeLibrary(Advapi32Handle); - - if (!b) - { - fprintf(stderr, _("%s: could not create restricted token: error code %lu\n"), progname, GetLastError()); - return 0; - } - -#ifndef __CYGWIN__ - AddUserToTokenDacl(restrictedToken); -#endif - - if (!CreateProcessAsUser(restrictedToken, - NULL, - cmd, - NULL, - NULL, - TRUE, - CREATE_SUSPENDED, - NULL, - NULL, - &si, - processInfo)) - - { - fprintf(stderr, _("%s: could not start process for command \"%s\": error code %lu\n"), progname, cmd, GetLastError()); - return 0; - } - - return ResumeThread(processInfo->hThread); -} -#endif - /* * print help text */ @@ -2957,53 +2839,6 @@ check_need_password(const char *authmethodlocal, const char *authmethodhost) } } -void -get_restricted_token(void) -{ -#ifdef WIN32 - - /* - * Before we execute another program, make sure that we are running with a - * restricted token. If not, re-execute ourselves with one. - */ - - if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL - || strcmp(restrict_env, "1") != 0) - { - PROCESS_INFORMATION pi; - char *cmdline; - - ZeroMemory(&pi, sizeof(pi)); - - cmdline = pg_strdup(GetCommandLine()); - - putenv("PG_RESTRICT_EXEC=1"); - - if (!CreateRestrictedProcess(cmdline, &pi)) - { - fprintf(stderr, _("%s: could not re-execute with restricted token: error code %lu\n"), progname, GetLastError()); - } - else - { - /* - * Successfully re-execed. Now wait for child process to capture - * exitcode. - */ - DWORD x; - - CloseHandle(pi.hThread); - WaitForSingleObject(pi.hProcess, INFINITE); - - if (!GetExitCodeProcess(pi.hProcess, &x)) - { - fprintf(stderr, _("%s: could not get exit code from subprocess: error code %lu\n"), progname, GetLastError()); - exit(1); - } - exit(x); - } - } -#endif -} void setup_pgdata(void) diff --git a/src/bin/pg_resetxlog/pg_resetxlog.c b/src/bin/pg_resetxlog/pg_resetxlog.c index a16089f..67fc0f2 100644 --- a/src/bin/pg_resetxlog/pg_resetxlog.c +++ b/src/bin/pg_resetxlog/pg_resetxlog.c @@ -53,6 +53,7 @@ #include "catalog/catversion.h" #include "catalog/pg_control.h" #include "common/fe_memutils.h" +#include "common/restricted_token.h" #include "storage/large_object.h" #include "pg_getopt.h" @@ -60,7 +61,6 @@ static ControlFileData ControlFile; /* pg_control values */ static XLogSegNo newXlogSegNo; /* new XLOG segment # */ static bool guessed = false; /* T if we had to guess at any values */ -static const char *progname; static uint32 set_xid_epoch = (uint32) -1; static TransactionId set_xid = 0; static TransactionId set_oldest_commit_ts = 0; @@ -82,6 +82,7 @@ static void KillExistingArchiveStatus(void); static void WriteEmptyXLOG(void); static void usage(void); +const char *progname; int main(int argc, char *argv[]) @@ -310,6 +311,8 @@ main(int argc, char *argv[]) } #endif + get_restricted_token(); + if (chdir(DataDir) < 0) { fprintf(stderr, _("%s: could not change directory to \"%s\": %s\n"), diff --git a/src/common/Makefile b/src/common/Makefile index c71415e..c2e456d 100644 --- a/src/common/Makefile +++ b/src/common/Makefile @@ -26,7 +26,7 @@ LIBS += $(PTHREAD_LIBS) OBJS_COMMON = exec.o pg_crc.o pg_lzcompress.o pgfnames.o psprintf.o relpath.o \ rmtree.o string.o username.o wait_error.o -OBJS_FRONTEND = $(OBJS_COMMON) fe_memutils.o +OBJS_FRONTEND = $(OBJS_COMMON) fe_memutils.o restricted_token.o OBJS_SRV = $(OBJS_COMMON:%.o=%_srv.o) diff --git a/src/tools/msvc/Mkvcbuild.pm b/src/tools/msvc/Mkvcbuild.pm index 5dc8426..1bc8673 100644 --- a/src/tools/msvc/Mkvcbuild.pm +++ b/src/tools/msvc/Mkvcbuild.pm @@ -80,7 +80,8 @@ sub mkvcbuild exec.c pg_crc.c pg_lzcompress.c pgfnames.c psprintf.c relpath.c rmtree.c string.c username.c wait_error.c); - our @pgcommonfrontendfiles = (@pgcommonallfiles, qw(fe_memutils.c)); + our @pgcommonfrontendfiles = (@pgcommonallfiles, qw(fe_memutils.c + restricted_token.c)); our @pgcommonbkndfiles = @pgcommonallfiles; diff --git a/src/common/restricted_token.c b/src/common/restricted_token.c new file mode 100644 index 0000000..53839f8 --- /dev/null +++ b/src/common/restricted_token.c @@ -0,0 +1,192 @@ +/*------------------------------------------------------------------------- + * + * restricted_token.c + * helper routine to ensure restricted token on Windows + * + * + * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * + * IDENTIFICATION + * src/common/restricted_token.c + * + *------------------------------------------------------------------------- + */ + +#ifndef FRONTEND +#error "This file is not expected to be compiled for backend code" +#endif + +#include "postgres_fe.h" + +#include "common/restricted_token.h" + +#ifdef WIN32 + +/* internal vars */ +extern const char *progname; +char *restrict_env; + +static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo); +typedef BOOL (WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); + +/* Windows API define missing from some versions of MingW headers */ +#ifndef DISABLE_MAX_PRIVILEGE +#define DISABLE_MAX_PRIVILEGE 0x1 +#endif + +/* + * Create a restricted token and execute the specified process with it. + * + * Returns 0 on failure, non-zero on success, same as CreateProcess(). + * + * On NT4, or any other system not containing the required functions, will + * NOT execute anything. + */ +static int +CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo) +{ + BOOL b; + STARTUPINFO si; + HANDLE origToken; + HANDLE restrictedToken; + SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY}; + SID_AND_ATTRIBUTES dropSids[2]; + __CreateRestrictedToken _CreateRestrictedToken = NULL; + HANDLE Advapi32Handle; + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + + Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); + if (Advapi32Handle != NULL) + { + _CreateRestrictedToken = (__CreateRestrictedToken) GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); + } + + if (_CreateRestrictedToken == NULL) + { + fprintf(stderr, _("%s: WARNING: cannot create restricted tokens on this platform\n"), progname); + if (Advapi32Handle != NULL) + FreeLibrary(Advapi32Handle); + return 0; + } + + /* Open the current token to use as a base for the restricted one */ + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) + { + fprintf(stderr, _("%s: could not open process token: error code %lu\n"), progname, GetLastError()); + return 0; + } + + /* Allocate list of SIDs to remove */ + ZeroMemory(&dropSids, sizeof(dropSids)); + if (!AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, + 0, &dropSids[0].Sid) || + !AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, + 0, &dropSids[1].Sid)) + { + fprintf(stderr, _("%s: could not allocate SIDs: error code %lu\n"), + progname, GetLastError()); + return 0; + } + + b = _CreateRestrictedToken(origToken, + DISABLE_MAX_PRIVILEGE, + sizeof(dropSids) / sizeof(dropSids[0]), + dropSids, + 0, NULL, + 0, NULL, + &restrictedToken); + + FreeSid(dropSids[1].Sid); + FreeSid(dropSids[0].Sid); + CloseHandle(origToken); + FreeLibrary(Advapi32Handle); + + if (!b) + { + fprintf(stderr, _("%s: could not create restricted token: error code %lu\n"), progname, GetLastError()); + return 0; + } + +#ifndef __CYGWIN__ + AddUserToTokenDacl(restrictedToken); +#endif + + if (!CreateProcessAsUser(restrictedToken, + NULL, + cmd, + NULL, + NULL, + TRUE, + CREATE_SUSPENDED, + NULL, + NULL, + &si, + processInfo)) + + { + fprintf(stderr, _("%s: could not start process for command \"%s\": error code %lu\n"), progname, cmd, GetLastError()); + return 0; + } + + return ResumeThread(processInfo->hThread); +} +#endif + +/* + * On Windows make sure that we are running with a restricted token, + * On other platforms do nothing. + */ + +void +get_restricted_token(void) +{ +#ifdef WIN32 + + /* + * Before we execute another program, make sure that we are running with a + * restricted token. If not, re-execute ourselves with one. + */ + + if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL + || strcmp(restrict_env, "1") != 0) + { + PROCESS_INFORMATION pi; + char *cmdline; + + ZeroMemory(&pi, sizeof(pi)); + + cmdline = pg_strdup(GetCommandLine()); + + putenv("PG_RESTRICT_EXEC=1"); + + if (!CreateRestrictedProcess(cmdline, &pi)) + { + fprintf(stderr, _("%s: could not re-execute with restricted token: error code %lu\n"), progname, GetLastError()); + } + else + { + /* + * Successfully re-execed. Now wait for child process to capture + * exitcode. + */ + DWORD x; + + CloseHandle(pi.hThread); + WaitForSingleObject(pi.hProcess, INFINITE); + + if (!GetExitCodeProcess(pi.hProcess, &x)) + { + fprintf(stderr, _("%s: could not get exit code from subprocess: error code %lu\n"), progname, GetLastError()); + exit(1); + } + exit(x); + } + } +#endif +} diff --git a/src/include/common/restricted_token.h b/src/include/common/restricted_token.h new file mode 100644 index 0000000..209dccf --- /dev/null +++ b/src/include/common/restricted_token.h @@ -0,0 +1,20 @@ +/* + * restricted_token.h + * helper routine to ensure restricted token on Windows + * + * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * src/include/common/restricted_token.h + */ +#ifndef COMMON_RESTRICTED_TOKEN_H +#define COMMON_RESTRICTED_TOKEN_H + +/* + * On Windows make sure that we are running with a restricted token, + * On other platforms do nothing. + */ + +void get_restricted_token(void); + +#endif /* COMMON_RESTRICTED_TOKEN_H */
^ permalink raw reply [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-03-05 06:37  Michael Paquier <michael.paquier@gmail.com>
  parent: Asif Naeem <anaeem.it@gmail.com>
  0 siblings, 1 reply; 35+ messages in thread

From: Michael Paquier @ 2015-03-05 06:37 UTC (permalink / raw)
  To: Asif Naeem <anaeem.it@gmail.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Bruce Momjian <bruce@momjian.us>; Alvaro Herrera <alvherre@2ndquadrant.com>; pgsql-bugs

On Wed, Mar 4, 2015 at 10:53 PM, Asif Naeem wrote:
> On Mon, Mar 2, 2015 at 9:42 AM, Michael Paquier wrote:
>>
>> The portion for initdb to make it use restricted tokens has been added
>> some time ago with fc9c20e, and the one of pg_ctl with a25cd81, both
>> of them in 2006, so instead of duplicating again the logic for
>> pg_upgrade and pg_resetxlog, shouldn't we create a common routine in
>> src/common and link to it all the frontend binaries that need it?
>> Hence, Asif, could you refactor first the existing code and make it
>> use a new API in libpqcommon?
>
> Sure. PFA patch, restricted token code is moved to
> src/common/restricted_token.c, Now it uses common routine for initdb,
> pg_upgrade and pg_resetxlog. Please do let me know if I missed something or
> more information is required. Thanks.

Thanks. This looks fine to me (tested on MinGW-32 and MSVC). I just
have one comment: get_restricted_token should use progname as
argument. This way you can just keep progname as a static variable for
each frontend and not play with constant variables in both code paths,
aka src/common and src/bin stuff.

Regards,
-- 
Michael


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-03-12 09:33  Asif Naeem <anaeem.it@gmail.com>
  parent: Michael Paquier <michael.paquier@gmail.com>
  0 siblings, 1 reply; 35+ messages in thread

From: Asif Naeem @ 2015-03-12 09:33 UTC (permalink / raw)
  To: Michael Paquier <michael.paquier@gmail.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Bruce Momjian <bruce@momjian.us>; Alvaro Herrera <alvherre@2ndquadrant.com>; pgsql-bugs

Thank you Michael. Good suggestion, PFA updated patch, it don't have
dependency on "progname" global variable any more and expecting this value
as related function argument.

Regards,
Muhammad Asif Naeem

On Thu, Mar 5, 2015 at 11:37 AM, Michael Paquier <michael.paquier@gmail.com>
wrote:

> On Wed, Mar 4, 2015 at 10:53 PM, Asif Naeem wrote:
> > On Mon, Mar 2, 2015 at 9:42 AM, Michael Paquier wrote:
> >>
> >> The portion for initdb to make it use restricted tokens has been added
> >> some time ago with fc9c20e, and the one of pg_ctl with a25cd81, both
> >> of them in 2006, so instead of duplicating again the logic for
> >> pg_upgrade and pg_resetxlog, shouldn't we create a common routine in
> >> src/common and link to it all the frontend binaries that need it?
> >> Hence, Asif, could you refactor first the existing code and make it
> >> use a new API in libpqcommon?
> >
> > Sure. PFA patch, restricted token code is moved to
> > src/common/restricted_token.c, Now it uses common routine for initdb,
> > pg_upgrade and pg_resetxlog. Please do let me know if I missed something
> or
> > more information is required. Thanks.
>
> Thanks. This looks fine to me (tested on MinGW-32 and MSVC). I just
> have one comment: get_restricted_token should use progname as
> argument. This way you can just keep progname as a static variable for
> each frontend and not play with constant variables in both code paths,
> aka src/common and src/bin stuff.
>
> Regards,
> --
> Michael
>

-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs

Attachments:

restricted_token.v2.patch (application/octet-stream, 13.9K) download diff --git a/contrib/pg_upgrade/pg_upgrade.c b/contrib/pg_upgrade/pg_upgrade.c index ed7de80..eb48da7 100644 --- a/contrib/pg_upgrade/pg_upgrade.c +++ b/contrib/pg_upgrade/pg_upgrade.c @@ -37,6 +37,7 @@ #include "postgres_fe.h" #include "pg_upgrade.h" +#include "common/restricted_token.h" #ifdef HAVE_LANGINFO_H #include <langinfo.h> @@ -75,6 +76,8 @@ main(int argc, char **argv) parseCommandLine(argc, argv); + get_restricted_token(os_info.progname); + adjust_data_dir(&old_cluster); adjust_data_dir(&new_cluster); diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c index 18614e7..b8abf19 100644 --- a/src/bin/initdb/initdb.c +++ b/src/bin/initdb/initdb.c @@ -62,6 +62,7 @@ #include "catalog/catalog.h" #include "common/username.h" +#include "common/restricted_token.h" #include "mb/pg_wchar.h" #include "getaddrinfo.h" #include "getopt_long.h" @@ -178,9 +179,6 @@ static char *authwarning = NULL; static const char *boot_options = "-F"; static const char *backend_options = "--single -F -O -c search_path=pg_catalog -c exit_on_error=true"; -#ifdef WIN32 -char *restrict_env; -#endif static const char *subdirs[] = { "global", "pg_xlog", @@ -260,7 +258,6 @@ static void check_locale_name(int category, const char *locale, static bool check_locale_encoding(const char *locale, int encoding); static void setlocales(void); static void usage(const char *progname); -void get_restricted_token(void); void setup_pgdata(void); void setup_bin_paths(const char *argv0); void setup_data_file_paths(void); @@ -272,12 +269,6 @@ void create_xlog_symlink(void); void warn_on_mount_point(int error); void initialize_data_directory(void); - -#ifdef WIN32 -static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo); -#endif - - /* * macros for running pipes to postgres */ @@ -2754,116 +2745,6 @@ setlocales(void) #endif } -#ifdef WIN32 -typedef BOOL (WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); - -/* Windows API define missing from some versions of MingW headers */ -#ifndef DISABLE_MAX_PRIVILEGE -#define DISABLE_MAX_PRIVILEGE 0x1 -#endif - -/* - * Create a restricted token and execute the specified process with it. - * - * Returns 0 on failure, non-zero on success, same as CreateProcess(). - * - * On NT4, or any other system not containing the required functions, will - * NOT execute anything. - */ -static int -CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo) -{ - BOOL b; - STARTUPINFO si; - HANDLE origToken; - HANDLE restrictedToken; - SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY}; - SID_AND_ATTRIBUTES dropSids[2]; - __CreateRestrictedToken _CreateRestrictedToken = NULL; - HANDLE Advapi32Handle; - - ZeroMemory(&si, sizeof(si)); - si.cb = sizeof(si); - - Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); - if (Advapi32Handle != NULL) - { - _CreateRestrictedToken = (__CreateRestrictedToken) GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); - } - - if (_CreateRestrictedToken == NULL) - { - fprintf(stderr, _("%s: WARNING: cannot create restricted tokens on this platform\n"), progname); - if (Advapi32Handle != NULL) - FreeLibrary(Advapi32Handle); - return 0; - } - - /* Open the current token to use as a base for the restricted one */ - if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) - { - fprintf(stderr, _("%s: could not open process token: error code %lu\n"), progname, GetLastError()); - return 0; - } - - /* Allocate list of SIDs to remove */ - ZeroMemory(&dropSids, sizeof(dropSids)); - if (!AllocateAndInitializeSid(&NtAuthority, 2, - SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, - 0, &dropSids[0].Sid) || - !AllocateAndInitializeSid(&NtAuthority, 2, - SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, - 0, &dropSids[1].Sid)) - { - fprintf(stderr, _("%s: could not allocate SIDs: error code %lu\n"), - progname, GetLastError()); - return 0; - } - - b = _CreateRestrictedToken(origToken, - DISABLE_MAX_PRIVILEGE, - sizeof(dropSids) / sizeof(dropSids[0]), - dropSids, - 0, NULL, - 0, NULL, - &restrictedToken); - - FreeSid(dropSids[1].Sid); - FreeSid(dropSids[0].Sid); - CloseHandle(origToken); - FreeLibrary(Advapi32Handle); - - if (!b) - { - fprintf(stderr, _("%s: could not create restricted token: error code %lu\n"), progname, GetLastError()); - return 0; - } - -#ifndef __CYGWIN__ - AddUserToTokenDacl(restrictedToken); -#endif - - if (!CreateProcessAsUser(restrictedToken, - NULL, - cmd, - NULL, - NULL, - TRUE, - CREATE_SUSPENDED, - NULL, - NULL, - &si, - processInfo)) - - { - fprintf(stderr, _("%s: could not start process for command \"%s\": error code %lu\n"), progname, cmd, GetLastError()); - return 0; - } - - return ResumeThread(processInfo->hThread); -} -#endif - /* * print help text */ @@ -2957,53 +2838,6 @@ check_need_password(const char *authmethodlocal, const char *authmethodhost) } } -void -get_restricted_token(void) -{ -#ifdef WIN32 - - /* - * Before we execute another program, make sure that we are running with a - * restricted token. If not, re-execute ourselves with one. - */ - - if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL - || strcmp(restrict_env, "1") != 0) - { - PROCESS_INFORMATION pi; - char *cmdline; - - ZeroMemory(&pi, sizeof(pi)); - - cmdline = pg_strdup(GetCommandLine()); - - putenv("PG_RESTRICT_EXEC=1"); - - if (!CreateRestrictedProcess(cmdline, &pi)) - { - fprintf(stderr, _("%s: could not re-execute with restricted token: error code %lu\n"), progname, GetLastError()); - } - else - { - /* - * Successfully re-execed. Now wait for child process to capture - * exitcode. - */ - DWORD x; - - CloseHandle(pi.hThread); - WaitForSingleObject(pi.hProcess, INFINITE); - - if (!GetExitCodeProcess(pi.hProcess, &x)) - { - fprintf(stderr, _("%s: could not get exit code from subprocess: error code %lu\n"), progname, GetLastError()); - exit(1); - } - exit(x); - } - } -#endif -} void setup_pgdata(void) @@ -3759,7 +3593,7 @@ main(int argc, char *argv[]) check_need_password(authmethodlocal, authmethodhost); - get_restricted_token(); + get_restricted_token(progname); setup_pgdata(); diff --git a/src/bin/pg_resetxlog/pg_resetxlog.c b/src/bin/pg_resetxlog/pg_resetxlog.c index a16089f..3361111 100644 --- a/src/bin/pg_resetxlog/pg_resetxlog.c +++ b/src/bin/pg_resetxlog/pg_resetxlog.c @@ -53,6 +53,7 @@ #include "catalog/catversion.h" #include "catalog/pg_control.h" #include "common/fe_memutils.h" +#include "common/restricted_token.h" #include "storage/large_object.h" #include "pg_getopt.h" @@ -310,6 +311,8 @@ main(int argc, char *argv[]) } #endif + get_restricted_token(progname); + if (chdir(DataDir) < 0) { fprintf(stderr, _("%s: could not change directory to \"%s\": %s\n"), diff --git a/src/common/Makefile b/src/common/Makefile index c71415e..c2e456d 100644 --- a/src/common/Makefile +++ b/src/common/Makefile @@ -26,7 +26,7 @@ LIBS += $(PTHREAD_LIBS) OBJS_COMMON = exec.o pg_crc.o pg_lzcompress.o pgfnames.o psprintf.o relpath.o \ rmtree.o string.o username.o wait_error.o -OBJS_FRONTEND = $(OBJS_COMMON) fe_memutils.o +OBJS_FRONTEND = $(OBJS_COMMON) fe_memutils.o restricted_token.o OBJS_SRV = $(OBJS_COMMON:%.o=%_srv.o) diff --git a/src/tools/msvc/Mkvcbuild.pm b/src/tools/msvc/Mkvcbuild.pm index 989a2ec..9c52a46 100644 --- a/src/tools/msvc/Mkvcbuild.pm +++ b/src/tools/msvc/Mkvcbuild.pm @@ -95,7 +95,8 @@ sub mkvcbuild exec.c pg_crc.c pg_lzcompress.c pgfnames.c psprintf.c relpath.c rmtree.c string.c username.c wait_error.c); - our @pgcommonfrontendfiles = (@pgcommonallfiles, qw(fe_memutils.c)); + our @pgcommonfrontendfiles = (@pgcommonallfiles, qw(fe_memutils.c + restricted_token.c)); our @pgcommonbkndfiles = @pgcommonallfiles; diff --git a/src/common/restricted_token.c b/src/common/restricted_token.c new file mode 100644 index 0000000..c046f8a --- /dev/null +++ b/src/common/restricted_token.c @@ -0,0 +1,191 @@ +/*------------------------------------------------------------------------- + * + * restricted_token.c + * helper routine to ensure restricted token on Windows + * + * + * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * + * IDENTIFICATION + * src/common/restricted_token.c + * + *------------------------------------------------------------------------- + */ + +#ifndef FRONTEND +#error "This file is not expected to be compiled for backend code" +#endif + +#include "postgres_fe.h" + +#include "common/restricted_token.h" + +#ifdef WIN32 + +/* internal vars */ +char *restrict_env; + +static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, const char *progname); +typedef BOOL (WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); + +/* Windows API define missing from some versions of MingW headers */ +#ifndef DISABLE_MAX_PRIVILEGE +#define DISABLE_MAX_PRIVILEGE 0x1 +#endif + +/* + * Create a restricted token and execute the specified process with it. + * + * Returns 0 on failure, non-zero on success, same as CreateProcess(). + * + * On NT4, or any other system not containing the required functions, will + * NOT execute anything. + */ +static int +CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, const char *progname) +{ + BOOL b; + STARTUPINFO si; + HANDLE origToken; + HANDLE restrictedToken; + SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY}; + SID_AND_ATTRIBUTES dropSids[2]; + __CreateRestrictedToken _CreateRestrictedToken = NULL; + HANDLE Advapi32Handle; + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + + Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); + if (Advapi32Handle != NULL) + { + _CreateRestrictedToken = (__CreateRestrictedToken) GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); + } + + if (_CreateRestrictedToken == NULL) + { + fprintf(stderr, _("%s: WARNING: cannot create restricted tokens on this platform\n"), progname); + if (Advapi32Handle != NULL) + FreeLibrary(Advapi32Handle); + return 0; + } + + /* Open the current token to use as a base for the restricted one */ + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) + { + fprintf(stderr, _("%s: could not open process token: error code %lu\n"), progname, GetLastError()); + return 0; + } + + /* Allocate list of SIDs to remove */ + ZeroMemory(&dropSids, sizeof(dropSids)); + if (!AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, + 0, &dropSids[0].Sid) || + !AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, + 0, &dropSids[1].Sid)) + { + fprintf(stderr, _("%s: could not allocate SIDs: error code %lu\n"), + progname, GetLastError()); + return 0; + } + + b = _CreateRestrictedToken(origToken, + DISABLE_MAX_PRIVILEGE, + sizeof(dropSids) / sizeof(dropSids[0]), + dropSids, + 0, NULL, + 0, NULL, + &restrictedToken); + + FreeSid(dropSids[1].Sid); + FreeSid(dropSids[0].Sid); + CloseHandle(origToken); + FreeLibrary(Advapi32Handle); + + if (!b) + { + fprintf(stderr, _("%s: could not create restricted token: error code %lu\n"), progname, GetLastError()); + return 0; + } + +#ifndef __CYGWIN__ + AddUserToTokenDacl(restrictedToken); +#endif + + if (!CreateProcessAsUser(restrictedToken, + NULL, + cmd, + NULL, + NULL, + TRUE, + CREATE_SUSPENDED, + NULL, + NULL, + &si, + processInfo)) + + { + fprintf(stderr, _("%s: could not start process for command \"%s\": error code %lu\n"), progname, cmd, GetLastError()); + return 0; + } + + return ResumeThread(processInfo->hThread); +} +#endif + +/* + * On Windows make sure that we are running with a restricted token, + * On other platforms do nothing. + */ + +void +get_restricted_token(const char *progname) +{ +#ifdef WIN32 + + /* + * Before we execute another program, make sure that we are running with a + * restricted token. If not, re-execute ourselves with one. + */ + + if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL + || strcmp(restrict_env, "1") != 0) + { + PROCESS_INFORMATION pi; + char *cmdline; + + ZeroMemory(&pi, sizeof(pi)); + + cmdline = pg_strdup(GetCommandLine()); + + putenv("PG_RESTRICT_EXEC=1"); + + if (!CreateRestrictedProcess(cmdline, &pi, progname)) + { + fprintf(stderr, _("%s: could not re-execute with restricted token: error code %lu\n"), progname, GetLastError()); + } + else + { + /* + * Successfully re-execed. Now wait for child process to capture + * exitcode. + */ + DWORD x; + + CloseHandle(pi.hThread); + WaitForSingleObject(pi.hProcess, INFINITE); + + if (!GetExitCodeProcess(pi.hProcess, &x)) + { + fprintf(stderr, _("%s: could not get exit code from subprocess: error code %lu\n"), progname, GetLastError()); + exit(1); + } + exit(x); + } + } +#endif +} diff --git a/src/include/common/restricted_token.h b/src/include/common/restricted_token.h new file mode 100644 index 0000000..144bf73 --- /dev/null +++ b/src/include/common/restricted_token.h @@ -0,0 +1,20 @@ +/* + * restricted_token.h + * helper routine to ensure restricted token on Windows + * + * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * src/include/common/restricted_token.h + */ +#ifndef COMMON_RESTRICTED_TOKEN_H +#define COMMON_RESTRICTED_TOKEN_H + +/* + * On Windows make sure that we are running with a restricted token, + * On other platforms do nothing. + */ + +void get_restricted_token(const char *progname); + +#endif /* COMMON_RESTRICTED_TOKEN_H */
^ permalink raw reply [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-03-12 13:50  Alvaro Herrera <alvherre@2ndquadrant.com>
  parent: Asif Naeem <anaeem.it@gmail.com>
  0 siblings, 1 reply; 35+ messages in thread

From: Alvaro Herrera @ 2015-03-12 13:50 UTC (permalink / raw)
  To: Asif Naeem <anaeem.it@gmail.com>; +Cc: Michael Paquier <michael.paquier@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Bruce Momjian <bruce@momjian.us>; pgsql-bugs

Asif Naeem wrote:
> Thank you Michael. Good suggestion, PFA updated patch, it don't have
> dependency on "progname" global variable any more and expecting this value
> as related function argument.

We have another copy of this in pg_ctl, which looks pretty much
identical except there's some additional stuff at the bottom.  Would it
make sense to add those additional "Job"-related things as a separate
routine, so that we can remove the duplicate copy of the "restricted
token" code, and have pg_ctl use get_restricted_process from src/common
instead?

There is a further copy of very similar stuff in pg_regress.c, but what
it does is slightly different; not sure how difficult it would be to
refactor that one too.

Is this a backpatchable bug fix, or are we considering this only for the
master branch?

-- 
Álvaro Herrera                http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-03-12 14:23  Michael Paquier <michael.paquier@gmail.com>
  parent: Alvaro Herrera <alvherre@2ndquadrant.com>
  0 siblings, 2 replies; 35+ messages in thread

From: Michael Paquier @ 2015-03-12 14:23 UTC (permalink / raw)
  To: Alvaro Herrera <alvherre@2ndquadrant.com>; +Cc: Asif Naeem <anaeem.it@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Bruce Momjian <bruce@momjian.us>; pgsql-bugs

On Thu, Mar 12, 2015 at 6:50 AM, Alvaro Herrera
<alvherre@2ndquadrant.com> wrote:
> Asif Naeem wrote:
>> Thank you Michael. Good suggestion, PFA updated patch, it don't have
>> dependency on "progname" global variable any more and expecting this value
>> as related function argument.
>
> We have another copy of this in pg_ctl, which looks pretty much
> identical except there's some additional stuff at the bottom.  Would it
> make sense to add those additional "Job"-related things as a separate
> routine, so that we can remove the duplicate copy of the "restricted
> token" code, and have pg_ctl use get_restricted_process from src/common
> instead?

Yes, looking at the code it makes sense.

> There is a further copy of very similar stuff in pg_regress.c, but what
> it does is slightly different; not sure how difficult it would be to
> refactor that one too.

In this part the only difference is a spawn of cmd /c, but I don't see
why it is useful to spawn a new command prompt here for this case, so
we could just drop this part. Looking at the log history, this has
been added since this code creation..

> Is this a backpatchable bug fix, or are we considering this only for the
> master branch?

It would be good to get that backpatched, that's something we really
miss now IMO. Now it modifies libpgcommon, so Windows packagers (me
being one) will certainly need to patch a bit stuff but that's a
one-line changer so it's not a big deal. And I imagine that this is
actually the reason why Asif reported that as a bug as well.
-- 
Michael


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-03-12 14:38  Michael Paquier <michael.paquier@gmail.com>
  parent: Michael Paquier <michael.paquier@gmail.com>
  1 sibling, 1 reply; 35+ messages in thread

From: Michael Paquier @ 2015-03-12 14:38 UTC (permalink / raw)
  To: Alvaro Herrera <alvherre@2ndquadrant.com>; +Cc: Asif Naeem <anaeem.it@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Bruce Momjian <bruce@momjian.us>; pgsql-bugs

On Thu, Mar 12, 2015 at 11:23 PM, Michael Paquier wrote:
> On Thu, Mar 12, 2015 at 6:50 AM, Alvaro Herrera wrote:
> In this part the only difference is a spawn of cmd /c, but I don't see
> why it is useful to spawn a new command prompt here for this case, so
> we could just drop this part. Looking at the log history, this has
> been added since this code creation..

Taking back my words here. We definitely want to spawn a new process
in the case of pg_regress, so I think that the best thing to do would
be to pass the to-be-launched command to get_restrict_token(), and be
careful with WaitForSingleObject and GetExitCodeProcess() as there are
cases where we cannot wait for a process, so we are going to need a
control flag, or to let the callers of get_restricted_token() do the
wait themselves. I would think that the latter is better, additional
opinions being welcome.
-- 
Michael


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-03-12 14:41  Alvaro Herrera <alvherre@2ndquadrant.com>
  parent: Michael Paquier <michael.paquier@gmail.com>
  0 siblings, 0 replies; 35+ messages in thread

From: Alvaro Herrera @ 2015-03-12 14:41 UTC (permalink / raw)
  To: Michael Paquier <michael.paquier@gmail.com>; +Cc: Asif Naeem <anaeem.it@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Bruce Momjian <bruce@momjian.us>; pgsql-bugs

Michael Paquier wrote:
> On Thu, Mar 12, 2015 at 11:23 PM, Michael Paquier wrote:
> > On Thu, Mar 12, 2015 at 6:50 AM, Alvaro Herrera wrote:
> > In this part the only difference is a spawn of cmd /c, but I don't see
> > why it is useful to spawn a new command prompt here for this case, so
> > we could just drop this part. Looking at the log history, this has
> > been added since this code creation..
> 
> Taking back my words here. We definitely want to spawn a new process
> in the case of pg_regress, so I think that the best thing to do would
> be to pass the to-be-launched command to get_restrict_token(), and be
> careful with WaitForSingleObject and GetExitCodeProcess() as there are
> cases where we cannot wait for a process, so we are going to need a
> control flag, or to let the callers of get_restricted_token() do the
> wait themselves. I would think that the latter is better, additional
> opinions being welcome.

Maybe we want a specialized routine for pg_regress; maybe
get_restricted_token would call it with some args set to null or false
as appropriate.  My point is not to make the other callers of
get_restricted_token more complex.

-- 
Álvaro Herrera                http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-03-12 14:45  Alvaro Herrera <alvherre@2ndquadrant.com>
  parent: Michael Paquier <michael.paquier@gmail.com>
  1 sibling, 1 reply; 35+ messages in thread

From: Alvaro Herrera @ 2015-03-12 14:45 UTC (permalink / raw)
  To: Michael Paquier <michael.paquier@gmail.com>; +Cc: Asif Naeem <anaeem.it@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Bruce Momjian <bruce@momjian.us>; pgsql-bugs

Michael Paquier wrote:
> On Thu, Mar 12, 2015 at 6:50 AM, Alvaro Herrera
> <alvherre@2ndquadrant.com> wrote:

> > Is this a backpatchable bug fix, or are we considering this only for the
> > master branch?
> 
> It would be good to get that backpatched, that's something we really
> miss now IMO. Now it modifies libpgcommon, so Windows packagers (me
> being one) will certainly need to patch a bit stuff but that's a
> one-line changer so it's not a big deal. And I imagine that this is
> actually the reason why Asif reported that as a bug as well.

I think it'd be better to patch only pg_upgrade in back branches, so
that there are no libpgcommon changes.  Seems that would make life
easier for packagers (See the \connect thread, where Robert opined that
it'd be better to duplicate some routines in back branches rather than
refactor libpq code and move the common code to pgcommon.  I didn't
completely agree with him at the time, but now that you mention
packagers pain, maybe he has a point.)

So let's do the refactoring in the master branch only, and duplicate
the code in back branches.  Nasty, but it seems the more robust
approach.

-- 
Álvaro Herrera                http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-03-12 23:32  Michael Paquier <michael.paquier@gmail.com>
  parent: Alvaro Herrera <alvherre@2ndquadrant.com>
  0 siblings, 1 reply; 35+ messages in thread

From: Michael Paquier @ 2015-03-12 23:32 UTC (permalink / raw)
  To: Alvaro Herrera <alvherre@2ndquadrant.com>; +Cc: Asif Naeem <anaeem.it@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Bruce Momjian <bruce@momjian.us>; pgsql-bugs

On Thu, Mar 12, 2015 at 11:45 PM, Alvaro Herrera
<alvherre@2ndquadrant.com> wrote:
> Michael Paquier wrote:
>> On Thu, Mar 12, 2015 at 6:50 AM, Alvaro Herrera
>> <alvherre@2ndquadrant.com> wrote:
>
>> > Is this a backpatchable bug fix, or are we considering this only for the
>> > master branch?
>>
>> It would be good to get that backpatched, that's something we really
>> miss now IMO. Now it modifies libpgcommon, so Windows packagers (me
>> being one) will certainly need to patch a bit stuff but that's a
>> one-line changer so it's not a big deal. And I imagine that this is
>> actually the reason why Asif reported that as a bug as well.
>
> I think it'd be better to patch only pg_upgrade in back branches, so
> that there are no libpgcommon changes.  Seems that would make life
> easier for packagers (See the \connect thread, where Robert opined that
> it'd be better to duplicate some routines in back branches rather than
> refactor libpq code and move the common code to pgcommon.  I didn't
> completely agree with him at the time, but now that you mention
> packagers pain, maybe he has a point.)
>
> So let's do the refactoring in the master branch only, and duplicate
> the code in back branches.  Nasty, but it seems the more robust
> approach.

This plan sounds fine to me.
-- 
Michael


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-03-16 09:07  Asif Naeem <anaeem.it@gmail.com>
  parent: Michael Paquier <michael.paquier@gmail.com>
  0 siblings, 1 reply; 35+ messages in thread

From: Asif Naeem @ 2015-03-16 09:07 UTC (permalink / raw)
  To: Michael Paquier <michael.paquier@gmail.com>; +Cc: Alvaro Herrera <alvherre@2ndquadrant.com>; Amit Kapila <amit.kapila16@gmail.com>; Bruce Momjian <bruce@momjian.us>; pgsql-bugs

+1

On Fri, Mar 13, 2015 at 4:32 AM, Michael Paquier <michael.paquier@gmail.com>
wrote:

> On Thu, Mar 12, 2015 at 11:45 PM, Alvaro Herrera
> <alvherre@2ndquadrant.com> wrote:
> > Michael Paquier wrote:
> >> On Thu, Mar 12, 2015 at 6:50 AM, Alvaro Herrera
> >> <alvherre@2ndquadrant.com> wrote:
> >
> >> > Is this a backpatchable bug fix, or are we considering this only for
> the
> >> > master branch?
> >>
> >> It would be good to get that backpatched, that's something we really
> >> miss now IMO. Now it modifies libpgcommon, so Windows packagers (me
> >> being one) will certainly need to patch a bit stuff but that's a
> >> one-line changer so it's not a big deal. And I imagine that this is
> >> actually the reason why Asif reported that as a bug as well.
> >
> > I think it'd be better to patch only pg_upgrade in back branches, so
> > that there are no libpgcommon changes.  Seems that would make life
> > easier for packagers (See the \connect thread, where Robert opined that
> > it'd be better to duplicate some routines in back branches rather than
> > refactor libpq code and move the common code to pgcommon.  I didn't
> > completely agree with him at the time, but now that you mention
> > packagers pain, maybe he has a point.)
> >
> > So let's do the refactoring in the master branch only, and duplicate
> > the code in back branches.  Nasty, but it seems the more robust
> > approach.
>
> This plan sounds fine to me.
> --
> Michael
>

^ permalink  raw  reply  [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-03-17 20:15  Asif Naeem <anaeem.it@gmail.com>
  parent: Asif Naeem <anaeem.it@gmail.com>
  0 siblings, 1 reply; 35+ messages in thread

From: Asif Naeem @ 2015-03-17 20:15 UTC (permalink / raw)
  To: Michael Paquier <michael.paquier@gmail.com>; +Cc: Alvaro Herrera <alvherre@2ndquadrant.com>; Amit Kapila <amit.kapila16@gmail.com>; Bruce Momjian <bruce@momjian.us>; pgsql-bugs

Thank you for useful suggestions, PFA patch, for pg_ctl.c and pg_regress.c
it relies on CreateRestrictedProcess() function now.

src/common/restricted_token.c

>      #define write_stderr(fmt, ...) fprintf(stderr, fmt, __VA_ARGS__)


src//bin/pg_ctl/pg_ctl.c

> static void
> write_stderr(const char *fmt,...)
> {
> ...
> /*
> * On Win32, we print to stderr if running on a console, or write to
> * eventlog if running as a service
> */
> if (!isatty(fileno(stderr))) /* Running as a service */
> {
> ...
> }
>

src/backend/port/win32/security.c

> void
> write_stderr(const char *fmt,...)
> {
> ...
> /*
> * On Win32, we print to stderr if running on a console, or write to
> * eventlog if running as a service
> */
> if (pgwin32_is_service()) /* Running as a service */
> {
> ...
> }
>

security.c write_stderr() implementation seems correct, that relies on
pgwin32_is_service() function but it seems little expensive operation to
write error messages. pg_ctl.c write_stderr() implementation depend on
isatty() to detect if it is running as service, I doubt that if it is right
way to to do so. Any suggestion how to tackle this situation, along with
this can we make common routine of write_stderr() function that others use
it instead of defining their own ?.

Please do let me know if I missed something or more information is
required. Thanks.


On Mon, Mar 16, 2015 at 2:07 PM, Asif Naeem <anaeem.it@gmail.com> wrote:

> +1
>
> On Fri, Mar 13, 2015 at 4:32 AM, Michael Paquier <
> michael.paquier@gmail.com> wrote:
>
>> On Thu, Mar 12, 2015 at 11:45 PM, Alvaro Herrera
>> <alvherre@2ndquadrant.com> wrote:
>> > Michael Paquier wrote:
>> >> On Thu, Mar 12, 2015 at 6:50 AM, Alvaro Herrera
>> >> <alvherre@2ndquadrant.com> wrote:
>> >
>> >> > Is this a backpatchable bug fix, or are we considering this only for
>> the
>> >> > master branch?
>> >>
>> >> It would be good to get that backpatched, that's something we really
>> >> miss now IMO. Now it modifies libpgcommon, so Windows packagers (me
>> >> being one) will certainly need to patch a bit stuff but that's a
>> >> one-line changer so it's not a big deal. And I imagine that this is
>> >> actually the reason why Asif reported that as a bug as well.
>> >
>> > I think it'd be better to patch only pg_upgrade in back branches, so
>> > that there are no libpgcommon changes.  Seems that would make life
>> > easier for packagers (See the \connect thread, where Robert opined that
>> > it'd be better to duplicate some routines in back branches rather than
>> > refactor libpq code and move the common code to pgcommon.  I didn't
>> > completely agree with him at the time, but now that you mention
>> > packagers pain, maybe he has a point.)
>> >
>> > So let's do the refactoring in the master branch only, and duplicate
>> > the code in back branches.  Nasty, but it seems the more robust
>> > approach.
>>
>> This plan sounds fine to me.
>> --
>> Michael
>>
>
>

-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs

Attachments:

restricted_token.v3.patch (application/octet-stream, 30.4K) download diff --git a/contrib/pg_upgrade/pg_upgrade.c b/contrib/pg_upgrade/pg_upgrade.c index ed7de80..eb48da7 100644 --- a/contrib/pg_upgrade/pg_upgrade.c +++ b/contrib/pg_upgrade/pg_upgrade.c @@ -37,6 +37,7 @@ #include "postgres_fe.h" #include "pg_upgrade.h" +#include "common/restricted_token.h" #ifdef HAVE_LANGINFO_H #include <langinfo.h> @@ -75,6 +76,8 @@ main(int argc, char **argv) parseCommandLine(argc, argv); + get_restricted_token(os_info.progname); + adjust_data_dir(&old_cluster); adjust_data_dir(&new_cluster); diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c index 18614e7..b8abf19 100644 --- a/src/bin/initdb/initdb.c +++ b/src/bin/initdb/initdb.c @@ -62,6 +62,7 @@ #include "catalog/catalog.h" #include "common/username.h" +#include "common/restricted_token.h" #include "mb/pg_wchar.h" #include "getaddrinfo.h" #include "getopt_long.h" @@ -178,9 +179,6 @@ static char *authwarning = NULL; static const char *boot_options = "-F"; static const char *backend_options = "--single -F -O -c search_path=pg_catalog -c exit_on_error=true"; -#ifdef WIN32 -char *restrict_env; -#endif static const char *subdirs[] = { "global", "pg_xlog", @@ -260,7 +258,6 @@ static void check_locale_name(int category, const char *locale, static bool check_locale_encoding(const char *locale, int encoding); static void setlocales(void); static void usage(const char *progname); -void get_restricted_token(void); void setup_pgdata(void); void setup_bin_paths(const char *argv0); void setup_data_file_paths(void); @@ -272,12 +269,6 @@ void create_xlog_symlink(void); void warn_on_mount_point(int error); void initialize_data_directory(void); - -#ifdef WIN32 -static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo); -#endif - - /* * macros for running pipes to postgres */ @@ -2754,116 +2745,6 @@ setlocales(void) #endif } -#ifdef WIN32 -typedef BOOL (WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); - -/* Windows API define missing from some versions of MingW headers */ -#ifndef DISABLE_MAX_PRIVILEGE -#define DISABLE_MAX_PRIVILEGE 0x1 -#endif - -/* - * Create a restricted token and execute the specified process with it. - * - * Returns 0 on failure, non-zero on success, same as CreateProcess(). - * - * On NT4, or any other system not containing the required functions, will - * NOT execute anything. - */ -static int -CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo) -{ - BOOL b; - STARTUPINFO si; - HANDLE origToken; - HANDLE restrictedToken; - SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY}; - SID_AND_ATTRIBUTES dropSids[2]; - __CreateRestrictedToken _CreateRestrictedToken = NULL; - HANDLE Advapi32Handle; - - ZeroMemory(&si, sizeof(si)); - si.cb = sizeof(si); - - Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); - if (Advapi32Handle != NULL) - { - _CreateRestrictedToken = (__CreateRestrictedToken) GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); - } - - if (_CreateRestrictedToken == NULL) - { - fprintf(stderr, _("%s: WARNING: cannot create restricted tokens on this platform\n"), progname); - if (Advapi32Handle != NULL) - FreeLibrary(Advapi32Handle); - return 0; - } - - /* Open the current token to use as a base for the restricted one */ - if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) - { - fprintf(stderr, _("%s: could not open process token: error code %lu\n"), progname, GetLastError()); - return 0; - } - - /* Allocate list of SIDs to remove */ - ZeroMemory(&dropSids, sizeof(dropSids)); - if (!AllocateAndInitializeSid(&NtAuthority, 2, - SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, - 0, &dropSids[0].Sid) || - !AllocateAndInitializeSid(&NtAuthority, 2, - SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, - 0, &dropSids[1].Sid)) - { - fprintf(stderr, _("%s: could not allocate SIDs: error code %lu\n"), - progname, GetLastError()); - return 0; - } - - b = _CreateRestrictedToken(origToken, - DISABLE_MAX_PRIVILEGE, - sizeof(dropSids) / sizeof(dropSids[0]), - dropSids, - 0, NULL, - 0, NULL, - &restrictedToken); - - FreeSid(dropSids[1].Sid); - FreeSid(dropSids[0].Sid); - CloseHandle(origToken); - FreeLibrary(Advapi32Handle); - - if (!b) - { - fprintf(stderr, _("%s: could not create restricted token: error code %lu\n"), progname, GetLastError()); - return 0; - } - -#ifndef __CYGWIN__ - AddUserToTokenDacl(restrictedToken); -#endif - - if (!CreateProcessAsUser(restrictedToken, - NULL, - cmd, - NULL, - NULL, - TRUE, - CREATE_SUSPENDED, - NULL, - NULL, - &si, - processInfo)) - - { - fprintf(stderr, _("%s: could not start process for command \"%s\": error code %lu\n"), progname, cmd, GetLastError()); - return 0; - } - - return ResumeThread(processInfo->hThread); -} -#endif - /* * print help text */ @@ -2957,53 +2838,6 @@ check_need_password(const char *authmethodlocal, const char *authmethodhost) } } -void -get_restricted_token(void) -{ -#ifdef WIN32 - - /* - * Before we execute another program, make sure that we are running with a - * restricted token. If not, re-execute ourselves with one. - */ - - if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL - || strcmp(restrict_env, "1") != 0) - { - PROCESS_INFORMATION pi; - char *cmdline; - - ZeroMemory(&pi, sizeof(pi)); - - cmdline = pg_strdup(GetCommandLine()); - - putenv("PG_RESTRICT_EXEC=1"); - - if (!CreateRestrictedProcess(cmdline, &pi)) - { - fprintf(stderr, _("%s: could not re-execute with restricted token: error code %lu\n"), progname, GetLastError()); - } - else - { - /* - * Successfully re-execed. Now wait for child process to capture - * exitcode. - */ - DWORD x; - - CloseHandle(pi.hThread); - WaitForSingleObject(pi.hProcess, INFINITE); - - if (!GetExitCodeProcess(pi.hProcess, &x)) - { - fprintf(stderr, _("%s: could not get exit code from subprocess: error code %lu\n"), progname, GetLastError()); - exit(1); - } - exit(x); - } - } -#endif -} void setup_pgdata(void) @@ -3759,7 +3593,7 @@ main(int argc, char *argv[]) check_need_password(authmethodlocal, authmethodhost); - get_restricted_token(); + get_restricted_token(progname); setup_pgdata(); diff --git a/src/bin/pg_ctl/pg_ctl.c b/src/bin/pg_ctl/pg_ctl.c index 052caff..90daa1d 100644 --- a/src/bin/pg_ctl/pg_ctl.c +++ b/src/bin/pg_ctl/pg_ctl.c @@ -21,6 +21,7 @@ #include "libpq-fe.h" #include "pqexpbuffer.h" +#include "common/restricted_token.h" #include <fcntl.h> #include <locale.h> @@ -151,7 +152,8 @@ static void pgwin32_SetServiceStatus(DWORD); static void WINAPI pgwin32_ServiceHandler(DWORD); static void WINAPI pgwin32_ServiceMain(DWORD, LPTSTR *); static void pgwin32_doRunAsService(void); -static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, bool as_service); +static int AssignProcessToJob(PROCESS_INFORMATION *processInfo, + bool as_service, HANDLE restrictedToken); #endif static pgpid_t get_pgpid(bool is_status_request); @@ -454,6 +456,7 @@ start_postmaster(void) * it to handle redirection etc. */ PROCESS_INFORMATION pi; + HANDLE restrictedToken; if (log_file != NULL) snprintf(cmd, MAXPGPATH, "CMD /C \"\"%s\" %s%s < \"%s\" >> \"%s\" 2>&1\"", @@ -462,8 +465,9 @@ start_postmaster(void) snprintf(cmd, MAXPGPATH, "CMD /C \"\"%s\" %s%s < \"%s\" 2>&1\"", exec_path, pgdata_opt, post_opts, DEVNULL); - if (!CreateRestrictedProcess(cmd, &pi, false)) + if ((restrictedToken = CreateRestrictedProcess(cmd, &pi, progname)) == 0) return GetLastError(); + CloseHandle(restrictedToken); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); return 0; @@ -1548,6 +1552,7 @@ pgwin32_ServiceMain(DWORD argc, LPTSTR *argv) { PROCESS_INFORMATION pi; DWORD ret; + HANDLE restrictedToken; /* Initialize variables */ status.dwWin32ExitCode = S_OK; @@ -1571,14 +1576,18 @@ pgwin32_ServiceMain(DWORD argc, LPTSTR *argv) /* Start the postmaster */ pgwin32_SetServiceStatus(SERVICE_START_PENDING); - if (!CreateRestrictedProcess(pgwin32_CommandLine(false), &pi, true)) + if ((restrictedToken = + CreateRestrictedProcess(pgwin32_CommandLine(false), &pi, progname)) == 0) { pgwin32_SetServiceStatus(SERVICE_STOPPED); return; } + + AssignProcessToJob(&pi, true, restrictedToken); postmasterPID = pi.dwProcessId; postmasterProcess = pi.hProcess; CloseHandle(pi.hThread); + CloseHandle(restrictedToken); if (do_wait) { @@ -1647,125 +1656,27 @@ pgwin32_doRunAsService(void) * also load the couple of functions that *do* exist in minwg headers but not * on NT4. That way, we don't break on NT4. */ -typedef BOOL (WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); typedef BOOL (WINAPI * __IsProcessInJob) (HANDLE, HANDLE, PBOOL); typedef HANDLE (WINAPI * __CreateJobObject) (LPSECURITY_ATTRIBUTES, LPCTSTR); typedef BOOL (WINAPI * __SetInformationJobObject) (HANDLE, JOBOBJECTINFOCLASS, LPVOID, DWORD); typedef BOOL (WINAPI * __AssignProcessToJobObject) (HANDLE, HANDLE); typedef BOOL (WINAPI * __QueryInformationJobObject) (HANDLE, JOBOBJECTINFOCLASS, LPVOID, DWORD, LPDWORD); -/* Windows API define missing from some versions of MingW headers */ -#ifndef DISABLE_MAX_PRIVILEGE -#define DISABLE_MAX_PRIVILEGE 0x1 -#endif - /* - * Create a restricted token, a job object sandbox, and execute the specified - * process with it. - * - * Returns 0 on success, non-zero on failure, same as CreateProcess(). - * - * On NT4, or any other system not containing the required functions, will - * launch the process under the current token without doing any modifications. - * - * NOTE! Job object will only work when running as a service, because it's - * automatically destroyed when pg_ctl exits. + * Create a job object and associate the specified process with it. + * Returns 0 on failure, non-zero on success */ static int -CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, bool as_service) +AssignProcessToJob(PROCESS_INFORMATION *processInfo, bool as_service, HANDLE restrictedToken) { - int r; - BOOL b; - STARTUPINFO si; - HANDLE origToken; - HANDLE restrictedToken; - SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY}; - SID_AND_ATTRIBUTES dropSids[2]; - /* Functions loaded dynamically */ - __CreateRestrictedToken _CreateRestrictedToken = NULL; __IsProcessInJob _IsProcessInJob = NULL; __CreateJobObject _CreateJobObject = NULL; __SetInformationJobObject _SetInformationJobObject = NULL; __AssignProcessToJobObject _AssignProcessToJobObject = NULL; __QueryInformationJobObject _QueryInformationJobObject = NULL; HANDLE Kernel32Handle; - HANDLE Advapi32Handle; - - ZeroMemory(&si, sizeof(si)); - si.cb = sizeof(si); - - Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); - if (Advapi32Handle != NULL) - { - _CreateRestrictedToken = (__CreateRestrictedToken) GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); - } - - if (_CreateRestrictedToken == NULL) - { - /* - * NT4 doesn't have CreateRestrictedToken, so just call ordinary - * CreateProcess - */ - write_stderr(_("%s: WARNING: cannot create restricted tokens on this platform\n"), progname); - if (Advapi32Handle != NULL) - FreeLibrary(Advapi32Handle); - return CreateProcess(NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, processInfo); - } - - /* Open the current token to use as a base for the restricted one */ - if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) - { - /* - * Most Windows targets make DWORD a 32-bit unsigned long. Cygwin - * x86_64, an LP64 target, makes it a 32-bit unsigned int. In code - * built for Cygwin as well as for native Windows targets, cast DWORD - * before printing. - */ - write_stderr(_("%s: could not open process token: error code %lu\n"), - progname, (unsigned long) GetLastError()); - return 0; - } - - /* Allocate list of SIDs to remove */ - ZeroMemory(&dropSids, sizeof(dropSids)); - if (!AllocateAndInitializeSid(&NtAuthority, 2, - SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, - 0, &dropSids[0].Sid) || - !AllocateAndInitializeSid(&NtAuthority, 2, - SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, - 0, &dropSids[1].Sid)) - { - write_stderr(_("%s: could not allocate SIDs: error code %lu\n"), - progname, (unsigned long) GetLastError()); - return 0; - } - - b = _CreateRestrictedToken(origToken, - DISABLE_MAX_PRIVILEGE, - sizeof(dropSids) / sizeof(dropSids[0]), - dropSids, - 0, NULL, - 0, NULL, - &restrictedToken); - - FreeSid(dropSids[1].Sid); - FreeSid(dropSids[0].Sid); - CloseHandle(origToken); - FreeLibrary(Advapi32Handle); - - if (!b) - { - write_stderr(_("%s: could not create restricted token: error code %lu\n"), - progname, (unsigned long) GetLastError()); - return 0; - } - -#ifndef __CYGWIN__ - AddUserToTokenDacl(restrictedToken); -#endif - - r = CreateProcessAsUser(restrictedToken, NULL, cmd, NULL, NULL, TRUE, CREATE_SUSPENDED, NULL, NULL, &si, processInfo); + BOOL inJob; Kernel32Handle = LoadLibrary("KERNEL32.DLL"); if (Kernel32Handle != NULL) @@ -1777,97 +1688,77 @@ CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, bool as_ser _QueryInformationJobObject = (__QueryInformationJobObject) GetProcAddress(Kernel32Handle, "QueryInformationJobObject"); } - /* Verify that we found all functions */ - if (_IsProcessInJob == NULL || _CreateJobObject == NULL || _SetInformationJobObject == NULL || _AssignProcessToJobObject == NULL || _QueryInformationJobObject == NULL) + if (_IsProcessInJob(processInfo->hProcess, NULL, &inJob)) { - /* - * IsProcessInJob() is not available on < WinXP, so there is no need - * to log the error every time in that case - */ - if (IsWindowsXPOrGreater()) - + if (!inJob) + { /* - * Log error if we can't get version, or if we're on WinXP/2003 or - * newer + * Job objects are working, and the new process isn't in one, + * so we can create one safely. If any problems show up when + * setting it, we're going to ignore them. */ - write_stderr(_("%s: WARNING: could not locate all job object functions in system API\n"), progname); - } - else - { - BOOL inJob; + HANDLE job; + char jobname[128]; - if (_IsProcessInJob(processInfo->hProcess, NULL, &inJob)) - { - if (!inJob) - { - /* - * Job objects are working, and the new process isn't in one, - * so we can create one safely. If any problems show up when - * setting it, we're going to ignore them. - */ - HANDLE job; - char jobname[128]; - - sprintf(jobname, "PostgreSQL_%lu", - (unsigned long) processInfo->dwProcessId); + sprintf(jobname, "PostgreSQL_%lu", + (unsigned long) processInfo->dwProcessId); - job = _CreateJobObject(NULL, jobname); - if (job) - { - JOBOBJECT_BASIC_LIMIT_INFORMATION basicLimit; - JOBOBJECT_BASIC_UI_RESTRICTIONS uiRestrictions; - JOBOBJECT_SECURITY_LIMIT_INFORMATION securityLimit; + job = _CreateJobObject(NULL, jobname); + if (job) + { + JOBOBJECT_BASIC_LIMIT_INFORMATION basicLimit; + JOBOBJECT_BASIC_UI_RESTRICTIONS uiRestrictions; + JOBOBJECT_SECURITY_LIMIT_INFORMATION securityLimit; - ZeroMemory(&basicLimit, sizeof(basicLimit)); - ZeroMemory(&uiRestrictions, sizeof(uiRestrictions)); - ZeroMemory(&securityLimit, sizeof(securityLimit)); + ZeroMemory(&basicLimit, sizeof(basicLimit)); + ZeroMemory(&uiRestrictions, sizeof(uiRestrictions)); + ZeroMemory(&securityLimit, sizeof(securityLimit)); - basicLimit.LimitFlags = JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION | JOB_OBJECT_LIMIT_PRIORITY_CLASS; - basicLimit.PriorityClass = NORMAL_PRIORITY_CLASS; - _SetInformationJobObject(job, JobObjectBasicLimitInformation, &basicLimit, sizeof(basicLimit)); + basicLimit.LimitFlags = JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION | JOB_OBJECT_LIMIT_PRIORITY_CLASS; + basicLimit.PriorityClass = NORMAL_PRIORITY_CLASS; + _SetInformationJobObject(job, JobObjectBasicLimitInformation, &basicLimit, sizeof(basicLimit)); - uiRestrictions.UIRestrictionsClass = JOB_OBJECT_UILIMIT_DESKTOP | JOB_OBJECT_UILIMIT_DISPLAYSETTINGS | - JOB_OBJECT_UILIMIT_EXITWINDOWS | JOB_OBJECT_UILIMIT_READCLIPBOARD | - JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS | JOB_OBJECT_UILIMIT_WRITECLIPBOARD; + uiRestrictions.UIRestrictionsClass = JOB_OBJECT_UILIMIT_DESKTOP | JOB_OBJECT_UILIMIT_DISPLAYSETTINGS | + JOB_OBJECT_UILIMIT_EXITWINDOWS | JOB_OBJECT_UILIMIT_READCLIPBOARD | + JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS | JOB_OBJECT_UILIMIT_WRITECLIPBOARD; - if (as_service) + if (as_service) + { + if (!IsWindows7OrGreater()) { - if (!IsWindows7OrGreater()) - { - /* - * On Windows 7 (and presumably later), - * JOB_OBJECT_UILIMIT_HANDLES prevents us from - * starting as a service. So we only enable it on - * Vista and earlier (version <= 6.0) - */ - uiRestrictions.UIRestrictionsClass |= JOB_OBJECT_UILIMIT_HANDLES; - } + /* + * On Windows 7 (and presumably later), + * JOB_OBJECT_UILIMIT_HANDLES prevents us from + * starting as a service. So we only enable it on + * Vista and earlier (version <= 6.0) + */ + uiRestrictions.UIRestrictionsClass |= JOB_OBJECT_UILIMIT_HANDLES; } - _SetInformationJobObject(job, JobObjectBasicUIRestrictions, &uiRestrictions, sizeof(uiRestrictions)); + } + _SetInformationJobObject(job, JobObjectBasicUIRestrictions, &uiRestrictions, sizeof(uiRestrictions)); - securityLimit.SecurityLimitFlags = JOB_OBJECT_SECURITY_NO_ADMIN | JOB_OBJECT_SECURITY_ONLY_TOKEN; - securityLimit.JobToken = restrictedToken; - _SetInformationJobObject(job, JobObjectSecurityLimitInformation, &securityLimit, sizeof(securityLimit)); + securityLimit.SecurityLimitFlags = JOB_OBJECT_SECURITY_NO_ADMIN | JOB_OBJECT_SECURITY_ONLY_TOKEN; + securityLimit.JobToken = restrictedToken; + _SetInformationJobObject(job, JobObjectSecurityLimitInformation, &securityLimit, sizeof(securityLimit)); - _AssignProcessToJobObject(job, processInfo->hProcess); + if(!_AssignProcessToJobObject(job, processInfo->hProcess)) + { + write_stderr(_("%s: could not associate the process with a job object: error code %lu\n"), + progname, GetLastError()); + return 0; } } + else + { + write_stderr(_("%s: could not create job object: error code %lu\n"), + progname, GetLastError()); + return 0; + } } } - - - CloseHandle(restrictedToken); - - ResumeThread(processInfo->hThread); - - FreeLibrary(Kernel32Handle); - - /* - * We intentionally don't close the job object handle, because we want the - * object to live on until pg_ctl shuts down. - */ - return r; + return 1; } + #endif /* defined(WIN32) || defined(__CYGWIN__) */ static void diff --git a/src/bin/pg_resetxlog/pg_resetxlog.c b/src/bin/pg_resetxlog/pg_resetxlog.c index a16089f..3361111 100644 --- a/src/bin/pg_resetxlog/pg_resetxlog.c +++ b/src/bin/pg_resetxlog/pg_resetxlog.c @@ -53,6 +53,7 @@ #include "catalog/catversion.h" #include "catalog/pg_control.h" #include "common/fe_memutils.h" +#include "common/restricted_token.h" #include "storage/large_object.h" #include "pg_getopt.h" @@ -310,6 +311,8 @@ main(int argc, char *argv[]) } #endif + get_restricted_token(progname); + if (chdir(DataDir) < 0) { fprintf(stderr, _("%s: could not change directory to \"%s\": %s\n"), diff --git a/src/common/Makefile b/src/common/Makefile index c71415e..c2e456d 100644 --- a/src/common/Makefile +++ b/src/common/Makefile @@ -26,7 +26,7 @@ LIBS += $(PTHREAD_LIBS) OBJS_COMMON = exec.o pg_crc.o pg_lzcompress.o pgfnames.o psprintf.o relpath.o \ rmtree.o string.o username.o wait_error.o -OBJS_FRONTEND = $(OBJS_COMMON) fe_memutils.o +OBJS_FRONTEND = $(OBJS_COMMON) fe_memutils.o restricted_token.o OBJS_SRV = $(OBJS_COMMON:%.o=%_srv.o) diff --git a/src/test/regress/pg_regress.c b/src/test/regress/pg_regress.c index 9d4fb9a..dc910b0 100644 --- a/src/test/regress/pg_regress.c +++ b/src/test/regress/pg_regress.c @@ -30,6 +30,7 @@ #endif #include "common/username.h" +#include "common/restricted_token.h" #include "getopt_long.h" #include "libpq/pqcomm.h" /* needed for UNIXSOCK_PATH() */ #include "pg_config_paths.h" @@ -147,15 +148,6 @@ psql_command(const char *database, const char *query,...) the supplied arguments. */ pg_attribute_printf(2, 3); -#ifdef WIN32 -typedef BOOL (WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); - -/* Windows API define missing from some versions of MingW headers */ -#ifndef DISABLE_MAX_PRIVILEGE -#define DISABLE_MAX_PRIVILEGE 0x1 -#endif -#endif - /* * allow core files if possible. */ @@ -1238,100 +1230,17 @@ spawn_process(const char *cmdline) /* in parent */ return pid; #else - char *cmdline2; - BOOL b; - STARTUPINFO si; - PROCESS_INFORMATION pi; - HANDLE origToken; - HANDLE restrictedToken; - SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY}; - SID_AND_ATTRIBUTES dropSids[2]; - __CreateRestrictedToken _CreateRestrictedToken = NULL; - HANDLE Advapi32Handle; - - ZeroMemory(&si, sizeof(si)); - si.cb = sizeof(si); - - Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); - if (Advapi32Handle != NULL) - { - _CreateRestrictedToken = (__CreateRestrictedToken) GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); - } - - if (_CreateRestrictedToken == NULL) - { - if (Advapi32Handle != NULL) - FreeLibrary(Advapi32Handle); - fprintf(stderr, _("%s: cannot create restricted tokens on this platform\n"), - progname); - exit(2); - } - - /* Open the current token to use as base for the restricted one */ - if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) - { - fprintf(stderr, _("could not open process token: error code %lu\n"), - GetLastError()); - exit(2); - } - - /* Allocate list of SIDs to remove */ - ZeroMemory(&dropSids, sizeof(dropSids)); - if (!AllocateAndInitializeSid(&NtAuthority, 2, - SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &dropSids[0].Sid) || - !AllocateAndInitializeSid(&NtAuthority, 2, - SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, 0, &dropSids[1].Sid)) - { - fprintf(stderr, _("could not allocate SIDs: error code %lu\n"), GetLastError()); - exit(2); - } - - b = _CreateRestrictedToken(origToken, - DISABLE_MAX_PRIVILEGE, - sizeof(dropSids) / sizeof(dropSids[0]), - dropSids, - 0, NULL, - 0, NULL, - &restrictedToken); - - FreeSid(dropSids[1].Sid); - FreeSid(dropSids[0].Sid); - CloseHandle(origToken); - FreeLibrary(Advapi32Handle); - - if (!b) - { - fprintf(stderr, _("could not create restricted token: error code %lu\n"), - GetLastError()); - exit(2); - } + PROCESS_INFORMATION pi; + char *cmdline2; + HANDLE restrictedToken; + memset(&pi, 0, sizeof(pi)); cmdline2 = psprintf("cmd /c \"%s\"", cmdline); -#ifndef __CYGWIN__ - AddUserToTokenDacl(restrictedToken); -#endif - - if (!CreateProcessAsUser(restrictedToken, - NULL, - cmdline2, - NULL, - NULL, - TRUE, - CREATE_SUSPENDED, - NULL, - NULL, - &si, - &pi)) - { - fprintf(stderr, _("could not start process for \"%s\": error code %lu\n"), - cmdline2, GetLastError()); + if((restrictedToken = + CreateRestrictedProcess(cmdline2, &pi, progname)) == 0) exit(2); - } - - free(cmdline2); - ResumeThread(pi.hThread); CloseHandle(pi.hThread); return pi.hProcess; #endif diff --git a/src/tools/msvc/Mkvcbuild.pm b/src/tools/msvc/Mkvcbuild.pm index 989a2ec..9c52a46 100644 --- a/src/tools/msvc/Mkvcbuild.pm +++ b/src/tools/msvc/Mkvcbuild.pm @@ -95,7 +95,8 @@ sub mkvcbuild exec.c pg_crc.c pg_lzcompress.c pgfnames.c psprintf.c relpath.c rmtree.c string.c username.c wait_error.c); - our @pgcommonfrontendfiles = (@pgcommonallfiles, qw(fe_memutils.c)); + our @pgcommonfrontendfiles = (@pgcommonallfiles, qw(fe_memutils.c + restricted_token.c)); our @pgcommonbkndfiles = @pgcommonallfiles; diff --git a/src/common/restricted_token.c b/src/common/restricted_token.c new file mode 100644 index 0000000..6425517 --- /dev/null +++ b/src/common/restricted_token.c @@ -0,0 +1,196 @@ +/*------------------------------------------------------------------------- + * + * restricted_token.c + * helper routine to ensure restricted token on Windows + * + * + * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * + * IDENTIFICATION + * src/common/restricted_token.c + * + *------------------------------------------------------------------------- + */ + +#ifndef FRONTEND +#error "This file is not expected to be compiled for backend code" +#endif + +#include "postgres_fe.h" + +#include "common/restricted_token.h" + +#define write_stderr(fmt, ...) fprintf(stderr, fmt, __VA_ARGS__) + +#ifdef WIN32 + +/* internal vars */ +char *restrict_env; + +typedef BOOL (WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); + +/* Windows API define missing from some versions of MingW headers */ +#ifndef DISABLE_MAX_PRIVILEGE +#define DISABLE_MAX_PRIVILEGE 0x1 +#endif + +/* + * Create a restricted token and execute the specified process with it. + * + * Returns restricted token on success and 0 on failure. + * + * On NT4, or any other system not containing the required functions, will + * NOT execute anything. + */ +HANDLE +CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, const char *progname) +{ + BOOL b; + STARTUPINFO si; + HANDLE origToken; + HANDLE restrictedToken; + SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY}; + SID_AND_ATTRIBUTES dropSids[2]; + __CreateRestrictedToken _CreateRestrictedToken = NULL; + HANDLE Advapi32Handle; + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + + Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); + if (Advapi32Handle != NULL) + { + _CreateRestrictedToken = (__CreateRestrictedToken) GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); + } + + if (_CreateRestrictedToken == NULL) + { + write_stderr(_("%s: WARNING: cannot create restricted tokens on this platform\n"), progname); + if (Advapi32Handle != NULL) + FreeLibrary(Advapi32Handle); + return 0; + } + + /* Open the current token to use as a base for the restricted one */ + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) + { + write_stderr(_("%s: could not open process token: error code %lu\n"), progname, GetLastError()); + return 0; + } + + /* Allocate list of SIDs to remove */ + ZeroMemory(&dropSids, sizeof(dropSids)); + if (!AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, + 0, &dropSids[0].Sid) || + !AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, + 0, &dropSids[1].Sid)) + { + write_stderr(_("%s: could not allocate SIDs: error code %lu\n"), + progname, GetLastError()); + return 0; + } + + b = _CreateRestrictedToken(origToken, + DISABLE_MAX_PRIVILEGE, + sizeof(dropSids) / sizeof(dropSids[0]), + dropSids, + 0, NULL, + 0, NULL, + &restrictedToken); + + FreeSid(dropSids[1].Sid); + FreeSid(dropSids[0].Sid); + CloseHandle(origToken); + FreeLibrary(Advapi32Handle); + + if (!b) + { + write_stderr(_("%s: could not create restricted token: error code %lu\n"), + progname, GetLastError()); + return 0; + } + +#ifndef __CYGWIN__ + AddUserToTokenDacl(restrictedToken); +#endif + + if (!CreateProcessAsUser(restrictedToken, + NULL, + cmd, + NULL, + NULL, + TRUE, + CREATE_SUSPENDED, + NULL, + NULL, + &si, + processInfo)) + + { + write_stderr(_("%s: could not start process for command \"%s\": error code %lu\n"), progname, cmd, GetLastError()); + return 0; + } + + ResumeThread(processInfo->hThread); + return restrictedToken; +} +#endif + +/* + * On Windows make sure that we are running with a restricted token, + * On other platforms do nothing. + */ + +void +get_restricted_token(const char *progname) +{ +#ifdef WIN32 + HANDLE restrictedToken; + + /* + * Before we execute another program, make sure that we are running with a + * restricted token. If not, re-execute ourselves with one. + */ + + if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL + || strcmp(restrict_env, "1") != 0) + { + PROCESS_INFORMATION pi; + char *cmdline; + + ZeroMemory(&pi, sizeof(pi)); + + cmdline = pg_strdup(GetCommandLine()); + + putenv("PG_RESTRICT_EXEC=1"); + + if ((restrictedToken = CreateRestrictedProcess(cmdline, &pi, progname)) == 0) + { + write_stderr(_("%s: could not re-execute with restricted token: error code %lu\n"), progname, GetLastError()); + } + else + { + /* + * Successfully re-execed. Now wait for child process to capture + * exitcode. + */ + DWORD x; + + CloseHandle(restrictedToken); + CloseHandle(pi.hThread); + WaitForSingleObject(pi.hProcess, INFINITE); + + if (!GetExitCodeProcess(pi.hProcess, &x)) + { + write_stderr(_("%s: could not get exit code from subprocess: error code %lu\n"), progname, GetLastError()); + exit(1); + } + exit(x); + } + } +#endif +} diff --git a/src/include/common/restricted_token.h b/src/include/common/restricted_token.h new file mode 100644 index 0000000..5cdf38e --- /dev/null +++ b/src/include/common/restricted_token.h @@ -0,0 +1,23 @@ +/* + * restricted_token.h + * helper routine to ensure restricted token on Windows + * + * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * src/include/common/restricted_token.h + */ +#ifndef COMMON_RESTRICTED_TOKEN_H +#define COMMON_RESTRICTED_TOKEN_H + +/* + * On Windows make sure that we are running with a restricted token, + * On other platforms do nothing. + */ +void get_restricted_token(const char *progname); + + +/* Create a restricted token and execute the specified process with it. */ +HANDLE CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, const char *progname); + +#endif /* COMMON_RESTRICTED_TOKEN_H */
^ permalink raw reply [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-03-18 00:57  Michael Paquier <michael.paquier@gmail.com>
  parent: Asif Naeem <anaeem.it@gmail.com>
  0 siblings, 1 reply; 35+ messages in thread

From: Michael Paquier @ 2015-03-18 00:57 UTC (permalink / raw)
  To: Asif Naeem <anaeem.it@gmail.com>; +Cc: Alvaro Herrera <alvherre@2ndquadrant.com>; Amit Kapila <amit.kapila16@gmail.com>; Bruce Momjian <bruce@momjian.us>; pgsql-bugs

On Wed, Mar 18, 2015 at 5:15 AM, Asif Naeem <anaeem.it@gmail.com> wrote:
> Thank you for useful suggestions, PFA patch, for pg_ctl.c and pg_regress.c
> it relies on CreateRestrictedProcess() function now.

Thanks for the updated version.

> src/common/restricted_token.c
>>
>>      #define write_stderr(fmt, ...) fprintf(stderr, fmt, __VA_ARGS__)

Oops, I forgot this stuff with pg_ctl. It is not nice to duplicate
this declaration in restricted_token.c.

> security.c write_stderr() implementation seems correct, that relies on
> pgwin32_is_service() function but it seems little expensive operation to
> write error messages. pg_ctl.c write_stderr() implementation depend on
> isatty() to detect if it is running as service, I doubt that if it is right
> way to to do so. Any suggestion how to tackle this situation, along with
> this can we make common routine of write_stderr() function that others use
> it instead of defining their own?

I think that we should rip out the dependency with write_stderr and
have get_restricted_token return a state code instead, with something
like that:
typedef enum RestrictedTokenState
{
     PG_RESTRICTED_TOKEN_OK = 0,
     PG_RESTRICTED_TOKEN_FAIL_EXECUTE,
     PG_RESTRICTED_TOKEN_ERROR_PLATFORM,
     [...]
} RestrictedTokenState;

Using that, caller can simply error out something with the error code.
We could have some documentation as well about that... But let's get
the code nicely done first.

> Please do let me know if I missed something or more information is required.

Some more comments:

I am getting a compilation failure when compiling on a non-Windows environment:
Configured with: --prefix=/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
In file included from restricted_token.c:23:
../../src/include/common/restricted_token.h:21:1: error: unknown type
name 'HANDLE'
HANDLE  CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION
*processInfo, const char *progname);
^
../../src/include/common/restricted_token.h:21:43: error: unknown type
name 'PROCESS_INFORMATION'
HANDLE  CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION
*processInfo, const char *progname);
                                           ^
2 errors generated.
make[2]: *** [restricted_token.o] Error 1
make[2]: *** Waiting for unfinished jobs....
make[1]: *** [all-common-recurse] Error 2
make: *** [all-src-recurse] Error 2

This is generated because CreateRestrictedProcess is missing #ifdef
WIN32 in restricted_token.h.

 #include "common/username.h"
+#include "common/restricted_token.h"
Be careful of the include file ordering.

It seems backward to me to make CreateRestrictedProcess available in
restricted_token.h. What I got in mind first was a common API like
this one for all the callers:
get_restricted_token(const char *progname, const char *cmd, bool no_wait);
no_wait controlling WaitForSingleObject() in get_restricted_token.

On top of that, it seems useful to me to use PG_RESTRICT_EXEC to
ensure that we do not try twice to get a token when we already have
one.
Regards,
-- 
Michael


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-03-18 06:50  Asif Naeem <anaeem.it@gmail.com>
  parent: Michael Paquier <michael.paquier@gmail.com>
  0 siblings, 1 reply; 35+ messages in thread

From: Asif Naeem @ 2015-03-18 06:50 UTC (permalink / raw)
  To: Michael Paquier <michael.paquier@gmail.com>; +Cc: Alvaro Herrera <alvherre@2ndquadrant.com>; Amit Kapila <amit.kapila16@gmail.com>; Bruce Momjian <bruce@momjian.us>; pgsql-bugs

Thank you Michael.

On Wed, Mar 18, 2015 at 5:57 AM, Michael Paquier <michael.paquier@gmail.com>
wrote:

> On Wed, Mar 18, 2015 at 5:15 AM, Asif Naeem <anaeem.it@gmail.com> wrote:
> > Thank you for useful suggestions, PFA patch, for pg_ctl.c and
> pg_regress.c
> > it relies on CreateRestrictedProcess() function now.
>
> Thanks for the updated version.
>
> > src/common/restricted_token.c
> >>
> >>      #define write_stderr(fmt, ...) fprintf(stderr, fmt, __VA_ARGS__)
>
> Oops, I forgot this stuff with pg_ctl. It is not nice to duplicate
> this declaration in restricted_token.c.
>
> > security.c write_stderr() implementation seems correct, that relies on
> > pgwin32_is_service() function but it seems little expensive operation to
> > write error messages. pg_ctl.c write_stderr() implementation depend on
> > isatty() to detect if it is running as service, I doubt that if it is
> right
> > way to to do so. Any suggestion how to tackle this situation, along with
> > this can we make common routine of write_stderr() function that others
> use
> > it instead of defining their own?
>
> I think that we should rip out the dependency with write_stderr and
> have get_restricted_token return a state code instead, with something
> like that:
> typedef enum RestrictedTokenState
> {
>      PG_RESTRICTED_TOKEN_OK = 0,
>      PG_RESTRICTED_TOKEN_FAIL_EXECUTE,
>      PG_RESTRICTED_TOKEN_ERROR_PLATFORM,
>      [...]
> } RestrictedTokenState;
>
> Using that, caller can simply error out something with the error code.
> We could have some documentation as well about that... But let's get
> the code nicely done first.
>
> > Please do let me know if I missed something or more information is
> required.
>
> Some more comments:
>
> I am getting a compilation failure when compiling on a non-Windows
> environment:
> Configured with: --prefix=/usr
> --with-gxx-include-dir=/usr/include/c++/4.2.1
> In file included from restricted_token.c:23:
> ../../src/include/common/restricted_token.h:21:1: error: unknown type
> name 'HANDLE'
> HANDLE  CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION
> *processInfo, const char *progname);
> ^
> ../../src/include/common/restricted_token.h:21:43: error: unknown type
> name 'PROCESS_INFORMATION'
> HANDLE  CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION
> *processInfo, const char *progname);
>                                            ^
> 2 errors generated.
> make[2]: *** [restricted_token.o] Error 1
> make[2]: *** Waiting for unfinished jobs....
> make[1]: *** [all-common-recurse] Error 2
> make: *** [all-src-recurse] Error 2
>
> This is generated because CreateRestrictedProcess is missing #ifdef
> WIN32 in restricted_token.h.
>

Oops. Sorry I missed that.


>  #include "common/username.h"
> +#include "common/restricted_token.h"
> Be careful of the include file ordering.
>
> It seems backward to me to make CreateRestrictedProcess available in
> restricted_token.h. What I got in mind first was a common API like
> this one for all the callers:
> get_restricted_token(const char *progname, const char *cmd, bool no_wait);
> no_wait controlling WaitForSingleObject() in get_restricted_token.
>
> On top of that, it seems useful to me to use PG_RESTRICT_EXEC to
> ensure that we do not try twice to get a token when we already have
> one.
>

At the moment there is a need to use restricted process logic in pg_regress
and pg_ctl in the following functions i.e.

src/test/regress/pg_regress.c

> /*
>  * Spawn a process to execute the given shell command; don't wait for it
>  *
>  * Returns the process ID (or HANDLE) so we can wait for it later
>  */
> PID_TYPE
> spawn_process(const char *cmdline)
> {
> ..
>

src/bin/pg_ctl/pg_ctl.c

> static void WINAPI
> pgwin32_ServiceMain(DWORD argc, LPTSTR *argv)
> {
> ..
>

src/bin/pg_ctl/pg_ctl.c

> /*
>  * start/test/stop routines
>  */
> static int
> start_postmaster(void)
> {
> ...
>

If spawn_process() is going to use get_restricted_token probably we need to
change its name too.

For pg_ctl and pg_regress, I tried to refactor only related code that
CreateRestrictedProcess was already doing so I thought to use it for these
utilities. Please do let me know if I missed something, Is it not going to
be more complicated if we use get_restricted_token/PG_RESTRICT_EXEC logic
there ?, at the moment get_restricted_token implementation seems like
re-execute ourselves with restricted token and exit as child process
terminates, If we want to change it to execute an another program with
restricted token, is't there a need to change it’s name to more descriptive
one ?. If we depend on PG_RESTRICT_EXEC environment variable execute once
logic, what if any of the parent program already ran
get_restricted_token(), e.g. pg_upgrade internally run pg_ctl ?

Please do let me know if I missed something or more information is
required. Thanks.

Regards,
> --
> Michael
>

^ permalink  raw  reply  [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-03-18 08:09  Michael Paquier <michael.paquier@gmail.com>
  parent: Asif Naeem <anaeem.it@gmail.com>
  0 siblings, 1 reply; 35+ messages in thread

From: Michael Paquier @ 2015-03-18 08:09 UTC (permalink / raw)
  To: Asif Naeem <anaeem.it@gmail.com>; +Cc: Alvaro Herrera <alvherre@2ndquadrant.com>; Amit Kapila <amit.kapila16@gmail.com>; Bruce Momjian <bruce@momjian.us>; pgsql-bugs

On Wed, Mar 18, 2015 at 3:50 PM, Asif Naeem wrote:
> If spawn_process() is going to use get_restricted_token probably we need to
> change its name too.
>
> For pg_ctl and pg_regress, I tried to refactor only related code that
> CreateRestrictedProcess was already doing so I thought to use it for these
> utilities. Please do let me know if I missed something, Is it not going to
> be more complicated if we use get_restricted_token/PG_RESTRICT_EXEC logic
> there ?, at the moment get_restricted_token implementation seems like
> re-execute ourselves with restricted token and exit as child process
> terminates, If we want to change it to execute an another program with
> restricted token, is't there a need to change it's name to more descriptive
> one ?. If we depend on PG_RESTRICT_EXEC environment variable execute once
> logic, what if any of the parent program already ran get_restricted_token(),
> e.g. pg_upgrade internally run pg_ctl ?

I have been poking at this patch for a couple of hours more
seriously... And yes I concur with your analysis that this may
complicate more the logic pg_ctl.c, and that PG_RESTRICT_EXEC may
interact badly with pg_ctl.

Also, I had a look at the stuff around write_stderr, trying to take it
using two approaches:
1) First using some status code as return value of
get_restricted_token and CreateRestrictedToken (total of 7 error
codes), but this is as well proving to be ugly, and would make the
user lose a lot of useful information about the error that happened
and is now flushed to stderr
2) Add write_stderr in libpqcommon, this is proving to be rather ugly
as this has a dependency with write_console in elog.c... (Note that
initdb has a local macro write_stderr)
So that's a bit disappointing, and we have a real problem with your
patch because reports related to restricted tokens are not written to
the event log when running PG instance as a service.

By the way, while reading your patch I found an additional issue, this
check has been removed:
-       /* Verify that we found all functions */
-       if (_IsProcessInJob == NULL || _CreateJobObject == NULL ||
_SetInformationJobObject == NULL || _AssignProcessToJobObject == NULL
|| _QueryInformationJobObject == NULL)
Because of this stuff removed process may crash if one or more
functions are not found.

After the stuff with LoadLibrary("KERNEL32.DLL"); simply write a
report to write_stderr and return if one of those functions is
missing, with the magic of IsWindowsXPOrGreater included of course.

Could you fix this with the ifdef WIN32 missing in restricted_token.h?

Now, after looking closely at this stuff, an option that we could
consider is dropping pg_ctl from the refactoring because what it does
is too low-level and even if pg_ctl uses restricted tokens, it does
not expect to have PG_RESTRICT_TOKEN set. So perhaps we could rename
restricted_token to something like env_restrict_token and mention in
the comments that PG_RESTRICT_TOKEN is at the center of the logic,
preventing the creation of a new token if process has already one.
Thoughts?

Regards,
-- 
Michael


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-03-18 21:42  Asif Naeem <anaeem.it@gmail.com>
  parent: Michael Paquier <michael.paquier@gmail.com>
  0 siblings, 2 replies; 35+ messages in thread

From: Asif Naeem @ 2015-03-18 21:42 UTC (permalink / raw)
  To: Michael Paquier <michael.paquier@gmail.com>; +Cc: Alvaro Herrera <alvherre@2ndquadrant.com>; Amit Kapila <amit.kapila16@gmail.com>; Bruce Momjian <bruce@momjian.us>; pgsql-bugs

On Wed, Mar 18, 2015 at 1:09 PM, Michael Paquier <michael.paquier@gmail.com>
wrote:

> On Wed, Mar 18, 2015 at 3:50 PM, Asif Naeem wrote:
> > If spawn_process() is going to use get_restricted_token probably we need
> to
> > change its name too.
> >
> > For pg_ctl and pg_regress, I tried to refactor only related code that
> > CreateRestrictedProcess was already doing so I thought to use it for
> these
> > utilities. Please do let me know if I missed something, Is it not going
> to
> > be more complicated if we use get_restricted_token/PG_RESTRICT_EXEC logic
> > there ?, at the moment get_restricted_token implementation seems like
> > re-execute ourselves with restricted token and exit as child process
> > terminates, If we want to change it to execute an another program with
> > restricted token, is't there a need to change it's name to more
> descriptive
> > one ?. If we depend on PG_RESTRICT_EXEC environment variable execute once
> > logic, what if any of the parent program already ran
> get_restricted_token(),
> > e.g. pg_upgrade internally run pg_ctl ?
>
> I have been poking at this patch for a couple of hours more
> seriously... And yes I concur with your analysis that this may
> complicate more the logic pg_ctl.c, and that PG_RESTRICT_EXEC may
> interact badly with pg_ctl.
>
> Also, I had a look at the stuff around write_stderr, trying to take it
> using two approaches:
> 1) First using some status code as return value of
> get_restricted_token and CreateRestrictedToken (total of 7 error
> codes), but this is as well proving to be ugly, and would make the
> user lose a lot of useful information about the error that happened
> and is now flushed to stderr
> 2) Add write_stderr in libpqcommon, this is proving to be rather ugly
> as this has a dependency with write_console in elog.c... (Note that
> initdb has a local macro write_stderr)
> So that's a bit disappointing, and we have a real problem with your
> patch because reports related to restricted tokens are not written to
> the event log when running PG instance as a service.
>
> By the way, while reading your patch I found an additional issue, this
> check has been removed:
> -       /* Verify that we found all functions */
> -       if (_IsProcessInJob == NULL || _CreateJobObject == NULL ||
> _SetInformationJobObject == NULL || _AssignProcessToJobObject == NULL
> || _QueryInformationJobObject == NULL)
> Because of this stuff removed process may crash if one or more
> functions are not found.
>

Oops, good catch.


> After the stuff with LoadLibrary("KERNEL32.DLL"); simply write a
> report to write_stderr and return if one of those functions is
> missing, with the magic of IsWindowsXPOrGreater included of course.
>
> Could you fix this with the ifdef WIN32 missing in restricted_token.h?
>

Done.

Now, after looking closely at this stuff, an option that we could
> consider is dropping pg_ctl from the refactoring because what it does
> is too low-level and even if pg_ctl uses restricted tokens, it does
> not expect to have PG_RESTRICT_TOKEN set. So perhaps we could rename
> restricted_token to something like env_restrict_token and mention in
> the comments that PG_RESTRICT_TOKEN is at the center of the logic,
> preventing the creation of a new token if process has already one.
> Thoughts?
>

I do agree, pg_ctl refactoring is making current patch more complicated,
eventually we can come up with robust patch that include pg_ctl but result
patch could be big and touching lot of areas, I doubt that if such
complicated and big patch going to make its way into the repository. It
seems appropriate to do incremental work, we can refactor pg_ctl changes as
next effort. PFA update patch, it removes pg_ctl related code changes.
Please do let me know if I missed something. Thanks.


> Regards,
> --
> Michael
>

-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs

Attachments:

restricted_token.v4.patch (application/octet-stream, 17.8K) download diff --git a/contrib/pg_upgrade/pg_upgrade.c b/contrib/pg_upgrade/pg_upgrade.c index ed7de80..eb48da7 100644 --- a/contrib/pg_upgrade/pg_upgrade.c +++ b/contrib/pg_upgrade/pg_upgrade.c @@ -37,6 +37,7 @@ #include "postgres_fe.h" #include "pg_upgrade.h" +#include "common/restricted_token.h" #ifdef HAVE_LANGINFO_H #include <langinfo.h> @@ -75,6 +76,8 @@ main(int argc, char **argv) parseCommandLine(argc, argv); + get_restricted_token(os_info.progname); + adjust_data_dir(&old_cluster); adjust_data_dir(&new_cluster); diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c index 18614e7..b8abf19 100644 --- a/src/bin/initdb/initdb.c +++ b/src/bin/initdb/initdb.c @@ -62,6 +62,7 @@ #include "catalog/catalog.h" #include "common/username.h" +#include "common/restricted_token.h" #include "mb/pg_wchar.h" #include "getaddrinfo.h" #include "getopt_long.h" @@ -178,9 +179,6 @@ static char *authwarning = NULL; static const char *boot_options = "-F"; static const char *backend_options = "--single -F -O -c search_path=pg_catalog -c exit_on_error=true"; -#ifdef WIN32 -char *restrict_env; -#endif static const char *subdirs[] = { "global", "pg_xlog", @@ -260,7 +258,6 @@ static void check_locale_name(int category, const char *locale, static bool check_locale_encoding(const char *locale, int encoding); static void setlocales(void); static void usage(const char *progname); -void get_restricted_token(void); void setup_pgdata(void); void setup_bin_paths(const char *argv0); void setup_data_file_paths(void); @@ -272,12 +269,6 @@ void create_xlog_symlink(void); void warn_on_mount_point(int error); void initialize_data_directory(void); - -#ifdef WIN32 -static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo); -#endif - - /* * macros for running pipes to postgres */ @@ -2754,116 +2745,6 @@ setlocales(void) #endif } -#ifdef WIN32 -typedef BOOL (WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); - -/* Windows API define missing from some versions of MingW headers */ -#ifndef DISABLE_MAX_PRIVILEGE -#define DISABLE_MAX_PRIVILEGE 0x1 -#endif - -/* - * Create a restricted token and execute the specified process with it. - * - * Returns 0 on failure, non-zero on success, same as CreateProcess(). - * - * On NT4, or any other system not containing the required functions, will - * NOT execute anything. - */ -static int -CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo) -{ - BOOL b; - STARTUPINFO si; - HANDLE origToken; - HANDLE restrictedToken; - SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY}; - SID_AND_ATTRIBUTES dropSids[2]; - __CreateRestrictedToken _CreateRestrictedToken = NULL; - HANDLE Advapi32Handle; - - ZeroMemory(&si, sizeof(si)); - si.cb = sizeof(si); - - Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); - if (Advapi32Handle != NULL) - { - _CreateRestrictedToken = (__CreateRestrictedToken) GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); - } - - if (_CreateRestrictedToken == NULL) - { - fprintf(stderr, _("%s: WARNING: cannot create restricted tokens on this platform\n"), progname); - if (Advapi32Handle != NULL) - FreeLibrary(Advapi32Handle); - return 0; - } - - /* Open the current token to use as a base for the restricted one */ - if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) - { - fprintf(stderr, _("%s: could not open process token: error code %lu\n"), progname, GetLastError()); - return 0; - } - - /* Allocate list of SIDs to remove */ - ZeroMemory(&dropSids, sizeof(dropSids)); - if (!AllocateAndInitializeSid(&NtAuthority, 2, - SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, - 0, &dropSids[0].Sid) || - !AllocateAndInitializeSid(&NtAuthority, 2, - SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, - 0, &dropSids[1].Sid)) - { - fprintf(stderr, _("%s: could not allocate SIDs: error code %lu\n"), - progname, GetLastError()); - return 0; - } - - b = _CreateRestrictedToken(origToken, - DISABLE_MAX_PRIVILEGE, - sizeof(dropSids) / sizeof(dropSids[0]), - dropSids, - 0, NULL, - 0, NULL, - &restrictedToken); - - FreeSid(dropSids[1].Sid); - FreeSid(dropSids[0].Sid); - CloseHandle(origToken); - FreeLibrary(Advapi32Handle); - - if (!b) - { - fprintf(stderr, _("%s: could not create restricted token: error code %lu\n"), progname, GetLastError()); - return 0; - } - -#ifndef __CYGWIN__ - AddUserToTokenDacl(restrictedToken); -#endif - - if (!CreateProcessAsUser(restrictedToken, - NULL, - cmd, - NULL, - NULL, - TRUE, - CREATE_SUSPENDED, - NULL, - NULL, - &si, - processInfo)) - - { - fprintf(stderr, _("%s: could not start process for command \"%s\": error code %lu\n"), progname, cmd, GetLastError()); - return 0; - } - - return ResumeThread(processInfo->hThread); -} -#endif - /* * print help text */ @@ -2957,53 +2838,6 @@ check_need_password(const char *authmethodlocal, const char *authmethodhost) } } -void -get_restricted_token(void) -{ -#ifdef WIN32 - - /* - * Before we execute another program, make sure that we are running with a - * restricted token. If not, re-execute ourselves with one. - */ - - if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL - || strcmp(restrict_env, "1") != 0) - { - PROCESS_INFORMATION pi; - char *cmdline; - - ZeroMemory(&pi, sizeof(pi)); - - cmdline = pg_strdup(GetCommandLine()); - - putenv("PG_RESTRICT_EXEC=1"); - - if (!CreateRestrictedProcess(cmdline, &pi)) - { - fprintf(stderr, _("%s: could not re-execute with restricted token: error code %lu\n"), progname, GetLastError()); - } - else - { - /* - * Successfully re-execed. Now wait for child process to capture - * exitcode. - */ - DWORD x; - - CloseHandle(pi.hThread); - WaitForSingleObject(pi.hProcess, INFINITE); - - if (!GetExitCodeProcess(pi.hProcess, &x)) - { - fprintf(stderr, _("%s: could not get exit code from subprocess: error code %lu\n"), progname, GetLastError()); - exit(1); - } - exit(x); - } - } -#endif -} void setup_pgdata(void) @@ -3759,7 +3593,7 @@ main(int argc, char *argv[]) check_need_password(authmethodlocal, authmethodhost); - get_restricted_token(); + get_restricted_token(progname); setup_pgdata(); diff --git a/src/bin/pg_resetxlog/pg_resetxlog.c b/src/bin/pg_resetxlog/pg_resetxlog.c index a16089f..3361111 100644 --- a/src/bin/pg_resetxlog/pg_resetxlog.c +++ b/src/bin/pg_resetxlog/pg_resetxlog.c @@ -53,6 +53,7 @@ #include "catalog/catversion.h" #include "catalog/pg_control.h" #include "common/fe_memutils.h" +#include "common/restricted_token.h" #include "storage/large_object.h" #include "pg_getopt.h" @@ -310,6 +311,8 @@ main(int argc, char *argv[]) } #endif + get_restricted_token(progname); + if (chdir(DataDir) < 0) { fprintf(stderr, _("%s: could not change directory to \"%s\": %s\n"), diff --git a/src/common/Makefile b/src/common/Makefile index c71415e..c2e456d 100644 --- a/src/common/Makefile +++ b/src/common/Makefile @@ -26,7 +26,7 @@ LIBS += $(PTHREAD_LIBS) OBJS_COMMON = exec.o pg_crc.o pg_lzcompress.o pgfnames.o psprintf.o relpath.o \ rmtree.o string.o username.o wait_error.o -OBJS_FRONTEND = $(OBJS_COMMON) fe_memutils.o +OBJS_FRONTEND = $(OBJS_COMMON) fe_memutils.o restricted_token.o OBJS_SRV = $(OBJS_COMMON:%.o=%_srv.o) diff --git a/src/test/regress/pg_regress.c b/src/test/regress/pg_regress.c index 9d4fb9a..dc910b0 100644 --- a/src/test/regress/pg_regress.c +++ b/src/test/regress/pg_regress.c @@ -30,6 +30,7 @@ #endif #include "common/username.h" +#include "common/restricted_token.h" #include "getopt_long.h" #include "libpq/pqcomm.h" /* needed for UNIXSOCK_PATH() */ #include "pg_config_paths.h" @@ -147,15 +148,6 @@ psql_command(const char *database, const char *query,...) the supplied arguments. */ pg_attribute_printf(2, 3); -#ifdef WIN32 -typedef BOOL (WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); - -/* Windows API define missing from some versions of MingW headers */ -#ifndef DISABLE_MAX_PRIVILEGE -#define DISABLE_MAX_PRIVILEGE 0x1 -#endif -#endif - /* * allow core files if possible. */ @@ -1238,100 +1230,17 @@ spawn_process(const char *cmdline) /* in parent */ return pid; #else - char *cmdline2; - BOOL b; - STARTUPINFO si; - PROCESS_INFORMATION pi; - HANDLE origToken; - HANDLE restrictedToken; - SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY}; - SID_AND_ATTRIBUTES dropSids[2]; - __CreateRestrictedToken _CreateRestrictedToken = NULL; - HANDLE Advapi32Handle; - - ZeroMemory(&si, sizeof(si)); - si.cb = sizeof(si); - - Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); - if (Advapi32Handle != NULL) - { - _CreateRestrictedToken = (__CreateRestrictedToken) GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); - } - - if (_CreateRestrictedToken == NULL) - { - if (Advapi32Handle != NULL) - FreeLibrary(Advapi32Handle); - fprintf(stderr, _("%s: cannot create restricted tokens on this platform\n"), - progname); - exit(2); - } - - /* Open the current token to use as base for the restricted one */ - if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) - { - fprintf(stderr, _("could not open process token: error code %lu\n"), - GetLastError()); - exit(2); - } - - /* Allocate list of SIDs to remove */ - ZeroMemory(&dropSids, sizeof(dropSids)); - if (!AllocateAndInitializeSid(&NtAuthority, 2, - SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &dropSids[0].Sid) || - !AllocateAndInitializeSid(&NtAuthority, 2, - SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, 0, &dropSids[1].Sid)) - { - fprintf(stderr, _("could not allocate SIDs: error code %lu\n"), GetLastError()); - exit(2); - } - - b = _CreateRestrictedToken(origToken, - DISABLE_MAX_PRIVILEGE, - sizeof(dropSids) / sizeof(dropSids[0]), - dropSids, - 0, NULL, - 0, NULL, - &restrictedToken); - - FreeSid(dropSids[1].Sid); - FreeSid(dropSids[0].Sid); - CloseHandle(origToken); - FreeLibrary(Advapi32Handle); - - if (!b) - { - fprintf(stderr, _("could not create restricted token: error code %lu\n"), - GetLastError()); - exit(2); - } + PROCESS_INFORMATION pi; + char *cmdline2; + HANDLE restrictedToken; + memset(&pi, 0, sizeof(pi)); cmdline2 = psprintf("cmd /c \"%s\"", cmdline); -#ifndef __CYGWIN__ - AddUserToTokenDacl(restrictedToken); -#endif - - if (!CreateProcessAsUser(restrictedToken, - NULL, - cmdline2, - NULL, - NULL, - TRUE, - CREATE_SUSPENDED, - NULL, - NULL, - &si, - &pi)) - { - fprintf(stderr, _("could not start process for \"%s\": error code %lu\n"), - cmdline2, GetLastError()); + if((restrictedToken = + CreateRestrictedProcess(cmdline2, &pi, progname)) == 0) exit(2); - } - - free(cmdline2); - ResumeThread(pi.hThread); CloseHandle(pi.hThread); return pi.hProcess; #endif diff --git a/src/tools/msvc/Mkvcbuild.pm b/src/tools/msvc/Mkvcbuild.pm index 989a2ec..9c52a46 100644 --- a/src/tools/msvc/Mkvcbuild.pm +++ b/src/tools/msvc/Mkvcbuild.pm @@ -95,7 +95,8 @@ sub mkvcbuild exec.c pg_crc.c pg_lzcompress.c pgfnames.c psprintf.c relpath.c rmtree.c string.c username.c wait_error.c); - our @pgcommonfrontendfiles = (@pgcommonallfiles, qw(fe_memutils.c)); + our @pgcommonfrontendfiles = (@pgcommonallfiles, qw(fe_memutils.c + restricted_token.c)); our @pgcommonbkndfiles = @pgcommonallfiles; diff --git a/src/common/restricted_token.c b/src/common/restricted_token.c new file mode 100644 index 0000000..0c07d47 --- /dev/null +++ b/src/common/restricted_token.c @@ -0,0 +1,195 @@ +/*------------------------------------------------------------------------- + * + * restricted_token.c + * helper routine to ensure restricted token on Windows + * + * + * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * + * IDENTIFICATION + * src/common/restricted_token.c + * + *------------------------------------------------------------------------- + */ + +#ifndef FRONTEND +#error "This file is not expected to be compiled for backend code" +#endif + +#include "postgres_fe.h" + +#include "common/restricted_token.h" + +#ifdef WIN32 + +/* internal vars */ +char *restrict_env; + +typedef BOOL (WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); + +/* Windows API define missing from some versions of MingW headers */ +#ifndef DISABLE_MAX_PRIVILEGE +#define DISABLE_MAX_PRIVILEGE 0x1 +#endif + +#define write_stderr(fmt, ...) fprintf(stderr, fmt, __VA_ARGS__) + +/* + * Create a restricted token and execute the specified process with it. + * + * Returns restricted token on success and 0 on failure. + * + * On NT4, or any other system not containing the required functions, will + * NOT execute anything. + */ +HANDLE +CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, const char *progname) +{ + BOOL b; + STARTUPINFO si; + HANDLE origToken; + HANDLE restrictedToken; + SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY}; + SID_AND_ATTRIBUTES dropSids[2]; + __CreateRestrictedToken _CreateRestrictedToken = NULL; + HANDLE Advapi32Handle; + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + + Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); + if (Advapi32Handle != NULL) + { + _CreateRestrictedToken = (__CreateRestrictedToken) GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); + } + + if (_CreateRestrictedToken == NULL) + { + write_stderr(_("%s: WARNING: cannot create restricted tokens on this platform\n"), progname); + if (Advapi32Handle != NULL) + FreeLibrary(Advapi32Handle); + return 0; + } + + /* Open the current token to use as a base for the restricted one */ + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) + { + write_stderr(_("%s: could not open process token: error code %lu\n"), progname, GetLastError()); + return 0; + } + + /* Allocate list of SIDs to remove */ + ZeroMemory(&dropSids, sizeof(dropSids)); + if (!AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, + 0, &dropSids[0].Sid) || + !AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, + 0, &dropSids[1].Sid)) + { + write_stderr(_("%s: could not allocate SIDs: error code %lu\n"), + progname, GetLastError()); + return 0; + } + + b = _CreateRestrictedToken(origToken, + DISABLE_MAX_PRIVILEGE, + sizeof(dropSids) / sizeof(dropSids[0]), + dropSids, + 0, NULL, + 0, NULL, + &restrictedToken); + + FreeSid(dropSids[1].Sid); + FreeSid(dropSids[0].Sid); + CloseHandle(origToken); + FreeLibrary(Advapi32Handle); + + if (!b) + { + write_stderr(_("%s: could not create restricted token: error code %lu\n"), + progname, GetLastError()); + return 0; + } + +#ifndef __CYGWIN__ + AddUserToTokenDacl(restrictedToken); +#endif + + if (!CreateProcessAsUser(restrictedToken, + NULL, + cmd, + NULL, + NULL, + TRUE, + CREATE_SUSPENDED, + NULL, + NULL, + &si, + processInfo)) + + { + write_stderr(_("%s: could not start process for command \"%s\": error code %lu\n"), progname, cmd, GetLastError()); + return 0; + } + + ResumeThread(processInfo->hThread); + return restrictedToken; +} +#endif + +/* + * On Windows make sure that we are running with a restricted token, + * On other platforms do nothing. + */ +void +get_restricted_token(const char *progname) +{ +#ifdef WIN32 + HANDLE restrictedToken; + + /* + * Before we execute another program, make sure that we are running with a + * restricted token. If not, re-execute ourselves with one. + */ + + if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL + || strcmp(restrict_env, "1") != 0) + { + PROCESS_INFORMATION pi; + char *cmdline; + + ZeroMemory(&pi, sizeof(pi)); + + cmdline = pg_strdup(GetCommandLine()); + + putenv("PG_RESTRICT_EXEC=1"); + + if ((restrictedToken = CreateRestrictedProcess(cmdline, &pi, progname)) == 0) + { + write_stderr(_("%s: could not re-execute with restricted token: error code %lu\n"), progname, GetLastError()); + } + else + { + /* + * Successfully re-execed. Now wait for child process to capture + * exitcode. + */ + DWORD x; + + CloseHandle(restrictedToken); + CloseHandle(pi.hThread); + WaitForSingleObject(pi.hProcess, INFINITE); + + if (!GetExitCodeProcess(pi.hProcess, &x)) + { + write_stderr(_("%s: could not get exit code from subprocess: error code %lu\n"), progname, GetLastError()); + exit(1); + } + exit(x); + } + } +#endif +} diff --git a/src/include/common/restricted_token.h b/src/include/common/restricted_token.h new file mode 100644 index 0000000..e243744 --- /dev/null +++ b/src/include/common/restricted_token.h @@ -0,0 +1,24 @@ +/* + * restricted_token.h + * helper routine to ensure restricted token on Windows + * + * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * src/include/common/restricted_token.h + */ +#ifndef COMMON_RESTRICTED_TOKEN_H +#define COMMON_RESTRICTED_TOKEN_H + +/* + * On Windows make sure that we are running with a restricted token, + * On other platforms do nothing. + */ +void get_restricted_token(const char *progname); + +#ifdef WIN32 +/* Create a restricted token and execute the specified process with it. */ +HANDLE CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, const char *progname); +#endif + +#endif /* COMMON_RESTRICTED_TOKEN_H */
^ permalink raw reply [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-03-18 22:04  Alvaro Herrera <alvherre@2ndquadrant.com>
  parent: Asif Naeem <anaeem.it@gmail.com>
  1 sibling, 1 reply; 35+ messages in thread

From: Alvaro Herrera @ 2015-03-18 22:04 UTC (permalink / raw)
  To: Asif Naeem <anaeem.it@gmail.com>; +Cc: Michael Paquier <michael.paquier@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Bruce Momjian <bruce@momjian.us>; pgsql-bugs

I haven't followed this effort at all.  Are we on the same page about
backpatching, i.e. we want a minimal patch to apply to the back branches
(which would be 9.0 to 9.4 at this point, I think, right?); and a larger
patch that would apply to 9.5.

Now that I think about this, perhaps it'd be better to apply the same
patch to all branches, and once that's settled (i.e. buildfarmed until
we're sure it works) we refactor things in HEAD.

Speaking of buildfarming the patch -- how are we to actually test this?
As far as I understand, this code only matters when the server is being
run by an administrator account, which the buildfarm code doesn't do ...
So we're going to have to trust testers running stuff manually, right?

-- 
Álvaro Herrera                http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-03-19 00:22  Michael Paquier <michael.paquier@gmail.com>
  parent: Alvaro Herrera <alvherre@2ndquadrant.com>
  0 siblings, 0 replies; 35+ messages in thread

From: Michael Paquier @ 2015-03-19 00:22 UTC (permalink / raw)
  To: Alvaro Herrera <alvherre@2ndquadrant.com>; +Cc: Asif Naeem <anaeem.it@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Bruce Momjian <bruce@momjian.us>; pgsql-bugs

On Thu, Mar 19, 2015 at 7:04 AM, Alvaro Herrera
<alvherre@2ndquadrant.com> wrote:
> I haven't followed this effort at all.  Are we on the same page about
> backpatching, i.e. we want a minimal patch to apply to the back branches
> (which would be 9.0 to 9.4 at this point, I think, right?); and a larger
> patch that would apply to 9.5.

Yes, that's the plan. What we have been arguing here is the refactoring patch.

> Now that I think about this, perhaps it'd be better to apply the same
> patch to all branches, and once that's settled (i.e. buildfarmed until
> we're sure it works) we refactor things in HEAD.

As a back-branch patch, it is possible to simply use the first version
that Asif has added upthread: it duplicates the restricted token stuff
directly in pg_upgrade and pg_resetxlog.

> Speaking of buildfarming the patch -- how are we to actually test this?
> As far as I understand, this code only matters when the server is being
> run by an administrator account, which the buildfarm code doesn't do ...

Well, I don't know. I am sure I could at least involve some internal
QE folks to get automated tests for this stuff, but the tests we do
are tightly integrated with our build infrastructure so this would
just stay internal, still I would get immediately reports if this
breaks and I could report and provide fixes easily. Having a solution
nicely integrated in the buildfarm scripts is something else though, a
build run being done only as one dedicated user.

> So we're going to have to trust testers running stuff manually, right?

I guess so.. Sorry I have no real solution to that.

Regards,
-- 
Michael


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-03-19 07:25  Michael Paquier <michael.paquier@gmail.com>
  parent: Asif Naeem <anaeem.it@gmail.com>
  1 sibling, 1 reply; 35+ messages in thread

From: Michael Paquier @ 2015-03-19 07:25 UTC (permalink / raw)
  To: Asif Naeem <anaeem.it@gmail.com>; +Cc: Alvaro Herrera <alvherre@2ndquadrant.com>; Amit Kapila <amit.kapila16@gmail.com>; Bruce Momjian <bruce@momjian.us>; pgsql-bugs

On Thu, Mar 19, 2015 at 6:42 AM, Asif Naeem wrote:
> I do agree, pg_ctl refactoring is making current patch more complicated,
> eventually we can come up with robust patch that include pg_ctl but result
> patch could be big and touching lot of areas, I doubt that if such
> complicated and big patch going to make its way into the repository. It
> seems appropriate to do incremental work, we can refactor pg_ctl changes as
> next effort. PFA update patch, it removes pg_ctl related code changes.
> Please do let me know if I missed something. Thanks.

After looking closely at those things, I agree with you: having some
code duplicated in two places instead of five is still a win... Now, I
think having this declaration of write_stderr in restricted_token.c is
confusing:
+#define write_stderr(fmt, ...) fprintf(stderr, fmt, __VA_ARGS__)
We could have bad surprises in the future if there is some work to
link pg_ctl with the stuff of restricted_token.c. Hence, could you
replace that with plain calls to fprintf(stderr, ...)? That's as well
what the other files of src/common are doing, so it would make the new
code more consistent with the rest.

[nitpicking]
inline patch 1: src/test/regress/pg_regress.c (+1/-0 lines) download inline-1.patch--- a/src/test/regress/pg_regress.c +++ b/src/test/regress/pg_regress.c @@ -30,6 +30,7 @@ #endif #include "common/username.h" +#include "common/restricted_token.h"
Alphabetical order of headers. [/nitpicking] Except those two small things, well I guess that's it for this patch. The stuff for write_stderr may need a TODO item, but I think that even with that we are going to finish by fixing the call to isatty that looks indeed strange... For the backpatching, the patches sent previously here (=> http://www.postgresql.org/message-id/CAEB4t-OHNE95=n5U4ySsYkWipQsWeQuTBSJkaYJ63_1VzkzkhA@mail.gmail....) are fine IMO. They simply consist of a copy of what is done in initdb.c. Now, perhaps we had better apply the patch duplicating the logic to all branches, including HEAD, first, see what the buildfarm says, and then finish wrapping up the refactoring patch. Regards, -- Michael -- Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org) To make changes to your subscription: http://www.postgresql.org/mailpref/pgsql-bugs ^ permalink raw reply [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-03-20 14:14  Asif Naeem <anaeem.it@gmail.com>
  parent: Michael Paquier <michael.paquier@gmail.com>
  0 siblings, 1 reply; 35+ messages in thread

From: Asif Naeem @ 2015-03-20 14:14 UTC (permalink / raw)
  To: Michael Paquier <michael.paquier@gmail.com>; +Cc: Alvaro Herrera <alvherre@2ndquadrant.com>; Amit Kapila <amit.kapila16@gmail.com>; Bruce Momjian <bruce@momjian.us>; pgsql-bugs

On Thu, Mar 19, 2015 at 12:25 PM, Michael Paquier <michael.paquier@gmail.com
> wrote:

> On Thu, Mar 19, 2015 at 6:42 AM, Asif Naeem wrote:
> > I do agree, pg_ctl refactoring is making current patch more complicated,
> > eventually we can come up with robust patch that include pg_ctl but
> result
> > patch could be big and touching lot of areas, I doubt that if such
> > complicated and big patch going to make its way into the repository. It
> > seems appropriate to do incremental work, we can refactor pg_ctl changes
> as
> > next effort. PFA update patch, it removes pg_ctl related code changes.
> > Please do let me know if I missed something. Thanks.
>
> After looking closely at those things, I agree with you: having some
> code duplicated in two places instead of five is still a win... Now, I
> think having this declaration of write_stderr in restricted_token.c is
> confusing:
> +#define write_stderr(fmt, ...) fprintf(stderr, fmt, __VA_ARGS__)
> We could have bad surprises in the future if there is some work to
> link pg_ctl with the stuff of restricted_token.c. Hence, could you
> replace that with plain calls to fprintf(stderr, ...)? That's as well
> what the other files of src/common are doing, so it would make the new
> code more consistent with the rest.
>
> [nitpicking]
> --- a/src/test/regress/pg_regress.c
> +++ b/src/test/regress/pg_regress.c
> @@ -30,6 +30,7 @@
>  #endif
>
>  #include "common/username.h"
> +#include "common/restricted_token.h"
>
> Alphabetical order of headers.
> [/nitpicking]
>
> Except those two small things, well I guess that's it for this patch.
>

Thank you so much. PFA v5 updated patch with above 2 changes.


> The stuff for write_stderr may need a TODO item, but I think that even
> with that we are going to finish by fixing the call to isatty that
> looks indeed strange...
>

+1


>
> For the backpatching, the patches sent previously here (=>
>
> http://www.postgresql.org/message-id/CAEB4t-OHNE95=n5U4ySsYkWipQsWeQuTBSJkaYJ63_1VzkzkhA@mail.gmail....
> )
> are fine IMO. They simply consist of a copy of what is done in
> initdb.c. Now, perhaps we had better apply the patch duplicating the
> logic to all branches, including HEAD, first, see what the buildfarm
> says, and then finish wrapping up the refactoring patch.
>

PFA patch for older branches, v1 patch was not applying cleaning other than
94. Thanks.


> Regards,
> --
> Michael
>

-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs

Attachments: download all (5 files, .tar.gz)

restricted_token.v5.patch (application/octet-stream, 17.8K) download diff --git a/contrib/pg_upgrade/pg_upgrade.c b/contrib/pg_upgrade/pg_upgrade.c index ed7de80..eb48da7 100644 --- a/contrib/pg_upgrade/pg_upgrade.c +++ b/contrib/pg_upgrade/pg_upgrade.c @@ -37,6 +37,7 @@ #include "postgres_fe.h" #include "pg_upgrade.h" +#include "common/restricted_token.h" #ifdef HAVE_LANGINFO_H #include <langinfo.h> @@ -75,6 +76,8 @@ main(int argc, char **argv) parseCommandLine(argc, argv); + get_restricted_token(os_info.progname); + adjust_data_dir(&old_cluster); adjust_data_dir(&new_cluster); diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c index 18614e7..b8abf19 100644 --- a/src/bin/initdb/initdb.c +++ b/src/bin/initdb/initdb.c @@ -62,6 +62,7 @@ #include "catalog/catalog.h" #include "common/username.h" +#include "common/restricted_token.h" #include "mb/pg_wchar.h" #include "getaddrinfo.h" #include "getopt_long.h" @@ -178,9 +179,6 @@ static char *authwarning = NULL; static const char *boot_options = "-F"; static const char *backend_options = "--single -F -O -c search_path=pg_catalog -c exit_on_error=true"; -#ifdef WIN32 -char *restrict_env; -#endif static const char *subdirs[] = { "global", "pg_xlog", @@ -260,7 +258,6 @@ static void check_locale_name(int category, const char *locale, static bool check_locale_encoding(const char *locale, int encoding); static void setlocales(void); static void usage(const char *progname); -void get_restricted_token(void); void setup_pgdata(void); void setup_bin_paths(const char *argv0); void setup_data_file_paths(void); @@ -272,12 +269,6 @@ void create_xlog_symlink(void); void warn_on_mount_point(int error); void initialize_data_directory(void); - -#ifdef WIN32 -static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo); -#endif - - /* * macros for running pipes to postgres */ @@ -2754,116 +2745,6 @@ setlocales(void) #endif } -#ifdef WIN32 -typedef BOOL (WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); - -/* Windows API define missing from some versions of MingW headers */ -#ifndef DISABLE_MAX_PRIVILEGE -#define DISABLE_MAX_PRIVILEGE 0x1 -#endif - -/* - * Create a restricted token and execute the specified process with it. - * - * Returns 0 on failure, non-zero on success, same as CreateProcess(). - * - * On NT4, or any other system not containing the required functions, will - * NOT execute anything. - */ -static int -CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo) -{ - BOOL b; - STARTUPINFO si; - HANDLE origToken; - HANDLE restrictedToken; - SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY}; - SID_AND_ATTRIBUTES dropSids[2]; - __CreateRestrictedToken _CreateRestrictedToken = NULL; - HANDLE Advapi32Handle; - - ZeroMemory(&si, sizeof(si)); - si.cb = sizeof(si); - - Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); - if (Advapi32Handle != NULL) - { - _CreateRestrictedToken = (__CreateRestrictedToken) GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); - } - - if (_CreateRestrictedToken == NULL) - { - fprintf(stderr, _("%s: WARNING: cannot create restricted tokens on this platform\n"), progname); - if (Advapi32Handle != NULL) - FreeLibrary(Advapi32Handle); - return 0; - } - - /* Open the current token to use as a base for the restricted one */ - if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) - { - fprintf(stderr, _("%s: could not open process token: error code %lu\n"), progname, GetLastError()); - return 0; - } - - /* Allocate list of SIDs to remove */ - ZeroMemory(&dropSids, sizeof(dropSids)); - if (!AllocateAndInitializeSid(&NtAuthority, 2, - SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, - 0, &dropSids[0].Sid) || - !AllocateAndInitializeSid(&NtAuthority, 2, - SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, - 0, &dropSids[1].Sid)) - { - fprintf(stderr, _("%s: could not allocate SIDs: error code %lu\n"), - progname, GetLastError()); - return 0; - } - - b = _CreateRestrictedToken(origToken, - DISABLE_MAX_PRIVILEGE, - sizeof(dropSids) / sizeof(dropSids[0]), - dropSids, - 0, NULL, - 0, NULL, - &restrictedToken); - - FreeSid(dropSids[1].Sid); - FreeSid(dropSids[0].Sid); - CloseHandle(origToken); - FreeLibrary(Advapi32Handle); - - if (!b) - { - fprintf(stderr, _("%s: could not create restricted token: error code %lu\n"), progname, GetLastError()); - return 0; - } - -#ifndef __CYGWIN__ - AddUserToTokenDacl(restrictedToken); -#endif - - if (!CreateProcessAsUser(restrictedToken, - NULL, - cmd, - NULL, - NULL, - TRUE, - CREATE_SUSPENDED, - NULL, - NULL, - &si, - processInfo)) - - { - fprintf(stderr, _("%s: could not start process for command \"%s\": error code %lu\n"), progname, cmd, GetLastError()); - return 0; - } - - return ResumeThread(processInfo->hThread); -} -#endif - /* * print help text */ @@ -2957,53 +2838,6 @@ check_need_password(const char *authmethodlocal, const char *authmethodhost) } } -void -get_restricted_token(void) -{ -#ifdef WIN32 - - /* - * Before we execute another program, make sure that we are running with a - * restricted token. If not, re-execute ourselves with one. - */ - - if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL - || strcmp(restrict_env, "1") != 0) - { - PROCESS_INFORMATION pi; - char *cmdline; - - ZeroMemory(&pi, sizeof(pi)); - - cmdline = pg_strdup(GetCommandLine()); - - putenv("PG_RESTRICT_EXEC=1"); - - if (!CreateRestrictedProcess(cmdline, &pi)) - { - fprintf(stderr, _("%s: could not re-execute with restricted token: error code %lu\n"), progname, GetLastError()); - } - else - { - /* - * Successfully re-execed. Now wait for child process to capture - * exitcode. - */ - DWORD x; - - CloseHandle(pi.hThread); - WaitForSingleObject(pi.hProcess, INFINITE); - - if (!GetExitCodeProcess(pi.hProcess, &x)) - { - fprintf(stderr, _("%s: could not get exit code from subprocess: error code %lu\n"), progname, GetLastError()); - exit(1); - } - exit(x); - } - } -#endif -} void setup_pgdata(void) @@ -3759,7 +3593,7 @@ main(int argc, char *argv[]) check_need_password(authmethodlocal, authmethodhost); - get_restricted_token(); + get_restricted_token(progname); setup_pgdata(); diff --git a/src/bin/pg_resetxlog/pg_resetxlog.c b/src/bin/pg_resetxlog/pg_resetxlog.c index a16089f..3361111 100644 --- a/src/bin/pg_resetxlog/pg_resetxlog.c +++ b/src/bin/pg_resetxlog/pg_resetxlog.c @@ -53,6 +53,7 @@ #include "catalog/catversion.h" #include "catalog/pg_control.h" #include "common/fe_memutils.h" +#include "common/restricted_token.h" #include "storage/large_object.h" #include "pg_getopt.h" @@ -310,6 +311,8 @@ main(int argc, char *argv[]) } #endif + get_restricted_token(progname); + if (chdir(DataDir) < 0) { fprintf(stderr, _("%s: could not change directory to \"%s\": %s\n"), diff --git a/src/common/Makefile b/src/common/Makefile index c71415e..c2e456d 100644 --- a/src/common/Makefile +++ b/src/common/Makefile @@ -26,7 +26,7 @@ LIBS += $(PTHREAD_LIBS) OBJS_COMMON = exec.o pg_crc.o pg_lzcompress.o pgfnames.o psprintf.o relpath.o \ rmtree.o string.o username.o wait_error.o -OBJS_FRONTEND = $(OBJS_COMMON) fe_memutils.o +OBJS_FRONTEND = $(OBJS_COMMON) fe_memutils.o restricted_token.o OBJS_SRV = $(OBJS_COMMON:%.o=%_srv.o) diff --git a/src/test/regress/pg_regress.c b/src/test/regress/pg_regress.c index 9d4fb9a..6f20120 100644 --- a/src/test/regress/pg_regress.c +++ b/src/test/regress/pg_regress.c @@ -29,6 +29,7 @@ #include <sys/resource.h> #endif +#include "common/restricted_token.h" #include "common/username.h" #include "getopt_long.h" #include "libpq/pqcomm.h" /* needed for UNIXSOCK_PATH() */ @@ -147,15 +148,6 @@ psql_command(const char *database, const char *query,...) the supplied arguments. */ pg_attribute_printf(2, 3); -#ifdef WIN32 -typedef BOOL (WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); - -/* Windows API define missing from some versions of MingW headers */ -#ifndef DISABLE_MAX_PRIVILEGE -#define DISABLE_MAX_PRIVILEGE 0x1 -#endif -#endif - /* * allow core files if possible. */ @@ -1238,100 +1230,17 @@ spawn_process(const char *cmdline) /* in parent */ return pid; #else - char *cmdline2; - BOOL b; - STARTUPINFO si; - PROCESS_INFORMATION pi; - HANDLE origToken; - HANDLE restrictedToken; - SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY}; - SID_AND_ATTRIBUTES dropSids[2]; - __CreateRestrictedToken _CreateRestrictedToken = NULL; - HANDLE Advapi32Handle; - - ZeroMemory(&si, sizeof(si)); - si.cb = sizeof(si); - - Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); - if (Advapi32Handle != NULL) - { - _CreateRestrictedToken = (__CreateRestrictedToken) GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); - } - - if (_CreateRestrictedToken == NULL) - { - if (Advapi32Handle != NULL) - FreeLibrary(Advapi32Handle); - fprintf(stderr, _("%s: cannot create restricted tokens on this platform\n"), - progname); - exit(2); - } - - /* Open the current token to use as base for the restricted one */ - if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) - { - fprintf(stderr, _("could not open process token: error code %lu\n"), - GetLastError()); - exit(2); - } - - /* Allocate list of SIDs to remove */ - ZeroMemory(&dropSids, sizeof(dropSids)); - if (!AllocateAndInitializeSid(&NtAuthority, 2, - SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &dropSids[0].Sid) || - !AllocateAndInitializeSid(&NtAuthority, 2, - SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, 0, &dropSids[1].Sid)) - { - fprintf(stderr, _("could not allocate SIDs: error code %lu\n"), GetLastError()); - exit(2); - } - - b = _CreateRestrictedToken(origToken, - DISABLE_MAX_PRIVILEGE, - sizeof(dropSids) / sizeof(dropSids[0]), - dropSids, - 0, NULL, - 0, NULL, - &restrictedToken); - - FreeSid(dropSids[1].Sid); - FreeSid(dropSids[0].Sid); - CloseHandle(origToken); - FreeLibrary(Advapi32Handle); - - if (!b) - { - fprintf(stderr, _("could not create restricted token: error code %lu\n"), - GetLastError()); - exit(2); - } + PROCESS_INFORMATION pi; + char *cmdline2; + HANDLE restrictedToken; + memset(&pi, 0, sizeof(pi)); cmdline2 = psprintf("cmd /c \"%s\"", cmdline); -#ifndef __CYGWIN__ - AddUserToTokenDacl(restrictedToken); -#endif - - if (!CreateProcessAsUser(restrictedToken, - NULL, - cmdline2, - NULL, - NULL, - TRUE, - CREATE_SUSPENDED, - NULL, - NULL, - &si, - &pi)) - { - fprintf(stderr, _("could not start process for \"%s\": error code %lu\n"), - cmdline2, GetLastError()); + if((restrictedToken = + CreateRestrictedProcess(cmdline2, &pi, progname)) == 0) exit(2); - } - - free(cmdline2); - ResumeThread(pi.hThread); CloseHandle(pi.hThread); return pi.hProcess; #endif diff --git a/src/tools/msvc/Mkvcbuild.pm b/src/tools/msvc/Mkvcbuild.pm index 989a2ec..9c52a46 100644 --- a/src/tools/msvc/Mkvcbuild.pm +++ b/src/tools/msvc/Mkvcbuild.pm @@ -95,7 +95,8 @@ sub mkvcbuild exec.c pg_crc.c pg_lzcompress.c pgfnames.c psprintf.c relpath.c rmtree.c string.c username.c wait_error.c); - our @pgcommonfrontendfiles = (@pgcommonallfiles, qw(fe_memutils.c)); + our @pgcommonfrontendfiles = (@pgcommonallfiles, qw(fe_memutils.c + restricted_token.c)); our @pgcommonbkndfiles = @pgcommonallfiles; diff --git a/src/common/restricted_token.c b/src/common/restricted_token.c new file mode 100644 index 0000000..a8213c0 --- /dev/null +++ b/src/common/restricted_token.c @@ -0,0 +1,193 @@ +/*------------------------------------------------------------------------- + * + * restricted_token.c + * helper routine to ensure restricted token on Windows + * + * + * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * + * IDENTIFICATION + * src/common/restricted_token.c + * + *------------------------------------------------------------------------- + */ + +#ifndef FRONTEND +#error "This file is not expected to be compiled for backend code" +#endif + +#include "postgres_fe.h" + +#include "common/restricted_token.h" + +#ifdef WIN32 + +/* internal vars */ +char *restrict_env; + +typedef BOOL (WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); + +/* Windows API define missing from some versions of MingW headers */ +#ifndef DISABLE_MAX_PRIVILEGE +#define DISABLE_MAX_PRIVILEGE 0x1 +#endif + +/* + * Create a restricted token and execute the specified process with it. + * + * Returns restricted token on success and 0 on failure. + * + * On NT4, or any other system not containing the required functions, will + * NOT execute anything. + */ +HANDLE +CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, const char *progname) +{ + BOOL b; + STARTUPINFO si; + HANDLE origToken; + HANDLE restrictedToken; + SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY}; + SID_AND_ATTRIBUTES dropSids[2]; + __CreateRestrictedToken _CreateRestrictedToken = NULL; + HANDLE Advapi32Handle; + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + + Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); + if (Advapi32Handle != NULL) + { + _CreateRestrictedToken = (__CreateRestrictedToken) GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); + } + + if (_CreateRestrictedToken == NULL) + { + fprintf(stderr, _("%s: WARNING: cannot create restricted tokens on this platform\n"), progname); + if (Advapi32Handle != NULL) + FreeLibrary(Advapi32Handle); + return 0; + } + + /* Open the current token to use as a base for the restricted one */ + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) + { + fprintf(stderr, _("%s: could not open process token: error code %lu\n"), progname, GetLastError()); + return 0; + } + + /* Allocate list of SIDs to remove */ + ZeroMemory(&dropSids, sizeof(dropSids)); + if (!AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, + 0, &dropSids[0].Sid) || + !AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, + 0, &dropSids[1].Sid)) + { + fprintf(stderr, _("%s: could not allocate SIDs: error code %lu\n"), + progname, GetLastError()); + return 0; + } + + b = _CreateRestrictedToken(origToken, + DISABLE_MAX_PRIVILEGE, + sizeof(dropSids) / sizeof(dropSids[0]), + dropSids, + 0, NULL, + 0, NULL, + &restrictedToken); + + FreeSid(dropSids[1].Sid); + FreeSid(dropSids[0].Sid); + CloseHandle(origToken); + FreeLibrary(Advapi32Handle); + + if (!b) + { + fprintf(stderr, _("%s: could not create restricted token: error code %lu\n"), + progname, GetLastError()); + return 0; + } + +#ifndef __CYGWIN__ + AddUserToTokenDacl(restrictedToken); +#endif + + if (!CreateProcessAsUser(restrictedToken, + NULL, + cmd, + NULL, + NULL, + TRUE, + CREATE_SUSPENDED, + NULL, + NULL, + &si, + processInfo)) + + { + fprintf(stderr, _("%s: could not start process for command \"%s\": error code %lu\n"), progname, cmd, GetLastError()); + return 0; + } + + ResumeThread(processInfo->hThread); + return restrictedToken; +} +#endif + +/* + * On Windows make sure that we are running with a restricted token, + * On other platforms do nothing. + */ +void +get_restricted_token(const char *progname) +{ +#ifdef WIN32 + HANDLE restrictedToken; + + /* + * Before we execute another program, make sure that we are running with a + * restricted token. If not, re-execute ourselves with one. + */ + + if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL + || strcmp(restrict_env, "1") != 0) + { + PROCESS_INFORMATION pi; + char *cmdline; + + ZeroMemory(&pi, sizeof(pi)); + + cmdline = pg_strdup(GetCommandLine()); + + putenv("PG_RESTRICT_EXEC=1"); + + if ((restrictedToken = CreateRestrictedProcess(cmdline, &pi, progname)) == 0) + { + fprintf(stderr, _("%s: could not re-execute with restricted token: error code %lu\n"), progname, GetLastError()); + } + else + { + /* + * Successfully re-execed. Now wait for child process to capture + * exitcode. + */ + DWORD x; + + CloseHandle(restrictedToken); + CloseHandle(pi.hThread); + WaitForSingleObject(pi.hProcess, INFINITE); + + if (!GetExitCodeProcess(pi.hProcess, &x)) + { + fprintf(stderr, _("%s: could not get exit code from subprocess: error code %lu\n"), progname, GetLastError()); + exit(1); + } + exit(x); + } + } +#endif +} diff --git a/src/include/common/restricted_token.h b/src/include/common/restricted_token.h new file mode 100644 index 0000000..e243744 --- /dev/null +++ b/src/include/common/restricted_token.h @@ -0,0 +1,24 @@ +/* + * restricted_token.h + * helper routine to ensure restricted token on Windows + * + * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * src/include/common/restricted_token.h + */ +#ifndef COMMON_RESTRICTED_TOKEN_H +#define COMMON_RESTRICTED_TOKEN_H + +/* + * On Windows make sure that we are running with a restricted token, + * On other platforms do nothing. + */ +void get_restricted_token(const char *progname); + +#ifdef WIN32 +/* Create a restricted token and execute the specified process with it. */ +HANDLE CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, const char *progname); +#endif + +#endif /* COMMON_RESTRICTED_TOKEN_H */
pg_upgrade_pg_resetxlog.v1_91.patch (application/octet-stream, 10.5K) download diff --git a/contrib/pg_upgrade/pg_upgrade.c b/contrib/pg_upgrade/pg_upgrade.c index b294d7b..fad7f6c 100644 --- a/contrib/pg_upgrade/pg_upgrade.c +++ b/contrib/pg_upgrade/pg_upgrade.c @@ -49,6 +49,11 @@ static void copy_clog_xlog_xid(void); static void set_frozenxids(void); static void setup(char *argv0, bool live_check); static void cleanup(void); +static void get_restricted_token(void); + +#ifdef WIN32 +static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo); +#endif /* This is the database used by pg_dumpall to restore global tables */ #define GLOBAL_DUMP_DB "postgres" @@ -57,6 +62,10 @@ ClusterInfo old_cluster, new_cluster; OSInfo os_info; +#ifdef WIN32 +static char *restrict_env; +#endif + int main(int argc, char **argv) { @@ -66,6 +75,8 @@ main(int argc, char **argv) parseCommandLine(argc, argv); + get_restricted_token(); + output_check_banner(&live_check); setup(argv[0], live_check); @@ -139,6 +150,162 @@ main(int argc, char **argv) return 0; } +#ifdef WIN32 +typedef BOOL(WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); + +/* Windows API define missing from some versions of MingW headers */ +#ifndef DISABLE_MAX_PRIVILEGE +#define DISABLE_MAX_PRIVILEGE 0x1 +#endif + +/* +* Create a restricted token and execute the specified process with it. +* +* Returns 0 on failure, non-zero on success, same as CreateProcess(). +* +* On NT4, or any other system not containing the required functions, will +* NOT execute anything. +*/ +static int +CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo) +{ + BOOL b; + STARTUPINFO si; + HANDLE origToken; + HANDLE restrictedToken; + SID_IDENTIFIER_AUTHORITY NtAuthority = { SECURITY_NT_AUTHORITY }; + SID_AND_ATTRIBUTES dropSids[2]; + __CreateRestrictedToken _CreateRestrictedToken = NULL; + HANDLE Advapi32Handle; + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + + Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); + if (Advapi32Handle != NULL) + { + _CreateRestrictedToken = (__CreateRestrictedToken)GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); + } + + if (_CreateRestrictedToken == NULL) + { + fprintf(stderr, _("WARNING: cannot create restricted tokens on this platform\n")); + if (Advapi32Handle != NULL) + FreeLibrary(Advapi32Handle); + return 0; + } + + /* Open the current token to use as a base for the restricted one */ + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) + { + fprintf(stderr, _("could not open process token: error code %lu\n"), GetLastError()); + return 0; + } + + /* Allocate list of SIDs to remove */ + ZeroMemory(&dropSids, sizeof(dropSids)); + if (!AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, + 0, &dropSids[0].Sid) || + !AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, + 0, &dropSids[1].Sid)) + { + fprintf(stderr, _("could not to allocate SIDs: error code %lu\n"), GetLastError()); + return 0; + } + + b = _CreateRestrictedToken(origToken, + DISABLE_MAX_PRIVILEGE, + sizeof(dropSids) / sizeof(dropSids[0]), + dropSids, + 0, NULL, + 0, NULL, + &restrictedToken); + + FreeSid(dropSids[1].Sid); + FreeSid(dropSids[0].Sid); + CloseHandle(origToken); + FreeLibrary(Advapi32Handle); + + if (!b) + { + fprintf(stderr, _("could not create restricted token: error code %lu\n"), GetLastError()); + return 0; + } + +#ifndef __CYGWIN__ + AddUserToTokenDacl(restrictedToken); +#endif + + if (!CreateProcessAsUser(restrictedToken, + NULL, + cmd, + NULL, + NULL, + TRUE, + CREATE_SUSPENDED, + NULL, + NULL, + &si, + processInfo)) + + { + fprintf(stderr, _("could not start process for command \"%s\": error code %lu\n"), cmd, GetLastError()); + return 0; + } + + return ResumeThread(processInfo->hThread); +} +#endif + +void +get_restricted_token(void) +{ +#ifdef WIN32 + + /* + * Before we execute another program, make sure that we are running with a + * restricted token. If not, re-execute ourselves with one. + */ + + if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL + || strcmp(restrict_env, "1") != 0) + { + PROCESS_INFORMATION pi; + char *cmdline; + + ZeroMemory(&pi, sizeof(pi)); + + cmdline = pg_strdup(GetCommandLine()); + + putenv("PG_RESTRICT_EXEC=1"); + + if (!CreateRestrictedProcess(cmdline, &pi)) + { + fprintf(stderr, _("could not re-execute with restricted token: error code %lu\n"), GetLastError()); + } + else + { + /* + * Successfully re-execed. Now wait for child process to capture + * exitcode. + */ + DWORD x; + + CloseHandle(pi.hThread); + WaitForSingleObject(pi.hProcess, INFINITE); + + if (!GetExitCodeProcess(pi.hProcess, &x)) + { + fprintf(stderr, _("could not get exit code from subprocess: error code %lu\n"), GetLastError()); + exit(1); + } + exit(x); + } + } +#endif +} static void setup(char *argv0, bool live_check) diff --git a/src/bin/pg_resetxlog/pg_resetxlog.c b/src/bin/pg_resetxlog/pg_resetxlog.c index d1b12dc..690e94b 100644 --- a/src/bin/pg_resetxlog/pg_resetxlog.c +++ b/src/bin/pg_resetxlog/pg_resetxlog.c @@ -65,6 +65,10 @@ static uint32 newXlogId, static bool guessed = false; /* T if we had to guess at any values */ static const char *progname; +#ifdef WIN32 +static char *restrict_env; +#endif + static bool ReadControlFile(void); static void GuessControlValues(void); static void PrintControlValues(bool guessed); @@ -74,7 +78,11 @@ static void KillExistingXLOG(void); static void KillExistingArchiveStatus(void); static void WriteEmptyXLOG(void); static void usage(void); +static void get_restricted_token(void); +#ifdef WIN32 +static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo); +#endif int main(int argc, char *argv[]) @@ -256,6 +264,7 @@ main(int argc, char *argv[]) } #endif + get_restricted_token(); DataDir = argv[optind]; if (chdir(DataDir) < 0) @@ -380,6 +389,18 @@ main(int argc, char *argv[]) return 0; } +char * +pg_strdup(const char *str) +{ + char *result = strdup(str); + + if (!result) + { + fprintf(stderr, _("out of memory\n")); + exit(1); + } + return result; +} /* * Try to read the existing pg_control file. @@ -1016,6 +1037,162 @@ WriteEmptyXLOG(void) close(fd); } +#ifdef WIN32 +typedef BOOL(WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); + +/* Windows API define missing from some versions of MingW headers */ +#ifndef DISABLE_MAX_PRIVILEGE +#define DISABLE_MAX_PRIVILEGE 0x1 +#endif + +/* +* Create a restricted token and execute the specified process with it. +* +* Returns 0 on failure, non-zero on success, same as CreateProcess(). +* +* On NT4, or any other system not containing the required functions, will +* NOT execute anything. +*/ +static int +CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo) +{ + BOOL b; + STARTUPINFO si; + HANDLE origToken; + HANDLE restrictedToken; + SID_IDENTIFIER_AUTHORITY NtAuthority = { SECURITY_NT_AUTHORITY }; + SID_AND_ATTRIBUTES dropSids[2]; + __CreateRestrictedToken _CreateRestrictedToken = NULL; + HANDLE Advapi32Handle; + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + + Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); + if (Advapi32Handle != NULL) + { + _CreateRestrictedToken = (__CreateRestrictedToken)GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); + } + + if (_CreateRestrictedToken == NULL) + { + fprintf(stderr, _("%s: WARNING: cannot create restricted tokens on this platform\n"), progname); + if (Advapi32Handle != NULL) + FreeLibrary(Advapi32Handle); + return 0; + } + + /* Open the current token to use as a base for the restricted one */ + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) + { + fprintf(stderr, _("%s: could not open process token: error code %lu\n"), progname, GetLastError()); + return 0; + } + + /* Allocate list of SIDs to remove */ + ZeroMemory(&dropSids, sizeof(dropSids)); + if (!AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, + 0, &dropSids[0].Sid) || + !AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, + 0, &dropSids[1].Sid)) + { + fprintf(stderr, _("%s: could not to allocate SIDs: error code %lu\n"), progname, GetLastError()); + return 0; + } + + b = _CreateRestrictedToken(origToken, + DISABLE_MAX_PRIVILEGE, + sizeof(dropSids) / sizeof(dropSids[0]), + dropSids, + 0, NULL, + 0, NULL, + &restrictedToken); + + FreeSid(dropSids[1].Sid); + FreeSid(dropSids[0].Sid); + CloseHandle(origToken); + FreeLibrary(Advapi32Handle); + + if (!b) + { + fprintf(stderr, _("%s: could not create restricted token: error code %lu\n"), progname, GetLastError()); + return 0; + } + +#ifndef __CYGWIN__ + AddUserToTokenDacl(restrictedToken); +#endif + + if (!CreateProcessAsUser(restrictedToken, + NULL, + cmd, + NULL, + NULL, + TRUE, + CREATE_SUSPENDED, + NULL, + NULL, + &si, + processInfo)) + + { + fprintf(stderr, _("%s: could not start process for command \"%s\": error code %lu\n"), progname, cmd, GetLastError()); + return 0; + } + + return ResumeThread(processInfo->hThread); +} +#endif + +void +get_restricted_token(void) +{ +#ifdef WIN32 + + /* + * Before we execute another program, make sure that we are running with a + * restricted token. If not, re-execute ourselves with one. + */ + + if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL + || strcmp(restrict_env, "1") != 0) + { + PROCESS_INFORMATION pi; + char *cmdline; + + ZeroMemory(&pi, sizeof(pi)); + + cmdline = pg_strdup(GetCommandLine()); + + putenv("PG_RESTRICT_EXEC=1"); + + if (!CreateRestrictedProcess(cmdline, &pi)) + { + fprintf(stderr, _("%s: could not re-execute with restricted token: error code %lu\n"), progname, GetLastError()); + } + else + { + /* + * Successfully re-execed. Now wait for child process to capture + * exitcode. + */ + DWORD x; + + CloseHandle(pi.hThread); + WaitForSingleObject(pi.hProcess, INFINITE); + + if (!GetExitCodeProcess(pi.hProcess, &x)) + { + fprintf(stderr, _("%s: could not get exit code from subprocess: error code %lu\n"), progname, GetLastError()); + exit(1); + } + exit(x); + } + } +#endif +} static void usage(void)
pg_upgrade_pg_resetxlog.v1_92.patch (application/octet-stream, 10.4K) download diff --git a/contrib/pg_upgrade/pg_upgrade.c b/contrib/pg_upgrade/pg_upgrade.c index a106511..b12d9c4 100644 --- a/contrib/pg_upgrade/pg_upgrade.c +++ b/contrib/pg_upgrade/pg_upgrade.c @@ -50,6 +50,11 @@ static void copy_clog_xlog_xid(void); static void set_frozenxids(void); static void setup(char *argv0, bool live_check); static void cleanup(void); +static void get_restricted_token(void); + +#ifdef WIN32 +static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo); +#endif ClusterInfo old_cluster, new_cluster; @@ -67,6 +72,9 @@ char *output_files[] = { NULL }; +#ifdef WIN32 +static char *restrict_env; +#endif int main(int argc, char **argv) @@ -78,6 +86,8 @@ main(int argc, char **argv) parseCommandLine(argc, argv); + get_restricted_token(); + adjust_data_dir(&old_cluster); adjust_data_dir(&new_cluster); @@ -170,6 +180,162 @@ main(int argc, char **argv) return 0; } +#ifdef WIN32 +typedef BOOL(WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); + +/* Windows API define missing from some versions of MingW headers */ +#ifndef DISABLE_MAX_PRIVILEGE +#define DISABLE_MAX_PRIVILEGE 0x1 +#endif + +/* +* Create a restricted token and execute the specified process with it. +* +* Returns 0 on failure, non-zero on success, same as CreateProcess(). +* +* On NT4, or any other system not containing the required functions, will +* NOT execute anything. +*/ +static int +CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo) +{ + BOOL b; + STARTUPINFO si; + HANDLE origToken; + HANDLE restrictedToken; + SID_IDENTIFIER_AUTHORITY NtAuthority = { SECURITY_NT_AUTHORITY }; + SID_AND_ATTRIBUTES dropSids[2]; + __CreateRestrictedToken _CreateRestrictedToken = NULL; + HANDLE Advapi32Handle; + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + + Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); + if (Advapi32Handle != NULL) + { + _CreateRestrictedToken = (__CreateRestrictedToken)GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); + } + + if (_CreateRestrictedToken == NULL) + { + fprintf(stderr, _("WARNING: cannot create restricted tokens on this platform\n")); + if (Advapi32Handle != NULL) + FreeLibrary(Advapi32Handle); + return 0; + } + + /* Open the current token to use as a base for the restricted one */ + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) + { + fprintf(stderr, _("could not open process token: error code %lu\n"), GetLastError()); + return 0; + } + + /* Allocate list of SIDs to remove */ + ZeroMemory(&dropSids, sizeof(dropSids)); + if (!AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, + 0, &dropSids[0].Sid) || + !AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, + 0, &dropSids[1].Sid)) + { + fprintf(stderr, _("could not to allocate SIDs: error code %lu\n"), GetLastError()); + return 0; + } + + b = _CreateRestrictedToken(origToken, + DISABLE_MAX_PRIVILEGE, + sizeof(dropSids) / sizeof(dropSids[0]), + dropSids, + 0, NULL, + 0, NULL, + &restrictedToken); + + FreeSid(dropSids[1].Sid); + FreeSid(dropSids[0].Sid); + CloseHandle(origToken); + FreeLibrary(Advapi32Handle); + + if (!b) + { + fprintf(stderr, _("could not create restricted token: error code %lu\n"), GetLastError()); + return 0; + } + +#ifndef __CYGWIN__ + AddUserToTokenDacl(restrictedToken); +#endif + + if (!CreateProcessAsUser(restrictedToken, + NULL, + cmd, + NULL, + NULL, + TRUE, + CREATE_SUSPENDED, + NULL, + NULL, + &si, + processInfo)) + + { + fprintf(stderr, _("could not start process for command \"%s\": error code %lu\n"), cmd, GetLastError()); + return 0; + } + + return ResumeThread(processInfo->hThread); +} +#endif + +void +get_restricted_token(void) +{ +#ifdef WIN32 + + /* + * Before we execute another program, make sure that we are running with a + * restricted token. If not, re-execute ourselves with one. + */ + + if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL + || strcmp(restrict_env, "1") != 0) + { + PROCESS_INFORMATION pi; + char *cmdline; + + ZeroMemory(&pi, sizeof(pi)); + + cmdline = pg_strdup(GetCommandLine()); + + putenv("PG_RESTRICT_EXEC=1"); + + if (!CreateRestrictedProcess(cmdline, &pi)) + { + fprintf(stderr, _("could not re-execute with restricted token: error code %lu\n"), GetLastError()); + } + else + { + /* + * Successfully re-execed. Now wait for child process to capture + * exitcode. + */ + DWORD x; + + CloseHandle(pi.hThread); + WaitForSingleObject(pi.hProcess, INFINITE); + + if (!GetExitCodeProcess(pi.hProcess, &x)) + { + fprintf(stderr, _("could not get exit code from subprocess: error code %lu\n"), GetLastError()); + exit(1); + } + exit(x); + } + } +#endif +} static void setup(char *argv0, bool live_check) diff --git a/src/bin/pg_resetxlog/pg_resetxlog.c b/src/bin/pg_resetxlog/pg_resetxlog.c index 92d98fc..f8aeab7 100644 --- a/src/bin/pg_resetxlog/pg_resetxlog.c +++ b/src/bin/pg_resetxlog/pg_resetxlog.c @@ -65,6 +65,10 @@ static uint32 newXlogId, static bool guessed = false; /* T if we had to guess at any values */ static const char *progname; +#ifdef WIN32 +static char *restrict_env; +#endif + static bool ReadControlFile(void); static void GuessControlValues(void); static void PrintControlValues(bool guessed); @@ -74,7 +78,11 @@ static void KillExistingXLOG(void); static void KillExistingArchiveStatus(void); static void WriteEmptyXLOG(void); static void usage(void); +static void get_restricted_token(void); +#ifdef WIN32 +static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo); +#endif int main(int argc, char *argv[]) @@ -256,6 +264,7 @@ main(int argc, char *argv[]) } #endif + get_restricted_token(); DataDir = argv[optind]; if (chdir(DataDir) < 0) @@ -380,6 +389,18 @@ main(int argc, char *argv[]) return 0; } +char * +pg_strdup(const char *str) +{ + char *result = strdup(str); + + if (!result) + { + fprintf(stderr, _("out of memory\n")); + exit(1); + } + return result; +} /* * Try to read the existing pg_control file. @@ -1022,6 +1043,162 @@ WriteEmptyXLOG(void) close(fd); } +#ifdef WIN32 +typedef BOOL(WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); + +/* Windows API define missing from some versions of MingW headers */ +#ifndef DISABLE_MAX_PRIVILEGE +#define DISABLE_MAX_PRIVILEGE 0x1 +#endif + +/* +* Create a restricted token and execute the specified process with it. +* +* Returns 0 on failure, non-zero on success, same as CreateProcess(). +* +* On NT4, or any other system not containing the required functions, will +* NOT execute anything. +*/ +static int +CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo) +{ + BOOL b; + STARTUPINFO si; + HANDLE origToken; + HANDLE restrictedToken; + SID_IDENTIFIER_AUTHORITY NtAuthority = { SECURITY_NT_AUTHORITY }; + SID_AND_ATTRIBUTES dropSids[2]; + __CreateRestrictedToken _CreateRestrictedToken = NULL; + HANDLE Advapi32Handle; + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + + Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); + if (Advapi32Handle != NULL) + { + _CreateRestrictedToken = (__CreateRestrictedToken)GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); + } + + if (_CreateRestrictedToken == NULL) + { + fprintf(stderr, _("%s: WARNING: cannot create restricted tokens on this platform\n"), progname); + if (Advapi32Handle != NULL) + FreeLibrary(Advapi32Handle); + return 0; + } + + /* Open the current token to use as a base for the restricted one */ + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) + { + fprintf(stderr, _("%s: could not open process token: error code %lu\n"), progname, GetLastError()); + return 0; + } + + /* Allocate list of SIDs to remove */ + ZeroMemory(&dropSids, sizeof(dropSids)); + if (!AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, + 0, &dropSids[0].Sid) || + !AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, + 0, &dropSids[1].Sid)) + { + fprintf(stderr, _("%s: could not to allocate SIDs: error code %lu\n"), progname, GetLastError()); + return 0; + } + + b = _CreateRestrictedToken(origToken, + DISABLE_MAX_PRIVILEGE, + sizeof(dropSids) / sizeof(dropSids[0]), + dropSids, + 0, NULL, + 0, NULL, + &restrictedToken); + + FreeSid(dropSids[1].Sid); + FreeSid(dropSids[0].Sid); + CloseHandle(origToken); + FreeLibrary(Advapi32Handle); + + if (!b) + { + fprintf(stderr, _("%s: could not create restricted token: error code %lu\n"), progname, GetLastError()); + return 0; + } + +#ifndef __CYGWIN__ + AddUserToTokenDacl(restrictedToken); +#endif + + if (!CreateProcessAsUser(restrictedToken, + NULL, + cmd, + NULL, + NULL, + TRUE, + CREATE_SUSPENDED, + NULL, + NULL, + &si, + processInfo)) + + { + fprintf(stderr, _("%s: could not start process for command \"%s\": error code %lu\n"), progname, cmd, GetLastError()); + return 0; + } + + return ResumeThread(processInfo->hThread); +} +#endif + +void +get_restricted_token(void) +{ +#ifdef WIN32 + + /* + * Before we execute another program, make sure that we are running with a + * restricted token. If not, re-execute ourselves with one. + */ + + if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL + || strcmp(restrict_env, "1") != 0) + { + PROCESS_INFORMATION pi; + char *cmdline; + + ZeroMemory(&pi, sizeof(pi)); + + cmdline = pg_strdup(GetCommandLine()); + + putenv("PG_RESTRICT_EXEC=1"); + + if (!CreateRestrictedProcess(cmdline, &pi)) + { + fprintf(stderr, _("%s: could not re-execute with restricted token: error code %lu\n"), progname, GetLastError()); + } + else + { + /* + * Successfully re-execed. Now wait for child process to capture + * exitcode. + */ + DWORD x; + + CloseHandle(pi.hThread); + WaitForSingleObject(pi.hProcess, INFINITE); + + if (!GetExitCodeProcess(pi.hProcess, &x)) + { + fprintf(stderr, _("%s: could not get exit code from subprocess: error code %lu\n"), progname, GetLastError()); + exit(1); + } + exit(x); + } + } +#endif +} static void usage(void)
pg_upgrade_pg_resetxlog.v1_93.patch (application/octet-stream, 10.1K) download diff --git a/contrib/pg_upgrade/pg_upgrade.c b/contrib/pg_upgrade/pg_upgrade.c index d7d8864..537ebff 100644 --- a/contrib/pg_upgrade/pg_upgrade.c +++ b/contrib/pg_upgrade/pg_upgrade.c @@ -50,6 +50,11 @@ static void copy_clog_xlog_xid(void); static void set_frozenxids(bool minmxid_only); static void setup(char *argv0, bool *live_check); static void cleanup(void); +static void get_restricted_token(void); + +#ifdef WIN32 +static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo); +#endif ClusterInfo old_cluster, new_cluster; @@ -66,6 +71,9 @@ char *output_files[] = { NULL }; +#ifdef WIN32 +static char *restrict_env; +#endif int main(int argc, char **argv) @@ -77,6 +85,8 @@ main(int argc, char **argv) parseCommandLine(argc, argv); + get_restricted_token(); + adjust_data_dir(&old_cluster); adjust_data_dir(&new_cluster); @@ -175,6 +185,162 @@ main(int argc, char **argv) return 0; } +#ifdef WIN32 +typedef BOOL(WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); + +/* Windows API define missing from some versions of MingW headers */ +#ifndef DISABLE_MAX_PRIVILEGE +#define DISABLE_MAX_PRIVILEGE 0x1 +#endif + +/* +* Create a restricted token and execute the specified process with it. +* +* Returns 0 on failure, non-zero on success, same as CreateProcess(). +* +* On NT4, or any other system not containing the required functions, will +* NOT execute anything. +*/ +static int +CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo) +{ + BOOL b; + STARTUPINFO si; + HANDLE origToken; + HANDLE restrictedToken; + SID_IDENTIFIER_AUTHORITY NtAuthority = { SECURITY_NT_AUTHORITY }; + SID_AND_ATTRIBUTES dropSids[2]; + __CreateRestrictedToken _CreateRestrictedToken = NULL; + HANDLE Advapi32Handle; + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + + Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); + if (Advapi32Handle != NULL) + { + _CreateRestrictedToken = (__CreateRestrictedToken)GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); + } + + if (_CreateRestrictedToken == NULL) + { + fprintf(stderr, _("WARNING: cannot create restricted tokens on this platform\n")); + if (Advapi32Handle != NULL) + FreeLibrary(Advapi32Handle); + return 0; + } + + /* Open the current token to use as a base for the restricted one */ + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) + { + fprintf(stderr, _("could not open process token: error code %lu\n"), GetLastError()); + return 0; + } + + /* Allocate list of SIDs to remove */ + ZeroMemory(&dropSids, sizeof(dropSids)); + if (!AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, + 0, &dropSids[0].Sid) || + !AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, + 0, &dropSids[1].Sid)) + { + fprintf(stderr, _("could not to allocate SIDs: error code %lu\n"), GetLastError()); + return 0; + } + + b = _CreateRestrictedToken(origToken, + DISABLE_MAX_PRIVILEGE, + sizeof(dropSids) / sizeof(dropSids[0]), + dropSids, + 0, NULL, + 0, NULL, + &restrictedToken); + + FreeSid(dropSids[1].Sid); + FreeSid(dropSids[0].Sid); + CloseHandle(origToken); + FreeLibrary(Advapi32Handle); + + if (!b) + { + fprintf(stderr, _("could not create restricted token: error code %lu\n"), GetLastError()); + return 0; + } + +#ifndef __CYGWIN__ + AddUserToTokenDacl(restrictedToken); +#endif + + if (!CreateProcessAsUser(restrictedToken, + NULL, + cmd, + NULL, + NULL, + TRUE, + CREATE_SUSPENDED, + NULL, + NULL, + &si, + processInfo)) + + { + fprintf(stderr, _("could not start process for command \"%s\": error code %lu\n"), cmd, GetLastError()); + return 0; + } + + return ResumeThread(processInfo->hThread); +} +#endif + +void +get_restricted_token(void) +{ +#ifdef WIN32 + + /* + * Before we execute another program, make sure that we are running with a + * restricted token. If not, re-execute ourselves with one. + */ + + if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL + || strcmp(restrict_env, "1") != 0) + { + PROCESS_INFORMATION pi; + char *cmdline; + + ZeroMemory(&pi, sizeof(pi)); + + cmdline = pg_strdup(GetCommandLine()); + + putenv("PG_RESTRICT_EXEC=1"); + + if (!CreateRestrictedProcess(cmdline, &pi)) + { + fprintf(stderr, _("could not re-execute with restricted token: error code %lu\n"), GetLastError()); + } + else + { + /* + * Successfully re-execed. Now wait for child process to capture + * exitcode. + */ + DWORD x; + + CloseHandle(pi.hThread); + WaitForSingleObject(pi.hProcess, INFINITE); + + if (!GetExitCodeProcess(pi.hProcess, &x)) + { + fprintf(stderr, _("could not get exit code from subprocess: error code %lu\n"), GetLastError()); + exit(1); + } + exit(x); + } + } +#endif +} static void setup(char *argv0, bool *live_check) diff --git a/src/bin/pg_resetxlog/pg_resetxlog.c b/src/bin/pg_resetxlog/pg_resetxlog.c index 38d03a3..c29864a 100644 --- a/src/bin/pg_resetxlog/pg_resetxlog.c +++ b/src/bin/pg_resetxlog/pg_resetxlog.c @@ -65,6 +65,10 @@ static XLogSegNo newXlogSegNo; /* new XLOG segment # */ static bool guessed = false; /* T if we had to guess at any values */ static const char *progname; +#ifdef WIN32 +static char *restrict_env; +#endif + static bool ReadControlFile(void); static void GuessControlValues(void); static void PrintControlValues(bool guessed); @@ -74,7 +78,11 @@ static void KillExistingXLOG(void); static void KillExistingArchiveStatus(void); static void WriteEmptyXLOG(void); static void usage(void); +static void get_restricted_token(void); +#ifdef WIN32 +static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo); +#endif int main(int argc, char *argv[]) @@ -260,6 +268,7 @@ main(int argc, char *argv[]) } #endif + get_restricted_token(); DataDir = argv[optind]; if (chdir(DataDir) < 0) @@ -1029,6 +1038,162 @@ WriteEmptyXLOG(void) close(fd); } +#ifdef WIN32 +typedef BOOL(WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); + +/* Windows API define missing from some versions of MingW headers */ +#ifndef DISABLE_MAX_PRIVILEGE +#define DISABLE_MAX_PRIVILEGE 0x1 +#endif + +/* +* Create a restricted token and execute the specified process with it. +* +* Returns 0 on failure, non-zero on success, same as CreateProcess(). +* +* On NT4, or any other system not containing the required functions, will +* NOT execute anything. +*/ +static int +CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo) +{ + BOOL b; + STARTUPINFO si; + HANDLE origToken; + HANDLE restrictedToken; + SID_IDENTIFIER_AUTHORITY NtAuthority = { SECURITY_NT_AUTHORITY }; + SID_AND_ATTRIBUTES dropSids[2]; + __CreateRestrictedToken _CreateRestrictedToken = NULL; + HANDLE Advapi32Handle; + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + + Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); + if (Advapi32Handle != NULL) + { + _CreateRestrictedToken = (__CreateRestrictedToken)GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); + } + + if (_CreateRestrictedToken == NULL) + { + fprintf(stderr, _("%s: WARNING: cannot create restricted tokens on this platform\n"), progname); + if (Advapi32Handle != NULL) + FreeLibrary(Advapi32Handle); + return 0; + } + + /* Open the current token to use as a base for the restricted one */ + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) + { + fprintf(stderr, _("%s: could not open process token: error code %lu\n"), progname, GetLastError()); + return 0; + } + + /* Allocate list of SIDs to remove */ + ZeroMemory(&dropSids, sizeof(dropSids)); + if (!AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, + 0, &dropSids[0].Sid) || + !AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, + 0, &dropSids[1].Sid)) + { + fprintf(stderr, _("%s: could not to allocate SIDs: error code %lu\n"), progname, GetLastError()); + return 0; + } + + b = _CreateRestrictedToken(origToken, + DISABLE_MAX_PRIVILEGE, + sizeof(dropSids) / sizeof(dropSids[0]), + dropSids, + 0, NULL, + 0, NULL, + &restrictedToken); + + FreeSid(dropSids[1].Sid); + FreeSid(dropSids[0].Sid); + CloseHandle(origToken); + FreeLibrary(Advapi32Handle); + + if (!b) + { + fprintf(stderr, _("%s: could not create restricted token: error code %lu\n"), progname, GetLastError()); + return 0; + } + +#ifndef __CYGWIN__ + AddUserToTokenDacl(restrictedToken); +#endif + + if (!CreateProcessAsUser(restrictedToken, + NULL, + cmd, + NULL, + NULL, + TRUE, + CREATE_SUSPENDED, + NULL, + NULL, + &si, + processInfo)) + + { + fprintf(stderr, _("%s: could not start process for command \"%s\": error code %lu\n"), progname, cmd, GetLastError()); + return 0; + } + + return ResumeThread(processInfo->hThread); +} +#endif + +void +get_restricted_token(void) +{ +#ifdef WIN32 + + /* + * Before we execute another program, make sure that we are running with a + * restricted token. If not, re-execute ourselves with one. + */ + + if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL + || strcmp(restrict_env, "1") != 0) + { + PROCESS_INFORMATION pi; + char *cmdline; + + ZeroMemory(&pi, sizeof(pi)); + + cmdline = pg_strdup(GetCommandLine()); + + putenv("PG_RESTRICT_EXEC=1"); + + if (!CreateRestrictedProcess(cmdline, &pi)) + { + fprintf(stderr, _("%s: could not re-execute with restricted token: error code %lu\n"), progname, GetLastError()); + } + else + { + /* + * Successfully re-execed. Now wait for child process to capture + * exitcode. + */ + DWORD x; + + CloseHandle(pi.hThread); + WaitForSingleObject(pi.hProcess, INFINITE); + + if (!GetExitCodeProcess(pi.hProcess, &x)) + { + fprintf(stderr, _("%s: could not get exit code from subprocess: error code %lu\n"), progname, GetLastError()); + exit(1); + } + exit(x); + } + } +#endif +} static void usage(void)
pg_upgrade_pg_resetxlog.v1_94.patch (application/octet-stream, 10.1K) download diff --git a/contrib/pg_upgrade/pg_upgrade.c b/contrib/pg_upgrade/pg_upgrade.c index 7a18e4e..169e7eb 100644 --- a/contrib/pg_upgrade/pg_upgrade.c +++ b/contrib/pg_upgrade/pg_upgrade.c @@ -49,6 +49,11 @@ static void copy_clog_xlog_xid(void); static void set_frozenxids(bool minmxid_only); static void setup(char *argv0, bool *live_check); static void cleanup(void); +static void get_restricted_token(void); + +#ifdef WIN32 +static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo); +#endif ClusterInfo old_cluster, new_cluster; @@ -65,6 +70,9 @@ char *output_files[] = { NULL }; +#ifdef WIN32 +static char *restrict_env; +#endif int main(int argc, char **argv) @@ -76,6 +84,8 @@ main(int argc, char **argv) parseCommandLine(argc, argv); + get_restricted_token(); + adjust_data_dir(&old_cluster); adjust_data_dir(&new_cluster); @@ -174,6 +184,162 @@ main(int argc, char **argv) return 0; } +#ifdef WIN32 +typedef BOOL(WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); + +/* Windows API define missing from some versions of MingW headers */ +#ifndef DISABLE_MAX_PRIVILEGE +#define DISABLE_MAX_PRIVILEGE 0x1 +#endif + +/* +* Create a restricted token and execute the specified process with it. +* +* Returns 0 on failure, non-zero on success, same as CreateProcess(). +* +* On NT4, or any other system not containing the required functions, will +* NOT execute anything. +*/ +static int +CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo) +{ + BOOL b; + STARTUPINFO si; + HANDLE origToken; + HANDLE restrictedToken; + SID_IDENTIFIER_AUTHORITY NtAuthority = { SECURITY_NT_AUTHORITY }; + SID_AND_ATTRIBUTES dropSids[2]; + __CreateRestrictedToken _CreateRestrictedToken = NULL; + HANDLE Advapi32Handle; + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + + Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); + if (Advapi32Handle != NULL) + { + _CreateRestrictedToken = (__CreateRestrictedToken)GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); + } + + if (_CreateRestrictedToken == NULL) + { + fprintf(stderr, _("WARNING: cannot create restricted tokens on this platform\n")); + if (Advapi32Handle != NULL) + FreeLibrary(Advapi32Handle); + return 0; + } + + /* Open the current token to use as a base for the restricted one */ + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) + { + fprintf(stderr, _("could not open process token: error code %lu\n"), GetLastError()); + return 0; + } + + /* Allocate list of SIDs to remove */ + ZeroMemory(&dropSids, sizeof(dropSids)); + if (!AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, + 0, &dropSids[0].Sid) || + !AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, + 0, &dropSids[1].Sid)) + { + fprintf(stderr, _("could not to allocate SIDs: error code %lu\n"), GetLastError()); + return 0; + } + + b = _CreateRestrictedToken(origToken, + DISABLE_MAX_PRIVILEGE, + sizeof(dropSids) / sizeof(dropSids[0]), + dropSids, + 0, NULL, + 0, NULL, + &restrictedToken); + + FreeSid(dropSids[1].Sid); + FreeSid(dropSids[0].Sid); + CloseHandle(origToken); + FreeLibrary(Advapi32Handle); + + if (!b) + { + fprintf(stderr, _("could not create restricted token: error code %lu\n"), GetLastError()); + return 0; + } + +#ifndef __CYGWIN__ + AddUserToTokenDacl(restrictedToken); +#endif + + if (!CreateProcessAsUser(restrictedToken, + NULL, + cmd, + NULL, + NULL, + TRUE, + CREATE_SUSPENDED, + NULL, + NULL, + &si, + processInfo)) + + { + fprintf(stderr, _("could not start process for command \"%s\": error code %lu\n"), cmd, GetLastError()); + return 0; + } + + return ResumeThread(processInfo->hThread); +} +#endif + +void +get_restricted_token(void) +{ +#ifdef WIN32 + + /* + * Before we execute another program, make sure that we are running with a + * restricted token. If not, re-execute ourselves with one. + */ + + if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL + || strcmp(restrict_env, "1") != 0) + { + PROCESS_INFORMATION pi; + char *cmdline; + + ZeroMemory(&pi, sizeof(pi)); + + cmdline = pg_strdup(GetCommandLine()); + + putenv("PG_RESTRICT_EXEC=1"); + + if (!CreateRestrictedProcess(cmdline, &pi)) + { + fprintf(stderr, _("could not re-execute with restricted token: error code %lu\n"), GetLastError()); + } + else + { + /* + * Successfully re-execed. Now wait for child process to capture + * exitcode. + */ + DWORD x; + + CloseHandle(pi.hThread); + WaitForSingleObject(pi.hProcess, INFINITE); + + if (!GetExitCodeProcess(pi.hProcess, &x)) + { + fprintf(stderr, _("could not get exit code from subprocess: error code %lu\n"), GetLastError()); + exit(1); + } + exit(x); + } + } +#endif +} static void setup(char *argv0, bool *live_check) diff --git a/src/bin/pg_resetxlog/pg_resetxlog.c b/src/bin/pg_resetxlog/pg_resetxlog.c index 302d005..55ffcd7 100644 --- a/src/bin/pg_resetxlog/pg_resetxlog.c +++ b/src/bin/pg_resetxlog/pg_resetxlog.c @@ -68,6 +68,10 @@ static MultiXactOffset set_mxoff = (MultiXactOffset) -1; static uint32 minXlogTli = 0; static XLogSegNo minXlogSegNo = 0; +#ifdef WIN32 +static char *restrict_env; +#endif + static bool ReadControlFile(void); static void GuessControlValues(void); static void PrintControlValues(bool guessed); @@ -78,6 +82,11 @@ static void KillExistingXLOG(void); static void KillExistingArchiveStatus(void); static void WriteEmptyXLOG(void); static void usage(void); +static void get_restricted_token(void); + +#ifdef WIN32 +static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo); +#endif int @@ -257,6 +266,7 @@ main(int argc, char *argv[]) } #endif + get_restricted_token(); DataDir = argv[optind]; if (chdir(DataDir) < 0) @@ -1072,6 +1082,162 @@ WriteEmptyXLOG(void) close(fd); } +#ifdef WIN32 +typedef BOOL(WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); + +/* Windows API define missing from some versions of MingW headers */ +#ifndef DISABLE_MAX_PRIVILEGE +#define DISABLE_MAX_PRIVILEGE 0x1 +#endif + +/* +* Create a restricted token and execute the specified process with it. +* +* Returns 0 on failure, non-zero on success, same as CreateProcess(). +* +* On NT4, or any other system not containing the required functions, will +* NOT execute anything. +*/ +static int +CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo) +{ + BOOL b; + STARTUPINFO si; + HANDLE origToken; + HANDLE restrictedToken; + SID_IDENTIFIER_AUTHORITY NtAuthority = { SECURITY_NT_AUTHORITY }; + SID_AND_ATTRIBUTES dropSids[2]; + __CreateRestrictedToken _CreateRestrictedToken = NULL; + HANDLE Advapi32Handle; + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + + Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); + if (Advapi32Handle != NULL) + { + _CreateRestrictedToken = (__CreateRestrictedToken)GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); + } + + if (_CreateRestrictedToken == NULL) + { + fprintf(stderr, _("%s: WARNING: cannot create restricted tokens on this platform\n"), progname); + if (Advapi32Handle != NULL) + FreeLibrary(Advapi32Handle); + return 0; + } + + /* Open the current token to use as a base for the restricted one */ + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) + { + fprintf(stderr, _("%s: could not open process token: error code %lu\n"), progname, GetLastError()); + return 0; + } + + /* Allocate list of SIDs to remove */ + ZeroMemory(&dropSids, sizeof(dropSids)); + if (!AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, + 0, &dropSids[0].Sid) || + !AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, + 0, &dropSids[1].Sid)) + { + fprintf(stderr, _("%s: could not to allocate SIDs: error code %lu\n"), progname, GetLastError()); + return 0; + } + + b = _CreateRestrictedToken(origToken, + DISABLE_MAX_PRIVILEGE, + sizeof(dropSids) / sizeof(dropSids[0]), + dropSids, + 0, NULL, + 0, NULL, + &restrictedToken); + + FreeSid(dropSids[1].Sid); + FreeSid(dropSids[0].Sid); + CloseHandle(origToken); + FreeLibrary(Advapi32Handle); + + if (!b) + { + fprintf(stderr, _("%s: could not create restricted token: error code %lu\n"), progname, GetLastError()); + return 0; + } + +#ifndef __CYGWIN__ + AddUserToTokenDacl(restrictedToken); +#endif + + if (!CreateProcessAsUser(restrictedToken, + NULL, + cmd, + NULL, + NULL, + TRUE, + CREATE_SUSPENDED, + NULL, + NULL, + &si, + processInfo)) + + { + fprintf(stderr, _("%s: could not start process for command \"%s\": error code %lu\n"), progname, cmd, GetLastError()); + return 0; + } + + return ResumeThread(processInfo->hThread); +} +#endif + +void +get_restricted_token(void) +{ +#ifdef WIN32 + + /* + * Before we execute another program, make sure that we are running with a + * restricted token. If not, re-execute ourselves with one. + */ + + if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL + || strcmp(restrict_env, "1") != 0) + { + PROCESS_INFORMATION pi; + char *cmdline; + + ZeroMemory(&pi, sizeof(pi)); + + cmdline = pg_strdup(GetCommandLine()); + + putenv("PG_RESTRICT_EXEC=1"); + + if (!CreateRestrictedProcess(cmdline, &pi)) + { + fprintf(stderr, _("%s: could not re-execute with restricted token: error code %lu\n"), progname, GetLastError()); + } + else + { + /* + * Successfully re-execed. Now wait for child process to capture + * exitcode. + */ + DWORD x; + + CloseHandle(pi.hThread); + WaitForSingleObject(pi.hProcess, INFINITE); + + if (!GetExitCodeProcess(pi.hProcess, &x)) + { + fprintf(stderr, _("%s: could not get exit code from subprocess: error code %lu\n"), progname, GetLastError()); + exit(1); + } + exit(x); + } + } +#endif +} static void usage(void)
^ permalink raw reply [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-03-21 12:09  Michael Paquier <michael.paquier@gmail.com>
  parent: Asif Naeem <anaeem.it@gmail.com>
  0 siblings, 1 reply; 35+ messages in thread

From: Michael Paquier @ 2015-03-21 12:09 UTC (permalink / raw)
  To: Asif Naeem <anaeem.it@gmail.com>; +Cc: Alvaro Herrera <alvherre@2ndquadrant.com>; Amit Kapila <amit.kapila16@gmail.com>; Bruce Momjian <bruce@momjian.us>; pgsql-bugs

On Fri, Mar 20, 2015 at 11:14 PM, Asif Naeem <anaeem.it@gmail.com> wrote:
>> For the backpatching, the patches sent previously here (=>
>>
>> http://www.postgresql.org/message-id/CAEB4t-OHNE95=n5U4ySsYkWipQsWeQuTBSJkaYJ63_1VzkzkhA@mail.gmail....)
>> are fine IMO. They simply consist of a copy of what is done in
>> initdb.c. Now, perhaps we had better apply the patch duplicating the
>> logic to all branches, including HEAD, first, see what the buildfarm
>> says, and then finish wrapping up the refactoring patch.
>
> PFA patch for older branches, v1 patch was not applying cleaning other than
> 94. Thanks.

Cool, thanks for all the patches!
Nothing to say about the patch on master, except this thing not fixed:
 #include "common/username.h"
+#include "common/restricted_token.h"
restricted_token.h should be declared before username.h.

In the back-branch patches, the format of the stderr messages is not
correct, and the suffix using progname is missing in pg_upgrade. For
example, this thing:
+               fprintf(stderr, _("could not open process token: error
code %lu\n"), GetLastError());
Should be rewritten like that for consistency with master and the
other utilities:
fprintf(stderr, _("%s: could not open process token: error code
%lu\n"), progname, GetLastError());
Perhaps now Bruce has a different opinion on the matter for pg_upgrade...

The 9.0 patch is missing as well, but I guess that the committer who
will pick up this series could get something up using the 9.1 patch...

I have also done some sanity checks down to 9.2 (got some issues when
building with ~9.1), and noticed no problems.
Regards,
-- 
Michael


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-03-24 10:48  Asif Naeem <anaeem.it@gmail.com>
  parent: Michael Paquier <michael.paquier@gmail.com>
  0 siblings, 1 reply; 35+ messages in thread

From: Asif Naeem @ 2015-03-24 10:48 UTC (permalink / raw)
  To: Michael Paquier <michael.paquier@gmail.com>; +Cc: Alvaro Herrera <alvherre@2ndquadrant.com>; Amit Kapila <amit.kapila16@gmail.com>; Bruce Momjian <bruce@momjian.us>; pgsql-bugs

On Sat, Mar 21, 2015 at 5:09 PM, Michael Paquier <michael.paquier@gmail.com>
wrote:

> On Fri, Mar 20, 2015 at 11:14 PM, Asif Naeem <anaeem.it@gmail.com> wrote:
> >> For the backpatching, the patches sent previously here (=>
> >>
> >>
> http://www.postgresql.org/message-id/CAEB4t-OHNE95=n5U4ySsYkWipQsWeQuTBSJkaYJ63_1VzkzkhA@mail.gmail....
> )
> >> are fine IMO. They simply consist of a copy of what is done in
> >> initdb.c. Now, perhaps we had better apply the patch duplicating the
> >> logic to all branches, including HEAD, first, see what the buildfarm
> >> says, and then finish wrapping up the refactoring patch.
> >
> > PFA patch for older branches, v1 patch was not applying cleaning other
> than
> > 94. Thanks.
>
> Cool, thanks for all the patches!
> Nothing to say about the patch on master, except this thing not fixed:
>  #include "common/username.h"
> +#include "common/restricted_token.h"
> restricted_token.h should be declared before username.h.
>

Oops, I did not realized that it require to be changed on multiple places,
PFA updated v6 patch for master branch.


> In the back-branch patches, the format of the stderr messages is not
> correct, and the suffix using progname is missing in pg_upgrade. For
> example, this thing:
> +               fprintf(stderr, _("could not open process token: error
> code %lu\n"), GetLastError());
> Should be rewritten like that for consistency with master and the
> other utilities:
> fprintf(stderr, _("%s: could not open process token: error code
> %lu\n"), progname, GetLastError());
> Perhaps now Bruce has a different opinion on the matter for pg_upgrade...
>

Okey sure, PFA updated patches for older branches, now it accepts progname
as a argument as master branch patch do.


> The 9.0 patch is missing as well, but I guess that the committer who
> will pick up this series could get something up using the 9.1 patch...
>

Ah. Okey. I was not sure till which back branch it need to fixed. PFA patch
for 90 branch.


> I have also done some sanity checks down to 9.2 (got some issues when
> building with ~9.1), and noticed no problems.
>

Thank you so much. I hope now there is nothing left from my side :).


> Regards,
> --
> Michael
>

-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs

Attachments: download all (6 files, .tar.gz)

pg_upgrade_pg_resetxlog.v2_91.patch (application/octet-stream, 10.8K) download diff --git a/contrib/pg_upgrade/pg_upgrade.c b/contrib/pg_upgrade/pg_upgrade.c index b294d7b..fad7f6c 100644 --- a/contrib/pg_upgrade/pg_upgrade.c +++ b/contrib/pg_upgrade/pg_upgrade.c @@ -49,6 +49,11 @@ static void copy_clog_xlog_xid(void); static void set_frozenxids(void); static void setup(char *argv0, bool live_check); static void cleanup(void); +static void get_restricted_token(const char *progname); + +#ifdef WIN32 +static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, const char *progname); +#endif /* This is the database used by pg_dumpall to restore global tables */ #define GLOBAL_DUMP_DB "postgres" @@ -57,6 +62,10 @@ ClusterInfo old_cluster, new_cluster; OSInfo os_info; +#ifdef WIN32 +static char *restrict_env; +#endif + int main(int argc, char **argv) { @@ -66,6 +75,8 @@ main(int argc, char **argv) parseCommandLine(argc, argv); + get_restricted_token(os_info.progname); + output_check_banner(&live_check); setup(argv[0], live_check); @@ -139,6 +150,162 @@ main(int argc, char **argv) return 0; } +#ifdef WIN32 +typedef BOOL(WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); + +/* Windows API define missing from some versions of MingW headers */ +#ifndef DISABLE_MAX_PRIVILEGE +#define DISABLE_MAX_PRIVILEGE 0x1 +#endif + +/* +* Create a restricted token and execute the specified process with it. +* +* Returns 0 on failure, non-zero on success, same as CreateProcess(). +* +* On NT4, or any other system not containing the required functions, will +* NOT execute anything. +*/ +static int +CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, const char *progname) +{ + BOOL b; + STARTUPINFO si; + HANDLE origToken; + HANDLE restrictedToken; + SID_IDENTIFIER_AUTHORITY NtAuthority = { SECURITY_NT_AUTHORITY }; + SID_AND_ATTRIBUTES dropSids[2]; + __CreateRestrictedToken _CreateRestrictedToken = NULL; + HANDLE Advapi32Handle; + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + + Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); + if (Advapi32Handle != NULL) + { + _CreateRestrictedToken = (__CreateRestrictedToken)GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); + } + + if (_CreateRestrictedToken == NULL) + { + fprintf(stderr, _("%s: WARNING: cannot create restricted tokens on this platform\n"), progname); + if (Advapi32Handle != NULL) + FreeLibrary(Advapi32Handle); + return 0; + } + + /* Open the current token to use as a base for the restricted one */ + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) + { + fprintf(stderr, _("%s: could not open process token: error code %lu\n"), progname, GetLastError()); + return 0; + } + + /* Allocate list of SIDs to remove */ + ZeroMemory(&dropSids, sizeof(dropSids)); + if (!AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, + 0, &dropSids[0].Sid) || + !AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, + 0, &dropSids[1].Sid)) + { + fprintf(stderr, _("%s: could not to allocate SIDs: error code %lu\n"), progname, GetLastError()); + return 0; + } + + b = _CreateRestrictedToken(origToken, + DISABLE_MAX_PRIVILEGE, + sizeof(dropSids) / sizeof(dropSids[0]), + dropSids, + 0, NULL, + 0, NULL, + &restrictedToken); + + FreeSid(dropSids[1].Sid); + FreeSid(dropSids[0].Sid); + CloseHandle(origToken); + FreeLibrary(Advapi32Handle); + + if (!b) + { + fprintf(stderr, _("%s: could not create restricted token: error code %lu\n"), progname, GetLastError()); + return 0; + } + +#ifndef __CYGWIN__ + AddUserToTokenDacl(restrictedToken); +#endif + + if (!CreateProcessAsUser(restrictedToken, + NULL, + cmd, + NULL, + NULL, + TRUE, + CREATE_SUSPENDED, + NULL, + NULL, + &si, + processInfo)) + + { + fprintf(stderr, _("%s: could not start process for command \"%s\": error code %lu\n"), progname, cmd, GetLastError()); + return 0; + } + + return ResumeThread(processInfo->hThread); +} +#endif + +void +get_restricted_token(const char *progname) +{ +#ifdef WIN32 + + /* + * Before we execute another program, make sure that we are running with a + * restricted token. If not, re-execute ourselves with one. + */ + + if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL + || strcmp(restrict_env, "1") != 0) + { + PROCESS_INFORMATION pi; + char *cmdline; + + ZeroMemory(&pi, sizeof(pi)); + + cmdline = pg_strdup(GetCommandLine()); + + putenv("PG_RESTRICT_EXEC=1"); + + if (!CreateRestrictedProcess(cmdline, &pi, progname)) + { + fprintf(stderr, _("%s: could not re-execute with restricted token: error code %lu\n"), progname, GetLastError()); + } + else + { + /* + * Successfully re-execed. Now wait for child process to capture + * exitcode. + */ + DWORD x; + + CloseHandle(pi.hThread); + WaitForSingleObject(pi.hProcess, INFINITE); + + if (!GetExitCodeProcess(pi.hProcess, &x)) + { + fprintf(stderr, _("%s: could not get exit code from subprocess: error code %lu\n"), progname, GetLastError()); + exit(1); + } + exit(x); + } + } +#endif +} static void setup(char *argv0, bool live_check) diff --git a/src/bin/pg_resetxlog/pg_resetxlog.c b/src/bin/pg_resetxlog/pg_resetxlog.c index d1b12dc..690e94b 100644 --- a/src/bin/pg_resetxlog/pg_resetxlog.c +++ b/src/bin/pg_resetxlog/pg_resetxlog.c @@ -65,6 +65,10 @@ static uint32 newXlogId, static bool guessed = false; /* T if we had to guess at any values */ static const char *progname; +#ifdef WIN32 +static char *restrict_env; +#endif + static bool ReadControlFile(void); static void GuessControlValues(void); static void PrintControlValues(bool guessed); @@ -74,7 +78,11 @@ static void KillExistingXLOG(void); static void KillExistingArchiveStatus(void); static void WriteEmptyXLOG(void); static void usage(void); +static void get_restricted_token(const char *progname); +#ifdef WIN32 +static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, const char *progname); +#endif int main(int argc, char *argv[]) @@ -256,6 +264,7 @@ main(int argc, char *argv[]) } #endif + get_restricted_token(progname); DataDir = argv[optind]; if (chdir(DataDir) < 0) @@ -380,6 +389,18 @@ main(int argc, char *argv[]) return 0; } +char * +pg_strdup(const char *str) +{ + char *result = strdup(str); + + if (!result) + { + fprintf(stderr, _("out of memory\n")); + exit(1); + } + return result; +} /* * Try to read the existing pg_control file. @@ -1016,6 +1037,162 @@ WriteEmptyXLOG(void) close(fd); } +#ifdef WIN32 +typedef BOOL(WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); + +/* Windows API define missing from some versions of MingW headers */ +#ifndef DISABLE_MAX_PRIVILEGE +#define DISABLE_MAX_PRIVILEGE 0x1 +#endif + +/* +* Create a restricted token and execute the specified process with it. +* +* Returns 0 on failure, non-zero on success, same as CreateProcess(). +* +* On NT4, or any other system not containing the required functions, will +* NOT execute anything. +*/ +static int +CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, const char *progname) +{ + BOOL b; + STARTUPINFO si; + HANDLE origToken; + HANDLE restrictedToken; + SID_IDENTIFIER_AUTHORITY NtAuthority = { SECURITY_NT_AUTHORITY }; + SID_AND_ATTRIBUTES dropSids[2]; + __CreateRestrictedToken _CreateRestrictedToken = NULL; + HANDLE Advapi32Handle; + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + + Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); + if (Advapi32Handle != NULL) + { + _CreateRestrictedToken = (__CreateRestrictedToken)GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); + } + + if (_CreateRestrictedToken == NULL) + { + fprintf(stderr, _("%s: WARNING: cannot create restricted tokens on this platform\n"), progname); + if (Advapi32Handle != NULL) + FreeLibrary(Advapi32Handle); + return 0; + } + + /* Open the current token to use as a base for the restricted one */ + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) + { + fprintf(stderr, _("%s: could not open process token: error code %lu\n"), progname, GetLastError()); + return 0; + } + + /* Allocate list of SIDs to remove */ + ZeroMemory(&dropSids, sizeof(dropSids)); + if (!AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, + 0, &dropSids[0].Sid) || + !AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, + 0, &dropSids[1].Sid)) + { + fprintf(stderr, _("%s: could not to allocate SIDs: error code %lu\n"), progname, GetLastError()); + return 0; + } + + b = _CreateRestrictedToken(origToken, + DISABLE_MAX_PRIVILEGE, + sizeof(dropSids) / sizeof(dropSids[0]), + dropSids, + 0, NULL, + 0, NULL, + &restrictedToken); + + FreeSid(dropSids[1].Sid); + FreeSid(dropSids[0].Sid); + CloseHandle(origToken); + FreeLibrary(Advapi32Handle); + + if (!b) + { + fprintf(stderr, _("%s: could not create restricted token: error code %lu\n"), progname, GetLastError()); + return 0; + } + +#ifndef __CYGWIN__ + AddUserToTokenDacl(restrictedToken); +#endif + + if (!CreateProcessAsUser(restrictedToken, + NULL, + cmd, + NULL, + NULL, + TRUE, + CREATE_SUSPENDED, + NULL, + NULL, + &si, + processInfo)) + + { + fprintf(stderr, _("%s: could not start process for command \"%s\": error code %lu\n"), progname, cmd, GetLastError()); + return 0; + } + + return ResumeThread(processInfo->hThread); +} +#endif + +void +get_restricted_token(const char *progname) +{ +#ifdef WIN32 + + /* + * Before we execute another program, make sure that we are running with a + * restricted token. If not, re-execute ourselves with one. + */ + + if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL + || strcmp(restrict_env, "1") != 0) + { + PROCESS_INFORMATION pi; + char *cmdline; + + ZeroMemory(&pi, sizeof(pi)); + + cmdline = pg_strdup(GetCommandLine()); + + putenv("PG_RESTRICT_EXEC=1"); + + if (!CreateRestrictedProcess(cmdline, &pi, progname)) + { + fprintf(stderr, _("%s: could not re-execute with restricted token: error code %lu\n"), progname, GetLastError()); + } + else + { + /* + * Successfully re-execed. Now wait for child process to capture + * exitcode. + */ + DWORD x; + + CloseHandle(pi.hThread); + WaitForSingleObject(pi.hProcess, INFINITE); + + if (!GetExitCodeProcess(pi.hProcess, &x)) + { + fprintf(stderr, _("%s: could not get exit code from subprocess: error code %lu\n"), progname, GetLastError()); + exit(1); + } + exit(x); + } + } +#endif +} static void usage(void)
pg_upgrade_pg_resetxlog.v2_92.patch (application/octet-stream, 10.7K) download diff --git a/contrib/pg_upgrade/pg_upgrade.c b/contrib/pg_upgrade/pg_upgrade.c index a106511..b12d9c4 100644 --- a/contrib/pg_upgrade/pg_upgrade.c +++ b/contrib/pg_upgrade/pg_upgrade.c @@ -50,6 +50,11 @@ static void copy_clog_xlog_xid(void); static void set_frozenxids(void); static void setup(char *argv0, bool live_check); static void cleanup(void); +static void get_restricted_token(const char *progname); + +#ifdef WIN32 +static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, const char *progname); +#endif ClusterInfo old_cluster, new_cluster; @@ -67,6 +72,9 @@ char *output_files[] = { NULL }; +#ifdef WIN32 +static char *restrict_env; +#endif int main(int argc, char **argv) @@ -78,6 +86,8 @@ main(int argc, char **argv) parseCommandLine(argc, argv); + get_restricted_token(os_info.progname); + adjust_data_dir(&old_cluster); adjust_data_dir(&new_cluster); @@ -170,6 +180,162 @@ main(int argc, char **argv) return 0; } +#ifdef WIN32 +typedef BOOL(WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); + +/* Windows API define missing from some versions of MingW headers */ +#ifndef DISABLE_MAX_PRIVILEGE +#define DISABLE_MAX_PRIVILEGE 0x1 +#endif + +/* +* Create a restricted token and execute the specified process with it. +* +* Returns 0 on failure, non-zero on success, same as CreateProcess(). +* +* On NT4, or any other system not containing the required functions, will +* NOT execute anything. +*/ +static int +CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, const char *progname) +{ + BOOL b; + STARTUPINFO si; + HANDLE origToken; + HANDLE restrictedToken; + SID_IDENTIFIER_AUTHORITY NtAuthority = { SECURITY_NT_AUTHORITY }; + SID_AND_ATTRIBUTES dropSids[2]; + __CreateRestrictedToken _CreateRestrictedToken = NULL; + HANDLE Advapi32Handle; + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + + Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); + if (Advapi32Handle != NULL) + { + _CreateRestrictedToken = (__CreateRestrictedToken)GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); + } + + if (_CreateRestrictedToken == NULL) + { + fprintf(stderr, _("%s: WARNING: cannot create restricted tokens on this platform\n"), progname); + if (Advapi32Handle != NULL) + FreeLibrary(Advapi32Handle); + return 0; + } + + /* Open the current token to use as a base for the restricted one */ + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) + { + fprintf(stderr, _("%s: could not open process token: error code %lu\n"), progname, GetLastError()); + return 0; + } + + /* Allocate list of SIDs to remove */ + ZeroMemory(&dropSids, sizeof(dropSids)); + if (!AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, + 0, &dropSids[0].Sid) || + !AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, + 0, &dropSids[1].Sid)) + { + fprintf(stderr, _("%s: could not to allocate SIDs: error code %lu\n"), progname, GetLastError()); + return 0; + } + + b = _CreateRestrictedToken(origToken, + DISABLE_MAX_PRIVILEGE, + sizeof(dropSids) / sizeof(dropSids[0]), + dropSids, + 0, NULL, + 0, NULL, + &restrictedToken); + + FreeSid(dropSids[1].Sid); + FreeSid(dropSids[0].Sid); + CloseHandle(origToken); + FreeLibrary(Advapi32Handle); + + if (!b) + { + fprintf(stderr, _("%s: could not create restricted token: error code %lu\n"), progname, GetLastError()); + return 0; + } + +#ifndef __CYGWIN__ + AddUserToTokenDacl(restrictedToken); +#endif + + if (!CreateProcessAsUser(restrictedToken, + NULL, + cmd, + NULL, + NULL, + TRUE, + CREATE_SUSPENDED, + NULL, + NULL, + &si, + processInfo)) + + { + fprintf(stderr, _("%s: could not start process for command \"%s\": error code %lu\n"), progname, cmd, GetLastError()); + return 0; + } + + return ResumeThread(processInfo->hThread); +} +#endif + +void +get_restricted_token(const char *progname) +{ +#ifdef WIN32 + + /* + * Before we execute another program, make sure that we are running with a + * restricted token. If not, re-execute ourselves with one. + */ + + if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL + || strcmp(restrict_env, "1") != 0) + { + PROCESS_INFORMATION pi; + char *cmdline; + + ZeroMemory(&pi, sizeof(pi)); + + cmdline = pg_strdup(GetCommandLine()); + + putenv("PG_RESTRICT_EXEC=1"); + + if (!CreateRestrictedProcess(cmdline, &pi, progname)) + { + fprintf(stderr, _("%s: could not re-execute with restricted token: error code %lu\n"), progname, GetLastError()); + } + else + { + /* + * Successfully re-execed. Now wait for child process to capture + * exitcode. + */ + DWORD x; + + CloseHandle(pi.hThread); + WaitForSingleObject(pi.hProcess, INFINITE); + + if (!GetExitCodeProcess(pi.hProcess, &x)) + { + fprintf(stderr, _("%s: could not get exit code from subprocess: error code %lu\n"), progname, GetLastError()); + exit(1); + } + exit(x); + } + } +#endif +} static void setup(char *argv0, bool live_check) diff --git a/src/bin/pg_resetxlog/pg_resetxlog.c b/src/bin/pg_resetxlog/pg_resetxlog.c index 92d98fc..f8aeab7 100644 --- a/src/bin/pg_resetxlog/pg_resetxlog.c +++ b/src/bin/pg_resetxlog/pg_resetxlog.c @@ -65,6 +65,10 @@ static uint32 newXlogId, static bool guessed = false; /* T if we had to guess at any values */ static const char *progname; +#ifdef WIN32 +static char *restrict_env; +#endif + static bool ReadControlFile(void); static void GuessControlValues(void); static void PrintControlValues(bool guessed); @@ -74,7 +78,11 @@ static void KillExistingXLOG(void); static void KillExistingArchiveStatus(void); static void WriteEmptyXLOG(void); static void usage(void); +static void get_restricted_token(const char *progname); +#ifdef WIN32 +static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, const char *progname); +#endif int main(int argc, char *argv[]) @@ -256,6 +264,7 @@ main(int argc, char *argv[]) } #endif + get_restricted_token(progname); DataDir = argv[optind]; if (chdir(DataDir) < 0) @@ -380,6 +389,18 @@ main(int argc, char *argv[]) return 0; } +char * +pg_strdup(const char *str) +{ + char *result = strdup(str); + + if (!result) + { + fprintf(stderr, _("out of memory\n")); + exit(1); + } + return result; +} /* * Try to read the existing pg_control file. @@ -1022,6 +1043,162 @@ WriteEmptyXLOG(void) close(fd); } +#ifdef WIN32 +typedef BOOL(WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); + +/* Windows API define missing from some versions of MingW headers */ +#ifndef DISABLE_MAX_PRIVILEGE +#define DISABLE_MAX_PRIVILEGE 0x1 +#endif + +/* +* Create a restricted token and execute the specified process with it. +* +* Returns 0 on failure, non-zero on success, same as CreateProcess(). +* +* On NT4, or any other system not containing the required functions, will +* NOT execute anything. +*/ +static int +CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, const char *progname) +{ + BOOL b; + STARTUPINFO si; + HANDLE origToken; + HANDLE restrictedToken; + SID_IDENTIFIER_AUTHORITY NtAuthority = { SECURITY_NT_AUTHORITY }; + SID_AND_ATTRIBUTES dropSids[2]; + __CreateRestrictedToken _CreateRestrictedToken = NULL; + HANDLE Advapi32Handle; + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + + Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); + if (Advapi32Handle != NULL) + { + _CreateRestrictedToken = (__CreateRestrictedToken)GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); + } + + if (_CreateRestrictedToken == NULL) + { + fprintf(stderr, _("%s: WARNING: cannot create restricted tokens on this platform\n"), progname); + if (Advapi32Handle != NULL) + FreeLibrary(Advapi32Handle); + return 0; + } + + /* Open the current token to use as a base for the restricted one */ + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) + { + fprintf(stderr, _("%s: could not open process token: error code %lu\n"), progname, GetLastError()); + return 0; + } + + /* Allocate list of SIDs to remove */ + ZeroMemory(&dropSids, sizeof(dropSids)); + if (!AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, + 0, &dropSids[0].Sid) || + !AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, + 0, &dropSids[1].Sid)) + { + fprintf(stderr, _("%s: could not to allocate SIDs: error code %lu\n"), progname, GetLastError()); + return 0; + } + + b = _CreateRestrictedToken(origToken, + DISABLE_MAX_PRIVILEGE, + sizeof(dropSids) / sizeof(dropSids[0]), + dropSids, + 0, NULL, + 0, NULL, + &restrictedToken); + + FreeSid(dropSids[1].Sid); + FreeSid(dropSids[0].Sid); + CloseHandle(origToken); + FreeLibrary(Advapi32Handle); + + if (!b) + { + fprintf(stderr, _("%s: could not create restricted token: error code %lu\n"), progname, GetLastError()); + return 0; + } + +#ifndef __CYGWIN__ + AddUserToTokenDacl(restrictedToken); +#endif + + if (!CreateProcessAsUser(restrictedToken, + NULL, + cmd, + NULL, + NULL, + TRUE, + CREATE_SUSPENDED, + NULL, + NULL, + &si, + processInfo)) + + { + fprintf(stderr, _("%s: could not start process for command \"%s\": error code %lu\n"), progname, cmd, GetLastError()); + return 0; + } + + return ResumeThread(processInfo->hThread); +} +#endif + +void +get_restricted_token(const char *progname) +{ +#ifdef WIN32 + + /* + * Before we execute another program, make sure that we are running with a + * restricted token. If not, re-execute ourselves with one. + */ + + if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL + || strcmp(restrict_env, "1") != 0) + { + PROCESS_INFORMATION pi; + char *cmdline; + + ZeroMemory(&pi, sizeof(pi)); + + cmdline = pg_strdup(GetCommandLine()); + + putenv("PG_RESTRICT_EXEC=1"); + + if (!CreateRestrictedProcess(cmdline, &pi, progname)) + { + fprintf(stderr, _("%s: could not re-execute with restricted token: error code %lu\n"), progname, GetLastError()); + } + else + { + /* + * Successfully re-execed. Now wait for child process to capture + * exitcode. + */ + DWORD x; + + CloseHandle(pi.hThread); + WaitForSingleObject(pi.hProcess, INFINITE); + + if (!GetExitCodeProcess(pi.hProcess, &x)) + { + fprintf(stderr, _("%s: could not get exit code from subprocess: error code %lu\n"), progname, GetLastError()); + exit(1); + } + exit(x); + } + } +#endif +} static void usage(void)
pg_upgrade_pg_resetxlog.v2_94.patch (application/octet-stream, 10.4K) download diff --git a/contrib/pg_upgrade/pg_upgrade.c b/contrib/pg_upgrade/pg_upgrade.c index 7a18e4e..61f65c3 100644 --- a/contrib/pg_upgrade/pg_upgrade.c +++ b/contrib/pg_upgrade/pg_upgrade.c @@ -49,6 +49,11 @@ static void copy_clog_xlog_xid(void); static void set_frozenxids(bool minmxid_only); static void setup(char *argv0, bool *live_check); static void cleanup(void); +static void get_restricted_token(const char *progname); + +#ifdef WIN32 +static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, const char *progname); +#endif ClusterInfo old_cluster, new_cluster; @@ -65,6 +70,9 @@ char *output_files[] = { NULL }; +#ifdef WIN32 +static char *restrict_env; +#endif int main(int argc, char **argv) @@ -76,6 +84,8 @@ main(int argc, char **argv) parseCommandLine(argc, argv); + get_restricted_token(os_info.progname); + adjust_data_dir(&old_cluster); adjust_data_dir(&new_cluster); @@ -174,6 +184,162 @@ main(int argc, char **argv) return 0; } +#ifdef WIN32 +typedef BOOL(WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); + +/* Windows API define missing from some versions of MingW headers */ +#ifndef DISABLE_MAX_PRIVILEGE +#define DISABLE_MAX_PRIVILEGE 0x1 +#endif + +/* +* Create a restricted token and execute the specified process with it. +* +* Returns 0 on failure, non-zero on success, same as CreateProcess(). +* +* On NT4, or any other system not containing the required functions, will +* NOT execute anything. +*/ +static int +CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, const char *progname) +{ + BOOL b; + STARTUPINFO si; + HANDLE origToken; + HANDLE restrictedToken; + SID_IDENTIFIER_AUTHORITY NtAuthority = { SECURITY_NT_AUTHORITY }; + SID_AND_ATTRIBUTES dropSids[2]; + __CreateRestrictedToken _CreateRestrictedToken = NULL; + HANDLE Advapi32Handle; + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + + Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); + if (Advapi32Handle != NULL) + { + _CreateRestrictedToken = (__CreateRestrictedToken)GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); + } + + if (_CreateRestrictedToken == NULL) + { + fprintf(stderr, _("%s: WARNING: cannot create restricted tokens on this platform\n"), progname); + if (Advapi32Handle != NULL) + FreeLibrary(Advapi32Handle); + return 0; + } + + /* Open the current token to use as a base for the restricted one */ + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) + { + fprintf(stderr, _("%s: could not open process token: error code %lu\n"), progname, GetLastError()); + return 0; + } + + /* Allocate list of SIDs to remove */ + ZeroMemory(&dropSids, sizeof(dropSids)); + if (!AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, + 0, &dropSids[0].Sid) || + !AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, + 0, &dropSids[1].Sid)) + { + fprintf(stderr, _("%s: could not to allocate SIDs: error code %lu\n"), progname, GetLastError()); + return 0; + } + + b = _CreateRestrictedToken(origToken, + DISABLE_MAX_PRIVILEGE, + sizeof(dropSids) / sizeof(dropSids[0]), + dropSids, + 0, NULL, + 0, NULL, + &restrictedToken); + + FreeSid(dropSids[1].Sid); + FreeSid(dropSids[0].Sid); + CloseHandle(origToken); + FreeLibrary(Advapi32Handle); + + if (!b) + { + fprintf(stderr, _("%s: could not create restricted token: error code %lu\n"), progname, GetLastError()); + return 0; + } + +#ifndef __CYGWIN__ + AddUserToTokenDacl(restrictedToken); +#endif + + if (!CreateProcessAsUser(restrictedToken, + NULL, + cmd, + NULL, + NULL, + TRUE, + CREATE_SUSPENDED, + NULL, + NULL, + &si, + processInfo)) + + { + fprintf(stderr, _("%s: could not start process for command \"%s\": error code %lu\n"), progname, cmd, GetLastError()); + return 0; + } + + return ResumeThread(processInfo->hThread); +} +#endif + +void +get_restricted_token(const char *progname) +{ +#ifdef WIN32 + + /* + * Before we execute another program, make sure that we are running with a + * restricted token. If not, re-execute ourselves with one. + */ + + if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL + || strcmp(restrict_env, "1") != 0) + { + PROCESS_INFORMATION pi; + char *cmdline; + + ZeroMemory(&pi, sizeof(pi)); + + cmdline = pg_strdup(GetCommandLine()); + + putenv("PG_RESTRICT_EXEC=1"); + + if (!CreateRestrictedProcess(cmdline, &pi, progname)) + { + fprintf(stderr, _("%s: could not re-execute with restricted token: error code %lu\n"), progname, GetLastError()); + } + else + { + /* + * Successfully re-execed. Now wait for child process to capture + * exitcode. + */ + DWORD x; + + CloseHandle(pi.hThread); + WaitForSingleObject(pi.hProcess, INFINITE); + + if (!GetExitCodeProcess(pi.hProcess, &x)) + { + fprintf(stderr, _("%s: could not get exit code from subprocess: error code %lu\n"), progname, GetLastError()); + exit(1); + } + exit(x); + } + } +#endif +} static void setup(char *argv0, bool *live_check) diff --git a/src/bin/pg_resetxlog/pg_resetxlog.c b/src/bin/pg_resetxlog/pg_resetxlog.c index 302d005..fe8c8d6 100644 --- a/src/bin/pg_resetxlog/pg_resetxlog.c +++ b/src/bin/pg_resetxlog/pg_resetxlog.c @@ -68,6 +68,10 @@ static MultiXactOffset set_mxoff = (MultiXactOffset) -1; static uint32 minXlogTli = 0; static XLogSegNo minXlogSegNo = 0; +#ifdef WIN32 +static char *restrict_env; +#endif + static bool ReadControlFile(void); static void GuessControlValues(void); static void PrintControlValues(bool guessed); @@ -78,6 +82,11 @@ static void KillExistingXLOG(void); static void KillExistingArchiveStatus(void); static void WriteEmptyXLOG(void); static void usage(void); +static void get_restricted_token(const char *progname); + +#ifdef WIN32 +static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, const char *progname); +#endif int @@ -257,6 +266,7 @@ main(int argc, char *argv[]) } #endif + get_restricted_token(progname); DataDir = argv[optind]; if (chdir(DataDir) < 0) @@ -1072,6 +1082,162 @@ WriteEmptyXLOG(void) close(fd); } +#ifdef WIN32 +typedef BOOL(WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); + +/* Windows API define missing from some versions of MingW headers */ +#ifndef DISABLE_MAX_PRIVILEGE +#define DISABLE_MAX_PRIVILEGE 0x1 +#endif + +/* +* Create a restricted token and execute the specified process with it. +* +* Returns 0 on failure, non-zero on success, same as CreateProcess(). +* +* On NT4, or any other system not containing the required functions, will +* NOT execute anything. +*/ +static int +CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, const char *progname) +{ + BOOL b; + STARTUPINFO si; + HANDLE origToken; + HANDLE restrictedToken; + SID_IDENTIFIER_AUTHORITY NtAuthority = { SECURITY_NT_AUTHORITY }; + SID_AND_ATTRIBUTES dropSids[2]; + __CreateRestrictedToken _CreateRestrictedToken = NULL; + HANDLE Advapi32Handle; + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + + Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); + if (Advapi32Handle != NULL) + { + _CreateRestrictedToken = (__CreateRestrictedToken)GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); + } + + if (_CreateRestrictedToken == NULL) + { + fprintf(stderr, _("%s: WARNING: cannot create restricted tokens on this platform\n"), progname); + if (Advapi32Handle != NULL) + FreeLibrary(Advapi32Handle); + return 0; + } + + /* Open the current token to use as a base for the restricted one */ + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) + { + fprintf(stderr, _("%s: could not open process token: error code %lu\n"), progname, GetLastError()); + return 0; + } + + /* Allocate list of SIDs to remove */ + ZeroMemory(&dropSids, sizeof(dropSids)); + if (!AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, + 0, &dropSids[0].Sid) || + !AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, + 0, &dropSids[1].Sid)) + { + fprintf(stderr, _("%s: could not to allocate SIDs: error code %lu\n"), progname, GetLastError()); + return 0; + } + + b = _CreateRestrictedToken(origToken, + DISABLE_MAX_PRIVILEGE, + sizeof(dropSids) / sizeof(dropSids[0]), + dropSids, + 0, NULL, + 0, NULL, + &restrictedToken); + + FreeSid(dropSids[1].Sid); + FreeSid(dropSids[0].Sid); + CloseHandle(origToken); + FreeLibrary(Advapi32Handle); + + if (!b) + { + fprintf(stderr, _("%s: could not create restricted token: error code %lu\n"), progname, GetLastError()); + return 0; + } + +#ifndef __CYGWIN__ + AddUserToTokenDacl(restrictedToken); +#endif + + if (!CreateProcessAsUser(restrictedToken, + NULL, + cmd, + NULL, + NULL, + TRUE, + CREATE_SUSPENDED, + NULL, + NULL, + &si, + processInfo)) + + { + fprintf(stderr, _("%s: could not start process for command \"%s\": error code %lu\n"), progname, cmd, GetLastError()); + return 0; + } + + return ResumeThread(processInfo->hThread); +} +#endif + +void +get_restricted_token(const char *progname) +{ +#ifdef WIN32 + + /* + * Before we execute another program, make sure that we are running with a + * restricted token. If not, re-execute ourselves with one. + */ + + if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL + || strcmp(restrict_env, "1") != 0) + { + PROCESS_INFORMATION pi; + char *cmdline; + + ZeroMemory(&pi, sizeof(pi)); + + cmdline = pg_strdup(GetCommandLine()); + + putenv("PG_RESTRICT_EXEC=1"); + + if (!CreateRestrictedProcess(cmdline, &pi, progname)) + { + fprintf(stderr, _("%s: could not re-execute with restricted token: error code %lu\n"), progname, GetLastError()); + } + else + { + /* + * Successfully re-execed. Now wait for child process to capture + * exitcode. + */ + DWORD x; + + CloseHandle(pi.hThread); + WaitForSingleObject(pi.hProcess, INFINITE); + + if (!GetExitCodeProcess(pi.hProcess, &x)) + { + fprintf(stderr, _("%s: could not get exit code from subprocess: error code %lu\n"), progname, GetLastError()); + exit(1); + } + exit(x); + } + } +#endif +} static void usage(void)
pg_upgrade_pg_resetxlog.v2_93.patch (application/octet-stream, 10.4K) download diff --git a/contrib/pg_upgrade/pg_upgrade.c b/contrib/pg_upgrade/pg_upgrade.c index d7d8864..537ebff 100644 --- a/contrib/pg_upgrade/pg_upgrade.c +++ b/contrib/pg_upgrade/pg_upgrade.c @@ -50,6 +50,11 @@ static void copy_clog_xlog_xid(void); static void set_frozenxids(bool minmxid_only); static void setup(char *argv0, bool *live_check); static void cleanup(void); +static void get_restricted_token(const char *progname); + +#ifdef WIN32 +static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, const char *progname); +#endif ClusterInfo old_cluster, new_cluster; @@ -66,6 +71,9 @@ char *output_files[] = { NULL }; +#ifdef WIN32 +static char *restrict_env; +#endif int main(int argc, char **argv) @@ -77,6 +85,8 @@ main(int argc, char **argv) parseCommandLine(argc, argv); + get_restricted_token(os_info.progname); + adjust_data_dir(&old_cluster); adjust_data_dir(&new_cluster); @@ -175,6 +185,162 @@ main(int argc, char **argv) return 0; } +#ifdef WIN32 +typedef BOOL(WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); + +/* Windows API define missing from some versions of MingW headers */ +#ifndef DISABLE_MAX_PRIVILEGE +#define DISABLE_MAX_PRIVILEGE 0x1 +#endif + +/* +* Create a restricted token and execute the specified process with it. +* +* Returns 0 on failure, non-zero on success, same as CreateProcess(). +* +* On NT4, or any other system not containing the required functions, will +* NOT execute anything. +*/ +static int +CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, const char *progname) +{ + BOOL b; + STARTUPINFO si; + HANDLE origToken; + HANDLE restrictedToken; + SID_IDENTIFIER_AUTHORITY NtAuthority = { SECURITY_NT_AUTHORITY }; + SID_AND_ATTRIBUTES dropSids[2]; + __CreateRestrictedToken _CreateRestrictedToken = NULL; + HANDLE Advapi32Handle; + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + + Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); + if (Advapi32Handle != NULL) + { + _CreateRestrictedToken = (__CreateRestrictedToken)GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); + } + + if (_CreateRestrictedToken == NULL) + { + fprintf(stderr, _("%s: WARNING: cannot create restricted tokens on this platform\n"), progname); + if (Advapi32Handle != NULL) + FreeLibrary(Advapi32Handle); + return 0; + } + + /* Open the current token to use as a base for the restricted one */ + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) + { + fprintf(stderr, _("%s: could not open process token: error code %lu\n"), progname, GetLastError()); + return 0; + } + + /* Allocate list of SIDs to remove */ + ZeroMemory(&dropSids, sizeof(dropSids)); + if (!AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, + 0, &dropSids[0].Sid) || + !AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, + 0, &dropSids[1].Sid)) + { + fprintf(stderr, _("%s: could not to allocate SIDs: error code %lu\n"), progname, GetLastError()); + return 0; + } + + b = _CreateRestrictedToken(origToken, + DISABLE_MAX_PRIVILEGE, + sizeof(dropSids) / sizeof(dropSids[0]), + dropSids, + 0, NULL, + 0, NULL, + &restrictedToken); + + FreeSid(dropSids[1].Sid); + FreeSid(dropSids[0].Sid); + CloseHandle(origToken); + FreeLibrary(Advapi32Handle); + + if (!b) + { + fprintf(stderr, _("%s: could not create restricted token: error code %lu\n"), progname, GetLastError()); + return 0; + } + +#ifndef __CYGWIN__ + AddUserToTokenDacl(restrictedToken); +#endif + + if (!CreateProcessAsUser(restrictedToken, + NULL, + cmd, + NULL, + NULL, + TRUE, + CREATE_SUSPENDED, + NULL, + NULL, + &si, + processInfo)) + + { + fprintf(stderr, _("%s: could not start process for command \"%s\": error code %lu\n"), progname, cmd, GetLastError()); + return 0; + } + + return ResumeThread(processInfo->hThread); +} +#endif + +void +get_restricted_token(const char *progname) +{ +#ifdef WIN32 + + /* + * Before we execute another program, make sure that we are running with a + * restricted token. If not, re-execute ourselves with one. + */ + + if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL + || strcmp(restrict_env, "1") != 0) + { + PROCESS_INFORMATION pi; + char *cmdline; + + ZeroMemory(&pi, sizeof(pi)); + + cmdline = pg_strdup(GetCommandLine()); + + putenv("PG_RESTRICT_EXEC=1"); + + if (!CreateRestrictedProcess(cmdline, &pi, progname)) + { + fprintf(stderr, _("%s: could not re-execute with restricted token: error code %lu\n"), progname, GetLastError()); + } + else + { + /* + * Successfully re-execed. Now wait for child process to capture + * exitcode. + */ + DWORD x; + + CloseHandle(pi.hThread); + WaitForSingleObject(pi.hProcess, INFINITE); + + if (!GetExitCodeProcess(pi.hProcess, &x)) + { + fprintf(stderr, _("%s: could not get exit code from subprocess: error code %lu\n"), progname, GetLastError()); + exit(1); + } + exit(x); + } + } +#endif +} static void setup(char *argv0, bool *live_check) diff --git a/src/bin/pg_resetxlog/pg_resetxlog.c b/src/bin/pg_resetxlog/pg_resetxlog.c index 38d03a3..c29864a 100644 --- a/src/bin/pg_resetxlog/pg_resetxlog.c +++ b/src/bin/pg_resetxlog/pg_resetxlog.c @@ -65,6 +65,10 @@ static XLogSegNo newXlogSegNo; /* new XLOG segment # */ static bool guessed = false; /* T if we had to guess at any values */ static const char *progname; +#ifdef WIN32 +static char *restrict_env; +#endif + static bool ReadControlFile(void); static void GuessControlValues(void); static void PrintControlValues(bool guessed); @@ -74,7 +78,11 @@ static void KillExistingXLOG(void); static void KillExistingArchiveStatus(void); static void WriteEmptyXLOG(void); static void usage(void); +static void get_restricted_token(const char *progname); +#ifdef WIN32 +static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, const char *progname); +#endif int main(int argc, char *argv[]) @@ -260,6 +268,7 @@ main(int argc, char *argv[]) } #endif + get_restricted_token(progname); DataDir = argv[optind]; if (chdir(DataDir) < 0) @@ -1029,6 +1038,162 @@ WriteEmptyXLOG(void) close(fd); } +#ifdef WIN32 +typedef BOOL(WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); + +/* Windows API define missing from some versions of MingW headers */ +#ifndef DISABLE_MAX_PRIVILEGE +#define DISABLE_MAX_PRIVILEGE 0x1 +#endif + +/* +* Create a restricted token and execute the specified process with it. +* +* Returns 0 on failure, non-zero on success, same as CreateProcess(). +* +* On NT4, or any other system not containing the required functions, will +* NOT execute anything. +*/ +static int +CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, const char *progname) +{ + BOOL b; + STARTUPINFO si; + HANDLE origToken; + HANDLE restrictedToken; + SID_IDENTIFIER_AUTHORITY NtAuthority = { SECURITY_NT_AUTHORITY }; + SID_AND_ATTRIBUTES dropSids[2]; + __CreateRestrictedToken _CreateRestrictedToken = NULL; + HANDLE Advapi32Handle; + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + + Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); + if (Advapi32Handle != NULL) + { + _CreateRestrictedToken = (__CreateRestrictedToken)GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); + } + + if (_CreateRestrictedToken == NULL) + { + fprintf(stderr, _("%s: WARNING: cannot create restricted tokens on this platform\n"), progname); + if (Advapi32Handle != NULL) + FreeLibrary(Advapi32Handle); + return 0; + } + + /* Open the current token to use as a base for the restricted one */ + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) + { + fprintf(stderr, _("%s: could not open process token: error code %lu\n"), progname, GetLastError()); + return 0; + } + + /* Allocate list of SIDs to remove */ + ZeroMemory(&dropSids, sizeof(dropSids)); + if (!AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, + 0, &dropSids[0].Sid) || + !AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, + 0, &dropSids[1].Sid)) + { + fprintf(stderr, _("%s: could not to allocate SIDs: error code %lu\n"), progname, GetLastError()); + return 0; + } + + b = _CreateRestrictedToken(origToken, + DISABLE_MAX_PRIVILEGE, + sizeof(dropSids) / sizeof(dropSids[0]), + dropSids, + 0, NULL, + 0, NULL, + &restrictedToken); + + FreeSid(dropSids[1].Sid); + FreeSid(dropSids[0].Sid); + CloseHandle(origToken); + FreeLibrary(Advapi32Handle); + + if (!b) + { + fprintf(stderr, _("%s: could not create restricted token: error code %lu\n"), progname, GetLastError()); + return 0; + } + +#ifndef __CYGWIN__ + AddUserToTokenDacl(restrictedToken); +#endif + + if (!CreateProcessAsUser(restrictedToken, + NULL, + cmd, + NULL, + NULL, + TRUE, + CREATE_SUSPENDED, + NULL, + NULL, + &si, + processInfo)) + + { + fprintf(stderr, _("%s: could not start process for command \"%s\": error code %lu\n"), progname, cmd, GetLastError()); + return 0; + } + + return ResumeThread(processInfo->hThread); +} +#endif + +void +get_restricted_token(const char *progname) +{ +#ifdef WIN32 + + /* + * Before we execute another program, make sure that we are running with a + * restricted token. If not, re-execute ourselves with one. + */ + + if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL + || strcmp(restrict_env, "1") != 0) + { + PROCESS_INFORMATION pi; + char *cmdline; + + ZeroMemory(&pi, sizeof(pi)); + + cmdline = pg_strdup(GetCommandLine()); + + putenv("PG_RESTRICT_EXEC=1"); + + if (!CreateRestrictedProcess(cmdline, &pi, progname)) + { + fprintf(stderr, _("%s: could not re-execute with restricted token: error code %lu\n"), progname, GetLastError()); + } + else + { + /* + * Successfully re-execed. Now wait for child process to capture + * exitcode. + */ + DWORD x; + + CloseHandle(pi.hThread); + WaitForSingleObject(pi.hProcess, INFINITE); + + if (!GetExitCodeProcess(pi.hProcess, &x)) + { + fprintf(stderr, _("%s: could not get exit code from subprocess: error code %lu\n"), progname, GetLastError()); + exit(1); + } + exit(x); + } + } +#endif +} static void usage(void)
pg_upgrade_pg_resetxlog.v1_90.patch (application/octet-stream, 10.7K) download diff --git a/contrib/pg_upgrade/pg_upgrade.c b/contrib/pg_upgrade/pg_upgrade.c index 37d2eed..f611a21 100644 --- a/contrib/pg_upgrade/pg_upgrade.c +++ b/contrib/pg_upgrade/pg_upgrade.c @@ -21,7 +21,15 @@ static void copy_clog_xlog_xid(migratorContext *ctx); static void set_frozenxids(migratorContext *ctx); static void setup(migratorContext *ctx, char *argv0, bool live_check); static void cleanup(migratorContext *ctx); +static void get_restricted_token(const char *progname); +#ifdef WIN32 +static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, const char *progname); +#endif + +#ifdef WIN32 +static char *restrict_env; +#endif int main(int argc, char **argv) @@ -35,6 +43,8 @@ main(int argc, char **argv) parseCommandLine(&ctx, argc, argv); + get_restricted_token(ctx.progname); + output_check_banner(&ctx, &live_check); setup(&ctx, argv[0], live_check); @@ -103,6 +113,162 @@ main(int argc, char **argv) return 0; } +#ifdef WIN32 +typedef BOOL(WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); + +/* Windows API define missing from some versions of MingW headers */ +#ifndef DISABLE_MAX_PRIVILEGE +#define DISABLE_MAX_PRIVILEGE 0x1 +#endif + +/* +* Create a restricted token and execute the specified process with it. +* +* Returns 0 on failure, non-zero on success, same as CreateProcess(). +* +* On NT4, or any other system not containing the required functions, will +* NOT execute anything. +*/ +static int +CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, const char *progname) +{ + BOOL b; + STARTUPINFO si; + HANDLE origToken; + HANDLE restrictedToken; + SID_IDENTIFIER_AUTHORITY NtAuthority = { SECURITY_NT_AUTHORITY }; + SID_AND_ATTRIBUTES dropSids[2]; + __CreateRestrictedToken _CreateRestrictedToken = NULL; + HANDLE Advapi32Handle; + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + + Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); + if (Advapi32Handle != NULL) + { + _CreateRestrictedToken = (__CreateRestrictedToken)GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); + } + + if (_CreateRestrictedToken == NULL) + { + fprintf(stderr, _("%s: WARNING: cannot create restricted tokens on this platform\n"), progname); + if (Advapi32Handle != NULL) + FreeLibrary(Advapi32Handle); + return 0; + } + + /* Open the current token to use as a base for the restricted one */ + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) + { + fprintf(stderr, _("%s: could not open process token: error code %lu\n"), progname, GetLastError()); + return 0; + } + + /* Allocate list of SIDs to remove */ + ZeroMemory(&dropSids, sizeof(dropSids)); + if (!AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, + 0, &dropSids[0].Sid) || + !AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, + 0, &dropSids[1].Sid)) + { + fprintf(stderr, _("%s: could not to allocate SIDs: error code %lu\n"), progname, GetLastError()); + return 0; + } + + b = _CreateRestrictedToken(origToken, + DISABLE_MAX_PRIVILEGE, + sizeof(dropSids) / sizeof(dropSids[0]), + dropSids, + 0, NULL, + 0, NULL, + &restrictedToken); + + FreeSid(dropSids[1].Sid); + FreeSid(dropSids[0].Sid); + CloseHandle(origToken); + FreeLibrary(Advapi32Handle); + + if (!b) + { + fprintf(stderr, _("%s: could not create restricted token: error code %lu\n"), progname, GetLastError()); + return 0; + } + +#ifndef __CYGWIN__ + AddUserToTokenDacl(restrictedToken); +#endif + + if (!CreateProcessAsUser(restrictedToken, + NULL, + cmd, + NULL, + NULL, + TRUE, + CREATE_SUSPENDED, + NULL, + NULL, + &si, + processInfo)) + + { + fprintf(stderr, _("%s: could not start process for command \"%s\": error code %lu\n"), progname, cmd, GetLastError()); + return 0; + } + + return ResumeThread(processInfo->hThread); +} +#endif + +void +get_restricted_token(const char *progname) +{ +#ifdef WIN32 + + /* + * Before we execute another program, make sure that we are running with a + * restricted token. If not, re-execute ourselves with one. + */ + + if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL + || strcmp(restrict_env, "1") != 0) + { + PROCESS_INFORMATION pi; + char *cmdline; + + ZeroMemory(&pi, sizeof(pi)); + + cmdline = pg_strdup(GetCommandLine()); + + putenv("PG_RESTRICT_EXEC=1"); + + if (!CreateRestrictedProcess(cmdline, &pi, progname)) + { + fprintf(stderr, _("%s: could not re-execute with restricted token: error code %lu\n"), progname, GetLastError()); + } + else + { + /* + * Successfully re-execed. Now wait for child process to capture + * exitcode. + */ + DWORD x; + + CloseHandle(pi.hThread); + WaitForSingleObject(pi.hProcess, INFINITE); + + if (!GetExitCodeProcess(pi.hProcess, &x)) + { + fprintf(stderr, _("%s: could not get exit code from subprocess: error code %lu\n"), progname, GetLastError()); + exit(1); + } + exit(x); + } + } +#endif +} static void setup(migratorContext *ctx, char *argv0, bool live_check) diff --git a/src/bin/pg_resetxlog/pg_resetxlog.c b/src/bin/pg_resetxlog/pg_resetxlog.c index a120c6f..2e1b918 100644 --- a/src/bin/pg_resetxlog/pg_resetxlog.c +++ b/src/bin/pg_resetxlog/pg_resetxlog.c @@ -65,6 +65,10 @@ static uint32 newXlogId, static bool guessed = false; /* T if we had to guess at any values */ static const char *progname; +#ifdef WIN32 +static char *restrict_env; +#endif + static bool ReadControlFile(void); static void GuessControlValues(void); static void PrintControlValues(bool guessed); @@ -74,7 +78,11 @@ static void KillExistingXLOG(void); static void KillExistingArchiveStatus(void); static void WriteEmptyXLOG(void); static void usage(void); +static void get_restricted_token(const char *progname); +#ifdef WIN32 +static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, const char *progname); +#endif int main(int argc, char *argv[]) @@ -256,6 +264,7 @@ main(int argc, char *argv[]) } #endif + get_restricted_token(progname); DataDir = argv[optind]; if (chdir(DataDir) < 0) @@ -380,6 +389,18 @@ main(int argc, char *argv[]) return 0; } +char * +pg_strdup(const char *str) +{ + char *result = strdup(str); + + if (!result) + { + fprintf(stderr, _("out of memory\n")); + exit(1); + } + return result; +} /* * Try to read the existing pg_control file. @@ -1016,6 +1037,162 @@ WriteEmptyXLOG(void) close(fd); } +#ifdef WIN32 +typedef BOOL(WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); + +/* Windows API define missing from some versions of MingW headers */ +#ifndef DISABLE_MAX_PRIVILEGE +#define DISABLE_MAX_PRIVILEGE 0x1 +#endif + +/* +* Create a restricted token and execute the specified process with it. +* +* Returns 0 on failure, non-zero on success, same as CreateProcess(). +* +* On NT4, or any other system not containing the required functions, will +* NOT execute anything. +*/ +static int +CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, const char *progname) +{ + BOOL b; + STARTUPINFO si; + HANDLE origToken; + HANDLE restrictedToken; + SID_IDENTIFIER_AUTHORITY NtAuthority = { SECURITY_NT_AUTHORITY }; + SID_AND_ATTRIBUTES dropSids[2]; + __CreateRestrictedToken _CreateRestrictedToken = NULL; + HANDLE Advapi32Handle; + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + + Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); + if (Advapi32Handle != NULL) + { + _CreateRestrictedToken = (__CreateRestrictedToken)GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); + } + + if (_CreateRestrictedToken == NULL) + { + fprintf(stderr, _("%s: WARNING: cannot create restricted tokens on this platform\n"), progname); + if (Advapi32Handle != NULL) + FreeLibrary(Advapi32Handle); + return 0; + } + + /* Open the current token to use as a base for the restricted one */ + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) + { + fprintf(stderr, _("%s: could not open process token: error code %lu\n"), progname, GetLastError()); + return 0; + } + + /* Allocate list of SIDs to remove */ + ZeroMemory(&dropSids, sizeof(dropSids)); + if (!AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, + 0, &dropSids[0].Sid) || + !AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, + 0, &dropSids[1].Sid)) + { + fprintf(stderr, _("%s: could not to allocate SIDs: error code %lu\n"), progname, GetLastError()); + return 0; + } + + b = _CreateRestrictedToken(origToken, + DISABLE_MAX_PRIVILEGE, + sizeof(dropSids) / sizeof(dropSids[0]), + dropSids, + 0, NULL, + 0, NULL, + &restrictedToken); + + FreeSid(dropSids[1].Sid); + FreeSid(dropSids[0].Sid); + CloseHandle(origToken); + FreeLibrary(Advapi32Handle); + + if (!b) + { + fprintf(stderr, _("%s: could not create restricted token: error code %lu\n"), progname, GetLastError()); + return 0; + } + +#ifndef __CYGWIN__ + AddUserToTokenDacl(restrictedToken); +#endif + + if (!CreateProcessAsUser(restrictedToken, + NULL, + cmd, + NULL, + NULL, + TRUE, + CREATE_SUSPENDED, + NULL, + NULL, + &si, + processInfo)) + + { + fprintf(stderr, _("%s: could not start process for command \"%s\": error code %lu\n"), progname, cmd, GetLastError()); + return 0; + } + + return ResumeThread(processInfo->hThread); +} +#endif + +void +get_restricted_token(const char *progname) +{ +#ifdef WIN32 + + /* + * Before we execute another program, make sure that we are running with a + * restricted token. If not, re-execute ourselves with one. + */ + + if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL + || strcmp(restrict_env, "1") != 0) + { + PROCESS_INFORMATION pi; + char *cmdline; + + ZeroMemory(&pi, sizeof(pi)); + + cmdline = pg_strdup(GetCommandLine()); + + putenv("PG_RESTRICT_EXEC=1"); + + if (!CreateRestrictedProcess(cmdline, &pi, progname)) + { + fprintf(stderr, _("%s: could not re-execute with restricted token: error code %lu\n"), progname, GetLastError()); + } + else + { + /* + * Successfully re-execed. Now wait for child process to capture + * exitcode. + */ + DWORD x; + + CloseHandle(pi.hThread); + WaitForSingleObject(pi.hProcess, INFINITE); + + if (!GetExitCodeProcess(pi.hProcess, &x)) + { + fprintf(stderr, _("%s: could not get exit code from subprocess: error code %lu\n"), progname, GetLastError()); + exit(1); + } + exit(x); + } + } +#endif +} static void usage(void)
restricted_token.v6.patch (application/octet-stream, 17.8K) download diff --git a/contrib/pg_upgrade/pg_upgrade.c b/contrib/pg_upgrade/pg_upgrade.c index ed7de80..eb48da7 100644 --- a/contrib/pg_upgrade/pg_upgrade.c +++ b/contrib/pg_upgrade/pg_upgrade.c @@ -37,6 +37,7 @@ #include "postgres_fe.h" #include "pg_upgrade.h" +#include "common/restricted_token.h" #ifdef HAVE_LANGINFO_H #include <langinfo.h> @@ -75,6 +76,8 @@ main(int argc, char **argv) parseCommandLine(argc, argv); + get_restricted_token(os_info.progname); + adjust_data_dir(&old_cluster); adjust_data_dir(&new_cluster); diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c index 18614e7..b9d6092 100644 --- a/src/bin/initdb/initdb.c +++ b/src/bin/initdb/initdb.c @@ -61,6 +61,7 @@ #endif #include "catalog/catalog.h" +#include "common/restricted_token.h" #include "common/username.h" #include "mb/pg_wchar.h" #include "getaddrinfo.h" @@ -178,9 +179,6 @@ static char *authwarning = NULL; static const char *boot_options = "-F"; static const char *backend_options = "--single -F -O -c search_path=pg_catalog -c exit_on_error=true"; -#ifdef WIN32 -char *restrict_env; -#endif static const char *subdirs[] = { "global", "pg_xlog", @@ -260,7 +258,6 @@ static void check_locale_name(int category, const char *locale, static bool check_locale_encoding(const char *locale, int encoding); static void setlocales(void); static void usage(const char *progname); -void get_restricted_token(void); void setup_pgdata(void); void setup_bin_paths(const char *argv0); void setup_data_file_paths(void); @@ -272,12 +269,6 @@ void create_xlog_symlink(void); void warn_on_mount_point(int error); void initialize_data_directory(void); - -#ifdef WIN32 -static int CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo); -#endif - - /* * macros for running pipes to postgres */ @@ -2754,116 +2745,6 @@ setlocales(void) #endif } -#ifdef WIN32 -typedef BOOL (WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); - -/* Windows API define missing from some versions of MingW headers */ -#ifndef DISABLE_MAX_PRIVILEGE -#define DISABLE_MAX_PRIVILEGE 0x1 -#endif - -/* - * Create a restricted token and execute the specified process with it. - * - * Returns 0 on failure, non-zero on success, same as CreateProcess(). - * - * On NT4, or any other system not containing the required functions, will - * NOT execute anything. - */ -static int -CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo) -{ - BOOL b; - STARTUPINFO si; - HANDLE origToken; - HANDLE restrictedToken; - SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY}; - SID_AND_ATTRIBUTES dropSids[2]; - __CreateRestrictedToken _CreateRestrictedToken = NULL; - HANDLE Advapi32Handle; - - ZeroMemory(&si, sizeof(si)); - si.cb = sizeof(si); - - Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); - if (Advapi32Handle != NULL) - { - _CreateRestrictedToken = (__CreateRestrictedToken) GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); - } - - if (_CreateRestrictedToken == NULL) - { - fprintf(stderr, _("%s: WARNING: cannot create restricted tokens on this platform\n"), progname); - if (Advapi32Handle != NULL) - FreeLibrary(Advapi32Handle); - return 0; - } - - /* Open the current token to use as a base for the restricted one */ - if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) - { - fprintf(stderr, _("%s: could not open process token: error code %lu\n"), progname, GetLastError()); - return 0; - } - - /* Allocate list of SIDs to remove */ - ZeroMemory(&dropSids, sizeof(dropSids)); - if (!AllocateAndInitializeSid(&NtAuthority, 2, - SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, - 0, &dropSids[0].Sid) || - !AllocateAndInitializeSid(&NtAuthority, 2, - SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, - 0, &dropSids[1].Sid)) - { - fprintf(stderr, _("%s: could not allocate SIDs: error code %lu\n"), - progname, GetLastError()); - return 0; - } - - b = _CreateRestrictedToken(origToken, - DISABLE_MAX_PRIVILEGE, - sizeof(dropSids) / sizeof(dropSids[0]), - dropSids, - 0, NULL, - 0, NULL, - &restrictedToken); - - FreeSid(dropSids[1].Sid); - FreeSid(dropSids[0].Sid); - CloseHandle(origToken); - FreeLibrary(Advapi32Handle); - - if (!b) - { - fprintf(stderr, _("%s: could not create restricted token: error code %lu\n"), progname, GetLastError()); - return 0; - } - -#ifndef __CYGWIN__ - AddUserToTokenDacl(restrictedToken); -#endif - - if (!CreateProcessAsUser(restrictedToken, - NULL, - cmd, - NULL, - NULL, - TRUE, - CREATE_SUSPENDED, - NULL, - NULL, - &si, - processInfo)) - - { - fprintf(stderr, _("%s: could not start process for command \"%s\": error code %lu\n"), progname, cmd, GetLastError()); - return 0; - } - - return ResumeThread(processInfo->hThread); -} -#endif - /* * print help text */ @@ -2957,53 +2838,6 @@ check_need_password(const char *authmethodlocal, const char *authmethodhost) } } -void -get_restricted_token(void) -{ -#ifdef WIN32 - - /* - * Before we execute another program, make sure that we are running with a - * restricted token. If not, re-execute ourselves with one. - */ - - if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL - || strcmp(restrict_env, "1") != 0) - { - PROCESS_INFORMATION pi; - char *cmdline; - - ZeroMemory(&pi, sizeof(pi)); - - cmdline = pg_strdup(GetCommandLine()); - - putenv("PG_RESTRICT_EXEC=1"); - - if (!CreateRestrictedProcess(cmdline, &pi)) - { - fprintf(stderr, _("%s: could not re-execute with restricted token: error code %lu\n"), progname, GetLastError()); - } - else - { - /* - * Successfully re-execed. Now wait for child process to capture - * exitcode. - */ - DWORD x; - - CloseHandle(pi.hThread); - WaitForSingleObject(pi.hProcess, INFINITE); - - if (!GetExitCodeProcess(pi.hProcess, &x)) - { - fprintf(stderr, _("%s: could not get exit code from subprocess: error code %lu\n"), progname, GetLastError()); - exit(1); - } - exit(x); - } - } -#endif -} void setup_pgdata(void) @@ -3759,7 +3593,7 @@ main(int argc, char *argv[]) check_need_password(authmethodlocal, authmethodhost); - get_restricted_token(); + get_restricted_token(progname); setup_pgdata(); diff --git a/src/bin/pg_resetxlog/pg_resetxlog.c b/src/bin/pg_resetxlog/pg_resetxlog.c index a16089f..3361111 100644 --- a/src/bin/pg_resetxlog/pg_resetxlog.c +++ b/src/bin/pg_resetxlog/pg_resetxlog.c @@ -53,6 +53,7 @@ #include "catalog/catversion.h" #include "catalog/pg_control.h" #include "common/fe_memutils.h" +#include "common/restricted_token.h" #include "storage/large_object.h" #include "pg_getopt.h" @@ -310,6 +311,8 @@ main(int argc, char *argv[]) } #endif + get_restricted_token(progname); + if (chdir(DataDir) < 0) { fprintf(stderr, _("%s: could not change directory to \"%s\": %s\n"), diff --git a/src/common/Makefile b/src/common/Makefile index c71415e..c2e456d 100644 --- a/src/common/Makefile +++ b/src/common/Makefile @@ -26,7 +26,7 @@ LIBS += $(PTHREAD_LIBS) OBJS_COMMON = exec.o pg_crc.o pg_lzcompress.o pgfnames.o psprintf.o relpath.o \ rmtree.o string.o username.o wait_error.o -OBJS_FRONTEND = $(OBJS_COMMON) fe_memutils.o +OBJS_FRONTEND = $(OBJS_COMMON) fe_memutils.o restricted_token.o OBJS_SRV = $(OBJS_COMMON:%.o=%_srv.o) diff --git a/src/test/regress/pg_regress.c b/src/test/regress/pg_regress.c index 9d4fb9a..6f20120 100644 --- a/src/test/regress/pg_regress.c +++ b/src/test/regress/pg_regress.c @@ -29,6 +29,7 @@ #include <sys/resource.h> #endif +#include "common/restricted_token.h" #include "common/username.h" #include "getopt_long.h" #include "libpq/pqcomm.h" /* needed for UNIXSOCK_PATH() */ @@ -147,15 +148,6 @@ psql_command(const char *database, const char *query,...) the supplied arguments. */ pg_attribute_printf(2, 3); -#ifdef WIN32 -typedef BOOL (WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); - -/* Windows API define missing from some versions of MingW headers */ -#ifndef DISABLE_MAX_PRIVILEGE -#define DISABLE_MAX_PRIVILEGE 0x1 -#endif -#endif - /* * allow core files if possible. */ @@ -1238,100 +1230,17 @@ spawn_process(const char *cmdline) /* in parent */ return pid; #else - char *cmdline2; - BOOL b; - STARTUPINFO si; - PROCESS_INFORMATION pi; - HANDLE origToken; - HANDLE restrictedToken; - SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY}; - SID_AND_ATTRIBUTES dropSids[2]; - __CreateRestrictedToken _CreateRestrictedToken = NULL; - HANDLE Advapi32Handle; - - ZeroMemory(&si, sizeof(si)); - si.cb = sizeof(si); - - Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); - if (Advapi32Handle != NULL) - { - _CreateRestrictedToken = (__CreateRestrictedToken) GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); - } - - if (_CreateRestrictedToken == NULL) - { - if (Advapi32Handle != NULL) - FreeLibrary(Advapi32Handle); - fprintf(stderr, _("%s: cannot create restricted tokens on this platform\n"), - progname); - exit(2); - } - - /* Open the current token to use as base for the restricted one */ - if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) - { - fprintf(stderr, _("could not open process token: error code %lu\n"), - GetLastError()); - exit(2); - } - - /* Allocate list of SIDs to remove */ - ZeroMemory(&dropSids, sizeof(dropSids)); - if (!AllocateAndInitializeSid(&NtAuthority, 2, - SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &dropSids[0].Sid) || - !AllocateAndInitializeSid(&NtAuthority, 2, - SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, 0, &dropSids[1].Sid)) - { - fprintf(stderr, _("could not allocate SIDs: error code %lu\n"), GetLastError()); - exit(2); - } - - b = _CreateRestrictedToken(origToken, - DISABLE_MAX_PRIVILEGE, - sizeof(dropSids) / sizeof(dropSids[0]), - dropSids, - 0, NULL, - 0, NULL, - &restrictedToken); - - FreeSid(dropSids[1].Sid); - FreeSid(dropSids[0].Sid); - CloseHandle(origToken); - FreeLibrary(Advapi32Handle); - - if (!b) - { - fprintf(stderr, _("could not create restricted token: error code %lu\n"), - GetLastError()); - exit(2); - } + PROCESS_INFORMATION pi; + char *cmdline2; + HANDLE restrictedToken; + memset(&pi, 0, sizeof(pi)); cmdline2 = psprintf("cmd /c \"%s\"", cmdline); -#ifndef __CYGWIN__ - AddUserToTokenDacl(restrictedToken); -#endif - - if (!CreateProcessAsUser(restrictedToken, - NULL, - cmdline2, - NULL, - NULL, - TRUE, - CREATE_SUSPENDED, - NULL, - NULL, - &si, - &pi)) - { - fprintf(stderr, _("could not start process for \"%s\": error code %lu\n"), - cmdline2, GetLastError()); + if((restrictedToken = + CreateRestrictedProcess(cmdline2, &pi, progname)) == 0) exit(2); - } - - free(cmdline2); - ResumeThread(pi.hThread); CloseHandle(pi.hThread); return pi.hProcess; #endif diff --git a/src/tools/msvc/Mkvcbuild.pm b/src/tools/msvc/Mkvcbuild.pm index 0ca786c..7f319df 100644 --- a/src/tools/msvc/Mkvcbuild.pm +++ b/src/tools/msvc/Mkvcbuild.pm @@ -95,7 +95,8 @@ sub mkvcbuild exec.c pg_crc.c pg_lzcompress.c pgfnames.c psprintf.c relpath.c rmtree.c string.c username.c wait_error.c); - our @pgcommonfrontendfiles = (@pgcommonallfiles, qw(fe_memutils.c)); + our @pgcommonfrontendfiles = (@pgcommonallfiles, qw(fe_memutils.c + restricted_token.c)); our @pgcommonbkndfiles = @pgcommonallfiles; diff --git a/src/common/restricted_token.c b/src/common/restricted_token.c new file mode 100644 index 0000000..a8213c0 --- /dev/null +++ b/src/common/restricted_token.c @@ -0,0 +1,193 @@ +/*------------------------------------------------------------------------- + * + * restricted_token.c + * helper routine to ensure restricted token on Windows + * + * + * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * + * IDENTIFICATION + * src/common/restricted_token.c + * + *------------------------------------------------------------------------- + */ + +#ifndef FRONTEND +#error "This file is not expected to be compiled for backend code" +#endif + +#include "postgres_fe.h" + +#include "common/restricted_token.h" + +#ifdef WIN32 + +/* internal vars */ +char *restrict_env; + +typedef BOOL (WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE); + +/* Windows API define missing from some versions of MingW headers */ +#ifndef DISABLE_MAX_PRIVILEGE +#define DISABLE_MAX_PRIVILEGE 0x1 +#endif + +/* + * Create a restricted token and execute the specified process with it. + * + * Returns restricted token on success and 0 on failure. + * + * On NT4, or any other system not containing the required functions, will + * NOT execute anything. + */ +HANDLE +CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, const char *progname) +{ + BOOL b; + STARTUPINFO si; + HANDLE origToken; + HANDLE restrictedToken; + SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY}; + SID_AND_ATTRIBUTES dropSids[2]; + __CreateRestrictedToken _CreateRestrictedToken = NULL; + HANDLE Advapi32Handle; + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + + Advapi32Handle = LoadLibrary("ADVAPI32.DLL"); + if (Advapi32Handle != NULL) + { + _CreateRestrictedToken = (__CreateRestrictedToken) GetProcAddress(Advapi32Handle, "CreateRestrictedToken"); + } + + if (_CreateRestrictedToken == NULL) + { + fprintf(stderr, _("%s: WARNING: cannot create restricted tokens on this platform\n"), progname); + if (Advapi32Handle != NULL) + FreeLibrary(Advapi32Handle); + return 0; + } + + /* Open the current token to use as a base for the restricted one */ + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken)) + { + fprintf(stderr, _("%s: could not open process token: error code %lu\n"), progname, GetLastError()); + return 0; + } + + /* Allocate list of SIDs to remove */ + ZeroMemory(&dropSids, sizeof(dropSids)); + if (!AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, + 0, &dropSids[0].Sid) || + !AllocateAndInitializeSid(&NtAuthority, 2, + SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, + 0, &dropSids[1].Sid)) + { + fprintf(stderr, _("%s: could not allocate SIDs: error code %lu\n"), + progname, GetLastError()); + return 0; + } + + b = _CreateRestrictedToken(origToken, + DISABLE_MAX_PRIVILEGE, + sizeof(dropSids) / sizeof(dropSids[0]), + dropSids, + 0, NULL, + 0, NULL, + &restrictedToken); + + FreeSid(dropSids[1].Sid); + FreeSid(dropSids[0].Sid); + CloseHandle(origToken); + FreeLibrary(Advapi32Handle); + + if (!b) + { + fprintf(stderr, _("%s: could not create restricted token: error code %lu\n"), + progname, GetLastError()); + return 0; + } + +#ifndef __CYGWIN__ + AddUserToTokenDacl(restrictedToken); +#endif + + if (!CreateProcessAsUser(restrictedToken, + NULL, + cmd, + NULL, + NULL, + TRUE, + CREATE_SUSPENDED, + NULL, + NULL, + &si, + processInfo)) + + { + fprintf(stderr, _("%s: could not start process for command \"%s\": error code %lu\n"), progname, cmd, GetLastError()); + return 0; + } + + ResumeThread(processInfo->hThread); + return restrictedToken; +} +#endif + +/* + * On Windows make sure that we are running with a restricted token, + * On other platforms do nothing. + */ +void +get_restricted_token(const char *progname) +{ +#ifdef WIN32 + HANDLE restrictedToken; + + /* + * Before we execute another program, make sure that we are running with a + * restricted token. If not, re-execute ourselves with one. + */ + + if ((restrict_env = getenv("PG_RESTRICT_EXEC")) == NULL + || strcmp(restrict_env, "1") != 0) + { + PROCESS_INFORMATION pi; + char *cmdline; + + ZeroMemory(&pi, sizeof(pi)); + + cmdline = pg_strdup(GetCommandLine()); + + putenv("PG_RESTRICT_EXEC=1"); + + if ((restrictedToken = CreateRestrictedProcess(cmdline, &pi, progname)) == 0) + { + fprintf(stderr, _("%s: could not re-execute with restricted token: error code %lu\n"), progname, GetLastError()); + } + else + { + /* + * Successfully re-execed. Now wait for child process to capture + * exitcode. + */ + DWORD x; + + CloseHandle(restrictedToken); + CloseHandle(pi.hThread); + WaitForSingleObject(pi.hProcess, INFINITE); + + if (!GetExitCodeProcess(pi.hProcess, &x)) + { + fprintf(stderr, _("%s: could not get exit code from subprocess: error code %lu\n"), progname, GetLastError()); + exit(1); + } + exit(x); + } + } +#endif +} diff --git a/src/include/common/restricted_token.h b/src/include/common/restricted_token.h new file mode 100644 index 0000000..e243744 --- /dev/null +++ b/src/include/common/restricted_token.h @@ -0,0 +1,24 @@ +/* + * restricted_token.h + * helper routine to ensure restricted token on Windows + * + * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * src/include/common/restricted_token.h + */ +#ifndef COMMON_RESTRICTED_TOKEN_H +#define COMMON_RESTRICTED_TOKEN_H + +/* + * On Windows make sure that we are running with a restricted token, + * On other platforms do nothing. + */ +void get_restricted_token(const char *progname); + +#ifdef WIN32 +/* Create a restricted token and execute the specified process with it. */ +HANDLE CreateRestrictedProcess(char *cmd, PROCESS_INFORMATION *processInfo, const char *progname); +#endif + +#endif /* COMMON_RESTRICTED_TOKEN_H */
^ permalink raw reply [nested|flat] 35+ messages in thread

* Re: pg_upgrade failure on Windows Server
@ 2015-03-24 11:05  Michael Paquier <michael.paquier@gmail.com>
  parent: Asif Naeem <anaeem.it@gmail.com>
  0 siblings, 0 replies; 35+ messages in thread

From: Michael Paquier @ 2015-03-24 11:05 UTC (permalink / raw)
  To: Asif Naeem <anaeem.it@gmail.com>; +Cc: Alvaro Herrera <alvherre@2ndquadrant.com>; Amit Kapila <amit.kapila16@gmail.com>; Bruce Momjian <bruce@momjian.us>; pgsql-bugs

On Tue, Mar 24, 2015 at 7:48 PM, Asif Naeem wrote:
> On Sat, Mar 21, 2015 at 5:09 PM, Michael Paquier wrote:
> Ah. Okey. I was not sure till which back branch it need to fixed. PFA patch
> for 90 branch.

OK. Thanks. This will surely help the committer who will pick up those
series of patches, particularly because it is for Windows.

>>
>> I have also done some sanity checks down to 9.2 (got some issues when
>> building with ~9.1), and noticed no problems.
>
>
> Thank you so much. I hope now there is nothing left from my side :).

I looked again at those patches and things are cool on my side, hence
I am switching it as "Ready for Committer".
Regards,
-- 
Michael


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 35+ messages in thread


end of thread, other threads:[~2015-03-24 11:05 UTC | newest]

Thread overview: 35+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2015-01-05 00:34 pg_upgrade failure on Windows Server Asif Naeem <anaeem.it@gmail.com>
2015-01-20 17:41 ` Asif Naeem <anaeem.it@gmail.com>
2015-01-21 18:14   ` Bruce Momjian <bruce@momjian.us>
2015-01-21 18:31     ` Alvaro Herrera <alvherre@2ndquadrant.com>
2015-01-21 18:36       ` Bruce Momjian <bruce@momjian.us>
2015-01-22 03:31         ` Amit Kapila <amit.kapila16@gmail.com>
2015-01-22 04:38           ` Michael Paquier <michael.paquier@gmail.com>
2015-01-22 07:07             ` Asif Naeem <anaeem.it@gmail.com>
2015-03-02 04:42               ` Michael Paquier <michael.paquier@gmail.com>
2015-03-04 13:53                 ` Asif Naeem <anaeem.it@gmail.com>
2015-03-05 06:37                   ` Michael Paquier <michael.paquier@gmail.com>
2015-03-12 09:33                     ` Asif Naeem <anaeem.it@gmail.com>
2015-03-12 13:50                       ` Alvaro Herrera <alvherre@2ndquadrant.com>
2015-03-12 14:23                         ` Michael Paquier <michael.paquier@gmail.com>
2015-03-12 14:38                           ` Michael Paquier <michael.paquier@gmail.com>
2015-03-12 14:41                             ` Alvaro Herrera <alvherre@2ndquadrant.com>
2015-03-12 14:45                           ` Alvaro Herrera <alvherre@2ndquadrant.com>
2015-03-12 23:32                             ` Michael Paquier <michael.paquier@gmail.com>
2015-03-16 09:07                               ` Asif Naeem <anaeem.it@gmail.com>
2015-03-17 20:15                                 ` Asif Naeem <anaeem.it@gmail.com>
2015-03-18 00:57                                   ` Michael Paquier <michael.paquier@gmail.com>
2015-03-18 06:50                                     ` Asif Naeem <anaeem.it@gmail.com>
2015-03-18 08:09                                       ` Michael Paquier <michael.paquier@gmail.com>
2015-03-18 21:42                                         ` Asif Naeem <anaeem.it@gmail.com>
2015-03-18 22:04                                           ` Alvaro Herrera <alvherre@2ndquadrant.com>
2015-03-19 00:22                                             ` Michael Paquier <michael.paquier@gmail.com>
2015-03-19 07:25                                           ` Michael Paquier <michael.paquier@gmail.com>
2015-03-20 14:14                                             ` Asif Naeem <anaeem.it@gmail.com>
2015-03-21 12:09                                               ` Michael Paquier <michael.paquier@gmail.com>
2015-03-24 10:48                                                 ` Asif Naeem <anaeem.it@gmail.com>
2015-03-24 11:05                                                   ` Michael Paquier <michael.paquier@gmail.com>
2015-01-22 16:24           ` Bruce Momjian <bruce@momjian.us>
2015-01-22 16:26             ` Andres Freund <andres@2ndquadrant.com>
2015-01-22 16:32               ` Bruce Momjian <bruce@momjian.us>
2015-03-02 04:44               ` Michael Paquier <michael.paquier@gmail.com>

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox