{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Title: msticpy - nbwidgets\n", "## Description:\n", "This contains a few aggregated widgets using IPyWidgets that help speed things up during an investigation.\n", "\n", "You must have msticpy installed to run this notebook:\n", "```\n", "%pip install --upgrade msticpy\n", "```\n", "\n", "MSTICpy versions >= 0.8.5" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## Table of Contents\n", "- [Setting query start/end times](#QueryTime)\n", "- [Simple time range](#Lookback)\n", "- [Selecting and Displaying Alerts](#AlertSelector)\n", "- [Selecting from list or dict](#SelectString)\n", "- [Getting a value from environment](#GetEnvironmentKey)\n" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "ExecuteTime": { "end_time": "2019-12-19T22:12:36.439490Z", "start_time": "2019-12-19T22:12:34.694845Z" }, "scrolled": true }, "outputs": [], "source": [ "# Imports\n", "import sys\n", "MIN_REQ_PYTHON = (3,6)\n", "if sys.version_info < MIN_REQ_PYTHON:\n", " print('Check the Kernel->Change Kernel menu and ensure that Python 3.6')\n", " print('or later is selected as the active kernel.')\n", " sys.exit(\"Python %s.%s or later is required.\\n\" % MIN_REQ_PYTHON)\n", "\n", "from IPython.display import display, Markdown\n", "import pandas as pd\n", "\n", "from msticpy import nbwidgets\n", "from msticpy.nbtools.security_alert import SecurityAlert\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[Contents](#contents)\n", "## QueryTime\n", "\n", "This widget is used to specify time boundaries - designed to be used with the built-in msticpy queries and custom queries.\n", "The `start` and `end` times are exposed as datetime properties.\n", "\n", "```\n", "QueryTime.\n", "\n", "Composite widget to capture date and time origin\n", "and set start and end times for queries.\n", "\n", "Parameters\n", "----------\n", "QueryParamProvider : QueryParamProvider\n", " Abstract base class\n", "\n", "Parameters\n", "----------\n", "origin_time : datetime, optional\n", " The origin time (the default is `datetime.utcnow()`)\n", "label : str, optional\n", " The description to display\n", " (the default is 'Select time ({units}) to look back')\n", "before : int, optional\n", " The default number of `units` before the `origin_time`\n", " (the default is 60)\n", "after : int, optional\n", " The default number of `units` after the `origin_time`\n", " (the default is 10)\n", "max_before : int, optional\n", " The largest value for `before` (the default is 600)\n", "max_after : int, optional\n", " The largest value for `after` (the default is 100)\n", "units : str, optional\n", " Time unit (the default is 'min')\n", " Permissable values are 'day', 'hour', 'minute', 'second'\n", " These can all be abbreviated down to initial characters\n", " ('d', 'm', etc.)\n", "auto_display : bool, optional\n", " Whether to display on instantiation (the default is False)\n", "```" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "ExecuteTime": { "end_time": "2019-12-19T22:12:42.494790Z", "start_time": "2019-12-19T22:12:42.453819Z" }, "tags": [] }, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "4a6e2f13719448c3adbae56ec68b6065", "version_major": 2, "version_minor": 0 }, "text/plain": [ "VBox(children=(HTML(value='

Set query time boundaries

'), HBox(children=(DatePicker(value=datetime.date…" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "q_times = nbwidgets.QueryTime(units='day', max_before=20, before=5, max_after=1)\n", "q_times.display()" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "ExecuteTime": { "end_time": "2019-09-02T23:37:00.573557Z", "start_time": "2019-09-02T23:37:00.569561Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2022-03-10 20:30:11.220186 .... 2022-03-16 20:30:11.220186\n" ] } ], "source": [ "print(q_times.start, '....', q_times.end)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Keep multiple query boundaries aligged by having QueryTime instances reference the time of the same alert or event, or have them chained from one another by referencing the origin_time of an earlier QueryTimes object" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "ExecuteTime": { "end_time": "2019-12-19T22:29:50.924729Z", "start_time": "2019-12-19T22:29:50.845790Z" }, "scrolled": true }, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "c479a26992aa437b953815cae7df1bd1", "version_major": 2, "version_minor": 0 }, "text/plain": [ "VBox(children=(HTML(value='

Set query time boundaries

'), HBox(children=(DatePicker(value=datetime.date…" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "e72dbce1822e436491d1ac4c8ebbc498", "version_major": 2, "version_minor": 0 }, "text/plain": [ "VBox(children=(HTML(value='

Set query time boundaries

'), HBox(children=(DatePicker(value=datetime.date…" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "from datetime import datetime, timedelta\n", "\n", "\n", "class MyAlert:\n", " pass\n", "\n", "alert = MyAlert()\n", "alert.TimeGenerated = datetime.utcnow() - timedelta(15)\n", "alert.TimeGenerated\n", "\n", "q_times1 = nbwidgets.QueryTime(units='hour', max_before=20, before=1, max_after=1, \n", " origin_time=alert.TimeGenerated, auto_display=True)\n", "\n", "q_times2 = nbwidgets.QueryTime(units='hour', max_before=20, before=4, max_after=2, \n", " origin_time=alert.TimeGenerated, auto_display=True)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "ExecuteTime": { "end_time": "2019-12-19T22:29:53.682587Z", "start_time": "2019-12-19T22:29:53.608644Z" }, "scrolled": true }, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "b10950cd7caa428fbc217a5c909e0ad4", "version_major": 2, "version_minor": 0 }, "text/plain": [ "VBox(children=(HTML(value='

Set query time boundaries

'), HBox(children=(DatePicker(value=datetime.date…" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "c545903af3d3408589fc34bcd23b8f76", "version_major": 2, "version_minor": 0 }, "text/plain": [ "VBox(children=(HTML(value='

Set query time boundaries

'), HBox(children=(DatePicker(value=datetime.date…" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "alert.TimeGenerated = datetime.utcnow()\n", "q_times1 = nbwidgets.QueryTime(units='hour', max_before=20, before=1, max_after=1, \n", " origin_time=alert.TimeGenerated, auto_display=True)\n", "\n", "q_times2 = nbwidgets.QueryTime(units='hour', max_before=20, before=4, max_after=2, \n", " origin_time=q_times2.origin_time, auto_display=True)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "ExecuteTime": { "end_time": "2019-09-02T23:37:04.725203Z", "start_time": "2019-09-02T23:37:04.721208Z" }, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "SecurityAlert \n", "| where TimeGenerated >= datetime(2022-03-15 19:30:11.736218)\n", "| where TimeGenerated <= datetime(2022-03-16 02:30:11.736218)\n" ] } ], "source": [ "# Use the values in a query\n", "my_kql = f'''\n", "SecurityAlert \n", "| where TimeGenerated >= datetime({q_times1.start})\n", "| where TimeGenerated <= datetime({q_times1.end})'''\n", "print(my_kql)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[Contents](#contents)\n", "## Lookback\n", "Simpler version with single slider value\n", "\n", "Docstring:\n", "`nbwidgets.Lookback?`" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "ExecuteTime": { "end_time": "2019-12-19T22:29:59.905261Z", "start_time": "2019-12-19T22:29:59.893270Z" }, "scrolled": true }, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "9b5b0182c6e341688450c16ce4728124", "version_major": 2, "version_minor": 0 }, "text/plain": [ "IntSlider(value=6, description='Select time (HOUR) to look back', layout=Layout(height='50px', width='60%'), m…" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "alert.TimeGenerated = datetime.utcnow() - timedelta(5)\n", "lb = nbwidgets.Lookback(origin_time=alert.TimeGenerated, auto_display=True, max_value=48)" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "ExecuteTime": { "end_time": "2019-09-02T23:37:09.268885Z", "start_time": "2019-09-02T23:37:09.265888Z" }, "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2022-03-10 14:30:12.020220 .... 2022-03-10 20:30:12.020220\n" ] } ], "source": [ "print(lb.start, '....', lb.end)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[Contents](#contents)\n", "## Alert Browser\n", "\n", "```\n", "SelectAlert.\n", "\n", "View list of alerts and select one for investigation.\n", "Optionally provide and action to call with the selected alert as a parameter\n", "(typically used to display the alert.)\n", "\n", "Attributes:\n", " selected_alert: the selected alert\n", " alert_id: the ID of the selected alert\n", " alerts: the current alert list (DataFrame)\n", "Init docstring:\n", "Create a new instance of AlertSelector.\n", "\n", "Parameters\n", "----------\n", "alerts : pd.DataFrame\n", " DataFrame of alerts.\n", "action : Callable[..., None], optional\n", " Optional function to execute for each selected alert.\n", " (the default is None)\n", "columns : list, optional\n", " Override the default column names to use from `alerts`\n", " (the default is ['StartTimeUtc', 'AlertName',\n", " 'CompromisedEntity', 'SystemAlertId'])\n", "auto_display : bool, optional\n", " Whether to display on instantiation (the default is False)\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Simple alert selector\n", "Selected alert is available as `select_alert_widget.selected_alert` property" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "ExecuteTime": { "end_time": "2019-12-19T22:33:01.169572Z", "start_time": "2019-12-19T22:33:01.108619Z" } }, "outputs": [ { "data": { "text/markdown": [ "### Simple alert selector" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/markdown": [ "Selected alert is available as `select_alert_widget.selected_alert`" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "8f232775764a4a66abe86df410eeafe1", "version_major": 2, "version_minor": 0 }, "text/plain": [ "VBox(children=(Text(value='', description='Filter alerts by title:', style=DescriptionStyle(description_width=…" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Load test data\n", "alerts = pd.read_csv('data/alertlist.csv')\n", "\n", "display(Markdown('### Simple alert selector'))\n", "display(Markdown('Selected alert is available as `select_alert_widget.selected_alert`'))\n", "alert_select = nbwidgets.SelectAlert(alerts=alerts)\n", "alert_select.display()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Alert selector with action=SecurityAlert'\n", "You can pass a function that returns one or more displayable objects.\n", "You can also pass a class (in this case we're passing `SecurityAlert`) that produces an IPython displayable object.\n", "\n", "The `action` class/function is passed the raw alert row as a parameter, as it is selected from the list" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "ExecuteTime": { "end_time": "2019-12-19T22:33:22.044868Z", "start_time": "2019-12-19T22:33:21.987913Z" } }, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "144bc9cf0333451f9fa588cfe2116605", "version_major": 2, "version_minor": 0 }, "text/plain": [ "VBox(children=(Text(value='', description='Filter alerts by title:', style=DescriptionStyle(description_width=…" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "\n", "

Alert: 'DC local group addition - Demo'

\n", " Alert_time: 2019-01-11 06:31:40,\n", " Compr_entity: nan,\n", " Alert_id: self.properties['SystemAlertId']\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
0
Unnamed: 00
TenantId802d39e1-9d70-404d-832c-2de5e2478eda
StartTimeUtc2019-01-11 06:31:40
EndTimeUtc2019-01-12 06:31:40
ProviderAlertIde0c9484b-ad5f-4161-b73b-388676c05818
SystemAlertId047f47d6-79b7-4502-824b-97abc4905a73
ProviderNameCustomAlertRule
VendorNameAlert Rule
AlertTypeDC local group addition - Demo
AlertNameDC local group addition - Demo
AlertDisplayNameDC local group addition - Demo
DescriptionDomain controllers local group addition
SeverityLow
IsIncidentFalse
ExtendedProperties{'Alert Mode': 'Aggregated', 'Search Query': '{\"detailBladeInputs\":{\"id\":\"/subscriptions/3c1bb38c-82e3-4f8d-a115-a7110ba70d05/resourcegroups/contoso77/providers/microsoft.operationalinsights/workspaces/contoso77\",\"parameters\":{\"q\":\"SecurityEvent\\n| where EventID == 4625\\n| extend IPCustomEntity = \\\"75.10.91.22\\\"\\n| extend HostCustomEntity = Computer\\n| extend AccountCustomEntity = Account\",\"timeInterval\":{\"intervalDuration\":86400,\"intervalEnd\":\"2019-01-12T06%3A31%3A40.000Z\"}}},\"detailBlade\":\"SearchBlade\",\"displayValue\":\"SecurityEvent\\n| where EventID == 4625\\n| extend IPCustomEntity = \\\"75.10.91.22\\\"\\n| extend HostCustomEntity = Computer\\n| extend AccountCustomEntity = Account\",\"extension\":\"Microsoft_OperationsManagementSuite_Workspace\",\"kind\":\"OpenBlade\"}', 'Search Query Results Overall Count': '23034', 'Threshold Operator': 'Greater Than', 'Threshold Value': '10000', 'Query Interval in Minutes': '1440', 'Suppression in Minutes': '800', 'Total Account Entities': '1563', 'Total IP Entities': '1', 'Total Host Entities': '1'}
Entities[{'$id': '3', 'Address': '75.10.91.22', 'Type': 'ip', 'Count': 23034}, {'$id': '4', 'HostName': 'DHCPContoso77', 'Type': 'host', 'Count': 23034}, {'$id': '5', 'Name': 'ADMINISTRATOR', 'NTDomain': '', 'Host': {'$ref': '4'}, 'IsDomainJoined': False, 'Type': 'account', 'Count': 5909}, {'$id': '6', 'Name': 'ADMIN', 'NTDomain': '', 'Host': {'$ref': '4'}, 'IsDomainJoined': False, 'Type': 'account', 'Count': 878}, {'$id': '7', 'Name': 'USER', 'NTDomain': '', 'Host': {'$ref': '4'}, 'IsDomainJoined': False, 'Type': 'account', 'Count': 486}]
ConfidenceLevelUnknown
ConfidenceScoreNaN
ExtendedLinksNaN
WorkspaceSubscriptionId3c1bb38c-82e3-4f8d-a115-a7110ba70d05
WorkspaceResourceGroupcontoso77
TimeGenerated2019-01-12 06:41:44
ResourceIdNaN
SourceComputerIdNaN
CompromisedEntityNaN

ExtendedProperties:

\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
0
Alert ModeAggregated
Search Query{\"detailBladeInputs\":{\"id\":\"/subscriptions/3c1bb38c-82e3-4f8d-a115-a7110ba70d05/resourcegroups/contoso77/providers/microsoft.operationalinsights/workspaces/contoso77\",\"parameters\":{\"q\":\"SecurityEvent\\n| where EventID == 4625\\n| extend IPCustomEntity = \\\"75.10.91.22\\\"\\n| extend HostCustomEntity = Computer\\n| extend AccountCustomEntity = Account\",\"timeInterval\":{\"intervalDuration\":86400,\"intervalEnd\":\"2019-01-12T06%3A31%3A40.000Z\"}}},\"detailBlade\":\"SearchBlade\",\"displayValue\":\"SecurityEvent\\n| where EventID == 4625\\n| extend IPCustomEntity = \\\"75.10.91.22\\\"\\n| extend HostCustomEntity = Computer\\n| extend AccountCustomEntity = Account\",\"extension\":\"Microsoft_OperationsManagementSuite_Workspace\",\"kind\":\"OpenBlade\"}
Search Query Results Overall Count23034
Threshold OperatorGreater Than
Threshold Value10000
Query Interval in Minutes1440
Suppression in Minutes800
Total Account Entities1563
Total IP Entities1
Total Host Entities1

Entity counts:

ip: 1, host: 1, account: 3" ], "text/plain": [ "SecurityAlert(Unnamed: 0=0, TenantId=802d39e1-9d70-404d-832c-2de5e2478eda, StartTimeUtc=2019-0...)" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "alert_select = nbwidgets.SelectAlert(alerts=alerts, action=SecurityAlert)\n", "alert_select.display()" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "ExecuteTime": { "end_time": "2019-12-19T22:39:52.652753Z", "start_time": "2019-12-19T22:39:52.584806Z" }, "scrolled": true }, "outputs": [ { "data": { "text/markdown": [ "### Or a more detailed display with extracted entities" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "544eb0a357774e3a971110f493845c7e", "version_major": 2, "version_minor": 0 }, "text/plain": [ "VBox(children=(Text(value='', description='Filter alerts by title:', style=DescriptionStyle(description_width=…" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stderr", "output_type": "stream", "text": [ "C:\\Users\\Ian\\AppData\\Local\\Temp\\ipykernel_43852\\315947405.py:6: DeprecationWarning: Call to deprecated class SecurityAlert. (Replaced by Alert entity in datamodel) -- Deprecated since version 1.7.0.\n", " return HTML(SecurityAlert(alert).to_html(show_entities=True))\n" ] }, { "data": { "text/html": [ "\n", "

Alert: 'Suspicious Account Creation Detected'

\n", " Alert_time: 2019-01-15 09:15:03,\n", " Compr_entity: MSTICALERTSWIN1,\n", " Alert_id: self.properties['SystemAlertId']\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
45
Unnamed: 045
TenantId802d39e1-9d70-404d-832c-2de5e2478eda
StartTimeUtc2019-01-15 09:15:03
EndTimeUtc2019-01-15 09:15:03
ProviderAlertId526e34b6-6578-4fc0-9db6-e126b4d673f0
SystemAlertId2518547570966661760_526e34b6-6578-4fc0-9db6-e126b4d673f0
ProviderNameDetection
VendorNameMicrosoft
AlertTypeSuspicious Account Creation Detected
AlertNameSuspicious Account Creation Detected
AlertDisplayNameSuspicious Account Creation Detected
DescriptionAnalysis of host data on MSTICALERTSWIN1 detected creation or use of a local account adm1nistrator : this account name closely resembles a standard Windows account or group name 'administrator'. This is potentially a rogue account created by an attacker, so named in order to avoid being noticed by a human administrator.
SeverityMedium
IsIncidentFalse
ExtendedProperties{'Compromised Host': 'MSTICALERTSWIN1', 'User Name': 'adm1nistrator', 'Account Session Id': '0x0', 'Suspicious Process': 'c:\\windows\\system32\\net.exe', 'Suspicious Command Line': 'net user adm1nistrator bob_testing /add', 'Parent Process': 'c:\\windows\\system32\\cmd.exe', 'Suspicious Process Id': '0x141c', 'Suspicious Account Name': 'adm1nistrator', 'Similar To Account Name': 'administrator', 'resourceType': 'Virtual Machine', 'ServiceId': '14fa08c7-c48e-4c18-950c-8148024b4398', 'ReportingSystem': 'Azure', 'OccuringDatacenter': 'eastus'}
Entities[{'$id': '4', 'DnsDomain': '', 'NTDomain': '', 'HostName': 'MSTICALERTSWIN1', 'NetBiosName': 'MSTICALERTSWIN1', 'OSFamily': 'Windows', 'OSVersion': 'Windows', 'IsDomainJoined': False, 'Type': 'host'}, {'$id': '5', 'Name': 'adm1nistrator', 'Host': {'$ref': '4'}, 'Type': 'account', 'LogonId': '0x0'}, {'$id': '6', 'Directory': 'c:\\windows\\system32', 'Name': 'cmd.exe', 'Type': 'file'}, {'$id': '7', 'ProcessId': '0x165c', 'CommandLine': '', 'ImageFile': {'$ref': '6'}, 'Host': {'$ref': '4'}, 'Type': 'process'}, {'$id': '8', 'Name': 'MSTICAdmin', 'NTDomain': 'MSTICAlertsWin1', 'Sid': 'S-1-5-21-996632719-2361334927-4038480536-500', 'IsDomainJoined': False, 'Type': 'account', 'LogonId': '0x13bded7'}, {'$id': '9', 'Directory': 'c:\\windows\\system32', 'Name': 'net.exe', 'Type': 'file'}, {'$id': '10', 'ProcessId': '0x141c', 'CommandLine': 'net user adm1nistrator bob_testing /add', 'ElevationToken': 'Default', 'CreationTimeUtc': '2019-01-15T09:15:03.3338239Z', 'ImageFile': {'$ref': '9'}, 'Account': {'$ref': '8'}, 'ParentProcess': {'$ref': '7'}, 'Host': {'$ref': '4'}, 'Type': 'process'}, {'$id': '11', 'SessionId': '0x0', 'StartTimeUtc': '2019-01-15T09:15:03.3338239Z', 'EndTimeUtc': '2019-01-15T09:15:03.3338239Z', 'Type': 'host-logon-session', 'Host': {'$ref': '4'}, 'Account': {'$ref': '5'}}]
ConfidenceLevelUnknown
ConfidenceScoreNaN
ExtendedLinksNaN
WorkspaceSubscriptionId3c1bb38c-82e3-4f8d-a115-a7110ba70d05
WorkspaceResourceGroupcontoso77
TimeGenerated2019-01-15 09:15:08
ResourceId/subscriptions/40dcc8bf-0478-4f3b-b275-ed0a94f2c013/resourceGroups/ASIHuntOMSWorkspaceRG/providers/Microsoft.Compute/virtualMachines/MSTICAlertsWin1
SourceComputerId46fe7078-61bb-4bed-9430-7ac01d91c273
CompromisedEntityMSTICALERTSWIN1

ExtendedProperties:

\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
0
Compromised HostMSTICALERTSWIN1
User Nameadm1nistrator
Account Session Id0x0
Suspicious Processc:\\windows\\system32\\net.exe
Suspicious Command Linenet user adm1nistrator bob_testing /add
Parent Processc:\\windows\\system32\\cmd.exe
Suspicious Process Id0x141c
Suspicious Account Nameadm1nistrator
Similar To Account Nameadministrator
resourceTypeVirtual Machine
ServiceId14fa08c7-c48e-4c18-950c-8148024b4398
ReportingSystemAzure
OccuringDatacentereastus

Entities:


{ 'HostName': 'MSTICALERTSWIN1',, 'NetBiosName': 'MSTICALERTSWIN1',, 'OSFamily': <OSFamily.Windows: 1>,, 'TimeGenerated': datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),, 'Type': 'host'}
{ 'Host': { 'HostName': 'MSTICALERTSWIN1',, 'NetBiosName': 'MSTICALERTSWIN1',, 'OSFamily': <OSFamily.Windows: 1>,, 'TimeGenerated': datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),, 'Type': 'host'},, 'LogonId': '0x0',, 'Name': 'adm1nistrator',, 'TimeGenerated': datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),, 'Type': 'account'}
{ 'Directory': 'c:\\\\windows\\\\system32',, 'FullPath': 'c:\\\\windows\\\\system32\\\\cmd.exe',, 'Name': 'cmd.exe',, 'OSFamily': <OSFamily.Windows: 1>,, 'PathSeparator': '\\\\',, 'TimeGenerated': datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),, 'Type': 'file'}
{ 'CreationTimeUtc': datetime.datetime(1, 1, 1, 0, 0),, 'Host': { 'HostName': 'MSTICALERTSWIN1',, 'NetBiosName': 'MSTICALERTSWIN1',, 'OSFamily': <OSFamily.Windows: 1>,, 'TimeGenerated': datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),, 'Type': 'host'},, 'ImageFile': { 'Directory': 'c:\\\\windows\\\\system32',, 'FullPath': 'c:\\\\windows\\\\system32\\\\cmd.exe',, 'Name': 'cmd.exe',, 'OSFamily': <OSFamily.Windows: 1>,, 'PathSeparator': '\\\\',, 'TimeGenerated': datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),, 'Type': 'file'},, 'ProcessId': '0x165c',, 'TimeGenerated': datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),, 'Type': 'process'}
{ 'LogonId': '0x13bded7',, 'NTDomain': 'MSTICAlertsWin1',, 'Name': 'MSTICAdmin',, 'Sid': 'S-1-5-21-996632719-2361334927-4038480536-500',, 'TimeGenerated': datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),, 'Type': 'account'}
{ 'Directory': 'c:\\\\windows\\\\system32',, 'FullPath': 'c:\\\\windows\\\\system32\\\\net.exe',, 'Name': 'net.exe',, 'OSFamily': <OSFamily.Windows: 1>,, 'PathSeparator': '\\\\',, 'TimeGenerated': datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),, 'Type': 'file'}
{ 'Account': { 'LogonId': '0x13bded7',, 'NTDomain': 'MSTICAlertsWin1',, 'Name': 'MSTICAdmin',, 'Sid': 'S-1-5-21-996632719-2361334927-4038480536-500',, 'TimeGenerated': datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),, 'Type': 'account'},, 'CommandLine': 'net user adm1nistrator bob_testing /add',, 'CreationTimeUtc': '2019-01-15T09:15:03.3338239Z',, 'ElevationToken': 'Default',, 'Host': { 'HostName': 'MSTICALERTSWIN1',, 'NetBiosName': 'MSTICALERTSWIN1',, 'OSFamily': <OSFamily.Windows: 1>,, 'TimeGenerated': datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),, 'Type': 'host'},, 'ImageFile': { 'Directory': 'c:\\\\windows\\\\system32',, 'FullPath': 'c:\\\\windows\\\\system32\\\\net.exe',, 'Name': 'net.exe',, 'OSFamily': <OSFamily.Windows: 1>,, 'PathSeparator': '\\\\',, 'TimeGenerated': datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),, 'Type': 'file'},, 'ParentProcess': { 'CreationTimeUtc': datetime.datetime(1, 1, 1, 0, 0),, 'Host': { 'HostName': 'MSTICALERTSWIN1',, 'NetBiosName': 'MSTICALERTSWIN1',, 'OSFamily': <OSFamily.Windows: 1>,, 'TimeGenerated': datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),, 'Type': 'host'},, 'ImageFile': { 'Directory': 'c:\\\\windows\\\\system32',, 'FullPath': 'c:\\\\windows\\\\system32\\\\cmd.exe',, 'Name': 'cmd.exe',, 'OSFamily': <OSFamily.Windows: 1>,, 'PathSeparator': '\\\\',, 'TimeGenerated': datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),, 'Type': 'file'},, 'ProcessId': '0x165c',, 'TimeGenerated': datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),, 'Type': 'process'},, 'ProcessId': '0x141c',, 'TimeGenerated': datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),, 'Type': 'process'}
{ 'Account': { 'Host': { 'HostName': 'MSTICALERTSWIN1',, 'NetBiosName': 'MSTICALERTSWIN1',, 'OSFamily': <OSFamily.Windows: 1>,, 'TimeGenerated': datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),, 'Type': 'host'},, 'LogonId': '0x0',, 'Name': 'adm1nistrator',, 'TimeGenerated': datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),, 'Type': 'account'},, 'EndTimeUtc': '2019-01-15T09:15:03.3338239Z',, 'Host': { 'HostName': 'MSTICALERTSWIN1',, 'NetBiosName': 'MSTICALERTSWIN1',, 'OSFamily': <OSFamily.Windows: 1>,, 'TimeGenerated': datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),, 'Type': 'host'},, 'SessionId': '0x0',, 'StartTimeUtc': '2019-01-15T09:15:03.3338239Z',, 'TimeGenerated': datetime.datetime(2022, 3, 15, 20, 30, 12, 568223),, 'Type': 'host-logon-session'}" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "from IPython.display import HTML\n", "security_alert = None\n", "\n", "# create a function to get the displayable object\n", "def alert_with_entities(alert):\n", " return HTML(SecurityAlert(alert).to_html(show_entities=True))\n", " \n", "alert_select = nbwidgets.SelectAlert(alerts=alerts.query('CompromisedEntity == \"MSTICALERTSWIN1\"'), \n", " action=alert_with_entities)\n", "display(Markdown('### Or a more detailed display with extracted entities'))\n", "alert_select" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[Contents](#contents)\n", "## SelectItem\n", "\n", "Similar to AlertSelector but simpler and allows you to use any list or dictionary of items.\n", "\n", "```\n", "Selection list from list or dict.\n", "\n", "Attributes:\n", " value : The selected value.\n", "Init docstring:\n", "Select an item from a list or dict.\n", "\n", "Parameters\n", "----------\n", "description : str, optional\n", " The widget label to display (the default is None)\n", "item_list : List[str], optional\n", " A `list` of items to select from (the default is None)\n", "item_dict : Mapping[str, str], optional\n", " A `dict` of items to select from. When using `item_dict`\n", " the keys are displayed as the selectable items and value\n", " corresponding to the selected key is set as the `value`\n", " property.\n", " (the default is None)\n", "action : Callable[..., None], optional\n", " function to call when item selected (passed a single\n", " parameter - the value of the currently selected item)\n", " (the default is None)\n", "auto_display : bool, optional\n", " Whether to display on instantiation (the default is False)\n", "height : str, optional\n", " Selection list height (the default is '100px')\n", "width : str, optional\n", " Selection list width (the default is '50%')\n", "```" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "ExecuteTime": { "end_time": "2019-12-19T22:40:00.225872Z", "start_time": "2019-12-19T22:40:00.198893Z" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "C:\\Users\\Ian\\AppData\\Local\\Temp\\ipykernel_43852\\2926117687.py:2: DeprecationWarning: Call to deprecated class SecurityAlert. (Replaced by Alert entity in datamodel) -- Deprecated since version 1.7.0.\n", " security_alert = SecurityAlert(alert_select.selected_alert)\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "57a8e800d29e4a709ba2d9daaf8d1deb", "version_major": 2, "version_minor": 0 }, "text/plain": [ "VBox(children=(Text(value='host', description='Filter:', style=DescriptionStyle(description_width='initial')),…" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "

host

{ 'HostName': 'MSTICALERTSWIN1',
  'NetBiosName': 'MSTICALERTSWIN1',
  'OSFamily': ,
  'TimeGenerated': datetime.datetime(2022, 3, 15, 20, 30, 12, 642220),
  'Type': 'host'}" ], "text/plain": [ "Host(HostName=MSTICALERTSWIN1, NetBiosName=MSTICALERTSWIN1, OSFamily=OSFamily.Windows...)" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# extract the entities from the previously selected alert\n", "security_alert = SecurityAlert(alert_select.selected_alert)\n", "if security_alert is None:\n", " security_alert = SecurityAlert(alerts.iloc[1])\n", "ent_dict = {ent['Type']:ent for ent in security_alert.entities}\n", "\n", "# from IPython.display import HTML\n", "\n", "# # create a display function for the entities\n", "# def entity_to_html(entity):\n", "# e_text = str(entity)\n", "# e_type = entity.Type\n", "# e_text = e_text.replace(\"\\n\", \"
\").replace(\" \", \" \")\n", "# return HTML(f\"

{e_type}

{e_text}\")\n", " \n", "nbwidgets.SelectItem(item_dict=ent_dict,\n", " description='Select an item',\n", " action=lambda x: x,\n", " auto_display=True);\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[Contents](#contents)\n", "## GetEnvironmentKey\n", "Get editable value of environment variable. Common use would be retrieving an API key from your environment or allowing you to paste in a value if the environment key isn't set.\n", "\n", "Note setting the variable only persists in the python kernel process running at the time. So you can retrieve it later in the notebook but not in other processes." ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "ExecuteTime": { "end_time": "2019-12-19T22:43:18.702480Z", "start_time": "2019-12-19T22:43:18.680497Z" }, "scrolled": true }, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "76bbbae36b054f0297a29ee8c26a696a", "version_major": 2, "version_minor": 0 }, "text/plain": [ "HBox(children=(Text(value='C:\\\\Users\\\\Ian', description='Enter the value: ', layout=Layout(width='50%'), style…" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "nbwidgets.GetEnvironmentKey(env_var='userprofile', auto_display=True);" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[Contents](#contents)\n", "## SelectSubset\n", "Allows you to select one or multiple items from a list to populate an output set.\n", "\n", "```\n", "Class to select a subset from an input list.\n", "\n", " Attributes\n", " ----------\n", " selected_values : List[Any]\n", " The selected item values.\n", " selected_items : List[Any]\n", " The selected items label and value\n", " \n", "Init docstring:\n", "Create instance of SelectSubset widget.\n", "\n", "Parameters\n", "----------\n", "source_items : Union[Dict[str, str], List[Any]]\n", " List of source items - either a dictionary(label, value),\n", " a simple list or\n", " a list of (label, value) tuples.\n", "default_selected : Union[Dict[str, str], List[Any]]\n", " Populate the selected list with values - either\n", " a dictionary(label, value),\n", " a simple list or\n", " a list of (label, value) tuples.\n", "```" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "ExecuteTime": { "end_time": "2019-12-19T22:52:10.297759Z", "start_time": "2019-12-19T22:52:10.252790Z" } }, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "c5c37e8b5d75487bad599809008f4583", "version_major": 2, "version_minor": 0 }, "text/plain": [ "VBox(children=(Text(value='', description='Filter:', style=DescriptionStyle(description_width='initial')), HBo…" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Simple list\n", "items = list(alerts[\"AlertName\"].values)\n", "sel_sub = nbwidgets.SelectSubset(source_items=items)" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "ExecuteTime": { "end_time": "2019-12-19T22:52:37.922930Z", "start_time": "2019-12-19T22:52:37.880962Z" }, "scrolled": true }, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "24055d94f2b3478491c0ef06ef80f2ec", "version_major": 2, "version_minor": 0 }, "text/plain": [ "VBox(children=(Text(value='', description='Filter:', style=DescriptionStyle(description_width='initial')), HBo…" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Label/Value pair items with a a subset of pre-selected items\n", "items = {v: k for k, v in alerts[\"AlertName\"].to_dict().items()}\n", "pre_selected = {v: k for k, v in alerts[\"AlertName\"].to_dict().items() if \"commandline\" in v}\n", "sel_sub = nbwidgets.SelectSubset(source_items=items, default_selected=pre_selected)\n" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "ExecuteTime": { "end_time": "2019-09-02T23:54:08.581230Z", "start_time": "2019-09-02T23:54:08.577235Z" }, "scrolled": true, "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Values: [79, 109, 83] \n", "\n", "Items: [('Detected suspicious commandline arguments', 79), ('Detected suspicious commandline used to start all executables in a directory', 109), ('Detected suspicious credentials in commandline', 83)]\n" ] } ], "source": [ "print(\"Values:\", sel_sub.selected_values, \"\\n\")\n", "print(\"Items:\", sel_sub.selected_items)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Progress Indicator" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "ExecuteTime": { "end_time": "2019-12-19T23:04:17.717178Z", "start_time": "2019-12-19T23:04:14.399755Z" }, "tags": [] }, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "806a520c945d4f1884efa8cdb37af174", "version_major": 2, "version_minor": 0 }, "text/plain": [ "HBox(children=(IntProgress(value=0, bar_style='info', description='Progress:', layout=Layout(visibility='visib…" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "a182ee6d8e0c49b6a0df5f72181810f4", "version_major": 2, "version_minor": 0 }, "text/plain": [ "HBox(children=(IntProgress(value=0, bar_style='info', description='Progress:', layout=Layout(visibility='visib…" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "Volume goes to eleven!\n" ] } ], "source": [ "from time import sleep\n", "progress = nbwidgets.Progress(completed_len=2000)\n", "for i in range(0, 2100, 100):\n", " progress.update_progress(new_total=i)\n", " sleep(0.1)\n", " \n", "inc_progress = nbwidgets.Progress(completed_len=10)\n", "for i in range(0, 11):\n", " inc_progress.update_progress(delta=1)\n", " sleep(0.1)\n", "print(\"Volume goes to eleven!\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Logon Display\n", "Display logon details for a Windows or Linux logon" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "710b36a6e98e4fb78a6d231c9d92da7f", "version_major": 2, "version_minor": 0 }, "text/plain": [ "VBox(children=(Text(value='MSTICAlertsWin1/MSTICAdmin (2019-01-15 05:15:02.980)', description='Filter:', sty…" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "\n", " \n", "
Account: MSTICAdmin
Account Domain: MSTICAlertsWin1
Logon Time: 2019-01-15 05:15:02.980
Logon type: 4(Batch)
User Id/SID: S-1-5-21-996632719-2361334927-4038480536-500
  SID S-1-5-21-996632719-2361334927-4038480536-500 is administrator
  SID S-1-5-21-996632719-2361334927-4038480536-500 is local machine or domain account

Subject (source) account: WORKGROUP/MSTICAlertsWin1$
Logon process: Advapi
Authentication: Negotiate
Source IpAddress: -
Source Host: MSTICAlertsWin1
Logon status: nan
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "win_logons = pd.read_csv(\"data/host_logons.csv\")\n", "user_dict = win_logons.apply(lambda x: f\"{x.TargetDomainName}/{x.TargetUserName} ({x.TimeGenerated})\", axis=1).to_dict()\n", "user_dict = {v: k for k, v in user_dict.items()}\n", "\n", "from msticpy.vis.nbdisplay import format_logon\n", "# create a display function for the entities\n", "def disp_logon(index):\n", " print\n", " logons = win_logons[win_logons.index == index]\n", " return format_logon(logons)\n", " \n", "acct_select = nbwidgets.SelectItem(item_dict=user_dict,\n", " description='Select an item',\n", " action=disp_logon,\n", " auto_display=True);" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Display a list of logons" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", " \n", "
Account: MSTICAdmin
Account Domain: MSTICAlertsWin1
Logon Time: 2019-01-15 05:15:02.980
Logon type: 4(Batch)
User Id/SID: S-1-5-21-996632719-2361334927-4038480536-500
  SID S-1-5-21-996632719-2361334927-4038480536-500 is administrator
  SID S-1-5-21-996632719-2361334927-4038480536-500 is local machine or domain account

Subject (source) account: WORKGROUP/MSTICAlertsWin1$
Logon process: Advapi
Authentication: Negotiate
Source IpAddress: -
Source Host: MSTICAlertsWin1
Logon status: nan
Account: SYSTEM
Account Domain: NT AUTHORITY
Logon Time: 2019-01-15 05:15:04.503
Logon type: 5(Service)
User Id/SID: S-1-5-18
  SID S-1-5-18 is LOCAL_SYSTEM

Subject (source) account: WORKGROUP/MSTICAlertsWin1$
Logon process: Advapi
Authentication: Negotiate
Source IpAddress: -
Source Host: -
Logon status: nan
Account: adm1nistrator
Account Domain: MSTICAlertsWin1
Logon Time: 2019-01-15 05:15:06.363
Logon type: 3(Network)
User Id/SID: S-1-5-21-996632719-2361334927-4038480536-1066
  SID S-1-5-21-996632719-2361334927-4038480536-1066 is local machine or domain account

Subject (source) account: -/-
Logon process: NtLmSsp
Authentication: NTLM
Source IpAddress: fe80::38dc:e4a9:61bd:b458
Source Host: MSTICAlertsWin1
Logon status: nan
Account: SYSTEM
Account Domain: NT AUTHORITY
Logon Time: 2019-01-15 05:15:10.813
Logon type: 5(Service)
User Id/SID: S-1-5-18
  SID S-1-5-18 is LOCAL_SYSTEM

Subject (source) account: WORKGROUP/MSTICAlertsWin1$
Logon process: Advapi
Authentication: Negotiate
Source IpAddress: -
Source Host: -
Logon status: nan
Account: SYSTEM
Account Domain: NT AUTHORITY
Logon Time: 2019-01-15 05:15:14.453
Logon type: 5(Service)
User Id/SID: S-1-5-18
  SID S-1-5-18 is LOCAL_SYSTEM

Subject (source) account: WORKGROUP/MSTICAlertsWin1$
Logon process: Advapi
Authentication: Negotiate
Source IpAddress: -
Source Host: -
Logon status: nan
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# display a list of logons\n", "display(format_logon(win_logons.head(5)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Registered Widgets\n", "\n", "Some of the widgets (QueryTimes, GetText) can register themselves and retain\n", "the setting and values previously entered. This can be useful when stepping through\n", "a notebook since it is a common mistake to enter text in a text box and then\n", "execute the same cell again by mistake. This, of course, usually results in the \n", "widget being reset to its default state and erasing the values you just entered.\n", "\n", "If you use a registered widget and then create a new copy of the widget with identical\n", "parameters it will look in the registry for a previous copy of itself and auto-populate\n", "it's values with the previous-entered ones.\n", "\n", "Registered widgets can also read their default values from notebook variables - this\n", "is mainly useful with notebooks that are programmatically supplied with \n", "parameters and executed with something like Papermill.\n", "\n", "Several of the additional parameters available in RegisteredWidgets init are\n", "for internal use by widgets but three are usable by users:\n", "```\n", " Parameters\n", " ----------\n", " nb_params : Optional[Dict[str, str]], optional\n", " A dictionary of attribute names and global variables. If the variable\n", " exists in the global namespace it will be used to populate the\n", " corresponding widget attribute. This is only done if the widget\n", " attribute currently has no value (i.e. restoring a value from\n", " the registry takes priority over this),\n", " by default None\n", " ns : Dict[str, Any], optional\n", " Namespace to look for global variables, by default None\n", " register : bool\n", " Do not register the widget or retrieve values from previously-\n", " registered instance.\n", "```" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", " Initialize a registered widget.\n", "\n", " Parameters\n", " ----------\n", " id_vals : Optional[List[Any]], optional\n", " The list of parameter values to use to identify this widget instance,\n", " by default None\n", " val_attrs : Optional[List[str]], optional\n", " The names of the attributes to persist in the registry\n", " and recall, by default [\"value\"]\n", " nb_params : Optional[Dict[str, str]], optional\n", " A dictionary of attribute names and global variables. If the variable\n", " exists in the global namespace it will be used to populate the\n", " corresponding widget attribute. This is only done if the widget\n", " attribute currently has no value (i.e. restoring a value from\n", " the registry takes priority over this),\n", " by default None\n", " name_space : Dict[str, Any], optional\n", " Namespace to look for global variables, by default None\n", " register : bool\n", " Do not register the widget or retrieve values from previously-\n", " registered instance.\n", "\n", " \n" ] } ], "source": [ "print(nbwidgets.RegisteredWidget.__init__.__doc__)" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "59b66341409d4a8f8f4c6a92567fbc16", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Text(value='Ian', description='Enter your name', layout=Layout(width='50%'), style=DescriptionStyle(descriptio…" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "mem_text = nbwidgets.GetText(prompt=\"Enter your name\")\n", "\n", "# we insert a value here to mimic typing something in the text box\n", "mem_text._value = \"Ian\"\n", "mem_text" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When we re-execute the cell or use the same widget with identical arguments\n", "the value is populated from the registry cache" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "cf26032317564441a5158d863fd6648e", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Text(value='Ian', description='Enter your name', layout=Layout(width='50%'), style=DescriptionStyle(descriptio…" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "mem_text = nbwidgets.GetText(prompt=\"Enter your name\")\n", "mem_text" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### QueryTime also supports registration" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "e240234b9bc740e6b5927ea7ed1e21db", "version_major": 2, "version_minor": 0 }, "text/plain": [ "VBox(children=(HTML(value='

Set query time boundaries

'), HBox(children=(DatePicker(value=datetime.date…" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "from datetime import datetime, timedelta\n", "q_times = nbwidgets.QueryTime(auto_display=True, max_before=12, max_after=2, units=\"day\")" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [], "source": [ "# mimic setting values in the control (these don't update the display)\n", "q_times.origin_time = datetime.utcnow() - timedelta(5)\n", "q_times.before = 3\n", "q_times.after = 5" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note the origin, before and after have all been copied from the previous instance" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "48db5e7718c74097a23748e09309be38", "version_major": 2, "version_minor": 0 }, "text/plain": [ "VBox(children=(HTML(value='

Set query time boundaries

'), HBox(children=(DatePicker(value=datetime.date…" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "q_times = nbwidgets.QueryTime(auto_display=True, max_before=12, max_after=2, units=\"day\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### To skip registration add the parameter `register=False`" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "8a710a5a6ec7496385d8a2877e677075", "version_major": 2, "version_minor": 0 }, "text/plain": [ "VBox(children=(HTML(value='

Set query time boundaries

'), HBox(children=(DatePicker(value=datetime.date…" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "q_times = nbwidgets.QueryTime(auto_display=True, max_before=12, max_after=2, units=\"day\", register=False)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Using notebook parameters to populate RegisteredWidgets" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "bdf6040a423e467d95813e5a398986cd", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Text(value='', description='enter your real name', layout=Layout(width='50%'), style=DescriptionStyle(descript…" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# This might be defined in a parameter cell at the beginning of the noteboook\n", "my_name = \"The other Ian\"\n", "\n", "my_text = nbwidgets.GetText(prompt=\"enter your real name\", nb_params={\"_value\": \"my_name\"}, ns=globals())\n", "my_text" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Multi-Option buttons with async wait\n", "This widget is pretty simple on the surface but has some useful features\n", "for waiting for user input.\n" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "e5223807b7b64fb6a6b38a89bacd8543", "version_major": 2, "version_minor": 0 }, "text/plain": [ "VBox(children=(Label(value='Do you really want to do this?'), HBox(children=(Button(description='Confirm', sty…" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "opt = nbwidgets.OptionButtons(\n", " description=\"Do you really want to do this?\",\n", " buttons=[\"Confirm\", \"Skip\", \"Cancel\"]\n", ")\n", "\n", "# Displaying the widget works as expected\n", "# and sets `widget.value` to the last chosen button value.\n", "opt" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Using OptionButtons to wait until an option is chosen (or timeout expires)\n", "Option buttons uses an asynchronous event loop to track both the button\n", "state and the timeout simultaneously.\n", "\n", "Because this requires the use of asynchronous code you must do the following\n", "- call *widget*`.display_async()` method rather than just `display()` or using the auto-display functionality of Jupyter\n", "- prefix this call with `await` - this tells IPython/Jupyter that you are executing asynchronous code and that it needs\n", " to wait until this call has completed before continuing with cell execution. " ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "2366fca93e2b4945bb9dad251deade1b", "version_major": 2, "version_minor": 0 }, "text/plain": [ "VBox(children=(Label(value='Continue?'), HBox(children=(Button(description='Yes', style=ButtonStyle()), Button…" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "# Using display_async will run the widget with a visible\n", "# timer. As soon as one option is chosen, that remains as the value\n", "# of the value of the widget.value property.\n", "opt = nbwidgets.OptionButtons(description=\"Continue?\", timeout=10)\n", "await opt.display_async()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "> **Note**\n", "> Awaiting the OptionButtons control does not pause the notebook execution.\n", "> This is a capability that we are still working on." ] } ], "metadata": { "hide_input": false, "interpreter": { "hash": "2bc37074a50de3994d4ebdf9197e864a43c9c15c9793b7f9f3363bcff9457253" }, "kernelspec": { "display_name": "Python (msticpy)", "language": "python", "name": "msticpy" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.7" }, "latex_envs": { "LaTeX_envs_menu_present": true, "autoclose": false, "autocomplete": true, "bibliofile": "biblio.bib", "cite_by": "apalike", "current_citInitial": 1, "eqLabelWithNumbers": true, "eqNumInitial": 1, "hotkeys": { "equation": "Ctrl-E", "itemize": "Ctrl-I" }, "labels_anchors": false, "latex_user_defs": false, "report_style_numbering": false, "user_envs_cfg": false }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": false, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": {}, "toc_section_display": true, "toc_window_display": false }, "varInspector": { "cols": { "lenName": 16, "lenType": 16, "lenVar": 40 }, "kernels_config": { "python": { "delete_cmd_postfix": "", "delete_cmd_prefix": "del ", "library": "var_list.py", "varRefreshCmd": "print(var_dic_list())" }, "r": { "delete_cmd_postfix": ") ", "delete_cmd_prefix": "rm(", "library": "var_list.r", "varRefreshCmd": "cat(var_dic_list()) " } }, "types_to_exclude": [ "module", "function", "builtin_function_or_method", "instance", "_Feature" ], "window_display": false }, "widgets": { "application/vnd.jupyter.widget-state+json": { "state": {}, "version_major": 2, "version_minor": 0 } } }, "nbformat": 4, "nbformat_minor": 4 }