1 /*-------------------------------------------------------------------------
4 * Functions for finding and validating executable files
7 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
12 * $PostgreSQL: pgsql/src/port/exec.c,v 1.59 2008/03/31 01:31:43 tgl Exp $
14 *-------------------------------------------------------------------------
20 #include "postgres_fe.h"
30 #ifndef S_IRUSR /* XXX [TRH] should be in a header */
31 #define S_IRUSR S_IREAD
32 #define S_IWUSR S_IWRITE
33 #define S_IXUSR S_IEXEC
34 #define S_IRGRP ((S_IRUSR)>>3)
35 #define S_IWGRP ((S_IWUSR)>>3)
36 #define S_IXGRP ((S_IXUSR)>>3)
37 #define S_IROTH ((S_IRUSR)>>6)
38 #define S_IWOTH ((S_IWUSR)>>6)
39 #define S_IXOTH ((S_IXUSR)>>6)
43 /* We use only 3-parameter elog calls in this file, for simplicity */
44 /* NOTE: caller must provide gettext call around str! */
45 #define log_error(str, param) elog(LOG, str, param)
47 #define log_error(str, param) (fprintf(stderr, str, param), fputc('\n', stderr))
50 #ifdef WIN32_ONLY_COMPILER
51 #define getcwd(cwd,len) GetCurrentDirectory(len, cwd)
54 static int validate_exec(const char *path);
55 static int resolve_symlinks(char *path);
56 static char *pipe_read_line(char *cmd, char *line, int maxsize);
59 static BOOL GetUserSid(PSID * ppSidUser, HANDLE hToken);
63 * validate_exec -- validate "path" as an executable file
65 * returns 0 if the file is found and no error is encountered.
66 * -1 if the regular file "path" does not exist or cannot be executed.
67 * -2 if the file is otherwise valid but cannot be read.
70 validate_exec(const char *path)
81 char path_exe[MAXPGPATH + sizeof(".exe") - 1];
87 /* Win32 requires a .exe suffix for stat() */
88 if (strlen(path) >= strlen(".exe") &&
89 pg_strcasecmp(path + strlen(path) - strlen(".exe"), ".exe") != 0)
91 strcpy(path_exe, path);
92 strcat(path_exe, ".exe");
98 * Ensure that the file exists and is a regular file.
100 * XXX if you have a broken system where stat() looks at the symlink
101 * instead of the underlying file, you lose.
103 if (stat(path, &buf) < 0)
106 if (!S_ISREG(buf.st_mode))
110 * Ensure that we are using an authorized executable.
114 * Ensure that the file is both executable and readable (required for
118 is_r = buf.st_mode & S_IRUSR;
119 is_x = buf.st_mode & S_IXUSR;
120 return is_x ? (is_r ? 0 : -2) : -1;
124 /* If owned by us, just check owner bits */
125 if (euid == buf.st_uid)
127 is_r = buf.st_mode & S_IRUSR;
128 is_x = buf.st_mode & S_IXUSR;
129 return is_x ? (is_r ? 0 : -2) : -1;
132 /* OK, check group bits */
134 pwp = getpwuid(euid); /* not thread-safe */
137 if (pwp->pw_gid == buf.st_gid) /* my primary group? */
139 else if (pwp->pw_name &&
140 (gp = getgrgid(buf.st_gid)) != NULL && /* not thread-safe */
142 { /* try list of member groups */
143 for (i = 0; gp->gr_mem[i]; ++i)
145 if (!strcmp(gp->gr_mem[i], pwp->pw_name))
154 is_r = buf.st_mode & S_IRGRP;
155 is_x = buf.st_mode & S_IXGRP;
156 return is_x ? (is_r ? 0 : -2) : -1;
160 /* Check "other" bits */
161 is_r = buf.st_mode & S_IROTH;
162 is_x = buf.st_mode & S_IXOTH;
163 return is_x ? (is_r ? 0 : -2) : -1;
169 * find_my_exec -- find an absolute path to a valid executable
171 * argv0 is the name passed on the command line
172 * retpath is the output area (must be of size MAXPGPATH)
173 * Returns 0 if OK, -1 if error.
175 * The reason we have to work so hard to find an absolute path is that
176 * on some platforms we can't do dynamic loading unless we know the
177 * executable's location. Also, we need a full path not a relative
178 * path because we will later change working directory. Finally, we want
179 * a true path not a symlink location, so that we can locate other files
180 * that are part of our installation relative to the executable.
182 * This function is not thread-safe because it calls validate_exec(),
183 * which calls getgrgid(). This function should be used only in
184 * non-threaded binaries, not in library routines.
187 find_my_exec(const char *argv0, char *retpath)
190 test_path[MAXPGPATH];
193 if (!getcwd(cwd, MAXPGPATH))
195 log_error(_("could not identify current directory: %s"),
201 * If argv0 contains a separator, then PATH wasn't used.
203 if (first_dir_separator(argv0) != NULL)
205 if (is_absolute_path(argv0))
206 StrNCpy(retpath, argv0, MAXPGPATH);
208 join_path_components(retpath, cwd, argv0);
209 canonicalize_path(retpath);
211 if (validate_exec(retpath) == 0)
212 return resolve_symlinks(retpath);
214 log_error(_("invalid binary \"%s\""), retpath);
219 /* Win32 checks the current directory first for names without slashes */
220 join_path_components(retpath, cwd, argv0);
221 if (validate_exec(retpath) == 0)
222 return resolve_symlinks(retpath);
226 * Since no explicit path was supplied, the user must have been relying on
227 * PATH. We'll search the same PATH.
229 if ((path = getenv("PATH")) && *path)
241 endp = first_path_separator(startp);
243 endp = startp + strlen(startp); /* point to end */
245 StrNCpy(test_path, startp, Min(endp - startp + 1, MAXPGPATH));
247 if (is_absolute_path(test_path))
248 join_path_components(retpath, test_path, argv0);
251 join_path_components(retpath, cwd, test_path);
252 join_path_components(retpath, retpath, argv0);
254 canonicalize_path(retpath);
256 switch (validate_exec(retpath))
258 case 0: /* found ok */
259 return resolve_symlinks(retpath);
260 case -1: /* wasn't even a candidate, keep looking */
262 case -2: /* found but disqualified */
263 log_error(_("could not read binary \"%s\""),
270 log_error(_("could not find a \"%s\" to execute"), argv0);
276 * resolve_symlinks - resolve symlinks to the underlying file
278 * Replace "path" by the absolute path to the referenced file.
280 * Returns 0 if OK, -1 if error.
282 * Note: we are not particularly tense about producing nice error messages
283 * because we are not really expecting error here; we just determined that
284 * the symlink does point to a valid executable.
287 resolve_symlinks(char *path)
291 char orig_wd[MAXPGPATH],
296 * To resolve a symlink properly, we have to chdir into its directory and
297 * then chdir to where the symlink points; otherwise we may fail to
298 * resolve relative links correctly (consider cases involving mount
299 * points, for example). After following the final symlink, we use
300 * getcwd() to figure out where the heck we're at.
302 * One might think we could skip all this if path doesn't point to a
303 * symlink to start with, but that's wrong. We also want to get rid of
304 * any directory symlinks that are present in the given path. We expect
305 * getcwd() to give us an accurate, symlink-free path.
307 if (!getcwd(orig_wd, MAXPGPATH))
309 log_error(_("could not identify current directory: %s"),
319 lsep = last_dir_separator(path);
323 if (chdir(path) == -1)
325 log_error(_("could not change directory to \"%s\""), path);
333 if (lstat(fname, &buf) < 0 ||
334 !S_ISLNK(buf.st_mode))
337 rllen = readlink(fname, link_buf, sizeof(link_buf));
338 if (rllen < 0 || rllen >= sizeof(link_buf))
340 log_error(_("could not read symbolic link \"%s\""), fname);
343 link_buf[rllen] = '\0';
344 strcpy(path, link_buf);
347 /* must copy final component out of 'path' temporarily */
348 strcpy(link_buf, fname);
350 if (!getcwd(path, MAXPGPATH))
352 log_error(_("could not identify current directory: %s"),
356 join_path_components(path, path, link_buf);
357 canonicalize_path(path);
359 if (chdir(orig_wd) == -1)
361 log_error(_("could not change directory to \"%s\""), orig_wd);
364 #endif /* HAVE_READLINK */
371 * Find another program in our binary's directory,
372 * then make sure it is the proper version.
375 find_other_exec(const char *argv0, const char *target,
376 const char *versionstr, char *retpath)
381 if (find_my_exec(argv0, retpath) < 0)
384 /* Trim off program name and keep just directory */
385 *last_dir_separator(retpath) = '\0';
386 canonicalize_path(retpath);
388 /* Now append the other program's name */
389 snprintf(retpath + strlen(retpath), MAXPGPATH - strlen(retpath),
390 "/%s%s", target, EXE);
392 if (validate_exec(retpath) != 0)
395 snprintf(cmd, sizeof(cmd), "\"%s\" -V 2>%s", retpath, DEVNULL);
397 if (!pipe_read_line(cmd, line, sizeof(line)))
400 if (strcmp(line, versionstr) != 0)
408 * The runtime library's popen() on win32 does not work when being
409 * called from a service when running on windows <= 2000, because
410 * there is no stdin/stdout/stderr.
412 * Executing a command in a pipe and reading the first line from it
416 pipe_read_line(char *cmd, char *line, int maxsize)
421 /* flush output buffers in case popen does not... */
425 if ((pgver = popen(cmd, "r")) == NULL)
428 if (fgets(line, maxsize, pgver) == NULL)
430 perror("fgets failure");
434 if (pclose_check(pgver))
440 SECURITY_ATTRIBUTES sattr;
441 HANDLE childstdoutrd,
444 PROCESS_INFORMATION pi;
448 sattr.nLength = sizeof(SECURITY_ATTRIBUTES);
449 sattr.bInheritHandle = TRUE;
450 sattr.lpSecurityDescriptor = NULL;
452 if (!CreatePipe(&childstdoutrd, &childstdoutwr, &sattr, 0))
455 if (!DuplicateHandle(GetCurrentProcess(),
461 DUPLICATE_SAME_ACCESS))
463 CloseHandle(childstdoutrd);
464 CloseHandle(childstdoutwr);
468 CloseHandle(childstdoutrd);
470 ZeroMemory(&pi, sizeof(pi));
471 ZeroMemory(&si, sizeof(si));
473 si.dwFlags = STARTF_USESTDHANDLES;
474 si.hStdError = childstdoutwr;
475 si.hStdOutput = childstdoutwr;
476 si.hStdInput = INVALID_HANDLE_VALUE;
478 if (CreateProcess(NULL,
489 /* Successfully started the process */
492 ZeroMemory(line, maxsize);
494 /* Try to read at least one line from the pipe */
495 /* This may require more than one wait/read attempt */
496 for (lineptr = line; lineptr < line + maxsize - 1;)
500 /* Let's see if we can read */
501 if (WaitForSingleObject(childstdoutrddup, 10000) != WAIT_OBJECT_0)
502 break; /* Timeout, but perhaps we got a line already */
504 if (!ReadFile(childstdoutrddup, lineptr, maxsize - (lineptr - line),
506 break; /* Error, but perhaps we got a line already */
508 lineptr += strlen(lineptr);
513 if (strchr(line, '\n'))
514 break; /* One or more lines read */
519 /* OK, we read some data */
522 /* If we got more than one line, cut off after the first \n */
523 lineptr = strchr(line, '\n');
525 *(lineptr + 1) = '\0';
530 * If EOL is \r\n, convert to just \n. Because stdout is a
531 * text-mode stream, the \n output by the child process is
532 * received as \r\n, so we convert it to \n. The server main.c
533 * sets setvbuf(stdout, NULL, _IONBF, 0) which has the effect of
534 * disabling \n to \r\n expansion for stdout.
536 if (len >= 2 && line[len - 2] == '\r' && line[len - 1] == '\n')
538 line[len - 2] = '\n';
539 line[len - 1] = '\0';
544 * We emulate fgets() behaviour. So if there is no newline at the
547 if (len == 0 || line[len - 1] != '\n')
553 CloseHandle(pi.hProcess);
554 CloseHandle(pi.hThread);
557 CloseHandle(childstdoutwr);
558 CloseHandle(childstdoutrddup);
566 * pclose() plus useful error reporting
567 * Is this necessary? bjm 2004-05-11
568 * It is better here because pipe.c has win32 backend linkage.
571 pclose_check(FILE *stream)
575 exitstatus = pclose(stream);
578 return 0; /* all is well */
580 if (exitstatus == -1)
582 /* pclose() itself failed, and hopefully set errno */
583 perror("pclose failed");
585 else if (WIFEXITED(exitstatus))
586 log_error(_("child process exited with exit code %d"),
587 WEXITSTATUS(exitstatus));
588 else if (WIFSIGNALED(exitstatus))
590 log_error(_("child process was terminated by exception 0x%X"),
591 WTERMSIG(exitstatus));
592 #elif defined(HAVE_DECL_SYS_SIGLIST) && HAVE_DECL_SYS_SIGLIST
596 snprintf(str, sizeof(str), "%d: %s", WTERMSIG(exitstatus),
597 WTERMSIG(exitstatus) < NSIG ?
598 sys_siglist[WTERMSIG(exitstatus)] : "(unknown)");
599 log_error(_("child process was terminated by signal %s"), str);
602 log_error(_("child process was terminated by signal %d"),
603 WTERMSIG(exitstatus));
606 log_error(_("child process exited with unrecognized status %d"),
614 * set_pglocale_pgservice
616 * Set application-specific locale and service directory
618 * This function takes the value of argv[0] rather than a full path.
620 * (You may be wondering why this is in exec.c. It requires this module's
621 * services and doesn't introduce any new dependencies, so this seems as
625 set_pglocale_pgservice(const char *argv0, const char *app)
627 char path[MAXPGPATH];
628 char my_exec_path[MAXPGPATH];
629 char env_path[MAXPGPATH + sizeof("PGSYSCONFDIR=")]; /* longer than
632 /* don't set LC_ALL in the backend */
633 if (strcmp(app, "postgres") != 0)
634 setlocale(LC_ALL, "");
636 if (find_my_exec(argv0, my_exec_path) < 0)
640 get_locale_path(my_exec_path, path);
641 bindtextdomain(app, path);
644 if (getenv("PGLOCALEDIR") == NULL)
646 /* set for libpq to use */
647 snprintf(env_path, sizeof(env_path), "PGLOCALEDIR=%s", path);
648 canonicalize_path(env_path + 12);
649 putenv(strdup(env_path));
653 if (getenv("PGSYSCONFDIR") == NULL)
655 get_etc_path(my_exec_path, path);
657 /* set for libpq to use */
658 snprintf(env_path, sizeof(env_path), "PGSYSCONFDIR=%s", path);
659 canonicalize_path(env_path + 13);
660 putenv(strdup(env_path));
667 * AddUserToDacl(HANDLE hProcess)
669 * This function adds the current user account to the default DACL
670 * which gets attached to the restricted token used when we create
671 * a restricted process.
673 * This is required because of some security changes in Windows
674 * that appeared in patches to XP/2K3 and in Vista/2008.
676 * On these machines, the Administrator account is not included in
677 * the default DACL - you just get Administrators + System. For
678 * regular users you get User + System. Because we strip Administrators
679 * when we create the restricted token, we are left with only System
680 * in the DACL which leads to access denied errors for later CreatePipe()
681 * and CreateProcess() calls when running as Administrator.
683 * This function fixes this problem by modifying the DACL of the
684 * specified process and explicitly re-adding the current user account.
685 * This is still secure because the Administrator account inherits it's
686 * privileges from the Administrators group - it doesn't have any of
690 AddUserToDacl(HANDLE hProcess)
693 ACL_SIZE_INFORMATION asi;
694 ACCESS_ALLOWED_ACE *pace;
697 DWORD dwTokenInfoLength = 0;
699 HANDLE hToken = NULL;
701 PSID psidUser = NULL;
702 TOKEN_DEFAULT_DACL tddNew;
703 TOKEN_DEFAULT_DACL *ptdd = NULL;
704 TOKEN_INFORMATION_CLASS tic = TokenDefaultDacl;
707 /* Get the token for the process */
708 if (!OpenProcessToken(hProcess, TOKEN_QUERY | TOKEN_ADJUST_DEFAULT, &hToken))
710 log_error("could not open process token: %ui", GetLastError());
714 /* Figure out the buffer size for the DACL info */
715 if (!GetTokenInformation(hToken, tic, (LPVOID) NULL, dwTokenInfoLength, &dwSize))
717 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
719 ptdd = (TOKEN_DEFAULT_DACL *) LocalAlloc(LPTR, dwSize);
722 log_error("could not allocate %i bytes of memory", dwSize);
726 if (!GetTokenInformation(hToken, tic, (LPVOID) ptdd, dwSize, &dwSize))
728 log_error("could not get token information: %ui", GetLastError());
734 log_error("could not get token information buffer size: %ui", GetLastError());
739 /* Get the ACL info */
740 if (!GetAclInformation(ptdd->DefaultDacl, (LPVOID) & asi,
741 (DWORD) sizeof(ACL_SIZE_INFORMATION),
744 log_error("could not get ACL information: %ui", GetLastError());
748 /* Get the SID for the current user. We need to add this to the ACL. */
749 if (!GetUserSid(&psidUser, hToken))
751 log_error("could not get user SID: %ui", GetLastError());
755 /* Figure out the size of the new ACL */
756 dwNewAclSize = asi.AclBytesInUse + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(psidUser) - sizeof(DWORD);
758 /* Allocate the ACL buffer & initialize it */
759 pacl = (PACL) LocalAlloc(LPTR, dwNewAclSize);
762 log_error("could not allocate %i bytes of memory", dwNewAclSize);
766 if (!InitializeAcl(pacl, dwNewAclSize, ACL_REVISION))
768 log_error("could not initialize ACL: %ui", GetLastError());
772 /* Loop through the existing ACEs, and build the new ACL */
773 for (i = 0; i < (int) asi.AceCount; i++)
775 if (!GetAce(ptdd->DefaultDacl, i, (LPVOID *) & pace))
777 log_error("could not get ACE: %ui", GetLastError());
781 if (!AddAce(pacl, ACL_REVISION, MAXDWORD, pace, ((PACE_HEADER) pace)->AceSize))
783 log_error("could not add ACE: %ui", GetLastError());
788 /* Add the new ACE for the current user */
789 if (!AddAccessAllowedAce(pacl, ACL_REVISION, GENERIC_ALL, psidUser))
791 log_error("could not add access allowed ACE: %ui", GetLastError());
795 /* Set the new DACL in the token */
796 tddNew.DefaultDacl = pacl;
798 if (!SetTokenInformation(hToken, tic, (LPVOID) & tddNew, dwNewAclSize))
800 log_error("could not set token information: %ui", GetLastError());
811 LocalFree((HLOCAL) pacl);
814 LocalFree((HLOCAL) ptdd);
823 * GetUserSid*PSID *ppSidUser, HANDLE hToken)
825 * Get the SID for the current user
828 GetUserSid(PSID * ppSidUser, HANDLE hToken)
832 DWORD cbDomainName = 250;
833 PTOKEN_USER pTokenUser = NULL;
836 if (!GetTokenInformation(hToken,
842 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
844 pTokenUser = (PTOKEN_USER) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwLength);
846 if (pTokenUser == NULL)
848 log_error("could not allocate %ui bytes of memory", dwLength);
854 log_error("could not get token information buffer size: %ui", GetLastError());
859 if (!GetTokenInformation(hToken,
865 HeapFree(GetProcessHeap(), 0, pTokenUser);
868 log_error("could not get token information: %ui", GetLastError());
872 *ppSidUser = pTokenUser->User.Sid;