VirtualBox

source: vbox/trunk/src/VBox/HostDrivers/Support/SUPR3HardenedVerify.cpp@ 78374

Last change on this file since 78374 was 76818, checked in by vboxsync, 6 years ago

Config.kmk, HostDrivers/Support, Main, FE/Qt, Installer: bugref:9049: Wipe out VBOX_GUI_WITH_SHARED_LIBRARY, leaving split GUI build as the only possible.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 83.5 KB
Line 
1/* $Id: SUPR3HardenedVerify.cpp 76818 2019-01-14 16:17:07Z vboxsync $ */
2/** @file
3 * VirtualBox Support Library - Verification of Hardened Installation.
4 */
5
6/*
7 * Copyright (C) 2006-2019 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*********************************************************************************************************************************
29* Header Files *
30*********************************************************************************************************************************/
31#if defined(RT_OS_OS2)
32# define INCL_BASE
33# define INCL_ERRORS
34# include <os2.h>
35# include <stdio.h>
36# include <stdlib.h>
37# include <unistd.h>
38# include <sys/fcntl.h>
39# include <sys/errno.h>
40# include <sys/syslimits.h>
41
42#elif defined(RT_OS_WINDOWS)
43# include <iprt/nt/nt-and-windows.h>
44# ifndef IN_SUP_HARDENED_R3
45# include <stdio.h>
46# endif
47
48#else /* UNIXes */
49# include <sys/types.h>
50# include <stdio.h>
51# include <stdlib.h>
52# include <dirent.h>
53# include <dlfcn.h>
54# include <fcntl.h>
55# include <limits.h>
56# include <errno.h>
57# include <unistd.h>
58# include <sys/stat.h>
59# include <sys/time.h>
60# include <sys/fcntl.h>
61# include <pwd.h>
62# ifdef RT_OS_DARWIN
63# include <mach-o/dyld.h>
64# endif
65
66#endif
67
68#include <VBox/sup.h>
69#include <VBox/err.h>
70#include <iprt/asm.h>
71#include <iprt/ctype.h>
72#include <iprt/param.h>
73#include <iprt/path.h>
74#include <iprt/string.h>
75#include <iprt/utf16.h>
76
77#include "SUPLibInternal.h"
78#if defined(RT_OS_WINDOWS) && defined(VBOX_WITH_HARDENING)
79# define SUPHNTVI_NO_NT_STUFF
80# include "win/SUPHardenedVerify-win.h"
81#endif
82
83
84/*********************************************************************************************************************************
85* Defined Constants And Macros *
86*********************************************************************************************************************************/
87/** The max path length acceptable for a trusted path. */
88#define SUPR3HARDENED_MAX_PATH 260U
89
90/** Enable to resolve symlinks using realpath() instead of cooking our own stuff. */
91#define SUP_HARDENED_VERIFY_FOLLOW_SYMLINKS_USE_REALPATH 1
92
93#ifdef RT_OS_SOLARIS
94# define dirfd(d) ((d)->d_fd)
95#endif
96
97/** Compare table file names with externally supplied names. */
98#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
99# define SUP_COMP_FILENAME RTStrICmp
100#else
101# define SUP_COMP_FILENAME suplibHardenedStrCmp
102#endif
103
104
105/*********************************************************************************************************************************
106* Global Variables *
107*********************************************************************************************************************************/
108/**
109 * The files that gets verified.
110 *
111 * @todo This needs reviewing against the linux packages.
112 * @todo The excessive use of kSupID_AppSharedLib needs to be reviewed at some point. For
113 * the time being we're building the linux packages with SharedLib pointing to
114 * AppPrivArch (lazy bird).
115 *
116 * @remarks If you add executables here, you might need to update
117 * g_apszSupNtVpAllowedVmExes in SUPHardenedVerifyProcess-win.cpp.
118 */
119static SUPINSTFILE const g_aSupInstallFiles[] =
120{
121 /* type, dir, fOpt, "pszFile" */
122 /* ---------------------------------------------------------------------- */
123 { kSupIFT_Dll, kSupID_AppPrivArch, false, "VMMR0.r0" },
124 { kSupIFT_Dll, kSupID_AppPrivArch, false, "VBoxDDR0.r0" },
125
126#ifdef VBOX_WITH_RAW_MODE
127 { kSupIFT_Rc, kSupID_AppPrivArch, false, "VMMRC.rc" },
128 { kSupIFT_Rc, kSupID_AppPrivArch, false, "VBoxDDRC.rc" },
129#endif
130
131 { kSupIFT_Dll, kSupID_AppSharedLib, false, "VBoxRT" SUPLIB_DLL_SUFF },
132 { kSupIFT_Dll, kSupID_AppSharedLib, false, "VBoxVMM" SUPLIB_DLL_SUFF },
133#ifdef VBOX_WITH_REM
134 { kSupIFT_Dll, kSupID_AppSharedLib, false, "VBoxREM" SUPLIB_DLL_SUFF },
135#endif
136#if HC_ARCH_BITS == 32
137 { kSupIFT_Dll, kSupID_AppSharedLib, true, "VBoxREM32" SUPLIB_DLL_SUFF },
138 { kSupIFT_Dll, kSupID_AppSharedLib, true, "VBoxREM64" SUPLIB_DLL_SUFF },
139#endif
140 { kSupIFT_Dll, kSupID_AppSharedLib, false, "VBoxDD" SUPLIB_DLL_SUFF },
141 { kSupIFT_Dll, kSupID_AppSharedLib, false, "VBoxDD2" SUPLIB_DLL_SUFF },
142 { kSupIFT_Dll, kSupID_AppSharedLib, false, "VBoxDDU" SUPLIB_DLL_SUFF },
143 { kSupIFT_Exe, kSupID_AppBin, true, "VBoxVMMPreload" SUPLIB_EXE_SUFF },
144 { kSupIFT_Dll, kSupID_AppPrivArch, true, "VBoxVMMPreload" SUPLIB_DLL_SUFF },
145
146//#ifdef VBOX_WITH_DEBUGGER_GUI
147 { kSupIFT_Dll, kSupID_AppSharedLib, true, "VBoxDbg" SUPLIB_DLL_SUFF },
148 { kSupIFT_Dll, kSupID_AppSharedLib, true, "VBoxDbg3" SUPLIB_DLL_SUFF },
149//#endif
150
151//#ifdef VBOX_WITH_SHARED_CLIPBOARD
152 { kSupIFT_Dll, kSupID_AppPrivArch, true, "VBoxSharedClipboard" SUPLIB_DLL_SUFF },
153//#endif
154//#ifdef VBOX_WITH_SHARED_FOLDERS
155 { kSupIFT_Dll, kSupID_AppPrivArch, true, "VBoxSharedFolders" SUPLIB_DLL_SUFF },
156//#endif
157//#ifdef VBOX_WITH_DRAG_AND_DROP
158 { kSupIFT_Dll, kSupID_AppPrivArch, true, "VBoxDragAndDropSvc" SUPLIB_DLL_SUFF },
159//#endif
160//#ifdef VBOX_WITH_GUEST_PROPS
161 { kSupIFT_Dll, kSupID_AppPrivArch, true, "VBoxGuestPropSvc" SUPLIB_DLL_SUFF },
162//#endif
163//#ifdef VBOX_WITH_GUEST_CONTROL
164 { kSupIFT_Dll, kSupID_AppPrivArch, true, "VBoxGuestControlSvc" SUPLIB_DLL_SUFF },
165//#endif
166 { kSupIFT_Dll, kSupID_AppPrivArch, true, "VBoxHostChannel" SUPLIB_DLL_SUFF },
167 { kSupIFT_Dll, kSupID_AppPrivArch, true, "VBoxSharedCrOpenGL" SUPLIB_DLL_SUFF },
168 { kSupIFT_Dll, kSupID_AppPrivArch, true, "VBoxOGLhostcrutil" SUPLIB_DLL_SUFF },
169 { kSupIFT_Dll, kSupID_AppPrivArch, true, "VBoxOGLhosterrorspu" SUPLIB_DLL_SUFF },
170 { kSupIFT_Dll, kSupID_AppPrivArch, true, "VBoxOGLrenderspu" SUPLIB_DLL_SUFF },
171
172 { kSupIFT_Exe, kSupID_AppBin, true, "VBoxManage" SUPLIB_EXE_SUFF },
173
174#ifdef VBOX_WITH_MAIN
175 { kSupIFT_Exe, kSupID_AppBin, false, "VBoxSVC" SUPLIB_EXE_SUFF },
176 #ifdef RT_OS_WINDOWS
177 { kSupIFT_Dll, kSupID_AppSharedLib, false, "VBoxC" SUPLIB_DLL_SUFF },
178 #else
179 { kSupIFT_Exe, kSupID_AppPrivArch, false, "VBoxXPCOMIPCD" SUPLIB_EXE_SUFF },
180 { kSupIFT_Dll, kSupID_AppSharedLib, false, "VBoxXPCOM" SUPLIB_DLL_SUFF },
181 { kSupIFT_Dll, kSupID_AppPrivArchComp, false, "VBoxXPCOMIPCC" SUPLIB_DLL_SUFF },
182 { kSupIFT_Dll, kSupID_AppPrivArchComp, false, "VBoxC" SUPLIB_DLL_SUFF },
183 { kSupIFT_Dll, kSupID_AppPrivArchComp, false, "VBoxSVCM" SUPLIB_DLL_SUFF },
184 { kSupIFT_Data, kSupID_AppPrivArchComp, false, "VBoxXPCOMBase.xpt" },
185 #endif
186#endif
187
188 { kSupIFT_Dll, kSupID_AppSharedLib, true, "VRDPAuth" SUPLIB_DLL_SUFF },
189 { kSupIFT_Dll, kSupID_AppSharedLib, true, "VBoxAuth" SUPLIB_DLL_SUFF },
190 { kSupIFT_Dll, kSupID_AppSharedLib, true, "VBoxVRDP" SUPLIB_DLL_SUFF },
191
192//#ifdef VBOX_WITH_HEADLESS
193 { kSupIFT_Exe, kSupID_AppBin, true, "VBoxHeadless" SUPLIB_EXE_SUFF },
194 { kSupIFT_Dll, kSupID_AppPrivArch, true, "VBoxHeadless" SUPLIB_DLL_SUFF },
195 { kSupIFT_Dll, kSupID_AppPrivArch, true, "VBoxVideoRecFB" SUPLIB_DLL_SUFF },
196//#endif
197
198//#ifdef VBOX_WITH_QTGUI
199 { kSupIFT_Exe, kSupID_AppBin, true, "VirtualBox" SUPLIB_EXE_SUFF },
200 { kSupIFT_Exe, kSupID_AppBin, true, "VirtualBoxVM" SUPLIB_EXE_SUFF },
201 { kSupIFT_Dll, kSupID_AppPrivArch, true, "VirtualBoxVM" SUPLIB_DLL_SUFF },
202 { kSupIFT_Dll, kSupID_AppPrivArch, true, "VBoxGlobal" SUPLIB_DLL_SUFF },
203# if !defined(RT_OS_DARWIN) && !defined(RT_OS_WINDOWS) && !defined(RT_OS_OS2)
204 { kSupIFT_Dll, kSupID_AppSharedLib, true, "VBoxKeyboard" SUPLIB_DLL_SUFF },
205# endif
206//#endif
207
208//#ifdef VBOX_WITH_VBOXSDL
209 { kSupIFT_Exe, kSupID_AppBin, true, "VBoxSDL" SUPLIB_EXE_SUFF },
210 { kSupIFT_Dll, kSupID_AppPrivArch, true, "VBoxSDL" SUPLIB_DLL_SUFF },
211//#endif
212
213//#ifdef VBOX_WITH_WEBSERVICES
214 { kSupIFT_Exe, kSupID_AppBin, true, "vboxwebsrv" SUPLIB_EXE_SUFF },
215//#endif
216
217#ifdef RT_OS_LINUX
218 { kSupIFT_Exe, kSupID_AppBin, true, "VBoxTunctl" SUPLIB_EXE_SUFF },
219#endif
220
221//#ifdef VBOX_WITH_NETFLT
222 { kSupIFT_Exe, kSupID_AppBin, true, "VBoxNetDHCP" SUPLIB_EXE_SUFF },
223 { kSupIFT_Dll, kSupID_AppPrivArch, true, "VBoxNetDHCP" SUPLIB_DLL_SUFF },
224//#endif
225
226//#ifdef VBOX_WITH_LWIP_NAT
227 { kSupIFT_Exe, kSupID_AppBin, true, "VBoxNetNAT" SUPLIB_EXE_SUFF },
228 { kSupIFT_Dll, kSupID_AppPrivArch, true, "VBoxNetNAT" SUPLIB_DLL_SUFF },
229//#endif
230#if defined(VBOX_WITH_HARDENING) && defined(RT_OS_WINDOWS)
231# define HARDENED_TESTCASE_BIN_ENTRY(a_szName) \
232 { kSupIFT_TestExe, kSupID_AppBin, true, a_szName SUPLIB_EXE_SUFF }, \
233 { kSupIFT_TestDll, kSupID_AppBin, true, a_szName SUPLIB_DLL_SUFF }
234 HARDENED_TESTCASE_BIN_ENTRY("tstMicro"),
235 HARDENED_TESTCASE_BIN_ENTRY("tstPDMAsyncCompletion"),
236 HARDENED_TESTCASE_BIN_ENTRY("tstPDMAsyncCompletionStress"),
237 HARDENED_TESTCASE_BIN_ENTRY("tstVMM"),
238 HARDENED_TESTCASE_BIN_ENTRY("tstVMREQ"),
239# define HARDENED_TESTCASE_ENTRY(a_szName) \
240 { kSupIFT_TestExe, kSupID_Testcase, true, a_szName SUPLIB_EXE_SUFF }, \
241 { kSupIFT_TestDll, kSupID_Testcase, true, a_szName SUPLIB_DLL_SUFF }
242 HARDENED_TESTCASE_ENTRY("tstCFGM"),
243 HARDENED_TESTCASE_ENTRY("tstGIP-2"),
244 HARDENED_TESTCASE_ENTRY("tstIntNet-1"),
245 HARDENED_TESTCASE_ENTRY("tstMMHyperHeap"),
246 HARDENED_TESTCASE_ENTRY("tstRTR0ThreadPreemptionDriver"),
247 HARDENED_TESTCASE_ENTRY("tstRTR0MemUserKernelDriver"),
248 HARDENED_TESTCASE_ENTRY("tstRTR0SemMutexDriver"),
249 HARDENED_TESTCASE_ENTRY("tstRTR0TimerDriver"),
250 HARDENED_TESTCASE_ENTRY("tstSSM"),
251#endif
252};
253
254
255/** Array parallel to g_aSupInstallFiles containing per-file status info. */
256static SUPVERIFIEDFILE g_aSupVerifiedFiles[RT_ELEMENTS(g_aSupInstallFiles)];
257
258/** Array index by install directory specifier containing info about verified directories. */
259static SUPVERIFIEDDIR g_aSupVerifiedDirs[kSupID_End];
260
261
262/**
263 * Assembles the path to a directory.
264 *
265 * @returns VINF_SUCCESS on success, some error code on failure (fFatal
266 * decides whether it returns or not).
267 *
268 * @param enmDir The directory.
269 * @param pszDst Where to assemble the path.
270 * @param cchDst The size of the buffer.
271 * @param fFatal Whether failures should be treated as fatal (true) or not (false).
272 */
273static int supR3HardenedMakePath(SUPINSTDIR enmDir, char *pszDst, size_t cchDst, bool fFatal)
274{
275 int rc;
276 switch (enmDir)
277 {
278 case kSupID_AppBin:
279 rc = supR3HardenedPathAppBin(pszDst, cchDst);
280 break;
281 case kSupID_AppSharedLib:
282 rc = supR3HardenedPathAppSharedLibs(pszDst, cchDst);
283 break;
284 case kSupID_AppPrivArch:
285 rc = supR3HardenedPathAppPrivateArch(pszDst, cchDst);
286 break;
287 case kSupID_AppPrivArchComp:
288 rc = supR3HardenedPathAppPrivateArch(pszDst, cchDst);
289 if (RT_SUCCESS(rc))
290 {
291 size_t off = suplibHardenedStrLen(pszDst);
292 if (cchDst - off >= sizeof("/components"))
293 suplibHardenedMemCopy(&pszDst[off], "/components", sizeof("/components"));
294 else
295 rc = VERR_BUFFER_OVERFLOW;
296 }
297 break;
298 case kSupID_AppPrivNoArch:
299 rc = supR3HardenedPathAppPrivateNoArch(pszDst, cchDst);
300 break;
301 case kSupID_Testcase:
302 rc = supR3HardenedPathAppBin(pszDst, cchDst);
303 if (RT_SUCCESS(rc))
304 {
305 size_t off = suplibHardenedStrLen(pszDst);
306 if (cchDst - off >= sizeof("/testcase"))
307 suplibHardenedMemCopy(&pszDst[off], "/testcase", sizeof("/testcase"));
308 else
309 rc = VERR_BUFFER_OVERFLOW;
310 }
311 break;
312 default:
313 return supR3HardenedError(VERR_INTERNAL_ERROR, fFatal,
314 "supR3HardenedMakePath: enmDir=%d\n", enmDir);
315 }
316 if (RT_FAILURE(rc))
317 supR3HardenedError(rc, fFatal,
318 "supR3HardenedMakePath: enmDir=%d rc=%d\n", enmDir, rc);
319 return rc;
320}
321
322
323
324/**
325 * Assembles the path to a file table entry, with or without the actual filename.
326 *
327 * @returns VINF_SUCCESS on success, some error code on failure (fFatal
328 * decides whether it returns or not).
329 *
330 * @param pFile The file table entry.
331 * @param pszDst Where to assemble the path.
332 * @param cchDst The size of the buffer.
333 * @param fWithFilename If set, the filename is included, otherwise it is omitted (no trailing slash).
334 * @param fFatal Whether failures should be treated as fatal (true) or not (false).
335 */
336static int supR3HardenedMakeFilePath(PCSUPINSTFILE pFile, char *pszDst, size_t cchDst, bool fWithFilename, bool fFatal)
337{
338 /*
339 * Combine supR3HardenedMakePath and the filename.
340 */
341 int rc = supR3HardenedMakePath(pFile->enmDir, pszDst, cchDst, fFatal);
342 if (RT_SUCCESS(rc) && fWithFilename)
343 {
344 size_t cchFile = suplibHardenedStrLen(pFile->pszFile);
345 size_t off = suplibHardenedStrLen(pszDst);
346 if (cchDst - off >= cchFile + 2)
347 {
348 pszDst[off++] = '/';
349 suplibHardenedMemCopy(&pszDst[off], pFile->pszFile, cchFile + 1);
350 }
351 else
352 rc = supR3HardenedError(VERR_BUFFER_OVERFLOW, fFatal,
353 "supR3HardenedMakeFilePath: pszFile=%s off=%lu\n",
354 pFile->pszFile, (long)off);
355 }
356 return rc;
357}
358
359
360/**
361 * Verifies a directory.
362 *
363 * @returns VINF_SUCCESS on success. On failure, an error code is returned if
364 * fFatal is clear and if it's set the function wont return.
365 * @param enmDir The directory specifier.
366 * @param fFatal Whether validation failures should be treated as
367 * fatal (true) or not (false).
368 */
369DECLHIDDEN(int) supR3HardenedVerifyFixedDir(SUPINSTDIR enmDir, bool fFatal)
370{
371 /*
372 * Validate the index just to be on the safe side...
373 */
374 if (enmDir <= kSupID_Invalid || enmDir >= kSupID_End)
375 return supR3HardenedError(VERR_INTERNAL_ERROR, fFatal,
376 "supR3HardenedVerifyDir: enmDir=%d\n", enmDir);
377
378 /*
379 * Already validated?
380 */
381 if (g_aSupVerifiedDirs[enmDir].fValidated)
382 return VINF_SUCCESS; /** @todo revalidate? */
383
384 /* initialize the entry. */
385 if (g_aSupVerifiedDirs[enmDir].hDir != 0)
386 supR3HardenedError(VERR_INTERNAL_ERROR, fFatal,
387 "supR3HardenedVerifyDir: hDir=%p enmDir=%d\n",
388 (void *)g_aSupVerifiedDirs[enmDir].hDir, enmDir);
389 g_aSupVerifiedDirs[enmDir].hDir = -1;
390 g_aSupVerifiedDirs[enmDir].fValidated = false;
391
392 /*
393 * Make the path and open the directory.
394 */
395 char szPath[RTPATH_MAX];
396 int rc = supR3HardenedMakePath(enmDir, szPath, sizeof(szPath), fFatal);
397 if (RT_SUCCESS(rc))
398 {
399#if defined(RT_OS_WINDOWS)
400 PRTUTF16 pwszPath;
401 rc = RTStrToUtf16(szPath, &pwszPath);
402 if (RT_SUCCESS(rc))
403 {
404 HANDLE hDir = CreateFileW(pwszPath,
405 GENERIC_READ,
406 FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE,
407 NULL,
408 OPEN_EXISTING,
409 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS,
410 NULL);
411 if (hDir != INVALID_HANDLE_VALUE)
412 {
413 /** @todo check the type */
414 /* That's all on windows, for now at least... */
415 g_aSupVerifiedDirs[enmDir].hDir = (intptr_t)hDir;
416 g_aSupVerifiedDirs[enmDir].fValidated = true;
417 }
418 else if (enmDir == kSupID_Testcase)
419 {
420 g_aSupVerifiedDirs[enmDir].fValidated = true;
421 rc = VINF_SUCCESS; /* Optional directory, ignore if missing. */
422 }
423 else
424 {
425 int err = RtlGetLastWin32Error();
426 rc = supR3HardenedError(VERR_PATH_NOT_FOUND, fFatal,
427 "supR3HardenedVerifyDir: Failed to open \"%s\": err=%d\n",
428 szPath, err);
429 }
430 RTUtf16Free(pwszPath);
431 }
432 else
433 rc = supR3HardenedError(rc, fFatal,
434 "supR3HardenedVerifyDir: Failed to convert \"%s\" to UTF-16: err=%d\n", szPath, rc);
435
436#else /* UNIXY */
437 int fd = open(szPath, O_RDONLY, 0);
438 if (fd >= 0)
439 {
440 /*
441 * On unixy systems we'll make sure the directory is owned by root
442 * and not writable by the group and user.
443 */
444 struct stat st;
445 if (!fstat(fd, &st))
446 {
447
448 if ( st.st_uid == 0
449 && !(st.st_mode & (S_IWGRP | S_IWOTH))
450 && S_ISDIR(st.st_mode))
451 {
452 g_aSupVerifiedDirs[enmDir].hDir = fd;
453 g_aSupVerifiedDirs[enmDir].fValidated = true;
454 }
455 else
456 {
457 if (!S_ISDIR(st.st_mode))
458 rc = supR3HardenedError(VERR_NOT_A_DIRECTORY, fFatal,
459 "supR3HardenedVerifyDir: \"%s\" is not a directory\n",
460 szPath, (long)st.st_uid);
461 else if (st.st_uid)
462 rc = supR3HardenedError(VERR_ACCESS_DENIED, fFatal,
463 "supR3HardenedVerifyDir: Cannot trust the directory \"%s\": not owned by root (st_uid=%ld)\n",
464 szPath, (long)st.st_uid);
465 else
466 rc = supR3HardenedError(VERR_ACCESS_DENIED, fFatal,
467 "supR3HardenedVerifyDir: Cannot trust the directory \"%s\": group and/or other writable (st_mode=0%lo)\n",
468 szPath, (long)st.st_mode);
469 close(fd);
470 }
471 }
472 else
473 {
474 int err = errno;
475 rc = supR3HardenedError(VERR_ACCESS_DENIED, fFatal,
476 "supR3HardenedVerifyDir: Failed to fstat \"%s\": %s (%d)\n",
477 szPath, strerror(err), err);
478 close(fd);
479 }
480 }
481 else if (enmDir == kSupID_Testcase)
482 {
483 g_aSupVerifiedDirs[enmDir].fValidated = true;
484 rc = VINF_SUCCESS; /* Optional directory, ignore if missing. */
485 }
486 else
487 {
488 int err = errno;
489 rc = supR3HardenedError(VERR_PATH_NOT_FOUND, fFatal,
490 "supR3HardenedVerifyDir: Failed to open \"%s\": %s (%d)\n",
491 szPath, strerror(err), err);
492 }
493#endif /* UNIXY */
494 }
495
496 return rc;
497}
498
499
500#ifdef RT_OS_WINDOWS
501/**
502 * Opens the file for verification.
503 *
504 * @returns VINF_SUCCESS on success. On failure, an error code is returned if
505 * fFatal is clear and if it's set the function wont return.
506 * @param pFile The file entry.
507 * @param fFatal Whether validation failures should be treated as
508 * kl fatal (true) or not (false).
509 * @param phFile The file handle, set to -1 if we failed to open
510 * the file. The function may return VINF_SUCCESS
511 * and a -1 handle if the file is optional.
512 */
513static int supR3HardenedVerifyFileOpen(PCSUPINSTFILE pFile, bool fFatal, intptr_t *phFile)
514{
515 *phFile = -1;
516
517 char szPath[RTPATH_MAX];
518 int rc = supR3HardenedMakeFilePath(pFile, szPath, sizeof(szPath), true /*fWithFilename*/, fFatal);
519 if (RT_SUCCESS(rc))
520 {
521 PRTUTF16 pwszPath;
522 rc = RTStrToUtf16(szPath, &pwszPath);
523 if (RT_SUCCESS(rc))
524 {
525 HANDLE hFile = CreateFileW(pwszPath,
526 GENERIC_READ,
527 FILE_SHARE_READ,
528 NULL,
529 OPEN_EXISTING,
530 FILE_ATTRIBUTE_NORMAL,
531 NULL);
532 if (hFile != INVALID_HANDLE_VALUE)
533 {
534 *phFile = (intptr_t)hFile;
535 rc = VINF_SUCCESS;
536 }
537 else
538 {
539 int err = RtlGetLastWin32Error();
540 if ( !pFile->fOptional
541 || ( err != ERROR_FILE_NOT_FOUND
542 && (err != ERROR_PATH_NOT_FOUND || pFile->enmDir != kSupID_Testcase) ) )
543 rc = supR3HardenedError(VERR_PATH_NOT_FOUND, fFatal,
544 "supR3HardenedVerifyFileInternal: Failed to open '%s': err=%d\n", szPath, err);
545 }
546 RTUtf16Free(pwszPath);
547 }
548 else
549 rc = supR3HardenedError(rc, fFatal, "supR3HardenedVerifyFileInternal: Failed to convert '%s' to UTF-16: %Rrc\n",
550 szPath, rc);
551 }
552 return rc;
553}
554
555
556/**
557 * Worker for supR3HardenedVerifyFileInternal.
558 *
559 * @returns VINF_SUCCESS on success. On failure, an error code is returned if
560 * fFatal is clear and if it's set the function wont return.
561 * @param pFile The file entry.
562 * @param pVerified The verification record.
563 * @param fFatal Whether validation failures should be treated as
564 * fatal (true) or not (false).
565 * @param fLeaveFileOpen Whether the file should be left open.
566 */
567static int supR3HardenedVerifyFileSignature(PCSUPINSTFILE pFile, PSUPVERIFIEDFILE pVerified, bool fFatal, bool fLeaveFileOpen)
568{
569# if defined(VBOX_WITH_HARDENING) && !defined(IN_SUP_R3_STATIC) /* Latter: Not in VBoxCpuReport and friends. */
570
571 /*
572 * Open the file if we have to.
573 */
574 int rc;
575 intptr_t hFileOpened;
576 intptr_t hFile = pVerified->hFile;
577 if (hFile != -1)
578 hFileOpened = -1;
579 else
580 {
581 rc = supR3HardenedVerifyFileOpen(pFile, fFatal, &hFileOpened);
582 if (RT_FAILURE(rc))
583 return rc;
584 hFile = hFileOpened;
585 }
586
587 /*
588 * Verify the signature.
589 */
590 char szErr[1024];
591 RTERRINFO ErrInfo;
592 RTErrInfoInit(&ErrInfo, szErr, sizeof(szErr));
593
594 uint32_t fFlags = SUPHNTVI_F_REQUIRE_BUILD_CERT;
595 if (pFile->enmType == kSupIFT_Rc)
596 fFlags |= SUPHNTVI_F_RC_IMAGE;
597
598 rc = supHardenedWinVerifyImageByHandleNoName((HANDLE)hFile, fFlags, &ErrInfo);
599 if (RT_SUCCESS(rc))
600 pVerified->fCheckedSignature = true;
601 else
602 {
603 pVerified->fCheckedSignature = false;
604 rc = supR3HardenedError(rc, fFatal, "supR3HardenedVerifyFileInternal: '%s': Image verify error rc=%Rrc: %s\n",
605 pFile->pszFile, rc, szErr);
606
607 }
608
609 /*
610 * Close the handle if we opened the file and we should close it.
611 */
612 if (hFileOpened != -1)
613 {
614 if (fLeaveFileOpen && RT_SUCCESS(rc))
615 pVerified->hFile = hFileOpened;
616 else
617 NtClose((HANDLE)hFileOpened);
618 }
619
620 return rc;
621
622# else /* Not checking signatures. */
623 RT_NOREF4(pFile, pVerified, fFatal, fLeaveFileOpen);
624 return VINF_SUCCESS;
625# endif /* Not checking signatures. */
626}
627#endif
628
629
630/**
631 * Verifies a file entry.
632 *
633 * @returns VINF_SUCCESS on success. On failure, an error code is returned if
634 * fFatal is clear and if it's set the function wont return.
635 *
636 * @param iFile The file table index of the file to be verified.
637 * @param fFatal Whether validation failures should be treated as
638 * fatal (true) or not (false).
639 * @param fLeaveFileOpen Whether the file should be left open.
640 * @param fVerifyAll Set if this is an verify all call and we will
641 * postpone signature checking.
642 */
643static int supR3HardenedVerifyFileInternal(int iFile, bool fFatal, bool fLeaveFileOpen, bool fVerifyAll)
644{
645#ifndef RT_OS_WINDOWS
646 RT_NOREF1(fVerifyAll);
647#endif
648 PCSUPINSTFILE pFile = &g_aSupInstallFiles[iFile];
649 PSUPVERIFIEDFILE pVerified = &g_aSupVerifiedFiles[iFile];
650
651 /*
652 * Already done validation? Do signature validation if we haven't yet.
653 */
654 if (pVerified->fValidated)
655 {
656 /** @todo revalidate? Check that the file hasn't been replace or similar. */
657#ifdef RT_OS_WINDOWS
658 if (!pVerified->fCheckedSignature && !fVerifyAll)
659 return supR3HardenedVerifyFileSignature(pFile, pVerified, fFatal, fLeaveFileOpen);
660#endif
661 return VINF_SUCCESS;
662 }
663
664
665 /* initialize the entry. */
666 if (pVerified->hFile != 0)
667 supR3HardenedError(VERR_INTERNAL_ERROR, fFatal,
668 "supR3HardenedVerifyFileInternal: hFile=%p (%s)\n",
669 (void *)pVerified->hFile, pFile->pszFile);
670 pVerified->hFile = -1;
671 pVerified->fValidated = false;
672#ifdef RT_OS_WINDOWS
673 pVerified->fCheckedSignature = false;
674#endif
675
676 /*
677 * Verify the directory then proceed to open it.
678 * (This'll make sure the directory is opened and that we can (later)
679 * use openat if we wish.)
680 */
681 int rc = supR3HardenedVerifyFixedDir(pFile->enmDir, fFatal);
682 if (RT_SUCCESS(rc))
683 {
684#if defined(RT_OS_WINDOWS)
685 rc = supR3HardenedVerifyFileOpen(pFile, fFatal, &pVerified->hFile);
686 if (RT_SUCCESS(rc))
687 {
688 if (!fVerifyAll)
689 rc = supR3HardenedVerifyFileSignature(pFile, pVerified, fFatal, fLeaveFileOpen);
690 if (RT_SUCCESS(rc))
691 {
692 pVerified->fValidated = true;
693 if (!fLeaveFileOpen)
694 {
695 NtClose((HANDLE)pVerified->hFile);
696 pVerified->hFile = -1;
697 }
698 }
699 }
700#else /* !RT_OS_WINDOWS */
701 char szPath[RTPATH_MAX];
702 rc = supR3HardenedMakeFilePath(pFile, szPath, sizeof(szPath), true /*fWithFilename*/, fFatal);
703 if (RT_SUCCESS(rc))
704 {
705 int fd = open(szPath, O_RDONLY, 0);
706 if (fd >= 0)
707 {
708 /*
709 * On unixy systems we'll make sure the file is owned by root
710 * and not writable by the group and user.
711 */
712 struct stat st;
713 if (!fstat(fd, &st))
714 {
715 if ( st.st_uid == 0
716 && !(st.st_mode & (S_IWGRP | S_IWOTH))
717 && S_ISREG(st.st_mode))
718 {
719 /* it's valid. */
720 if (fLeaveFileOpen)
721 pVerified->hFile = fd;
722 else
723 close(fd);
724 pVerified->fValidated = true;
725 }
726 else
727 {
728 if (!S_ISREG(st.st_mode))
729 rc = supR3HardenedError(VERR_IS_A_DIRECTORY, fFatal,
730 "supR3HardenedVerifyFileInternal: \"%s\" is not a regular file\n",
731 szPath, (long)st.st_uid);
732 else if (st.st_uid)
733 rc = supR3HardenedError(VERR_ACCESS_DENIED, fFatal,
734 "supR3HardenedVerifyFileInternal: Cannot trust the file \"%s\": not owned by root (st_uid=%ld)\n",
735 szPath, (long)st.st_uid);
736 else
737 rc = supR3HardenedError(VERR_ACCESS_DENIED, fFatal,
738 "supR3HardenedVerifyFileInternal: Cannot trust the file \"%s\": group and/or other writable (st_mode=0%lo)\n",
739 szPath, (long)st.st_mode);
740 close(fd);
741 }
742 }
743 else
744 {
745 int err = errno;
746 rc = supR3HardenedError(VERR_ACCESS_DENIED, fFatal,
747 "supR3HardenedVerifyFileInternal: Failed to fstat \"%s\": %s (%d)\n",
748 szPath, strerror(err), err);
749 close(fd);
750 }
751 }
752 else
753 {
754 int err = errno;
755 if (!pFile->fOptional || err != ENOENT)
756 rc = supR3HardenedError(VERR_PATH_NOT_FOUND, fFatal,
757 "supR3HardenedVerifyFileInternal: Failed to open \"%s\": %s (%d)\n",
758 szPath, strerror(err), err);
759 }
760 }
761#endif /* !RT_OS_WINDOWS */
762 }
763
764 return rc;
765}
766
767
768/**
769 * Verifies that the specified table entry matches the given filename.
770 *
771 * @returns VINF_SUCCESS if matching. On mismatch fFatal indicates whether an
772 * error is returned or we terminate the application.
773 *
774 * @param iFile The file table index.
775 * @param pszFilename The filename.
776 * @param fFatal Whether validation failures should be treated as
777 * fatal (true) or not (false).
778 */
779static int supR3HardenedVerifySameFile(int iFile, const char *pszFilename, bool fFatal)
780{
781 PCSUPINSTFILE pFile = &g_aSupInstallFiles[iFile];
782
783 /*
784 * Construct the full path for the file table entry
785 * and compare it with the specified file.
786 */
787 char szName[RTPATH_MAX];
788 int rc = supR3HardenedMakeFilePath(pFile, szName, sizeof(szName), true /*fWithFilename*/, fFatal);
789 if (RT_FAILURE(rc))
790 return rc;
791 if (SUP_COMP_FILENAME(szName, pszFilename))
792 {
793 /*
794 * Normalize the two paths and compare again.
795 */
796 rc = VERR_NOT_SAME_DEVICE;
797#if defined(RT_OS_WINDOWS)
798 LPSTR pszIgnored;
799 char szName2[RTPATH_MAX]; /** @todo Must use UTF-16 here! Code is mixing UTF-8 and native. */
800 if ( GetFullPathName(szName, RT_ELEMENTS(szName2), &szName2[0], &pszIgnored)
801 && GetFullPathName(pszFilename, RT_ELEMENTS(szName), &szName[0], &pszIgnored))
802 if (!SUP_COMP_FILENAME(szName2, szName))
803 rc = VINF_SUCCESS;
804#else
805 AssertCompile(RTPATH_MAX >= PATH_MAX);
806 char szName2[RTPATH_MAX];
807 if ( realpath(szName, szName2) != NULL
808 && realpath(pszFilename, szName) != NULL)
809 if (!SUP_COMP_FILENAME(szName2, szName))
810 rc = VINF_SUCCESS;
811#endif
812
813 if (RT_FAILURE(rc))
814 {
815 supR3HardenedMakeFilePath(pFile, szName, sizeof(szName), true /*fWithFilename*/, fFatal);
816 return supR3HardenedError(rc, fFatal,
817 "supR3HardenedVerifySameFile: \"%s\" isn't the same as \"%s\"\n",
818 pszFilename, szName);
819 }
820 }
821
822 /*
823 * Check more stuff like the stat info if it's an already open file?
824 */
825
826
827
828 return VINF_SUCCESS;
829}
830
831
832/**
833 * Verifies a file.
834 *
835 * @returns VINF_SUCCESS on success.
836 * VERR_NOT_FOUND if the file isn't in the table, this isn't ever a fatal error.
837 * On verification failure, an error code will be returned when fFatal is clear,
838 * otherwise the program will be terminated.
839 *
840 * @param pszFilename The filename.
841 * @param fFatal Whether validation failures should be treated as
842 * fatal (true) or not (false).
843 */
844DECLHIDDEN(int) supR3HardenedVerifyFixedFile(const char *pszFilename, bool fFatal)
845{
846 /*
847 * Lookup the file and check if it's the same file.
848 */
849 const char *pszName = supR3HardenedPathFilename(pszFilename);
850 for (unsigned iFile = 0; iFile < RT_ELEMENTS(g_aSupInstallFiles); iFile++)
851 if (!SUP_COMP_FILENAME(pszName, g_aSupInstallFiles[iFile].pszFile))
852 {
853 int rc = supR3HardenedVerifySameFile(iFile, pszFilename, fFatal);
854 if (RT_SUCCESS(rc))
855 rc = supR3HardenedVerifyFileInternal(iFile, fFatal, false /* fLeaveFileOpen */, false /* fVerifyAll */);
856 return rc;
857 }
858
859 return VERR_NOT_FOUND;
860}
861
862
863/**
864 * Verifies a program, worker for supR3HardenedVerifyAll.
865 *
866 * @returns See supR3HardenedVerifyAll.
867 * @param pszProgName See supR3HardenedVerifyAll.
868 * @param pszExePath The path to the executable.
869 * @param fFatal See supR3HardenedVerifyAll.
870 * @param fLeaveOpen The leave open setting used by
871 * supR3HardenedVerifyAll.
872 * @param fMainFlags Flags supplied to SUPR3HardenedMain.
873 */
874static int supR3HardenedVerifyProgram(const char *pszProgName, const char *pszExePath, bool fFatal,
875 bool fLeaveOpen, uint32_t fMainFlags)
876{
877 /*
878 * Search the table looking for the executable and the DLL/DYLIB/SO.
879 * Note! On darwin we have a hack in place for VirtualBoxVM helper app
880 * to share VirtualBox.dylib with the VirtualBox app. This ASSUMES
881 * that cchProgNameDll is equal or shorter to the exe name.
882 */
883 int rc = VINF_SUCCESS;
884 bool fExe = false;
885 bool fDll = false;
886 size_t const cchProgNameExe = suplibHardenedStrLen(pszProgName);
887#ifndef RT_OS_DARWIN
888 size_t const cchProgNameDll = cchProgNameExe;
889 NOREF(fMainFlags);
890#else
891 size_t const cchProgNameDll = fMainFlags & SUPSECMAIN_FLAGS_OSX_VM_APP
892 ? sizeof("VirtualBox") - 1
893 : cchProgNameExe;
894 if (cchProgNameDll > cchProgNameExe)
895 return supR3HardenedError(VERR_INTERNAL_ERROR, fFatal,
896 "supR3HardenedVerifyProgram: SUPSECMAIN_FLAGS_OSX_VM_APP + '%s'", pszProgName);
897#endif
898 for (unsigned iFile = 0; iFile < RT_ELEMENTS(g_aSupInstallFiles); iFile++)
899 if (!suplibHardenedStrNCmp(pszProgName, g_aSupInstallFiles[iFile].pszFile, cchProgNameDll))
900 {
901 if ( ( g_aSupInstallFiles[iFile].enmType == kSupIFT_Dll
902 || g_aSupInstallFiles[iFile].enmType == kSupIFT_TestDll)
903 && !suplibHardenedStrCmp(&g_aSupInstallFiles[iFile].pszFile[cchProgNameDll], SUPLIB_DLL_SUFF))
904 {
905 /* This only has to be found (once). */
906 if (fDll)
907 rc = supR3HardenedError(VERR_INTERNAL_ERROR, fFatal,
908 "supR3HardenedVerifyProgram: duplicate DLL entry for \"%s\"\n", pszProgName);
909 else
910 rc = supR3HardenedVerifyFileInternal(iFile, fFatal, fLeaveOpen,
911 true /* fVerifyAll - check sign later, only final process need check it on load. */);
912 fDll = true;
913 }
914 else if ( ( g_aSupInstallFiles[iFile].enmType == kSupIFT_Exe
915 || g_aSupInstallFiles[iFile].enmType == kSupIFT_TestExe)
916 && ( cchProgNameExe == cchProgNameDll
917 || !suplibHardenedStrNCmp(pszProgName, g_aSupInstallFiles[iFile].pszFile, cchProgNameExe))
918 && !suplibHardenedStrCmp(&g_aSupInstallFiles[iFile].pszFile[cchProgNameExe], SUPLIB_EXE_SUFF))
919 {
920 /* Here we'll have to check that the specific program is the same as the entry. */
921 if (fExe)
922 rc = supR3HardenedError(VERR_INTERNAL_ERROR, fFatal,
923 "supR3HardenedVerifyProgram: duplicate EXE entry for \"%s\"\n", pszProgName);
924 else
925 rc = supR3HardenedVerifyFileInternal(iFile, fFatal, fLeaveOpen, false /* fVerifyAll */);
926 fExe = true;
927
928 supR3HardenedVerifySameFile(iFile, pszExePath, fFatal);
929 }
930 }
931
932 /*
933 * Check the findings.
934 */
935 if (RT_SUCCESS(rc))
936 {
937 if (!fDll && !fExe)
938 rc = supR3HardenedError(VERR_NOT_FOUND, fFatal,
939 "supR3HardenedVerifyProgram: Couldn't find the program \"%s\"\n", pszProgName);
940 else if (!fExe)
941 rc = supR3HardenedError(VERR_NOT_FOUND, fFatal,
942 "supR3HardenedVerifyProgram: Couldn't find the EXE entry for \"%s\"\n", pszProgName);
943 else if (!fDll)
944 rc = supR3HardenedError(VERR_NOT_FOUND, fFatal,
945 "supR3HardenedVerifyProgram: Couldn't find the DLL entry for \"%s\"\n", pszProgName);
946 }
947 return rc;
948}
949
950
951/**
952 * Verifies all the known files (called from SUPR3HardenedMain).
953 *
954 * @returns VINF_SUCCESS on success.
955 * On verification failure, an error code will be returned when fFatal is clear,
956 * otherwise the program will be terminated.
957 *
958 * @param fFatal Whether validation failures should be treated as
959 * fatal (true) or not (false).
960 * @param pszProgName The program name. This is used to verify that
961 * both the executable and corresponding
962 * DLL/DYLIB/SO are valid.
963 * @param pszExePath The path to the executable.
964 * @param fMainFlags Flags supplied to SUPR3HardenedMain.
965 */
966DECLHIDDEN(int) supR3HardenedVerifyAll(bool fFatal, const char *pszProgName, const char *pszExePath, uint32_t fMainFlags)
967{
968 /*
969 * On windows
970 */
971#if defined(RT_OS_WINDOWS)
972 bool fLeaveOpen = true;
973#else
974 bool fLeaveOpen = false;
975#endif
976
977 /*
978 * The verify all the files.
979 */
980 int rc = VINF_SUCCESS;
981 for (unsigned iFile = 0; iFile < RT_ELEMENTS(g_aSupInstallFiles); iFile++)
982 {
983 int rc2 = supR3HardenedVerifyFileInternal(iFile, fFatal, fLeaveOpen, true /* fVerifyAll */);
984 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
985 rc = rc2;
986 }
987
988 /*
989 * Verify the program name, that is to say, check that it's in the table
990 * (thus verified above) and verify the signature on platforms where we
991 * sign things.
992 */
993 int rc2 = supR3HardenedVerifyProgram(pszProgName, pszExePath, fFatal, fLeaveOpen, fMainFlags);
994 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
995 rc2 = rc;
996
997 return rc;
998}
999
1000
1001/**
1002 * Copies the N messages into the error buffer and returns @a rc.
1003 *
1004 * @returns Returns @a rc
1005 * @param rc The return code.
1006 * @param pErrInfo The error info structure.
1007 * @param cMsgs The number of messages in the ellipsis.
1008 * @param ... Message parts.
1009 */
1010static int supR3HardenedSetErrorN(int rc, PRTERRINFO pErrInfo, unsigned cMsgs, ...)
1011{
1012 if (pErrInfo)
1013 {
1014 size_t cbErr = pErrInfo->cbMsg;
1015 char *pszErr = pErrInfo->pszMsg;
1016
1017 va_list va;
1018 va_start(va, cMsgs);
1019 while (cMsgs-- > 0 && cbErr > 0)
1020 {
1021 const char *pszMsg = va_arg(va, const char *);
1022 size_t cchMsg = VALID_PTR(pszMsg) ? suplibHardenedStrLen(pszMsg) : 0;
1023 if (cchMsg >= cbErr)
1024 cchMsg = cbErr - 1;
1025 suplibHardenedMemCopy(pszErr, pszMsg, cchMsg);
1026 pszErr[cchMsg] = '\0';
1027 pszErr += cchMsg;
1028 cbErr -= cchMsg;
1029 }
1030 va_end(va);
1031
1032 pErrInfo->rc = rc;
1033 pErrInfo->fFlags |= RTERRINFO_FLAGS_SET;
1034 }
1035
1036 return rc;
1037}
1038
1039
1040#if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX)
1041/**
1042 * Copies the four messages into the error buffer and returns @a rc.
1043 *
1044 * @returns Returns @a rc
1045 * @param rc The return code.
1046 * @param pErrInfo The error info structure.
1047 * @param pszMsg1 The first message part.
1048 * @param pszMsg2 The second message part.
1049 * @param pszMsg3 The third message part.
1050 * @param pszMsg4 The fourth message part.
1051 */
1052static int supR3HardenedSetError4(int rc, PRTERRINFO pErrInfo, const char *pszMsg1,
1053 const char *pszMsg2, const char *pszMsg3, const char *pszMsg4)
1054{
1055 return supR3HardenedSetErrorN(rc, pErrInfo, 4, pszMsg1, pszMsg2, pszMsg3, pszMsg4);
1056}
1057#endif
1058
1059
1060/**
1061 * Copies the three messages into the error buffer and returns @a rc.
1062 *
1063 * @returns Returns @a rc
1064 * @param rc The return code.
1065 * @param pErrInfo The error info structure.
1066 * @param pszMsg1 The first message part.
1067 * @param pszMsg2 The second message part.
1068 * @param pszMsg3 The third message part.
1069 */
1070static int supR3HardenedSetError3(int rc, PRTERRINFO pErrInfo, const char *pszMsg1,
1071 const char *pszMsg2, const char *pszMsg3)
1072{
1073 return supR3HardenedSetErrorN(rc, pErrInfo, 3, pszMsg1, pszMsg2, pszMsg3);
1074}
1075
1076
1077#ifdef SOME_UNUSED_FUNCTION
1078/**
1079 * Copies the two messages into the error buffer and returns @a rc.
1080 *
1081 * @returns Returns @a rc
1082 * @param rc The return code.
1083 * @param pErrInfo The error info structure.
1084 * @param pszMsg1 The first message part.
1085 * @param pszMsg2 The second message part.
1086 */
1087static int supR3HardenedSetError2(int rc, PRTERRINFO pErrInfo, const char *pszMsg1,
1088 const char *pszMsg2)
1089{
1090 return supR3HardenedSetErrorN(rc, pErrInfo, 2, pszMsg1, pszMsg2);
1091}
1092#endif
1093
1094
1095#ifndef SUP_HARDENED_VERIFY_FOLLOW_SYMLINKS_USE_REALPATH
1096# if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX)
1097/**
1098 * Copies the error message to the error buffer and returns @a rc.
1099 *
1100 * @returns Returns @a rc
1101 * @param rc The return code.
1102 * @param pErrInfo The error info structure.
1103 * @param pszMsg The message.
1104 */
1105static int supR3HardenedSetError(int rc, PRTERRINFO pErrInfo, const char *pszMsg)
1106{
1107 return supR3HardenedSetErrorN(rc, pErrInfo, 1, pszMsg);
1108}
1109# endif
1110#endif
1111
1112
1113/**
1114 * Output from a successfull supR3HardenedVerifyPathSanity call.
1115 */
1116typedef struct SUPR3HARDENEDPATHINFO
1117{
1118 /** The length of the path in szCopy. */
1119 uint16_t cch;
1120 /** The number of path components. */
1121 uint16_t cComponents;
1122 /** Set if the path ends with slash, indicating that it's a directory
1123 * reference and not a file reference. The slash has been removed from
1124 * the copy. */
1125 bool fDirSlash;
1126 /** The offset where each path component starts, i.e. the char after the
1127 * slash. The array has cComponents + 1 entries, where the final one is
1128 * cch + 1 so that one can always terminate the current component by
1129 * szPath[aoffComponent[i] - 1] = '\0'. */
1130 uint16_t aoffComponents[32+1];
1131 /** A normalized copy of the path.
1132 * Reserve some extra space so we can be more relaxed about overflow
1133 * checks and terminator paddings, especially when recursing. */
1134 char szPath[SUPR3HARDENED_MAX_PATH * 2];
1135} SUPR3HARDENEDPATHINFO;
1136/** Pointer to a parsed path. */
1137typedef SUPR3HARDENEDPATHINFO *PSUPR3HARDENEDPATHINFO;
1138
1139
1140/**
1141 * Verifies that the path is absolutely sane, it also parses the path.
1142 *
1143 * A sane path starts at the root (w/ drive letter on DOS derived systems) and
1144 * does not have any relative bits (/../) or unnecessary slashes (/bin//ls).
1145 * Sane paths are less or equal to SUPR3HARDENED_MAX_PATH bytes in length. UNC
1146 * paths are not supported.
1147 *
1148 * @returns VBox status code.
1149 * @param pszPath The path to check.
1150 * @param pErrInfo The error info structure.
1151 * @param pInfo Where to return a copy of the path along with
1152 * parsing information.
1153 */
1154static int supR3HardenedVerifyPathSanity(const char *pszPath, PRTERRINFO pErrInfo, PSUPR3HARDENEDPATHINFO pInfo)
1155{
1156 const char *pszSrc = pszPath;
1157 char *pszDst = pInfo->szPath;
1158
1159 /*
1160 * Check that it's an absolute path and copy the volume/root specifier.
1161 */
1162#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
1163 if ( !RT_C_IS_ALPHA(pszSrc[0])
1164 || pszSrc[1] != ':'
1165 || !RTPATH_IS_SLASH(pszSrc[2]))
1166 return supR3HardenedSetError3(VERR_SUPLIB_PATH_NOT_ABSOLUTE, pErrInfo, "The path is not absolute: '", pszPath, "'");
1167
1168 *pszDst++ = RT_C_TO_UPPER(pszSrc[0]);
1169 *pszDst++ = ':';
1170 *pszDst++ = RTPATH_SLASH;
1171 pszSrc += 3;
1172
1173#else
1174 if (!RTPATH_IS_SLASH(pszSrc[0]))
1175 return supR3HardenedSetError3(VERR_SUPLIB_PATH_NOT_ABSOLUTE, pErrInfo, "The path is not absolute: '", pszPath, "'");
1176
1177 *pszDst++ = RTPATH_SLASH;
1178 pszSrc += 1;
1179#endif
1180
1181 /*
1182 * No path specifying the root or something very shortly thereafter will
1183 * be approved of.
1184 */
1185 if (pszSrc[0] == '\0')
1186 return supR3HardenedSetError3(VERR_SUPLIB_PATH_IS_ROOT, pErrInfo, "The path is root: '", pszPath, "'");
1187 if ( pszSrc[1] == '\0'
1188 || pszSrc[2] == '\0')
1189 return supR3HardenedSetError3(VERR_SUPLIB_PATH_TOO_SHORT, pErrInfo, "The path is too short: '", pszPath, "'");
1190
1191#if RTPATH_STYLE == RTPATH_STR_F_STYLE_UNIX
1192 /*
1193 * Skip double slashes.
1194 */
1195 while (RTPATH_IS_SLASH(*pszSrc))
1196 pszSrc++;
1197#else
1198 /*
1199 * The root slash should be alone to avoid UNC confusion.
1200 */
1201 if (RTPATH_IS_SLASH(pszSrc[0]))
1202 return supR3HardenedSetError3(VERR_SUPLIB_PATH_NOT_CLEAN, pErrInfo,
1203 "The path is not clean of leading double slashes: '", pszPath, "'");
1204#endif
1205 /*
1206 * Check each component. No parent references.
1207 */
1208 pInfo->cComponents = 0;
1209 pInfo->fDirSlash = false;
1210 while (pszSrc[0])
1211 {
1212 /* Sanity checks. */
1213 if ( pszSrc[0] == '.'
1214 && pszSrc[1] == '.'
1215 && RTPATH_IS_SLASH(pszSrc[2]))
1216 return supR3HardenedSetError3(VERR_SUPLIB_PATH_NOT_ABSOLUTE, pErrInfo,
1217 "The path is not absolute: '", pszPath, "'");
1218
1219 /* Record the start of the component. */
1220 if (pInfo->cComponents >= RT_ELEMENTS(pInfo->aoffComponents) - 1)
1221 return supR3HardenedSetError3(VERR_SUPLIB_PATH_TOO_MANY_COMPONENTS, pErrInfo,
1222 "The path has too many components: '", pszPath, "'");
1223 pInfo->aoffComponents[pInfo->cComponents++] = pszDst - &pInfo->szPath[0];
1224
1225 /* Traverse to the end of the component, copying it as we go along. */
1226 while (pszSrc[0])
1227 {
1228 if (RTPATH_IS_SLASH(pszSrc[0]))
1229 {
1230 pszSrc++;
1231 if (*pszSrc)
1232 *pszDst++ = RTPATH_SLASH;
1233 else
1234 pInfo->fDirSlash = true;
1235 break;
1236 }
1237 *pszDst++ = *pszSrc++;
1238 if ((uintptr_t)(pszDst - &pInfo->szPath[0]) >= SUPR3HARDENED_MAX_PATH)
1239 return supR3HardenedSetError3(VERR_SUPLIB_PATH_TOO_LONG, pErrInfo,
1240 "The path is too long: '", pszPath, "'");
1241 }
1242
1243 /* Skip double slashes. */
1244 while (RTPATH_IS_SLASH(*pszSrc))
1245 pszSrc++;
1246 }
1247
1248 /* Terminate the string and enter its length. */
1249 pszDst[0] = '\0';
1250 pszDst[1] = '\0'; /* for aoffComponents */
1251 pInfo->cch = (uint16_t)(pszDst - &pInfo->szPath[0]);
1252 pInfo->aoffComponents[pInfo->cComponents] = pInfo->cch + 1;
1253
1254 return VINF_SUCCESS;
1255}
1256
1257
1258/**
1259 * The state information collected by supR3HardenedVerifyFsObject.
1260 *
1261 * This can be used to verify that a directory we've opened for enumeration is
1262 * the same as the one that supR3HardenedVerifyFsObject just verified. It can
1263 * equally be used to verify a native specfied by the user.
1264 */
1265typedef struct SUPR3HARDENEDFSOBJSTATE
1266{
1267#ifdef RT_OS_WINDOWS
1268 /** Not implemented for windows yet. */
1269 char chTodo;
1270#else
1271 /** The stat output. */
1272 struct stat Stat;
1273#endif
1274} SUPR3HARDENEDFSOBJSTATE;
1275/** Pointer to a file system object state. */
1276typedef SUPR3HARDENEDFSOBJSTATE *PSUPR3HARDENEDFSOBJSTATE;
1277/** Pointer to a const file system object state. */
1278typedef SUPR3HARDENEDFSOBJSTATE const *PCSUPR3HARDENEDFSOBJSTATE;
1279
1280
1281/**
1282 * Query information about a file system object by path.
1283 *
1284 * @returns VBox status code, error buffer filled on failure.
1285 * @param pszPath The path to the object.
1286 * @param pFsObjState Where to return the state information.
1287 * @param pErrInfo The error info structure.
1288 */
1289static int supR3HardenedQueryFsObjectByPath(char const *pszPath, PSUPR3HARDENEDFSOBJSTATE pFsObjState, PRTERRINFO pErrInfo)
1290{
1291#if defined(RT_OS_WINDOWS)
1292 /** @todo Windows hardening. */
1293 pFsObjState->chTodo = 0;
1294 RT_NOREF2(pszPath, pErrInfo);
1295 return VINF_SUCCESS;
1296
1297#else
1298 /*
1299 * Stat the object, do not follow links.
1300 */
1301 if (lstat(pszPath, &pFsObjState->Stat) != 0)
1302 {
1303 /* Ignore access errors */
1304 if (errno != EACCES)
1305 return supR3HardenedSetErrorN(VERR_SUPLIB_STAT_FAILED, pErrInfo,
1306 5, "stat failed with ", strerror(errno), " on: '", pszPath, "'");
1307 }
1308
1309 /*
1310 * Read ACLs.
1311 */
1312 /** @todo */
1313
1314 return VINF_SUCCESS;
1315#endif
1316}
1317
1318
1319/**
1320 * Query information about a file system object by native handle.
1321 *
1322 * @returns VBox status code, error buffer filled on failure.
1323 * @param hNative The native handle to the object @a pszPath
1324 * specifies and this should be verified to be the
1325 * same file system object.
1326 * @param pFsObjState Where to return the state information.
1327 * @param pszPath The path to the object. (For the error message
1328 * only.)
1329 * @param pErrInfo The error info structure.
1330 */
1331static int supR3HardenedQueryFsObjectByHandle(RTHCUINTPTR hNative, PSUPR3HARDENEDFSOBJSTATE pFsObjState,
1332 char const *pszPath, PRTERRINFO pErrInfo)
1333{
1334#if defined(RT_OS_WINDOWS)
1335 /** @todo Windows hardening. */
1336 pFsObjState->chTodo = 0;
1337 RT_NOREF3(hNative, pszPath, pErrInfo);
1338 return VINF_SUCCESS;
1339
1340#else
1341 /*
1342 * Stat the object, do not follow links.
1343 */
1344 if (fstat((int)hNative, &pFsObjState->Stat) != 0)
1345 return supR3HardenedSetErrorN(VERR_SUPLIB_STAT_FAILED, pErrInfo,
1346 5, "fstat failed with ", strerror(errno), " on '", pszPath, "'");
1347
1348 /*
1349 * Read ACLs.
1350 */
1351 /** @todo */
1352
1353 return VINF_SUCCESS;
1354#endif
1355}
1356
1357
1358/**
1359 * Verifies that the file system object indicated by the native handle is the
1360 * same as the one @a pFsObjState indicates.
1361 *
1362 * @returns VBox status code, error buffer filled on failure.
1363 * @param pFsObjState1 File system object information/state by path.
1364 * @param pFsObjState2 File system object information/state by handle.
1365 * @param pszPath The path to the object @a pFsObjState
1366 * describes. (For the error message.)
1367 * @param pErrInfo The error info structure.
1368 */
1369static int supR3HardenedIsSameFsObject(PCSUPR3HARDENEDFSOBJSTATE pFsObjState1, PCSUPR3HARDENEDFSOBJSTATE pFsObjState2,
1370 const char *pszPath, PRTERRINFO pErrInfo)
1371{
1372#if defined(RT_OS_WINDOWS)
1373 /** @todo Windows hardening. */
1374 RT_NOREF4(pFsObjState1, pFsObjState2, pszPath, pErrInfo);
1375 return VINF_SUCCESS;
1376
1377#elif defined(RT_OS_OS2)
1378 RT_NOREF4(pFsObjState1, pFsObjState2, pszPath, pErrInfo);
1379 return VINF_SUCCESS;
1380
1381#else
1382 /*
1383 * Compare the ino+dev, then the uid+gid and finally the important mode
1384 * bits. Technically the first one should be enough, but we're paranoid.
1385 */
1386 if ( pFsObjState1->Stat.st_ino != pFsObjState2->Stat.st_ino
1387 || pFsObjState1->Stat.st_dev != pFsObjState2->Stat.st_dev)
1388 return supR3HardenedSetError3(VERR_SUPLIB_NOT_SAME_OBJECT, pErrInfo,
1389 "The native handle is not the same as '", pszPath, "' (ino/dev)");
1390 if ( pFsObjState1->Stat.st_uid != pFsObjState2->Stat.st_uid
1391 || pFsObjState1->Stat.st_gid != pFsObjState2->Stat.st_gid)
1392 return supR3HardenedSetError3(VERR_SUPLIB_NOT_SAME_OBJECT, pErrInfo,
1393 "The native handle is not the same as '", pszPath, "' (uid/gid)");
1394 if ( (pFsObjState1->Stat.st_mode & (S_IFMT | S_IWUSR | S_IWGRP | S_IWOTH))
1395 != (pFsObjState2->Stat.st_mode & (S_IFMT | S_IWUSR | S_IWGRP | S_IWOTH)))
1396 return supR3HardenedSetError3(VERR_SUPLIB_NOT_SAME_OBJECT, pErrInfo,
1397 "The native handle is not the same as '", pszPath, "' (mode)");
1398 return VINF_SUCCESS;
1399#endif
1400}
1401
1402
1403/**
1404 * Verifies a file system object (file or directory).
1405 *
1406 * @returns VBox status code, error buffer filled on failure.
1407 * @param pFsObjState The file system object information/state to be
1408 * verified.
1409 * @param fDir Whether this is a directory or a file.
1410 * @param fRelaxed Whether we can be more relaxed about this
1411 * directory (only used for grand parent
1412 * directories).
1413 * @param fSymlinksAllowed Flag whether symlinks are allowed or not.
1414 * If allowed the symlink object is verified not the target.
1415 * @param pszPath The path to the object. For error messages and
1416 * securing a couple of hacks.
1417 * @param pErrInfo The error info structure.
1418 */
1419static int supR3HardenedVerifyFsObject(PCSUPR3HARDENEDFSOBJSTATE pFsObjState, bool fDir, bool fRelaxed,
1420 bool fSymlinksAllowed, const char *pszPath, PRTERRINFO pErrInfo)
1421{
1422#if defined(RT_OS_WINDOWS)
1423 /** @todo Windows hardening. */
1424 RT_NOREF(pFsObjState, fDir, fRelaxed, fSymlinksAllowed, pszPath, pErrInfo);
1425 return VINF_SUCCESS;
1426
1427#elif defined(RT_OS_OS2)
1428 /* No hardening here - it's a single user system. */
1429 RT_NOREF(pFsObjState, fDir, fRelaxed, fSymlinksAllowed, pszPath, pErrInfo);
1430 return VINF_SUCCESS;
1431
1432#else
1433 /*
1434 * The owner must be root.
1435 *
1436 * This can be extended to include predefined system users if necessary.
1437 */
1438 if (pFsObjState->Stat.st_uid != 0)
1439 return supR3HardenedSetError3(VERR_SUPLIB_OWNER_NOT_ROOT, pErrInfo, "The owner is not root: '", pszPath, "'");
1440
1441 /*
1442 * The object type must be directory or file. It can be a symbolic link
1443 * if explicitely allowed. Otherwise this and other risky stuff is not allowed
1444 * (sorry dude, but we're paranoid on purpose here).
1445 */
1446 if ( !S_ISLNK(pFsObjState->Stat.st_mode)
1447 || !fSymlinksAllowed)
1448 {
1449
1450 if ( !S_ISDIR(pFsObjState->Stat.st_mode)
1451 && !S_ISREG(pFsObjState->Stat.st_mode))
1452 {
1453 if (S_ISLNK(pFsObjState->Stat.st_mode))
1454 return supR3HardenedSetError3(VERR_SUPLIB_SYMLINKS_ARE_NOT_PERMITTED, pErrInfo,
1455 "Symlinks are not permitted: '", pszPath, "'");
1456 return supR3HardenedSetError3(VERR_SUPLIB_NOT_DIR_NOT_FILE, pErrInfo,
1457 "Not regular file or directory: '", pszPath, "'");
1458 }
1459 if (fDir != !!S_ISDIR(pFsObjState->Stat.st_mode))
1460 {
1461 if (S_ISDIR(pFsObjState->Stat.st_mode))
1462 return supR3HardenedSetError3(VERR_SUPLIB_IS_DIRECTORY, pErrInfo,
1463 "Expected file but found directory: '", pszPath, "'");
1464 return supR3HardenedSetError3(VERR_SUPLIB_IS_FILE, pErrInfo,
1465 "Expected directory but found file: '", pszPath, "'");
1466 }
1467 }
1468
1469 /*
1470 * The group does not matter if it does not have write access, if it has
1471 * write access it must be group 0 (root/wheel/whatever).
1472 *
1473 * This can be extended to include predefined system groups or groups that
1474 * only root is member of.
1475 */
1476 if ( (pFsObjState->Stat.st_mode & S_IWGRP)
1477 && pFsObjState->Stat.st_gid != 0)
1478 {
1479# ifdef RT_OS_DARWIN
1480 /* HACK ALERT: On Darwin /Applications is root:admin with admin having
1481 full access. So, to work around we relax the hardening a bit and
1482 permit grand parents and beyond to be group writable by admin. */
1483 /** @todo dynamically resolve the admin group? */
1484 bool fBad = !fRelaxed || pFsObjState->Stat.st_gid != 80 /*admin*/ || suplibHardenedStrCmp(pszPath, "/Applications");
1485
1486# elif defined(RT_OS_FREEBSD)
1487 /* HACK ALERT: PC-BSD 9 has group-writable /usr/pib directory which is
1488 similar to /Applications on OS X (see above).
1489 On FreeBSD root is normally the only member of this group, on
1490 PC-BSD the default user is a member. */
1491 /** @todo dynamically resolve the operator group? */
1492 bool fBad = !fRelaxed || pFsObjState->Stat.st_gid != 5 /*operator*/ || suplibHardenedStrCmp(pszPath, "/usr/pbi");
1493 NOREF(fRelaxed);
1494# elif defined(RT_OS_SOLARIS)
1495 /* HACK ALERT: Solaris has group-writable /usr/lib/iconv directory from
1496 which the appropriate module is loaded.
1497 By default only root and daemon are part of that group.
1498 . */
1499 /** @todo dynamically resolve the bin group? */
1500 bool fBad = !fRelaxed || pFsObjState->Stat.st_gid != 2 /*bin*/ || suplibHardenedStrCmp(pszPath, "/usr/lib/iconv");
1501# else
1502 NOREF(fRelaxed);
1503 bool fBad = true;
1504# endif
1505 if (fBad)
1506 return supR3HardenedSetError3(VERR_SUPLIB_WRITE_NON_SYS_GROUP, pErrInfo,
1507 "An unknown (and thus untrusted) group has write access to '", pszPath,
1508 "' and we therefore cannot trust the directory content or that of any subdirectory");
1509 }
1510
1511 /*
1512 * World must not have write access. There is no relaxing this rule.
1513 * Linux exception: Symbolic links are always give permission 0777, there
1514 * is no lchmod or lchown APIs. The permissions on parent
1515 * directory that contains the symbolic link is what is
1516 * decising wrt to modifying it. (Caller is expected not
1517 * to allow symbolic links in the first path component.)
1518 */
1519 if ( (pFsObjState->Stat.st_mode & S_IWOTH)
1520# ifdef RT_OS_LINUX
1521 && ( !S_ISLNK(pFsObjState->Stat.st_mode)
1522 || !fSymlinksAllowed /* paranoia */)
1523# endif
1524 )
1525 return supR3HardenedSetError3(VERR_SUPLIB_WORLD_WRITABLE, pErrInfo,
1526 "World writable: '", pszPath, "'");
1527
1528 /*
1529 * Check the ACLs.
1530 */
1531 /** @todo */
1532
1533 return VINF_SUCCESS;
1534#endif
1535}
1536
1537
1538/**
1539 * Verifies that the file system object indicated by the native handle is the
1540 * same as the one @a pFsObjState indicates.
1541 *
1542 * @returns VBox status code, error buffer filled on failure.
1543 * @param hNative The native handle to the object @a pszPath
1544 * specifies and this should be verified to be the
1545 * same file system object.
1546 * @param pFsObjState The information/state returned by a previous
1547 * query call.
1548 * @param pszPath The path to the object @a pFsObjState
1549 * describes. (For the error message.)
1550 * @param pErrInfo The error info structure.
1551 */
1552static int supR3HardenedVerifySameFsObject(RTHCUINTPTR hNative, PCSUPR3HARDENEDFSOBJSTATE pFsObjState,
1553 const char *pszPath, PRTERRINFO pErrInfo)
1554{
1555 SUPR3HARDENEDFSOBJSTATE FsObjState2;
1556 int rc = supR3HardenedQueryFsObjectByHandle(hNative, &FsObjState2, pszPath, pErrInfo);
1557 if (RT_SUCCESS(rc))
1558 rc = supR3HardenedIsSameFsObject(pFsObjState, &FsObjState2, pszPath, pErrInfo);
1559 return rc;
1560}
1561
1562
1563/**
1564 * Does the recursive directory enumeration.
1565 *
1566 * @returns VBox status code, error buffer filled on failure.
1567 * @param pszDirPath The path buffer containing the subdirectory to
1568 * enumerate followed by a slash (this is never
1569 * the root slash). The buffer is RTPATH_MAX in
1570 * size and anything starting at @a cchDirPath
1571 * - 1 and beyond is scratch space.
1572 * @param cchDirPath The length of the directory path + slash.
1573 * @param pFsObjState Pointer to the file system object state buffer.
1574 * On input this will hold the stats for
1575 * the directory @a pszDirPath indicates and will
1576 * be used to verified that we're opening the same
1577 * thing.
1578 * @param fRecursive Whether to recurse into subdirectories.
1579 * @param pErrInfo The error info structure.
1580 */
1581static int supR3HardenedVerifyDirRecursive(char *pszDirPath, size_t cchDirPath, PSUPR3HARDENEDFSOBJSTATE pFsObjState,
1582 bool fRecursive, PRTERRINFO pErrInfo)
1583{
1584#if defined(RT_OS_WINDOWS)
1585 /** @todo Windows hardening. */
1586 RT_NOREF5(pszDirPath, cchDirPath, pFsObjState, fRecursive, pErrInfo);
1587 return VINF_SUCCESS;
1588
1589#elif defined(RT_OS_OS2)
1590 /* No hardening here - it's a single user system. */
1591 RT_NOREF5(pszDirPath, cchDirPath, pFsObjState, fRecursive, pErrInfo);
1592 return VINF_SUCCESS;
1593
1594#else
1595 /*
1596 * Open the directory. Now, we could probably eliminate opendir here
1597 * and go down on kernel API level (open + getdents for instance), however
1598 * that's not very portable and hopefully not necessary.
1599 */
1600 DIR *pDir = opendir(pszDirPath);
1601 if (!pDir)
1602 {
1603 /* Ignore access errors. */
1604 if (errno == EACCES)
1605 return VINF_SUCCESS;
1606 return supR3HardenedSetErrorN(VERR_SUPLIB_DIR_ENUM_FAILED, pErrInfo,
1607 5, "opendir failed with ", strerror(errno), " on '", pszDirPath, "'");
1608 }
1609 if (dirfd(pDir) != -1)
1610 {
1611 int rc = supR3HardenedVerifySameFsObject(dirfd(pDir), pFsObjState, pszDirPath, pErrInfo);
1612 if (RT_FAILURE(rc))
1613 {
1614 closedir(pDir);
1615 return rc;
1616 }
1617 }
1618
1619 /*
1620 * Enumerate the directory, check all the requested bits.
1621 */
1622 int rc = VINF_SUCCESS;
1623 for (;;)
1624 {
1625 pszDirPath[cchDirPath] = '\0'; /* for error messages. */
1626
1627 struct dirent Entry;
1628 struct dirent *pEntry;
1629#if RT_GNUC_PREREQ(4, 6)
1630# pragma GCC diagnostic push
1631# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
1632#endif
1633 int iErr = readdir_r(pDir, &Entry, &pEntry);
1634#if RT_GNUC_PREREQ(4, 6)
1635# pragma GCC diagnostic pop
1636#endif
1637 if (iErr)
1638 {
1639 rc = supR3HardenedSetErrorN(VERR_SUPLIB_DIR_ENUM_FAILED, pErrInfo,
1640 5, "readdir_r failed with ", strerror(iErr), " in '", pszDirPath, "'");
1641 break;
1642 }
1643 if (!pEntry)
1644 break;
1645
1646 /*
1647 * Check the length and copy it into the path buffer so it can be
1648 * stat()'ed.
1649 */
1650 size_t cchName = suplibHardenedStrLen(pEntry->d_name);
1651 if (cchName + cchDirPath > SUPR3HARDENED_MAX_PATH)
1652 {
1653 rc = supR3HardenedSetErrorN(VERR_SUPLIB_PATH_TOO_LONG, pErrInfo,
1654 4, "Path grew too long during recursion: '", pszDirPath, pEntry->d_name, "'");
1655 break;
1656 }
1657 suplibHardenedMemCopy(&pszDirPath[cchName], pEntry->d_name, cchName + 1);
1658
1659 /*
1660 * Query the information about the entry and verify it.
1661 * (We don't bother skipping '.' and '..' at this point, a little bit
1662 * of extra checks doesn't hurt and neither requires relaxed handling.)
1663 */
1664 rc = supR3HardenedQueryFsObjectByPath(pszDirPath, pFsObjState, pErrInfo);
1665 if (RT_SUCCESS(rc))
1666 break;
1667 rc = supR3HardenedVerifyFsObject(pFsObjState, S_ISDIR(pFsObjState->Stat.st_mode), false /*fRelaxed*/,
1668 false /*fSymlinksAllowed*/, pszDirPath, pErrInfo);
1669 if (RT_FAILURE(rc))
1670 break;
1671
1672 /*
1673 * Recurse into subdirectories if requested.
1674 */
1675 if ( fRecursive
1676 && S_ISDIR(pFsObjState->Stat.st_mode)
1677 && suplibHardenedStrCmp(pEntry->d_name, ".")
1678 && suplibHardenedStrCmp(pEntry->d_name, ".."))
1679 {
1680 pszDirPath[cchDirPath + cchName] = RTPATH_SLASH;
1681 pszDirPath[cchDirPath + cchName + 1] = '\0';
1682
1683 rc = supR3HardenedVerifyDirRecursive(pszDirPath, cchDirPath + cchName + 1, pFsObjState,
1684 fRecursive, pErrInfo);
1685 if (RT_FAILURE(rc))
1686 break;
1687 }
1688 }
1689
1690 closedir(pDir);
1691 return VINF_SUCCESS;
1692#endif
1693}
1694
1695
1696/**
1697 * Worker for SUPR3HardenedVerifyDir.
1698 *
1699 * @returns See SUPR3HardenedVerifyDir.
1700 * @param pszDirPath See SUPR3HardenedVerifyDir.
1701 * @param fRecursive See SUPR3HardenedVerifyDir.
1702 * @param fCheckFiles See SUPR3HardenedVerifyDir.
1703 * @param pErrInfo See SUPR3HardenedVerifyDir.
1704 */
1705DECLHIDDEN(int) supR3HardenedVerifyDir(const char *pszDirPath, bool fRecursive, bool fCheckFiles, PRTERRINFO pErrInfo)
1706{
1707 /*
1708 * Validate the input path and parse it.
1709 */
1710 SUPR3HARDENEDPATHINFO Info;
1711 int rc = supR3HardenedVerifyPathSanity(pszDirPath, pErrInfo, &Info);
1712 if (RT_FAILURE(rc))
1713 return rc;
1714
1715 /*
1716 * Verify each component from the root up.
1717 */
1718 SUPR3HARDENEDFSOBJSTATE FsObjState;
1719 uint32_t const cComponents = Info.cComponents;
1720 for (uint32_t iComponent = 0; iComponent < cComponents; iComponent++)
1721 {
1722 bool fRelaxed = iComponent + 2 < cComponents;
1723 Info.szPath[Info.aoffComponents[iComponent + 1] - 1] = '\0';
1724 rc = supR3HardenedQueryFsObjectByPath(Info.szPath, &FsObjState, pErrInfo);
1725 if (RT_SUCCESS(rc))
1726 rc = supR3HardenedVerifyFsObject(&FsObjState, true /*fDir*/, fRelaxed,
1727 false /*fSymlinksAllowed*/, Info.szPath, pErrInfo);
1728 if (RT_FAILURE(rc))
1729 return rc;
1730 Info.szPath[Info.aoffComponents[iComponent + 1] - 1] = iComponent + 1 != cComponents ? RTPATH_SLASH : '\0';
1731 }
1732
1733 /*
1734 * Check files and subdirectories if requested.
1735 */
1736 if (fCheckFiles || fRecursive)
1737 {
1738 Info.szPath[Info.cch] = RTPATH_SLASH;
1739 Info.szPath[Info.cch + 1] = '\0';
1740 return supR3HardenedVerifyDirRecursive(Info.szPath, Info.cch + 1, &FsObjState,
1741 fRecursive, pErrInfo);
1742 }
1743
1744 return VINF_SUCCESS;
1745}
1746
1747
1748/**
1749 * Verfies a file.
1750 *
1751 * @returns VBox status code, error buffer filled on failure.
1752 * @param pszFilename The file to verify.
1753 * @param hNativeFile Handle to the file, verify that it's the same
1754 * as we ended up with when verifying the path.
1755 * RTHCUINTPTR_MAX means NIL here.
1756 * @param fMaybe3rdParty Set if the file is could be a supplied by a
1757 * third party. Different validation rules may
1758 * apply to 3rd party code on some platforms.
1759 * @param pErrInfo Where to return extended error information.
1760 * Optional.
1761 */
1762DECLHIDDEN(int) supR3HardenedVerifyFile(const char *pszFilename, RTHCUINTPTR hNativeFile,
1763 bool fMaybe3rdParty, PRTERRINFO pErrInfo)
1764{
1765 /*
1766 * Validate the input path and parse it.
1767 */
1768 SUPR3HARDENEDPATHINFO Info;
1769 int rc = supR3HardenedVerifyPathSanity(pszFilename, pErrInfo, &Info);
1770 if (RT_FAILURE(rc))
1771 return rc;
1772 if (Info.fDirSlash)
1773 return supR3HardenedSetError3(VERR_SUPLIB_IS_DIRECTORY, pErrInfo,
1774 "The file path specifies a directory: '", pszFilename, "'");
1775
1776 /*
1777 * Verify each component from the root up.
1778 */
1779 SUPR3HARDENEDFSOBJSTATE FsObjState;
1780 uint32_t const cComponents = Info.cComponents;
1781 for (uint32_t iComponent = 0; iComponent < cComponents; iComponent++)
1782 {
1783 bool fFinal = iComponent + 1 == cComponents;
1784 bool fRelaxed = iComponent + 2 < cComponents;
1785 Info.szPath[Info.aoffComponents[iComponent + 1] - 1] = '\0';
1786 rc = supR3HardenedQueryFsObjectByPath(Info.szPath, &FsObjState, pErrInfo);
1787 if (RT_SUCCESS(rc))
1788 rc = supR3HardenedVerifyFsObject(&FsObjState, !fFinal /*fDir*/, fRelaxed,
1789 false /*fSymlinksAllowed*/, Info.szPath, pErrInfo);
1790 if (RT_FAILURE(rc))
1791 return rc;
1792 Info.szPath[Info.aoffComponents[iComponent + 1] - 1] = !fFinal ? RTPATH_SLASH : '\0';
1793 }
1794
1795 /*
1796 * Verify the file handle against the last component, if specified.
1797 */
1798 if (hNativeFile != RTHCUINTPTR_MAX)
1799 {
1800 rc = supR3HardenedVerifySameFsObject(hNativeFile, &FsObjState, Info.szPath, pErrInfo);
1801 if (RT_FAILURE(rc))
1802 return rc;
1803 }
1804
1805#ifdef RT_OS_WINDOWS
1806 /*
1807 * The files shall be signed on windows, verify that.
1808 */
1809 rc = VINF_SUCCESS;
1810 HANDLE hVerify;
1811 if (hNativeFile == RTHCUINTPTR_MAX)
1812 {
1813 PRTUTF16 pwszPath;
1814 rc = RTStrToUtf16(pszFilename, &pwszPath);
1815 if (RT_SUCCESS(rc))
1816 {
1817 hVerify = CreateFileW(pwszPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1818 RTUtf16Free(pwszPath);
1819 }
1820 else
1821 {
1822 rc = RTErrInfoSetF(pErrInfo, rc, "Error converting '%s' to UTF-16: %Rrc", pszFilename, rc);
1823 hVerify = INVALID_HANDLE_VALUE;
1824 }
1825 }
1826 else
1827 {
1828 NTSTATUS rcNt = NtDuplicateObject(NtCurrentProcess(), (HANDLE)hNativeFile, NtCurrentProcess(), &hVerify,
1829 GENERIC_READ, 0 /*HandleAttributes*/, 0 /*Options*/);
1830 if (!NT_SUCCESS(rcNt))
1831 hVerify = INVALID_HANDLE_VALUE;
1832 }
1833 if (hVerify != INVALID_HANDLE_VALUE)
1834 {
1835# ifdef VBOX_WITH_HARDENING
1836 uint32_t fFlags = SUPHNTVI_F_REQUIRE_KERNEL_CODE_SIGNING;
1837 if (!fMaybe3rdParty)
1838 fFlags = SUPHNTVI_F_REQUIRE_BUILD_CERT;
1839 const char *pszSuffix = RTPathSuffix(pszFilename);
1840 if ( pszSuffix
1841 && pszSuffix[0] == '.'
1842 && ( RT_C_TO_LOWER(pszSuffix[1]) == 'r'
1843 || RT_C_TO_LOWER(pszSuffix[1]) == 'g')
1844 && RT_C_TO_LOWER(pszSuffix[2]) == 'c'
1845 && pszSuffix[3] == '\0' )
1846 fFlags |= SUPHNTVI_F_RC_IMAGE;
1847# ifndef IN_SUP_R3_STATIC /* Not in VBoxCpuReport and friends. */
1848 rc = supHardenedWinVerifyImageByHandleNoName(hVerify, fFlags, pErrInfo);
1849# endif
1850# else
1851 RT_NOREF1(fMaybe3rdParty);
1852# endif
1853 NtClose(hVerify);
1854 }
1855 else if (RT_SUCCESS(rc))
1856 rc = RTErrInfoSetF(pErrInfo, RTErrConvertFromWin32(RtlGetLastWin32Error()),
1857 "Error %u trying to open (or duplicate handle for) '%s'", RtlGetLastWin32Error(), pszFilename);
1858 if (RT_FAILURE(rc))
1859 return rc;
1860#else
1861 RT_NOREF1(fMaybe3rdParty);
1862#endif
1863
1864 return VINF_SUCCESS;
1865}
1866
1867
1868#if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX)
1869/**
1870 * Verfies a file following symlinks.
1871 *
1872 * @returns VBox status code, error buffer filled on failure.
1873 * @param pszFilename The file to verify.
1874 * @param hNativeFile Handle to the file, verify that it's the same
1875 * as we ended up with when verifying the path.
1876 * RTHCUINTPTR_MAX means NIL here.
1877 * @param fMaybe3rdParty Set if the file is could be a supplied by a
1878 * third party. Different validation rules may
1879 * apply to 3rd party code on some platforms.
1880 * @param pErrInfo Where to return extended error information.
1881 * Optional.
1882 *
1883 * @note This is only used on OS X for libraries loaded with dlopen() because
1884 * the frameworks use symbolic links to point to the relevant library.
1885 *
1886 * @sa supR3HardenedVerifyFile
1887 */
1888DECLHIDDEN(int) supR3HardenedVerifyFileFollowSymlinks(const char *pszFilename, RTHCUINTPTR hNativeFile, bool fMaybe3rdParty,
1889 PRTERRINFO pErrInfo)
1890{
1891 RT_NOREF1(fMaybe3rdParty);
1892
1893 /*
1894 * Validate the input path and parse it.
1895 */
1896 SUPR3HARDENEDPATHINFO Info;
1897 int rc = supR3HardenedVerifyPathSanity(pszFilename, pErrInfo, &Info);
1898 if (RT_FAILURE(rc))
1899 return rc;
1900 if (Info.fDirSlash)
1901 return supR3HardenedSetError3(VERR_SUPLIB_IS_DIRECTORY, pErrInfo,
1902 "The file path specifies a directory: '", pszFilename, "'");
1903
1904 /*
1905 * Verify each component from the root up.
1906 */
1907#ifndef SUP_HARDENED_VERIFY_FOLLOW_SYMLINKS_USE_REALPATH
1908 uint32_t iLoops = 0;
1909#endif
1910 SUPR3HARDENEDFSOBJSTATE FsObjState;
1911 uint32_t iComponent = 0;
1912 while (iComponent < Info.cComponents)
1913 {
1914 bool fFinal = iComponent + 1 == Info.cComponents;
1915 bool fRelaxed = iComponent + 2 < Info.cComponents;
1916 Info.szPath[Info.aoffComponents[iComponent + 1] - 1] = '\0';
1917 rc = supR3HardenedQueryFsObjectByPath(Info.szPath, &FsObjState, pErrInfo);
1918 if (RT_SUCCESS(rc))
1919 {
1920 /*
1921 * In case the component is a symlink expand it and start from the beginning after
1922 * verifying it has the proper access rights.
1923 * Furthermore only allow symlinks which don't contain any .. or . in the target
1924 * (enforced by supR3HardenedVerifyPathSanity).
1925 */
1926 rc = supR3HardenedVerifyFsObject(&FsObjState, !fFinal /*fDir*/, fRelaxed,
1927 true /*fSymlinksAllowed*/, Info.szPath, pErrInfo);
1928 if ( RT_SUCCESS(rc)
1929 && S_ISLNK(FsObjState.Stat.st_mode))
1930 {
1931#if SUP_HARDENED_VERIFY_FOLLOW_SYMLINKS_USE_REALPATH /* Another approach using realpath() and verifying the result when encountering a symlink. */
1932 char *pszFilenameResolved = realpath(pszFilename, NULL);
1933 if (pszFilenameResolved)
1934 {
1935 rc = supR3HardenedVerifyFile(pszFilenameResolved, hNativeFile, fMaybe3rdParty, pErrInfo);
1936 free(pszFilenameResolved);
1937 return rc;
1938 }
1939 else
1940 {
1941 int iErr = errno;
1942 supR3HardenedError(VERR_ACCESS_DENIED, false /*fFatal*/,
1943 "supR3HardenedVerifyFileFollowSymlinks: Failed to resolve the real path '%s': %s (%d)\n",
1944 pszFilename, strerror(iErr), iErr);
1945 return supR3HardenedSetError4(VERR_ACCESS_DENIED, pErrInfo,
1946 "realpath failed for '", pszFilename, "': ", strerror(iErr));
1947 }
1948#else
1949 /* Don't loop forever. */
1950 iLoops++;
1951 if (iLoops < 8)
1952 {
1953 /*
1954 * Construct new path by replacing the current component by the symlink value.
1955 * Note! readlink() is a weird API that doesn't necessarily indicates if the
1956 * buffer is too small.
1957 */
1958 char szPath[RTPATH_MAX];
1959 size_t const cchBefore = Info.aoffComponents[iComponent]; /* includes slash */
1960 size_t const cchAfter = fFinal ? 0 : 1 /*slash*/ + Info.cch - Info.aoffComponents[iComponent + 1];
1961 if (sizeof(szPath) > cchBefore + cchAfter + 2)
1962 {
1963 ssize_t cchTarget = readlink(Info.szPath, szPath, sizeof(szPath) - 1);
1964 if (cchTarget > 0)
1965 {
1966 /* Some serious paranoia against embedded zero terminator and weird return values. */
1967 szPath[cchTarget] = '\0';
1968 size_t cchLink = strlen(szPath);
1969
1970 /* Strip trailing dirslashes of non-final link. */
1971 if (!fFinal)
1972 while (cchLink > 1 and szPath[cchLink - 1] == '/')
1973 cchLink--;
1974
1975 /* Check link value sanity and buffer size. */
1976 if (cchLink == 0)
1977 return supR3HardenedSetError3(VERR_ACCESS_DENIED, pErrInfo,
1978 "Bad readlink return for '", Info.szPath, "'");
1979 if (szPath[0] == '/')
1980 return supR3HardenedSetError3(VERR_ACCESS_DENIED, pErrInfo,
1981 "Absolute symbolic link not allowed: '", szPath, "'");
1982 if (cchBefore + cchLink + cchAfter + 1 /*terminator*/ > sizeof(szPath))
1983 return supR3HardenedSetError(VERR_SUPLIB_PATH_TOO_LONG, pErrInfo,
1984 "Symlinks causing too long path!");
1985
1986 /* Construct the new path. */
1987 if (cchBefore)
1988 memmove(&szPath[cchBefore], &szPath[0], cchLink);
1989 memcpy(&szPath[0], Info.szPath, cchBefore);
1990 if (!cchAfter)
1991 szPath[cchBefore + cchLink] = '\0';
1992 else
1993 {
1994 szPath[cchBefore + cchLink] = RTPATH_SLASH;
1995 memcpy(&szPath[cchBefore + cchLink + 1],
1996 &Info.szPath[Info.aoffComponents[iComponent + 1]],
1997 cchAfter); /* cchAfter includes a zero terminator */
1998 }
1999
2000 /* Parse, copy and check the sanity (no '..' or '.') of the altered path. */
2001 rc = supR3HardenedVerifyPathSanity(szPath, pErrInfo, &Info);
2002 if (RT_FAILURE(rc))
2003 return rc;
2004 if (Info.fDirSlash)
2005 return supR3HardenedSetError3(VERR_SUPLIB_IS_DIRECTORY, pErrInfo,
2006 "The file path specifies a directory: '", szPath, "'");
2007
2008 /* Restart from the current component. */
2009 continue;
2010 }
2011 int iErr = errno;
2012 supR3HardenedError(VERR_ACCESS_DENIED, false /*fFatal*/,
2013 "supR3HardenedVerifyFileFollowSymlinks: Failed to readlink '%s': %s (%d)\n",
2014 Info.szPath, strerror(iErr), iErr);
2015 return supR3HardenedSetError4(VERR_ACCESS_DENIED, pErrInfo,
2016 "readlink failed for '", Info.szPath, "': ", strerror(iErr));
2017 }
2018 return supR3HardenedSetError(VERR_SUPLIB_PATH_TOO_LONG, pErrInfo, "Path too long for symlink replacing!");
2019 }
2020 else
2021 return supR3HardenedSetError3(VERR_TOO_MANY_SYMLINKS, pErrInfo,
2022 "Too many symbolic links: '", pszFilename, "'");
2023#endif
2024 }
2025 }
2026 if (RT_FAILURE(rc))
2027 return rc;
2028 Info.szPath[Info.aoffComponents[iComponent + 1] - 1] = !fFinal ? RTPATH_SLASH : '\0';
2029 iComponent++;
2030 }
2031
2032 /*
2033 * Verify the file handle against the last component, if specified.
2034 */
2035 if (hNativeFile != RTHCUINTPTR_MAX)
2036 {
2037 rc = supR3HardenedVerifySameFsObject(hNativeFile, &FsObjState, Info.szPath, pErrInfo);
2038 if (RT_FAILURE(rc))
2039 return rc;
2040 }
2041
2042 return VINF_SUCCESS;
2043}
2044#endif /* RT_OS_DARWIN || RT_OS_LINUX */
2045
2046
2047/**
2048 * Gets the pre-init data for the hand-over to the other version
2049 * of this code.
2050 *
2051 * The reason why we pass this information on is that it contains
2052 * open directories and files. Later it may include even more info
2053 * (int the verified arrays mostly).
2054 *
2055 * The receiver is supR3HardenedRecvPreInitData.
2056 *
2057 * @param pPreInitData Where to store it.
2058 */
2059DECLHIDDEN(void) supR3HardenedGetPreInitData(PSUPPREINITDATA pPreInitData)
2060{
2061 pPreInitData->cInstallFiles = RT_ELEMENTS(g_aSupInstallFiles);
2062 pPreInitData->paInstallFiles = &g_aSupInstallFiles[0];
2063 pPreInitData->paVerifiedFiles = &g_aSupVerifiedFiles[0];
2064
2065 pPreInitData->cVerifiedDirs = RT_ELEMENTS(g_aSupVerifiedDirs);
2066 pPreInitData->paVerifiedDirs = &g_aSupVerifiedDirs[0];
2067}
2068
2069
2070/**
2071 * Receives the pre-init data from the static executable stub.
2072 *
2073 * @returns VBox status code. Will not bitch on failure since the
2074 * runtime isn't ready for it, so that is left to the exe stub.
2075 *
2076 * @param pPreInitData The hand-over data.
2077 */
2078DECLHIDDEN(int) supR3HardenedRecvPreInitData(PCSUPPREINITDATA pPreInitData)
2079{
2080 /*
2081 * Compare the array lengths and the contents of g_aSupInstallFiles.
2082 */
2083 if ( pPreInitData->cInstallFiles != RT_ELEMENTS(g_aSupInstallFiles)
2084 || pPreInitData->cVerifiedDirs != RT_ELEMENTS(g_aSupVerifiedDirs))
2085 return VERR_VERSION_MISMATCH;
2086 SUPINSTFILE const *paInstallFiles = pPreInitData->paInstallFiles;
2087 for (unsigned iFile = 0; iFile < RT_ELEMENTS(g_aSupInstallFiles); iFile++)
2088 if ( g_aSupInstallFiles[iFile].enmDir != paInstallFiles[iFile].enmDir
2089 || g_aSupInstallFiles[iFile].enmType != paInstallFiles[iFile].enmType
2090 || g_aSupInstallFiles[iFile].fOptional != paInstallFiles[iFile].fOptional
2091 || suplibHardenedStrCmp(g_aSupInstallFiles[iFile].pszFile, paInstallFiles[iFile].pszFile))
2092 return VERR_VERSION_MISMATCH;
2093
2094 /*
2095 * Check that we're not called out of order.
2096 * If dynamic linking it screwed up, we may end up here.
2097 */
2098 if ( !ASMMemIsZero(&g_aSupVerifiedFiles[0], sizeof(g_aSupVerifiedFiles))
2099 || !ASMMemIsZero(&g_aSupVerifiedDirs[0], sizeof(g_aSupVerifiedDirs)))
2100 return VERR_WRONG_ORDER;
2101
2102 /*
2103 * Copy the verification data over.
2104 */
2105 suplibHardenedMemCopy(&g_aSupVerifiedFiles[0], pPreInitData->paVerifiedFiles, sizeof(g_aSupVerifiedFiles));
2106 suplibHardenedMemCopy(&g_aSupVerifiedDirs[0], pPreInitData->paVerifiedDirs, sizeof(g_aSupVerifiedDirs));
2107 return VINF_SUCCESS;
2108}
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette