Coverage Report

Created: 2026-01-17 06:06

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/sudo/plugins/sudoers/sudoers.c
Line
Count
Source
1
/*
2
 * SPDX-License-Identifier: ISC
3
 *
4
 * Copyright (c) 1993-1996, 1998-2023 Todd C. Miller <Todd.Miller@sudo.ws>
5
 *
6
 * Permission to use, copy, modify, and distribute this software for any
7
 * purpose with or without fee is hereby granted, provided that the above
8
 * copyright notice and this permission notice appear in all copies.
9
 *
10
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
 *
18
 * Sponsored in part by the Defense Advanced Research Projects
19
 * Agency (DARPA) and Air Force Research Laboratory, Air Force
20
 * Materiel Command, USAF, under agreement number F39502-99-1-0512.
21
 */
22
23
#ifdef __TANDEM
24
# include <floss.h>
25
#endif
26
27
#include <config.h>
28
29
#include <sys/types.h>
30
#include <sys/resource.h>
31
#include <sys/stat.h>
32
#include <sys/socket.h>
33
#include <stdio.h>
34
#include <stdlib.h>
35
#include <string.h>
36
#include <unistd.h>
37
#include <pwd.h>
38
#include <errno.h>
39
#include <fcntl.h>
40
#include <grp.h>
41
#include <netdb.h>
42
#ifdef HAVE_LOGIN_CAP_H
43
# include <login_cap.h>
44
# ifndef LOGIN_DEFROOTCLASS
45
#  define LOGIN_DEFROOTCLASS  "daemon"
46
# endif
47
# ifndef LOGIN_SETENV
48
#  define LOGIN_SETENV  0
49
# endif
50
#endif
51
#ifdef HAVE_SELINUX
52
# include <selinux/selinux.h>
53
#endif
54
#include <ctype.h>
55
#ifndef HAVE_GETADDRINFO
56
# include <compat/getaddrinfo.h>
57
#endif
58
59
#include <sudoers.h>
60
#include <timestamp.h>
61
#include <sudo_iolog.h>
62
63
/*
64
 * Prototypes
65
 */
66
static int set_cmnd(struct sudoers_context *ctx);
67
static bool init_vars(struct sudoers_context *ctx, char * const *);
68
static bool set_loginclass(struct sudoers_context *);
69
static bool set_runaspw(struct sudoers_context *ctx, const char *, bool);
70
static bool set_runasgr(struct sudoers_context *ctx, const char *, bool);
71
72
/*
73
 * Globals
74
 */
75
static char *prev_user;
76
static struct sudoers_context sudoers_ctx = SUDOERS_CONTEXT_INITIALIZER;
77
static struct sudo_nss_list *snl;
78
static bool unknown_runas_uid;
79
static bool unknown_runas_gid;
80
static int cmnd_status = NOT_FOUND_ERROR;
81
static struct defaults_list initial_defaults = TAILQ_HEAD_INITIALIZER(initial_defaults);
82
83
#ifdef __linux__
84
static struct rlimit nproclimit;
85
#endif
86
87
#ifdef SUDOERS_LOG_CLIENT
88
5.35k
# define remote_iologs  (!SLIST_EMPTY(&def_log_servers))
89
#else
90
# define remote_iologs  0
91
#endif
92
93
/*
94
 * Unlimit the number of processes since Linux's setuid() will
95
 * apply resource limits when changing uid and return EAGAIN if
96
 * nproc would be exceeded by the uid switch.
97
 */
98
static void
99
unlimit_nproc(void)
100
26.3k
{
101
26.3k
#ifdef __linux__
102
26.3k
    struct rlimit rl;
103
26.3k
    debug_decl(unlimit_nproc, SUDOERS_DEBUG_UTIL);
104
105
26.3k
    if (getrlimit(RLIMIT_NPROC, &nproclimit) != 0)
106
0
      sudo_warn("getrlimit(RLIMIT_NPROC)");
107
26.3k
    rl.rlim_cur = rl.rlim_max = RLIM_INFINITY;
108
26.3k
    if (setrlimit(RLIMIT_NPROC, &rl) != 0) {
109
0
  rl.rlim_cur = rl.rlim_max = nproclimit.rlim_max;
110
0
  if (setrlimit(RLIMIT_NPROC, &rl) != 0)
111
0
      sudo_warn("setrlimit(RLIMIT_NPROC)");
112
0
    }
113
26.3k
    debug_return;
114
26.3k
#endif /* __linux__ */
115
26.3k
}
116
117
/*
118
 * Restore saved value of RLIMIT_NPROC.
119
 */
120
static void
121
restore_nproc(void)
122
26.3k
{
123
26.3k
#ifdef __linux__
124
26.3k
    debug_decl(restore_nproc, SUDOERS_DEBUG_UTIL);
125
126
26.3k
    if (setrlimit(RLIMIT_NPROC, &nproclimit) != 0)
127
0
  sudo_warn("setrlimit(RLIMIT_NPROC)");
128
129
26.3k
    debug_return;
130
26.3k
#endif /* __linux__ */
131
26.3k
}
132
133
/*
134
 * Re-initialize Defaults settings.
135
 * We do not warn, log or send mail for errors when reinitializing,
136
 * this would have already been done the first time through.
137
 */
138
static bool
139
sudoers_reinit_defaults(struct sudoers_context *ctx)
140
5.65k
{
141
5.65k
    struct sudo_nss *nss, *nss_next;
142
5.65k
    sudoers_logger_t logger = sudoers_error_hook;
143
5.65k
    debug_decl(sudoers_reinit_defaults, SUDOERS_DEBUG_PLUGIN);
144
145
5.65k
    if (!init_defaults()) {
146
0
  sudo_warnx("%s", U_("unable to initialize sudoers default values"));
147
0
  debug_return_bool(false);
148
0
    }
149
150
    /* It should not be possible for the initial defaults to fail to apply. */
151
5.65k
    if (!update_defaults(ctx, NULL, &initial_defaults,
152
5.65k
      SETDEF_GENERIC|SETDEF_HOST|SETDEF_USER|SETDEF_RUNAS, false))
153
0
  debug_return_bool(false);
154
155
    /* Disable error logging while re-processing defaults. */
156
5.65k
    sudoers_error_hook = NULL;
157
158
5.65k
    TAILQ_FOREACH_SAFE(nss, snl, entries, nss_next) {
159
  /* Missing/invalid defaults is not a fatal error. */
160
5.65k
  if (nss->getdefs(ctx, nss) != -1) {
161
5.65k
      (void)update_defaults(ctx, nss->parse_tree, NULL,
162
5.65k
    SETDEF_GENERIC|SETDEF_HOST|SETDEF_USER|SETDEF_RUNAS, true);
163
5.65k
  }
164
5.65k
    }
165
166
    /* Restore error logging. */
167
5.65k
    sudoers_error_hook = logger;
168
169
    /* No need to check the admin flag file multiple times. */
170
5.65k
    if (ISSET(ctx->mode, MODE_POLICY_INTERCEPTED)) {
171
0
  free(def_admin_flag);
172
0
  def_admin_flag = NULL;
173
0
    }
174
175
5.65k
    debug_return_bool(true);
176
5.65k
}
177
178
static bool sudoers_initialized;
179
180
/*
181
 * Initialize sudoers data structures and parse sudoers sources.
182
 * Returns 1 on success and -1 on error.
183
 */
184
int
185
sudoers_init(void *info, sudoers_logger_t logger, char * const envp[])
186
24.5k
{
187
24.5k
    struct sudo_nss *nss, *nss_next;
188
24.5k
    int oldlocale, sources = 0;
189
24.5k
    static int ret;
190
24.5k
    debug_decl(sudoers_init, SUDOERS_DEBUG_PLUGIN);
191
192
    /* Only attempt to initialize once. */
193
24.5k
    if (sudoers_initialized)
194
0
  debug_return_int(ret);
195
24.5k
    sudoers_initialized = true;
196
24.5k
    ret = -1;
197
198
24.5k
    bindtextdomain("sudoers", LOCALEDIR);
199
200
    /* Hook up logging function for parse errors. */
201
24.5k
    sudoers_error_hook = logger;
202
203
    /* Register fatal/fatalx callback. */
204
24.5k
    sudo_fatal_callback_register(sudoers_cleanup);
205
206
    /* Initialize environment functions (including replacements). */
207
24.5k
    if (!env_init(envp))
208
0
  debug_return_int(-1);
209
210
    /* Setup defaults data structures. */
211
24.5k
    if (!init_defaults()) {
212
0
  sudo_warnx("%s", U_("unable to initialize sudoers default values"));
213
0
  debug_return_int(-1);
214
0
    }
215
216
    /* Parse info from front-end. */
217
24.5k
    sudoers_ctx.mode = sudoers_policy_deserialize_info(&sudoers_ctx, info,
218
24.5k
  &initial_defaults);
219
24.5k
    if (ISSET(sudoers_ctx.mode, MODE_ERROR))
220
5.13k
  debug_return_int(-1);
221
222
19.4k
    if (!init_vars(&sudoers_ctx, envp))
223
258
  debug_return_int(-1);
224
225
    /* Parse nsswitch.conf for sudoers order. */
226
19.1k
    snl = sudo_read_nss();
227
228
    /* LDAP or NSS may modify the euid so we need to be root for the open. */
229
19.1k
    if (!set_perms(NULL, PERM_ROOT))
230
0
  debug_return_int(-1);
231
232
    /* Use the C locale unless another is specified in sudoers. */
233
19.1k
    sudoers_setlocale(SUDOERS_LOCALE_SUDOERS, &oldlocale);
234
19.1k
    sudo_warn_set_locale_func(sudoers_warn_setlocale);
235
236
    /* Update defaults set by front-end. */
237
19.1k
    if (!update_defaults(&sudoers_ctx, NULL, &initial_defaults,
238
19.1k
      SETDEF_GENERIC|SETDEF_HOST|SETDEF_USER|SETDEF_RUNAS, false)) {
239
0
  goto cleanup;
240
0
    }
241
242
    /* Open and parse sudoers, set global defaults.  */
243
19.1k
    TAILQ_FOREACH_SAFE(nss, snl, entries, nss_next) {
244
19.1k
  if (nss->open(&sudoers_ctx, nss) == -1 || (nss->parse_tree = nss->parse(&sudoers_ctx, nss)) == NULL) {
245
0
      TAILQ_REMOVE(snl, nss, entries);
246
0
      continue;
247
0
  }
248
19.1k
  sources++;
249
250
  /* Missing/invalid defaults is not a fatal error. */
251
19.1k
  if (nss->getdefs(&sudoers_ctx, nss) == -1) {
252
0
      log_warningx(&sudoers_ctx, SLOG_PARSE_ERROR|SLOG_NO_STDERR,
253
0
    N_("unable to get defaults from %s"), nss->source);
254
19.1k
  } else {
255
19.1k
      (void)update_defaults(&sudoers_ctx, nss->parse_tree, NULL,
256
19.1k
    SETDEF_GENERIC|SETDEF_HOST|SETDEF_USER|SETDEF_RUNAS, false);
257
19.1k
  }
258
19.1k
    }
259
19.1k
    if (sources == 0) {
260
  /* Display an extra warning if there are multiple sudoers sources. */
261
0
  if (TAILQ_FIRST(snl) != TAILQ_LAST(snl, sudo_nss_list))
262
0
      sudo_warnx("%s", U_("no valid sudoers sources found, quitting"));
263
0
  goto cleanup;
264
0
    }
265
266
    /* Set login class if applicable (after sudoers is parsed). */
267
19.1k
    if (set_loginclass(&sudoers_ctx))
268
19.1k
  ret = true;
269
270
19.1k
cleanup:
271
19.1k
    mail_parse_errors(&sudoers_ctx);
272
273
19.1k
    if (!restore_perms())
274
0
  ret = -1;
275
276
    /* Restore user's locale. */
277
19.1k
    sudo_warn_set_locale_func(NULL);
278
19.1k
    sudoers_setlocale(oldlocale, NULL);
279
280
19.1k
    debug_return_int(ret);
281
19.1k
}
282
283
/*
284
 * Expand I/O log dir and file into a full path.
285
 * Returns the full I/O log path prefixed with "iolog_path=".
286
 * Sets ctx->iolog_file and ctx->iolog_path as a side effect.
287
 */
288
static char *
289
format_iolog_path(struct sudoers_context *ctx)
290
2.55k
{
291
2.55k
    char dir[PATH_MAX], file[PATH_MAX];
292
2.55k
    char *iolog_path = NULL;
293
2.55k
    int oldlocale;
294
2.55k
    bool ok;
295
2.55k
    debug_decl(format_iolog_path, SUDOERS_DEBUG_PLUGIN);
296
297
    /* Use sudoers locale for strftime() */
298
2.55k
    sudoers_setlocale(SUDOERS_LOCALE_SUDOERS, &oldlocale);
299
2.55k
    ok = expand_iolog_path(def_iolog_dir, dir, sizeof(dir),
300
2.55k
  &sudoers_iolog_path_escapes[1], ctx);
301
2.55k
    if (ok) {
302
2.55k
  ctx->iolog_dir = dir;
303
2.55k
  ok = expand_iolog_path(def_iolog_file, file, sizeof(file),
304
2.55k
      &sudoers_iolog_path_escapes[0], ctx);
305
2.55k
  ctx->iolog_dir = NULL;
306
2.55k
    }
307
2.55k
    sudoers_setlocale(oldlocale, NULL);
308
2.55k
    if (!ok)
309
0
  goto done;
310
311
2.55k
    if (asprintf(&iolog_path, "iolog_path=%s/%s", dir, file) == -1) {
312
0
  iolog_path = NULL;
313
0
  goto done;
314
0
    }
315
316
    /* Stash pointer to the I/O log for the event log. */
317
2.55k
    ctx->iolog_path = iolog_path + sizeof("iolog_path=") - 1;
318
2.55k
    ctx->iolog_file = ctx->iolog_path + 1 + strlen(dir);
319
320
2.55k
done:
321
2.55k
    debug_return_str(iolog_path);
322
2.55k
}
323
324
static void
325
cb_lookup(const struct sudoers_parse_tree *parse_tree,
326
    const struct userspec *us, int user_match, const struct privilege *priv,
327
    int host_match, const struct cmndspec *cs, int date_match, int runas_match,
328
    int cmnd_match, void *closure)
329
0
{
330
0
    struct sudoers_match_info *info = closure;
331
332
0
    if (cmnd_match != UNSPEC) {
333
0
  info->us = us;
334
0
  info->priv = priv;
335
0
  info->cs = cs;
336
0
    }
337
0
}
338
339
/*
340
 * Find the command, perform a sudoers lookup, ask for a password as
341
 * needed, and perform post-lookup checks.  Logs success/failure.
342
 * This is used by the check, list and validate plugin methods.
343
 *
344
 * Returns true if allowed, false if denied, -1 on error and
345
 * -2 for usage error.
346
 */
347
static int
348
sudoers_check_common(struct sudoers_context *ctx, int pwflag)
349
26.3k
{
350
26.3k
    struct sudoers_match_info match_info = { NULL };
351
26.3k
    int oldlocale, ret = -1;
352
26.3k
    unsigned int validated;
353
26.3k
    time_t now;
354
26.3k
    debug_decl(sudoers_check_common, SUDOERS_DEBUG_PLUGIN);
355
356
    /* The user may only specify a host for "sudo -l". */
357
26.3k
    if (!ISSET(ctx->mode, MODE_LIST|MODE_CHECK)) {
358
16.5k
  if (strcmp(ctx->runas.host, ctx->user.host) != 0) {
359
0
      log_warningx(ctx, SLOG_NO_STDERR|SLOG_AUDIT,
360
0
    N_("user not allowed to set remote host for command"));
361
0
      sudo_warnx("%s",
362
0
    U_("a remote host may only be specified when listing privileges."));
363
0
      ret = false;
364
0
      goto done;
365
0
  }
366
16.5k
    }
367
368
    /* If given the -P option, set the "preserve_groups" flag. */
369
26.3k
    if (ISSET(ctx->mode, MODE_PRESERVE_GROUPS))
370
60
  def_preserve_groups = true;
371
372
    /* Find command in path and apply per-command Defaults. */
373
26.3k
    cmnd_status = set_cmnd(ctx);
374
26.3k
    if (cmnd_status == NOT_FOUND_ERROR)
375
0
  goto done;
376
377
    /* Is root even allowed to run sudo? */
378
26.3k
    if (ctx->user.uid == 0 && !def_root_sudo) {
379
  /* Not an audit event (should it be?). */
380
0
  sudo_warnx("%s",
381
0
      U_("sudoers specifies that root is not allowed to sudo"));
382
0
  ret = false;
383
0
  goto done;
384
0
    }
385
386
    /* Check for -C overriding def_closefrom. */
387
26.3k
    if (ctx->user.closefrom >= 0 && ctx->user.closefrom != def_closefrom) {
388
1.19k
  if (!def_closefrom_override) {
389
1.19k
      log_warningx(ctx, SLOG_NO_STDERR|SLOG_AUDIT,
390
1.19k
    N_("user not allowed to override closefrom limit"));
391
1.19k
      sudo_warnx("%s", U_("you are not permitted to use the -C option"));
392
1.19k
      goto bad;
393
1.19k
  }
394
0
  def_closefrom = ctx->user.closefrom;
395
0
    }
396
397
    /*
398
     * Check sudoers sources, using the locale specified in sudoers.
399
     */
400
25.1k
    time(&now);
401
25.1k
    sudoers_setlocale(SUDOERS_LOCALE_SUDOERS, &oldlocale);
402
25.1k
    validated = sudoers_lookup(snl, ctx, now, cb_lookup, &match_info,
403
25.1k
  &cmnd_status, pwflag);
404
25.1k
    sudoers_setlocale(oldlocale, NULL);
405
25.1k
    if (ISSET(validated, VALIDATE_ERROR)) {
406
  /* The lookup function should have printed an error. */
407
0
  goto done;
408
0
    }
409
410
25.1k
    if (match_info.us != NULL && match_info.us->file != NULL) {
411
0
  free(ctx->source);
412
0
  if (match_info.us->line != 0) {
413
0
      if (asprintf(&ctx->source, "%s:%d:%d", match_info.us->file,
414
0
        match_info.us->line, match_info.us->column) == -1)
415
0
    ctx->source = NULL;
416
0
  } else {
417
0
      ctx->source = strdup(match_info.us->file);
418
0
  }
419
0
  if (ctx->source == NULL) {
420
0
      sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
421
0
      goto done;
422
0
  }
423
0
    }
424
425
25.1k
    if (ctx->runas.cmnd == NULL) {
426
25.1k
  if ((ctx->runas.cmnd = strdup(ctx->user.cmnd)) == NULL) {
427
0
      sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
428
0
      goto done;
429
0
  }
430
25.1k
    }
431
432
    /* Defer uid/gid checks until after defaults have been updated. */
433
25.1k
    if (unknown_runas_uid && !def_runas_allow_unknown_id) {
434
82
  log_warningx(ctx, SLOG_AUDIT, N_("unknown user %s"),
435
82
      ctx->runas.pw->pw_name);
436
82
  goto done;
437
82
    }
438
25.0k
    if (ctx->runas.gr != NULL) {
439
284
  if (unknown_runas_gid && !def_runas_allow_unknown_id) {
440
37
      log_warningx(ctx, SLOG_AUDIT, N_("unknown group %s"),
441
37
    ctx->runas.gr->gr_name);
442
37
      goto done;
443
37
  }
444
284
    }
445
446
    /* If no command line args and "shell_noargs" is not set, error out. */
447
24.9k
    if (ISSET(ctx->mode, MODE_IMPLIED_SHELL) && !def_shell_noargs) {
448
  /* Not an audit event. */
449
35
  ret = -2; /* usage error */
450
35
  goto done;
451
35
    }
452
453
    /* Bail if a tty is required and we don't have one. */
454
24.9k
    if (def_requiretty && !sudoers_tty_present(ctx)) {
455
0
  log_warningx(ctx, SLOG_NO_STDERR|SLOG_AUDIT, N_("no tty"));
456
0
  sudo_warnx("%s", U_("sorry, you must have a tty to run sudo"));
457
0
  goto bad;
458
0
    }
459
460
    /* Check runas user's shell if running (or checking) a command. */
461
24.9k
    if (ISSET(ctx->mode, MODE_RUN|MODE_CHECK)) {
462
14.8k
  if (!user_shell_valid(ctx->runas.pw)) {
463
0
      log_warningx(ctx, SLOG_RAW_MSG|SLOG_AUDIT,
464
0
    N_("invalid shell for user %s: %s"),
465
0
    ctx->runas.pw->pw_name, ctx->runas.pw->pw_shell);
466
0
      goto bad;
467
0
  }
468
14.8k
    }
469
470
    /*
471
     * We don't reset the environment for sudoedit or if the user
472
     * specified the -E command line flag and they have setenv privs.
473
     */
474
24.9k
    if (ISSET(ctx->mode, MODE_EDIT) ||
475
24.0k
  (ISSET(ctx->mode, MODE_PRESERVE_ENV) && def_setenv))
476
880
  def_env_reset = false;
477
478
    /* Build a new environment that avoids any nasty bits. */
479
24.9k
    if (!rebuild_env(ctx))
480
0
  goto bad;
481
482
    /* Require a password if sudoers says so.  */
483
24.9k
    switch (check_user(ctx, validated, ctx->mode)) {
484
24.9k
    case AUTH_SUCCESS:
485
  /* user authenticated successfully. */
486
24.9k
  break;
487
0
    case AUTH_FAILURE:
488
  /* Note: log_denial() calls audit for us. */
489
0
  if (!ISSET(validated, VALIDATE_SUCCESS)) {
490
      /* Only display a denial message if no password was read. */
491
0
      if (!log_denial(ctx, validated, def_passwd_tries <= 0))
492
0
    goto done;
493
0
  }
494
0
  goto bad;
495
0
    default:
496
  /* some other error, ret is -1. */
497
0
  goto done;
498
24.9k
    }
499
500
    /* Check whether ctx->runas.chroot is permitted (if specified). */
501
24.9k
    switch (check_user_runchroot(ctx->runas.chroot)) {
502
24.9k
    case true:
503
24.9k
  break;
504
0
    case false:
505
0
  log_warningx(ctx, SLOG_NO_STDERR|SLOG_AUDIT,
506
0
      N_("user not allowed to change root directory to %s"),
507
0
      ctx->runas.chroot);
508
0
  sudo_warnx(U_("you are not permitted to use the -R option with %s"),
509
0
      ctx->user.cmnd);
510
0
  goto bad;
511
0
    default:
512
0
  goto done;
513
24.9k
    }
514
515
    /* Check whether ctx->runas.cwd is permitted (if specified). */
516
24.9k
    switch (check_user_runcwd(ctx->runas.cwd)) {
517
24.9k
    case true:
518
24.9k
  break;
519
0
    case false:
520
0
  log_warningx(ctx, SLOG_NO_STDERR|SLOG_AUDIT,
521
0
      N_("user not allowed to change directory to %s"), ctx->runas.cwd);
522
0
  sudo_warnx(U_("you are not permitted to use the -D option with %s"),
523
0
      ctx->user.cmnd);
524
0
  goto bad;
525
0
    default:
526
0
  goto done;
527
24.9k
    }
528
529
    /* If run as root with SUDO_USER set, set ctx->user.pw to that user. */
530
    /* XXX - causes confusion when root is not listed in sudoers */
531
24.9k
    if (ISSET(ctx->mode, MODE_RUN|MODE_EDIT) && prev_user != NULL) {
532
0
  if (ctx->user.uid == 0 && strcmp(prev_user, "root") != 0) {
533
0
      struct passwd *pw;
534
535
0
      if ((pw = sudo_getpwnam(prev_user)) != NULL) {
536
0
        if (ctx->user.pw != NULL)
537
0
      sudo_pw_delref(ctx->user.pw);
538
0
        ctx->user.pw = pw;
539
0
      }
540
0
  }
541
0
    }
542
543
    /* If the user was not allowed to run the command we are done. */
544
24.9k
    if (!ISSET(validated, VALIDATE_SUCCESS)) {
545
  /* Note: log_failure() calls audit for us. */
546
0
  if (!log_failure(ctx, validated, cmnd_status))
547
0
      goto done;
548
0
  goto bad;
549
0
    }
550
551
    /*
552
     * Check if the user is trying to run a setid binary in intercept mode.
553
     * For the DSO intercept_type, we reject attempts to run setid binaries
554
     * by default since the dynamic loader will clear LD_PRELOAD, defeating
555
     * intercept.
556
     */
557
24.9k
    if (def_intercept || ISSET(ctx->mode, MODE_POLICY_INTERCEPTED)) {
558
0
  if (!def_intercept_allow_setid && ctx->user.cmnd_stat != NULL) {
559
0
      if (ISSET(ctx->user.cmnd_stat->st_mode, S_ISUID|S_ISGID)) {
560
0
    CLR(validated, VALIDATE_SUCCESS);
561
0
    if (!log_denial(ctx, validated|FLAG_INTERCEPT_SETID, true))
562
0
        goto done;
563
0
    goto bad;
564
0
      }
565
0
  }
566
0
    }
567
568
    /* Create Ubuntu-style dot file to indicate sudo was successful. */
569
24.9k
    if (create_admin_success_flag(ctx) == -1)
570
0
  goto done;
571
572
    /* Finally tell the user if the command did not exist. */
573
24.9k
    if (cmnd_status == NOT_FOUND_DOT) {
574
3.42k
  audit_failure(ctx, ctx->runas.argv, N_("command in current directory"));
575
3.42k
  sudo_warnx(U_("ignoring \"%s\" found in '.'\nUse \"sudo ./%s\" if this is the \"%s\" you wish to run."), ctx->user.cmnd, ctx->user.cmnd, ctx->user.cmnd);
576
3.42k
  goto bad;
577
21.5k
    } else if (cmnd_status == NOT_FOUND) {
578
1.74k
  if (ISSET(ctx->mode, MODE_CHECK)) {
579
0
      audit_failure(ctx, ctx->runas.argv, N_("%s: command not found"),
580
0
    ctx->runas.argv[1]);
581
0
      sudo_warnx(U_("%s: command not found"), ctx->runas.argv[1]);
582
1.74k
  } else {
583
1.74k
      audit_failure(ctx, ctx->runas.argv, N_("%s: command not found"),
584
1.74k
    ctx->user.cmnd);
585
1.74k
      sudo_warnx(U_("%s: command not found"), ctx->user.cmnd);
586
1.74k
      if (strncmp(ctx->user.cmnd, "cd", 2) == 0 && (ctx->user.cmnd[2] == '\0' ||
587
0
        isblank((unsigned char)ctx->user.cmnd[2]))) {
588
0
    sudo_warnx("%s",
589
0
        U_("\"cd\" is a shell built-in command, it cannot be run directly."));
590
0
    sudo_warnx("%s",
591
0
        U_("the -s option may be used to run a privileged shell."));
592
0
    sudo_warnx("%s",
593
0
        U_("the -D option may be used to run a command in a specific directory."));
594
0
      }
595
1.74k
  }
596
1.74k
  goto bad;
597
1.74k
    }
598
599
    /* If user specified a timeout make sure sudoers allows it. */
600
19.8k
    if (!def_user_command_timeouts && ctx->user.timeout > 0) {
601
669
  log_warningx(ctx, SLOG_NO_STDERR|SLOG_AUDIT,
602
669
      N_("user not allowed to set a command timeout"));
603
669
  sudo_warnx("%s",
604
669
      U_("sorry, you are not allowed set a command timeout"));
605
669
  goto bad;
606
669
    }
607
608
    /* If user specified env vars make sure sudoers allows it. */
609
19.1k
    if (ISSET(ctx->mode, MODE_RUN) && !def_setenv) {
610
6.50k
  if (ISSET(ctx->mode, MODE_PRESERVE_ENV)) {
611
16
      log_warningx(ctx, SLOG_NO_STDERR|SLOG_AUDIT,
612
16
    N_("user not allowed to preserve the environment"));
613
16
      sudo_warnx("%s",
614
16
    U_("sorry, you are not allowed to preserve the environment"));
615
16
      goto bad;
616
6.48k
  } else {
617
6.48k
      if (!validate_env_vars(ctx, ctx->user.env_add))
618
1.86k
    goto bad;
619
6.48k
  }
620
6.50k
    }
621
622
17.2k
    ret = true;
623
17.2k
    goto done;
624
625
8.89k
bad:
626
8.89k
    ret = false;
627
26.3k
done:
628
26.3k
    debug_return_int(ret);
629
26.3k
}
630
631
static bool need_reinit;
632
633
/*
634
 * Check whether the user is allowed to run the specified command.
635
 * Returns true if allowed, false if denied, -1 on error and
636
 * -2 for usage error.
637
 */
638
int
639
sudoers_check_cmnd(int argc, char * const argv[], char *env_add[],
640
    void *closure)
641
13.2k
{
642
13.2k
    char *iolog_path = NULL;
643
13.2k
    mode_t cmnd_umask = ACCESSPERMS;
644
13.2k
    int ret = -1;
645
13.2k
    debug_decl(sudoers_check_cmnd, SUDOERS_DEBUG_PLUGIN);
646
647
13.2k
    sudo_warn_set_locale_func(sudoers_warn_setlocale);
648
649
13.2k
    if (argc == 0) {
650
0
  sudo_warnx("%s", U_("no command specified"));
651
0
  debug_return_int(-1);
652
0
    }
653
654
13.2k
    if (need_reinit) {
655
  /* Was previous command intercepted? */
656
5.65k
  if (ISSET(sudoers_ctx.mode, MODE_RUN) && def_intercept)
657
0
      SET(sudoers_ctx.mode, MODE_POLICY_INTERCEPTED);
658
659
  /* Only certain mode flags are legal for intercepted commands. */
660
5.65k
  if (ISSET(sudoers_ctx.mode, MODE_POLICY_INTERCEPTED))
661
0
      sudoers_ctx.mode &= MODE_INTERCEPT_MASK;
662
663
  /* Re-initialize defaults if we are called multiple times. */
664
5.65k
  if (!sudoers_reinit_defaults(&sudoers_ctx))
665
0
      debug_return_int(-1);
666
5.65k
    }
667
13.2k
    need_reinit = true;
668
669
13.2k
    unlimit_nproc();
670
671
13.2k
    if (!set_perms(&sudoers_ctx, PERM_INITIAL))
672
0
  goto bad;
673
674
    /* Environment variables specified on the command line. */
675
13.2k
    if (env_add != NULL && env_add[0] != NULL)
676
5.92k
  sudoers_ctx.user.env_add = env_add;
677
678
    /*
679
     * Make a local copy of argc/argv, with special handling for the
680
     * '-i' option.  We also allocate an extra slot for bash's --login.
681
     */
682
13.2k
    if (sudoers_ctx.runas.argv != NULL && sudoers_ctx.runas.argv != sudoers_ctx.runas.argv_saved) {
683
3.17k
  sudoers_gc_remove(GC_PTR, sudoers_ctx.runas.argv);
684
3.17k
  free(sudoers_ctx.runas.argv);
685
3.17k
    }
686
13.2k
    sudoers_ctx.runas.argv = reallocarray(NULL, (size_t)argc + 2, sizeof(char *));
687
13.2k
    if (sudoers_ctx.runas.argv == NULL) {
688
0
  sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
689
0
  goto error;
690
0
    }
691
13.2k
    sudoers_gc_add(GC_PTR, sudoers_ctx.runas.argv);
692
13.2k
    memcpy(sudoers_ctx.runas.argv, argv, (size_t)argc * sizeof(char *));
693
13.2k
    sudoers_ctx.runas.argc = argc;
694
13.2k
    sudoers_ctx.runas.argv[sudoers_ctx.runas.argc] = NULL;
695
13.2k
    if (ISSET(sudoers_ctx.mode, MODE_LOGIN_SHELL) && sudoers_ctx.runas.pw != NULL) {
696
217
  sudoers_ctx.runas.argv[0] = strdup(sudoers_ctx.runas.pw->pw_shell);
697
217
  if (sudoers_ctx.runas.argv[0] == NULL) {
698
0
      sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
699
0
      goto error;
700
0
  }
701
217
  sudoers_gc_add(GC_PTR, sudoers_ctx.runas.argv[0]);
702
217
    }
703
704
13.2k
    ret = sudoers_check_common(&sudoers_ctx, 0);
705
13.2k
    if (ret != true)
706
7.92k
  goto done;
707
708
5.35k
    if (!remote_iologs) {
709
2.55k
  if (iolog_enabled && def_iolog_file && def_iolog_dir) {
710
2.55k
      if ((iolog_path = format_iolog_path(&sudoers_ctx)) == NULL) {
711
0
    if (!def_ignore_iolog_errors)
712
0
        goto error;
713
    /* Unable to expand I/O log path, disable I/O logging. */
714
0
    def_log_input = false;
715
0
    def_log_output = false;
716
0
    def_log_stdin = false;
717
0
    def_log_stdout = false;
718
0
    def_log_stderr = false;
719
0
    def_log_ttyin = false;
720
0
    def_log_ttyout = false;
721
0
      }
722
2.55k
  }
723
2.55k
    }
724
725
    /*
726
     * Set umask based on sudoers.
727
     * If user's umask is more restrictive, OR in those bits too
728
     * unless umask_override is set.
729
     */
730
5.35k
    if (def_umask != ACCESSPERMS) {
731
5.35k
  cmnd_umask = def_umask;
732
5.35k
  if (!def_umask_override)
733
5.35k
      cmnd_umask |= sudoers_ctx.user.umask;
734
5.35k
    }
735
736
5.35k
    if (ISSET(sudoers_ctx.mode, MODE_LOGIN_SHELL)) {
737
104
  char *p;
738
739
  /* Convert /bin/sh -> -sh so shell knows it is a login shell */
740
104
  if ((p = strrchr(sudoers_ctx.runas.argv[0], '/')) == NULL)
741
0
      p = sudoers_ctx.runas.argv[0];
742
104
  *p = '-';
743
104
  sudoers_ctx.runas.argv[0] = p;
744
745
  /*
746
   * Newer versions of bash require the --login option to be used
747
   * in conjunction with the -c option even if the shell name starts
748
   * with a '-'.  Unfortunately, bash 1.x uses -login, not --login
749
   * so this will cause an error for that.
750
   */
751
104
  if (sudoers_ctx.runas.argc > 1 && strcmp(sudoers_ctx.runas.argv[0], "-bash") == 0 &&
752
72
      strcmp(sudoers_ctx.runas.argv[1], "-c") == 0) {
753
      /* We allocated extra space for the --login above. */
754
0
      memmove(&sudoers_ctx.runas.argv[2], &sudoers_ctx.runas.argv[1],
755
0
    (size_t)sudoers_ctx.runas.argc * sizeof(char *));
756
0
      sudoers_ctx.runas.argv[1] = (char *)"--login";
757
0
      sudoers_ctx.runas.argc++;
758
0
  }
759
760
104
#ifdef _PATH_ENVIRONMENT
761
  /* Insert system-wide environment variables. */
762
104
  if (!read_env_file(&sudoers_ctx, _PATH_ENVIRONMENT, true, false))
763
0
      sudo_warn("%s", _PATH_ENVIRONMENT);
764
104
#endif
765
#ifdef HAVE_LOGIN_CAP_H
766
  /* Set environment based on login class. */
767
  if (sudoers_ctx.runas.class) {
768
      login_cap_t *lc = login_getclass(sudoers_ctx.runas.class);
769
      if (lc != NULL) {
770
    setusercontext(lc, sudoers_ctx.runas.pw,
771
        sudoers_ctx.runas.pw->pw_uid, LOGIN_SETPATH|LOGIN_SETENV);
772
    login_close(lc);
773
      }
774
  }
775
#endif /* HAVE_LOGIN_CAP_H */
776
104
    }
777
778
    /* Insert system-wide environment variables. */
779
5.35k
    if (def_restricted_env_file) {
780
5.35k
  if (!read_env_file(&sudoers_ctx, def_restricted_env_file, false, true))
781
0
      sudo_warn("%s", def_restricted_env_file);
782
5.35k
    }
783
5.35k
    if (def_env_file) {
784
5.35k
  if (!read_env_file(&sudoers_ctx, def_env_file, false, false))
785
0
      sudo_warn("%s", def_env_file);
786
5.35k
    }
787
788
    /* Insert user-specified environment variables. */
789
5.35k
    if (!insert_env_vars(sudoers_ctx.user.env_add)) {
790
115
  sudo_warnx("%s",
791
115
      U_("error setting user-specified environment variables"));
792
115
  goto error;
793
115
    }
794
795
    /* Note: must call audit before uid change. */
796
5.24k
    if (ISSET(sudoers_ctx.mode, MODE_EDIT)) {
797
716
  const char *env_editor = NULL;
798
716
  char **edit_argv;
799
716
  int edit_argc;
800
801
716
  sudoers_ctx.sudoedit_nfiles = sudoers_ctx.runas.argc - 1;
802
716
  free(sudoers_ctx.runas.cmnd);
803
716
  sudoers_ctx.runas.cmnd = find_editor(sudoers_ctx.sudoedit_nfiles,
804
716
      sudoers_ctx.runas.argv + 1, &edit_argc, &edit_argv, NULL, &env_editor);
805
716
  if (sudoers_ctx.runas.cmnd == NULL) {
806
248
      switch (errno) {
807
248
      case ENOENT:
808
248
    audit_failure(&sudoers_ctx, sudoers_ctx.runas.argv,
809
248
        N_("%s: command not found"),
810
248
        env_editor ? env_editor : def_editor);
811
248
    sudo_warnx(U_("%s: command not found"),
812
248
        env_editor ? env_editor : def_editor);
813
248
    goto error;
814
0
      case EINVAL:
815
0
    if (def_env_editor && env_editor != NULL) {
816
        /* User tried to do something funny with the editor. */
817
0
        log_warningx(&sudoers_ctx,
818
0
      SLOG_NO_STDERR|SLOG_AUDIT|SLOG_SEND_MAIL,
819
0
      "invalid user-specified editor: %s", env_editor);
820
0
        goto error;
821
0
    }
822
0
    FALLTHROUGH;
823
0
      default:
824
0
    goto error;
825
248
      }
826
248
  }
827
  /* find_editor() already g/c'd edit_argv[] */
828
468
  if (sudoers_ctx.runas.argv != sudoers_ctx.runas.argv_saved) {
829
468
      sudoers_gc_remove(GC_PTR, sudoers_ctx.runas.argv);
830
468
      free(sudoers_ctx.runas.argv);
831
468
  }
832
468
  sudoers_ctx.runas.argv = edit_argv;
833
468
  sudoers_ctx.runas.argc = edit_argc;
834
835
  /* We want to run the editor with the unmodified environment. */
836
468
  env_swap_old();
837
468
    }
838
839
    /* Save the initial command and argv so we have it for exit logging. */
840
4.99k
    if (sudoers_ctx.runas.cmnd_saved == NULL) {
841
2.52k
  sudoers_ctx.runas.cmnd_saved = strdup(sudoers_ctx.runas.cmnd);
842
2.52k
  if (sudoers_ctx.runas.cmnd_saved == NULL) {
843
0
      sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
844
0
      goto error;
845
0
  }
846
2.52k
  sudoers_ctx.runas.argv_saved = sudoers_ctx.runas.argv;
847
2.52k
    }
848
849
4.99k
    ret = true;
850
4.99k
    goto done;
851
852
0
bad:
853
0
    ret = false;
854
0
    goto done;
855
856
363
error:
857
363
    ret = -1;
858
859
13.2k
done:
860
13.2k
    mail_parse_errors(&sudoers_ctx);
861
862
13.2k
    if (def_group_plugin)
863
0
  group_plugin_unload();
864
13.2k
    reset_parser();
865
866
13.2k
    if (ret == -1) {
867
  /* Free locally-allocated strings. */
868
426
  free(iolog_path);
869
12.8k
    } else {
870
  /* Store settings to pass back to front-end. */
871
12.8k
  if (!sudoers_policy_store_result(&sudoers_ctx, ret,
872
12.8k
      sudoers_ctx.runas.argv, env_get(), cmnd_umask, iolog_path, closure))
873
0
      ret = -1;
874
12.8k
    }
875
876
    /* Zero out stashed copy of environment, it is owned by the front-end. */
877
13.2k
    (void)env_init(NULL);
878
879
13.2k
    if (!rewind_perms())
880
0
  ret = -1;
881
882
13.2k
    restore_nproc();
883
884
13.2k
    sudo_warn_set_locale_func(NULL);
885
886
13.2k
    debug_return_int(ret);
887
13.2k
}
888
889
/*
890
 * Validate the user and update their timestamp file entry.
891
 * Returns true if allowed, false if denied, -1 on error and
892
 * -2 for usage error.
893
 */
894
int
895
sudoers_validate_user(void)
896
3.25k
{
897
3.25k
    int ret = -1;
898
3.25k
    debug_decl(sudoers_validate_user, SUDOERS_DEBUG_PLUGIN);
899
900
3.25k
    sudo_warn_set_locale_func(sudoers_warn_setlocale);
901
902
3.25k
    unlimit_nproc();
903
904
3.25k
    if (!set_perms(&sudoers_ctx, PERM_INITIAL))
905
0
  goto done;
906
907
3.25k
    sudoers_ctx.runas.argv = reallocarray(NULL, 2, sizeof(char *));
908
3.25k
    if (sudoers_ctx.runas.argv == NULL) {
909
0
  sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
910
0
  goto done;
911
0
    }
912
3.25k
    sudoers_gc_add(GC_PTR, sudoers_ctx.runas.argv);
913
3.25k
    sudoers_ctx.runas.argv[0] = (char *)"validate";
914
3.25k
    sudoers_ctx.runas.argv[1] = NULL;
915
3.25k
    sudoers_ctx.runas.argc = 2;
916
917
3.25k
    ret = sudoers_check_common(&sudoers_ctx, I_VERIFYPW);
918
919
3.25k
done:
920
3.25k
    mail_parse_errors(&sudoers_ctx);
921
922
3.25k
    if (def_group_plugin)
923
0
  group_plugin_unload();
924
3.25k
    reset_parser();
925
3.25k
    env_init(NULL);
926
927
3.25k
    if (!rewind_perms())
928
0
  ret = -1;
929
930
3.25k
    restore_nproc();
931
932
3.25k
    sudo_warn_set_locale_func(NULL);
933
934
3.25k
    debug_return_int(ret);
935
3.25k
}
936
937
/*
938
 * List a user's privileges or check whether a specific command may be run.
939
 * Returns true if allowed, false if denied, -1 on error and
940
 * -2 for usage error.
941
 */
942
int
943
sudoers_list(int argc, char * const argv[], const char *list_user, int verbose)
944
9.76k
{
945
9.76k
    struct passwd *pw;
946
9.76k
    int ret = -1;
947
9.76k
    debug_decl(sudoers_list, SUDOERS_DEBUG_PLUGIN);
948
949
9.76k
    sudo_warn_set_locale_func(sudoers_warn_setlocale);
950
951
9.76k
    unlimit_nproc();
952
953
9.76k
    if (!set_perms(&sudoers_ctx, PERM_INITIAL))
954
0
  goto done;
955
956
9.76k
    if (list_user) {
957
3.25k
  if (sudoers_ctx.runas.list_pw != NULL)
958
1.62k
      sudo_pw_delref(sudoers_ctx.runas.list_pw);
959
3.25k
  sudoers_ctx.runas.list_pw = sudo_getpwnam(list_user);
960
3.25k
  if (sudoers_ctx.runas.list_pw == NULL) {
961
0
      sudo_warnx(U_("unknown user %s"), list_user);
962
0
      goto done;
963
0
  }
964
3.25k
    }
965
966
9.76k
    sudoers_ctx.runas.argv = reallocarray(NULL, (size_t)argc + 2, sizeof(char *));
967
9.76k
    if (sudoers_ctx.runas.argv == NULL) {
968
0
  sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
969
0
  goto done;
970
0
    }
971
9.76k
    sudoers_gc_add(GC_PTR, sudoers_ctx.runas.argv);
972
9.76k
    sudoers_ctx.runas.argv[0] = (char *)"list";
973
9.76k
    if (argc != 0)
974
3.25k
  memcpy(sudoers_ctx.runas.argv + 1, argv, (size_t)argc * sizeof(char *));
975
9.76k
    sudoers_ctx.runas.argc = argc + 1;
976
9.76k
    sudoers_ctx.runas.argv[sudoers_ctx.runas.argc] = NULL;
977
978
9.76k
    ret = sudoers_check_common(&sudoers_ctx, I_LISTPW);
979
9.76k
    if (ret != true)
980
846
  goto done;
981
982
8.92k
    pw = sudoers_ctx.runas.list_pw ? sudoers_ctx.runas.list_pw : sudoers_ctx.user.pw;
983
8.92k
    if (ISSET(sudoers_ctx.mode, MODE_CHECK))
984
2.97k
  ret = display_cmnd(&sudoers_ctx, snl, pw, verbose);
985
5.94k
    else
986
5.94k
  ret = display_privs(&sudoers_ctx, snl, pw, verbose);
987
988
9.76k
done:
989
9.76k
    mail_parse_errors(&sudoers_ctx);
990
991
9.76k
    if (def_group_plugin)
992
0
  group_plugin_unload();
993
9.76k
    reset_parser();
994
9.76k
    env_init(NULL);
995
996
9.76k
    if (!rewind_perms())
997
0
  ret = -1;
998
999
9.76k
    restore_nproc();
1000
1001
9.76k
    sudo_warn_set_locale_func(NULL);
1002
1003
9.76k
    debug_return_int(ret);
1004
9.76k
}
1005
1006
/*
1007
 * Initialize timezone and fill in ctx->user.
1008
 */
1009
static bool
1010
init_vars(struct sudoers_context *ctx, char * const envp[])
1011
19.4k
{
1012
19.4k
    char * const * ep;
1013
19.4k
    bool unknown_user = false;
1014
19.4k
    debug_decl(init_vars, SUDOERS_DEBUG_PLUGIN);
1015
1016
19.4k
    if (!sudoers_initlocale(setlocale(LC_ALL, NULL), def_sudoers_locale)) {
1017
0
  sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
1018
0
  debug_return_bool(false);
1019
0
    }
1020
1021
19.4k
#define MATCHES(s, v) \
1022
233k
    (strncmp((s), (v), sizeof(v) - 1) == 0 && (s)[sizeof(v) - 1] != '\0')
1023
1024
19.4k
    ctx->user.envp = envp;
1025
699k
    for (ep = ctx->user.envp; *ep; ep++) {
1026
679k
  switch (**ep) {
1027
19.4k
      case 'K':
1028
19.4k
    if (MATCHES(*ep, "KRB5CCNAME="))
1029
19.4k
        ctx->user.ccname = *ep + sizeof("KRB5CCNAME=") - 1;
1030
19.4k
    break;
1031
38.8k
      case 'P':
1032
38.8k
    if (MATCHES(*ep, "PATH="))
1033
19.4k
        ctx->user.path = *ep + sizeof("PATH=") - 1;
1034
38.8k
    break;
1035
97.1k
      case 'S':
1036
97.1k
    if (MATCHES(*ep, "SUDO_PROMPT=")) {
1037
        /* Don't override "sudo -p prompt" */
1038
19.4k
        if (ctx->user.prompt == NULL)
1039
18.9k
      ctx->user.prompt = *ep + sizeof("SUDO_PROMPT=") - 1;
1040
19.4k
        break;
1041
19.4k
    }
1042
77.7k
    if (MATCHES(*ep, "SUDO_USER="))
1043
0
        prev_user = *ep + sizeof("SUDO_USER=") - 1;
1044
77.7k
    break;
1045
679k
      }
1046
679k
    }
1047
19.4k
#undef MATCHES
1048
1049
19.4k
    if (ctx->user.pw == NULL) {
1050
  /* Fake a struct passwd for the call to log_warningx(). */
1051
139
  ctx->user.pw = sudo_mkpwent(ctx->user.name, ctx->user.uid,
1052
139
      ctx->user.gid, NULL, NULL);
1053
139
  unknown_user = true;
1054
139
    }
1055
19.4k
    if (ctx->user.gid_list == NULL)
1056
19.4k
  ctx->user.gid_list = sudo_get_gidlist(ctx->user.pw, ENTRY_TYPE_ANY);
1057
1058
    /* Store initialize permissions so we can restore them later. */
1059
19.4k
    if (!set_perms(ctx, PERM_INITIAL))
1060
0
  debug_return_bool(false);
1061
1062
    /* Set parse callbacks */
1063
19.4k
    set_callbacks();
1064
1065
    /* It is now safe to use log_warningx() and set_perms() */
1066
19.4k
    if (unknown_user) {
1067
139
  log_warningx(ctx, SLOG_SEND_MAIL, N_("unknown user %s"), ctx->user.name);
1068
139
  debug_return_bool(false);
1069
139
    }
1070
1071
    /*
1072
     * Set runas passwd/group entries based on command line or sudoers.
1073
     * Note that if runas_group was specified without runas_user we
1074
     * run the command as the invoking user.
1075
     */
1076
19.2k
    if (ctx->runas.group != NULL) {
1077
579
  if (!set_runasgr(ctx, ctx->runas.group, false))
1078
97
      debug_return_bool(false);
1079
482
  if (!set_runaspw(ctx, ctx->runas.user ?
1080
482
    ctx->runas.user : ctx->user.name, false))
1081
2
      debug_return_bool(false);
1082
18.7k
    } else {
1083
18.7k
  if (!set_runaspw(ctx, ctx->runas.user ?
1084
18.7k
    ctx->runas.user : def_runas_default, false))
1085
20
      debug_return_bool(false);
1086
18.7k
    }
1087
1088
19.1k
    debug_return_bool(true);
1089
19.1k
}
1090
1091
/*
1092
 * Fill in ctx->user.cmnd and ctx->user.cmnd_stat variables.
1093
 * Does not fill in ctx->user.cmnd_base.
1094
 */
1095
int
1096
set_cmnd_path(struct sudoers_context *ctx, const char *runchroot)
1097
21.5k
{
1098
21.5k
    const char *cmnd_in;
1099
21.5k
    char *cmnd_out = NULL;
1100
21.5k
    char *path = ctx->user.path;
1101
21.5k
    int ret;
1102
21.5k
    debug_decl(set_cmnd_path, SUDOERS_DEBUG_PLUGIN);
1103
1104
21.5k
    cmnd_in = ISSET(ctx->mode, MODE_CHECK) ?
1105
18.3k
  ctx->runas.argv[1] : ctx->runas.argv[0];
1106
1107
21.5k
    free(ctx->user.cmnd_list);
1108
21.5k
    ctx->user.cmnd_list = NULL;
1109
21.5k
    free(ctx->user.cmnd);
1110
21.5k
    ctx->user.cmnd = NULL;
1111
21.5k
    canon_path_free(ctx->user.cmnd_dir);
1112
21.5k
    ctx->user.cmnd_dir = NULL;
1113
21.5k
    if (def_secure_path && !user_is_exempt(ctx))
1114
0
  path = def_secure_path;
1115
1116
21.5k
    ret = resolve_cmnd(ctx, cmnd_in, &cmnd_out, path, runchroot);
1117
21.5k
    if (ret == FOUND) {
1118
14.2k
  char *slash = strrchr(cmnd_out, '/');
1119
14.2k
  if (slash != NULL) {
1120
14.2k
      *slash = '\0';
1121
14.2k
      ctx->user.cmnd_dir = canon_path(cmnd_out);
1122
14.2k
      if (ctx->user.cmnd_dir == NULL && errno == ENOMEM)
1123
0
    goto error;
1124
14.2k
      *slash = '/';
1125
14.2k
  }
1126
14.2k
    }
1127
1128
21.5k
    if (ISSET(ctx->mode, MODE_CHECK))
1129
3.25k
  ctx->user.cmnd_list = cmnd_out;
1130
18.3k
    else
1131
18.3k
  ctx->user.cmnd = cmnd_out;
1132
1133
21.5k
    debug_return_int(ret);
1134
0
error:
1135
0
    free(cmnd_out);
1136
0
    debug_return_int(NOT_FOUND_ERROR);
1137
0
}
1138
1139
/*
1140
 * Fill in ctx->user.cmnd, ctx->user.cmnd_stat and cmnd_status variables.
1141
 * Does not fill in ctx->user.cmnd_base.
1142
 */
1143
void
1144
set_cmnd_status(struct sudoers_context *ctx, const char *runchroot)
1145
5.65k
{
1146
5.65k
    cmnd_status = set_cmnd_path(ctx, runchroot);
1147
5.65k
}
1148
1149
/*
1150
 * Fill in ctx->user.cmnd, ctx->user.cmnd_args, ctx->user.cmnd_base and
1151
 * ctx->user.cmnd_stat variables and apply any command-specific defaults entries.
1152
 */
1153
static int
1154
set_cmnd(struct sudoers_context *ctx)
1155
26.3k
{
1156
26.3k
    struct sudo_nss *nss;
1157
26.3k
    int ret = FOUND;
1158
26.3k
    debug_decl(set_cmnd, SUDOERS_DEBUG_PLUGIN);
1159
1160
    /* Allocate ctx->user.cmnd_stat for find_path() and match functions. */
1161
26.3k
    free(ctx->user.cmnd_stat);
1162
26.3k
    ctx->user.cmnd_stat = calloc(1, sizeof(struct stat));
1163
26.3k
    if (ctx->user.cmnd_stat == NULL) {
1164
0
  sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
1165
0
  debug_return_int(NOT_FOUND_ERROR);
1166
0
    }
1167
1168
    /* Re-initialize for when we are called multiple times. */
1169
26.3k
    free(ctx->runas.cmnd);
1170
26.3k
    ctx->runas.cmnd = NULL;
1171
1172
26.3k
    if (ISSET(ctx->mode, MODE_RUN|MODE_EDIT|MODE_CHECK)) {
1173
16.5k
  if (!ISSET(ctx->mode, MODE_EDIT)) {
1174
15.9k
      const char *runchroot = ctx->runas.chroot;
1175
15.9k
      if (runchroot == NULL && def_runchroot != NULL &&
1176
15.8k
        strcmp(def_runchroot, "*") != 0)
1177
15.8k
    runchroot = def_runchroot;
1178
1179
15.9k
      ret = set_cmnd_path(ctx, runchroot);
1180
15.9k
      if (ret == NOT_FOUND_ERROR) {
1181
0
    if (errno == ENAMETOOLONG) {
1182
0
        audit_failure(ctx, ctx->runas.argv, N_("command too long"));
1183
0
    }
1184
0
    log_warning(ctx, 0, "%s", ctx->runas.argv[0]);
1185
0
    debug_return_int(ret);
1186
0
      }
1187
15.9k
  }
1188
1189
  /* set ctx->user.cmnd_args */
1190
16.5k
  free(ctx->user.cmnd_args);
1191
16.5k
  ctx->user.cmnd_args = NULL;
1192
16.5k
  if (ISSET(ctx->mode, MODE_CHECK)) {
1193
3.25k
      if (ctx->runas.argc > 2) {
1194
    /* Skip the command being listed in ctx->runas.argv[1]. */
1195
148
    ctx->user.cmnd_args = strvec_join(ctx->runas.argv + 2, ' ', NULL);
1196
148
    if (ctx->user.cmnd_args == NULL)
1197
0
        debug_return_int(NOT_FOUND_ERROR);
1198
148
      }
1199
13.2k
  } else if (ctx->runas.argc > 1) {
1200
1.20k
      if (ISSET(ctx->mode, MODE_SHELL|MODE_LOGIN_SHELL) &&
1201
552
        ISSET(ctx->mode, MODE_RUN)) {
1202
    /*
1203
     * When running a command via a shell, the sudo front-end
1204
     * escapes potential meta chars.  We unescape non-spaces
1205
     * for sudoers matching and logging purposes.
1206
     * TODO: move escaping to the policy plugin instead
1207
     */
1208
552
    ctx->user.cmnd_args = strvec_join(ctx->runas.argv + 1, ' ',
1209
552
        strlcpy_unescape);
1210
651
      } else {
1211
651
    ctx->user.cmnd_args = strvec_join(ctx->runas.argv + 1, ' ',
1212
651
        NULL);
1213
651
      }
1214
1.20k
      if (ctx->user.cmnd_args == NULL)
1215
0
    debug_return_int(NOT_FOUND_ERROR);
1216
1.20k
  }
1217
16.5k
    }
1218
26.3k
    if (ctx->user.cmnd == NULL) {
1219
13.9k
  ctx->user.cmnd = strdup(ctx->runas.argv[0]);
1220
13.9k
  if (ctx->user.cmnd == NULL)
1221
0
      debug_return_int(NOT_FOUND_ERROR);
1222
13.9k
    }
1223
26.3k
    ctx->user.cmnd_base = sudo_basename(ctx->user.cmnd);
1224
1225
    /* Convert "sudo sudoedit" -> "sudoedit" */
1226
26.3k
    if (ISSET(ctx->mode, MODE_RUN) && strcmp(ctx->user.cmnd_base, "sudoedit") == 0) {
1227
256
  char *new_cmnd;
1228
1229
256
  CLR(ctx->mode, MODE_RUN);
1230
256
  SET(ctx->mode, MODE_EDIT);
1231
256
  sudo_warnx("%s", U_("sudoedit doesn't need to be run via sudo"));
1232
256
  if ((new_cmnd = strdup("sudoedit")) == NULL) {
1233
0
      sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
1234
0
      debug_return_int(NOT_FOUND_ERROR);
1235
0
  }
1236
256
  free(ctx->user.cmnd);
1237
256
  ctx->user.cmnd_base = ctx->user.cmnd = new_cmnd;
1238
256
    }
1239
1240
26.3k
    TAILQ_FOREACH(nss, snl, entries) {
1241
  /* Missing/invalid defaults is not a fatal error. */
1242
26.3k
  (void)update_defaults(ctx, nss->parse_tree, NULL, SETDEF_CMND, false);
1243
26.3k
    }
1244
1245
26.3k
    debug_return_int(ret);
1246
26.3k
}
1247
1248
static int
1249
open_file(const char *path, int flags)
1250
0
{
1251
0
    int fd;
1252
0
    debug_decl(open_file, SUDOERS_DEBUG_PLUGIN);
1253
1254
0
    if (!set_perms(NULL, PERM_SUDOERS))
1255
0
  debug_return_int(-1);
1256
1257
0
    fd = open(path, flags);
1258
0
    if (fd == -1 && errno == EACCES && geteuid() != ROOT_UID) {
1259
  /*
1260
   * If we tried to open sudoers as non-root but got EACCES,
1261
   * try again as root.
1262
   */
1263
0
  int serrno = errno;
1264
0
  if (restore_perms() && set_perms(NULL, PERM_ROOT))
1265
0
      fd = open(path, flags);
1266
0
  errno = serrno;
1267
0
    }
1268
0
    if (!restore_perms()) {
1269
  /* unable to change back to root */
1270
0
  if (fd != -1) {
1271
0
      close(fd);
1272
0
      fd = -1;
1273
0
  }
1274
0
    }
1275
1276
0
    debug_return_int(fd);
1277
0
}
1278
1279
/*
1280
 * Open sudoers file and check mode/owner/type.
1281
 * Returns a handle to the sudoers file or NULL on error.
1282
 */
1283
FILE *
1284
open_sudoers(const char *path, char **outfile, bool doedit, bool *keepopen)
1285
0
{
1286
0
    char fname[PATH_MAX];
1287
0
    FILE *fp = NULL;
1288
0
    struct stat sb;
1289
0
    int error, fd;
1290
0
    debug_decl(open_sudoers, SUDOERS_DEBUG_PLUGIN);
1291
1292
0
    fd = sudo_open_conf_path(path, fname, sizeof(fname), open_file);
1293
0
    if (sudoers_ctx.parser_conf.ignore_perms) {
1294
  /* Skip sudoers security checks when ignore_perms is set. */
1295
0
  if (fd == -1 || fstat(fd, &sb) == -1)
1296
0
      error = SUDO_PATH_MISSING;
1297
0
  else
1298
0
      error = SUDO_PATH_SECURE;
1299
0
    } else {
1300
0
  error = sudo_secure_fd(fd, S_IFREG, sudoers_file_uid(),
1301
0
      sudoers_file_gid(), &sb);
1302
0
    }
1303
0
    switch (error) {
1304
0
    case SUDO_PATH_SECURE:
1305
  /*
1306
   * Make sure we can read the file so we can present the
1307
   * user with a reasonable error message (unlike the lexer).
1308
   */
1309
0
  if ((fp = fdopen(fd, "r")) == NULL) {
1310
0
      log_warning(&sudoers_ctx, SLOG_PARSE_ERROR,
1311
0
    N_("unable to open %s"), fname);
1312
0
  } else {
1313
0
      fd = -1;
1314
0
      if (sb.st_size != 0 && fgetc(fp) == EOF) {
1315
0
    log_warning(&sudoers_ctx, SLOG_PARSE_ERROR,
1316
0
        N_("unable to read %s"), fname);
1317
0
    fclose(fp);
1318
0
    fp = NULL;
1319
0
      } else {
1320
    /* Rewind fp and set close on exec flag. */
1321
0
    rewind(fp);
1322
0
    (void)fcntl(fileno(fp), F_SETFD, FD_CLOEXEC);
1323
0
    if (outfile != NULL) {
1324
0
                    *outfile = sudo_rcstr_dup(fname);
1325
0
        if (*outfile == NULL) {
1326
0
      sudo_warnx(U_("%s: %s"), __func__,
1327
0
          U_("unable to allocate memory"));
1328
0
      fclose(fp);
1329
0
      fp = NULL;
1330
0
        }
1331
0
    }
1332
0
      }
1333
0
  }
1334
0
  break;
1335
0
    case SUDO_PATH_MISSING:
1336
0
  log_warning(&sudoers_ctx, SLOG_PARSE_ERROR,
1337
0
      N_("unable to open %s"), path);
1338
0
  break;
1339
0
    case SUDO_PATH_BAD_TYPE:
1340
0
  log_warningx(&sudoers_ctx, SLOG_PARSE_ERROR,
1341
0
      N_("%s is not a regular file"), fname);
1342
0
  break;
1343
0
    case SUDO_PATH_WRONG_OWNER:
1344
0
  log_warningx(&sudoers_ctx, SLOG_PARSE_ERROR,
1345
0
      N_("%s is owned by uid %u, should be %u"), fname,
1346
0
      (unsigned int)sb.st_uid, (unsigned int)sudoers_file_uid());
1347
0
  break;
1348
0
    case SUDO_PATH_WORLD_WRITABLE:
1349
0
  log_warningx(&sudoers_ctx, SLOG_PARSE_ERROR,
1350
0
      N_("%s is world writable"), fname);
1351
0
  break;
1352
0
    case SUDO_PATH_GROUP_WRITABLE:
1353
0
  log_warningx(&sudoers_ctx, SLOG_PARSE_ERROR,
1354
0
      N_("%s is owned by gid %u, should be %u"), fname,
1355
0
      (unsigned int)sb.st_gid, (unsigned int)sudoers_file_gid());
1356
0
  break;
1357
0
    default:
1358
0
  sudo_warnx("%s: internal error, unexpected error %d", __func__, error);
1359
0
  break;
1360
0
    }
1361
1362
0
    if (fp == NULL && fd != -1)
1363
0
  close(fd);
1364
1365
0
    debug_return_ptr(fp);
1366
0
}
1367
1368
#ifdef HAVE_LOGIN_CAP_H
1369
static bool
1370
set_loginclass(struct sudoers_context *ctx)
1371
{
1372
    const struct passwd *pw = ctx->runas.pw ? ctx->runas.pw : ctx->user.pw;
1373
    const unsigned int errflags = SLOG_RAW_MSG;
1374
    login_cap_t *lc;
1375
    bool ret = true;
1376
    debug_decl(set_loginclass, SUDOERS_DEBUG_PLUGIN);
1377
1378
    if (!def_use_loginclass)
1379
  goto done;
1380
1381
    if (ctx->runas.class && strcmp(ctx->runas.class, "-") != 0) {
1382
  if (ctx->user.uid != 0 && pw->pw_uid != 0) {
1383
      sudo_warnx(U_("only root can use \"-c %s\""), ctx->runas.class);
1384
      ret = false;
1385
      goto done;
1386
  }
1387
    } else {
1388
  ctx->runas.class = pw->pw_class;
1389
  if (!ctx->runas.class || !*ctx->runas.class)
1390
      ctx->runas.class = (char *)
1391
    ((pw->pw_uid == 0) ? LOGIN_DEFROOTCLASS : LOGIN_DEFCLASS);
1392
    }
1393
1394
    /* Make sure specified login class is valid. */
1395
    lc = login_getclass(ctx->runas.class);
1396
    if (!lc || !lc->lc_class || strcmp(lc->lc_class, ctx->runas.class) != 0) {
1397
  /*
1398
   * Don't make it an error if the user didn't specify the login
1399
   * class themselves.  We do this because if login.conf gets
1400
   * corrupted we want the admin to be able to use sudo to fix it.
1401
   */
1402
  log_warningx(ctx, errflags, N_("unknown login class %s"),
1403
      ctx->runas.class);
1404
  def_use_loginclass = false;
1405
  if (ctx->runas.class)
1406
      ret = false;
1407
    }
1408
    login_close(lc);
1409
done:
1410
    debug_return_bool(ret);
1411
}
1412
#else
1413
static bool
1414
set_loginclass(struct sudoers_context *ctx)
1415
19.1k
{
1416
19.1k
    return true;
1417
19.1k
}
1418
#endif /* HAVE_LOGIN_CAP_H */
1419
1420
/*
1421
 * Get passwd entry for the user we are going to run commands as
1422
 * and store it in ctx->runas.pw.  By default, commands run as "root".
1423
 */
1424
static bool
1425
set_runaspw(struct sudoers_context *ctx, const char *user, bool quiet)
1426
43.0k
{
1427
43.0k
    struct passwd *pw = NULL;
1428
43.0k
    debug_decl(set_runaspw, SUDOERS_DEBUG_PLUGIN);
1429
1430
43.0k
    unknown_runas_uid = false;
1431
43.0k
    if (*user == '#') {
1432
305
  const char *errstr;
1433
305
  uid_t uid = sudo_strtoid(user + 1, &errstr);
1434
305
  if (errstr == NULL) {
1435
300
      if ((pw = sudo_getpwuid(uid)) == NULL) {
1436
90
    unknown_runas_uid = true;
1437
90
    pw = sudo_fakepwnam(user, ctx->user.gid);
1438
90
      }
1439
300
  }
1440
305
    }
1441
43.0k
    if (pw == NULL) {
1442
42.7k
  if ((pw = sudo_getpwnam(user)) == NULL) {
1443
22
      if (!quiet)
1444
22
    log_warningx(ctx, SLOG_AUDIT, N_("unknown user %s"), user);
1445
22
      debug_return_bool(false);
1446
22
  }
1447
42.7k
    }
1448
43.0k
    if (ctx->runas.pw != NULL)
1449
23.8k
  sudo_pw_delref(ctx->runas.pw);
1450
43.0k
    ctx->runas.pw = pw;
1451
43.0k
    debug_return_bool(true);
1452
43.0k
}
1453
1454
/*
1455
 * Get group entry for the group we are going to run commands as
1456
 * and store it in ctx->runas.gr.
1457
 */
1458
static bool
1459
set_runasgr(struct sudoers_context *ctx, const char *group, bool quiet)
1460
579
{
1461
579
    struct group *gr = NULL;
1462
579
    debug_decl(set_runasgr, SUDOERS_DEBUG_PLUGIN);
1463
1464
579
    unknown_runas_gid = false;
1465
579
    if (*group == '#') {
1466
453
  const char *errstr;
1467
453
  gid_t gid = sudo_strtoid(group + 1, &errstr);
1468
453
  if (errstr == NULL) {
1469
452
      if ((gr = sudo_getgrgid(gid)) == NULL) {
1470
311
    unknown_runas_gid = true;
1471
311
    gr = sudo_fakegrnam(group);
1472
311
      }
1473
452
  }
1474
453
    }
1475
579
    if (gr == NULL) {
1476
127
  if ((gr = sudo_getgrnam(group)) == NULL) {
1477
97
      if (!quiet)
1478
97
    log_warningx(ctx, SLOG_AUDIT, N_("unknown group %s"), group);
1479
97
      debug_return_bool(false);
1480
97
  }
1481
127
    }
1482
482
    if (ctx->runas.gr != NULL)
1483
0
  sudo_gr_delref(ctx->runas.gr);
1484
482
    ctx->runas.gr = gr;
1485
482
    debug_return_bool(true);
1486
482
}
1487
1488
/*
1489
 * Callback for runas_default sudoers setting.
1490
 */
1491
bool
1492
cb_runas_default(struct sudoers_context *ctx, const char *file, int line,
1493
    int column, const union sudo_defs_val *sd_un, int op)
1494
24.8k
{
1495
24.8k
    debug_decl(cb_runas_default, SUDOERS_DEBUG_PLUGIN);
1496
1497
    /* Only reset runaspw if user didn't specify one. */
1498
24.8k
    if (ctx->runas.user == NULL && ctx->runas.group == NULL)
1499
23.8k
  debug_return_bool(set_runaspw(ctx, sd_un->str, true));
1500
975
    debug_return_bool(true);
1501
975
}
1502
1503
/*
1504
 * Cleanup hook for sudo_fatal()/sudo_fatalx()
1505
 * Also called at policy close time.
1506
 */
1507
void
1508
sudoers_cleanup(void)
1509
24.5k
{
1510
24.5k
    struct sudo_nss *nss;
1511
24.5k
    struct defaults *def;
1512
24.5k
    debug_decl(sudoers_cleanup, SUDOERS_DEBUG_PLUGIN);
1513
1514
24.5k
    if (snl != NULL) {
1515
19.1k
  TAILQ_FOREACH(nss, snl, entries) {
1516
19.1k
      nss->close(&sudoers_ctx, nss);
1517
19.1k
  }
1518
19.1k
  snl = NULL;
1519
19.1k
  reset_parser();
1520
19.1k
    }
1521
44.2k
    while ((def = TAILQ_FIRST(&initial_defaults)) != NULL) {
1522
19.7k
  TAILQ_REMOVE(&initial_defaults, def, entries);
1523
19.7k
  free(def->var);
1524
19.7k
  free(def->val);
1525
19.7k
  free(def);
1526
19.7k
    }
1527
24.5k
    sudoers_initialized = false;
1528
24.5k
    need_reinit = false;
1529
24.5k
    if (def_group_plugin)
1530
0
  group_plugin_unload();
1531
24.5k
    sudoers_ctx_free(&sudoers_ctx);
1532
24.5k
    sudo_freepwcache();
1533
24.5k
    sudo_freegrcache();
1534
24.5k
    canon_path_free_cache();
1535
1536
    /* We must free the cached environment before running g/c. */
1537
24.5k
    env_free();
1538
1539
    /* Run garbage collector. */
1540
24.5k
    sudoers_gc_run();
1541
1542
    /* Clear globals */
1543
24.5k
    prev_user = NULL;
1544
1545
24.5k
    debug_return;
1546
24.5k
}
1547
1548
bool
1549
sudoers_set_mode(unsigned int flags, unsigned int mask)
1550
32.5k
{
1551
32.5k
    SET(sudoers_ctx.mode, flags);
1552
32.5k
    return ((sudoers_ctx.mode & mask) == sudoers_ctx.mode);
1553
32.5k
}
1554
1555
const struct sudoers_context *
1556
sudoers_get_context(void)
1557
64.8k
{
1558
64.8k
    return &sudoers_ctx;
1559
64.8k
}
1560
1561
bool
1562
sudoers_set_log_format(enum def_tuple tuple)
1563
0
{
1564
0
    enum eventlog_format format;
1565
0
    debug_decl(cb_log_format, SUDOERS_DEBUG_PLUGIN);
1566
1567
    /* FFR - make "json" an alias for EVLOG_JSON_COMPACT instead. */
1568
0
    switch (tuple) {
1569
0
    case json_compact:
1570
0
        format = EVLOG_JSON_COMPACT;
1571
0
        break;
1572
0
    case json:
1573
0
    case json_pretty:
1574
0
        format = EVLOG_JSON_PRETTY;
1575
0
        break;
1576
0
    case sudo:
1577
0
        format = EVLOG_SUDO;
1578
0
        break;
1579
0
    default:
1580
0
  debug_return_bool(false);
1581
0
    }
1582
0
    eventlog_set_format(format);
1583
1584
    debug_return_bool(true);
1585
0
}