Esempio n. 1
0
HRESULT
ExecuteMethod3InInstance(
    __in IWbemServices* WbemServices,
    __in IWbemClassObject* ClassObj,
    __in const BSTR InstancePath,
    __in ULONG InData1,
    __in ULONG InData2
    )
{
    HRESULT status;

    IWbemClassObject* inputParamsObj  = NULL;
    IWbemClassObject* inputParamsInstanceObj  = NULL;
    IWbemClassObject* outputParamsInstanceObj = NULL;

    const BSTR methodName = SysAllocString(TOASTER_METHOD_3);
    VARIANT funcParam;

    //
    // Get the input parameters class objects for the method.
    //
    status = ClassObj->GetMethod(methodName, 0, &inputParamsObj, NULL);
    if (FAILED(status)) {
        goto exit;
    }

    //
    // Spawn an instance of the input parameters class object.
    //
    status = inputParamsObj->SpawnInstance(0, &inputParamsInstanceObj);
    if (FAILED(status)) {
        goto exit;
    }

    //
    // Set the input variables values (i.e., inData1, inData2 for ToasterMethod3).
    //
    funcParam.vt = VT_I4;
    funcParam.ulVal = InData1;

    status = inputParamsInstanceObj->Put(L"InData1", 0, &funcParam, 0);
    if (FAILED(status)) {
        goto exit;
    }

    funcParam.vt = VT_I4;
    funcParam.ulVal = InData2;

    status = inputParamsInstanceObj->Put(L"InData2", 0, &funcParam, 0);
    if (FAILED(status)) {
        goto exit;
    }

    //
    // Call the method.
    //
    printf("\n");
    printf("Instance Path .: %ws\n", (wchar_t*)InstancePath);
    printf("  Method Name..: %ws\n", (wchar_t*)methodName);
    status = WbemServices->ExecMethod(InstancePath,
                                      methodName,
                                      0,
                                      NULL,
                                      inputParamsInstanceObj,
                                      &outputParamsInstanceObj,
                                      NULL);

    if (FAILED(status)) {
        goto exit;
    }

    //
    // Get the "in" Parameter values from the input parameters object.
    //
    status = inputParamsInstanceObj->Get(L"InData1", 0, &funcParam, NULL, NULL);
    if (FAILED(status)) {
        goto exit;
    }
    printf("     InData1...: %d\n", funcParam.ulVal);

    status = inputParamsInstanceObj->Get(L"InData2", 0, &funcParam, NULL, NULL);
    if (FAILED(status)) {
        goto exit;
    }
    printf("     InData2...: %d\n", funcParam.ulVal);

    //
    // Get the "out" Parameter values from the output parameters object.
    //
    status = outputParamsInstanceObj->Get(L"OutData1", 0, &funcParam, NULL, NULL);
    if (FAILED(status)) {
        goto exit;
    }
    printf("     OutData1..: %d\n", funcParam.ulVal);

    status = outputParamsInstanceObj->Get(L"OutData2", 0, &funcParam, NULL, NULL);
    if (FAILED(status)) {
        goto exit;
    }
    printf("     OutData2..: %d\n", funcParam.ulVal);

exit:

    if (methodName != NULL) {
        SysFreeString(methodName);
    }

    if (inputParamsObj != NULL) {
        inputParamsObj->Release();
    }

    if (inputParamsInstanceObj != NULL) {
        inputParamsInstanceObj->Release();
    }

    if (outputParamsInstanceObj != NULL) {
        outputParamsInstanceObj->Release();
    }

    return status;
}
HRESULT
GetAndSetValuesInClass(
    _In_     IWbemServices* WbemServices,
    _In_opt_ PWSTR UserId,
    _In_opt_ PWSTR Password,
    _In_opt_ PWSTR DomainName
    )

/*++

Routine Description:

    This routine enumerates the instances of the Toaster Device Information
    class and gets/sets the value of one of its Properties.

Arguments:

    WbemServices - Pointer to the WBEM services interface used for accessing
        the WMI services.

    UserId - Pointer to the user id information or NULL.

    Password - Pointer to password or NULL. If the user id is not specified,
        this parameter is ignored.

    DomainName - Pointer to domain name or NULL. If the user id is not specified,
        this parameter is ignored.

Return Value:

    HRESULT Status code.

--*/

{
    HRESULT status = S_OK;

    IEnumWbemClassObject* enumerator  = NULL;
    IWbemClassObject* classObj        = NULL;
    IWbemClassObject* instanceObj     = NULL;

    const BSTR className   = SysAllocString(TOASTER_DEVICE_INFO_CLASS);

    VARIANT instProperty;
    ULONG   nbrObjsSought = 1;
    ULONG   nbrObjsReturned;

    //
    // Create an Enumeration object to enumerate the instances of the given class.
    //
    status = WbemServices->CreateInstanceEnum(className,
                                              WBEM_FLAG_SHALLOW | WBEM_FLAG_RETURN_IMMEDIATELY | WBEM_FLAG_FORWARD_ONLY,
                                              NULL,
                                              &enumerator);
    if (FAILED(status)) {
        goto exit;
    }

    //
    // Set authentication information for the interface.
    //
    status = SetInterfaceSecurity(enumerator, UserId, Password, DomainName);
    if (FAILED(status)) {
        goto exit;
    }

    do {

        //
        // Get the instance object for each instance of the class.
        //
        status = enumerator->Next(WBEM_INFINITE,
                                  nbrObjsSought,
                                  &instanceObj,
                                  &nbrObjsReturned);

        if (status == WBEM_S_FALSE) {
            status = S_OK;
            break;
        }

        if (FAILED(status)) {
            if (status == WBEM_E_INVALID_CLASS) {
                printf("ERROR: Toaster driver may not be active on the system.\n");
            }
            goto exit;
        }

        //
        // To obtain the object path of the object for which the method has to be
        // executed, query the "__PATH" property of the WMI instance object.
        //
        status = instanceObj->Get(_bstr_t(L"__PATH"), 0, &instProperty, 0, 0);
        if (FAILED(status)) {
            goto exit;
        }

        printf("\n");
        printf("Instance Path .: %ws\n", (wchar_t*)instProperty.bstrVal);

        //
        // Get the current value of the DummyValue property.
        //
        status = instanceObj->Get(TOASTER_VAR1, 0, &instProperty, NULL, NULL);
        if (FAILED(status)) {
            goto exit;
        }

        printf("  Property ....: %ws\n", TOASTER_VAR1);
        printf("  Old Value ...: %d\n", instProperty.lVal);

        //
        // Set a new value for the DummyValue property.
        //
        instProperty.lVal++;

        status = instanceObj->Put(TOASTER_VAR1, 0, &instProperty, 0);
        if (FAILED(status)) {
            goto exit;
        }

        status = WbemServices->PutInstance(instanceObj,
                                           WBEM_FLAG_UPDATE_ONLY,
                                           NULL,
                                           NULL);
        if (FAILED(status)) {
            goto exit;
        }

        status = instanceObj->Get(_bstr_t(TOASTER_VAR1), 0, &instProperty, NULL, NULL);
        if (FAILED(status)) {
            goto exit;
        }

        printf("  New Value ...: %d\n", instProperty.lVal);

        instanceObj->Release();
        instanceObj = NULL;

    } while (!FAILED(status));

exit:

    if (className != NULL) {
        SysFreeString(className);
    }

    if (classObj != NULL) {
        classObj->Release();
    }

    if (enumerator != NULL) {
        enumerator->Release();
    }

    if (instanceObj != NULL) {
        instanceObj->Release();
    }

    return status;
}
Esempio n. 3
0
int ipmi_cmdraw_ms(uchar cmd, uchar netfn, uchar lun, uchar sa,
		uchar bus, uchar *pdata, int sdata, uchar *presp, int *sresp, 
		uchar *pcc, char fdebugcmd)
{
   int bRet;
   HRESULT hres;
   IWbemClassObject* pInParams = NULL; /*class definition*/
   IWbemClassObject* pInReq = NULL;    /*instance*/
   IWbemClassObject* pOutResp = NULL;
   VARIANT varCmd, varNetfn, varLun, varSa, varSize, varData;
   SAFEARRAY* psa = NULL;
   long i;
   uchar *p;

   fdebugms = fdebugcmd;
   if (!fmsopen) {
      bRet = ipmi_open_ms(fdebugcmd);
      if (bRet != 0) return(bRet);
   }
   bRet = -1;


   hres = pClass->GetMethod(L"RequestResponse",0,&pInParams,NULL);
   if (FAILED(hres)) {
        if (fdebugcmd) 
	     printf("ipmi_cmdraw_ms: Cannot get RequestResponse method\n");
        return (bRet);
   }

#ifdef WDM_FIXED
   /* see http://support.microsoft.com/kb/951242 for WDM bug info */
   hres = pInParams->SpawnInstance(0,&pInReq);
   if (FAILED(hres)) {
        if (fdebugcmd) 
	     printf("ipmi_cmdraw_ms: Cannot get RequestResponse instance\n");
        return (bRet);
   }
   // also substitute pInReq for pInParams below if this gets fixed.
#endif

   VariantInit(&varCmd);
   varCmd.vt = VT_UI1;
   varCmd.bVal = cmd;
   hres = pInParams->Put(_bstr_t(L"Command"), 0, &varCmd, 0);
   // VariantClear(&varCmd);
   if (FAILED(hres)) goto MSRET;

   VariantInit(&varNetfn);
   varNetfn.vt = VT_UI1;
   varNetfn.bVal = netfn;
   hres = pInParams->Put(_bstr_t(L"NetworkFunction"), 0, &varNetfn, 0);
   // VariantClear(&varNetfn);
   if (FAILED(hres)) goto MSRET;

   VariantInit(&varLun);
   varLun.vt = VT_UI1;
   varLun.bVal = lun;
   hres = pInParams->Put(_bstr_t(L"Lun"), 0, &varLun, 0);
   // VariantClear(&varLun);
   if (FAILED(hres)) goto MSRET;

   VariantInit(&varSa);
   varSa.vt = VT_UI1;
   varSa.bVal = sa;
   hres = pInParams->Put(_bstr_t(L"ResponderAddress"), 0, &varSa, 0);
   // VariantClear(&varSa);
   if (FAILED(hres)) goto MSRET;

   VariantInit(&varSize);
   varSize.vt = VT_I4;
   varSize.lVal = sdata;
   hres = pInParams->Put(_bstr_t(L"RequestDataSize"), 0, &varSize, 0);
   // VariantClear(&varSize);
   if (FAILED(hres)) goto MSRET;

   SAFEARRAYBOUND rgsabound[1];
   rgsabound[0].cElements = sdata;
   rgsabound[0].lLbound = 0;
   psa = SafeArrayCreate(VT_UI1,1,rgsabound);
   if(!psa) {
      printf("ipmi_cmdraw_ms: SafeArrayCreate failed\n");
      goto MSRET;
   }
#ifdef SHOULD_WORK_BUT_NO
   /* The SafeArrayPutElement does not put the data in the right 
    * place, so skip this and copy the raw data below. */
   VARIANT tvar;
   if (fdebugcmd && sdata > 0) 
	{ printf("psa1(%p):",psa); dumpbuf((uchar *)psa,42,1); }   

   for(i =0; i< sdata; i++)
   {
      VariantInit(&tvar);
      tvar.vt = VT_UI1;
      tvar.bVal = pdata[i];
      hres = SafeArrayPutElement(psa, &i, &tvar);
      // VariantClear(&tvar);
      if (FAILED(hres)) { 
         printf("ipmi_cmdraw_ms: SafeArrayPutElement(%d) failed\n",i);
         goto MSRET;
      }
   } /*end for*/
   if (fdebugcmd && sdata > 0) 
	{ printf("psa2(%p):",psa); dumpbuf((uchar *)psa,42,1); }  
#endif

   /* Copy the real RequestData into psa */
   memcpy(psa->pvData,pdata,sdata);

   VariantInit(&varData);
   varData.vt = VT_ARRAY | VT_UI1;
   varData.parray = psa;
   hres = pInParams->Put(_bstr_t(L"RequestData"), 0, &varData, 0);
   // VariantClear(&varData);
   if (FAILED(hres)) {
	printf("Put(RequestData) error %x\n",hres);
        goto MSRET;
   }

#ifdef TEST_METHODS
   IWbemClassObject* pOutSms = NULL;
   if (fdebugcmd) printf("ipmi_cmdraw_ms: calling SMS_Attention(%ls)\n",
			  V_BSTR(&varPath)); 
   hres = pSvc->ExecMethod( V_BSTR(&varPath), _bstr_t(L"SMS_Attention"), 
				0, NULL, NULL, &pOutSms, NULL);
   if (FAILED(hres)) {
	printf("ipmi_cmdraw_ms: SMS_Attention method error %x\n",hres);
        goto MSRET;
   }
   if (fdebugcmd) printf("ipmi_cmdraw_ms: SMS_Attention method ok\n"); 
   /* This does work, without input parameters */
   pOutSms->Release();
#endif

   hres = pSvc->ExecMethod( V_BSTR(&varPath), _bstr_t(L"RequestResponse"), 
				0, NULL, pInParams, &pOutResp, NULL);
   if (fdebugcmd) {
       printf("ipmi_cmdraw_ms(cmd=%x,netfn=%x,lun=%x,sa=%x,sdata=%d)"
	      " RequestResponse ret=%x\n", cmd,netfn,lun,sa,sdata,hres); 
       if (sdata > 0) {
	   printf("ipmi_cmdraw_ms: req data(%d):",sdata); 
	   dumpbuf(pdata,sdata,0); 
       }
   }
   if (FAILED(hres)) {
	printf("ipmi_cmdraw_ms: RequestResponse error %x %s\n",
		hres,res_str(hres));
#ifdef EXTRA_DESC
	/* This does not usually add any meaning for IPMI. */
	BSTR desc;
	IErrorInfo *pIErrorInfo;
	GetErrorInfo(0,&pIErrorInfo);
	pIErrorInfo->GetDescription(&desc);
	printf("ipmi_cmdraw_ms: ErrorInfoDescr: %ls\n",desc);
	SysFreeString(desc);
#endif
	bRet = -1; 
	/*fall through for cleanup and return*/
   }
   else {  /*successful, get ccode and response data */
	VARIANT varByte, varRSz, varRData;
        VariantInit(&varByte);
        VariantInit(&varRSz);
        VariantInit(&varRData);
	long rlen;

	hres = pOutResp->Get(_bstr_t(L"CompletionCode"),0, &varByte, NULL, 0);
	if (FAILED(hres)) goto MSRET;
	if (fdebugcmd) printf("ipmi_cmdraw_ms: CompletionCode %x returned\n",
				V_UI1(&varByte) );
	*pcc = V_UI1(&varByte);

	hres = pOutResp->Get(_bstr_t(L"ResponseDataSize"),0, &varRSz, NULL, 0);
	if (FAILED(hres)) goto MSRET;
        rlen = V_I4(&varRSz);
	if (rlen > 1) rlen--;   /*skip cc*/
	if (rlen > *sresp) {
	   if (fdebugcmd) printf("ResponseData truncated from %d to %d\n",
					rlen,*sresp);
	   rlen = *sresp; /*truncate*/
	}
	*sresp = (int)rlen;

	hres = pOutResp->Get(_bstr_t(L"ResponseData"),0, &varRData, NULL,0);
	if (FAILED(hres)) { /*ignore failure */ 
	   if (fdebugcmd) printf("Get ResponseData error %x\n",hres); 
	} else {  /* success */
#ifdef SHOULD_WORK_BUT_NO
	    uchar *pa;
	    p = (uchar*)varRData.parray->pvData;
	    pa = (uchar*)varRData.parray;
	    printf("pa=%p, pa+12=%p p=%p\n",pa,(pa+12),p);
	    if (fdebugcmd) {   
		 printf("Data.vt = %04x, Data.parray(%p):",
			varRData.vt, varRData.parray); 
	         // 0x2011 means VT_ARRAY | VT_UI1
		 dumpbuf((uchar *)varRData.parray,40,1);
	    }
	    /* The SafeArrayGetElement does not get the data from the right 
	     * place, so skip this and copy the raw data below. */
	    VARIANT rgvar[NVAR];
	    if (rlen > NVAR) *pcc = 0xEE; 
	    for (i = 0; i <= rlen; i++)
         	VariantInit(&rgvar[i]);
	    /* copy the response data from varRData to presp */
	    for( i = 0; i <= rlen; i++)
	    {
		hres = SafeArrayGetElement(varRData.parray, &i, &rgvar[i]);
		if (FAILED(hres)) { 
		   if (fdebugcmd)
		      printf("ipmi_cmdraw_ms: SafeArrayGetElement(%d) failed\n",i);
		   break;
		}
		if (fdebugcmd) {   
		     printf("Data[%d] vt=%02x val=%02x, rgvar(%p):",i,
				rgvar[i].vt, V_UI1(&rgvar[i]),&rgvar[i]);
		     dumpbuf((uchar *)&rgvar[i],12,0);
		}
	        /* skip the completion code */
	    	// if (i > 0) presp[i-1] = V_UI1(&rgvar[i]);
	    } /*end for*/
#endif
	    /* 
	     * parray from a GetDeviceId response:
	     * 0015CEE0: 01 00 80 00 01 00 00 00 00 00 00 00 00 cf 15 00
	     * 0015CEF0: 10 00 00 00 00 00 00 00 03 00 06 00 95 01 08 00
             *           ^- datalen=0x10
	     * 0015CF00: 00 20 01 00 19 02 9f 57 01 ...  
             *           ^- start of data (cc=00, ...)
	     */
	    /* Copy the real ResponseData into presp. */
	    p = (uchar*)varRData.parray->pvData;
	    for( i = 0; i <= rlen; i++) {
	        /* skip the completion code */
	    	if (i > 0) presp[i-1] = p[i];
	    }
	    if (fdebugcmd) {
		printf("ipmi_cmdraw_ms: resp data(%d):",rlen+1); 
		dumpbuf(p,rlen+1,0); 
	    }
	}
	bRet = 0;
   }

MSRET:
#define CLEAN_OK  1
#ifdef CLEAN_OK
   /* VariantClear(&var*) should be done by pInParams->Release() */
   if (psa != NULL) SafeArrayDestroy(psa);
   if (pInParams != NULL) pInParams->Release();
   if (pOutResp != NULL) pOutResp->Release();
#endif
   return(bRet);
}
Esempio n. 4
0
int main(int iArgCnt, char ** argv)
{
    IWbemLocator *pLocator = NULL;
    IWbemServices *pNamespace = 0;
    IWbemClassObject * pClass = NULL;
    IWbemClassObject * pOutInst = NULL;
    IWbemClassObject * pInClass = NULL;
    IWbemClassObject * pInInst = NULL;
	BSTR Text = NULL;
	HRESULT hr = S_OK;
  
    BSTR path = SysAllocString(L"root\\default");
    BSTR ClassPath = SysAllocString(L"MethProvSamp");
    BSTR MethodName = SysAllocString(L"Echo");
    BSTR ArgName = SysAllocString(L"sInArg");

	if (!path || ! ClassPath || !MethodName || ! ArgName)
	{
		printf("SysAllocString failed. Out of memory.\n");
		goto cleanup;
	}
  

    // Initialize COM and connect up to CIMOM

    hr = CoInitialize(0);
	if (FAILED(hr))
	{
	    printf("CoInitialize returned 0x%x:", hr);
		goto cleanup;
	}

	//  NOTE:
	//  When using asynchronous WMI API's remotely in an environment where the "Local System" account 
	//  has no network identity (such as non-Kerberos domains), the authentication level of 
	//  RPC_C_AUTHN_LEVEL_NONE is needed. However, lowering the authentication level to 
	//  RPC_C_AUTHN_LEVEL_NONE makes your application less secure. It is wise to
	//	use semi-synchronous API's for accessing WMI data and events instead of the asynchronous ones.

    hr = CoInitializeSecurity	( NULL, -1, NULL, NULL,
					RPC_C_AUTHN_LEVEL_PKT_PRIVACY, 
					RPC_C_IMP_LEVEL_IMPERSONATE, 
					NULL, 
					EOAC_SECURE_REFS, //change to EOAC_NONE if you change dwAuthnLevel to RPC_C_AUTHN_LEVEL_NONE
					NULL );
	if (FAILED(hr))
	{
	    printf("CoInitializeSecurity returned 0x%x:", hr);
		goto cleanup;
	}

    hr = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER,
            IID_IWbemLocator, (LPVOID *) &pLocator);
	if (FAILED(hr))
	{
	    printf("CoCreateInstance returned 0x%x:", hr);
		goto cleanup;
	}
    hr = pLocator->ConnectServer(path, NULL, NULL, NULL, 0, NULL, NULL, &pNamespace);
    printf("\n\nConnectServer returned 0x%x:", hr);
    if(hr != WBEM_S_NO_ERROR)
		goto cleanup;

    // Get the class object

    hr = pNamespace->GetObject(ClassPath, 0, NULL, &pClass, NULL);
    printf("\nGetObject returned 0x%x:", hr);
    if(hr != WBEM_S_NO_ERROR)
		goto cleanup;

    // Get the input argument and set the property

    hr = pClass->GetMethod(MethodName, 0, &pInClass, NULL); 
    printf("\nGetMethod returned 0x%x:", hr);
    if(hr != WBEM_S_NO_ERROR)
		goto cleanup;

    hr = pInClass->SpawnInstance(0, &pInInst);
    printf("\nSpawnInstance returned 0x%x:", hr);
    if(hr != WBEM_S_NO_ERROR)
		goto cleanup;

    VARIANT var;
    var.vt = VT_BSTR;
    var.bstrVal= SysAllocString(L"hello");
    if (var.bstrVal == NULL)
		goto cleanup;
    hr = pInInst->Put(ArgName, 0, &var, 0);
    VariantClear(&var);

    // Call the method

    hr = pNamespace->ExecMethod(ClassPath, MethodName, 0, NULL, pInInst, &pOutInst, NULL);
    printf("\nExecMethod returned 0x%x:", hr);
    if(hr != WBEM_S_NO_ERROR)
		goto cleanup;

    
    // Display the results.

    hr = pOutInst->GetObjectText(0, &Text);
	if(hr != WBEM_S_NO_ERROR)
		goto cleanup;
    printf("\n\nThe object text of the output object is:\n%S", Text);
    
	printf("Terminating normally\n");


	// Free up resources
cleanup:

    SysFreeString(path);
    SysFreeString(ClassPath);
    SysFreeString(MethodName);
    SysFreeString(ArgName);
    SysFreeString(Text);

	if (pClass)
		pClass->Release();
	if (pInInst)
		pInInst->Release();
	if (pInClass)
		pInClass->Release();
	if (pOutInst)
		pOutInst->Release();
	if (pLocator)
		pLocator->Release();
	if (pNamespace)
		pNamespace->Release();
    CoUninitialize();
    return 0;
}
bool StoreSD(IWbemServices * pSession, PSECURITY_DESCRIPTOR pSD)
{
    bool bRet = false;
    HRESULT hr;

	if (!IsValidSecurityDescriptor(pSD))
		return false;

    // Get the class object

    IWbemClassObject * pClass = NULL;
    _bstr_t InstPath(L"__systemsecurity=@");
    _bstr_t ClassPath(L"__systemsecurity");
    hr = pSession->GetObject(ClassPath, 0, NULL, &pClass, NULL);
    if(FAILED(hr))
        return false;

    // Get the input parameter class

    _bstr_t MethName(L"SetSD");
    IWbemClassObject * pInClassSig = NULL;
    hr = pClass->GetMethod(MethName,0, &pInClassSig, NULL);
    pClass->Release();
    if(FAILED(hr))
        return false;

    // spawn an instance of the input parameter class

    IWbemClassObject * pInArg = NULL;
    pInClassSig->SpawnInstance(0, &pInArg);
    pInClassSig->Release();
    if(FAILED(hr))
        return false;


    // move the SD into a variant.

    SAFEARRAY FAR* psa;
    SAFEARRAYBOUND rgsabound[1];    rgsabound[0].lLbound = 0;
    long lSize = GetSecurityDescriptorLength(pSD);
    rgsabound[0].cElements = lSize;
    psa = SafeArrayCreate( VT_UI1, 1 , rgsabound );
    if(psa == NULL)
    {
        pInArg->Release();
        return false;
    }

    char * pData = NULL;
    hr = SafeArrayAccessData(psa, (void HUGEP* FAR*)&pData);
    if(FAILED(hr))
    {
        pInArg->Release();
        return false;
    }

    memcpy(pData, pSD, lSize);

    SafeArrayUnaccessData(psa);
    _variant_t var;
    var.vt = VT_I4|VT_ARRAY;
    var.parray = psa;

    // put the property

    hr = pInArg->Put(L"SD" , 0, &var, 0);      
    if(FAILED(hr))
    {
        pInArg->Release();
        return false;
    }

    // Execute the method

    IWbemClassObject * pOutParams = NULL;
    hr = pSession->ExecMethod(InstPath,
            MethName,
            0,
            NULL, pInArg,
            NULL, NULL);
    if(FAILED(hr))
        printf("\nPut failed, returned 0x%x",hr);

    return bRet;
}
Esempio n. 6
0
File: wmi.cpp Progetto: 0x00ach/CRET
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//	Description :
//		Sends WMI command to target after logging on.
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
DWORD startWMICommand(char* command, char* target, char* username, char* password)
{	
	HRESULT hres;
	IWbemLocator *pLoc = NULL;
	IWbemServices *pSvc = NULL;
	COAUTHIDENTITY *userAcct =  NULL ;
	COAUTHIDENTITY authIdent;
	char* serverWMIA;
	PWCHAR serverWMIW;
	PWCHAR usernameW;
	PWCHAR commandW;
	PWCHAR passwordW;
	WCHAR pszDomain[CREDUI_MAX_USERNAME_LENGTH+1];
	WCHAR pszUserName[CREDUI_MAX_USERNAME_LENGTH+1];
	PWCHAR slash;
	int len = 0;

	// WCHAR
	len = strlen(target)+12;
	serverWMIA = (char*)malloc(sizeof(char)*(len));
	strcpy_s(serverWMIA, len, target);
	strcat_s(serverWMIA, len, "\\ROOT\\CIMV2");
	len = MultiByteToWideChar(CP_ACP,0,serverWMIA,-1,NULL,0);
	serverWMIW = (PWCHAR)malloc(sizeof(WCHAR)*len);
	MultiByteToWideChar(CP_ACP,0,serverWMIA,-1,serverWMIW,len);
	free(serverWMIA);
	len = MultiByteToWideChar(CP_ACP,0,username,-1,NULL,0);
	usernameW = (PWCHAR)malloc(sizeof(WCHAR)*len);
	MultiByteToWideChar(CP_ACP,0,username,-1,usernameW,len);
	len = MultiByteToWideChar(CP_ACP,0,password,-1,NULL,0);
	passwordW = (PWCHAR)malloc(sizeof(WCHAR)*len);
	MultiByteToWideChar(CP_ACP,0,password,-1,passwordW,len);
	len = MultiByteToWideChar(CP_ACP,0,command,-1,NULL,0);
	commandW = (PWCHAR)malloc(sizeof(WCHAR)*len);
	MultiByteToWideChar(CP_ACP,0,command,-1,commandW,len);

	hres =  CoInitializeEx(0, COINIT_MULTITHREADED); 
	if(hres<0)
	{
		free(usernameW);
		free(passwordW);
		free(commandW);
		free(serverWMIA);
		free(serverWMIW);
		return -1;
	}
	hres =  CoInitializeSecurity(NULL,-1,NULL,NULL,RPC_C_AUTHN_LEVEL_DEFAULT,RPC_C_IMP_LEVEL_IDENTIFY,NULL,EOAC_NONE,NULL);	   
	if(hres<0)
	{
		free(usernameW);
		free(passwordW);
		free(commandW);
		free(serverWMIA);
		free(serverWMIW);
		CoUninitialize();
		return -1;
	}
	hres = CoCreateInstance(CLSID_WbemLocator,0,CLSCTX_INPROC_SERVER,IID_IWbemLocator, (LPVOID *) &pLoc);
	if(hres<0)
	{
		free(usernameW);
		free(passwordW);
		free(commandW);
		free(serverWMIA);
		free(serverWMIW);
		CoUninitialize();
		return -1;
	}

	//WMI connection
	hres = pLoc->ConnectServer(_bstr_t(serverWMIW),_bstr_t(usernameW),_bstr_t(passwordW),NULL,NULL,NULL,NULL,&pSvc);
	if(hres<0)
	{
		free(usernameW);
		free(passwordW);
		free(commandW);
		free(serverWMIA);
		free(serverWMIW);
		pLoc->Release();	 
		CoUninitialize();
		return -1;
	}

	//Set ProxyBlanket options
	memset(&authIdent, 0, sizeof(COAUTHIDENTITY));
	authIdent.PasswordLength = wcslen (passwordW);
	authIdent.Password = (USHORT*)passwordW;
	slash = wcschr (usernameW, L'\\');
	if(slash == NULL)
	{
		free(usernameW);
		free(passwordW);
		free(commandW);
		free(serverWMIA);
		free(serverWMIW);
		pSvc->Release();
		pLoc->Release();	 
		CoUninitialize();
		return -1;
	}
	wcscpy_s(pszUserName,CREDUI_MAX_USERNAME_LENGTH+1, slash+1);
	authIdent.User = (USHORT*)pszUserName;
	authIdent.UserLength = wcslen(pszUserName);
	wcsncpy_s(pszDomain, CREDUI_MAX_USERNAME_LENGTH+1, usernameW, slash - usernameW);
	authIdent.Domain = (USHORT*)pszDomain;
	authIdent.DomainLength = slash - usernameW;
	authIdent.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
	userAcct = &authIdent;
	
	//Set the ProxyBlanket
	hres = CoSetProxyBlanket(pSvc,RPC_C_AUTHN_DEFAULT,RPC_C_AUTHZ_DEFAULT,COLE_DEFAULT_PRINCIPAL,RPC_C_AUTHN_LEVEL_PKT_PRIVACY,RPC_C_IMP_LEVEL_IMPERSONATE,userAcct,EOAC_NONE);
	if(hres<0)
	{
		free(usernameW);
		free(passwordW);
		free(commandW);
		free(serverWMIA);
		free(serverWMIW);
		pSvc->Release();
		pLoc->Release();	 
		CoUninitialize();
		return -1;
	}


	BSTR MethodName = SysAllocString(L"Create");
	BSTR ClassName = SysAllocString(L"Win32_Process");

	IWbemClassObject* pClass = NULL;
	hres = pSvc->GetObject(ClassName, 0, NULL, &pClass, NULL);
	IWbemClassObject* pInParamsDefinition = NULL;
	hres = pClass->GetMethod(MethodName, 0, 
		&pInParamsDefinition, NULL);
	IWbemClassObject* pClassInstance = NULL;
	hres = pInParamsDefinition->SpawnInstance(0, &pClassInstance);

	// Create the values for the "in" parameters
	VARIANT varCommand;
	varCommand.vt = VT_BSTR;
	varCommand.bstrVal = BSTR(commandW);

	// Store the value for the "in" parameters
	hres = pClassInstance->Put(L"CommandLine", 0, &varCommand, 0);

	 // Execute Method
	IWbemClassObject* pOutParams = NULL;
	hres = pSvc->ExecMethod(ClassName, MethodName, 0,
	NULL, pClassInstance, &pOutParams, NULL);

	if (FAILED(hres))
	{
		free(usernameW);
		free(passwordW);
		free(commandW);
		free(serverWMIA);
		free(serverWMIW);
		VariantClear(&varCommand);
		SysFreeString(ClassName);
		SysFreeString(MethodName);
		pClass->Release();
		pInParamsDefinition->Release();
		pOutParams->Release();
		pSvc->Release();
		pLoc->Release();	 
		CoUninitialize();
		return -1;
	}


	free(usernameW);
	free(passwordW);
	free(commandW);
	free(serverWMIA);
	free(serverWMIW);
	SecureZeroMemory(pszUserName, sizeof(pszUserName));
	SecureZeroMemory(pszDomain, sizeof(pszDomain));
	VariantClear(&varCommand);
	SysFreeString(ClassName);
	SysFreeString(MethodName);
	pClass->Release();
	pInParamsDefinition->Release();
	pOutParams->Release();
	pSvc->Release();
	pLoc->Release();
	CoUninitialize();

	return 0;
}