[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6AE8VHBR2P1BQFNQR4566MX":3,"skill-same:01M6AE8VHBR2P1BQFNQR4566MX":163},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":31,"publishedAt":49,"linkOnly":50,"markdownContent":51,"markdownBody":52,"frontMatter":53,"refName":98,"commitSha":99,"skillDirectory":100,"forksCount":101,"repositoryHtmlUrl":102,"repositoryHomepageUrl":103,"ownerHtmlUrl":104,"ownerBlogUrl":105,"ownerDescription":106,"updatedAt":107,"install":108,"resources":121},"01M6AE8VHBR2P1BQFNQR4566MX","detecting-anomalous-authentication-patterns",null,"Detects anomalous authentication patterns using UEBA analytics, statistical baselines, and machine learning models to identify impossible travel, credential stuffing, brute force, password spraying, and compromised account behaviors across authentication logs. Activates for requests involving authentication anomaly detection, login behavior analysis, UEBA implementation, or suspicious sign-in investigation.","mukul975\u002FAnthropic-Cybersecurity-Skills","mukul975","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F42860185?v=4","01M6ADEQR8T5M4EEG6C67BQCWF","Mahipal","01M6ADJPMYWG1E5GM1FWBE3128",36078,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fdetecting-anomalous-authentication-patterns\u002FSKILL.md",[18,23,26],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000013","分析与可视化","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发",{"categoryNo":27,"categoryName":28,"taxonomyType":29,"taxonomyTypeDesc":30},"01JBSEEDCAT000000000000033","数据分析师","PROFESSION","适用职业",[32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48],"detecting anomalous authentication patterns","authentication","logs","behavioral-analytics","credential-stuffing","brute-force","impossible-travel","authentication-anomaly","UEBA","detection","suspicious","pr","analytics","identity","web","machine learning","cybersecurity","2026-11-10 10:12:30",false,"---\nname: detecting-anomalous-authentication-patterns\ndescription: 'Detects anomalous authentication patterns using UEBA analytics, statistical\n  baselines, and machine learning models to identify impossible travel, credential\n  stuffing, brute force, password spraying, and compromised account behaviors across\n  authentication logs. Activates for requests involving authentication anomaly detection,\n  login behavior analysis, UEBA implementation, or suspicious sign-in investigation.\n\n  '\ndomain: cybersecurity\nsubdomain: identity-access-management\ntags:\n- UEBA\n- authentication-anomaly\n- impossible-travel\n- brute-force\n- credential-stuffing\n- behavioral-analytics\nversion: '1.0'\nauthor: mahipal\nlicense: Apache-2.0\natlas_techniques:\n- AML.T0043\n- AML.T0018\nnist_ai_rmf:\n- MEASURE-2.7\n- MEASURE-2.5\n- MAP-5.1\nnist_csf:\n- PR.AA-01\n- PR.AA-02\n- PR.AA-05\n- PR.AA-06\nmitre_attack:\n- T1110\n- T1110.003\n- T1110.004\n- T1078\n- T1021\nmitre_f3:\n  version: '1.1'\n  tactics:\n  - initial-access\n  - positioning\n  techniques:\n  - id: T1110.004\n    name: 'Brute Force:  Credential Stuffing'\n    tactic: initial-access\n    source: attack\n  - id: T1110.003\n    name: 'Brute Force: Password Spraying'\n    tactic: initial-access\n    source: attack\n  - id: F1006\n    name: Account Takeover\n    tactic: initial-access\n    source: f3\n  - id: F1006.002\n    name: 'Account Takeover: Exposed Login Credential'\n    tactic: initial-access\n    source: f3\n  - id: T1539\n    name: Steal Web Session Cookie\n    tactic: positioning\n    source: attack\n---\n\n# Detecting Anomalous Authentication Patterns\n\n## When to Use\n\n- Security operations needs to identify compromised accounts from authentication log analysis\n- Implementing impossible travel detection to flag geographically inconsistent logins\n- Detecting brute force, password spraying, and credential stuffing attacks in real time\n- Building behavioral baselines for users to identify deviations indicating account compromise\n- Correlating authentication anomalies with threat intelligence for lateral movement detection\n- Investigating alerts from SIEM or IdP for suspicious sign-in activity\n\n**Do not use** for static rule-based alerting on single failed logins; anomaly detection requires statistical baselines across time and entity dimensions to reduce false positives.\n\n## Prerequisites\n\n- Authentication log sources (Azure AD\u002FEntra ID sign-in logs, Okta system logs, Active Directory event logs 4624\u002F4625\u002F4648\u002F4768\u002F4771)\n- SIEM platform (Splunk, Microsoft Sentinel, Elastic SIEM) with at least 90 days of baseline data\n- GeoIP database for location-based anomaly detection (MaxMind GeoLite2 or IP2Location)\n- Python 3.9+ with pandas, scikit-learn, and scipy for custom analytics\n- User identity context (department, role, typical work hours, location)\n\n## Workflow\n\n### Step 1: Collect and Normalize Authentication Logs\n\nAggregate authentication events from all identity sources:\n\n```python\nimport pandas as pd\nimport json\nfrom datetime import datetime, timedelta\nfrom collections import defaultdict\n\n# Parse authentication logs from multiple sources\ndef normalize_auth_logs(log_source, raw_logs):\n    \"\"\"Normalize authentication events to a common schema.\"\"\"\n    normalized = []\n\n    for event in raw_logs:\n        if log_source == \"azure_ad\":\n            normalized.append({\n                \"timestamp\": event[\"createdDateTime\"],\n                \"user\": event[\"userPrincipalName\"],\n                \"source_ip\": event[\"ipAddress\"],\n                \"location\": {\n                    \"city\": event.get(\"location\", {}).get(\"city\"),\n                    \"state\": event.get(\"location\", {}).get(\"state\"),\n                    \"country\": event.get(\"location\", {}).get(\"countryOrRegion\"),\n                    \"lat\": event.get(\"location\", {}).get(\"geoCoordinates\", {}).get(\"latitude\"),\n                    \"lon\": event.get(\"location\", {}).get(\"geoCoordinates\", {}).get(\"longitude\")\n                },\n                \"result\": \"success\" if event[\"status\"][\"errorCode\"] == 0 else \"failure\",\n                \"failure_reason\": event[\"status\"].get(\"failureReason\", \"\"),\n                \"app\": event.get(\"appDisplayName\", \"Unknown\"),\n                \"device\": event.get(\"deviceDetail\", {}).get(\"operatingSystem\", \"Unknown\"),\n                \"browser\": event.get(\"deviceDetail\", {}).get(\"browser\", \"Unknown\"),\n                \"mfa_result\": event.get(\"authenticationDetails\", [{}])[0].get(\"succeeded\", None),\n                \"risk_level\": event.get(\"riskLevelDuringSignIn\", \"none\"),\n                \"client_app\": event.get(\"clientAppUsed\", \"Unknown\"),\n                \"source\": \"azure_ad\"\n            })\n        elif log_source == \"okta\":\n            normalized.append({\n                \"timestamp\": event[\"published\"],\n                \"user\": event[\"actor\"][\"alternateId\"],\n                \"source_ip\": event[\"client\"][\"ipAddress\"],\n                \"location\": {\n                    \"city\": event[\"client\"].get(\"geographicalContext\", {}).get(\"city\"),\n                    \"state\": event[\"client\"].get(\"geographicalContext\", {}).get(\"state\"),\n                    \"country\": event[\"client\"].get(\"geographicalContext\", {}).get(\"country\"),\n                    \"lat\": event[\"client\"].get(\"geographicalContext\", {}).get(\"geolocation\", {}).get(\"lat\"),\n                    \"lon\": event[\"client\"].get(\"geographicalContext\", {}).get(\"geolocation\", {}).get(\"lon\")\n                },\n                \"result\": \"success\" if event[\"outcome\"][\"result\"] == \"SUCCESS\" else \"failure\",\n                \"failure_reason\": event[\"outcome\"].get(\"reason\", \"\"),\n                \"app\": event.get(\"target\", [{}])[0].get(\"displayName\", \"Unknown\"),\n                \"device\": event[\"client\"].get(\"device\", \"Unknown\"),\n                \"browser\": event[\"client\"].get(\"userAgent\", {}).get(\"browser\", \"Unknown\"),\n                \"source\": \"okta\"\n            })\n        elif log_source == \"windows_ad\":\n            normalized.append({\n                \"timestamp\": event[\"TimeCreated\"],\n                \"user\": event[\"TargetUserName\"],\n                \"source_ip\": event.get(\"IpAddress\", \"\"),\n                \"location\": None,  # Requires GeoIP enrichment\n                \"result\": \"success\" if event[\"EventId\"] in [4624, 4648] else \"failure\",\n                \"failure_reason\": event.get(\"FailureReason\", \"\"),\n                \"logon_type\": event.get(\"LogonType\", \"\"),\n                \"source\": \"windows_ad\"\n            })\n\n    return pd.DataFrame(normalized)\n\n# Enrich with GeoIP data for Windows AD logs missing location\nimport geoip2.database\n\ndef enrich_geoip(df, geoip_db_path=\"\u002Fopt\u002Fgeoip\u002FGeoLite2-City.mmdb\"):\n    \"\"\"Add geolocation data to events missing location information.\"\"\"\n    reader = geoip2.database.Reader(geoip_db_path)\n\n    for idx, row in df.iterrows():\n        if row[\"location\"] is None and row[\"source_ip\"]:\n            try:\n                response = reader.city(row[\"source_ip\"])\n                df.at[idx, \"location\"] = {\n                    \"city\": response.city.name,\n                    \"country\": response.country.iso_code,\n                    \"lat\": response.location.latitude,\n                    \"lon\": response.location.longitude\n                }\n            except Exception:\n                pass\n\n    reader.close()\n    return df\n```\n\n### Step 2: Detect Impossible Travel Anomalies\n\nIdentify logins from geographically impossible locations:\n\n```python\nfrom math import radians, sin, cos, sqrt, atan2\nfrom datetime import datetime\n\ndef haversine_distance(lat1, lon1, lat2, lon2):\n    \"\"\"Calculate great-circle distance between two points in km.\"\"\"\n    R = 6371  # Earth's radius in kilometers\n\n    lat1, lon1, lat2, lon2 = map(radians, [lat1, lon1, lat2, lon2])\n    dlat = lat2 - lat1\n    dlon = lon2 - lon1\n\n    a = sin(dlat\u002F2)**2 + cos(lat1) * cos(lat2) * sin(dlon\u002F2)**2\n    c = 2 * atan2(sqrt(a), sqrt(1-a))\n\n    return R * c\n\ndef detect_impossible_travel(df, max_speed_kmh=900):\n    \"\"\"\n    Detect impossible travel events where a user authenticates from\n    two locations faster than physically possible.\n\n    max_speed_kmh: Maximum realistic travel speed (900 km\u002Fh ~= commercial flight)\n    \"\"\"\n    alerts = []\n\n    # Sort by user and timestamp\n    df_sorted = df.sort_values([\"user\", \"timestamp\"])\n\n    for user, user_events in df_sorted.groupby(\"user\"):\n        successful_events = user_events[user_events[\"result\"] == \"success\"]\n\n        for i in range(1, len(successful_events)):\n            prev = successful_events.iloc[i-1]\n            curr = successful_events.iloc[i]\n\n            # Skip if location data is missing\n            if not prev.get(\"location\") or not curr.get(\"location\"):\n                continue\n            if not prev[\"location\"].get(\"lat\") or not curr[\"location\"].get(\"lat\"):\n                continue\n\n            # Calculate distance and time delta\n            distance_km = haversine_distance(\n                prev[\"location\"][\"lat\"], prev[\"location\"][\"lon\"],\n                curr[\"location\"][\"lat\"], curr[\"location\"][\"lon\"]\n            )\n\n            time_diff = (pd.Timestamp(curr[\"timestamp\"]) -\n                        pd.Timestamp(prev[\"timestamp\"])).total_seconds() \u002F 3600\n\n            if time_diff \u003C= 0:\n                continue\n\n            required_speed = distance_km \u002F time_diff\n\n            # Flag if required speed exceeds maximum realistic travel\n            if required_speed > max_speed_kmh and distance_km > 100:\n                alerts.append({\n                    \"alert_type\": \"IMPOSSIBLE_TRAVEL\",\n                    \"severity\": \"HIGH\",\n                    \"user\": user,\n                    \"timestamp\": curr[\"timestamp\"],\n                    \"details\": {\n                        \"location_1\": f\"{prev['location']['city']}, {prev['location']['country']}\",\n                        \"location_2\": f\"{curr['location']['city']}, {curr['location']['country']}\",\n                        \"time_1\": prev[\"timestamp\"],\n                        \"time_2\": curr[\"timestamp\"],\n                        \"distance_km\": round(distance_km, 1),\n                        \"time_hours\": round(time_diff, 2),\n                        \"required_speed_kmh\": round(required_speed, 1),\n                        \"source_ip_1\": prev[\"source_ip\"],\n                        \"source_ip_2\": curr[\"source_ip\"]\n                    }\n                })\n\n    return alerts\n\n# Run impossible travel detection\ntravel_alerts = detect_impossible_travel(auth_df)\nprint(f\"Impossible travel alerts: {len(travel_alerts)}\")\nfor alert in travel_alerts:\n    print(f\"  [{alert['severity']}] {alert['user']}: \"\n          f\"{alert['details']['location_1']} -> {alert['details']['location_2']} \"\n          f\"({alert['details']['distance_km']} km in {alert['details']['time_hours']}h)\")\n```\n\n### Step 3: Detect Brute Force and Password Spraying\n\nIdentify credential attack patterns across authentication logs:\n\n```python\nfrom collections import Counter\n\ndef detect_brute_force(df, threshold_failures=10, window_minutes=10):\n    \"\"\"\n    Detect brute force attacks: many failed attempts against\n    a single account in a short time window.\n    \"\"\"\n    alerts = []\n    failed = df[df[\"result\"] == \"failure\"].copy()\n    failed[\"timestamp\"] = pd.to_datetime(failed[\"timestamp\"])\n\n    for user, user_fails in failed.groupby(\"user\"):\n        user_fails_sorted = user_fails.sort_values(\"timestamp\")\n\n        # Sliding window analysis\n        for i, row in user_fails_sorted.iterrows():\n            window_start = row[\"timestamp\"]\n            window_end = window_start + timedelta(minutes=window_minutes)\n\n            window_events = user_fails_sorted[\n                (user_fails_sorted[\"timestamp\"] >= window_start) &\n                (user_fails_sorted[\"timestamp\"] \u003C= window_end)\n            ]\n\n            if len(window_events) >= threshold_failures:\n                source_ips = window_events[\"source_ip\"].unique()\n                alerts.append({\n                    \"alert_type\": \"BRUTE_FORCE\",\n                    \"severity\": \"HIGH\",\n                    \"user\": user,\n                    \"timestamp\": str(window_start),\n                    \"details\": {\n                        \"failed_attempts\": len(window_events),\n                        \"window_minutes\": window_minutes,\n                        \"source_ips\": list(source_ips),\n                        \"distributed\": len(source_ips) > 1,\n                        \"failure_reasons\": dict(Counter(window_events[\"failure_reason\"]))\n                    }\n                })\n                break  # One alert per user per detection pass\n\n    return alerts\n\ndef detect_password_spray(df, threshold_users=10, window_minutes=30):\n    \"\"\"\n    Detect password spraying: failed logins against many different\n    accounts from the same source in a short window (1-2 attempts per user).\n    \"\"\"\n    alerts = []\n    failed = df[df[\"result\"] == \"failure\"].copy()\n    failed[\"timestamp\"] = pd.to_datetime(failed[\"timestamp\"])\n\n    for source_ip, ip_events in failed.groupby(\"source_ip\"):\n        ip_events_sorted = ip_events.sort_values(\"timestamp\")\n\n        for i, row in ip_events_sorted.iterrows():\n            window_start = row[\"timestamp\"]\n            window_end = window_start + timedelta(minutes=window_minutes)\n\n            window_events = ip_events_sorted[\n                (ip_events_sorted[\"timestamp\"] >= window_start) &\n                (ip_events_sorted[\"timestamp\"] \u003C= window_end)\n            ]\n\n            unique_users = window_events[\"user\"].nunique()\n            attempts_per_user = len(window_events) \u002F unique_users if unique_users > 0 else 0\n\n            # Password spray: many users targeted, few attempts per user\n            if unique_users >= threshold_users and attempts_per_user \u003C= 3:\n                # Check if any succeeded (compromised account)\n                success_after = df[\n                    (df[\"source_ip\"] == source_ip) &\n                    (df[\"result\"] == \"success\") &\n                    (pd.to_datetime(df[\"timestamp\"]) > window_start) &\n                    (pd.to_datetime(df[\"timestamp\"]) \u003C window_end + timedelta(hours=1))\n                ]\n\n                alerts.append({\n                    \"alert_type\": \"PASSWORD_SPRAY\",\n                    \"severity\": \"CRITICAL\" if len(success_after) > 0 else \"HIGH\",\n                    \"timestamp\": str(window_start),\n                    \"details\": {\n                        \"source_ip\": source_ip,\n                        \"targeted_users\": unique_users,\n                        \"total_attempts\": len(window_events),\n                        \"avg_attempts_per_user\": round(attempts_per_user, 1),\n                        \"window_minutes\": window_minutes,\n                        \"successful_logins_after\": len(success_after),\n                        \"compromised_accounts\": list(success_after[\"user\"].unique()) if len(success_after) > 0 else []\n                    }\n                })\n                break\n\n    return alerts\n\n# Run detections\nbrute_force_alerts = detect_brute_force(auth_df)\nspray_alerts = detect_password_spray(auth_df)\nprint(f\"Brute force alerts: {len(brute_force_alerts)}\")\nprint(f\"Password spray alerts: {len(spray_alerts)}\")\n```\n\n### Step 4: Build Behavioral Baselines and Detect Deviations\n\nCreate user behavioral profiles and flag statistical anomalies:\n\n```python\nimport numpy as np\nfrom scipy import stats\nfrom sklearn.ensemble import IsolationForest\n\ndef build_user_baseline(df, user, lookback_days=90):\n    \"\"\"Build behavioral baseline for a specific user.\"\"\"\n    user_events = df[df[\"user\"] == user].copy()\n    user_events[\"timestamp\"] = pd.to_datetime(user_events[\"timestamp\"])\n    user_events[\"hour\"] = user_events[\"timestamp\"].dt.hour\n    user_events[\"day_of_week\"] = user_events[\"timestamp\"].dt.dayofweek\n\n    baseline = {\n        \"user\": user,\n        \"typical_hours\": {\n            \"start\": int(user_events[\"hour\"].quantile(0.05)),\n            \"end\": int(user_events[\"hour\"].quantile(0.95)),\n            \"mean\": float(user_events[\"hour\"].mean()),\n            \"std\": float(user_events[\"hour\"].std())\n        },\n        \"typical_days\": list(user_events[\"day_of_week\"].mode().values),\n        \"typical_ips\": list(user_events[\"source_ip\"].value_counts().head(10).index),\n        \"typical_locations\": list(\n            user_events[\"location\"].apply(\n                lambda x: x.get(\"country\") if isinstance(x, dict) else None\n            ).dropna().value_counts().head(5).index\n        ),\n        \"typical_apps\": list(user_events[\"app\"].value_counts().head(10).index),\n        \"typical_devices\": list(user_events[\"device\"].value_counts().head(5).index),\n        \"avg_daily_logins\": float(\n            user_events.groupby(user_events[\"timestamp\"].dt.date).size().mean()\n        ),\n        \"std_daily_logins\": float(\n            user_events.groupby(user_events[\"timestamp\"].dt.date).size().std()\n        ),\n        \"failure_rate\": float(\n            (user_events[\"result\"] == \"failure\").mean()\n        )\n    }\n\n    return baseline\n\ndef detect_behavioral_anomalies(event, baseline):\n    \"\"\"Compare a new authentication event against user baseline.\"\"\"\n    anomalies = []\n    event_time = pd.Timestamp(event[\"timestamp\"])\n\n    # Off-hours login detection\n    hour = event_time.hour\n    if baseline[\"typical_hours\"][\"std\"] > 0:\n        z_score = abs(hour - baseline[\"typical_hours\"][\"mean\"]) \u002F baseline[\"typical_hours\"][\"std\"]\n        if z_score > 2.5:\n            anomalies.append({\n                \"type\": \"OFF_HOURS_LOGIN\",\n                \"severity\": \"MEDIUM\",\n                \"detail\": f\"Login at {hour}:00 (baseline: {baseline['typical_hours']['start']}:00-{baseline['typical_hours']['end']}:00)\",\n                \"z_score\": round(z_score, 2)\n            })\n\n    # New source IP\n    if event[\"source_ip\"] not in baseline[\"typical_ips\"]:\n        anomalies.append({\n            \"type\": \"NEW_SOURCE_IP\",\n            \"severity\": \"MEDIUM\",\n            \"detail\": f\"Login from unknown IP: {event['source_ip']}\"\n        })\n\n    # New country\n    if event.get(\"location\") and isinstance(event[\"location\"], dict):\n        country = event[\"location\"].get(\"country\")\n        if country and country not in baseline[\"typical_locations\"]:\n            anomalies.append({\n                \"type\": \"NEW_COUNTRY\",\n                \"severity\": \"HIGH\",\n                \"detail\": f\"Login from new country: {country}\"\n            })\n\n    # New application\n    if event.get(\"app\") and event[\"app\"] not in baseline[\"typical_apps\"]:\n        anomalies.append({\n            \"type\": \"NEW_APPLICATION\",\n            \"severity\": \"LOW\",\n            \"detail\": f\"Access to new application: {event['app']}\"\n        })\n\n    # New device\n    if event.get(\"device\") and event[\"device\"] not in baseline[\"typical_devices\"]:\n        anomalies.append({\n            \"type\": \"NEW_DEVICE\",\n            \"severity\": \"MEDIUM\",\n            \"detail\": f\"Login from new device: {event['device']}\"\n        })\n\n    # Weekend login for weekday-only users\n    if event_time.dayofweek >= 5 and 5 not in baseline[\"typical_days\"] and 6 not in baseline[\"typical_days\"]:\n        anomalies.append({\n            \"type\": \"WEEKEND_LOGIN\",\n            \"severity\": \"LOW\",\n            \"detail\": f\"Weekend login detected (typical days: {baseline['typical_days']})\"\n        })\n\n    return anomalies\n\ndef isolation_forest_anomaly_detection(df):\n    \"\"\"Use Isolation Forest for multivariate anomaly detection.\"\"\"\n    # Feature engineering\n    features_df = df.copy()\n    features_df[\"timestamp\"] = pd.to_datetime(features_df[\"timestamp\"])\n    features_df[\"hour\"] = features_df[\"timestamp\"].dt.hour\n    features_df[\"day_of_week\"] = features_df[\"timestamp\"].dt.dayofweek\n    features_df[\"is_failure\"] = (features_df[\"result\"] == \"failure\").astype(int)\n\n    # Encode categorical features\n    features_df[\"ip_frequency\"] = features_df.groupby(\"source_ip\")[\"source_ip\"].transform(\"count\")\n    features_df[\"user_frequency\"] = features_df.groupby(\"user\")[\"user\"].transform(\"count\")\n\n    feature_columns = [\"hour\", \"day_of_week\", \"is_failure\", \"ip_frequency\", \"user_frequency\"]\n    X = features_df[feature_columns].fillna(0)\n\n    # Train Isolation Forest\n    model = IsolationForest(\n        n_estimators=200,\n        contamination=0.01,  # Expect 1% anomaly rate\n        random_state=42,\n        n_jobs=-1\n    )\n    features_df[\"anomaly_score\"] = model.fit_predict(X)\n    features_df[\"anomaly_probability\"] = model.score_samples(X)\n\n    # Extract anomalies (labeled as -1)\n    anomalies = features_df[features_df[\"anomaly_score\"] == -1]\n\n    return anomalies.sort_values(\"anomaly_probability\")\n```\n\n### Step 5: Implement SIEM Detection Rules\n\nDeploy detection rules for common authentication attack patterns:\n\n```yaml\n# Splunk SPL queries for authentication anomaly detection\n\n# 1. Brute Force Detection\n# name: Authentication Brute Force - Multiple Failed Logins\n# severity: high\nbrute_force_spl: |\n  index=auth sourcetype IN (\"azure:aad:signin\", \"okta:im:log\", \"WinEventLog:Security\")\n  (result=\"failure\" OR EventCode=4625)\n  | bin _time span=10m\n  | stats count as failed_attempts dc(src_ip) as unique_ips\n    values(src_ip) as source_ips\n    latest(_time) as last_attempt\n    by user _time\n  | where failed_attempts >= 10\n  | eval alert_type=if(unique_ips > 3, \"Distributed Brute Force\", \"Standard Brute Force\")\n\n# 2. Password Spray Detection\n# name: Password Spray Attack - Multiple Users Same Source\n# severity: critical\npassword_spray_spl: |\n  index=auth sourcetype IN (\"azure:aad:signin\", \"okta:im:log\")\n  result=\"failure\"\n  | bin _time span=30m\n  | stats dc(user) as targeted_users count as total_attempts\n    values(user) as users_targeted\n    by src_ip _time\n  | where targeted_users >= 10\n  | eval attempts_per_user = round(total_attempts \u002F targeted_users, 1)\n  | where attempts_per_user \u003C= 3\n  | eval severity=if(targeted_users > 50, \"CRITICAL\", \"HIGH\")\n\n# 3. Impossible Travel Detection\n# name: Impossible Travel - Geographically Inconsistent Logins\n# severity: high\nimpossible_travel_spl: |\n  index=auth result=\"success\"\n  | iplocation src_ip\n  | sort user _time\n  | streamstats current=f last(lat) as prev_lat last(lon) as prev_lon\n    last(_time) as prev_time last(City) as prev_city last(Country) as prev_country\n    by user\n  | where isnotnull(prev_lat) AND isnotnull(lat)\n  | eval distance_km = 6371 * 2 * asin(sqrt(\n      pow(sin((lat - prev_lat) * pi() \u002F 360), 2) +\n      cos(prev_lat * pi() \u002F 180) * cos(lat * pi() \u002F 180) *\n      pow(sin((lon - prev_lon) * pi() \u002F 360), 2)))\n  | eval time_hours = (_time - prev_time) \u002F 3600\n  | eval required_speed = distance_km \u002F time_hours\n  | where required_speed > 900 AND distance_km > 100\n\n# 4. Credential Stuffing Detection\n# name: Credential Stuffing - High Volume Failed Logins with Some Successes\n# severity: critical\ncredential_stuffing_spl: |\n  index=auth\n  | bin _time span=1h\n  | stats count(eval(result=\"failure\")) as failures\n    count(eval(result=\"success\")) as successes\n    dc(user) as unique_users\n    dc(src_ip) as unique_ips\n    by src_ip _time\n  | where failures > 100 AND successes > 0 AND unique_users > 20\n  | eval success_rate = round(successes \u002F (failures + successes) * 100, 2)\n  | where success_rate \u003C 5\n```\n\n### Step 6: Correlate and Score Authentication Anomalies\n\nCombine multiple detection signals into risk scores:\n\n```python\ndef calculate_auth_risk_score(user, alerts, baseline):\n    \"\"\"\n    Calculate composite risk score for authentication events.\n    Combines multiple anomaly signals with weighted scoring.\n    \"\"\"\n    score = 0\n    risk_factors = []\n\n    weights = {\n        \"IMPOSSIBLE_TRAVEL\": 40,\n        \"PASSWORD_SPRAY\": 35,\n        \"BRUTE_FORCE\": 30,\n        \"CREDENTIAL_STUFFING\": 35,\n        \"NEW_COUNTRY\": 25,\n        \"OFF_HOURS_LOGIN\": 15,\n        \"NEW_SOURCE_IP\": 10,\n        \"NEW_DEVICE\": 10,\n        \"NEW_APPLICATION\": 5,\n        \"WEEKEND_LOGIN\": 5,\n        \"MFA_BYPASS\": 45,\n        \"LEGACY_PROTOCOL\": 20\n    }\n\n    for alert in alerts:\n        alert_type = alert.get(\"type\") or alert.get(\"alert_type\")\n        weight = weights.get(alert_type, 10)\n\n        # Adjust weight based on severity\n        severity_multiplier = {\n            \"CRITICAL\": 2.0,\n            \"HIGH\": 1.5,\n            \"MEDIUM\": 1.0,\n            \"LOW\": 0.5\n        }\n        severity = alert.get(\"severity\", \"MEDIUM\")\n        adjusted_weight = weight * severity_multiplier.get(severity, 1.0)\n\n        score += adjusted_weight\n        risk_factors.append({\n            \"factor\": alert_type,\n            \"weight\": adjusted_weight,\n            \"detail\": alert.get(\"detail\", alert.get(\"details\", \"\"))\n        })\n\n    # Normalize score to 0-100\n    normalized_score = min(100, score)\n\n    # Determine risk level\n    if normalized_score >= 80:\n        risk_level = \"CRITICAL\"\n        recommended_action = \"Immediate account suspension and investigation\"\n    elif normalized_score >= 60:\n        risk_level = \"HIGH\"\n        recommended_action = \"Force MFA re-enrollment and notify SOC\"\n    elif normalized_score >= 40:\n        risk_level = \"MEDIUM\"\n        recommended_action = \"Require step-up authentication\"\n    elif normalized_score >= 20:\n        risk_level = \"LOW\"\n        recommended_action = \"Monitor and log for trend analysis\"\n    else:\n        risk_level = \"INFORMATIONAL\"\n        recommended_action = \"No action required\"\n\n    return {\n        \"user\": user,\n        \"risk_score\": normalized_score,\n        \"risk_level\": risk_level,\n        \"recommended_action\": recommended_action,\n        \"risk_factors\": sorted(risk_factors, key=lambda x: x[\"weight\"], reverse=True),\n        \"timestamp\": datetime.utcnow().isoformat()\n    }\n```\n\n## Key Concepts\n\n| Term | Definition |\n|------|------------|\n| **Impossible Travel** | Authentication anomaly where a user logs in from two geographically distant locations within a timeframe that makes physical travel impossible |\n| **Password Spraying** | Credential attack that tries a small number of commonly used passwords against many accounts to avoid lockout thresholds |\n| **Credential Stuffing** | Automated attack using stolen username\u002Fpassword pairs from data breaches to gain unauthorized access to accounts |\n| **UEBA** | User and Entity Behavior Analytics technology that builds behavioral baselines and detects deviations using machine learning and statistical analysis |\n| **Behavioral Baseline** | Statistical profile of a user's normal authentication patterns including typical hours, locations, devices, and applications |\n| **Isolation Forest** | Unsupervised machine learning algorithm that detects anomalies by isolating observations that differ from the majority of data points |\n| **Risk Score** | Composite numerical value aggregating multiple anomaly signals with weighted scoring to prioritize authentication threats |\n\n## Tools & Systems\n\n- **Microsoft Sentinel UEBA**: Cloud-native SIEM with built-in entity behavior analytics for Azure AD and multi-cloud authentication anomaly detection\n- **Exabeam Advanced Analytics**: UEBA platform using machine learning for user session analysis and automated threat timeline construction\n- **Splunk UBA**: Behavioral analytics add-on for Splunk providing pre-built authentication anomaly models and risk scoring\n- **Elastic SIEM ML Jobs**: Machine learning anomaly detection jobs for authentication log analysis in the Elastic Stack\n\n## Common Scenarios\n\n### Scenario: Detecting Compromised Executive Account After Password Spray\n\n**Context**: SOC observes a spike in failed authentication attempts from a cloud VPS IP address targeting 200+ accounts. Two hours later, an executive account shows successful authentication from the same IP range followed by mailbox rule creation and data exfiltration.\n\n**Approach**:\n1. Run password spray detection across the timeframe to identify all targeted accounts\n2. Cross-reference targeted accounts with subsequent successful logins from related IP ranges\n3. Build behavioral baseline for the executive account and flag all deviations\n4. Check for impossible travel between the executive's last legitimate login and the attacker's session\n5. Identify post-compromise activity: mailbox rules, file downloads, delegated access changes\n6. Calculate composite risk score combining password spray, new IP, off-hours login, and new device signals\n7. Trigger automated response: force session termination, disable account, notify manager\n\n**Pitfalls**:\n- Relying on single-signal detection (failed logins only) misses successful spray results\n- Not correlating across identity providers when users have accounts in multiple IdPs\n- Static thresholds that do not account for legitimate VPN IP changes or travel\n- Ignoring successful authentications after the spray window closes (attackers may wait before using credentials)\n\n## Output Format\n\n```\nAUTHENTICATION ANOMALY DETECTION REPORT\n=========================================\nAnalysis Period:   2026-02-01 to 2026-02-24\nTotal Auth Events: 2,847,392\nUsers Monitored:   3,847\nAlert Sources:     Azure AD, Okta, Windows AD\n\nTHREAT DETECTION SUMMARY\nPassword Spray Attacks:    3\nBrute Force Attacks:       12\nImpossible Travel:         8\nCredential Stuffing:       1\nBehavioral Anomalies:      47\n\nHIGH-RISK ACCOUNTS\n[CRITICAL] j.smith@corp.com     Score: 92\n  - Impossible travel: Chicago -> Moscow (7,876 km in 0.5h)\n  - Password spray target followed by successful login\n  - New device and browser fingerprint\n  - Off-hours access to SharePoint and email\n  Action: Account suspended, SOC investigation initiated\n\n[HIGH] m.johnson@corp.com       Score: 67\n  - Login from new country (Brazil)\n  - New source IP not matching VPN ranges\n  - Access to HR application outside normal pattern\n  Action: MFA re-enrollment required, manager notified\n\n[MEDIUM] a.williams@corp.com    Score: 38\n  - Weekend login at 03:00 UTC\n  - New device (Linux, typically Windows user)\n  Action: Step-up authentication applied\n\nATTACK CAMPAIGN DETAILS\nPassword Spray Campaign #1:\n  Source:            185.220.101.x\u002F24 (Tor exit node)\n  Targeted Users:    247\n  Success Rate:      0.8% (2 accounts compromised)\n  Compromised:       j.smith@corp.com, r.davis@corp.com\n  Duration:          45 minutes\n  Pattern:           2 attempts per user, 3-second interval\n```\n","# Detecting Anomalous Authentication Patterns\n\n## When to Use\n\n- Security operations needs to identify compromised accounts from authentication log analysis\n- Implementing impossible travel detection to flag geographically inconsistent logins\n- Detecting brute force, password spraying, and credential stuffing attacks in real time\n- Building behavioral baselines for users to identify deviations indicating account compromise\n- Correlating authentication anomalies with threat intelligence for lateral movement detection\n- Investigating alerts from SIEM or IdP for suspicious sign-in activity\n\n**Do not use** for static rule-based alerting on single failed logins; anomaly detection requires statistical baselines across time and entity dimensions to reduce false positives.\n\n## Prerequisites\n\n- Authentication log sources (Azure AD\u002FEntra ID sign-in logs, Okta system logs, Active Directory event logs 4624\u002F4625\u002F4648\u002F4768\u002F4771)\n- SIEM platform (Splunk, Microsoft Sentinel, Elastic SIEM) with at least 90 days of baseline data\n- GeoIP database for location-based anomaly detection (MaxMind GeoLite2 or IP2Location)\n- Python 3.9+ with pandas, scikit-learn, and scipy for custom analytics\n- User identity context (department, role, typical work hours, location)\n\n## Workflow\n\n### Step 1: Collect and Normalize Authentication Logs\n\nAggregate authentication events from all identity sources:\n\n```python\nimport pandas as pd\nimport json\nfrom datetime import datetime, timedelta\nfrom collections import defaultdict\n\n# Parse authentication logs from multiple sources\ndef normalize_auth_logs(log_source, raw_logs):\n    \"\"\"Normalize authentication events to a common schema.\"\"\"\n    normalized = []\n\n    for event in raw_logs:\n        if log_source == \"azure_ad\":\n            normalized.append({\n                \"timestamp\": event[\"createdDateTime\"],\n                \"user\": event[\"userPrincipalName\"],\n                \"source_ip\": event[\"ipAddress\"],\n                \"location\": {\n                    \"city\": event.get(\"location\", {}).get(\"city\"),\n                    \"state\": event.get(\"location\", {}).get(\"state\"),\n                    \"country\": event.get(\"location\", {}).get(\"countryOrRegion\"),\n                    \"lat\": event.get(\"location\", {}).get(\"geoCoordinates\", {}).get(\"latitude\"),\n                    \"lon\": event.get(\"location\", {}).get(\"geoCoordinates\", {}).get(\"longitude\")\n                },\n                \"result\": \"success\" if event[\"status\"][\"errorCode\"] == 0 else \"failure\",\n                \"failure_reason\": event[\"status\"].get(\"failureReason\", \"\"),\n                \"app\": event.get(\"appDisplayName\", \"Unknown\"),\n                \"device\": event.get(\"deviceDetail\", {}).get(\"operatingSystem\", \"Unknown\"),\n                \"browser\": event.get(\"deviceDetail\", {}).get(\"browser\", \"Unknown\"),\n                \"mfa_result\": event.get(\"authenticationDetails\", [{}])[0].get(\"succeeded\", None),\n                \"risk_level\": event.get(\"riskLevelDuringSignIn\", \"none\"),\n                \"client_app\": event.get(\"clientAppUsed\", \"Unknown\"),\n                \"source\": \"azure_ad\"\n            })\n        elif log_source == \"okta\":\n            normalized.append({\n                \"timestamp\": event[\"published\"],\n                \"user\": event[\"actor\"][\"alternateId\"],\n                \"source_ip\": event[\"client\"][\"ipAddress\"],\n                \"location\": {\n                    \"city\": event[\"client\"].get(\"geographicalContext\", {}).get(\"city\"),\n                    \"state\": event[\"client\"].get(\"geographicalContext\", {}).get(\"state\"),\n                    \"country\": event[\"client\"].get(\"geographicalContext\", {}).get(\"country\"),\n                    \"lat\": event[\"client\"].get(\"geographicalContext\", {}).get(\"geolocation\", {}).get(\"lat\"),\n                    \"lon\": event[\"client\"].get(\"geographicalContext\", {}).get(\"geolocation\", {}).get(\"lon\")\n                },\n                \"result\": \"success\" if event[\"outcome\"][\"result\"] == \"SUCCESS\" else \"failure\",\n                \"failure_reason\": event[\"outcome\"].get(\"reason\", \"\"),\n                \"app\": event.get(\"target\", [{}])[0].get(\"displayName\", \"Unknown\"),\n                \"device\": event[\"client\"].get(\"device\", \"Unknown\"),\n                \"browser\": event[\"client\"].get(\"userAgent\", {}).get(\"browser\", \"Unknown\"),\n                \"source\": \"okta\"\n            })\n        elif log_source == \"windows_ad\":\n            normalized.append({\n                \"timestamp\": event[\"TimeCreated\"],\n                \"user\": event[\"TargetUserName\"],\n                \"source_ip\": event.get(\"IpAddress\", \"\"),\n                \"location\": None,  # Requires GeoIP enrichment\n                \"result\": \"success\" if event[\"EventId\"] in [4624, 4648] else \"failure\",\n                \"failure_reason\": event.get(\"FailureReason\", \"\"),\n                \"logon_type\": event.get(\"LogonType\", \"\"),\n                \"source\": \"windows_ad\"\n            })\n\n    return pd.DataFrame(normalized)\n\n# Enrich with GeoIP data for Windows AD logs missing location\nimport geoip2.database\n\ndef enrich_geoip(df, geoip_db_path=\"\u002Fopt\u002Fgeoip\u002FGeoLite2-City.mmdb\"):\n    \"\"\"Add geolocation data to events missing location information.\"\"\"\n    reader = geoip2.database.Reader(geoip_db_path)\n\n    for idx, row in df.iterrows():\n        if row[\"location\"] is None and row[\"source_ip\"]:\n            try:\n                response = reader.city(row[\"source_ip\"])\n                df.at[idx, \"location\"] = {\n                    \"city\": response.city.name,\n                    \"country\": response.country.iso_code,\n                    \"lat\": response.location.latitude,\n                    \"lon\": response.location.longitude\n                }\n            except Exception:\n                pass\n\n    reader.close()\n    return df\n```\n\n### Step 2: Detect Impossible Travel Anomalies\n\nIdentify logins from geographically impossible locations:\n\n```python\nfrom math import radians, sin, cos, sqrt, atan2\nfrom datetime import datetime\n\ndef haversine_distance(lat1, lon1, lat2, lon2):\n    \"\"\"Calculate great-circle distance between two points in km.\"\"\"\n    R = 6371  # Earth's radius in kilometers\n\n    lat1, lon1, lat2, lon2 = map(radians, [lat1, lon1, lat2, lon2])\n    dlat = lat2 - lat1\n    dlon = lon2 - lon1\n\n    a = sin(dlat\u002F2)**2 + cos(lat1) * cos(lat2) * sin(dlon\u002F2)**2\n    c = 2 * atan2(sqrt(a), sqrt(1-a))\n\n    return R * c\n\ndef detect_impossible_travel(df, max_speed_kmh=900):\n    \"\"\"\n    Detect impossible travel events where a user authenticates from\n    two locations faster than physically possible.\n\n    max_speed_kmh: Maximum realistic travel speed (900 km\u002Fh ~= commercial flight)\n    \"\"\"\n    alerts = []\n\n    # Sort by user and timestamp\n    df_sorted = df.sort_values([\"user\", \"timestamp\"])\n\n    for user, user_events in df_sorted.groupby(\"user\"):\n        successful_events = user_events[user_events[\"result\"] == \"success\"]\n\n        for i in range(1, len(successful_events)):\n            prev = successful_events.iloc[i-1]\n            curr = successful_events.iloc[i]\n\n            # Skip if location data is missing\n            if not prev.get(\"location\") or not curr.get(\"location\"):\n                continue\n            if not prev[\"location\"].get(\"lat\") or not curr[\"location\"].get(\"lat\"):\n                continue\n\n            # Calculate distance and time delta\n            distance_km = haversine_distance(\n                prev[\"location\"][\"lat\"], prev[\"location\"][\"lon\"],\n                curr[\"location\"][\"lat\"], curr[\"location\"][\"lon\"]\n            )\n\n            time_diff = (pd.Timestamp(curr[\"timestamp\"]) -\n                        pd.Timestamp(prev[\"timestamp\"])).total_seconds() \u002F 3600\n\n            if time_diff \u003C= 0:\n                continue\n\n            required_speed = distance_km \u002F time_diff\n\n            # Flag if required speed exceeds maximum realistic travel\n            if required_speed > max_speed_kmh and distance_km > 100:\n                alerts.append({\n                    \"alert_type\": \"IMPOSSIBLE_TRAVEL\",\n                    \"severity\": \"HIGH\",\n                    \"user\": user,\n                    \"timestamp\": curr[\"timestamp\"],\n                    \"details\": {\n                        \"location_1\": f\"{prev['location']['city']}, {prev['location']['country']}\",\n                        \"location_2\": f\"{curr['location']['city']}, {curr['location']['country']}\",\n                        \"time_1\": prev[\"timestamp\"],\n                        \"time_2\": curr[\"timestamp\"],\n                        \"distance_km\": round(distance_km, 1),\n                        \"time_hours\": round(time_diff, 2),\n                        \"required_speed_kmh\": round(required_speed, 1),\n                        \"source_ip_1\": prev[\"source_ip\"],\n                        \"source_ip_2\": curr[\"source_ip\"]\n                    }\n                })\n\n    return alerts\n\n# Run impossible travel detection\ntravel_alerts = detect_impossible_travel(auth_df)\nprint(f\"Impossible travel alerts: {len(travel_alerts)}\")\nfor alert in travel_alerts:\n    print(f\"  [{alert['severity']}] {alert['user']}: \"\n          f\"{alert['details']['location_1']} -> {alert['details']['location_2']} \"\n          f\"({alert['details']['distance_km']} km in {alert['details']['time_hours']}h)\")\n```\n\n### Step 3: Detect Brute Force and Password Spraying\n\nIdentify credential attack patterns across authentication logs:\n\n```python\nfrom collections import Counter\n\ndef detect_brute_force(df, threshold_failures=10, window_minutes=10):\n    \"\"\"\n    Detect brute force attacks: many failed attempts against\n    a single account in a short time window.\n    \"\"\"\n    alerts = []\n    failed = df[df[\"result\"] == \"failure\"].copy()\n    failed[\"timestamp\"] = pd.to_datetime(failed[\"timestamp\"])\n\n    for user, user_fails in failed.groupby(\"user\"):\n        user_fails_sorted = user_fails.sort_values(\"timestamp\")\n\n        # Sliding window analysis\n        for i, row in user_fails_sorted.iterrows():\n            window_start = row[\"timestamp\"]\n            window_end = window_start + timedelta(minutes=window_minutes)\n\n            window_events = user_fails_sorted[\n                (user_fails_sorted[\"timestamp\"] >= window_start) &\n                (user_fails_sorted[\"timestamp\"] \u003C= window_end)\n            ]\n\n            if len(window_events) >= threshold_failures:\n                source_ips = window_events[\"source_ip\"].unique()\n                alerts.append({\n                    \"alert_type\": \"BRUTE_FORCE\",\n                    \"severity\": \"HIGH\",\n                    \"user\": user,\n                    \"timestamp\": str(window_start),\n                    \"details\": {\n                        \"failed_attempts\": len(window_events),\n                        \"window_minutes\": window_minutes,\n                        \"source_ips\": list(source_ips),\n                        \"distributed\": len(source_ips) > 1,\n                        \"failure_reasons\": dict(Counter(window_events[\"failure_reason\"]))\n                    }\n                })\n                break  # One alert per user per detection pass\n\n    return alerts\n\ndef detect_password_spray(df, threshold_users=10, window_minutes=30):\n    \"\"\"\n    Detect password spraying: failed logins against many different\n    accounts from the same source in a short window (1-2 attempts per user).\n    \"\"\"\n    alerts = []\n    failed = df[df[\"result\"] == \"failure\"].copy()\n    failed[\"timestamp\"] = pd.to_datetime(failed[\"timestamp\"])\n\n    for source_ip, ip_events in failed.groupby(\"source_ip\"):\n        ip_events_sorted = ip_events.sort_values(\"timestamp\")\n\n        for i, row in ip_events_sorted.iterrows():\n            window_start = row[\"timestamp\"]\n            window_end = window_start + timedelta(minutes=window_minutes)\n\n            window_events = ip_events_sorted[\n                (ip_events_sorted[\"timestamp\"] >= window_start) &\n                (ip_events_sorted[\"timestamp\"] \u003C= window_end)\n            ]\n\n            unique_users = window_events[\"user\"].nunique()\n            attempts_per_user = len(window_events) \u002F unique_users if unique_users > 0 else 0\n\n            # Password spray: many users targeted, few attempts per user\n            if unique_users >= threshold_users and attempts_per_user \u003C= 3:\n                # Check if any succeeded (compromised account)\n                success_after = df[\n                    (df[\"source_ip\"] == source_ip) &\n                    (df[\"result\"] == \"success\") &\n                    (pd.to_datetime(df[\"timestamp\"]) > window_start) &\n                    (pd.to_datetime(df[\"timestamp\"]) \u003C window_end + timedelta(hours=1))\n                ]\n\n                alerts.append({\n                    \"alert_type\": \"PASSWORD_SPRAY\",\n                    \"severity\": \"CRITICAL\" if len(success_after) > 0 else \"HIGH\",\n                    \"timestamp\": str(window_start),\n                    \"details\": {\n                        \"source_ip\": source_ip,\n                        \"targeted_users\": unique_users,\n                        \"total_attempts\": len(window_events),\n                        \"avg_attempts_per_user\": round(attempts_per_user, 1),\n                        \"window_minutes\": window_minutes,\n                        \"successful_logins_after\": len(success_after),\n                        \"compromised_accounts\": list(success_after[\"user\"].unique()) if len(success_after) > 0 else []\n                    }\n                })\n                break\n\n    return alerts\n\n# Run detections\nbrute_force_alerts = detect_brute_force(auth_df)\nspray_alerts = detect_password_spray(auth_df)\nprint(f\"Brute force alerts: {len(brute_force_alerts)}\")\nprint(f\"Password spray alerts: {len(spray_alerts)}\")\n```\n\n### Step 4: Build Behavioral Baselines and Detect Deviations\n\nCreate user behavioral profiles and flag statistical anomalies:\n\n```python\nimport numpy as np\nfrom scipy import stats\nfrom sklearn.ensemble import IsolationForest\n\ndef build_user_baseline(df, user, lookback_days=90):\n    \"\"\"Build behavioral baseline for a specific user.\"\"\"\n    user_events = df[df[\"user\"] == user].copy()\n    user_events[\"timestamp\"] = pd.to_datetime(user_events[\"timestamp\"])\n    user_events[\"hour\"] = user_events[\"timestamp\"].dt.hour\n    user_events[\"day_of_week\"] = user_events[\"timestamp\"].dt.dayofweek\n\n    baseline = {\n        \"user\": user,\n        \"typical_hours\": {\n            \"start\": int(user_events[\"hour\"].quantile(0.05)),\n            \"end\": int(user_events[\"hour\"].quantile(0.95)),\n            \"mean\": float(user_events[\"hour\"].mean()),\n            \"std\": float(user_events[\"hour\"].std())\n        },\n        \"typical_days\": list(user_events[\"day_of_week\"].mode().values),\n        \"typical_ips\": list(user_events[\"source_ip\"].value_counts().head(10).index),\n        \"typical_locations\": list(\n            user_events[\"location\"].apply(\n                lambda x: x.get(\"country\") if isinstance(x, dict) else None\n            ).dropna().value_counts().head(5).index\n        ),\n        \"typical_apps\": list(user_events[\"app\"].value_counts().head(10).index),\n        \"typical_devices\": list(user_events[\"device\"].value_counts().head(5).index),\n        \"avg_daily_logins\": float(\n            user_events.groupby(user_events[\"timestamp\"].dt.date).size().mean()\n        ),\n        \"std_daily_logins\": float(\n            user_events.groupby(user_events[\"timestamp\"].dt.date).size().std()\n        ),\n        \"failure_rate\": float(\n            (user_events[\"result\"] == \"failure\").mean()\n        )\n    }\n\n    return baseline\n\ndef detect_behavioral_anomalies(event, baseline):\n    \"\"\"Compare a new authentication event against user baseline.\"\"\"\n    anomalies = []\n    event_time = pd.Timestamp(event[\"timestamp\"])\n\n    # Off-hours login detection\n    hour = event_time.hour\n    if baseline[\"typical_hours\"][\"std\"] > 0:\n        z_score = abs(hour - baseline[\"typical_hours\"][\"mean\"]) \u002F baseline[\"typical_hours\"][\"std\"]\n        if z_score > 2.5:\n            anomalies.append({\n                \"type\": \"OFF_HOURS_LOGIN\",\n                \"severity\": \"MEDIUM\",\n                \"detail\": f\"Login at {hour}:00 (baseline: {baseline['typical_hours']['start']}:00-{baseline['typical_hours']['end']}:00)\",\n                \"z_score\": round(z_score, 2)\n            })\n\n    # New source IP\n    if event[\"source_ip\"] not in baseline[\"typical_ips\"]:\n        anomalies.append({\n            \"type\": \"NEW_SOURCE_IP\",\n            \"severity\": \"MEDIUM\",\n            \"detail\": f\"Login from unknown IP: {event['source_ip']}\"\n        })\n\n    # New country\n    if event.get(\"location\") and isinstance(event[\"location\"], dict):\n        country = event[\"location\"].get(\"country\")\n        if country and country not in baseline[\"typical_locations\"]:\n            anomalies.append({\n                \"type\": \"NEW_COUNTRY\",\n                \"severity\": \"HIGH\",\n                \"detail\": f\"Login from new country: {country}\"\n            })\n\n    # New application\n    if event.get(\"app\") and event[\"app\"] not in baseline[\"typical_apps\"]:\n        anomalies.append({\n            \"type\": \"NEW_APPLICATION\",\n            \"severity\": \"LOW\",\n            \"detail\": f\"Access to new application: {event['app']}\"\n        })\n\n    # New device\n    if event.get(\"device\") and event[\"device\"] not in baseline[\"typical_devices\"]:\n        anomalies.append({\n            \"type\": \"NEW_DEVICE\",\n            \"severity\": \"MEDIUM\",\n            \"detail\": f\"Login from new device: {event['device']}\"\n        })\n\n    # Weekend login for weekday-only users\n    if event_time.dayofweek >= 5 and 5 not in baseline[\"typical_days\"] and 6 not in baseline[\"typical_days\"]:\n        anomalies.append({\n            \"type\": \"WEEKEND_LOGIN\",\n            \"severity\": \"LOW\",\n            \"detail\": f\"Weekend login detected (typical days: {baseline['typical_days']})\"\n        })\n\n    return anomalies\n\ndef isolation_forest_anomaly_detection(df):\n    \"\"\"Use Isolation Forest for multivariate anomaly detection.\"\"\"\n    # Feature engineering\n    features_df = df.copy()\n    features_df[\"timestamp\"] = pd.to_datetime(features_df[\"timestamp\"])\n    features_df[\"hour\"] = features_df[\"timestamp\"].dt.hour\n    features_df[\"day_of_week\"] = features_df[\"timestamp\"].dt.dayofweek\n    features_df[\"is_failure\"] = (features_df[\"result\"] == \"failure\").astype(int)\n\n    # Encode categorical features\n    features_df[\"ip_frequency\"] = features_df.groupby(\"source_ip\")[\"source_ip\"].transform(\"count\")\n    features_df[\"user_frequency\"] = features_df.groupby(\"user\")[\"user\"].transform(\"count\")\n\n    feature_columns = [\"hour\", \"day_of_week\", \"is_failure\", \"ip_frequency\", \"user_frequency\"]\n    X = features_df[feature_columns].fillna(0)\n\n    # Train Isolation Forest\n    model = IsolationForest(\n        n_estimators=200,\n        contamination=0.01,  # Expect 1% anomaly rate\n        random_state=42,\n        n_jobs=-1\n    )\n    features_df[\"anomaly_score\"] = model.fit_predict(X)\n    features_df[\"anomaly_probability\"] = model.score_samples(X)\n\n    # Extract anomalies (labeled as -1)\n    anomalies = features_df[features_df[\"anomaly_score\"] == -1]\n\n    return anomalies.sort_values(\"anomaly_probability\")\n```\n\n### Step 5: Implement SIEM Detection Rules\n\nDeploy detection rules for common authentication attack patterns:\n\n```yaml\n# Splunk SPL queries for authentication anomaly detection\n\n# 1. Brute Force Detection\n# name: Authentication Brute Force - Multiple Failed Logins\n# severity: high\nbrute_force_spl: |\n  index=auth sourcetype IN (\"azure:aad:signin\", \"okta:im:log\", \"WinEventLog:Security\")\n  (result=\"failure\" OR EventCode=4625)\n  | bin _time span=10m\n  | stats count as failed_attempts dc(src_ip) as unique_ips\n    values(src_ip) as source_ips\n    latest(_time) as last_attempt\n    by user _time\n  | where failed_attempts >= 10\n  | eval alert_type=if(unique_ips > 3, \"Distributed Brute Force\", \"Standard Brute Force\")\n\n# 2. Password Spray Detection\n# name: Password Spray Attack - Multiple Users Same Source\n# severity: critical\npassword_spray_spl: |\n  index=auth sourcetype IN (\"azure:aad:signin\", \"okta:im:log\")\n  result=\"failure\"\n  | bin _time span=30m\n  | stats dc(user) as targeted_users count as total_attempts\n    values(user) as users_targeted\n    by src_ip _time\n  | where targeted_users >= 10\n  | eval attempts_per_user = round(total_attempts \u002F targeted_users, 1)\n  | where attempts_per_user \u003C= 3\n  | eval severity=if(targeted_users > 50, \"CRITICAL\", \"HIGH\")\n\n# 3. Impossible Travel Detection\n# name: Impossible Travel - Geographically Inconsistent Logins\n# severity: high\nimpossible_travel_spl: |\n  index=auth result=\"success\"\n  | iplocation src_ip\n  | sort user _time\n  | streamstats current=f last(lat) as prev_lat last(lon) as prev_lon\n    last(_time) as prev_time last(City) as prev_city last(Country) as prev_country\n    by user\n  | where isnotnull(prev_lat) AND isnotnull(lat)\n  | eval distance_km = 6371 * 2 * asin(sqrt(\n      pow(sin((lat - prev_lat) * pi() \u002F 360), 2) +\n      cos(prev_lat * pi() \u002F 180) * cos(lat * pi() \u002F 180) *\n      pow(sin((lon - prev_lon) * pi() \u002F 360), 2)))\n  | eval time_hours = (_time - prev_time) \u002F 3600\n  | eval required_speed = distance_km \u002F time_hours\n  | where required_speed > 900 AND distance_km > 100\n\n# 4. Credential Stuffing Detection\n# name: Credential Stuffing - High Volume Failed Logins with Some Successes\n# severity: critical\ncredential_stuffing_spl: |\n  index=auth\n  | bin _time span=1h\n  | stats count(eval(result=\"failure\")) as failures\n    count(eval(result=\"success\")) as successes\n    dc(user) as unique_users\n    dc(src_ip) as unique_ips\n    by src_ip _time\n  | where failures > 100 AND successes > 0 AND unique_users > 20\n  | eval success_rate = round(successes \u002F (failures + successes) * 100, 2)\n  | where success_rate \u003C 5\n```\n\n### Step 6: Correlate and Score Authentication Anomalies\n\nCombine multiple detection signals into risk scores:\n\n```python\ndef calculate_auth_risk_score(user, alerts, baseline):\n    \"\"\"\n    Calculate composite risk score for authentication events.\n    Combines multiple anomaly signals with weighted scoring.\n    \"\"\"\n    score = 0\n    risk_factors = []\n\n    weights = {\n        \"IMPOSSIBLE_TRAVEL\": 40,\n        \"PASSWORD_SPRAY\": 35,\n        \"BRUTE_FORCE\": 30,\n        \"CREDENTIAL_STUFFING\": 35,\n        \"NEW_COUNTRY\": 25,\n        \"OFF_HOURS_LOGIN\": 15,\n        \"NEW_SOURCE_IP\": 10,\n        \"NEW_DEVICE\": 10,\n        \"NEW_APPLICATION\": 5,\n        \"WEEKEND_LOGIN\": 5,\n        \"MFA_BYPASS\": 45,\n        \"LEGACY_PROTOCOL\": 20\n    }\n\n    for alert in alerts:\n        alert_type = alert.get(\"type\") or alert.get(\"alert_type\")\n        weight = weights.get(alert_type, 10)\n\n        # Adjust weight based on severity\n        severity_multiplier = {\n            \"CRITICAL\": 2.0,\n            \"HIGH\": 1.5,\n            \"MEDIUM\": 1.0,\n            \"LOW\": 0.5\n        }\n        severity = alert.get(\"severity\", \"MEDIUM\")\n        adjusted_weight = weight * severity_multiplier.get(severity, 1.0)\n\n        score += adjusted_weight\n        risk_factors.append({\n            \"factor\": alert_type,\n            \"weight\": adjusted_weight,\n            \"detail\": alert.get(\"detail\", alert.get(\"details\", \"\"))\n        })\n\n    # Normalize score to 0-100\n    normalized_score = min(100, score)\n\n    # Determine risk level\n    if normalized_score >= 80:\n        risk_level = \"CRITICAL\"\n        recommended_action = \"Immediate account suspension and investigation\"\n    elif normalized_score >= 60:\n        risk_level = \"HIGH\"\n        recommended_action = \"Force MFA re-enrollment and notify SOC\"\n    elif normalized_score >= 40:\n        risk_level = \"MEDIUM\"\n        recommended_action = \"Require step-up authentication\"\n    elif normalized_score >= 20:\n        risk_level = \"LOW\"\n        recommended_action = \"Monitor and log for trend analysis\"\n    else:\n        risk_level = \"INFORMATIONAL\"\n        recommended_action = \"No action required\"\n\n    return {\n        \"user\": user,\n        \"risk_score\": normalized_score,\n        \"risk_level\": risk_level,\n        \"recommended_action\": recommended_action,\n        \"risk_factors\": sorted(risk_factors, key=lambda x: x[\"weight\"], reverse=True),\n        \"timestamp\": datetime.utcnow().isoformat()\n    }\n```\n\n## Key Concepts\n\n| Term | Definition |\n|------|------------|\n| **Impossible Travel** | Authentication anomaly where a user logs in from two geographically distant locations within a timeframe that makes physical travel impossible |\n| **Password Spraying** | Credential attack that tries a small number of commonly used passwords against many accounts to avoid lockout thresholds |\n| **Credential Stuffing** | Automated attack using stolen username\u002Fpassword pairs from data breaches to gain unauthorized access to accounts |\n| **UEBA** | User and Entity Behavior Analytics technology that builds behavioral baselines and detects deviations using machine learning and statistical analysis |\n| **Behavioral Baseline** | Statistical profile of a user's normal authentication patterns including typical hours, locations, devices, and applications |\n| **Isolation Forest** | Unsupervised machine learning algorithm that detects anomalies by isolating observations that differ from the majority of data points |\n| **Risk Score** | Composite numerical value aggregating multiple anomaly signals with weighted scoring to prioritize authentication threats |\n\n## Tools & Systems\n\n- **Microsoft Sentinel UEBA**: Cloud-native SIEM with built-in entity behavior analytics for Azure AD and multi-cloud authentication anomaly detection\n- **Exabeam Advanced Analytics**: UEBA platform using machine learning for user session analysis and automated threat timeline construction\n- **Splunk UBA**: Behavioral analytics add-on for Splunk providing pre-built authentication anomaly models and risk scoring\n- **Elastic SIEM ML Jobs**: Machine learning anomaly detection jobs for authentication log analysis in the Elastic Stack\n\n## Common Scenarios\n\n### Scenario: Detecting Compromised Executive Account After Password Spray\n\n**Context**: SOC observes a spike in failed authentication attempts from a cloud VPS IP address targeting 200+ accounts. Two hours later, an executive account shows successful authentication from the same IP range followed by mailbox rule creation and data exfiltration.\n\n**Approach**:\n1. Run password spray detection across the timeframe to identify all targeted accounts\n2. Cross-reference targeted accounts with subsequent successful logins from related IP ranges\n3. Build behavioral baseline for the executive account and flag all deviations\n4. Check for impossible travel between the executive's last legitimate login and the attacker's session\n5. Identify post-compromise activity: mailbox rules, file downloads, delegated access changes\n6. Calculate composite risk score combining password spray, new IP, off-hours login, and new device signals\n7. Trigger automated response: force session termination, disable account, notify manager\n\n**Pitfalls**:\n- Relying on single-signal detection (failed logins only) misses successful spray results\n- Not correlating across identity providers when users have accounts in multiple IdPs\n- Static thresholds that do not account for legitimate VPN IP changes or travel\n- Ignoring successful authentications after the spray window closes (attackers may wait before using credentials)\n\n## Output Format\n\n```\nAUTHENTICATION ANOMALY DETECTION REPORT\n=========================================\nAnalysis Period:   2026-02-01 to 2026-02-24\nTotal Auth Events: 2,847,392\nUsers Monitored:   3,847\nAlert Sources:     Azure AD, Okta, Windows AD\n\nTHREAT DETECTION SUMMARY\nPassword Spray Attacks:    3\nBrute Force Attacks:       12\nImpossible Travel:         8\nCredential Stuffing:       1\nBehavioral Anomalies:      47\n\nHIGH-RISK ACCOUNTS\n[CRITICAL] j.smith@corp.com     Score: 92\n  - Impossible travel: Chicago -> Moscow (7,876 km in 0.5h)\n  - Password spray target followed by successful login\n  - New device and browser fingerprint\n  - Off-hours access to SharePoint and email\n  Action: Account suspended, SOC investigation initiated\n\n[HIGH] m.johnson@corp.com       Score: 67\n  - Login from new country (Brazil)\n  - New source IP not matching VPN ranges\n  - Access to HR application outside normal pattern\n  Action: MFA re-enrollment required, manager notified\n\n[MEDIUM] a.williams@corp.com    Score: 38\n  - Weekend login at 03:00 UTC\n  - New device (Linux, typically Windows user)\n  Action: Step-up authentication applied\n\nATTACK CAMPAIGN DETAILS\nPassword Spray Campaign #1:\n  Source:            185.220.101.x\u002F24 (Tor exit node)\n  Targeted Users:    247\n  Success Rate:      0.8% (2 accounts compromised)\n  Compromised:       j.smith@corp.com, r.davis@corp.com\n  Duration:          45 minutes\n  Pattern:           2 attempts per user, 3-second interval\n```\n",{"name":5,"tags":54,"author":55,"domain":48,"license":15,"version":56,"mitre_f3":57,"nist_csf":80,"subdomain":85,"description":86,"nist_ai_rmf":87,"mitre_attack":91,"atlas_techniques":95},[40,39,38,37,36,35],"mahipal","1.0",{"tactics":58,"version":61,"techniques":62},[59,60],"initial-access","positioning","1.1",[63,67,70,74,77],{"id":64,"name":65,"source":66,"tactic":59},"T1110.004","Brute Force:  Credential Stuffing","attack",{"id":68,"name":69,"source":66,"tactic":59},"T1110.003","Brute Force: Password Spraying",{"id":71,"name":72,"source":73,"tactic":59},"F1006","Account Takeover","f3",{"id":75,"name":76,"source":73,"tactic":59},"F1006.002","Account Takeover: Exposed Login Credential",{"id":78,"name":79,"source":66,"tactic":60},"T1539","Steal Web Session Cookie",[81,82,83,84],"PR.AA-01","PR.AA-02","PR.AA-05","PR.AA-06","identity-access-management","Detects anomalous authentication patterns using UEBA analytics, statistical baselines, and machine learning models to identify impossible travel, credential stuffing, brute force, password spraying, and compromised account behaviors across authentication logs. Activates for requests involving authentication anomaly detection, login behavior analysis, UEBA implementation, or suspicious sign-in investigation.\n",[88,89,90],"MEASURE-2.7","MEASURE-2.5","MAP-5.1",[92,68,64,93,94],"T1110","T1078","T1021",[96,97],"AML.T0043","AML.T0018","main","54a798831d2266a3ca61ce68a7acb80b81160d57","skills\u002Fdetecting-anomalous-authentication-patterns",4414,"https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills","https:\u002F\u002Fmahipal.engineer\u002FAnthropic-Cybersecurity-Skills\u002F","https:\u002F\u002Fgithub.com\u002Fmukul975","Mahipal.engineer","🔐 Cybersecurity | 💻 Dev | 📷 Street Photographer\r\n🎓 MSc | 📚 Research & AI Security","2026-08-31 12:32:44",{"source":8,"skillName":5,"commands":109,"prompt":119,"zipAvailable":120},[110,113,116],{"tool":111,"command":112},"npx","npx skills add mukul975\u002FAnthropic-Cybersecurity-Skills --skill detecting-anomalous-authentication-patterns",{"tool":114,"command":115},"bunx","bunx skills add mukul975\u002FAnthropic-Cybersecurity-Skills --skill detecting-anomalous-authentication-patterns",{"tool":117,"command":118},"pnpm","pnpm dlx skills add mukul975\u002FAnthropic-Cybersecurity-Skills --skill detecting-anomalous-authentication-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fdetecting-anomalous-authentication-patterns\u002FSKILL.md",true,[122,128,132,136,140,144,149,153,159],{"path":123,"resourceType":124,"resourceTypeDesc":125,"sizeBytes":126,"sourceHtmlUrl":127},"agents\u002Fopenai.yaml","REFERENCE","参考文档",152,"https:\u002F\u002Fgithub.com\u002Fhareki\u002Fdotfiles\u002Fblob\u002Fmain\u002Fagents\u002F.agents\u002Fskills\u002Fsetup-matt-pocock-skills\u002Fagents\u002Fopenai.yaml",{"path":129,"resourceType":124,"resourceTypeDesc":125,"sizeBytes":130,"sourceHtmlUrl":131},"domain.md",2042,"https:\u002F\u002Fgithub.com\u002Fhareki\u002Fdotfiles\u002Fblob\u002Fmain\u002Fagents\u002F.agents\u002Fskills\u002Fsetup-matt-pocock-skills\u002Fdomain.md",{"path":133,"resourceType":124,"resourceTypeDesc":125,"sizeBytes":134,"sourceHtmlUrl":135},"issue-tracker-github.md",5082,"https:\u002F\u002Fgithub.com\u002Fhareki\u002Fdotfiles\u002Fblob\u002Fmain\u002Fagents\u002F.agents\u002Fskills\u002Fsetup-matt-pocock-skills\u002Fissue-tracker-github.md",{"path":137,"resourceType":124,"resourceTypeDesc":125,"sizeBytes":138,"sourceHtmlUrl":139},"issue-tracker-gitlab.md",3979,"https:\u002F\u002Fgithub.com\u002Fhareki\u002Fdotfiles\u002Fblob\u002Fmain\u002Fagents\u002F.agents\u002Fskills\u002Fsetup-matt-pocock-skills\u002Fissue-tracker-gitlab.md",{"path":141,"resourceType":124,"resourceTypeDesc":125,"sizeBytes":142,"sourceHtmlUrl":143},"issue-tracker-local.md",1810,"https:\u002F\u002Fgithub.com\u002Fhareki\u002Fdotfiles\u002Fblob\u002Fmain\u002Fagents\u002F.agents\u002Fskills\u002Fsetup-matt-pocock-skills\u002Fissue-tracker-local.md",{"path":145,"resourceType":145,"resourceTypeDesc":146,"sizeBytes":147,"sourceHtmlUrl":148},"LICENSE","许可证",11255,"https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fdetecting-anomalous-authentication-patterns\u002FLICENSE",{"path":150,"resourceType":124,"resourceTypeDesc":125,"sizeBytes":151,"sourceHtmlUrl":152},"references\u002Fapi-reference.md",2378,"https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fdetecting-anomalous-authentication-patterns\u002Freferences\u002Fapi-reference.md",{"path":154,"resourceType":155,"resourceTypeDesc":156,"sizeBytes":157,"sourceHtmlUrl":158},"scripts\u002Fagent.py","SCRIPT","脚本",8777,"https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fdetecting-anomalous-authentication-patterns\u002Fscripts\u002Fagent.py",{"path":160,"resourceType":124,"resourceTypeDesc":125,"sizeBytes":161,"sourceHtmlUrl":162},"triage-labels.md",1057,"https:\u002F\u002Fgithub.com\u002Fhareki\u002Fdotfiles\u002Fblob\u002Fmain\u002Fagents\u002F.agents\u002Fskills\u002Fsetup-matt-pocock-skills\u002Ftriage-labels.md",[164,189,213,240,265,292],{"skillNo":165,"name":166,"nameZh":6,"description":167,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":168,"categories":169,"keywords":171,"publishedAt":49},"01M6AGDM3HJXTKXX15ZZ0ZVCJ3","verifying-build-provenance-with-slsa-sigstore","Verifies artifact signatures and SLSA provenance using Sigstore's cosign (verify, verify-attestation, verify-blob-attestation) and slsa-verifier (verify-artifact), enforcing keyless OIDC builder identity and source repo against SLSA Build levels. Use in CI\u002FCD before deploying artifacts, when consuming third-party attestations, establishing a SLSA Build L3 pipeline, or confirming provenance during incident response or admission control.","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fverifying-build-provenance-with-slsa-sigstore\u002FSKILL.md",[170],{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[172,173,174,175,176,48,177,45,43,178,179,180,181,182,183,184,185,186,187,188],"sigstore","provenance","slsa","verifying build provenance with slsa sigstore","security","incident response","code","artifacts","ci","supply-chain","pipeline","supply-chain-security","t1195","attestation","code-signing","cosign","keyless",{"skillNo":190,"name":191,"nameZh":6,"description":192,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":193,"categories":194,"keywords":196,"publishedAt":49},"01M6AGDGBPWYVZ2F11GFKJ4HZ9","validating-tpm-measured-boot-attestation","Verifies TPM 2.0 measured-boot integrity and remote attestation with tpm2-tools -- reading PCRs (tpm2_pcrread), replaying the boot event log, generating and checking signed quotes (tpm2_quote\u002Ftpm2_checkquote), and sealing secrets to a PCR policy. Use to confirm a system booted trusted firmware\u002Fkernel for Zero Trust device posture, detect boot-chain tampering via PCR drift, or build a golden-value baseline for fleet attestation.","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fvalidating-tpm-measured-boot-attestation\u002FSKILL.md",[195],{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[197,185,198,199,176,200,48,43,201,202,203,204,205,206,207,208,209,210,211,212],"boot","TPM","validating tpm measured boot attestation","policy","verification","ZeRO","firmware","Tools","measured-boot","PCR","integrity","secrets","remote-attestation","tpm2-tools","integrity-verification","trusted-computing",{"skillNo":214,"name":215,"nameZh":6,"description":216,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":217,"categories":218,"keywords":223,"publishedAt":49},"01M6AGDCW0Y4FXZ3362GT1941M","validating-backup-integrity-for-recovery","Validates backup integrity through cryptographic hash verification, automated restore testing, corruption detection, and recoverability checks to confirm backups are reliable for disaster recovery and ransomware response. Use before relying on backups for recovery, when building post-backup validation pipelines, auditing backup infrastructure for compliance, or checking immutable\u002Fair-gapped backups for silent corruption or tampering.","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fvalidating-backup-integrity-for-recovery\u002FSKILL.md",[219,222],{"categoryNo":220,"categoryName":221,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000008","测试与质量",{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[207,224,225,226,227,48,228,229,201,230,231,232,233,234,41,235,236,237,238,239],"backup","recovery","validating backup integrity for recovery","testing","infrastructure","validation","compliance","hash-verification","incident-response","ransomware","cryptocurrency","t1078","t1490","immutable","disaster-recovery","restore-testing",{"skillNo":241,"name":242,"nameZh":6,"description":243,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":244,"categories":245,"keywords":247,"publishedAt":49},"01M6AGD9GBG2KZ336AE763J3WH","triaging-windows-with-kape","Runs KAPE (Kroll Artifact Parser and Extractor) to collect targeted forensic artifacts (registry hives, $MFT, event logs, prefetch, browser data) via Targets and parse them with Modules wrapping Eric Zimmerman's EZ Tools (PECmd, MFTECmd, RECmd). Use during early incident containment\u002Ftriage when full disk imaging is impractical but a defensible, parseable Windows artifact set is needed quickly, including at-scale remote collection.","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Ftriaging-windows-with-kape\u002FSKILL.md",[246],{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[248,249,250,48,251,252,34,253,254,255,256,257,258,259,260,261,204,262,263,264],"windows","kape","triaging windows with kape","registry","browser","windows-forensics","dfir","mft","mftecmd","data","prefetch","eric-zimmerman","digital-forensics","SET","collection","pecmd","artifact-collection",{"skillNo":266,"name":267,"nameZh":6,"description":268,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":269,"categories":270,"keywords":272,"publishedAt":49},"01M6AGD5PW5J4EVZM958WD74ZQ","triaging-vulnerabilities-with-ssvc-framework","Triages and prioritizes vulnerabilities with CISA's Stakeholder-Specific Vulnerability Categorization (SSVC) decision tree, weighing exploitation status (via the CISA KEV catalog and FIRST EPSS API), technical impact, automatability, and mission prevalence to output Track\u002FTrack*\u002FAttend\u002FAct decisions. Use when prioritizing vulnerability scan results (OpenVAS, Nessus, Qualys) for remediation planning beyond raw CVSS scores.","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Ftriaging-vulnerabilities-with-ssvc-framework\u002FSKILL.md",[271],{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[273,274,275,48,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291],"vulnerabilities","framework","triaging vulnerabilities with ssvc framework","status","planning","CISA","vulnerability-management","risk-management","nessus","qualys","openvas","cvss","remediation","risk","vulnerability","api","prioritization","ssvc","decision-tree",{"skillNo":293,"name":294,"nameZh":6,"description":295,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":296,"categories":297,"keywords":299,"publishedAt":49},"01M6AGD24TTQQM4CXG69E3B9TJ","triaging-security-incident","Performs initial triage of security incidents using the NIST SP 800-61r3 and SANS PICERL frameworks, classifying incident type, assigning priority by business impact, and routing to the appropriate response team. Use when a SIEM\u002FEDR alert needs human classification, concurrent alerts must be prioritized, or a user report or threat-intel IOC match requires initial incident categorization.","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Ftriaging-security-incident\u002FSKILL.md",[298],{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[176,300,48,301,302,303,304,305,306,307,308,235,309,236,310,311,312,313,314,315],"triaging security incident","siem","file","ioc","soc","NIST-800-61","NIST","severity","edr","execution","analysis","classification","severity-classification","incident-triage","SANS-PICERL","SOC-operations"]