feat: SentinelOne SDL + VirusTotal Hunting integrations
SentinelOne SDL (endpoint): Unified Alerts via the GraphQL API. Alert ingestion (get_alerts) with rich filtering and an exhaustive OCSF mapper + 'SentinelOne SDL Alert' default type, full alert details, update (status/verdict/assignee), add note and trigger mitigation action. ApiToken auth; watermark converted to epoch ms for the detectedAt filter; alert edges flattened to nodes for ingestion. VirusTotal Hunting (enrichment, Premium): Livehunt notification-file ingestion (livehunt_files) with an OCSF mapper + 'VirusTotal Hunting File' default type (severity bucketed from malicious AV detections), Livehunt notifications listing, and Retrohunt job + matching-file listing. The core VT v3 reputation already ships as 'virustotal'; the XSOAR-feed and Premium file-download/zip/pcap commands were intentionally left out. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
name: "SentinelOne SDL Alert"
|
||||
color: "#6a0dad"
|
||||
icon: "alert"
|
||||
@@ -0,0 +1,119 @@
|
||||
id: sentinelone_sdl
|
||||
name: SentinelOne SDL
|
||||
version: 1.0.0
|
||||
description: "SentinelOne SDL (Security Data Lake) Unified Alerts via the GraphQL API — alert ingestion with rich filtering, full alert details, status/verdict/assignee updates, analyst notes and mitigation actions."
|
||||
changelog: "1.0.0 — Initial release: unified alert ingestion (get_alerts) with an exhaustive OCSF mapper, alert details, update (status/verdict/assignee), add note and trigger mitigation action."
|
||||
category: endpoint
|
||||
|
||||
# Per-instance configuration. The Unified Alerts GraphQL endpoint is on the
|
||||
# tenant console URL; authentication uses an API token (ApiToken scheme).
|
||||
config_schema:
|
||||
properties:
|
||||
url:
|
||||
type: string
|
||||
description: "SentinelOne console URL, e.g. https://tenant.sentinelone.net"
|
||||
api_token:
|
||||
type: string
|
||||
description: "SentinelOne API token"
|
||||
x-soar-sensitive: true
|
||||
required:
|
||||
- url
|
||||
- api_token
|
||||
|
||||
auth:
|
||||
- id: apitoken
|
||||
type: api_key
|
||||
in: header
|
||||
name: Authorization
|
||||
value_template: "ApiToken {{secret}}"
|
||||
secret_field: api_token
|
||||
|
||||
commands:
|
||||
# ── Ingestion ───────────────────────────────────────────────────────────────
|
||||
- id: get_alerts
|
||||
name: sentinelone-sdl-get-alerts
|
||||
description: "Fetch Unified Alerts with optional filters. Used for ingestion: results path = data (edges are flattened to alert nodes)."
|
||||
risk: read
|
||||
inputs_schema:
|
||||
properties:
|
||||
severity: { type: string, description: "Comma-separated severities (CRITICAL,HIGH,MEDIUM,LOW,INFO)" }
|
||||
status: { type: string, description: "Comma-separated statuses (NEW,IN_PROGRESS,RESOLVED)" }
|
||||
classification: { type: string, description: "Comma-separated classifications (MALWARE,RANSOMWARE,TROJAN,...)" }
|
||||
os_type: { type: string, description: "Comma-separated OS types (WINDOWS,LINUX,MACOS)" }
|
||||
attack_surface: { type: string, description: "Comma-separated attack surfaces (ENDPOINT,CLOUD,IDENTITY,NETWORK,EMAIL)" }
|
||||
analyst_verdict: { type: string, description: "Comma-separated analyst verdicts" }
|
||||
asset_id: { type: string, description: "Filter by asset ID" }
|
||||
external_id: { type: string, description: "Filter by external ID" }
|
||||
search_text: { type: string, description: "Full-text search on the alert name" }
|
||||
start_time: { type: string, description: "Lower bound on detectedAt (ISO-8601, epoch, or relative like '24 hours'). Incremental fetch watermark." }
|
||||
end_time: { type: string, description: "Upper bound on detectedAt (ISO-8601, epoch, or relative)" }
|
||||
unassigned_only: { type: string, description: "Only unassigned alerts (true/false)" }
|
||||
unmitigated_only: { type: string, description: "Only unmitigated alerts (true/false)" }
|
||||
limit: { type: number, description: "Maximum number of alerts (default 50, max 200)" }
|
||||
required: []
|
||||
outputs_schema: { properties: {} }
|
||||
ingest:
|
||||
results_path: data
|
||||
dedup_key: id
|
||||
incremental_field: start_time
|
||||
|
||||
- id: get_alert_details
|
||||
name: sentinelone-sdl-get-alert-details
|
||||
description: "Get the full details of a single alert, including indicators, observables and related alerts."
|
||||
risk: read
|
||||
inputs_schema:
|
||||
properties:
|
||||
alert_id: { type: string, description: "Alert ID" }
|
||||
required: [alert_id]
|
||||
outputs_schema: { properties: {} }
|
||||
|
||||
- id: update_alert
|
||||
name: sentinelone-sdl-update-alert
|
||||
description: "Update an alert: status, analyst verdict and/or assignee."
|
||||
risk: safe_write
|
||||
inputs_schema:
|
||||
properties:
|
||||
alert_id: { type: string, description: "Alert ID" }
|
||||
status: { type: string, description: "New status (NEW, IN_PROGRESS, RESOLVED)" }
|
||||
analyst_verdict: { type: string, description: "Analyst verdict (TRUE_POSITIVE_MALWARE, FALSE_POSITIVE_BENIGN, UNDEFINED, ...)" }
|
||||
assignee_user_id: { type: string, description: "User ID to assign (leave empty to skip)" }
|
||||
required: [alert_id]
|
||||
outputs_schema: { properties: {} }
|
||||
|
||||
- id: add_note
|
||||
name: sentinelone-sdl-add-note
|
||||
description: "Add an analyst note to an alert."
|
||||
risk: safe_write
|
||||
inputs_schema:
|
||||
properties:
|
||||
alert_id: { type: string, description: "Alert ID" }
|
||||
note_text: { type: string, description: "Note content" }
|
||||
required: [alert_id, note_text]
|
||||
outputs_schema: { properties: {} }
|
||||
|
||||
- id: trigger_action
|
||||
name: sentinelone-sdl-trigger-action
|
||||
description: "Trigger a mitigation action on an alert (e.g. QUARANTINE, KILL, REMEDIATE)."
|
||||
risk: destructive
|
||||
inputs_schema:
|
||||
properties:
|
||||
alert_id: { type: string, description: "Alert ID" }
|
||||
action_id: { type: string, description: "Action ID to trigger" }
|
||||
action_type: { type: string, description: "Action type (QUARANTINE, UNQUARANTINE, KILL, REMEDIATE, BLOCKLIST_ADD, EXCLUSION_ADD)" }
|
||||
required: [alert_id, action_id]
|
||||
outputs_schema: { properties: {} }
|
||||
|
||||
# ── Connectivity test ─────────────────────────────────────────────────────
|
||||
- id: test_connection
|
||||
name: sentinelone-sdl-test-connection
|
||||
description: "Verify connectivity and credentials (used by the Test button)."
|
||||
risk: read
|
||||
inputs_schema:
|
||||
properties: {}
|
||||
required: []
|
||||
outputs_schema: { properties: {} }
|
||||
|
||||
ingestion:
|
||||
command: get_alerts
|
||||
mapper: get_alerts
|
||||
default_incident_type: "SentinelOne SDL Alert"
|
||||
@@ -0,0 +1,52 @@
|
||||
name: "SentinelOne SDL Alerts → OCSF"
|
||||
description: "Maps a SentinelOne SDL Unified Alert (GraphQL alerts query, results_path = data — edges flattened to nodes) to OCSF Detection Finding fields."
|
||||
field_mappings:
|
||||
title: "name"
|
||||
description: "description"
|
||||
# toSeverity maps CRITICAL→5, HIGH→3, MEDIUM→2, LOW→1, INFO→1.
|
||||
severity: "severity"
|
||||
source: "detectionSource.vendor"
|
||||
# results_path = data; source_path is JSONata over ONE alert node.
|
||||
ocsf:
|
||||
# ── Finding ───────────────────────────────────────────────────────
|
||||
- { source_path: "id", ocsf_field: "finding_info.uid" }
|
||||
- { source_path: "name", ocsf_field: "finding_info.title" }
|
||||
- { source_path: "description", ocsf_field: "finding_info.desc" }
|
||||
- { source_path: "detectedAt", ocsf_field: "finding_info.created_time" }
|
||||
- { source_path: "updatedAt", ocsf_field: "finding_info.modified_time" }
|
||||
- { source_path: "firstSeenAt", ocsf_field: "finding_info.first_seen_time" }
|
||||
- { source_path: "lastSeenAt", ocsf_field: "finding_info.last_seen_time" }
|
||||
- { source_path: "externalId", ocsf_field: "finding_info.uid_alt" }
|
||||
# ── Incident state ────────────────────────────────────────────────
|
||||
- { source_path: "status", ocsf_field: "status" }
|
||||
- { source_path: "analystVerdict", ocsf_field: "disposition" }
|
||||
- { source_path: "classification", ocsf_field: "activity_name" }
|
||||
- { source_path: "confidenceLevel", ocsf_field: "confidence" }
|
||||
- { source_path: "attackSurfaces[0]", ocsf_field: "metadata.labels" }
|
||||
# ── Detection analytic ────────────────────────────────────────────
|
||||
- { source_path: "analytics.name", ocsf_field: "finding_info.analytic.name" }
|
||||
- { source_path: "analytics.uid", ocsf_field: "finding_info.analytic.uid" }
|
||||
- { source_path: "analytics.category", ocsf_field: "finding_info.analytic.category" }
|
||||
- { source_path: "detectionSource.vendor", ocsf_field: "metadata.product.vendor_name" }
|
||||
- { source_path: "detectionSource.product", ocsf_field: "metadata.product.name" }
|
||||
- { source_path: "detectionSource.engine", ocsf_field: "metadata.product.feature.name" }
|
||||
# ── Affected device ───────────────────────────────────────────────
|
||||
- { source_path: "asset.name", ocsf_field: "device.hostname" }
|
||||
- { source_path: "asset.id", ocsf_field: "device.uid" }
|
||||
- { source_path: "asset.osType", ocsf_field: "device.os.type" }
|
||||
- { source_path: "asset.osVersion", ocsf_field: "device.os.build" }
|
||||
- { source_path: "asset.agentVersion", ocsf_field: "device.agent.version" }
|
||||
- { source_path: "asset.name", ocsf_field: "src_endpoint.hostname" }
|
||||
- { source_path: "asset.lastLoggedInUser", ocsf_field: "user.name" }
|
||||
# ── Offending process (actor) ─────────────────────────────────────
|
||||
- { source_path: "process.cmdLine", ocsf_field: "actor.process.cmd_line" }
|
||||
- { source_path: "process.parentName", ocsf_field: "actor.process.parent_process.name" }
|
||||
- { source_path: "process.username", ocsf_field: "actor.user.name" }
|
||||
- { source_path: "process.file.name", ocsf_field: "actor.process.file.name" }
|
||||
- { source_path: "process.file.path", ocsf_field: "actor.process.file.path" }
|
||||
- { source_path: "process.file.md5", ocsf_field: "actor.process.file.hashes.md5" }
|
||||
- { source_path: "process.file.sha1", ocsf_field: "actor.process.file.hashes.sha1" }
|
||||
- { source_path: "process.file.sha256", ocsf_field: "actor.process.file.hashes.sha256" }
|
||||
# ── Assignee ──────────────────────────────────────────────────────
|
||||
- { source_path: "assignee.fullName", ocsf_field: "assignee.name" }
|
||||
- { source_path: "assignee.email", ocsf_field: "assignee.email_addr" }
|
||||
@@ -0,0 +1,50 @@
|
||||
import json, os, sys, urllib.request, urllib.parse, urllib.error
|
||||
|
||||
GRAPHQL = "/web/api/v2.1/unifiedalerts/graphql"
|
||||
|
||||
MUTATION = """
|
||||
mutation AddNote($alertId: ID!, $text: String!) {
|
||||
addAlertNote(alertId: $alertId, text: $text) {
|
||||
data { id text createdAt author { userId fullName } }
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def _cfg():
|
||||
s = json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
|
||||
base = str(s.get("url") or "").rstrip("/")
|
||||
headers = {"Authorization": "ApiToken " + s.get("api_token", ""), "Content-Type": "application/json", "Accept": "application/json"}
|
||||
return base, headers
|
||||
|
||||
|
||||
def _inputs():
|
||||
return json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
|
||||
|
||||
|
||||
def _graphql(query, variables):
|
||||
base, headers = _cfg()
|
||||
data = json.dumps({"query": query, "variables": variables}).encode("utf-8")
|
||||
req = urllib.request.Request(base + GRAPHQL, data=data, headers=headers, method="POST")
|
||||
with urllib.request.urlopen(req, timeout=90) as r:
|
||||
raw = r.read()
|
||||
resp = json.loads(raw) if raw else {}
|
||||
if resp.get("errors"):
|
||||
raise RuntimeError("GraphQL: " + "; ".join(e.get("message", str(e)) for e in resp["errors"]))
|
||||
return resp
|
||||
|
||||
|
||||
def run():
|
||||
inp = _inputs()
|
||||
resp = _graphql(MUTATION, {"alertId": inp.get("alert_id", ""), "text": inp.get("note_text", "")})
|
||||
print(json.dumps(resp.get("data", {}).get("addAlertNote", {})))
|
||||
|
||||
|
||||
try:
|
||||
run()
|
||||
except urllib.error.HTTPError as e:
|
||||
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
print(json.dumps({"error": str(e)}))
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,61 @@
|
||||
import json, os, sys, urllib.request, urllib.parse, urllib.error
|
||||
|
||||
GRAPHQL = "/web/api/v2.1/unifiedalerts/graphql"
|
||||
|
||||
QUERY = """
|
||||
query GetAlertDetails($id: ID!) {
|
||||
alert(id: $id) {
|
||||
id externalId name description severity status classification confidenceLevel
|
||||
analystVerdict result detectedAt createdAt updatedAt firstSeenAt lastSeenAt
|
||||
storylineId attackSurfaces noteExists
|
||||
asset { id name osType osVersion agentVersion lastLoggedInUser }
|
||||
assignee { userId fullName email }
|
||||
detectionSource { vendor product engine }
|
||||
process { cmdLine parentName username file { name path md5 sha1 sha256 size } }
|
||||
indicators { uid type message severity eventTime
|
||||
attacks { tactic { name uid } technique { name uid } }
|
||||
observables { name value type typeName } }
|
||||
observables { name value type typeName }
|
||||
relatedAlerts { id name }
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def _cfg():
|
||||
s = json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
|
||||
base = str(s.get("url") or "").rstrip("/")
|
||||
headers = {"Authorization": "ApiToken " + s.get("api_token", ""), "Content-Type": "application/json", "Accept": "application/json"}
|
||||
return base, headers
|
||||
|
||||
|
||||
def _inputs():
|
||||
return json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
|
||||
|
||||
|
||||
def _graphql(query, variables):
|
||||
base, headers = _cfg()
|
||||
data = json.dumps({"query": query, "variables": variables}).encode("utf-8")
|
||||
req = urllib.request.Request(base + GRAPHQL, data=data, headers=headers, method="POST")
|
||||
with urllib.request.urlopen(req, timeout=90) as r:
|
||||
raw = r.read()
|
||||
resp = json.loads(raw) if raw else {}
|
||||
if resp.get("errors"):
|
||||
raise RuntimeError("GraphQL: " + "; ".join(e.get("message", str(e)) for e in resp["errors"]))
|
||||
return resp
|
||||
|
||||
|
||||
def run():
|
||||
alert_id = _inputs().get("alert_id", "")
|
||||
resp = _graphql(QUERY, {"id": alert_id})
|
||||
print(json.dumps(resp.get("data", {}).get("alert", {})))
|
||||
|
||||
|
||||
try:
|
||||
run()
|
||||
except urllib.error.HTTPError as e:
|
||||
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
print(json.dumps({"error": str(e)}))
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,138 @@
|
||||
import json, os, sys, time, urllib.request, urllib.parse, urllib.error
|
||||
from datetime import datetime, timezone
|
||||
|
||||
GRAPHQL = "/web/api/v2.1/unifiedalerts/graphql"
|
||||
_UNITS = {"second": 1, "minute": 60, "hour": 3600, "day": 86400, "week": 604800, "month": 2592000, "year": 31536000}
|
||||
|
||||
QUERY = """
|
||||
query GetAlerts($first: Int!, $filters: [FilterInput!], $sorts: [SortInput!]) {
|
||||
alerts(first: $first, filters: $filters, sorts: $sorts, viewType: ALL) {
|
||||
totalCount
|
||||
edges { node {
|
||||
id externalId name description severity status classification confidenceLevel
|
||||
analystVerdict result detectedAt createdAt updatedAt firstSeenAt lastSeenAt
|
||||
storylineId attackSurfaces
|
||||
asset { id name osType osVersion agentVersion lastLoggedInUser }
|
||||
assignee { userId fullName email }
|
||||
detectionSource { vendor product engine }
|
||||
process { cmdLine parentName file { name path md5 sha1 sha256 } }
|
||||
analytics { category name type uid }
|
||||
} }
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def _cfg():
|
||||
s = json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
|
||||
base = str(s.get("url") or "").rstrip("/")
|
||||
headers = {"Authorization": "ApiToken " + s.get("api_token", ""), "Content-Type": "application/json", "Accept": "application/json"}
|
||||
return base, headers
|
||||
|
||||
|
||||
def _inputs():
|
||||
return json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
|
||||
|
||||
|
||||
def _list(v):
|
||||
if v in (None, ""):
|
||||
return []
|
||||
if isinstance(v, list):
|
||||
return [str(x).strip().upper() for x in v if str(x).strip()]
|
||||
return [p.strip().upper() for p in str(v).split(",") if p.strip()]
|
||||
|
||||
|
||||
def _rel_seconds(text):
|
||||
num = unit = None
|
||||
for t in str(text).lower().replace("last", "").split():
|
||||
if t.isdigit():
|
||||
num = int(t)
|
||||
elif t.rstrip("s") in _UNITS:
|
||||
unit = t.rstrip("s")
|
||||
return num * _UNITS[unit] if (num is not None and unit) else None
|
||||
|
||||
|
||||
def _to_ms(v):
|
||||
if not v:
|
||||
return None
|
||||
s = str(v).strip()
|
||||
secs = _rel_seconds(s)
|
||||
if secs is not None:
|
||||
return int((time.time() - secs) * 1000)
|
||||
if s.isdigit():
|
||||
n = int(s)
|
||||
return n if n >= 10 ** 12 else n * 1000
|
||||
try:
|
||||
dt = datetime.fromisoformat(s.replace("Z", "+00:00"))
|
||||
if dt.tzinfo is None:
|
||||
dt = dt.replace(tzinfo=timezone.utc)
|
||||
return int(dt.timestamp() * 1000)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _graphql(query, variables):
|
||||
base, headers = _cfg()
|
||||
data = json.dumps({"query": query, "variables": variables}).encode("utf-8")
|
||||
req = urllib.request.Request(base + GRAPHQL, data=data, headers=headers, method="POST")
|
||||
with urllib.request.urlopen(req, timeout=90) as r:
|
||||
raw = r.read()
|
||||
resp = json.loads(raw) if raw else {}
|
||||
if resp.get("errors"):
|
||||
msgs = [e.get("message", str(e)) for e in resp["errors"]]
|
||||
raise RuntimeError("GraphQL: " + "; ".join(msgs))
|
||||
return resp
|
||||
|
||||
|
||||
def _filters(inp):
|
||||
f = []
|
||||
for field, key in [("severity", "severity"), ("status", "status"), ("classification", "classification"),
|
||||
("attack_surface", "attackSurfaces"), ("analyst_verdict", "analystVerdict")]:
|
||||
vals = _list(inp.get(field))
|
||||
if vals:
|
||||
f.append({"fieldId": key, "stringIn": {"values": vals}})
|
||||
os_types = _list(inp.get("os_type"))
|
||||
if os_types:
|
||||
f.append({"fieldId": "asset.osType", "stringIn": {"values": os_types}})
|
||||
if inp.get("asset_id"):
|
||||
f.append({"fieldId": "asset.id", "stringEqual": {"value": inp["asset_id"]}})
|
||||
if inp.get("external_id"):
|
||||
f.append({"fieldId": "externalId", "stringEqual": {"value": inp["external_id"]}})
|
||||
if inp.get("search_text"):
|
||||
f.append({"fieldId": "name", "match": {"values": [inp["search_text"]]}})
|
||||
if str(inp.get("unassigned_only") or "").lower() in ("1", "true", "yes"):
|
||||
f.append({"fieldId": "assignee.userId", "isNegated": True, "stringEqual": {"value": None}})
|
||||
if str(inp.get("unmitigated_only") or "").lower() in ("1", "true", "yes"):
|
||||
f.append({"fieldId": "result", "stringEqual": {"value": "UNMITIGATED"}})
|
||||
start = _to_ms(inp.get("start_time"))
|
||||
end = _to_ms(inp.get("end_time"))
|
||||
if start or end:
|
||||
rng = {}
|
||||
if start:
|
||||
rng["start"] = start
|
||||
rng["startInclusive"] = True
|
||||
if end:
|
||||
rng["end"] = end
|
||||
rng["endInclusive"] = True
|
||||
f.append({"fieldId": "detectedAt", "dateTimeRange": rng})
|
||||
return f
|
||||
|
||||
|
||||
def run():
|
||||
inp = _inputs()
|
||||
limit = min(int(inp.get("limit") or 50), 200)
|
||||
variables = {"first": limit, "filters": _filters(inp), "sorts": [{"by": "detectedAt", "order": "ASC"}]}
|
||||
resp = _graphql(QUERY, variables)
|
||||
alerts = resp.get("data", {}).get("alerts", {})
|
||||
nodes = [e.get("node", {}) for e in alerts.get("edges", [])]
|
||||
print(json.dumps({"data": nodes, "totalCount": alerts.get("totalCount", 0)}))
|
||||
|
||||
|
||||
try:
|
||||
run()
|
||||
except urllib.error.HTTPError as e:
|
||||
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
print(json.dumps({"error": str(e)}))
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,36 @@
|
||||
import json, os, sys, urllib.request, urllib.parse, urllib.error
|
||||
|
||||
GRAPHQL = "/web/api/v2.1/unifiedalerts/graphql"
|
||||
QUERY = "query { alerts(first: 1, viewType: ALL) { totalCount } }"
|
||||
|
||||
|
||||
def _cfg():
|
||||
s = json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
|
||||
base = str(s.get("url") or "").rstrip("/")
|
||||
headers = {"Authorization": "ApiToken " + s.get("api_token", ""), "Content-Type": "application/json", "Accept": "application/json"}
|
||||
return base, headers
|
||||
|
||||
|
||||
def run():
|
||||
base, headers = _cfg()
|
||||
data = json.dumps({"query": QUERY, "variables": {}}).encode("utf-8")
|
||||
req = urllib.request.Request(base + GRAPHQL, data=data, headers=headers, method="POST")
|
||||
with urllib.request.urlopen(req, timeout=60) as r:
|
||||
raw = r.read()
|
||||
resp = json.loads(raw) if raw else {}
|
||||
if resp.get("errors"):
|
||||
print(json.dumps({"ok": False, "error": "; ".join(e.get("message", str(e)) for e in resp["errors"])}))
|
||||
sys.exit(1)
|
||||
print(json.dumps({"ok": True}))
|
||||
|
||||
|
||||
try:
|
||||
run()
|
||||
except urllib.error.HTTPError as e:
|
||||
detail = e.read().decode("utf-8", "replace")
|
||||
msg = "API token is not valid." if e.code in (401, 403) else "HTTP " + str(e.code)
|
||||
print(json.dumps({"ok": False, "error": msg, "detail": detail}))
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
print(json.dumps({"ok": False, "error": str(e)}))
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,60 @@
|
||||
import json, os, sys, urllib.request, urllib.parse, urllib.error
|
||||
|
||||
GRAPHQL = "/web/api/v2.1/unifiedalerts/graphql"
|
||||
|
||||
MUTATION = """
|
||||
mutation TriggerAction($actions: [TriggerActionInput!]!, $filter: OrFilterSelectionInput) {
|
||||
alertTriggerActions(actions: $actions, filter: $filter) {
|
||||
... on ActionsTriggered {
|
||||
actions { actionId alertCount
|
||||
success { id }
|
||||
failure { id errorMessage } }
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def _cfg():
|
||||
s = json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
|
||||
base = str(s.get("url") or "").rstrip("/")
|
||||
headers = {"Authorization": "ApiToken " + s.get("api_token", ""), "Content-Type": "application/json", "Accept": "application/json"}
|
||||
return base, headers
|
||||
|
||||
|
||||
def _inputs():
|
||||
return json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
|
||||
|
||||
|
||||
def _graphql(query, variables):
|
||||
base, headers = _cfg()
|
||||
data = json.dumps({"query": query, "variables": variables}).encode("utf-8")
|
||||
req = urllib.request.Request(base + GRAPHQL, data=data, headers=headers, method="POST")
|
||||
with urllib.request.urlopen(req, timeout=90) as r:
|
||||
raw = r.read()
|
||||
resp = json.loads(raw) if raw else {}
|
||||
if resp.get("errors"):
|
||||
raise RuntimeError("GraphQL: " + "; ".join(e.get("message", str(e)) for e in resp["errors"]))
|
||||
return resp
|
||||
|
||||
|
||||
def run():
|
||||
inp = _inputs()
|
||||
alert_id = inp.get("alert_id", "")
|
||||
payload = {}
|
||||
if inp.get("action_type"):
|
||||
payload["type"] = inp["action_type"]
|
||||
actions = [{"id": inp.get("action_id", ""), "payload": payload}]
|
||||
filt = {"or": [{"and": [{"fieldId": "id", "stringEqual": {"value": alert_id}}]}]}
|
||||
resp = _graphql(MUTATION, {"actions": actions, "filter": filt})
|
||||
print(json.dumps({"triggered": True, "alert_id": alert_id, "result": resp.get("data", {})}))
|
||||
|
||||
|
||||
try:
|
||||
run()
|
||||
except urllib.error.HTTPError as e:
|
||||
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
print(json.dumps({"error": str(e)}))
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,70 @@
|
||||
import json, os, sys, urllib.request, urllib.parse, urllib.error
|
||||
|
||||
GRAPHQL = "/web/api/v2.1/unifiedalerts/graphql"
|
||||
|
||||
MUTATION = """
|
||||
mutation TriggerActions($actions: [TriggerActionInput!]!, $filter: OrFilterSelectionInput) {
|
||||
alertTriggerActions(actions: $actions, filter: $filter) {
|
||||
... on ActionsTriggered {
|
||||
actions { actionId alertCount
|
||||
success { id }
|
||||
failure { id errorMessage errorType } }
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def _cfg():
|
||||
s = json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
|
||||
base = str(s.get("url") or "").rstrip("/")
|
||||
headers = {"Authorization": "ApiToken " + s.get("api_token", ""), "Content-Type": "application/json", "Accept": "application/json"}
|
||||
return base, headers
|
||||
|
||||
|
||||
def _inputs():
|
||||
return json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
|
||||
|
||||
|
||||
def _graphql(query, variables):
|
||||
base, headers = _cfg()
|
||||
data = json.dumps({"query": query, "variables": variables}).encode("utf-8")
|
||||
req = urllib.request.Request(base + GRAPHQL, data=data, headers=headers, method="POST")
|
||||
with urllib.request.urlopen(req, timeout=90) as r:
|
||||
raw = r.read()
|
||||
resp = json.loads(raw) if raw else {}
|
||||
if resp.get("errors"):
|
||||
raise RuntimeError("GraphQL: " + "; ".join(e.get("message", str(e)) for e in resp["errors"]))
|
||||
return resp
|
||||
|
||||
|
||||
def run():
|
||||
inp = _inputs()
|
||||
alert_id = inp.get("alert_id", "")
|
||||
actions = []
|
||||
if inp.get("status"):
|
||||
actions.append({"id": "update-status-" + alert_id, "payload": {"status": {"value": inp["status"]}}})
|
||||
if inp.get("analyst_verdict"):
|
||||
actions.append({"id": "update-verdict-" + alert_id, "payload": {"analystVerdict": {"value": inp["analyst_verdict"]}}})
|
||||
if inp.get("assignee_user_id"):
|
||||
try:
|
||||
assignee = int(inp["assignee_user_id"])
|
||||
except Exception:
|
||||
assignee = inp["assignee_user_id"]
|
||||
actions.append({"id": "assign-user-" + alert_id, "payload": {"assignUser": {"value": assignee}}})
|
||||
if not actions:
|
||||
print(json.dumps({"error": "Nothing to update: provide status, analyst_verdict or assignee_user_id."}))
|
||||
sys.exit(1)
|
||||
filt = {"or": [{"and": [{"fieldId": "id", "stringEqual": {"value": alert_id}}]}]}
|
||||
resp = _graphql(MUTATION, {"actions": actions, "filter": filt})
|
||||
print(json.dumps({"updated": True, "alert_id": alert_id, "result": resp.get("data", {})}))
|
||||
|
||||
|
||||
try:
|
||||
run()
|
||||
except urllib.error.HTTPError as e:
|
||||
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
print(json.dumps({"error": str(e)}))
|
||||
sys.exit(1)
|
||||
Reference in New Issue
Block a user