Merge pull request #3322 from socprime/apigeex_connector_function_app

ApigeeX Data Connector
This commit is contained in:
v-jayakal 2021-10-27 23:48:29 -07:00 коммит произвёл GitHub
Родитель a986e4ed41 88be7755d3
Коммит 2129b74c1c
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
12 изменённых файлов: 828 добавлений и 0 удалений

Просмотреть файл

@ -0,0 +1,162 @@
[
{
"RawData": "",
"payload_request_name_s": "organizations/test-project-12345/environments/eval",
"payload_request_environment_apiProxyType_s": "PROGRAMMABLE",
"payload_request_environment_deploymentType_s": "PROXY",
"payload_request_environment_description_s": "",
"payload_request_environment_displayName_s": "eval-test",
"payload_request_environment_name_s": "eval",
"payload_response__type_s": "type.googleapis.com/google.cloud.apigee.v1.Environment",
"payload_response_name_s": "eval",
"payload_response_displayName_s": "eval-test",
"payload_response_deploymentType_s": "PROXY",
"payload_response_apiProxyType_s": "PROGRAMMABLE",
"payload_status_code_d": "",
"payload_status_message_s": "",
"payload_request_reportTime_t": "",
"payload_requestMetadata_requestAttributes_time_t": "2021-10-26T07:55:35.414000",
"log_name_s": "projects/test-project-12345/logs/cloudaudit.googleapis.com%2Factivity",
"insert_id_s": "1mu6d7ye5gz28",
"severity_s": "NOTICE",
"timestamp_t": "2021-10-26T07:55:36.177000",
"resource_type_s": "audited_resource",
"resource_labels_method_s": "google.cloud.apigee.v1.EnvironmentService.UpdateEnvironment",
"resource_labels_service_s": "apigee.googleapis.com",
"resource_labels_project_id_s": "test-project-12345",
"payload__type_s": "type.googleapis.com/google.cloud.audit.AuditLog",
"payload_authenticationInfo_principalEmail_s": "sanitized@sanitized.com",
"payload_requestMetadata_callerIp_s": "10.10.10.10",
"payload_requestMetadata_callerSuppliedUserAgent_s": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36,gzip(gfe)",
"payload_requestMetadata_requestAttributes_time_s": "",
"payload_serviceName_s": "apigee.googleapis.com",
"payload_methodName_s": "google.cloud.apigee.v1.EnvironmentService.UpdateEnvironment",
"payload_authorizationInfo_s": "[\n {\n \"resource\": \"organizations/test-project-12345/environments/eval\",\n \"permission\": \"apigee.environments.update\",\n \"granted\": true,\n \"resourceAttributes\": {}\n }\n]",
"payload_resourceName_s": "organizations/test-project-12345/environments/eval",
"payload_request_instanceUid_g": "",
"payload_request_reportTime_s": "",
"payload_request_instance_s": "",
"payload_request__type_s": "type.googleapis.com/google.cloud.apigee.v1.UpdateEnvironmentRequest",
"payload_request_resources_s": ""
},
{
"RawData": "",
"payload_request_name_s": "",
"payload_request_environment_apiProxyType_s": "",
"payload_request_environment_deploymentType_s": "",
"payload_request_environment_description_s": "",
"payload_request_environment_displayName_s": "",
"payload_request_environment_name_s": "",
"payload_response__type_s": "",
"payload_response_name_s": "",
"payload_response_displayName_s": "",
"payload_response_deploymentType_s": "",
"payload_response_apiProxyType_s": "",
"payload_status_code_d": "",
"payload_status_message_s": "",
"payload_request_reportTime_t": "2021-10-26T07:55:47.529000",
"payload_requestMetadata_requestAttributes_time_t": "2021-10-26T07:55:47.548000",
"log_name_s": "projects/test-project-12345/logs/cloudaudit.googleapis.com%2Factivity",
"insert_id_s": "hrjlv7e5e616",
"severity_s": "NOTICE",
"timestamp_t": "2021-10-26T07:55:48.386000",
"resource_type_s": "audited_resource",
"resource_labels_method_s": "google.cloud.apigee.v1.RuntimeService.ReportInstanceStatus",
"resource_labels_service_s": "apigee.googleapis.com",
"resource_labels_project_id_s": "test-project-12345",
"payload__type_s": "type.googleapis.com/google.cloud.audit.AuditLog",
"payload_authenticationInfo_principalEmail_s": "sanitized@sanitized.com",
"payload_requestMetadata_callerIp_s": "gce-internal-ip",
"payload_requestMetadata_callerSuppliedUserAgent_s": "Go-http-client/1.1,gzip(gfe),gzip(gfe)",
"payload_requestMetadata_requestAttributes_time_s": "",
"payload_serviceName_s": "apigee.googleapis.com",
"payload_methodName_s": "google.cloud.apigee.v1.RuntimeService.ReportInstanceStatus",
"payload_authorizationInfo_s": "[\n {\n \"resource\": \"organizations/test-project-12345/instances/eval-instance\",\n \"permission\": \"apigee.instances.reportStatus\",\n \"granted\": true,\n \"resourceAttributes\": {}\n }\n]",
"payload_resourceName_s": "organizations/test-project-12345/instances/eval-instance",
"payload_request_instanceUid_g": "xxxxxxxxx-6e37-472d-8d48-ab2fabff3358",
"payload_request_reportTime_s": "",
"payload_request_instance_s": "organizations/test-project-12345/instances/eval-instance",
"payload_request__type_s": "type.googleapis.com/google.cloud.apigee.v1.ReportInstanceStatusRequest",
"payload_request_resources_s": ""
},
{
"RawData": "",
"payload_request_name_s": "",
"payload_request_environment_apiProxyType_s": "",
"payload_request_environment_deploymentType_s": "",
"payload_request_environment_description_s": "",
"payload_request_environment_displayName_s": "",
"payload_request_environment_name_s": "",
"payload_response__type_s": "",
"payload_response_name_s": "",
"payload_response_displayName_s": "",
"payload_response_deploymentType_s": "",
"payload_response_apiProxyType_s": "",
"payload_status_code_d": "",
"payload_status_message_s": "",
"payload_request_reportTime_t": "2021-10-26T07:55:47.633000",
"payload_requestMetadata_requestAttributes_time_t": "2021-10-26T07:55:47.639000",
"log_name_s": "projects/test-project-12345/logs/cloudaudit.googleapis.com%2Factivity",
"insert_id_s": "hrjlv7e5e61c",
"severity_s": "NOTICE",
"timestamp_t": "2021-10-26T07:55:48.386000",
"resource_type_s": "audited_resource",
"resource_labels_method_s": "google.cloud.apigee.v1.RuntimeService.ReportInstanceStatus",
"resource_labels_service_s": "apigee.googleapis.com",
"resource_labels_project_id_s": "test-project-12345",
"payload__type_s": "type.googleapis.com/google.cloud.audit.AuditLog",
"payload_authenticationInfo_principalEmail_s": "sanitized@sanitized.com",
"payload_requestMetadata_callerIp_s": "gce-internal-ip",
"payload_requestMetadata_callerSuppliedUserAgent_s": "Go-http-client/1.1,gzip(gfe),gzip(gfe)",
"payload_requestMetadata_requestAttributes_time_s": "",
"payload_serviceName_s": "apigee.googleapis.com",
"payload_methodName_s": "google.cloud.apigee.v1.RuntimeService.ReportInstanceStatus",
"payload_authorizationInfo_s": "[\n {\n \"resource\": \"organizations/test-project-12345/instances/eval-instance\",\n \"permission\": \"apigee.instances.reportStatus\",\n \"granted\": true,\n \"resourceAttributes\": {}\n }\n]",
"payload_resourceName_s": "organizations/test-project-12345/instances/eval-instance",
"payload_request_instanceUid_g": "xxxxxxxxx-6e37-472d-8d48-ab2fabff3358",
"payload_request_reportTime_s": "",
"payload_request_instance_s": "organizations/test-project-12345/instances/eval-instance",
"payload_request__type_s": "type.googleapis.com/google.cloud.apigee.v1.ReportInstanceStatusRequest",
"payload_request_resources_s": "[\n {\n \"totalReplicas\": 2,\n \"revisions\": [\n {\n \"replicas\": 2,\n \"revisionId\": \"2-26E371B5\"\n }\n ],\n \"resource\": \"organizations/test-project-12345/environments/eval/deployedConfig\",\n \"uid\": \"xxxxxxxxx-273f-4194-bc2a-7a3087d1f4c8\"\n }\n]"
},
{
"RawData": "",
"payload_request_name_s": "",
"payload_request_environment_apiProxyType_s": "",
"payload_request_environment_deploymentType_s": "",
"payload_request_environment_description_s": "",
"payload_request_environment_displayName_s": "",
"payload_request_environment_name_s": "",
"payload_response__type_s": "",
"payload_response_name_s": "",
"payload_response_displayName_s": "",
"payload_response_deploymentType_s": "",
"payload_response_apiProxyType_s": "",
"payload_status_code_d": "",
"payload_status_message_s": "",
"payload_request_reportTime_t": "2021-10-26T07:55:47.804000",
"payload_requestMetadata_requestAttributes_time_t": "2021-10-26T07:55:47.816000",
"log_name_s": "projects/test-project-12345/logs/cloudaudit.googleapis.com%2Factivity",
"insert_id_s": "1awjdz6e5eq3s",
"severity_s": "NOTICE",
"timestamp_t": "2021-10-26T07:55:48.642000",
"resource_type_s": "audited_resource",
"resource_labels_method_s": "google.cloud.apigee.v1.RuntimeService.ReportInstanceStatus",
"resource_labels_service_s": "apigee.googleapis.com",
"resource_labels_project_id_s": "test-project-12345",
"payload__type_s": "type.googleapis.com/google.cloud.audit.AuditLog",
"payload_authenticationInfo_principalEmail_s": "sanitized@sanitized.com",
"payload_requestMetadata_callerIp_s": "gce-internal-ip",
"payload_requestMetadata_callerSuppliedUserAgent_s": "Go-http-client/1.1,gzip(gfe),gzip(gfe)",
"payload_requestMetadata_requestAttributes_time_s": "",
"payload_serviceName_s": "apigee.googleapis.com",
"payload_methodName_s": "google.cloud.apigee.v1.RuntimeService.ReportInstanceStatus",
"payload_authorizationInfo_s": "[\n {\n \"resource\": \"organizations/test-project-12345/instances/eval-instance\",\n \"permission\": \"apigee.instances.reportStatus\",\n \"granted\": true,\n \"resourceAttributes\": {}\n }\n]",
"payload_resourceName_s": "organizations/test-project-12345/instances/eval-instance",
"payload_request_instanceUid_g": "xxxxxxxxx-6e37-472d-8d48-ab2fabff3358",
"payload_request_reportTime_s": "",
"payload_request_instance_s": "organizations/test-project-12345/instances/eval-instance",
"payload_request__type_s": "type.googleapis.com/google.cloud.apigee.v1.ReportInstanceStatusRequest",
"payload_request_resources_s": "[\n {\n \"totalReplicas\": 2,\n \"uid\": \"xxxxxxxxx-1248-433f-8109-06a8ce81a9fc\",\n \"resource\": \"organizations/test-project-12345/envgroups/eval-group\",\n \"revisions\": [\n {\n \"revisionId\": \"3\",\n \"replicas\": 2\n }\n ]\n }\n]"
}
]

Двоичные данные
Solutions/ApigeeX/Data Connectors/ApigeeXConn.zip Normal file

Двоичный файл не отображается.

Просмотреть файл

@ -0,0 +1,130 @@
{
"id": "ApigeeXDataConnector",
"title": "Google ApigeeX",
"publisher": "Google",
"descriptionMarkdown": "The [Google ApigeeX](https://cloud.google.com/apigee/docs) data connector provides the capability to ingest ApigeeX audit logs into Azure Sentinel using the GCP Logging API. Refer to [GCP Logging API documentation](https://cloud.google.com/logging/docs/reference/v2/rest) for more information.",
"additionalRequirementBanner": ">This data connector depends on a parser based on a Kusto Function to work as expected [**ApigeeX**](https://aka.ms/sentinel-ApigeeXDataConnector-parser) which is deployed with the Azure Sentinel Solution.",
"graphQueries": [
{
"metricName": "ApigeeX logs",
"legend": "ApigeeX_CL",
"baseQuery": "ApigeeX_CL"
}
],
"sampleQueries": [
{
"description" : "All ApigeeX logs",
"query": "ApigeeX_CL\n| sort by TimeGenerated desc"
}
],
"dataTypes": [
{
"name": "ApigeeX_CL",
"lastDataReceivedQuery": "ApigeeX_CL\n | summarize Time = max(TimeGenerated)\n | where isnotempty(Time)"
}
],
"connectivityCriterias": [
{
"type": "IsConnectedQuery",
"value": [
"ApigeeX_CL\n | summarize LastLogReceived = max(TimeGenerated)\n | project IsConnected = LastLogReceived > ago(1d)"
]
}
],
"availability": {
"status": 1,
"isPreview": true
},
"permissions": {
"resourceProvider": [
{
"provider": "Microsoft.OperationalInsights/workspaces",
"permissionsDisplayText": "read and write permissions on the workspace are required.",
"providerDisplayName": "Workspace",
"scope": "Workspace",
"requiredPermissions": {
"write": true,
"read": true,
"delete": true
}
},
{
"provider": "Microsoft.OperationalInsights/workspaces/sharedKeys",
"permissionsDisplayText": "read permissions to shared keys for the workspace are required. [See the documentation to learn more about workspace keys](https://docs.microsoft.com/azure/azure-monitor/platform/agent-windows#obtain-workspace-id-and-key).",
"providerDisplayName": "Keys",
"scope": "Workspace",
"requiredPermissions": {
"action": true
}
}
],
"customs": [
{
"name": "Microsoft.Web/sites permissions",
"description": "Read and write permissions to Azure Functions to create a Function App is required. [See the documentation to learn more about Azure Functions](https://docs.microsoft.com/azure/azure-functions/)."
},
{
"name": "GCP service account",
"description": "GCP service account with permissions to read logs is required for GCP Logging API. Also json file with service account key is required. See the documentation to learn more about [required permissions](https://cloud.google.com/iam/docs/audit-logging#audit_log_permissions), [creating service account](https://cloud.google.com/iam/docs/creating-managing-service-accounts) and [creating service account key](https://cloud.google.com/iam/docs/creating-managing-service-account-keys)."
}
]
},
"instructionSteps": [
{
"title": "",
"description": ">**NOTE:** This connector uses Azure Functions to connect to the GCP API to pull logs into Azure Sentinel. This might result in additional data ingestion costs. Check the [Azure Functions pricing page](https://azure.microsoft.com/pricing/details/functions/) for details."
},
{
"title": "",
"description": ">**(Optional Step)** Securely store workspace and API authorization key(s) or token(s) in Azure Key Vault. Azure Key Vault provides a secure mechanism to store and retrieve key values. [Follow these instructions](https://docs.microsoft.com/azure/app-service/app-service-key-vault-references) to use Azure Key Vault with an Azure Function App."
},
{
"title": "",
"description": ">**NOTE:** This data connector depends on a parser based on a Kusto Function to work as expected [**ApigeeX**](https://aka.ms/sentinel-ApigeeXDataConnector-parser) which is deployed with the Azure Sentinel Solution."
},
{
"title": "",
"description": "**STEP 1 - Configuring GCP and obtaining credentials**\n\n1. Make sure that Logging API is [enabled](https://cloud.google.com/apis/docs/getting-started#enabling_apis). \n\n2. [Create service account](https://cloud.google.com/iam/docs/creating-managing-service-accounts) with [required permissions](https://cloud.google.com/iam/docs/audit-logging#audit_log_permissions) and [get service account key json file](https://cloud.google.com/iam/docs/creating-managing-service-account-keys).\n\n3. Prepare GCP project ID where ApigeeX is located."
},
{
"title": "",
"description": "**STEP 2 - Choose ONE from the following two deployment options to deploy the connector and the associated Azure Function**\n\n>**IMPORTANT:** Before deploying the data connector, have the Workspace ID and Workspace Primary Key (can be copied from the following), as well as Azure Blob Storage connection string and container name, readily available.",
"instructions":[
{
"parameters": {
"fillWith": [
"WorkspaceId"
],
"label": "Workspace ID"
},
"type": "CopyableLabel"
},
{
"parameters": {
"fillWith": [
"PrimaryKey"
],
"label": "Primary Key"
},
"type": "CopyableLabel"
}
]
},
{
"title": "Option 1 - Azure Resource Manager (ARM) Template",
"description": "Use this method for automated deployment of the data connector using an ARM Template.\n\n1. Click the **Deploy to Azure** button below. \n\n\t[![Deploy To Azure](https://aka.ms/deploytoazurebutton)](https://aka.ms/sentinel-ApigeeXDataConnector-azuredeploy)\n2. Select the preferred **Subscription**, **Resource Group** and **Location**. \n3. Enter the **Google Cloud Platform Project Id**, **Google Cloud Platform Credentials File Content**, **Azure Sentinel Workspace Id**, **Azure Sentinel Shared Key**\n4. Mark the checkbox labeled **I agree to the terms and conditions stated above**.\n5. Click **Purchase** to deploy."
},
{
"title": "Option 2 - Manual Deployment of Azure Functions",
"description": "Use the following step-by-step instructions to deploy the data connector manually with Azure Functions (Deployment via Visual Studio Code)."
},
{
"title": "",
"description": "**1. Deploy a Function App**\n\n> **NOTE:** You will need to [prepare VS code](https://docs.microsoft.com/azure/azure-functions/create-first-function-vs-code-python) for Azure function development.\n\n1. Download the [Azure Function App](https://aka.ms/sentinel-ApigeeXDataConnector-functionapp) file. Extract archive to your local development computer.\n2. Start VS Code. Choose File in the main menu and select Open Folder.\n3. Select the top level folder from extracted files.\n4. Choose the Azure icon in the Activity bar, then in the **Azure: Functions** area, choose the **Deploy to function app** button.\nIf you aren't already signed in, choose the Azure icon in the Activity bar, then in the **Azure: Functions** area, choose **Sign in to Azure**\nIf you're already signed in, go to the next step.\n5. Provide the following information at the prompts:\n\n\ta. **Select folder:** Choose a folder from your workspace or browse to one that contains your function app.\n\n\tb. **Select Subscription:** Choose the subscription to use.\n\n\tc. Select **Create new Function App in Azure** (Don't choose the Advanced option)\n\n\td. **Enter a globally unique name for the function app:** Type a name that is valid in a URL path. The name you type is validated to make sure that it's unique in Azure Functions.\n\n\te. **Select a runtime:** Choose Python 3.8.\n\n\tf. Select a location for new resources. For better performance and lower costs choose the same [region](https://azure.microsoft.com/regions/) where Azure Sentinel is located.\n\n6. Deployment will begin. A notification is displayed after your function app is created and the deployment package is applied.\n7. Go to Azure Portal for the Function App configuration."
},
{
"title": "",
"description": "**2. Configure the Function App**\n\n1. In the Function App, select the Function App Name and select **Configuration**.\n2. In the **Application settings** tab, select **+ New application setting**.\n3. Add each of the following application settings individually, with their respective string values (case-sensitive): \n\t\tRESOURCE_NAMES\n\t\tCREDENTIALS_FILE_CONTENT\n\t\tWORKSPACE_ID\n\t\tSHARED_KEY\n\t\tlogAnalyticsUri (Optional)\n - Use logAnalyticsUri to override the log analytics API endpoint for dedicated cloud. For example, for public cloud, leave the value empty; for Azure GovUS cloud environment, specify the value in the following format: `https://WORKSPACE_ID.ods.opinsights.azure.us`. \n4. Once all application settings have been entered, click **Save**."
}
]
}

Просмотреть файл

@ -0,0 +1,12 @@
{
"scriptFile": "main.py",
"bindings": [
{
"name": "mytimer",
"type": "timerTrigger",
"direction": "in",
"schedule": "0 */5 * * * *",
"runOnStartup": false
}
]
}

Просмотреть файл

@ -0,0 +1,143 @@
import json
import os
from google.cloud.logging_v2 import Client
import datetime
import logging
import re
import time
import azure.functions as func
from dateutil.parser import parse as parse_date
from .sentinel_connector import AzureSentinelConnector
from .state_manager import StateManager
CREDENTIALS_FILE_CONTENT = os.environ['CREDENTIALS_FILE_CONTENT']
RESOURCE_NAMES = os.environ['RESOURCE_NAMES']
WORKSPACE_ID = os.environ['WORKSPACE_ID']
SHARED_KEY = os.environ['SHARED_KEY']
LOG_TYPE = 'ApigeeX'
# interval of script execution
SCRIPT_EXECUTION_INTERVAL_MINUTES = 5
# if ts of last processed file is older than "now - MAX_PERIOD_MINUTES" then script will get events from "now - MAX_PERIOD_MINUTES"
MAX_PERIOD_MINUTES = 60 * 24 * 7
MAX_SCRIPT_EXEC_TIME_MINUTES = 5
LOG_ANALYTICS_URI = os.environ.get('logAnalyticsUri')
if not LOG_ANALYTICS_URI or str(LOG_ANALYTICS_URI).isspace():
LOG_ANALYTICS_URI = 'https://' + WORKSPACE_ID + '.ods.opinsights.azure.com'
pattern = r'https:\/\/([\w\-]+)\.ods\.opinsights\.azure.([a-zA-Z\.]+)$'
match = re.match(pattern, str(LOG_ANALYTICS_URI))
if not match:
raise Exception("Invalid Log Analytics Uri.")
CREDS_FILE_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), '.creds')
logging.getLogger('azure.core.pipeline.policies.http_logging_policy').setLevel(logging.ERROR)
def main(mytimer: func.TimerRequest):
logging.info('Starting script')
start_ts = int(time.time())
create_credentials_file()
gcp_cli = Client(_use_grpc=False)
sentinel = AzureSentinelConnector(log_analytics_uri=LOG_ANALYTICS_URI, workspace_id=WORKSPACE_ID, shared_key=SHARED_KEY, log_type=LOG_TYPE, queue_size=3000)
state_manager = StateManager(os.environ['AzureWebJobsStorage'])
last_ts = get_last_ts(state_manager)
filt = """
resource.type="audited_resource" AND resource.labels.service="apigee.googleapis.com"
AND
timestamp>="{}"
""".format(last_ts)
last_ts = None
with sentinel:
for entry in gcp_cli.list_entries(resource_names=get_recource_names(), filter_=filt, order_by='timestamp', page_size=1000):
event = parse_entry(entry)
sentinel.send(event)
last_ts = event['timestamp']
if sentinel.is_empty():
logging.info('Saving last timestamp - {}'.format(last_ts))
state_manager.post(last_ts)
if check_if_script_runs_too_long(start_ts):
logging.info('Script is running too long. Saving progress and exit.')
break
if last_ts:
last_ts = event['timestamp']
logging.info('Saving last timestamp - {}'.format(last_ts))
state_manager.post(last_ts)
remove_credentials_file()
logging.info('Script finished. Sent events number: {}'.format(sentinel.successfull_sent_events_number))
def create_credentials_file():
with open(CREDS_FILE_PATH, 'w') as f:
content = CREDENTIALS_FILE_CONTENT.strip().replace('\n', '\\n')
f.write(content)
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = CREDS_FILE_PATH
def remove_credentials_file():
if os.path.exists(CREDS_FILE_PATH):
os.remove(CREDS_FILE_PATH)
def get_recource_names():
return [x for x in RESOURCE_NAMES.split(',') if x]
def parse_entry(entry):
event = entry._asdict()
if isinstance(event.get('timestamp'), datetime.datetime):
event['timestamp'] = event['timestamp'].isoformat()
if 'logger' in event:
del event['logger']
if event.get('resource'):
event['resource'] = event['resource']._asdict()
return event
def get_last_ts(state_manager: StateManager):
logging.info('Getting last timestamp')
last_ts = state_manager.get()
now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
if last_ts:
last_ts = parse_date(last_ts)
logging.info('Last timestamp - {}'.format(last_ts.isoformat()))
else:
last_ts = now - datetime.timedelta(minutes=SCRIPT_EXECUTION_INTERVAL_MINUTES)
logging.info('Last timestamp is not known')
diff_seconds = (now - last_ts).days * 86400 + (now - last_ts).seconds
if diff_seconds > MAX_PERIOD_MINUTES * 60:
old_last_ts = last_ts
last_ts = now - datetime.timedelta(minutes=MAX_PERIOD_MINUTES)
logging.info('Last timestamp {} is older than max search period ({} minutes). Getting data for max search period (from {})'.format(old_last_ts, MAX_PERIOD_MINUTES, last_ts))
else:
last_ts += datetime.timedelta(microseconds=1)
logging.info('Getting data from {}'.format(last_ts.isoformat()))
return last_ts.isoformat()
def check_if_script_runs_too_long(start_ts):
now = int(time.time())
duration = now - start_ts
max_duration = int(MAX_SCRIPT_EXEC_TIME_MINUTES * 60 * 0.85)
return duration > max_duration

Просмотреть файл

@ -0,0 +1,117 @@
import requests
import datetime
import logging
import json
import hashlib
import hmac
import base64
import time
class AzureSentinelConnector:
def __init__(self, log_analytics_uri, workspace_id, shared_key, log_type, queue_size=200, queue_size_bytes=25 * (2**20)):
self.log_analytics_uri = log_analytics_uri
self.workspace_id = workspace_id
self.shared_key = shared_key
self.log_type = log_type
self.queue_size = queue_size
self.bulks_number = 1
self.queue_size_bytes = queue_size_bytes
self._queue = []
self._bulks_list = []
self.successfull_sent_events_number = 0
def send(self, event):
self._queue.append(event)
if len(self._queue) >= self.queue_size:
self.flush(force=False)
def flush(self, force=True):
self._bulks_list.append(self._queue)
if force:
self._flush_bulks()
else:
if len(self._bulks_list) >= self.bulks_number:
self._flush_bulks()
self._queue = []
def _flush_bulks(self):
for queue in self._bulks_list:
if queue:
queue_list = self._split_big_request(queue)
for q in queue_list:
self._post_data(self.workspace_id, self.shared_key, q, self.log_type)
self._bulks_list = []
def is_empty(self):
return not self._queue and not self._bulks_list
def __enter__(self):
pass
def __exit__(self, type, value, traceback):
self.flush()
def _build_signature(self, workspace_id, shared_key, date, content_length, method, content_type, resource):
x_headers = 'x-ms-date:' + date
string_to_hash = method + "\n" + str(content_length) + "\n" + content_type + "\n" + x_headers + "\n" + resource
bytes_to_hash = bytes(string_to_hash, encoding="utf-8")
decoded_key = base64.b64decode(shared_key)
encoded_hash = base64.b64encode(hmac.new(decoded_key, bytes_to_hash, digestmod=hashlib.sha256).digest()).decode()
authorization = "SharedKey {}:{}".format(workspace_id, encoded_hash)
return authorization
def _post_data(self, workspace_id, shared_key, body, log_type):
events_number = len(body)
body = json.dumps(body)
method = 'POST'
content_type = 'application/json'
resource = '/api/logs'
rfc1123date = datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
content_length = len(body)
signature = self._build_signature(workspace_id, shared_key, rfc1123date, content_length, method, content_type, resource)
uri = self.log_analytics_uri + resource + '?api-version=2016-04-01'
headers = {
'content-type': content_type,
'Authorization': signature,
'Log-Type': log_type,
'x-ms-date': rfc1123date
}
try_number = 1
while True:
try:
self._make_request(uri, body, headers)
except Exception as err:
if try_number < 3:
logging.warning('Error while sending data to Azure Sentinel. Try number: {}. {}'.format(try_number, err))
time.sleep(try_number)
try_number += 1
else:
logging.error(str(err))
self.failed_sent_events_number += events_number
raise err
else:
logging.info('{} events have been successfully sent to Azure Sentinel'.format(events_number))
self.successfull_sent_events_number += events_number
break
def _make_request(self, uri, body, headers):
response = requests.post(uri, data=body, headers=headers)
if not (200 <= response.status_code <= 299):
raise Exception("Error during sending events to Azure Sentinel. Response code: {}".format(response.status_code))
def _check_size(self, queue):
data_bytes_len = len(json.dumps(queue).encode())
return data_bytes_len < self.queue_size_bytes
def _split_big_request(self, queue):
if self._check_size(queue):
return [queue]
else:
middle = int(len(queue) / 2)
queues_list = [queue[:middle], queue[middle:]]
return self._split_big_request(queues_list[0]) + self._split_big_request(queues_list[1])

Просмотреть файл

@ -0,0 +1,22 @@
from azure.storage.fileshare import ShareClient
from azure.storage.fileshare import ShareFileClient
from azure.core.exceptions import ResourceNotFoundError
class StateManager:
def __init__(self, connection_string, share_name='funcstatemarkershare', file_path='funcstatemarkerfile'):
self.share_cli = ShareClient.from_connection_string(conn_str=connection_string, share_name=share_name)
self.file_cli = ShareFileClient.from_connection_string(conn_str=connection_string, share_name=share_name, file_path=file_path)
def post(self, marker_text: str):
try:
self.file_cli.upload_file(marker_text)
except ResourceNotFoundError:
self.share_cli.create_share()
self.file_cli.upload_file(marker_text)
def get(self):
try:
return self.file_cli.download_file().readall().decode()
except ResourceNotFoundError:
return None

Просмотреть файл

@ -0,0 +1,206 @@
{
"$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"FunctionName": {
"defaultValue": "ApigeeX",
"type": "string",
"minLength": 1,
"maxLength": 11
},
"GoogleCloudPlatformProjectId": {
"type": "string",
"defaultValue": "projects/<PROJECT_ID>",
"metadata": {
"description": "GCP project where ApiggeX is deployed. For example: projects/PROJECT_ID"
}
},
"GoogleCloudPlatformCredentialsFileContent": {
"type": "securestring",
"defaultValue": "",
"metadata": {
"description": "Content of json file with credentials for service account that has permissions to read logs using Logging API"
}
},
"AzureSentinelWorkspaceId": {
"type": "string",
"defaultValue": ""
},
"AzureSentinelSharedKey": {
"type": "securestring",
"defaultValue": ""
}
},
"variables": {
"FunctionName": "[concat(toLower(parameters('FunctionName')), uniqueString(resourceGroup().id))]",
"StorageSuffix": "[environment().suffixes.storage]",
"LogAnaltyicsUri": "[replace(environment().portal, 'https://portal', concat('https://', toLower(parameters('AzureSentinelWorkspaceId')), '.ods.opinsights'))]"
},
"resources": [
{
"type": "Microsoft.Insights/components",
"apiVersion": "2015-05-01",
"name": "[variables('FunctionName')]",
"location": "[resourceGroup().location]",
"kind": "web",
"properties": {
"Application_Type": "web",
"ApplicationId": "[variables('FunctionName')]"
}
},
{
"type": "Microsoft.Storage/storageAccounts",
"apiVersion": "2019-06-01",
"name": "[tolower(variables('FunctionName'))]",
"location": "[resourceGroup().location]",
"sku": {
"name": "Standard_LRS",
"tier": "Standard"
},
"kind": "StorageV2",
"properties": {
"networkAcls": {
"bypass": "AzureServices",
"virtualNetworkRules": [],
"ipRules": [],
"defaultAction": "Allow"
},
"supportsHttpsTrafficOnly": true,
"encryption": {
"services": {
"file": {
"keyType": "Account",
"enabled": true
},
"blob": {
"keyType": "Account",
"enabled": true
}
},
"keySource": "Microsoft.Storage"
}
}
},
{
"type": "Microsoft.Storage/storageAccounts/blobServices",
"apiVersion": "2019-06-01",
"name": "[concat(variables('FunctionName'), '/default')]",
"dependsOn": [
"[resourceId('Microsoft.Storage/storageAccounts', tolower(variables('FunctionName')))]"
],
"sku": {
"name": "Standard_LRS",
"tier": "Standard"
},
"properties": {
"cors": {
"corsRules": []
},
"deleteRetentionPolicy": {
"enabled": false
}
}
},
{
"type": "Microsoft.Storage/storageAccounts/fileServices",
"apiVersion": "2019-06-01",
"name": "[concat(variables('FunctionName'), '/default')]",
"dependsOn": [
"[resourceId('Microsoft.Storage/storageAccounts', tolower(variables('FunctionName')))]"
],
"sku": {
"name": "Standard_LRS",
"tier": "Standard"
},
"properties": {
"cors": {
"corsRules": []
}
}
},
{
"type": "Microsoft.Web/sites",
"apiVersion": "2018-11-01",
"name": "[variables('FunctionName')]",
"location": "[resourceGroup().location]",
"dependsOn": [
"[resourceId('Microsoft.Storage/storageAccounts', tolower(variables('FunctionName')))]",
"[resourceId('Microsoft.Insights/components', variables('FunctionName'))]"
],
"kind": "functionapp,linux",
"identity": {
"type": "SystemAssigned"
},
"properties": {
"name": "[variables('FunctionName')]",
"httpsOnly": true,
"clientAffinityEnabled": true,
"alwaysOn": true,
"reserved": true,
"siteConfig": {
"linuxFxVersion": "python|3.8"
}
},
"resources": [
{
"apiVersion": "2018-11-01",
"type": "config",
"name": "appsettings",
"dependsOn": [
"[concat('Microsoft.Web/sites/', variables('FunctionName'))]"
],
"properties": {
"FUNCTIONS_EXTENSION_VERSION": "~3",
"FUNCTIONS_WORKER_RUNTIME": "python",
"APPINSIGHTS_INSTRUMENTATIONKEY": "[reference(resourceId('Microsoft.insights/components', variables('FunctionName')), '2015-05-01').InstrumentationKey]",
"APPLICATIONINSIGHTS_CONNECTION_STRING": "[reference(resourceId('microsoft.insights/components', variables('FunctionName')), '2015-05-01').ConnectionString]",
"AzureWebJobsStorage": "[concat('DefaultEndpointsProtocol=https;AccountName=', toLower(variables('FunctionName')),';AccountKey=',listKeys(resourceId('Microsoft.Storage/storageAccounts', toLower(variables('FunctionName'))), '2019-06-01').keys[0].value, ';EndpointSuffix=',toLower(variables('StorageSuffix')))]",
"RESOURCE_NAMES": "[parameters('GoogleCloudPlatformProjectId')]",
"CREDENTIALS_FILE_CONTENT": "[parameters('GoogleCloudPlatformCredentialsFileContent')]",
"WORKSPACE_ID": "[parameters('AzureSentinelWorkspaceId')]",
"SHARED_KEY": "[parameters('AzureSentinelSharedKey')]",
"logAnalyticsUri": "[variables('LogAnaltyicsUri')]",
"WEBSITE_RUN_FROM_PACKAGE": "https://aka.ms/sentinel-ApigeeXDataConnector-functionapp"
}
}
]
},
{
"type": "Microsoft.Storage/storageAccounts/blobServices/containers",
"apiVersion": "2019-06-01",
"name": "[concat(variables('FunctionName'), '/default/azure-webjobs-hosts')]",
"dependsOn": [
"[resourceId('Microsoft.Storage/storageAccounts/blobServices', variables('FunctionName'), 'default')]",
"[resourceId('Microsoft.Storage/storageAccounts', variables('FunctionName'))]"
],
"properties": {
"publicAccess": "None"
}
},
{
"type": "Microsoft.Storage/storageAccounts/blobServices/containers",
"apiVersion": "2019-06-01",
"name": "[concat(variables('FunctionName'), '/default/azure-webjobs-secrets')]",
"dependsOn": [
"[resourceId('Microsoft.Storage/storageAccounts/blobServices', variables('FunctionName'), 'default')]",
"[resourceId('Microsoft.Storage/storageAccounts', variables('FunctionName'))]"
],
"properties": {
"publicAccess": "None"
}
},
{
"type": "Microsoft.Storage/storageAccounts/fileServices/shares",
"apiVersion": "2019-06-01",
"name": "[concat(variables('FunctionName'), '/default/', tolower(variables('FunctionName')))]",
"dependsOn": [
"[resourceId('Microsoft.Storage/storageAccounts/fileServices', variables('FunctionName'), 'default')]",
"[resourceId('Microsoft.Storage/storageAccounts', variables('FunctionName'))]"
],
"properties": {
"shareQuota": 5120
}
}
]
}

Просмотреть файл

@ -0,0 +1,15 @@
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
}
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[1.*, 2.0.0)"
}
}

Просмотреть файл

@ -0,0 +1,4 @@
{
"$schema": "http://json.schemastore.org/proxies",
"proxies": {}
}

Просмотреть файл

@ -0,0 +1,5 @@
azure-functions
grpcio==1.37.0
google-cloud-logging==2.3.1
azure-storage-file-share==12.3.0
python-dateutil==2.8.1

Просмотреть файл

@ -0,0 +1,12 @@
// Usage Instruction :
// Paste below query in log analytics, click on Save button and select as Function from drop down by specifying function name and alias as ApigeeX.
// Function usually takes 10-15 minutes to activate. You can then use function alias from any other queries (e.g. ApigeeX | take 10).
// Reference : Using functions in Azure monitor log queries : https://docs.microsoft.com/azure/azure-monitor/log-query/functions
ApigeeX_CL
| extend EventVendor = 'Google'
| extend EventProduct = 'ApigeeX'
| project-rename
EventSeverity=severity_s,
EventEndTime=timestamp_t,
SrcIpAddr=payload_requestMetadata_callerIp_s,
HttpUserAgentOriginal=payload_requestMetadata_callerSuppliedUserAgent_s