ArcSight Logger

ArcSight events logger.

Analytics & SIEM · ArcSight Logger

Details

IDArcSight Logger
ProviderOpenText
CategoryAnalytics & SIEM
From Version5.0.0
Supported ModulesAgentix XSIAM

README

ArcSight Logger delivers a universal log management solution that unifies searching, reporting, alerting, and analysis across any type of enterprise machine data.

The Cortex XSOAR-ArcSight Logger integration allows you to run a search session, refine or limit the search and retrieve a list of events detected in the search.

To set up Arcsight Logger to work with Cortex XSOAR:

  • Make sure you have the Arcsight Logger server url.
  • Make sure you have credentials for Arcsight Logger.

To set up the integration on Cortex XSOAR:

  1. Go to ‘Settings > Integrations > Servers & Services’
  2. Locate ‘ArcSight Logger’ by searching for it using the search box on the top of the page.
  3. Click ‘Add instance’ to create and configure a new integration. You should configure the following settings:
    Name: A textual name for the integration instance.
    Server URL and Port: The API server URL and port number.
    Credentials and Password: User and password used to access ArcSight Logger.
    Import events as incidents - Mark to automatically create Cortex XSOAR incidents from ArcSight Logger events. 
    Incident type: Choose the incident type from the drop-down list. This incident type will be triggered when an event is received from the integration.  
    Events query - The events query received from the integration.  
    Do not validate server certificate (insecure) - Select to avoid server certification validation. You may want to do this in case Cortex XSOAR cannot validate the integration server certificate (due to missing CA certificate).
    Use system proxy settings: Select whether to communicate via the system proxy server or not.
    Cortex XSOAR engine: If relevant, select the engine that acts as a proxy to the server.
    Engines are used when you need to access a remote network segments and there are network devices such as proxies, firewalls, etc. that prevent the Cortex XSOAR server from accessing the remote networks.
    For more information on Cortex XSOAR engines see:
    Cortex XSOAR 6.13 - Engines
    Cortex XSOAR 8 Cloud- Engines
    Cortex XSOAR 8.7 On-prem - Engines
    Require users to enter additional password: Select whether you’d like an additional step where users are required to authenticate themselves with a password.
  4. Press the ‘Test’ button to validate connection.
  5. After completing the test successfully, press the ‘Done’ button.

Fetched incidents data:

The integration imports events as incidents. All events from 24 hours prior to the instance configuration and up to the current time will be fetched.

Top Use-case:

Arcsight Logger integration can be used to run a search session, refine or limit the search, and retrieve a list of events detected in the search.

This can be achieved in two possible ways:

  • Use ‘as-search-events’ for the complete flow of the use case to be executed.
    ‘as-search-events’ starts a new search session, waits until the search status is complete or reaches the required number of hits, and then returns the list of detected events.
  • Alternatively, the explicit commands can be used to ‘breakdown’ the search-events process. A possible flow of commands can be:
    • Use ‘as-search’ to start a new search session and receive the session ID and search session ID to be used in the following commands.
    • Use ‘as-drilldown’ to narrow-down the search results to the specified time range.
    • Use ‘as-status’ to inquire if the search session is complete or still running, view the number of scanned events and hits.
    • Use ‘as-events’ to get a list of all events detected in the search.
    • Use ‘as-close’ to stop the execution of the search and clear the session data from the server.

Commands:

  • as-search-events

Input:

query, discover_fields, endTime, startTime, summary_fields, field_summary, local_search, timeout, lastDays, offset, length, dir, fields

for example:

  • !as-search-events
    query=”deviceVendor= Arcsight AND name CONTAINS \”CPU\””  
    length=10
  • !as-search-events
    offset=15
    length=10
    fields=name,deviceVendor

       Find more query examples at wikis/ArcsightLogger.

Context output (example):

{

    "ArcSightLogger": {

        "Events": [

            {

                "destinationAddress": ##.##.##.##,

                "agentSeverity": "1",

                "Version": "0",

                "Logger": "Local",

                "ReceiptTime": 1513249919185,

                "deviceCustomNumber1Label": "Percent Usage",

                "deviceCustomNumber1": 2,

                "deviceAddress":  ##.##.##.##,

                "deviceCustomString2Label": "timeframe",

                "deviceVendor": "ArcSight",

                "Device": "Logger",

                "deviceProduct": "Logger",

                "EventTime": 1513249440017,

                "baseEventCount": 1,

                "deviceReceiptTime": 1513249440017,

                "startTime": 1513249440017,

                "deviceEventClassId": "cpu:100",

                "deviceCustomString2": "CurrentValue",

                "name": "CPU Usage",

                "deviceEventCategory": "/Monitor/CPU/Usage",

                "rowId": "347259-26@Local",

                "endTime": 1513249440017,

                "deviceVersion": "6.2.0.7633.0"

            }, 

       ]

   }

}

Raw output (example):

[

   {

Device:Logger

EventTime:1513249693332

Logger:Local

ReceiptTime:1513249693838

Version:0

agentSeverity:3

baseEventCount:1

cn1label:Session

destinationAddress: ##.##.##.##,

destinationUserId:1

destinationUserName:admin

deviceCustomNumber1: 741618068

deviceEventCategory:/Platform/Authentication/Login

deviceEventClassId:platform:230

deviceProduct:Logger

deviceVendor:ArcSight

deviceVersion:L7633

name:Successful login

rowId:347186-0@Local

sourceAddress: ##.##.##.##,

               },

                     …

]

 

  • as-search

Input:

query, discover_fields, endTime, startTime, summary_fields, field_summary, local_search, timeout, lastDays

for example:

  • !as-search

    startTime=2017-12-21T06:30:00.000Z

    endTime=2017-12-21T07:30:00.000Z

    local_search=false

  •  

    !as-search

    lastDays=1

       Find more query examples at wikis/ArcsightLogger.

Context output (example):

{

"ArcSightLogger": {

"Search": {

"SearchSessionId": 1513260595933,

"SessionId": "3dxITLyDE9FyRiflQD7UFG_hSsUPq4uCTM4B6Y5D3p4."

}

}

}

Raw output (example):

{

searchSessionId:1513260595933

sessionId:3dxITLyDE9FyRiflQD7UFG_hSsUPq4uCTM4B6Y5D3p4.

}

  • as-drilldown

Input:

searchSessionId, sessionId, startTime, endTime, lastDays

for example:

  • !as-drilldown

    lastDays=1
    searchSessionId="1513875662638"
    sessionId="18t2-5sQ4h1LcTqFwEUJj0XIatasCpM8l0T8NZlhxEg."

  •  !as-drilldown
    startTime=2017-12-21T06:30:00.000Z
    endTime=2017-12-21T07:30:00.000Z
    searchSessionId="1513875662638" sessionId="18t25sQ4h1LcTqFwEUJj0XIatasCpM8l0T8NZlhxEg."

Context output:

 The command has no context.

Raw output:

The command has no raw output.

  • as-status

Input:

searchSessionId, sessionId 

Context output (example):

{

"ArcSightLogger": {

"Status": {

"Status": "complete",

"Hit": 2462,

"Elapsed": "00:00:00.290",

"ResultType": "histogram",

"Scanned": 2520,

"SearchSessionId": "1513272858387",

"Message": []

Raw output (example):

{

elapsed: 00:00:00.290

hit:2462

message: []

result_type: histogram

scanned: 2520

status: complete

}

  • as-events

Input:

searchSessionId, sessionId, length, dir, offset, fields

Command use example

  • !as-events
    searchSessionId="1513875662638" sessionId="18t25sQ4h1LcTqFwEUJj0XIatasCpM8l0T8NZlhxEg."
    length=10
    fields=name,deviceAddress,deviceVendor,EventTime

Context output (example):

{

"ArcSightLogger": {

"Events": [

{

"destinationAddress": ##.##.##.##,

"agentSeverity": "1",

"Version": "0",

"Logger": "Local",

"ReceiptTime": 1513249919185,

"deviceCustomNumber1Label": "Percent Usage",

"deviceCustomNumber1": 2,

"deviceAddress":  ##.##.##.##,

"deviceCustomString2Label": "timeframe",

"deviceVendor": "ArcSight",

"Device": "Logger",

"deviceProduct": "Logger",

"EventTime": 1513249440017,

"baseEventCount": 1,

"deviceReceiptTime": 1513249440017,

"startTime": 1513249440017,

"deviceEventClassId": "cpu:100",

"deviceCustomString2": "CurrentValue",

"name": "CPU Usage",

"deviceEventCategory": "/Monitor/CPU/Usage",

"rowId": "347259-26@Local",

"endTime": 1513249440017,

"deviceVersion": "6.2.0.7633.0"

}, 

]

}

}

Raw output (example):

[

{

Device:Logger

EventTime:1513249693332

Logger:Local

ReceiptTime:1513249693838

Version:0

agentSeverity:3

baseEventCount:1

cn1label:Session

destinationAddress: ##.##.##.##,

destinationUserId:1

destinationUserName:admin

deviceCustomNumber1: 741618068

deviceEventCategory:/Platform/Authentication/Login

deviceEventClassId:platform:230

deviceProduct:Logger

deviceVendor:ArcSight

deviceVersion:L7633

name:Successful login

rowId:347186-0@Local

sourceAddress: ##.##.##.##,

},

]

 

{

  • as-stop

Input:

searchSessionId, sessionId 

Context output (example):

The command has no context. 

Raw output (example):

The command has no raw output.

  • as-close

Input:

searchSessionId, sessionId 

Context output (example):

The command has no context. 

Raw output (example):

The command has no raw output.

 

Additional info:         

  • Search time range: When no time limitations are applied on a search session, Arcsight Logger will use its default time limitation and will search events in time range of the last 2 hours.
    To set the search time range:
    • When starting a new search session, using ‘as-search’: pass both startTime and endTime parameters to set the time range for the search. Alternatively, you can use the lastDays parameter.
    • When in an active search session: use ‘as-drilldown’ to narrow-down the search results to a specified time range.
    • When starting a new search, using ‘as-search-events’: pass both startTime and endTime parameters to set the time range for the search. Alternatively, use lastDays parameter.
  • Date/time format: Use the compliant date/time format when passing startTime and endTime parameters.
  • Expected date/time format: yyyy-MM-dd’T’HH:mm:ss.SSSXXX.
    For example, May 26 2014 at 21:49:46 PM could have a format like one of the following:
    • Format in PDT: 2014-05-26T21:49:46.000-07:00
    • Format in UTC: 2014-05-26T21:49:46.000Z
  • Events list default limitation: The default events list length is 100. To set a new length specify the path length parameter in the relevant commands.
  • Local/global search: In ‘as-search’ and ‘as-search-events’ you can optionally pass the  ‘local_search’ parameter, to Indicate whether the search is local only, and does not include peers. Please note that local search is the default option for a search session.

Known Limitations

  • Session limitations: Arcsight Logger has default limitations for running maximum sessions simultaneously, and for inactive sessions. 
    To change the default limitation for both, use administrator credentials to login to Archsight Logger UI, navigate to ‘System Admin’->’Users/Groups’->’Authentication’ and set new limitations for ‘Max Simultaneous Logins/User’ and ‘Logout Inactive Session After’.

Troubleshooting

  • Reoccurring ‘timeout’ error when using commands ‘as-search-events’ or ‘as-events’:

This may indicate that a large amount of data returned from Arcsight Logger. To resolve this error, try to limit the search time range or the events list length.  See additional ways to set the search time range in ‘Additional info’ above.
DBot error snap-shot
 

 

  • Reoccurring ‘Login failed’ error when using ‘as-search’ or ‘as-search-events’:

First eliminate the case of wrong credentials configured in the Arcsight Logger instance.

If this error still araises, it may indicate that Arcsight Logger is failing to generate a new search session. New sessions cannot be generated by Arcsight Logger when the maximum allowed number of simultaneous sessions was reached.

To resolve this problem, use administrator credentials to login to Archsight Logger UI and set a new limitation for maximum simultaneous sessions.
See ’Known Limitations’ above for more information.

If administrator credentials are not available for you, use ‘as-close’ to close the running sessions.

 DBot error snap-shot
 

 

  • Reoccurring ‘User session id is not valid’ error:

The search session timed out.

Search session timeout can be caused by the followings:
- Low ‘timeout’ passed to ‘as-search’. This can be resolved by passing a higher ‘timeout’      value to ‘as-search’.
- Arcsight Logger limitation on inactive sessions - Inactive sessions are automatically terminated after a defined period of time determined by Arcsight Logger, even if the ‘timeout’ argument is changed to ‘as-search’.

To resolve this problem, use administrator credentials to login to Archsight Logger UI and set a new limitation for inactive sessions. See ’Known Limitations’ above for more information. 

DBot error snap-shot

Configuration parameters

  • url — Server URL (e.g. https://192.168.0.1)* (required)
  • port — Port (required)
  • isFetch — Fetch incidents
  • incidentType — Incident type
  • incidentFetchInterval — Incidents Fetch Interval
  • eventsQuery — Events query
  • fields — Fields
  • aggregate — Aggregate events into one incident
  • fetchlimit — Fetch limit
  • insecure — Trust any certificate (not secure)
  • proxy — Use system proxy settings
  • credentials — Credentials

Commands (7)

  • as-close

    Stops the execution of the search and clears the search session data from the server.

  • as-drilldown

    Narrows-down the search results to the specified time range

  • as-events

    Returns the list of events found in the specified search.

  • as-search

    In opposite to as-search-events, as-search-events waits until the search query is complete and returns the events, as-search initiates new logger search query, and returns sessionId and searchSessionId which should be used in other commands like as-status, as-stop, as-events, etc.

  • as-search-events

    Start a new search, wait until the search status is complete and then return the events. This command combine 3 commands - as-search, as-status, as-events

  • as-status

    Returns the latest status of the specified search.

  • as-stop

    Stops the search operation but keeps the search session so that the search results can be narrowed down later

var serverURL = params.url;
if (serverURL.slice(-1) === '/') {
    serverURL = serverURL.slice(0,-1);
}
var SERVER_URL = serverURL + ':' + params.port + '/';
var DAY_IN_MILLIS = 24*60*60*1000;

function login(username, password) {
    var fullUrl = SERVER_URL + 'core-service/rest/LoginService/login';

    var bodyObj = {
        login: username,
        password: password
    };
    var bodyString = encodeToURLQuery(bodyObj).substring(1);

    var req = {
        Method: 'POST',
        Headers: {
            'Content-Type': ['application/x-www-form-urlencoded']
        },
        Body: bodyString
    };

    var res = http(fullUrl, req, params.insecure, params.proxy);
    if (res.StatusCode !== 200) {
        throw 'Login failed. StatusCode: ' + res.StatusCode + (res.Body !== '' ? '. Error: ' + res.Body : '');
    }

    var resBody = parseXML(res.Body);
    if (!resBody.loginResponse.return) {
        throw 'Login to ArcSight Logger has failed - Session id is missing from response';
    }

    var userSessionId = resBody.loginResponse.return;
    return userSessionId;
}

function logout(userSessionId) {
    if (!userSessionId) {
        throw 'Unable to preform logout from ArcSight Logger. Seesion id is missing';
    }
    var fullUrl = SERVER_URL + 'core-service/rest/LoginService/logout';

    var bodyObj = {
        authToken: userSessionId
    };
    var bodyString = encodeToURLQuery(bodyObj).substring(1);

    var req = {
        Method: 'POST',
        Headers: {
            'Content-Type': ['application/x-www-form-urlencoded']
        },
        Body: bodyString
    };

    var res = http(fullUrl, req, params.insecure, params.proxy);
    if (res.StatusCode !== 200 && res.StatusCode !== 204) {
        throw 'Logout failed. StatusCode: ' + res.StatusCode + (res.Body !== '' ? '. Error: ' + res.Body : '');
    }
}

function getSearchEvents(userSessionId) {
    var events = getSearchEventsRequest(
        userSessionId,
        args.query,
        args.timeout,
        args.startTime,
        args.endTime,
        args.discover_fields,
        args.summary_fields,
        args.field_summary,
        args.local_search,
        args.lastDays,
        args.offset,
        args.dir,
        args.length,
        args.fields);

    var entry = {
        Type: entryTypes.note,
        Contents: events,
        ContentsFormat: formats.json,
        ReadableContentsFormat: formats.markdown
    };
    var title = 'ArcSight Logger - Events';
    var context = events;
    entry.HumanReadable = tableToMarkdown(title, events);
    entry.EntryContext = {};
    entry.EntryContext['ArcSightLogger.Events(val.rowId === obj.rowId)'] = context;
    return entry;
}

function getSearchEventsRequest(userSessionId, query, timeout, startTime,
    endTime, discoverFields, summaryFields, fieldSummary, localSearch, lastDays,
    offset, dir, length, fields) {
    // start new search
    var searchSessionId = startSearchSessionRequest(
        userSessionId,
        query,
        timeout,
        startTime,
        endTime,
        discoverFields,
        summaryFields,
        fieldSummary,
        localSearch,
        lastDays);

    // wait until the search is complete so we could collect the events
    var statusResult;
    var requiredEvents = Infinity;
    if(length){
        requiredEvents = offset ? parseInt(length) + parseInt(offset) : parseInt (length);
    }
    do {
        wait(1);
        statusResult = getSearchStatusRequest(userSessionId, searchSessionId);
        if (statusResult.status === 'error') {
            throw 'Invalid query.\nSearch status: ' + JSON.stringify(statusResult, null ,2);
        }
    } while(statusResult.status !== 'complete' && requiredEvents > statusResult.hit);
    // get the results
    var events;
    if (statusResult.result_type === 'chart') {
        events = getChartRequest(userSessionId, searchSessionId);
    } else {
        events = getEventsRequest(userSessionId, searchSessionId, offset, dir, length, fields);
    }
    // close the session
    closeSessionRequest(userSessionId, searchSessionId);

    logout(userSessionId);
    return events;
}

function startSearchSession(userSessionId) {
    var searchSessionId = startSearchSessionRequest(
        userSessionId,
        args.query,
        args.timeout,
        args.startTime,
        args.endTime,
        args.discover_fields,
        args.summary_fields,
        args.field_summary,
        args.local_search,
        args.lastDays);

    var entry = {
        Type: entryTypes.note,
        Contents: {
            searchSessionId: searchSessionId,
            sessionId : userSessionId
        },
        ContentsFormat: formats.json,
        ReadableContentsFormat: formats.markdown
    };
    var title = "ArcSight Logger - Start Search Session";
    var context = {
        'SearchSessionId': searchSessionId,
        'SessionId' : userSessionId
    };
    entry.HumanReadable = tableToMarkdown(title, context);
    entry.EntryContext = {};
    entry.EntryContext['ArcSightLogger.Search'] = context;
    return entry;
}

function startSearchSessionRequest(userSessionId, query, timeout, startTime, endTime, discoverFields, summaryFields, fieldSummary, localSearch, lastDays) {
    var searchSessionId = generateSearchSessionId();
    var bodyArgs = {
        search_session_id: searchSessionId,
        user_session_id: userSessionId
    };
    if (query) {
        bodyArgs.query = query;
    }
    if (timeout) {
        bodyArgs.timeout = parseInt(timeout);
    }
    if (lastDays) {
        if (isNaN(lastDays)) {
            throw 'LastDays must be a number';
        }
        var ld = parseInt(lastDays);
        var now = new Date();
        bodyArgs.end_time = now.toISOString();
        now.setTime(now.getTime() - ld * DAY_IN_MILLIS)
        bodyArgs.start_time = now.toISOString();
    } else if (startTime && endTime) {
        bodyArgs.end_time = endTime;
        bodyArgs.start_time = startTime;
    }
    if (discoverFields) {
        bodyArgs.discover_fields = parseBool(discoverFields);
    }
    if (summaryFields) {
        bodyArgs.summary_fields = parseArray(summaryFields);
    }
    if (fieldSummary) {
        bodyArgs.field_summary = parseBool(fieldSummary);
    }
    if (localSearch) {
        bodyArgs.local_search = parseBool(localSearch);
    }

    var resBody = httpPost('server/search', null, bodyArgs);

    return searchSessionId;
}

function closeSession() {
    closeSessionRequest(args.sessionId, args.searchSessionId);
    return {
        Type: entryTypes.note,
        ContentsFormat: formats.text,
        Contents: 'Session closed successfully'
    };
}

function closeSessionRequest(userSessionId, searchSessionId) {
    var bodyArgs = {
        search_session_id: parseInt(searchSessionId),
        user_session_id: userSessionId
    };
    httpPost('server/search/close', null, bodyArgs);
}

function getSearchStatus() {
    var searchStatus = getSearchStatusRequest(args.sessionId, args.searchSessionId);
    var contextKey = 'ArcSightLogger.Status(val.SearchSessionId === obj.SearchSessionId)';
    var entry = createEntry(searchStatus, {
        data: [
            {to: 'Status', from: 'status'},
            {to: 'ResultType', from: 'result_type'},
            {to: 'Hit', from: 'hit'},
            {to: 'Scanned', from: 'scanned'},
            {to: 'Elapsed', from: 'elapsed'},
            {to: 'Message', from: 'message'}
        ],
        title: 'ArcSight Logger - Search Status',
        contextPath: contextKey
    });
    entry.EntryContext[contextKey]['SearchSessionId'] = args.searchSessionId;
    return entry;
}

function getSearchStatusRequest(userSessionId, searchSessionId) {
    var bodyArgs = {
        search_session_id: parseInt(searchSessionId),
        user_session_id: userSessionId
    };

    var resBody = httpPost('server/search/status', null, bodyArgs);
    return resBody;
}

function getEvents() {
    var statusResult = getSearchStatusRequest(
        args.sessionId,
        args.searchSessionId);
    var events;
    if (statusResult.result_type === 'chart'){
        events = getChartRequest(
            args.sessionId,
            args.searchSessionId);
    } else {
       events = getEventsRequest(
            args.sessionId,
            args.searchSessionId,
            args.offset,
            args.dir,
            args.length,
            args.fields);
    }
    var entry = {
        Type: entryTypes.note,
        Contents: events,
        ContentsFormat: formats.json,
        ReadableContentsFormat: formats.markdown
    };
    var title = 'ArcSight Logger - Events';
    var context = events;
    entry.HumanReadable = tableToMarkdown(title, events);
    entry.EntryContext = {};
    entry.EntryContext['ArcSightLogger.Events(val.rowId === obj.rowId)'] = context;
    return entry;
}

function getEventsRequest(userSessionId, searchSessionId, offset, dir, length, fields) {
    var bodyArgs = {
        search_session_id: parseInt(searchSessionId),
        user_session_id: userSessionId
    };
    if (offset) {
        bodyArgs.offset = parseInt(offset);
    }
    if (dir) {
        bodyArgs.dir = dir;
    }
    if (length) {
        if (isNaN(length)) {
            throw 'Length must be a number';
        }
        bodyArgs.length = parseInt(length);
    }
    if (fields) {
        bodyArgs.fields = fields.split(",");
    }
    var resBody = httpPost('server/search/events', null, bodyArgs);
    var events = xmlObjectToJSON(resBody);
    return events;
}

function getChartRequest(userSessionId, searchSessionId) {
    var bodyArgs = {
        search_session_id: parseInt(searchSessionId),
        user_session_id: userSessionId
    };
    bodyArgs.offset = 0;
    bodyArgs.length = 100;
    var resBody = httpPost('/server/search/chart_data', null, bodyArgs);
    var events = xmlObjectToJSON(resBody);
    return events;
}

function drilldown() {
    var result = drilldownRequest(args.sessionId, args.searchSessionId, args.startTime, args.endTime, args.lastDays);
    var entry = {
        Type: entryTypes.note,
        Contents: result,
        ContentsFormat: formats.json,
        ReadableContentsFormat: formats.text,
        HumanReadable: 'Success drilldown request'
    };
    return entry;
}

function drilldownRequest(userSessionId, searchSessionId, startTime, endTime, lastDays) {
    var bodyArgs = {
        search_session_id: parseInt(searchSessionId),
        user_session_id: userSessionId
    };
    if (lastDays) {
        if (isNaN(lastDays)) {
            throw 'LastDays must be a number';
        }
        var ld = parseInt(lastDays);
        var now = new Date();
        bodyArgs.end_time = now.toISOString();
        now.setTime(now.getTime() - ld * DAY_IN_MILLIS)
        bodyArgs.start_time = now.toISOString();
    } else if (startTime && endTime) {
        bodyArgs.end_time = endTime;
        bodyArgs.start_time = startTime;
    } else {
        throw 'Make sure lastDays is provided, or both startTime and endTime are provided'
    }
    var resBody = httpPost('server/search/drilldown', null, bodyArgs);
    return resBody;
}

function stopSearch() {
    stopSearchRequest(args.sessionId, args.searchSessionId);
    return {
        Type: entryTypes.note,
        ContentsFormat: formats.text,
        Contents: 'Search stopped successfully'
    };
}

function stopSearchRequest(userSessionId, searchSessionId) {
    var bodyArgs = {
        search_session_id: parseInt(searchSessionId),
        user_session_id: userSessionId
    };

    httpPost('server/search/stop', null, bodyArgs);
}

function fetchIncidents() {
    var userSessionId = login(params.credentials.identifier, params.credentials.password);
    var lastRun = getLastRun();

    var n = new Date();
    var endTime = n.toISOString();
    var startTime;
    var query;
    if (lastRun && lastRun.time && lastRun.time !== '') {
        startTime = lastRun.time;
    } else {
        n.setTime(n.getTime() - 1 * DAY_IN_MILLIS);
        startTime = n.toISOString();
    }
    if (params.eventsQuery){
        query = params.eventsQuery;
    }
    if (params.fields){
        var fields = params.fields;
        var discover_fields = true;
    } else {
        var fields = null;
        var discover_fields = false;
    }
    if (params.fetchlimit){
        var fetchlimit = params.fetchlimit;
    } else {
        var fetchlimit = 100;
    }
    var events = getSearchEventsRequest(userSessionId, query, 120000, startTime,
        endTime, discover_fields, null, null, false, null,
        null, null, fetchlimit, fields);

    var incidents = [];
    if(params.aggregate){
        var events_aggregate = { "Events" : events };
        var incident = incidentFromEvent(events_aggregate);
        incidents.push(incident);
    } else {
        for (var i = 0; i < events.length; i++) {
            var incident = incidentFromEvent(events[i]);
            incidents.push(incident);
        }
    }

    setLastRun({ time: endTime });
    return JSON.stringify(incidents);
}

switch(command) {
    case 'test-module':
        var userSessionId = login(params.credentials.identifier, params.credentials.password);
        logout(userSessionId);
        return 'ok';
    case 'fetch-incidents':
        return fetchIncidents();
    case 'as-search-events':
        var userSessionId = login(params.credentials.identifier, params.credentials.password);
        return getSearchEvents(userSessionId);
    case 'as-search':
        var userSessionId = login(params.credentials.identifier, params.credentials.password);
        var result = startSearchSession(userSessionId);
        return result;
    case 'as-status':
        var result = getSearchStatus();
        return result;
    case 'as-events':
        return getEvents();
    case 'as-close':
        var result = closeSession();
        logout(args.sessionId);
        return result;
    case 'as-stop':
        return stopSearch();
    case 'as-drilldown':
        return drilldown();
    default:
        throw 'Command ' + command + ' not exists';
}

function httpPost(path, queryObject, body) {
    var fullUrl = SERVER_URL + path;
    if (queryObject) {
        fullUrl += encodeToURLQuery(queryObject)
    }

    var req = {
        Method: 'POST',
        Headers: {
            'Content-Type' : ['application/json; charset=UTF-8'],
            'Accept': ['appliction/json']
        },
        Body: JSON.stringify(body)
    }
    var res = http(fullUrl, req, params.insecure, params.proxy);

    if (res.StatusCode < 200 || res.StatusCode >= 300) {
        try {
            var resBody = JSON.parse(res.Body);
        } catch(e) {
            throw 'Request to ' + fullUrl + ' failed. StatusCode: ' + res.StatusCode + (res.Body !== '' ? '. Error: ' + res.Body : '');
        }
        var errTbl = resBody.errors;
        var errMessage = '';
        if (errTbl) {
            errTbl.forEach(function(err) {
                if(err.message) {
                    errMessage =  errMessage === '' ?  err.message : errMessage + ', ' + err.message;
                }
            });
        }
        throw 'Request to ' + fullUrl + ' failed. StatusCode: ' + res.StatusCode + '. Error: ' + errMessage;
    }
    try {
        return JSON.parse(res.Body);
    } catch(err){
        return res.Body;
    }
}

function parseXML(httpResponseBody) {
    var body = httpResponseBody.replace(/&#x.*?;/g, "");
    var parsed = JSON.parse(x2j(body));
    return parsed;
}

function parseBool(val) {
    return val === 'true' ? true : false;
}

function generateSearchSessionId() {
    var sessID = new Date().getTime();
    return sessID;
}

function parseArray(commaSepList) {
    return commaSepList.split(',');
}
function xmlObjectToJSON(xmlObject) {
    var context = [];
    if (xmlObject && xmlObject.fields && xmlObject.results) {
        var keys = [];
        var fields = xmlObject.fields;
        var entries = xmlObject.results;
        var isDateField = [];
        fields.forEach(function(field){
            if(field.name){
                keys.push(field.name.replace(/\s/g, '').replace(/^\_/,''));
                isDateField.push(field.type == 'date');
            }
        });
        entries.forEach(function(entry){
            if (entry.length == keys.length){
                var newEntry = {};
                for (var i = 0; i<  entry.length; i++){
                    if (isDateField[i] && !isNaN(entry[i])) {
                        var dateEntry = new Date(0);
                        dateEntry.setUTCSeconds(parseInt(entry[i]) / 1000);
                        entry[i] = dateEntry.toISOString();
                    }
                    newEntry[keys[i]] = entry[i];
                }
                context.push(newEntry);
            }
        });
    }
    return context;
}

function incidentFromEvent(event){
    var incident = {}
    //incident.labels = Object.keys(event);
    incident.rawJSON = JSON.stringify(event);
    var name = 'ArcSight Logger Incident';
    name = event.rowId ? name + ' ' + event.rowId : name;
    incident.name = name;
    incident.dbotMirrorId = event.rowId;
    return incident;
}