cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Running Powershell directly via the IQService

Running Powershell directly via the IQService

It's sometimes necessary to run a Powershell script "out of band" (i.e. from a Workflow or Run Rule task). This is not well-suited to the Before/After model used by IQService connectors. In this article, I will go through how the IQService invokes Powershell and how you can hook into this process to run your own Powershell scripts.

I've seen a lot of code floating around for calling Powershell, but nothing that explains why you're using that specific code.

Calling the IQService from code

The IQService is a .NET application that listens on a configured port for commands from IIQ. These commands are XML-RPC blobs that are encrypted using TLS and/or an agreed-upon private key. Ordinarily, usage of the IQService is buried within IIQ's connector code. However, since you can use any part of the IdentityIQ API in your custom workflows and rules, the IQService classes are available for you too.

These are:

  • RPCService: The service class that handles all of the communication from IIQ to the IQService, including serialization and encryption of requests and responses.

  • RpcRequest: Wraps a request to the IQService, designating which type of command is being sent and what the arguments to that command are. Different commands will require different arguments, but you'll always be using the ScriptExecutor command.

  • RpcResponse: Wraps the response from the IQService. What gets returned depends heavily on what the command is, as we'll see below.

To make a call to a Powershell script, you will need to:

  • Construct an RpcRequest using a service name of ScriptExecutor, also passing your Powershell code and other arguments.

  • Construct an RPCService instance, passing the connection parameters for your IQService instance.

  • Invoke RPCService.execute() against your RpcRequest.

  • Interpret the RpcResponse returned from execute().

The ScriptExecutor service

The IQService exposes the ScriptExecutor service for running command line utilities. This can run not only Powershell but also Windows bash or other command line tools. The parameters to the command in question are passed as part of your RpcRequest.

There are two types (more or less) of script executors:

  • runBeforeScript: In the usual model, these are intended to run before execution, like a Before Provisioning rule. Consequently, they can modify the passed AccountRequest, but they cannot return any errors, warnings, or other messages.

  • runAfterScript: In the usual model, these are intended to run after execution, like an After Provisioning rule. Consequently, they cannot modify the passed AccountRequest (because it's already been executed). However, they can return errors, warnings, or other messages.

For a runBeforeScript, you must pass a preScript parameter with your Rule. For a runAfterScript, you must pass a postScript parameter with your Rule.

I tend to prefer runAfterScript for ad hoc Powershell, just because returning error messages is useful.

The code

The following is the simplest bit of code that will invoke Powershell on the server. Note the use of postScript and runAfterScript.

import sailpoint.object.RpcRequest;
import sailpoint.object.RpcResponse;
import sailpoint.connector.RPCService;

Map data = new HashMap();
data.put("postScript", yourPowershellRuleObject);
RPCService service = new RPCService(iqServiceHost, iqServicePort, false, useTLS);
RpcRequest request = new RpcRequest("ScriptExecutor", "runAfterScript", data);
RpcResponse response = service.execute(request);

If you want to pass additional values to your script, you will need use the AccountRequest object. Specifically, create a new AccountRequest and add any parameters you'd like to pass as AttributeRequests. This must be added to your data Map as the field Request. 

This Request field is not optional, even if you don't actually use it. Your RPC call will fail if you don't include it.

// Fake account request
AccountRequest accountRequest = new AccountRequest();
accountRequest.setApplication("IIQ");
accountRequest.setNativeIdentity("*FAKE*");
accountRequest.setOperation(AccountRequest.Operation.Modify);

// Fake attribute request
AttributeRequest fakeAttribute = new AttributeRequest();
fakeAttribute.setOperation(Operation.Add);
fakeAttribute.setName(paramName);
fakeAttribute.setValue(paramValue);
fakeAttributeRequests.add(fakeAttribute);
accountRequest.setAttributeRequests(fakeAttributeRequests);

// Add to the IQService params
data.put("Request", accountRequest);

Client authentication

If you are using client authentication, a newer security feature for the IQService available since 2019, you will need to additionally pass an Application object's Attributes with IQService configuration in your parameters.

For example:

Application ad = context.getObjectByName(Application.class, "Customer Active Directory");
data.put("Application", ad.getAttributes());

The RPCService will automatically use the configuration stored in that application, specifically the IQServiceUser and IQServicePassword attributes.

You will also need to provide it with an instance of ConnectorServices, which the RPCService will use to decrypt the passwords stored in the Application object. Failing to do this will result in a NullPointerException.

service.setConnectorServices(new sailpoint.connector.DefaultConnectorServices());

The Powershell side

Temporary script file

The IQService will write your entire Rule's source to a temporary file, which by default is in the same directory. These files are intended to be deleted once the script completes, but the IQService is (for some reason) sometimes unable to do that. If you see a number of temp objects piling up in your IQService folder, you can safely delete them.

However, since the IQService writes each script to disk, you should not hardcode any credentials in your Powershell rules.

Receiving the input

Receiving the values passed to Powershell rules (in that fake AccountRequest) is a bit convoluted. To support various types of command line scripts, the IQService passes all parameters as environment variables. To make things more confusing, it passes them in the environment variables as XML.

Reading your AccountRequest input in Powershell thus looks like:

Add-type -path utils.dll
$sReader = New-Object System.IO.StringReader([System.String]$env:Request); 
$xmlReader = [System.xml.XmlTextReader]([sailpoint.Utils.xml.XmlUtil]::getReader($sReader)); 
$requestObject = New-Object Sailpoint.Utils.objects.AccountRequest($xmlReader);
$resultObject = New-Object Sailpoint.Utils.objects.ServiceResult;

In the first line, utils.dll is a utility provided by SailPoint that exposes several useful Powershell object types. We are using some .NET classes to read the data out of $env:Request, which is where the IQService stuffs our AccountRequest object.

Finally, we create a Sailpoint.Utils.objects.ServiceResult, which we'll use later to return the results from our script.

Interpreting the input

To interpret the Powershell input, you will need to read the data out of the AccountRequest. Fortunately, the API is identical to that in IIQ Beanshell. To make things easier, though, I like to build a Powershell hash object (i.e. a Map) with the data.

$attributes = @{}
foreach ($attribute in $requestObject.AttributeRequests){
$attributes[$attribute.Name] = $attribute.Value;
}

After this code, you can simply refer to $attributes["name"] to get at your passed data. Note that printing this value will just produce a hash.

Handling output

Once you've completed your Powershell actions, you will need to return some values back to IIQ. You will do this by dumping an object XML to the filename passed as the first parameter to your script. The IQService will read an appropriate object out of that file and pass it back to IIQ. (As with the input, this indirect method is used so that any number of scripting interfaces, not only Powershell, can be invoked by the IQService.)

I like to wrap the entire thing in a Try/Catch/Finally block so that the output is always written and errors are properly handled.

Try {
# Handle input and do stuff here
$resultObject.Messages.add("Success!");
} catch [Exception] {   
# You should probably do some logging here too
$ErrorMessage = $_.Exception.ToString()
$resultObject.Errors.add($ErrorMessage);
} finally {
$resultObject.toxml() | out-file $args[0];
}  

The "magic" takes place in the finally block, in which the $resultObject that we constructed earlier is exported as XML to the destination file. As with the rule source, this output object is being written to disk, so you should not store any sensitive data in your script output.

You can return Messages and Errors, which are simply Powershell lists of string.

For returning more complex objects, use the Attributes hashtable stored on the ServiceResult object. The keys must be strings, but the values can be a variety of simple object types - strings, numbers, dates, hashtables, lists, and byte arrays. Other objects that are not handled by the XML serializer will be dropped from the response, so make sure you convert your data to a handled type.

$resultObject.Attributes["someVariable"] = $someResultObject;

Using a wrapper script

It's nice to avoid boilerplate code wherever possible. To do this, I usually write a Powershell script that resides locally on the IQService host, e.g. in a D:\IQService\Scripts folder, and invoke those scripts once I've parsed my input. The rules in IIQ are responsible only for ensuring that the correct data is passed to the local scripts.

This also means that those scripts can be reused outside of IIQ, e.g. as part of a batch operation or an administrator action.

Back in IIQ: Interpreting the output

Your $resultObject will be returned to IIQ as an RpcResponse. This will contain any errors, messages, or attributes your Powershell script produced. You may want to create a standard method to check for errors and throw an exception. The following is a barebones error handler.

(Remember that, like most IIQ APIs, pretty much anything can be null at any time.)

public RpcResponse checkRpcFailure(RpcResponse response) throws Exception {
if (response == null) {
return null;
}
if (response.getErrors() != null && response.getErrors().size() > 0) {
throw new IllegalStateException(response.getErrors().toString());
}
return response;
}

 You can use this waaaaay back up in the RPCService code like so:

RpcResponse response = checkRpcFailure(service.execute(request));

If you need to return structured data, passing textual values like JSON or XML as part of a Message is one option, as is returning it as part of the Attributes. See what works best for your purposes.

Comments

Hi @gabriel_daems ,

 

"yourPowershellRuleObject" is just a ConnectorAfterCreate rule.

Here's an example:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE Rule PUBLIC "sailpoint.dtd" "sailpoint.dtd">
<Rule language="beanshell" name="yourPowershellRuleObject" type="ConnectorAfterCreate">
  <Attributes>
    <Map>
      <entry key="ObjectOrientedScript" value="true"/>
      <entry key="disabled" value="false"/>
      <entry key="extension" value=".ps1"/>
      <entry key="program" value="powershell.exe"/>
      <entry key="timeout" value="120"/>
    </Map>
  </Attributes>
  <Description>  
  This example is for IQService Script.    
  </Description>
  <Signature returnType="Map">
    <Inputs>
      <Argument name="email">
        <Description>
            Email address to call powershell script 
        </Description>
      </Argument>
    </Inputs>
    <Returns>
      <Argument name="response">
        <Description>
            Response of the Powershell script.
          </Description>
      </Argument>
    </Returns>
  </Signature>
  <Source>
Add-type -path "C:\Program Files\IQS\Utils.dll";

# Read the environment variables
$sReader = New-Object System.IO.StringReader([System.String]$env:Request);
   
$xmlReader = [System.xml.XmlTextReader]([sailpoint.Utils.xml.XmlUtil]::getReader($sReader)); 
$requestObject = New-Object Sailpoint.Utils.objects.AccountRequest($xmlReader);
$resultObject = New-Object Sailpoint.Utils.objects.ServiceResult;

#Check if the request was processed successfully
foreach ($attribute in $requestObject.AttributeRequests){
	if($attribute.Name -eq "email"){
		$attribute.Value |  Out-File -filepath C:\Scripts\email.txt
		$result=C:\Scripts\charlietest.ps1 $attribute.Value
	}
}

"Result IS $result $args" | Out-File -filepath C:\Scripts\homedirresult.txt
[System.Collections.ArrayList]$messagesList = @()

if($result -ne 0) {
	$messagesList.Add("An error occured");
	$messagesList.Add($result);
	"ResultObject is $resultObject" | Out-File -Append -filepath C:\Scripts\result.txt
	$resultObject.Errors = $messagesList
	$resultObject.toxml() | Out-File -Append -filepath C:\Scripts\result.txt
}
  
$env:Result = $resultObject.toxml()
$PSCommandPath = $MyInvocation.MyCommand.Path
$PSCommandPath = $PSCommandPath.replace(".ps1",".tmp")
$resultObject.toxml()
$resultObject.toxml() | Out-File -FilePath $PSCommandPath -Append;
  </Source>
</Rule>

@Charlie  yes obvious now. Thank you

Hello. Is there a way of specifying the user and password where the script in the IQService server will be run as? Or it just uses the user the IQService is running as, which by default is local system. I saw the following as part of a training material that is supposed to be supported as the rule parameters:

Additional attributes within the rule itself control:
ObjectOrientedScript (true/false)
disabled (true/false)
extension (.bat or .ps1)
program ( Cmd.exe or PowerShell.exe)
timeout (value in minutes)
user
password (encrypted with iiq encypt command)

But when we try we get a base64 decode error 

Invalid length for a Base-64 char array or string.

We are using IIQ 7.3SP1

@josemdavila I was looking for the same feature/behaviour but it never worked on my side (7.3p4). I can confirm it is using the script of the IQService is runnning as. Thus we decided to run the IQService with a different user (other than local system).

Happy to see these 2 variables working soon ...

Thanks. Let's see if more detailed information is published regarding this

@drosenbauer 

I am trying to follow this approach but regardless what I have in my rule, it always gives an error "Exception occured in executing the script : Object reference not set to an instance of an object."

 

 

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE Rule PUBLIC "sailpoint.dtd" "sailpoint.dtd">
<Rule language="beanshell" name="Test Rule">
	<Source>
	<![CDATA[
	import sailpoint.object.RpcRequest;
	import sailpoint.object.RpcResponse;
	import sailpoint.connector.RPCService;
	import sailpoint.object.Rule;
	import sailpoint.object.Application;
	import sailpoint.object.ProvisioningPlan.AccountRequest;
	
	Map data = new HashMap();
	
	Rule rule = context.getObjectByName(Rule.class, "Rule Name");
	data.put("postScript", rule);
	
	Application application = context.getObjectByName(Application.class, "Active Directory");
	data.put("Application", application.getAttributes());
	
	String IQServiceServer = "IQServiceServer";
	int IQServicePort = 6060;
	
	RPCService service = new RPCService(IQServiceServer, IQServicePort, false, true);
	service.setConnectorServices(new sailpoint.connector.DefaultConnectorServices());
	 
	RpcRequest request = new RpcRequest("ScriptExecutor", "runAfterScript", data);
	
	RpcResponse response = service.execute(request);
	System.out.println(response.toXml());
	
	Map map = response.getResultAttributes();
	System.out.println(map);
		
	]]>
  	</Source>
</Rule>

 

Here is the rule that I am trying to execute:

 

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE Rule PUBLIC "sailpoint.dtd" "sailpoint.dtd">
<Rule   language="beanshell"  name="Rule Name">
  <Attributes>
    <Map>
      <entry key="ObjectOrientedScript" value="true"/>
      <entry key="extension" value=".ps1"/>
      <entry key="program" value="Powershell.exe"/>
      <entry key="timeout" value="25"/>
    </Map>
  </Attributes>
  <Source>
  <![CDATA[
  $outFile = "beforeCreateLog.txt"
   Out-File $outFile -InputObject "Test Message" -Append

]]>
</Source>
</Rule>

 

 

 

Do you see any issue with this rule?

 

Thanks,

Gaurav

hi @gaurav_jain , shouldn't IQServiceServer contain the address of the iqservice server, rather than the String "IQServiceServer"?

Also, I am assuming that you have a postScript rule named "Rule Name"

It does have correct values and able to connect to IQService. I intentionally did not post actual values on Compass.

 

Thanks,

Gaurav

hi @gaurav_jain , "Rule Name" does not seem to be calling any powershell script.

Please, check my comment above on "‎12-11-2019 02:59 PM" to find an example that you can execute. Hope this helps.

hi @gaurav_jain ,

I had the following error too "Object reference not set to an instance of an object" when I did not pass any Account Request.

As the native script is supposed to be "runAfterScript", I guess IQService is expecting something...

You may wish to try with that :


// Fake account request
AccountRequest accountRequest = new AccountRequest();
accountRequest.setApplication("IIQ");
accountRequest.setNativeIdentity("*FAKE*");
accountRequest.setOperation(AccountRequest.Operation.Modify);

// Fake attribute request
AttributeRequest fakeAttribute = new AttributeRequest();
fakeAttribute.setOperation(Operation.Add);
fakeAttribute.setName("param");
fakeAttribute.setValue("value");
accountRequest.add(fakeAttribute);

// Add to the IQService params
data.put("Request", accountRequest);

 

Also, your rule should have a type isn't it ? <Rule language="beanshell" name="Rule Name" type="ConnectorAfterCreate">

 

Hope this help.

Regards

Version history
Revision #:
13 of 13
Last update:
‎Jan 09, 2020 02:26 PM
Updated by:
 
Contributors