SUPR3HardenedMain.cpp revision cbc4fdcbcaa06e2fa339e863429f05e9f537b0e9
/* $Id$ */
/** @file
* VirtualBox Support Library - Hardened main().
*/
/*
* Copyright (C) 2006-2008 Sun Microsystems, Inc.
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 USA or visit http://www.sun.com if you need
* additional information or have any questions.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#if defined(RT_OS_OS2)
# define INCL_BASE
# define INCL_ERRORS
# include <os2.h>
# include <stdio.h>
# include <stdlib.h>
# include <dlfcn.h>
# include <Windows.h>
# include <stdio.h>
#else /* UNIXes */
# include <stdio.h>
# include <stdlib.h>
# include <dlfcn.h>
# include <limits.h>
# include <errno.h>
# include <unistd.h>
# include <stdio.h>
# if defined(RT_OS_LINUX)
libcap1 or libcap2 */
# include <sys/capability.h>
# ifndef CAP_TO_MASK
# endif
# elif defined(RT_OS_FREEBSD)
# elif defined(RT_OS_SOLARIS)
# include <priv.h>
# endif
# include <pwd.h>
# ifdef RT_OS_DARWIN
# endif
#endif
#include "SUPLibInternal.h"
/*******************************************************************************
* Defined Constants And Macros *
*******************************************************************************/
/** @def SUP_HARDENED_SUID
* Whether we're employing set-user-ID-on-execute in the hardening.
*/
# define SUP_HARDENED_SUID
#else
#endif
/** @def SUP_HARDENED_SYM
* Decorate a symbol that's resolved dynamically.
*/
#ifdef RT_OS_OS2
#else
#endif
/*******************************************************************************
* Structures and Typedefs *
*******************************************************************************/
/** @see RTR3InitEx */
typedef DECLCALLBACK(int) FNRTR3INITEX(uint32_t iVersion, const char *pszProgramPath, bool fInitSUPLib);
typedef FNRTR3INITEX *PFNRTR3INITEX;
/*******************************************************************************
* Global Variables *
*******************************************************************************/
/** The pre-init data we pass on to SUPR3 (residing in VBoxRT). */
static SUPPREINITDATA g_SupPreInitData;
/** The progam executable path. */
static char g_szSupLibHardenedExePath[RTPATH_MAX];
/** The program directory path. */
static char g_szSupLibHardenedDirPath[RTPATH_MAX];
/** The program name. */
static const char *g_pszSupLibHardenedProgName;
#ifdef SUP_HARDENED_SUID
/** The real UID at startup. */
/** The real GID at startup. */
# ifdef RT_OS_LINUX
# endif
#endif
/*******************************************************************************
* Internal Functions *
*******************************************************************************/
#ifdef SUP_HARDENED_SUID
static void supR3HardenedMainDropPrivileges(void);
#endif
/**
* @copydoc RTPathStripFilename.
*/
static void suplibHardenedPathStripFilename(char *pszPath)
{
char *pszLastSep = pszPath;
for (;; psz++)
{
switch (*psz)
{
/* handle separators. */
#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
case ':':
break;
case '\\':
#endif
case '/':
pszLastSep = psz;
break;
/* the end */
case '\0':
if (pszLastSep == pszPath)
*pszLastSep++ = '.';
*pszLastSep = '\0';
return;
}
}
/* will never get here */
}
/**
* @copydoc RTPathFilename
*/
{
const char *pszLastComp = pszPath;
for (;; psz++)
{
switch (*psz)
{
/* handle separators. */
#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
case ':':
break;
case '\\':
#endif
case '/':
break;
/* the end */
case '\0':
if (*pszLastComp)
return (char *)(void *)pszLastComp;
return NULL;
}
}
/* will never get here */
return NULL;
}
/**
* @copydoc RTPathAppPrivateNoArch
*/
{
#if !defined(RT_OS_WINDOWS) && defined(RTPATH_APP_PRIVATE)
const char *pszSrcPath = RTPATH_APP_PRIVATE;
if (cchPathPrivateNoArch >= cchPath)
supR3HardenedFatal("supR3HardenedPathAppPrivateNoArch: Buffer overflow, %lu >= %lu\n",
(unsigned long)cchPathPrivateNoArch, (unsigned long)cchPath);
return VINF_SUCCESS;
#else
#endif
}
/**
* @copydoc RTPathAppPrivateArch
*/
{
#if !defined(RT_OS_WINDOWS) && defined(RTPATH_APP_PRIVATE_ARCH)
const char *pszSrcPath = RTPATH_APP_PRIVATE_ARCH;
if (cchPathPrivateArch >= cchPath)
supR3HardenedFatal("supR3HardenedPathAppPrivateArch: Buffer overflow, %lu >= %lu\n",
(unsigned long)cchPathPrivateArch, (unsigned long)cchPath);
return VINF_SUCCESS;
#else
#endif
}
/**
* @copydoc RTPathSharedLibs
*/
{
#if !defined(RT_OS_WINDOWS) && defined(RTPATH_SHARED_LIBS)
const char *pszSrcPath = RTPATH_SHARED_LIBS;
if (cchPathSharedLibs >= cchPath)
supR3HardenedFatal("supR3HardenedPathSharedLibs: Buffer overflow, %lu >= %lu\n",
(unsigned long)cchPathSharedLibs, (unsigned long)cchPath);
return VINF_SUCCESS;
#else
#endif
}
/**
* @copydoc RTPathAppDocs
*/
{
#if !defined(RT_OS_WINDOWS) && defined(RTPATH_APP_DOCS)
const char *pszSrcPath = RTPATH_APP_DOCS;
if (cchPathAppDocs >= cchPath)
supR3HardenedFatal("supR3HardenedPathAppDocs: Buffer overflow, %lu >= %lu\n",
(unsigned long)cchPathAppDocs, (unsigned long)cchPath);
return VINF_SUCCESS;
#else
#endif
}
/**
* Returns the full path to the executable.
*
* @returns IPRT status code.
* @param pszPath Where to store it.
* @param cchPath How big that buffer is.
*/
static void supR3HardenedGetFullExePath(void)
{
/*
* Get the program filename.
*
* Most UNIXes have no API for obtaining the executable path, but provides a symbolic
* link in the proc file system that tells who was exec'ed. The bad thing about this
* is that we have to use readlink, one of the weirder UNIX APIs.
*
* Darwin, OS/2 and Windows all have proper APIs for getting the program file name.
*/
# ifdef RT_OS_LINUX
int cchLink = readlink("/proc/self/exe", &g_szSupLibHardenedExePath[0], sizeof(g_szSupLibHardenedExePath) - 1);
# elif defined(RT_OS_SOLARIS)
int cchLink = readlink(szFileBuf, &g_szSupLibHardenedExePath[0], sizeof(g_szSupLibHardenedExePath) - 1);
# else /* RT_OS_FREEBSD */
int aiName[4];
supR3HardenedFatal("supR3HardenedExecDir: sysctl failed\n");
# endif
supR3HardenedFatal("supR3HardenedExecDir: couldn't read \"%s\", errno=%d cchLink=%d\n",
#elif defined(RT_OS_DARWIN)
const char *pszImageName = _dyld_get_image_name(0);
if (!pszImageName)
supR3HardenedFatal("supR3HardenedExecDir: _dyld_get_image_name(0) failed\n");
supR3HardenedFatal("supR3HardenedExecDir: _dyld_get_image_name(0) failed, cchImageName=%d\n", cchImageName);
#elif defined(RT_OS_WINDOWS)
#else
#endif
/*
* Strip off the filename part (RTPathStripFilename()).
*/
}
#ifdef RT_OS_LINUX
/**
*
* This is used on linux to see if we have to call init
* with program path or not.
*
* @returns true / false.
*/
static bool supR3HardenedMainIsProcSelfExeAccssible(void)
{
char szPath[RTPATH_MAX];
return cchLink != -1;
}
#endif /* RT_OS_LINUX */
/**
* @copydoc RTPathExecDir
*/
{
/*
* Lazy init (probably not required).
*/
if (!g_szSupLibHardenedDirPath[0])
/*
* Calc the length and check if there is space before copying.
*/
{
return VINF_SUCCESS;
}
return VERR_BUFFER_OVERFLOW;
}
DECLHIDDEN(void) supR3HardenedFatalMsgV(const char *pszWhere, SUPINITOP enmWhat, int rc, const char *pszMsgFmt, va_list va)
{
/*
* To the console first, like supR3HardenedFatalV.
*/
switch (enmWhat)
{
case kSupInitOp_Driver:
"\n"
"%s: Tip! Make sure the kernel module is loaded. It may also help to reinstall VirtualBox.\n",
break;
case kSupInitOp_IPRT:
case kSupInitOp_Integrity:
case kSupInitOp_RootCheck:
"\n"
"%s: Tip! It may help to reinstall VirtualBox.\n",
break;
default:
/* no hints here */
break;
}
#ifdef SUP_HARDENED_SUID
/*
* Drop any root privileges we might be holding, this won't return
* if it fails but end up calling supR3HardenedFatal[V].
*/
#endif /* SUP_HARDENED_SUID */
/*
* Now try resolve and call the TrustedError entry point if we can
* find it. We'll fork before we attempt this because that way the
* session management in main will see us exiting immediately (if
* it's invovled with us).
*/
#if !defined(RT_OS_WINDOWS) && !defined(RT_OS_OS2)
if (pid <= 0)
#endif
{
if (pfnTrustedError)
}
/*
* Quit
*/
for (;;)
#ifdef _MSC_VER
exit(1);
#else
_Exit(1);
#endif
}
DECLHIDDEN(void) supR3HardenedFatalMsg(const char *pszWhere, SUPINITOP enmWhat, int rc, const char *pszMsgFmt, ...)
{
}
{
for (;;)
#ifdef _MSC_VER
exit(1);
#else
_Exit(1);
#endif
}
{
}
{
if (fFatal)
return rc;
}
{
return rc;
}
/**
* Wrapper around snprintf which will throw a fatal error on buffer overflow.
*
* @returns Number of chars in the result string.
* @param pszDst The destination buffer.
* @param cchDst The size of the buffer.
* @param pszFormat The format string.
* @param ... Format arguments.
*/
{
#ifdef _MSC_VER
#else
#endif
return cch;
}
/**
*
* @remarks This function will not return on failure.
*/
static void supR3HardenedMainOpenDevice(void)
{
if (RT_SUCCESS(rc))
return;
switch (rc)
{
/** @todo better messages! */
"Kernel driver not installed");
"Kernel driver not accessible");
"VERR_VM_DRIVER_LOAD_ERROR");
"VERR_VM_DRIVER_OPEN_ERROR");
"Kernel driver version mismatch");
case VERR_ACCESS_DENIED:
"VERR_ACCESS_DENIED");
case VERR_NO_MEMORY:
"Kernel memory allocation/mapping failed");
default:
"Unknown rc=%d", rc);
}
}
#ifdef SUP_HARDENED_SUID
/**
* Grabs extra non-root capabilities / privileges that we might require.
*
* This is currently only used for being able to do ICMP from the NAT engine.
*
* @note We still have root privileges at the time of this call.
*/
static void supR3HardenedMainGrabCapabilites(void)
{
# if defined(RT_OS_LINUX)
/*
* We are about to drop all our privileges. Remove all capabilities but
* keep the cap_net_raw capability for ICMP sockets for the NAT stack.
*/
if (g_uCaps != 0)
{
# ifdef USE_LIB_PCAP
/* XXX cap_net_bind_service */
# else
# endif /* !USE_LIB_PCAP */
}
# elif defined(RT_OS_SOLARIS)
/*
* Add net_icmpaccess privilege to permitted, effective and inheritable privileges
* before dropping root privileges.
*/
if (pPrivSet)
{
if (!rc)
{
if (!rc)
{
if (rc)
}
else
}
else
}
else
# endif
}
/*
* Look at the environment for some special options.
*/
static void supR3GrabOptions(void)
{
const char *pszOpt;
# ifdef RT_OS_LINUX
g_uCaps = 0;
/*
* Do _not_ perform any capability-related system calls for root processes
* (leaving g_uCaps at 0).
* (Hint: getuid gets the real user id, not the effective.)
*/
if (getuid() != 0)
{
/*
* CAP_NET_RAW.
* Default: enabled.
* Can be disabled with 'export VBOX_HARD_CAP_NET_RAW=0'.
*/
if ( !pszOpt
/*
* CAP_NET_BIND_SERVICE.
* Default: disabled.
* Can be enabled with 'export VBOX_HARD_CAP_NET_BIND_SERVICE=1'.
*/
if ( pszOpt
}
# endif
}
/**
* Drop any root privileges we might be holding.
*/
static void supR3HardenedMainDropPrivileges(void)
{
/*
* leave fewer traces behind that libs like GTK+ may pick up.
*/
# if defined(RT_OS_DARWIN)
/* The really great thing here is that setreuid isn't available on
OS X 10.4, libc emulates it. While 10.4 have a sligtly different and
non-standard setuid implementation compared to 10.5, the following
works the same way with both version since we're super user (10.5 req).
The following will set all three variants of the group and user IDs. */
# elif defined(RT_OS_SOLARIS)
/* Solaris doesn't have setresuid, but the setreuid interface is BSD
compatible and will set the saved uid to euid when we pass it a ruid
that isn't -1 (which we do). */
# else
/* This is the preferred one, full control no questions about semantics.
PORTME: If this isn't work, try join one of two other gangs above. */
{
}
{
}
# endif
/* Check that it worked out all right. */
supR3HardenedFatal("SUPR3HardenedMain: failed to drop root privileges!"
" (euid=%d ruid=%d suid=%d egid=%d rgid=%d sgid=%d; wanted uid=%d and gid=%d)\n",
# if RT_OS_LINUX
/*
* Re-enable the cap_net_raw capability which was disabled during setresuid.
*/
if (g_uCaps != 0)
{
# ifdef USE_LIB_PCAP
/** @todo Warn if that does not work? */
/* XXX cap_net_bind_service */
# else
/** @todo Warn if that does not work? */
# endif /* !USE_LIB_PCAP */
}
# endif
}
#endif /* SUP_HARDENED_SUID */
/**
* and calls RTR3Init.
*
* @param fFlags The SUPR3HardenedMain fFlags argument, passed to supR3PreInit.
*
* @remarks VBoxRT contains both IPRT and SUPR3.
* @remarks This function will not return on failure.
*/
{
/*
* Construct the name.
*/
char szPath[RTPATH_MAX];
/*
* Open it and resolve the symbols.
*/
#if defined(RT_OS_WINDOWS)
/** @todo consider using LOAD_WITH_ALTERED_SEARCH_PATH here! */
if (!hMod)
"LoadLibraryEx(\"%s\",,) failed (rc=%d)",
szPath, GetLastError());
if (!pfnRTInitEx)
"Entrypoint \"RTR3InitEx\" not found in \"%s\" (rc=%d)",
szPath, GetLastError());
PFNSUPR3PREINIT pfnSUPPreInit = (PFNSUPR3PREINIT)GetProcAddress(hMod, SUP_HARDENED_SYM("supR3PreInit"));
if (!pfnSUPPreInit)
"Entrypoint \"supR3PreInit\" not found in \"%s\" (rc=%d)",
szPath, GetLastError());
#else
/* the dlopen crowd */
if (!pvMod)
"dlopen(\"%s\",) failed: %s",
if (!pfnRTInitEx)
"Entrypoint \"RTR3InitEx\" not found in \"%s\"!\ndlerror: %s",
PFNSUPR3PREINIT pfnSUPPreInit = (PFNSUPR3PREINIT)(uintptr_t)dlsym(pvMod, SUP_HARDENED_SYM("supR3PreInit"));
if (!pfnSUPPreInit)
"Entrypoint \"supR3PreInit\" not found in \"%s\"!\ndlerror: %s",
#endif
/*
* Make the calls.
*/
if (RT_FAILURE(rc))
"supR3PreInit failed with rc=%d", rc);
const char *pszExePath = NULL;
#ifdef RT_OS_LINUX
#endif
if (RT_FAILURE(rc))
"RTR3Init failed with rc=%d", rc);
}
/**
* resolves the TrustedError symbol.
*
* This is very similar to supR3HardenedMainGetTrustedMain().
*
* @returns Pointer to the trusted error symbol if it is exported, NULL
* and no error messages otherwise.
* @param pszProgName The program name.
*/
{
/*
* Construct the name.
*/
char szPath[RTPATH_MAX];
/*
* Open it and resolve the symbol.
*/
#if defined(RT_OS_WINDOWS)
/** @todo consider using LOAD_WITH_ALTERED_SEARCH_PATH here! */
if (!hMod)
return NULL;
if (!pfn)
return NULL;
return (PFNSUPTRUSTEDERROR)pfn;
#else
/* the dlopen crowd */
if (!pvMod)
return NULL;
if (!pvSym)
return NULL;
#endif
}
/**
* resolves the TrustedMain symbol.
*
* @returns Pointer to the trusted main of the actual program.
* @param pszProgName The program name.
* @remarks This function will not return on failure.
*/
{
/*
* Construct the name.
*/
char szPath[RTPATH_MAX];
/*
* Open it and resolve the symbol.
*/
#if defined(RT_OS_WINDOWS)
/** @todo consider using LOAD_WITH_ALTERED_SEARCH_PATH here! */
if (!hMod)
supR3HardenedFatal("supR3HardenedMainGetTrustedMain: LoadLibraryEx(\"%s\",,) failed, rc=%d\n",
szPath, GetLastError());
if (!pfn)
supR3HardenedFatal("supR3HardenedMainGetTrustedMain: Entrypoint \"TrustedMain\" not found in \"%s\" (rc=%d)\n",
szPath, GetLastError());
return (PFNSUPTRUSTEDMAIN)pfn;
#else
/* the dlopen crowd */
if (!pvMod)
supR3HardenedFatal("supR3HardenedMainGetTrustedMain: dlopen(\"%s\",) failed: %s\n",
if (!pvSym)
supR3HardenedFatal("supR3HardenedMainGetTrustedMain: Entrypoint \"TrustedMain\" not found in \"%s\"!\ndlerror: %s\n",
#endif
}
/**
* Secure main.
*
* This is used for the set-user-ID-on-execute binaries on unixy systems
* and when using the open-vboxdrv-via-root-service setup on Windows.
*
* This function will perform the integrity checks of the VirtualBox
* installation, open the support driver, open the root service (later),
* and load the DLL corresponding to \a pszProgName and execute its main
* function.
*
* @returns Return code appropriate for main().
*
* @param pszProgName The program name. This will be used to figure out which
* @param fFlags Flags.
* @param argc The argument count.
* @param argv The argument vector.
* @param envp The environment vector.
*/
DECLHIDDEN(int) SUPR3HardenedMain(const char *pszProgName, uint32_t fFlags, int argc, char **argv, char **envp)
{
/*
* Note! At this point there is no IPRT, so we will have to stick
* to basic CRT functions that everyone agree upon.
*/
#ifdef SUP_HARDENED_SUID
# ifdef RT_OS_LINUX
/*
* On linux we have to make sure the path is initialized because we
*/
# endif
/*
* Grab any options from the environment.
*/
/*
* Check that we're root, if we aren't then the installation is butchered.
*/
if (geteuid() != 0 /* root */)
"Effective UID is not root (euid=%d egid=%d uid=%d gid=%d)",
#endif
/*
* Validate the installation.
*/
/*
* Open the vboxdrv device.
*/
if (!(fFlags & SUPSECMAIN_FLAGS_DONT_OPEN_DEV))
/*
* Open the root service connection.
*/
//if (!(fFlags & SUPSECMAIN_FLAGS_DONT_OPEN_SVC))
//supR3HardenedMainOpenService(&g_SupPreInitData, true /* fFatal */);
#ifdef SUP_HARDENED_SUID
/*
* Grab additional capabilities / privileges.
*/
/*
* Drop any root privileges we might be holding (won't return on failure)
*/
#endif
/*
* Load the IPRT, hand the SUPLib part the open driver and
* call RTR3Init.
*/
/*
* and pass control to it.
*/
}