VirtualBox

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

Last change on this file since 40029 was 39133, checked in by vboxsync, 13 years ago

SUPR3HardenedVerify.cpp: tightened the Mac OS X and PC-BSD 9 hacks.

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