Skip to content

Instantly share code, notes, and snippets.

@frk1
Last active April 8, 2018 18:21
Show Gist options
  • Save frk1/ccdbc5f794bc4e292877ae28cf8c25c1 to your computer and use it in GitHub Desktop.
Save frk1/ccdbc5f794bc4e292877ae28cf8c25c1 to your computer and use it in GitHub Desktop.
Use the cloudflare firewall to block ddos attacks
#!/usr/bin/env python3
# pip3 install --upgrade requests pycountry dnspython
import ipaddress
import requests
import pycountry
import dns.resolver
ALLOWED_COUNTRIES = ['DE', 'AT']
CF_CREDENTIALS = {'X-Auth-Email': 'YOUR_MAIL',
'X-Auth-Key': 'YOUR_KEY'}
def airvpn_exit_ips_country(code):
res = dns.resolver.Resolver(configure=False)
res.nameservers = ['1.1.1.1', '1.0.0.1']
return [str(ipaddress.ip_address(i) + 1)
for i in res.query('%s.all.vpn.airdns.org' % code, 'A')]
def airvpn_exit_ips_servers(names):
res = dns.resolver.Resolver(configure=False)
res.nameservers = ['1.1.1.1', '1.0.0.1']
exit_ips = []
for name in names:
try:
exit_ips.append(
(name,
[str(ipaddress.ip_address(i) + 1)
for i in res.query('%s.airservers.org' % name, 'A')]))
except BaseException:
print("Error resolving ip for server '{}'".format(name))
return exit_ips
def delete_existing_rules():
rules = requests.get(
'https://api.cloudflare.com/client/v4/user/firewall/access_rules/rules',
headers=CF_CREDENTIALS).json()['result']
while len(rules) > 0:
for rule in rules:
print(rule['id'])
requests.delete(
'https://api.cloudflare.com/client/v4/user/firewall/access_rules/rules/%s' %
rule['id'], headers=CF_CREDENTIALS)
rules = requests.get(
'https://api.cloudflare.com/client/v4/user/firewall/access_rules/rules',
headers=CF_CREDENTIALS).json()['result']
def block_bad_countries():
for country in [c.alpha_2 for c in list(
pycountry.countries) if c.alpha_2 not in ALLOWED_COUNTRIES]:
print(country)
data = {
'mode': 'challenge',
'configuration': {
'target': 'country',
'value': country}}
requests.post(
'https://api.cloudflare.com/client/v4/user/firewall/access_rules/rules',
headers=CF_CREDENTIALS,
json=data)
def whitelist_ips(ips, comment):
for i in ips:
print('{} ({})'.format(i, comment))
data = {
'mode': 'whitelist',
'configuration': {
'target': 'ip',
'value': i},
'notes': comment
}
requests.post(
'https://api.cloudflare.com/client/v4/user/firewall/access_rules/rules',
headers=CF_CREDENTIALS,
json=data)
def whitelist_airvpn_servers(server_names):
for name, ips in airvpn_exit_ips_servers(server_names):
whitelist_ips(ips, 'AirVPN ({})'.format(name))
def main():
delete_existing_rules()
block_bad_countries()
whitelist_ips(airvpn_exit_ips_country('nl'), 'AirVPN NL')
whitelist_ips(airvpn_exit_ips_country('ch'), 'AirVPN CH')
whitelist_ips(airvpn_exit_ips_country('be'), 'AirVPN BE')
whitelist_ips(airvpn_exit_ips_country('no'), 'AirVPN NO')
whitelist_airvpn_servers(['Mirach', 'Baiten', 'Fomalhaut', 'Diadema'])
print('Done!')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment