/*1* SPDX-License-Identifier: ISC2*3* Copyright (c) 2020 Todd C. Miller <[email protected]>4*5* Permission to use, copy, modify, and distribute this software for any6* purpose with or without fee is hereby granted, provided that the above7* copyright notice and this permission notice appear in all copies.8*9* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES10* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF11* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR12* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES13* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN14* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF15* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.16*/1718#include <config.h>1920#include <stdio.h>21#include <stdlib.h>22#include <string.h>23#include <grp.h>24#include <pwd.h>2526#include <sudoers.h>27#include <pwutil.h>2829/*30* Expand leading tilde in *path, which must be dynamically allocated.31* Replaces path with the expanded version as needed, freeing the old one.32* Returns true on success, false on failure.33*/34bool35expand_tilde(char **path, const char *user)36{37char *npath, *opath = *path;38char *slash = NULL;39struct passwd *pw;40int len;41debug_decl(expand_tilde, SUDOERS_DEBUG_UTIL);4243switch (*opath++) {44case '/':45/* A fully-qualified path, nothing to do. */46debug_return_bool(true);47case '~':48/* See below. */49break;50default:51/* Not a fully-qualified path or one that starts with a tilde. */52debug_return_bool(false);53}5455switch (*opath) {56case '\0':57/* format: ~ */58break;59case '/':60/* format: ~/foo */61opath++;62break;63default:64/* format: ~user/foo */65user = opath;66slash = strchr(opath, '/');67if (slash != NULL) {68*slash = '\0';69opath = slash + 1;70} else {71opath = (char *)"";72}73}74pw = sudo_getpwnam(user);75if (slash != NULL)76*slash = '/';77if (pw == NULL) {78/* Unknown user. */79sudo_warnx(U_("unknown user %s"), user);80debug_return_bool(false);81}8283len = asprintf(&npath, "%s%s%s", pw->pw_dir, *opath ? "/" : "", opath);84sudo_pw_delref(pw);85if (len == -1) {86sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory"));87debug_return_bool(false);88}8990free(*path);91*path = npath;92debug_return_bool(true);93}949596