VirtualBox

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

Last change on this file since 35346 was 35188, checked in by vboxsync, 14 years ago

Use RTERRINFO in SUPLib for hardening APIs and such.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 57.8 KB
Line 
1/* $Id: SUPR3HardenedVerify.cpp 35188 2010-12-16 15:13:07Z 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 group does not matter if it does not have write access, if it has
1154 * write access it must be group 0 (root/wheel/whatever).
1155 *
1156 * This can be extended to include predefined system groups or groups that
1157 * only root is member of.
1158 */
1159 if ( (pFsObjState->Stat.st_mode & S_IWGRP)
1160 && pFsObjState->Stat.st_gid != 0)
1161 {
1162#ifdef RT_OS_DARWIN
1163 /* HACK ALERT: On Darwin /Applications is root:admin with admin having
1164 full access. So, to work around we relax the hardening a bit and
1165 permit grand parents and beyond to be group writable by admin. */
1166 if (pFsObjState->Stat.st_gid != 80 /*admin*/) /** @todo dynamically resolve the admin group? */
1167#endif
1168 return supR3HardenedSetError3(VERR_SUPLIB_WRITE_NON_SYS_GROUP, pErrInfo,
1169 "The group is not a system group and it has write access to '", pszPath, "'");
1170 }
1171
1172 /*
1173 * World must not have write access. There is no relaxing this rule.
1174 */
1175 if (pFsObjState->Stat.st_mode & S_IWOTH)
1176 return supR3HardenedSetError3(VERR_SUPLIB_WORLD_WRITABLE, pErrInfo,
1177 "World writable: '", pszPath, "'");
1178
1179 /*
1180 * Check the ACLs.
1181 */
1182 /** @todo */
1183
1184 /*
1185 * Check the object type.
1186 */
1187 if ( !S_ISDIR(pFsObjState->Stat.st_mode)
1188 && !S_ISREG(pFsObjState->Stat.st_mode))
1189 {
1190 if (S_ISLNK(pFsObjState->Stat.st_mode))
1191 return supR3HardenedSetError3(VERR_SUPLIB_SYMLINKS_ARE_NOT_PERMITTED, pErrInfo,
1192 "Symlinks are not permitted: '", pszPath, "'");
1193 return supR3HardenedSetError3(VERR_SUPLIB_NOT_DIR_NOT_FILE, pErrInfo,
1194 "Not regular file or directory: '", pszPath, "'");
1195 }
1196 if (fDir != !!S_ISDIR(pFsObjState->Stat.st_mode))
1197 {
1198 if (S_ISDIR(pFsObjState->Stat.st_mode))
1199 return supR3HardenedSetError3(VERR_SUPLIB_IS_DIRECTORY, pErrInfo,
1200 "Expected file but found directory: '", pszPath, "'");
1201 return supR3HardenedSetError3(VERR_SUPLIB_IS_FILE, pErrInfo,
1202 "Expected directory but found file: '", pszPath, "'");
1203 }
1204
1205 return VINF_SUCCESS;
1206#endif
1207
1208}
1209
1210
1211/**
1212 * Verifies that the file system object indicated by the native handle is the
1213 * same as the one @a pFsObjState indicates.
1214 *
1215 * @returns VBox status code, error buffer filled on failure.
1216 * @param hNative The native handle to the object @a pszPath
1217 * specifies and this should be verified to be the
1218 * same file system object.
1219 * @param pFsObjState The information/state returned by a previous
1220 * query call.
1221 * @param pszPath The path to the object @a pFsObjState
1222 * describes. (For the error message.)
1223 * @param pErrInfo The error info structure.
1224 */
1225static int supR3HardenedVerifySameFsObject(RTHCUINTPTR hNative, PCSUPR3HARDENEDFSOBJSTATE pFsObjState,
1226 const char *pszPath, PRTERRINFO pErrInfo)
1227{
1228 SUPR3HARDENEDFSOBJSTATE FsObjState2;
1229 int rc = supR3HardenedQueryFsObjectByHandle(hNative, &FsObjState2, pszPath, pErrInfo);
1230 if (RT_SUCCESS(rc))
1231 rc = supR3HardenedIsSameFsObject(pFsObjState, &FsObjState2, pszPath, pErrInfo);
1232 return rc;
1233}
1234
1235
1236/**
1237 * Does the recursive directory enumeration.
1238 *
1239 * @returns VBox status code, error buffer filled on failure.
1240 * @param pszDirPath The path buffer containing the subdirectory to
1241 * enumerate followed by a slash (this is never
1242 * the root slash). The buffer is RTPATH_MAX in
1243 * size and anything starting at @a cchDirPath
1244 * - 1 and beyond is scratch space.
1245 * @param cchDirPath The length of the directory path + slash.
1246 * @param pFsObjState Pointer to the file system object state buffer.
1247 * On input this will hold the stats for
1248 * the directory @a pszDirPath indicates and will
1249 * be used to verified that we're opening the same
1250 * thing.
1251 * @param fRecursive Whether to recurse into subdirectories.
1252 * @param pErrInfo The error info structure.
1253 */
1254static int supR3HardenedVerifyDirRecursive(char *pszDirPath, size_t cchDirPath, PSUPR3HARDENEDFSOBJSTATE pFsObjState,
1255 bool fRecursive, PRTERRINFO pErrInfo)
1256{
1257#if defined(RT_OS_WINDOWS)
1258 /** @todo Windows hardening. */
1259 return VINF_SUCCESS;
1260
1261#elif defined(RT_OS_OS2)
1262 /* No hardening here - it's a single user system. */
1263 return VINF_SUCCESS;
1264
1265#else
1266 /*
1267 * Open the directory. Now, we could probably eliminate opendir here
1268 * and go down on kernel API level (open + getdents for instance), however
1269 * that's not very portable and hopefully not necessary.
1270 */
1271 DIR *pDir = opendir(pszDirPath);
1272 if (!pDir)
1273 {
1274 /* Ignore access errors. */
1275 if (errno == EACCES)
1276 return VINF_SUCCESS;
1277 return supR3HardenedSetErrorN(VERR_SUPLIB_DIR_ENUM_FAILED, pErrInfo,
1278 5, "opendir failed with ", strerror(errno), " on '", pszDirPath, "'");
1279 }
1280 if (dirfd(pDir) != -1)
1281 {
1282 int rc = supR3HardenedVerifySameFsObject(dirfd(pDir), pFsObjState, pszDirPath, pErrInfo);
1283 if (RT_FAILURE(rc))
1284 {
1285 closedir(pDir);
1286 return rc;
1287 }
1288 }
1289
1290 /*
1291 * Enumerate the directory, check all the requested bits.
1292 */
1293 int rc = VINF_SUCCESS;
1294 for (;;)
1295 {
1296 pszDirPath[cchDirPath] = '\0'; /* for error messages. */
1297
1298 struct dirent Entry;
1299 struct dirent *pEntry;
1300 int iErr = readdir_r(pDir, &Entry, &pEntry);
1301 if (iErr)
1302 {
1303 rc = supR3HardenedSetErrorN(VERR_SUPLIB_DIR_ENUM_FAILED, pErrInfo,
1304 5, "readdir_r failed with ", strerror(iErr), " in '", pszDirPath, "'");
1305 break;
1306 }
1307 if (!pEntry)
1308 break;
1309
1310 /*
1311 * Check the length and copy it into the path buffer so it can be
1312 * stat()'ed.
1313 */
1314 size_t cchName = strlen(pEntry->d_name);
1315 if (cchName + cchDirPath > SUPR3HARDENED_MAX_PATH)
1316 {
1317 rc = supR3HardenedSetErrorN(VERR_SUPLIB_PATH_TOO_LONG, pErrInfo,
1318 4, "Path grew too long during recursion: '", pszDirPath, pEntry->d_name, "'");
1319 break;
1320 }
1321 memcpy(&pszDirPath[cchName], pEntry->d_name, cchName + 1);
1322
1323 /*
1324 * Query the information about the entry and verify it.
1325 * (We don't bother skipping '.' and '..' at this point, a little bit
1326 * of extra checks doesn't hurt and neither requires relaxed handling.)
1327 */
1328 rc = supR3HardenedQueryFsObjectByPath(pszDirPath, pFsObjState, pErrInfo);
1329 if (RT_SUCCESS(rc))
1330 break;
1331 rc = supR3HardenedVerifyFsObject(pFsObjState, S_ISDIR(pFsObjState->Stat.st_mode), false /*fRelaxed*/,
1332 pszDirPath, pErrInfo);
1333 if (RT_FAILURE(rc))
1334 break;
1335
1336 /*
1337 * Recurse into subdirectories if requested.
1338 */
1339 if ( fRecursive
1340 && S_ISDIR(pFsObjState->Stat.st_mode)
1341 && strcmp(pEntry->d_name, ".")
1342 && strcmp(pEntry->d_name, ".."))
1343 {
1344 pszDirPath[cchDirPath + cchName] = RTPATH_SLASH;
1345 pszDirPath[cchDirPath + cchName + 1] = '\0';
1346
1347 rc = supR3HardenedVerifyDirRecursive(pszDirPath, cchDirPath + cchName + 1, pFsObjState,
1348 fRecursive, pErrInfo);
1349 if (RT_FAILURE(rc))
1350 break;
1351 }
1352 }
1353
1354 closedir(pDir);
1355 return VINF_SUCCESS;
1356#endif
1357}
1358
1359
1360/**
1361 * Worker for SUPR3HardenedVerifyDir.
1362 *
1363 * @returns See SUPR3HardenedVerifyDir.
1364 * @param pszDirPath See SUPR3HardenedVerifyDir.
1365 * @param fRecursive See SUPR3HardenedVerifyDir.
1366 * @param fCheckFiles See SUPR3HardenedVerifyDir.
1367 * @param pErrInfo See SUPR3HardenedVerifyDir.
1368 */
1369DECLHIDDEN(int) supR3HardenedVerifyDir(const char *pszDirPath, bool fRecursive, bool fCheckFiles, PRTERRINFO pErrInfo)
1370{
1371 /*
1372 * Validate the input path and parse it.
1373 */
1374 SUPR3HARDENEDPATHINFO Info;
1375 int rc = supR3HardenedVerifyPathSanity(pszDirPath, pErrInfo, &Info);
1376 if (RT_FAILURE(rc))
1377 return rc;
1378
1379 /*
1380 * Verify each component from the root up.
1381 */
1382 SUPR3HARDENEDFSOBJSTATE FsObjState;
1383 uint32_t const cComponents = Info.cComponents;
1384 for (uint32_t iComponent = 0; iComponent < cComponents; iComponent++)
1385 {
1386 bool fRelaxed = iComponent + 2 < cComponents;
1387 Info.szPath[Info.aoffComponents[iComponent + 1] - 1] = '\0';
1388 rc = supR3HardenedQueryFsObjectByPath(Info.szPath, &FsObjState, pErrInfo);
1389 if (RT_SUCCESS(rc))
1390 rc = supR3HardenedVerifyFsObject(&FsObjState, true /*fDir*/, fRelaxed, Info.szPath, pErrInfo);
1391 if (RT_FAILURE(rc))
1392 return rc;
1393 Info.szPath[Info.aoffComponents[iComponent + 1] - 1] = iComponent + 1 != cComponents ? RTPATH_SLASH : '\0';
1394 }
1395
1396 /*
1397 * Check files and subdirectories if requested.
1398 */
1399 if (fCheckFiles || fRecursive)
1400 {
1401 Info.szPath[Info.cch] = RTPATH_SLASH;
1402 Info.szPath[Info.cch + 1] = '\0';
1403 return supR3HardenedVerifyDirRecursive(Info.szPath, Info.cch + 1, &FsObjState,
1404 fRecursive, pErrInfo);
1405 }
1406
1407 return VINF_SUCCESS;
1408}
1409
1410
1411/**
1412 * Verfies a file.
1413 *
1414 * @returns VBox status code, error buffer filled on failure.
1415 * @param pszFilename The file to verify.
1416 * @param hNativeFile Handle to the file, verify that it's the same
1417 * as we ended up with when verifying the path.
1418 * RTHCUINTPTR_MAX means NIL here.
1419 * @param pErrInfo Where to return extended error information.
1420 * Optional.
1421 */
1422DECLHIDDEN(int) supR3HardenedVerifyFile(const char *pszFilename, RTHCUINTPTR hNativeFile, PRTERRINFO pErrInfo)
1423{
1424 /*
1425 * Validate the input path and parse it.
1426 */
1427 SUPR3HARDENEDPATHINFO Info;
1428 int rc = supR3HardenedVerifyPathSanity(pszFilename, pErrInfo, &Info);
1429 if (RT_FAILURE(rc))
1430 return rc;
1431 if (Info.fDirSlash)
1432 return supR3HardenedSetError3(VERR_SUPLIB_IS_DIRECTORY, pErrInfo,
1433 "The file path specifies a directory: '", pszFilename, "'");
1434
1435 /*
1436 * Verify each component from the root up.
1437 */
1438 SUPR3HARDENEDFSOBJSTATE FsObjState;
1439 uint32_t const cComponents = Info.cComponents;
1440 for (uint32_t iComponent = 0; iComponent < cComponents; iComponent++)
1441 {
1442 bool fFinal = iComponent + 1 == cComponents;
1443 bool fRelaxed = iComponent + 2 < cComponents;
1444 Info.szPath[Info.aoffComponents[iComponent + 1] - 1] = '\0';
1445 rc = supR3HardenedQueryFsObjectByPath(Info.szPath, &FsObjState, pErrInfo);
1446 if (RT_SUCCESS(rc))
1447 rc = supR3HardenedVerifyFsObject(&FsObjState, !fFinal /*fDir*/, fRelaxed, Info.szPath, pErrInfo);
1448 if (RT_FAILURE(rc))
1449 return rc;
1450 Info.szPath[Info.aoffComponents[iComponent + 1] - 1] = !fFinal ? RTPATH_SLASH : '\0';
1451 }
1452
1453 /*
1454 * Verify the file.
1455 */
1456 if (hNativeFile != RTHCUINTPTR_MAX)
1457 return supR3HardenedVerifySameFsObject(hNativeFile, &FsObjState, Info.szPath, pErrInfo);
1458 return VINF_SUCCESS;
1459}
1460
1461
1462/**
1463 * Gets the pre-init data for the hand-over to the other version
1464 * of this code.
1465 *
1466 * The reason why we pass this information on is that it contains
1467 * open directories and files. Later it may include even more info
1468 * (int the verified arrays mostly).
1469 *
1470 * The receiver is supR3HardenedRecvPreInitData.
1471 *
1472 * @param pPreInitData Where to store it.
1473 */
1474DECLHIDDEN(void) supR3HardenedGetPreInitData(PSUPPREINITDATA pPreInitData)
1475{
1476 pPreInitData->cInstallFiles = RT_ELEMENTS(g_aSupInstallFiles);
1477 pPreInitData->paInstallFiles = &g_aSupInstallFiles[0];
1478 pPreInitData->paVerifiedFiles = &g_aSupVerifiedFiles[0];
1479
1480 pPreInitData->cVerifiedDirs = RT_ELEMENTS(g_aSupVerifiedDirs);
1481 pPreInitData->paVerifiedDirs = &g_aSupVerifiedDirs[0];
1482}
1483
1484
1485/**
1486 * Receives the pre-init data from the static executable stub.
1487 *
1488 * @returns VBox status code. Will not bitch on failure since the
1489 * runtime isn't ready for it, so that is left to the exe stub.
1490 *
1491 * @param pPreInitData The hand-over data.
1492 */
1493DECLHIDDEN(int) supR3HardenedRecvPreInitData(PCSUPPREINITDATA pPreInitData)
1494{
1495 /*
1496 * Compare the array lengths and the contents of g_aSupInstallFiles.
1497 */
1498 if ( pPreInitData->cInstallFiles != RT_ELEMENTS(g_aSupInstallFiles)
1499 || pPreInitData->cVerifiedDirs != RT_ELEMENTS(g_aSupVerifiedDirs))
1500 return VERR_VERSION_MISMATCH;
1501 SUPINSTFILE const *paInstallFiles = pPreInitData->paInstallFiles;
1502 for (unsigned iFile = 0; iFile < RT_ELEMENTS(g_aSupInstallFiles); iFile++)
1503 if ( g_aSupInstallFiles[iFile].enmDir != paInstallFiles[iFile].enmDir
1504 || g_aSupInstallFiles[iFile].enmType != paInstallFiles[iFile].enmType
1505 || g_aSupInstallFiles[iFile].fOptional != paInstallFiles[iFile].fOptional
1506 || strcmp(g_aSupInstallFiles[iFile].pszFile, paInstallFiles[iFile].pszFile))
1507 return VERR_VERSION_MISMATCH;
1508
1509 /*
1510 * Check that we're not called out of order.
1511 * If dynamic linking it screwed up, we may end up here.
1512 */
1513 if ( ASMMemIsAll8(&g_aSupVerifiedFiles[0], sizeof(g_aSupVerifiedFiles), 0) != NULL
1514 || ASMMemIsAll8(&g_aSupVerifiedDirs[0], sizeof(g_aSupVerifiedDirs), 0) != NULL)
1515 return VERR_WRONG_ORDER;
1516
1517 /*
1518 * Copy the verification data over.
1519 */
1520 memcpy(&g_aSupVerifiedFiles[0], pPreInitData->paVerifiedFiles, sizeof(g_aSupVerifiedFiles));
1521 memcpy(&g_aSupVerifiedDirs[0], pPreInitData->paVerifiedDirs, sizeof(g_aSupVerifiedDirs));
1522 return VINF_SUCCESS;
1523}
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