142fa3
#!/bin/sh
142fa3
#
142fa3
# ipset      Start and stop ipset firewall sets
142fa3
#
142fa3
# config: /etc/sysconfig/ipset-config
142fa3
142fa3
IPSET_BIN=/usr/sbin/ipset
142fa3
IPSET_CONFIG=/etc/sysconfig/ipset-config
142fa3
IPSET_DATA_COMPAT=/etc/sysconfig/ipset
142fa3
IPSET_DATA_COMPAT_BACKUP=${IPSET_DATA_COMPAT}.save
142fa3
IPSET_DATA_DIR=/etc/sysconfig/ipset.d
142fa3
IPSET_DATA_DIR_BACKUP=${IPSET_DATA_DIR}.save
142fa3
IPSET_DATA_SAVED_FLAG=${IPSET_DATA_DIR}/.saved
142fa3
IPSET_LOCK=/run/ipset.lock
142fa3
IPSET_RUN=/run/ipset.run
142fa3
CLEAN_FILES=""
142fa3
142fa3
trap "rm -rf \${CLEAN_FILES}" EXIT
142fa3
142fa3
info() {
142fa3
	echo "ipset: ${*}" >&2
142fa3
}
142fa3
142fa3
warn() {
142fa3
	echo "<4>ipset: ${*}" >&2
142fa3
}
142fa3
142fa3
err() {
142fa3
	echo "<3>ipset: ${*}" >&2
142fa3
}
142fa3
142fa3
[ -x ${IPSET_BIN} ] || { err "Cannot execute ${IPSET_BIN}"; exit 1; }
142fa3
142fa3
# Source ipset configuration
142fa3
# shellcheck source=ipset-config
142fa3
[ -f ${IPSET_CONFIG} ] && . ${IPSET_CONFIG}
142fa3
142fa3
set -f
142fa3
142fa3
lock() {
142fa3
	CLEAN_FILES="${CLEAN_FILES} ${IPSET_LOCK}"
142fa3
	until mkdir ${IPSET_LOCK} 2>/dev/null; do :; done
142fa3
}
142fa3
142fa3
save() {
142fa3
	fail=0
142fa3
142fa3
	# Make backups of existing configuration first, if any
142fa3
	[ -d ${IPSET_DATA_DIR} ] && mv -Tf ${IPSET_DATA_DIR} ${IPSET_DATA_DIR_BACKUP}
142fa3
	[ -f ${IPSET_DATA_COMPAT} ] && mv -Tf ${IPSET_DATA_COMPAT} ${IPSET_DATA_COMPAT_BACKUP}
142fa3
142fa3
	rm -f ${IPSET_DATA_SAVED_FLAG}
142fa3
142fa3
	# Save each set in a separate file
142fa3
	mkdir -p ${IPSET_DATA_DIR}
142fa3
	chmod 0700 ${IPSET_DATA_DIR}
142fa3
	IFS="
142fa3
"
142fa3
	for set in $(${IPSET_BIN} list -n -t); do
142fa3
		# Empty name allowed, use ".set" as suffix. 'ipset save' doesn't
142fa3
		# quote set names with spaces: if we have a space in the name,
142fa3
		# work around this by quoting it ourselves in the output.
142fa3
		# shellcheck disable=SC2003 # No POSIX equivalent to expr index
142fa3
		if expr index "${set}" " " >/dev/null; then
142fa3
			:> "${IPSET_DATA_DIR}/${set}.set"
142fa3
			for line in $(${IPSET_BIN} save "${set}"); do
142fa3
				create=0
142fa3
				echo "${line}" | grep -q "^create " && create=1
142fa3
				if [ $create -eq 1 ]; then
142fa3
					line=${line#create *}
142fa3
				else
142fa3
					line=${line#add *}
142fa3
				fi
142fa3
				line=${line#${set} *}
142fa3
				set="$(echo "${set}" | sed 's/"/\\"/g')"
142fa3
				if [ $create -eq 1 ]; then
142fa3
					echo "create \"${set}\" ${line}" >> "${IPSET_DATA_DIR}/${set}.set"
142fa3
				else
142fa3
					echo "add \"${set}\" ${line}" >> "${IPSET_DATA_DIR}/${set}.set"
142fa3
				fi
142fa3
			done
142fa3
		else
142fa3
			${IPSET_BIN} save "${set}" > "${IPSET_DATA_DIR}/${set}.set" || fail=1
142fa3
		fi
142fa3
		[ -f "${IPSET_DATA_DIR}/${set}.set" ] && chmod 600 "${IPSET_DATA_DIR}/${set}.set"
142fa3
		[ $fail -eq 1 ] && err "Cannot save set ${set}" && unset IFS && return 1
142fa3
	done
142fa3
	touch ${IPSET_DATA_SAVED_FLAG} || { unset IFS; return 1; }
142fa3
	unset IFS
142fa3
142fa3
	# Done: remove backups
142fa3
	rm -rf ${IPSET_DATA_DIR_BACKUP}
142fa3
	rm -rf ${IPSET_DATA_COMPAT_BACKUP}
142fa3
142fa3
	return 0
142fa3
}
142fa3
142fa3
# Generate a grep regexp matching abbreviated command forms. E.g., for create:
142fa3
# \(c\|cr\|cre\|crea\|creat\|create\)
142fa3
cmd_short_expr() {
142fa3
	out=
142fa3
	cmd_len=1
142fa3
	while [ "${cmd_len}" -le "${#1}" ]; do
142fa3
		[ -z "${out}" ] && out='\(' || out="${out}"'\|'
142fa3
		# shellcheck disable=SC2003 # No POSIX equivalent to expr substr
142fa3
		out="${out}$(expr substr "${1}" 1 "${cmd_len}")"
142fa3
		cmd_len=$((cmd_len + 1))
142fa3
	done
142fa3
	echo "${out}"'\)'
142fa3
}
142fa3
142fa3
ipset_restore() {
142fa3
	file="${1}"
142fa3
142fa3
	retfile="$(mktemp -q /tmp/ipset.XXXXXX)"
142fa3
	CLEAN_FILES="${CLEAN_FILES} ${retfile}"
142fa3
142fa3
	# If restore fails due to invalid lines, remove them and retry
142fa3
	while ! restore_err="$( (${IPSET_BIN} -f "${file}" -! restore 2>&1; echo $? >"${retfile}") | head -n1; exit "$(cat "${retfile}")" )"; do
142fa3
		warn "${restore_err}"
142fa3
		case ${restore_err#*: } in
142fa3
		"No command specified"*)
142fa3
			line="$(grep -m1 -n "^${restore_err##* }" "${file}")"
142fa3
			line="${line%:*}"
142fa3
			;;
142fa3
		"Missing second mandatory argument to command "*)
142fa3
			cmd="${restore_err##* }"
142fa3
			cmd_expr="$(cmd_short_expr "${cmd}")"
142fa3
			line="$(grep -n '^'"${cmd_expr}" "${file}" | grep -m1 -v '^[0-9]\+\:'"${cmd_expr}"'[[:blank:]]\+[^[:blank:]]\+[[:blank:]]\+[^[:blank:]]\+')"
142fa3
			line="${line%:*}"
142fa3
			;;
142fa3
		"Missing mandatory argument to command "*)
142fa3
			cmd="${restore_err##* }"
142fa3
			cmd_expr="$(cmd_short_expr "${cmd}")"
142fa3
			line="$(grep -n '^'"${cmd_expr}" "${file}" | grep -m1 -v '^[0-9]\+\:'"${cmd_expr}"'[[:blank:]]\+[^[:blank:]]\+')"
142fa3
			line="${line%:*}"
142fa3
			;;
142fa3
		"Command "*"is invalid in restore mode"*)
142fa3
			restore_err_cmd="${restore_err#*: }"
142fa3
			restore_err_cmd="${restore_err_cmd#*\`}"
142fa3
			restore_err_cmd="${restore_err_cmd%%\'*}"
142fa3
			cmd="${restore_err_cmd##* }"
142fa3
			cmd_expr="$(cmd_short_expr "${cmd}")"
142fa3
			line="$(grep -m1 -ne '^'"${cmd_expr}"'[[:blank:]]\+' -e '^'"${restore_err_cmd}"'$' "${file}")"
142fa3
			line="${line%:*}"
142fa3
			;;
142fa3
		"Error in line "*)
142fa3
			line="${restore_err%: *}"
142fa3
			line="${line##* }"
142fa3
			;;
142fa3
		*)
142fa3
			rm "${retfile}"
142fa3
			CLEAN_FILES="${CLEAN_FILES%* ${retfile}}"
142fa3
			return 1
142fa3
			;;
142fa3
		esac
142fa3
142fa3
		[ -z "${line}" ] && return 1
142fa3
142fa3
		warn "Skipped invalid entry: $(sed "${line}q;d" "${file}")"
142fa3
		sed -i -e "${line}d" "${file}"
142fa3
142fa3
		[ -s "${file}" ] || return 1
142fa3
	done
142fa3
142fa3
	rm "${retfile}"
142fa3
	CLEAN_FILES="${CLEAN_FILES%* ${retfile}}"
142fa3
}
142fa3
142fa3
load() {
142fa3
	if [ -f ${IPSET_DATA_SAVED_FLAG} ]; then
142fa3
		# If we have a cleanly saved directory with all sets, we can
142fa3
		# delete any left-overs and use it
142fa3
		rm -rf ${IPSET_DATA_DIR_BACKUP}
142fa3
		rm -f ${IPSET_DATA_COMPAT_BACKUP}
142fa3
	else
142fa3
		# If sets weren't cleanly saved, restore from backups
142fa3
		[ -d ${IPSET_DATA_DIR_BACKUP} ] && rm -rf ${IPSET_DATA_DIR} && mv -Tf ${IPSET_DATA_DIR_BACKUP} ${IPSET_DATA_DIR}
142fa3
		[ -f ${IPSET_DATA_COMPAT_BACKUP} ] && rm -f ${IPSET_DATA_COMPAT} && mv -Tf ${IPSET_DATA_COMPAT_BACKUP} ${IPSET_DATA_COMPAT}
142fa3
	fi
142fa3
142fa3
	if [ ! -d ${IPSET_DATA_DIR} ] && [ ! -f ${IPSET_DATA_COMPAT} ]; then
142fa3
		info "No existing configuration available, none loaded"
142fa3
		touch ${IPSET_RUN}
142fa3
		return
142fa3
	fi
142fa3
142fa3
	# Merge all sets into temporary file
142fa3
	merged="$(mktemp -q /tmp/ipset.XXXXXX)"
142fa3
	CLEAN_FILES="${CLEAN_FILES} ${merged}"
142fa3
	chmod 600 "${merged}"
142fa3
	set +f
142fa3
	if [ -d ${IPSET_DATA_DIR} ]; then
142fa3
		# Copy create commands from each saved set first, then the rest:
142fa3
		# list:set entries depend on other sets, so make sure they all
142fa3
		# get created first
142fa3
		for f in "${IPSET_DATA_DIR}"/*; do
142fa3
			[ "${f}" = "${IPSET_DATA_DIR}/*" ] && break
142fa3
			[ -f "${f}" ] || continue
142fa3
			grep '^c' "${f}" >> "${merged}"
142fa3
		done
142fa3
		for f in "${IPSET_DATA_DIR}"/*; do
142fa3
			[ "${f}" = "${IPSET_DATA_DIR}/*" ] && break
142fa3
			[ -f "${f}" ] || continue
142fa3
			grep -v '^c' "${f}" >> "${merged}"
142fa3
		done
142fa3
	fi
142fa3
	set -f
142fa3
	[ -f ${IPSET_DATA_COMPAT} ] && cat ${IPSET_DATA_COMPAT} >> "${merged}"
142fa3
142fa3
	# Drop sets that aren't in saved data, mark conflicts with existing sets
142fa3
	conflicts=""
142fa3
	IFS="
142fa3
"
142fa3
	for set in $(${IPSET_BIN} list -n -t); do
142fa3
		grep -q "^create ${set} " "${merged}" && conflicts="${conflicts}|${set}" && continue
142fa3
142fa3
		# We can't destroy the set if it's in use, flush it instead
142fa3
		if ! ${IPSET_BIN} destroy "${set}" 2>/dev/null; then
142fa3
			${IPSET_BIN} flush "${set}"
142fa3
		fi
142fa3
	done
142fa3
	unset IFS
142fa3
	conflicts="${conflicts#|*}"
142fa3
142fa3
	# Common case: if we have no conflicts, just restore in one shot
142fa3
	if [ -z "${conflicts}" ]; then
142fa3
		if ! ipset_restore "${merged}"; then
142fa3
			err "Failed to restore configured sets"
142fa3
			exit 1
142fa3
		fi
142fa3
		rm "${merged}"
142fa3
		CLEAN_FILES="${CLEAN_FILES%* ${merged}}"
142fa3
		touch ${IPSET_RUN}
142fa3
		return
142fa3
	fi
142fa3
142fa3
	# Find a salt for md5sum that makes names of saved sets unique
142fa3
	salt=0
142fa3
	while true; do
142fa3
		unique=1
142fa3
		IFS="
142fa3
"
142fa3
		for set in $(${IPSET_BIN} list -n -t); do
142fa3
			if grep -q "^create $(echo "${salt}${set}" | md5sum | head -c31) " "${merged}"; then
142fa3
				unique=0
142fa3
				break
142fa3
			fi
142fa3
		done
142fa3
		unset IFS
142fa3
		[ ${unique} -eq 1 ] && break
142fa3
		salt=$((salt + 1))
142fa3
	done
142fa3
142fa3
	# Add sets, mangling names for conflicting sets
142fa3
	mangled="$(mktemp -q /tmp/ipset.XXXXXX)"
142fa3
	CLEAN_FILES="${CLEAN_FILES} ${mangled}"
142fa3
	chmod 600 "${mangled}"
142fa3
142fa3
	awk '/^(add|create) ('"${conflicts}"')/ { printf "%s ",$1; system("echo '${salt}'" $2 " | md5sum | head -c31"); $1=""; $2=""; print; next} {print}' "${merged}" > "${mangled}"
142fa3
	if ! ipset_restore "${mangled}"; then
142fa3
		err "Failed to restore configured sets"
142fa3
		exit 1
142fa3
	fi
142fa3
142fa3
	rm "${mangled}"
142fa3
	CLEAN_FILES="${CLEAN_FILES%* ${mangled}}"
142fa3
142fa3
	# Swap and delete old sets
142fa3
	IFS='|'
142fa3
	for set in ${conflicts}; do
142fa3
		mangled="$(echo "${salt}${set}" | md5sum | head -c31)"
142fa3
		if ! ${IPSET_BIN} swap "${set}" "${mangled}" 2>/dev/null; then
142fa3
			# This fails if set types are different: try to destroy
142fa3
			# existing set
142fa3
			if ! ${IPSET_BIN} destroy "${set}" 2>/dev/null; then
142fa3
				# Conflicting set is in use, we can only warn
142fa3
				# and flush the existing set
142fa3
				err "Cannot load set \"${set}\", set with same name and conflicting type in use"
142fa3
				${IPSET_BIN} flush "${set}"
142fa3
				${IPSET_BIN} destroy "${mangled}"
142fa3
			else
142fa3
				${IPSET_BIN} rename "${mangled}" "${set}"
142fa3
			fi
142fa3
		else
142fa3
			${IPSET_BIN} destroy "${mangled}"
142fa3
		fi
142fa3
	done
142fa3
	unset IFS
142fa3
142fa3
	rm "${merged}"
142fa3
	CLEAN_FILES="${CLEAN_FILES%* ${merged}}"
142fa3
	touch ${IPSET_RUN}
142fa3
}
142fa3
142fa3
cleanup() {
142fa3
	${IPSET_BIN} flush || err "Failed to flush sets"
142fa3
142fa3
	# Try to destroy all sets at once. This will fail if some are in use,
142fa3
	# destroy all the other ones in that case
142fa3
	${IPSET_BIN} destroy 2>/dev/null && return
142fa3
	IFS="
142fa3
"
142fa3
	for set in $(${IPSET_BIN} list -n -t); do
142fa3
		if ! ${IPSET_BIN} destroy "${set}"; then
142fa3
			err "Failed to destroy set ${set}"
142fa3
		fi
142fa3
	done
142fa3
	unset IFS
142fa3
}
142fa3
142fa3
stop() {
142fa3
	[ -f ${IPSET_RUN} ] || { info "Not running"; return 0; }
142fa3
	[ "${IPSET_SAVE_ON_STOP}" = "yes" ] && { save || err "Failed to save sets"; }
142fa3
142fa3
	# Nothing to stop if the ip_set module is not loaded
142fa3
	lsmod | grep -q "^ip_set " || { info "Not running"; rm ${IPSET_RUN}; return 0; }
142fa3
142fa3
	# If the xt_set module is in use, then iptables is using ipset, so
142fa3
	# refuse to stop the service
142fa3
	if mod="$(lsmod | grep ^xt_set)"; then
142fa3
		if [ "$(echo "${mod}" | tr -s ' ' | cut -d' ' -f3)" != "0" ]; then
142fa3
			err "Current iptables configuration requires ipset" && return 1
142fa3
		fi
142fa3
	fi
142fa3
142fa3
	cleanup
142fa3
142fa3
	rm ${IPSET_RUN}
142fa3
	return 0
142fa3
}
142fa3
142fa3
lock
142fa3
case "$1" in
142fa3
start)
142fa3
	load
142fa3
	;;
142fa3
stop)
142fa3
	stop
142fa3
	;;
142fa3
reload)
142fa3
	cleanup
142fa3
	load
142fa3
	;;
142fa3
save)
142fa3
	save
142fa3
	;;
142fa3
*)
142fa3
	info "Usage: $0 {start|stop|reload|save}"
142fa3
	exit 1
142fa3
esac
142fa3
142fa3
exit $?