Skip to content

Instantly share code, notes, and snippets.

@metasta
Last active August 17, 2016 04:41
Show Gist options
  • Save metasta/1823314 to your computer and use it in GitHub Desktop.
Save metasta/1823314 to your computer and use it in GitHub Desktop.
iptables Country Filter

iptables Country Filter

特定の国からのアクセスを遮断する IP フィルタ. iptables 環境専用

用法

準備

  1. うざい国からのアクセスを全て遮断 から, ページ上部の *NIXシステム用 をダウンロード.

  2. ダウンロードした countryfilter.pl をテキストエディタで開き,

     print "TARGET=CKFILTERED\n";
    

    と書かれた行を

     print "TARGET=DROP\n";
    

    に変更.

  3. 変更した countryfilter.plckfilter.sh と同じ場所に置く.

実行

マシンの起動時に, また定期的に, ckfilter.sh を実行する (管理者権限が必要).

#
# upstart init script (optional). put in /etc/init/ .
#
# NOTE:
# Make sure you replace "<PATH>" with /your/path/to/(ckfilter.sh).
#
start on (local-filesystems and net-device-up)
task
exec <PATH>/ckfilter.sh
#!/bin/sh -
#
# ckfilter
#
# run at startup (init)
# and regular interval (cron)
#
# http://www.42ch.net/~shutoff/
#
PROGNAME=$(basename "$0")
BASEDIR=$(cd $(dirname "$0"); pwd)
COUNTRY=CN,KR
CHAINNAME=CKFILTER
SCRIPT_PL="$BASEDIR/countryfilter.pl"
FILTER_SH="$BASEDIR/filter.rules"
updated()
{
test `stat -c %Y $FILTER_SH` -gt `date -d '5 days ago' +%s` > /dev/null 2>&1
return $?
}
update_filter()
{
URL_APNIC='http://ftp.apnic.net/stats/apnic/delegated-apnic-latest'
wget -O - $URL_APNIC | perl $SCRIPT_PL iptables $COUNTRY > $FILTER_SH
}
chain_exists()
{
iptables -n -L $CHAINNAME > /dev/null 2>&1
return $?
}
update_chain()
{
iptables -F $CHAINNAME
sh $FILTER_SH
}
create_chain()
{
iptables -N $CHAINNAME
update_chain
iptables -A INPUT -m state --state NEW -j $CHAINNAME
}
main()
{
if chain_exists; then
if updated; then
echo "$PROGNAME: $CHAINNAME is already up to date" >&2
else
echo "$PROGNAME: update $CHAINNAME chain" >&2
update_filter
update_chain
fi
else
echo "$PROGNAME: create $CHAINNAME chain" >&2
updated || update_filter
create_chain
fi
}
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment