ServiceNow IAM

Integrate with ServiceNow's services to execute CRUD operations for employee lifecycle processes.

Identity and Access Management · ServiceNow

Details

IDServiceNow IAM
ProviderServiceNow
CategoryIdentity and Access Management
From Version6.0.0
Docker Imagedemisto/python3:3.12.13.10116658
Supported ModulesAttack Surface Management Exposure Management Agentix Cortex Cloud Cloud Runtime Security Cloud Posture Security XSIAM EDR

README

Note: This integration should be used along with our IAM premium pack. For further details, visit our IAM pack documentation.

Integrate with ServiceNow’s services to perform Identity Lifecycle Management operations.
This integration was integrated and tested with London version of ServiceNow.
For more information, please refer to the Identity Lifecycle Management article.

Configure ServiceNow IAM in Cortex

Parameter Description Required
ServiceNow URL (https://domain.service-now.com)   True
ServiceNow API Version (e.g. ‘v1’). Specify this value to use an endpoint version other than the latest.   False
Username   True
Password   True
Trust any certificate (not secure)   False
Use system proxy settings   False
Allow creating users   False
Allow updating users   False
Allow enabling users   False
Allow disabling users   False
Automatically create user if not found in update command   False
Incoming Mapper   True
Outgoing Mapper Cortex XSOAR only parameter. False

Commands

You can execute these commands from the CLI, as part of an automation, or in a playbook.
After you successfully execute a command, a DBot message appears in the War Room with the command details.

iam-create-user


Creates a user.

Base Command

iam-create-user

Input

Argument Name Description Required
user-profile User Profile indicator details. Required
allow-enable Enable the user. Optional

Context Output

Path Type Description
IAM.Vendor.active Boolean If true, the employee’s status is active, otherwise false.
IAM.Vendor.brand String Name of the integration.
IAM.Vendor.details string Indicates if the API was successful or provides error information.
IAM.Vendor.email String The employee’s email address.
IAM.Vendor.errorCode Number HTTP error response code.
IAM.Vendor.errorMessage String Reason why the API failed.
IAM.Vendor.id String The employee’s user ID in the app.
IAM.Vendor.instanceName string Name of the integration instance.
IAM.Vendor.success Boolean If true, the command was executed successfully, otherwise false.
IAM.Vendor.username String The employee’s username in the app.

Command Example

!iam-create-user user-profile=`{"email":"testdemisto2@paloaltonetworks.com", "givenname":"Test","surname":"Demisto"}`

Human Readable Output

Create User Results (ServiceNow IAM)

brand instanceName success active id email details
ServiceNow IAM ServiceNow IAM_instance_1 true true edab746f1b142410042611b4bd4bcb23 testdemisto2@paloaltonetworks.com calendar_integration: 1
country:
user_password:
last_login_time:
source:
sys_updated_on: 2020-11-11 14:55:48
building:
web_service_access_only: false
notification: 2
enable_multifactor_authn: false
sys_updated_by: admin
sys_created_on: 2020-11-11 14:55:48
sys_domain: {“link”: “https://ven03941.service-now.com/api/now/table/sys_user_group/global”, “value”: “global”}
state:
vip: false
sys_created_by: admin
zip:
home_phone:
time_format:
last_login:
default_perspective:
active: true
sys_domain_path: /
cost_center:
phone:
name: Test Demisto
employee_number:
password_needs_reset: false
gender:
city:
failed_attempts:
user_name:
roles:
title:
sys_class_name: sys_user
sys_id: edab746f1b142410042611b4bd4bcb23
internal_integration_user: false
ldap_server:
mobile_phone:
street:
company:
department:
first_name: Test
email: testdemisto2@paloaltonetworks.com
introduction:
preferred_language:
manager:
locked_out: false
sys_mod_count: 0
last_name: Demisto
photo:
avatar:
middle_name:
sys_tags:
time_zone:
schedule:
date_format:
location:

iam-update-user


Updates an existing user with the data passed in the user-profile argument.

Base Command

iam-update-user

Input

Argument Name Description Required
user-profile A User Profile indicator. Required
allow-enable Enable the user. Optional

Context Output

Path Type Description
IAM.Vendor.active Boolean If true, the employee’s status is active, otherwise false.
IAM.Vendor.brand String Name of the integration.
IAM.Vendor.details string Indicates if the API was successful or provides error information.
IAM.Vendor.email String The employee’s email address.
IAM.Vendor.errorCode Number HTTP error response code.
IAM.Vendor.errorMessage String Reason why the API failed.
IAM.Vendor.id String The employee’s user ID in the app.
IAM.Vendor.instanceName string Name of the integration instance.
IAM.Vendor.success Boolean If true, the command was executed successfully, otherwise false.
IAM.Vendor.username String The employee’s username in the app.

Command Example

!iam-update-user user-profile=`{"email":"testdemisto2@paloaltonetworks.com", "givenname":"Test","surname":"Demisto_updated"}`

Human Readable Output

Update User Results (ServiceNow IAM)

brand instanceName success active id email details
ServiceNow IAM ServiceNow IAM_instance_1 true true edab746f1b142410042611b4bd4bcb23 testdemisto2@paloaltonetworks.com calendar_integration: 1
country:
user_password:
last_login_time:
source:
sys_updated_on: 2020-11-11 14:55:48
building:
web_service_access_only: false
notification: 2
enable_multifactor_authn: false
sys_updated_by: admin
sys_created_on: 2020-11-11 14:55:48
sys_domain: {“link”: “https://ven03941.service-now.com/api/now/table/sys_user_group/global”, “value”: “global”}
state:
vip: false
sys_created_by: admin
zip:
home_phone:
time_format:
last_login:
default_perspective:
active: true
sys_domain_path: /
cost_center:
phone:
name: Test Demisto_updated
employee_number:
password_needs_reset: false
gender:
city:
failed_attempts:
user_name:
roles:
title:
sys_class_name: sys_user
sys_id: edab746f1b142410042611b4bd4bcb23
internal_integration_user: false
ldap_server:
mobile_phone:
street:
company:
department:
first_name: Test
email: testdemisto2@paloaltonetworks.com
introduction:
preferred_language:
manager:
locked_out: false
sys_mod_count: 0
last_name: Demisto_updated
photo:
avatar:
middle_name:
sys_tags:
time_zone:
schedule:
date_format:
location:

iam-get-user


Retrieves a single user resource.

Base Command

iam-get-user

Input

Argument Name Description Required
user-profile A User Profile indicator. Required

Context Output

Path Type Description
IAM.Vendor.active Boolean If true, the employee’s status is active, otherwise false.
IAM.Vendor.brand String Name of the integration.
IAM.Vendor.details string Indicates if the API was successful or provides error information.
IAM.Vendor.email String The employee’s email address.
IAM.Vendor.errorCode Number HTTP error response code.
IAM.Vendor.errorMessage String Reason why the API failed.
IAM.Vendor.id String The employee’s user ID in the app.
IAM.Vendor.instanceName string Name of the integration instance.
IAM.Vendor.success Boolean If true, the command was executed successfully, otherwise false.
IAM.Vendor.username String The employee’s username in the app.

Command Example

!iam-get-user user-profile=`{"email":"testdemisto2@paloaltonetworks.com"}`

Human Readable Output

Get User Results (ServiceNow IAM)

brand instanceName success active id email details
ServiceNow IAM ServiceNow IAM_instance_1 true true edab746f1b142410042611b4bd4bcb23 testdemisto2@paloaltonetworks.com calendar_integration: 1
country:
user_password:
last_login_time:
source:
sys_updated_on: 2020-11-11 14:55:48
building:
web_service_access_only: false
notification: 2
enable_multifactor_authn: false
sys_updated_by: admin
sys_created_on: 2020-11-11 14:55:48
sys_domain: {“link”: “https://ven03941.service-now.com/api/now/table/sys_user_group/global”, “value”: “global”}
state:
vip: false
sys_created_by: admin
zip:
home_phone:
time_format:
last_login:
default_perspective:
active: true
sys_domain_path: /
cost_center:
phone:
name: Test Demisto_updated
employee_number:
password_needs_reset: false
gender:
city:
failed_attempts:
user_name:
roles:
title:
sys_class_name: sys_user
sys_id: edab746f1b142410042611b4bd4bcb23
internal_integration_user: false
ldap_server:
mobile_phone:
street:
company:
department:
first_name: Test
email: testdemisto2@paloaltonetworks.com
introduction:
preferred_language:
manager:
locked_out: false
sys_mod_count: 0
last_name: Demisto_updated
photo:
avatar:
middle_name:
sys_tags:
time_zone:
schedule:
date_format:
location:

iam-disable-user


Disable an active user.

Base Command

iam-disable-user

Input

Argument Name Description Required
user-profile A User Profile indicator. Required

Context Output

Path Type Description
IAM.Vendor.active Boolean If true, the employee’s status is active, otherwise false.
IAM.Vendor.brand String Name of the integration.
IAM.Vendor.details string Indicates if the API was successful or provides error information.
IAM.Vendor.email String The employee’s email address.
IAM.Vendor.errorCode Number HTTP error response code.
IAM.Vendor.errorMessage String Reason why the API failed.
IAM.Vendor.id String The employee’s user ID in the app.
IAM.Vendor.instanceName string Name of the integration instance.
IAM.Vendor.success Boolean If true, the command was executed successfully, otherwise false.
IAM.Vendor.username String The employee’s username in the app.

Command Example

!iam-disable-user user-profile=`{"email":"testdemisto2@paloaltonetworks.com"}`

Human Readable Output

Disable User Results (ServiceNow IAM)

brand instanceName success active id email details
ServiceNow IAM ServiceNow IAM_instance_1 true false edab746f1b142410042611b4bd4bcb23 testdemisto2@paloaltonetworks.com calendar_integration: 1
country:
user_password:
last_login_time:
source:
sys_updated_on: 2020-11-11 14:55:48
building:
web_service_access_only: false
notification: 2
enable_multifactor_authn: false
sys_updated_by: admin
sys_created_on: 2020-11-11 14:55:48
sys_domain: {“link”: “https://ven03941.service-now.com/api/now/table/sys_user_group/global”, “value”: “global”}
state:
vip: false
sys_created_by: admin
zip:
home_phone:
time_format:
last_login:
default_perspective:
active: false
sys_domain_path: /
cost_center:
phone:
name: Test Demisto_updated
employee_number:
password_needs_reset: false
gender:
city:
failed_attempts:
user_name:
roles:
title:
sys_class_name: sys_user
sys_id: edab746f1b142410042611b4bd4bcb23
internal_integration_user: false
ldap_server:
mobile_phone:
street:
company:
department:
first_name: Test
email: testdemisto2@paloaltonetworks.com
introduction:
preferred_language:
manager:
locked_out: false
sys_mod_count: 0
last_name: Demisto_updated
photo:
avatar:
middle_name:
sys_tags:
time_zone:
schedule:
date_format:
location:

Configuration parameters

  • url — ServiceNow URL (https://<domain>.service-now.com) (required)
  • api_version — ServiceNow API Version (e.g. 'v1'). Specify this value to use an endpoint version other than the latest.
  • credentials — Username (required)
  • insecure — Trust any certificate (not secure)
  • proxy — Use system proxy settings
  • create_user_enabled — Allow creating users
  • update_user_enabled — Allow updating users
  • enable_user_enabled — Allow enabling users
  • disable_user_enabled — Allow disabling users
  • create_if_not_exists — Automatically create user if not found in update command
  • mapper_in — Incoming Mapper (required)
  • mapper_out — Outgoing Mapper

Commands (5)

  • get-mapping-fields

    Retrieves a User Profile schema, which holds all of the user fields within the application. Used for outgoing-mapping through the Get Schema option.

  • iam-create-user

    Creates a user in ServiceNow.

  • iam-disable-user

    Disable an active user.

  • iam-get-user

    Retrieves a single user resource.

  • iam-update-user

    Updates an existing user with the data passed in the user-profile argument.

# noqa: F401
# noqa: F401
# noqa: F401
# noqa: F401
import traceback

import demistomock as demisto  # noqa: F401
import urllib3
from CommonServerPython import *  # noqa: F401

# Disable insecure warnings
urllib3.disable_warnings()

IAM_GET_USER_ATTRIBUTES = ["id", "user_name", "email"]
"""CLIENT CLASS"""


class Client(BaseClient):
    """
    ServiceNow IAM Client class that implements logic to authenticate with ServiceNow.
    """

    def test(self):
        uri = "/table/sys_user?sysparm_limit=1"
        self._http_request(method="GET", url_suffix=uri)

    def get_user(self, filter_name: str, filter_value: str):
        uri = "table/sys_user"
        query_params = {filter_name: filter_value}

        res = self._http_request(method="GET", url_suffix=uri, params=query_params)

        if res and len(res.get("result", [])) > 0:
            return res.get("result")[0]
        return None

    def create_user(self, user_data):
        uri = "table/sys_user"
        res = self._http_request(method="POST", url_suffix=uri, json_data=user_data)
        return res.get("result")

    def update_user(self, user_id, user_data):
        uri = f"/table/sys_user/{user_id}"
        res = self._http_request(method="PATCH", url_suffix=uri, json_data=user_data)
        return res.get("result")

    def get_service_now_fields(self):
        service_now_fields = {}
        uri = "table/sys_dictionary?sysparm_query=name=sys_user"
        res = self._http_request(method="GET", url_suffix=uri)

        elements = res.get("result", [])
        for elem in elements:
            if elem.get("element"):
                field_name = elem.get("element")
                description = elem.get("sys_name")
                service_now_fields[field_name] = description

        return service_now_fields


"""HELPER FUNCTIONS"""


def handle_exception(user_profile, e, action):
    """Handles failed responses from ServiceNow API by setting the User Profile object with the results.

    Args:
        user_profile (IAMUserProfile): The User Profile object.
        e (Exception): The exception error. If DemistoException, holds the response json.
        action (IAMActions): An enum represents the current action (get, update, create, etc).
    """
    if e.__class__ is DemistoException and hasattr(e, "res") and e.res is not None:
        error_code = e.res.status_code
        try:
            resp = e.res.json()
            error_message = get_error_details(resp)
        except ValueError:
            error_message = str(e)
    else:
        error_code = ""
        error_message = str(e)

    user_profile.set_result(action=action, success=False, error_code=error_code, error_message=error_message)

    demisto.error(traceback.format_exc())


def get_error_details(res):
    """Parses the error details retrieved from ServiceNow and outputs the resulted string.

    Args:
        res (dict): The data retrieved from ServiceNow.

    Returns:
        (str) The parsed error details.
    """
    message = res.get("error", {}).get("message")
    details = res.get("error", {}).get("detail")
    return f"{message}: {details}"


"""COMMAND FUNCTIONS"""


def test_module(client):
    client.test()
    return_results("ok")


def get_mapping_fields_command(client):
    service_now_fields = client.get_service_now_fields()
    incident_type_scheme = SchemeTypeMapping(type_name=IAMUserProfile.DEFAULT_INCIDENT_TYPE)

    for field, description in service_now_fields.items():
        incident_type_scheme.add_field(field, description)

    return GetMappingFieldsResponse([incident_type_scheme])


def get_user_command(client, args, mapper_in, mapper_out):
    user_profile = IAMUserProfile(
        user_profile=args.get("user-profile"), mapper=mapper_out, incident_type=IAMUserProfile.UPDATE_INCIDENT_TYPE
    )
    try:
        iam_attr, iam_attr_value = user_profile.get_first_available_iam_user_attr(IAM_GET_USER_ATTRIBUTES)
        service_now_filter_name: str = "sys_id" if iam_attr == "id" else iam_attr
        service_now_user = client.get_user(service_now_filter_name, iam_attr_value)
        if not service_now_user:
            error_code, error_message = IAMErrors.USER_DOES_NOT_EXIST
            user_profile.set_result(action=IAMActions.GET_USER, success=False, error_code=error_code, error_message=error_message)
        else:
            user_profile.update_with_app_data(service_now_user, mapper_in)
            user_profile.set_result(
                action=IAMActions.GET_USER,
                success=True,
                active=service_now_user.get("active") == "true",
                iden=service_now_user.get("sys_id"),
                email=service_now_user.get("email"),
                username=service_now_user.get("user_name"),
                details=service_now_user,
            )

    except Exception as e:
        handle_exception(user_profile, e, IAMActions.GET_USER)

    return user_profile


def disable_user_command(client, args, is_command_enabled, mapper_out):
    user_profile = IAMUserProfile(
        user_profile=args.get("user-profile"), mapper=mapper_out, incident_type=IAMUserProfile.UPDATE_INCIDENT_TYPE
    )
    if not is_command_enabled:
        user_profile.set_result(action=IAMActions.DISABLE_USER, skip=True, skip_reason="Command is disabled.")
    else:
        try:
            iam_attr, iam_attr_value = user_profile.get_first_available_iam_user_attr(IAM_GET_USER_ATTRIBUTES)
            service_now_filter_name: str = "sys_id" if iam_attr == "id" else iam_attr
            service_now_user = client.get_user(service_now_filter_name, iam_attr_value)
            if not service_now_user:
                _, error_message = IAMErrors.USER_DOES_NOT_EXIST
                user_profile.set_result(action=IAMActions.DISABLE_USER, skip=True, skip_reason=error_message)
            else:
                if service_now_user.get("active", "true") == "false":
                    user_profile.set_user_is_already_disabled(service_now_user)
                else:
                    user_id = service_now_user.get("sys_id")
                    user_data = {"active": False}
                    updated_user = client.update_user(user_id, user_data)
                    user_profile.set_result(
                        action=IAMActions.DISABLE_USER,
                        success=True,
                        active=False,
                        iden=updated_user.get("sys_id"),
                        email=updated_user.get("email"),
                        username=updated_user.get("user_name"),
                        details=updated_user,
                    )

        except Exception as e:
            handle_exception(user_profile, e, IAMActions.DISABLE_USER)

    return user_profile


def create_user_command(client, args, mapper_out, is_command_enabled, is_update_enabled, is_enable_enabled):
    user_profile = IAMUserProfile(
        user_profile=args.get("user-profile"), mapper=mapper_out, incident_type=IAMUserProfile.CREATE_INCIDENT_TYPE
    )

    if not is_command_enabled:
        user_profile.set_result(action=IAMActions.CREATE_USER, skip=True, skip_reason="Command is disabled.")
    else:
        try:
            iam_attr, iam_attr_value = user_profile.get_first_available_iam_user_attr(IAM_GET_USER_ATTRIBUTES)
            service_now_filter_name: str = "sys_id" if iam_attr == "id" else iam_attr
            service_now_user = client.get_user(service_now_filter_name, iam_attr_value)
            if service_now_user:
                # if user exists, update it
                user_profile = update_user_command(client, args, mapper_out, is_update_enabled, is_enable_enabled, False, False)

            else:
                service_now_profile = user_profile.map_object(mapper_out, incident_type=IAMUserProfile.CREATE_INCIDENT_TYPE)
                created_user = client.create_user(service_now_profile)
                user_profile.set_result(
                    action=IAMActions.CREATE_USER,
                    success=True,
                    active=created_user.get("active") == "true",
                    iden=created_user.get("sys_id"),
                    email=created_user.get("email"),
                    username=created_user.get("user_name"),
                    details=created_user,
                )

        except Exception as e:
            handle_exception(user_profile, e, IAMActions.CREATE_USER)

    return user_profile


def update_user_command(
    client, args, mapper_out, is_command_enabled, is_enable_enabled, is_create_user_enabled, create_if_not_exists
):
    user_profile = IAMUserProfile(
        user_profile=args.get("user-profile"), mapper=mapper_out, incident_type=IAMUserProfile.UPDATE_INCIDENT_TYPE
    )
    allow_enable = args.get("allow-enable") == "true"
    if not is_command_enabled:
        user_profile.set_result(action=IAMActions.UPDATE_USER, skip=True, skip_reason="Command is disabled.")
    else:
        try:
            iam_attr, iam_attr_value = user_profile.get_first_available_iam_user_attr(IAM_GET_USER_ATTRIBUTES)
            service_now_filter_name: str = "sys_id" if iam_attr == "id" else iam_attr
            service_now_user = client.get_user(service_now_filter_name, iam_attr_value)
            if service_now_user:
                user_id = service_now_user.get("sys_id")
                service_now_profile = user_profile.map_object(mapper_out, incident_type=IAMUserProfile.UPDATE_INCIDENT_TYPE)

                if allow_enable and is_enable_enabled:
                    service_now_profile["active"] = True
                    service_now_profile["locked_out"] = False

                updated_user = client.update_user(user_id, service_now_profile)
                user_profile.set_result(
                    action=IAMActions.UPDATE_USER,
                    success=True,
                    active=updated_user.get("active") == "true",
                    iden=updated_user.get("sys_id"),
                    email=updated_user.get("email"),
                    username=updated_user.get("user_name"),
                    details=updated_user,
                )
            else:
                if create_if_not_exists:
                    user_profile = create_user_command(client, args, mapper_out, is_create_user_enabled, False, False)
                else:
                    _, error_message = IAMErrors.USER_DOES_NOT_EXIST
                    user_profile.set_result(action=IAMActions.UPDATE_USER, skip=True, skip_reason=error_message)

        except Exception as e:
            handle_exception(user_profile, e, IAMActions.UPDATE_USER)

    return user_profile


def main():
    user_profile = None
    params = demisto.params()
    api_version = params.get("api_version", "")
    base_url = urljoin(params["url"].strip("/"), "/api/now/")
    if api_version:
        base_url += api_version
    username = params.get("credentials", {}).get("identifier")
    password = params.get("credentials", {}).get("password")
    mapper_in = params.get("mapper_in")
    mapper_out = params.get("mapper_out")
    verify_certificate = not params.get("insecure", False)
    proxy = params.get("proxy", False)
    command = demisto.command()
    args = demisto.args()

    is_create_enabled = params.get("create_user_enabled")
    is_disable_enabled = params.get("disable_user_enabled")
    is_enable_enabled = params.get("enable_user_enabled")
    is_update_enabled = demisto.params().get("update_user_enabled")
    create_if_not_exists = demisto.params().get("create_if_not_exists")

    headers = {"Content-Type": "application/json", "Accept": "application/json"}

    client = Client(
        base_url=base_url, verify=verify_certificate, proxy=proxy, headers=headers, ok_codes=(200, 201), auth=(username, password)
    )

    demisto.debug(f"Command being called is {command}")

    if command == "iam-get-user":
        user_profile = get_user_command(client, args, mapper_in, mapper_out)

    elif command == "iam-create-user":
        user_profile = create_user_command(client, args, mapper_out, is_create_enabled, is_update_enabled, is_enable_enabled)

    elif command == "iam-update-user":
        user_profile = update_user_command(
            client, args, mapper_out, is_update_enabled, is_enable_enabled, is_create_enabled, create_if_not_exists
        )

    elif command == "iam-disable-user":
        user_profile = disable_user_command(client, args, is_disable_enabled, mapper_out)

    if user_profile:
        return_results(user_profile)

    try:
        if command == "test-module":
            test_module(client)

        elif command == "get-mapping-fields":
            return_results(get_mapping_fields_command(client))

    except Exception as e:
        # For any other integration command exception, return an error
        return_error(f"Failed to execute {command} command. Error: {e!s}")


from IAMApiModule import *  # noqa E402

if __name__ in ("__main__", "__builtin__", "builtins"):
    main()