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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
|
/*
* Copyright (c) 1996, 1998-2005, 2007-2008
* Todd C. Miller <Todd.Miller@courtesan.com>
*
* 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.
*/
/*
* Lock the sudoers file for safe editing (ala vipw) and check for parse errors.
*/
#define _SUDO_MAIN
#ifdef __TANDEM
# include <floss.h>
#endif
#include <config.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/time.h>
#ifndef __TANDEM
# include <sys/file.h>
#endif
#include <sys/wait.h>
#include <stdio.h>
#ifdef STDC_HEADERS
# include <stdlib.h>
# include <stddef.h>
#else
# ifdef HAVE_STDLIB_H
# include <stdlib.h>
# endif
#endif /* STDC_HEADERS */
#ifdef HAVE_STRING_H
# include <string.h>
#else
# ifdef HAVE_STRINGS_H
# include <strings.h>
# endif
#endif /* HAVE_STRING_H */
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif /* HAVE_UNISTD_H */
#include <ctype.h>
#include <pwd.h>
#include <grp.h>
#include <signal.h>
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#if TIME_WITH_SYS_TIME
# include <time.h>
#endif
#ifdef __STDC__
# include <stdarg.h>
#else
# include <varargs.h>
#endif
#ifndef HAVE_TIMESPEC
# include <emul/timespec.h>
#endif
#include "sudo.h"
#include "interfaces.h"
#include "parse.h"
#include <gram.h>
#include "version.h"
#ifndef lint
__unused static const char rcsid[] = "$Sudo: visudo.c,v 1.221 2008/11/18 15:50:53 millert Exp $";
#endif /* lint */
struct sudoersfile {
char *path;
int fd;
char *tpath;
int tfd;
int modified;
struct sudoersfile *next;
};
/*
* Function prototypes
*/
static RETSIGTYPE quit __P((int));
static char *get_args __P((char *));
static char *get_editor __P((char **));
static char whatnow __P((void));
static int check_aliases __P((int));
static int check_syntax __P((char *, int, int));
static int edit_sudoers __P((struct sudoersfile *, char *, char *, int));
static int install_sudoers __P((struct sudoersfile *, int));
static int print_unused __P((void *, void *));
static int reparse_sudoers __P((char *, char *, int, int));
static int run_command __P((char *, char **));
static void setup_signals __P((void));
static void usage __P((void)) __attribute__((__noreturn__));
extern void yyerror __P((const char *));
extern void yyrestart __P((FILE *));
/*
* External globals exported by the parser
*/
extern FILE *yyin;
extern char *sudoers, *errorfile;
extern int errorlineno, parse_error;
/* For getopt(3) */
extern char *optarg;
extern int optind;
/*
* Globals
*/
int Argc;
char **Argv;
int num_interfaces;
struct interface *interfaces;
struct sudo_user sudo_user;
struct passwd *list_pw;
static struct sudoerslist {
struct sudoersfile *first, *last;
} sudoerslist;
int
main(argc, argv)
int argc;
char **argv;
{
struct sudoersfile *sp;
char *args, *editor, *sudoers_path;
int ch, checkonly, quiet, strict, oldperms;
Argv = argv;
if ((Argc = argc) < 1)
usage();
/*
* Arg handling.
*/
checkonly = oldperms = quiet = strict = FALSE;
sudoers_path = _PATH_SUDOERS;
while ((ch = getopt(argc, argv, "Vcf:sq")) != -1) {
switch (ch) {
case 'V':
(void) printf("%s version %s\n", getprogname(), version);
exit(0);
case 'c':
checkonly++; /* check mode */
break;
case 'f':
sudoers_path = optarg; /* sudoers file path */
oldperms = TRUE;
break;
case 's':
strict++; /* strict mode */
break;
case 'q':
quiet++; /* quiet mode */
break;
default:
usage();
}
}
argc -= optind;
argv += optind;
if (argc)
usage();
sudo_setpwent();
sudo_setgrent();
/* Mock up a fake sudo_user struct. */
user_host = user_shost = user_cmnd = "";
if ((sudo_user.pw = sudo_getpwuid(getuid())) == NULL)
errorx(1, "you don't exist in the passwd database");
/* Setup defaults data structures. */
init_defaults();
if (checkonly)
exit(check_syntax(sudoers_path, quiet, strict));
/*
* Parse the existing sudoers file(s) in quiet mode to highlight any
* existing errors and to pull in editor and env_editor conf values.
*/
if ((yyin = open_sudoers(sudoers_path, NULL)) == NULL)
error(1, "%s", sudoers_path);
init_parser(sudoers_path, 0);
yyparse();
(void) update_defaults(SETDEF_GENERIC|SETDEF_HOST|SETDEF_USER);
editor = get_editor(&args);
/* Install signal handlers to clean up temp files if we are killed. */
setup_signals();
/* Edit the sudoers file(s) */
tq_foreach_fwd(&sudoerslist, sp) {
if (sp != tq_first(&sudoerslist)) {
printf("press return to edit %s: ", sp->path);
while ((ch = getchar()) != EOF && ch != '\n')
continue;
}
edit_sudoers(sp, editor, args, -1);
}
/* Check edited files for a parse error and re-edit any that fail. */
reparse_sudoers(editor, args, strict, quiet);
/* Install the sudoers temp files. */
tq_foreach_fwd(&sudoerslist, sp) {
if (!sp->modified)
(void) unlink(sp->tpath);
else
(void) install_sudoers(sp, oldperms);
}
exit(0);
}
/*
* Edit each sudoers file.
* Returns TRUE on success, else FALSE.
*/
static int
edit_sudoers(sp, editor, args, lineno)
struct sudoersfile *sp;
char *editor, *args;
int lineno;
{
int tfd; /* sudoers temp file descriptor */
int modified; /* was the file modified? */
int ac; /* argument count */
char **av; /* argument vector for run_command */
char *cp; /* scratch char pointer */
char buf[PATH_MAX*2]; /* buffer used for copying files */
char linestr[64]; /* string version of lineno */
struct timespec ts1, ts2; /* time before and after edit */
struct timespec orig_mtim; /* starting mtime of sudoers file */
off_t orig_size; /* starting size of sudoers file */
ssize_t nread; /* number of bytes read */
struct stat sb; /* stat buffer */
#ifdef HAVE_FSTAT
if (fstat(sp->fd, &sb) == -1)
#else
if (stat(sp->path, &sb) == -1)
#endif
error(1, "can't stat %s", sp->path);
orig_size = sb.st_size;
orig_mtim.tv_sec = mtim_getsec(sb);
orig_mtim.tv_nsec = mtim_getnsec(sb);
/* Create the temp file if needed and set timestamp. */
if (sp->tpath == NULL) {
easprintf(&sp->tpath, "%s.tmp", sp->path);
tfd = open(sp->tpath, O_WRONLY | O_CREAT | O_TRUNC, 0600);
if (tfd < 0)
error(1, "%s", sp->tpath);
/* Copy sp->path -> sp->tpath and reset the mtime. */
if (orig_size != 0) {
(void) lseek(sp->fd, (off_t)0, SEEK_SET);
while ((nread = read(sp->fd, buf, sizeof(buf))) > 0)
if (write(tfd, buf, nread) != nread)
error(1, "write error");
/* Add missing newline at EOF if needed. */
if (nread > 0 && buf[nread - 1] != '\n') {
buf[0] = '\n';
write(tfd, buf, 1);
}
}
(void) close(tfd);
}
(void) touch(-1, sp->tpath, &orig_mtim);
/* Find the length of the argument vector */
ac = 3 + (lineno > 0);
if (args) {
int wasblank;
ac++;
for (wasblank = FALSE, cp = args; *cp; cp++) {
if (isblank((unsigned char) *cp))
wasblank = TRUE;
else if (wasblank) {
wasblank = FALSE;
ac++;
}
}
}
/* Build up argument vector for the command */
av = emalloc2(ac, sizeof(char *));
if ((av[0] = strrchr(editor, '/')) != NULL)
av[0]++;
else
av[0] = editor;
ac = 1;
if (lineno > 0) {
(void) snprintf(linestr, sizeof(linestr), "+%d", lineno);
av[ac++] = linestr;
}
if (args) {
for ((cp = strtok(args, " \t")); cp; (cp = strtok(NULL, " \t")))
av[ac++] = cp;
}
av[ac++] = sp->tpath;
av[ac++] = NULL;
/*
* Do the edit:
* We cannot check the editor's exit value against 0 since
* XPG4 specifies that vi's exit value is a function of the
* number of errors during editing (?!?!).
*/
gettime(&ts1);
if (run_command(editor, av) != -1) {
gettime(&ts2);
/*
* Sanity checks.
*/
if (stat(sp->tpath, &sb) < 0) {
warningx("cannot stat temporary file (%s), %s unchanged",
sp->tpath, sp->path);
return(FALSE);
}
if (sb.st_size == 0 && orig_size != 0) {
warningx("zero length temporary file (%s), %s unchanged",
sp->tpath, sp->path);
sp->modified = TRUE;
return(FALSE);
}
} else {
warningx("editor (%s) failed, %s unchanged", editor, sp->path);
return(FALSE);
}
/* Set modified bit if use changed the file. */
modified = TRUE;
if (orig_size == sb.st_size &&
orig_mtim.tv_sec == mtim_getsec(sb) &&
orig_mtim.tv_nsec == mtim_getnsec(sb)) {
/*
* If mtime and size match but the user spent no measurable
* time in the editor we can't tell if the file was changed.
*/
#ifdef HAVE_TIMESPECSUB2
timespecsub(&ts1, &ts2);
#else
timespecsub(&ts1, &ts2, &ts2);
#endif
if (timespecisset(&ts2))
modified = FALSE;
}
/*
* If modified in this edit session, mark as modified.
*/
if (modified)
sp->modified = modified;
else
warningx("%s unchanged", sp->tpath);
return(TRUE);
}
/*
* Parse sudoers after editing and re-edit any ones that caused a parse error.
* Returns TRUE on success, else FALSE.
*/
static int
reparse_sudoers(editor, args, strict, quiet)
char *editor, *args;
int strict, quiet;
{
struct sudoersfile *sp, *last;
FILE *fp;
int ch;
/*
* Parse the edited sudoers files and do sanity checking
*/
do {
sp = tq_first(&sudoerslist);
last = tq_last(&sudoerslist);
fp = fopen(sp->tpath, "r+");
if (fp == NULL)
errorx(1, "can't re-open temporary file (%s), %s unchanged.",
sp->tpath, sp->path);
/* Clean slate for each parse */
init_defaults();
init_parser(sp->path, quiet);
/* Parse the sudoers temp file */
yyrestart(fp);
if (yyparse() && parse_error != TRUE) {
warningx("unabled to parse temporary file (%s), unknown error",
sp->tpath);
parse_error = TRUE;
}
fclose(yyin);
if (check_aliases(strict) != 0)
parse_error = TRUE;
/*
* Got an error, prompt the user for what to do now
*/
if (parse_error) {
switch (whatnow()) {
case 'Q' : parse_error = FALSE; /* ignore parse error */
break;
case 'x' : cleanup(0);
exit(0);
break;
}
}
if (parse_error) {
/* Edit file with the parse error */
tq_foreach_fwd(&sudoerslist, sp) {
if (errorfile == NULL || strcmp(sp->path, errorfile) == 0) {
edit_sudoers(sp, editor, args, errorlineno);
break;
}
}
if (sp == NULL)
errorx(1, "internal error, can't find %s in list!", sudoers);
}
/* If any new #include directives were added, edit them too. */
for (sp = last->next; sp != NULL; sp = sp->next) {
printf("press return to edit %s: ", sp->path);
while ((ch = getchar()) != EOF && ch != '\n')
continue;
edit_sudoers(sp, editor, args, errorlineno);
}
} while (parse_error);
return(TRUE);
}
/*
* Set the owner and mode on a sudoers temp file and
* move it into place. Returns TRUE on success, else FALSE.
*/
static int
install_sudoers(sp, oldperms)
struct sudoersfile *sp;
int oldperms;
{
struct stat sb;
/*
* Change mode and ownership of temp file so when
* we move it to sp->path things are kosher.
*/
if (oldperms) {
/* Use perms of the existing file. */
#ifdef HAVE_FSTAT
if (fstat(sp->fd, &sb) == -1)
#else
if (stat(sp->path, &sb) == -1)
#endif
error(1, "can't stat %s", sp->path);
(void) chown(sp->tpath, sb.st_uid, sb.st_gid);
(void) chmod(sp->tpath, sb.st_mode & 0777);
} else {
if (chown(sp->tpath, SUDOERS_UID, SUDOERS_GID) != 0) {
warning("unable to set (uid, gid) of %s to (%d, %d)",
sp->tpath, SUDOERS_UID, SUDOERS_GID);
return(FALSE);
}
if (chmod(sp->tpath, SUDOERS_MODE) != 0) {
warning("unable to change mode of %s to 0%o", sp->tpath,
SUDOERS_MODE);
return(FALSE);
}
}
/*
* Now that sp->tpath is sane (parses ok) it needs to be
* rename(2)'d to sp->path. If the rename(2) fails we try using
* mv(1) in case sp->tpath and sp->path are on different file systems.
*/
if (rename(sp->tpath, sp->path) == 0) {
efree(sp->tpath);
sp->tpath = NULL;
} else {
if (errno == EXDEV) {
char *av[4];
warningx("%s and %s not on the same file system, using mv to rename",
sp->tpath, sp->path);
/* Build up argument vector for the command */
if ((av[0] = strrchr(_PATH_MV, '/')) != NULL)
av[0]++;
else
av[0] = _PATH_MV;
av[1] = sp->tpath;
av[2] = sp->path;
av[3] = NULL;
/* And run it... */
if (run_command(_PATH_MV, av)) {
warningx("command failed: '%s %s %s', %s unchanged",
_PATH_MV, sp->tpath, sp->path, sp->path);
(void) unlink(sp->tpath);
efree(sp->tpath);
sp->tpath = NULL;
return(FALSE);
}
efree(sp->tpath);
sp->tpath = NULL;
} else {
warning("error renaming %s, %s unchanged", sp->tpath, sp->path);
(void) unlink(sp->tpath);
return(FALSE);
}
}
return(TRUE);
}
/* STUB */
void
set_fqdn()
{
return;
}
/* STUB */
void
init_envtables()
{
return;
}
/* STUB */
int
user_is_exempt()
{
return(FALSE);
}
/* STUB */
void
sudo_setspent()
{
return;
}
/* STUB */
void
sudo_endspent()
{
return;
}
char *
sudo_getepw(pw)
const struct passwd *pw;
{
return (pw->pw_passwd);
}
/*
* Assuming a parse error occurred, prompt the user for what they want
* to do now. Returns the first letter of their choice.
*/
static char
whatnow()
{
int choice, c;
for (;;) {
(void) fputs("What now? ", stdout);
choice = getchar();
for (c = choice; c != '\n' && c != EOF;)
c = getchar();
switch (choice) {
case EOF:
choice = 'x';
/* FALLTHROUGH */
case 'e':
case 'x':
case 'Q':
return(choice);
default:
(void) puts("Options are:");
(void) puts(" (e)dit sudoers file again");
(void) puts(" e(x)it without saving changes to sudoers file");
(void) puts(" (Q)uit and save changes to sudoers file (DANGER!)\n");
}
}
}
/*
* Install signal handlers for visudo.
*/
static void
setup_signals()
{
sigaction_t sa;
/*
* Setup signal handlers to cleanup nicely.
*/
zero_bytes(&sa, sizeof(sa));
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
sa.sa_handler = quit;
(void) sigaction(SIGTERM, &sa, NULL);
(void) sigaction(SIGHUP, &sa, NULL);
(void) sigaction(SIGINT, &sa, NULL);
(void) sigaction(SIGQUIT, &sa, NULL);
}
static int
run_command(path, argv)
char *path;
char **argv;
{
int status;
pid_t pid, rv;
switch (pid = fork()) {
case -1:
error(1, "unable to run %s", path);
break; /* NOTREACHED */
case 0:
sudo_endpwent();
sudo_endgrent();
closefrom(STDERR_FILENO + 1);
execv(path, argv);
warning("unable to run %s", path);
_exit(127);
break; /* NOTREACHED */
}
do {
#ifdef sudo_waitpid
rv = sudo_waitpid(pid, &status, 0);
#else
rv = wait(&status);
#endif
} while (rv == -1 && errno == EINTR);
if (rv == -1 || !WIFEXITED(status))
return(-1);
return(WEXITSTATUS(status));
}
static int
check_syntax(sudoers_path, quiet, strict)
char *sudoers_path;
int quiet;
int strict;
{
struct stat sb;
int error;
if ((yyin = fopen(sudoers_path, "r")) == NULL) {
if (!quiet)
warning("unable to open %s", sudoers_path);
exit(1);
}
init_parser(sudoers_path, quiet);
if (yyparse() && parse_error != TRUE) {
if (!quiet)
warningx("failed to parse %s file, unknown error", sudoers_path);
parse_error = TRUE;
}
error = parse_error;
if (!quiet) {
if (parse_error)
(void) printf("parse error in %s near line %d\n", sudoers_path,
errorlineno);
else
(void) printf("%s: parsed OK\n", sudoers_path);
}
/* Check mode and owner in strict mode. */
#ifdef HAVE_FSTAT
if (strict && fstat(fileno(yyin), &sb) == 0)
#else
if (strict && stat(sudoers_path, &sb) == 0)
#endif
{
if (sb.st_uid != SUDOERS_UID || sb.st_gid != SUDOERS_GID) {
error = TRUE;
if (!quiet) {
fprintf(stderr, "%s: wrong owner (uid, gid) should be (%d, %d)\n",
sudoers_path, SUDOERS_UID, SUDOERS_GID);
}
}
if ((sb.st_mode & 07777) != SUDOERS_MODE) {
error = TRUE;
if (!quiet) {
fprintf(stderr, "%s: bad permissions, should be mode 0%o\n",
sudoers_path, SUDOERS_MODE);
}
}
}
return(error);
}
/*
* Used to open (and lock) the initial sudoers file and to also open
* any subsequent files #included via a callback from the parser.
*/
FILE *
open_sudoers(path, keepopen)
const char *path;
int *keepopen;
{
struct sudoersfile *entry;
FILE *fp;
/* Check for existing entry */
tq_foreach_fwd(&sudoerslist, entry) {
if (strcmp(path, entry->path) == 0)
break;
}
if (entry == NULL) {
entry = emalloc(sizeof(*entry));
entry->path = estrdup(path);
entry->modified = 0;
entry->next = NULL;
entry->fd = open(entry->path, O_RDWR | O_CREAT, SUDOERS_MODE);
entry->tpath = NULL;
if (entry->fd == -1) {
warning("%s", entry->path);
efree(entry);
return(NULL);
}
if (!lock_file(entry->fd, SUDO_TLOCK))
errorx(1, "%s busy, try again later", entry->path);
if ((fp = fdopen(entry->fd, "r")) == NULL)
error(1, "%s", entry->path);
/* XXX - macro here? */
if (sudoerslist.last == NULL)
sudoerslist.first = sudoerslist.last = entry;
else {
sudoerslist.last->next = entry;
sudoerslist.last = entry;
}
if (keepopen != NULL)
*keepopen = TRUE;
} else {
/* Already exists, open .tmp version if there is one. */
if (entry->tpath != NULL) {
if ((fp = fopen(entry->tpath, "r")) == NULL)
error(1, "%s", entry->tpath);
} else {
if ((fp = fdopen(entry->fd, "r")) == NULL)
error(1, "%s", entry->path);
}
}
return(fp);
}
static char *
get_editor(args)
char **args;
{
char *Editor, *EditorArgs, *EditorPath, *UserEditor, *UserEditorArgs;
/*
* Check VISUAL and EDITOR environment variables to see which editor
* the user wants to use (we may not end up using it though).
* If the path is not fully-qualified, make it so and check that
* the specified executable actually exists.
*/
UserEditorArgs = NULL;
if ((UserEditor = getenv("VISUAL")) == NULL || *UserEditor == '\0')
UserEditor = getenv("EDITOR");
if (UserEditor && *UserEditor == '\0')
UserEditor = NULL;
else if (UserEditor) {
UserEditorArgs = get_args(UserEditor);
if (find_path(UserEditor, &Editor, NULL, getenv("PATH")) == FOUND) {
UserEditor = Editor;
} else {
if (def_env_editor) {
/* If we are honoring $EDITOR this is a fatal error. */
errorx(1, "specified editor (%s) doesn't exist!", UserEditor);
} else {
/* Otherwise, just ignore $EDITOR. */
UserEditor = NULL;
}
}
}
/*
* See if we can use the user's choice of editors either because
* we allow any $EDITOR or because $EDITOR is in the allowable list.
*/
Editor = EditorArgs = EditorPath = NULL;
if (def_env_editor && UserEditor) {
Editor = UserEditor;
EditorArgs = UserEditorArgs;
} else if (UserEditor) {
struct stat editor_sb;
struct stat user_editor_sb;
char *base, *userbase;
if (stat(UserEditor, &user_editor_sb) != 0) {
/* Should never happen since we already checked above. */
error(1, "unable to stat editor (%s)", UserEditor);
}
EditorPath = estrdup(def_editor);
Editor = strtok(EditorPath, ":");
do {
EditorArgs = get_args(Editor);
/*
* Both Editor and UserEditor should be fully qualified but
* check anyway...
*/
if ((base = strrchr(Editor, '/')) == NULL)
continue;
if ((userbase = strrchr(UserEditor, '/')) == NULL) {
Editor = NULL;
break;
}
base++, userbase++;
/*
* We compare the basenames first and then use stat to match
* for sure.
*/
if (strcmp(base, userbase) == 0) {
if (stat(Editor, &editor_sb) == 0 && S_ISREG(editor_sb.st_mode)
&& (editor_sb.st_mode & 0000111) &&
editor_sb.st_dev == user_editor_sb.st_dev &&
editor_sb.st_ino == user_editor_sb.st_ino)
break;
}
} while ((Editor = strtok(NULL, ":")));
}
/*
* Can't use $EDITOR, try each element of def_editor until we
* find one that exists, is regular, and is executable.
*/
if (Editor == NULL || *Editor == '\0') {
efree(EditorPath);
EditorPath = estrdup(def_editor);
Editor = strtok(EditorPath, ":");
do {
EditorArgs = get_args(Editor);
if (sudo_goodpath(Editor, NULL))
break;
} while ((Editor = strtok(NULL, ":")));
/* Bleah, none of the editors existed! */
if (Editor == NULL || *Editor == '\0')
errorx(1, "no editor found (editor path = %s)", def_editor);
}
*args = EditorArgs;
return(Editor);
}
/*
* Split out any command line arguments and return them.
*/
static char *
get_args(cmnd)
char *cmnd;
{
char *args;
args = cmnd;
while (*args && !isblank((unsigned char) *args))
args++;
if (*args) {
*args++ = '\0';
while (*args && isblank((unsigned char) *args))
args++;
}
return(*args ? args : NULL);
}
/*
* Iterate through the sudoers datastructures looking for undefined
* aliases or unused aliases.
*/
static int
check_aliases(strict)
int strict;
{
struct cmndspec *cs;
struct member *m;
struct privilege *priv;
struct userspec *us;
int error = 0;
/* Forward check. */
tq_foreach_fwd(&userspecs, us) {
tq_foreach_fwd(&us->users, m) {
if (m->type == ALIAS) {
alias_seqno++;
if (find_alias(m->name, USERALIAS) == NULL) {
warningx("%s: User_Alias `%s' referenced but not defined",
strict ? "Error" : "Warning", m->name);
error++;
}
}
}
tq_foreach_fwd(&us->privileges, priv) {
tq_foreach_fwd(&priv->hostlist, m) {
if (m->type == ALIAS) {
alias_seqno++;
if (find_alias(m->name, HOSTALIAS) == NULL) {
warningx("%s: Host_Alias `%s' referenced but not defined",
strict ? "Error" : "Warning", m->name);
error++;
}
}
}
tq_foreach_fwd(&priv->cmndlist, cs) {
tq_foreach_fwd(&cs->runasuserlist, m) {
if (m->type == ALIAS) {
alias_seqno++;
if (find_alias(m->name, RUNASALIAS) == NULL) {
warningx("%s: Runas_Alias `%s' referenced but not defined",
strict ? "Error" : "Warning", m->name);
error++;
}
}
}
if ((m = cs->cmnd)->type == ALIAS) {
alias_seqno++;
if (find_alias(m->name, CMNDALIAS) == NULL) {
warningx("%s: Cmnd_Alias `%s' referenced but not defined",
strict ? "Error" : "Warning", m->name);
error++;
}
}
}
}
}
/* Reverse check (destructive) */
tq_foreach_fwd(&userspecs, us) {
tq_foreach_fwd(&us->users, m) {
if (m->type == ALIAS)
(void) alias_remove(m->name, USERALIAS);
}
tq_foreach_fwd(&us->privileges, priv) {
tq_foreach_fwd(&priv->hostlist, m) {
if (m->type == ALIAS)
(void) alias_remove(m->name, HOSTALIAS);
}
tq_foreach_fwd(&priv->cmndlist, cs) {
tq_foreach_fwd(&cs->runasuserlist, m) {
if (m->type == ALIAS)
(void) alias_remove(m->name, RUNASALIAS);
}
if ((m = cs->cmnd)->type == ALIAS)
(void) alias_remove(m->name, CMNDALIAS);
}
}
}
/* If all aliases were referenced we will have an empty tree. */
if (no_aliases())
return(0);
alias_apply(print_unused, strict ? "Error" : "Warning");
return (strict ? 1 : 0);
}
static int
print_unused(v1, v2)
void *v1;
void *v2;
{
struct alias *a = (struct alias *)v1;
char *prefix = (char *)v2;
warningx("%s: unused %s_Alias %s", prefix,
a->type == HOSTALIAS ? "Host" : a->type == CMNDALIAS ? "Cmnd" :
a->type == USERALIAS ? "User" : a->type == RUNASALIAS ? "Runas" :
"Unknown", a->name);
return(0);
}
/*
* Unlink any sudoers temp files that remain.
*/
void
cleanup(gotsignal)
int gotsignal;
{
struct sudoersfile *sp;
tq_foreach_fwd(&sudoerslist, sp) {
if (sp->tpath != NULL)
(void) unlink(sp->tpath);
}
if (!gotsignal) {
sudo_endpwent();
sudo_endgrent();
}
}
/*
* Unlink sudoers temp files (if any) and exit.
*/
static RETSIGTYPE
quit(signo)
int signo;
{
cleanup(signo);
#define emsg " exiting due to signal.\n"
write(STDERR_FILENO, getprogname(), strlen(getprogname()));
write(STDERR_FILENO, emsg, sizeof(emsg) - 1);
_exit(signo);
}
static void
usage()
{
(void) fprintf(stderr, "usage: %s [-c] [-q] [-s] [-V] [-f sudoers]\n",
getprogname());
exit(1);
}
|