VOID * QueueHashLookup(Queue *pQueue, PSID Sid, BOOL EnterCritSec) {
    VOID * pValue;
    QueueNode *pNextNode;

    ASSERT(pQueue != NULL);

    if (pQueue->lpCriticalSection != NULL && EnterCritSec) EnterCriticalSection(pQueue->lpCriticalSection);

#ifdef DEBUG2
    DbgMsgRecord(TEXT("-> QueueHashLookup\n"));
#endif

    pValue = NULL;

    for (QueueNode *pNode = pQueue->pFirst; pNode != NULL; pNode = pNextNode) {
        pNextNode = pNode->pNext;
        if (EqualSid(((QueueHashNode *)(pNode->pData))->pKey, Sid) == TRUE) {
            pValue = ((QueueHashNode *)(pNode->pData))->pValue;
            break;
        }
    }

#ifdef DEBUG2
    DbgMsgRecord(TEXT("<- QueueHashLookup\n"));
#endif

    if (pQueue->lpCriticalSection != NULL && EnterCritSec) LeaveCriticalSection(pQueue->lpCriticalSection);

    return pValue;
}
Example #2
0
int
is_root( void ) 
{
	int root = 0;
#if 1
    PSID psid = my_user_Sid();
	if( ! psid ) {
		dprintf( D_ALWAYS, 
				 "ERROR in is_root(): my_user_Sid() returned NULL\n" );
		return 0;
	}
    root = EqualSid(psid, const_cast<SID*>(&sids.LocalSystem));
    free (psid);
#else
	char* user = my_username( 0 );
	if( ! user ) {
		dprintf( D_ALWAYS, 
				 "ERROR in is_root(): my_username() returned NULL\n" );
		return 0;
	}
	if( !strcasecmp(user, "SYSTEM") ) {
		root = 1;
	}
	free( user );
#endif
	return root;
}
Example #3
0
/***********************************************************************
 *              IsNTAdmin	(ADVPACK.@)
 *
 * Checks if the user has admin privileges.
 *
 * PARAMS
 *   reserved  [I] Reserved.  Must be 0.
 *   pReserved [I] Reserved.  Must be NULL.
 *
 * RETURNS
 *   TRUE if user has admin rights, FALSE otherwise.
 */
BOOL WINAPI IsNTAdmin(DWORD reserved, LPDWORD pReserved)
{
    SID_IDENTIFIER_AUTHORITY SidAuthority = {SECURITY_NT_AUTHORITY};
    PTOKEN_GROUPS pTokenGroups;
    BOOL bSidFound = FALSE;
    DWORD dwSize, i;
    HANDLE hToken;
    PSID pSid;

    TRACE("(%d, %p)\n", reserved, pReserved);

    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
        return FALSE;

    if (!GetTokenInformation(hToken, TokenGroups, NULL, 0, &dwSize))
    {
        if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
        {
            CloseHandle(hToken);
            return FALSE;
        }
    }

    pTokenGroups = HeapAlloc(GetProcessHeap(), 0, dwSize);
    if (!pTokenGroups)
    {
        CloseHandle(hToken);
        return FALSE;
    }

    if (!GetTokenInformation(hToken, TokenGroups, pTokenGroups, dwSize, &dwSize))
    {
        HeapFree(GetProcessHeap(), 0, pTokenGroups);
        CloseHandle(hToken);
        return FALSE;
    }

    CloseHandle(hToken);

    if (!AllocateAndInitializeSid(&SidAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID,
                                  DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &pSid))
    {
        HeapFree(GetProcessHeap(), 0, pTokenGroups);
        return FALSE;
    }

    for (i = 0; i < pTokenGroups->GroupCount; i++)
    {
        if (EqualSid(pSid, pTokenGroups->Groups[i].Sid))
        {
            bSidFound = TRUE;
            break;
        }
    }

    HeapFree(GetProcessHeap(), 0, pTokenGroups);
    FreeSid(pSid);

    return bSidFound;
}
Example #4
0
static int
iwin32_uid_compare (user_id_t a, user_id_t b)
{
  assert (a.value != NULL);
  assert (b.value != NULL);

  return EqualSid (a.value, b.value);
}
Example #5
0
static int
iwin32_gid_compare (group_id_t a, group_id_t b)
{
  assert (a.value != NULL);
  assert (b.value != NULL);

  return EqualSid (a.value, b.value);
}
Example #6
0
JBoolean
JUserIsAdmin()
{
	HANDLE tokenHandle;
	if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &tokenHandle))
		{
		return kJFalse;
		}

	DWORD returnLength;
	GetTokenInformation(tokenHandle, TokenGroups, NULL, 0, &returnLength);
	if (returnLength > 65535)
		{
		CloseHandle(tokenHandle);
		return kJFalse;
		}

	TOKEN_GROUPS* groupList = (TOKEN_GROUPS*) malloc(returnLength);
	if (groupList == NULL)
		{
		CloseHandle(tokenHandle);
		return kJFalse;
		}

	if (!GetTokenInformation(tokenHandle, TokenGroups,
							 groupList, returnLength, &returnLength))
		{
		CloseHandle(tokenHandle);
		free(groupList);
		return kJFalse;
		}
	CloseHandle(tokenHandle);

	SID_IDENTIFIER_AUTHORITY siaNtAuth = SECURITY_NT_AUTHORITY;
	PSID adminSid;
	if (!AllocateAndInitializeSid(&siaNtAuth, 2, SECURITY_BUILTIN_DOMAIN_RID,
								  DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0,
								  &adminSid))
		{
		free(groupList);
		return kJFalse;
		}

	JBoolean found = kJFalse;
	for (DWORD i = 0; i < groupList->GroupCount; i++)
		{
		if (EqualSid(adminSid, groupList->Groups[i].Sid))
			{
			found = kJTrue;
			break;
			}
		}

	FreeSid(adminSid);
	free(groupList);

	return found;
}
Example #7
0
BOOL uac::Am_I_In_Admin_Group(BOOL bCheckAdminMode /*= FALSE*/)
{
	BOOL   fAdmin;
	HANDLE  hThread;
	TOKEN_GROUPS *ptg = NULL;
	DWORD  cbTokenGroups;
	DWORD  dwGroup;
	PSID   psidAdmin;
	SID_IDENTIFIER_AUTHORITY SystemSidAuthority = SECURITY_NT_AUTHORITY;
	if (!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, FALSE, &hThread))
	{
		if (GetLastError() == ERROR_NO_TOKEN)
		{
			if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY,
				&hThread))
				return (FALSE);
		}
		else
			return (FALSE);
	}
	if (GetTokenInformation(hThread, TokenGroups, NULL, 0, &cbTokenGroups))
		return (FALSE);
	if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
		return (FALSE);
	if (!(ptg = (TOKEN_GROUPS*)_alloca(cbTokenGroups)))
		return (FALSE);
	if (!GetTokenInformation(hThread, TokenGroups, ptg, cbTokenGroups,
		&cbTokenGroups))
		return (FALSE);
	if (!AllocateAndInitializeSid(&SystemSidAuthority, 2,
		SECURITY_BUILTIN_DOMAIN_RID,
		DOMAIN_ALIAS_RID_ADMINS,
		0, 0, 0, 0, 0, 0, &psidAdmin))
		return (FALSE);
	fAdmin = FALSE;
	for (dwGroup = 0; dwGroup < ptg->GroupCount; dwGroup++)
	{
		if (EqualSid(ptg->Groups[dwGroup].Sid, psidAdmin))
		{
			if (bCheckAdminMode)
			{
				if ((ptg->Groups[dwGroup].Attributes) & SE_GROUP_ENABLED)
				{
					fAdmin = TRUE;
				}
			}
			else
			{
				fAdmin = TRUE;
			}
			break;
		}
	}
	FreeSid(psidAdmin);
	return (fAdmin);
}
Example #8
0
/*-----------------------------------------------------------------------------
	Kill any Dr. Watson windows that are open (we already killed the browser process)
-----------------------------------------------------------------------------*/
void CurlBlastDlg::KillProcs(void)
{
#ifndef _DEBUG

    WTS_PROCESS_INFO * proc = NULL;
    DWORD count = 0;
    if( WTSEnumerateProcesses(WTS_CURRENT_SERVER_HANDLE, 0, 1, &proc, &count) )
    {
        for( DWORD i = 0; i < count; i++ )
        {
            bool terminate = false;

            // check for Dr. Watson
            if( !lstrcmpi(PathFindFileName(proc[i].pProcessName), _T("dwwin.exe")) )
            {
                if( !bDrWatson )
                {
                    log.LogEvent(event_KilledDrWatson);
                    bDrWatson = true;
                }
                terminate = true;
            }
            else if(lstrcmpi(PathFindFileName(proc[i].pProcessName), _T("iexplore.exe")))
            {
                if (worker) {
                    EnterCriticalSection( &(worker->cs) );
                    // make sure it's not the browser we launched
                    if( proc[i].ProcessId != worker->browserPID
                            && worker->userSID && proc[i].pUserSid
                            && IsValidSid(worker->userSID) && IsValidSid(proc[i].pUserSid) )
                    {
                        // see if the SID matches
                        if( EqualSid(proc[i].pUserSid, worker->userSID ) )
                            terminate = true;
                    }
                    LeaveCriticalSection( &(worker->cs) );
                }
            }

            if( terminate )
            {
                HANDLE hProc = OpenProcess(PROCESS_TERMINATE, FALSE, proc[i].ProcessId);
                if( hProc )
                {
                    TerminateProcess(hProc, 0);
                    CloseHandle(hProc);
                }
            }
        }

        WTSFreeMemory(proc);
    }
#endif
}
Example #9
0
APR_DECLARE(apr_status_t) apr_uid_compare(apr_uid_t left, apr_uid_t right)
{
    if (!left || !right)
        return APR_EINVAL;
#ifndef _WIN32_WCE
    if (!IsValidSid(left) || !IsValidSid(right))
        return APR_EINVAL;
    if (!EqualSid(left, right))
        return APR_EMISMATCH;
#endif
    return APR_SUCCESS;
}
Example #10
0
BOOL IsLocalSid( PSID ps )
{
	static PSID pComparisonSid = NULL;

	if ( pComparisonSid == NULL )
	{
		// build "BUILTIN\LOCAL" SID for comparison: S-1-2-0
		SID_IDENTIFIER_AUTHORITY sia = SECURITY_LOCAL_SID_AUTHORITY;
		AllocateAndInitializeSid( &sia, 1, 0, 0, 0, 0, 0, 0, 0, 0, &pComparisonSid );
	}

	return EqualSid( ps, pComparisonSid );
}
Example #11
0
const wchar_t* GetNameFromSIDCache(PSID Sid)
{
	LPCWSTR Result=nullptr;
	for(SIDCacheItem** i=SIDCache.First();i;i=SIDCache.Next(i))
	{
		if (EqualSid((*i)->Sid,Sid))
		{
			Result=(*i)->strUserName;
			break;
		}
	}
	return Result;
}
Example #12
0
BOOL IsInteractiveSid( PSID ps )
{
	static PSID pComparisonSid = NULL;

	if ( pComparisonSid == NULL )
	{
		// build "BUILTIN\LOCAL" SID for comparison: S-1-5-4
		SID_IDENTIFIER_AUTHORITY sia = SECURITY_NT_AUTHORITY; // "-5-"
		AllocateAndInitializeSid( &sia, 1, 4, 0, 0, 0, 0, 0, 0, 0, &pComparisonSid );
	}

	return EqualSid( ps, pComparisonSid );
}
QString DiagnosticsDialog::getUserRights() const
{
	SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
	PSID AdministratorsGroup = NULL;
	HANDLE hToken = NULL;
	DWORD dwIndex, dwLength = 0;
	PTOKEN_GROUPS pGroup = NULL;
	QString rights = tr( "User" );

	if ( !OpenThreadToken( GetCurrentThread(), TOKEN_QUERY, TRUE, &hToken ) )
	{
		if ( GetLastError() != ERROR_NO_TOKEN )
			return tr( "Unknown - error %1" ).arg( GetLastError() );
		if ( !OpenProcessToken( GetCurrentProcess(), TOKEN_QUERY, &hToken ) )
			return tr( "Unknown - error %1" ).arg( GetLastError() );
	}
	if ( !GetTokenInformation( hToken, TokenGroups, NULL, dwLength, &dwLength ) )
	{
		if( GetLastError() != ERROR_INSUFFICIENT_BUFFER )
			return tr( "Unknown - error %1" ).arg( GetLastError() );
	}
	pGroup = (PTOKEN_GROUPS)GlobalAlloc( GPTR, dwLength );

	if ( !GetTokenInformation( hToken, TokenGroups, pGroup, dwLength, &dwLength ) )
	{
		if ( pGroup )
			GlobalFree( pGroup );
		return tr( "Unknown - error %1" ).arg( GetLastError() );;
	}

	if( AllocateAndInitializeSid( &NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS,
									0, 0, 0, 0, 0, 0, &AdministratorsGroup ) )
	{
		for ( dwIndex = 0; dwIndex < pGroup->GroupCount; dwIndex++ )
		{
			if ( EqualSid( AdministratorsGroup, pGroup->Groups[dwIndex].Sid ) )
			{
				rights = tr( "Administrator" );
				break;
			}
		}
	}

	if ( AdministratorsGroup )
		FreeSid( AdministratorsGroup );
	if ( pGroup )
		GlobalFree( pGroup );
	
	return rights;
}
Example #14
0
VOID
WINAPI
CachedGetUserFromSid(
    PSID pSid,
    LPWSTR pUserName,
    PULONG pcwcUserName)
{
    PLIST_ENTRY pCur;
    PSIDTOUSERNAME pEntry;
    ULONG cbSid, cwcUserName;

    cwcUserName = *pcwcUserName;

    /* Walk through the list */
    for(pCur = SidToUserNameHead.Flink;
        pCur != &SidToUserNameHead;
        pCur = pCur->Flink)
    {
        pEntry = CONTAINING_RECORD(pCur, SIDTOUSERNAME, List);
        if (EqualSid((PSID)&pEntry->Data, pSid))
        {
            wcsncpy(pUserName, pEntry->pszName, cwcUserName);
            *pcwcUserName = cwcUserName;
            return;
        }
    }

    /* We didn't find the SID in the list, get the name conventional */
    SidToUserName(pSid, pUserName, cwcUserName);

    /* Allocate a new entry */
    *pcwcUserName = wcslen(pUserName);
    cwcUserName = *pcwcUserName + 1;
    cbSid = GetLengthSid(pSid);
    pEntry = HeapAlloc(GetProcessHeap(), 0, sizeof(SIDTOUSERNAME) + cbSid + cwcUserName * sizeof(WCHAR));

    /* Copy the Sid and name to our entry */
    CopySid(cbSid, (PSID)&pEntry->Data, pSid);
    pEntry->pszName = (LPWSTR)(pEntry->Data + cbSid);
    wcsncpy(pEntry->pszName, pUserName, cwcUserName);

    /* Insert the new entry */
    pEntry->List.Flink = &SidToUserNameHead;
    pEntry->List.Blink = SidToUserNameHead.Blink;
    SidToUserNameHead.Blink->Flink = &pEntry->List;
    SidToUserNameHead.Blink = &pEntry->List;

    return;
}
Example #15
0
/*
 * Returns JNI_TRUE if the specified owner is the only SID will access
 * to the file.
 */
static jboolean isAccessUserOnly(JNIEnv* env, SID* owner, ACL* acl) {
    ACL_SIZE_INFORMATION acl_size_info;
    DWORD i;

    /*
     * If there's no DACL then there's no access to the file
     */
    if (acl == NULL) {
        return JNI_TRUE;
    }

    /*
     * Get the ACE count
     */
    if (!GetAclInformation(acl, (void *) &acl_size_info, sizeof(acl_size_info),
                           AclSizeInformation)) {
        JNU_ThrowIOExceptionWithLastError(env, "GetAclInformation failed");
        return JNI_FALSE;
    }

    /*
     * Iterate over the ACEs. For each "allow" type check that the SID
     * matches the owner, and check that the access is read only.
     */
    for (i = 0; i < acl_size_info.AceCount; i++) {
        void* ace;
        ACCESS_ALLOWED_ACE *access;
        SID* sid;

        if (!GetAce(acl, i, &ace)) {
            JNU_ThrowIOExceptionWithLastError(env, "GetAce failed");
            return -1;
        }
        if (((ACCESS_ALLOWED_ACE *)ace)->Header.AceType != ACCESS_ALLOWED_ACE_TYPE) {
            continue;
        }
        access = (ACCESS_ALLOWED_ACE *)ace;
        sid = (SID *) &access->SidStart;
        if (!EqualSid(owner, sid)) {
            /*
             * If the ACE allows any access then the file is not secure.
             */
            if (access->Mask & ANY_ACCESS) {
                return JNI_FALSE;
            }
        }
    }
    return JNI_TRUE;
}
Example #16
0
BOOL IsCurrentUserAdmin()  
{    
	HANDLE hAccessToken;    
	BYTE * InfoBuffer = new BYTE[1024];    
	PTOKEN_GROUPS ptgGroups;    
	DWORD dwInfoBufferSize;    
	PSID psidAdministrators;    
	SID_IDENTIFIER_AUTHORITY siaNtAuthority = SECURITY_NT_AUTHORITY;    

	if(!OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY,&hAccessToken))    
	{    
		delete InfoBuffer;    
		return FALSE;    
	}    

	if(!GetTokenInformation(hAccessToken,TokenGroups,InfoBuffer,1024,&dwInfoBufferSize))    
	{    
		delete InfoBuffer;    
		CloseHandle(hAccessToken);    
		return FALSE;    
	}    

	CloseHandle(hAccessToken);    

	if(!AllocateAndInitializeSid(&siaNtAuthority,    
		2,    
		SECURITY_BUILTIN_DOMAIN_RID,    
		DOMAIN_ALIAS_RID_ADMINS,    
		0,0,0,0,0,0,    
		&psidAdministrators))    
	{    
		delete InfoBuffer;    
		return FALSE;    
	}    

	ptgGroups = (PTOKEN_GROUPS)InfoBuffer;    

	for(UINT i = 0; i < ptgGroups->GroupCount; i++)    
	{    
		if(EqualSid(psidAdministrators,ptgGroups->Groups[i].Sid))    
		{    
			FreeSid(psidAdministrators);    
			delete InfoBuffer;    
			return TRUE;    
		}    
	}    
	return FALSE;    
}  
Example #17
0
BOOL PLUGIN_FILTER_FILTERACE(
    _In_ PLUGIN_API_TABLE const * const api,
    _Inout_ PIMPORTED_ACE ace
) {
    PSID trusteeSidAce = api->Ace.GetTrustee(ace);

    if (gs_TrusteeFilter == NULL && gs_TrusteeDnFilter != NULL) {
        PIMPORTED_OBJECT object = api->Resolver.GetObjectByDn(gs_TrusteeDnFilter);
        if (!object) {
            API_FATAL(_T("Cannot resolve DN <%s>"), gs_TrusteeDnFilter);
        }
        gs_TrusteeFilter = &object->imported.sid;
    }

    return EqualSid(trusteeSidAce, gs_TrusteeFilter);
}
Example #18
0
static BOOL is_token_admin(HANDLE token)
{
    PSID administrators = NULL;
    SID_IDENTIFIER_AUTHORITY nt_authority = { SECURITY_NT_AUTHORITY };
    DWORD groups_size;
    PTOKEN_GROUPS groups;
    DWORD group_index;

    /* Create a well-known SID for the Administrators group. */
    if (! AllocateAndInitializeSid(&nt_authority, 2, SECURITY_BUILTIN_DOMAIN_RID,
                                   DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0,
                                   &administrators))
        return FALSE;

    /* Get the group info from the token */
    groups_size = 0;
    GetTokenInformation(token, TokenGroups, NULL, 0, &groups_size);
    groups = HeapAlloc(GetProcessHeap(), 0, groups_size);
    if (groups == NULL)
    {
        FreeSid(administrators);
        return FALSE;
    }
    if (! GetTokenInformation(token, TokenGroups, groups, groups_size, &groups_size))
    {
        HeapFree(GetProcessHeap(), 0, groups);
        FreeSid(administrators);
        return FALSE;
    }

    /* Now check if the token groups include the Administrators group */
    for (group_index = 0; group_index < groups->GroupCount; group_index++)
    {
        if (EqualSid(groups->Groups[group_index].Sid, administrators))
        {
            HeapFree(GetProcessHeap(), 0, groups);
            FreeSid(administrators);
            return TRUE;
        }
    }

    /* If we end up here we didn't find the Administrators group */
    HeapFree(GetProcessHeap(), 0, groups);
    FreeSid(administrators);
    return FALSE;
}
// checks user SID in both tokens for equality
bool SecurityHelper::IsSameUser(HANDLE hToken1, HANDLE hToken2, bool* pbIsSameUser)
{
    *pbIsSameUser = false;
    bool result = false;

    const DWORD bufSize = sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE;
    char buf1[bufSize];
    char buf2[bufSize];

    DWORD cb;
    if (GetTokenInformation(hToken1, TokenUser, buf1, bufSize, &cb) &&
        GetTokenInformation(hToken2, TokenUser, buf2, bufSize, &cb))
	{
        *pbIsSameUser = EqualSid(((TOKEN_USER*)buf1)->User.Sid, ((TOKEN_USER*)buf2)->User.Sid) ? true : false;
        result = true;
    }
    else LCF1(L"GetTokenInformation failed: %d", GetLastError());

    return result;
}
static void get_sid_cache(PSID sid,bool full,wchar_t **username)
{
  *username=NULL;
  CacheRecord *tmp_rec=sid_cache;
  while(tmp_rec)
  {
    if(EqualSid(tmp_rec->sid,sid))
    {
      if(full)
      {
        *username=tmp_rec->username;
      }
      else
      {
        *username=tmp_rec->username_only;
      }
      break;
    }
    tmp_rec=tmp_rec->next;
  }
}
Example #21
0
static BOOL
RunningAsSYSTEM(VOID)
{
    /* S-1-5-18 -- Local System */
    static SID SystemSid = { SID_REVISION, 1, { SECURITY_NT_AUTHORITY }, { SECURITY_LOCAL_SYSTEM_RID } };

    BOOL bRet = FALSE;
    PTOKEN_USER pTokenUser;
    HANDLE hToken;
    DWORD cbTokenBuffer = 0;

    /* Get the process token */
    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
        return FALSE;

    /* Retrieve token's information */
    if (!GetTokenInformation(hToken, TokenUser, NULL, 0, &cbTokenBuffer) &&
        GetLastError() != ERROR_INSUFFICIENT_BUFFER)
    {
        goto Quit;
    }

    pTokenUser = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbTokenBuffer);
    if (!pTokenUser)
        goto Quit;

    if (GetTokenInformation(hToken, TokenUser, pTokenUser, cbTokenBuffer, &cbTokenBuffer))
    {
        /* Compare with SYSTEM SID */
        bRet = EqualSid(pTokenUser->User.Sid, &SystemSid);
    }

    HeapFree(GetProcessHeap(), 0, pTokenUser);

Quit:
    CloseHandle(hToken);
    return bRet;
}
Example #22
0
void ProcessList::init()
{
    HANDLE h;
    PROCESSENTRY32 pe32;

    h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (h == INVALID_HANDLE_VALUE) {
        return;
    }
    pe32.dwSize = sizeof(PROCESSENTRY32);
    if (!Process32First(h, &pe32)) {
        return;
    }

    do {
        HANDLE hProcess = getProcessHandle(pe32.th32ProcessID);
        if (!hProcess) {
            continue;
        }
        QString name = getProcessName(pe32.th32ProcessID);
#ifndef _WIN32_WCE
        PSID sid = getProcessOwner(hProcess);
        if (!sid || m_userId && !EqualSid(m_userId, sid)) {
            freeSid(sid);
            continue;
        }
#else
        PSID sid = 0;
#endif
        m_processes << new ProcessListEntry(hProcess, name, pe32.th32ProcessID, sid);
    } while (Process32Next(h, &pe32));
#ifndef _WIN32_WCE
    CloseHandle(h);
#else
    CloseToolhelp32Snapshot(h);
#endif
}
Example #23
0
/*
 * Returns nonzero if the current user has administrative privileges,
 * or zero if not.
 *
 * Note: this cannot use ereport() because it's called too early during
 * startup.
 */
int
pgwin32_is_admin(void)
{
	HANDLE		AccessToken;
	char	   *InfoBuffer = NULL;
	char		errbuf[256];
	PTOKEN_GROUPS Groups;
	PSID		AdministratorsSid;
	PSID		PowerUsersSid;
	SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY};
	UINT		x;
	BOOL		success;

	if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &AccessToken))
	{
		write_stderr("could not open process token: error code %d\n",
					 (int) GetLastError());
		exit(1);
	}

	if (!pgwin32_get_dynamic_tokeninfo(AccessToken, TokenGroups,
									   &InfoBuffer, errbuf, sizeof(errbuf)))
	{
		write_stderr(errbuf);
		exit(1);
	}

	Groups = (PTOKEN_GROUPS) InfoBuffer;

	CloseHandle(AccessToken);

	if (!AllocateAndInitializeSid(&NtAuthority, 2,
		 SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0,
								  0, &AdministratorsSid))
	{
		write_stderr("could not get SID for Administrators group: error code %d\n",
					 (int) GetLastError());
		exit(1);
	}

	if (!AllocateAndInitializeSid(&NtAuthority, 2,
	SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0,
								  0, &PowerUsersSid))
	{
		write_stderr("could not get SID for PowerUsers group: error code %d\n",
					 (int) GetLastError());
		exit(1);
	}

	success = FALSE;

	for (x = 0; x < Groups->GroupCount; x++)
	{
		if ((EqualSid(AdministratorsSid, Groups->Groups[x].Sid) && (Groups->Groups[x].Attributes & SE_GROUP_ENABLED)) ||
			(EqualSid(PowerUsersSid, Groups->Groups[x].Sid) && (Groups->Groups[x].Attributes & SE_GROUP_ENABLED)))
		{
			success = TRUE;
			break;
		}
	}

	free(InfoBuffer);
	FreeSid(AdministratorsSid);
	FreeSid(PowerUsersSid);
	return success;
}
Example #24
0
/*
 * We consider ourselves running as a service if one of the following is
 * true:
 *
 * 1) We are running as Local System (only used by services)
 * 2) Our token contains SECURITY_SERVICE_RID (automatically added to the
 *	  process token by the SCM when starting a service)
 *
 * Return values:
 *	 0 = Not service
 *	 1 = Service
 *	-1 = Error
 *
 * Note: we can't report errors via either ereport (we're called too early)
 * or write_stderr (because that calls this).  We are therefore reduced to
 * writing directly on stderr, which sucks, but we have few alternatives.
 */
int
pgwin32_is_service(void)
{
	static int	_is_service = -1;
	HANDLE		AccessToken;
	char	   *InfoBuffer = NULL;
	char		errbuf[256];
	PTOKEN_GROUPS Groups;
	PTOKEN_USER User;
	PSID		ServiceSid;
	PSID		LocalSystemSid;
	SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY};
	UINT		x;

	/* Only check the first time */
	if (_is_service != -1)
		return _is_service;

	if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &AccessToken))
	{
		fprintf(stderr, "could not open process token: error code %d\n",
				(int) GetLastError());
		return -1;
	}

	/* First check for local system */
	if (!pgwin32_get_dynamic_tokeninfo(AccessToken, TokenUser, &InfoBuffer,
									   errbuf, sizeof(errbuf)))
	{
		fprintf(stderr, errbuf);
		return -1;
	}

	User = (PTOKEN_USER) InfoBuffer;

	if (!AllocateAndInitializeSid(&NtAuthority, 1,
							  SECURITY_LOCAL_SYSTEM_RID, 0, 0, 0, 0, 0, 0, 0,
								  &LocalSystemSid))
	{
		fprintf(stderr, "could not get SID for local system account\n");
		CloseHandle(AccessToken);
		return -1;
	}

	if (EqualSid(LocalSystemSid, User->User.Sid))
	{
		FreeSid(LocalSystemSid);
		free(InfoBuffer);
		CloseHandle(AccessToken);
		_is_service = 1;
		return _is_service;
	}

	FreeSid(LocalSystemSid);
	free(InfoBuffer);

	/* Now check for group SID */
	if (!pgwin32_get_dynamic_tokeninfo(AccessToken, TokenGroups, &InfoBuffer,
									   errbuf, sizeof(errbuf)))
	{
		fprintf(stderr, errbuf);
		return -1;
	}

	Groups = (PTOKEN_GROUPS) InfoBuffer;

	if (!AllocateAndInitializeSid(&NtAuthority, 1,
								  SECURITY_SERVICE_RID, 0, 0, 0, 0, 0, 0, 0,
								  &ServiceSid))
	{
		fprintf(stderr, "could not get SID for service group\n");
		free(InfoBuffer);
		CloseHandle(AccessToken);
		return -1;
	}

	_is_service = 0;
	for (x = 0; x < Groups->GroupCount; x++)
	{
		if (EqualSid(ServiceSid, Groups->Groups[x].Sid))
		{
			_is_service = 1;
			break;
		}
	}

	free(InfoBuffer);
	FreeSid(ServiceSid);

	CloseHandle(AccessToken);

	return _is_service;
}
BOOL RemoveAceFromDesktop(HDESK hdesk, PSID psid)
{
    // Obtain the security descriptor for the desktop object.
    SECURITY_INFORMATION si = DACL_SECURITY_INFORMATION;
    DWORD sd_size = 0;
    if (!GetUserObjectSecurity(hdesk, &si, NULL, 0, &sd_size)) {
         if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
            printf("GetUserObjectSecurity() failed: %d\n", GetLastError());
            return FALSE;
         }
    }
    auto_buffer<PSECURITY_DESCRIPTOR> psd(sd_size);
    if (!GetUserObjectSecurity(hdesk, &si, psd.get(), sd_size, &sd_size)) {
        printf("GetUserObjectSecurity() failed: %d\n", GetLastError());
        return FALSE;
    }

    // Create a new security descriptor.
    auto_buffer<PSECURITY_DESCRIPTOR> psd_new(sd_size);
    if (!InitializeSecurityDescriptor(psd_new.get(), SECURITY_DESCRIPTOR_REVISION)) {
        printf("InitializeSecurityDescriptor() failed: %d\n", GetLastError());
        return FALSE;
    }

    // Obtain the DACL from the security descriptor.
    BOOL bDaclPresent;
    PACL pacl;
    BOOL bDaclExist;
    if (!GetSecurityDescriptorDacl(psd.get(), &bDaclPresent, &pacl, &bDaclExist)) {
        printf("GetSecurityDescriptorDacl() failed: %d\n", GetLastError());
        return FALSE;
    }

    // Initialize.
    ACL_SIZE_INFORMATION aclSizeInfo = {};
    aclSizeInfo.AclBytesInUse = sizeof(ACL);
    if (pacl != NULL) {
        // Determine the size of the ACL information.
        if (!GetAclInformation(pacl, (LPVOID)&aclSizeInfo, sizeof aclSizeInfo, AclSizeInformation)) {
            printf("GetAclInformation() failed: %d\n", GetLastError());
            return FALSE;
        }
    }

    // Allocate buffer for the new ACL.
    DWORD dwNewAclSize = aclSizeInfo.AclBytesInUse -
                         (sizeof(ACCESS_ALLOWED_ACE) +
                          GetLengthSid(psid) - sizeof(DWORD));
    auto_buffer<PACL> new_acl(dwNewAclSize);

    // Initialize the new ACL.
    if (!InitializeAcl(new_acl.get(), dwNewAclSize, ACL_REVISION)) {
        printf("InitializeAcl() failed: %d\n", GetLastError());
        return FALSE;
    }

    // If DACL is present, copy it to a new DACL.
    if (bDaclPresent) {
        // Copy the ACEs to the new ACL.
        for (DWORD i = 0; i != aclSizeInfo.AceCount; ++i) {
            // Get an ACE.
            ACCESS_ALLOWED_ACE* pace;
            if (!GetAce(pacl, i, (void**)&pace)) {
                printf("GetAce() failed: %d\n", GetLastError());
                return FALSE;
            }
            if (!EqualSid(psid, &pace->SidStart)) {
                // Add the ACE to the new ACL.
                if (!AddAce(new_acl.get(), ACL_REVISION,MAXDWORD, pace,
                            pace->Header.AceSize)) {
                    printf("AddAce() failed: %d\n", GetLastError());
                    return FALSE;
                }
            }
        }
    }

    // Set new DACL to the new security descriptor.
    if (!SetSecurityDescriptorDacl(psd_new.get(), TRUE, new_acl.get(), FALSE)) {
        printf("SetSecurityDescriptorDacl() failed: %d\n", GetLastError());
        return FALSE;
    }

    // Set the new security descriptor for the desktop object.
    if (!SetUserObjectSecurity(hdesk, &si, psd_new.get())) {
        printf("SetUserObjectSecurity() failed: %d\n", GetLastError());
        return FALSE;
    }
    
    return TRUE;
}
BOOL RemoveAceFromWindowStation(HWINSTA hwinsta, PSID psid)
{
    // Obtain the DACL for the window station.
    SECURITY_INFORMATION si = DACL_SECURITY_INFORMATION;
    DWORD sd_length = 0;
    if (!GetUserObjectSecurity(hwinsta, &si, NULL, 0, &sd_length)) {
        if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
            printf("GetUserObjectSecurity() failed: %d\n", GetLastError());
            return FALSE;
        }
    }
    auto_buffer<PSECURITY_DESCRIPTOR> psd(sd_length);
    if (!GetUserObjectSecurity(hwinsta, &si, psd.get(), sd_length, &sd_length)) {
        printf("GetUserObjectSecurity() failed: %d\n", GetLastError());
        return FALSE;
    }

    // Create a new DACL.
    auto_buffer<PSECURITY_DESCRIPTOR> psd_new(sd_length);
    if (!InitializeSecurityDescriptor(psd_new.get(), SECURITY_DESCRIPTOR_REVISION)) {
        printf("InitializeSecurityDescriptor() failed: %d\n", GetLastError());
        return FALSE;
    }

    // Get the DACL from the security descriptor.
    BOOL bDaclPresent;
    PACL pacl;
    BOOL bDaclExist;
    if (!GetSecurityDescriptorDacl(psd.get(), &bDaclPresent, &pacl, &bDaclExist)) {
        printf("GetSecurityDescriptorDacl() failed: %d\n", GetLastError());
        return FALSE;
    }
    
    // Initialize the ACL.
    ACL_SIZE_INFORMATION aclSizeInfo = {};
    aclSizeInfo.AclBytesInUse = sizeof(ACL);
    if (NULL != pacl) {
        // get the file ACL size info
        if (!GetAclInformation(pacl, &aclSizeInfo, sizeof aclSizeInfo, AclSizeInformation)) {
            printf("GetAclInformation() failed: %d\n", GetLastError());
            return FALSE;
        }
    }

    // Compute the size of the new ACL.
    DWORD new_acl_size = aclSizeInfo.AclBytesInUse -
                         ((2 * sizeof(ACCESS_ALLOWED_ACE)) + 
                          (2 * GetLengthSid(psid)) - (2 * sizeof(DWORD)));
    auto_buffer<PACL> new_acl(new_acl_size);

    // Initialize the new DACL.
    if (!InitializeAcl(new_acl.get(), new_acl_size, ACL_REVISION)) {
        printf("InitializeAcl() failed: %d\n", GetLastError());
        return FALSE;
    }

    // If DACL is present, copy it to a new DACL.
    if (bDaclPresent) {
        // Copy the ACEs to the new ACL.
        for (DWORD i = 0; i != aclSizeInfo.AceCount; ++i) {
            ACCESS_ALLOWED_ACE* pace;
            if (!GetAce(pacl, i, (void**)&pace)) {
                printf("GetAce() failed: %d\n", GetLastError());
                return FALSE;
            }
            if (!EqualSid(psid, &pace->SidStart)) {
                if (!AddAce(new_acl.get(), ACL_REVISION, MAXDWORD,
                            pace, pace->Header.AceSize)) {
                    printf("AddAce() failed: %d\n", GetLastError());
                    return FALSE;
                }
            }
        }
    }

    // Set a new DACL for the security descriptor.
    if (!SetSecurityDescriptorDacl(psd_new.get(), TRUE, new_acl.get(), FALSE)) {
        printf("SetSecurityDescriptorDacl() failed: %d\n", GetLastError());
        return FALSE;
    }

    // Set the new security descriptor for the window station.
    if (!SetUserObjectSecurity(hwinsta, &si, psd_new.get())) {
        printf("SetUserObjectSecurity() failed: %d\n", GetLastError());
        return FALSE;
    }

    return TRUE;
}
Example #27
0
HRESULT COpcSecurity::RemovePrincipalFromACL(PACL pAcl, LPCTSTR pszPrincipal)
{
	ACL_SIZE_INFORMATION aclSizeInfo;
	ULONG i;
	LPVOID ace;
	ACCESS_ALLOWED_ACE *accessAllowedAce;
	ACCESS_DENIED_ACE *accessDeniedAce;
	SYSTEM_AUDIT_ACE *systemAuditAce;
	PSID principalSID;
	DWORD returnValue;
	ACE_HEADER *aceHeader;

	returnValue = GetPrincipalSID(pszPrincipal, &principalSID);
	if (FAILED(returnValue))
		return returnValue;

	GetAclInformation(pAcl, (LPVOID) &aclSizeInfo, (DWORD) sizeof(ACL_SIZE_INFORMATION), AclSizeInformation);

	for (i = 0; i < aclSizeInfo.AceCount; i++)
	{
		if (!GetAce(pAcl, i, &ace))
		{
			free(principalSID);
			return HRESULT_FROM_WIN32(GetLastError());
		}

		aceHeader = (ACE_HEADER *) ace;

		if (aceHeader->AceType == ACCESS_ALLOWED_ACE_TYPE)
		{
			accessAllowedAce = (ACCESS_ALLOWED_ACE *) ace;

			if (EqualSid(principalSID, (PSID) &accessAllowedAce->SidStart))
			{
				DeleteAce(pAcl, i);
				free(principalSID);
				return S_OK;
			}
		} else

		if (aceHeader->AceType == ACCESS_DENIED_ACE_TYPE)
		{
			accessDeniedAce = (ACCESS_DENIED_ACE *) ace;

			if (EqualSid(principalSID, (PSID) &accessDeniedAce->SidStart))
			{
				DeleteAce(pAcl, i);
				free(principalSID);
				return S_OK;
			}
		} else

		if (aceHeader->AceType == SYSTEM_AUDIT_ACE_TYPE)
		{
			systemAuditAce = (SYSTEM_AUDIT_ACE *) ace;

			if (EqualSid(principalSID, (PSID) &systemAuditAce->SidStart))
			{
				DeleteAce(pAcl, i);
				free(principalSID);
				return S_OK;
			}
		}
	}
	free(principalSID);
	return S_OK;
}
Example #28
0
/**************************************************************************
 * IsUserAdmin [SETUPAPI.@]
 *
 * Checks whether the current user is a member of the Administrators group.
 *
 * PARAMS
 *     None
 *
 * RETURNS
 *     Success: TRUE
 *     Failure: FALSE
 */
BOOL WINAPI IsUserAdmin(VOID)
{
    SID_IDENTIFIER_AUTHORITY Authority = {SECURITY_NT_AUTHORITY};
    HANDLE hToken;
    DWORD dwSize;
    PTOKEN_GROUPS lpGroups;
    PSID lpSid;
    DWORD i;
    BOOL bResult = FALSE;

    TRACE("\n");

    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
    {
        return FALSE;
    }

    if (!GetTokenInformation(hToken, TokenGroups, NULL, 0, &dwSize))
    {
        if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
        {
            CloseHandle(hToken);
            return FALSE;
        }
    }

    lpGroups = MyMalloc(dwSize);
    if (lpGroups == NULL)
    {
        CloseHandle(hToken);
        return FALSE;
    }

    if (!GetTokenInformation(hToken, TokenGroups, lpGroups, dwSize, &dwSize))
    {
        MyFree(lpGroups);
        CloseHandle(hToken);
        return FALSE;
    }

    CloseHandle(hToken);

    if (!AllocateAndInitializeSid(&Authority, 2, SECURITY_BUILTIN_DOMAIN_RID,
                                  DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0,
                                  &lpSid))
    {
        MyFree(lpGroups);
        return FALSE;
    }

    for (i = 0; i < lpGroups->GroupCount; i++)
    {
        if (EqualSid(lpSid, lpGroups->Groups[i].Sid))
        {
            bResult = TRUE;
            break;
        }
    }

    FreeSid(lpSid);
    MyFree(lpGroups);

    return bResult;
}
Example #29
0
			bool operator ()(const sid& Sid1, const sid& Sid2) const
			{
				return EqualSid(Sid1.get(), Sid2.get()) != FALSE;
			}
Example #30
0
	bool IsAdmin()
	{
		DWORD dwSize = 0;
		HANDLE hToken;
		PTOKEN_GROUPS pGroupInfo;
		BYTE sidBuffer[100];
		PSID pSID = (PSID)&sidBuffer;
		SID_IDENTIFIER_AUTHORITY SIDAuth = SECURITY_NT_AUTHORITY;

		// Open a handle to the access token for the calling process.
		if (!OpenProcessToken( GetCurrentProcess(), TOKEN_QUERY, &hToken )) 
		{
			LogTheError(_T("OpenProcessToken Error"));
			return false;
		}

		// Call GetTokenInformation to get the buffer size.
		if(!GetTokenInformation(hToken, TokenGroups, NULL, dwSize, &dwSize)) 
		{
			if( GetLastError() != ERROR_INSUFFICIENT_BUFFER ) 
			{
				LogTheError(_T("GetTokenInformation Error"));
				return false;
			}
		}

		// Call GetTokenInformation again to get the group information.
		pGroupInfo = (PTOKEN_GROUPS) GlobalAlloc( GPTR, dwSize );
		if(! GetTokenInformation(hToken, TokenGroups, pGroupInfo, dwSize, &dwSize ) )
		{
			LogTheError(_T("GetTokenInformation Error"));
			if ( pGroupInfo )
				GlobalFree( pGroupInfo );
			return false;
		}

		// Create a SID for the BUILTIN\Administrators group.
		if(! AllocateAndInitializeSid( &SIDAuth, 2, 
			SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS,
			0, 0, 0, 0, 0, 0, &pSID) )
		{
			LogTheError(_T("AllocateAndInitializeSid Error"));
			if (pSID)
				FreeSid(pSID);
			if ( pGroupInfo )
				GlobalFree( pGroupInfo );
			return false;
		}

		// Loop through the group SIDs looking for the administrator SID.
		bool bFound = false;
		for(DWORD i=0; i<pGroupInfo->GroupCount; i++) 
		{
			if ( EqualSid(pSID, pGroupInfo->Groups[i].Sid) ) 
				bFound = true;
		}

		if (pSID)
			FreeSid(pSID);
		if ( pGroupInfo )
			GlobalFree( pGroupInfo );
		return bFound;
	}