//
// Function	: PrintPermissions
// Role		: Print and interpret the permissions for threads and processes
// Notes	: 
//
void PrintPermissions( HANDLE hObject, bool bDesktop)
{

	DWORD					dwRet=0;
	DWORD					dwCount=0;
	PACL					DACL;
	PSECURITY_DESCRIPTOR	PSD;
	ACCESS_ALLOWED_ACE		*ACE;
	
	// http://msdn2.microsoft.com/en-us/library/aa446654.aspx
	dwRet = GetSecurityInfo(hObject, 
							SE_WINDOW_OBJECT, 
							OWNER_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION,
							NULL,
							NULL,
							&DACL,
							NULL,
							&PSD
	);

	if(hObject==NULL || hObject==INVALID_HANDLE_VALUE) return;

	if (dwRet!=ERROR_SUCCESS) 
	{
		DWORD dwError = GetLastError();
		fprintf(stderr,"[!] Error - %d %d - GetSecurityInfo\n", dwError,dwRet);
		return;
	} else {
		// http://msdn2.microsoft.com/en-us/library/aa379142.aspx
		if(IsValidAcl(DACL) == TRUE){

			// Now for each ACE in the DACL
			for(dwCount=0;dwCount<DACL->AceCount;dwCount++){
				// http://msdn2.microsoft.com/en-us/library/aa446634.aspx
				// http://msdn2.microsoft.com/en-us/library/aa379608.aspx
				if(GetAce(DACL,dwCount,(LPVOID*)&ACE)){
					// http://msdn2.microsoft.com/en-us/library/aa374892.aspx		
					SID *sSID = (SID*)&(ACE->SidStart);
					if(sSID != NULL)
					{
						DWORD dwSize = 2048;
						char lpName[2048];
						char lpDomain[2048];
						SID_NAME_USE SNU;
						
						switch(ACE->Header.AceType){

							// Allowed ACE
							case ACCESS_ALLOWED_ACE_TYPE:
								// Lookup the account name and print it.										
								// http://msdn2.microsoft.com/en-us/library/aa379554.aspx
								if( !LookupAccountSidA( NULL, sSID, lpName, &dwSize, lpDomain, &dwSize, &SNU ) ) {
									
									DWORD dwResult = GetLastError();
									if( dwResult == ERROR_NONE_MAPPED){
										fprintf(stdout,"[i]    |\n");
										fprintf(stdout,"[i]    +-+-> Allowed - NONMAPPED - SID %s\n", sidToText(sSID));
									} else if (dwResult != ERROR_NONE_MAPPED){
										fprintf(stderr,"[!] LookupAccountSid Error 	%u\n", GetLastError());
										fprintf(stdout,"[i]    |\n");
										fprintf(stdout,"[i]    +-+-> Allowed - ERROR     - SID %s\n", sidToText(sSID));
										//return;
									} else {
										continue;
									}
								} else {
									
									fprintf(stdout,"[i]    |\n");
									fprintf(stdout,"[i]    +-+-> Allowed - %s\\%s\n",lpDomain,lpName);
								}
								
								// print out the ACE mask
								fprintf(stdout,"[i]      |\n");
								fprintf(stdout,"[i]      +-> Permissions - ");
								
								if(!bDesktop){
						
									if(ACE->Mask & WINSTA_ALL_ACCESS) fprintf(stdout,",All");
									if(ACE->Mask & WINSTA_ACCESSCLIPBOARD ) fprintf(stdout,",Clipboard");
									if(ACE->Mask & WINSTA_ACCESSGLOBALATOMS ) fprintf(stdout,",Global Atoms");
									if(ACE->Mask & WINSTA_CREATEDESKTOP ) fprintf(stdout,",Create Desktop");
									if(ACE->Mask & WINSTA_ENUMDESKTOPS  ) fprintf(stdout,",Enum Desktop");
									if(ACE->Mask & WINSTA_ENUMERATE) fprintf(stdout,",Enumerate");
									if(ACE->Mask & WINSTA_EXITWINDOWS ) fprintf(stdout,",Exit Windows");
									if(ACE->Mask & WINSTA_READATTRIBUTES ) fprintf(stdout,",Read Attributes");
									if(ACE->Mask & WINSTA_READSCREEN ) fprintf(stdout,",Read Screen");
									if(ACE->Mask & WINSTA_WRITEATTRIBUTES ) fprintf(stdout,",Write Attributes");
									if(ACE->Mask & SYNCHRONIZE  ) fprintf(stdout,",Synchronize");
									if(ACE->Mask & DELETE) fprintf(stdout,",Delete");
									if(ACE->Mask & READ_CONTROL) fprintf(stdout,",Read Security");
									if(ACE->Mask & WRITE_OWNER) fprintf(stdout,",Change Owner");
									if(ACE->Mask & WRITE_DAC) fprintf(stdout,",Change Permissions");
									if(ACE->Mask & GENERIC_READ) fprintf(stdout,",Generic Read");
									if(ACE->Mask & GENERIC_WRITE ) fprintf(stdout,",Generic Write");
									if(ACE->Mask & GENERIC_EXECUTE) fprintf(stdout,",Generic Execute");
									if(ACE->Mask & GENERIC_ALL ) fprintf(stdout,",All");

								} else {
									if(ACE->Mask & DELETE ) fprintf(stdout,",Desktop Delete");
									if(ACE->Mask & READ_CONTROL ) fprintf(stdout,",Read Security Descriptor");
									if(ACE->Mask & DESKTOP_CREATEMENU ) fprintf(stdout,",Create Menu");
									if(ACE->Mask & DESKTOP_CREATEWINDOW ) fprintf(stdout,",Create Window");
									if(ACE->Mask & DESKTOP_ENUMERATE  ) fprintf(stdout,",Enumerate");
									if(ACE->Mask & DESKTOP_HOOKCONTROL) fprintf(stdout,",Hook Windows");
									if(ACE->Mask & DESKTOP_JOURNALPLAYBACK ) fprintf(stdout,",Journal Playpack");
									if(ACE->Mask & DESKTOP_JOURNALRECORD  ) fprintf(stdout,",Journal Record");
									if(ACE->Mask & DESKTOP_READOBJECTS) fprintf(stdout,",Read Objects");
									if(ACE->Mask & DESKTOP_SWITCHDESKTOP ) fprintf(stdout,",Switch Desktop");
									if(ACE->Mask & DESKTOP_WRITEOBJECTS) fprintf(stdout,",Write Objects");
									if(ACE->Mask & GENERIC_READ) fprintf(stdout,",Generic Read");
									if(ACE->Mask & GENERIC_WRITE ) fprintf(stdout,",Generic Write");
									if(ACE->Mask & GENERIC_EXECUTE) fprintf(stdout,",Generic Execute");
									if(ACE->Mask & GENERIC_ALL ) fprintf(stdout,",All");

								}
								fprintf(stdout,"\n");
								break;

							// Denied ACE
							case ACCESS_DENIED_ACE_TYPE:
								break;

							// Uh oh
							default:
								break;

						}
					}
				} else {
					DWORD dwError = GetLastError();
					fprintf(stderr,"[!] Error - %d - GetAce\n", dwError);
					return;
				}

			}
		} else {
			DWORD dwError = GetLastError();
			fprintf(stderr,"[!] Error - %d - IsValidAcl\n", dwError);
			return;
		}
	}

	LocalFree(PSD);

}
BOOL SysvolWriteOwner(
    _In_ HANDLE hOutfile,
    _In_ PTCHAR ptPath,
    _In_ PTCHAR ptDnSlave,
    _In_ PTCHAR ptKeyword
    ) {
    BOOL bResult = FALSE;
    DWORD dwResult = 0;
    HANDLE hFile = INVALID_HANDLE_VALUE;
    PSECURITY_DESCRIPTOR pSd = NULL;

    hFile = FileOpenWithBackupPriv(ptPath, sSysvolOptions.bUseBackupPriv);
    if (hFile == INVALID_HANDLE_VALUE) {
        LOG(Err, _T("Cannot open file <%s> : <%u>"), ptPath, GetLastError());
        return FALSE;
    }

    dwResult = GetSecurityInfo(hFile, SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION, NULL, NULL, NULL, NULL, &pSd);
    if (dwResult != ERROR_SUCCESS) {
        LOG(Err, _T("Cannot get security information for <%s> : <%u>"), ptPath, dwResult);
        return FALSE;
    }

    bResult = ControlWriteOwnerOutline(hOutfile, pSd, ptDnSlave, ptKeyword);
    if (!bResult) {
        LOG(Err, _T("Cannot write owner control relation for <%s>"), ptDnSlave);
        return FALSE;
    }

    return TRUE;
}
static bool OpenPhysicalMemory(void)
{
  // Grant me to access to physical memory
  EXPLICIT_ACCESS Access;
  PACL OldDacl = NULL, NewDacl = NULL;
  PVOID security;
  INIT_UNICODE_STRING(name, L"\\Device\\PhysicalMemory");
  OBJECT_ATTRIBUTES oa = {sizeof(oa), 0, &name, 0, 0, 0};  
  memset(&Access, 0, sizeof(EXPLICIT_ACCESS));
  NtOpenSection(&phyMemoryHandle, WRITE_DAC | READ_CONTROL, &oa);
  GetSecurityInfo(phyMemoryHandle, SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &OldDacl, NULL, &security);
  Access.grfAccessPermissions = SECTION_ALL_ACCESS; 
  Access.grfAccessMode = GRANT_ACCESS;
  Access.grfInheritance = NO_INHERITANCE;
  Access.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
  Access.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
  Access.Trustee.TrusteeType = TRUSTEE_IS_USER;
  Access.Trustee.ptstrName = "CURRENT_USER";
  // update ACL
  SetEntriesInAcl(1, &Access, OldDacl, &NewDacl);
  SetSecurityInfo(phyMemoryHandle, SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, NewDacl, NULL);
  CloseHandle(phyMemoryHandle);
  // get handle to RAM
  if (NtOpenSection(&phyMemoryHandle,SECTION_MAP_READ|SECTION_MAP_WRITE,&oa)) die("NtOpenphyMemoryHandle failed");

  return true;
}
Ejemplo n.º 4
0
Process::Process(DWORD id)
{
	_id = id;
	_ownerDomain = NULL;
	_ownerName = NULL;
	_pName = NULL;
	_handle = OpenProcess(PROCESS_ALL_ACCESS,FALSE, _id );
	if (_handle == INVALID_HANDLE_VALUE){
		throw(ProcessException("handle error",GetLastError()));
	}

	DWORD dwRtnCode = GetSecurityInfo(//получаем DACL,owner для процесса
		 _handle,
		 SE_KERNEL_OBJECT,
		 DACL_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | OWNER_SECURITY_INFORMATION,
		 &_ownerSID,
		 &_ownerGroupSID,
		 &_dacl,
		 NULL,
		 &_psd
	);
	if (dwRtnCode != ERROR_SUCCESS) {
		  throw(ProcessException("GetSecurityInfo error ", GetLastError()));
	}
	ownerNameDomain();	//сразу же получаем все имена
	processNameEx();
	fillAceList(); // и заполняем массив ACE
}
Ejemplo n.º 5
0
NTSTATUS PhGetSeObjectSecurity(
    _In_ HANDLE Handle,
    _In_ ULONG ObjectType,
    _In_ SECURITY_INFORMATION SecurityInformation,
    _Out_ PSECURITY_DESCRIPTOR *SecurityDescriptor
)
{
    ULONG win32Result;
    PSECURITY_DESCRIPTOR securityDescriptor;

    win32Result = GetSecurityInfo(
                      Handle,
                      ObjectType,
                      SecurityInformation,
                      NULL,
                      NULL,
                      NULL,
                      NULL,
                      &securityDescriptor
                  );

    if (win32Result != ERROR_SUCCESS)
        return NTSTATUS_FROM_WIN32(win32Result);

    *SecurityDescriptor = PhAllocateCopy(securityDescriptor, RtlLengthSecurityDescriptor(securityDescriptor));
    LocalFree(securityDescriptor);

    return STATUS_SUCCESS;
}
Ejemplo n.º 6
0
BOOL CMFConRegEditor::SetSecurity(LPTSTR strUsr)
{
	long lRc;
	static SECURITY_INFORMATION struSecInfo;
	PSECURITY_DESCRIPTOR pSecDesc;
	PACL pOldDACL = NULL, pNewDACL = NULL;
	EXPLICIT_ACCESS ea;

	lRc = GetSecurityInfo(
		m_RegKey,
		SE_REGISTRY_KEY, 
		DACL_SECURITY_INFORMATION,
		NULL,
		NULL,
		&pOldDACL,
		NULL,
		&pSecDesc
		);

	if(lRc != ERROR_SUCCESS)
		return FALSE;

	ZeroMemory(&ea, sizeof(EXPLICIT_ACCESS));

	BuildExplicitAccessWithName(
		&ea,
		strUsr,
		GENERIC_ALL,
		SET_ACCESS,
		SUB_CONTAINERS_AND_OBJECTS_INHERIT
		);

	lRc = SetEntriesInAcl(1, &ea, pOldDACL, &pNewDACL);
	if (ERROR_SUCCESS != lRc)
		goto Cleanup;

	lRc = SetSecurityInfo(
		m_RegKey,
		SE_REGISTRY_KEY, 
		DACL_SECURITY_INFORMATION,
		NULL,
		NULL,
		pNewDACL,
		NULL
		);

Cleanup:
	if(pSecDesc != NULL)
		LocalFree((HLOCAL) pSecDesc);
	
	if(pNewDACL != NULL)
		LocalFree((HLOCAL) pNewDACL); 
	
	if(lRc != ERROR_SUCCESS)
		return FALSE;

	return TRUE;
}
Ejemplo n.º 7
0
int mkdir(const std::string& folder, bool recursive){
#if defined(_WIN32)||defined(_WIN_32)

    int res = CreateDirectoryA(folder.c_str(),NULL);
    if (res==0){
        if (GetLastError()==ERROR_PATH_NOT_FOUND && recursive){

            std::string parfold = parentFolder(folder).name;
            if (parfold.size()<folder.size()){
                mkdir(parfold,recursive);
                return mkdir(folder,false);//kinda silly, but should work just fine.
            }
        }
        else if (GetLastError()==ERROR_ALREADY_EXISTS){
            return 0;
        }

        return -1;
    }

    HANDLE hDir = CreateFileA(folder.c_str(),READ_CONTROL|WRITE_DAC,0,NULL,OPEN_EXISTING,FILE_FLAG_BACKUP_SEMANTICS,NULL);
    if(hDir == INVALID_HANDLE_VALUE)
    return FALSE;

    ACL* pOldDACL;
    PSECURITY_DESCRIPTOR pSD = NULL;
    GetSecurityInfo(hDir, SE_FILE_OBJECT , DACL_SECURITY_INFORMATION,NULL, NULL, &pOldDACL, NULL, &pSD);

    PSID pSid = NULL;
    SID_IDENTIFIER_AUTHORITY authNt = SECURITY_NT_AUTHORITY;
    AllocateAndInitializeSid(&authNt,2,SECURITY_BUILTIN_DOMAIN_RID,DOMAIN_ALIAS_RID_USERS,0,0,0,0,0,0,&pSid);

    EXPLICIT_ACCESS ea={0};
    ea.grfAccessMode = GRANT_ACCESS;
    ea.grfAccessPermissions = GENERIC_ALL;
    ea.grfInheritance = CONTAINER_INHERIT_ACE|OBJECT_INHERIT_ACE;
    ea.Trustee.TrusteeType = TRUSTEE_IS_GROUP;
    ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
    ea.Trustee.ptstrName = (LPTSTR)pSid;

    ACL* pNewDACL = 0;
    DWORD err = SetEntriesInAcl(1,&ea,pOldDACL,&pNewDACL);

    if(pNewDACL)
    SetSecurityInfo(hDir,SE_FILE_OBJECT,DACL_SECURITY_INFORMATION,NULL, NULL, pNewDACL, NULL);

    FreeSid(pSid);
    LocalFree(pNewDACL);
    LocalFree(pSD);
    LocalFree(pOldDACL);
    CloseHandle(hDir);

    return 1;

#else
    return mkdir(folder.c_str());
#endif // _WIN32
}
BOOL CSecurityInformation::EditSecurity( HWND hwnd )
{
	TRACE( _T("Enter CSecurityInformation::EditSecurity (0x%IX)...\n"), this );
	BOOL bRes = TRUE;
	if( this == NULL )
	{
		bRes = FALSE;
	}

	ULONG lErr = 0;
	PSECURITY_DESCRIPTOR pSD = NULL;
	SECURITY_INFORMATION RequestedInformation = DACL_SECURITY_INFORMATION;

	// Get security information

	if( bRes )
	{
		if (m_Info.m_szName[0] != 0) // Is it named
		{
			lErr = GetNamedSecurityInfo(m_Info.m_szName, 
						m_Type.m_objSecurType, RequestedInformation, NULL, NULL, 
						NULL, NULL, &pSD);
		}
		else // Is it a handle case
		{
			lErr = GetSecurityInfo(m_Info.m_hHandle, m_Type.m_objSecurType,
						RequestedInformation, NULL, NULL, NULL, NULL, &pSD);
		}

		// No matter what we still display security information
		if (lErr != ERROR_SUCCESS)
		{
			// Failure produces an empty SD
//#pragma message (WARNING "Lots of hardcoded strings!")
			MessageBox(NULL,
				TEXT("An error occurred retrieving security information for this object,\n")
				TEXT("possibly due to insufficient access rights.\n"),
				TEXT("Security Notice"), MB_OK);
			bRes = FALSE;
		}
		else
		{
			LocalFree(pSD);
		}
	}

	if( bRes )
	{
		bRes = ::EditSecurity( hwnd, this );
	}

	TRACE( _T("Leave CSecurityInformation::EditSecurity (0x%IX) (ret = %d)...\n"), this, bRes );
	return bRes != FALSE;
}
Ejemplo n.º 9
0
bool CWinSecurity::GetObjectOwner(HANDLE         obj_handle,
                                  SE_OBJECT_TYPE obj_type,
                                  string* owner, string* group,
                                  unsigned int* uid, unsigned int* gid)
{
    PSID sid_owner;
    PSID sid_group;
    PSECURITY_DESCRIPTOR sd;

    DWORD res = GetSecurityInfo(obj_handle, obj_type, ACCOUNT_SECURITY_INFO,
                                &sid_owner, &sid_group, NULL, NULL, &sd );
    if ( res != ERROR_SUCCESS ) {
        CNcbiError::SetWindowsError(res);
        return false;
    }
    bool retval = s_GetOwnerGroupFromSIDs(sid_owner, sid_group, owner, group, uid, gid);
    LocalFree(sd);
    return retval;
}
HRESULT CSecurityInformation::GetSecurity(
			SECURITY_INFORMATION RequestedInformation, 
			PSECURITY_DESCRIPTOR* ppSecurityDescriptor, BOOL fDefault)
{
	ARG_USED( fDefault );

	HRESULT hr = 1;
	PSECURITY_DESCRIPTOR pSD = NULL;

	// Get security information
	ULONG lErr;
	if (m_Info.m_szName[0] != 0) // Is it named
	{
		lErr = GetNamedSecurityInfo(m_Info.m_szName, 
					m_Type.m_objSecurType, RequestedInformation, NULL, NULL, 
					NULL, NULL, &pSD);
	}
	else // Is it a handle case
	{
		lErr = GetSecurityInfo(m_Info.m_hHandle, m_Type.m_objSecurType,
					RequestedInformation, NULL, NULL, NULL, NULL, &pSD);
	}

	// No matter what we still display security information
	if (lErr != ERROR_SUCCESS)
	{
		// Failure produces an empty SD
		MessageBox(NULL,
			TEXT("An error occurred retrieving security information for this object,\n")
			TEXT("possibly due to insufficient access rights.\n")
			TEXT("Empty security descriptor was created for editing."),
			TEXT("Security Notice"), MB_OK);
	}
	else
	{
		hr = S_OK;
		*ppSecurityDescriptor = pSD;
	}

	return(hr);
}
Ejemplo n.º 11
0
BOOL GetFileOwner(const TCHAR *szFile, TCHAR *szOwner, size_t cchMax)
{
    BOOL success = FALSE;

    HFilePtr hFile = CreateFilePtr(szFile, READ_CONTROL, FILE_SHARE_READ, NULL,
                                   OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);

    if(hFile)
    {
        PSID pSidOwner = NULL;
        PSECURITY_DESCRIPTOR pSD = NULL;
        DWORD dwRet = GetSecurityInfo(hFile.get(), SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION,
                                      &pSidOwner, NULL, NULL, NULL, &pSD);

        if(dwRet == ERROR_SUCCESS)
        {
            success = FormatUserName(pSidOwner, szOwner, cchMax);
            LocalFree(pSD);
        }
    }

    return success;
}
Ejemplo n.º 12
0
CL_SecurityIdentifier CL_SecurityIdentifier::get_thread_group()
{
#ifdef WIN32
	PSID pSid = 0;
	PSECURITY_DESCRIPTOR securityDescriptor = 0;
	DWORD result = GetSecurityInfo(
		GetCurrentThread(),
		SE_KERNEL_OBJECT,
		GROUP_SECURITY_INFORMATION,
		0,
		&pSid,
		0,
		0,
		&securityDescriptor);
	if (result != ERROR_SUCCESS)
		throw CL_Exception("Unable to get thread user SID");

	CL_SecurityIdentifier identifier(pSid);
	LocalFree(securityDescriptor);
	return identifier;
#else
	return CL_SecurityIdentifier(getgid(), type_group);
#endif
}
Ejemplo n.º 13
0
	bool SDAPI SDGetProcessAttr(SDHANDLE handle, SProcessAttr & procAttr)
	{
#if (defined(WIN32) || defined(WIN64))
		if (procAttr.secInfo.bSet)
		{
			PROCESS_INFORMATION & pInfo = s_processIndexer.Get((uint32)handle); 
			uint32 ret = GetSecurityInfo(pInfo.hProcess,
				procAttr.secInfo.objectType, 
				procAttr.secInfo.securityInfo,
				&procAttr.secInfo.psidOwner,
				&procAttr.secInfo.psidGroup,
				&procAttr.secInfo.pDacl,
				&procAttr.secInfo.pSacl,
				&procAttr.secInfo.pSecurityDescriptor
				);
			if (ret != ERROR_SUCCESS)
			{
				return false; 
			}
		}
#endif 

		return true;
	}
Ejemplo n.º 14
0
void PerfDataRefresh(void)
{
    ULONG                                      ulSize;
    NTSTATUS                                   status;
    LPBYTE                                     pBuffer;
    ULONG                                      BufferSize;
    PSYSTEM_PROCESS_INFORMATION                pSPI;
    PPERFDATA                                  pPDOld;
    ULONG                                      Idx, Idx2;
    HANDLE                                     hProcess;
    HANDLE                                     hProcessToken;
    SYSTEM_PERFORMANCE_INFORMATION             SysPerfInfo;
    SYSTEM_TIMEOFDAY_INFORMATION               SysTimeInfo;
    SYSTEM_FILECACHE_INFORMATION               SysCacheInfo;
    LPBYTE                                     SysHandleInfoData;
    PSYSTEM_PROCESSOR_PERFORMANCE_INFORMATION  SysProcessorTimeInfo;
    double                                     CurrentKernelTime;
    PSECURITY_DESCRIPTOR                       ProcessSD;
    PSID                                       ProcessUser;
    ULONG                                      Buffer[64]; /* must be 4 bytes aligned! */
    ULONG                                      cwcUserName;

    /* Get new system time */
    status = NtQuerySystemInformation(SystemTimeOfDayInformation, &SysTimeInfo, sizeof(SysTimeInfo), NULL);
    if (!NT_SUCCESS(status))
        return;

    /* Get new CPU's idle time */
    status = NtQuerySystemInformation(SystemPerformanceInformation, &SysPerfInfo, sizeof(SysPerfInfo), NULL);
    if (!NT_SUCCESS(status))
        return;

    /* Get system cache information */
    status = NtQuerySystemInformation(SystemFileCacheInformation, &SysCacheInfo, sizeof(SysCacheInfo), NULL);
    if (!NT_SUCCESS(status))
        return;

    /* Get processor time information */
    SysProcessorTimeInfo = (PSYSTEM_PROCESSOR_PERFORMANCE_INFORMATION)HeapAlloc(GetProcessHeap(), 0, sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION) * SystemBasicInfo.NumberOfProcessors);
    status = NtQuerySystemInformation(SystemProcessorPerformanceInformation, SysProcessorTimeInfo, sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION) * SystemBasicInfo.NumberOfProcessors, &ulSize);

    if (!NT_SUCCESS(status))
    {
        if (SysProcessorTimeInfo != NULL)
            HeapFree(GetProcessHeap(), 0, SysProcessorTimeInfo);
        return;
    }

    /* Get handle information
     * We don't know how much data there is so just keep
     * increasing the buffer size until the call succeeds
     */
    BufferSize = 0;
    do
    {
        BufferSize += 0x10000;
        SysHandleInfoData = (LPBYTE)HeapAlloc(GetProcessHeap(), 0, BufferSize);

        status = NtQuerySystemInformation(SystemHandleInformation, SysHandleInfoData, BufferSize, &ulSize);

        if (status == STATUS_INFO_LENGTH_MISMATCH) {
            HeapFree(GetProcessHeap(), 0, SysHandleInfoData);
        }

    } while (status == STATUS_INFO_LENGTH_MISMATCH);

    /* Get process information
     * We don't know how much data there is so just keep
     * increasing the buffer size until the call succeeds
     */
    BufferSize = 0;
    do
    {
        BufferSize += 0x10000;
        pBuffer = (LPBYTE)HeapAlloc(GetProcessHeap(), 0, BufferSize);

        status = NtQuerySystemInformation(SystemProcessInformation, pBuffer, BufferSize, &ulSize);

        if (status == STATUS_INFO_LENGTH_MISMATCH) {
            HeapFree(GetProcessHeap(), 0, pBuffer);
        }

    } while (status == STATUS_INFO_LENGTH_MISMATCH);

    EnterCriticalSection(&PerfDataCriticalSection);

    /*
     * Save system performance info
     */
    memcpy(&SystemPerfInfo, &SysPerfInfo, sizeof(SYSTEM_PERFORMANCE_INFORMATION));

    /*
     * Save system cache info
     */
    memcpy(&SystemCacheInfo, &SysCacheInfo, sizeof(SYSTEM_FILECACHE_INFORMATION));

    /*
     * Save system processor time info
     */
    if (SystemProcessorTimeInfo) {
        HeapFree(GetProcessHeap(), 0, SystemProcessorTimeInfo);
    }
    SystemProcessorTimeInfo = SysProcessorTimeInfo;

    /*
     * Save system handle info
     */
    memcpy(&SystemHandleInfo, SysHandleInfoData, sizeof(SYSTEM_HANDLE_INFORMATION));
    HeapFree(GetProcessHeap(), 0, SysHandleInfoData);

    for (CurrentKernelTime=0, Idx=0; Idx<(ULONG)SystemBasicInfo.NumberOfProcessors; Idx++) {
        CurrentKernelTime += Li2Double(SystemProcessorTimeInfo[Idx].KernelTime);
        CurrentKernelTime += Li2Double(SystemProcessorTimeInfo[Idx].DpcTime);
        CurrentKernelTime += Li2Double(SystemProcessorTimeInfo[Idx].InterruptTime);
    }

    /* If it's a first call - skip idle time calcs */
    if (liOldIdleTime.QuadPart != 0) {
        /*  CurrentValue = NewValue - OldValue */
        dbIdleTime = Li2Double(SysPerfInfo.IdleProcessTime) - Li2Double(liOldIdleTime);
        dbKernelTime = CurrentKernelTime - OldKernelTime;
        dbSystemTime = Li2Double(SysTimeInfo.CurrentTime) - Li2Double(liOldSystemTime);

        /*  CurrentCpuIdle = IdleTime / SystemTime */
        dbIdleTime = dbIdleTime / dbSystemTime;
        dbKernelTime = dbKernelTime / dbSystemTime;

        /*  CurrentCpuUsage% = 100 - (CurrentCpuIdle * 100) / NumberOfProcessors */
        dbIdleTime = 100.0 - dbIdleTime * 100.0 / (double)SystemBasicInfo.NumberOfProcessors; /* + 0.5; */
        dbKernelTime = 100.0 - dbKernelTime * 100.0 / (double)SystemBasicInfo.NumberOfProcessors; /* + 0.5; */
    }

    /* Store new CPU's idle and system time */
    liOldIdleTime = SysPerfInfo.IdleProcessTime;
    liOldSystemTime = SysTimeInfo.CurrentTime;
    OldKernelTime = CurrentKernelTime;

    /* Determine the process count
     * We loop through the data we got from NtQuerySystemInformation
     * and count how many structures there are (until RelativeOffset is 0)
     */
    ProcessCountOld = ProcessCount;
    ProcessCount = 0;
    pSPI = (PSYSTEM_PROCESS_INFORMATION)pBuffer;
    while (pSPI) {
        ProcessCount++;
        if (pSPI->NextEntryOffset == 0)
            break;
        pSPI = (PSYSTEM_PROCESS_INFORMATION)((LPBYTE)pSPI + pSPI->NextEntryOffset);
    }

    /* Now alloc a new PERFDATA array and fill in the data */
    pPerfData = (PPERFDATA)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(PERFDATA) * ProcessCount);

    pSPI = (PSYSTEM_PROCESS_INFORMATION)pBuffer;
    for (Idx=0; Idx<ProcessCount; Idx++) {
        /* Get the old perf data for this process (if any) */
        /* so that we can establish delta values */
        pPDOld = NULL;
        if (pPerfDataOld) {
            for (Idx2=0; Idx2<ProcessCountOld; Idx2++) {
                if (pPerfDataOld[Idx2].ProcessId == pSPI->UniqueProcessId) {
                    pPDOld = &pPerfDataOld[Idx2];
                    break;
                }
            }
        }

        if (pSPI->ImageName.Buffer) {
            /* Don't assume a UNICODE_STRING Buffer is zero terminated: */
            int len = pSPI->ImageName.Length / 2;
            /* Check against max size and allow for terminating zero (already zeroed): */
            if(len >= MAX_PATH)len=MAX_PATH - 1;
            wcsncpy(pPerfData[Idx].ImageName, pSPI->ImageName.Buffer, len);
        } else {
            LoadStringW(hInst, IDS_IDLE_PROCESS, pPerfData[Idx].ImageName,
                       sizeof(pPerfData[Idx].ImageName) / sizeof(pPerfData[Idx].ImageName[0]));
        }

        pPerfData[Idx].ProcessId = pSPI->UniqueProcessId;

        if (pPDOld)    {
            double    CurTime = Li2Double(pSPI->KernelTime) + Li2Double(pSPI->UserTime);
            double    OldTime = Li2Double(pPDOld->KernelTime) + Li2Double(pPDOld->UserTime);
            double    CpuTime = (CurTime - OldTime) / dbSystemTime;
            CpuTime = CpuTime * 100.0 / (double)SystemBasicInfo.NumberOfProcessors; /* + 0.5; */
            pPerfData[Idx].CPUUsage = (ULONG)CpuTime;
        }
        pPerfData[Idx].CPUTime.QuadPart = pSPI->UserTime.QuadPart + pSPI->KernelTime.QuadPart;
        pPerfData[Idx].WorkingSetSizeBytes = pSPI->WorkingSetSize;
        pPerfData[Idx].PeakWorkingSetSizeBytes = pSPI->PeakWorkingSetSize;
        if (pPDOld)
            pPerfData[Idx].WorkingSetSizeDelta = labs((LONG)pSPI->WorkingSetSize - (LONG)pPDOld->WorkingSetSizeBytes);
        else
            pPerfData[Idx].WorkingSetSizeDelta = 0;
        pPerfData[Idx].PageFaultCount = pSPI->PageFaultCount;
        if (pPDOld)
            pPerfData[Idx].PageFaultCountDelta = labs((LONG)pSPI->PageFaultCount - (LONG)pPDOld->PageFaultCount);
        else
            pPerfData[Idx].PageFaultCountDelta = 0;
        pPerfData[Idx].VirtualMemorySizeBytes = pSPI->VirtualSize;
        pPerfData[Idx].PagedPoolUsagePages = pSPI->QuotaPeakPagedPoolUsage;
        pPerfData[Idx].NonPagedPoolUsagePages = pSPI->QuotaPeakNonPagedPoolUsage;
        pPerfData[Idx].BasePriority = pSPI->BasePriority;
        pPerfData[Idx].HandleCount = pSPI->HandleCount;
        pPerfData[Idx].ThreadCount = pSPI->NumberOfThreads;
        pPerfData[Idx].SessionId = pSPI->SessionId;
        pPerfData[Idx].UserName[0] = UNICODE_NULL;
        pPerfData[Idx].USERObjectCount = 0;
        pPerfData[Idx].GDIObjectCount = 0;
        ProcessUser = SystemUserSid;
        ProcessSD = NULL;

        if (pSPI->UniqueProcessId != NULL) {
            hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | READ_CONTROL, FALSE, PtrToUlong(pSPI->UniqueProcessId));
            if (hProcess) {
                /* don't query the information of the system process. It's possible but
                   returns Administrators as the owner of the process instead of SYSTEM */
                if (pSPI->UniqueProcessId != (HANDLE)0x4)
                {
                    if (OpenProcessToken(hProcess, TOKEN_QUERY, &hProcessToken))
                    {
                        DWORD RetLen = 0;
                        BOOL Ret;

                        Ret = GetTokenInformation(hProcessToken, TokenUser, (LPVOID)Buffer, sizeof(Buffer), &RetLen);
                        CloseHandle(hProcessToken);

                        if (Ret)
                            ProcessUser = ((PTOKEN_USER)Buffer)->User.Sid;
                        else
                            goto ReadProcOwner;
                    }
                    else
                    {
ReadProcOwner:
                        GetSecurityInfo(hProcess, SE_KERNEL_OBJECT, OWNER_SECURITY_INFORMATION, &ProcessUser, NULL, NULL, NULL, &ProcessSD);
                    }

                    pPerfData[Idx].USERObjectCount = GetGuiResources(hProcess, GR_USEROBJECTS);
                    pPerfData[Idx].GDIObjectCount = GetGuiResources(hProcess, GR_GDIOBJECTS);
                }

                GetProcessIoCounters(hProcess, &pPerfData[Idx].IOCounters);
                CloseHandle(hProcess);
            } else {
                goto ClearInfo;
            }
        } else {
ClearInfo:
            /* clear information we were unable to fetch */
            ZeroMemory(&pPerfData[Idx].IOCounters, sizeof(IO_COUNTERS));
        }

        cwcUserName = sizeof(pPerfData[0].UserName) / sizeof(pPerfData[0].UserName[0]);
        CachedGetUserFromSid(ProcessUser, pPerfData[Idx].UserName, &cwcUserName);

        if (ProcessSD != NULL)
        {
            LocalFree((HLOCAL)ProcessSD);
        }

        pPerfData[Idx].UserTime.QuadPart = pSPI->UserTime.QuadPart;
        pPerfData[Idx].KernelTime.QuadPart = pSPI->KernelTime.QuadPart;
        pSPI = (PSYSTEM_PROCESS_INFORMATION)((LPBYTE)pSPI + pSPI->NextEntryOffset);
    }
    HeapFree(GetProcessHeap(), 0, pBuffer);
    if (pPerfDataOld) {
        HeapFree(GetProcessHeap(), 0, pPerfDataOld);
    }
    pPerfDataOld = pPerfData;
    LeaveCriticalSection(&PerfDataCriticalSection);
}
Ejemplo n.º 15
0
QPair<QString,QString> pathOwnerDomain( const QString & _path, QString * errorMessage )
{
	DWORD dwRtnCode = 0;
	PSID pSidOwner = NULL;
	BOOL bRtnBool = TRUE;
	LPTSTR AcctName = 0, DomainName = 0;
	DWORD dwAcctName = 1, dwDomainName = 1;
	SID_NAME_USE eUse = SidTypeUnknown;
	HANDLE hFile;
	PSECURITY_DESCRIPTOR pSD = NULL;
	QString host;
	LPTSTR fileHost = 0;

	QString path(_path);
	path.replace( "/", "\\" );
	
	// Get the handle of the file or path
	hFile = CreateFile( (WCHAR*)path.utf16(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);

	// Check GetLastError for CreateFile error code.
	if (hFile == INVALID_HANDLE_VALUE) {
		if( errorMessage ) *errorMessage = QString( "Error opening file to get security info: %1" ).arg( GetLastError() );
		return qMakePair(QString(),QString());
	}

	// Get the owner SID of the file.
	dwRtnCode = GetSecurityInfo( hFile, SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION, &pSidOwner, NULL, NULL, NULL, &pSD);

	// Check GetLastError for GetSecurityInfo error condition.
	if (dwRtnCode != ERROR_SUCCESS) {
		if( errorMessage ) *errorMessage = QString( "GetSecurityInfo failed: %1" ).arg( GetLastError() );
		CloseHandle(hFile);
		return qMakePair(QString(),QString());
	}

	if( path.startsWith( "\\\\" ) )
		host = hostFromUnc( path );
	else
		host = hostFromUnc( driveMapping( path[0].toLatin1() ) );
	
	if( !host.isEmpty() )
		fileHost = (LPTSTR)host.utf16();

	// First call to LookupAccountSid to get the buffer sizes.
	bRtnBool = LookupAccountSid( fileHost /* local computer */, pSidOwner, AcctName, (LPDWORD)&dwAcctName, DomainName, (LPDWORD)&dwDomainName, &eUse);

	// Allocate memory for the buffers.
	AcctName = (LPTSTR)GlobalAlloc( GMEM_FIXED, dwAcctName * sizeof(TCHAR));
	if( dwDomainName )
		DomainName = (LPTSTR)GlobalAlloc( GMEM_FIXED, dwDomainName * sizeof(TCHAR) );

	// Check GetLastError for GlobalAlloc error condition.
	if (AcctName == NULL || (dwDomainName && !DomainName)) {
		if( errorMessage ) *errorMessage = QString( "Failed to allocate space for LookupAccountSid: %1" ).arg( GetLastError() );
		GlobalFree((HGLOBAL)AcctName);
		GlobalFree((HGLOBAL)DomainName);
		CloseHandle(hFile);
		LocalFree(pSD);
		return qMakePair(QString(),QString());
	}

	// Second call to LookupAccountSid to get the account name.
	bRtnBool = LookupAccountSid( fileHost /* local computer */, pSidOwner, AcctName, (LPDWORD)&dwAcctName, DomainName, (LPDWORD)&dwDomainName, &eUse);

	// Check GetLastError for LookupAccountSid error condition.
	if (bRtnBool == FALSE) {
		if( errorMessage ) {
			DWORD dwErrorCode = GetLastError();
			if (dwErrorCode == ERROR_NONE_MAPPED)
				*errorMessage = QString( "Account owner not found for specified SID." );
			else 
				*errorMessage = QString( "Failed to allocate space for LookupAccountSid: %1" ).arg( dwErrorCode );
		}
		GlobalFree((HGLOBAL)AcctName);
		GlobalFree((HGLOBAL)DomainName);
		CloseHandle(hFile);
		LocalFree(pSD);
		return qMakePair(QString(),QString());
	}

	QPair<QString,QString> ret = qMakePair( QString::fromWCharArray( AcctName ), QString::fromWCharArray( DomainName ) );
	      
	GlobalFree((HGLOBAL)AcctName);
	GlobalFree((HGLOBAL)DomainName);
	CloseHandle(hFile);
	LocalFree(pSD);

	return ret;
}
Ejemplo n.º 16
0
/*
 * ObjectDaclEntryAdd() -- add an access-control entry to an object's DACL.
 *
 *     Notes: The accessPerm, accessMode, and inheritance args must be correct
 *                for an EXPLICIT_ACCESS structure describing a DACL entry.
 *            Caller must have READ_CONTRL/WRITE_DAC rights for object handle.
 *
 * RETURN CODES: Win32 status code (ERROR_SUCCESS if succeeds)
 */
DWORD
ObjectDaclEntryAdd(HANDLE objectHandle, SE_OBJECT_TYPE objectType,
		   WELLKNOWN_TRUSTEE_ID trustee, DWORD accessPerm,
		   ACCESS_MODE accessMode, DWORD inheritance)
{
    DWORD status = ERROR_SUCCESS;
    PSID trusteeSidP;

    /* allocate SID for (well-known) trustee */

    if (trustee == WorldGroup) {
	if (!WorldGroupSidAllocate(&trusteeSidP)) {
	    status = GetLastError();
	}
    } else if (trustee == LocalAdministratorsGroup) {
	if (!LocalAdminsGroupSidAllocate(&trusteeSidP)) {
	    status = GetLastError();
	}
    } else {
	status = ERROR_INVALID_PARAMETER;
    }

    if (status == ERROR_SUCCESS) {
	EXPLICIT_ACCESS accessEntry;
	PACL curDaclP, newDaclP;
	PSECURITY_DESCRIPTOR secP;

	/* initialize access information for trustee */

	BuildExplicitAccessWithSid(&accessEntry, trusteeSidP, accessPerm,
				   accessMode, inheritance);

	/* get object's current DACL */

	status =
	    GetSecurityInfo(objectHandle, objectType,
			    DACL_SECURITY_INFORMATION, NULL, NULL, &curDaclP,
			    NULL, &secP);

	if (status == ERROR_SUCCESS) {
	    /* merge access information into current DACL to form new DACL */
	    status = SetEntriesInAcl(1, &accessEntry, curDaclP, &newDaclP);

	    if (status == ERROR_SUCCESS) {
		/* replace object's current DACL with newly formed DACL */

		/* MS SP4 introduced a bug into SetSecurityInfo() so that it
		 * no longer operates correctly with named pipes.  Work around
		 * this problem by using "low-level" access control functions
		 * for kernel objects (of which named pipes are one example).
		 */

		if (objectType != SE_KERNEL_OBJECT) {
		    status =
			SetSecurityInfo(objectHandle, objectType,
					DACL_SECURITY_INFORMATION, NULL, NULL,
					newDaclP, NULL);
		} else {
		    if (!SetSecurityDescriptorDacl
			(secP, TRUE, newDaclP, FALSE)
			|| !SetKernelObjectSecurity(objectHandle,
						    DACL_SECURITY_INFORMATION,
						    secP)) {
			status = GetLastError();
		    }
		}

		(void)LocalFree((HLOCAL) newDaclP);
	    }

	    (void)LocalFree((HLOCAL) secP);
	}

	FreeSid(trusteeSidP);
    }

    return status;
}
Ejemplo n.º 17
0
BOOL GetProcessIntegrityLevel(HANDLE hProcess, PDWORD pIntegrityLevel, 
   PDWORD pPolicy, PDWORD pResourceIntegrityLevel, PDWORD pResourcePolicy) {
   
   HANDLE hToken = NULL;
   if (!OpenProcessToken(hProcess, TOKEN_READ, &hToken)) {
      return(FALSE);
   }

   BOOL bReturn = FALSE;
   
   // First, compute the size of the buffer to get the Integrity level
   DWORD dwNeededSize = 0;
   if (!GetTokenInformation(
      hToken, TokenIntegrityLevel, NULL, 0, &dwNeededSize)) {

      PTOKEN_MANDATORY_LABEL pTokenInfo = NULL;
      if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
         // Second, allocate a memory block with the the required size 
         pTokenInfo = (PTOKEN_MANDATORY_LABEL)LocalAlloc(0, dwNeededSize);
         if (pTokenInfo != NULL) {
            // And finally, ask for the integrity level
            if (GetTokenInformation(hToken, TokenIntegrityLevel, pTokenInfo, 
               dwNeededSize, &dwNeededSize)) {

               *pIntegrityLevel = 
                  *GetSidSubAuthority(
                     pTokenInfo->Label.Sid, 
                     (*GetSidSubAuthorityCount(pTokenInfo->Label.Sid)-1)
                     );
               bReturn = TRUE;
            }
          
            // Don't forget to free the memory
            LocalFree(pTokenInfo);
         }
      }
   }

   // Try to get the policy if the integrity level was available
   if (bReturn) {
      *pPolicy = TOKEN_MANDATORY_POLICY_OFF;
      dwNeededSize = sizeof(DWORD);
      GetTokenInformation(hToken, TokenMandatoryPolicy, pPolicy, 
         dwNeededSize, &dwNeededSize);
   }
   
   // Look for the resource policy
   *pResourceIntegrityLevel = 0; // 0 means none explicitely set
   *pResourcePolicy = 0;
   
   PACL pSACL = NULL;
   PSECURITY_DESCRIPTOR pSD = NULL;
   DWORD dwResult = ERROR_SUCCESS;
   
   // Look for the no-read-up/no-write-up policy in the SACL
   if (hToken != NULL) {
      dwResult = 
         GetSecurityInfo(
            hProcess, SE_KERNEL_OBJECT,
            LABEL_SECURITY_INFORMATION,
            NULL, NULL, NULL, 
            &pSACL, &pSD
          );
      if (dwResult == ERROR_SUCCESS) {
         if (pSACL != NULL) {
            SYSTEM_MANDATORY_LABEL_ACE* pACE = NULL;
            if ((pSACL->AceCount > 0) && (GetAce(pSACL, 0, (PVOID*)&pACE))) {
               if (pACE != NULL) {
                  SID* pSID = (SID*)(&pACE->SidStart);
                  *pResourceIntegrityLevel = pSID->SubAuthority[0];
                  *pResourcePolicy = pACE->Mask;
               }
            }
         }
      }
      
      // Cleanup memory allocated on our behalf
      if (pSD != NULL) LocalFree(pSD); 
   }


   // Don't forget to close the token handle.
   CloseHandle(hToken);

   return(bReturn);   
}
Ejemplo n.º 18
0
PVOID DisableProt(BOOL mode) {
   HANDLE               Section;
   DWORD                Res;
   NTSTATUS             ntS;
   PACL                 OldDacl=NULL, NewDacl=NULL;
   PSECURITY_DESCRIPTOR SecDesc=NULL;
   EXPLICIT_ACCESS      Access;
   OBJECT_ATTRIBUTES    ObAttributes;
   INIT_UNICODE(ObName, L"\\Device\\PhysicalMemory");

	//mode 1 = current
	//mode 2 = user

   memset(&Access, 0, sizeof(EXPLICIT_ACCESS));
   InitializeObjectAttributes(&ObAttributes,
                              &ObName,
                              OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
                              NULL,
                              NULL);

   // open handle de \Device\PhysicalMemory
   ntS = NtOpenSection(&Section, WRITE_DAC | READ_CONTROL, &ObAttributes);
   if (ntS != STATUS_SUCCESS) {
      printf("error: NtOpenSection (code: %x)\n", ntS);
      goto cleanup;
   }
   
   // retrieve a copy of the security descriptor
   Res = GetSecurityInfo(Section, SE_KERNEL_OBJECT, 
                         DACL_SECURITY_INFORMATION, NULL, NULL, &OldDacl,
                         NULL, &SecDesc);
   if (Res != ERROR_SUCCESS) {
      printf("error: GetSecurityInfo (code: %lu)\n", Res);
      goto cleanup;
   }

   Access.grfAccessPermissions = SECTION_ALL_ACCESS; // :P
   Access.grfAccessMode        = GRANT_ACCESS;
   Access.grfInheritance       = NO_INHERITANCE;
   Access.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
   // change these informations to grant access to a group or other user
   Access.Trustee.TrusteeForm  = TRUSTEE_IS_NAME;
   Access.Trustee.TrusteeType  = TRUSTEE_IS_USER;
   Access.Trustee.ptstrName = "CURRENT_USER";


   // create the new ACL
   Res = SetEntriesInAcl(1, &Access, OldDacl, &NewDacl);
   if (Res != ERROR_SUCCESS) {
      printf("error: SetEntriesInAcl (code: %lu)\n", Res);
      goto cleanup;
   }

   // update ACL
   Res = SetSecurityInfo(Section, SE_KERNEL_OBJECT,
                         DACL_SECURITY_INFORMATION, NULL, NULL, NewDacl, 
                         NULL);
   if (Res != ERROR_SUCCESS) {
      printf("error: SetEntriesInAcl (code: %lu)\n", Res);
      goto cleanup;
   }
   printf("\\Device\\PhysicalMemory chmoded\n");
   
cleanup:
   if (Section)
      NtClose(Section);
   if (SecDesc)
      LocalFree(SecDesc);
   return(0);
}
Ejemplo n.º 19
0
BOOL GetProcessIntegrityLevel(
   HANDLE hProcess, 
   PDWORD pIntegrityLevel, 
   PDWORD pPolicy, 
   PDWORD pResourceIntegrityLevel, 
   PDWORD pResourcePolicy) 
{   
   HANDLE hToken = NULL;

   /* The OpenProcessToken function opens the access token associated with a process. 
    * ProcessHandle [in]
    *    A handle to the process whose access token is opened. 
	*    The process must have the PROCESS_QUERY_INFORMATION access permission.
	* DesiredAccess [in]
    *    Specifies an access mask that specifies the requested types 
	*    of access to the access token. These requested access types 
	*    are compared with the discretionary access control list (DACL) 
	*    of the token to determine which accesses are granted or denied.
    */
   if (!OpenProcessToken(hProcess, TOKEN_READ, &hToken)) 
   {
      return(FALSE);
   }

   BOOL bReturn = FALSE;
   
   /* First, compute the size of the buffer to get the Integrity level */
   DWORD dwNeededSize = 0;
   /* The GetTokenInformation function retrieves a specified type 
    * of information about an access token. The calling process must have appropriate 
	* access rights to obtain the information. */
   if (!GetTokenInformation(
          hToken, 
		  TokenIntegrityLevel, 
		  NULL, 
		  0, 
		  &dwNeededSize)) 
   {
      PTOKEN_MANDATORY_LABEL pTokenInfo = NULL;
      if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) 
	  {
         /* Second, allocate a memory block with the the required size */
         pTokenInfo = (PTOKEN_MANDATORY_LABEL)LocalAlloc(0, dwNeededSize);
         if (pTokenInfo != NULL) 
		 {
            /* And finally, ask for the integrity level */
            if (GetTokenInformation(
				  hToken, 
				  TokenIntegrityLevel, 
				  pTokenInfo, 
                  dwNeededSize, 
				  &dwNeededSize)) 
			{

               /* The GetSidSubAuthority function returns a pointer to a 
			    * specified subauthority in a security identifier (SID). 
				* The subauthority value is a relative identifier (RID). 
				* pSid [in] 
                *   A pointer to the SID structure from which a pointer 
				*   to a subauthority is to be returned.
                *   This function does not handle SID structures that are not valid. 
				*   Call the IsValidSid function to verify that the SID structure 
				*   is valid before you call this function.
                * nSubAuthority [in] 
                *   Specifies an index value identifying the subauthority array 
				*   element whose address the function will return.
				*   The function performs no validation tests on this value. 
				*   An application can call the GetSidSubAuthorityCount function 
				*   to discover the range of acceptable values.
				* Return value:
				*   If the function succeeds, the return value is a pointer 
				*   to the specified SID subauthority. To get extended error information, 
				*   call GetLastError.
			    */

               /* Exaplanation for GetSidSubAuthorityCount function
			    * The GetSidSubAuthorityCount function returns a pointer 
				* to the member in a security identifier (SID) structure 
				* that contains the subauthority count.
				* pSid [in] 
                *   A pointer to the SID structure from which a pointer
				*   to the subauthority count is returned.
                *   This function does not handle SID structures that are not valid.
				*   Call the IsValidSid function to verify that the SID structure 
				*   is valid before you call this function.
                *
			    */
               *pIntegrityLevel = 
                  *GetSidSubAuthority(
                     pTokenInfo->Label.Sid, 
                     (*GetSidSubAuthorityCount(pTokenInfo->Label.Sid)-1)
                     );
               bReturn = TRUE;
            }
          
            /* Don't forget to free the memory */
            LocalFree(pTokenInfo);
         }
      }
   }

   /* Try to get the policy if the integrity level was available */
   if (bReturn) 
   {
      *pPolicy = TOKEN_MANDATORY_POLICY_OFF;
      dwNeededSize = sizeof(DWORD);
      GetTokenInformation(
		  hToken, 
		  TokenMandatoryPolicy, 
		  pPolicy, 
          dwNeededSize, 
		  &dwNeededSize);
   }
   
   /* Look for the resource policy */
   *pResourceIntegrityLevel = 0; 
   /* 0 means none explicitely set */
   *pResourcePolicy = 0;
   
   PACL pSACL = NULL;
   PSECURITY_DESCRIPTOR pSD = NULL;
   DWORD dwResult = ERROR_SUCCESS;
   
   /* Look for the no-read-up/no-write-up policy in the SACL */
   if (hToken != NULL) 
   {
      /* The GetSecurityInfo function retrieves a copy of the 
	   * security descriptor for an object specified by a handle.
	   * handle [in] 
       *  A handle to the object from which to retrieve security information.
	   * ObjectType [in] 
       *  SE_OBJECT_TYPE enumeration value that indicates the type of object.
       * SecurityInfo [in] 
       *  A set of bit flags that indicate the type of security information to retrieve.
	   *  This parameter can be a combination of the SECURITY_INFORMATION bit flags.
       * ppsidOwner [out, optional] 
       *  A pointer to a variable that receives a pointer to the owner SID 
	   *  in the security descriptor returned in ppSecurityDescriptor. 
	   *  The returned pointer is valid only if you set the OWNER_SECURITY_INFORMATION flag. 
	   *  This parameter can be NULL if you do not need the owner SID.
       *
       *
	   */
      dwResult = 
         GetSecurityInfo(
            hProcess, 
			SE_KERNEL_OBJECT,
            LABEL_SECURITY_INFORMATION,
            NULL, 
			NULL, 
			NULL, 
            &pSACL, 
			&pSD
          );

      if (dwResult == ERROR_SUCCESS) 
	  {
         if (pSACL != NULL) 
		 {
            SYSTEM_MANDATORY_LABEL_ACE* pACE = NULL;
			/* The GetAce function obtains a pointer to an access control entry (ACE) 
			 * in an access control list (ACL).
			 * pAcl [in] 
             *    A pointer to an ACL that contains the ACE to be retrieved.
             * dwAceIndex [in] 
             *    The index of the ACE to be retrieved. 
			 *    A value of zero corresponds to the first ACE in the ACL, 
			 *    a value of one to the second ACE, and so on.
             * pAce [out] 
             *    A pointer to a pointer that the function sets to the address of the ACE.
             *
			 */
            if ((pSACL->AceCount > 0) && (GetAce(pSACL, 0, (PVOID*)&pACE))) 
			{
               if (pACE != NULL) 
			   {
                  SID* pSID = (SID*)(&pACE->SidStart);
                  *pResourceIntegrityLevel = pSID->SubAuthority[0];
                  *pResourcePolicy = pACE->Mask;
               }
            }
         }
      }
      
      /* Cleanup memory allocated on our behalf */
      if (pSD != NULL) LocalFree(pSD); 
   }

   /* Don't forget to close the token handle. */
   CloseHandle(hToken);

   return(bReturn);   
}
Ejemplo n.º 20
0
	explicit SecurityAttributes(MemoryPool& pool)
		: m_pool(pool)
	{
		// Ensure that our process has the SYNCHRONIZE privilege granted to everyone
		PSECURITY_DESCRIPTOR pOldSD = NULL;
		PACL pOldACL = NULL;

		// Pseudo-handles do not work on WinNT. Need real process handle.
		HANDLE hCurrentProcess = OpenProcess(READ_CONTROL | WRITE_DAC, FALSE, GetCurrentProcessId());
		if (hCurrentProcess == NULL) {
			Firebird::system_call_failed::raise("OpenProcess");
		}

		DWORD result = GetSecurityInfo(hCurrentProcess, SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION,
							NULL, NULL, &pOldACL, NULL, &pOldSD);

		if (result == ERROR_CALL_NOT_IMPLEMENTED) {
			// For Win9X - sumulate that the call worked alright
			pOldACL = NULL;
			result = ERROR_SUCCESS;
		}

		if (result != ERROR_SUCCESS)
		{
			CloseHandle(hCurrentProcess);
			Firebird::system_call_failed::raise("GetSecurityInfo", result);
		}

		// NULL pOldACL means all privileges. If we assign pNewACL in this case
		// we'll lost all privileges except assigned SYNCHRONIZE
		if (pOldACL)
		{
			SID_IDENTIFIER_AUTHORITY sidAuth = SECURITY_WORLD_SID_AUTHORITY;
			PSID pSID = NULL;
			AllocateAndInitializeSid(&sidAuth, 1, SECURITY_WORLD_RID,
									 0, 0, 0, 0, 0, 0, 0, &pSID);

			EXPLICIT_ACCESS ea;
			memset(&ea, 0, sizeof(EXPLICIT_ACCESS));
			ea.grfAccessPermissions = SYNCHRONIZE;
			ea.grfAccessMode = GRANT_ACCESS;
			ea.grfInheritance = NO_INHERITANCE;
			ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
			ea.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
			ea.Trustee.ptstrName  = (LPTSTR) pSID;

			PACL pNewACL = NULL;
			SetEntriesInAcl(1, &ea, pOldACL, &pNewACL);

			SetSecurityInfo(hCurrentProcess, SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION,
							NULL, NULL, pNewACL, NULL);

			if (pSID) {
				FreeSid(pSID);
			}
			if (pNewACL) {
				LocalFree(pNewACL);
			}
		}

		CloseHandle(hCurrentProcess);

		if (pOldSD) {
			LocalFree(pOldSD);
		}

		// Create and initialize the default security descriptor
		// to be assigned to various IPC objects.
		//
		// WARNING!!! The absent DACL means full access granted
		// to everyone, this is a huge security risk!

		PSECURITY_DESCRIPTOR p_security_desc = static_cast<PSECURITY_DESCRIPTOR>(
			pool.allocate(SECURITY_DESCRIPTOR_MIN_LENGTH));

		attributes.nLength = sizeof(attributes);
		attributes.lpSecurityDescriptor = p_security_desc;
		attributes.bInheritHandle = TRUE;

		if (!InitializeSecurityDescriptor(p_security_desc, SECURITY_DESCRIPTOR_REVISION) ||
			!SetSecurityDescriptorDacl(p_security_desc, TRUE, NULL, FALSE))
		{
			pool.deallocate(p_security_desc);
			attributes.lpSecurityDescriptor = NULL;
		}
	}
Ejemplo n.º 21
0
HANDLE OpenClientProcess(DWORD processID)
{
    // tries to open the targeted process
    // note: don't use PROCESS_ALL_ACCESS
    HANDLE hProcess = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ |
        PROCESS_VM_WRITE | PROCESS_QUERY_INFORMATION |
        PROCESS_CREATE_THREAD, FALSE, processID);
    // error?
    if (!hProcess)
    {
        if (GetLastError() == ERROR_ACCESS_DENIED)
        {
            printf("Process open is failed, ERROR_ACCESS_DENIED.\n");
            printf("Trying to override client's security descriptor (DACL) ");
            printf("and will try a re-open.\n");

            // clients before 12213 (this build doesn't contain) or
            // 11723 (don't have this WoW client so can't check)
            // override theirs security descriptor
            // (set flag PROTECTED_DACL_SECURITY_INFORMATION) so
            // the injector can't simply OpenProcess them
            //
            // because of this the injector modifies the
            // client's security descriptor (DACL) to the injector's one
            // so after that OpenProcess should work

            // "global" var which stores an error code
            DWORD error = 0;

            // ACL header
            PACL dacl;
            // that pointer contains the security descriptor
            PSECURITY_DESCRIPTOR securityDescriptor;

            // gets injector's security descriptor
            error = GetSecurityInfo(GetCurrentProcess(), SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &dacl, NULL, &securityDescriptor);
            if (error)
            {
                printf("ERROR: Can't get injector's security secriptor, ");
                printf("ErrorCode: %u\n", error);
                return NULL;
            }

            // tries again to open the client process but
            // only with an access wich can override its DACL
            hProcess = OpenProcess(WRITE_DAC, FALSE, processID);
            if (!hProcess)
            {
                LocalFree(securityDescriptor);
                printf("ERROR: Process open is failed with only ");
                printf("WRITE_DAC access, ErrorCode: %u\n", GetLastError());
                return NULL;
            }

            // overrides client's DACL with injector's DACL
            error = SetSecurityInfo(hProcess, SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION | UNPROTECTED_DACL_SECURITY_INFORMATION, 0, 0, dacl, 0);
            if (error)
            {
                LocalFree(securityDescriptor);
                CloseHandle(hProcess);
                printf("ERROR: Can't override client's DACL, ");
                printf("ErrorCode: %u\n", error);
                return NULL;
            }

            // release resources
            LocalFree(securityDescriptor);
            CloseHandle(hProcess);

            // now this should work
            hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processID);
        }
        // error!
        if (!hProcess)
        {
            printf("ERROR: Process open is failed, ");
            printf("ErrorCode: %u\n", GetLastError());
            return NULL;
        }
    }
    return hProcess;
}
Ejemplo n.º 22
0
// "in" means "to pageant", "out" means "from pageant". Sorry.
int
send_request_to_pageant(byte *inbuf, int inbytes, byte *outbuf, int outbuflen)
{
    EPRINTF(3, "Sending %d bytes to pageant.\n", inbytes);

    if (inbytes < 4) {
        EPRINTF(0, "Pageant-bound message too short (%d bytes).\n", inbytes);
        return 0;
    }
    int claimed_inbytes = GET_32BIT(inbuf);
    if (inbytes != claimed_inbytes + 4) {
        EPRINTF(0, "Pageant-bound message is %d bytes long, but it "
                "*says* it has %d=%d+4 bytes in it.\n",
                inbytes, claimed_inbytes+4, claimed_inbytes);
        return 0;
    }

    EPRINTF(5, "Message to pageant (%d bytes):\n", inbytes);
    print_buf(5, inbuf, inbytes);

    HWND hwnd;
    hwnd = FindWindow("Pageant", "Pageant");
    if (!hwnd) {
        EPRINTF(0, "Can't FindWindow(\"Pageant\"...) - "
                   "is pageant running?. (GetLastError is %x)\n",
                   (unsigned) GetLastError());
        return 0;
    }

    char mapname[512];
    sprintf(mapname, "PageantRequest%08x", (unsigned)GetCurrentThreadId());

    PSECURITY_ATTRIBUTES psa = NULL;
#ifndef NO_SECURITY
    SECURITY_ATTRIBUTES sa = {0};
    if (advapi_initialised || init_advapi()) {
        /*
         * Set the security info for the file mapping to the same as Pageant's
         * process, to make sure Pageant's SID check will pass.
         */

        DWORD dwProcId = 0;
        GetWindowThreadProcessId(hwnd, &dwProcId);
        HANDLE proc = OpenProcess(MAXIMUM_ALLOWED, FALSE, dwProcId);
        if (proc != NULL) {
			sa.nLength = sizeof(sa);
			sa.bInheritHandle = TRUE;
			sa.lpSecurityDescriptor = NULL;
			GetSecurityInfo(proc, SE_KERNEL_OBJECT, OWNER_SECURITY_INFORMATION,
					NULL, NULL, NULL, NULL, (PSECURITY_DESCRIPTOR*)&sa.lpSecurityDescriptor);
			if (sa.lpSecurityDescriptor) {
				psa = &sa;
			}
        }
		CloseHandle(proc);
    } else {
        EPRINTF(0, "Couldn't initialize advapi.\n");
    }
#endif /* NO_SECURITY */

    HANDLE filemap = CreateFileMapping(INVALID_HANDLE_VALUE, psa, 
                                       PAGE_READWRITE, 0, 
                                       AGENT_MAX_MSGLEN, mapname);
    if (filemap == NULL || filemap == INVALID_HANDLE_VALUE) {
        EPRINTF(0, "Can't CreateFileMapping.\n");
        return 0;
    }

    byte *shmem = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, 0);
    memcpy(shmem, inbuf, inbytes);
    COPYDATASTRUCT cds;
    cds.dwData = AGENT_COPYDATA_ID;
    cds.cbData = 1 + strlen(mapname);
    cds.lpData = mapname;

    int id = SendMessage(hwnd, WM_COPYDATA, (WPARAM) NULL, (LPARAM) &cds);
    int retlen = 0;
    if (id > 0) {
        retlen = 4 + GET_32BIT(shmem);
        if (retlen > outbuflen) {
            EPRINTF(0, "Buffer too small to contain reply from pageant.\n");
            return 0;
        }

        memcpy(outbuf, shmem, retlen);

        EPRINTF(5, "Reply from pageant (%d bytes):\n", retlen);
        print_buf(5, outbuf, retlen);
    } else {
        EPRINTF(0, "Couldn't SendMessage().\n");
        return 0;
    }

    // enum_windows();


    UnmapViewOfFile(shmem);
    CloseHandle(filemap);
#ifndef NO_SECURITY
    if (sa.lpSecurityDescriptor)
        LocalFree(sa.lpSecurityDescriptor);
#endif

    EPRINTF(3, "Got %d bytes back from pageant.\n", retlen);

    return retlen;
}