summaryrefslogtreecommitdiff
path: root/apache/mksuexec/suexec.c
blob: af67ad571793fafdde25043306d436ee8911f83c (plain)
  1. /* Copyright 1999-2004 The Apache Software Foundation
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. /*
  16. * suexec.c -- "Wrapper" support program for suEXEC behaviour for Apache
  17. *
  18. ***********************************************************************
  19. *
  20. * NOTE! : DO NOT edit this code!!! Unless you know what you are doing,
  21. * editing this code might open up your system in unexpected
  22. * ways to would-be crackers. Every precaution has been taken
  23. * to make this code as safe as possible; alter it at your own
  24. * risk.
  25. *
  26. ***********************************************************************
  27. *
  28. *
  29. */
  30. #include "apr.h"
  31. #include "ap_config.h"
  32. #include "suexec.h"
  33. #define AP_DOC_ROOT "/home"
  34. #include <sys/param.h>
  35. #include <sys/stat.h>
  36. #include <sys/types.h>
  37. #include <string.h>
  38. #include <time.h>
  39. #if APR_HAVE_UNISTD_H
  40. #include <unistd.h>
  41. #endif
  42. #include <stdio.h>
  43. #include <stdarg.h>
  44. #include <stdlib.h>
  45. #ifdef HAVE_PWD_H
  46. #include <pwd.h>
  47. #endif
  48. #ifdef HAVE_GRP_H
  49. #include <grp.h>
  50. #endif
  51. /*
  52. ***********************************************************************
  53. * There is no initgroups() in QNX, so I believe this is safe :-)
  54. * Use cc -osuexec -3 -O -mf -DQNX suexec.c to compile.
  55. *
  56. * May 17, 1997.
  57. * Igor N. Kovalenko -- infoh@mail.wplus.net
  58. ***********************************************************************
  59. */
  60. #if defined(NEED_INITGROUPS)
  61. int initgroups(const char *name, gid_t basegid)
  62. {
  63. /* QNX and MPE do not appear to support supplementary groups. */
  64. return 0;
  65. }
  66. #endif
  67. #if defined(SUNOS4)
  68. extern char *sys_errlist[];
  69. #define strerror(x) sys_errlist[(x)]
  70. #endif
  71. #if defined(PATH_MAX)
  72. #define AP_MAXPATH PATH_MAX
  73. #elif defined(MAXPATHLEN)
  74. #define AP_MAXPATH MAXPATHLEN
  75. #else
  76. #define AP_MAXPATH 8192
  77. #endif
  78. #define AP_ENVBUF 256
  79. extern char **environ;
  80. static FILE *log = NULL;
  81. char *safe_env_lst[] =
  82. {
  83. /* variable name starts with */
  84. "HTTP_",
  85. "SSL_",
  86. /* variable name is */
  87. "AUTH_TYPE=",
  88. "CONTENT_LENGTH=",
  89. "CONTENT_TYPE=",
  90. "DATE_GMT=",
  91. "DATE_LOCAL=",
  92. "DOCUMENT_NAME=",
  93. "DOCUMENT_PATH_INFO=",
  94. "DOCUMENT_ROOT=",
  95. "DOCUMENT_URI=",
  96. "FILEPATH_INFO=",
  97. "GATEWAY_INTERFACE=",
  98. "HTTPS=",
  99. "LAST_MODIFIED=",
  100. "PATH_INFO=",
  101. "PATH_TRANSLATED=",
  102. "QUERY_STRING=",
  103. "QUERY_STRING_UNESCAPED=",
  104. "REMOTE_ADDR=",
  105. "REMOTE_HOST=",
  106. "REMOTE_IDENT=",
  107. "REMOTE_PORT=",
  108. "REMOTE_USER=",
  109. "REDIRECT_QUERY_STRING=",
  110. "REDIRECT_REMOTE_USER=",
  111. "REDIRECT_STATUS=",
  112. "REDIRECT_URL=",
  113. "REQUEST_METHOD=",
  114. "REQUEST_URI=",
  115. "SCRIPT_FILENAME=",
  116. "SCRIPT_NAME=",
  117. "SCRIPT_URI=",
  118. "SCRIPT_URL=",
  119. "SERVER_ADMIN=",
  120. "SERVER_NAME=",
  121. "SERVER_ADDR=",
  122. "SERVER_PORT=",
  123. "SERVER_PROTOCOL=",
  124. "SERVER_SIGNATURE=",
  125. "SERVER_SOFTWARE=",
  126. "UNIQUE_ID=",
  127. "USER_NAME=",
  128. "TZ=",
  129. NULL
  130. };
  131. static void err_output(const char *fmt, va_list ap)
  132. {
  133. #ifdef AP_LOG_EXEC
  134. time_t timevar;
  135. struct tm *lt;
  136. if (!log) {
  137. if ((log = fopen(AP_LOG_EXEC, "a")) == NULL) {
  138. fprintf(stderr, "failed to open log file\n");
  139. perror("fopen");
  140. exit(1);
  141. }
  142. }
  143. time(&timevar);
  144. lt = localtime(&timevar);
  145. fprintf(log, "[%d-%.2d-%.2d %.2d:%.2d:%.2d]: ",
  146. lt->tm_year + 1900, lt->tm_mon + 1, lt->tm_mday,
  147. lt->tm_hour, lt->tm_min, lt->tm_sec);
  148. vfprintf(log, fmt, ap);
  149. fflush(log);
  150. #endif /* AP_LOG_EXEC */
  151. return;
  152. }
  153. static void log_err(const char *fmt,...)
  154. {
  155. #ifdef AP_LOG_EXEC
  156. va_list ap;
  157. va_start(ap, fmt);
  158. err_output(fmt, ap);
  159. va_end(ap);
  160. #endif /* AP_LOG_EXEC */
  161. return;
  162. }
  163. static void clean_env(void)
  164. {
  165. char pathbuf[512];
  166. char **cleanenv;
  167. char **ep;
  168. int cidx = 0;
  169. int idx;
  170. /* While cleaning the environment, the environment should be clean.
  171. * (e.g. malloc() may get the name of a file for writing debugging info.
  172. * Bad news if MALLOC_DEBUG_FILE is set to /etc/passwd. Sprintf() may be
  173. * susceptible to bad locale settings....)
  174. * (from PR 2790)
  175. */
  176. char **envp = environ;
  177. char *empty_ptr = NULL;
  178. environ = &empty_ptr; /* VERY safe environment */
  179. if ((cleanenv = (char **) calloc(AP_ENVBUF, sizeof(char *))) == NULL) {
  180. log_err("failed to malloc memory for environment\n");
  181. exit(120);
  182. }
  183. sprintf(pathbuf, "PATH=%s", AP_SAFE_PATH);
  184. cleanenv[cidx] = strdup(pathbuf);
  185. cidx++;
  186. for (ep = envp; *ep && cidx < AP_ENVBUF-1; ep++) {
  187. for (idx = 0; safe_env_lst[idx]; idx++) {
  188. if (!strncmp(*ep, safe_env_lst[idx],
  189. strlen(safe_env_lst[idx]))) {
  190. cleanenv[cidx] = *ep;
  191. cidx++;
  192. break;
  193. }
  194. }
  195. }
  196. cleanenv[cidx] = NULL;
  197. environ = cleanenv;
  198. }
  199. int main(int argc, char *argv[])
  200. {
  201. int userdir = 0; /* ~userdir flag */
  202. uid_t uid; /* user information */
  203. gid_t gid; /* target group placeholder */
  204. char *target_uname; /* target user name */
  205. char *target_gname; /* target group name */
  206. char *target_homedir; /* target home directory */
  207. char *actual_uname; /* actual user name */
  208. char *actual_gname; /* actual group name */
  209. char *prog; /* name of this program */
  210. char *cmd; /* command to be executed */
  211. char cwd[AP_MAXPATH]; /* current working directory */
  212. char dwd[AP_MAXPATH]; /* docroot working directory */
  213. struct passwd *pw; /* password entry holder */
  214. struct group *gr; /* group entry holder */
  215. struct stat dir_info; /* directory info holder */
  216. struct stat prg_info; /* program info holder */
  217. /*
  218. * Start with a "clean" environment
  219. */
  220. clean_env();
  221. prog = argv[0];
  222. /*
  223. * Check existence/validity of the UID of the user
  224. * running this program. Error out if invalid.
  225. */
  226. uid = getuid();
  227. if ((pw = getpwuid(uid)) == NULL) {
  228. log_err("crit: invalid uid: (%ld)\n", uid);
  229. exit(102);
  230. }
  231. /*
  232. * See if this is a 'how were you compiled' request, and
  233. * comply if so.
  234. */
  235. if ((argc > 1)
  236. && (! strcmp(argv[1], "-V"))
  237. && ((uid == 0)
  238. #ifdef _OSD_POSIX
  239. /* User name comparisons are case insensitive on BS2000/OSD */
  240. || (! strcasecmp(AP_HTTPD_USER, pw->pw_name)))
  241. #else /* _OSD_POSIX */
  242. || (! strcmp(AP_HTTPD_USER, pw->pw_name)))
  243. #endif /* _OSD_POSIX */
  244. ) {
  245. #ifdef AP_DOC_ROOT
  246. fprintf(stderr, " -D AP_DOC_ROOT=\"%s\"\n", AP_DOC_ROOT);
  247. #endif
  248. #ifdef AP_GID_MIN
  249. fprintf(stderr, " -D AP_GID_MIN=%d\n", AP_GID_MIN);
  250. #endif
  251. #ifdef AP_HTTPD_USER
  252. fprintf(stderr, " -D AP_HTTPD_USER=\"%s\"\n", AP_HTTPD_USER);
  253. #endif
  254. #ifdef AP_LOG_EXEC
  255. fprintf(stderr, " -D AP_LOG_EXEC=\"%s\"\n", AP_LOG_EXEC);
  256. #endif
  257. #ifdef AP_SAFE_PATH
  258. fprintf(stderr, " -D AP_SAFE_PATH=\"%s\"\n", AP_SAFE_PATH);
  259. #endif
  260. #ifdef AP_SUEXEC_UMASK
  261. fprintf(stderr, " -D AP_SUEXEC_UMASK=%03o\n", AP_SUEXEC_UMASK);
  262. #endif
  263. #ifdef AP_UID_MIN
  264. fprintf(stderr, " -D AP_UID_MIN=%d\n", AP_UID_MIN);
  265. #endif
  266. #ifdef AP_USERDIR_SUFFIX
  267. fprintf(stderr, " -D AP_USERDIR_SUFFIX=\"%s\"\n", AP_USERDIR_SUFFIX);
  268. #endif
  269. exit(0);
  270. }
  271. /*
  272. * If there are a proper number of arguments, set
  273. * all of them to variables. Otherwise, error out.
  274. */
  275. if (argc < 4) {
  276. log_err("too few arguments\n");
  277. exit(101);
  278. }
  279. target_uname = argv[1];
  280. target_gname = argv[2];
  281. cmd = argv[3];
  282. /*
  283. * Check to see if the user running this program
  284. * is the user allowed to do so as defined in
  285. * suexec.h. If not the allowed user, error out.
  286. */
  287. #ifdef _OSD_POSIX
  288. /* User name comparisons are case insensitive on BS2000/OSD */
  289. if (strcasecmp(AP_HTTPD_USER, pw->pw_name)) {
  290. log_err("user mismatch (%s instead of %s)\n", pw->pw_name, AP_HTTPD_USER);
  291. exit(103);
  292. }
  293. #else /*_OSD_POSIX*/
  294. if (strcmp(AP_HTTPD_USER, pw->pw_name)) {
  295. log_err("user mismatch (%s instead of %s)\n", pw->pw_name, AP_HTTPD_USER);
  296. exit(103);
  297. }
  298. #endif /*_OSD_POSIX*/
  299. /*
  300. * Check for a leading '/' (absolute path) in the command to be executed,
  301. * or attempts to back up out of the current directory,
  302. * to protect against attacks. If any are
  303. * found, error out. Naughty naughty crackers.
  304. */
  305. if ((cmd[0] == '/') || (!strncmp(cmd, "../", 3))
  306. || (strstr(cmd, "/../") != NULL)) {
  307. log_err("invalid command (%s)\n", cmd);
  308. exit(104);
  309. }
  310. /*
  311. * Check to see if this is a ~userdir request. If
  312. * so, set the flag, and remove the '~' from the
  313. * target username.
  314. */
  315. if (!strncmp("~", target_uname, 1)) {
  316. target_uname++;
  317. userdir = 1;
  318. }
  319. /*
  320. * Error out if the target username is invalid.
  321. */
  322. if (strspn(target_uname, "1234567890") != strlen(target_uname)) {
  323. if ((pw = getpwnam(target_uname)) == NULL) {
  324. log_err("invalid target user name: (%s)\n", target_uname);
  325. exit(105);
  326. }
  327. }
  328. else {
  329. if ((pw = getpwuid(atoi(target_uname))) == NULL) {
  330. log_err("invalid target user id: (%s)\n", target_uname);
  331. exit(121);
  332. }
  333. }
  334. /*
  335. * Error out if the target group name is invalid.
  336. */
  337. if (strspn(target_gname, "1234567890") != strlen(target_gname)) {
  338. if ((gr = getgrnam(target_gname)) == NULL) {
  339. log_err("invalid target group name: (%s)\n", target_gname);
  340. exit(106);
  341. }
  342. gid = gr->gr_gid;
  343. actual_gname = strdup(gr->gr_name);
  344. }
  345. else {
  346. gid = atoi(target_gname);
  347. actual_gname = strdup(target_gname);
  348. }
  349. #ifdef _OSD_POSIX
  350. /*
  351. * Initialize BS2000 user environment
  352. */
  353. {
  354. pid_t pid;
  355. int status;
  356. switch (pid = ufork(target_uname)) {
  357. case -1: /* Error */
  358. log_err("failed to setup bs2000 environment for user %s: %s\n",
  359. target_uname, strerror(errno));
  360. exit(150);
  361. case 0: /* Child */
  362. break;
  363. default: /* Father */
  364. while (pid != waitpid(pid, &status, 0))
  365. ;
  366. /* @@@ FIXME: should we deal with STOP signals as well? */
  367. if (WIFSIGNALED(status)) {
  368. kill (getpid(), WTERMSIG(status));
  369. }
  370. exit(WEXITSTATUS(status));
  371. }
  372. }
  373. #endif /*_OSD_POSIX*/
  374. /*
  375. * Save these for later since initgroups will hose the struct
  376. */
  377. uid = pw->pw_uid;
  378. actual_uname = strdup(pw->pw_name);
  379. target_homedir = strdup(pw->pw_dir);
  380. /*
  381. * Log the transaction here to be sure we have an open log
  382. * before we setuid().
  383. */
  384. log_err("uid: (%s/%s) gid: (%s/%s) cmd: %s\n",
  385. target_uname, actual_uname,
  386. target_gname, actual_gname,
  387. cmd);
  388. /*
  389. * Error out if attempt is made to execute as root or as
  390. * a UID less than AP_UID_MIN. Tsk tsk.
  391. */
  392. if ((uid == 0) || (uid < AP_UID_MIN)) {
  393. log_err("cannot run as forbidden uid (%d/%s)\n", uid, cmd);
  394. exit(107);
  395. }
  396. /*
  397. * Error out if attempt is made to execute as root group
  398. * or as a GID less than AP_GID_MIN. Tsk tsk.
  399. */
  400. if ((gid == 0) || (gid < AP_GID_MIN)) {
  401. log_err("cannot run as forbidden gid (%d/%s)\n", gid, cmd);
  402. exit(108);
  403. }
  404. /*
  405. * Change UID/GID here so that the following tests work over NFS.
  406. *
  407. * Initialize the group access list for the target user,
  408. * and setgid() to the target group. If unsuccessful, error out.
  409. */
  410. if (((setgid(gid)) != 0) || (initgroups(actual_uname, gid) != 0)) {
  411. log_err("failed to setgid (%ld: %s)\n", gid, cmd);
  412. exit(109);
  413. }
  414. /*
  415. * setuid() to the target user. Error out on fail.
  416. */
  417. if ((setuid(uid)) != 0) {
  418. log_err("failed to setuid (%ld: %s)\n", uid, cmd);
  419. exit(110);
  420. }
  421. /*
  422. * Get the current working directory, as well as the proper
  423. * document root (dependant upon whether or not it is a
  424. * ~userdir request). Error out if we cannot get either one,
  425. * or if the current working directory is not in the docroot.
  426. * Use chdir()s and getcwd()s to avoid problems with symlinked
  427. * directories. Yuck.
  428. */
  429. if (getcwd(cwd, AP_MAXPATH) == NULL) {
  430. log_err("cannot get current working directory\n");
  431. exit(111);
  432. }
  433. if (userdir) {
  434. if (((chdir(target_homedir)) != 0) ||
  435. ((chdir(AP_USERDIR_SUFFIX)) != 0) ||
  436. ((getcwd(dwd, AP_MAXPATH)) == NULL) ||
  437. ((chdir(cwd)) != 0)) {
  438. log_err("cannot get docroot information (%s)\n", target_homedir);
  439. exit(112);
  440. }
  441. }
  442. else {
  443. if (((chdir(AP_DOC_ROOT)) != 0) ||
  444. ((getcwd(dwd, AP_MAXPATH)) == NULL) ||
  445. ((chdir(cwd)) != 0)) {
  446. log_err("cannot get docroot information (%s)\n", AP_DOC_ROOT);
  447. exit(113);
  448. }
  449. }
  450. if ((strncmp(cwd, dwd, strlen(dwd))) != 0) {
  451. log_err("command not in docroot (%s/%s)\n", cwd, cmd);
  452. exit(114);
  453. }
  454. /*
  455. * Stat the cwd and verify it is a directory, or error out.
  456. */
  457. if (((lstat(cwd, &dir_info)) != 0) || !(S_ISDIR(dir_info.st_mode))) {
  458. log_err("cannot stat directory: (%s)\n", cwd);
  459. exit(115);
  460. }
  461. /*
  462. * Error out if cwd is writable by others.
  463. */
  464. if ((dir_info.st_mode & S_IWOTH) || (dir_info.st_mode & S_IWGRP)) {
  465. log_err("directory is writable by others: (%s)\n", cwd);
  466. exit(116);
  467. }
  468. /*
  469. * Error out if we cannot stat the program.
  470. */
  471. if (((lstat(cmd, &prg_info)) != 0) || (S_ISLNK(prg_info.st_mode))) {
  472. log_err("cannot stat program: (%s)\n", cmd);
  473. exit(117);
  474. }
  475. /*
  476. * Error out if the program is writable by others.
  477. */
  478. if ((prg_info.st_mode & S_IWOTH) || (prg_info.st_mode & S_IWGRP)) {
  479. log_err("file is writable by others: (%s/%s)\n", cwd, cmd);
  480. exit(118);
  481. }
  482. /*
  483. * Error out if the file is setuid or setgid.
  484. */
  485. if ((prg_info.st_mode & S_ISUID) || (prg_info.st_mode & S_ISGID)) {
  486. log_err("file is either setuid or setgid: (%s/%s)\n", cwd, cmd);
  487. exit(119);
  488. }
  489. /*
  490. * Error out if the target name/group is different from
  491. * the name/group of the cwd or the program.
  492. */
  493. if ((uid != dir_info.st_uid) ||
  494. (gid != dir_info.st_gid) ||
  495. (uid != prg_info.st_uid) ||
  496. (gid != prg_info.st_gid)) {
  497. log_err("target uid/gid (%ld/%ld) mismatch "
  498. "with directory (%ld/%ld) or program (%ld/%ld)\n",
  499. uid, gid,
  500. dir_info.st_uid, dir_info.st_gid,
  501. prg_info.st_uid, prg_info.st_gid);
  502. exit(120);
  503. }
  504. /*
  505. * Error out if the program is not executable for the user.
  506. * Otherwise, she won't find any error in the logs except for
  507. * "[error] Premature end of script headers: ..."
  508. */
  509. if (!(prg_info.st_mode & S_IXUSR)) {
  510. log_err("file has no execute permission: (%s/%s)\n", cwd, cmd);
  511. exit(121);
  512. }
  513. #ifdef AP_SUEXEC_UMASK
  514. /*
  515. * umask() uses inverse logic; bits are CLEAR for allowed access.
  516. */
  517. if ((~AP_SUEXEC_UMASK) & 0022) {
  518. log_err("notice: AP_SUEXEC_UMASK of %03o allows "
  519. "write permission to group and/or other\n", AP_SUEXEC_UMASK);
  520. }
  521. umask(AP_SUEXEC_UMASK);
  522. #endif /* AP_SUEXEC_UMASK */
  523. /*
  524. * Be sure to close the log file so the CGI can't
  525. * mess with it. If the exec fails, it will be reopened
  526. * automatically when log_err is called. Note that the log
  527. * might not actually be open if AP_LOG_EXEC isn't defined.
  528. * However, the "log" cell isn't ifdef'd so let's be defensive
  529. * and assume someone might have done something with it
  530. * outside an ifdef'd AP_LOG_EXEC block.
  531. */
  532. if (log != NULL) {
  533. fclose(log);
  534. log = NULL;
  535. }
  536. /*
  537. * Execute the command, replacing our image with its own.
  538. */
  539. #ifdef NEED_HASHBANG_EMUL
  540. /* We need the #! emulation when we want to execute scripts */
  541. {
  542. extern char **environ;
  543. ap_execve(cmd, &argv[3], environ);
  544. }
  545. #else /*NEED_HASHBANG_EMUL*/
  546. execv(cmd, &argv[3]);
  547. #endif /*NEED_HASHBANG_EMUL*/
  548. /*
  549. * (I can't help myself...sorry.)
  550. *
  551. * Uh oh. Still here. Where's the kaboom? There was supposed to be an
  552. * EARTH-shattering kaboom!
  553. *
  554. * Oh well, log the failure and error out.
  555. */
  556. log_err("(%d)%s: exec failed (%s)\n", errno, strerror(errno), cmd);
  557. exit(255);
  558. }