aboutsummaryrefslogtreecommitdiffstats
path: root/safepath.c
blob: ce95740dd609c90e5dc41421fe0afed762b2549b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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
150
151
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
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
232
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
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
/*
 * safepath: safe path traversal for POSIX systems
 * Copyright 2022 Kaz Kylheku <kaz@kylheku.com>
 *
 * BSD-2 License
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <pwd.h>
#include <grp.h>
#include "safepath.h"

/*
 * Returns non-zero if st informs about an object that is not writable by
 * anyone other than the real user ID of the process, or else the superuser.
 */
static int safe_group(gid_t gid)
{
  char buf_root[256], buf_real[256], buf_grp[256];
  struct passwd pw_root, *pwr, pw_real, *pwu;
  struct group grp, *pgr;
  int i;

  /* Obtain passwd info about root user, to get at the name. */
  if (getpwuid_r(0, &pw_root, buf_root, sizeof buf_root, &pwr) < 0 ||
      pwr == 0)
  {
    return 0;
  }

  /* Obtain passwd info about effective user ID, to get at the name. */
  if (getpwuid_r(geteuid(), &pw_real, buf_real, sizeof buf_real, &pwu) < 0 ||
      pwu == 0)
  {
    return 0;
  }

  /* Obtain group info. */
  if (getgrgid_r(gid, &grp, buf_grp, sizeof buf_grp, &pgr) < 0 ||
      pgr == 0)
  {
    return 0;
  }

  /* Check that the group contains no member names other than
   * the root user or the real user.
   */
  for (i = 0; ; i++) {
    if (pgr->gr_mem[i] == 0)
      break;
    if (strcmp(pgr->gr_mem[i], pwr->pw_name) != 0 &&
        strcmp(pgr->gr_mem[i], pwu->pw_name) != 0)
      return 0;
  }

  return 1;
}

/*
 * Returns non-zero if st informs about an object that is not writable by
 * anyone other than the real user ID of the process, or else the superuser.
 */
static int tamper_proof(const struct stat *st)
{
  /* Owner isn't caller or root; that owner could
   * change the permissions to whatever they want
   * and modify the object.
   */
  if (st->st_uid != 0 && st->st_uid != geteuid())
    return 0;

  /* Ownership is good, but permissions are open; object is writable to
   * group owner or others. That could still be safe.
   */
  if ((st->st_mode & (S_IWGRP | S_IWOTH)) != 0) {
    /* Is this a directory owned by root, which has the sticky bit, such
     * as /tmp? That's OK.
     */
    if (S_ISDIR(st->st_mode) && (st->st_mode & S_ISVTX) != 0)
      return 1;
    /* Check for some situations of just the group permissions
     * being open, not others.
     */
    if ((st->st_mode & (S_IWGRP | S_IWOTH)) == S_IWGRP) {
      /* The group owner is the superuser group.
       * That is OK.
       */
      if (st->st_gid == 0)
        return 1;

      /* Otherwise, we do a complicated check
       */
      return safe_group(st->st_gid);
    }
    return 0;
  } else {
    return 1;
  }
}

static int safepath_err(int eno)
{
  switch (eno) {
  case 0:
    return SAFEPATH_OK;
  case ENOENT:
    return SAFEPATH_NOENT;
  case ENOTDIR:
    return SAFEPATH_NOTDIR;
  case EPERM:
  case EACCES:
    return SAFEPATH_PERM;
  case ENOMEM:
    return SAFEPATH_NOMEM;
  case ELOOP:
    return SAFEPATH_LOOP;
  default:
    return SAFEPATH_INVAL;
  }
}

static void set_errno(int spres)
{
  switch (spres) {
  case SAFEPATH_OK:
    break;
  case SAFEPATH_UNSAFE:
    errno = EACCES;
    break;
  case SAFEPATH_PERM:
    errno = EPERM;
    break;
  case SAFEPATH_NOENT:
    errno = ENOENT;
    break;
  case SAFEPATH_NOTDIR:
    errno = ENOTDIR;
    break;
  case SAFEPATH_INVAL:
    errno = EINVAL;
    break;
  case SAFEPATH_NOMEM:
    errno = ENOMEM;
    break;
  case SAFEPATH_LOOP:
    errno = ELOOP;
    break;
  }
}

int safepath_check(const char *name)
{
  struct stat st;
  const char *start = (*name == '/') ? "/" : ".";
  size_t pos = (*name == '/') ? 1 : 0;
  char *copy;
  int ret = SAFEPATH_OK, count = 0;

  /* empty name is invalid */
  if (*name == 0) {
    ret = SAFEPATH_INVAL;
    goto out;
  }

  /* check starting directory */
  if (stat(start, &st) < 0) {
    ret = safepath_err(errno);
    goto out;
  }

  if (!tamper_proof(&st)) {
    ret = SAFEPATH_UNSAFE;
    goto out;
  }

  /* check if that was the whole path */
  if (name[pos] == 0) {
    ret = SAFEPATH_OK;
    goto out;
  }

  /* now process path */
  if ((copy = strdup(name)) == 0) {
    ret = SAFEPATH_NOMEM;
    goto out;
  }

  while (copy[pos] != 0) {
    size_t nxslash = pos + strcspn(copy + pos, "/");
    int savechar = copy[nxslash];

    /* consecutive slashes */
    if (nxslash == pos) {
      ret = SAFEPATH_INVAL;
      goto free_out;
    }

    /* null terminate the path at the next slash */
    copy[nxslash] = 0;

    /* use lstat in case the component is a symlink */
    if (lstat(copy, &st) < 0) {
      ret = safepath_err(errno);
      goto free_out;
    }

    /* If it is a symlink, we can trust it because we validated the
     * previous component, which is the directory it lives in. However,
     * we trust only that link, and not what it points to.  It could
     * point to another link which is not secured against tampering.
     * Thus, we must implement symlink resolution right here ourselves:
     * replace the symlink component with its expansion and continue
     * checking the expansion, component by component.
     */
    if (S_ISLNK(st.st_mode)) {
      char link[256];
      int len;

      if (++count > 8) {
        ret = SAFEPATH_LOOP;
        goto free_out;
      }

      if ((len = readlink(copy, link, sizeof link)) < 0) {
        ret = safepath_err(errno);
        goto free_out;
      }

      if (len == sizeof link) {
        ret = SAFEPATH_TOOLONG;
        goto free_out;
      }

      link[len] = 0;

      /* Resolve the symlink, using two different cases based
       * on whether the target is absolute or relative.
       * Either way it's string grafting.
       */
      if (link[0] == '/') {
        /* If savechar is zero, we are working with the last component.
         * If the last component is an absolute symlink, we just replace
         * the path with the target, and iterate.  Otherwise, we must
         * graft the remainder of the path onto the symlink target.
         */
        if (savechar == 0) {
          free(copy);
          if ((copy = strdup(link)) == NULL) {
            ret = SAFEPATH_NOMEM;
            goto out;
          }
          pos = 1;
          continue;
        } else {
          size_t total = len + 1 + strlen(copy + nxslash + 1) + 1;
          char *resolved = malloc(total);
          if (resolved == NULL) {
            ret = SAFEPATH_NOMEM;
            goto free_out;
          }
          strcpy(resolved, link);
          resolved[len] = '/';
          strcpy(resolved + len + 1, copy + nxslash + 1);
          free(copy);
          copy = resolved;
          pos = 1;
          continue;
        }
      } else {
        if (savechar == 0) {
          size_t total = pos + len + 1;
          char *resolved = malloc(total);
          if (resolved == NULL) {
            ret = SAFEPATH_NOMEM;
            goto free_out;
          }
          memcpy(resolved, copy, pos);
          strcpy(resolved + pos, link);
          free(copy);
          copy = resolved;
          continue;
        } else {
          size_t total = pos + len + 1 + strlen(copy + nxslash + 1) + 1;
          char *resolved = malloc(total);
          if (resolved == NULL) {
            ret = SAFEPATH_NOMEM;
            goto free_out;
          }
          memcpy(resolved, copy, pos);
          strcpy(resolved + pos, link);
          resolved[pos + len] = '/';
          strcpy(resolved + pos + len, copy + nxslash + 1);
          free(copy);
          copy = resolved;
          continue;
        }
      }
    }

    /* Not symlink: check if it's safe
     * and move to next component, if any.
     */
    if (!tamper_proof(&st)) {
      ret = SAFEPATH_UNSAFE;
      goto free_out;
    }

    /* Undo null termination */
    copy[nxslash] = savechar;

    /* Start search for next slash after current slash;
     * but not if nxslash is actually at the end of the string
     */
    pos = nxslash + (savechar != 0);
  }

free_out:
  free(copy);
out:
  return ret;
}

const char *safepath_strerr(int err)
{
  const char *str[] = {
    [SAFEPATH_OK]       = "path appears safe",
    [SAFEPATH_UNSAFE]   = "path contains untrusted component",
    [SAFEPATH_PERM]     = "path contains inaccessible component",
    [SAFEPATH_NOENT]    = "path contains nonexistent component",
    [SAFEPATH_NOTDIR]   = "path contains non-directory component",
    [SAFEPATH_INVAL]    = "path is syntactically invalid",
    [SAFEPATH_NOMEM]    = "out of memory",
    [SAFEPATH_LOOP]     = "too many symlink resolutions",
    [SAFEPATH_TOOLONG]  = "path component or symlink target too long"
  };
  const char *ret = "SAFEPATH_BAD_ERROR_CODE";

  if (err >= 0 && err <= (int) (sizeof str / sizeof str[0]) && str[err] != 0)
  {
    ret = str[err];
  }

  return ret;
}

int safepath_open(const char *name, int flags)
{
  int res = safepath_check(name);

  if (res == SAFEPATH_OK)
    return open(name, flags);

  set_errno(res);
  return -1;
}

int safepath_open_mode(const char *name, int flags, mode_t mode)
{
  int res = safepath_check(name);

  if (res == SAFEPATH_OK)
    return open(name, flags, mode);

  set_errno(res);
  return -1;
}

/* STDIO wrappers */
FILE* safepath_fopen(const char *name, const char *mode)
{
  int res = safepath_check(name);

  if (res == SAFEPATH_OK)
    return fopen(name, mode);

  set_errno(res);
  return 0;
}

FILE* safepath_freopen(const char *name, const char *mode, FILE *stream)
{
  int res = safepath_check(name);

  if (res == SAFEPATH_OK)
    return freopen(name, mode, stream);

  set_errno(res);
  return 0;
}