]> granicus.if.org Git - sudo/blob - plugins/sample/sample_plugin.c
Add SPDX-License-Identifier to files.
[sudo] / plugins / sample / sample_plugin.c
1 /*
2  * SPDX-License-Identifier: ISC
3  *
4  * Copyright (c) 2010-2016 Todd C. Miller <Todd.Miller@sudo.ws>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18
19 /*
20  * This is an open source non-commercial project. Dear PVS-Studio, please check it.
21  * PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
22  */
23
24 #include <config.h>
25
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <sys/wait.h>
29
30 #include <stdio.h>
31 #include <stdlib.h>
32 #ifdef HAVE_STDBOOL_H
33 # include <stdbool.h>
34 #else
35 # include "compat/stdbool.h"
36 #endif /* HAVE_STDBOOL_H */
37 #ifdef HAVE_STRING_H
38 # include <string.h>
39 #endif /* HAVE_STRING_H */
40 #ifdef HAVE_STRINGS_H
41 # include <strings.h>
42 #endif /* HAVE_STRINGS_H */
43 #include <unistd.h>
44 #include <ctype.h>
45 #include <fcntl.h>
46 #include <limits.h>
47 #include <grp.h>
48 #include <pwd.h>
49 #include <stdarg.h>
50
51 #include <pathnames.h>
52 #include "sudo_compat.h"
53 #include "sudo_plugin.h"
54 #include "sudo_util.h"
55
56 /*
57  * Sample plugin module that allows any user who knows the password
58  * ("test") to run any command as root.  Since there is no credential
59  * caching the validate and invalidate functions are NULL.
60  */
61
62 #ifdef __TANDEM
63 # define ROOT_UID       65535
64 #else
65 # define ROOT_UID       0
66 #endif
67
68 static struct plugin_state {
69     char **envp;
70     char * const *settings;
71     char * const *user_info;
72 } plugin_state;
73 static sudo_conv_t sudo_conv;
74 static sudo_printf_t sudo_log;
75 static FILE *input, *output;
76 static uid_t runas_uid = ROOT_UID;
77 static gid_t runas_gid = -1;
78 static int use_sudoedit = false;
79
80 /*
81  * Plugin policy open function.
82  */
83 static int
84 policy_open(unsigned int version, sudo_conv_t conversation,
85     sudo_printf_t sudo_printf, char * const settings[],
86     char * const user_info[], char * const user_env[], char * const args[])
87 {
88     char * const *ui;
89     struct passwd *pw;
90     const char *runas_user = NULL;
91     struct group *gr;
92     const char *runas_group = NULL;
93
94     if (!sudo_conv)
95         sudo_conv = conversation;
96     if (!sudo_log)
97         sudo_log = sudo_printf;
98
99     if (SUDO_API_VERSION_GET_MAJOR(version) != SUDO_API_VERSION_MAJOR) {
100         sudo_log(SUDO_CONV_ERROR_MSG,
101             "the sample plugin requires API version %d.x\n",
102             SUDO_API_VERSION_MAJOR);
103         return -1;
104     }
105
106     /* Only allow commands to be run as root. */
107     for (ui = settings; *ui != NULL; ui++) {
108         if (strncmp(*ui, "runas_user=", sizeof("runas_user=") - 1) == 0) {
109             runas_user = *ui + sizeof("runas_user=") - 1;
110         }
111         if (strncmp(*ui, "runas_group=", sizeof("runas_group=") - 1) == 0) {
112             runas_group = *ui + sizeof("runas_group=") - 1;
113         }
114         if (strncmp(*ui, "progname=", sizeof("progname=") - 1) == 0) {
115             initprogname(*ui + sizeof("progname=") - 1);
116         }
117         /* Check to see if sudo was called as sudoedit or with -e flag. */
118         if (strncmp(*ui, "sudoedit=", sizeof("sudoedit=") - 1) == 0) {
119             if (strcasecmp(*ui + sizeof("sudoedit=") - 1, "true") == 0)
120                 use_sudoedit = true;
121         }
122         /* This plugin doesn't support running sudo with no arguments. */
123         if (strncmp(*ui, "implied_shell=", sizeof("implied_shell=") - 1) == 0) {
124             if (strcasecmp(*ui + sizeof("implied_shell=") - 1, "true") == 0)
125                 return -2; /* usage error */
126         }
127     }
128     if (runas_user != NULL) {
129         if ((pw = getpwnam(runas_user)) == NULL) {
130             sudo_log(SUDO_CONV_ERROR_MSG, "unknown user %s\n", runas_user);
131             return 0;
132         }
133         runas_uid = pw->pw_uid;
134     }
135     if (runas_group != NULL) {
136         if ((gr = getgrnam(runas_group)) == NULL) {
137             sudo_log(SUDO_CONV_ERROR_MSG, "unknown group %s\n", runas_group);
138             return 0;
139         }
140         runas_gid = gr->gr_gid;
141     }
142
143     /* Plugin state. */
144     plugin_state.envp = (char **)user_env;
145     plugin_state.settings = settings;
146     plugin_state.user_info = user_info;
147
148     return 1;
149 }
150
151 static char *
152 find_in_path(char *command, char **envp)
153 {
154     struct stat sb;
155     char *path, *path0, **ep, *cp;
156     char pathbuf[PATH_MAX], *qualified = NULL;
157
158     if (strchr(command, '/') != NULL)
159         return command;
160
161     path = _PATH_DEFPATH;
162     for (ep = plugin_state.envp; *ep != NULL; ep++) {
163         if (strncmp(*ep, "PATH=", 5) == 0) {
164             path = *ep + 5;
165             break;
166         }
167     }
168     path = path0 = strdup(path);
169     do {
170         if ((cp = strchr(path, ':')))
171             *cp = '\0';
172         snprintf(pathbuf, sizeof(pathbuf), "%s/%s", *path ? path : ".",
173             command);
174         if (stat(pathbuf, &sb) == 0) {
175             if (S_ISREG(sb.st_mode) && (sb.st_mode & 0000111)) {
176                 qualified = pathbuf;
177                 break;
178             }
179         }
180         path = cp + 1;
181     } while (cp != NULL);
182     free(path0);
183     return qualified ? strdup(qualified) : NULL;
184 }
185
186 static int
187 check_passwd(void)
188 {
189     struct sudo_conv_message msg;
190     struct sudo_conv_reply repl;
191
192     /* Prompt user for password via conversation function. */
193     memset(&msg, 0, sizeof(msg));
194     msg.msg_type = SUDO_CONV_PROMPT_ECHO_OFF;
195     msg.msg = "Password: ";
196     memset(&repl, 0, sizeof(repl));
197     sudo_conv(1, &msg, &repl, NULL);
198     if (repl.reply == NULL) {
199         sudo_log(SUDO_CONV_ERROR_MSG, "missing password\n");
200         return false;
201     }
202     if (strcmp(repl.reply, "test") != 0) {
203         sudo_log(SUDO_CONV_ERROR_MSG, "incorrect password\n");
204         return false;
205     }
206     return true;
207 }
208
209 static char **
210 build_command_info(const char *command)
211 {
212     static char **command_info;
213     int i = 0;
214
215     /* Setup command info. */
216     command_info = calloc(32, sizeof(char *));
217     if (command_info == NULL)
218         return NULL;
219     if ((command_info[i++] = sudo_new_key_val("command", command)) == NULL ||
220         asprintf(&command_info[i++], "runas_euid=%ld", (long)runas_uid) == -1 ||
221         asprintf(&command_info[i++], "runas_uid=%ld", (long)runas_uid) == -1) {
222         return NULL;
223     }
224     if (runas_gid != (gid_t)-1) {
225         if (asprintf(&command_info[i++], "runas_gid=%ld", (long)runas_gid) == -1 ||
226             asprintf(&command_info[i++], "runas_egid=%ld", (long)runas_gid) == -1) {
227             return NULL;
228         }
229     }
230     if (use_sudoedit) {
231         command_info[i] = strdup("sudoedit=true");
232         if (command_info[i++] == NULL)
233                 return NULL;
234     }
235 #ifdef USE_TIMEOUT
236     command_info[i++] = "timeout=30";
237 #endif
238     return command_info;
239 }
240
241 static char *
242 find_editor(int nfiles, char * const files[], char **argv_out[])
243 {
244     char *cp, *last, **ep, **nargv, *editor, *editor_path;
245     int ac, i, nargc, wasblank;
246
247     /* Lookup EDITOR in user's environment. */
248     editor = _PATH_VI;
249     for (ep = plugin_state.envp; *ep != NULL; ep++) {
250         if (strncmp(*ep, "EDITOR=", 7) == 0) {
251             editor = *ep + 7;
252             break;
253         }
254     }
255     editor = strdup(editor);
256     if (editor == NULL) {
257         sudo_log(SUDO_CONV_ERROR_MSG, "unable to allocate memory\n");
258         return NULL;
259     }
260
261     /*
262      * Split editor into an argument vector; editor is reused (do not free).
263      * The EDITOR environment variables may contain command
264      * line args so look for those and alloc space for them too.
265      */
266     nargc = 1;
267     for (wasblank = 0, cp = editor; *cp != '\0'; cp++) {
268         if (isblank((unsigned char) *cp))
269             wasblank = 1;
270         else if (wasblank) {
271             wasblank = 0;
272             nargc++;
273         }
274     }
275     /* If we can't find the editor in the user's PATH, give up. */
276     cp = strtok_r(editor, " \t", &last);
277     if (cp == NULL ||
278         (editor_path = find_in_path(editor, plugin_state.envp)) == NULL) {
279         free(editor);
280         return NULL;
281     }
282     if (editor_path != editor)
283         free(editor);
284     nargv = malloc((nargc + 1 + nfiles + 1) * sizeof(char *));
285     if (nargv == NULL) {
286         sudo_log(SUDO_CONV_ERROR_MSG, "unable to allocate memory\n");
287         free(editor_path);
288         return NULL;
289     }
290     for (ac = 0; cp != NULL && ac < nargc; ac++) {
291         nargv[ac] = cp;
292         cp = strtok_r(NULL, " \t", &last);
293     }
294     nargv[ac++] = "--";
295     for (i = 0; i < nfiles; )
296         nargv[ac++] = files[i++];
297     nargv[ac] = NULL;
298
299     *argv_out = nargv;
300     return editor_path;
301 }
302
303 /*
304  * Plugin policy check function.
305  * Simple example that prompts for a password, hard-coded to "test".
306  */
307 static int 
308 policy_check(int argc, char * const argv[],
309     char *env_add[], char **command_info_out[],
310     char **argv_out[], char **user_env_out[])
311 {
312     char *command;
313
314     if (!argc || argv[0] == NULL) {
315         sudo_log(SUDO_CONV_ERROR_MSG, "no command specified\n");
316         return false;
317     }
318
319     if (!check_passwd())
320         return false;
321
322     command = find_in_path(argv[0], plugin_state.envp);
323     if (command == NULL) {
324         sudo_log(SUDO_CONV_ERROR_MSG, "%s: command not found\n", argv[0]);
325         return false;
326     }
327
328     /* If "sudo vi" is run, auto-convert to sudoedit.  */
329     if (strcmp(command, _PATH_VI) == 0)
330         use_sudoedit = true;
331
332     if (use_sudoedit) {
333         /* Rebuild argv using editor */
334         free(command);
335         command = find_editor(argc - 1, argv + 1, argv_out);
336         if (command == NULL) {
337             sudo_log(SUDO_CONV_ERROR_MSG, "unable to find valid editor\n");
338             return -1;
339         }
340         use_sudoedit = true;
341     } else {
342         /* No changes needd to argv */
343         *argv_out = (char **)argv;
344     }
345
346     /* No changes to envp */
347     *user_env_out = plugin_state.envp;
348
349     /* Setup command info. */
350     *command_info_out = build_command_info(command);
351     free(command);
352     if (*command_info_out == NULL) {
353         sudo_log(SUDO_CONV_ERROR_MSG, "out of memory\n");
354         return -1;
355     }
356
357     return true;
358 }
359
360 static int
361 policy_list(int argc, char * const argv[], int verbose, const char *list_user)
362 {
363     /*
364      * List user's capabilities.
365      */
366     sudo_log(SUDO_CONV_INFO_MSG, "Validated users may run any command\n");
367     return true;
368 }
369
370 static int
371 policy_version(int verbose)
372 {
373     sudo_log(SUDO_CONV_INFO_MSG, "Sample policy plugin version %s\n", PACKAGE_VERSION);
374     return true;
375 }
376
377 static void
378 policy_close(int exit_status, int error)
379 {
380     /*
381      * The policy might log the command exit status here.
382      * In this example, we just print a message.
383      */
384     if (error) {
385         sudo_log(SUDO_CONV_ERROR_MSG, "Command error: %s\n", strerror(error));
386     } else {
387         if (WIFEXITED(exit_status)) {
388             sudo_log(SUDO_CONV_INFO_MSG, "Command exited with status %d\n",
389                 WEXITSTATUS(exit_status));
390         } else if (WIFSIGNALED(exit_status)) {
391             sudo_log(SUDO_CONV_INFO_MSG, "Command killed by signal %d\n",
392                 WTERMSIG(exit_status));
393         }
394     }
395 }
396
397 static int
398 io_open(unsigned int version, sudo_conv_t conversation,
399     sudo_printf_t sudo_printf, char * const settings[],
400     char * const user_info[], char * const command_info[],
401     int argc, char * const argv[], char * const user_env[], char * const args[])
402 {
403     int fd;
404     char path[PATH_MAX];
405
406     if (!sudo_conv)
407         sudo_conv = conversation;
408     if (!sudo_log)
409         sudo_log = sudo_printf;
410
411     /* Open input and output files. */
412     snprintf(path, sizeof(path), "/var/tmp/sample-%u.output",
413         (unsigned int)getpid());
414     fd = open(path, O_WRONLY|O_CREAT|O_EXCL, 0644);
415     if (fd == -1)
416         return false;
417     output = fdopen(fd, "w");
418
419     snprintf(path, sizeof(path), "/var/tmp/sample-%u.input",
420         (unsigned int)getpid());
421     fd = open(path, O_WRONLY|O_CREAT|O_EXCL, 0644);
422     if (fd == -1)
423         return false;
424     input = fdopen(fd, "w");
425
426     return true;
427 }
428
429 static void
430 io_close(int exit_status, int error)
431 {
432     fclose(input);
433     fclose(output);
434 }
435
436 static int
437 io_version(int verbose)
438 {
439     sudo_log(SUDO_CONV_INFO_MSG, "Sample I/O plugin version %s\n",
440         PACKAGE_VERSION);
441     return true;
442 }
443
444 static int
445 io_log_input(const char *buf, unsigned int len)
446 {
447     ignore_result(fwrite(buf, len, 1, input));
448     return true;
449 }
450
451 static int
452 io_log_output(const char *buf, unsigned int len)
453 {
454     const char *cp, *ep;
455     bool ret = true;
456
457     ignore_result(fwrite(buf, len, 1, output));
458     /*
459      * If we find the string "honk!" in the buffer, reject it.
460      * In practice we'd want to be able to detect the word
461      * broken across two buffers.
462      */
463     for (cp = buf, ep = buf + len; cp < ep; cp++) {
464         if (cp + 5 < ep && memcmp(cp, "honk!", 5) == 0) {
465             ret = false;
466             break;
467         }
468     }
469     return ret;
470 }
471
472 __dso_public struct policy_plugin sample_policy = {
473     SUDO_POLICY_PLUGIN,
474     SUDO_API_VERSION,
475     policy_open,
476     policy_close,
477     policy_version,
478     policy_check,
479     policy_list,
480     NULL, /* validate */
481     NULL, /* invalidate */
482     NULL, /* init_session */
483     NULL, /* register_hooks */
484     NULL /* deregister_hooks */
485 };
486
487 /*
488  * Note: This plugin does not differentiate between tty and pipe I/O.
489  *       It all gets logged to the same file.
490  */
491 __dso_public struct io_plugin sample_io = {
492     SUDO_IO_PLUGIN,
493     SUDO_API_VERSION,
494     io_open,
495     io_close,
496     io_version,
497     io_log_input,       /* tty input */
498     io_log_output,      /* tty output */
499     io_log_input,       /* command stdin if not tty */
500     io_log_output,      /* command stdout if not tty */
501     io_log_output       /* command stderr if not tty */
502 };