id: teleport-session-and-mfa-failure-audit
namespace: company.team
description: |
A burst of failed MFA challenges against one Teleport user is the classic
signature of credential stuffing, yet the audit log only shows the attempts
one line at a time and nobody correlates them. This flow accepts a batch of
Teleport audit events from a webhook, groups the authentication events per
user, and counts consecutive failed logins and MFA challenge validations
inside a configurable time window. Users whose streak reaches the observe
threshold are routed for review, users at the contain threshold trigger a
Slack escalation and a GitHub incident issue, and the risk band, the risky
users, the maximum streak, and the event count are published as outputs.
triggers:
- id: audit_events_webhook
type: io.kestra.plugin.core.trigger.Webhook
description: The Teleport auth service, or a log forwarder tailing its audit
log, POSTs batches of audit events here.
key: "{{ secret('TELEPORT_AUDIT_WEBHOOK_KEY') }}"
- id: hourly_mfa_sweep
type: io.kestra.plugin.core.trigger.Schedule
description: Disabled hourly rehearsal that audits a bundled sample batch,
switched on only when a scheduled sweep is wanted.
cron: "0 * * * *"
disabled: true
inputs:
- id: observe_threshold
type: INT
defaults: 3
description: Consecutive MFA failures that mark a user for review instead of
leaving the batch clean.
- id: mfa_failure_threshold
type: INT
defaults: 5
description: Consecutive MFA failures at which the response escalates from
observe to contain.
- id: window_minutes
type: INT
defaults: 10
description: Maximum minutes between two failures for them to count as one
unbroken streak.
tasks:
# --- 1. correlate the audit batch ---
- id: audit_mfa_events
type: io.kestra.plugin.scripts.python.Script
description: Parse the webhook batch, group authentication events per user,
count unbroken MFA failure streaks, and emit the risk band through the
outputs protocol.
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
containerImage: python:3.12-slim
env:
EVENTS_JSON: "{{ (trigger.body ?? '') | toJson }}"
OBSERVE_THRESHOLD: "{{ inputs.observe_threshold }}"
CONTAIN_THRESHOLD: "{{ inputs.mfa_failure_threshold }}"
WINDOW_MINUTES: "{{ inputs.window_minutes }}"
script: |
import datetime as dt
import json
import os
SAMPLE_EVENTS = [
{"event": "user.login", "code": "T1001E", "time": "2026-10-15T09:10:02Z",
"user": "j.rivera@acme.io", "method": "local", "success": False,
"error": "invalid credentials"},
{"event": "mfa_auth_challenge.create", "code": "T1015I",
"time": "2026-10-15T09:10:04Z", "user": "j.rivera@acme.io"},
{"event": "mfa_auth_challenge.validate", "code": "T1016E",
"time": "2026-10-15T09:10:09Z", "user": "j.rivera@acme.io",
"mfa": {"status": "FAILED"}},
{"event": "mfa_auth_challenge.create", "code": "T1015I",
"time": "2026-10-15T09:10:13Z", "user": "j.rivera@acme.io"},
{"event": "mfa_auth_challenge.validate", "code": "T1016E",
"time": "2026-10-15T09:10:17Z", "user": "j.rivera@acme.io",
"mfa": {"status": "FAILED"}},
{"event": "mfa_auth_challenge.validate", "code": "T1016E",
"time": "2026-10-15T09:10:24Z", "user": "j.rivera@acme.io",
"mfa": {"status": "FAILED"}},
{"event": "mfa_auth_challenge.validate", "code": "T1016E",
"time": "2026-10-15T09:10:31Z", "user": "j.rivera@acme.io",
"mfa": {"status": "FAILED"}},
{"event": "mfa_auth_challenge.validate", "code": "T1016E",
"time": "2026-10-15T09:10:38Z", "user": "j.rivera@acme.io",
"mfa": {"status": "FAILED"}},
{"event": "user.login", "code": "T1001I", "time": "2026-10-15T09:11:02Z",
"user": "a.okafor@acme.io", "method": "github", "success": True},
{"event": "session.start", "code": "T1003I", "time": "2026-10-15T09:11:05Z",
"user": "a.okafor@acme.io", "login": "root", "sid": "demo-session"},
]
def env_int(name, default):
text = (os.environ.get(name) or "").strip()
if not text:
return default, ""
try:
return int(text), ""
except ValueError:
return default, "%s is not an integer (%s)" % (name, text)
def parse_clock(value):
text = str(value or "").strip()
if not text:
return None
try:
moment = dt.datetime.fromisoformat(text.replace("Z", "+00:00"))
except ValueError:
return None
if moment.tzinfo is None:
moment = moment.replace(tzinfo=dt.timezone.utc)
return moment
def clock_of(event):
for key in ("time", "timestamp", "ts", "created_at"):
if event.get(key):
moment = parse_clock(event.get(key))
if moment is not None:
return moment
return None
def truthy(value):
if isinstance(value, str):
return value.strip().lower() == "true"
if value is None:
return None
return bool(value)
def classify(event):
etype = str(event.get("event") or event.get("event_type") or "").lower()
code = str(event.get("code") or "").upper()
success = truthy(event.get("success"))
mfa = event.get("mfa") if isinstance(event.get("mfa"), dict) else {}
status = str(mfa.get("status") or event.get("mfa_status") or "").lower()
if status in ("failed", "failure", "denied", "error"):
return "failure"
is_check = etype.startswith("mfa_auth_challenge") or "mfa_challenge" in etype
if is_check:
if etype.endswith(".create"):
return "neutral"
if code.endswith("E") or success is False or "fail" in etype:
return "failure"
if code.endswith("I") or success is True:
return "success"
return "neutral"
if etype in ("user.login", "auth"):
if success is False or code.endswith("E"):
return "failure"
if success is True or code.endswith("I"):
return "success"
return "neutral"
if "mfa" in etype and "fail" in etype:
return "failure"
return None
observe, observe_error = env_int("OBSERVE_THRESHOLD", 3)
contain, contain_error = env_int("CONTAIN_THRESHOLD", 5)
window, window_error = env_int("WINDOW_MINUTES", 10)
config_error = "; ".join(x for x in (observe_error, contain_error, window_error) if x)
if observe > contain:
config_error = (config_error + "; " if config_error else "") + "observe_threshold exceeds contain_threshold"
window_seconds = max(window, 0) * 60
raw = (os.environ.get("EVENTS_JSON") or "").strip()
source = "webhook"
body_error = ""
doc = None
if raw and raw not in ("null", '""'):
try:
doc = json.loads(raw)
except ValueError as exc:
body_error = "body is not valid JSON (%s)" % exc
if not body_error and isinstance(doc, str):
text = doc.strip()
if text:
try:
doc = json.loads(text)
except ValueError as exc:
body_error = "body is not valid JSON (%s)" % exc
else:
doc = None
events = []
if doc is None and not body_error:
events = [dict(e) for e in SAMPLE_EVENTS]
source = "sample"
elif not body_error:
if isinstance(doc, dict):
batch = doc.get("events")
if isinstance(batch, list):
events = [e for e in batch if isinstance(e, dict)]
elif "event" in doc or "event_type" in doc or "uid" in doc:
events = [doc]
else:
body_error = "payload carries no events array and no single event"
elif isinstance(doc, list):
events = [e for e in doc if isinstance(e, dict)]
else:
body_error = "payload is neither an object nor an array"
parse_error = "; ".join(x for x in (config_error, body_error) if x)
per_user = {}
for index, event in enumerate(events):
state = classify(event)
if state is None:
continue
user = str(event.get("user") or event.get("username") or "").strip() or "unknown"
per_user.setdefault(user, []).append(
{"order": index, "clock": clock_of(event), "state": state})
user_streaks = {}
for user, entries in per_user.items():
entries.sort(key=lambda e: (0, e["clock"].timestamp()) if e["clock"] else (1, e["order"]))
streak = 0
best = 0
prev_failure = None
for entry in entries:
if entry["state"] == "neutral":
continue
if entry["state"] == "success":
streak = 0
prev_failure = None
continue
clock = entry["clock"].timestamp() if entry["clock"] else None
if streak == 0:
streak = 1
elif clock is None or prev_failure is None or (clock - prev_failure) <= window_seconds:
streak += 1
else:
streak = 1
if clock is not None:
prev_failure = clock
best = max(best, streak)
user_streaks[user] = best
max_streak = max(user_streaks.values()) if user_streaks else 0
risky = sorted(((name, count) for name, count in user_streaks.items()
if count >= observe), key=lambda pair: (-pair[1], pair[0]))
risky_users = ["%s (streak=%d)" % (name, count) for name, count in risky]
if max_streak >= contain and not parse_error:
risk_band = "contain"
elif max_streak >= observe or parse_error:
risk_band = "observe"
else:
risk_band = "clear"
summary = "%d event(s) from %d user(s), max streak %d, band %s" % (
len(events), len(per_user), max_streak, risk_band)
payload = {"outputs": {
"risk_band": risk_band,
"risky_users": risky_users,
"max_streak": max_streak,
"event_count": len(events),
"user_count": len(per_user),
"observe_threshold": observe,
"contain_threshold": contain,
"window_minutes": window,
"source": source,
"parse_error": parse_error,
"summary": summary,
}}
print(summary)
print("::" + json.dumps(payload) + "::")
# --- 2. risk gate, route, and escalate ---
- id: gate_on_mfa_risk
type: io.kestra.plugin.core.flow.If
description: Escalate as soon as one user's streak reaches the contain
threshold, and route every lower band to its own record.
condition: "{{ outputs.audit_mfa_events.vars.risk_band == 'contain' }}"
then:
- id: escalate_to_oncall
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Alert the security channel with the risky users, the maximum
streak, and the thresholds that were crossed.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"text": "Teleport MFA failure audit CONTAIN - max streak {{ outputs.audit_mfa_events.vars.max_streak }} across {{ outputs.audit_mfa_events.vars.event_count }} event(s). Risky user(s): {{ outputs.audit_mfa_events.vars.risky_users | join(', ') }}. Thresholds observe {{ inputs.observe_threshold }}, contain {{ inputs.mfa_failure_threshold }}, window {{ inputs.window_minutes }} minute(s). Execution {{ execution.id }}."
}
- id: open_incident_issue
type: io.kestra.plugin.github.issues.Create
description: Open a labeled incident issue listing the risky users so
containment work is tracked, not just announced.
jwtToken: "{{ secret('GITHUB_TOKEN') }}"
repository: "{{ trigger.body.repository ?? 'acme/security-operations' }}"
title: "Teleport MFA failure streak for {{
outputs.audit_mfa_events.vars.max_streak }} attempts"
body: |
## Teleport MFA failure streak
**{{ outputs.audit_mfa_events.vars.risky_users | length }}** user(s) crossed the contain threshold in one batch.
Risky user(s):
{{ outputs.audit_mfa_events.vars.risky_users | join(', ') }}
Maximum streak **{{ outputs.audit_mfa_events.vars.max_streak }}** within a **{{ inputs.window_minutes }} minute(s)** window, thresholds observe **{{ inputs.observe_threshold }}** and contain **{{ inputs.mfa_failure_threshold }}**.
{{ outputs.audit_mfa_events.vars.event_count }} audit event(s) checked from source `{{ outputs.audit_mfa_events.vars.source }}`.
Execution {{ execution.id }}
Confirm the attempts were a real user mistyping a second factor or lock the accounts and rotate credentials, then close this issue.
labels:
- teleport
- mfa
- security
else:
- id: route_response
type: io.kestra.plugin.core.flow.Switch
description: Split the batches below contain between a streak worth reviewing
and a batch that came back clean.
value: "{{ outputs.audit_mfa_events.vars.risk_band }}"
cases:
observe:
- id: log_for_review
type: io.kestra.plugin.core.log.Log
description: Record the streaks below the contain threshold so the execution
history shows who is trending toward escalation.
message: "Teleport MFA audit observe - {{ outputs.audit_mfa_events.vars.summary
}}, observe threshold {{ inputs.observe_threshold }}."
clear:
- id: log_clear
type: io.kestra.plugin.core.log.Log
description: Record the clean batch so execution history doubles as evidence
that the correlation ran.
message: "Teleport MFA audit clear - {{ outputs.audit_mfa_events.vars.summary
}}, below the observe threshold {{ inputs.observe_threshold }}."
defaults:
- id: log_unexpected_band
type: io.kestra.plugin.core.log.Log
description: Catch an unexpected band value instead of letting the response path
fall through silently.
message: "Unexpected risk band from audit_mfa_events: {{
outputs.audit_mfa_events.vars.risk_band }}."
errors:
- id: notify_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Escalate any failure to the ops channel with the execution url.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{"text": "FAILED: {{ flow.id }} {{ execution.id }}"}
outputs:
- id: risk_band
type: STRING
value: "{{ outputs.audit_mfa_events.vars.risk_band }}"
- id: risky_users
type: ARRAY
value: "{{ outputs.audit_mfa_events.vars.risky_users | toJson }}"
- id: max_streak
type: INT
value: "{{ outputs.audit_mfa_events.vars.max_streak }}"
- id: event_count
type: INT
value: "{{ outputs.audit_mfa_events.vars.event_count }}"
- id: parse_error
type: BOOL
value: "{{ outputs.audit_mfa_events.vars.parse_error != '' }}"