{ "cells": [ { "cell_type": "markdown", "source": [ "# Hands on - Surfing Your Data using Azure SDK for Python\n", "\n", "__Notebook Version:__ 1.0
\n", "__Python Version:__ Python 3.8 - AzureML
\n", "__Required Packages:__ No
\n", "__Platforms Supported:__ Azure Machine Learning Notebooks\n", " \n", "__Data Source Required:__ Log Analytics tables \n", " \n", "### Description\n", "This notebook will provide step-by-step instructions and sample code to guide you through Azure authentication, Microsoft Sentinel log data discovery by using Azure SDK for Python and Kusto Query Language (KQL).
\n", "*** No need to download and install any other Python modules. ***
\n", "*** Please run the cells sequentially to avoid errors. ***
\n", "Need to know more about KQL? [Getting started with Kusto Query Language](https://docs.microsoft.com/azure/data-explorer/kusto/concepts/).\n", "\n", "## Table of Contents\n", "1. Warm-up\n", "2. Azure Authentication\n", "3. Log Analytics Data Queries" ], "metadata": { "nteract": { "transient": { "deleting": false } } } }, { "cell_type": "markdown", "source": [ "## 1. Warm-up" ], "metadata": { "nteract": { "transient": { "deleting": false } } } }, { "cell_type": "code", "source": [ "# If you need to know what Python modules are available, you may run this:\n", "# help(\"modules\")\n", "!pip install azure-monitor-query" ], "outputs": [], "execution_count": null, "metadata": { "collapsed": true, "gather": { "logged": 1605055050943 }, "jupyter": { "outputs_hidden": false, "source_hidden": false }, "nteract": { "transient": { "deleting": false } } } }, { "cell_type": "code", "source": [ "# Load Python libraries that will be used in this notebook\n", "from azure.identity import AzureCliCredential, DefaultAzureCredential\n", "from azure.monitor.query import LogsQueryClient, MetricsQueryClient, LogsQueryStatus\n", "from azure.mgmt.loganalytics import LogAnalyticsManagementClient\n", "\n", "from datetime import datetime, timezone\n", "from IPython.display import display, HTML, Markdown\n", "import pandas as pd\n", "import json\n", "import ipywidgets\n", "import matplotlib.pyplot as plt" ], "outputs": [], "execution_count": null, "metadata": { "collapsed": true, "gather": { "logged": 1632434958264 }, "jupyter": { "outputs_hidden": false, "source_hidden": false }, "nteract": { "transient": { "deleting": false } } } }, { "cell_type": "code", "source": [ "# Functions will be used in this notebook\n", "def read_config_values(file_path):\n", " \"This loads pre-generated parameters for Microsoft Sentinel Workspace\"\n", " with open(file_path) as json_file:\n", " if json_file:\n", " json_config = json.load(json_file)\n", " return (json_config[\"tenant_id\"],\n", " json_config[\"subscription_id\"],\n", " json_config[\"resource_group\"],\n", " json_config[\"workspace_id\"],\n", " json_config[\"workspace_name\"],\n", " json_config[\"user_alias\"],\n", " json_config[\"user_object_id\"])\n", " return None\n", "\n", "def has_valid_token():\n", " \"Check to see if there is a valid AAD token\"\n", " try:\n", " error = \"ERROR: Please run 'az login' to setup account.\"\n", " expired = \"ERROR: AADSTS70043: The refresh token has expired or is invalid\"\n", " validator = !az account get-access-token\n", " \n", " if any(expired in item for item in validator.get_list()):\n", " return '**The refresh token has expired.
Please continue your login process. Then:
1. If you plan to run multiple notebooks on the same compute instance today, you may restart the compute instance by clicking \"Compute\" on left menu, then select the instance, clicking \"Restart\";
2. Otherwise, you may just restart the kernel from top menu.
Finally, close and re-load the notebook, then re-run cells one by one from the top.**'\n", " elif any(error in item for item in validator.get_list()):\n", " return \"Please run 'az login' to setup account\"\n", " else:\n", " return None\n", " except:\n", " return \"Please login\"\n" ], "outputs": [], "execution_count": null, "metadata": { "collapsed": true, "gather": { "logged": 1632434960353 }, "jupyter": { "outputs_hidden": false, "source_hidden": false }, "nteract": { "transient": { "deleting": false } } } }, { "cell_type": "code", "source": [ "# Calling the above function to populate Microsoft Sentinel workspace parameters\n", "# The file, config.json, was generated by the system, however, you may modify the values, or manually set the variables\n", "tenant_id, subscription_id, resource_group, workspace_id, workspace_name, user_alias, user_object_id = read_config_values('config.json');" ], "outputs": [], "execution_count": null, "metadata": { "collapsed": true, "gather": { "logged": 1632434963736 }, "jupyter": { "outputs_hidden": false, "source_hidden": false }, "nteract": { "transient": { "deleting": false } } } }, { "cell_type": "markdown", "source": [ "## 2. Azure Authentication" ], "metadata": { "nteract": { "transient": { "deleting": false } } } }, { "cell_type": "code", "source": [ "# Azure CLI is used to get device code to login into Azure, you need to copy the code and open the DeviceLogin site.\n", "# You may add [--tenant $tenant_id] to the command\n", "if has_valid_token() != None:\n", " message = '**The refresh token has expired.
Please continue your login process. Then:
1. If you plan to run multiple notebooks on the same compute instance today, you may restart the compute instance by clicking \"Compute\" on left menu, then select the instance, clicking \"Restart\";
2. Otherwise, you may just restart the kernel from top menu.
Finally, close and re-load the notebook, then re-run cells one by one from the top.**'\n", " display(Markdown(message))\n", " !echo -e '\\e[42m'\n", " !az login --tenant $tenant_id --use-device-code\n", "\n", "# Initialzie Azure LogAnalyticsDataClient, which is used to access Microsoft Sentinel log data in Azure Log Analytics. \n", "# You may need to change resource_uri for various cloud environments.\n", "resource_uri = \"https://api.loganalytics.io\"\n", "la_client = LogAnalyticsManagementClient(AzureCliCredential(), subscription_id = subscription_id)\n", "credential = DefaultAzureCredential()\n", "la_data_client = LogsQueryClient(credential)" ], "outputs": [], "execution_count": null, "metadata": { "gather": { "logged": 1632434967398 } } }, { "cell_type": "markdown", "source": [ "## 3. Log Analytics Data Queries" ], "metadata": { "nteract": { "transient": { "deleting": false } } } }, { "cell_type": "code", "source": [ "# Get all tables available using Kusto query language. If you need to know more about KQL, please check out the link provided at the introductory section.\n", "start_time=datetime(2022, 1, 1, tzinfo=timezone.utc)\n", "end_time=datetime(2022, 12, 31, tzinfo=timezone.utc)\n", "all_tables_query = \"union withsource = SentinelTableName * | distinct SentinelTableName | sort by SentinelTableName asc\"\n", "tables_result = la_data_client.query_workspace(\n", " workspace_id=workspace_id,\n", " query=all_tables_query,\n", " timespan=(start_time, end_time))\n", "\n", "if tables_result.status == LogsQueryStatus.SUCCESS:\n", " df = pd.DataFrame(data=tables_result.tables[0].rows, columns=tables_result.tables[0].columns)\n", " table_list = list(df[\"SentinelTableName\"])\n", " table_dropdown = ipywidgets.Dropdown(options=table_list, description='Tables:')\n", " display(table_dropdown)" ], "outputs": [], "execution_count": null, "metadata": { "collapsed": true, "gather": { "logged": 1632434977640 }, "jupyter": { "outputs_hidden": false, "source_hidden": false }, "nteract": { "transient": { "deleting": false } } } }, { "cell_type": "code", "source": [ "# You may query the table based on your needs, here I use TimeGenerated column as an example, going back to 7 days, counting events per day\n", "# Then process the data and display the result\n", "# To look at the query, you may run: print(sample_query)\n", "columns_result = None\n", "column_list = None\n", "all_columns_query = \"{0} | getschema | project ColumnName | order by ColumnName asc\".format(table_dropdown.value)\n", "columns_result = la_data_client.query_workspace(\n", " workspace_id=workspace_id,\n", " query=all_columns_query,\n", " timespan=(start_time, end_time))\n", "\n", "if columns_result.status == LogsQueryStatus.SUCCESS:\n", " df = pd.DataFrame(data=columns_result.tables[0].rows, columns=columns_result.tables[0].columns)\n", " col_list = list(df[\"ColumnName\"])\n", " column_dropdown = ipywidgets.Dropdown(options=col_list, description='Columns:')\n", " display(column_dropdown)\n", "else:\n", " column_list= []" ], "outputs": [], "execution_count": null, "metadata": { "collapsed": true, "gather": { "logged": 1632434985789 }, "jupyter": { "outputs_hidden": false, "source_hidden": false }, "nteract": { "transient": { "deleting": false } } } } ], "metadata": { "celltoolbar": "Tags", "kernel_info": { "name": "python38-azureml" }, "kernelspec": { "name": "python38-azureml", "language": "python", "display_name": "Python 3.8 - AzureML" }, "language_info": { "name": "python", "version": "3.8.5", "mimetype": "text/x-python", "codemirror_mode": { "name": "ipython", "version": 3 }, "pygments_lexer": "ipython3", "nbconvert_exporter": "python", "file_extension": ".py" }, "microsoft": { "host": { "AzureML": { "notebookHasBeenCompleted": true } } }, "nteract": { "version": "nteract-front-end@1.0.0" } }, "nbformat": 4, "nbformat_minor": 0 }