|
| 1 | +/* |
| 2 | + Derived from source code of TrueCrypt 7.1a, which is |
| 3 | + Copyright (c) 2008-2012 TrueCrypt Developers Association and which is governed |
| 4 | + by the TrueCrypt License 3.0. |
| 5 | +
|
| 6 | + Modifications and additions to the original source code (contained in this file) |
| 7 | + and all other portions of this file are Copyright (c) 2013-2026 AM Crypto |
| 8 | + and are governed by the Apache License 2.0 the full text of which is |
| 9 | + contained in the file License.txt included in VeraCrypt binary and source |
| 10 | + code distribution packages. |
| 11 | +*/ |
| 12 | + |
| 13 | +#ifndef TC_HEADER_Core_Unix_UnixUser |
| 14 | +#define TC_HEADER_Core_Unix_UnixUser |
| 15 | + |
| 16 | +#include <errno.h> |
| 17 | +#include <pwd.h> |
| 18 | +#include <stdlib.h> |
| 19 | +#include <string.h> |
| 20 | +#include <sys/types.h> |
| 21 | +#include <unistd.h> |
| 22 | +#include <vector> |
| 23 | + |
| 24 | +#define TC_DOAS_CORE_SERVICE_ENV "VERACRYPT_DOAS_CORE_SERVICE" |
| 25 | + |
| 26 | +namespace VeraCrypt |
| 27 | +{ |
| 28 | + static inline bool GetDoasUserIds (uid_t *uid, gid_t *gid) |
| 29 | + { |
| 30 | + if (getuid () != 0 || geteuid () != 0 || getenv ("SUDO_UID") || getenv ("SUDO_GID")) |
| 31 | + return false; |
| 32 | + |
| 33 | +#ifndef TC_OPENBSD |
| 34 | + const char *trustedDoasService = getenv (TC_DOAS_CORE_SERVICE_ENV); |
| 35 | + if (!trustedDoasService || strcmp (trustedDoasService, "1") != 0) |
| 36 | + return false; |
| 37 | +#endif |
| 38 | + |
| 39 | + const char *env = getenv ("DOAS_USER"); |
| 40 | + if (!env || !env[0]) |
| 41 | + return false; |
| 42 | + |
| 43 | + long bufferSize = 16384; |
| 44 | +#ifdef _SC_GETPW_R_SIZE_MAX |
| 45 | + long sysconfBufferSize = sysconf (_SC_GETPW_R_SIZE_MAX); |
| 46 | + if (sysconfBufferSize > 0) |
| 47 | + bufferSize = sysconfBufferSize; |
| 48 | +#endif |
| 49 | + |
| 50 | + struct passwd pw; |
| 51 | + struct passwd *pwResult = nullptr; |
| 52 | + std::vector <char> buffer (static_cast <size_t> (bufferSize)); |
| 53 | + int status; |
| 54 | + |
| 55 | + while ((status = getpwnam_r (env, &pw, &buffer[0], buffer.size(), &pwResult)) == ERANGE) |
| 56 | + { |
| 57 | + if (buffer.size () > 1024 * 1024) |
| 58 | + return false; |
| 59 | + buffer.resize (buffer.size () * 2); |
| 60 | + } |
| 61 | + |
| 62 | + if (status != 0 || !pwResult) |
| 63 | + return false; |
| 64 | + |
| 65 | + if (uid) |
| 66 | + *uid = pw.pw_uid; |
| 67 | + if (gid) |
| 68 | + *gid = pw.pw_gid; |
| 69 | + |
| 70 | + return true; |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +#endif // TC_HEADER_Core_Unix_UnixUser |
0 commit comments