#!/usr/bin/env sh

##################################################################################
#
#  Copyright (C) 2025 Craig Miller
#
#  See the file "LICENSE" for information on usage and redistribution
#  of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#  Distributed under GPLv2 License
#
##################################################################################


#
#	Script auto discovers v4 subnets in 'whois' results, and creates an iptables IPv4 block list
#
#	by Craig Miller		13 Nov 2025
#
#		10/15/2025 - Add IPv6 support, using -a
#			test: 2a06:4883:b000::be



#
#	todo:
#

usage () {
               echo "	$0  - creates block list, supports both IPv4 and IPv6 "
	       echo "	e.g. $0 -a <ip_addr> "
	       echo "	-a  <IP address>"
	       echo "	-S  prepends sudo"
	       echo "	-o  over-rides OrgName check"
	       echo "	"
	       echo "	\"Pau\" is Hawaiian for Done"
	       echo "	"
	       echo " By Craig Miller - Version: $VERSION"
	       exit 1
           }

VERSION=0.95

# initialize some vars
WHOIS="whois"

SUDO="" 
ORG=1
DEBUG=0


while getopts "?hi:a:kdSo" options; do
  case $options in
    d ) DEBUG=1
    	numopts=$(( numopts + 1));;
    o ) ORG=0
    	numopts=$(( numopts + 1));;
    S ) SUDO="sudo " 
    	numopts=$(( numopts + 1));;
    a ) IP_ADDR=$OPTARG
    	numopts=$(( numopts + 2));;
    h ) usage;;
    \? ) usage;;	# show usage with flag and no value

    * ) usage;;		# show usage with unknown flag

  esac
done
# remove the options as cli arguments
shift $numopts


print_block () {
	# print iptables command
	
	block_ip=$1
	org=$2
	# check for IPv6 address
	colons=$(echo "$block_ip" | grep -o ':' | wc -l )
	if [ $colons -eq 0 ]; then 
		echo  "${SUDO}iptables -A INPUT -s $block_ip -j DROP        #$org"
	else
		echo  "${SUDO}ip6tables -A INPUT -s $block_ip -j DROP        #$org"
	fi
}


## get down to work

if [ $DEBUG -eq 1 ]; then echo "DEBUG: parms: $WHOIS $IP_ADDR";fi


block_list=$($WHOIS "$IP_ADDR" | grep -E '(CIDR:|route:|route6:)' | sed -r 's/(CIDR:|route:|route6:)[ ]+//g' | cut -d "," -f 1-8 | tr -d ',')

if [ $DEBUG -eq 1 ]; then echo "DEBUG: blocklist: $(echo "$block_list" | od -c)";fi

#check for empty blocklist
if [ -z "$block_list" ]; then
	echo "Block list is empty"
	exit 1
fi

# get Org Name

org_name=$($WHOIS "$IP_ADDR" | grep -E 'OrgName|org-name|role:' | sed -r 's/(OrgName:[ ]+|org-name:[ ]+|role:[ ]+)//'  | tr ' ' '-')

#check for empty orgname
if [ -z "$org_name" ]; then
	echo "Org Name is empty"
	if [ $ORG -eq 1 ]; then
		# require Org (0=skip)
		exit 1
	fi
fi


for block in $block_list
do
	if [ $DEBUG -eq 1 ]; then echo "DEBUG: block: $block";fi
	print_block $block $org_name
done


if [ $DEBUG -eq 1 ]; then echo "Pau!";fi











