SSH Honeypot + CrowdSec

If you like this project, consider supporting me on Buy Me a Coffee ☕️


tags:

Context: This guide covers deploying a Cowrie SSH honeypot on port 22 while moving the real SSH service to a non-standard port. Cowrie emulates a vulnerable SSH server, logging attacker commands and credentials. Combined with CrowdSec, attacking IPs are automatically banned via firewall rules and optionally shared with the community blocklist. / Руководство по развёртыванию SSH-ловушки Cowrie на порту 22 с переносом реального SSH на нестандартный порт. Cowrie эмулирует уязвимый SSH-сервер, логируя команды и пароли атакующих. В связке с CrowdSec атакующие IP автоматически банятся. Role: Security Engineer / Sysadmin See also: CrowdSec, SSH Keys


📚 Table of Contents


1. Overview

Goal / Цель:

  • Real SSH runs on port 2222 / Реальный SSH работает на порту 2222
  • Port 22 becomes a Cowrie honeypot / Порт 22 становится ловушкой Cowrie
  • CrowdSec automatically bans attacking IPs / CrowdSec автоматически банит атакующие IP
  • Logs saved and optionally sent to CrowdSec community blocklist / Логи сохраняются и отправляются в CrowdSec
  • Optional web dashboard and GeoIP visualization / Опциональная веб-панель и визуализация GeoIP

Architecture

Internet
   |
   v
Port 22  ---> Cowrie Honeypot ---> Logs & GeoIP Dashboard
   |
   v
CrowdSec detection
   |
   v
Firewall ban & optional Community feed

Real admin access:
Port 2222 ---> OpenSSH

2. Install Docker

sudo apt update                                           # Update packages / Обновить пакеты
sudo apt install -y docker.io                             # Install Docker / Установить Docker
sudo systemctl enable --now docker                        # Enable & start / Включить и запустить
docker --version                                          # Verify install / Проверить установку

3. Move Real SSH to Port 2222

[!CAUTION] Open firewall for the new SSH port before disconnecting from the current session! Откройте порт в файрволе до отключения от текущей сессии!

Edit SSH Config

/etc/ssh/sshd_config

Port 2222

Apply Changes

sudo ufw allow 2222/tcp                                   # Open firewall / Открыть файрвол
sudo systemctl restart ssh                                # Restart SSH / Перезапустить SSH
ssh <USER>@<HOST> -p 2222                                 # Test login / Тестовый вход

4. Install Cowrie Honeypot

docker pull cowrie/cowrie                                  # Pull image / Скачать образ
docker run -d --name cowrie \
  -p 22:2222 \
  --restart unless-stopped \
  cowrie/cowrie                                            # Run on port 22 / Запустить на порту 22
docker ps                                                 # Check container / Проверить контейнер

5. Save Honeypot Logs

# Run with persistent logs
docker run -d --name cowrie \
  -p 22:2222 \
  -v /opt/cowrie/log:/cowrie/var/log/cowrie \
  --restart unless-stopped \
  cowrie/cowrie

ls /opt/cowrie/log                                        # Access logs / Доступ к логам

6. Install CrowdSec

curl -s https://install.crowdsec.net | sudo sh            # Add repo / Добавить репозиторий
sudo apt install -y crowdsec                              # Install CrowdSec / Установить CrowdSec
sudo apt install -y crowdsec-firewall-bouncer-iptables    # Install bouncer / Установить bouncer
sudo systemctl status crowdsec                            # Check status / Проверить статус

7. Install Cowrie Parser

sudo cscli collections install crowdsecurity/cowrie       # Install collection / Установить коллекцию
sudo systemctl restart crowdsec                           # Restart CrowdSec / Перезапустить CrowdSec

8. Community Integration

sudo cscli hub update                                     # Update hub / Обновить хаб
sudo cscli hub install crowdsecurity/lapi                  # Install LAPI / Установить LAPI

9. Web Dashboard

docker run -d -p 8080:8080 \
  --name cowrie-web \
  --link cowrie:db \
  cowrie/cowrie-web                                        # Start dashboard / Запустить панель

Access / Доступ: http://<HOST>:8080

[!TIP] Use Python script or Kibana to parse /opt/cowrie/log/cowrie.json and plot IPs on a GeoIP map. Используйте Python-скрипт или Kibana для парсинга логов и отображения IP на карте.


10. Verify Detection & Firewall

sudo cscli decisions list                                  # Active bans / Активные баны
sudo cscli alerts list                                     # Alert history / История алертов
sudo cscli metrics                                         # CrowdSec metrics / Метрики CrowdSec
sudo iptables -L -n                                        # Firewall rules / Правила файрвола
sudo cscli bouncers list                                   # Registered bouncers / Зарегистрированные bouncer'ы

Useful Commands

sudo cscli alerts list -o human                            # Top attackers / Топ атакующих
sudo cscli decisions delete --ip <IP>                      # Unban IP / Разбанить IP
sudo cscli scenarios list                                  # List scenarios / Список сценариев

11. Cowrie Log Analysis Script

watch_cowrie_commands.py

#!/usr/bin/env python3
"""Watch Cowrie Honeypot Commands.

Reads Cowrie logs and prints top commands entered by attacking IPs.
Скрипт читает логи Cowrie и выводит топ команд атакующих IP.
"""

import json
from pathlib import Path
from collections import Counter

log_dir = Path("/opt/cowrie/log")              # Path to Cowrie logs / Путь к логам
commands = Counter()

for log_file in log_dir.glob("cowrie.json*"):
    with log_file.open() as f:
        for line in f:
            try:
                evt = json.loads(line)
                if evt.get("eventid") == "cowrie.command.input":
                    ip = evt.get("src_ip", "")
                    cmd = evt.get("input", "").strip()
                    commands[(ip, cmd)] += 1
            except json.JSONDecodeError:
                continue

print("\nTop 10 commands by attacking IPs:\n")
for (ip, cmd), count in commands.most_common(10):
    print(f"{ip}: {cmd} ({count} times)")


On this page

linux SSH Honeypot + CrowdSec Sysadmin Cheatsheet 📚 Table of Contents 1. Overview Architecture 2. Install Docker 3. Move Real SSH to Port 2222 Edit SSH Config Apply Changes 4. Install Cowrie Honeypot 5. Save Honeypot Logs 6. Install CrowdSec 7. Install Cowrie Parser 8. Community Integration 9. Web Dashboard 10. Verify Detection &amp; Firewall Useful Commands 11. Cowrie Log Analysis Script watch_cowrie_commands.py 12. Documentation Links