VirtualBox

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

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

SUPR3HardenedVerify.cpp: Corrected CreateFileW result check (NULL vs INVALID_HANDLE_VALUE).

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

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