VirtualBox

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

Last change on this file since 48952 was 47894, checked in by vboxsync, 11 years ago

VBoxNetLwipNAT => VBoxNetNAT

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