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 @drosenbauer ,

Thanks for this useful article

 

Is there any extra parameter that needs to be passed to the service (or the request?) in case useTLS = true?

Introducing TLS broke our functionality, and now we are getting a "Connection refused" error when we try to run the powershell scripts through IIQ/IQService.

 

Thanks.

 

Charlie

@Charlie - I don't believe there's anything extra that needs to be done for TLS apart from setting the flag. If IIQ trusts the IQService host's certificate, it should communicate. Make sure you've also updated your port in IIQ to match whatever you passed to the -o flag when you set up TLS on the IQService side.

Where are you getting "Connection refused"? One interesting thing about hitting "Test connection" on an AD application is that if IIQ can't reach the IQService for whatever reason, it falls back to an LDAP connection to AD, which may be where your "Connection refused" error is coming from. A separate error related to the initial attempt to hit the IQService may appear in your logs.

Hi @drosenbauer , thanks for taking the time to reply to me.

When TLS is enabled, test connection is successful, and so is provisioning.

The IQService is set up correctly, and the certificates are trusted, since provisioning is working.

The "Connection refused" is thrown when IIQ tries to run the powershell scripts. I don't see anything on the IQService logs, so the request does not reach that side at all.

 

I thought I should have sent username and password when creating the service, but I could not find any method that would allow me to do that, and the API is not documented. I also tried explicitly passing username and password when creating the request, trying to guess the parameters name to put in the data map, but again, no success.

 

Thanks,

 

Charlie

Good morning @Charlie ! Are you using client authentication with your IQService? The code above does not support that, and you will need to do some extra configuration to do so. If you have it all configured on your application so that it works for provisioning, that should be sufficient. You can just pass the configured Application object in its entirety as part of your request arguments (data in the above example code), in a field called (creatively) Application.

(Edit: I added a section about client auth above.)

Had to dig around a bit to figure this out so I'm including this to help others.  The relevant imports are:

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

 

 

Thanks @drosenbauer , @justin_harbison .

I decided to reply on https://community.sailpoint.com/t5/IdentityIQ-Forum/Error-while-running-Powershell-directly-via-the-... as I can include attachments there and keep the comment short.

Unfortunately, data.put("Application", app) did not work fro me.

Hey @Charlie , sorry for the lengthy delay! If you haven't yet, I figured it out!

You need to pass in a ConnectorServices object to the RPCService.

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

With that change - and passing the application Attributes in the data Map - client authentication now works for me in my lab environment.

hi @drosenbauer ,

 

Thanks again for your reply and your help.

This finally worked for me, only when TLS is disabled though. When I enable TLS (in both AD application and IQService), I get a "sailpoint.tools.GeneralException: Connection reset" error, and the request does not get to the IQService.

 

Did you test yours with TLS enabled? I wonder if there is other information that I need to pass to either the RPCService (perhaps related to the certificates, etc), or to the request.

 

Thanks,

 

Charlie

Hi Everyone,

Due to our architecture we can't reach IQService directly but we are using CGW. Is there any way to execute powershell script on iqservice through Cloud Gateway? How to do that?

Hello,

Do you have an example on how to use "yourPowershellRuleObject" ?

Map data = new HashMap();
data.put("postScript", yourPowershellRuleObject);

Thanks

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