1 /*
2 * SPDX-License-Identifier: ISC
3 *
4 * Copyright (c) 2020 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 <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <grp.h>
30 #include <pwd.h>
31
32 #include "sudoers.h"
33 #include "pwutil.h"
34
35 /*
36 * Expand leading tilde in *path, which must be dynamically allocated.
37 * Replaces path with the expanded version as needed, freeing the old one.
38 * Returns true on success, false on failure.
39 */
40 bool
expand_tilde(char ** path,const char * user)41 expand_tilde(char **path, const char *user)
42 {
43 char *npath, *opath = *path;
44 char *slash = NULL;
45 struct passwd *pw;
46 int len;
47 debug_decl(expand_tilde, SUDOERS_DEBUG_UTIL);
48
49 switch (*opath++) {
50 case '/':
51 /* A fully-qualified path, nothing to do. */
52 debug_return_bool(true);
53 case '~':
54 /* See below. */
55 break;
56 default:
57 /* Not a fully-qualified path or one that starts with a tilde. */
58 debug_return_bool(false);
59 }
60
61 switch (*opath) {
62 case '\0':
63 /* format: ~ */
64 break;
65 case '/':
66 /* format: ~/foo */
67 opath++;
68 break;
69 default:
70 /* format: ~user/foo */
71 user = opath;
72 slash = strchr(opath, '/');
73 if (slash != NULL) {
74 *slash = '\0';
75 opath = slash + 1;
76 } else {
77 opath = "";
78 }
79 }
80 pw = sudo_getpwnam(user);
81 if (slash != NULL)
82 *slash = '/';
83 if (pw == NULL) {
84 /* Unknown user. */
85 sudo_warnx(U_("unknown user %s"), user);
86 debug_return_bool(false);
87 }
88
89 len = asprintf(&npath, "%s%s%s", pw->pw_dir, *opath ? "/" : "", opath);
90 sudo_pw_delref(pw);
91 if (len == -1) {
92 sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
93 debug_return_bool(false);
94 }
95
96 free(*path);
97 *path = npath;
98 debug_return_bool(true);
99 }
100