socat-mux.sh and socat-broker.sh use low ports when run as root

This commit is contained in:
Gerhard Rieger 2024-05-16 15:25:26 +02:00
parent 1241600b81
commit a6c8c3ad89
3 changed files with 38 additions and 6 deletions

View file

@ -26,6 +26,9 @@ Features:
Changed socat-chain.sh, socat-mux.sh, and socat-broker.sh to work with
older Socat versions.
socat-mux.sh and socat-broker.sh, when run as root, now internally use
low (512..1023) UDP ports to increase security.
Porting:
Changes for building and testing on NetBSD

View file

@ -65,8 +65,18 @@ esac
if [ -z "$SOCAT" ]; then SOCAT=socat; fi
[ "$VERBOSE" ] && echo "# $0: Using executable $SOCAT" >&2
# When run as root we try low ports
LOWPORT=
PATTERN=bound
if [ "$(id -u)" = 0 ]; then
LOWPORT="lowport"
PATTERN="successfully prepared local socket"
fi
# We need a free UDP port (on loopback)
PORT=$($SOCAT -d -d -T 0.000001 UDP4-RECV:0 /dev/null 2>&1 |grep bound |sed 's/.*:\([1-9][0-9]*\)$/\1/')
if [ -z "$LOWPORT" ]; then
PORT=$($SOCAT -d -d -T 0.000001 UDP4-RECV:0 /dev/null 2>&1 |grep bound |sed 's/.*:\([1-9][0-9]*\)$/\1/')
fi
if [ -z "$PORT" ]; then
# Probably old Socat version, use a different approach
if type ss >/dev/null 2>&1; then
@ -79,7 +89,11 @@ if [ -z "$PORT" ]; then
fi
PORT=
while [ -z "$PORT" ] || ss -aun |grep -e ":$PORT\>" >/dev/null; do
PORT=$((16384+RANDOM))
if [ -z "$LOWPORT" ]; then
PORT=$((16384+RANDOM))
else
PORT=$((512+(RANDOM>>6) ))
fi
done
fi
[ "$VERBOSE" ] && echo "# $0: Using UDP port $PORT" >&2

View file

@ -72,9 +72,19 @@ esac
if [ -z "$SOCAT" ]; then SOCAT=socat; fi
[ "$VERBOSE" ] && echo "# $0: Using executable $SOCAT" >&2
# When run as root we try low ports
LOWPORT=
PATTERN=bound
if [ "$(id -u)" = 0 ]; then
LOWPORT="lowport"
PATTERN="successfully prepared local socket"
fi
# We need two free UDP ports (on loopback)
PORT1=$($SOCAT -d -d -T 0.000001 UDP4-RECV:0 /dev/null 2>&1 |grep bound |sed 's/.*:\([1-9][0-9]*\)$/\1/')
PORT2=$($SOCAT -d -d -T 0.000001 UDP4-RECV:0 /dev/null 2>&1 |grep bound |sed 's/.*:\([1-9][0-9]*\)$/\1/')
if [ -z "$LOWPORT" ]; then
PORT1=$($SOCAT -d -d -T 0.000001 UDP4-RECV:0 /dev/null 2>&1 |grep "$PATTERN" |sed 's/.*:\([1-9][0-9]*\)$/\1/')
PORT2=$($SOCAT -d -d -T 0.000001 UDP4-RECV:0 /dev/null 2>&1 |grep "$PATTERN" |sed 's/.*:\([1-9][0-9]*\)$/\1/')
fi
if [ -z "$PORT1" -o -z "$PORT2" ]; then
# Probably old Socat version, use a different approach
if type ss >/dev/null 2>&1; then
@ -87,8 +97,13 @@ if [ -z "$PORT1" -o -z "$PORT2" ]; then
fi
PORT1= PORT2=
while [ -z "$PORT1" -o -z "$PORT2" -o "$PORT1" = "$PORT2" ] || ss -aun |grep -e ":$PORT1\>" -e ":$PORT2\>" >/dev/null; do
PORT1=$((16384+RANDOM))
PORT2=$((16384+RANDOM))
if [ -z "$LOWPORT" ]; then
PORT1=$((16384+RANDOM))
PORT2=$((16384+RANDOM))
else
PORT1=$((512+(RANDOM>>6) ))
PORT2=$((512+(RANDOM>>6) ))
fi
done
fi
[ "$VERBOSE" ] && echo "# $0: Using UDP ports $PORT1, $PORT2" >&2