summaryrefslogtreecommitdiff
path: root/plugins/sudoers/testsudoers.c
blob: 4e727539830f6bcf457a1362bb507ed5ce59f77f (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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
/*
 * SPDX-License-Identifier: ISC
 *
 * Copyright (c) 1996, 1998-2005, 2007-2022
 *	Todd C. Miller <Todd.Miller@sudo.ws>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 * Sponsored in part by the Defense Advanced Research Projects
 * Agency (DARPA) and Air Force Research Laboratory, Air Force
 * Materiel Command, USAF, under agreement number F39502-99-1-0512.
 */

/*
 * This is an open source non-commercial project. Dear PVS-Studio, please check it.
 * PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
 */

#include <config.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef HAVE_STRINGS_H
# include <strings.h>
#endif /* HAVE_STRINGS_H */
#include <unistd.h>
#include <errno.h>

#include "tsgetgrpw.h"
#include "sudoers.h"
#include "interfaces.h"
#include "sudo_conf.h"
#include "sudo_lbuf.h"
#include <gram.h>

#ifndef YYDEBUG
# define YYDEBUG 0
#endif

enum sudoers_formats {
    format_ldif,
    format_sudoers
};

/*
 * Function Prototypes
 */
static void dump_sudoers(struct sudo_lbuf *lbuf);
static void set_runaspw(const char *);
static void set_runasgr(const char *);
static bool cb_runas_default(const char *file, int line, int column, const union sudo_defs_val *, int);
static int testsudoers_error(const char *msg);
static int testsudoers_output(const char *buf);
sudo_noreturn static void usage(void);

/* testsudoers_pwutil.c */
extern struct cache_item *testsudoers_make_gritem(gid_t gid, const char *group);
extern struct cache_item *testsudoers_make_grlist_item(const struct passwd *pw, char * const *groups);
extern struct cache_item *testsudoers_make_gidlist_item(const struct passwd *pw, char * const *gids, unsigned int type);
extern struct cache_item *testsudoers_make_pwitem(uid_t uid, const char *user);

/* gram.y */
extern int (*trace_print)(const char *msg);

/*
 * Globals
 */
struct sudo_user sudo_user;
struct passwd *list_pw;
static const char *orig_cmnd;
static char *runas_group, *runas_user;

#if defined(SUDO_DEVEL) && defined(__OpenBSD__)
extern char *malloc_options;
#endif
#if YYDEBUG
extern int sudoersdebug;
#endif

sudo_dso_public int main(int argc, char *argv[]);

int
main(int argc, char *argv[])
{
    enum sudoers_formats input_format = format_sudoers;
    struct cmndspec *cs;
    struct privilege *priv;
    struct userspec *us;
    char *p, *grfile, *pwfile;
    const char *errstr;
    int match, host_match, runas_match, cmnd_match;
    int ch, dflag, exitcode = EXIT_FAILURE;
    struct sudo_lbuf lbuf;
    debug_decl(main, SUDOERS_DEBUG_MAIN);

#if defined(SUDO_DEVEL) && defined(__OpenBSD__)
    malloc_options = "S";
#endif
#if YYDEBUG
    sudoersdebug = 1;
#endif

    initprogname(argc > 0 ? argv[0] : "testsudoers");

    if (!sudoers_initlocale(setlocale(LC_ALL, ""), def_sudoers_locale))
	sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
    sudo_warn_set_locale_func(sudoers_warn_setlocale);
    bindtextdomain("sudoers", LOCALEDIR); /* XXX - should have own domain */
    textdomain("sudoers");

    /* No word wrap on output. */
    sudo_lbuf_init(&lbuf, testsudoers_output, 0, NULL, 0);

    /* Initialize the debug subsystem. */
    if (sudo_conf_read(NULL, SUDO_CONF_DEBUG) == -1)
	goto done;
    if (!sudoers_debug_register(getprogname(), sudo_conf_debug_files(getprogname())))
	goto done;

    dflag = 0;
    grfile = pwfile = NULL;
    while ((ch = getopt(argc, argv, "+dg:G:h:i:P:p:tu:U:")) != -1) {
	switch (ch) {
	    case 'd':
		dflag = 1;
		break;
	    case 'G':
		sudoers_gid = (gid_t)sudo_strtoid(optarg, &errstr);
		if (errstr != NULL)
		    sudo_fatalx("group-ID %s: %s", optarg, errstr);
		break;
	    case 'g':
		runas_group = optarg;
		SET(sudo_user.flags, RUNAS_GROUP_SPECIFIED);
		break;
	    case 'h':
		user_host = optarg;
		break;
	    case 'i':
		if (strcasecmp(optarg, "ldif") == 0) {
		    input_format = format_ldif;
		} else if (strcasecmp(optarg, "sudoers") == 0) {
		    input_format = format_sudoers;
		} else {
		    sudo_warnx(U_("unsupported input format %s"), optarg);
		    usage();
		}
		break;
	    case 'p':
		pwfile = optarg;
		break;
	    case 'P':
		grfile = optarg;
		break;
	    case 't':
		trace_print = testsudoers_error;
		break;
	    case 'U':
		sudoers_uid = (uid_t)sudo_strtoid(optarg, &errstr);
		if (errstr != NULL)
		    sudo_fatalx("user-ID %s: %s", optarg, errstr);
		break;
	    case 'u':
		runas_user = optarg;
		SET(sudo_user.flags, RUNAS_USER_SPECIFIED);
		break;
	    default:
		usage();
		break;
	}
    }
    argc -= optind;
    argv += optind;

    if (grfile != NULL || pwfile != NULL) {
	/* Set group/passwd file and init the cache. */
	if (grfile)
	    testsudoers_setgrfile(grfile);
	if (pwfile)
	    testsudoers_setpwfile(pwfile);

	/* Use custom passwd/group backend. */
	sudo_pwutil_set_backend(testsudoers_make_pwitem,
	    testsudoers_make_gritem, testsudoers_make_gidlist_item,
	    testsudoers_make_grlist_item);
    }

    if (argc < 2) {
	if (!dflag)
	    usage();
	user_name = argc ? *argv++ : (char *)"root";
	orig_cmnd = "true";
	argc = 0;
    } else {
	user_name = *argv++;
	orig_cmnd = *argv++;
	argc -= 2;
    }
    user_cmnd = strdup(orig_cmnd);
    if (user_cmnd == NULL)
	sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
    user_base = sudo_basename(user_cmnd);

    if ((sudo_user.pw = sudo_getpwnam(user_name)) == NULL)
	sudo_fatalx(U_("unknown user %s"), user_name);

    if (user_host == NULL) {
	if ((user_host = sudo_gethostname()) == NULL)
	    sudo_fatal("gethostname");
    }
    if ((p = strchr(user_host, '.'))) {
	*p = '\0';
	if ((user_shost = strdup(user_host)) == NULL)
	    sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
	*p = '.';
    } else {
	user_shost = user_host;
    }
    user_runhost = user_host;
    user_srunhost = user_shost;

    /* Fill in user_args from argv. */
    if (argc > 0) {
	char *to, **from;
	size_t size, n;

	for (size = 0, from = argv; *from; from++)
	    size += strlen(*from) + 1;

	if ((user_args = malloc(size)) == NULL)
	    sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
	for (to = user_args, from = argv; *from; from++) {
	    n = strlcpy(to, *from, size - (to - user_args));
	    if (n >= size - (to - user_args))
		sudo_fatalx(U_("internal error, %s overflow"), getprogname());
	    to += n;
	    *to++ = ' ';
	}
	*--to = '\0';
    }

    /* Initialize default values. */
    if (!init_defaults())
	sudo_fatalx("%s", U_("unable to initialize sudoers default values"));

    /* Set group_plugin callback. */
    sudo_defs_table[I_GROUP_PLUGIN].callback = cb_group_plugin;

    /* Set runas callback. */
    sudo_defs_table[I_RUNAS_DEFAULT].callback = cb_runas_default;

    /* Set locale callback. */
    sudo_defs_table[I_SUDOERS_LOCALE].callback = sudoers_locale_callback;

    /* Load ip addr/mask for each interface. */
    if (get_net_ifs(&p) > 0) {
	if (!set_interfaces(p))
	    sudo_fatal("%s", U_("unable to parse network address list"));
    }

    /* Initialize the parser and set sudoers filename to "sudoers". */
    init_parser("sudoers", NULL, true, 2);

    /*
     * Set runas passwd/group entries based on command line or sudoers.
     * Note that if runas_group was specified without runas_user we
     * run the command as the invoking user.
     */
    if (runas_group != NULL) {
        set_runasgr(runas_group);
        set_runaspw(runas_user ? runas_user : user_name);
    } else
        set_runaspw(runas_user ? runas_user : def_runas_default);

    /* Parse the policy file. */
    sudoers_setlocale(SUDOERS_LOCALE_SUDOERS, NULL);
    switch (input_format) {
    case format_ldif:
        if (!sudoers_parse_ldif(&parsed_policy, stdin, NULL, true)) {
	    (void) puts("Parse error in LDIF");
	    parse_error = true;
	}
        break;
    case format_sudoers:
	if (sudoersparse() != 0)
	    parse_error = true;
        break;
    default:
        sudo_fatalx("error: unhandled input %d", input_format);
    }
    if (!update_defaults(&parsed_policy, NULL, SETDEF_ALL, false))
	parse_error = true;

    if (!parse_error)
	(void) puts("Parses OK");

    if (dflag) {
	(void) putchar('\n');
	dump_sudoers(&lbuf);
	if (argc < 2) {
	    exitcode = parse_error ? 1 : 0;
	    goto done;
	}
    }

    /* This loop must match the one in sudo_file_lookup() */
    printf("\nEntries for user %s:\n", user_name);
    match = UNSPEC;
    TAILQ_FOREACH_REVERSE(us, &parsed_policy.userspecs, userspec_list, entries) {
	if (userlist_matches(&parsed_policy, sudo_user.pw, &us->users) != ALLOW)
	    continue;
	TAILQ_FOREACH_REVERSE(priv, &us->privileges, privilege_list, entries) {
	    sudo_lbuf_append(&lbuf, "\n");
	    sudoers_format_privilege(&lbuf, &parsed_policy, priv, false);
	    sudo_lbuf_print(&lbuf);
	    host_match = hostlist_matches(&parsed_policy, sudo_user.pw,
		&priv->hostlist);
	    if (host_match == ALLOW) {
		puts("\thost  matched");
		TAILQ_FOREACH_REVERSE(cs, &priv->cmndlist, cmndspec_list, entries) {
		    runas_match = runaslist_matches(&parsed_policy,
			cs->runasuserlist, cs->runasgrouplist, NULL, NULL);
		    if (runas_match == ALLOW) {
			puts("\trunas matched");
			cmnd_match = cmnd_matches(&parsed_policy, cs->cmnd,
			    cs->runchroot, NULL);
			if (cmnd_match != UNSPEC)
			    match = cmnd_match;
			printf("\tcmnd  %s\n", match == ALLOW ? "allowed" :
			    match == DENY ? "denied" : "unmatched");
		    }
		}
	    } else
		puts(U_("\thost  unmatched"));
	}
    }
    puts(match == ALLOW ? U_("\nCommand allowed") :
	match == DENY ?  U_("\nCommand denied") :  U_("\nCommand unmatched"));

    /*
     * Exit codes:
     *	0 - parsed OK and command matched.
     *	1 - parse error
     *	2 - command not matched
     *	3 - command denied
     */
    exitcode = parse_error ? 1 : (match == ALLOW ? 0 : match + 3);
done:
    sudo_lbuf_destroy(&lbuf);
    sudo_freepwcache();
    sudo_freegrcache();
    sudo_debug_exit_int(__func__, __FILE__, __LINE__, sudo_debug_subsys, exitcode);
    exit(exitcode);
}

static void
set_runaspw(const char *user)
{
    struct passwd *pw = NULL;
    debug_decl(set_runaspw, SUDOERS_DEBUG_UTIL);

    if (*user == '#') {
	const char *errstr;
	uid_t uid = sudo_strtoid(user + 1, &errstr);
	if (errstr == NULL) {
	    if ((pw = sudo_getpwuid(uid)) == NULL)
		pw = sudo_fakepwnam(user, user_gid);
	}
    }
    if (pw == NULL) {
	if ((pw = sudo_getpwnam(user)) == NULL)
	    sudo_fatalx(U_("unknown user %s"), user);
    }
    if (runas_pw != NULL)
	sudo_pw_delref(runas_pw);
    runas_pw = pw;
    debug_return;
}

static void
set_runasgr(const char *group)
{
    struct group *gr = NULL;
    debug_decl(set_runasgr, SUDOERS_DEBUG_UTIL);

    if (*group == '#') {
	const char *errstr;
	gid_t gid = sudo_strtoid(group + 1, &errstr);
	if (errstr == NULL) {
	    if ((gr = sudo_getgrgid(gid)) == NULL)
		gr = sudo_fakegrnam(group);
	}
    }
    if (gr == NULL) {
	if ((gr = sudo_getgrnam(group)) == NULL)
	    sudo_fatalx(U_("unknown group %s"), group);
    }
    if (runas_gr != NULL)
	sudo_gr_delref(runas_gr);
    runas_gr = gr;
    debug_return;
}

/* 
 * Callback for runas_default sudoers setting.
 */
static bool
cb_runas_default(const char *file, int line, int column,
    const union sudo_defs_val *sd_un, int op)
{
    /* Only reset runaspw if user didn't specify one. */
    if (!runas_user && !runas_group)
        set_runaspw(sd_un->str);
    return true;
}

void
sudo_setspent(void)
{
    return;
}

void
sudo_endspent(void)
{
    return;
}

FILE *
open_sudoers(const char *file, char **outfile, bool doedit, bool *keepopen)
{
    struct stat sb;
    FILE *fp = NULL;
    const char *base;
    int error, fd;
    debug_decl(open_sudoers, SUDOERS_DEBUG_UTIL);

    /* Report errors using the basename for consistent test output. */
    base = sudo_basename(file);
    fd = sudo_secure_open_file(file, sudoers_uid, sudoers_gid, &sb, &error);
    if (fd != -1) {
	if ((fp = fdopen(fd, "r")) == NULL) {
	    sudo_warn("unable to open %s", base);
	    close(fd);
	}
    } else {
	switch (error) {
	case SUDO_PATH_MISSING:
	    sudo_warn("unable to open %s", base);
	    break;
	case SUDO_PATH_BAD_TYPE:
	    sudo_warnx("%s is not a regular file", base);
	    break;
	case SUDO_PATH_WRONG_OWNER:
	    sudo_warnx("%s should be owned by uid %u",
		base, (unsigned int) sudoers_uid);
	    break;
	case SUDO_PATH_WORLD_WRITABLE:
	    sudo_warnx("%s is world writable", base);
	    break;
	case SUDO_PATH_GROUP_WRITABLE:
	    sudo_warnx("%s should be owned by gid %u",
		base, (unsigned int) sudoers_gid);
	    break;
	default:
	    sudo_warnx("%s: internal error, unexpected error %d",
		__func__, error);
	    break;
	}
    }

    debug_return_ptr(fp);
}

bool
init_envtables(void)
{
    return(true);
}

bool
set_perms(int perm)
{
    return true;
}

bool
restore_perms(void)
{
    return true;
}

void
init_eventlog_config(void)
{
    return;
}

bool
pivot_root(const char *new_root, int fds[2])
{
    return true;
}

bool
unpivot_root(int fds[2])
{
    return true;
}

int
set_cmnd_path(const char *runchroot)
{
    /* Reallocate user_cmnd to catch bugs in command_matches(). */
    char *new_cmnd = strdup(orig_cmnd);
    if (new_cmnd == NULL)
	return NOT_FOUND_ERROR;
    free(user_cmnd);
    user_cmnd = new_cmnd;
    return FOUND;
}

static bool
print_defaults(struct sudo_lbuf *lbuf)
{
    struct defaults *def, *next;
    debug_decl(print_defaults, SUDOERS_DEBUG_UTIL);

    TAILQ_FOREACH_SAFE(def, &parsed_policy.defaults, entries, next)
	sudoers_format_default_line(lbuf, &parsed_policy, def, &next, false);

    debug_return_bool(!sudo_lbuf_error(lbuf));
}

static int
print_alias(struct sudoers_parse_tree *parse_tree, struct alias *a, void *v)
{
    struct sudo_lbuf *lbuf = v;
    struct member *m;
    debug_decl(print_alias, SUDOERS_DEBUG_UTIL);

    sudo_lbuf_append(lbuf, "%s %s = ", alias_type_to_string(a->type),
	a->name);
    TAILQ_FOREACH(m, &a->members, entries) {
	if (m != TAILQ_FIRST(&a->members))
	    sudo_lbuf_append(lbuf, ", ");
	sudoers_format_member(lbuf, parse_tree, m, NULL, UNSPEC);
    }
    sudo_lbuf_append(lbuf, "\n");

    debug_return_int(sudo_lbuf_error(lbuf) ? -1 : 0);
}

static bool
print_aliases(struct sudo_lbuf *lbuf)
{
    debug_decl(print_aliases, SUDOERS_DEBUG_UTIL);

    alias_apply(&parsed_policy, print_alias, lbuf);

    debug_return_bool(!sudo_lbuf_error(lbuf));
}

static void
dump_sudoers(struct sudo_lbuf *lbuf)
{
    debug_decl(dump_sudoers, SUDOERS_DEBUG_UTIL);

    /* Print Defaults */
    if (!print_defaults(lbuf))
	goto done;
    if (lbuf->len > 0) {
	sudo_lbuf_print(lbuf);
	sudo_lbuf_append(lbuf, "\n");
    }

    /* Print Aliases */
    if (!print_aliases(lbuf))
	goto done;
    if (lbuf->len > 1) {
	sudo_lbuf_print(lbuf);
	sudo_lbuf_append(lbuf, "\n");
    }

    /* Print User_Specs */
    if (!sudoers_format_userspecs(lbuf, &parsed_policy, NULL, false, true))
	goto done;
    if (lbuf->len > 1) {
	sudo_lbuf_print(lbuf);
    }

done:
    if (sudo_lbuf_error(lbuf)) {
	if (errno == ENOMEM)
	    sudo_fatalx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
    }

    debug_return;
}

static int
testsudoers_output(const char *buf)
{
    return fputs(buf, stdout);
}

static int
testsudoers_error(const char *buf)
{
    return fputs(buf, stderr);
}

static void
usage(void)
{
    (void) fprintf(stderr, "usage: %s [-dt] [-G sudoers_gid] [-g group] [-h host] [-i input_format] [-P grfile] [-p pwfile] [-U sudoers_uid] [-u user] <user> <command> [args]\n", getprogname());
    exit(EXIT_FAILURE);
}