suexec.c 10.8 KB
Newer Older
ale's avatar
ale committed
1
2
3
4
5
6
7
8
9
10
/*
 * Simple suexec replacement, customized for A/I hosting needs.
 *
 * It is configurable, and it does not use NSS.
 */

#define _GNU_SOURCE 1

#include "config.h"
#include "log.h"
ale's avatar
ale committed
11
#include "sandbox.h"
ale's avatar
ale committed
12
13
14
15
#include "strlist.h"

#include <ctype.h>
#include <fcntl.h>
ale's avatar
ale committed
16
#include <grp.h> /* for setgroups() */
ale's avatar
ale committed
17
18
19
20
21
22
23
24
25
26
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>

ale's avatar
ale committed
27
28
#define SUEXEC_CONFIG "/etc/apache2/suexec-sandbox.conf"
#define SUEXEC_CONFIG_DIR "/etc/apache2/suexec-sandbox.d"
ale's avatar
ale committed
29
#define DEFAULT_SAFE_PATH "/bin:/usr/bin"
ale's avatar
ale committed
30
31
32
33
34
35

#define MAX_ENV_SIZE 256
#define MAX_LINE_SIZE 1024

struct config {
  char *path;
ale's avatar
ale committed
36
  char *root;
ale's avatar
ale committed
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
  char **allowed_cmds;
  int num_allowed_cmds;
  char **docroots;
  int num_docroots;
  int min_uid;
  int min_gid;
};

// Convert string to int, with syntax checking.
static int s2i(char *s, int *i) {
  char *endptr = NULL;
  long n = strtol(s, &endptr, 10);
  if (endptr == s)
    return -1;
  *i = (int)n;
  return 0;
}

static int config_add_allowed_cmd(struct config *config, char *value) {
ale's avatar
ale committed
56
57
  return strlist_append(&(config->allowed_cmds), &(config->num_allowed_cmds),
                        value);
ale's avatar
ale committed
58
59
60
61
62
63
64
65
66
67
68
69
70
}

static int config_add_docroot(struct config *config, char *value) {
  // Check the value (it must be an absolute path).
  if (value[0] != '/') {
    log_printf("docroot '%s' is not an absolute path", value);
    return -1;
  }
  if (value[1] == '/' || value[1] == '.' || value[1] == '\0') {
    log_printf("invalid docroot '%s'", value);
    return -1;
  }

ale's avatar
ale committed
71
72
73
74
75
76
77
  // Strip trailing slashes.
  {
    int n = strlen(value);
    while (n > 1 && value[n - 1] == '/')
      value[n--] = '\0';
  }

ale's avatar
ale committed
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
  // Extend the docroots array.
  return strlist_append(&(config->docroots), &(config->num_docroots), value);
}

static int config_set_min_uid(struct config *config, char *value) {
  return s2i(value, &(config->min_uid));
}

static int config_set_min_gid(struct config *config, char *value) {
  return s2i(value, &(config->min_gid));
}

static char *trim_comment(char *s) {
  if (s) {
    char *p = strchr(s, '#');
    if (p)
      *p = 0;
  }
  return s;
}

static char *trim_right(char *s) {
  if (s) {
    char *p = s;
    while (*p)
      p++;
    p--;
    while (isspace(*p) && p >= s)
      *p-- = 0;
  }
  return s;
}

static int parse_assignment(char *line, char **key, char **value) {
  char *sep;

  line = trim_right(trim_comment(line));
  if (*line == '\0')
    return 0;
  sep = strchr(line, ' ');
  if (!sep)
    return -1;
  while (*sep && isspace(*sep))
    *sep++ = 0;
  *key = line;
  *value = sep;
  return 0;
}

static int read_config(const char *path, struct config *config) {
  char buf[MAX_LINE_SIZE], *p;
  int r = 0, lineno = 1;
  FILE *fp = NULL;

  fp = fopen(path, "r");
  if (!fp) {
    log_printf("Could not open configuration file %s", path);
    return -1;
  }

  while ((p = fgets(buf, MAX_LINE_SIZE, fp)) != NULL) {
    char *key = NULL, *value = NULL;
    if (parse_assignment(p, &key, &value) < 0) {
      log_printf("Syntax error at %s:%d: not in 'attribute value' format", path,
                 lineno);
      return -1;
    }
    if (!key)
      continue;

    if (!strcmp(key, "path")) {
      config->path = strdup(value);
ale's avatar
ale committed
150
151
    } else if (!strcmp(key, "root")) {
      config->root = strdup(value);
ale's avatar
ale committed
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
    } else if (!strcmp(key, "allowed_cmd")) {
      r = config_add_allowed_cmd(config, value);
    } else if (!strcmp(key, "docroot")) {
      r = config_add_docroot(config, value);
    } else if (!strcmp(key, "min_uid")) {
      r = config_set_min_uid(config, value);
    } else if (!strcmp(key, "min_gid")) {
      r = config_set_min_gid(config, value);
    } else {
      log_printf("Syntax error at %s:%d: unknown directive '%s'", path, lineno,
                 key);
      return -1;
    }
    if (r < 0) {
      log_printf("Syntax error at %s:%d: error setting attribute", path,
                 lineno);
      return r;
    }

    lineno++;
  };

  fclose(fp);
  return 0;
}

static const char *const safe_env_lst[] = {
    /* variable name starts with */
ale's avatar
ale committed
180
181
182
  "HTTP_", "SSL_",

  "PHPRC=",
ale's avatar
ale committed
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204

    /* variable name is */
    "AUTH_TYPE=", "CONTENT_LENGTH=", "CONTENT_TYPE=", "CONTEXT_DOCUMENT_ROOT=",
    "CONTEXT_PREFIX=", "DATE_GMT=", "DATE_LOCAL=", "DOCUMENT_ARGS=",
    "DOCUMENT_NAME=", "DOCUMENT_PATH_INFO=", "DOCUMENT_ROOT=", "DOCUMENT_URI=",
    "GATEWAY_INTERFACE=", "HTTPS=", "LAST_MODIFIED=", "PATH_INFO=",
    "PATH_TRANSLATED=", "QUERY_STRING=", "QUERY_STRING_UNESCAPED=",
    "REMOTE_ADDR=", "REMOTE_HOST=", "REMOTE_IDENT=", "REMOTE_PORT=",
    "REMOTE_USER=", "REDIRECT_ERROR_NOTES=", "REDIRECT_HANDLER=",
    "REDIRECT_QUERY_STRING=", "REDIRECT_REMOTE_USER=",
    "REDIRECT_SCRIPT_FILENAME=", "REDIRECT_STATUS=", "REDIRECT_URL=",
    "REQUEST_METHOD=", "REQUEST_URI=", "REQUEST_SCHEME=", "SCRIPT_FILENAME=",
    "SCRIPT_NAME=", "SCRIPT_URI=", "SCRIPT_URL=", "SERVER_ADMIN=",
    "SERVER_NAME=", "SERVER_ADDR=", "SERVER_PORT=", "SERVER_PROTOCOL=",
    "SERVER_SIGNATURE=", "SERVER_SOFTWARE=", "UNIQUE_ID=", "USER_NAME=", "TZ=",
    NULL};

extern char **environ;

static char **saved_env;

static void save_env() {
ale's avatar
ale committed
205
206
  /* Wipe the environment as soon as possible, to prevent libc function side
   * effects. */
ale's avatar
ale committed
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
  static char *empty_ptr = NULL;
  saved_env = environ;
  environ = &empty_ptr;
}

static int clear_env(struct config *config) {
  char pathbuf[512];
  char **cleanenv;
  char **ep;
  int cidx = 0;
  int idx;

  /* While cleaning the environment, the environment should be clean.
   * (e.g. malloc() may get the name of a file for writing debugging info.
   * Bad news if MALLOC_DEBUG_FILE is set to /etc/passwd.  Sprintf() may be
   * susceptible to bad locale settings....)
   * (from PR 2790)
   */
  char **envp = saved_env;

  if ((cleanenv = (char **)calloc(MAX_ENV_SIZE, sizeof(char *))) == NULL) {
    log_println("failed to malloc memory for environment");
    return -1;
  }

ale's avatar
ale committed
232
  sprintf(pathbuf, "PATH=%s", config->path ? config->path : DEFAULT_SAFE_PATH);
ale's avatar
ale committed
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
  cleanenv[cidx] = strdup(pathbuf);
  if (cleanenv[cidx] == NULL) {
    log_println("failed to malloc memory for environment");
    return -1;
  }
  cidx++;

  for (ep = envp; *ep && cidx < MAX_ENV_SIZE - 1; ep++) {
    for (idx = 0; safe_env_lst[idx]; idx++) {
      if (!strncmp(*ep, safe_env_lst[idx], strlen(safe_env_lst[idx]))) {
        cleanenv[cidx] = *ep;
        cidx++;
        break;
      }
    }
  }

  cleanenv[cidx] = NULL;

  environ = cleanenv;
  return 0;
}

static int check_cmd(struct config *config, char *cmd) {
  struct stat prg_info;
  int i, allowed = 1;

  // Check if the command is allowed (only if allowed_cmd directives
  // are specified in the configuration).
  if (config->num_allowed_cmds > 0) {
    allowed = 0;
    for (i = 0; i < config->num_allowed_cmds; i++) {
      if (!strcmp(cmd, config->allowed_cmds[i])) {
        allowed = 1;
        break;
      }
    }
  }
  if (!allowed) {
    log_printf("command not allowed (%s)", cmd);
    return -1;
  }

  // Stat the program.
  if ((lstat(cmd, &prg_info) != 0) || (S_ISLNK(prg_info.st_mode))) {
    log_printf("cannot stat program (%s)", cmd);
    return -1;
  }

  if ((prg_info.st_mode & S_IWOTH) || (prg_info.st_mode & S_IWGRP)) {
    log_printf("program is writable by others (%s)", cmd);
    return -1;
  }

  if ((prg_info.st_mode & S_ISUID) || (prg_info.st_mode & S_ISGID)) {
    log_printf("program is setuid/setgid (%s)", cmd);
    return -1;
  }

  return 0;
}

ale's avatar
ale committed
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
static int check_cwd(struct config *config) {
  struct stat dir_info;
  int i, allowed = 1;
  char cwd[PATH_MAX];

  if (!getcwd(cwd, sizeof(cwd))) {
    log_println_errno("getcwd failed");
    return -1;
  }

  if ((lstat(cwd, &dir_info) != 0) || (!S_ISDIR(dir_info.st_mode))) {
    log_printf("cannot stat cwd (%s)", cwd);
    return -1;
  }
  if ((dir_info.st_mode & S_IWOTH) || (dir_info.st_mode & S_IWGRP)) {
    log_printf("directory is writable by others (%s)", cwd);
    return -1;
  }

  if (config->num_docroots > 0) {
    allowed = 0;
    for (i = 0; i < config->num_docroots; i++) {
      // Docroot must either match identically cwd, or cwd must have
      // (docroot + /) as a prefix.
      int n = strlen(config->docroots[i]);
      if (!strcmp(cwd, config->docroots[i]) ||
          (!strncmp(cwd, config->docroots[i], n) && cwd[n] == '/')) {
        allowed = 1;
        break;
      }
    }
  }
  if (!allowed) {
    log_printf("docroot not allowed (%s)", cwd);
    return -1;
  }
ale's avatar
ale committed
331

ale's avatar
ale committed
332
333
  return 0;
}
ale's avatar
ale committed
334
335
336
337
338

int main(int argc, char **argv) {
  int target_uid;
  int target_gid;
  char *cmd, *real_cmd;
ale's avatar
ale committed
339
  char user_config[512];
ale's avatar
ale committed
340
341
342
343
344
345

  // Create a new config and initialize it to nil.
  struct config config = (const struct config){0};
  struct sandbox_config sandbox_config;

  save_env();
ale's avatar
ale committed
346

ale's avatar
ale committed
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
  // Parse command-line arguments.
  if (argc == 2 && !strcmp(argv[1], "-V")) {
    fprintf(stderr, "%s (send bugs to <%s>)\n", PACKAGE_STRING,
            PACKAGE_BUGREPORT);
    exit(0);
  }
  if (argc < 4) {
    log_println("too few arguments");
    exit(1);
  }

  if (s2i(argv[1], &target_uid) < 0) {
    log_println("bad target_uid argument");
    exit(1);
  }
  if (s2i(argv[2], &target_gid) < 0) {
    log_println("bad target_gid argument");
    exit(1);
  }

  // In the standard apache2 suexec, cmd should not be an absolute
  // path. Worth checking anyway even if we don't care much (because
  // the later allow_cmd checks supersede it).
  cmd = argv[3];
  if (cmd[0] == '/') {
    log_printf("command must be a relative path (%s)", cmd);
    exit(1);
  }

  // Convert cmd to its real path to figure out what we want to
  // execute.
  real_cmd = realpath(cmd, NULL);
  if (!real_cmd) {
    log_printf("cannot find '%s'", cmd);
    exit(1);
  }

  // Read configuration file.
ale's avatar
ale committed
385
  if (read_config(SUEXEC_CONFIG, &config) < 0)
ale's avatar
ale committed
386
    exit(102);
ale's avatar
ale committed
387

ale's avatar
ale committed
388
389
390
391
392
393
394
395
396
397
398
399
400
401
  // Clean the environment.
  if (clear_env(&config) < 0)
    exit(110);

  // Check validity of arguments against configuration.
  if ((target_uid == 0) || (target_uid < config.min_uid)) {
    log_printf("cannot run as forbidden uid (%d/%s)", target_uid, cmd);
    exit(103);
  }
  if ((target_gid == 0) || (target_gid < config.min_gid)) {
    log_printf("cannot run as forbidden gid (%d/%s)", target_gid, cmd);
    exit(104);
  }

ale's avatar
ale committed
402
403
404
405
  // Read the user-specific configuration, if any.
  snprintf(user_config, sizeof(user_config), SUEXEC_CONFIG_DIR "/%d", target_uid);
  read_config(user_config, &config);
  
ale's avatar
ale committed
406
407
408
  if (check_cwd(&config) < 0)
    exit(105);

ale's avatar
ale committed
409
410
411
412
  if (check_cmd(&config, real_cmd) < 0)
    exit(105);

  // Invoke the sandbox.
ale's avatar
ale committed
413
414
  if (sandbox_config_init(&sandbox_config, target_uid, target_gid, argc - 4,
                          real_cmd, (argv + 3)) < 0)
ale's avatar
ale committed
415
416
    exit(106);

ale's avatar
ale committed
417
418
  if (config.root)
    sandbox_config.new_root_dir = config.root;
ale's avatar
ale committed
419
420
421

  if (sandbox_start(&sandbox_config) < 0)
    exit(107);
ale's avatar
ale committed
422

ale's avatar
ale committed
423
  // Switch user.
ale's avatar
ale committed
424
  // if (change_user(target_uid, target_gid) < 0)
ale's avatar
ale committed
425
  //  exit(105);
ale's avatar
ale committed
426

ale's avatar
ale committed
427
  // Execute the command (with arguments), in our clean environment.
ale's avatar
ale committed
428
429
  // execv(real_cmd, (argv + 3));

ale's avatar
ale committed
430
431
  exit(110);
}