VirtualBox

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

Last change on this file since 38323 was 37344, checked in by vboxsync, 14 years ago

comment

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 58.1 KB
Line 
1/* $Id: SUPR3HardenedVerify.cpp 37344 2011-06-07 12:23:53Z 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))
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, 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
817/**
818 * Copies the two messages into the error buffer and returns @a rc.
819 *
820 * @returns Returns @a rc
821 * @param rc The return code.
822 * @param pErrInfo The error info structure.
823 * @param pszMsg1 The first message part.
824 * @param pszMsg2 The second message part.
825 */
826static int supR3HardenedSetError2(int rc, PRTERRINFO pErrInfo, const char *pszMsg1,
827 const char *pszMsg2)
828{
829 return supR3HardenedSetErrorN(rc, pErrInfo, 2, pszMsg1, pszMsg2);
830}
831
832
833/**
834 * Copies the error message to the error buffer and returns @a rc.
835 *
836 * @returns Returns @a rc
837 * @param rc The return code.
838 * @param pErrInfo The error info structure.
839 * @param pszMsg The message.
840 */
841static int supR3HardenedSetError(int rc, PRTERRINFO pErrInfo, const char *pszMsg)
842{
843 return supR3HardenedSetErrorN(rc, pErrInfo, 1, pszMsg);
844}
845
846
847/**
848 * Output from a successfull supR3HardenedVerifyPathSanity call.
849 */
850typedef struct SUPR3HARDENEDPATHINFO
851{
852 /** The length of the path in szCopy. */
853 uint16_t cch;
854 /** The number of path components. */
855 uint16_t cComponents;
856 /** Set if the path ends with slash, indicating that it's a directory
857 * reference and not a file reference. The slash has been removed from
858 * the copy. */
859 bool fDirSlash;
860 /** The offset where each path component starts, i.e. the char after the
861 * slash. The array has cComponents + 1 entries, where the final one is
862 * cch + 1 so that one can always terminate the current component by
863 * szPath[aoffComponent[i] - 1] = '\0'. */
864 uint16_t aoffComponents[32+1];
865 /** A normalized copy of the path.
866 * Reserve some extra space so we can be more relaxed about overflow
867 * checks and terminator paddings, especially when recursing. */
868 char szPath[SUPR3HARDENED_MAX_PATH * 2];
869} SUPR3HARDENEDPATHINFO;
870/** Pointer to a parsed path. */
871typedef SUPR3HARDENEDPATHINFO *PSUPR3HARDENEDPATHINFO;
872
873
874/**
875 * Verifies that the path is absolutely sane, it also parses the path.
876 *
877 * A sane path starts at the root (w/ drive letter on DOS derived systems) and
878 * does not have any relative bits (/../) or unnecessary slashes (/bin//ls).
879 * Sane paths are less or equal to SUPR3HARDENED_MAX_PATH bytes in length. UNC
880 * paths are not supported.
881 *
882 * @returns VBox status code.
883 * @param pszPath The path to check.
884 * @param pErrInfo The error info structure.
885 * @param pInfo Where to return a copy of the path along with
886 * parsing information.
887 */
888static int supR3HardenedVerifyPathSanity(const char *pszPath, PRTERRINFO pErrInfo, PSUPR3HARDENEDPATHINFO pInfo)
889{
890 const char *pszSrc = pszPath;
891 char *pszDst = pInfo->szPath;
892
893 /*
894 * Check that it's an absolute path and copy the volume/root specifier.
895 */
896#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
897 if ( RT_C_IS_ALPHA(pszSrc[0])
898 || pszSrc[1] != ':'
899 || !RTPATH_IS_SLASH(pszSrc[2]))
900 return supR3HardenedSetError3(VERR_SUPLIB_PATH_NOT_ABSOLUTE, pErrInfo, "The path is not absolute: '", pszPath, "'");
901
902 *pszDst++ = RT_C_TO_UPPER(pszSrc[0]);
903 *pszDst++ = ':';
904 *pszDst++ = RTPATH_SLASH;
905 pszSrc += 3;
906
907#else
908 if (!RTPATH_IS_SLASH(pszSrc[0]))
909 return supR3HardenedSetError3(VERR_SUPLIB_PATH_NOT_ABSOLUTE, pErrInfo, "The path is not absolute: '", pszPath, "'");
910
911 *pszDst++ = RTPATH_SLASH;
912 pszSrc += 1;
913#endif
914
915 /*
916 * No path specifying the root or something very shortly thereafter will
917 * be approved of.
918 */
919 if (pszSrc[0] == '\0')
920 return supR3HardenedSetError3(VERR_SUPLIB_PATH_IS_ROOT, pErrInfo, "The path is root: '", pszPath, "'");
921 if ( pszSrc[1] == '\0'
922 || pszSrc[2] == '\0')
923 return supR3HardenedSetError3(VERR_SUPLIB_PATH_TOO_SHORT, pErrInfo, "The path is too short: '", pszPath, "'");
924
925 /*
926 * Check each component. No parent references or double slashes.
927 */
928 pInfo->cComponents = 0;
929 pInfo->fDirSlash = false;
930 while (pszSrc[0])
931 {
932 /* Sanity checks. */
933 if (RTPATH_IS_SLASH(pszSrc[0])) /* can be relaxed if we care. */
934 return supR3HardenedSetError3(VERR_SUPLIB_PATH_NOT_CLEAN, pErrInfo,
935 "The path is not clean of double slashes: '", pszPath, "'");
936 if ( pszSrc[0] == '.'
937 && pszSrc[1] == '.'
938 && RTPATH_IS_SLASH(pszSrc[2]))
939 return supR3HardenedSetError3(VERR_SUPLIB_PATH_NOT_ABSOLUTE, pErrInfo,
940 "The path is not absolute: '", pszPath, "'");
941
942 /* Record the start of the component. */
943 if (pInfo->cComponents >= RT_ELEMENTS(pInfo->aoffComponents) - 1)
944 return supR3HardenedSetError3(VERR_SUPLIB_PATH_TOO_MANY_COMPONENTS, pErrInfo,
945 "The path has too many components: '", pszPath, "'");
946 pInfo->aoffComponents[pInfo->cComponents++] = pszDst - &pInfo->szPath[0];
947
948 /* Traverse to the end of the component, copying it as we go along. */
949 while (pszSrc[0])
950 {
951 if (RTPATH_IS_SLASH(pszSrc[0]))
952 {
953 pszSrc++;
954 if (*pszSrc)
955 *pszDst++ = RTPATH_SLASH;
956 else
957 pInfo->fDirSlash = true;
958 break;
959 }
960 *pszDst++ = *pszSrc++;
961 if ((uintptr_t)(pszDst - &pInfo->szPath[0]) >= SUPR3HARDENED_MAX_PATH)
962 return supR3HardenedSetError3(VERR_SUPLIB_PATH_TOO_LONG, pErrInfo,
963 "The path is too long: '", pszPath, "'");
964 }
965 }
966
967 /* Terminate the string and enter its length. */
968 pszDst[0] = '\0';
969 pszDst[1] = '\0'; /* for aoffComponents */
970 pInfo->cch = (uint16_t)(pszDst - &pInfo->szPath[0]);
971 pInfo->aoffComponents[pInfo->cComponents] = pInfo->cch + 1;
972
973 return VINF_SUCCESS;
974}
975
976
977/**
978 * The state information collected by supR3HardenedVerifyFsObject.
979 *
980 * This can be used to verify that a directory we've opened for enumeration is
981 * the same as the one that supR3HardenedVerifyFsObject just verified. It can
982 * equally be used to verify a native specfied by the user.
983 */
984typedef struct SUPR3HARDENEDFSOBJSTATE
985{
986#ifdef RT_OS_WINDOWS
987 /** Not implemented for windows yet. */
988 char chTodo;
989#else
990 /** The stat output. */
991 struct stat Stat;
992#endif
993} SUPR3HARDENEDFSOBJSTATE;
994/** Pointer to a file system object state. */
995typedef SUPR3HARDENEDFSOBJSTATE *PSUPR3HARDENEDFSOBJSTATE;
996/** Pointer to a const file system object state. */
997typedef SUPR3HARDENEDFSOBJSTATE const *PCSUPR3HARDENEDFSOBJSTATE;
998
999
1000/**
1001 * Query information about a file system object by path.
1002 *
1003 * @returns VBox status code, error buffer filled on failure.
1004 * @param pszPath The path to the object.
1005 * @param pFsObjState Where to return the state information.
1006 * @param pErrInfo The error info structure.
1007 */
1008static int supR3HardenedQueryFsObjectByPath(char const *pszPath, PSUPR3HARDENEDFSOBJSTATE pFsObjState, PRTERRINFO pErrInfo)
1009{
1010#if defined(RT_OS_WINDOWS)
1011 /** @todo Windows hardening. */
1012 pFsObjState->chTodo = 0;
1013 return VINF_SUCCESS;
1014
1015#else
1016 /*
1017 * Stat the object, do not follow links.
1018 */
1019 if (lstat(pszPath, &pFsObjState->Stat) != 0)
1020 {
1021 /* Ignore access errors */
1022 if (errno != EACCES)
1023 return supR3HardenedSetErrorN(VERR_SUPLIB_STAT_FAILED, pErrInfo,
1024 5, "stat failed with ", strerror(errno), " on: '", pszPath, "'");
1025 }
1026
1027 /*
1028 * Read ACLs.
1029 */
1030 /** @todo */
1031
1032 return VINF_SUCCESS;
1033#endif
1034}
1035
1036
1037/**
1038 * Query information about a file system object by native handle.
1039 *
1040 * @returns VBox status code, error buffer filled on failure.
1041 * @param hNative The native handle to the object @a pszPath
1042 * specifies and this should be verified to be the
1043 * same file system object.
1044 * @param pFsObjState Where to return the state information.
1045 * @param pszPath The path to the object. (For the error message
1046 * only.)
1047 * @param pErrInfo The error info structure.
1048 */
1049static int supR3HardenedQueryFsObjectByHandle(RTHCUINTPTR hNative, PSUPR3HARDENEDFSOBJSTATE pFsObjState,
1050 char const *pszPath, PRTERRINFO pErrInfo)
1051{
1052#if defined(RT_OS_WINDOWS)
1053 /** @todo Windows hardening. */
1054 pFsObjState->chTodo = 0;
1055 return VINF_SUCCESS;
1056
1057#else
1058 /*
1059 * Stat the object, do not follow links.
1060 */
1061 if (fstat((int)hNative, &pFsObjState->Stat) != 0)
1062 return supR3HardenedSetErrorN(VERR_SUPLIB_STAT_FAILED, pErrInfo,
1063 5, "fstat failed with ", strerror(errno), " on '", pszPath, "'");
1064
1065 /*
1066 * Read ACLs.
1067 */
1068 /** @todo */
1069
1070 return VINF_SUCCESS;
1071#endif
1072}
1073
1074
1075/**
1076 * Verifies that the file system object indicated by the native handle is the
1077 * same as the one @a pFsObjState indicates.
1078 *
1079 * @returns VBox status code, error buffer filled on failure.
1080 * @param pFsObjState1 File system object information/state by path.
1081 * @param pFsObjState2 File system object information/state by handle.
1082 * @param pszPath The path to the object @a pFsObjState
1083 * describes. (For the error message.)
1084 * @param pErrInfo The error info structure.
1085 */
1086static int supR3HardenedIsSameFsObject(PCSUPR3HARDENEDFSOBJSTATE pFsObjState1, PCSUPR3HARDENEDFSOBJSTATE pFsObjState2,
1087 const char *pszPath, PRTERRINFO pErrInfo)
1088{
1089#if defined(RT_OS_WINDOWS)
1090 /** @todo Windows hardening. */
1091 return VINF_SUCCESS;
1092
1093#elif defined(RT_OS_OS2)
1094 return VINF_SUCCESS;
1095
1096#else
1097 /*
1098 * Compare the ino+dev, then the uid+gid and finally the important mode
1099 * bits. Technically the first one should be enough, but we're paranoid.
1100 */
1101 if ( pFsObjState1->Stat.st_ino != pFsObjState2->Stat.st_ino
1102 || pFsObjState1->Stat.st_dev != pFsObjState2->Stat.st_dev)
1103 return supR3HardenedSetError3(VERR_SUPLIB_NOT_SAME_OBJECT, pErrInfo,
1104 "The native handle is not the same as '", pszPath, "' (ino/dev)");
1105 if ( pFsObjState1->Stat.st_uid != pFsObjState2->Stat.st_uid
1106 || pFsObjState1->Stat.st_gid != pFsObjState2->Stat.st_gid)
1107 return supR3HardenedSetError3(VERR_SUPLIB_NOT_SAME_OBJECT, pErrInfo,
1108 "The native handle is not the same as '", pszPath, "' (uid/gid)");
1109 if ( (pFsObjState1->Stat.st_mode & (S_IFMT | S_IWUSR | S_IWGRP | S_IWOTH))
1110 != (pFsObjState2->Stat.st_mode & (S_IFMT | S_IWUSR | S_IWGRP | S_IWOTH)))
1111 return supR3HardenedSetError3(VERR_SUPLIB_NOT_SAME_OBJECT, pErrInfo,
1112 "The native handle is not the same as '", pszPath, "' (mode)");
1113 return VINF_SUCCESS;
1114#endif
1115}
1116
1117
1118/**
1119 * Verifies a file system object (file or directory).
1120 *
1121 * @returns VBox status code, error buffer filled on failure.
1122 * @param pFsObjState The file system object information/state to be
1123 * verified.
1124 * @param fDir Whether this is a directory or a file.
1125 * @param fRelaxed Whether we can be more relaxed about this
1126 * directory (only used for grand parent
1127 * directories).
1128 * @param pszPath The path to the object. (For error messages
1129 * only.)
1130 * @param pErrInfo The error info structure.
1131 */
1132static int supR3HardenedVerifyFsObject(PCSUPR3HARDENEDFSOBJSTATE pFsObjState, bool fDir, bool fRelaxed,
1133 const char *pszPath, PRTERRINFO pErrInfo)
1134{
1135#if defined(RT_OS_WINDOWS)
1136 /** @todo Windows hardening. */
1137 return VINF_SUCCESS;
1138
1139#elif defined(RT_OS_OS2)
1140 /* No hardening here - it's a single user system. */
1141 return VINF_SUCCESS;
1142
1143#else
1144 /*
1145 * The owner must be root.
1146 *
1147 * This can be extended to include predefined system users if necessary.
1148 */
1149 if (pFsObjState->Stat.st_uid != 0)
1150 return supR3HardenedSetError3(VERR_SUPLIB_OWNER_NOT_ROOT, pErrInfo, "The owner is not root: '", pszPath, "'");
1151
1152 /*
1153 * The object type must be directory or file, no symbolic links or other
1154 * risky stuff (sorry dude, but we're paranoid on purpose here).
1155 */
1156 if ( !S_ISDIR(pFsObjState->Stat.st_mode)
1157 && !S_ISREG(pFsObjState->Stat.st_mode))
1158 {
1159 if (S_ISLNK(pFsObjState->Stat.st_mode))
1160 return supR3HardenedSetError3(VERR_SUPLIB_SYMLINKS_ARE_NOT_PERMITTED, pErrInfo,
1161 "Symlinks are not permitted: '", pszPath, "'");
1162 return supR3HardenedSetError3(VERR_SUPLIB_NOT_DIR_NOT_FILE, pErrInfo,
1163 "Not regular file or directory: '", pszPath, "'");
1164 }
1165 if (fDir != !!S_ISDIR(pFsObjState->Stat.st_mode))
1166 {
1167 if (S_ISDIR(pFsObjState->Stat.st_mode))
1168 return supR3HardenedSetError3(VERR_SUPLIB_IS_DIRECTORY, pErrInfo,
1169 "Expected file but found directory: '", pszPath, "'");
1170 return supR3HardenedSetError3(VERR_SUPLIB_IS_FILE, pErrInfo,
1171 "Expected directory but found file: '", pszPath, "'");
1172 }
1173
1174 /*
1175 * The group does not matter if it does not have write access, if it has
1176 * write access it must be group 0 (root/wheel/whatever).
1177 *
1178 * This can be extended to include predefined system groups or groups that
1179 * only root is member of.
1180 */
1181 if ( (pFsObjState->Stat.st_mode & S_IWGRP)
1182 && pFsObjState->Stat.st_gid != 0)
1183 {
1184#ifdef RT_OS_DARWIN
1185 /* HACK ALERT: On Darwin /Applications is root:admin with admin having
1186 full access. So, to work around we relax the hardening a bit and
1187 permit grand parents and beyond to be group writable by admin. */
1188 if (pFsObjState->Stat.st_gid != 80 /*admin*/) /** @todo dynamically resolve the admin group? */
1189#elif defined(RT_OS_FREEBSD)
1190 /* HACK ALERT: PC-BSD 9 has group-writable application directory,
1191 similar to OS X and their /Applications directory (see above). */
1192 if (pFsObjState->Stat.st_gid != 5 /*operators*/)
1193#endif
1194 return supR3HardenedSetError3(VERR_SUPLIB_WRITE_NON_SYS_GROUP, pErrInfo,
1195 "The group is not a system group and it has write access to '", pszPath, "'");
1196 }
1197
1198 /*
1199 * World must not have write access. There is no relaxing this rule.
1200 */
1201 if (pFsObjState->Stat.st_mode & S_IWOTH)
1202 return supR3HardenedSetError3(VERR_SUPLIB_WORLD_WRITABLE, pErrInfo,
1203 "World writable: '", pszPath, "'");
1204
1205 /*
1206 * Check the ACLs.
1207 */
1208 /** @todo */
1209
1210 return VINF_SUCCESS;
1211#endif
1212
1213}
1214
1215
1216/**
1217 * Verifies that the file system object indicated by the native handle is the
1218 * same as the one @a pFsObjState indicates.
1219 *
1220 * @returns VBox status code, error buffer filled on failure.
1221 * @param hNative The native handle to the object @a pszPath
1222 * specifies and this should be verified to be the
1223 * same file system object.
1224 * @param pFsObjState The information/state returned by a previous
1225 * query call.
1226 * @param pszPath The path to the object @a pFsObjState
1227 * describes. (For the error message.)
1228 * @param pErrInfo The error info structure.
1229 */
1230static int supR3HardenedVerifySameFsObject(RTHCUINTPTR hNative, PCSUPR3HARDENEDFSOBJSTATE pFsObjState,
1231 const char *pszPath, PRTERRINFO pErrInfo)
1232{
1233 SUPR3HARDENEDFSOBJSTATE FsObjState2;
1234 int rc = supR3HardenedQueryFsObjectByHandle(hNative, &FsObjState2, pszPath, pErrInfo);
1235 if (RT_SUCCESS(rc))
1236 rc = supR3HardenedIsSameFsObject(pFsObjState, &FsObjState2, pszPath, pErrInfo);
1237 return rc;
1238}
1239
1240
1241/**
1242 * Does the recursive directory enumeration.
1243 *
1244 * @returns VBox status code, error buffer filled on failure.
1245 * @param pszDirPath The path buffer containing the subdirectory to
1246 * enumerate followed by a slash (this is never
1247 * the root slash). The buffer is RTPATH_MAX in
1248 * size and anything starting at @a cchDirPath
1249 * - 1 and beyond is scratch space.
1250 * @param cchDirPath The length of the directory path + slash.
1251 * @param pFsObjState Pointer to the file system object state buffer.
1252 * On input this will hold the stats for
1253 * the directory @a pszDirPath indicates and will
1254 * be used to verified that we're opening the same
1255 * thing.
1256 * @param fRecursive Whether to recurse into subdirectories.
1257 * @param pErrInfo The error info structure.
1258 */
1259static int supR3HardenedVerifyDirRecursive(char *pszDirPath, size_t cchDirPath, PSUPR3HARDENEDFSOBJSTATE pFsObjState,
1260 bool fRecursive, PRTERRINFO pErrInfo)
1261{
1262#if defined(RT_OS_WINDOWS)
1263 /** @todo Windows hardening. */
1264 return VINF_SUCCESS;
1265
1266#elif defined(RT_OS_OS2)
1267 /* No hardening here - it's a single user system. */
1268 return VINF_SUCCESS;
1269
1270#else
1271 /*
1272 * Open the directory. Now, we could probably eliminate opendir here
1273 * and go down on kernel API level (open + getdents for instance), however
1274 * that's not very portable and hopefully not necessary.
1275 */
1276 DIR *pDir = opendir(pszDirPath);
1277 if (!pDir)
1278 {
1279 /* Ignore access errors. */
1280 if (errno == EACCES)
1281 return VINF_SUCCESS;
1282 return supR3HardenedSetErrorN(VERR_SUPLIB_DIR_ENUM_FAILED, pErrInfo,
1283 5, "opendir failed with ", strerror(errno), " on '", pszDirPath, "'");
1284 }
1285 if (dirfd(pDir) != -1)
1286 {
1287 int rc = supR3HardenedVerifySameFsObject(dirfd(pDir), pFsObjState, pszDirPath, pErrInfo);
1288 if (RT_FAILURE(rc))
1289 {
1290 closedir(pDir);
1291 return rc;
1292 }
1293 }
1294
1295 /*
1296 * Enumerate the directory, check all the requested bits.
1297 */
1298 int rc = VINF_SUCCESS;
1299 for (;;)
1300 {
1301 pszDirPath[cchDirPath] = '\0'; /* for error messages. */
1302
1303 struct dirent Entry;
1304 struct dirent *pEntry;
1305 int iErr = readdir_r(pDir, &Entry, &pEntry);
1306 if (iErr)
1307 {
1308 rc = supR3HardenedSetErrorN(VERR_SUPLIB_DIR_ENUM_FAILED, pErrInfo,
1309 5, "readdir_r failed with ", strerror(iErr), " in '", pszDirPath, "'");
1310 break;
1311 }
1312 if (!pEntry)
1313 break;
1314
1315 /*
1316 * Check the length and copy it into the path buffer so it can be
1317 * stat()'ed.
1318 */
1319 size_t cchName = strlen(pEntry->d_name);
1320 if (cchName + cchDirPath > SUPR3HARDENED_MAX_PATH)
1321 {
1322 rc = supR3HardenedSetErrorN(VERR_SUPLIB_PATH_TOO_LONG, pErrInfo,
1323 4, "Path grew too long during recursion: '", pszDirPath, pEntry->d_name, "'");
1324 break;
1325 }
1326 memcpy(&pszDirPath[cchName], pEntry->d_name, cchName + 1);
1327
1328 /*
1329 * Query the information about the entry and verify it.
1330 * (We don't bother skipping '.' and '..' at this point, a little bit
1331 * of extra checks doesn't hurt and neither requires relaxed handling.)
1332 */
1333 rc = supR3HardenedQueryFsObjectByPath(pszDirPath, pFsObjState, pErrInfo);
1334 if (RT_SUCCESS(rc))
1335 break;
1336 rc = supR3HardenedVerifyFsObject(pFsObjState, S_ISDIR(pFsObjState->Stat.st_mode), false /*fRelaxed*/,
1337 pszDirPath, pErrInfo);
1338 if (RT_FAILURE(rc))
1339 break;
1340
1341 /*
1342 * Recurse into subdirectories if requested.
1343 */
1344 if ( fRecursive
1345 && S_ISDIR(pFsObjState->Stat.st_mode)
1346 && strcmp(pEntry->d_name, ".")
1347 && strcmp(pEntry->d_name, ".."))
1348 {
1349 pszDirPath[cchDirPath + cchName] = RTPATH_SLASH;
1350 pszDirPath[cchDirPath + cchName + 1] = '\0';
1351
1352 rc = supR3HardenedVerifyDirRecursive(pszDirPath, cchDirPath + cchName + 1, pFsObjState,
1353 fRecursive, pErrInfo);
1354 if (RT_FAILURE(rc))
1355 break;
1356 }
1357 }
1358
1359 closedir(pDir);
1360 return VINF_SUCCESS;
1361#endif
1362}
1363
1364
1365/**
1366 * Worker for SUPR3HardenedVerifyDir.
1367 *
1368 * @returns See SUPR3HardenedVerifyDir.
1369 * @param pszDirPath See SUPR3HardenedVerifyDir.
1370 * @param fRecursive See SUPR3HardenedVerifyDir.
1371 * @param fCheckFiles See SUPR3HardenedVerifyDir.
1372 * @param pErrInfo See SUPR3HardenedVerifyDir.
1373 */
1374DECLHIDDEN(int) supR3HardenedVerifyDir(const char *pszDirPath, bool fRecursive, bool fCheckFiles, PRTERRINFO pErrInfo)
1375{
1376 /*
1377 * Validate the input path and parse it.
1378 */
1379 SUPR3HARDENEDPATHINFO Info;
1380 int rc = supR3HardenedVerifyPathSanity(pszDirPath, pErrInfo, &Info);
1381 if (RT_FAILURE(rc))
1382 return rc;
1383
1384 /*
1385 * Verify each component from the root up.
1386 */
1387 SUPR3HARDENEDFSOBJSTATE FsObjState;
1388 uint32_t const cComponents = Info.cComponents;
1389 for (uint32_t iComponent = 0; iComponent < cComponents; iComponent++)
1390 {
1391 bool fRelaxed = iComponent + 2 < cComponents;
1392 Info.szPath[Info.aoffComponents[iComponent + 1] - 1] = '\0';
1393 rc = supR3HardenedQueryFsObjectByPath(Info.szPath, &FsObjState, pErrInfo);
1394 if (RT_SUCCESS(rc))
1395 rc = supR3HardenedVerifyFsObject(&FsObjState, true /*fDir*/, fRelaxed, Info.szPath, pErrInfo);
1396 if (RT_FAILURE(rc))
1397 return rc;
1398 Info.szPath[Info.aoffComponents[iComponent + 1] - 1] = iComponent + 1 != cComponents ? RTPATH_SLASH : '\0';
1399 }
1400
1401 /*
1402 * Check files and subdirectories if requested.
1403 */
1404 if (fCheckFiles || fRecursive)
1405 {
1406 Info.szPath[Info.cch] = RTPATH_SLASH;
1407 Info.szPath[Info.cch + 1] = '\0';
1408 return supR3HardenedVerifyDirRecursive(Info.szPath, Info.cch + 1, &FsObjState,
1409 fRecursive, pErrInfo);
1410 }
1411
1412 return VINF_SUCCESS;
1413}
1414
1415
1416/**
1417 * Verfies a file.
1418 *
1419 * @returns VBox status code, error buffer filled on failure.
1420 * @param pszFilename The file to verify.
1421 * @param hNativeFile Handle to the file, verify that it's the same
1422 * as we ended up with when verifying the path.
1423 * RTHCUINTPTR_MAX means NIL here.
1424 * @param pErrInfo Where to return extended error information.
1425 * Optional.
1426 */
1427DECLHIDDEN(int) supR3HardenedVerifyFile(const char *pszFilename, RTHCUINTPTR hNativeFile, PRTERRINFO pErrInfo)
1428{
1429 /*
1430 * Validate the input path and parse it.
1431 */
1432 SUPR3HARDENEDPATHINFO Info;
1433 int rc = supR3HardenedVerifyPathSanity(pszFilename, pErrInfo, &Info);
1434 if (RT_FAILURE(rc))
1435 return rc;
1436 if (Info.fDirSlash)
1437 return supR3HardenedSetError3(VERR_SUPLIB_IS_DIRECTORY, pErrInfo,
1438 "The file path specifies a directory: '", pszFilename, "'");
1439
1440 /*
1441 * Verify each component from the root up.
1442 */
1443 SUPR3HARDENEDFSOBJSTATE FsObjState;
1444 uint32_t const cComponents = Info.cComponents;
1445 for (uint32_t iComponent = 0; iComponent < cComponents; iComponent++)
1446 {
1447 bool fFinal = iComponent + 1 == cComponents;
1448 bool fRelaxed = iComponent + 2 < cComponents;
1449 Info.szPath[Info.aoffComponents[iComponent + 1] - 1] = '\0';
1450 rc = supR3HardenedQueryFsObjectByPath(Info.szPath, &FsObjState, pErrInfo);
1451 if (RT_SUCCESS(rc))
1452 rc = supR3HardenedVerifyFsObject(&FsObjState, !fFinal /*fDir*/, fRelaxed, Info.szPath, pErrInfo);
1453 if (RT_FAILURE(rc))
1454 return rc;
1455 Info.szPath[Info.aoffComponents[iComponent + 1] - 1] = !fFinal ? RTPATH_SLASH : '\0';
1456 }
1457
1458 /*
1459 * Verify the file.
1460 */
1461 if (hNativeFile != RTHCUINTPTR_MAX)
1462 return supR3HardenedVerifySameFsObject(hNativeFile, &FsObjState, Info.szPath, pErrInfo);
1463 return VINF_SUCCESS;
1464}
1465
1466
1467/**
1468 * Gets the pre-init data for the hand-over to the other version
1469 * of this code.
1470 *
1471 * The reason why we pass this information on is that it contains
1472 * open directories and files. Later it may include even more info
1473 * (int the verified arrays mostly).
1474 *
1475 * The receiver is supR3HardenedRecvPreInitData.
1476 *
1477 * @param pPreInitData Where to store it.
1478 */
1479DECLHIDDEN(void) supR3HardenedGetPreInitData(PSUPPREINITDATA pPreInitData)
1480{
1481 pPreInitData->cInstallFiles = RT_ELEMENTS(g_aSupInstallFiles);
1482 pPreInitData->paInstallFiles = &g_aSupInstallFiles[0];
1483 pPreInitData->paVerifiedFiles = &g_aSupVerifiedFiles[0];
1484
1485 pPreInitData->cVerifiedDirs = RT_ELEMENTS(g_aSupVerifiedDirs);
1486 pPreInitData->paVerifiedDirs = &g_aSupVerifiedDirs[0];
1487}
1488
1489
1490/**
1491 * Receives the pre-init data from the static executable stub.
1492 *
1493 * @returns VBox status code. Will not bitch on failure since the
1494 * runtime isn't ready for it, so that is left to the exe stub.
1495 *
1496 * @param pPreInitData The hand-over data.
1497 */
1498DECLHIDDEN(int) supR3HardenedRecvPreInitData(PCSUPPREINITDATA pPreInitData)
1499{
1500 /*
1501 * Compare the array lengths and the contents of g_aSupInstallFiles.
1502 */
1503 if ( pPreInitData->cInstallFiles != RT_ELEMENTS(g_aSupInstallFiles)
1504 || pPreInitData->cVerifiedDirs != RT_ELEMENTS(g_aSupVerifiedDirs))
1505 return VERR_VERSION_MISMATCH;
1506 SUPINSTFILE const *paInstallFiles = pPreInitData->paInstallFiles;
1507 for (unsigned iFile = 0; iFile < RT_ELEMENTS(g_aSupInstallFiles); iFile++)
1508 if ( g_aSupInstallFiles[iFile].enmDir != paInstallFiles[iFile].enmDir
1509 || g_aSupInstallFiles[iFile].enmType != paInstallFiles[iFile].enmType
1510 || g_aSupInstallFiles[iFile].fOptional != paInstallFiles[iFile].fOptional
1511 || strcmp(g_aSupInstallFiles[iFile].pszFile, paInstallFiles[iFile].pszFile))
1512 return VERR_VERSION_MISMATCH;
1513
1514 /*
1515 * Check that we're not called out of order.
1516 * If dynamic linking it screwed up, we may end up here.
1517 */
1518 if ( ASMMemIsAll8(&g_aSupVerifiedFiles[0], sizeof(g_aSupVerifiedFiles), 0) != NULL
1519 || ASMMemIsAll8(&g_aSupVerifiedDirs[0], sizeof(g_aSupVerifiedDirs), 0) != NULL)
1520 return VERR_WRONG_ORDER;
1521
1522 /*
1523 * Copy the verification data over.
1524 */
1525 memcpy(&g_aSupVerifiedFiles[0], pPreInitData->paVerifiedFiles, sizeof(g_aSupVerifiedFiles));
1526 memcpy(&g_aSupVerifiedDirs[0], pPreInitData->paVerifiedDirs, sizeof(g_aSupVerifiedDirs));
1527 return VINF_SUCCESS;
1528}
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