# ================= TASK 4: Local rule + incident response =================
source ~/lab.env

# ---------- 1. install custom rules (no IPs inside, nothing to edit) ----------
docker exec -i $MGR sh -c 'cat >> /var/ossec/etc/rules/local_rules.xml' <<'EOF'

<group name="local,custom_ssh,authentication_failures,">

  <rule id="100100" level="12" frequency="5" timeframe="60">
    <if_matched_group>authentication_failed</if_matched_group>
    <same_source_ip />
    <description>LAB: 5+ failed SSH logins from same source IP within 60s (possible brute force)</description>
    <mitre>
      <id>T1110</id>
    </mitre>
    <group>lab_bruteforce,</group>
  </rule>

  <rule id="100101" level="10">
    <if_group>authentication_failed</if_group>
    <field name="dstuser">^root$</field>
    <description>LAB: failed SSH login targeting root account</description>
    <mitre>
      <id>T1110.001</id>
    </mitre>
    <group>lab_root_target,</group>
  </rule>

</group>
EOF

# ---------- 2. validate + restart ----------
docker exec $MGR /var/ossec/bin/wazuh-analysisd -t && echo "CONFIG OK"
docker restart $MGR
sleep 40; docker exec $MGR /var/ossec/bin/agent_control -l

# ---------- 3. wazuh-logtest ----------
for i in 1 2 3 4 5 6; do echo "Nov  3 11:00:0$i $H sshd[900]: Failed password for root from $ATTACKER_TEST port 4000$i ssh2"; done | docker exec -i $MGR /var/ossec/bin/wazuh-logtest 2>&1 | grep -E "id:|level:|description:" | tail -12

# ---------- 4. live end-to-end test ----------
for i in $(seq 1 7); do echo "$(date '+%b %e %H:%M:%S') $H sshd[4100]: Failed password for root from $ATTACKER_TEST port $((43000+i)) ssh2" | sudo tee -a $LAB_LOG >/dev/null; sleep 1; done
sleep 5
docker exec $MGR cat /var/ossec/logs/alerts/alerts.json | jq -r 'select(.rule.id=="100100" or .rule.id=="100101") | [.timestamp[0:19],.agent.name,.rule.id,.rule.level,.data.srcip,.rule.description]|@tsv' | tail
# browser: Threat Hunting -> rule.id: (100100 or 100101)

# ---------- 5. ACTIVE RESPONSE (block attacker IP) ----------
cd $WAZUH_DIR
cp config/wazuh_cluster/wazuh_manager.conf /tmp/wazuh_manager.conf.bak
python3 - <<'EOF'
p='config/wazuh_cluster/wazuh_manager.conf'
s=open(p).read()
blk='''
  <active-response>
    <command>firewall-drop</command>
    <location>local</location>
    <rules_id>100100</rules_id>
    <timeout>600</timeout>
  </active-response>

'''
if '100100' not in s.split('<active-response>')[-1] if '<active-response>' in s else True:
    i=s.rfind('</ossec_config>')
    open(p,'w').write(s[:i]+blk+s[i:])
EOF
grep -n -B1 -A5 "firewall-drop" config/wazuh_cluster/wazuh_manager.conf | tail -12
docker compose restart wazuh.manager
sleep 40

# trigger from the block-test IP
for i in $(seq 1 7); do echo "$(date '+%b %e %H:%M:%S') $H sshd[4200]: Failed password for root from $ATTACKER_BLOCK port $((44000+i)) ssh2" | sudo tee -a $LAB_LOG >/dev/null; sleep 1; done
sleep 5

sudo tail -n 5 /var/ossec/logs/active-responses.log
sudo iptables -L INPUT -n | grep $ATTACKER_BLOCK        # DROP rule present
# after 600 s: sudo iptables -L INPUT -n | grep $ATTACKER_BLOCK   -> gone

# ---------- 6. IR recommendations (write in report) ----------
# Identify   : rule 100100 (level 12) for $ATTACKER_BRUTE; MITRE T1110
# Contain    : firewall-drop AR / sudo ufw deny from <ip>;  sudo passwd -l $LAB_USER ; sudo pkill -KILL -u $LAB_USER
# Investigate: sudo grep Accepted /var/log/auth.log ; last -a | head ; check authorized_keys, new users, cron
# Eradicate  : reset credentials, remove unknown keys/accounts/persistence
# Harden     : PasswordAuthentication no, PermitRootLogin no, MaxAuthTries 3, VPN/IP allow-list, fail2ban, MFA
# Recover    : unblock legit users, monitor 24-48 h
# Lessons    : keep rule 100100, tune frequency/timeframe, alert on success-after-failure

# ---------- 7. cleanup ----------
sudo userdel -r $LAB_USER
sudo rm -f $LAB_LOG
sudo iptables -D INPUT -s $ATTACKER_BLOCK -j DROP 2>/dev/null
# stop stack: cd $WAZUH_DIR && docker compose downso 