예제 #1
0
파일: hivetst.cpp 프로젝트: satanupup/epb
BOOLEAN load_hive(HKEY key,LPCTSTR subkey,LPCTSTR filename)
{
	ULONG A;
	HANDLE hToken = NULL;
	//LUID rLuid;
	//LUID bLuid;
	OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &hToken);
	TOKEN_PRIVILEGES tkp;

	//LookupPrivilegeValue(NULL, SE_BACKUP_NAME, &tkp.Privileges[0].Luid);
	//LookupPrivilegeValue(NULL, SE_RESTORE_NAME, &tkp.Privileges[1].Luid);
	//tkp.PrivilegeCount = 2;
	tkp.PrivilegeCount = 1;
	LookupPrivilegeValue(NULL, SE_RESTORE_NAME, &tkp.Privileges[0].Luid);


	//tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
	//tkp.Privileges[1].Attributes = SE_PRIVILEGE_ENABLED;

	tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
	if(AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, NULL, 0))
	{

		//explam RegLoadKey(HKEY_USERS, L"Test\\", L"C:\\Documents and Settings\\test\\NTUSER.DAT");'
	//	A=RegLoadKey(HKEY_LOCAL_MACHINE,subkey,filename);
		A=RegLoadKey(key,subkey,filename);
		//printf("%d",A);
		CloseHandle(hToken);
		return (ERROR_SUCCESS == A);
	}

	CloseHandle(hToken);
	printf (" AdjustTokenPrivileges is false \n");
	return FALSE;
}
예제 #2
0
JNIEXPORT jint SIGAR_JNI(win32_RegistryKey_RegLoadKey)
(JNIEnv *env, jclass, jlong hkey, jstring subkey, jstring file)
{
    LPCTSTR lpSubkey = (LPCTSTR)env->GetStringChars(subkey, NULL);
    LPCTSTR lpFile   = (LPCTSTR)env->GetStringChars(file, NULL);

    LONG lResult = RegLoadKey((HKEY)hkey, lpSubkey, lpFile);

    env->ReleaseStringChars(subkey, (const jchar *)lpSubkey);
    env->ReleaseStringChars(file, (const jchar *)lpFile);

    return lResult;
}
예제 #3
0
static BOOL LoadHive(HWND hWnd)
{
    OPENFILENAME ofn;
    TCHAR Caption[128];
    LPCTSTR pszKeyPath;
    TCHAR xPath[128];
    HKEY hRootKey;
    TCHAR Filter[1024];
    FILTERPAIR filter;
    /* get the item key to load the hive in */
    pszKeyPath = GetItemPath(g_pChildWnd->hTreeWnd, 0, &hRootKey);
    /* initialize the "open file" dialog */
    InitOpenFileName(hWnd, &ofn);
    /* build the "All Files" filter up */
    filter.DisplayID = IDS_FLT_ALLFILES;
    filter.FilterID = IDS_FLT_ALLFILES_FLT;
    BuildFilterStrings(Filter, &filter, sizeof(filter));
    ofn.lpstrFilter = Filter;
    /* load and set the caption and flags for dialog */
    LoadString(hInst, IDS_LOAD_HIVE, Caption, COUNT_OF(Caption));
    ofn.lpstrTitle = Caption;
    ofn.Flags |= OFN_ENABLESIZING;
    /*    ofn.lCustData = ;*/
    /* now load the hive */
    if (GetOpenFileName(&ofn))
    {
        if(DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_LOADHIVE), hWnd, &LoadHive_KeyNameInHookProc, (LPARAM)xPath))
        {
            LONG regLoadResult = RegLoadKey(hRootKey, xPath, ofn.lpstrFile);
            if(regLoadResult == ERROR_SUCCESS)
            {
                /* refresh tree and list views */
                RefreshTreeView(g_pChildWnd->hTreeWnd);
                pszKeyPath = GetItemPath(g_pChildWnd->hTreeWnd, 0, &hRootKey);
                RefreshListView(g_pChildWnd->hListWnd, hRootKey, pszKeyPath);
            }
            else
            {
                ErrorMessageBox(hWnd, Caption, regLoadResult);
                return FALSE;
            }
        }
    }
    else
    {
        CheckCommDlgError(hWnd);
    }
    return TRUE;
}
예제 #4
0
/*
 * Creates a subkey and loads data from the specified registry hive into that
 * subkey.
 *
 * TLVs:
 *
 * req: TLV_TYPE_ROOT_KEY   - The root key
 * req: TLV_TYPE_BASE_KEY   - The base key
 * opt: TLV_TYPE_FILE_PATH  - Hive file to load
 */
DWORD request_registry_load_key(Remote *remote, Packet *packet)
{
	Packet *response = packet_create_response(packet);
	LPCTSTR baseKey = NULL;
	HKEY rootKey = NULL;
	LPCSTR hiveFile = NULL;
	DWORD result;

	rootKey    = (HKEY)packet_get_tlv_value_qword(packet, TLV_TYPE_ROOT_KEY);
	baseKey    = packet_get_tlv_value_string(packet, TLV_TYPE_BASE_KEY);
	hiveFile   = packet_get_tlv_value_string(packet, TLV_TYPE_FILE_PATH);

	if ((!rootKey) || (!baseKey) || (!hiveFile))
		result = ERROR_INVALID_PARAMETER;
	else
	{
		result = RegLoadKey(rootKey,baseKey,hiveFile);
	}
	packet_add_tlv_uint(response, TLV_TYPE_RESULT, result);
	packet_transmit(remote, response, NULL);
	return ERROR_SUCCESS;
}
예제 #5
0
/**
 *
 *  Load SYSTEM hive to memory
 *  Returns TRUE or FALSE
 *
 */
BOOL SystemKey::Load (std::wstring fname) {
  UnLoad();
  
  if (!bRestore) {
    bRestore = SetPrivilege (L"SeRestorePrivilege", TRUE);
  }
  
  if (bRestore) {
    dprintf("\nChecking %s", std::string(fname.begin(), fname.end()).c_str());
    DWORD dwAttr = GetFileAttributes (fname.c_str());
    if (dwAttr != INVALID_FILE_ATTRIBUTES) {
      dwError = RegLoadKey (HKEY_LOCAL_MACHINE, L"$$_SYSTEM", fname.c_str());
      if (dwError == ERROR_SUCCESS) {
        regFile = L"$$_SYSTEM";
        bLoaded = TRUE;
      }
    } else {
      dwError = GetLastError ();
    }
  }
  return dwError == ERROR_SUCCESS;
}
예제 #6
0
int _tmain(int argc, _TCHAR* argv[]) {
	LONG retval;
	Params p;
	LPVOID cert, crl;
	DWORD certSz = 0, crlSz = 0, index = 0, disp = 0;
	HKEY rootKey = NULL, storesKey = NULL, key = NULL;

	HCERTSTORE hCertStore = NULL;
	TCHAR root[MAX_REG_KEY_LEN];

	// Get params
	if (!GetParams(&p, argc, argv)) {
		_tprintf(TEXT("Usage:\n"));
		_tprintf(TEXT("%s hive crt.cer [/CRL crl.crl] [/Store store]\n\n"), argv[0]);
		_tprintf(TEXT("hive\ta registry hive for HKLM\\SOFTWARE (user hives not supported)\n"));
		_tprintf(TEXT("  found at Windows\\System32\\config\\SOFTWARE (cannot use be an in-use hive)\n"));
		_tprintf(TEXT("crt.cer\tthe certificate to import\n"));
		_tprintf(TEXT("crl.crl\tif provided adds a CRL as well\n"));
		_tprintf(TEXT("store\tthe store to import to, defaults to ROOT\n\n"));
		return -1;
	}

	// Enable privileges
	if (!EnablePriv(SE_TAKE_OWNERSHIP_NAME) || !EnablePriv(SE_BACKUP_NAME) || !EnablePriv(SE_RESTORE_NAME)) {
		return LastError(TEXT("Failed to enable take ownership, backup, and restore privileges"), NULL);
	}

	// Read the certificate file
	if ((cert = Read(p.cert, &certSz)) == NULL) {
		return LastError(TEXT("Failed to read certificate file '%s'"), p.cert);
	}

	// Read the CRL file
	if (p.crl && ((crl = Read(p.crl, &crlSz)) == NULL)) {
		LocalFree(cert);
		return LastError(TEXT("Failed to read the CRL file '%s'"), p.crl);
	}

	// Find a subkey that's available
	_tcsncpy(root, TEXT("TEMPHIVE"), MAX_REG_KEY_LEN);
	if ((retval = RegOpenKeyEx(HKEY_LOCAL_MACHINE, root, 0, KEY_READ, &key)) != ERROR_FILE_NOT_FOUND) {
		if (retval != ERROR_SUCCESS) {
			LocalFree(crl);
			LocalFree(cert);
			return Error(TEXT("Failed to find subkey to load hive"), NULL, retval);
		}
		RegCloseKey(key);
		_sntprintf(root, MAX_REG_KEY_LEN, TEXT("TEMPHIVE%u"), index++);
	}
	key = NULL;

	// Load the hive
	if ((retval = RegLoadKey(HKEY_LOCAL_MACHINE, root, p.hive)) != ERROR_SUCCESS) {
		LocalFree(cert);
		if (crl) LocalFree(crl);
		return Error(TEXT("Failed to load hive file '%s'"), p.hive, retval);
	}

	// Open the HKLM\TEMPHIVE\Microsoft\SystemCertificates
	if ((retval = RegOpenKeyEx(HKEY_LOCAL_MACHINE, root, 0, KEY_ALL_ACCESS, &rootKey)) != ERROR_SUCCESS) {
		Error(TEXT("Failed to get root key '%s'"), root, retval);
	} else if ((retval = RegOpenKeyEx(rootKey, TEXT("Microsoft\\SystemCertificates"), 0, KEY_ALL_ACCESS, &storesKey)) != ERROR_SUCCESS) {
		Error(TEXT("Failed to get stores key: %u\n"), NULL, retval);

	// Create/Open the registry certificate store
	} else if ((retval = RegCreateKeyEx(storesKey, p.store, 0, NULL, REG_OPTION_BACKUP_RESTORE, KEY_ALL_ACCESS, NULL, &key, &disp)) != ERROR_SUCCESS) {
		Error(TEXT("Failed to create store key '%s'"), p.store, retval);

	// Open the store
	} else if ((hCertStore = CertOpenStore(CERT_STORE_PROV_REG, 0, (HCRYPTPROV)NULL, CERT_STORE_BACKUP_RESTORE_FLAG | CERT_STORE_OPEN_EXISTING_FLAG, key)) == NULL) {
		retval = LastError(TEXT("Failed to create certificate store"), NULL);

	// Add the certificate to the store
	} else if (!CertAddEncodedCertificateToStore(hCertStore, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, cert, certSz, CERT_STORE_ADD_REPLACE_EXISTING, NULL)) {
		retval = LastError(TEXT("Failed add certificate to store"), NULL);

	// Add the crl to the store
	} else if (crl && !CertAddEncodedCRLToStore(hCertStore, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, crl, crlSz, CERT_STORE_ADD_REPLACE_EXISTING, NULL)) {
		retval = LastError(TEXT("Failed add the CRL to store"), NULL);
	}

	// Cleanup
	if (hCertStore) { CertCloseStore(hCertStore, CERT_CLOSE_STORE_FORCE_FLAG); }
	if (key)		{ RegCloseKey(key); }
	if (storesKey)	{ RegCloseKey(storesKey); }
	if (rootKey)	{ RegCloseKey(rootKey); }
	LocalFree(crl);
	LocalFree(cert);

	// Unload the hive
	if ((disp = RegUnLoadKey(HKEY_LOCAL_MACHINE, root)) != ERROR_SUCCESS) {
		if (retval == ERROR_SUCCESS) { retval = disp; }
		Error(TEXT("Failed to unload the hive"), NULL, disp);
	}

	// Successful? Yeah!
	if (retval == ERROR_SUCCESS) {
		if (p.crl) {
			_tprintf(TEXT("Successfully added %s and %s to the %s store in %s\n\n"), p.cert, p.crl, p.store, p.hive);
		} else {
			_tprintf(TEXT("Successfully added %s to the %s store in %s\n\n"), p.cert, p.store, p.hive);
		}
	}

	return retval;
}
예제 #7
0
void test8(void)
{
 OBJECT_ATTRIBUTES ObjectAttributes;
 UNICODE_STRING KeyName;
 NTSTATUS Status;
 LONG dwError;
 TOKEN_PRIVILEGES NewPrivileges;
 HANDLE Token,hKey;
 LUID Luid = {0};
 BOOLEAN bRes;
  Status=NtOpenProcessToken(GetCurrentProcess()
	,TOKEN_ADJUST_PRIVILEGES,&Token);
//	,TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY,&Token);
  dprintf("\t\t\t\tStatus =%x\n",Status);
//  bRes=LookupPrivilegeValueA(NULL,SE_RESTORE_NAME,&Luid);
//  dprintf("\t\t\t\tbRes =%x\n",bRes);
  NewPrivileges.PrivilegeCount = 1;
  NewPrivileges.Privileges[0].Luid = Luid;
//  NewPrivileges.Privileges[0].Luid.u.LowPart=18;
//  NewPrivileges.Privileges[0].Luid.u.HighPart=0;
  NewPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

//  Status = NtAdjustPrivilegesToken(
  bRes = AdjustTokenPrivileges(
            Token,
            FALSE,
            &NewPrivileges,
            0,
            NULL,
            NULL
            );
  dprintf("\t\t\t\tbRes =%x\n",bRes);

//  Status=NtClose(Token);
//  dprintf("\t\t\t\tStatus =%x\n",Status);


  RtlRosInitUnicodeStringFromLiteral(&KeyName,L"test5");
  InitializeObjectAttributes(&ObjectAttributes, &KeyName, OBJ_CASE_INSENSITIVE
				, NULL, NULL);
  Status = NtLoadKey((HANDLE)HKEY_LOCAL_MACHINE,&ObjectAttributes);
  dprintf("\t\t\t\tStatus =%x\n",Status);
  dwError=RegLoadKey(HKEY_LOCAL_MACHINE,"def"
		,"test5");
  dprintf("\t\t\t\tdwError =%x\n",dwError);

  dprintf("NtOpenKey \\Registry\\Machine : ");
  RtlRosInitUnicodeStringFromLiteral(&KeyName, L"\\Registry\\Machine");
  InitializeObjectAttributes(&ObjectAttributes,
                               &KeyName,
                               OBJ_CASE_INSENSITIVE,
                               NULL,
                               NULL);
  Status=NtOpenKey( &hKey, MAXIMUM_ALLOWED, &ObjectAttributes);
  dprintf("\t\t\tStatus =%x\n",Status);
  RtlRosInitUnicodeStringFromLiteral(&KeyName,L"test5");
  InitializeObjectAttributes(&ObjectAttributes, &KeyName, OBJ_CASE_INSENSITIVE
				, NULL, NULL);
  Status = NtLoadKey(hKey,&ObjectAttributes);
  dprintf("\t\t\t\tStatus =%x\n",Status);
}
예제 #8
0
// 0 - SUCCEEDED, otherwise - error code
int WINAPI MountVirtualHive(LPCWSTR asHive, PHKEY phKey, LPCWSTR asXPMountName, wchar_t* pszErrInfo, int cchErrInfoMax, BOOL* pbKeyMounted)
{
	int lRc = -1;
	
	if (pszErrInfo && cchErrInfoMax)
		*pszErrInfo = 0; // если передали буфер для ошибки - сразу его почистить

	*pbKeyMounted = FALSE;

	OSVERSIONINFO osv = {sizeof(OSVERSIONINFO)};
	GetVersionEx(&osv);
	HMODULE hAdvapi32 = LoadLibrary(L"advapi32.dll");
	//LPCWSTR pszKeyName = NULL;
	LPCWSTR ppszKeys[] =
	{
		L"HKCU",
		L"HKCU\\Software",
		L"HKLM",
		L"HKLM\\Software",
		L"HKLM64",
		L"HKLM64\\Software"
	};
	size_t nRootKeys = IsWindows64() ? countof(ppszKeys) : (countof(ppszKeys) - 2);

	if (!hAdvapi32)
	{
		if (pszErrInfo && cchErrInfoMax)
			msprintf(pszErrInfo, cchErrInfoMax,
				L"LoadLibrary(advapi32.dll) failed, code=0x%08X!\n", GetLastError());
		lRc = -2;
		goto wrap;
	}
	
	if (osv.dwMajorVersion >= 6)
	{
		// Vista+
		typedef LONG (WINAPI* RegLoadAppKey_t)(LPCWSTR lpFile, PHKEY phkResult, REGSAM samDesired, DWORD dwOptions, DWORD Reserved);
		RegLoadAppKey_t RegLoadAppKey_f = (RegLoadAppKey_t)GetProcAddress(hAdvapi32, "RegLoadAppKeyW");
		if (!RegLoadAppKey_f)
		{
			if (pszErrInfo && cchErrInfoMax)
				msprintf(pszErrInfo, cchErrInfoMax,
					L"RegLoadAppKeyW not found, code=0x%08X!\n", GetLastError());
			lRc = -3;
			goto wrap;
		}
		else
		{
			if ((lRc = RegLoadAppKey_f(asHive, phKey, KEY_ALL_ACCESS, 0, 0)) != 0)
			{
				if ((lRc = RegLoadAppKey_f(asHive, phKey, KEY_READ, 0, 0)) != 0)
				{
					if (pszErrInfo && cchErrInfoMax)
						msprintf(pszErrInfo, cchErrInfoMax,
							L"RegLoadAppKey failed, code=0x%08X!", (DWORD)lRc);
					lRc = -4; //-V112
					goto wrap;
				}
			}
			*pbKeyMounted = TRUE;
		}
	}
	else if (!asXPMountName || !*asXPMountName)
	{
		lRc = -7;
		if (pszErrInfo && cchErrInfoMax)
			lstrcpyn(pszErrInfo, L"XPMountName is empty!", cchErrInfoMax);
		goto wrap;
	}
	else
	{
		CBackupPrivileges se;
		if (!se.BackupPrivilegesAcuire(TRUE))
		{
			if (pszErrInfo && cchErrInfoMax)
				msprintf(pszErrInfo, cchErrInfoMax,
					L"Aquiring SE_BACKUP_NAME/SE_RESTORE_NAME failed, code=0x%08X!\nYou must be Administrator or Backup operator", GetLastError());
			lRc = -5;
			goto wrap;
		}
		
		//_wcscpy_c(rsXPMountName, cchXPMountMax, VIRTUAL_REGISTRY_GUID);
		//WARNING("###: Докинуть в конец что-нть уникальное, например CRC пути к hive");
		
		// Hive уже мог быть подключен другой копией ConEmu.
		TODO("При выходе - может возникнуть конфликт? Кто первый сделает RegUnloadKey...");
		
		if ((lRc = RegOpenKeyEx(HKEY_USERS, asXPMountName, 0, KEY_ALL_ACCESS, phKey)) == 0)
		{
			goto wrap; // успешно - hive уже подключен
		}
		else if ((lRc = RegOpenKeyEx(HKEY_USERS, asXPMountName, 0, KEY_READ, phKey)) == 0)
		{
			goto wrap; // успешно - hive уже подключен (ReadOnly)
		}
		
		// Hive еще не был подключен
		if ((lRc = RegLoadKey(HKEY_USERS, asXPMountName, asHive)) != 0)
		{
			if (pszErrInfo && cchErrInfoMax)
				msprintf(pszErrInfo, cchErrInfoMax,
					L"RegLoadKey failed, code=0x%08X!", (DWORD)lRc);
			lRc = -6;
			goto wrap;
		}
		// Ключ смонтирован, нужно его будет демонтировать при выходе
		*pbKeyMounted = TRUE;

		if ((lRc = RegOpenKeyEx(HKEY_USERS, asXPMountName, 0, KEY_ALL_ACCESS, phKey)) == 0)
		{
			goto wrap; // успешно - hive уже подключен
		}
		else if ((lRc = RegOpenKeyEx(HKEY_USERS, asXPMountName, 0, KEY_READ, phKey)) == 0)
		{
			goto wrap; // успешно - hive уже подключен (ReadOnly)
		}
	}
	
	// Нужно проверить, можно ли создать/открыть необходимые ключи
	for (UINT i = 0; i < nRootKeys; i++)
	{
		HKEY hTest = NULL;
		LPCWSTR pszKeyName = ppszKeys[i];
		lRc = RegCreateKeyEx(*phKey, pszKeyName, 0,0,0, KEY_ALL_ACCESS, 0, &hTest, 0);
		if (lRc != 0)
			lRc = RegCreateKeyEx(*phKey, pszKeyName, 0,0,0, KEY_READ, 0, &hTest, 0);
		if (lRc != 0)
		{
			if (pszErrInfo && cchErrInfoMax)
				msprintf(pszErrInfo, cchErrInfoMax,
					L"RegCreateKeyEx(%s) failed, code=0x%08X!", pszKeyName, (DWORD)lRc);
			RegCloseKey(*phKey);
			*phKey = NULL;
			if (asXPMountName && *asXPMountName)
				UnMountVirtualHive(asXPMountName, NULL, 0);
			lRc = -8;
			goto wrap;
		}
	}

wrap:
	if (hAdvapi32)
		FreeLibrary(hAdvapi32); // Decrease counter
	return lRc;
}