Created
August 17, 2022 13:24
-
-
Save Skipper0707/e0765b091a253e4bf7fd150dc2dc198a to your computer and use it in GitHub Desktop.
Script to avoid MAC & IP spoofing and block desired ports for Qemu/KVM virtual machines via nft or nftables on Debian Bullseye
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# set -x for debugging | |
set +x | |
readonly SCRIPT_NAME=$(basename $0) | |
function help { | |
echo "Usage: $0 options" | |
echo " -n <ifname> VM TAP interface name on the host" | |
echo " -m <mac> VM MAC address inside the virtual machine" | |
echo " -i <id> VM id" | |
echo " -h <ip> Allowed IP address for the VM" | |
} | |
function err { | |
logger -p user.crit -t $SCRIPT_NAME "$@" | |
} | |
optstring=":n:m:i:h:" | |
while getopts $optstring opt | |
do | |
case $opt in | |
n) | |
VM_IF=$OPTARG | |
;; | |
m) | |
VM_MAC=$OPTARG | |
;; | |
i) | |
VM_ID=$OPTARG | |
;; | |
h) | |
VM_IP=$OPTARG | |
;; | |
esac | |
done | |
if [[ -z $VM_IF || | |
-z $VM_MAC || | |
-z $VM_ID || | |
-z $VM_IP ]] | |
then | |
help | |
exit 1 | |
fi | |
ebtables-nft -N $VM_ID-MAC | |
ebtables-nft -N $VM_ID-PORT | |
ebtables-nft -A FORWARD -p ip -i $VM_IF -j $VM_ID-MAC | |
ebtables-nft -A FORWARD -p ip -o $VM_IF -j $VM_ID-PORT | |
ebtables-nft -P $VM_ID-MAC DROP | |
ebtables-nft -A $VM_ID-MAC -p ip --ip-src $VM_IP -s $VM_MAC -j ACCEPT | |
ebtables-nft -A $VM_ID-PORT -p ip --ip-protocol tcp --ip-sport 25 -j DROP | |
ebtables-nft -A $VM_ID-PORT -p ip --ip-protocol tcp --ip-sport 587 -j DROP | |
ebtables-nft -A $VM_ID-PORT -p ip --ip-protocol tcp --ip-sport 465 -j DROP | |
ebtables-nft -A $VM_ID-PORT -p ip --ip-protocol udp --ip-sport 25 -j DROP | |
ebtables-nft -A $VM_ID-PORT -p ip --ip-protocol udp --ip-sport 587 -j DROP | |
ebtables-nft -A $VM_ID-PORT -p ip --ip-protocol udp --ip-sport 465 -j DROP | |
ebtables-nft-save | |
ret=$? | |
if [[ $ret -ne 0 ]] | |
then | |
err "Could not create nft ruleset for instance ${VM_ID}" | |
exit $ret | |
fi | |
echo -e "nft ruleset for instance ${VM_ID} created." | |
exit $ret |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment