Exemplo n.º 1
0
/// \brief Starts a new process with low integrity level
///
/// The newly started process is sandboxed and cannot increase its integrity level
///
int StartRestricted()
{
    BOOL ret;
    HANDLE token = nullptr;
    HANDLE newToken = nullptr;
    PSID integritySid = nullptr;
    TOKEN_MANDATORY_LABEL til = { 0 };
    PROCESS_INFORMATION procInfo = { 0 };
    STARTUPINFO startupInfo = { 0 };
    WCHAR procCommand[MAX_PATH] = _T("QnSend.exe /restricted");
    WCHAR lowIntegrityLevelSid[20] = _T("S-1-16-4096");

    try
    {
        ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE | TOKEN_ADJUST_DEFAULT | TOKEN_QUERY | TOKEN_ASSIGN_PRIMARY, &token);
        if (!ret)
            throw ret;
        ret = DuplicateTokenEx(token, 0, nullptr, SecurityImpersonation, TokenPrimary, &newToken);
        if (!ret)
            throw ret;
        ret = ConvertStringSidToSid(lowIntegrityLevelSid, &integritySid);
        if (!ret)
            throw ret;
        til.Label.Attributes = SE_GROUP_INTEGRITY;
        til.Label.Sid = integritySid;
        ret = SetTokenInformation(newToken, TokenIntegrityLevel, &til, sizeof(TOKEN_MANDATORY_LABEL) + GetLengthSid(integritySid));
        if (!ret)
            throw ret;
        ret = CreateProcessAsUser(newToken, NULL, procCommand, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &procInfo);
        if (!ret)
            throw ret;
    }
    catch (...)
    {
#pragma region Cleanup
        if (procInfo.hProcess != nullptr)
            CloseHandle(procInfo.hProcess);
        if (procInfo.hThread != nullptr)
            CloseHandle(procInfo.hThread);
        LocalFree(integritySid);
        if (newToken != nullptr)
            CloseHandle(newToken);
        if (token != nullptr)
            CloseHandle(token);
#pragma endregion
        return ERROR_C;
    }
#pragma region Cleanup
    if (procInfo.hProcess != nullptr)
        CloseHandle(procInfo.hProcess);
    if (procInfo.hThread != nullptr)
        CloseHandle(procInfo.hThread);
    LocalFree(integritySid);
    if (newToken != nullptr)
        CloseHandle(newToken);
    if (token != nullptr)
        CloseHandle(token);
#pragma endregion
    return SUCCESS_C;
}
Exemplo n.º 2
0
static
VOID
InstallBuiltinAccounts(VOID)
{
    LPWSTR BuiltinAccounts[] = {
        L"S-1-1-0",         /* Everyone */
        L"S-1-5-4",         /* Interactive */
        L"S-1-5-6",         /* Service */
        L"S-1-5-19",        /* Local Service */
        L"S-1-5-20",        /* Network Service */
        L"S-1-5-32-544",    /* Administrators */
        L"S-1-5-32-545",    /* Users */
        L"S-1-5-32-547",    /* Power Users */
        L"S-1-5-32-551",    /* Backup Operators */
        L"S-1-5-32-555"};   /* Remote Desktop Users */
    LSA_OBJECT_ATTRIBUTES ObjectAttributes;
    NTSTATUS Status;
    LSA_HANDLE PolicyHandle = NULL;
    LSA_HANDLE AccountHandle = NULL;
    PSID AccountSid;
    ULONG i;

    DPRINT("InstallBuiltinAccounts()\n");

    memset(&ObjectAttributes, 0, sizeof(LSA_OBJECT_ATTRIBUTES));

    Status = LsaOpenPolicy(NULL,
                           &ObjectAttributes,
                           POLICY_CREATE_ACCOUNT,
                           &PolicyHandle);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("LsaOpenPolicy failed (Status %08lx)\n", Status);
        return;
    }

    for (i = 0; i < 10; i++)
    {
        if (!ConvertStringSidToSid(BuiltinAccounts[i], &AccountSid))
        {
            DPRINT1("ConvertStringSidToSid(%S) failed: %lu\n", BuiltinAccounts[i], GetLastError());
            continue;
        }

        Status = LsaCreateAccount(PolicyHandle,
                                  AccountSid,
                                  0,
                                  &AccountHandle);
        if (NT_SUCCESS(Status))
        {
            LsaClose(AccountHandle);
        }

        LocalFree(AccountSid);
    }

    LsaClose(PolicyHandle);
}
Exemplo n.º 3
0
static unsigned int
iwin32_uid_scan (const char *buffer, user_id_t *uid)
{
  assert (buffer     != NULL);
  assert (uid        != NULL);
  assert (uid->value == NULL);

  if (!ConvertStringSidToSid ((char *) buffer, &uid->value)) return 0;
  return strlen (buffer);
}
Exemplo n.º 4
0
BOOL CImageUtility::CreateMediumIntegrityProcess(PCTSTR pszApplicationName, PTSTR pszCommandLine, PPROCESS_INFORMATION pPI, BOOL bShowWnd)
{
	BOOL bRet = FALSE;

	CAccessToken ProcToken;
	CAccessToken PrimaryToken;

	PSID pSid = NULL;

	STARTUPINFO si = { sizeof(si) };

	if (!ProcToken.GetEffectiveToken(TOKEN_DUPLICATE | TOKEN_ADJUST_DEFAULT | TOKEN_QUERY | TOKEN_ASSIGN_PRIMARY))
	{
		goto FUNC_EXIT;
	}

	if (!ProcToken.CreatePrimaryToken(&PrimaryToken))
	{
		goto FUNC_EXIT;
	}

	TCHAR szIntegritySid[20] = _T("S-1-16-8192");
	ConvertStringSidToSid(szIntegritySid, &pSid);

	TOKEN_MANDATORY_LABEL TIL;
	TIL.Label.Attributes = SE_GROUP_INTEGRITY;
	TIL.Label.Sid        = pSid;
	if (!SetTokenInformation(PrimaryToken.GetHandle(), (TOKEN_INFORMATION_CLASS)TokenIntegrityLevel, &TIL, sizeof(TOKEN_MANDATORY_LABEL) + GetLengthSid(pSid)))
	{
		goto FUNC_EXIT;
	}

	GetStartupInfo(&si);
	si.dwFlags = si.dwFlags|STARTF_USESHOWWINDOW;
	si.wShowWindow = SW_HIDE;

	bRet = CreateProcessAsUser(PrimaryToken.GetHandle(), pszApplicationName, pszCommandLine, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, pPI);

FUNC_EXIT:

	if (pSid != NULL)
	{
		LocalFree(pSid);
	}

	if (!bRet)
	{
		bRet = CreateProcess(pszApplicationName, pszCommandLine, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, pPI);
	}

	return bRet;
}
Exemplo n.º 5
0
static NTSTATUS id_sid(PWSTR SidStr)
{
    PSID Sid = 0;

    if (!ConvertStringSidToSid(SidStr, &Sid))
        return FspNtStatusFromWin32(GetLastError());

    id_print_sid("%S(%S) (uid=%u)", Sid);

    LocalFree(Sid);

    return STATUS_SUCCESS;
}
Exemplo n.º 6
0
NTSTATUS kuhl_m_sid_lookup(int argc, wchar_t * argv[])
{
	PWSTR name, domain;
	PSID pSid;
	SID_NAME_USE nameUse;
	PCWCHAR szName, szSystem = NULL;
	kull_m_string_args_byName(argc, argv, L"system", &szSystem, NULL);

	if(kull_m_string_args_byName(argc, argv, L"sid", &szName, NULL))
	{
		if(ConvertStringSidToSid(szName, &pSid))
		{
			kprintf(L"SID   : %s\n", szName);
			if(IsValidSid(pSid))
			{
				if(kull_m_token_getNameDomainFromSID(pSid, &name, &domain, &nameUse, szSystem))
				{
					kprintf(L"Type  : %s\n"
						L"Domain: %s\n"
						L"Name  : %s\n", kull_m_token_getSidNameUse(nameUse), domain, name);
					LocalFree(name);
					LocalFree(domain);
				}
				else PRINT_ERROR_AUTO(L"kull_m_token_getNameDomainFromSID");
			}
			else PRINT_ERROR(L"Invalid SID\n");
			LocalFree(pSid);
		}
		else PRINT_ERROR_AUTO(L"ConvertStringSidToSid");
	}
	else if(kull_m_string_args_byName(argc, argv, L"name", &szName, NULL))
	{
		kprintf(L"Name  : %s\n", szName);
		if(kull_m_token_getSidDomainFromName(szName, &pSid, &domain, &nameUse, szSystem))
		{
			kprintf(L"Type  : %s\n"
				L"Domain: %s\n"
				L"SID   : ", kull_m_token_getSidNameUse(nameUse), domain);
			kull_m_string_displaySID(pSid);
			kprintf(L"\n");
			LocalFree(pSid);
			LocalFree(domain);
		}
		else PRINT_ERROR_AUTO(L"kull_m_token_getSidDomainFromName");
	}
	else PRINT_ERROR(L"/sid or /name is missing\n");

	return STATUS_SUCCESS;
}
Exemplo n.º 7
0
bool SetOwnerInternal(LPCWSTR Object, LPCWSTR Owner)
{
	bool Result = false;

	PSID Sid = nullptr;
	//в winapi от mingw.org неправильный тип параметра.
	if(!ConvertStringSidToSid((LPWSTR)Owner, &Sid))
	{
		SID_NAME_USE Use;
		DWORD cSid=0, ReferencedDomain=0;
		LookupAccountName(nullptr, Owner, nullptr, &cSid, nullptr, &ReferencedDomain, &Use);
		if(cSid)
		{
			Sid = LocalAlloc(LMEM_FIXED, cSid);
			if(Sid)
			{
				LPWSTR ReferencedDomainName = new WCHAR[ReferencedDomain];
				if(ReferencedDomainName)
				{
					if(LookupAccountName(nullptr, Owner, Sid, &cSid, ReferencedDomainName, &ReferencedDomain, &Use))
					{
					}
					delete[] ReferencedDomainName;
				}
			}
		}
	}
	if(Sid)
	{
		Privilege TakeOwnershipPrivilege(SE_TAKE_OWNERSHIP_NAME);
		Privilege RestorePrivilege(SE_RESTORE_NAME);
		DWORD dwResult = SetNamedSecurityInfo(const_cast<LPWSTR>(Object), SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION, Sid, nullptr, nullptr, nullptr);
		if(dwResult == ERROR_SUCCESS)
		{
			Result = true;
		}
		else
		{
			SetLastError(dwResult);
		}
	}
	if(Sid)
	{
		LocalFree(Sid);
	}
	return Result;
}
Exemplo n.º 8
0
NTSTATUS kuhl_m_sid_add(int argc, wchar_t * argv[])
{
	PLDAP ld;
	DWORD dwErr;
	PCWCHAR szName;
	PWCHAR domain = NULL;
	PLDAPMessage pMessage = NULL;
	BERVAL NewSid;
	PBERVAL pNewSid[2] = {&NewSid, NULL};
	LDAPMod Modification = {LDAP_MOD_ADD | LDAP_MOD_BVALUES, L"sIDHistory"};
	PLDAPMod pModification[2] = {&Modification, NULL};
	Modification.mod_vals.modv_bvals = pNewSid;

	if(kull_m_string_args_byName(argc, argv, L"new", &szName, NULL))
	{
		if(ConvertStringSidToSid(szName, (PSID *) &NewSid.bv_val) || kull_m_token_getSidDomainFromName(szName, (PSID *) &NewSid.bv_val, &domain, NULL, NULL))
		{
			if(IsValidSid((PSID) NewSid.bv_val))
			{
				NewSid.bv_len = GetLengthSid((PSID) NewSid.bv_val);
				if(kuhl_m_sid_quickSearch(argc, argv, TRUE, NULL, &ld, &pMessage))
				{
					kprintf(L"\n  * Will try to add \'%s\' this new SID:\'", Modification.mod_type);
					kull_m_string_displaySID(NewSid.bv_val);
					kprintf(L"\': ");
					dwErr = ldap_modify_s(ld, ldap_get_dn(ld, pMessage), pModification);
					if(dwErr == LDAP_SUCCESS)
						kprintf(L"OK!\n");
					else PRINT_ERROR(L"ldap_modify_s 0x%x (%u)\n", dwErr, dwErr);
					if(pMessage)
						ldap_msgfree(pMessage);
					ldap_unbind(ld);
				}
			}
			else PRINT_ERROR(L"Invalid SID\n");
			LocalFree(NewSid.bv_val);
			if(domain)
				LocalFree(domain);
		}
		else PRINT_ERROR_AUTO(L"ConvertStringSidToSid / kull_m_token_getSidDomainFromName");
	}
	else PRINT_ERROR(L"/new:sid or /new:resolvable_name is needed");
	return STATUS_SUCCESS;
}
Exemplo n.º 9
0
DWORD ModLoader::AdjustGroupPolicy(std::wstring wstrFilePath)
{
	PACL pOldDACL = NULL, pNewDACL = NULL;
	PSECURITY_DESCRIPTOR pSD = NULL;
	EXPLICIT_ACCESS eaAccess;
	SECURITY_INFORMATION siInfo = DACL_SECURITY_INFORMATION;
	DWORD dwResult = ERROR_SUCCESS;
	PSID pSID;

	// Get a pointer to the existing DACL (Conditionaly).
	dwResult = GetNamedSecurityInfo(wstrFilePath.c_str(), SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &pOldDACL, NULL, &pSD);
	if (dwResult != ERROR_SUCCESS)
		goto Cleanup;

	ConvertStringSidToSid(L"S-1-15-2-1", &pSID);
	if (pSID == NULL)
		goto Cleanup;

	ZeroMemory(&eaAccess, sizeof(EXPLICIT_ACCESS));
	eaAccess.grfAccessPermissions = GENERIC_READ | GENERIC_EXECUTE;
	eaAccess.grfAccessMode = SET_ACCESS;
	eaAccess.grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
	eaAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
	eaAccess.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
	eaAccess.Trustee.ptstrName = (LPWSTR)pSID;

	// Create a new ACL that merges the new ACE into the existing DACL.
	dwResult = SetEntriesInAcl(1, &eaAccess, pOldDACL, &pNewDACL);
	if (ERROR_SUCCESS != dwResult)
		goto Cleanup;

	// Attach the new ACL as the object's DACL.
	dwResult = SetNamedSecurityInfo((LPWSTR)wstrFilePath.c_str(), SE_FILE_OBJECT, siInfo, NULL, NULL, pNewDACL, NULL);
	if (ERROR_SUCCESS != dwResult)
		goto Cleanup;

Cleanup:
	if (pSD != NULL)
		LocalFree((HLOCAL)pSD);
	if (pNewDACL != NULL)
		LocalFree((HLOCAL)pNewDACL);

	return dwResult;
}
BOOL SetTokenIL(HANDLE hToken, DWORD dwIntegrityLevel)
{

    BOOL                  fRet = FALSE;
    PSID                  pIntegritySid = NULL;
    TOKEN_MANDATORY_LABEL TIL = { 0 };

    // Low integrity SID
    WCHAR wszIntegritySid[32];

    if (FAILED(StringCbPrintf(wszIntegritySid, sizeof(wszIntegritySid), L"S-1-16-%d", dwIntegrityLevel)))
    {
        printf("Error creating IL SID\n");
        goto CleanExit;
    }

    fRet = ConvertStringSidToSid(wszIntegritySid, &pIntegritySid);

    if (!fRet)
    {
        printf("Error converting IL string %ls\n", GetErrorMessage().c_str());
        goto CleanExit;
    }

    TIL.Label.Attributes = SE_GROUP_INTEGRITY;
    TIL.Label.Sid = pIntegritySid;

    fRet = SetTokenInformation(hToken,
                               TokenIntegrityLevel,
                               &TIL,
                               sizeof(TOKEN_MANDATORY_LABEL) + GetLengthSid(pIntegritySid));

    if (!fRet)
    {
        printf("Error setting IL %d\n", GetLastError());
        goto CleanExit;
    }

CleanExit:

    LocalFree(pIntegritySid);

    return fRet;
}
Exemplo n.º 11
0
PWCHAR kuhl_m_sid_filterFromArgs(int argc, wchar_t * argv[])
{
	PWCHAR filter = NULL;
	PCWCHAR szName;
	DWORD i, sidLen;
	size_t buffLen;
	PSID pSid;

	if(kull_m_string_args_byName(argc, argv, L"sam", &szName, NULL))
	{
		buffLen = wcslen(L"(sAMAccountName=") + wcslen(szName) + wcslen(L")") + 1;
		if(filter = (PWCHAR) LocalAlloc(LPTR, buffLen * sizeof(wchar_t)))
		{
			if(swprintf_s(filter, buffLen, L"(sAMAccountName=%s)", szName) != (buffLen - 1))
				filter = (PWCHAR) LocalFree(filter);
		}
	}
	else if(kull_m_string_args_byName(argc, argv, L"sid", &szName, NULL))
	{
		if(ConvertStringSidToSid(szName, &pSid))
		{
			if(IsValidSid(pSid))
			{
				sidLen = GetLengthSid(pSid);
				buffLen = wcslen(L"(objectSid=") + (sidLen * 3) + wcslen(L")") + 1;
				if(filter = (PWCHAR) LocalAlloc(LPTR, buffLen * sizeof(wchar_t)))
				{
					RtlCopyMemory(filter, L"(objectSid=", sizeof(L"(objectSid="));
					for(i = 0; i < sidLen; i++)
						swprintf_s(filter + ARRAYSIZE(L"(objectSid=") - 1 + (i * 3), 3 + 1, L"\\%02x", ((PBYTE) pSid)[i]);
					filter[buffLen - 2] = L')';
				}
			}
			else PRINT_ERROR(L"Invalid SID\n");
			LocalFree(pSid);
		}
		else PRINT_ERROR_AUTO(L"ConvertStringSidToSid");
	}
	else PRINT_ERROR(L"/sam or /sid to target the account is needed\n");
	
	return filter;
}
Exemplo n.º 12
0
scoped_handle CreateLowboxToken()
{
  PSID package_sid_p;
  if (!ConvertStringSidToSid(L"S-1-15-2-1-1-1-1-1-1-1-1-1-1-1", &package_sid_p))
  {
    printf("[ERROR] creating SID: %d\n", GetLastError());
    return nullptr;
  }
  local_free_ptr package_sid(package_sid_p);

  HANDLE process_token_h;
  if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &process_token_h))
  {
    printf("[ERROR] error opening process token SID: %d\n", GetLastError());
    return nullptr;
  }

  scoped_handle process_token(process_token_h);

  NtCreateLowBoxToken fNtCreateLowBoxToken = (NtCreateLowBoxToken)GetProcAddress(GetModuleHandle(L"ntdll"), "NtCreateLowBoxToken");
  HANDLE lowbox_token_h;
  OBJECT_ATTRIBUTES obja = {};
  obja.Length = sizeof(obja);

  NTSTATUS status = fNtCreateLowBoxToken(&lowbox_token_h, process_token_h, TOKEN_ALL_ACCESS, &obja, package_sid_p, 0, nullptr, 0, nullptr);
  if (status != 0)
  {
    printf("[ERROR] creating lowbox token: %08X\n", status);
    return nullptr;
  }

  scoped_handle lowbox_token(lowbox_token_h);
  HANDLE imp_token;

  if (!DuplicateTokenEx(lowbox_token_h, TOKEN_ALL_ACCESS, nullptr, SecurityImpersonation, TokenImpersonation, &imp_token))
  {
    printf("[ERROR] duplicating lowbox: %d\n", GetLastError());
    return nullptr;
  }

  return scoped_handle(imp_token);
}
Exemplo n.º 13
0
bool SetOwnerInternal(const string& Object, const string& Owner)
{
	bool Result = false;

	PSID Sid = nullptr;
	SCOPE_EXIT { LocalFree(Sid); };

	if(!ConvertStringSidToSid(Owner.data(), &Sid))
	{
		SID_NAME_USE Use;
		DWORD cSid=0, ReferencedDomain=0;
		LookupAccountName(nullptr, Owner.data(), nullptr, &cSid, nullptr, &ReferencedDomain, &Use);
		if(cSid)
		{
			Sid = LocalAlloc(LMEM_FIXED, cSid);
			if(Sid)
			{
				std::vector<wchar_t> ReferencedDomainName(ReferencedDomain);
				if(LookupAccountName(nullptr, Owner.data(), Sid, &cSid, ReferencedDomainName.data(), &ReferencedDomain, &Use))
				{
					;
				}
			}
		}
	}
	if(Sid)
	{
		SCOPED_ACTION(Privilege)(SE_TAKE_OWNERSHIP_NAME);
		SCOPED_ACTION(Privilege)(SE_RESTORE_NAME);
		DWORD dwResult = SetNamedSecurityInfo(const_cast<LPWSTR>(Object.data()), SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION, Sid, nullptr, nullptr, nullptr);
		if(dwResult == ERROR_SUCCESS)
		{
			Result = true;
		}
		else
		{
			SetLastError(dwResult);
		}
	}
	return Result;
}
Exemplo n.º 14
0
BOOL PLUGIN_GENERIC_INITIALIZE(
    _In_ PLUGIN_API_TABLE const * const api
) {
    BOOL bResult = FALSE;
    LPTSTR trustee = api->Common.GetPluginOption(_T("trustee"), TRUE);

    if (_tcsncmp(SID_STR_PREFIX, trustee, strlen(SID_STR_PREFIX)) == 0) {
        bResult = ConvertStringSidToSid(trustee, &gs_TrusteeFilter);
        if (!bResult) {
            API_FATAL(_T("Failed to convert SID <%s> to its binary form : <%u>"), trustee, GetLastError());
        }
        API_LOG(Info, _T("Filtering trustee by SID <%s>"), trustee);
    }
    else {
        // Resolution will take place later since resolver has not been activated yet
        gs_TrusteeDnFilter = trustee;
        API_LOG(Info, _T("Filtering trustee by DN <%s>"), trustee);
    }

    return TRUE;
}
static char * ParseSid(TCHAR * trustee)
{
  PSID pSid = NULL;
  TCHAR * strend = trustee + lstrlen(trustee) - 1;

  if ('(' == *trustee && ')' == *strend)
  {
    *strend = '\0'; 
    ++trustee;

    //pSid = GetBinarySid(trustee);
    if (!ConvertStringSidToSid(trustee, &pSid))
      pSid = NULL;
  }
  else
  {
    DWORD sidLen = 0;
    DWORD domLen = 0;
    TCHAR * domain = NULL;
    SID_NAME_USE use;

    if ((LookupAccountName(NULL, trustee, 
       NULL, &sidLen, NULL, &domLen, &use) ||
       ERROR_INSUFFICIENT_BUFFER == GetLastError()) &&
        NULL != (domain = (TCHAR *)LocalAlloc(LPTR, domLen*sizeof(TCHAR))) &&
      NULL != (pSid = (PSID)LocalAlloc(LPTR, sidLen)))
    {
      if (!LookupAccountName(NULL, trustee, 
        pSid, &sidLen, domain, &domLen, &use))
      {
        LocalFree(pSid);
        pSid = NULL;
      }
    }

    LocalFree(domain);
  }

  return (char *)pSid;
}
Exemplo n.º 16
0
PSID convert_jsstring_to_sid(JSContext * cx, JSString * curMemberString, DWORD * errorCode)
{
	PSID curMember;
	if(!ConvertStringSidToSid((LPWSTR)JS_GetStringChars(curMemberString), &curMember))
	{
		DWORD sidSize = 0, cbDomain;
		SID_NAME_USE peUse;
		*errorCode = GetLastError();
		JS_YieldRequest(cx);
		if(!LookupAccountName(NULL, (LPWSTR)JS_GetStringChars(curMemberString), NULL, &sidSize, NULL, &cbDomain, &peUse) && GetLastError() != ERROR_INSUFFICIENT_BUFFER)
		{
			*errorCode = GetLastError();
			return NULL;
		}
		curMember = (PSID)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sidSize);
		JS_YieldRequest(cx);
		LPTSTR domainName = (LPTSTR)HeapAlloc(GetProcessHeap(), 0, cbDomain * sizeof(TCHAR));
		if(!LookupAccountName(NULL, (LPWSTR)JS_GetStringChars(curMemberString), curMember, &sidSize, domainName, &cbDomain, &peUse))
		{
			*errorCode = GetLastError();
			HeapFree(GetProcessHeap(), 0, curMember);
			HeapFree(GetProcessHeap(), 0, domainName);
			return NULL;
		}
		HeapFree(GetProcessHeap(), 0, domainName);
		*errorCode = ERROR_SUCCESS;
	}
	else
	{
		DWORD sidSize = GetLengthSid(curMember);
		PSID retMember = (PSID)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sidSize);
		CopySid(sidSize, retMember, curMember);
		LocalFree(curMember);
		curMember = retMember;
	}
	return curMember;
}
/** Parses a trustee string. If enclosed in brackets the string contains
 ** a string SID. Otherwise it's assumed that the string contains a
 ** trustee name.
 **/
static TCHAR * ParseTrustee(TCHAR * trustee, DWORD * trusteeForm)
{
  TCHAR * strend = trustee + lstrlen(trustee) - 1;

  if ('(' == *trustee && ')' == *strend)
  {
    PSID pSid = NULL;

    *strend = '\0'; 
    trustee++;

    //pSid = GetBinarySid(trustee);
    if (!ConvertStringSidToSid(trustee, &pSid))
      pSid = NULL;

    *trusteeForm = TRUSTEE_IS_SID;
		return (TCHAR *)pSid;
  }

  *trusteeForm = TRUSTEE_IS_NAME;
  TCHAR * ret = (TCHAR *)LocalAlloc(LPTR, g_string_size*sizeof(TCHAR));
  lstrcpy(ret, trustee);
  return ret;
}
PUBLIC_FUNCTION_END

/*****************************************************************************
 OTHER ACCOUNT RELATED FUNCTIONS
 *****************************************************************************/

PUBLIC_FUNCTION(SidToName)
{
  TCHAR * param = (TCHAR *)LocalAlloc(LPTR, string_size*sizeof(TCHAR));
  PSID pSid;
  SID_NAME_USE eUse;
  TCHAR * name = (TCHAR *)LocalAlloc(LPTR, string_size*sizeof(TCHAR));
  DWORD dwName = string_size;
  TCHAR * domain = (TCHAR *)LocalAlloc(LPTR, string_size*sizeof(TCHAR));
  DWORD dwDomain = string_size;

  popstring(param);
  //pSid = GetBinarySid(param);
  if (!ConvertStringSidToSid(param, &pSid))
    pSid = NULL;

  if (NULL != pSid &&
      !LookupAccountSid(NULL, pSid,
        name, &dwName,
        domain, &dwDomain,
        &eUse))
	  ABORT_d("Cannot look up owner. Error code: %d", GetLastError());

  pushstring(name);
  pushstring(domain);

cleanup:
  LocalFree(domain);
  LocalFree(name);
  LocalFree(param);
}
Exemplo n.º 19
0
NTSTATUS kuhl_m_dpapi_masterkey(int argc, wchar_t * argv[])
{
	PKULL_M_DPAPI_MASTERKEYS masterkeys;
	PBYTE buffer;
	PPVK_FILE_HDR pvkBuffer;
	DWORD szBuffer, szPvkBuffer;

	LPCWSTR szIn = NULL, szSid = NULL, szPassword = NULL, szHash = NULL, szSystem = NULL, szDomainpvk = NULL;
	BOOL isProtected = kull_m_string_args_byName(argc, argv, L"protected", NULL, NULL);
	PWSTR convertedSid = NULL;
	PSID pSid;

	PBYTE pHash = NULL, pSystem = NULL;
	DWORD cbHash = 0, cbSystem = 0;

	PVOID output;
	DWORD cbOutput;

	if(kull_m_string_args_byName(argc, argv, L"in", &szIn, NULL))
	{
		kull_m_string_args_byName(argc, argv, L"sid", &szSid, NULL);
		kull_m_string_args_byName(argc, argv, L"password", &szPassword, NULL);
		kull_m_string_args_byName(argc, argv, L"hash", &szHash, NULL);
		kull_m_string_args_byName(argc, argv, L"system", &szSystem, NULL);
		kull_m_string_args_byName(argc, argv, L"domainpvk", &szDomainpvk, NULL);

		if(kull_m_file_readData(szIn, &buffer, &szBuffer))
		{
			if(masterkeys = kull_m_dpapi_masterkeys_create(buffer))
			{
				//kull_m_dpapi_masterkeys_descr(masterkeys);
				if(szSid)
				{
					if(ConvertStringSidToSid(szSid, &pSid))
					{
						ConvertSidToStringSid(pSid, &convertedSid);
						LocalFree(pSid);
					}
					else PRINT_ERROR_AUTO(L"ConvertStringSidToSid");
				}
				if(szHash)
					kull_m_string_stringToHexBuffer(szHash, &pHash, &cbHash);
				if(szSystem)
					kull_m_string_stringToHexBuffer(szSystem, &pSystem, &cbSystem);

				if(convertedSid)
				{
					if(masterkeys->MasterKey && masterkeys->dwMasterKeyLen)
					{
						if(szPassword)
						{
							kprintf(L"\n[masterkey] with password: %s (%s user)\n", szPassword, isProtected ? L"protected" : L"normal");
							if(kull_m_dpapi_unprotect_masterkey_with_password(masterkeys->dwFlags, masterkeys->MasterKey, szPassword, convertedSid, isProtected, &output, &cbOutput))
								kuhl_m_dpapi_displayInfosAndFree(output, cbOutput, NULL);
							else PRINT_ERROR(L"kull_m_dpapi_unprotect_masterkey_with_password\n");
						}
						if(pHash)
						{
							kprintf(L"\n[masterkey] with hash: "); kull_m_string_wprintf_hex(pHash, cbHash, 0);
							if(cbHash == LM_NTLM_HASH_LENGTH)
								kprintf(L" (ntlm type)\n");
							else if(cbHash == SHA_DIGEST_LENGTH)
								kprintf(L" (sha1 type)\n");
							else 
								kprintf(L" (?)\n");

							if(kull_m_dpapi_unprotect_masterkey_with_userHash(masterkeys->MasterKey, pHash, cbHash, convertedSid, &output, &cbOutput))
								kuhl_m_dpapi_displayInfosAndFree(output, cbOutput, NULL);
							else PRINT_ERROR(L"kull_m_dpapi_unprotect_masterkey_with_userHash\n");
						}
					}
					if(masterkeys->BackupKey && masterkeys->dwBackupKeyLen)
					{
						if(!(masterkeys->dwFlags & 1) || (pSystem && cbSystem))
						{
							kprintf(L"\n[backupkey] %s DPAPI_SYSTEM: ", pSystem ? L"with" : L"without");
							if(pSystem)
								kull_m_string_wprintf_hex(pSystem, cbSystem, 0);
							kprintf(L"\n");

							if(kull_m_dpapi_unprotect_backupkey_with_secret(masterkeys->dwFlags, masterkeys->BackupKey, convertedSid, pSystem, cbSystem, &output, &cbOutput))
								kuhl_m_dpapi_displayInfosAndFree(output, cbOutput, NULL);
							else PRINT_ERROR(L"kull_m_dpapi_unprotect_backupkey_with_secret\n");
						}
					}
					LocalFree(convertedSid);
				}

				if(pHash)
					LocalFree(pHash);
				if(pSystem)
					LocalFree(pSystem);

				if(szDomainpvk && masterkeys->DomainKey && masterkeys->dwDomainKeyLen)
				{
					kprintf(L"\n[domainkey] with RSA private key\n");
					if(kull_m_file_readData(szDomainpvk, (PBYTE *) &pvkBuffer, &szPvkBuffer))
					{
						if(kull_m_dpapi_unprotect_domainkey_with_key(masterkeys->DomainKey, (PBYTE) pvkBuffer + sizeof(PVK_FILE_HDR), pvkBuffer->cbPvk, &output, &cbOutput, &pSid))
							kuhl_m_dpapi_displayInfosAndFree(output, cbOutput, pSid);
						else PRINT_ERROR(L"kull_m_dpapi_unprotect_domainkey_with_key\n");
						LocalFree(pvkBuffer);
					}
				}
				kull_m_dpapi_masterkeys_delete(masterkeys);
			}
			LocalFree(buffer);
		}
	}
	else PRINT_ERROR(L"Input masterkeys file needed (/in:file)\n");
	return STATUS_SUCCESS;
}
Exemplo n.º 20
0
static
VOID
InstallPrivileges(VOID)
{
    HINF hSecurityInf = INVALID_HANDLE_VALUE;
    LSA_OBJECT_ATTRIBUTES ObjectAttributes;
    WCHAR szPrivilegeString[256];
    WCHAR szSidString[256];
    INFCONTEXT InfContext;
    DWORD i;
    PRIVILEGE_SET PrivilegeSet;
    PSID AccountSid;
    NTSTATUS Status;
    LSA_HANDLE PolicyHandle = NULL;
    LSA_HANDLE AccountHandle;

    DPRINT("InstallPrivileges()\n");

    hSecurityInf = SetupOpenInfFileW(L"defltws.inf", //szNameBuffer,
                                     NULL,
                                     INF_STYLE_WIN4,
                                     NULL);
    if (hSecurityInf == INVALID_HANDLE_VALUE)
    {
        DPRINT1("SetupOpenInfFileW failed\n");
        return;
    }

    memset(&ObjectAttributes, 0, sizeof(LSA_OBJECT_ATTRIBUTES));

    Status = LsaOpenPolicy(NULL,
                           &ObjectAttributes,
                           POLICY_CREATE_ACCOUNT,
                           &PolicyHandle);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("LsaOpenPolicy failed (Status %08lx)\n", Status);
        goto done;
    }

    if (!SetupFindFirstLineW(hSecurityInf,
                             L"Privilege Rights",
                             NULL,
                             &InfContext))
    {
        DPRINT1("SetupFindfirstLineW failed\n");
        goto done;
    }

    PrivilegeSet.PrivilegeCount = 1;
    PrivilegeSet.Control = 0;

    do
    {
        /* Retrieve the privilege name */
        if (!SetupGetStringFieldW(&InfContext,
                                  0,
                                  szPrivilegeString,
                                  256,
                                  NULL))
        {
            DPRINT1("SetupGetStringFieldW() failed\n");
            goto done;
        }
        DPRINT("Privilege: %S\n", szPrivilegeString);

        if (!LookupPrivilegeValueW(NULL,
                                   szPrivilegeString,
                                   &(PrivilegeSet.Privilege[0].Luid)))
        {
            DPRINT1("LookupPrivilegeNameW() failed\n");
            goto done;
        }

        PrivilegeSet.Privilege[0].Attributes = 0;

        for (i = 0; i < SetupGetFieldCount(&InfContext); i++)
        {
            if (!SetupGetStringFieldW(&InfContext,
                                      i + 1,
                                      szSidString,
                                      256,
                                      NULL))
            {
                DPRINT1("SetupGetStringFieldW() failed\n");
                goto done;
            }
            DPRINT("SID: %S\n", szSidString);

            ConvertStringSidToSid(szSidString, &AccountSid);

            Status = LsaOpenAccount(PolicyHandle,
                                    AccountSid,
                                    ACCOUNT_VIEW | ACCOUNT_ADJUST_PRIVILEGES,
                                    &AccountHandle);
            if (NT_SUCCESS(Status))
            {
                Status = LsaAddPrivilegesToAccount(AccountHandle,
                                                   &PrivilegeSet);
                if (!NT_SUCCESS(Status))
                {
                    DPRINT1("LsaAddPrivilegesToAccount() failed (Status %08lx)\n", Status);
                }

                LsaClose(AccountHandle);
            }

            LocalFree(AccountSid);
        }

    }
    while (SetupFindNextLine(&InfContext, &InfContext));

done:
    if (PolicyHandle != NULL)
        LsaClose(PolicyHandle);

    if (hSecurityInf != INVALID_HANDLE_VALUE)
        SetupCloseInfFile(hSecurityInf);
}
Exemplo n.º 21
0
/////////////////////////////////////////////////////////////////////
// 
// Function:    
//
// Description: 
//
/////////////////////////////////////////////////////////////////////
UINT CACreateBOINCGroups::OnExecution()
{
    NET_API_STATUS   nasReturnValue;
    DWORD            dwParameterError;
    UINT             uiReturnValue = -1;
    BOOL             bBOINCAdminsCreated = FALSE;
    BOOL             bBOINCUsersCreated = FALSE;
    BOOL             bBOINCProjectsCreated = FALSE;
    tstring          strUserSID;
    tstring          strUsersGroupName;
    tstring          strBOINCMasterAccountUsername;
    tstring          strBOINCProjectAccountUsername;
    tstring          strEnableProtectedApplicationExecution;
    PSID             pAdminSID = NULL;
    PSID             pInstallingUserSID = NULL;
    PSID             pBOINCMasterSID = NULL;
    PSID             pBOINCProjectSID = NULL;
    SID_IDENTIFIER_AUTHORITY SIDAuthNT = SECURITY_NT_AUTHORITY;


    uiReturnValue = GetProperty( _T("UserSID"), strUserSID );
    if ( uiReturnValue ) return uiReturnValue;

    uiReturnValue = GetProperty( _T("GROUPALIAS_USERS"), strUsersGroupName );
    if ( uiReturnValue ) return uiReturnValue;

    uiReturnValue = GetProperty( _T("BOINC_MASTER_USERNAME"), strBOINCMasterAccountUsername );
    if ( uiReturnValue ) return uiReturnValue;

    uiReturnValue = GetProperty( _T("BOINC_PROJECT_USERNAME"), strBOINCProjectAccountUsername );
    if ( uiReturnValue ) return uiReturnValue;

    uiReturnValue = GetProperty( _T("ENABLEPROTECTEDAPPLICATIONEXECUTION2"), strEnableProtectedApplicationExecution );
    if ( uiReturnValue ) return uiReturnValue;


    // Create a SID for the BUILTIN\Administrators group.
    if(!AllocateAndInitializeSid(
                     &SIDAuthNT, 2,
                     SECURITY_BUILTIN_DOMAIN_RID,
                     DOMAIN_ALIAS_RID_ADMINS,
                     0, 0, 0, 0, 0, 0,
                     &pAdminSID)) 
    {
        LogMessage(
            INSTALLMESSAGE_ERROR,
            NULL, 
            NULL,
            NULL,
            GetLastError(),
            _T("AllocateAndInitializeSid Error for BUILTIN\\Administrators")
        );
        return ERROR_INSTALL_FAILURE;
    }

    // Create a SID for the current logged in user.
    if(!ConvertStringSidToSid(strUserSID.c_str(), &pInstallingUserSID)) 
    {
        LogMessage(
            INSTALLMESSAGE_ERROR,
            NULL, 
            NULL,
            NULL,
            GetLastError(),
            _T("ConvertStringSidToSid Error for installing user")
        );
        return ERROR_INSTALL_FAILURE;
    }

    // Create a SID for the 'boinc_master' user account.
    if (_T("1") == strEnableProtectedApplicationExecution) {

        if(!GetAccountSid(NULL, strBOINCMasterAccountUsername.c_str(), &pBOINCMasterSID))
        {
            LogMessage(
                INSTALLMESSAGE_ERROR,
                NULL, 
                NULL,
                NULL,
                GetLastError(),
                _T("GetAccountSid Error for 'boinc_master' user account")
            );
            return ERROR_INSTALL_FAILURE;
        }

    }

    // Create a SID for the 'boinc_project' user account.
    if (_T("1") == strEnableProtectedApplicationExecution) {

        if(!GetAccountSid(NULL, strBOINCProjectAccountUsername.c_str(), &pBOINCProjectSID))
        {
            LogMessage(
                INSTALLMESSAGE_ERROR,
                NULL, 
                NULL,
                NULL,
                GetLastError(),
                _T("GetAccountSid Error for 'boinc_master' user account")
            );
            return ERROR_INSTALL_FAILURE;
        }

    }


    // Create the 'boinc_admins' group if needed
    //
    LOCALGROUP_INFO_1 lgrpiAdmins;

    lgrpiAdmins.lgrpi1_name = _T("boinc_admins");
    lgrpiAdmins.lgrpi1_comment = _T("Accounts in this group can control the BOINC client.");

    nasReturnValue = NetLocalGroupAdd(
        NULL,
        1,
        (LPBYTE)&lgrpiAdmins,
        &dwParameterError
    );

    if ((NERR_Success != nasReturnValue) && (ERROR_ALIAS_EXISTS != nasReturnValue)) {
        LogMessage(
            INSTALLMESSAGE_INFO,
            NULL, 
            NULL,
            NULL,
            nasReturnValue,
            _T("NetLocalGroupAdd retval")
        );
        LogMessage(
            INSTALLMESSAGE_ERROR,
            NULL, 
            NULL,
            NULL,
            nasReturnValue,
            _T("Failed to create the 'boinc_admins' group.")
        );
        return ERROR_INSTALL_FAILURE;
    }

    if (NERR_Success == nasReturnValue) {
        bBOINCAdminsCreated = TRUE;
    }

    // If we just created the 'boinc_admins' local group then we need to populate
    //   it with the default accounts.
    LOCALGROUP_MEMBERS_INFO_0    lgrmiAdmins;
    lgrmiAdmins.lgrmi0_sid = pAdminSID;

    nasReturnValue = NetLocalGroupAddMembers(
        NULL,
        _T("boinc_admins"),
        0,
        (LPBYTE)&lgrmiAdmins,
        1
    );

    if ((NERR_Success != nasReturnValue) && (ERROR_MEMBER_IN_ALIAS != nasReturnValue)) {
        LogMessage(
            INSTALLMESSAGE_INFO,
            NULL, 
            NULL,
            NULL,
            nasReturnValue,
            _T("NetLocalGroupAddMembers retval")
        );
        LogMessage(
            INSTALLMESSAGE_ERROR,
            NULL, 
            NULL,
            NULL,
            nasReturnValue,
            _T("Failed to add user to the 'boinc_admins' group (Administrator).")
        );
        return ERROR_INSTALL_FAILURE;
    }

    lgrmiAdmins.lgrmi0_sid = pInstallingUserSID;

    nasReturnValue = NetLocalGroupAddMembers(
        NULL,
        _T("boinc_admins"),
        0,
        (LPBYTE)&lgrmiAdmins,
        1
    );

    if ((NERR_Success != nasReturnValue) && (ERROR_MEMBER_IN_ALIAS != nasReturnValue)) {
        LogMessage(
            INSTALLMESSAGE_INFO,
            NULL, 
            NULL,
            NULL,
            nasReturnValue,
            _T("NetLocalGroupAddMembers retval")
        );
        LogMessage(
            INSTALLMESSAGE_ERROR,
            NULL, 
            NULL,
            NULL,
            nasReturnValue,
            _T("Failed to add user to the 'boinc_admins' group (Installing User).")
        );
        return ERROR_INSTALL_FAILURE;
    }

    if (_T("1") == strEnableProtectedApplicationExecution) {

        lgrmiAdmins.lgrmi0_sid = pBOINCMasterSID;

        nasReturnValue = NetLocalGroupAddMembers(
            NULL,
            _T("boinc_admins"),
            0,
            (LPBYTE)&lgrmiAdmins,
            1
        );

        if ((NERR_Success != nasReturnValue) && (ERROR_MEMBER_IN_ALIAS != nasReturnValue)) {
            LogMessage(
                INSTALLMESSAGE_INFO,
                NULL, 
                NULL,
                NULL,
                nasReturnValue,
                _T("NetLocalGroupAddMembers retval")
            );
            LogMessage(
                INSTALLMESSAGE_ERROR,
                NULL, 
                NULL,
                NULL,
                nasReturnValue,
                _T("Failed to add user to the 'boinc_admins' group (BOINC Master).")
            );
            return ERROR_INSTALL_FAILURE;
        }

    }


    // Create the 'boinc_users' group if needed
    //
    LOCALGROUP_INFO_1 lgrpiUsers;

    lgrpiUsers.lgrpi1_name = _T("boinc_users");
    lgrpiUsers.lgrpi1_comment = _T("Accounts in this group can monitor the BOINC client.");

    nasReturnValue = NetLocalGroupAdd(
        NULL,
        1,
        (LPBYTE)&lgrpiUsers,
        &dwParameterError
    );

    if ((NERR_Success != nasReturnValue) && (ERROR_ALIAS_EXISTS != nasReturnValue)) {
        LogMessage(
            INSTALLMESSAGE_INFO,
            NULL, 
            NULL,
            NULL,
            nasReturnValue,
            _T("NetLocalGroupAdd retval")
        );
        LogMessage(
            INSTALLMESSAGE_ERROR,
            NULL, 
            NULL,
            NULL,
            nasReturnValue,
            _T("Failed to create the 'boinc_users' group.")
        );
        return ERROR_INSTALL_FAILURE;
    }

    if (NERR_Success == nasReturnValue) {
        bBOINCUsersCreated = TRUE;
    }


    // Create the 'boinc_project' group if needed
    //
    LOCALGROUP_INFO_1 lgrpiProjects;

    lgrpiProjects.lgrpi1_name = _T("boinc_projects");
    lgrpiProjects.lgrpi1_comment = _T("Accounts in this group are used to execute boinc applications.");

    nasReturnValue = NetLocalGroupAdd(
        NULL,
        1,
        (LPBYTE)&lgrpiProjects,
        &dwParameterError
    );

    if ((NERR_Success != nasReturnValue) && (ERROR_ALIAS_EXISTS != nasReturnValue)) {
        LogMessage(
            INSTALLMESSAGE_INFO,
            NULL, 
            NULL,
            NULL,
            nasReturnValue,
            _T("NetLocalGroupAdd retval")
        );
        LogMessage(
            INSTALLMESSAGE_ERROR,
            NULL, 
            NULL,
            NULL,
            nasReturnValue,
            _T("Failed to create the 'boinc_projects' group.")
        );
        return ERROR_INSTALL_FAILURE;
    }

    if (NERR_Success == nasReturnValue) {
        bBOINCProjectsCreated = TRUE;
    }

    // If the user has enabled protected application execution then we need to add the 'boinc_project'
    //   account to the local group and the 'Users' local group.  As an aside 'boinc_master' is also added
    //   to the 'Users' group.
    if (_T("1") == strEnableProtectedApplicationExecution) {

        LOCALGROUP_MEMBERS_INFO_0    lgrmiMembers;

        lgrmiMembers.lgrmi0_sid = pBOINCProjectSID;

        nasReturnValue = NetLocalGroupAddMembers(
            NULL,
            _T("boinc_projects"),
            0,
            (LPBYTE)&lgrmiMembers,
            1
        );

        if ((NERR_Success != nasReturnValue) && (ERROR_MEMBER_IN_ALIAS != nasReturnValue)) {
            LogMessage(
                INSTALLMESSAGE_INFO,
                NULL, 
                NULL,
                NULL,
                nasReturnValue,
                _T("NetLocalGroupAddMembers retval")
            );
            LogMessage(
                INSTALLMESSAGE_ERROR,
                NULL, 
                NULL,
                NULL,
                nasReturnValue,
                _T("Failed to add user to the 'boinc_projects' group (boinc_project).")
            );
            return ERROR_INSTALL_FAILURE;
        }

        nasReturnValue = NetLocalGroupAddMembers(
            NULL,
            strUsersGroupName.c_str(),
            0,
            (LPBYTE)&lgrmiMembers,
            1
        );

        if ((NERR_Success != nasReturnValue) && (ERROR_MEMBER_IN_ALIAS != nasReturnValue)) {
            LogMessage(
                INSTALLMESSAGE_INFO,
                NULL, 
                NULL,
                NULL,
                nasReturnValue,
                _T("NetLocalGroupAddMembers retval")
            );
            LogMessage(
                INSTALLMESSAGE_ERROR,
                NULL, 
                NULL,
                NULL,
                nasReturnValue,
                _T("Failed to add user to the 'Users' group (boinc_project).")
            );
            return ERROR_INSTALL_FAILURE;
        }

        lgrmiMembers.lgrmi0_sid = pBOINCMasterSID;

        nasReturnValue = NetLocalGroupAddMembers(
            NULL,
            strUsersGroupName.c_str(),
            0,
            (LPBYTE)&lgrmiMembers,
            1
        );

        if ((NERR_Success != nasReturnValue) && (ERROR_MEMBER_IN_ALIAS != nasReturnValue)) {
            LogMessage(
                INSTALLMESSAGE_INFO,
                NULL, 
                NULL,
                NULL,
                nasReturnValue,
                _T("NetLocalGroupAddMembers retval")
            );
            LogMessage(
                INSTALLMESSAGE_ERROR,
                NULL, 
                NULL,
                NULL,
                nasReturnValue,
                _T("Failed to add user to the 'Users' group (boinc_master).")
            );
            return ERROR_INSTALL_FAILURE;
        }
    }

    SetProperty( _T("BOINC_ADMINS_GROUPNAME"), _T("boinc_admins") );
    SetProperty( _T("BOINC_USERS_GROUPNAME"), _T("boinc_users") );
    SetProperty( _T("BOINC_PROJECTS_GROUPNAME"), _T("boinc_projects") );

    if (bBOINCAdminsCreated || bBOINCUsersCreated || bBOINCProjectsCreated) {
        RebootWhenFinished();
    }

    if(pAdminSID != NULL) FreeSid(pAdminSID);
    if(pInstallingUserSID != NULL) FreeSid(pInstallingUserSID);
    if(pBOINCMasterSID != NULL) FreeSid(pBOINCMasterSID);
    if(pBOINCProjectSID != NULL) FreeSid(pBOINCProjectSID);

    return ERROR_SUCCESS;
}
Exemplo n.º 22
0
int _tmain(int argc, TCHAR *argv[])
{
   BOOL bResult;
   NTSTATUS Status;
   NTSTATUS SubStatus;

   HANDLE hLsa = NULL;
   HANDLE hProcess = NULL;
   HANDLE hToken = NULL;
   HANDLE hTokenS4U = NULL;

   LSA_STRING Msv1_0Name = { 0 };
   LSA_STRING OriginName = { 0 };
   PMSV1_0_S4U_LOGON pS4uLogon = NULL;
   TOKEN_SOURCE TokenSource;
   ULONG ulAuthenticationPackage;
   DWORD dwMessageLength;

   PBYTE pbPosition;

   PROCESS_INFORMATION pi = { 0 };
   STARTUPINFO si = { 0 };

   PTOKEN_GROUPS pGroups = NULL;
   PSID pLogonSid = NULL;
   PSID pExtraSid = NULL;

   PVOID pvProfile = NULL;
   DWORD dwProfile = 0;
   LUID logonId = { 0 };
   QUOTA_LIMITS quotaLimits;

   LPTSTR szCommandLine = NULL;
   LPTSTR szSrcCommandLine = TEXT("%systemroot%\\system32\\cmd.exe");
   LPTSTR szDomain = NULL;
   LPTSTR szUsername = NULL;
   TCHAR seps[] = TEXT("\\");
   TCHAR *next_token = NULL;

   g_hHeap = GetProcessHeap();

   if (argc < 2)
   {
      fprintf(stderr, "Usage:\n   s4u.exe Domain\\Username [Extra SID]\n\n");
      goto End;
   }

   //
   // Get DOMAIN and USERNAME from command line.
   //
   szDomain = _tcstok_s(argv[1], seps, &next_token);
   if (szDomain == NULL)
   {
      fprintf(stderr, "Unable to parse command line.\n");
      goto End;
   }

   szUsername = _tcstok_s(NULL, seps, &next_token);
   if (szUsername == NULL)
   {
      fprintf(stderr, "Unable to parse command line.\n");
      goto End;
   }

   //
   // Activate the TCB privilege
   //
   hProcess = GetCurrentProcess();
   OpenProcessToken(hProcess, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken);
   if (!SetPrivilege(hToken, SE_TCB_NAME, TRUE))
   {
      goto End;
   }

   //
   // Get logon SID
   //
   if (!GetLogonSID(hToken, &pLogonSid))
   {
      fprintf(stderr, "Unable to find logon SID.\n");
      goto End;
   }

   //
   // Connect (Untrusted) to LSA
   //
   Status = LsaConnectUntrusted(&hLsa);
   if (Status!=STATUS_SUCCESS)
   {
      fprintf(stderr, "LsaConnectUntrusted failed (error 0x%x).", Status);
      hLsa = NULL;
      goto End;
   }

   //
   // Lookup for the MSV1_0 authentication package (NTLMSSP)
   //
   InitLsaString(&Msv1_0Name, MSV1_0_PACKAGE_NAME);
   Status = LsaLookupAuthenticationPackage(hLsa, &Msv1_0Name, &ulAuthenticationPackage);
   if (Status!=STATUS_SUCCESS)
   {
      fprintf(stderr, "LsaLookupAuthenticationPackage failed (error 0x%x).", Status);
      hLsa = NULL;
      goto End;
   }

   //
   // Create MSV1_0_S4U_LOGON structure
   //
   dwMessageLength = sizeof(MSV1_0_S4U_LOGON) + (2 + wcslen(szDomain) + wcslen(szUsername)) * sizeof(WCHAR);
   pS4uLogon = (PMSV1_0_S4U_LOGON)HeapAlloc(g_hHeap, HEAP_ZERO_MEMORY, dwMessageLength);
   if (pS4uLogon == NULL)
   {
      fprintf(stderr, "HeapAlloc failed (error %u).", GetLastError());
      goto End;
   }

   pS4uLogon->MessageType = MsV1_0S4ULogon;
   pbPosition = (PBYTE)pS4uLogon + sizeof(MSV1_0_S4U_LOGON);
   pbPosition = InitUnicodeString(&pS4uLogon->UserPrincipalName, szUsername, pbPosition);
   pbPosition = InitUnicodeString(&pS4uLogon->DomainName, szDomain, pbPosition);

   //
   // Misc
   //
   strcpy_s(TokenSource.SourceName, TOKEN_SOURCE_LENGTH, "S4UWin");
   InitLsaString(&OriginName, "S4U for Windows");
   AllocateLocallyUniqueId(&TokenSource.SourceIdentifier);

   //
   // Add extra SID to token.
   //
   // If the application needs to connect to a Windows Desktop, Logon SID must be added to the Token.
   //
   pGroups = (PTOKEN_GROUPS)HeapAlloc(g_hHeap, HEAP_ZERO_MEMORY, sizeof(TOKEN_GROUPS) + 2*sizeof(SID_AND_ATTRIBUTES));
   if (pGroups == NULL)
   {
      fprintf(stderr, "HeapAlloc failed (error %u).", GetLastError());
      goto End;
   }

   pGroups->GroupCount = 1;
   pGroups->Groups[0].Attributes = SE_GROUP_ENABLED | SE_GROUP_ENABLED_BY_DEFAULT | SE_GROUP_MANDATORY;
   pGroups->Groups[0].Sid = pLogonSid;

   //
   // If an extra SID is specified to command line, add it to the pGroups structure.
   //
   if (argc==3)
   {
      bResult = ConvertStringSidToSid(argv[2], &pExtraSid);

      if (bResult == TRUE)
      {
         pGroups->GroupCount = 2;
         pGroups->Groups[1].Attributes = SE_GROUP_ENABLED | SE_GROUP_ENABLED_BY_DEFAULT | SE_GROUP_MANDATORY;
         pGroups->Groups[1].Sid = pExtraSid;
      }
      else
      {
         fprintf(stderr, "Unable to convert SID (error %u).", GetLastError());
      }
   }

   //
   // Call LSA
   //
   Status = LsaLogonUser(
      hLsa,
      &OriginName,
      Network,                // Or Batch
      ulAuthenticationPackage,
      pS4uLogon,
      dwMessageLength,
      pGroups,                // LocalGroups
      &TokenSource,           // SourceContext
      &pvProfile,
      &dwProfile,
      &logonId,
      &hTokenS4U,
      &quotaLimits,
      &SubStatus
      );
   if (Status!=STATUS_SUCCESS)
   {
      printf("LsaLogonUser failed (error 0x%x).\n", Status);
      goto End;
   }

   printf("LsaLogonUser: OK, LogonId: 0x%x-0x%x\n", logonId.HighPart, logonId.LowPart);

   //
   // Create process with S4U token.
   //
   si.cb = sizeof(STARTUPINFO);
   si.lpDesktop = TEXT("winsta0\\default");

   //
   // Warning: szCommandLine parameter of CreateProcessAsUser() must be writable
   //
   szCommandLine = (LPTSTR)HeapAlloc(g_hHeap, HEAP_ZERO_MEMORY, MAX_PATH * sizeof(TCHAR));
   if (szCommandLine == NULL)
   {
      fprintf(stderr, "HeapAlloc failed (error %u).", GetLastError());
      goto End;
   }

   if (ExpandEnvironmentStrings(szSrcCommandLine, szCommandLine, MAX_PATH) == 0)
   {
      fprintf(stderr, "ExpandEnvironmentStrings failed (error %u).", GetLastError());
      goto End;
   }

   //
   // CreateProcessAsUser required SeAssignPrimaryTokenPrivilege but no need to be activated.
   //
   bResult = CreateProcessAsUser(
      hTokenS4U,
      NULL,
      szCommandLine,
      NULL,
      NULL,
      FALSE,
      NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE,
      NULL,
      TEXT("c:\\"),
      &si,
      &pi
      );
   if (bResult == FALSE)
   {
      printf("CreateProcessAsUser failed (error %u).\n", GetLastError());
      goto End;
   }

End:
   //
   // Free resources
   //
   if (Msv1_0Name.Buffer)
      HeapFree(g_hHeap, 0, Msv1_0Name.Buffer);
   if (OriginName.Buffer)
      HeapFree(g_hHeap, 0, OriginName.Buffer);
   if (pLogonSid)
      HeapFree(g_hHeap, 0, pLogonSid);
   if (pExtraSid)
      LocalFree(pExtraSid);
   if (pS4uLogon)
      HeapFree(g_hHeap, 0, pS4uLogon);
   if (pGroups)
      HeapFree(g_hHeap, 0, pGroups);
   if (pvProfile)
      LsaFreeReturnBuffer(pvProfile);
   if (hLsa)
      LsaClose(hLsa);
   if (hToken)
      CloseHandle(hToken);
   if (hTokenS4U)
      CloseHandle(hTokenS4U);
   if (pi.hProcess)
      CloseHandle(pi.hProcess);
   if (pi.hThread)
      CloseHandle(pi.hThread);

   return EXIT_SUCCESS;
}
Exemplo n.º 23
0
int main(int argc, const char **argv)
{
	NET_API_STATUS status;
	struct libnetapi_ctx *ctx = NULL;
	const char *hostname = NULL;
	const char *groupname = NULL;
	struct LOCALGROUP_MEMBERS_INFO_0 *g0;
	struct LOCALGROUP_MEMBERS_INFO_3 *g3;
	uint32_t total_entries = 0;
	uint8_t *buffer = NULL;
	uint32_t level = 3;
	const char **names = NULL;
	int i = 0;

	poptContext pc;
	int opt;

	struct poptOption long_options[] = {
		POPT_AUTOHELP
		POPT_COMMON_LIBNETAPI_EXAMPLES
		POPT_TABLEEND
	};

	status = libnetapi_init(&ctx);
	if (status != 0) {
		return status;
	}

	pc = poptGetContext("localgroup_addmembers", argc, argv, long_options, 0);

	poptSetOtherOptionHelp(pc, "hostname groupname member1 member2 ...");
	while((opt = poptGetNextOpt(pc)) != -1) {
	}

	if (!poptPeekArg(pc)) {
		poptPrintHelp(pc, stderr, 0);
		goto out;
	}
	hostname = poptGetArg(pc);

	if (!poptPeekArg(pc)) {
		poptPrintHelp(pc, stderr, 0);
		goto out;
	}
	groupname = poptGetArg(pc);

	if (!poptPeekArg(pc)) {
		poptPrintHelp(pc, stderr, 0);
		goto out;
	}

	names = poptGetArgs(pc);
	for (i=0; names[i] != NULL; i++) {
		total_entries++;
	}

	switch (level) {
		case 0:
			status = NetApiBufferAllocate(sizeof(struct LOCALGROUP_MEMBERS_INFO_0) * total_entries,
						      (void **)&g0);
			if (status) {
				printf("NetApiBufferAllocate failed with: %s\n",
					libnetapi_get_error_string(ctx, status));
				goto out;
			}

			for (i=0; i<total_entries; i++) {
				if (!ConvertStringSidToSid(names[i], &g0[i].lgrmi0_sid)) {
					printf("could not convert sid\n");
					goto out;
				}
			}

			buffer = (uint8_t *)g0;
			break;
		case 3:
			status = NetApiBufferAllocate(sizeof(struct LOCALGROUP_MEMBERS_INFO_3) * total_entries,
						      (void **)&g3);
			if (status) {
				printf("NetApiBufferAllocate failed with: %s\n",
					libnetapi_get_error_string(ctx, status));
				goto out;
			}

			for (i=0; i<total_entries; i++) {
				g3[i].lgrmi3_domainandname = names[i];
			}

			buffer = (uint8_t *)g3;
			break;
		default:
			break;
	}

	/* NetLocalGroupAddMembers */

	status = NetLocalGroupAddMembers(hostname,
					 groupname,
					 level,
					 buffer,
					 total_entries);
	if (status != 0) {
		printf("NetLocalGroupAddMembers failed with: %s\n",
			libnetapi_get_error_string(ctx, status));
	}

 out:
	libnetapi_free(ctx);
	poptFreeContext(pc);

	return status;
}
Exemplo n.º 24
0
void setSecurityACLs()
{
	CString fullPath = getPathToCurrentExeContainer();
	// Check to make sure that the dll has the ACLs to load in an appcontainer
	// We're doing this here as the adapter has no setup script and should be xcopy deployable/removeable

	PACL pOldDACL = NULL, pNewDACL = NULL;
	PSECURITY_DESCRIPTOR pSD = NULL;
	EXPLICIT_ACCESS ea;
	SECURITY_INFORMATION si = DACL_SECURITY_INFORMATION;

	// The check is done on the folder and should be inherited to all objects
	DWORD dwRes = GetNamedSecurityInfo(fullPath, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &pOldDACL, NULL, &pSD);

	// Get the SID for "ALL APPLICATION PACAKGES" since it is localized
	PSID pAllAppPackagesSID = NULL;
	bool bResult = ConvertStringSidToSid(L"S-1-15-2-1", &pAllAppPackagesSID);

	if (bResult)
	{
		// Initialize an EXPLICIT_ACCESS structure for the new ACE. 
		ZeroMemory(&ea, sizeof(EXPLICIT_ACCESS));
		ea.grfAccessPermissions = GENERIC_READ | GENERIC_EXECUTE;
		ea.grfAccessMode = SET_ACCESS;
		ea.grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
		ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;;
		ea.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
		ea.Trustee.ptstrName = (LPTSTR)pAllAppPackagesSID;

		// Create a new ACL that merges the new ACE into the existing DACL.
		dwRes = SetEntriesInAcl(1, &ea, pOldDACL, &pNewDACL);
		if (dwRes == ERROR_SUCCESS)
		{
			dwRes = SetNamedSecurityInfo(fullPath.GetBuffer(), SE_FILE_OBJECT, si, NULL, NULL, pNewDACL, NULL);
			if (dwRes == ERROR_SUCCESS)
			{

			}
			else
			{
				// The ACL was not set, this isn't fatal as it only impacts IE in EPM and Edge and the user can set it manually
				wcout << L"Could not set ACL to allow access to IE EPM or Edge.";
				wcout << L"\n";
				wcout << Helpers::GetLastErrorMessage().GetBuffer();
				wcout << L"\n";
				wcout << L"You can set the ACL manually by adding Read & Execute permissions for 'All APPLICATION PACAKGES' to each dll.";
				wcout << L"\n";
			}
		}
	}
	else
	{
		std::cerr << "Failed to get the SID for ALL_APP_PACKAGES." << std::endl;
		std::cerr << "Win32 error code: " << GetLastError() << std::endl;
	}

	if (pAllAppPackagesSID != NULL)
	{
		LocalFree(pAllAppPackagesSID);
	}

	if (pSD != NULL)
	{
		LocalFree((HLOCAL)pSD);
	}
	if (pNewDACL != NULL)
	{
		LocalFree((HLOCAL)pNewDACL);
	}
}
Exemplo n.º 25
0
Arquivo: ms11013.c Projeto: OJ/kekeo
int main(int argc, char * argv[])
{
	EncryptionKey userKey;
	LPCSTR szUser, szDomain, szTarget, szService, szPassword = NULL, szKey = NULL, szSid, szRid, szKdc = NULL, szFilename = NULL;
	PSID sid = NULL, domainSid = NULL;
	DWORD ret, rid = 0;
	PDOMAIN_CONTROLLER_INFO cInfo = NULL;

	kprintf("\n"
		"  .#####.   " MIMIKATZ_FULL "\n"
		" .## ^ ##.  \n"
		" ## / \\ ##  /* * *\n"
		" ## \\ / ##   Benjamin DELPY `gentilkiwi` ( [email protected] )\n"
		" '## v ##'   http://blog.gentilkiwi.com                      (oe.eo)\n"
		"  '#####'    ...   with thanks to Tom Maddock & Sylvain Monne * * */\n\n");
	
	if(init())
	{
		if(!kull_m_string_args_byName(argc, argv, "ptt", NULL, NULL))
			kull_m_string_args_byName(argc, argv, "ticket", &szFilename, TICKET_FILENAME);

		if(kull_m_string_args_byName(argc, argv, "target", &szTarget, NULL))
		{
			if(kull_m_string_args_byName(argc, argv, "service", &szService, NULL))
			{
				if(kull_m_string_args_byName(argc, argv, "user", &szUser, NULL))
				{
					if(kull_m_string_args_byName(argc, argv, "domain", &szDomain, NULL))
					{
						if(kull_m_string_args_byName(argc, argv, "key", &szKey, NULL) || kull_m_string_args_byName(argc, argv, "password", &szPassword, NULL))
						{
							if(kull_m_string_args_byName(argc, argv, "aes256", NULL, NULL))
								userKey.keytype = KERB_ETYPE_AES256_CTS_HMAC_SHA1_96;
							else if(kull_m_string_args_byName(argc, argv, "aes128", NULL, NULL))
								userKey.keytype = KERB_ETYPE_AES128_CTS_HMAC_SHA1_96;
							else
								userKey.keytype = KERB_ETYPE_RC4_HMAC_NT;

							if(NT_SUCCESS(kull_m_kerberos_asn1_helper_util_stringToKey(szUser, szDomain, szPassword, szKey, &userKey)))
							{
								if(!kull_m_string_args_byName(argc, argv, "kdc", &szKdc, NULL))
								{
									ret = DsGetDcName(NULL, szDomain, NULL, NULL, DS_IS_DNS_NAME | DS_RETURN_DNS_NAME, &cInfo);
									if(ret == ERROR_SUCCESS)
									{
										szKdc = cInfo->DomainControllerName + 2;
										kprintf("[KDC] \'%s\' will be the main server\n", szKdc);
									}
									else PRINT_ERROR("[KDC] DsGetDcName: %u\n", ret);
								}

								if(szKdc)
								{
									if(kull_m_string_args_byName(argc, argv, "sid", &szSid, NULL) && kull_m_string_args_byName(argc, argv, "rid", &szRid, NULL))
									{
										if(ConvertStringSidToSid(szSid, &sid))
											rid = strtoul(szRid, NULL, 0);
										else PRINT_ERROR_AUTO("ConvertStringSidToSid");
									}

									if(!(sid && rid))
									{
										if(szPassword)
										{
#pragma warning(push)
#pragma warning(disable:4996)
											impersonateToGetData(szUser, szDomain, szPassword, szKdc,&sid, &rid, _pgmptr);
#pragma warning(pop)
										}
										else PRINT_ERROR("Impersonate is only supported with a password (you need KDC, SID & RID)\n");
									}

									if(sid && rid)
									{
										kprintf("\n"
											"user     : %s\n"
											"domain   : %s\n"
											"password : %s\n"
											"sid      : "
											, szUser, szDomain, szKey ? "<NULL>" : "***");
										kull_m_string_displaySID(sid);
										kprintf("\n"
											"target   : %s\n"
											"service  : %s\n"
											"rid      : %u\n"
											"key      : "
											, szTarget, szService, rid);
										kull_m_string_printf_hex(userKey.keyvalue.value, userKey.keyvalue.length, 0);
										kprintf(" (%s)\n"
											"ticket   : %s\n"
											, kull_m_kerberos_asn1_helper_util_etypeToString(userKey.keytype), szFilename ? szFilename : "** Pass The Ticket **");

										if(szKdc)
										{
											kprintf("kdc      : %s\n\n", szKdc);
											makeInception(szUser, szDomain, sid, rid, szTarget, szService, &userKey, szKdc, 88, szFilename);
										}
										else PRINT_ERROR("No KDC at all\n");

										LocalFree(sid);
									}
									else PRINT_ERROR("Missing valid SID & RID (argument or auto)\n");
								}
								else PRINT_ERROR("Missing one valid DC (argument or auto)\n");

								if(cInfo)
									NetApiBufferFree(cInfo);

								LocalFree(userKey.keyvalue.value);
							}
						}
						else PRINT_ERROR("Missing password/key argument\n");
					}
					else PRINT_ERROR("Missing domain argument\n");
				}
				else PRINT_ERROR("Missing user argument\n");
			}
			else PRINT_ERROR("Missing service argument\n");
		}
		else PRINT_ERROR("Missing target argument\n");
	}
	else PRINT_ERROR("init() failed\n");
	term();
	return 0;
}