def main(argv): global tm global resolver try: try: opts, args = getopt.getopt(argv[1:], 'f:d:l:c:r:t:64b:u:kmpo:a:R:x:EAs:Fh') except getopt.GetoptError, e: usage(str(e)) sys.exit(1) tm = transport.DNSQueryTransportManager() resolver = Resolver.from_file('/etc/resolv.conf', StandardRecursiveQueryCD, transport_manager=tm) # get all the -x options explicit_delegations = {} client_ipv4 = None client_ipv6 = None for opt, arg in opts: if opt == '-x': try: domain, mappings = arg.split(':', 1) except ValueError: usage('Incorrect usage of -x option: "%s"' % arg) sys.exit(1) domain = domain.strip() mappings = mappings.strip() try: domain = dns.name.from_text(domain) except dns.exception.DNSException: usage('The domain name was invalid: "%s"' % domain) sys.exit(1) if not mappings: usage('Incorrect usage of -x option: "%s"' % arg) sys.exit(1) if domain not in explicit_delegations: explicit_delegations[domain] = set() explicit_delegations[domain].update(name_addr_mappings_from_string(mappings)) elif opt == '-b': try: addr = IPAddr(arg) except ValueError: usage('The IP address was invalid: "%s"' % arg) sys.exit(1) if addr.version == 4: client_ipv4 = addr fam = socket.AF_INET else: client_ipv6 = addr fam = socket.AF_INET6 try: s = socket.socket(fam) s.bind((addr, 0)) del s except socket.error, e: if e.errno == errno.EADDRNOTAVAIL: usage('Cannot bind to specified IP address: "%s"' % addr) sys.exit(1)
def probe(config: ProbeConfig, name_list: typing.List[str], cache={}): tm = transport.DNSQueryTransportManager() try: rdclass = dns.rdataclass.IN ceiling = None analyst_cls = None new_resolver_function = None explicit_delegations, odd_ports = get_explicit_delegations( tm, config.query_authoritative_servers, config.server_list) if not config.query_authoritative_servers: ceiling = None analyst_cls = PrivateRecursiveAnalyst new_resolver_function = _init_stub_resolver else: ceiling = dns.name.root analyst_cls = PrivateAnalyst new_resolver_function = _init_full_resolver resolver = new_resolver_function(tm, explicit_delegations, odd_ports) query_class_mixin = CustomQueryMixin CustomQueryMixin.edns_options.append(_get_dns_cookie_option()) cache_lock = threading.Lock() analysis_structured = OrderedDict() analysis_structured['_meta._dnsviz.'] = { 'names': [lb2s(n) for n in name_list] } for name in name_list: try: name = dns.name.from_text(name) except UnicodeDecodeError as e: logger.error('%s: "%s"' % (e, name)) except dns.exception.DNSException: logger.error('The domain name was invalid: "%s"' % name) else: r = _probe( analyst_cls, name, config, rdclass, ceiling, query_class_mixin, explicit_delegations, odd_ports, cache, cache_lock, tm, resolver, ) if r is not None: r.serialize(analysis_structured, config.meta_only) return analysis_structured finally: tm.close()
def setUp(self): self.tm = transport.DNSQueryTransportManager() self.resolver = Resolver.from_file('/etc/resolv.conf', StandardRecursiveQueryCD, transport_manager=self.tm) self.helper = DomainListArgHelper(self.resolver) self.logger = logging.getLogger() for handler in self.logger.handlers: self.logger.removeHandler(handler) self.logger.addHandler(logging.NullHandler()) try: ArgHelper.bindable_ip('::1') except argparse.ArgumentTypeError: self.use_ipv6 = False else: self.use_ipv6 = True self.first_port = ZoneFileToServe._next_free_port self.custom_query_mixin_edns_options_orig = CustomQueryMixin.edns_options[:]
def main(argv): sock = transport.ReaderWriter(io.open(sys.stdin.fileno(), 'rb'), io.open(sys.stdout.fileno(), 'wb')) sock.lock = threading.Lock() qth_reader = transport.DNSQueryTransportHandlerWebSocketClientReader(sock) qth_writer = transport.DNSQueryTransportHandlerWebSocketClientWriter(sock) response_queue = queue.Queue() queries_in_waiting = set() th_factory = transport.DNSQueryTransportHandlerDNSFactory() tm = transport.DNSQueryTransportManager() try: while True: try: qth_writer.qtms = [] tm.handle_msg(qth_reader) qth_reader.finalize() if len(qth_reader.msg_recv) == 0: break # load the json content try: content = json.loads( codecs.decode(qth_reader.msg_recv, 'utf-8')) except ValueError: raise RemoteQueryError( 'JSON decoding of request failed: %s' % qth_reader.msg_recv) if 'version' not in content: raise RemoteQueryError( 'No version information in request.') try: major_vers, minor_vers = [ int(x) for x in str(content['version']).split('.', 1) ] except ValueError: raise RemoteQueryError( 'Version of JSON input in request is invalid: %s' % content['version']) # ensure major version is a match and minor version is no greater # than the current minor version curr_major_vers, curr_minor_vers = [ int(x) for x in str(transport.DNS_TRANSPORT_VERSION).split( '.', 1) ] if major_vers != curr_major_vers or minor_vers > curr_minor_vers: raise RemoteQueryError( 'Version %d.%d of JSON input in request is incompatible with this software.' % (major_vers, minor_vers)) if 'requests' not in content: raise RemoteQueryError( 'No request information in request.') for i, qtm_serialized in enumerate(content['requests']): try: qtm = transport.DNSQueryTransportMeta.deserialize_request( qtm_serialized) except transport.TransportMetaDeserializationError as e: raise RemoteQueryError( 'Error deserializing request information: %s' % e) qth_writer.add_qtm(qtm) th = th_factory.build(processed_queue=response_queue) th.add_qtm(qtm) th.init_req() tm.handle_msg_nowait(th) queries_in_waiting.add(th) while queries_in_waiting: th = response_queue.get() th.finalize() queries_in_waiting.remove(th) qth_writer.init_req() except RemoteQueryError as e: qth_writer.init_err_send(str(e)) tm.handle_msg(qth_writer) except EOFError: pass finally: tm.close()
def _init_tm(): global tm tm = transport.DNSQueryTransportManager()