Portsentry/TMP

Aus Foxwiki

TMP

Portsentry

Wer Ports auf fremden Rechnern abtastet, gilt nach vorherrschender Meinung nicht als Angreifer. Allerdings geht einer ernst gemeinten Attacke fast immer ein Portscan voraus. Mütter der Porzellankiste reagieren auf Portscans deshalb vorsorglich (“proaktiv” auf Consultingdeutsch), indem sie von der IP-Adresse, die den Portscan ausgeführt hat, für eine Zeit lang keine weiteren Verbindungen annehmen. Das dazu passende Werkzeug heißt Portsentry http://1 und gehört zum Umfang der meisten Distributionen. Der Daemon erkennt und loggt Portscans und führt daraufhin Kommandos aus.

In der Datei »/etc/default/portsentry« stelle ich den Erkennungsmodus ein:

TCP_MODE="tcp"
UDP_MODE="udp"

Wenn ich nicht will, dass Portsentry UDP-Ports überwacht, lösche ich die zweite Zeile. Ersetze ich »tcp« und »udp« durch »stcp« und »sudp« , reagiert das Tool sensibler und erkennt auch Stealth-Scans. Gebe ich »atcp« und »audp« an, bindet es alle unbenutzten Ports unterhalb von 1024 und meldet sie dem Angreifer als offen, woraufhin der Verdutzte genau so schlau ist wie vor seinem Scan.

Weiteren Raum fürs Setup öffnet »/etc/portsentry/portsentry.conf« . Hier darf ich Triggerports definieren, die als Portscan-Detektoren dienen. Die vorgegebene Auswahl ist recht gut, ich würde sie nur ändern, wenn ich auf einem dieser Ports einen Daemon betriebe.

Wichtiger ist es, die Sensibilität mit der Variablen »SCAN_TRIGGER« festzulegen. Beim Default »0« reagiert Portsentry sofort, wenn ein Triggerport anspricht. Werte wie »1« oder »2« reduzieren die Empfindlichkeit und damit die falsch-positiven Alarme. Dem gleichen Ziel dient »ADVANCED_EXCLUDE_TCP=« : Ports, die oft von fremden Hosts angesprochen werden wie Ident (Port 113) und Netbios (Port 139), klammert der »atcp« -Modus explizit aus, ebenso wie -»ADVANCED_EXCLUDE_UDP-« die UDP-Ports 67, 137, 138 und 520 (DHCP, Netbios, RIP).

Per Default reagiert Portsentry nicht auf Scans, sondern schreibt nur einen Log-Eintrag. Dieses Verhalten steuern:

BLOCK_UDP="0"
BLOCK_TCP="0"

Eine »1« an dieser Stelle bewirkt, dass IP-Adressen, von denen Portscans ausgehen, sich nicht mehr verbinden können, weil Portsentry das Kommando

/sbin/route add -host $TARGET$ reject

ausführt, das alle Anfragen mit Connection Refused abbügelt (Abbildung 1). Die IP-Adresse, von der der Portscan ausging, landet außerdem in der Datei »/var/lib/portsentry/portsentry.blocked« und bleibt dort bis zum Neustart des Daemon.

"Abbildung 1: Portsentry initialisiert sich und detektiert Portscans entsprechend seiner Konfiguration."

Abbildung 1: Portsentry initialisiert sich und detektiert Portscans entsprechend seiner Konfiguration.

Waffe gesichert

Um zu verhindern, dass eigene Systeme in Portsentrys Fänge geraten, gibt es die Datei »/etc/portsentry/portsentry.ignore.static« . Hier kann ich einzelne Hosts oder ganze Netze definieren, die von allen Gegenmaßnahmen verschont bleiben. Apropos: Wenn ich »BLOCK_TCP« und »BLOCK_UDP« auf »2« stelle, führt Portsentry jeden Befehl aus, den ich in »KILL _RUN_CMD« hinterlege – das Alarmieren per SMS oder Ähnliches, es bedient aber auch die Großkaliberwaffe Metasploit für brutale Gegenschläge. Bedenke: Es wirkt ungehobelt, jedem die Doppelläufige in die Nasenlöcher zu schieben, der zaghaft an die Tür klopft.

Infos# Portsentry: http://sourceforge.net/projects/sentrytools/

# https://www.linux-magazin.de/ausgaben/2012/02/einfuehrung2/

Portsentry

Ihre Server evtl. unterschiedliche Portscans zu identifizieren, z. B. Dienste, die auf vorhanden sind Ihre Server oder sogar das Betriebssystem installiert (Das ermöglicht beispielsweise Nmap, ). Diese Informationen könnten dann ausgenutzt werden, wenn eine böswillige Person, die Integrität der erreichen Ihre Server.

Zum Schutz gegen diese Praktiken können Sie Portsentry implementieren, die die IP-Adressen der Verbindungen am Ursprung der diese Scans blockiert wird.

Portsentry kann eine Ergänzung zum Scheitern verurteilt sein 2verbieten wollen Sie die Sicherheit verbessern Ihre Server. In der Tat fehl 2verbieten, Blockieren von IP-Adressen der Verbindungen, die erfolglose während Portsentry Authentifizierung, er führt eine Sperrung von IP-Adressen, die darauf abgezielt werden, offene Ports zu identifizieren Ihre Server. Beide Pakete können ergänzt werden und somit zur Erhöhung der Sicherheits Ihrer Server.

Wir beginnen, indem Sie die Installation des Pakets die uns, mit dem folgenden Befehl betrifft :

root@flex:~# apt-get update && apt-get install portsentry

Eine Warnmeldung wird Ihnen sagen, dass Portsentry gelten keine Blockierung, wenn Sie, es sagen zu tun : "Portsentry.png"

Sobald die Installation abgeschlossen ist, werden wir daher mit Portsentry Konfiguration fortfahren.

In einem ersten Schritt beenden wir Dienst :

root@flex:~# /etc/init.d/portsentry stop Stopping anti portscan daemon: portsentry.

Wir setzen dann die Ausnahmen nicht zu verschiedenen IP-Adressen blockieren (zumindest Ihre IP-Adresse sowie die IP-Adressen der Servers der Überwachung usw..).

Für die Strände von IP-Adressen ermöglichen und von unserem Server Überwachung, entnehmen Sie bitte den folgenden Artikel : https://fr.ikoula.wiki/fr/Quelles_sont_les_IP_%C3%A0_autoriser_dans_mon_firewall_pour_qu%27Ikoula_ait_acc%C3%A8s_%C3%A0_mon_Server

Um diese Ausnahmen zu implementieren, bearbeiten wir die Datei /etc/portsentry/portsentry.ignore.static

Zu Beginn des Dienstes, werden der Inhalt der Datei in die Datei hinzugefügt /etc/portsentry/portsentry.ignore.

Portsentry eine Ausnahme hinzu, fügen Sie einfach eine IP-Adresse pro Zeile. Sie können auch und gerade einen hinzufügen oder ein CIDR.

Nun, da Sie hinzugefügt haben Ihre /Ihre IP-Adressen in der Liste Weiße, wir konfiguriere Portsentry, richtig gesprochen durch Bearbeiten der Konfigurationsdatei das über /etc/portsentry/portsentry.conf.

Wir benutzen Portsentry im erweiterten Modus für die Protokolle TCP und UDP. Hierzu müssen Sie die Datei ändern /etc/default/portsentry um :

TCP_MODE="atcp" UDP_MODE="audp"

Wir möchten auch, dass diese Portsentry eine Blockade ist. Deshalb müssen wir es aktivieren, indem Sie BLOCK_UDP und BLOCK_TCP zu übergeben 1 wie unten beschrieben :

################## # Ignore Options # ################## # 0 = Do not block UDP/TCP scans. # 1 = Block UDP/TCP scans. # 2 = Run external command only (KILL_RUN_CMD)

BLOCK_UDP="1" BLOCK_TCP="1"

Wir entscheiden Sie sich für eine Sperrung von böswilligen Personen über Iptables. Wir werden daher auf allen Linien der Konfigurationsdatei, die mit KILL_ROUTE, mit Ausnahme der nächsten beginnen Kommentar :

KILL_ROUTE="/sbin/iptables -I INPUT -s $TARGET$ -j DROP"

Sie können überprüfen, ob dies der Fall, sobald die gespeicherte Datei mit Katze und Grep ist :

cat portsentry.conf | grep KILL_ROUTE | grep -v "#"

Wir können jetzt starten Dienst Portsentry und es beginnt nun die Portscans blockieren :

root@flex:~# /etc/init.d/portsentry start Starting anti portscan daemon: portsentry in atcp & audp mode.

Portsentry protokolliert in der Datei /var/log/syslog und wie Sie unten sehen können, einen Anschluss für die Betreuung des Lernprogramms mit Nmap hergestellt nach, Scan die Adresse wurde blockiert, durch Iptables :

Mar 17 16:59:02 sd-24527 portsentry[6557]: adminalert: PortSentry is now active and listening. Mar 17 17:00:29 sd-24527 portsentry[6553]: attackalert: Connect from host: 178.170.xxx.xxx/178.170.xxx.xxx to TCP port: 1 Mar 17 17:00:29 sd-24527 portsentry[6553]: attackalert: Host 178.170.xxx.xxx has been blocked via wrappers with string: "ALL: 178.170.xxx.xxx : DENY" Mar 17 17:00:29 sd-24527 portsentry[6553]: attackalert: Host 178.170.xxx.xxx has been blocked via dropped route using command: "/sbin/iptables -I INPUT -s 178.170.xxx.xxx -j DROP" Mar 17 17:00:29 sd-24527 portsentry[6553]: attackalert: Connect from host: 178.170.xxx.xxx/178.170.xxx.xxx to TCP port: 79 Mar 17 17:00:29 sd-24527 portsentry[6553]: attackalert: Host: 178.170.xxx.xxx is already blocked. Ignoring [...]

Wenn Sie einen Block werfen möchten, können Sie überprüfen die IP Adressen über Iptables verboten. Gibt es die IP, die blockiert wurde nach unserem vorherigen Test :

root@flex:~# iptables -L -n -v Chain INPUT (policy ACCEPT 52381 packets, 6428K bytes)

pkts bytes target prot opt in out source destination
794 42696 DROP all -- *  *  178.170.xxx.xxx 0.0.0.0/0

Also lasst uns den Eintrag löschen :

iptables -D INPUT -s 178.170.xxx.xxx -j DROP

PS : vergessen Sie nicht, die IP-Adressen erlauben unsere Servers der Überwachung in den Ausnahmen von Portsentry vermeiden Fehlalarme und verursachen unnötige Warnungen.

https://de-wiki.ikoula.com/de/Zum_Schutz_vor_der_Untersuchung_der_Ports_mit_portsentry

Mit Portsentry Portscans vermeiden

Mit PortSentry könnt Ihr ausgewählte Ports auf Port Scans überwachen und die Port Scan Quelle blockieren. Damit kriegen Angreifer sofort die Türen zu gemacht und werden schon vorm Versuch in den Server einzudringen ausgesperrt. Allesdings muss dafür ein Port offen gelassen werden, hier müsst Ihr selber entscheiden was Euch lieber ist, Ports schließen oder offen lassen…

In diesem Beispiel werden die Ports 22 und 23 offen gelassen und sobald darauf ein Scan statt findet, wird diese IP für min. 30 Minuten gesperrt. Dafür wird ein Script und die Beschreibung von Rob-Schulze.de verwendet. Vielen Dank an dieser Stelle für das Script und Tutorial!!!

Die Installation wird mit apt-get durchgeführt:

apt-get install portsentry

Die Konfigurationsdatei liegt im Pfad /etc/portsentry/portsentry.conf. Hier müssen diverse Einstellungen getätigt werden, zunächst empfehle ich zu prüfen, ob in der Datei alle Einträge die mit

KILL_ROUTE== beginnen auskommentiert sind. Wenn nicht, dann müssen diese Einträge auskommentiert werden.

Selbiges gilt für die folgenden Einträge:

TCP_PORTS== UDP_PORTS== Anstatt dessen werden nun folgende Werte in die Datei eingetragen:

TCP_PORTS=“22,23″

UDP_PORTS=“22,23″

KILL_RUN_CMD=“/etc/portsentry/filtermgr -a $TARGET$“

TCP_PORTS und UDP_PORTS definieren die Ports, die geprüft werden sollen. Hier können auch weitere Ports durch ein „,“ getrennt eingetragen werden. Die Firewall darf natürlich nicht diesen Port blocken. Wenn auf Port 22 gelauscht werden soll, dann ist es wichtig, dass vorher der SSH-Port umgelegt wurde, da man sich ansonsten im schlimmsten Fall aussperren kann.

Die folgenden Werte werden von der Default-Einstellung „0“ auf „2“ geändert, damit ein das externe Script von Rob Schulze überhaupt aufgerufen werden kann:

BLOCK_UDP="2"

BLOCK_TCP="2"

Jetzt wird das Script von Rob Schulze benötigt:

cd /etc/portsentry

wget http://www.rob-schulze.de/informatik/tutorials/portsentry/rcportsentry

chmod 700 rcportsentry

Dieses Script muss editiert werden, u.a. muss hier der Pfad zur iptables und zum Pfad von der PortSentry-Konfiguration angegeben werden:

my $BASE_DIR=“/etc/portsentry“;

my $BLOCK_FILE=“/var/lib/portsentry/portsentry.blocked“;

my $IPTABLES_CMD=“/sbin/iptables“;

my $BLOCK_TIMEOUT=60*30;

Der Wert BLOCK_TIMEOUT gibt die Sperrzeit in Sekunden an. Hier kann auch gerechnet werden, also 60*30 wären somit 1800 Sekunden oder 30 Minuten.

Damit die gesperrten IP-Adressen auch wieder freigegeben werden ist es notwendig, dass per Crontab das Script von Rob Schulze die iptables-Regeln wieder entfernt. Ich rufe das Script alle 30 Minuten auf, somit ist eine IP-Adresse im schlimmsten Fall 60 Minuten oder im schnellsten Fall nur 30 Minuten gesperrt. Hier der Crontab-Eintrag:

*/30 * * * * /etc/portsentry/filtermgr -d

Ich nutze ein Firewall-Script zum starten der „Sicherheits“programme auf dem vServer. Portsentry wird automatisch beim Systemstart geladen, allerdings soll Portsentry im Firewall-Script integriert werden, deshalb wird der automatische Start wie folgt aufgehoben:

update-rc.d -f portsentry remove

Das Firewall-Script inkl. der Einträge für PortSentry sieht dann so aus (die neuen Einträge sind durch #### vorher gekennzeichnet, damit Ihr diese leichter erkennt):

#!/bin/sh

# script written by Gargi 2009 http://www.gargi.org

#needed modules

modprobe ip_conntrack_ftp

BLACKLIST=/usr/local/etc/blacklist.txt

#trigger for your ports

IN_ALLOWED_TCP=“21 22 23 25 53 80″

OUT_ALLOWED_TCP=“21 22 23 25 53 80″

IN_ALLOWED_UDP=“53 7878″

OUT_ALLOWED_UDP=“53″

IN_ALLOWED_ICMP=“ “

OUT_ALLOWED_IMCP=“ “

case „$1“ in

start)

##### Stopping PortSentry

/etc/init.d/portsentry stop

# Stopping IP trap

/etc/init.d/fail2ban stop

echo „Stopping fail2ban IP trap …“

# Clear iptables

iptables -F

#Defaults

iptables -P INPUT DROP

iptables -P OUTPUT DROP

iptables -P FORWARD DROP

# loopback communication

iptables -A INPUT -i lo -j ACCEPT

iptables -A OUTPUT -o lo -j ACCEPT

# persist on connections

iptables -A INPUT -m state –state ESTABLISHED,RELATED -j ACCEPT

iptables -A OUTPUT -m state –state ESTABLISHED,RELATED -j ACCEPT

# Ban blacklisted IPs

for x in `grep -v ^# $BLACKLIST | awk ‚{print $1}’`; do

echo „Blocking $x…“

iptables -A INPUT -t filter -s $x -j DROP

done

# TCP rules in

for port in $IN_ALLOWED_TCP; do

echo „Accepting TCP port $port“

iptables -A INPUT -t filter -p tcp –dport $port -j ACCEPT

done

# TCP rules out

for port in $OUT_ALLOWED_TCP; do

echo „Allowing sending over TCP port $port“

iptables -A OUTPUT -t filter -p tcp –dport $port -j ACCEPT

done

# UDP rules in

for port in $IN_ALLOWED_UDP; do

echo „Accepting UDP port $port“

iptables -A INPUT -t filter -p udp –dport $port -j ACCEPT

done

# UDP rules out

for port in $OUT_ALLOWED_UDP; do

echo „Allowing sending over UDP port $port“

iptables -A OUTPUT -t filter -p udp –dport $port -j ACCEPT

done

# ICMP rules in

for port in $IN_ALLOWED_ICMP; do

echo „Accepting ICMP port $port“

iptables -A INPUT -t filter -p icmp –dport $port -j ACCEPT

done

# ICMP rules out

for port in $OUT_ALLOWED_ICMP; do

echo „Allowing sending over ICMP port $port“

iptables -A OUTPUT -t filter -p icmp –dport $port -j ACCEPT

done

# Dropping startup requests

iptables -A INPUT -t filter -p tcp –syn -j DROP

# Restarting IP trap

/etc/init.d/fail2ban start

echo „Fire up IP trap again …“

##### Restating PortSentry

/etc/init.d/portsentry start

ps -ef | grep „portsentry -tcp“ | grep -v grep | awk ‚{print $2}‘ > /var/run/portsentry-tcp.pid

ps -ef | grep „portsentry -udp“ | grep -v grep | awk ‚{print $2}‘ > /var/run/portsentry-udp.pid

;;

stop)

/etc/init.d/portsentry stop

/etc/init.d/fail2ban stop

iptables -F

iptables -P INPUT ACCEPT

iptables -P OUTPUT ACCEPT

echo „Warning! Firewall is stopped, server is unprotected now!“

;;

restart)

$0 stop

sleep 1

$0 start

;;

*)

echo „Usage $0 {start|stop|restart}“

;;

esac

# https://splittscheid.de/mit-portsentry-portscans-vermeiden/

Mehr Sicherheit durch portsentry

Die meisten Angriffe auf Systeme beginnen mit einem portscan, das hier erklärte Tool portsentry erkennt diese und leitet Gegenmaßnahmen ein. Man kann dem Angreifer blocken oder aber ihm einfach sagen, um ihn zu verwirren, dass alle Ports offen sind. Das Tool kann auch Gegenangriffe ausführen, was aber nicht wirklich zu empfehlen ist, da es ja auch ungefährliche Portscans gibt.

Installation

unter Debian / Ubuntu einfach:

aptitude install portsentry

Standardmäßig loggt portsentry nur, erst nach editieren der Konfigurationsdatei /etc/portsentry/portsentry.conf führt es auch Aktionen aus.

Konfiguration

/etc/default/portsentry

# /etc/default/portsentry # # This file is read by /etc/init.d/portsentry. See the portsentry.8 # manpage for details. # # The options in this file refer to commandline arguments (all in lowercase) # of portsentry. Use only one tcp and udp mode at a time. # TCP_MODE="stcp" UDP_MODE="sudp"

Die Beiden Schalter stcp und sudp sorgen dafür das auch Stealth Scans erkannt werden. Bei der Konfiguration ist zu beachten, das falls eine Firewall eingesetzt wird, ein Port aufgemacht werden muss auf dem dann der Portscanner läuft. Zum Beispiel kann man den SSH Port umlegen und den Port 22 per portsentry überwachen. Portsentry kann nicht auf einem bereits vorhandenen Port lauschen! /etc/portsentry/portsentry.conf

TCP_PORTS="22" Block_TCP="1" Block_UDP="1" KILL_ROUTE="/sbin/route add -host $TARGET$ reject" SCAN_TRIGGER="1"

Quellen

Portsentry

Portsentry7 ist Teil des Abacus-Projektes, einer Sammlung von Security-Tools. Alle Programme des Abacus-Projektes zeichnen sich durch einfache Konfiguration aus und sind wartungsfrei zu betreiben.8

Portsentry überwacht die TCP/UDP-Ports eines Systems. Es erkennt Portscans, die gegen das System gerichtet sind. Dabei spürt es mit verschiedenen Betriebsarten (Classic Mode, Enhanced Stealth Mode, Advanced Stealth Mode) unterschiedliche Arten von Stealth-Scans, wie z.B. SYN/half-open, FIN, NULL und X-MAS auf. Portsentry arbeitet sehr ressourcensparend. Es muß nur einmal gestartet werden und überwacht beliebig viele Ports. Alle Angriffsversuche werden in den Systemlogdateien mitprotokolliert.

Portsentry antwortet auf versuchte Portscans, indem es den angreifenden Computer blockt:* Die lokale Route der Pakete kann zurück zum Angreifer gesetzt werden

  • Der angreifende Computer wird in die Datei hosts.deny eingetragen
  • Es wird eine Regel in das Firewallskript eingefügt

Die meisten Angriffe werden so im Keim erstickt.

Portsentry sollte in eine der Startdateien (z.B. /etc/rc.d/rc.local) eingetragen werden, um nach dem Booten automatisch seinen Dienst zu verrichten.

Portsentry-Konfiguration:

Portsentry wird über die Datei /usr/local/psionic/portsentry/portsentry.conf konfiguriert.

Einige wichtige Abschnitte der Konfigurationsdatei:* Port Configurations

Hier werden die Ports angegeben, die überwacht werden sollen. Standardmäßig stehen drei Portbereiche zur Auswahl bereit.* Advanced Stealth Scan Detection Options

Hier werden die Ports für den erweiterten Modus angegeben. Standardmäßig werden alle privilegierten Ports überwacht.* Configuration Files

Lage der Dateien, die die geblockten Rechner enthalten.* Response Options

In diesem Abschnitt wird bestimmt, was bei einem entdeckten Portscan geschehen soll. Eine der folgenden Optionen kann genutzt werden:* Ignore Options

  • Den Portscan nicht blocken (Do not block UDP/TCP scans)
  • Den Portscan blocken (Block UDP/TCP scans)
  • Ein externes Kommando starten (Run external command only)
  • Dropping Routes

Hier lassen sich die Pakete des Angreifers durch eine Firewallregel blocken

KILL_ROUTE="/sbin/ipchains -I input -s $TARGET$ -j DENY -l"* Scan trigger value

Hier läßt sich die Anzahl von Verbindungen bestimmen, bevor ein Alarm ausgelöst wird. Als Standard ist 0 angegeben, dies bewirkt einen Alarm beim ersten Verbindungsversuch. Eine größere Zahl sollte die Anzahl der falschen Alarme vermindern.

# https://www.pro-linux.de/artikel/2/1021/5,portsentry.html?cop=300

Portsentry to block port scans

Debian11 Server GNU Linux Linux Debian Debian 10 Debian 11 Buster Bullseye Server Installation Portsentry Fail2ban Security IPTables TCPWrappers

Installing and configuring Portsentry as a second line of defense against port scanning, after IPTables lscan and psd rules. It will ban attacker’s machines temporarily of definitely, but will whitelist my own network and IP addresses.

Portsentry presentation

Portsentry listen to most unused network ports. It receives all the incoming connections and can detect sequences of connections from a source to detect a network port scan. Then, it can react with arbitrary commands, to block the scans, to return garbage, to trigger countermeasures… Most scans will be detected and blocked by the IPTables chain, PortSentry is configured as a second line of defense. It will use TCPWrappers and IPTables to block the scans on UDP and TCP. It will also be configured to ignore my own IP addresses.

Prerequisites

This article only depends on the Generic machine preparation post serie.

Existing variables

We need the LAN_* variable which was already defined in the configuration file, the Configuration variables post.

Reload the variables

Ensure that the variables are available, by loading the configuration script :

source /root/config.env

Common installation

I first pre-configure the answer to a question that would otherwise be asked by the package and I install it.

echo portsentry portsentry/warn_no_block string "" | debconf-set-selections apt-get install -y portsentry

Automatic bind to unused ports

Configure portsentry to use the advanced mode, which listen to all the ports below a threashold, both for UDP and TCP. This could be an issue if a service try to bind himself, later to a dynamic port and if portsentry is already bound to this port. By default, the threshold is set to 1024

sed -i 's/TCP_MODE="tcp"/TCP_MODE="atcp"/' /etc/default/portsentry sed -i 's/UDP_MODE="udp"/UDP_MODE="audp"/' /etc/default/portsentry

Block scans with IPTables, CHAOS and TCPWrappers

Then, let’s activate the scan blocking using IPTables and TCPWrappers. Portsentry will execute the provided iptables command and add the attacking host in the /etc/hosts.deny file. Both are useful because IPTables is not persistent, whereas TCP wrappers is persistent. Furthermore, I provide my own iptables command to use the CHAOS target instead of DROP. The attacker knows that there is machine, ignoring the packets would inform him that we are protecting the machine and he will try something else. Using the CHAOS target returns random data, it will not look like we are protecting ourself but will not provide him useful information. It would be better to insert the iptable blocking rules after the iptables whitelist rule, and before the ACCEPT rules. I would need to know the white list rule number to do that, so I’d need to create a whitelist iptables chain in the IPTable configuration, but I did not. You can improve your scripts.

sed -i 's/BLOCK_UDP="0"/BLOCK_UDP="1"/' /etc/portsentry/portsentry.conf sed -i 's/BLOCK_TCP="0"/BLOCK_TCP="1"/' /etc/portsentry/portsentry.conf sed -i 's/RESOLVE_HOST = "0"/RESOLVE_HOST = "1"/' /etc/portsentry/portsentry.conf sed -i 's/^KILL_ROUTE/#&/' /etc/portsentry/portsentry.conf sed -i 's/^#\?KILL_ROUTE="\/sbin\/iptables -I INPUT -s $TARGET$ -j DROP"/KILL_ROUTE="\/sbin\/iptables -I INPUT -s $TARGET$ -j CHAOS"/' /etc/portsentry/portsentry.conf

Whitelist safe IPs

I can make some mistake, I could want to scan my own server… But I dont want to be blocked. Thus, I add my own IP address in the list to ignore and, just in case, I also add it to the TCPWrapper’s whitelist.

echo "ALL: ${LAN_IP}/${LAN_NM}" >> /etc/hosts.allow echo "${LAN_IP}/${LAN_NM}" >> /etc/portsentry/portsentry.ignore.static

Apply the configuration

systemctl restart portsentry

Strengthen with Fail2ban

Fail2ban can use portsentry log to take further actions. When portsentry blocks a scan, it blocks it with iptables for TCP and UDP scans, but this is not persisted in case of server reboot or service restart. It uses also TCPWrappers, which are persisted. fail2ban will double block using iptables, but it also has a persisted database and will restore the blocking rules in case or restart.

> /var/lib/portsentry/portsentry.history cat << EOF > /etc/fail2ban/jail.d/portsentry.conf [portsentry] enabled = true EOF systemctl restart fail2ban # https://fcerbell.github.io/Debian113Server080Portsentrytoblockportscans-en/

PortSentry - Port scan detection and active defense

E-Mail : craigrowland at users dot sourceforge dot net Date : 05-23-2003 Version: 1.2

Introduction

This is the "long" install version. You should read this file if you want to understand everything going on and the method to the madness in the program logic. Skip to Install down below if you don't care about this.

More information can be obtained from http://sourceforge.net/projects/sentrytools

PortSentry has a number of options to detect port scans, when it finds one it can react in the following ways:

- A log indicating the incident is made via syslog()
- The target host is automatically dropped into /etc/hosts.deny
for TCP Wrappers
- The local host is automatically re-configured to route all
traffic to the target to a dead host to make the target system
disappear.
- The local host is automatically re-configured to drop all
packets from the target via a local packet filter.

The purpose of this is to give an admin a heads up that their host is being probed. There are similar programs that do this already (klaxon, etc.) We have added a little twist to the whole idea (auto-blocking), plus extensive support for stealth scan detection.

PortSentry has four "stealth" scan detection modes. Method one uses a pre-defined list of ports to watch over. If someone pokes at them it activates. The second method is what is called "inverse" port binding, where every port under a range is watched *except* for those that the system has bound for network daemons when the PortSentry starts or ones that you've manually excluded. This is a very sensitive way for looking for port probes, but also the most prone to false alarms.

Install

Step ONE

Pull the portsentry_config.h file into your editor and make sure the following are to your liking:

CONFIG_FILE - The path to the PortSentry configuration file. WRAPPER_HOSTS_DENY - The path and name of TCP wrapper hosts.deny file. SYSLOG_FACILITY - The syslog facility for PortSentry to use. SYSLOG_LEVEL - The syslog level to send messages.

We suggest not changing any of these options unless you know what you are doing.

NOTE: For advanced users, you may wish to change the SYSLOG_FACILITY from LOG_DAEMON to LOG_LOCAL0 (or one of the other LOCAL reporting facilities). This will allow you to edit the syslog.conf file and drop PortSentry messages direcly to its own file on the system for separate monitoring.

SECOND NOTE: DO NOT DELETE THE "#" SIGNS FROM THIS FILE. They are NOT comments, they are required by the C compiler to pre-process the headers. If you delete the "#" signs you will get compile errors.

Step TWO

Next, pull in portsentry.conf into your editor and check/change the following options:

TCP_PORTS - A comma delimited string of TCP ports you want PortSentry to listen to. This string can NOT have any spaces in it. You can put in as many sockets as you want. PortSentry will try to bind them all up until the default limit of 64.

For the stealth scan detection modes, the ports are not "bound" per se, but they are monitored at the socket level for connections.

For the Advanced Stealth Scan Detection (see below). This list is *ignored*

UDP_PORTS - The same as above, except for UDP ports. You need to be very careful with UDP mode as an attacker can forge a port sweep and make you block any number of hosts. Use this option with caution, or not at all if your host is a well-known Internet connected system.

For the Advanced Stealth Scan Detection (see below). This list is *ignored*

ADVANCED_PORTS_TCP - A number indicating the highest port number to monitor down from. Any port *below* this number is then monitored. The default is 1024 (reserved port range), but can be made as large as 65535 (system max). It's not recommended going over 1024 with this option.

ADVANCED_PORTS_UDP - Same as above, except for UDP.

ADVANCED_EXCLUDE_TCP - A comma delimited string of TCP ports that should be manually excluded from monitoring in Advanced mode. These are normally ports that may get hit by mistake by remote clients and shouldn't cause alarms (ident, SSL, etc).

ADVANCED_EXCLUDE_UDP - Same as above, except for UDP.

IGNORE_FILE - The path to the file that contains IP addresses of hosts you want to always be ignored. This will be explained later.

BLOCKED_FILE - The path to the file that contains the IP addresses of blocked hosts.

RESOLVE_HOST - This option turns off DNS resolution for hosts. If you have a slow DNS server it may be more effective to turn off resolution.

BLOCK_UDP - This option disables all automatic responses to UDP probes. Because UDP can be easily forged, it may allow an attacker to start a denial of service attack against the protected host, causing it to block all manner of hosts that should normally be left alone. Setting this option to "0" will disable all responses, although the connects are still logged. This option is mainly useful for Internet exposed hosts. For internal hosts you should leave this enabled. If someone internally is firing spoofed packets at you, then you have a much bigger problem than a denial of service.

BLOCK_TCP - Same as above, but for TCP. Packet forgery is not as big a problem though because PortSentry waits for a full connect to occur and this is much harder to forge in the basic modes. Leave this enabled, even for Internet connected hosts. For stealth scan detection modes the UDP warning applies:

An attacker can cause you to block hosts you don't want to
through packet forgery.

KILL_ROUTE - This is the command to run to drop the offending route if an attack is detected. This is the *full path* to the route command along with the necessary parameters to make the command work. The macro $TARGET$ will be substituted with the attacking host IP and is REQUIRED in this option. Your gateway should be a *dead host* on the local subnet. On some systems though you can just put in the localhost address (127.0.0.1) and this will probably work. All packets from the target host will get routed to this address so don't mess this up. More modern route commands will include a "-blackhole" or "-reject" flag. Check your man(1) pages and if your route command supports this feature you should use it (although it's recommended using packet filtering instead, see below).

Also be aware that this creates what is known as an "asynchronous route" which basically means packets enter your host via one route and are sent out on another (dead) route. This works OK for full TCP connect requests, but for UDP and stealth scan modes it still allows packets to activate PortSentry and you may get a series of "already blocked" alarms by PortSentry. For UDP scans this method prevents ICMP messages from returning to the attacker so all ports appear open. However, if the attacker is performing an actual exploit with UDP the drop route method will not work. The asynchronous route allows the packet to hit the system and the attacker could perform a "blind" attack with UDP if they know what the responses are going to be.

By far the best method is to use the local packet filter (such as Linux ipfwadm/ipchains or *BSD ipfw). This is a much cleaner solution and is detailed in the config file. The macro $PORT$ will substitute the port that was connected to by the attacker, but this is NOT required for this option. The macro $MODE$ reports what mode the blocking occurred in (tcp, udp, stcp, sudp, atcp, audp) but is also NOT required.

KILL_HOSTS_DENY - This is the format of the string to drop into the hosts.deny file that TCP wrappers uses. Again the $TARGET$ macro is expanded out to be the IP of the attacker and is required. You can also drop in any TCP wrapper escape codes here as well (%h, twist, etc). The macro $PORT$ will substitute the port that was connected to by the attacker, but this is NOT required for this option. The macro $MODE$ reports what mode the blocking occurred in (tcp, udp, stcp, sudp, atcp, audp) but is also NOT required.

KILL_RUN_CMD - This is a command you want run *before* the route is dropped to the attacker. You can put in any program/script you want executed when an attack is detected. WE NEVER RECOMMEND PUTTING IN RETALIATORY ACTION AGAINST AN ATTACKING HOST. Virtually every time you're are port scanned the host doing the scanning has been compromised itself. Therefore, if you retaliate you are probably attacking an innocent(?) party. Also the goal of security is to make the person GO AWAY. You don't want to irritate them into making a personal vendetta against you. Remember, even a 13 year old can run a [insert favorite D.O.S. program here] attack against you from their Windows box to make your life miserable. As above, the $TARGET$, $PORT$, and $MODE$ macros are available to you but they are not required with this option as above.

KILL_RUN_CMD_FIRST - Setting this to "0" makes the command above run before the route is dropped. Setting it to "1" makes the command run aftter the blocking has occurred.

SCAN_TRIGGER - PortSentry has a state engine that will remember hosts that connected to it. Setting this value will tell PortSentry to allow X number of grace port hits before it reacts. This will detect both sequential and random port sweeps. The default is 0 which will react immediately. A setting of 1 or 2 will reduce false alarms, anything higher is probably too much as anything more than 3 hits to different ports is pretty suspicious behavior. Usually you can leave this at 0 without any consequence, with the exception of Advanced stealth scan detection modes where you may create a "hair trigger" if you aren't careful. Use your own discretion.

PORT_BANNER - A text banner you want displayed to the connecting host if the PortSentry is activated. Leave this commented out if you don't want this feature. If you do use it, try not to taunt the person too badly. It's recommended keeping it professional and to the point. The banner is *not* displayed when stealth scan detection modes are used.

Step THREE

Pull the portsentry.ignore file into your editor and add in any host you want to have ignored if it connects to a tripwired port. This should always contain at least the localhost (127.0.0.1) and the IP's of the local interfaces. We would *not* recommend putting in every machine IP on your network, but you can use a netmask to do this. Format for this is:

<IP Address>/<Netmask Bits>

192.168.2.0/24 192.168.0.0/16 etc.

We don't recommend ignoring too much. It may be important for you to see who is connecting to you, even if it is a "friendly" machine. This can help you detect internal host compromises faster. To answer your paranoia, yes this does happen and we've had cases of admins ignoring too much and getting hacked by their own machines as a result with no warning.

Step FOUR

Compile. Type make and pick your system type and allow it to build and install. The default directory is /usr/local/psionic/portsentry. If you don't like this directory just edit the Makefile and make sure your portsentry.conf and portsentry_config.h files reflect the new path.

Type make install after the build to have it copy files to your install directory.

Step FIVE

Start up PortSentry. PortSentry has six modes of operation. ONLY ONE PROTOCOL MODE TYPE CAN BE STARTED AT A TIME (i.e. one TCP mode and one UDP mode) The available modes are:

portsentry -tcp (basic port-bound TCP mode)
portsentry -udp (basic port-bound UDP mode)
portsentry -stcp (Stealth TCP scan detection)
portsentry -atcp (Advanced TCP stealth scan detection)
portsentry -sudp ("Stealth" UDP scan detection)
portsentry -audp (Advanced "Stealth" UDP scan detection)
-tcp - Basic port-bound TCP mode

PortSentry will check the config files and then bind to all the TCP ports in the background. If you want to check the init status you should just look in your local syslog file that you are having the messages directed to.

-udp - Basic port-bound UDP mode

PortSentry will check the config files and then bind to all the UDP ports in the background. If you want to check the init status you should just look in your local syslog file that you are having the messages directed to. UDP/Stealth scan warnings apply (read: README.stealth).

-stcp - Stealth TCP scan detection mode

PortSentry will use a raw socket to monitor all incoming packets. If an incoming packet is destined for a monitored port it will react to block the host. This method will detect connect() scans, SYN/half-open scans, and FIN scans. UDP/Stealth scan warnings apply (read: README.stealth).

-sudp - "Stealth" UDP scan detection mode

This operates the same as the TCP stealth mode above. UDP ports need to be listed and they are then monitored. This does not bind any sockets, and while not really "stealth" scan detection (doesn't usually apply to UDP), it operates in a similar manner (reacts to *any* UDP packet). UDP/Stealth scan warnings apply (read: README.stealth).

-atcp - Advanced TCP stealth scan detection mode

PortSentry will start by making a list of all the ports listening in the port area under the ADVANCED_PORTS_TCP option and will then create an exclusion list based on these ports. Any host connecting to *any port* in this range that is *not excluded* (i.e not a listening network daemon [SMTP, HTTP, etc.]) is blocked. This has some very powerful implications that you should be aware of:

1) This mode is the most sensitive and the most effective of all the protection options. It reacts to port probes with lightning speed because you don't have to wait for them to hit a tripwired port.

2) Because it reacts so abruptly, you may cut off legitimate traffic. A FTP site may send an ident request at you. If you are monitoring the ident port (113 TCP) then you have just cut off the FTP site you were going to! As a result you should put in ports that fall into this situation in this list.

** Advanced Logic Mode ** - PortSentry is intelligent about how it monitors ports. For some protocols such as FTP the client actually opens up ports in the ephemeral range (1024-65535) and the server then connects *back* to you. This would normally cause the port scanner to activate. PortSentry though will look at the incoming connection and determine if it is destined for one of these "temporary" bindings. If it is, then the connection is ignored for that one time. As soon as the connection is torn down the window closes and full protection is back again. This is in fact a rudimentary stateful inspection engine. UDP/Stealth scan warnings apply (read: README.stealth).

-audp - Advanced UDP "stealth" scan detection mode

This is the same as above except for the UDP protocol. This is a very advanced option and you stand a good chance of causing false alarms. This is because PortSentry makes no distinction between broadcast and direct traffic. If you have a router on your local network putting out RIP broadcasts then there is a good likelihood you will block them. Use this option with extreme caution. You need to be sure you put in these exclusions into the ADVANCED_EXCLUDE_UDP line (i.e 520 [RIP]) UDP/Stealth scan warnings apply (read: README.stealth).

Test the install

Tail the local log and you should see several PortSentry initialization messages.

A successful startup looks like this:

Oct 9 09:11:35 nemesis portsentry[1644]: adminalert: portsentry is starting.
Oct 9 09:11:36 nemesis portsentry[1644]: adminalert: Going into listen mode on TCP port: 143
. . .
Oct 9 09:11:37 nemesis portsentry[1644]: adminalert: PortSentry is now active and listening.

************************************************************************ ** The last line indicates the PortSentry is properly initialized, if ** ** you don't see it then something failed. ** ************************************************************************

You should see all the ports you told it to listen to in the log. If a port is in use PortSentry will give you a warning that it couldn't bind to it and will continue on until all the other ports are bound. If *none* of the ports could be bound it will exit with an error.

For the Advanced stealth scan detection mode it will list the ports that it will *not* listen for. This is an inverse binding.

Now you can go to another host and telnet to a booby-trapped port. DO NOT DO THIS FROM YOUR ONLY ACCESS POINT TO THE PROTECTED HOST BECAUSE YOU WILL BLOCK YOURSELF OFF COMPLETELY IF IT WORKS.

You should immediately see something like:

Oct 9 09:12:44 nemesis portsentry[1644]: attackalert: Connect from host: 123.345.56.78 to TCP port: 143
Oct 9 09:12:46 nemesis portsentry[1644]: attackalert: Host server.haxor.org/123.345.56.78 has been blocked via dropped route.
Oct 9 09:12:46 nemesis portsentry[1644]: attackalert: Host server.haxor.org/123.345.56.78 has been blocked via wrappers.

For advanced mode you can telnet to any port not excluded to trip an alarm.

If you disconnect and try to telnet back again you should find that the target system is now unreachable. Congratulations you are now operational.

If you are running Logcheck this will show up in the next pass and it should be screaming at you.

If you do a netstat -rn you will see the suspect host pointed at the dead route you supplied (unless using a packet filter, which is recommended).

Drop the PortSentry commands in a startup file and get back to work as you are done.

How will it help?

Here are some ideas:

- Run as a UDP service on port 69 to catch TFTP probes.
- Run as a UDP service on port 161,162 to catch SNMP probes.
- Run as a UDP service in the port range 32000-33000 to catch RPC
probes.
- Run as a TCP service on port 143 to catch IMAP probes.
- Run as a TCP service on ports 11,15 to catch netstat/systat
probes.
- etc.

The fact is that PortSentry reacts quickly enough that a port scan of your host by an attacker will be stopped within one second after hitting any tripwired port, even faster in the Advanced TCP stealth scan detection mode.

For any type of UDP scan it will prove highly irritating for the person trying to scan you as all the ports will likely appear "open." For TCP scans the attacker will simply get no response whatsoever.

Safety

If we missed anything in the program's safety considerations we would very much like to hear about it before you post it to BugTraq :).

Messages

To the best we could, all states/errors/successes and unknowns are written to the syslog. The following tags identify each one:

adminalert: - Some message indicating the status of the PortSentry. securityalert: - A message indicating a security relevant event occurred. attackalert: - A host has tripped a sensor and an action was performed.

Files

As it stands now, all hosts are dropped into the portsentry.blocked.* file when they are blocked as well as a portsentry.history file. The blocked file is erased each time PortSentry is restarted. The history file is simply appended to and can be used as a record of all hosts that have been blocked to date. The portsentry.blocked.* has an appended extension indicating what mode it applies to. I.E.:

portsentry.blocked.tcp
portsentry.blocked.udp
portsentry.blocked.stcp
portsentry.blocked.sudp
portsentry.blocked.atcp
portsentry.blocked.audp

Each file is created depending on what startup mode is selected and is removed when PortSentry re-starts.

The way the route blocking works is that it drops the *return* route to the attacking host, not the *incoming* route. If an attacker is doing a UDP scan of your host the packets will still trip the sensor, they just don't return to the host. If the blocked file did not exist the host would be written possibly hundreds or thousands of times to hosts.deny!! This is not good. A better solution is to integrate in with a real packet filter locally (ala Linux ipfwadm which is supported or any other similar package on your system).

After a period of time elapses you may wish to delete the local dead route to the offender and keep them in the hosts.deny file. This is solely your choice. If you wish to re-enable blocking should the offender return, just re-start PortSentry or delete the individual entry from the blocked file.

If you need to restore the route to the blocked host on most systems you can simply delete the route like so:

Linux:

route del <ip_address> reject

Others:

route delete <ip_address> <dead_route>

Or you can simply flush your packet filters.

That's about it. It's highly recommended you use Logcheck to keep an eye on things in the log files as well so you can detect other problems, and see what the PortSentry is saying to you.

You can find this program at