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

Thanks for the response. After passing in Request, it is working fine now.

 

Thanks,

Gaurav

@gaurav_jain 

I've just added a bolded note to the tutorial above to call out that Request is not optional!

@josemdavila @gabriel_daems 

I've not found any evidence that the username/password you can pass along with the Rule are used. The user does get logged if you turn logging way up to DEBUG, but it doesn't seem to change anything. Perhaps this is older behavior that they've stubbed out in current IIQ versions?

If you need to run part of your script as another user, you could probably just "runas" another script from within your Powershell script. I realize that means having two scripts on the server (or doing something hacky with an AttributeRequest) but it would probably work.

@drosenbauer @gaurav_jain We are using IIQ 7.3p1. We applied efix [identityiq-7.3p1-conetn2645] to enable TLS in our environment. Post efix, we are getting issue with native rule "ConnectorAfterCreate".

Below Commands in Native rule :

$sReader = New-Object System.IO.StringReader([System.String]$env:Request);
$sResult = New-Object System.IO.StringReader([System.String]$env:Result);

# Form the xml reader objects
$xmlReader = [System.xml.XmlTextReader]([sailpoint.utils.xml.XmlUtil]::getReader($sReader));
$xmlReader_Result = [System.xml.XmlTextReader]([sailpoint.utils.xml.XmlUtil]::getReader($sResult));

$env:Request is coming as account request but $xmlReader is coming as null value after applying this efix. 

Is there any change required on this commands or any new efix available apart from which is mentioned above?

Thanks.

How to read application object in the powershell script ? Could you please suggest ?

1. Can we invoke PowerShell script from IIQ?
2. Can IIQ invoke PowersShell  script on any server? Or it has to be residing on IIQ server?
3. Can we pass user’s UPN or domain\nwID combo to the powershell script?

 

1.Can we invoke PowerShell script from IIQ?
2. Can IIQ invoke PowersShell  script on any server? Or it has to be residing on IIQ server?
3. Can we pass user’s UPN or domain\nwID combo to the powershell script?

 

Former_User

Can you please help me to understand the below line.

I am not able to find this constructor in eclipse, my java code is not getting compiled.

RPCService service = new RPCService(iqServiceHost, iqServicePort,false,true);

Thanks in advance.

IIQ Version 7.3 p1

Thanks,

Kasi

@e0449369 

1.Can we invoke PowerShell script from IIQ?

Yes, but always through the IQService method.


2. Can IIQ invoke PowersShell  script on any server? Or it has to be residing on IIQ server?

No, only where an IQService service is installed.


3. Can we pass user’s UPN or domain\nwID combo to the powershell script?

Do you mean as part of the parameters, data or as "run as" user

@Former_User 

These constructor is part of the RPCService.class included in identityiq-7.3p1-conetn2645 which adds TLS capabilities to IQService.

RPCService service = new RPCService(iqServiceHost, iqServicePort,false,true);

So you need to update your libraries with this class. 

 

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