Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Azure
GitHub Repository: Azure/Azure-Sentinel-Notebooks
Path: blob/master/tutorials-and-examples/example-notebooks/M365 Defender - hunting.ipynb
3253 views
Kernel: Python 3.7.6 64-bit ('base': conda)
# Microsoft Threat Protection advanced hunting notebook # Version 1.0 # Author: Maarten Goet, MVP & RD # http://www.maartengoet.org import json import pandas import urllib.request import urllib.parse # Your MTP environment tenantId = '00000000-0000-0000-0000-000000000000' # Replace with your Tenant ID appId = '000000000000000000-0000-000000000000' # Replace with your Application ID appSecret = '0000000000000000000000000000000000' # Replace with the Secret for your Application url = "https://login.windows.net/%s/oauth2/token" % (tenantId) resourceAppIdUri = 'https://api.security.microsoft.com' # Hello, MTP body = { 'resource' : resourceAppIdUri, 'client_id' : appId, 'client_secret' : appSecret, 'grant_type' : 'client_credentials' } data = urllib.parse.urlencode(body).encode("utf-8") req = urllib.request.Request(url, data) response = urllib.request.urlopen(req) jsonResponse = json.loads(response.read()) aadToken = jsonResponse["access_token"] # Access token for the next hour
# Specify your Advanced Hunting query (KQL) # Sample: get indicators of comprise for COVID-19 campaigns query = (''' let Covid19IoC = (externaldata(Covid19Indicators:string ) [@"https://raw.githubusercontent.com/Azure/Azure-Sentinel/master/Sample%20Data/Feeds/Microsoft.Covid19.Indicators.json"] with (format="multijson")); Covid19IoC | mv-expand(parse_json(Covid19Indicators)) | project Covid19Indicators = todynamic(Covid19Indicators) | evaluate bag_unpack(Covid19Indicators) | evaluate bag_unpack(AdditionalMetadata) | project FirstSeen, ThreatType, FileSha256=Indicator, FileMd5, FileSha1, ExternalId ''') # KQL # Need inspiration? Here's a MTP cheat sheet: # https://medium.com/threathunt/introducing-mtp-advance-hunting-cheat-sheet-1535862c5e84
url = "https://api.security.microsoft.com/api/advancedhunting/run" # Query the MTP Advanced Hunting API headers = { 'Content-Type' : 'application/json', 'Accept' : 'application/json', 'Authorization' : "Bearer " + aadToken } data = json.dumps({ 'Query' : query }).encode("utf-8") req = urllib.request.Request(url, data, headers) response = urllib.request.urlopen(req) jsonResponse = json.loads(response.read()) schema = jsonResponse["Schema"] results = jsonResponse["Results"] # JSON response will be loaded in variable called 'results'
from pandas.io.json import json_normalize json_normalize(results) # Convert JSON to a dataframe and display output