Exemple #1
0
bool DebugToken::Enable()
{
	if (enabled || hDebugToken == NULL)
		return true;

	BOOL rc = OpenThreadToken(GetCurrentThread(), TOKEN_IMPERSONATE, TRUE, &hSavedToken);

	if (!rc)
	{
		hSavedToken = NULL;

		if (GetLastError()==ERROR_NO_TOKEN)
			rc = ERROR_SUCCESS;
		else
			return false;
	}

	rc = SetThreadToken(NULL, hDebugToken);

	if (!rc)
	{
		if (hSavedToken != NULL)
		{
			CloseHandle(hSavedToken);
			hSavedToken = NULL;
		}

		return false;
	}

	enabled = true;
	return true;
}
Exemple #2
0
NTSTATUS kuhl_m_token_revert(int argc, wchar_t * argv[])
{
	if(SetThreadToken(NULL, NULL))
		kuhl_m_token_whoami(0, NULL);
	else
		PRINT_ERROR_AUTO(L"SetThreadToken");
	return STATUS_SUCCESS;
}
Exemple #3
0
BOOL CALLBACK kuhl_m_token_list_or_elevate_callback(HANDLE hToken, DWORD ptid, PVOID pvArg)
{
	HANDLE hNewToken;
	TOKEN_STATISTICS tokenStats;
	DWORD szNeeded;
	BOOL isUserOK = TRUE;
	PKUHL_M_TOKEN_ELEVATE_DATA pData = (PKUHL_M_TOKEN_ELEVATE_DATA) pvArg;
	PWSTR name, domainName;

	if(ptid != GetCurrentProcessId())
	{
		if(GetTokenInformation(hToken, TokenStatistics, &tokenStats, sizeof(TOKEN_STATISTICS), &szNeeded))
		{
			if(pData->pUsername)
			{
				if(kull_m_token_getNameDomainFromToken(hToken, &name, &domainName, NULL, NULL))
				{
					isUserOK = (_wcsicmp(name, pData->pUsername) == 0);
					LocalFree(name);
					LocalFree(domainName);
				}
			} else if(pData->tokenId)
				isUserOK = (pData->tokenId == tokenStats.TokenId.LowPart);

			if(isUserOK && DuplicateTokenEx(hToken, TOKEN_QUERY | TOKEN_IMPERSONATE, NULL, (tokenStats.TokenType == TokenPrimary) ? SecurityDelegation : tokenStats.ImpersonationLevel, TokenImpersonation, &hNewToken))
			{
				if(pData->pSid)
				{
					isUserOK = FALSE;
					if(!CheckTokenMembership(hNewToken, pData->pSid, &isUserOK))
						PRINT_ERROR_AUTO(L"CheckTokenMembership");
				}
				if(isUserOK)
				{
					kprintf(L"%u\t", ptid);
					kuhl_m_token_displayAccount(hToken);

					if(pData->elevateIt)
					{
						if(SetThreadToken(NULL, hNewToken))
						{
							kprintf(L" -> Impersonated !\n");
							kuhl_m_token_whoami(0, NULL);
							isUserOK = FALSE;
						}
						else PRINT_ERROR_AUTO(L"SetThreadToken");
					}
				}
				else isUserOK = TRUE;
				CloseHandle(hNewToken);
			}
			else isUserOK = TRUE;
		}
	}
	return isUserOK;
}
 Win32ThreadImpersonator(HANDLE hToken)
 {
     BOOL ok = SetThreadToken(NULL, hToken);
     if (!ok)
     {
         DWORD dwErr = GetLastError();
         RCF_THROW( Exception( 
             _RcfError_Win32ApiError("SetThreadToken()"), 
             dwErr) ); 
     }
 }
Exemple #5
0
void* __stdcall CsrClientCallServerHook(void* a, void* b, DWORD c, void* d)
{
  void* ret = nullptr;
  printf("In ClientCall hook %08X\n", c);
  if (c == 0x10010005)
  {
    printf("Set Anonymous Token: %d\n", SetThreadToken(nullptr, GetAnonymousToken()));
  }

  ret = g_pCsgClientCallServer(a, b, c, d);
  RevertToSelf();
  return ret;
}
Exemple #6
0
bool DebugToken::Revert()
{
	if (!enabled)
		return true;

	BOOL rc = SetThreadToken(NULL, hSavedToken);

	if (!rc)
		return false;

	if (hSavedToken != NULL)
	{
		CloseHandle(hSavedToken);
		hSavedToken = NULL;
	}

	enabled = false;
	return true;
}
Exemple #7
0
/**
 * RevertToPrinterSelf reverts the security context from the current user's context back to the process context.
 * As spoolss.dll is used by spoolsv.exe, this is usually the SYSTEM security context.
 *
 * Unlike the traditional ImpersonateClient and then RevertToSelf approach, we do it the other way round here,
 * because spoolss.dll is delay-loaded by spoolsv.exe in the current user's context. Use RevertToPrinterSelf then to
 * return to the SYSTEM context for specific tasks.
 */
HANDLE WINAPI
RevertToPrinterSelf(VOID)
{
    DWORD dwErrorCode;
    HANDLE hReturnValue = NULL;
    HANDLE hToken = NULL;

    // All spoolss code is usually called after impersonating the client. In this case, we can retrieve our current thread impersonation token using OpenThreadToken.
    // But in rare occasions, spoolss code is also called from a higher-privileged thread that doesn't impersonate the client. Then we don't get an impersonation token.
    // Anyway, we can't just return nothing in this case, because this is being treated as failure by the caller. So we return the token of the current process.
    // This behaviour is verified with Windows!
    if (OpenThreadToken(GetCurrentThread(), TOKEN_IMPERSONATE, TRUE, &hToken))
    {
        // Tell the thread to stop impersonating.
        if (!SetThreadToken(NULL, NULL))
        {
            dwErrorCode = GetLastError();
            ERR("SetThreadToken failed with error %lu!\n", dwErrorCode);
            goto Cleanup;
        }
    }
    else if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
    {
        dwErrorCode = GetLastError();
        ERR("OpenProcessToken failed with error %lu!\n", dwErrorCode);
        goto Cleanup;
    }

    // We were successful, return a token!
    dwErrorCode = ERROR_SUCCESS;
    hReturnValue = hToken;

    // Don't let the cleanup routine close this.
    hToken = NULL;

Cleanup:
    if (hToken)
        CloseHandle(hToken);

    SetLastError(dwErrorCode);
    return hReturnValue;
}
Exemple #8
0
/**
 * @see RevertToPrinterSelf
 */
BOOL WINAPI
ImpersonatePrinterClient(HANDLE hToken)
{
    DWORD cbReturned;
    DWORD dwErrorCode;
    TOKEN_TYPE Type;

    // Sanity check
    if (!hToken)
    {
        dwErrorCode = ERROR_INVALID_HANDLE;
        goto Cleanup;
    }

    // Get the type of the supplied token.
    if (!GetTokenInformation(hToken, TokenType, &Type, sizeof(TOKEN_TYPE), &cbReturned))
    {
        dwErrorCode = GetLastError();
        ERR("GetTokenInformation failed with error %lu!\n", dwErrorCode);
        goto Cleanup;
    }

    // Check if this is an impersonation token and only set it as the thread token in this case.
    // This is not always an impersonation token, see RevertToPrinterSelf.
    if (Type == TokenImpersonation)
    {
        if (!SetThreadToken(NULL, hToken))
        {
            dwErrorCode = GetLastError();
            ERR("SetThreadToken failed with error %lu!\n", dwErrorCode);
            goto Cleanup;
        }
    }

Cleanup:
    if (hToken)
        CloseHandle(hToken);

    SetLastError(dwErrorCode);
    return (dwErrorCode == ERROR_SUCCESS);
}
/*++

Routine Name:

    CPTManager::GetMergedTicket

Routine Description:

    This routine retrieves a merged PrintTicket at the requested scope given the base
    and delta PrintTickets as IXMLDOMDocument2 interface pointers

Arguments:

    ptScope  - The scope at which the merge should take place
    pDelta   - The delta PrintTicket as an IXMLDOMDocument2 pointer
    pBase    - The base PrintTicket as an IXMLDOMDocument2 pointer
    ppResult - The resulting PrintTicket after the merge has completed

Return Value:

    HRESULT
    S_OK - On success
    E_*  - On error

--*/
HRESULT
CPTManager::GetMergedTicket(
    _In_        CONST EPrintTicketScope ptScope,
    _In_        CONST IXMLDOMDocument2* pDelta,
    _In_        IXMLDOMDocument2*       pBase,
    _Outptr_ IXMLDOMDocument2**      ppResult
    )
{
    ASSERTMSG(pDelta != NULL, "NULL PT reference part passed.\n");
    ASSERTMSG(pBase != NULL, "NULL base PT passed.\n");
    ASSERTMSG(ppResult != NULL, "NULL out PT passed.\n");

    HRESULT hr = S_OK;

    if (SUCCEEDED(hr = CHECK_HANDLE(m_hProvider, E_PENDING)) &&
        SUCCEEDED(hr = CHECK_POINTER(ppResult, E_POINTER)) &&
        SUCCEEDED(hr = CHECK_POINTER(pDelta, E_POINTER)) &&
        SUCCEEDED(hr = CHECK_POINTER(pBase, E_POINTER)))
    {
        *ppResult = NULL;
    }

    CComPtr<IStream> pResultStream(NULL);
    CComPtr<IStream> pBaseStream(NULL);
    CComPtr<IStream> pDeltaStream(NULL);

    CComPtr<IXMLDOMDocument2> pNewPT(NULL);

    //
    // Create a new DOM doc based off the result ticket and
    // assign to the resultant DOM doc
    //
    try
    {
        CComBSTR bstrErrorMessage;

        if (SUCCEEDED(hr) &&
            SUCCEEDED(hr = CreateStreamOnHGlobal(NULL, TRUE, &pResultStream)) &&
            SUCCEEDED(hr = pBase->QueryInterface(IID_IStream, reinterpret_cast<VOID**>(&pBaseStream)))  &&
            SUCCEEDED(hr = const_cast<IXMLDOMDocument2*>(pDelta)->QueryInterface(IID_IStream, reinterpret_cast<VOID**>(&pDeltaStream))))
        {
            if (SetThreadToken(NULL, m_hToken))
            {
                if (SUCCEEDED(hr = PTMergeAndValidatePrintTicket(m_hProvider,
                                                                 pBaseStream,
                                                                 pDeltaStream,
                                                                 ptScope,
                                                                 pResultStream,
                                                                 &bstrErrorMessage)))
                {
                    if (SUCCEEDED(hr = SetPTFromStream(pResultStream, &pNewPT)))
                    {
                        //
                        // Assign the outgoing element pointer - detach from CComPtr to release ownership
                        //
                        *ppResult = pNewPT.Detach();
                    }
                }
                else
                {
                    CStringXDA cstrMessage;
                    CStringXDA cstrError(bstrErrorMessage);
                    cstrMessage.Format("PTMergeAndValidatePrintTicket failed with message: %s\n", cstrError);

                    ERR(cstrMessage.GetBuffer());
                }

                //
                // Always revert back to the default security context
                //
                if (!SetThreadToken(NULL, NULL))
                {
                    //
                    // We couldn't revert the security context. The filter pipeline
                    // manager will clean up the thread when operation is complete,
                    // when it is determined that the security context was not 
                    // reverted. Since there are no security implications with 
                    // running this filter in an elevated context, we can 
                    // continue to run.
                    //
                }
            }
            else
            {
                hr = HRESULT_FROM_WIN32(GetLastError());

                //
                // If SetThreadToken fails, GetLastError will return an error
                //
                _Analysis_assume_(FAILED(hr));
            }
        }
    }
    catch (CXDException& e)
    {
        hr = e;
    }

    ERR_ON_HR(hr);
    return hr;
}
/*++

Routine Name:

    CPTManager::GetCapabilities

Routine Description:

    This routine retrieves a PrintCapabilities document given a PrintTicket

Arguments:

    pTicket - Pointer to the PrintTicket as a DOM document
    pTicket - Pointer to a DOM document pointer that recieves the PrintCapabilities

Return Value:

    HRESULT
    S_OK - On success
    E_*  - On error

--*/
HRESULT
CPTManager::GetCapabilities(
    _In_        IXMLDOMDocument2*  pTicket,
    _Outptr_ IXMLDOMDocument2** ppCapabilities
    )
{
    HRESULT hr = S_OK;

    if (SUCCEEDED(hr = CHECK_POINTER(pTicket, E_POINTER)) &&
        SUCCEEDED(hr = CHECK_POINTER(ppCapabilities, E_POINTER)))
    {
        *ppCapabilities = NULL;

        CComBSTR bstrError;
        CComPtr<IStream> pPTIn(NULL);
        CComPtr<IStream> pPCOut(NULL);
        CComPtr<IXMLDOMDocument2> pCapabilitiesDoc(NULL);

        //
        // Create the PrintCapabilities DOM document, retrieve the IStreams from the
        // DOM documents and call the PT api to retrieve the capabilities document
        //
        if (SUCCEEDED(hr = pCapabilitiesDoc.CoCreateInstance(CLSID_DOMDocument60)) &&
            SUCCEEDED(hr = pTicket->QueryInterface(IID_IStream, reinterpret_cast<VOID**>(&pPTIn))) &&
            SUCCEEDED(hr = pCapabilitiesDoc->QueryInterface(IID_IStream, reinterpret_cast<VOID**>(&pPCOut))))
        {
            if (SetThreadToken(NULL, m_hToken))
            {
                if (SUCCEEDED(hr = PTGetPrintCapabilities(m_hProvider, pPTIn, pPCOut, &bstrError)))
                {
                    LARGE_INTEGER cbMove = {0};
                    if (SUCCEEDED(hr = pPCOut->Seek(cbMove, STREAM_SEEK_SET, NULL)))
                    {
                        *ppCapabilities = pCapabilitiesDoc.Detach();
                    }
                }
                else
                {
                    try
                    {
                        CStringXDA cstrError(bstrError);
                        ERR(cstrError.GetBuffer());
                    }
                    catch (CXDException&)
                    {
                    }
                }
            
                //
                // Always revert back to the default security context
                //
                if (!SetThreadToken(NULL, NULL))
                {
                    //
                    // We couldn't revert the security context. The filter pipeline
                    // manager will clean up the thread when operation is complete,
                    // when it is determined that the security context was not 
                    // reverted. Since there are no security implications with 
                    // running this filter in an elevated context, we can 
                    // continue to run.
                    //
                }
            }
            else
            {
                hr = HRESULT_FROM_WIN32(GetLastError());

                //
                // If SetThreadToken fails, GetLastError will return an error
                //
                _Analysis_assume_(FAILED(hr));
            }
        }
    }

    ERR_ON_HR(hr);
    return hr;
}
/*++

Routine Name:

    CPTManager::Initialise

Routine Description:

    This routine Initialises the PrintTicket manager with the default PrintTicket
    and the device name.

Arguments:

    pDefaultTicketStream - Pointer to the default user PrintTicket as an IStream
    bstrPrinterName      - The name of the printer
    userToken            - The user's security token

Return Value:

    HRESULT
    S_OK - On success
    E_*  - On error

--*/
HRESULT
CPTManager::Initialise(
    _In_   IPrintReadStream* pDefaultTicketStream,
    _In_z_ BSTR              bstrPrinterName,
    _In_   HANDLE            userToken
    )
{
    HRESULT hr = S_OK;

    m_hToken = userToken;

    //
    // If the provider is already open close it
    //
    CloseProvider();

    if (SUCCEEDED(hr = CHECK_POINTER(pDefaultTicketStream, E_POINTER)))
    {
        if (SysStringLen(bstrPrinterName) <= 0)
        {
            hr = E_INVALIDARG;
        }
    }

    //
    // We need to impersonate the user who submitted the job
    // in order to always have sufficient rights to call
    // PTOpenProvider.
    //
    if (SUCCEEDED(hr))
    {
        if (SetThreadToken(NULL, m_hToken))
        {
            //
            // Open the PT interface and initialise PrintTickets
            //
            if (SUCCEEDED(hr = PTOpenProvider(bstrPrinterName, 1, &m_hProvider)))
            {
                CComPtr<IStream> pPTStream(NULL);
                pPTStream.Attach(new(std::nothrow) CPrintReadStreamToIStream(pDefaultTicketStream));

                if (SUCCEEDED(hr = CHECK_POINTER(pPTStream, E_OUTOFMEMORY)))
                {
                    hr = InitialisePrintTickets(pPTStream);
                }
            }

            //
            // Always revert back to the default security context
            //
            if (!SetThreadToken(NULL, NULL))
            {
                //
                // We couldn't revert the security context. The filter pipeline
                // manager will clean up the thread when operation is complete,
                // when it is determined that the security context was not 
                // reverted. Since there are no security implications with 
                // running this filter in an elevated context, we can 
                // continue to run.
                //
            }
        }
        else
        {
            hr = HRESULT_FROM_WIN32(GetLastError());
        }
    }

    ERR_ON_HR(hr);
    return hr;
}
void MI_CALL MSFT_DSCLocalConfigManager_Invoke_GetConfiguration(
    _In_opt_ MSFT_DSCLocalConfigManager_Self* self,
    _In_ MI_Context* context,
    _In_opt_z_ const MI_Char* nameSpace,
    _In_opt_z_ const MI_Char* className,
    _In_opt_z_ const MI_Char* methodName,
    _In_ const MSFT_DSCLocalConfigManager* instanceName,
    _In_opt_ const MSFT_DSCLocalConfigManager_GetConfiguration* in)
{
    MI_Result miResult;
    MI_Instance *cimErrorDetails = NULL;
    MI_InstanceA outInstances = {0};
    MI_Value val;
    MI_Uint32 bufferIndex = 0;    
    MSFT_DSCLocalConfigManager_GetConfiguration outputObject;
    HANDLE m_clientThreadToken;
    
    MI_UNREFERENCED_PARAMETER(self);
    MI_UNREFERENCED_PARAMETER(nameSpace);
    MI_UNREFERENCED_PARAMETER(className);
    MI_UNREFERENCED_PARAMETER(methodName);
    MI_UNREFERENCED_PARAMETER(instanceName);
    MI_UNREFERENCED_PARAMETER(in);

            
    if(!in->configurationData.exists)
    {
        MI_Context_PostResult(context, MI_RESULT_INVALID_PARAMETER);
        return;        
    }

    if(!OpenThreadToken(GetCurrentThread(), TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_DUPLICATE, TRUE, &m_clientThreadToken))
    {
        GetCimWin32Error(GetLastError(), &cimErrorDetails, ID_LCMHELPER_THREADIMPERSONATION_FAILED);
        MI_PostCimError(context, cimErrorDetails);
        MI_Instance_Delete(cimErrorDetails);
        return;
    }

    if (!SetThreadToken(NULL, NULL))
    {
        GetCimWin32Error(GetLastError(), &cimErrorDetails, ID_LCMHELPER_REVERTSELF_FAILED);
        MI_PostCimError(context, cimErrorDetails);
        MI_Instance_Delete(cimErrorDetails);
        CloseHandle(m_clientThreadToken);
        return;
    }

    miResult = MSFT_DSCLocalConfigManager_GetConfiguration_Construct(&outputObject, context);
    if(miResult != MI_RESULT_OK)
    {
        GetCimMIError(miResult, &cimErrorDetails, ID_LCMHELPER_CONSTRUCTGET_FAILED);
        MI_PostCimError(context, cimErrorDetails);
        MI_Instance_Delete(cimErrorDetails);
        return;
    }   

    GetRealBufferIndex( &(in->configurationData.value), &bufferIndex);
    miResult = CallGetConfiguration(in->configurationData.value.data + bufferIndex, 
                                in->configurationData.value.size - bufferIndex, &outInstances, 
                                context, &cimErrorDetails);
    if(miResult != MI_RESULT_OK)
    {
        MI_PostCimError(context, cimErrorDetails);
        MI_Instance_Delete(cimErrorDetails);
        MSFT_DSCLocalConfigManager_GetConfiguration_Destruct(&outputObject);
        SetThreadToken(NULL, m_clientThreadToken);
        CloseHandle(m_clientThreadToken);
        return;
    }
   
    val.instancea.data = outInstances.data;
    val.instancea.size = outInstances.size;
    miResult = MI_Context_WriteStreamParameter(context, L"configurations", &val, MI_INSTANCEA, 0);
    CleanUpInstanceCache(&outInstances);
    if(miResult != MI_RESULT_OK)
    {
        GetCimMIError(miResult, &cimErrorDetails, ID_LCMHELPER_WRITEGET_FAILED);
        MI_PostCimError(context, cimErrorDetails);
        MI_Instance_Delete(cimErrorDetails);
        MSFT_DSCLocalConfigManager_GetConfiguration_Destruct(&outputObject);
        SetThreadToken(NULL, m_clientThreadToken);
        CloseHandle(m_clientThreadToken);
        return;
    }

    miResult = MSFT_DSCLocalConfigManager_GetConfiguration_Set_MIReturn(&outputObject, 0);
    if(miResult != MI_RESULT_OK)
    {
        GetCimMIError(miResult, &cimErrorDetails, ID_LCMHELPER_SETGET_FAILED);
        MI_PostCimError(context, cimErrorDetails);
        MI_Instance_Delete(cimErrorDetails);
        MSFT_DSCLocalConfigManager_GetConfiguration_Destruct(&outputObject);
        SetThreadToken(NULL, m_clientThreadToken);
        CloseHandle(m_clientThreadToken);
        return;
    }

    miResult = MSFT_DSCLocalConfigManager_GetConfiguration_Post(&outputObject, context);
    MSFT_DSCLocalConfigManager_GetConfiguration_Destruct(&outputObject);

    if (!SetThreadToken(NULL, m_clientThreadToken))
    {
        GetCimWin32Error(GetLastError(), &cimErrorDetails, ID_LCMHELPER_RESUMEIMPERSONATION_FAILED);
        MI_PostCimError(context, cimErrorDetails);
        MI_Instance_Delete(cimErrorDetails);
        CloseHandle(m_clientThreadToken);
        return;
    }

    CloseHandle(m_clientThreadToken);

    if(miResult != MI_RESULT_OK)
    {
        GetCimMIError(miResult, &cimErrorDetails, ID_LCMHELPER_POSTGET_FAILED);
        MI_PostCimError(context, cimErrorDetails);
        MI_Instance_Delete(cimErrorDetails);
        return;
    }

    MI_Context_PostResult(context, MI_RESULT_OK);
}
 ~Win32ThreadImpersonator()
 {
     SetThreadToken(NULL, NULL);
 }
void MI_CALL MSFT_DSCLocalConfigManager_Invoke_SendMetaConfiguration(
    _In_opt_ MSFT_DSCLocalConfigManager_Self* self,
    _In_ MI_Context* context,
    _In_opt_z_ const MI_Char* nameSpace,
    _In_opt_z_ const MI_Char* className,
    _In_opt_z_ const MI_Char* methodName,
    _In_ const MSFT_DSCLocalConfigManager* instanceName,
    _In_opt_ const MSFT_DSCLocalConfigManager_SendMetaConfiguration* in)
{
    MI_Result miResult;
    MI_Instance *cimErrorDetails = NULL;
    HANDLE m_clientThreadToken;
    MI_UNREFERENCED_PARAMETER(self);
    MI_UNREFERENCED_PARAMETER(nameSpace);
    MI_UNREFERENCED_PARAMETER(className);
    MI_UNREFERENCED_PARAMETER(methodName);
    MI_UNREFERENCED_PARAMETER(instanceName);
    MI_UNREFERENCED_PARAMETER(in);

    if(!in->MetaConfiguration.exists)
    {
        MI_Context_PostResult(context, MI_RESULT_INVALID_PARAMETER);
        return;        
    }

    if(!OpenThreadToken(GetCurrentThread(), TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_DUPLICATE, TRUE, &m_clientThreadToken))
    {
        GetCimWin32Error(GetLastError(), &cimErrorDetails, ID_LCMHELPER_THREADIMPERSONATION_FAILED);
        MI_PostCimError(context, cimErrorDetails);
        MI_Instance_Delete(cimErrorDetails);
        return;
    }

    if (!SetThreadToken(NULL, NULL))
    {
        GetCimWin32Error(GetLastError(), &cimErrorDetails, ID_LCMHELPER_REVERTSELF_FAILED);
        MI_PostCimError(context, cimErrorDetails);
        MI_Instance_Delete(cimErrorDetails);
        CloseHandle(m_clientThreadToken);
        return;
    }

    miResult = SetMetaConfig(in->MetaConfiguration.value, &cimErrorDetails);

    
    if (!SetThreadToken(NULL, m_clientThreadToken))
    {
        GetCimWin32Error(GetLastError(), &cimErrorDetails, ID_LCMHELPER_RESUMEIMPERSONATION_FAILED);
        MI_PostCimError(context, cimErrorDetails);
        MI_Instance_Delete(cimErrorDetails);
        CloseHandle(m_clientThreadToken);
        return;
    }

    CloseHandle(m_clientThreadToken);

    if(miResult != MI_RESULT_OK)
    {
        MI_PostCimError(context, cimErrorDetails);
        MI_Instance_Delete(cimErrorDetails);
        return;
    }

    MI_Context_PostResult(context, MI_RESULT_OK);
}
void MI_CALL MSFT_DSCLocalConfigManager_Invoke_ApplyConfiguration(
    _In_opt_ MSFT_DSCLocalConfigManager_Self* self,
    _In_ MI_Context* context,
    _In_opt_z_ const MI_Char* nameSpace,
    _In_opt_z_ const MI_Char* className,
    _In_opt_z_ const MI_Char* methodName,
    _In_ const MSFT_DSCLocalConfigManager* instanceName,
    _In_opt_ const MSFT_DSCLocalConfigManager_ApplyConfiguration* in)
{
    MI_Result miResult;
    MI_Instance *cimErrorDetails = NULL;
    MSFT_DSCLocalConfigManager_ApplyConfiguration outputObject;
    HANDLE m_clientThreadToken;
    MI_UNREFERENCED_PARAMETER(self);
    MI_UNREFERENCED_PARAMETER(nameSpace);
    MI_UNREFERENCED_PARAMETER(className);
    MI_UNREFERENCED_PARAMETER(methodName);
    MI_UNREFERENCED_PARAMETER(instanceName);
    MI_UNREFERENCED_PARAMETER(in);

    if(!OpenThreadToken(GetCurrentThread(), TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_DUPLICATE, TRUE, &m_clientThreadToken))
    {
        GetCimWin32Error(GetLastError(), &cimErrorDetails, ID_LCMHELPER_THREADIMPERSONATION_FAILED);
        MI_PostCimError(context, cimErrorDetails);
        MI_Instance_Delete(cimErrorDetails);
        return;
    }

    if (!SetThreadToken(NULL, NULL))
    {
        GetCimWin32Error(GetLastError(), &cimErrorDetails, ID_LCMHELPER_REVERTSELF_FAILED);
        MI_PostCimError(context, cimErrorDetails);
        MI_Instance_Delete(cimErrorDetails);
        CloseHandle(m_clientThreadToken);
        return;
    }

    miResult = MSFT_DSCLocalConfigManager_ApplyConfiguration_Construct(&outputObject, context);
    if(miResult != MI_RESULT_OK)
    {
        GetCimMIError(miResult, &cimErrorDetails, ID_LCMHELPER_CONSTRUCTAPPLY_FAILED);
        MI_PostCimError(context, cimErrorDetails);
        MI_Instance_Delete(cimErrorDetails);
        SetThreadToken(NULL, m_clientThreadToken);
        CloseHandle(m_clientThreadToken);
        return;
    }       


    miResult = CallConsistencyEngine(context, &cimErrorDetails); 

    if(miResult != MI_RESULT_OK)
    {
        MI_PostCimError(context, cimErrorDetails);
        MI_Instance_Delete(cimErrorDetails);
        SetThreadToken(NULL, m_clientThreadToken);
        CloseHandle(m_clientThreadToken);
        return;
    }

    miResult = MSFT_DSCLocalConfigManager_ApplyConfiguration_Set_MIReturn(&outputObject, 0);
    if(miResult != MI_RESULT_OK)
    {
        GetCimMIError(miResult, &cimErrorDetails, ID_LCMHELPER_SETAPPLY_FAILED);
        MI_PostCimError(context, cimErrorDetails);
        MI_Instance_Delete(cimErrorDetails);
        SetThreadToken(NULL, m_clientThreadToken);
        CloseHandle(m_clientThreadToken);
        return;
    }

    miResult = MSFT_DSCLocalConfigManager_ApplyConfiguration_Post(&outputObject, context);
    MSFT_DSCLocalConfigManager_ApplyConfiguration_Destruct(&outputObject);

    
    if (!SetThreadToken(NULL, m_clientThreadToken))
    {
        GetCimWin32Error(GetLastError(), &cimErrorDetails, ID_LCMHELPER_RESUMEIMPERSONATION_FAILED);
        MI_PostCimError(context, cimErrorDetails);
        MI_Instance_Delete(cimErrorDetails);
        CloseHandle(m_clientThreadToken);
        return;
    }

    CloseHandle(m_clientThreadToken);

    if(miResult != MI_RESULT_OK)
    {
        GetCimMIError(miResult, &cimErrorDetails, ID_LCMHELPER_POSTAPPLY_FAILED);
        MI_PostCimError(context, cimErrorDetails);
        MI_Instance_Delete(cimErrorDetails);
        return;
    }    

    MI_Context_PostResult(context, MI_RESULT_OK);

}
Exemple #16
0
//
// Assert an NT privilege for this thread.
//
BOOL
AssertPrivilege(
    IN  LPCSTR PrivilegeName
    )

{
    BOOL                b;
    HANDLE              hThread;
    HANDLE              hProcess;
    TOKEN_PRIVILEGES    tokenPrivileges, oldTokenPrivileges;
    DWORD               oldPrivilegesLength;


    b = OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES |
                        TOKEN_QUERY, TRUE, &hThread);
    if (!b) {
        if (GetLastError() != ERROR_NO_TOKEN) {
            return b;
        }

        b = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE, &hProcess);
        if (!b) {
            return b;
        }

        b = DuplicateTokenEx(hProcess, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY |
                             TOKEN_IMPERSONATE, NULL, SecurityImpersonation,
                             TokenImpersonation, &hThread);
        if (!b) {
            CloseHandle(hProcess);
            return b;
        }

        b = SetThreadToken(NULL, hThread);
        if (!b) {
            CloseHandle(hProcess);
            CloseHandle(hThread);
            return b;
        }

        CloseHandle(hProcess);
    }

    ZeroMemory(&tokenPrivileges, sizeof(tokenPrivileges));

    b = LookupPrivilegeValue(NULL,PrivilegeName,&tokenPrivileges.Privileges[0].Luid);
    if (!b) {
        return b;
    }

    tokenPrivileges.PrivilegeCount = 1;
    tokenPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

    b = AdjustTokenPrivileges(hThread, FALSE, &tokenPrivileges,
                              sizeof(tokenPrivileges), &oldTokenPrivileges,
                              &oldPrivilegesLength);

    CloseHandle(hThread);

    return b;
}
Exemple #17
0
void impersonateToGetData(PCSTR user, PCSTR domain, PCSTR password, PCSTR kdc, PSID *sid, DWORD *rid, PCSTR usingWhat)
{
	NTSTATUS status;
	DWORD ret, *aRid, *usage;
	ANSI_STRING aUser, aKdc, aDomain, aPass, aProg;
	UNICODE_STRING uUser, uKdc, uDomain, uPass, uProg;
	SAMPR_HANDLE hServerHandle, hDomainHandle;
	PSID domainSid;
	HANDLE hToken, hNewToken;
	PROCESS_INFORMATION processInfos;
	STARTUPINFOW startupInfo;
	RtlZeroMemory(&startupInfo, sizeof(STARTUPINFOW));
	startupInfo.cb = sizeof(STARTUPINFOW);

	RtlInitString(&aUser, user);
	RtlInitString(&aKdc, kdc);
	RtlInitString(&aDomain, domain);
	RtlInitString(&aPass, password);
	RtlInitString(&aProg, usingWhat ? usingWhat : "winver.exe");
	if(NT_SUCCESS(RtlAnsiStringToUnicodeString(&uUser, &aUser, TRUE)))
	{
		if(NT_SUCCESS(RtlAnsiStringToUnicodeString(&uKdc, &aKdc, TRUE)))
		{
			if(NT_SUCCESS(RtlAnsiStringToUnicodeString(&uDomain, &aDomain, TRUE)))
			{
				if(NT_SUCCESS(RtlAnsiStringToUnicodeString(&uPass, &aPass, TRUE)))
				{

					if(NT_SUCCESS(RtlAnsiStringToUnicodeString(&uProg, &aProg, TRUE)))
					{
						if(CreateProcessWithLogonW(uUser.Buffer, uDomain.Buffer, uPass.Buffer, LOGON_NETCREDENTIALS_ONLY, uProg.Buffer, NULL, CREATE_SUSPENDED, NULL, NULL, &startupInfo, &processInfos))
						{
							if(OpenProcessToken(processInfos.hProcess, TOKEN_DUPLICATE, &hToken))
							{
								if(DuplicateTokenEx(hToken, TOKEN_QUERY | TOKEN_IMPERSONATE, NULL, SecurityDelegation, TokenImpersonation, &hNewToken))
								{
									if(SetThreadToken(NULL, hNewToken))
									{
										kprintf("[AUTH] Impersonation\n");
										if(!(*sid && *rid))
										{
											kprintf("[SID/RID] \'%s @ %s\' must be translated to SID/RID\n", user, domain);
											status = SamConnect(&uKdc, &hServerHandle, SAM_SERVER_CONNECT | SAM_SERVER_LOOKUP_DOMAIN, FALSE);
											if(NT_SUCCESS(status))
											{
												status = SamLookupDomainInSamServer(hServerHandle, &uDomain, &domainSid);
												if(NT_SUCCESS(status))
												{
													status = SamOpenDomain(hServerHandle, DOMAIN_LIST_ACCOUNTS | DOMAIN_LOOKUP, domainSid, &hDomainHandle);
													if(NT_SUCCESS(status))
													{
														status = SamLookupNamesInDomain(hDomainHandle, 1, &uUser, &aRid, &usage);
														if(NT_SUCCESS(status))
															*rid = *aRid;
														else PRINT_ERROR("SamLookupNamesInDomain %08x\n", status);
													}
													else PRINT_ERROR("SamOpenDomain %08x\n", status);

													ret = GetLengthSid(domainSid);
													if(*sid = (PSID) LocalAlloc(LPTR, ret))
													{
														if(!CopySid(ret, *sid, domainSid))
														{
															*sid = (PSID) LocalFree(*sid);
															PRINT_ERROR_AUTO("CopySid");
														}
													}
													SamFreeMemory(domainSid);
												}
												else PRINT_ERROR("SamLookupDomainInSamServer %08x\n", status);
												SamCloseHandle(hServerHandle);
											}
											else PRINT_ERROR("SamConnect %08x\n", status);
										}
										RevertToSelf();
									}
									else PRINT_ERROR_AUTO("SetThreadToken");
									CloseHandle(hNewToken);
								}
								else PRINT_ERROR_AUTO("DuplicateTokenEx");
								CloseHandle(hToken);
							}
							else PRINT_ERROR_AUTO("OpenProcessToken");
							TerminateProcess(processInfos.hProcess, 0);
							CloseHandle(processInfos.hProcess);
							CloseHandle(processInfos.hThread);
						}
						else PRINT_ERROR_AUTO("CreateProcessWithLogonW");

						RtlFreeUnicodeString(&uProg);
					}
					RtlFreeUnicodeString(&uPass);
				}
				RtlFreeUnicodeString(&uDomain);
			}
			RtlFreeUnicodeString(&uKdc);
		}
		RtlFreeUnicodeString(&uUser);
	}
}
void MI_CALL MSFT_DSCLocalConfigManager_Invoke_SendConfigurationApply(
    _In_opt_ MSFT_DSCLocalConfigManager_Self* self,
    _In_ MI_Context* context,
    _In_opt_z_ const MI_Char* nameSpace,
    _In_opt_z_ const MI_Char* className,
    _In_opt_z_ const MI_Char* methodName,
    _In_ const MSFT_DSCLocalConfigManager* instanceName,
    _In_opt_ const MSFT_DSCLocalConfigManager_SendConfigurationApply* in)
{
    MI_Result miResult;
    MI_Instance *cimErrorDetails = NULL;
    MI_Uint32 bufferIndex = 0;
    HANDLE m_clientThreadToken;
    MI_UNREFERENCED_PARAMETER(self);
    MI_UNREFERENCED_PARAMETER(nameSpace);
    MI_UNREFERENCED_PARAMETER(className);
    MI_UNREFERENCED_PARAMETER(methodName);
    MI_UNREFERENCED_PARAMETER(instanceName);
    MI_UNREFERENCED_PARAMETER(in);

    if(!in->ConfigurationData.exists)
    {
        MI_Context_PostResult(context, MI_RESULT_INVALID_PARAMETER);
        return;        
    }

    if(!OpenThreadToken(GetCurrentThread(), TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_DUPLICATE, TRUE, &m_clientThreadToken))
    {
        GetCimWin32Error(GetLastError(), &cimErrorDetails, ID_LCMHELPER_THREADIMPERSONATION_FAILED);
        MI_PostCimError(context, cimErrorDetails);
        MI_Instance_Delete(cimErrorDetails);
        return;
    }

    if (!SetThreadToken(NULL, NULL))
    {
        GetCimWin32Error(GetLastError(), &cimErrorDetails, ID_LCMHELPER_REVERTSELF_FAILED);
        MI_PostCimError(context, cimErrorDetails);
        MI_Instance_Delete(cimErrorDetails);
        CloseHandle(m_clientThreadToken);
        return;
    }

    GetRealBufferIndex( &(in->ConfigurationData.value), &bufferIndex);

    miResult = CallSetConfiguration(in->ConfigurationData.value.data + bufferIndex, 
                            in->ConfigurationData.value.size - bufferIndex, LCM_SETFLAGS_DEFAULT, context, &cimErrorDetails); 

    if (!SetThreadToken(NULL, m_clientThreadToken))
    {
        GetCimWin32Error(GetLastError(), &cimErrorDetails, ID_LCMHELPER_RESUMEIMPERSONATION_FAILED);
        MI_PostCimError(context, cimErrorDetails);
        MI_Instance_Delete(cimErrorDetails);
        CloseHandle(m_clientThreadToken);
        return;
    }

    CloseHandle(m_clientThreadToken);

    if(miResult != MI_RESULT_OK)
    {
        MI_PostCimError(context, cimErrorDetails);
        MI_Instance_Delete(cimErrorDetails);
        return;
    }

    MI_Context_PostResult(context, MI_RESULT_OK);
}