Спарринг улья: две локальные модели спорят о защите Linux
🛰️ Орбита
Академия Starbound · Киберзащита · Около 25 минут
В улей не пускают того, кто только кажется пчелой. То же должно быть и с вашей командной оболочкой (shell).
1. Цель упражнения
Запустите две локальные языковые модели как спарринг-партнёров — узел-01 (Phi) и узел-02 (R Eng) — вокруг одного вопроса: как защиты пчелиной семьи соотносятся с укреплением Linux и с реагированием на инциденты (incident response, IR)?
Что вы здесь отрабатываете:
Превращать аналогию в конкретные, проверяемые команды. «Сторожевые пчёлы», например, становятся летком Secure Shell (SSH) со списком разрешённых пользователей.
Держать спор больших языковых моделей (large language models, LLM) незамкнутым: настройками выборки, сжатым системным запросом (system prompt) и периодической перенастройкой.
Никогда не пускать вывод модели в оболочку без проверки. Каждая команда проходит через шлюз проверки, прежде чем выполниться.
Карта соответствий, с которой узлы начинают:
Защита улья
Соответствие в Linux и в реагировании на инциденты
Наблюдение за здоровьем машины: температура и нагрузка
2. Устройство
┌─────────────┐ prompt/round ┌──────────────────────────┐
│ bhda-spar.sh│ ───────────────► │ llama-server (local) │
│ (bash loop)│ ◄─────────────── │ qwen2.5-coder-7b, :8080 │
└─────┬───────┘ reply (text) └──────────────────────────┘
│ extract fenced bash blocks
▼
┌─────────────┐ RO / ACT tag ┌──────────────────────────┐
│ classifier │ ───────────────► │ print_plan (ASCII table) │
└─────┬───────┘ └────────────┬─────────────┘
▼ ▼
┌──────────────────────────────────────────────────────────┐
│ validator gate: a person reads the plan, approves each │
│ step (y/N), and only then does run_with_gate execute it │
└──────────────────────────────────────────────────────────┘
Хост: машина без внешней сети на время запуска. Модель, сценарий и журналы остаются на этой машине.
Сервер модели:llama-server из проекта llama.cpp подаёт модель qwen2.5-coder-7b через совместимую с OpenAI точку /v1/chat/completions на локальном узле (localhost) [15]. В текущем руководстве сервера по умолчанию указан адрес 127.0.0.1:9931. В примерах ниже заданы --host 127.0.0.1 --port 8080, чтобы сценарий и сервер совпали.
Две роли, одна модель: узел-01 и узел-02 — это системные запросы, а не две отдельные модели. Они ходят по очереди, и каждый видит последний ответ другого.
Шлюз проверки: ничего из ответа модели не выполняется, пока человек не прочитает план и не даст согласие.
Имя сценария, bhda-spar.sh, расшифровывается как спарринг по аналогии защиты улья (Bee-Hive Defense Analogy sparring).
3. Ключевые части, шаг за шагом
Код ниже — минимальная справочная реализация, написанная для этого урока. Она показывает схему; это не копия исходного сценария. Каждый фрагмент проверен синтаксисом командой bash -n. Функции extract_bash, classify и print_plan прогнаны на образцах ввода; модель при этом не вызывалась, и ни одна команда, которая меняет состояние (ACT), не выполнялась.
jq собирает объект в формате JavaScript Object Notation (JSON), поэтому кавычки в запросах не ломают данные. Для проверок этого урока функцию к живому серверу не запускайте: она нужна, чтобы потом собрать рабочий сценарий.
3.2 extract_bash: забрать только огороженный bash
extract_bash() { # stdin: model reply; stdout: one command per line
awk 'tolower($0) ~ /^```(bash|sh)([[:space:]]|$)/ {f=1; next}
/^```/ {f=0}
f' |
sed '/^[[:space:]]*#/d;/^[[:space:]]*$/d'
}
Связный текст никогда не выполняется. Кандидатами становятся только строки внутри ограждения ```bash или ```sh. Совпадение не зависит от регистра (BASH тоже считается), комментарии и пустые строки отбрасываются, а голое ограждение ``` игнорируется.
3.3 Классификация «только чтение» (RO) и «изменение состояния» (ACT)
classify() { # RO = read-only, ACT = changes state
local c="$1"
if grep -Eq '(^|[;&|[:space:]])(rm|mv|cp|dd|chmod|chown|kill|pkill|systemctl([[:space:]]+-+[^[:space:]]+)*[[:space:]]+(start|stop|restart|reload|daemon-reload|enable|disable|mask|unmask)|ufw|iptables|nft|sed -i|tee|mkfs|mount|useradd|usermod|passwd|sudo)([[:space:]]|$)|>' <<<"$c"
then echo ACT; else echo RO; fi
}
Классификатор скорее пометит команду как ACT. Ошибочный ACT стоит одного лишнего нажатия клавиши, ошибочный RO может стоить машины. Любое перенаправление (>) считается ACT, в том числе 2>/dev/null. Необязательные флаги между systemctl и глаголом (systemctl --now enable, systemctl --user stop) тоже дают ACT, как и daemon-reload и unmask.
3.4 print_plan: предварительная таблица плана
print_plan() { # args: commands
printf '+----+------+%s+\n' "$(printf -- '-%.0s' {1..62})"
printf '| %-2s | %-4s | %-60s |\n' '#' 'TYPE' 'COMMAND'
printf '+----+------+%s+\n' "$(printf -- '-%.0s' {1..62})"
local i=1 c shown
for c in "$@"; do
shown="$c"
if ((${#c}>60)); then shown="${c:0:57}..."; fi
printf '| %-2d | %-4s | %-60s |\n' "$i" "$(classify "$c")" "$shown"
((i++))
done
printf '+----+------+%s+\n' "$(printf -- '-%.0s' {1..62})"
}
Весь план раунда виден до запуска — как контрольный список пилота. Команды длиннее 60 символов сокращаются многоточием, чтобы таблица оставалась читаемой. В шлюз проверки по-прежнему уходит полная команда. Таблица набрана в коде American Standard Code for Information Interchange (ASCII).
3.5 run_with_gate: шлюз проверки
run_with_gate() {
local c="$1" t; t=$(classify "$c")
[[ $EUID -eq 0 ]] && { echo "refusing: running as root"; return 1; }
read -r -p "[$t] run: $c ? [y/N] " a </dev/tty
[[ $a == y ]] || { echo "skipped" | tee -a "$LOG"; return 0; }
timeout 20 bash -c "$c" 2>&1 | head -n 60 | tee -a "$LOG"
}
По умолчанию ответ — нет (No).
</dev/tty заставляет запрос читать клавиатуру, а не вывод модели из канала.
timeout и head обрезают зависшие команды и потоки вывода.
Каждое решение записывается в журнал, в том числе пропуски.
В проверках урока эту функцию не запускайте: только она могла бы выполнить команду.
3.6 Оценка
Простая оценка каждого ответа не даёт спору закрутиться вхолостую:
Признак
Баллы
Названо конкретное поведение улья и конкретный механизм Linux
+2
Есть выполняемая проверка только на чтение (например ss -tulpn, systemctl is-enabled ssh)
+2
Указан отказной режим («это ломается, когда…»)
+1
Повторена мысль предыдущего хода (перекрытие ключевых слов выше порога)
−2
Чистая метафора, без механизма
−2
Фрагмент ниже считает только положительные признаки. Два штрафа требуют предыдущего хода, поэтому они живут в полном сценарии, а не в этом отрывке.
Каждые N раундов, или когда оценка падает (например, два раунда с 1 баллом или ниже), сценарий подставляет принудительный запрос:
RECALIBRATE. In at most 6 lines:
1. One hive defense.
2. The exact Linux mechanism it maps to.
3. One read-only command that checks it.
4. One concrete failure mode of that mapping.
No metaphors beyond line 1. No repetition of earlier rounds.
Так оба узла стаскивают с поэзии обратно к инженерии.
3.8 Основной цикл
LOG=./bhda-spar.log; N=4; low=0
reply="Open: map guard bees to Linux. Be concrete."
for round in $(seq 1 12); do
for node in 01 02; do
sys=$([[ $node == 01 ]] && echo "$SYS_PHI" || echo "$SYS_RENG")
reply=$(ask "$sys" "$reply")
echo -e "\n== node-$node · round $round ==\n$reply" | tee -a "$LOG"
s=$(score "$reply"); (( s <= 1 )) && ((low++)) || low=0
mapfile -t cmds < <(extract_bash <<<"$reply")
if ((${#cmds[@]})); then print_plan "${cmds[@]}"; for c in "${cmds[@]}"; do run_with_gate "$c"; done; fi
done
if (( round % N == 0 || low >= 2 )); then reply="$RECAL_PROMPT"; low=0; fi
done
4. Запросы моделям: что сработало и куда уносило
Что сработало
Контраст ролей. Один узел предлагает соответствие, другой атакует его отказным режимом. Разногласие, заложенное заранее, даёт более конкретный вывод, чем согласие.
Короткий договор в системном запросе. «Не больше восьми строк. Не больше одного блока bash. Команды только на чтение, пока не попросят иначе.» Короткие договоры соблюдаются лучше, чем длинные.
Выборка: температура (temperature) около 0,3–0,5 удерживала ответы ближе к делу. Штраф за присутствие (presence_penalty) около 0,6 и штраф за частоту (frequency_penalty) около 0,4 сокращали повтор одних и тех же фраз между раундами.
Перенастройка по нумерованному шаблону (раздел 3.7) за один раунд возвращала спор в колею.
Куда уносило
Метафорическая спираль. Без присмотра оба узла начинают описывать пчёл, которые описывают пчёл. Лечится штрафом в оценке и перенастройкой.
Круговое согласие. «Отличная мысль, продолжая её…» три раунда подряд и ни одного нового механизма. Лечится запретом пересказывать соперника и требованием одного нового механизма за ход.
Замах слишком широкий. Модель-кодер на семь миллиардов параметров охотно предлагает sudo и изменения через systemctl. Классификатор помечает их как ACT, а шлюз по умолчанию отвечает «нет».
Слишком высокая температура (выше примерно 0,8) порождала выдуманные флаги и несуществующие инструменты. Каждый флаг считайте непроверенным, пока его не подтвердит man.
5. Безопасность и работа без прав администратора
Никогда не запускайте цикл от имени администратора (root). Шлюз отказывается, если EUID равен 0. Запускайте от обычного пользователя; шаг ACT, которому вправду нужны повышенные права, выполняется вручную, вне сценария.
Без внешней сети: если сеть отключена, неудачное предложение не сможет загрузить чужой код и не «позвонит домой». Держите llama-server привязанным к 127.0.0.1[15].
Сначала только чтение: в первых раундах выполняйте только команды RO (ss -tulpn, systemctl list-unit-files --state=enabled, journalctl -p warning -b). Сухая проверка вроде sudo -n true лишь показывает, настроен ли sudo без пароля; классификатор всё равно пометит её как ACT, и в этих раундах шлюз должен оставаться на «нет».
Ограничение по времени и по объёму вывода на каждой выполняемой команде.
Журналы — это доказательства: храните полную расшифровку, таблицы плана и решения «да/нет». Это ваш аудиторский след в духе реагирования на инциденты.
Уход за машиной при длинных запусках:
Чтобы машина не засыпала при закрытой крышке, шаг делайте вручную, как ACT, а не из цикла. Один вариант: sudo systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target (и потом systemctl unmask) [16]. Другой: HandleLidSwitch=ignore в /etc/systemd/logind.conf (по умолчанию стоит suspend) [17].
Температуру смотрите во втором терминале: watch -n 5 sensors (lm-sensors) [18], и останавливайте запуск, если центральный процессор (CPU) долго остаётся горячим. Модель на семь миллиардов параметров на полной нагрузке — это небольшой обогреватель.
6. Как воспроизвести минимальную версию
Установите llama.cpp [15], а также jq, curl и lm-sensors[18].
Возьмите модель: небольшой instruct- или coder-файл в формате GPT-Generated Unified Format (GGUF), например qwen2.5-coder-7b-instruct Q4_K_M, скопированный на машину.
Поднимите её локально, зафиксировав адрес так, чтобы он совпал со сценарием: llama-server -m qwen2.5-coder-7b-instruct-q4_k_m.gguf --host 127.0.0.1 --port 8080 -c 4096
Напишите два системных запроса:
SYS_PHI: «Ты узел-01. За ход предложи ОДНО соответствие „улей — Linux“ и одну проверку только на чтение в одном огороженном блоке bash. Не больше восьми строк.»
SYS_RENG: «Ты узел-02, специалист по обратной разработке. Атакуй соответствие узла-01: назови один отказной режим и одну лучшую проверку только на чтение. Не больше восьми строк. Не пересказывай узел-01.»
Соберите сценарий из разделов 3.1–3.8 в файл bhda-spar.sh, выполните chmod +x и запустите его от обычного пользователя.
Первый запуск: 4 раунда, только RO. На всё, что помечено как ACT, отвечайте N.
Разберите журнал: какие соответствия набрали 4 балла или выше? Какие команды вправду пригодились? Три лучших внесите в свой собственный список укрепления.
Домашнее задание. Добавьте седьмую защиту улья. Пчёлы-санитары (их также называют некрофорными рабочими) уносят из семьи мёртвых соседей [12][13]. Отдельное, родственное поведение — гигиеническое удаление мёртвого или больного расплода — может запускаться химическим сигналом смерти, олеиновой кислотой [14]. В Linux это соответствует уборке застывших учётных записей, ключей и заданий cron. Пусть узлы спорят о соответствии санитаров в течение 4 раундов без единого штрафа за метафору.
Ссылка ведёт к исходной публикации. Для каждого поведения пчёл приведены как минимум два независимых источника. Для техники указана первичная документация.
Bee-hive sparring: two local models debate Linux defense
🛰️ Orbit
Starbound Academy · Cyber defense · About 25 minutes
A hive doesn't let anyone in who just looks like a bee. Neither should your shell.
1. Goal of the exercise
Run two local language models against each other as sparring partners, node-01 (Phi) and node-02 (R Eng), on one question: how do the defenses of a honey bee colony map to Linux hardening and incident response (IR)?
What you practice:
Turning an analogy into concrete, checkable commands. “Guard bees”, for example, become an allow-listed Secure Shell (SSH) entrance.
Keeping a debate between large language models (LLMs) non-circular with sampling settings, a tight system prompt and periodic recalibration.
Never letting model output run unchecked. Every command passes a validator gate before it executes.
Health monitoring: thermal and load watch on the host
2. Architecture
┌─────────────┐ prompt/round ┌──────────────────────────┐
│ bhda-spar.sh│ ───────────────► │ llama-server (local) │
│ (bash loop)│ ◄─────────────── │ qwen2.5-coder-7b, :8080 │
└─────┬───────┘ reply (text) └──────────────────────────┘
│ extract fenced bash blocks
▼
┌─────────────┐ RO / ACT tag ┌──────────────────────────┐
│ classifier │ ───────────────► │ print_plan (ASCII table) │
└─────┬───────┘ └────────────┬─────────────┘
▼ ▼
┌──────────────────────────────────────────────────────────┐
│ validator gate: a person reads the plan, approves each │
│ step (y/N), and only then does run_with_gate execute it │
└──────────────────────────────────────────────────────────┘
Host: a machine with no external network during the run. The model, the script and the logs all stay local.
Model server:llama-server (from llama.cpp) serving qwen2.5-coder-7b via an OpenAI-compatible /v1/chat/completions endpoint on localhost [15]. The current server README defaults to 127.0.0.1:9931. The examples below set --host 127.0.0.1 --port 8080 so the script and the server agree.
Two personas, one model: node-01 and node-02 are system prompts, not separate models. They alternate turns, and each sees the other's last reply.
Validator gate: nothing from a model executes until a person reads the plan and says yes.
The script name, bhda-spar.sh, is short for Bee-Hive Defense Analogy sparring.
3. Key components, step by step
The code below is a minimal reference implementation written for this lesson. It shows the pattern; it is not a copy of the original script. Every snippet below was syntax-checked with bash -n. extract_bash, classify and print_plan were also run on sample input; they were not used to call a model or to run any command that changes state (ACT).
jq builds the JavaScript Object Notation (JSON), so quotes in prompts can't break the payload. Do not run this function against a live server for this lesson's checks; it is shown so you can assemble a working script later.
3.2 extract_bash: pull out only fenced bash
extract_bash() { # stdin: model reply; stdout: one command per line
awk 'tolower($0) ~ /^```(bash|sh)([[:space:]]|$)/ {f=1; next}
/^```/ {f=0}
f' |
sed '/^[[:space:]]*#/d;/^[[:space:]]*$/d'
}
Prose never executes. Only lines inside a ```bash or ```sh fence become candidates. The match is case-insensitive (BASH counts), comments and blank lines are dropped, and a bare ``` fence is ignored.
classify() { # RO = read-only, ACT = changes state
local c="$1"
if grep -Eq '(^|[;&|[:space:]])(rm|mv|cp|dd|chmod|chown|kill|pkill|systemctl([[:space:]]+-+[^[:space:]]+)*[[:space:]]+(start|stop|restart|reload|daemon-reload|enable|disable|mask|unmask)|ufw|iptables|nft|sed -i|tee|mkfs|mount|useradd|usermod|passwd|sudo)([[:space:]]|$)|>' <<<"$c"
then echo ACT; else echo RO; fi
}
It errs toward ACT. A false ACT costs one extra keypress, while a false RO could cost the box. Any redirect (>) counts as ACT, including 2>/dev/null. Optional flags between systemctl and the verb (systemctl --now enable, systemctl --user stop) also count as ACT, as do daemon-reload and unmask.
3.4 print_plan: the pre-flight table
print_plan() { # args: commands
printf '+----+------+%s+\n' "$(printf -- '-%.0s' {1..62})"
printf '| %-2s | %-4s | %-60s |\n' '#' 'TYPE' 'COMMAND'
printf '+----+------+%s+\n' "$(printf -- '-%.0s' {1..62})"
local i=1 c shown
for c in "$@"; do
shown="$c"
if ((${#c}>60)); then shown="${c:0:57}..."; fi
printf '| %-2d | %-4s | %-60s |\n' "$i" "$(classify "$c")" "$shown"
((i++))
done
printf '+----+------+%s+\n' "$(printf -- '-%.0s' {1..62})"
}
The whole round's plan is visible before anything runs, like a pilot's checklist. Commands longer than 60 characters are shortened with an ellipsis so the table stays readable. The full command is still what the gate asks about. The table is drawn in American Standard Code for Information Interchange (ASCII).
3.5 run_with_gate: the validator gate
run_with_gate() {
local c="$1" t; t=$(classify "$c")
[[ $EUID -eq 0 ]] && { echo "refusing: running as root"; return 1; }
read -r -p "[$t] run: $c ? [y/N] " a </dev/tty
[[ $a == y ]] || { echo "skipped" | tee -a "$LOG"; return 0; }
timeout 20 bash -c "$c" 2>&1 | head -n 60 | tee -a "$LOG"
}
The default is No.
</dev/tty makes the prompt read the keyboard, not piped model output.
timeout and head cap runaway commands and floods of output.
Every decision is logged, including skips.
Do not use this function in the lesson checks: it is the only place that would execute a command.
3.6 Scoring
A simple per-reply score keeps the debate honest:
Signal
Points
Names a specific hive behavior and a specific Linux mechanism
+2
Includes a runnable read-only check (for example ss -tulpn, systemctl is-enabled ssh)
+2
States a failure mode (“this breaks when…”)
+1
Repeats the previous turn's idea (keyword overlap above a threshold)
−2
Pure metaphor, no mechanism
−2
The snippet below scores only the positive signals. The two penalties need the previous turn, so they belong in the full script, not in this fragment.
Every N rounds, or when the score drops (for example two rounds at 1 or below), the script injects a forcing prompt:
RECALIBRATE. In at most 6 lines:
1. One hive defense.
2. The exact Linux mechanism it maps to.
3. One read-only command that checks it.
4. One concrete failure mode of that mapping.
No metaphors beyond line 1. No repetition of earlier rounds.
This drags both nodes back from poetry to engineering.
3.8 The main loop
LOG=./bhda-spar.log; N=4; low=0
reply="Open: map guard bees to Linux. Be concrete."
for round in $(seq 1 12); do
for node in 01 02; do
sys=$([[ $node == 01 ]] && echo "$SYS_PHI" || echo "$SYS_RENG")
reply=$(ask "$sys" "$reply")
echo -e "\n== node-$node · round $round ==\n$reply" | tee -a "$LOG"
s=$(score "$reply"); (( s <= 1 )) && ((low++)) || low=0
mapfile -t cmds < <(extract_bash <<<"$reply")
if ((${#cmds[@]})); then print_plan "${cmds[@]}"; for c in "${cmds[@]}"; do run_with_gate "$c"; done; fi
done
if (( round % N == 0 || low >= 2 )); then reply="$RECAL_PROMPT"; low=0; fi
done
4. Prompt engineering: what worked and what drifted
What worked
Role contrast. One node proposes and the other attacks the proposal with a failure mode. Disagreement by design produces more concrete output than agreement.
Output contract in the system prompt. “Max 8 lines. At most one bash block. Read-only commands only unless asked.” Short contracts are obeyed better than long ones.
Sampling: temperature around 0.3–0.5 kept answers grounded. presence_penalty around 0.6 and frequency_penalty around 0.4 cut down repeated phrases between rounds.
Recalibration with a numbered template (section 3.7) reliably reset drift within one round.
What drifted
Metaphor spiral. Left alone, both nodes start describing bees describing bees. The fix is the scoring penalty plus recal.
Circular agreement. “Great point, building on that...” for three rounds with no new mechanism. The fix is to forbid restating the opponent and require one new mechanism per turn.
Overreach. The 7-billion-parameter coder model likes to propose sudo and systemctl changes. The classifier tags them ACT, and the gate defaults to No.
Too-high temperature (above about 0.8) produced invented flags and nonexistent tools. Treat every flag as unverified until man says otherwise.
5. Safety and non-root considerations
Never run the loop as root. The gate refuses when EUID is 0. Run it as an unprivileged user; any ACT step that truly needs privilege is done by hand, outside the script.
No external network: with the network off, a bad suggestion can't pull a payload or phone home. Keep llama-server bound to 127.0.0.1[15].
Read-only first: the opening rounds should run RO commands only (ss -tulpn, systemctl list-unit-files --state=enabled, journalctl -p warning -b). A dry check such as sudo -n true only tells you whether passwordless sudo is configured; the classifier still tags it ACT, and the gate should stay at No in those rounds.
Timeouts and output caps on every executed command.
Logs are evidence: keep the full transcript, the plan tables and the y/N decisions. That's your IR-style audit trail.
Host care for long runs:
Keep the machine awake with the lid closed by hand, as an ACT step, not from the loop. One option is sudo systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target (and systemctl unmask afterwards) [16]. Another is HandleLidSwitch=ignore in /etc/systemd/logind.conf (the default is suspend) [17].
Watch temperatures in a second terminal: watch -n 5 sensors (lm-sensors) [18], and stop the run if the central processing unit (CPU) stays hot. A 7-billion-parameter model at full tilt is a small space heater.
6. Reproduce a minimal version
Install: build or install llama.cpp [15], plus jq, curl and lm-sensors[18].
Get a model: a small instruct or coder file in GPT-Generated Unified Format (GGUF), for example qwen2.5-coder-7b-instruct Q4_K_M, copied onto the machine.
Serve it locally, pinning the address so it matches the script: llama-server -m qwen2.5-coder-7b-instruct-q4_k_m.gguf --host 127.0.0.1 --port 8080 -c 4096
Write two system prompts:
SYS_PHI: “You are node-01. Propose ONE hive-to-Linux mapping per turn, with one read-only bash check in a single fenced block. Max 8 lines.”
SYS_RENG: “You are node-02, a reverse engineer. Attack node-01's mapping: name one failure mode and one better read-only check. Max 8 lines. Don't restate node-01.”
Assemble the script from sections 3.1–3.8 into bhda-spar.sh, run chmod +x, and run it as a normal user.
First run: 4 rounds, RO only. Answer N to anything tagged ACT.
Review the log: which mappings scored 4 or higher? Which commands were genuinely useful? Turn the best three into your own hardening checklist.
Homework. Add a seventh hive defense. Undertaker bees (also called necrophoric workers) remove dead nestmates from the colony [12][13]. A separate, related behaviour — hygienic removal of dead or diseased brood — can be triggered by a death-related chemical cue, oleic acid [14]. The Linux mapping is cleaning up stale accounts, keys and cron jobs. Make the nodes argue the undertaker mapping in 4 rounds without a single metaphor penalty.
Credit links go to the original publication. Each bee behaviour has at least two independent sources. Technical citations are the primary documentation.
Sparring en la colmena: dos modelos locales debaten la defensa de Linux
🛰️ Órbita
Starbound Academy · Ciberdefensa · Unos 25 minutos
Una colmena no deja entrar a quien solo parece una abeja. Su shell tampoco debería.
1. Objetivo del ejercicio
Enfrente a dos modelos de lenguaje locales como contrincantes de entrenamiento, node-01 (Phi) y node-02 (R Eng), en torno a una sola pregunta: ¿cómo se corresponden las defensas de una colonia de abejas melíferas con el endurecimiento (hardening) de Linux y la respuesta a incidentes (IR)?
Qué practicará:
Convertir una analogía en comandos concretos y verificables. Las «abejas guardianas», por ejemplo, se convierten en una entrada Secure Shell (SSH) con lista de permitidos.
Evitar que un debate entre modelos de lenguaje de gran tamaño (LLM) sea circular, mediante parámetros de muestreo, un prompt de sistema preciso y una recalibración periódica.
No dejar nunca que la salida del modelo se ejecute sin control. Cada comando pasa por una compuerta de validación antes de ejecutarse.
Cortafuegos con denegación por defecto, lista de permitidos de Secure Shell (SSH), AllowUsers
Feromona de alarma (acetato de isopentilo, también llamado acetato de isoamilo) [3][1]
Alertas: journalctl -f, reglas de auditd, disparadores basados en registros
Restricción de la entrada (estrechamiento con propóleo) [4][5]
Mínimo de puertos abiertos, revisión con ss -tulpn, desactivación de servicios sin uso
Defensa sacrificial (el aguijón, la autotomía del aguijón) [6][7]
Terminar o aislar un proceso o contenedor comprometido, asumiendo la pérdida
Negación de recursos (nada de miel para los saqueadores) [8][9]
Mínimo privilegio, montajes de solo lectura, cuotas, sin secretos en disco
Regulación de la temperatura de la colmena [10][11]
Monitoreo de estado: vigilancia térmica y de carga del equipo
2. Arquitectura
┌─────────────┐ prompt/ronda ┌──────────────────────────┐
│ bhda-spar.sh│ ───────────────► │ llama-server (local) │
│ (bash loop)│ ◄─────────────── │ qwen2.5-coder-7b, :8080 │
└─────┬───────┘ respuesta (texto)└──────────────────────────┘
│ extrae los bloques bash delimitados
▼
┌─────────────┐ RO / ACT tag ┌──────────────────────────┐
│ classifier │ ───────────────► │ print_plan (ASCII table) │
└─────┬───────┘ └────────────┬─────────────┘
▼ ▼
┌──────────────────────────────────────────────────────────┐
│ validator gate: una persona lee el plan, aprueba cada │
│ paso (y/N) y solo entonces run_with_gate lo ejecuta │
└──────────────────────────────────────────────────────────┘
Equipo: una máquina sin red externa durante la ejecución. El modelo, el script y los registros permanecen en local.
Servidor del modelo:llama-server (de llama.cpp) que sirve qwen2.5-coder-7b mediante un punto de acceso /v1/chat/completions compatible con OpenAI en localhost [15]. El README actual del servidor usa por defecto 127.0.0.1:9931. Los ejemplos siguientes fijan --host 127.0.0.1 --port 8080 para que el script y el servidor coincidan.
Dos personajes, un solo modelo: node-01 y node-02 son prompts de sistema, no modelos distintos. Se turnan, y cada uno ve la última respuesta del otro.
Compuerta de validación: nada de lo que produce un modelo se ejecuta hasta que una persona lee el plan y dice que sí.
El nombre del script, bhda-spar.sh, es la abreviatura de Bee-Hive Defense Analogy sparring.
3. Componentes clave, paso a paso
El código siguiente es una implementación de referencia mínima escrita para esta lección. Muestra el patrón; no es una copia del script original. Todos los fragmentos se verificaron sintácticamente con bash -n. Además, extract_bash, classify y print_plan se ejecutaron con datos de ejemplo; no se usaron para llamar a un modelo ni para ejecutar ningún comando que cambie el estado (ACT).
jq construye el JavaScript Object Notation (JSON), de modo que las comillas de los prompts no pueden romper la carga. No ejecute esta función contra un servidor en funcionamiento para las verificaciones de esta lección; se muestra para que más adelante pueda armar un script funcional.
3.2 extract_bash: extraer solo el bash delimitado
extract_bash() { # stdin: model reply; stdout: one command per line
awk 'tolower($0) ~ /^```(bash|sh)([[:space:]]|$)/ {f=1; next}
/^```/ {f=0}
f' |
sed '/^[[:space:]]*#/d;/^[[:space:]]*$/d'
}
El texto en prosa nunca se ejecuta. Solo las líneas dentro de un bloque ```bash o ```sh pasan a ser candidatas. La coincidencia no distingue mayúsculas de minúsculas (BASH cuenta), se descartan los comentarios y las líneas en blanco, y se ignora un bloque ``` sin lenguaje.
3.3 Clasificación: solo lectura (RO) / cambio de estado (ACT)
classify() { # RO = read-only, ACT = changes state
local c="$1"
if grep -Eq '(^|[;&|[:space:]])(rm|mv|cp|dd|chmod|chown|kill|pkill|systemctl([[:space:]]+-+[^[:space:]]+)*[[:space:]]+(start|stop|restart|reload|daemon-reload|enable|disable|mask|unmask)|ufw|iptables|nft|sed -i|tee|mkfs|mount|useradd|usermod|passwd|sudo)([[:space:]]|$)|>' <<<"$c"
then echo ACT; else echo RO; fi
}
Se equivoca hacia ACT: un falso ACT cuesta una pulsación de tecla más, mientras que un falso RO podría costarle el equipo. Cualquier redirección (>) cuenta como ACT, incluido 2>/dev/null. Las opciones entre systemctl y el verbo (systemctl --now enable, systemctl --user stop) también cuentan como ACT, igual que daemon-reload y unmask.
3.4 print_plan: la tabla de revisión previa
print_plan() { # args: commands
printf '+----+------+%s+\n' "$(printf -- '-%.0s' {1..62})"
printf '| %-2s | %-4s | %-60s |\n' '#' 'TYPE' 'COMMAND'
printf '+----+------+%s+\n' "$(printf -- '-%.0s' {1..62})"
local i=1 c shown
for c in "$@"; do
shown="$c"
if ((${#c}>60)); then shown="${c:0:57}..."; fi
printf '| %-2d | %-4s | %-60s |\n' "$i" "$(classify "$c")" "$shown"
((i++))
done
printf '+----+------+%s+\n' "$(printf -- '-%.0s' {1..62})"
}
El plan completo de la ronda es visible antes de que se ejecute nada, como la lista de verificación de un piloto. Los comandos de más de 60 caracteres se abrevian con puntos suspensivos para que la tabla siga siendo legible. La compuerta pregunta siempre por el comando completo. La tabla se dibuja en American Standard Code for Information Interchange (ASCII).
3.5 run_with_gate: la compuerta de validación
run_with_gate() {
local c="$1" t; t=$(classify "$c")
[[ $EUID -eq 0 ]] && { echo "refusing: running as root"; return 1; }
read -r -p "[$t] run: $c ? [y/N] " a </dev/tty
[[ $a == y ]] || { echo "skipped" | tee -a "$LOG"; return 0; }
timeout 20 bash -c "$c" 2>&1 | head -n 60 | tee -a "$LOG"
}
La respuesta por defecto es No.
</dev/tty hace que la consulta lea el teclado y no la salida canalizada del modelo.
timeout y head limitan los comandos descontrolados y los desbordes de salida.
Cada decisión queda registrada, incluidas las omisiones.
No use esta función en las verificaciones de la lección: es el único lugar que ejecutaría un comando.
3.6 Puntuación
Una puntuación sencilla por respuesta mantiene el debate honesto:
Señal
Puntos
Nombra un comportamiento concreto de la colmena y un mecanismo concreto de Linux
+2
Incluye una verificación ejecutable de solo lectura (por ejemplo ss -tulpn, systemctl is-enabled ssh)
+2
Indica un modo de fallo («esto falla cuando…»)
+1
Repite la idea del turno anterior (coincidencia de palabras clave por encima de un umbral)
−2
Pura metáfora, sin mecanismo
−2
El fragmento siguiente puntúa solo las señales positivas. Las dos penalizaciones requieren el turno anterior, por lo que corresponden al script completo y no a este fragmento.
Cada N rondas, o cuando baja la puntuación (por ejemplo, dos rondas con 1 o menos), el script inyecta un prompt de corrección:
RECALIBRATE. In at most 6 lines:
1. One hive defense.
2. The exact Linux mechanism it maps to.
3. One read-only command that checks it.
4. One concrete failure mode of that mapping.
No metaphors beyond line 1. No repetition of earlier rounds.
Esto devuelve a ambos nodos de la poesía a la ingeniería.
3.8 El bucle principal
LOG=./bhda-spar.log; N=4; low=0
reply="Open: map guard bees to Linux. Be concrete."
for round in $(seq 1 12); do
for node in 01 02; do
sys=$([[ $node == 01 ]] && echo "$SYS_PHI" || echo "$SYS_RENG")
reply=$(ask "$sys" "$reply")
echo -e "\n== node-$node · round $round ==\n$reply" | tee -a "$LOG"
s=$(score "$reply"); (( s <= 1 )) && ((low++)) || low=0
mapfile -t cmds < <(extract_bash <<<"$reply")
if ((${#cmds[@]})); then print_plan "${cmds[@]}"; for c in "${cmds[@]}"; do run_with_gate "$c"; done; fi
done
if (( round % N == 0 || low >= 2 )); then reply="$RECAL_PROMPT"; low=0; fi
done
4. Ingeniería de prompts: lo que funcionó y lo que se desvió
Lo que funcionó
Contraste de roles. Un nodo propone y el otro ataca la propuesta con un modo de fallo. El desacuerdo por diseño produce resultados más concretos que el acuerdo.
Contrato de salida en el prompt de sistema. «Máximo 8 líneas. Como máximo un bloque bash. Solo comandos de solo lectura, salvo que se pida otra cosa». Los contratos breves se cumplen mejor que los largos.
Muestreo: una temperatura de entre 0,3 y 0,5 mantuvo las respuestas con los pies en la tierra. Un presence_penalty cercano a 0,6 y un frequency_penalty cercano a 0,4 redujeron las frases repetidas entre rondas.
La recalibración con una plantilla numerada (sección 3.7) corrigió la deriva de forma fiable en una sola ronda.
Lo que se desvió
Espiral de metáforas. Si se les deja solos, ambos nodos empiezan a describir abejas que describen abejas. La solución es la penalización de puntuación más la recalibración.
Acuerdo circular. «Excelente punto, a partir de eso…» durante tres rondas sin ningún mecanismo nuevo. La solución es prohibir reformular al oponente y exigir un mecanismo nuevo por turno.
Exceso de iniciativa. Al modelo de programación de 7000 millones de parámetros le gusta proponer cambios con sudo y systemctl. El clasificador los marca como ACT y la compuerta responde No por defecto.
Una temperatura demasiado alta (por encima de 0,8, aproximadamente) produjo opciones inventadas y herramientas inexistentes. Considere cada opción como no verificada hasta que man diga lo contrario.
5. Seguridad y consideraciones sin privilegios de root
No ejecute nunca el bucle como root. La compuerta se niega cuando EUID es 0. Ejecútelo con un usuario sin privilegios; cualquier paso ACT que realmente requiera privilegios se hace a mano, fuera del script.
Sin red externa: con la red desactivada, una mala sugerencia no puede descargar una carga maliciosa ni comunicarse con el exterior. Mantenga llama-server enlazado a 127.0.0.1[15].
Primero, solo lectura: las rondas iniciales deben ejecutar únicamente comandos RO (ss -tulpn, systemctl list-unit-files --state=enabled, journalctl -p warning -b). Una comprobación en seco como sudo -n true solo indica si sudo sin contraseña está configurado; el clasificador la marca igualmente como ACT, y la compuerta debe permanecer en No en esas rondas.
Tiempos límite y topes de salida en cada comando ejecutado.
Los registros son evidencia: conserve la transcripción completa, las tablas de plan y las decisiones y/N. Esa es su pista de auditoría al estilo de IR.
Cuidado del equipo en ejecuciones largas:
Mantenga el equipo activo con la tapa cerrada de forma manual, como un paso ACT y no desde el bucle. Una opción es sudo systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target (y después systemctl unmask) [16]. Otra es HandleLidSwitch=ignore en /etc/systemd/logind.conf (el valor por defecto es suspend) [17].
Vigile las temperaturas en una segunda terminal: watch -n 5 sensors (lm-sensors) [18], y detenga la ejecución si la unidad central de procesamiento (CPU) permanece caliente. Un modelo de 7000 millones de parámetros a plena carga es un pequeño calefactor.
6. Reproduzca una versión mínima
Instale: compile o instale llama.cpp [15], más jq, curl y lm-sensors[18].
Obtenga un modelo: un archivo pequeño de tipo instruct o coder en GPT-Generated Unified Format (GGUF), por ejemplo qwen2.5-coder-7b-instruct Q4_K_M, copiado en la máquina.
Sírvalo en local, fijando la dirección para que coincida con el script: llama-server -m qwen2.5-coder-7b-instruct-q4_k_m.gguf --host 127.0.0.1 --port 8080 -c 4096
Escriba dos prompts de sistema:
SYS_PHI: «Eres node-01. Propón UNA correspondencia colmena-Linux por turno, con una verificación bash de solo lectura en un único bloque delimitado. Máximo 8 líneas.»
SYS_RENG: «Eres node-02, un ingeniero inverso. Ataca la correspondencia de node-01: nombra un modo de fallo y una mejor verificación de solo lectura. Máximo 8 líneas. No reformules a node-01.»
Arme el script con las secciones 3.1 a 3.8 en bhda-spar.sh, ejecute chmod +x y lance el script como un usuario normal.
Primera ejecución: 4 rondas, solo RO. Responda N a todo lo marcado como ACT.
Revise el registro: ¿qué correspondencias obtuvieron 4 puntos o más? ¿Qué comandos resultaron realmente útiles? Convierta las tres mejores en su propia lista de verificación de endurecimiento.
Tarea. Añada una séptima defensa de la colmena. Las abejas sepultureras (también llamadas obreras necróforas) retiran de la colonia a las compañeras muertas [12][13]. Un comportamiento distinto pero relacionado —la retirada higiénica de crías muertas o enfermas— puede desencadenarse por una señal química asociada a la muerte, el ácido oleico [14]. La correspondencia en Linux es la limpieza de cuentas, claves y tareas cron obsoletas. Haga que los nodos debatan la correspondencia de las sepultureras en 4 rondas sin una sola penalización por metáfora.
Los enlaces de crédito llevan a la publicación original. Cada comportamiento de las abejas cuenta con al menos dos fuentes independientes. Las citas técnicas remiten a la documentación primaria.
extract_bash() { # stdin: model reply; stdout: one command per line
awk 'tolower($0) ~ /^```(bash|sh)([[:space:]]|$)/ {f=1; next}
/^```/ {f=0}
f' |
sed '/^[[:space:]]*#/d;/^[[:space:]]*$/d'
}
print_plan() { # args: commands
printf '+----+------+%s+\n' "$(printf -- '-%.0s' {1..62})"
printf '| %-2s | %-4s | %-60s |\n' '#' 'TYPE' 'COMMAND'
printf '+----+------+%s+\n' "$(printf -- '-%.0s' {1..62})"
local i=1 c shown
for c in "$@"; do
shown="$c"
if ((${#c}>60)); then shown="${c:0:57}..."; fi
printf '| %-2d | %-4s | %-60s |\n' "$i" "$(classify "$c")" "$shown"
((i++))
done
printf '+----+------+%s+\n' "$(printf -- '-%.0s' {1..62})"
}
そのラウンドの計画全体が、何かが動く前に見えます。パイロットのチェックリストのようなものです。60文字を超えるコマンドは、表が読みやすいように、省略記号で短くされます。ゲートが尋ねるのは、あくまで完全なコマンドです。表は、American Standard Code for Information Interchange(ASCII)で描かれます。
3.5 run_with_gate:検証ゲート
run_with_gate() {
local c="$1" t; t=$(classify "$c")
[[ $EUID -eq 0 ]] && { echo "refusing: running as root"; return 1; }
read -r -p "[$t] run: $c ? [y/N] " a </dev/tty
[[ $a == y ]] || { echo "skipped" | tee -a "$LOG"; return 0; }
timeout 20 bash -c "$c" 2>&1 | head -n 60 | tee -a "$LOG"
}
RECALIBRATE. In at most 6 lines:
1. One hive defense.
2. The exact Linux mechanism it maps to.
3. One read-only command that checks it.
4. One concrete failure mode of that mapping.
No metaphors beyond line 1. No repetition of earlier rounds.
これで、両方のノードを、詩的な話から、エンジニアリングに引き戻します。
3.8 メインのループ
LOG=./bhda-spar.log; N=4; low=0
reply="Open: map guard bees to Linux. Be concrete."
for round in $(seq 1 12); do
for node in 01 02; do
sys=$([[ $node == 01 ]] && echo "$SYS_PHI" || echo "$SYS_RENG")
reply=$(ask "$sys" "$reply")
echo -e "\n== node-$node · round $round ==\n$reply" | tee -a "$LOG"
s=$(score "$reply"); (( s <= 1 )) && ((low++)) || low=0
mapfile -t cmds < <(extract_bash <<<"$reply")
if ((${#cmds[@]})); then print_plan "${cmds[@]}"; for c in "${cmds[@]}"; do run_with_gate "$c"; done; fi
done
if (( round % N == 0 || low >= 2 )); then reply="$RECAL_PROMPT"; low=0; fi
done