MongoDB Log

Writes log data to a MongoDB collection.

Database · MongoDB

Details

IDMongoDB Log
ProviderMongoDB Inc.
CategoryDatabase
From Version5.0.0
Docker Imagedemisto/py3-tools:1.0.0.114656
Supported ModulesAgentix XSIAM

README

Overview


Writes log data to a MongoDB collection.
This integration was integrated and tested with version v4.2.3 of MongoDB.

The account user must have appropriate permissions - root role to execute the API calls.

Use Cases


  1. Write to MongoDB Log collection.
  2. Read from MongoDB log collection.
  3. Get the number of log entries.

Configure MongoDB Log on Demisto


  1. Navigate to Settings > Integrations > Servers & Services.
  2. Search for MongoDB Log.
  3. Click Add instance to create and configure a new integration instance.
    • Name: a textual name for the integration instance.
    • MongoDB Username
    • URI (mongodb://IP/FQDN:Port Number)
    • Database Name
    • Collection Name
    • Trust any certificate (not secure)
    • Use SSL/TLS secured connection
  4. Click Test to validate the URLs, token, and connection.

Commands


You can execute these commands from the Demisto 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.

  1. mongodb-read-log
  2. mongodb-write-log
  3. mongodb-logs-number

1. mongodb-read-log


Returns all log entries.

Base Command

mongodb-read-log

Input
Argument Name Description Required
limit The maximum number of logs to return. Optional
Context Output

There is no context output for this command.

Command Example

!mongodb-read-log limit=5

Human Readable Output

The log documents/records for collection “log”

log
{‘name’: ‘Midhuna’, ‘age’: 23, ‘cars’: [‘BMW 320d’, ‘Audi R8’], ‘place’: ‘Amaravati’},{‘timestamp’: ‘2020-03-22T18:57:33+00:00’, ‘entity’: ‘test’, ‘playbook’: ‘my playbook’, ‘action’: ‘create’, ‘analyst’: ‘admin’},{‘test’: ‘value’},{‘123’: {‘modified’: ‘2020-03-22T19:14:29+00:00’, ‘key’: ‘test’, ‘value’: ‘123’}},{‘timestamp’: ‘2020-03-23T10:45:39+00:00’, ‘entity’: ‘{test: demisto}’, ‘playbook’: ‘mongodb’, ‘action’: ‘create’, ‘analyst’: ‘admin’}

2. mongodb-write-log


Adds a log entry.

Base Command

mongodb-write-log

Input
Argument Name Description Required
playbook The playbook that was used. Optional
user The assigned user. Optional
id Entity to write to the log. Optional
action The actions that were performed. Optional
message Message for the entry. Optional
Context Output
Path Type Description
MongoDB.Entry.Action String The actions that were performed.
MongoDB.Entry.User String Assigned analyst.
MongoDB.Entry.ID String Entity to write to the log.
MongoDB.Entry.EntryID String Entry ID.
MongoDB.Entry.Playbook String The playbook that was used.
MongoDB.Entry.Timestamp Date Entry timestamp.
MongoDB.Entry.Message String The message of the entry.
Command Example

!mongodb-write-log action=create message="This is a test message"

Context Example
{
    "MongoDB.Entry": {
        "Timestamp": "2020-04-12T07:59:43+00:00", 
        "EntryID": "5e92ca6f8f55e45510637880", 
        "Playbook": null, 
        "Action": "create", 
        "Message": "This is a test message", 
        "ID": "6e1807d3-b0ae-40a0-8e82-dad33539c587", 
        "User": null
    }
}
Human Readable Output

MongoDB Log - 1 document/record added

3. mongodb-logs-number


Returns the number of log entries.

Base Command

mongodb-logs-number

Input

There are no input arguments for this command.

Context Output

There is no context output for this command.

Command Example

!mongodb-logs-number

Human Readable Output

The count of log documents/records is 56

Configuration parameters

  • credentials — MongoDB Username (required)
  • uri — URI (mongodb://<IP/FQDN>:<Port Number>) (required)
  • database — Database Name (required)
  • collection — Collection Name (required)
  • insecure — Trust any certificate (not secure)
  • use_ssl — Use SSL/TLS secured connection

Commands (3)

  • mongodb-logs-number

    Returns the number of log entries.

  • mongodb-read-log

    Returns all log entries.

  • mongodb-write-log

    Adds a log entry.

import demistomock as demisto
from CommonServerPython import *

from CommonServerUserPython import *

""" IMPORTS """
from datetime import datetime

from pymongo import MongoClient

""" GLOBALS/PARAMS """

# Get Credentials
USERNAME = demisto.params().get("credentials").get("identifier")
PASSWORD = demisto.params().get("credentials").get("password")
# Get Server
URI = demisto.params().get("uri")
# Get Database
DATABASE = demisto.params().get("database")
USE_SSL = demisto.params().get("use_ssl", False)
INSECURE = demisto.params().get("insecure", False)
TIMEOUT = 5000
if INSECURE and not USE_SSL:
    raise DemistoException('"Trust any certificate (not secure)" must be ticked with "Use TLS/SSL secured connection"')
if not INSECURE and not USE_SSL:
    # Connect to MongoDB - Need to add credentials and lock down MongoDB (add auth)
    CLIENT = MongoClient(  # type: ignore[var-annotated]
        URI,
        username=USERNAME,
        password=PASSWORD,
        authSource=DATABASE,
        authMechanism="SCRAM-SHA-1",
        ssl=USE_SSL,
        socketTimeoutMS=TIMEOUT,
    )
else:
    CLIENT = MongoClient(
        URI,
        username=USERNAME,
        password=PASSWORD,
        authSource=DATABASE,
        authMechanism="SCRAM-SHA-1",
        ssl=USE_SSL,
        tlsAllowInvalidCertificates=INSECURE,
        socketTimeoutMS=TIMEOUT,
    )
DB = CLIENT[DATABASE]
# Set Collection
COLLECTION_NAME = demisto.params().get("collection")
COLLECTION = DB[COLLECTION_NAME]


def test_module():
    """Check DB Status"""
    if CLIENT.server_info().get("ok") == 1.0:
        return "ok", {}, {}
    return "MongoDB Server Error", {}, {}


def write_log_json():
    """Gather Args, form json document, write document to MondoDB"""
    investigation = demisto.investigation()
    investigation_id = investigation.get("id")
    investigation_user = investigation.get("user")
    timestamp = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S+00:00")
    id_ = demisto.args().get("id", investigation_id)
    playbook = demisto.args().get("playbook")
    action = demisto.args().get("action")
    user = demisto.args().get("user", investigation_user)
    message = demisto.args().get("message")
    logjson = {"timestamp": timestamp, "id": id_, "playbook": playbook, "action": action, "user": user, "message": message}
    # Add json to the document collection in MondoDB
    result = COLLECTION.insert_one(logjson)
    entry_id = result.inserted_id

    context = {
        "EntryID": str(entry_id),
        "Timestamp": timestamp,
        "ID": id_,
        "Playbook": playbook,
        "Action": action,
        "User": user,
        "Message": message,
    }
    ec = {"MongoDB.Entry(val.EntryID === obj.EntryID)": context}
    return "MongoDB Log - 1 document/record added", ec, {}


def read_log_json():
    """Get all log documents/records from MondoDB"""
    limit = int(demisto.args().get("limit"))
    # Point to all the documents
    doc_count = COLLECTION.count_documents(filter={}, limit=limit)
    cursor = COLLECTION.find({}, {"_id": False})
    # Create an empty log list
    entries = []
    # Iterate through those documents
    if doc_count > 0:
        for i in cursor:
            # Append log entry to list
            entries.append(i)
        return_json = {COLLECTION_NAME: entries}
        human_readable = tableToMarkdown(
            f'The log documents/records for collection "{COLLECTION_NAME}"', return_json.get(COLLECTION_NAME)
        )
        return human_readable, {}, {}
    return "MongoDB - no documents/records - Log collection is empty", {}, {}


def num_log_json():
    """Get a count of all log documents/records from MondoDB"""
    # Point to the documents
    doc_count = COLLECTION.count_documents(filter={})
    human_readable = f"The count of log documents/records is {doc_count!s}"
    return human_readable, {}, {}


def main():
    LOG(f"Command being called is {demisto.command()}")
    try:
        if demisto.command() == "test-module":
            # This is the call made when pressing the integration test button.
            test_module()
            return_outputs(*test_module())
        elif demisto.command() == "mongodb-write-log":
            return_outputs(*write_log_json())
        elif demisto.command() == "mongodb-read-log":
            return_outputs(*read_log_json())
        elif demisto.command() == "mongodb-logs-number":
            return_outputs(*num_log_json())
    except Exception as e:
        return_error(f"MongoDB: {e!s}", error=e)


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