VirtualBox

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

Last change on this file since 57252 was 56817, checked in by vboxsync, 9 years ago

Attempt at fixing VirtualBoxVM (untested).

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

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