Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Anti gfw6's dns pollution
#!/usr/bin/env python2
# -*- coding:utf-8 -*-
import os
import sys
def ip62hex(ip):
ip = map(lambda x: int(x, 16), ip.split(':'))
hexed = reduce(list.__add__,
[[(x >> 8), (x & 0x00FF)] for x in ip])
hexed = map(lambda x: "%02X" % x, hexed)
return hexed
def natural2hex(ip):
if ip.find(':') >= 0:
# AAAA
ip = ip.split('::')
if len(ip) == 1:
hexed_ip = ' '.join(ip62hex(ip[0]))
else:
head, tail = map(ip62hex, ip)
nzero = 16 - len(head) - len(tail)
zeros = ['00' for x in range(nzero)]
hexed_ip = ' '.join(head + zeros + tail)
elif ip.find('.') >= 0:
ip_tuple = ip.split('.')
hexed_ip = ' '.join(map(lambda x: "%02X" % int(x), ip_tuple))
return hexed_ip
def block_ip(hexed_ip):
print "blocked", hexed_ip
cmd = "ip6tables -A INPUT -p udp --sport 53 -s 2001:470:20::2 -m string --algo bm --hex-string \"|%s|\" --from 60 --to 180 -j DROP" % hexed_ip
os.system(cmd)
def main():
if len(sys.argv) == 1:
for line in sys.stdin.readlines():
hexed_ip = line.strip()
block_ip(hexed_ip)
else:
ip = sys.argv[1]
hexed_ip = natural2hex(ip)
block_ip(hexed_ip)
if __name__=="__main__":
main()
# vim: ts=4 sw=4 sts=4 expandtab
#!/usr/bin/env python2
# -*- coding:utf-8 -*-
import dnslib
import socket
def init_socket():
HOST = "2001:470:20::2"
PORT = 53
for res in socket.getaddrinfo(HOST, PORT, socket.AF_INET6, socket.SOCK_DGRAM):
af, socktype, proto, canonname, sa = res
try:
s = socket.socket(af, socktype, proto)
except socket.error:
s = None
continue
try:
s.connect(sa)
except socket.error:
s.close()
s = None
continue
break
return s
def touch_gfw():
HOST = "www.youtube.com"
query = dnslib.DNSRecord(q=dnslib.DNSQuestion(HOST, dnslib.QTYPE.AAAA))
s = init_socket()
if s is None:
raise
s.settimeout(5)
s.send(query.pack())
answer_packets = []
while 1:
try:
a, t = s.recvfrom(65535)
except socket.timeout:
break
answer_packets.append(a)
answer_packets.pop()
for answer in answer_packets:
d = dnslib.DNSRecord.parse(answer)
bad_ip = d.a.rdata.data
print ' '.join(map(lambda x: "%02X" % x, bad_ip))
if __name__=="__main__":
touch_gfw()
# vim: ts=4 sw=4 sts=4 expandtab
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.