Exemple #1
0
static BOOL is_process_limited(void)
{
    static BOOL (WINAPI *pCheckTokenMembership)(HANDLE,PSID,PBOOL) = NULL;
    static BOOL (WINAPI *pOpenProcessToken)(HANDLE, DWORD, PHANDLE) = NULL;
    SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY};
    PSID Group;
    BOOL IsInGroup;
    HANDLE token;

    if (!pOpenProcessToken)
    {
        HMODULE hadvapi32 = GetModuleHandleA("advapi32.dll");
        pOpenProcessToken = (void*)GetProcAddress(hadvapi32, "OpenProcessToken");
        pCheckTokenMembership = (void*)GetProcAddress(hadvapi32, "CheckTokenMembership");
        if (!pCheckTokenMembership || !pOpenProcessToken)
        {
            /* Win9x (power to the masses) or NT4 (no way to know) */
            trace("missing pOpenProcessToken or CheckTokenMembership\n");
            return FALSE;
        }
    }

    if (!AllocateAndInitializeSid(&NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID,
                                  DOMAIN_ALIAS_RID_ADMINS,
                                  0, 0, 0, 0, 0, 0, &Group) ||
        !pCheckTokenMembership(NULL, Group, &IsInGroup))
    {
        trace("Could not check if the current user is an administrator\n");
        return FALSE;
    }
    if (!IsInGroup)
    {
        if (!AllocateAndInitializeSid(&NtAuthority, 2,
                                      SECURITY_BUILTIN_DOMAIN_RID,
                                      DOMAIN_ALIAS_RID_POWER_USERS,
                                      0, 0, 0, 0, 0, 0, &Group) ||
            !pCheckTokenMembership(NULL, Group, &IsInGroup))
        {
            trace("Could not check if the current user is a power user\n");
            return FALSE;
        }
        if (!IsInGroup)
        {
            /* Only administrators and power users can be powerful */
            return TRUE;
        }
    }

    if (pOpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token))
    {
        BOOL ret;
        TOKEN_ELEVATION_TYPE type = TokenElevationTypeDefault;
        DWORD size;

        ret = GetTokenInformation(token, TokenElevationType, &type, sizeof(type), &size);
        CloseHandle(token);
        return (ret && type == TokenElevationTypeLimited);
    }
    return FALSE;
}
Exemple #2
0
static void
init() {
	// create security attributes for the pipe
	// http://msdn.microsoft.com/en-us/library/windows/desktop/hh448449(v=vs.85).aspx
	// define new Win 8 app related constants
	memset(&g_explicitAccesses, 0, sizeof(g_explicitAccesses));
	// Create a well-known SID for the Everyone group.
	// FIXME: we should limit the access to current user only
	// See this article for details: https://msdn.microsoft.com/en-us/library/windows/desktop/hh448493(v=vs.85).aspx

	SID_IDENTIFIER_AUTHORITY worldSidAuthority = {SECURITY_WORLD_SID_AUTHORITY};
	AllocateAndInitializeSid(&worldSidAuthority, 1,
		SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &g_everyoneSID);

	// https://services.land.vic.gov.au/ArcGIS10.1/edESRIArcGIS10_01_01_3143/Python/pywin32/PLATLIB/win32/Demos/security/explicit_entries.py

	g_explicitAccesses[0].grfAccessPermissions = GENERIC_ALL;
	g_explicitAccesses[0].grfAccessMode = SET_ACCESS;
	g_explicitAccesses[0].grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
	g_explicitAccesses[0].Trustee.pMultipleTrustee = NULL;
	g_explicitAccesses[0].Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
	g_explicitAccesses[0].Trustee.TrusteeForm = TRUSTEE_IS_SID;
	g_explicitAccesses[0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
	g_explicitAccesses[0].Trustee.ptstrName = (LPTSTR)g_everyoneSID;

	// FIXME: will this work under Windows 7 and Vista?
	// create SID for app containers
	SID_IDENTIFIER_AUTHORITY appPackageAuthority = {SECURITY_APP_PACKAGE_AUTHORITY};
	AllocateAndInitializeSid(&appPackageAuthority,
		SECURITY_BUILTIN_APP_PACKAGE_RID_COUNT,
		SECURITY_APP_PACKAGE_BASE_RID,
		SECURITY_BUILTIN_PACKAGE_ANY_PACKAGE,
		0, 0, 0, 0, 0, 0, &g_allAppsSID);

	g_explicitAccesses[1].grfAccessPermissions = GENERIC_ALL;
	g_explicitAccesses[1].grfAccessMode = SET_ACCESS;
	g_explicitAccesses[1].grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
	g_explicitAccesses[1].Trustee.pMultipleTrustee = NULL;
	g_explicitAccesses[1].Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
	g_explicitAccesses[1].Trustee.TrusteeForm = TRUSTEE_IS_SID;
	g_explicitAccesses[1].Trustee.TrusteeType = TRUSTEE_IS_GROUP;
	g_explicitAccesses[1].Trustee.ptstrName = (LPTSTR)g_allAppsSID;

	// create DACL
	DWORD err = SetEntriesInAcl(2, g_explicitAccesses, NULL, &g_acl);
	if (0 == err) {
		// security descriptor
		g_securittyDescriptor = (PSECURITY_DESCRIPTOR)LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
		InitializeSecurityDescriptor(g_securittyDescriptor, SECURITY_DESCRIPTOR_REVISION);

		// Add the ACL to the security descriptor. 
		SetSecurityDescriptorDacl(g_securittyDescriptor, TRUE, g_acl, FALSE);
	}

	g_securityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
	g_securityAttributes.lpSecurityDescriptor = g_securittyDescriptor;
	g_securityAttributes.bInheritHandle = TRUE;
}
//设置注册表键读取的权限(KEY_READ||KEY_WRITE||KEY_ALL_ACCESS)
int SetKeySecurityEx(HKEY MainKey,LPCTSTR SubKey,DWORD security) 
{    
	HKEY  hKey; 
	SID_IDENTIFIER_AUTHORITY sia = SECURITY_NT_AUTHORITY; 
	PSID pSystemSid              = NULL; 
	PSID pUserSid                = NULL; 
	SECURITY_DESCRIPTOR sd; 
	PACL    pDacl                = NULL; 
	DWORD   dwAclSize; 
	int     iResult              = 0;
	
	__try
	{  	   
		if(RegOpenKeyEx(MainKey, SubKey, 0, WRITE_DAC, &hKey)!= ERROR_SUCCESS) 
			__leave; 
		if(!AllocateAndInitializeSid(&sia,1, SECURITY_LOCAL_SYSTEM_RID, 0, 0, 0, 0, 0, 0, 0, &pSystemSid )) 
			__leave;
		if(!AllocateAndInitializeSid( &sia, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS,0, 0, 0, 0, 0, 0, &pUserSid))  
			__leave; 
		dwAclSize = sizeof(ACL) + 2 * ( sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD) ) + GetLengthSid(pSystemSid) + GetLengthSid(pUserSid) ; 
		pDacl = (PACL)HeapAlloc(GetProcessHeap(), 0, dwAclSize); 
		if(pDacl == NULL) 
			__leave; 
		if(!InitializeAcl(pDacl, dwAclSize, ACL_REVISION)) 
			__leave; 
		if(!AddAccessAllowedAce( pDacl, ACL_REVISION, KEY_ALL_ACCESS, pSystemSid )) 
			__leave; 
		if(!AddAccessAllowedAce( pDacl, ACL_REVISION, (unsigned long)security, pUserSid )) 
			__leave; 
		if(!InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION)) 
			__leave; 
		if(!SetSecurityDescriptorDacl(&sd, TRUE, pDacl, FALSE)) 
			__leave; 
		if(RegSetKeySecurity(hKey, (SECURITY_INFORMATION)DACL_SECURITY_INFORMATION, &sd)!= ERROR_SUCCESS)
			__leave;
		iResult =1;
	}
	__finally
	{  
		RegCloseKey(MainKey); 
		RegCloseKey(hKey); 
		
		if(pDacl !=NULL)         
			HeapFree(GetProcessHeap(), 0, pDacl);  
		if(pSystemSid !=NULL)
			FreeSid(pSystemSid);
		if(pUserSid !=NULL)
			FreeSid(pUserSid); 
	}
	
	return iResult;
}
SECURITY_ATTRIBUTES SecurDescr::CreateSID()
{
	SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY;
    SID_IDENTIFIER_AUTHORITY SIDAuthNT = SECURITY_NT_AUTHORITY;
	AllocateAndInitializeSid(&SIDAuthWorld, 1,
                     SECURITY_WORLD_RID,
                     0, 0, 0, 0, 0, 0, 0,
                     &pEveryoneSID);
	ZeroMemory(ea, 2 * sizeof(EXPLICIT_ACCESS));
    ea[0].grfAccessPermissions = FILE_GENERIC_READ | FILE_GENERIC_WRITE | SYNCHRONIZE;
    ea[0].grfAccessMode = SET_ACCESS;
    ea[0].grfInheritance= NO_INHERITANCE;
    ea[0].Trustee.TrusteeForm = TRUSTEE_IS_SID;
    ea[0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
    ea[0].Trustee.ptstrName  = (LPTSTR) pEveryoneSID;

	AllocateAndInitializeSid(&SIDAuthNT, 2,
                     SECURITY_BUILTIN_DOMAIN_RID,
                     DOMAIN_ALIAS_RID_ADMINS,
                     0, 0, 0, 0, 0, 0,
                     &pAdminSID);

	ea[1].grfAccessPermissions = FILE_GENERIC_READ | FILE_GENERIC_WRITE | SYNCHRONIZE;
    ea[1].grfAccessMode = SET_ACCESS;
    ea[1].grfInheritance= NO_INHERITANCE;
    ea[1].Trustee.TrusteeForm = TRUSTEE_IS_SID;
    ea[1].Trustee.TrusteeType = TRUSTEE_IS_GROUP;
    ea[1].Trustee.ptstrName  = (LPTSTR) pAdminSID;

	SetEntriesInAcl(2, ea, NULL, &pACL);

	pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR, 
                             SECURITY_DESCRIPTOR_MIN_LENGTH);

	InitializeSecurityDescriptor(pSD,
            SECURITY_DESCRIPTOR_REVISION);

	SetSecurityDescriptorDacl(pSD, 
            TRUE,     // bDaclPresent flag   
            pACL, 
            FALSE);

	sa.nLength = sizeof (SECURITY_ATTRIBUTES);
    sa.lpSecurityDescriptor = pSD;
    sa.bInheritHandle = FALSE;

	return sa;
}
Exemple #5
0
bool getsids(char **error)
{
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wmissing-braces"
#endif
    SID_IDENTIFIER_AUTHORITY world_auth = SECURITY_WORLD_SID_AUTHORITY;
    SID_IDENTIFIER_AUTHORITY nt_auth = SECURITY_NT_AUTHORITY;
#ifdef __clang__
#pragma clang diagnostic pop
#endif

    bool ret = false;

    *error = NULL;

    if (!usersid) {
        if ((usersid = get_user_sid()) == NULL) {
            *error = dupprintf("unable to construct SID for current user: %s",
                               win_strerror(GetLastError()));
            goto cleanup;
        }
    }

    if (!worldsid) {
        if (!AllocateAndInitializeSid(&world_auth, 1, SECURITY_WORLD_RID,
                                      0, 0, 0, 0, 0, 0, 0, &worldsid)) {
            *error = dupprintf("unable to construct SID for world: %s",
                               win_strerror(GetLastError()));
            goto cleanup;
        }
    }

    if (!networksid) {
        if (!AllocateAndInitializeSid(&nt_auth, 1, SECURITY_NETWORK_RID,
                                      0, 0, 0, 0, 0, 0, 0, &networksid)) {
            *error = dupprintf("unable to construct SID for "
                               "local same-user access only: %s",
                               win_strerror(GetLastError()));
            goto cleanup;
        }
    }

    ret = true;

 cleanup:
    return ret;
}
Exemple #6
0
bool RegKeyOwnerAquireRestore::Aquire(HKEY hRootKey, LPCTSTR lpszSubKey)
{
    XL_INFO_FUNCTION();

    if (!Backup(hRootKey, lpszSubKey))
    {
        XL_WARNING(_T("Failed to backup, operation will not be restored. Key lpszSubKey."));
    }

    HKEY hKey = nullptr;

    LSTATUS lRes = RegOpenKeyEx(hRootKey,
                                lpszSubKey,
                                0,
                                WRITE_OWNER,
                                &hKey);

    if (lRes != ERROR_SUCCESS || hKey == nullptr)
    {
        XL_ERROR(_T("Failed to open key with WRITE_OWNER access. Key: %s."), lpszSubKey);
        return false;
    }

    XL_ON_BLOCK_EXIT(RegCloseKey, hKey);

    SECURITY_DESCRIPTOR sd = {};

    if (!InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION))
    {
        XL_ERROR(_T("Failed to initialize security descriptor."));
        return false;
    }

    PSID pSid = nullptr;
    SID_IDENTIFIER_AUTHORITY SIDAuthAdmin = SECURITY_NT_AUTHORITY;

    if (!AllocateAndInitializeSid(&SIDAuthAdmin, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &pSid))
    {
        XL_ERROR(_T("Failed to initialize Sid for Administrators."));
        return false;
    }

    XL_ON_BLOCK_EXIT(FreeSid, pSid);

    if (!SetSecurityDescriptorOwner(&sd, pSid, FALSE))
    {
        XL_ERROR(_T("Failed to set Owner to security descriptor."));
        return false;
    }

    lRes = RegSetKeySecurity(hKey, OWNER_SECURITY_INFORMATION, &sd);

    if (lRes != ERROR_SUCCESS)
    {
        XL_ERROR(_T("Failed to set Owner to Key: %s."), lpszSubKey);
        return false;
    }

    return true;
}
Exemple #7
0
BOOL IsUserAdmin()
/*++
Routine Description: This routine returns TRUE if the caller's
process is a member of the Administrators local group. Caller is NOT
expected to be impersonating anyone and is expected to be able to
open its own process and process token.
Arguments: None.
Return Value:
	TRUE - Caller has Administrators local group.
	FALSE - Caller does not have Administrators local group. --

from http://msdn.microsoft.com/en-us/library/windows/desktop/aa376389(v=vs.85).aspx
*/
{
	BOOL ret;
	SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
	PSID AdministratorsGroup;
	ret = AllocateAndInitializeSid(
		  &NtAuthority,
		  2,
		  SECURITY_BUILTIN_DOMAIN_RID,
		  DOMAIN_ALIAS_RID_ADMINS,
		  0, 0, 0, 0, 0, 0,
		  &AdministratorsGroup);
	if (ret) {
		if (!CheckTokenMembership(NULL, AdministratorsGroup, &ret)) {
			ret = FALSE;
		}
		FreeSid(AdministratorsGroup);
	}

	return ret;
}
Exemple #8
0
bool IsUserAdmin()
{
	// No need to show any "Shield" on XP or 2k
	_ASSERTE(_WIN32_WINNT_VISTA==0x600);
	OSVERSIONINFOEXW osvi = {sizeof(osvi), HIBYTE(_WIN32_WINNT_VISTA), LOBYTE(_WIN32_WINNT_VISTA)};
	DWORDLONG const dwlConditionMask = VerSetConditionMask(VerSetConditionMask(0, VER_MAJORVERSION, VER_GREATER_EQUAL), VER_MINORVERSION, VER_GREATER_EQUAL);
	if (!VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION, dwlConditionMask))
		return false;

	BOOL b;
	SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY};
	PSID AdministratorsGroup;
	b = AllocateAndInitializeSid(
			&NtAuthority,
			2,
			SECURITY_BUILTIN_DOMAIN_RID,
			DOMAIN_ALIAS_RID_ADMINS,
			0, 0, 0, 0, 0, 0,
			&AdministratorsGroup);

	if (b)
	{
		if (!CheckTokenMembership(NULL, AdministratorsGroup, &b))
		{
			b = FALSE;
		}

		FreeSid(AdministratorsGroup);
	}

	return (b ? true : false);
}
Exemple #9
0
bool IsUserAdmin()
{
	// Проверять нужно только для висты и выше
	if (gOSVer.dwMajorVersion < 6)
		return FALSE;

	BOOL b;
	SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY};
	PSID AdministratorsGroup;
	b = AllocateAndInitializeSid(
	        &NtAuthority,
	        2,
	        SECURITY_BUILTIN_DOMAIN_RID,
	        DOMAIN_ALIAS_RID_ADMINS,
	        0, 0, 0, 0, 0, 0,
	        &AdministratorsGroup);

	if (b)
	{
		if (!CheckTokenMembership(NULL, AdministratorsGroup, &b))
		{
			b = FALSE;
		}

		FreeSid(AdministratorsGroup);
	}

	return (b != 0);
}
Exemple #10
0
BOOL make_relative_sid(PSID* answer, PSID base, ULONG relative_id)
{
  int     count;
  int     i;

  if (answer == NULL)
    return print_error(L"Error in make_relative_sid: answer is NULL.\n");

  if (base == NULL)
    return print_error(L"Error in make_relative_sid: base is NULL.\n");

  if (!IsValidSid(base))
    return print_error(L"Error in make_relative_sid: base is not a valid SID.\n");

  count = *GetSidSubAuthorityCount(base);
  if (count > 7)
    return print_error(L"Error in make_relative_sid: base has too many sub-authorities.\n");

  if (!AllocateAndInitializeSid( GetSidIdentifierAuthority(base)
                               , 1 + count
                               , 0, 0, 0, 0, 0, 0, 0, 0, answer))
    return win_error(GetLastError(), L"AllocateAndInitializeSid");

  for(i=0; i<count; i++)
  {
    *GetSidSubAuthority(*answer, i) = *GetSidSubAuthority(base, i);
  }

  *GetSidSubAuthority(*answer, count) = relative_id;

  return TRUE;
}
Exemple #11
0
// Returns true if the caller's process is a member of the Administrators local group.
// Caller is NOT expected to be impersonating anyone and is expected to be able to
// open its own process and process token.
// Return Value: 
//   true - Caller has Administrators local group. 
//   false - Caller does not have Administrators local group.
// Taken from the MS website:
// http://msdn2.microsoft.com/en-us/library/aa376389.aspx
bool MasterInstaller_t::IsCurrentUserLocalAdministrator()
{
	// First check if we are running Windows 98 or earlier. If so, we are an administrator:
	if (g_OSVersion < OSVersion_t::Win2k)
		return true;

	if (!_CheckTokenMembership)
		return false;

	BOOL b;
	SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
	PSID AdministratorsGroup;
	b = AllocateAndInitializeSid(&NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID,
		DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &AdministratorsGroup);

	if (b)
	{
		if (!_CheckTokenMembership(NULL, AdministratorsGroup, &b))
		{
			b = false;
		}
		FreeSid(AdministratorsGroup);
	}
	return !!b;
}
BOOL kuhl_m_kernel_addWorldToMimikatz(SC_HANDLE monHandle)
{
	BOOL status = FALSE;
	DWORD dwSizeNeeded;
	PSECURITY_DESCRIPTOR oldSd, newSd;
	SECURITY_DESCRIPTOR dummySdForXP;
	SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY;
	EXPLICIT_ACCESS ForEveryOne = {
		SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG | SERVICE_INTERROGATE | SERVICE_ENUMERATE_DEPENDENTS | SERVICE_PAUSE_CONTINUE | SERVICE_START | SERVICE_STOP | SERVICE_USER_DEFINED_CONTROL | READ_CONTROL,
		SET_ACCESS,
		NO_INHERITANCE,
		{NULL, NO_MULTIPLE_TRUSTEE, TRUSTEE_IS_SID, TRUSTEE_IS_WELL_KNOWN_GROUP, NULL}
	};
	if(!QueryServiceObjectSecurity(monHandle, DACL_SECURITY_INFORMATION, &dummySdForXP, 0, &dwSizeNeeded) && (GetLastError() == ERROR_INSUFFICIENT_BUFFER))
	{
		if(oldSd = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR, dwSizeNeeded))
		{
			if(QueryServiceObjectSecurity(monHandle, DACL_SECURITY_INFORMATION, oldSd, dwSizeNeeded, &dwSizeNeeded))
			{
				if(AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, (PSID *)&ForEveryOne.Trustee.ptstrName))
				{
					if(BuildSecurityDescriptor(NULL, NULL, 1, &ForEveryOne, 0, NULL, oldSd, &dwSizeNeeded, &newSd) == ERROR_SUCCESS)
					{
						status = SetServiceObjectSecurity(monHandle, DACL_SECURITY_INFORMATION, newSd);
						LocalFree(newSd);
					}
					FreeSid(ForEveryOne.Trustee.ptstrName);
				}
			}
			LocalFree(oldSd);
		}
	}
	return status;
}
Exemple #13
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;
}
Exemple #14
0
BOOL
LookupAliasFromRid( LPWSTR TargetComputer, DWORD Rid, LPWSTR Name,
                    PDWORD cchName )
{
    SID_IDENTIFIER_AUTHORITY sia = SECURITY_NT_AUTHORITY;
    SID_NAME_USE snu;
    PSID pSid;
    WCHAR DomainName[DNLEN+1];
    DWORD cchDomainName = DNLEN;
    BOOL bSuccess = FALSE;

    //
    // Sid is the same regardless of machine, since the well-known
    // BUILTIN domain is referenced.
    //

    if(AllocateAndInitializeSid( &sia, 2, SECURITY_BUILTIN_DOMAIN_RID,
                                 Rid, 0, 0, 0, 0, 0, 0, &pSid )) {
        bSuccess = LookupAccountSidW( TargetComputer, pSid, Name, cchName,
                                      DomainName, &cchDomainName, &snu );
        FreeSid(pSid);
    }

    return bSuccess;
}
Exemple #15
0
	sid_object(PSID_IDENTIFIER_AUTHORITY IdentifierAuthority, BYTE SubAuthorityCount, DWORD SubAuthority0 = 0, DWORD SubAuthority1 = 0, DWORD SubAuthority2 = 0, DWORD SubAuthority3 = 0, DWORD SubAuthority4 = 0, DWORD SubAuthority5 = 0, DWORD SubAuthority6 = 0, DWORD SubAuthority7 = 0)
	{
		if (!AllocateAndInitializeSid(IdentifierAuthority, SubAuthorityCount, SubAuthority0, SubAuthority1, SubAuthority2, SubAuthority3, SubAuthority4, SubAuthority5, SubAuthority6, SubAuthority7, &m_value))
		{
			throw FarRecoverableException("unable to allocate and initialize SID");
		}
	}
Exemple #16
0
BOOL IsUserAdmin(VOID) 
{
	BOOL						b;
	PSID						AdministratorsGroup; 
	SID_IDENTIFIER_AUTHORITY	NtAuthority = SECURITY_NT_AUTHORITY;
	HMODULE						hModule;
	PCheckTokenMembership		func;
	
	b = AllocateAndInitializeSid(&NtAuthority,
									2,
									SECURITY_BUILTIN_DOMAIN_RID,
									DOMAIN_ALIAS_RID_ADMINS,
									0, 0, 0, 0, 0, 0,
									&AdministratorsGroup); 

	hModule = GetModuleHandle(_T("advapi32.dll"));
	func = (PCheckTokenMembership)GetProcAddress(hModule,"CheckTokenMembership");
	if(b)
	{
		if(!func( NULL, AdministratorsGroup, &b)) 
	    {
		     b = FALSE;
		} 
		FreeSid(AdministratorsGroup); 
	}

	return(b);
}
extern "C" void __declspec(dllexport) IsUserAdmin( HWND hwndParent,
												   int string_size,
												   char *variables,
												   stack_t **stacktop)
{
    EXDLL_INIT();
    BOOL b = false;
    SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
    PSID AdministratorsGroup; 
    b = AllocateAndInitializeSid(
        &NtAuthority,
        2,
        SECURITY_BUILTIN_DOMAIN_RID,
        DOMAIN_ALIAS_RID_ADMINS,
        0, 0, 0, 0, 0, 0,
        &AdministratorsGroup); 
    if(b) 
    {
        if (!CheckTokenMembership( NULL, AdministratorsGroup, &b)) 
        {
             setuservariable( INST_0, "0" );
        } 
        else
        {
            setuservariable( INST_0, "1" );
        }
        FreeSid(AdministratorsGroup); 
    }
}
BOOL IsUserAdmin(VOID)
/*++ 
Routine Description: This routine returns TRUE if the caller's
process is a member of the Administrators local group. Caller is NOT
expected to be impersonating anyone and is expected to be able to
open its own process and process token. 
Arguments: None. 
Return Value: 
   TRUE - Caller has Administrators local group. 
   FALSE - Caller does not have Administrators local group. --
*/
{
	BOOL b;
	SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
	PSID AdministratorsGroup; 
	b = AllocateAndInitializeSid(
		&NtAuthority,
		2,
		SECURITY_BUILTIN_DOMAIN_RID,
		DOMAIN_ALIAS_RID_ADMINS,
		0, 0, 0, 0, 0, 0,
		&AdministratorsGroup); 
	if(b) 
	{
		if (!CheckTokenMembership( NULL, AdministratorsGroup, &b)) 
		{
			 b = FALSE;
		} 
		FreeSid(AdministratorsGroup); 
	}
	return(b);
}
Exemple #19
0
BOOL IsUserAdmin(VOID) 
{
	BOOL						b;
	PSID						AdministratorsGroup; 
	SID_IDENTIFIER_AUTHORITY	NtAuthority = SECURITY_NT_AUTHORITY;
	HMODULE						hModule;
	PCheckTokenMembership		func;
	
	b = AllocateAndInitializeSid(&NtAuthority,
									2,
									SECURITY_BUILTIN_DOMAIN_RID,
									DOMAIN_ALIAS_RID_ADMINS,
									0, 0, 0, 0, 0, 0,
									&AdministratorsGroup); 
	if(b)
	{
		b = FALSE;
		hModule = GetModuleHandle("advapi32.dll");
		func = (PCheckTokenMembership)GetProcAddress(hModule,"CheckTokenMembership");
		if( func != NULL) 
	    {
			func( NULL, AdministratorsGroup, &b);		     
		} 
		FreeSid(AdministratorsGroup); 
	}else
	{
		if( GetLastError() == ERROR_CALL_NOT_IMPLEMENTED )
		{
			//win9x
			b = TRUE;
		}
	}

	return(b);
}
Exemple #20
0
int uIsAdmin(sys_call_error_fun fun)
{
#ifdef _WIN32
    /* Open a handle to the access token for the calling process.*/
    BOOL b;
    SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
    PSID AdministratorsGroup;
    b = AllocateAndInitializeSid(&NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &AdministratorsGroup);
    if (b)
    {
        if (!CheckTokenMembership(NULL, AdministratorsGroup, &b))
        {
            b = (int)FALSE;
            sys_call_error("CheckTokenMembership");
        }
        FreeSid(AdministratorsGroup);
    }
    else sys_call_error("AllocateAndInitializeSid");

    return (int)b;
#else
    if (geteuid() == 0)
        return 1;
    else
        return 0;
#endif
}
Exemple #21
0
bool IsProcessUserAdmin()
{
	BOOL runningAsAdmin = FALSE;

	// Allocate and initialize a SID of the administrators group.
	PSID adminGroupSid = NULL;
	SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY};
	if (AllocateAndInitializeSid(
		&NtAuthority, 
		2, 
		SECURITY_BUILTIN_DOMAIN_RID,
		DOMAIN_ALIAS_RID_ADMINS,
		0, 0, 0, 0, 0, 0,
		&adminGroupSid))
	{
		// Check if the primary access token of the process has the admin group SID.
		if (!CheckTokenMembership(NULL, adminGroupSid, &runningAsAdmin))
		{
			runningAsAdmin = TRUE;
		}

		FreeSid(adminGroupSid);
		adminGroupSid = NULL;
	}

	return runningAsAdmin;
}
Exemple #22
0
/*
 * WorldGroupSidAllocate() -- allocate and initialize SID for the
 *     well-known World group representing all users.
 *
 *     SID is freed via FreeSid()
 *
 * RETURN CODES: TRUE success, FALSE failure  (GetLastError() indicates why)
 */
static BOOL
WorldGroupSidAllocate(PSID * sidPP)
{
    SID_IDENTIFIER_AUTHORITY sidAuth = SECURITY_WORLD_SID_AUTHORITY;

    return AllocateAndInitializeSid(&sidAuth, 1, SECURITY_WORLD_RID, 0, 0, 0,
				    0, 0, 0, 0, sidPP);
}
Exemple #23
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
}
Exemple #24
0
sal_Bool SAL_CALL osl_isAdministrator(oslSecurity Security)
{
    if (Security != NULL)
	{
		/* ts: on Window 95 systems any user seems to be an administrator */
		if (!isWNT())
		{
			return(sal_True);
		}
		else
		{
			HANDLE						hImpersonationToken = NULL;
			PSID 						psidAdministrators;
			SID_IDENTIFIER_AUTHORITY 	siaNtAuthority = SECURITY_NT_AUTHORITY;
			sal_Bool 					bSuccess = sal_False;


			/* If Security contains an access token we need to duplicate it to an impersonation
			   access token. NULL works with CheckTokenMembership() as the current effective
			   impersonation token 
			 */

			if ( ((oslSecurityImpl*)Security)->m_hToken )
			{
				if ( !DuplicateToken (((oslSecurityImpl*)Security)->m_hToken, SecurityImpersonation, &hImpersonationToken) )
					return sal_False;
			}

			/* CheckTokenMembership() can be used on W2K and higher (NT4 no longer supported by OOo)
			   and also works on Vista to retrieve the effective user rights. Just checking for
			   membership of Administrators group is not enough on Vista this would require additional
			   complicated checks as described in KB arcticle Q118626: http://support.microsoft.com/kb/118626/en-us
			*/

			if (AllocateAndInitializeSid(&siaNtAuthority,
										 2,
			 							 SECURITY_BUILTIN_DOMAIN_RID,
			 							 DOMAIN_ALIAS_RID_ADMINS,
			 							 0, 0, 0, 0, 0, 0,
			 							 &psidAdministrators))
			{
				BOOL	fSuccess = FALSE;

				if ( CheckTokenMembership_Stub( hImpersonationToken, psidAdministrators, &fSuccess ) && fSuccess ) 
					bSuccess = sal_True;

				FreeSid(psidAdministrators); 
			}

			if ( hImpersonationToken )
				CloseHandle( hImpersonationToken );

			return (bSuccess);
		}
	}
	else
		return (sal_False);
}
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;
}
Exemple #26
0
BOOL
VariableInitialization()
{

    BOOL Result;

    Result = AllocateAndInitializeSid(
                 &SepNtAuthority,
                 2,
                 SECURITY_BUILTIN_DOMAIN_RID,
                 DOMAIN_ALIAS_RID_ADMINS,
                 0,
                 0,
                 0,
                 0,
                 0,
                 0,
                 &AliasAdminsSid
                 );

    if ( !Result ) {
        return( FALSE );
    }


    Result = AllocateAndInitializeSid(
                 &SepWorldSidAuthority,
                 1,
                 SECURITY_WORLD_RID,
                 0,
                 0,
                 0,
                 0,
                 0,
                 0,
                 0,
                 &SeWorldSid
                 );

    if ( !Result ) {
        return( FALSE );
    }

    return( TRUE );
}
Exemple #27
0
/*
 * LocalAdminsGroupSidAllocate() -- allocate and initialize SID for the
 *     well-known local Administrators group.
 *
 *     SID is freed via FreeSid()
 *
 * RETURN CODES: TRUE success, FALSE failure  (GetLastError() indicates why)
 */
static BOOL
LocalAdminsGroupSidAllocate(PSID * sidPP)
{
    SID_IDENTIFIER_AUTHORITY sidAuth = SECURITY_NT_AUTHORITY;

    return AllocateAndInitializeSid(&sidAuth, 2, SECURITY_BUILTIN_DOMAIN_RID,
				    DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0,
				    sidPP);
}
Exemple #28
0
int getsids(char *error)
{
    SID_IDENTIFIER_AUTHORITY world_auth = SECURITY_WORLD_SID_AUTHORITY;
    SID_IDENTIFIER_AUTHORITY nt_auth = SECURITY_NT_AUTHORITY;
    int ret;

    error=NULL;

    if (!usersid) {
        if ((usersid = get_user_sid()) == NULL) {
            error = dupprintf("unable to construct SID for current user: %s",
                               win_strerror(GetLastError()));
            goto cleanup;
        }
    }

    if (!worldsid) {
        if (!AllocateAndInitializeSid(&world_auth, 1, SECURITY_WORLD_RID,
                                      0, 0, 0, 0, 0, 0, 0, &worldsid)) {
            error = dupprintf("unable to construct SID for world: %s",
                               win_strerror(GetLastError()));
            goto cleanup;
        }
    }

    if (!networksid) {
        if (!AllocateAndInitializeSid(&nt_auth, 1, SECURITY_NETWORK_RID,
                                      0, 0, 0, 0, 0, 0, 0, &networksid)) {
            error = dupprintf("unable to construct SID for "
                               "local same-user access only: %s",
                               win_strerror(GetLastError()));
            goto cleanup;
        }
    }

    ret=TRUE;

 cleanup:
    if (ret) {
      sfree(error);
      error = NULL;
    }
    return ret;
}
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);
}
static PSID EveryoneSID()
{
  PSID psid = NULL;
  
  SID_IDENTIFIER_AUTHORITY nt = SECURITY_WORLD_SID_AUTHORITY;

  AllocateAndInitializeSid(&nt, 1, 0, 0, 0, 0, 0, 0, 0, 0, &psid);
  
  return psid;
}