Beispiel #1
0
def get_fqdn(name, domain):
    domain = dnslib.DNSLabel(domain)
    name = dnslib.DNSLabel(name)
    if name.label[-1 * len(domain.label):] != domain.label:
        return dnslib.DNSLabel(name.label + domain.label).idna()
    else:
        return name.idna()
Beispiel #2
0
def valid_zone(zone_root_txt):
    zone_root = dnslib.DNSLabel(zone_root_txt)
    other_zones = list(models.DNSZone.objects.all()) + list(models.SecondaryDNSZone.objects.all())
    if not psl.is_private(zone_root_txt):
        return "Zone not a publicly registrable domain"
    else:
        for zone in other_zones:
            other_zone_root = dnslib.DNSLabel(zone.zone_root.lower())
            if zone_root.matchSuffix(other_zone_root):
                return "Same or more generic zone already exists"
Beispiel #3
0
    def handle(self, *args, **options):
        for zone in list(models.DNSZone.objects.all()) + list(
                models.SecondaryDNSZone.objects.all()):
            try:
                ns = query_authoritative_ns(zone.zone_root)
            except (dnslib.DNSError, OSError) as e:
                print(f"Cant validate {zone}: {e}")
                continue

            if not ns:
                print(f"{zone} does not exist")
                self.increment_zone_fail(zone)
                continue

            if isinstance(zone, models.DNSZone) and zone.custom_ns.count():
                wanted_ns = [
                    dnslib.DNSLabel(ns.nameserver)
                    for ns in zone.custom_ns.all()
                ]
            else:
                wanted_ns = WANTED_NS

            is_valid = all(
                any(rr.rdata.label == wns for rr in ns) for wns in wanted_ns)

            if is_valid:
                print(f"{zone} is valid")
                if not zone.active:
                    print(f"Setting {zone} to active")
                zone.active = True
                zone.num_check_fails = 0
                zone.save()
            else:
                print(f"{zone} is invalid")
                self.increment_zone_fail(zone)
Beispiel #4
0
def make_zone_digest(zone_name: str):
    buffer = dnslib.DNSBuffer()
    rd = get_dnskey()
    buffer.encode_name(dnslib.DNSLabel(zone_name))
    rd.pack(buffer)
    digest = hashlib.sha256(buffer.data).hexdigest()
    tag = grpc.make_key_tag(settings.DNSSEC_PUBKEY, flags=257)
    return digest, tag
Beispiel #5
0
def query_authoritative_ns(domain):
    dns_name = dnslib.DNSLabel(domain)
    ns = lookup_ns(".", settings.RESOLVER_ADDR, port=settings.RESOLVER_PORT)
    use_ns = random.choice(ns)

    last = False
    depth = 1
    while not last:
        cur_dns_name = dnslib.DNSLabel(dns_name.label[-depth:])

        ns = lookup_ns(cur_dns_name, str(use_ns.rdata.label))

        if not ns:
            return None

        use_ns = random.choice(ns)

        if use_ns.rname == dns_name:
            break

        depth += 1

    return ns
Beispiel #6
0
def domain_encode(data, domain, base_encoding) -> dns.DNSLabel:
    """ 
        Encodes data to DNS domain name (RFC 1035).
    """
    labels = [i.encode('idna') for i in domain.split('.')]

    data = base_encoding(data)
    chucked_data = chunk(data, 63)

    try:
        result = dns.DNSLabel(chucked_data + labels)
        return result
    except Exception:
        print("Original data length must be less than 141 bytes!")
Beispiel #7
0
    def inital_validate(self):
        self._label=dnslib.DNSLabel(self.conf['zone'])
        
        if not 'zone_file' in self.conf:
            raise SWAN_ModuleConfigurationError('zone_file attribute is missing from module configuration')
        
        if not os.path.isfile(self.conf['zone_file']):
            raise SWAN_ModuleConfigurationError('The zone file defined %s does not exists or is not a file' %self.conf['zone_file'])
        
        try:
            zfile=open(self.conf['zone_file'],'r').read()
            self.zone_parser=list(dnslib.ZoneParser(zfile))
        except:
            raise SWAN_ModuleConfigurationError('Failed to load zone file %s' %self.conf['zone_file'])

        for rr in self.zone_parser:
            self._set_rr_map_record(rr)
Beispiel #8
0
def parse_zonefile(s_zone):
    l_lines = s_zone.split("\n")
    s_apex_domain = l_lines[0].split(" ")[1]
    i_default_ttl = int(l_lines[1].split(" ")[1])
    l_zone = []
    print("domain: {}.".format(s_apex_domain))
    for s_line in l_lines[2:-1]:
        rr_record = dnslib.RR.fromZone(s_line)[0]
        s_label = str(rr_record.rname)
        if s_label != ".":
            s_label = s_label + s_apex_domain
        else:
            s_label = s_apex_domain
        rr_record.rname = dnslib.DNSLabel(s_label)
        l_zone.append(rr_record)
    if verbose:
        print_l_zone(l_zone)
    return l_zone
Beispiel #9
0
def application(environ: dict, start_response):
    headers = [("Server", "HexDNS Redirect Server")]

    host = environ.get("HTTP_HOST")

    if not host:
        start_response("404 Not Found", headers)
        return []

    host_parts = host.split(":", 1)
    host_dns_label = dnslib.DNSLabel(host_parts[0])
    zone, record_name = grpc.DnsServiceServicer.find_zone(host_dns_label)

    if not zone:
        start_response("404 Not Found", headers)
        return []

    redirect_record = grpc.DnsServiceServicer.find_records(
        models.RedirectRecord, record_name, zone).first()
    if not redirect_record:
        start_response("404 Not Found", headers)
        return []

    target = redirect_record.target
    if redirect_record.include_path:
        target += environ.get("PATH_INFO", "")

    headers.append(("Location", target))

    now = datetime.datetime.utcnow()
    expiry = now + datetime.timedelta(seconds=redirect_record.ttl)
    headers.append(("Date", now.strftime("%a, %d %b %Y %H:%M:%S GMT")))
    headers.append(("Expires", expiry.strftime("%a, %d %b %Y %H:%M:%S GMT")))

    start_response("308 Permanent Redirect", headers)
    return []
Beispiel #10
0
 def _get_rr(self, rname, rtype, rdata):
     return dnslib.RR(rname=dnslib.DNSLabel(rname),
                      rtype=dnslib.QTYPE.reverse[rtype],
                      rclass=dnslib.CLASS.reverse['IN'],
                      rdata=getattr(dns, rtype)(rdata))
Beispiel #11
0
from django.core.management.base import BaseCommand
from django.template.loader import render_to_string
from django.core.mail import EmailMultiAlternatives
from django.conf import settings
from dns_grpc import models, views
import keycloak.exceptions
import random
import retry
import dnslib

WANTED_NS = [
    dnslib.DNSLabel('ns1.as207960.net'),
    dnslib.DNSLabel('ns2.as207960.net')
]


def mail_valid(user, zone):
    feedback_url = views.utils.get_feedback_url(f"HexDNS for {zone.zone_root}",
                                                zone.id)

    context = {
        "name": user.first_name,
        "zone": zone,
        "feedback_url": feedback_url
    }
    html_content = render_to_string("dns_email/valid.html", context)
    txt_content = render_to_string("dns_email/valid.txt", context)

    email = EmailMultiAlternatives(
        subject='HexDNS Zone Activated',
        body=txt_content,
Beispiel #12
0
 if not cache.get((domain, question_type)):
     print(
         'В кэше нет ответа на запрос, отправляем запрос авторитетному серверу'
     )
 else:
     print('Овет взять из кэша')
 while not cache.get((domain, question_type)) and new_domain:
     if flag1:
         fun(request, '192.5.5.241', client)
         flag1 = False
         flag2 = True
     elif flag2:
         l = new_domain.rfind('.')
         d = str_domain[l + 1:]
         new_domain = new_domain[:l]
         if cache.get((dnslib.DNSLabel(d), 2)):
             ns = cache.get((dnslib.DNSLabel(d), 2))[0]
             for i in ns:
                 try:
                     ip = str(
                         cache.get((dnslib.DNSLabel(str(i.rdata)),
                                    1))[0][0].rdata)
                     fun(request, ip, client)
                 except Exception:
                     pass
     else:
         l = new_domain.find('.')
         if not l == -1:
             d = str_domain[l + 1:]
             new_domain = new_domain[l + 1:]
             try: