Merge commit 'upstream/1.8.1p2'
[debian/sudo] / src / sudo_edit.c
1 /*
2  * Copyright (c) 2004-2008, 2010-2011 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 #if defined(HAVE_SETRESUID) || defined(HAVE_SETREUID) || defined(HAVE_SETEUID)
20
21 #include <sys/types.h>
22 #include <sys/param.h>
23 #include <sys/stat.h>
24 #include <sys/time.h>
25 #include <sys/wait.h>
26 #include <sys/socket.h>
27 #include <stdio.h>
28 #ifdef STDC_HEADERS
29 # include <stdlib.h>
30 # include <stddef.h>
31 #else
32 # ifdef HAVE_STDLIB_H
33 #  include <stdlib.h>
34 # endif
35 #endif /* STDC_HEADERS */
36 #ifdef HAVE_STRING_H
37 # include <string.h>
38 #endif /* HAVE_STRING_H */
39 #ifdef HAVE_STRINGS_H
40 # include <strings.h>
41 #endif /* HAVE_STRINGS_H */
42 #ifdef HAVE_UNISTD_H
43 # include <unistd.h>
44 #endif /* HAVE_UNISTD_H */
45 #include <ctype.h>
46 #include <grp.h>
47 #include <pwd.h>
48 #include <signal.h>
49 #include <errno.h>
50 #include <fcntl.h>
51 #if TIME_WITH_SYS_TIME
52 # include <time.h>
53 #endif
54
55 #include "sudo.h"
56
57 static void
58 switch_user(uid_t euid, gid_t egid, int ngroups, GETGROUPS_T *groups)
59 {
60     int serrno = errno;
61
62     /* When restoring root, change euid first; otherwise change it last. */
63     if (euid == ROOT_UID) {
64         if (seteuid(ROOT_UID) != 0)
65             error(1, "seteuid(ROOT_UID)");
66     }
67     if (ngroups != -1) {
68         if (setgroups(ngroups, groups) != 0)
69             error(1, "setgroups");
70     }
71     if (setegid(egid) != 0)
72         error(1, "setegid(%d)", (int)egid);
73     if (euid != ROOT_UID) {
74         if (seteuid(euid) != 0)
75             error(1, "seteuid(%d)", (int)euid);
76     }
77
78     errno = serrno;
79 }
80
81 /*
82  * Wrapper to allow users to edit privileged files with their own uid.
83  */
84 int
85 sudo_edit(struct command_details *command_details)
86 {
87     struct command_details editor_details;
88     ssize_t nread, nwritten;
89     const char *tmpdir;
90     char *cp, *suff, **nargv, **ap, **files = NULL;
91     char buf[BUFSIZ];
92     int rc, i, j, ac, ofd, tfd, nargc, rval, tmplen;
93     int editor_argc = 0, nfiles = 0;
94     struct stat sb;
95     struct timeval tv, tv1, tv2;
96     struct tempfile {
97         char *tfile;
98         char *ofile;
99         struct timeval omtim;
100         off_t osize;
101     } *tf;
102
103     /*
104      * Set real, effective and saved uids to root.
105      * We will change the euid as needed below.
106      */
107     if (setuid(ROOT_UID) != 0) {
108         warning("unable to change to uid to root (%u)", ROOT_UID);
109         return 1;
110     }
111
112     /*
113      * Find our temporary directory, one of /var/tmp, /usr/tmp, or /tmp
114      */
115     if (stat(_PATH_VARTMP, &sb) == 0 && S_ISDIR(sb.st_mode))
116         tmpdir = _PATH_VARTMP;
117 #ifdef _PATH_USRTMP
118     else if (stat(_PATH_USRTMP, &sb) == 0 && S_ISDIR(sb.st_mode))
119         tmpdir = _PATH_USRTMP;
120 #endif
121     else
122         tmpdir = _PATH_TMP;
123     tmplen = strlen(tmpdir);
124     while (tmplen > 0 && tmpdir[tmplen - 1] == '/')
125         tmplen--;
126
127     /*
128      * The user's editor must be separated from the files to be
129      * edited by a "--" option.
130      */
131     for (ap = command_details->argv; *ap != NULL; ap++) {
132         if (files)
133             nfiles++;
134         else if (strcmp(*ap, "--") == 0)
135             files = ap + 1;
136         else
137             editor_argc++;
138     }
139     if (nfiles == 0) {
140         warningx("plugin error: missing file list for sudoedit");
141         return 1;
142     }
143
144     /*
145      * For each file specified by the user, make a temporary version
146      * and copy the contents of the original to it.
147      */
148     tf = emalloc2(nfiles, sizeof(*tf));
149     zero_bytes(tf, nfiles * sizeof(*tf));
150     for (i = 0, j = 0; i < nfiles; i++) {
151         rc = -1;
152         switch_user(command_details->euid, command_details->egid,
153             command_details->ngroups, command_details->groups);
154         if ((ofd = open(files[i], O_RDONLY, 0644)) != -1 || errno == ENOENT) {
155             if (ofd == -1) {
156                 zero_bytes(&sb, sizeof(sb));            /* new file */
157                 rc = 0;
158             } else {
159 #ifdef HAVE_FSTAT
160                 rc = fstat(ofd, &sb);
161 #else
162                 rc = stat(tf[j].ofile, &sb);
163 #endif
164             }
165         }
166         switch_user(ROOT_UID, user_details.egid,
167             user_details.ngroups, user_details.groups);
168         if (rc || (ofd != -1 && !S_ISREG(sb.st_mode))) {
169             if (rc)
170                 warning("%s", files[i]);
171             else
172                 warningx("%s: not a regular file", files[i]);
173             if (ofd != -1)
174                 close(ofd);
175             continue;
176         }
177         tf[j].ofile = files[i];
178         tf[j].osize = sb.st_size;
179         mtim_get(&sb, &tf[j].omtim);
180         if ((cp = strrchr(tf[j].ofile, '/')) != NULL)
181             cp++;
182         else
183             cp = tf[j].ofile;
184         suff = strrchr(cp, '.');
185         if (suff != NULL) {
186             easprintf(&tf[j].tfile, "%.*s/%.*sXXXXXXXX%s", tmplen, tmpdir,
187                 (int)(size_t)(suff - cp), cp, suff);
188         } else {
189             easprintf(&tf[j].tfile, "%.*s/%s.XXXXXXXX", tmplen, tmpdir, cp);
190         }
191         if (seteuid(user_details.uid) != 0)
192             error(1, "seteuid(%d)", (int)user_details.uid);
193         tfd = mkstemps(tf[j].tfile, suff ? strlen(suff) : 0);
194         if (seteuid(ROOT_UID) != 0)
195             error(1, "seteuid(ROOT_UID)");
196         if (tfd == -1) {
197             warning("mkstemps");
198             goto cleanup;
199         }
200         if (ofd != -1) {
201             while ((nread = read(ofd, buf, sizeof(buf))) != 0) {
202                 if ((nwritten = write(tfd, buf, nread)) != nread) {
203                     if (nwritten == -1)
204                         warning("%s", tf[j].tfile);
205                     else
206                         warningx("%s: short write", tf[j].tfile);
207                     goto cleanup;
208                 }
209             }
210             close(ofd);
211         }
212         /*
213          * We always update the stashed mtime because the time
214          * resolution of the filesystem the temporary file is on may
215          * not match that of the filesystem where the file to be edited
216          * resides.  It is OK if touch() fails since we only use the info
217          * to determine whether or not a file has been modified.
218          */
219         (void) touch(tfd, NULL, &tf[j].omtim);
220 #ifdef HAVE_FSTAT
221         rc = fstat(tfd, &sb);
222 #else
223         rc = stat(tf[j].tfile, &sb);
224 #endif
225         if (!rc)
226             mtim_get(&sb, &tf[j].omtim);
227         close(tfd);
228         j++;
229     }
230     if ((nfiles = j) == 0)
231         return 1;                       /* no files readable, you lose */
232
233     /*
234      * Allocate space for the new argument vector and fill it in.
235      * We concatenate the editor with its args and the file list
236      * to create a new argv.
237      */
238     nargc = editor_argc + nfiles;
239     nargv = (char **) emalloc2(nargc + 1, sizeof(char *));
240     for (ac = 0; ac < editor_argc; ac++)
241         nargv[ac] = command_details->argv[ac];
242     for (i = 0; i < nfiles && ac < nargc; )
243         nargv[ac++] = tf[i++].tfile;
244     nargv[ac] = NULL;
245
246     /*
247      * Run the editor with the invoking user's creds,
248      * keeping track of the time spent in the editor.
249      */
250     gettimeofday(&tv1, NULL);
251     memcpy(&editor_details, command_details, sizeof(editor_details));
252     editor_details.uid = user_details.uid;
253     editor_details.euid = user_details.uid;
254     editor_details.gid = user_details.gid;
255     editor_details.egid = user_details.gid;
256     editor_details.ngroups = user_details.ngroups;
257     editor_details.groups = user_details.groups;
258     editor_details.argv = nargv;
259     rval = run_command(&editor_details);
260     gettimeofday(&tv2, NULL);
261
262     /* Copy contents of temp files to real ones */
263     for (i = 0; i < nfiles; i++) {
264         rc = -1;
265         if (seteuid(user_details.uid) != 0)
266             error(1, "seteuid(%d)", (int)user_details.uid);
267         if ((tfd = open(tf[i].tfile, O_RDONLY, 0644)) != -1) {
268 #ifdef HAVE_FSTAT
269             rc = fstat(tfd, &sb);
270 #else
271             rc = stat(tf[i].tfile, &sb);
272 #endif
273         }
274         if (seteuid(ROOT_UID) != 0)
275             error(1, "seteuid(ROOT_UID)");
276         if (rc || !S_ISREG(sb.st_mode)) {
277             if (rc)
278                 warning("%s", tf[i].tfile);
279             else
280                 warningx("%s: not a regular file", tf[i].tfile);
281             warningx("%s left unmodified", tf[i].ofile);
282             if (tfd != -1)
283                 close(tfd);
284             continue;
285         }
286         mtim_get(&sb, &tv);
287         if (tf[i].osize == sb.st_size && timevalcmp(&tf[i].omtim, &tv, ==)) {
288             /*
289              * If mtime and size match but the user spent no measurable
290              * time in the editor we can't tell if the file was changed.
291              */
292             timevalsub(&tv1, &tv2);
293             if (timevalisset(&tv2)) {
294                 warningx("%s unchanged", tf[i].ofile);
295                 unlink(tf[i].tfile);
296                 close(tfd);
297                 continue;
298             }
299         }
300         switch_user(command_details->euid, command_details->egid,
301             command_details->ngroups, command_details->groups);
302         ofd = open(tf[i].ofile, O_WRONLY|O_TRUNC|O_CREAT, 0644);
303         switch_user(ROOT_UID, user_details.egid,
304             user_details.ngroups, user_details.groups);
305         if (ofd == -1) {
306             warning("unable to write to %s", tf[i].ofile);
307             warningx("contents of edit session left in %s", tf[i].tfile);
308             close(tfd);
309             continue;
310         }
311         while ((nread = read(tfd, buf, sizeof(buf))) > 0) {
312             if ((nwritten = write(ofd, buf, nread)) != nread) {
313                 if (nwritten == -1)
314                     warning("%s", tf[i].ofile);
315                 else
316                     warningx("%s: short write", tf[i].ofile);
317                 break;
318             }
319         }
320         if (nread == 0) {
321             /* success, got EOF */
322             unlink(tf[i].tfile);
323         } else if (nread < 0) {
324             warning("unable to read temporary file");
325             warningx("contents of edit session left in %s", tf[i].tfile);
326         } else {
327             warning("unable to write to %s", tf[i].ofile);
328             warningx("contents of edit session left in %s", tf[i].tfile);
329         }
330         close(ofd);
331     }
332
333     return rval;
334 cleanup:
335     /* Clean up temp files and return. */
336     for (i = 0; i < nfiles; i++) {
337         if (tf[i].tfile != NULL)
338             unlink(tf[i].tfile);
339     }
340     return 1;
341 }
342
343 #else /* HAVE_SETRESUID || HAVE_SETREUID || HAVE_SETEUID */
344
345 /*
346  * Must have the ability to change the effective uid to use sudoedit.
347  */
348 int
349 sudo_edit(struct command_details *command_details)
350 {
351     return 1;
352 }
353
354 #endif /* HAVE_SETRESUID || HAVE_SETREUID || HAVE_SETEUID */