#!/bin/sh
#
# portblock: iptables temporary portblocking control 
#
# Author:	Sun Jiang Dong
#
# License:	GNU General Public License (GPL)
#
# Copyright:	(C) 2005 International Business Machines
#
#	  OCF parameters are as below:
#		OCF_RESKEY_protocol
#		OCF_RESKEY_portno
#		OCF_RESKEY_action
#######################################################################
# Initialization:

. ${OCF_ROOT}/resource.d/heartbeat/.ocf-shellfuncs
. ${HA_DIR}/shellfuncs

#######################################################################
CMD=`basename $0`

usage()
{
	cat <<-!USAGE >&2
	usage: $CMD {start|stop|status|monitor|meta-data|validate-all}

	$CMD is used to temporarily block ports using iptables.

	It can be used to turn off a port before bringing
	up an IP address, and enable it after a service is started.
	To do that for samba, the following resource line can be used:

	$CMD::tcp::137,138::block		\\
	    10.10.10.20				\\
	    nmbd smbd 				\\
	    $CMD::tcp::137,138::unblock

	This will do the follwing things:

	  - DROP all incoming packets for TCP ports 137 and 138
	  - Bring up the IP alias 10.10.10.20
	  - start the nmbd and smbd services
	  - Re-enable TCP ports 137 and 138
	        (enable normal firewall rules on those ports)

	This prevents clients from getting ICMP port unreachable
	if they try to reconnect to the service after the alias is
	enabled but before nmbd and smbd are running.  These packets
	will cause some clients to give up attempting to reconnect to
	the server.

	NOTE:  iptables is linux-specific...

	!USAGE
}

meta_data() {
	cat <<END
<?xml version="1.0"?>
<!DOCTYPE resource-agent SYSTEM "ra-api-1.dtd">
<resource-agent name="portblock">
<version>1.0</version>

<longdesc lang="en">
Resource script for portblock. It is used to temporarily block ports 
using iptables. 
</longdesc>
<shortdesc lang="en">portblock resource agent</shortdesc>

<parameters>
<parameter name="protocol" unique="0" required="1">
<longdesc lang="en">
The protocol used to be blocked/unblocked.
</longdesc>
<shortdesc lang="en">protocol</shortdesc>
<content type="string" default="" />
</parameter>

<parameter name="portno" unique="0" required="1">
<longdesc lang="en">
The port number used to be blocked/unblocked.
</longdesc>
<shortdesc lang="en">portno</shortdesc>
<content type="integer" default="" />
</parameter>

<parameter name="action" unique="0" required="1">
<longdesc lang="en">
The action (block/unblock) to be done on the protocol::portno.
</longdesc>
<shortdesc lang="en">action</shortdesc>
<content type="string" default="" />
</parameter>
</parameters>

<actions>
<action name="start" timeout="20" />
<action name="stop" timeout="20" />
<action name="status" depth="0" timeout="10" interval="10" start-delay="10" />
<action name="monitor" depth="0" timeout="10" interval="10" start-delay="10" />
<action name="meta-data" timeout="5" />
<action name="validate-all" timeout="5" />
</actions>
</resource-agent>
END
}


#
#	Because this is the normal usage, we consider "block"
#	resources to be pseudo-resources -- that is, their status can't
#	be reliably determined through external means.
#	This is because we expect an "unblock" resource to come along
#	and disable us -- but we're still in some sense active...
#
#	So, we track the state here using the pseudo_resource() function.
#
#	The psuedo_resource function should be moved into the functions
#	available to resources so other resource scripts could use it...
#
#

# pseudo_resource filename operation
pseudo_resource()
{
  ha_pseudo_resource $*
}

#iptables_spec {udp|tcp} portno,portno
iptables_spec()
{
  echo -D INPUT -p $1 -m multiport --dports $2 -j DROP
}

#active_grep_pat {udp|tcp} portno,portno
active_grep_pat()
{
  w="[ 	][ 	]*"
  any="0\\.0\\.0\\.0/0"
  echo "^DROP${w}${1}${w}--${w}${any}${w}${any}${w}multiport${w}dports${w}${2} "
}

#chain_isactive  {udp|tcp} portno,portno
chain_isactive()
{
  PAT=`active_grep_pat "$1" "$2"`
  $IPTABLES -n -L INPUT | grep "$PAT" >/dev/null
}

SayActive()
{
  echo "$CMD DROP rule for INPUT chain [$*]  is running (OK)"
  return 0
}

SayConsideredActive()
{
  echo "$CMD DROP rule for INPUT chain [$*] considered to be running (OK)"
  return 0
}

SayInactive()
{
  echo "$CMD DROP rule for INPUT chain [$*] is inactive"
  return 1
}

#IptablesStatus  {udp|tcp} portno,portno {block|unblock}
IptablesStatus()
{
  activewords="$CMD $1 $2 is running (OK)"
  if
    chain_isactive "$1" "$2"
  then
    case $3 in
	  block)	SayActive $*;;
	  *) 		SayInactive $*;;
    esac
  else
    case $3 in
	  block)
	        if
		  pseudo_resource "$RSCNAME" status
		then
		  SayConsideredActive $*
		else
		  SayInactive $*
		fi;;

	  *)	SayActive $*;;
    esac
  fi      

  return $?
}

#IptablesBLOCK  {udp|tcp} portno,portno
IptablesBLOCK()
{
  if
    chain_isactive "$1" "$2"
  then
    : OK -- chain already active
  else
    $IPTABLES -I INPUT -p "$1" -m multiport --dports "$2" -j DROP
  fi

  return $?
}

#IptablesUNBLOCK  {udp|tcp} portno,portno
IptablesUNBLOCK()
{
  if
    chain_isactive "$1" "$2"
  then
    $IPTABLES -D INPUT -p "$1" -m multiport --dports "$2" -j DROP
  else
    : Chain Not active
  fi

  return $?
}

#IptablesStart  {udp|tcp} portno,portno {block|unblock}
IptablesStart()
{
  pseudo_resource "$RSCNAME" start
  case $3 in
    block)	IptablesBLOCK "$@";;
    unblock)	IptablesUNBLOCK "$@";;
    *)		usage; return 1;
  esac

  return $?
}

#IptablesStop  {udp|tcp} portno,portno {block|unblock}
IptablesStop()
{
  pseudo_resource "$RSCNAME" stop
  case $3 in
    block)	IptablesUNBLOCK "$@";;
    unblock)	IptablesBLOCK "$@";;
    *)		usage; return 1;;
  esac

  return $?
}

#
#	Check if the port is valid, this function code is not decent, but works
#
CheckPort() {
#	Examples of valid port: "1080", "1", "0080"
#	Examples of invalid port: "1080bad", "0", "0000", ""
  case "$1" in
    *[^0-9]*) #got invalid char
	false;;
    *[1-9]*) #no invalid char, and has non-zero digit, so is a good port
	true;;
    *) #empty string, or string of 0's 
	false;;
  esac
}

IptablesValidateAll()
{
  check_binary $IPTABLES
  case $protocol in
    tcp|udp)
	;;
    *)
	ocf_log err "Invalid protocol $protocol!"
	exit $OCF_ERR_ARGS
	;;
  esac

  if CheckPort "$portno"; then
	:
  else
	ocf_log err "Invalid port number $portno!"
	exit $OCF_ERR_ARGS
  fi

  case $action in
    block|unblock)	
	;;
    *)		
	ocf_log err "Invalid action $action!"
	exit $OCF_ERR_ARGS
	;; 
  esac
  return $OCF_SUCCESS
}

if
  ( [ $# -ne 1 ] )
then
  usage
  exit $OCF_ERR_ARGS
fi

case $1 in
  meta-data)		meta_data
			exit $OCF_SUCCESS
			;;

  usage)		usage
			exit $OCF_SUCCESS
			;;
  *)			;;
esac

if [ -z "$OCF_RESKEY_protocol" ]; then
  ocf_log err "Please set OCF_RESKEY_protocol"
  exit $OCF_ERR_ARGS
fi 

if [ -z "$OCF_RESKEY_portno" ]; then
  ocf_log err "Please set OCF_RESKEY_portno"
  exit $OCF_ERR_ARGS
fi 

if [ -z "$OCF_RESKEY_action" ]; then
  ocf_log err "Please set OCF_RESKEY_action"
  exit $OCF_ERR_ARGS
fi 

protocol=$OCF_RESKEY_protocol
portno=$OCF_RESKEY_portno
action=$OCF_RESKEY_action

RSCNAME=${CMD}_${protocol}_${portno}_${action}

case $1 in
  start)	
			IptablesStart $protocol $portno $action 
			;;

  stop)		
			IptablesStop $protocol $portno $action
			;;

  status|monitor)	
			IptablesStatus $protocol $portno $action
			;;

  validate-all)
			IptablesValidateAll
			;;

  *)			usage
			exit $OCF_ERR_UNIMPLEMENTED
			;;
esac

exit $?
