VirtualBox

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

最後變更 在這個檔案從57351是 57351,由 vboxsync 提交於 10 年 前

tstGIP-2: Hardening.

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

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