VirtualBox

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

Last change on this file since 66632 was 66632, checked in by vboxsync, 8 years ago

HostDrivers/Support: Allow following symlinks on Linux for libraries loaded through dlopen()

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