update init.d to clean new state location /var/lib/sudo, prepare to upload
[debian/sudo] / sudo_edit.c
1 /*
2  * Copyright (c) 2004-2008 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
17 #include <config.h>
18
19 #include <sys/types.h>
20 #include <sys/param.h>
21 #include <sys/stat.h>
22 #include <sys/time.h>
23 #include <sys/wait.h>
24 #include <sys/socket.h>
25 #include <stdio.h>
26 #ifdef STDC_HEADERS
27 # include <stdlib.h>
28 # include <stddef.h>
29 #else
30 # ifdef HAVE_STDLIB_H
31 #  include <stdlib.h>
32 # endif
33 #endif /* STDC_HEADERS */
34 #ifdef HAVE_STRING_H
35 # include <string.h>
36 #else
37 # ifdef HAVE_STRINGS_H
38 #  include <strings.h>
39 # endif
40 #endif /* HAVE_STRING_H */
41 #ifdef HAVE_UNISTD_H
42 # include <unistd.h>
43 #endif /* HAVE_UNISTD_H */
44 #include <ctype.h>
45 #include <pwd.h>
46 #include <signal.h>
47 #include <errno.h>
48 #include <fcntl.h>
49 #if TIME_WITH_SYS_TIME
50 # include <time.h>
51 #endif
52 #ifndef HAVE_TIMESPEC
53 # include <emul/timespec.h>
54 #endif
55
56 #include "sudo.h"
57
58 extern sigaction_t saved_sa_int, saved_sa_quit, saved_sa_tstp;
59 extern char **environ;
60
61 static char *find_editor();
62
63 /*
64  * Wrapper to allow users to edit privileged files with their own uid.
65  */
66 int
67 sudo_edit(argc, argv, envp)
68     int argc;
69     char **argv;
70     char **envp;
71 {
72     ssize_t nread, nwritten;
73     pid_t kidpid, pid;
74     const char *tmpdir;
75     char **nargv, **ap, *editor, *cp;
76     char buf[BUFSIZ];
77     int error, i, ac, ofd, tfd, nargc, rval, tmplen, wasblank;
78     struct stat sb;
79     struct timespec ts1, ts2;
80     struct tempfile {
81         char *tfile;
82         char *ofile;
83         struct timespec omtim;
84         off_t osize;
85     } *tf;
86
87     /*
88      * Find our temporary directory, one of /var/tmp, /usr/tmp, or /tmp
89      */
90     if (stat(_PATH_VARTMP, &sb) == 0 && S_ISDIR(sb.st_mode))
91         tmpdir = _PATH_VARTMP;
92 #ifdef _PATH_USRTMP
93     else if (stat(_PATH_USRTMP, &sb) == 0 && S_ISDIR(sb.st_mode))
94         tmpdir = _PATH_USRTMP;
95 #endif
96     else
97         tmpdir = _PATH_TMP;
98     tmplen = strlen(tmpdir);
99     while (tmplen > 0 && tmpdir[tmplen - 1] == '/')
100         tmplen--;
101
102     /*
103      * Close password, shadow, and group files before we try to open
104      * user-specified files to prevent the opening of things like /dev/fd/4
105      */
106     sudo_endpwent();
107     sudo_endgrent();
108
109     /*
110      * For each file specified by the user, make a temporary version
111      * and copy the contents of the original to it.
112      */
113     tf = emalloc2(argc - 1, sizeof(*tf));
114     zero_bytes(tf, (argc - 1) * sizeof(*tf));
115     for (i = 0, ap = argv + 1; i < argc - 1 && *ap != NULL; i++, ap++) {
116         error = -1;
117         set_perms(PERM_RUNAS);
118         if ((ofd = open(*ap, O_RDONLY, 0644)) != -1 || errno == ENOENT) {
119             if (ofd == -1) {
120                 zero_bytes(&sb, sizeof(sb));            /* new file */
121                 error = 0;
122             } else {
123 #ifdef HAVE_FSTAT
124                 error = fstat(ofd, &sb);
125 #else
126                 error = stat(tf[i].ofile, &sb);
127 #endif
128             }
129         }
130         set_perms(PERM_ROOT);
131         if (error || (ofd != -1 && !S_ISREG(sb.st_mode))) {
132             if (error)
133                 warning("%s", *ap);
134             else
135                 warningx("%s: not a regular file", *ap);
136             if (ofd != -1)
137                 close(ofd);
138             argc--;
139             i--;
140             continue;
141         }
142         tf[i].ofile = *ap;
143         tf[i].omtim.tv_sec = mtim_getsec(sb);
144         tf[i].omtim.tv_nsec = mtim_getnsec(sb);
145         tf[i].osize = sb.st_size;
146         if ((cp = strrchr(tf[i].ofile, '/')) != NULL)
147             cp++;
148         else
149             cp = tf[i].ofile;
150         easprintf(&tf[i].tfile, "%.*s/%s.XXXXXXXX", tmplen, tmpdir, cp);
151         set_perms(PERM_USER);
152         tfd = mkstemp(tf[i].tfile);
153         set_perms(PERM_ROOT);
154         if (tfd == -1) {
155             warning("mkstemp");
156             goto cleanup;
157         }
158         if (ofd != -1) {
159             while ((nread = read(ofd, buf, sizeof(buf))) != 0) {
160                 if ((nwritten = write(tfd, buf, nread)) != nread) {
161                     if (nwritten == -1)
162                         warning("%s", tf[i].tfile);
163                     else
164                         warningx("%s: short write", tf[i].tfile);
165                     goto cleanup;
166                 }
167             }
168             close(ofd);
169         }
170         /*
171          * We always update the stashed mtime because the time
172          * resolution of the filesystem the temporary file is on may
173          * not match that of the filesystem where the file to be edited
174          * resides.  It is OK if touch() fails since we only use the info
175          * to determine whether or not a file has been modified.
176          */
177         (void) touch(tfd, NULL, &tf[i].omtim);
178 #ifdef HAVE_FSTAT
179         error = fstat(tfd, &sb);
180 #else
181         error = stat(tf[i].tfile, &sb);
182 #endif
183         if (!error) {
184             tf[i].omtim.tv_sec = mtim_getsec(sb);
185             tf[i].omtim.tv_nsec = mtim_getnsec(sb);
186         }
187         close(tfd);
188     }
189     if (argc == 1)
190         return(1);                      /* no files readable, you lose */
191
192     environ = envp;
193     editor = find_editor();
194
195     /*
196      * Allocate space for the new argument vector and fill it in.
197      * The EDITOR and VISUAL environment variables may contain command
198      * line args so look for those and alloc space for them too.
199      */
200     nargc = argc;
201     for (wasblank = FALSE, cp = editor; *cp != '\0'; cp++) {
202         if (isblank((unsigned char) *cp))
203             wasblank = TRUE;
204         else if (wasblank) {
205             wasblank = FALSE;
206             nargc++;
207         }
208     }
209     nargv = (char **) emalloc2(nargc + 1, sizeof(char *));
210     ac = 0;
211     for ((cp = strtok(editor, " \t")); cp != NULL; (cp = strtok(NULL, " \t")))
212         nargv[ac++] = cp;
213     for (i = 0; i < argc - 1 && ac < nargc; )
214         nargv[ac++] = tf[i++].tfile;
215     nargv[ac] = NULL;
216
217     /* Allow the editor to be suspended. */
218     (void) sigaction(SIGTSTP, &saved_sa_tstp, NULL);
219
220     /*
221      * Fork and exec the editor with the invoking user's creds,
222      * keeping track of the time spent in the editor.
223      */
224     gettime(&ts1);
225     kidpid = fork();
226     if (kidpid == -1) {
227         warning("fork");
228         goto cleanup;
229     } else if (kidpid == 0) {
230         /* child */
231         (void) sigaction(SIGINT, &saved_sa_int, NULL);
232         (void) sigaction(SIGQUIT, &saved_sa_quit, NULL);
233         set_perms(PERM_FULL_USER);
234         closefrom(def_closefrom);
235         execvp(nargv[0], nargv);
236         warning("unable to execute %s", nargv[0]);
237         _exit(127);
238     }
239
240     /*
241      * Wait for status from the child.  Most modern kernels
242      * will not let an unprivileged child process send a
243      * signal to its privileged parent so we have to request
244      * status when the child is stopped and then send the
245      * same signal to our own pid.
246      */
247     do {
248 #ifdef sudo_waitpid
249         pid = sudo_waitpid(kidpid, &i, WUNTRACED);
250 #else
251         pid = wait(&i);
252 #endif
253         if (pid == kidpid) {
254             if (WIFSTOPPED(i))
255                 kill(getpid(), WSTOPSIG(i));
256             else
257                 break;
258         }
259     } while (pid != -1 || errno == EINTR);
260     gettime(&ts2);
261     if (pid == -1 || !WIFEXITED(i))
262         rval = 1;
263     else
264         rval = WEXITSTATUS(i);
265
266     /* Copy contents of temp files to real ones */
267     for (i = 0; i < argc - 1; i++) {
268         error = -1;
269         set_perms(PERM_USER);
270         if ((tfd = open(tf[i].tfile, O_RDONLY, 0644)) != -1) {
271 #ifdef HAVE_FSTAT
272             error = fstat(tfd, &sb);
273 #else
274             error = stat(tf[i].tfile, &sb);
275 #endif
276         }
277         set_perms(PERM_ROOT);
278         if (error || !S_ISREG(sb.st_mode)) {
279             if (error)
280                 warning("%s", tf[i].tfile);
281             else
282                 warningx("%s: not a regular file", tf[i].tfile);
283             warningx("%s left unmodified", tf[i].ofile);
284             if (tfd != -1)
285                 close(tfd);
286             continue;
287         }
288         if (tf[i].osize == sb.st_size && tf[i].omtim.tv_sec == mtim_getsec(sb)
289             && tf[i].omtim.tv_nsec == mtim_getnsec(sb)) {
290             /*
291              * If mtime and size match but the user spent no measurable
292              * time in the editor we can't tell if the file was changed.
293              */
294 #ifdef HAVE_TIMESPECSUB2
295             timespecsub(&ts1, &ts2);
296 #else
297             timespecsub(&ts1, &ts2, &ts2);
298 #endif
299             if (timespecisset(&ts2)) {
300                 warningx("%s unchanged", tf[i].ofile);
301                 unlink(tf[i].tfile);
302                 close(tfd);
303                 continue;
304             }
305         }
306         set_perms(PERM_RUNAS);
307         ofd = open(tf[i].ofile, O_WRONLY|O_TRUNC|O_CREAT, 0644);
308         set_perms(PERM_ROOT);
309         if (ofd == -1) {
310             warning("unable to write to %s", tf[i].ofile);
311             warningx("contents of edit session left in %s", tf[i].tfile);
312             close(tfd);
313             continue;
314         }
315         while ((nread = read(tfd, buf, sizeof(buf))) > 0) {
316             if ((nwritten = write(ofd, buf, nread)) != nread) {
317                 if (nwritten == -1)
318                     warning("%s", tf[i].ofile);
319                 else
320                     warningx("%s: short write", tf[i].ofile);
321                 break;
322             }
323         }
324         if (nread == 0) {
325             /* success, got EOF */
326             unlink(tf[i].tfile);
327         } else if (nread < 0) {
328             warning("unable to read temporary file");
329             warningx("contents of edit session left in %s", tf[i].tfile);
330         } else {
331             warning("unable to write to %s", tf[i].ofile);
332             warningx("contents of edit session left in %s", tf[i].tfile);
333         }
334         close(ofd);
335     }
336
337     return(rval);
338 cleanup:
339     /* Clean up temp files and return. */
340     for (i = 0; i < argc - 1; i++) {
341         if (tf[i].tfile != NULL)
342             unlink(tf[i].tfile);
343     }
344     return(1);
345 }
346
347 /*
348  * Determine which editor to use.  We don't bother restricting this
349  * based on def_env_editor or def_editor since the editor runs with
350  * the uid of the invoking user, not the runas (privileged) user.
351  */
352 static char *
353 find_editor()
354 {
355     char *cp, *editor = NULL, **ev, *ev0[4];
356
357     ev0[0] = "SUDO_EDITOR";
358     ev0[1] = "VISUAL";
359     ev0[2] = "EDITOR";
360     ev0[3] = NULL;
361     for (ev = ev0; *ev != NULL; ev++) {
362         if ((editor = getenv(*ev)) != NULL && *editor != '\0') {
363             if ((cp = strrchr(editor, '/')) != NULL)
364                 cp++;
365             else
366                 cp = editor;
367             /* Ignore "sudoedit" and "sudo" to avoid an endless loop. */
368             if (strncmp(cp, "sudo", 4) != 0 ||
369                 (cp[4] != ' ' && cp[4] != '\0' && strcmp(cp + 4, "edit") != 0)) {
370                 editor = estrdup(editor);
371                 break;
372             }
373         }
374         editor = NULL;
375     }
376     if (editor == NULL) {
377         editor = estrdup(def_editor);
378         if ((cp = strchr(editor, ':')) != NULL)
379             *cp = '\0';                 /* def_editor could be a path */
380     }
381     return(editor);
382 }