fix typo in changelog
[debian/sudo] / check.c
1 /*
2  * Copyright (c) 1993-1996,1998-2005 Todd C. Miller <Todd.Miller@courtesan.com>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  *
16  * Sponsored in part by the Defense Advanced Research Projects
17  * Agency (DARPA) and Air Force Research Laboratory, Air Force
18  * Materiel Command, USAF, under agreement number F39502-99-1-0512.
19  */
20
21 #include <config.h>
22
23 #include <sys/types.h>
24 #include <sys/param.h>
25 #include <sys/stat.h>
26 #ifndef __TANDEM
27 # include <sys/file.h>
28 #endif
29 #include <stdio.h>
30 #ifdef STDC_HEADERS
31 # include <stdlib.h>
32 # include <stddef.h>
33 #else
34 # ifdef HAVE_STDLIB_H
35 #  include <stdlib.h>
36 # endif
37 #endif /* STDC_HEADERS */
38 #ifdef HAVE_STRING_H
39 # include <string.h>
40 #else
41 # ifdef HAVE_STRINGS_H
42 #  include <strings.h>
43 # endif
44 #endif /* HAVE_STRING_H */
45 #ifdef HAVE_UNISTD_H
46 # include <unistd.h>
47 #endif /* HAVE_UNISTD_H */
48 #ifdef HAVE_ERR_H
49 # include <err.h>
50 #else
51 # include "emul/err.h"
52 #endif /* HAVE_ERR_H */
53 #include <errno.h>
54 #include <fcntl.h>
55 #include <signal.h>
56 #include <time.h>
57 #include <pwd.h>
58 #include <grp.h>
59 #ifndef HAVE_TIMESPEC
60 # include <emul/timespec.h>
61 #endif
62
63 #include "sudo.h"
64
65 #ifndef lint
66 __unused static const char rcsid[] = "$Sudo: check.c,v 1.223.2.10 2008/01/05 23:59:42 millert Exp $";
67 #endif /* lint */
68
69 /* Status codes for timestamp_status() */
70 #define TS_CURRENT              0
71 #define TS_OLD                  1
72 #define TS_MISSING              2
73 #define TS_NOFILE               3
74 #define TS_ERROR                4
75
76 /* Flags for timestamp_status() */
77 #define TS_MAKE_DIRS            1
78 #define TS_REMOVE               2
79
80 static void  build_timestamp    __P((char **, char **));
81 static int   timestamp_status   __P((char *, char *, char *, int));
82 static char *expand_prompt      __P((char *, char *, char *));
83 static void  lecture            __P((int));
84 static void  update_timestamp   __P((char *, char *));
85
86 /*
87  * This function only returns if the user can successfully
88  * verify who he/she is.
89  */
90 void
91 check_user(validated)
92     int validated;
93 {
94     char *timestampdir = NULL;
95     char *timestampfile = NULL;
96     char *prompt;
97     int status;
98
99     if (user_uid == 0 || user_uid == runas_pw->pw_uid || user_is_exempt())
100         return;
101
102     build_timestamp(&timestampdir, &timestampfile);
103     status = timestamp_status(timestampdir, timestampfile, user_name,
104         TS_MAKE_DIRS);
105     if (status != TS_CURRENT || ISSET(validated, FLAG_CHECK_USER)) {
106         lecture(status);
107
108         /* Expand any escapes in the prompt. */
109         prompt = expand_prompt(user_prompt ? user_prompt : def_passprompt,
110             user_name, user_shost);
111
112         verify_user(auth_pw, prompt);
113     }
114     /* Only update timestamp if user was validated. */
115     if (status != TS_ERROR && ISSET(validated, VALIDATE_OK))
116         update_timestamp(timestampdir, timestampfile);
117     efree(timestampdir);
118     efree(timestampfile);
119 }
120
121 /*
122  * Standard sudo lecture.
123  * TODO: allow the user to specify a file name instead.
124  */
125 static void
126 lecture(status)
127     int status;
128 {
129     FILE *fp;
130     char buf[BUFSIZ];
131     ssize_t nread;
132
133     if (def_lecture == never ||
134         (def_lecture == once && status != TS_MISSING && status != TS_ERROR))
135         return;
136
137     if (def_lecture_file && (fp = fopen(def_lecture_file, "r")) != NULL) {
138         while ((nread = fread(buf, sizeof(char), sizeof(buf), fp)) != 0)
139             fwrite(buf, nread, 1, stderr);
140         fclose(fp);
141     } else {
142         (void) fputs("\n\
143 We trust you have received the usual lecture from the local System\n\
144 Administrator. It usually boils down to these three things:\n\
145 \n\
146     #1) Respect the privacy of others.\n\
147     #2) Think before you type.\n\
148     #3) With great power comes great responsibility.\n\n",
149     stderr);
150     }
151 }
152
153 /*
154  * Update the time on the timestamp file/dir or create it if necessary.
155  */
156 static void
157 update_timestamp(timestampdir, timestampfile)
158     char *timestampdir;
159     char *timestampfile;
160 {
161     if (timestamp_uid != 0)
162         set_perms(PERM_TIMESTAMP);
163     if (touch(-1, timestampfile ? timestampfile : timestampdir, NULL) == -1) {
164         if (timestampfile) {
165             int fd = open(timestampfile, O_WRONLY|O_CREAT|O_TRUNC, 0600);
166
167             if (fd == -1)
168                 log_error(NO_EXIT|USE_ERRNO, "Can't open %s", timestampfile);
169             else
170                 close(fd);
171         } else {
172             if (mkdir(timestampdir, 0700) == -1)
173                 log_error(NO_EXIT|USE_ERRNO, "Can't mkdir %s", timestampdir);
174         }
175     }
176     if (timestamp_uid != 0)
177         set_perms(PERM_ROOT);
178 }
179
180 /*
181  * Expand %h and %u escapes in the prompt and pass back the dynamically
182  * allocated result.  Returns the same string if there are no escapes.
183  */
184 static char *
185 expand_prompt(old_prompt, user, host)
186     char *old_prompt;
187     char *user;
188     char *host;
189 {
190     size_t len, n;
191     int subst;
192     char *p, *np, *new_prompt, *endp;
193
194     /* How much space do we need to malloc for the prompt? */
195     subst = 0;
196     for (p = old_prompt, len = strlen(old_prompt); *p; p++) {
197         if (p[0] =='%') {
198             switch (p[1]) {
199                 case 'h':
200                     p++;
201                     len += strlen(user_shost) - 2;
202                     subst = 1;
203                     break;
204                 case 'H':
205                     p++;
206                     len += strlen(user_host) - 2;
207                     subst = 1;
208                     break;
209                 case 'p':
210                     p++;
211                     if (def_rootpw)
212                             len += 2;
213                     else if (def_targetpw || def_runaspw)
214                             len += strlen(*user_runas) - 2;
215                     else
216                             len += strlen(user_name) - 2;
217                     subst = 1;
218                     break;
219                 case 'u':
220                     p++;
221                     len += strlen(user_name) - 2;
222                     subst = 1;
223                     break;
224                 case 'U':
225                     p++;
226                     len += strlen(*user_runas) - 2;
227                     subst = 1;
228                     break;
229                 case '%':
230                     p++;
231                     len--;
232                     subst = 1;
233                     break;
234                 default:
235                     break;
236             }
237         }
238     }
239
240     if (subst) {
241         new_prompt = (char *) emalloc(++len);
242         endp = new_prompt + len;
243         for (p = old_prompt, np = new_prompt; *p; p++) {
244             if (p[0] =='%') {
245                 switch (p[1]) {
246                     case 'h':
247                         p++;
248                         n = strlcpy(np, user_shost, np - endp);
249                         if (n >= np - endp)
250                             goto oflow;
251                         np += n;
252                         continue;
253                     case 'H':
254                         p++;
255                         n = strlcpy(np, user_host, np - endp);
256                         if (n >= np - endp)
257                             goto oflow;
258                         np += n;
259                         continue;
260                     case 'p':
261                         p++;
262                         if (def_rootpw)
263                                 n = strlcpy(np, "root", np - endp);
264                         else if (def_targetpw || def_runaspw)
265                                 n = strlcpy(np, *user_runas, np - endp);
266                         else
267                                 n = strlcpy(np, user_name, np - endp);
268                         if (n >= np - endp)
269                                 goto oflow;
270                         np += n;
271                         continue;
272                     case 'u':
273                         p++;
274                         n = strlcpy(np, user_name, np - endp);
275                         if (n >= np - endp)
276                             goto oflow;
277                         np += n;
278                         continue;
279                     case 'U':
280                         p++;
281                         n = strlcpy(np,  *user_runas, np - endp);
282                         if (n >= np - endp)
283                             goto oflow;
284                         np += n;
285                         continue;
286                     case '%':
287                         /* convert %% -> % */
288                         p++;
289                         break;
290                     default:
291                         /* no conversion */
292                         break;
293                 }
294             }
295             *np++ = *p;
296             if (np >= endp)
297                 goto oflow;
298         }
299         *np = '\0';
300     } else
301         new_prompt = old_prompt;
302
303     return(new_prompt);
304
305 oflow:
306     /* We pre-allocate enough space, so this should never happen. */
307     errx(1, "internal error, expand_prompt() overflow");
308 }
309
310 /*
311  * Checks if the user is exempt from supplying a password.
312  */
313 int
314 user_is_exempt()
315 {
316     struct group *grp;
317     char **gr_mem;
318
319     if (!def_exempt_group)
320         return(FALSE);
321
322     if (!(grp = getgrnam(def_exempt_group)))
323         return(FALSE);
324
325     if (user_gid == grp->gr_gid)
326         return(TRUE);
327
328     for (gr_mem = grp->gr_mem; *gr_mem; gr_mem++) {
329         if (strcmp(user_name, *gr_mem) == 0)
330             return(TRUE);
331     }
332
333     return(FALSE);
334 }
335
336 /*
337  * Fills in timestampdir as well as timestampfile if using tty tickets.
338  */
339 static void
340 build_timestamp(timestampdir, timestampfile)
341     char **timestampdir;
342     char **timestampfile;
343 {
344     char *dirparent;
345     int len;
346
347     dirparent = def_timestampdir;
348     len = easprintf(timestampdir, "%s/%s", dirparent, user_name);
349     if (len >= PATH_MAX)
350         log_error(0, "timestamp path too long: %s", *timestampdir);
351
352     /*
353      * Timestamp file may be a file in the directory or NUL to use
354      * the directory as the timestamp.
355      */
356     if (def_tty_tickets) {
357         char *p;
358
359         if ((p = strrchr(user_tty, '/')))
360             p++;
361         else
362             p = user_tty;
363         if (def_targetpw)
364             len = easprintf(timestampfile, "%s/%s/%s:%s", dirparent, user_name,
365                 p, *user_runas);
366         else
367             len = easprintf(timestampfile, "%s/%s/%s", dirparent, user_name, p);
368         if (len >= PATH_MAX)
369             log_error(0, "timestamp path too long: %s", *timestampfile);
370     } else if (def_targetpw) {
371         len = easprintf(timestampfile, "%s/%s/%s", dirparent, user_name,
372             *user_runas);
373         if (len >= PATH_MAX)
374             log_error(0, "timestamp path too long: %s", *timestampfile);
375     } else
376         *timestampfile = NULL;
377 }
378
379 /*
380  * Check the timestamp file and directory and return their status.
381  */
382 static int
383 timestamp_status(timestampdir, timestampfile, user, flags)
384     char *timestampdir;
385     char *timestampfile;
386     char *user;
387     int flags;
388 {
389     struct stat sb;
390     time_t now;
391     char *dirparent = def_timestampdir;
392     int status = TS_ERROR;              /* assume the worst */
393
394     if (timestamp_uid != 0)
395         set_perms(PERM_TIMESTAMP);
396
397     /*
398      * Sanity check dirparent and make it if it doesn't already exist.
399      * We start out assuming the worst (that the dir is not sane) and
400      * if it is ok upgrade the status to ``no timestamp file''.
401      * Note that we don't check the parent(s) of dirparent for
402      * sanity since the sudo dir is often just located in /tmp.
403      */
404     if (lstat(dirparent, &sb) == 0) {
405         if (!S_ISDIR(sb.st_mode))
406             log_error(NO_EXIT, "%s exists but is not a directory (0%o)",
407                 dirparent, (unsigned int) sb.st_mode);
408         else if (sb.st_uid != timestamp_uid)
409             log_error(NO_EXIT, "%s owned by uid %lu, should be uid %lu",
410                 dirparent, (unsigned long) sb.st_uid,
411                 (unsigned long) timestamp_uid);
412         else if ((sb.st_mode & 0000022))
413             log_error(NO_EXIT,
414                 "%s writable by non-owner (0%o), should be mode 0700",
415                 dirparent, (unsigned int) sb.st_mode);
416         else {
417             if ((sb.st_mode & 0000777) != 0700)
418                 (void) chmod(dirparent, 0700);
419             status = TS_MISSING;
420         }
421     } else if (errno != ENOENT) {
422         log_error(NO_EXIT|USE_ERRNO, "can't stat %s", dirparent);
423     } else {
424         /* No dirparent, try to make one. */
425         if (ISSET(flags, TS_MAKE_DIRS)) {
426             if (mkdir(dirparent, S_IRWXU))
427                 log_error(NO_EXIT|USE_ERRNO, "can't mkdir %s",
428                     dirparent);
429             else
430                 status = TS_MISSING;
431         }
432     }
433     if (status == TS_ERROR) {
434         if (timestamp_uid != 0)
435             set_perms(PERM_ROOT);
436         return(status);
437     }
438
439     /*
440      * Sanity check the user's ticket dir.  We start by downgrading
441      * the status to TS_ERROR.  If the ticket dir exists and is sane
442      * this will be upgraded to TS_OLD.  If the dir does not exist,
443      * it will be upgraded to TS_MISSING.
444      */
445     status = TS_ERROR;                  /* downgrade status again */
446     if (lstat(timestampdir, &sb) == 0) {
447         if (!S_ISDIR(sb.st_mode)) {
448             if (S_ISREG(sb.st_mode)) {
449                 /* convert from old style */
450                 if (unlink(timestampdir) == 0)
451                     status = TS_MISSING;
452             } else
453                 log_error(NO_EXIT, "%s exists but is not a directory (0%o)",
454                     timestampdir, (unsigned int) sb.st_mode);
455         } else if (sb.st_uid != timestamp_uid)
456             log_error(NO_EXIT, "%s owned by uid %lu, should be uid %lu",
457                 timestampdir, (unsigned long) sb.st_uid,
458                 (unsigned long) timestamp_uid);
459         else if ((sb.st_mode & 0000022))
460             log_error(NO_EXIT,
461                 "%s writable by non-owner (0%o), should be mode 0700",
462                 timestampdir, (unsigned int) sb.st_mode);
463         else {
464             if ((sb.st_mode & 0000777) != 0700)
465                 (void) chmod(timestampdir, 0700);
466             status = TS_OLD;            /* do date check later */
467         }
468     } else if (errno != ENOENT) {
469         log_error(NO_EXIT|USE_ERRNO, "can't stat %s", timestampdir);
470     } else
471         status = TS_MISSING;
472
473     /*
474      * If there is no user ticket dir, AND we are in tty ticket mode,
475      * AND the TS_MAKE_DIRS flag is set, create the user ticket dir.
476      */
477     if (status == TS_MISSING && timestampfile && ISSET(flags, TS_MAKE_DIRS)) {
478         if (mkdir(timestampdir, S_IRWXU) == -1) {
479             status = TS_ERROR;
480             log_error(NO_EXIT|USE_ERRNO, "can't mkdir %s", timestampdir);
481         }
482     }
483
484     /*
485      * Sanity check the tty ticket file if it exists.
486      */
487     if (timestampfile && status != TS_ERROR) {
488         if (status != TS_MISSING)
489             status = TS_NOFILE;                 /* dir there, file missing */
490         if (lstat(timestampfile, &sb) == 0) {
491             if (!S_ISREG(sb.st_mode)) {
492                 status = TS_ERROR;
493                 log_error(NO_EXIT, "%s exists but is not a regular file (0%o)",
494                     timestampfile, (unsigned int) sb.st_mode);
495             } else {
496                 /* If bad uid or file mode, complain and kill the bogus file. */
497                 if (sb.st_uid != timestamp_uid) {
498                     log_error(NO_EXIT,
499                         "%s owned by uid %lu, should be uid %lu",
500                         timestampfile, (unsigned long) sb.st_uid,
501                         (unsigned long) timestamp_uid);
502                     (void) unlink(timestampfile);
503                 } else if ((sb.st_mode & 0000022)) {
504                     log_error(NO_EXIT,
505                         "%s writable by non-owner (0%o), should be mode 0600",
506                         timestampfile, (unsigned int) sb.st_mode);
507                     (void) unlink(timestampfile);
508                 } else {
509                     /* If not mode 0600, fix it. */
510                     if ((sb.st_mode & 0000777) != 0600)
511                         (void) chmod(timestampfile, 0600);
512
513                     status = TS_OLD;    /* actually check mtime below */
514                 }
515             }
516         } else if (errno != ENOENT) {
517             log_error(NO_EXIT|USE_ERRNO, "can't stat %s", timestampfile);
518             status = TS_ERROR;
519         }
520     }
521
522     /*
523      * If the file/dir exists and we are not removing it, check its mtime.
524      */
525     if (status == TS_OLD && !ISSET(flags, TS_REMOVE)) {
526         /* Negative timeouts only expire manually (sudo -k). */
527         if (def_timestamp_timeout < 0 && sb.st_mtime != 0)
528             status = TS_CURRENT;
529         else {
530             /* XXX - should use timespec here */
531             now = time(NULL);
532             if (def_timestamp_timeout &&
533                 now - sb.st_mtime < 60 * def_timestamp_timeout) {
534                 /*
535                  * Check for bogus time on the stampfile.  The clock may
536                  * have been set back or someone could be trying to spoof us.
537                  */
538                 if (sb.st_mtime > now + 60 * def_timestamp_timeout * 2) {
539                     log_error(NO_EXIT,
540                         "timestamp too far in the future: %20.20s",
541                         4 + ctime(&sb.st_mtime));
542                     if (timestampfile)
543                         (void) unlink(timestampfile);
544                     else
545                         (void) rmdir(timestampdir);
546                     status = TS_MISSING;
547                 } else
548                     status = TS_CURRENT;
549             }
550         }
551     }
552
553     if (timestamp_uid != 0)
554         set_perms(PERM_ROOT);
555     return(status);
556 }
557
558 /*
559  * Remove the timestamp ticket file/dir.
560  */
561 void
562 remove_timestamp(remove)
563     int remove;
564 {
565     struct timespec ts;
566     char *timestampdir, *timestampfile, *path;
567     int status;
568
569     build_timestamp(&timestampdir, &timestampfile);
570     status = timestamp_status(timestampdir, timestampfile, user_name,
571         TS_REMOVE);
572     if (status == TS_OLD || status == TS_CURRENT) {
573         path = timestampfile ? timestampfile : timestampdir;
574         if (remove) {
575             if (timestampfile)
576                 status = unlink(timestampfile);
577             else
578                 status = rmdir(timestampdir);
579             if (status == -1 && errno != ENOENT) {
580                 log_error(NO_EXIT, "can't remove %s (%s), will reset to Epoch",
581                     path, strerror(errno));
582                 remove = FALSE;
583             }
584         } else {
585             timespecclear(&ts);
586             if (touch(-1, path, &ts) == -1)
587                 err(1, "can't reset %s to Epoch", path);
588         }
589     }
590
591     efree(timestampdir);
592     efree(timestampfile);
593 }