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.
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 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 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);
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());
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.
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.
If you didn’t solve this yet, encryption is one of the Boolean parameters to RPCService.
Hello @drosenbauer I'm facing a really particular issue regarding the use of RPCService class, I'm launching ps script using the following code: (It's practically the same as the example of this post):
The Java side:
import sailpoint.object.RpcRequest;
import sailpoint.object.RpcResponse;
import sailpoint.connector.RPCService;
import sailpoint.object.Rule;
import sailpoint.object.ProvisioningPlan.AccountRequest;
import sailpoint.object.ProvisioningPlan.AttributeRequest;
import sailpoint.object.ProvisioningPlan.Operation;
import sailpoint.object.Application;
Map data = new HashMap();
//Se levanta el script a ejecutar en AD
Rule afterProvisioningScript = context.getObjectByName(Rule.class, "AfterCreate-Powershell-test"); //Agregar nombre de la rule
Application ad = context.getObjectByName(Application.class, "Active Directory");
data.put("Application", ad.getAttributes());
data.put("postScript", afterProvisioningScript);
// 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("uid");
fakeAttribute.setValue("some");
List <AttributeRequest> fakeAttributeRequests = new ArrayList<AttributeRequest>();
fakeAttributeRequests.add(fakeAttribute);
accountRequest.setAttributeRequests(fakeAttributeRequests);
data.put("Request", accountRequest);
// Add to the IQService params
RPCService service = new RPCService("192.168.100.14", 5050, false, false);
RpcRequest request = new RpcRequest("ScriptExecutor", "runAfterScript", data);
service.checkForErrors(false);
RpcResponse response = service.execute(request);
if (response.hasMessages()) {
return response.getMessages().toString();
} else if (response.hasErrors()) {
return response.getErrors().toString();
}
return "There are no actions";
The PowerShell side:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE Rule PUBLIC "sailpoint.dtd" "sailpoint.dtd">
<Rule language="beanshell" name="AfterCreate-Powershell-test" type="ConnectorAfterModify">
<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="150"/>
</Map>
</Attributes>
<Description>
This is a sample PowerShell after script which ensures that the request was processed successfully and creates home directory at the path specified in the request
</Description>
<Source>
Try {
Add-type -path C:\SailPoint\IQService\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;
$attributes = @{}
foreach ($attribute in $requestObject.AttributeRequests){
$attributes[$attribute.Name] = $attribute.Value;
}
#Handle input and do stuff here
$resultObject.Messages.add($attributes["uid"]);
} catch [Exception] {
# You should probably do some logging here too
$ErrorMessage = $_.Exception.ToString()
$resultObject.Messages.add("Error: " + $ErrorMessage); #In here I pass the errors as messages as an advice from a comment in the post
} finally {
$resultObject.toxml() | out-file $args[0];
}
</Source>
</Rule>
When I run this from the debug graphic interface on my personal lab, I get the following successful response getting the value I pass from the java side to the ps side and back without problem:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE String PUBLIC "sailpoint.dtd" "sailpoint.dtd">
<String>[some]</String>
But when I try to run the same logic on my customer environment, I get the following message:
Exception running rule: The application script threw an exception: sailpoint.tools.GeneralException: NullPointerException BSF info: test_ejecucionDeScript at line: 0 column: columnNo
Using log messages, I could identify that this error was coming from the line:
RpcResponse response = service.execute(request);
I tried some different things that I could get from dumping the Class on my IDE and check the available methods and seeing the comments on this and other posts, but I can't troubleshoot this, I guess the problem is coming from the customer environment, but I have no idea what could it be.
"""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."""
It's not clear from your example how to get the decrypted password if you are connecting to AD and using the username and password stored in the forestSettings.
I can retrieve both the username and the password easily, but the password is encrypted.
Hi Team,
I have kept one .exe file in the Connector server, and I want to call it by passing 2 arguments. This will return some string and use this string in Global Provisioning connector rule updating account attribute. So can I use the RPC call to do the same?
Thank you for the highly detailed article!
Wanted to ask for opinion for this scenario:
We want to have single PowerShell script which can handle multiple scenarios. How can we handle multiple account requests in the PowerShell script and respective results?
Specifically:
1. How will the following lines change to handle multiple account requests?
$requestObject = New-Object Sailpoint.Utils.objects.AccountRequest($xmlReader);
2. How can we handle multiple RpcResponse(s)?