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