Skip to content

Instantly share code, notes, and snippets.

@vimagick
Last active February 29, 2024 10:14
Show Gist options
  • Save vimagick/21e931143ec04d91a2f220e36a9c64bb to your computer and use it in GitHub Desktop.
Save vimagick/21e931143ec04d91a2f220e36a9c64bb to your computer and use it in GitHub Desktop.
#!/bin/bash
#
# IPv4 Address by Country
#
declare -A URLS=(
[afrinic]='http://ftp.afrinic.net/pub/stats/afrinic/delegated-afrinic-extended-latest'
[apnic]='http://ftp.apnic.net/pub/stats/apnic/delegated-apnic-extended-latest'
[arin]='http://ftp.arin.net/pub/stats/arin/delegated-arin-extended-latest'
[ripe]='http://ftp.ripe.net/pub/stats/ripencc/delegated-ripencc-extended-latest'
[lacnic]='http://ftp.lacnic.net/pub/stats/lacnic/delegated-lacnic-extended-latest'
)
for i in ${!URLS[@]}
do
echo "====== $i ======"
url=${URLS[$i]}
curl -sSL $url | awk -F '|' 'NF==8 && $3=="ipv4" {printf("%s/%s\n", $4, int(32-log($5)/log(2))) >> $2 ".txt"}'
done
@vimagick
Copy link
Author

vimagick commented Jul 4, 2023

$ wc -l [A-Z][A-Z].txt | sort -nr | head
 239162 total
  65440 US.txt
  12123 BR.txt
  11320 RU.txt
  10064 DE.txt
   8873 CA.txt
   8675 CN.txt
   8339 IN.txt
   8222 GB.txt
   7959 AU.txt
$ awk -F/ '{print gensub(".txt", ":", "g", FILENAME), 2**(32-$2)}' ??.txt | datamash -t ' ' -s -g 1 sum 2 | sort -k 2nr | head
US: 1619272288
CN: 343170560
JP: 190742528
DE: 124159848
GB: 121756488
KR: 112499968
BR: 87124224
FR: 83979792
CA: 69012992
IT: 57763840

@vimagick
Copy link
Author

vimagick commented Jul 4, 2023

#!/bin/bash
#
# generate ipset by country
#

rm -f ipset.txt

for i in ??.txt
do
  country=${i%.txt}
  echo "====== $country ======"
  echo "create $country hash:net" >> ipset.txt
  sed "s/^/add $country /" $i >> ipset.txt
done

# ipset -! restore -f ipset.txt
# ipset list -t
# ipset save -f ipset.txt

@vimagick
Copy link
Author

vimagick commented Jul 4, 2023

Only Allow CN+US

  • vim /etc/ufw/before.rules
###################################################################################
-A ufw-before-input -m set ! --match-set CN src -m set ! --match-set US src -j DROP
###################################################################################
  • ufw reload

You need to start ipset-persistent.service before ufw.service

# /etc/systemd/system/ipset-persistent.service

[Unit]
Description=ipset persistent configuration
Before=network.target
Before=netfilter-persistent.service
Before=ufw.service
ConditionFileNotEmpty=/etc/iptables/ipset.txt

[Service]
Type=oneshot
ExecStart=/sbin/ipset restore -file /etc/iptables/ipset.txt
ExecStop=/sbin/ipset save -file /etc/iptables/ipset.txt
ExecStop=/sbin/ipset flush
ExecStopPost=/sbin/ipset destroy
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target
RequiredBy=netfilter-persistent.service
RequiredBy=ufw.service

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment