return self._lookup(name, dns.IN, dns.A, timeout) ## this sets up the application application = service.Application('dnsserver', 1, 1) # set up a resolver that uses the mapping or a secondary nameserver xnsresolver = MapResolver(servers=[('8.8.8.8', 53)]) # create the protocols f = server.DNSServerFactory(caches=[cache.CacheResolver()], clients=[xnsresolver]) p = dns.DNSDatagramProtocol(f) f.noisy = p.noisy = False # register as tcp and udp ret = service.MultiService() PORT=53 for (klass, arg) in [(internet.TCPServer, f), (internet.UDPServer, p)]: s = klass(PORT, arg) s.setServiceParent(ret) # run all of the above as a twistd application ret.setServiceParent(service.IServiceCollection(application))
server.Site( servers.http.HTTPJsonResource()), interface=interface) print(f"Starting HTTP service on port {port}/tcp") elif protocol == "dns": unknown_arguments = set(service.keys()).difference( ["protocol", "port", "interface"]) if len(unknown_arguments): raise Exception( f"Unknown arguments for service 'dns': ", ", ".join(f"'{x}'" for x in unknown_arguments)) dns_server_factory = servers.dns.DNSJsonServerFactory() reactor.listenUDP( port, dns.DNSDatagramProtocol(dns_server_factory), interface=interface) reactor.listenTCP(port, dns_server_factory, interface=interface) print( f"Starting DNS service on port {port}/tcp and {port}/udp" ) else: raise Exception(f"Unknown protocol '{protocol}'") except Exception as e: msg = str(e) if isinstance(e, error.CannotListenError): msg = f"Cannot listen on '{interface}:{port}' address already in use" print(msg)
def main(): parser = argparse.ArgumentParser( description="A lightweight yet useful proxy DNS server") parser.add_argument( '-b', '--bind-addr', type=str, help='local address to listen', default='127.0.0.1', ) parser.add_argument( '-p', '--bind-port', type=int, help="local port to listen", default=53, ) parser.add_argument('--upstream-ip', type=str, help="upstream DNS server ip address", default='208.67.222.222') parser.add_argument('--upstream-port', type=int, help="upstream DNS server port", default=53) parser.add_argument('--query-timeout', type=int, help="time before close port used for querying", default=1) parser.add_argument('--min-ttl', type=int, help="the minimum time a record is held in cache", default=0) parser.add_argument('--max-ttl', type=int, help="the maximum time a record is held in cache", default=604800) parser.add_argument('--cache-size', type=int, help="record cache size", default=500) parser.add_argument('-t', '--tcp-server', help="enables TCP serving", action="store_true") parser.add_argument('--hosts-file', help="hosts file", default="") parser.add_argument('--dispatch-conf', help="URL dispatch conf file", default="/usr/local/etc/simpledns/dispatch.conf") parser.add_argument('-v', '--verbosity', type=int, choices=[0, 1, 2], help="output verbosity", default=0) parser.add_argument('-q', '--quiet', help="disable output", action='store_true') parser.add_argument('-V', '--version', help="print version number and exit", action='store_true') args = parser.parse_args() if args.version: print("SimpleDNS " + __version__) return if not args.quiet: log.startLogging(sys.stdout) addr = args.bind_addr port = args.bind_port log.msg("Listening on " + addr + ':' + str(port)) log.msg("Using " + args.upstream_ip + ':' + str(args.upstream_port) + ' as upstream server') hosts_file = None if not args.hosts_file: hosts_file = '/etc/hosts' if os.environ.__contains__('WINDIR'): hosts_file = os.environ['WINDIR'] + '/system32/drivers/etc/hosts' else: hosts_file = args.hosts_file factory = ExtendDNSServerFactory( caches=[ ExtendCacheResolver(verbose=args.verbosity, cacheSize=args.cache_size, minTTL=args.min_ttl, maxTTL=args.max_ttl) ], clients=[ hosts.Resolver(hosts_file), DispatchResolver(args.dispatch_conf, servers=[(args.upstream_ip, args.upstream_port)], minTTL=args.min_ttl, query_timeout=args.query_timeout, verbose=args.verbosity) ], verbose=args.verbosity) protocol = dns.DNSDatagramProtocol(controller=factory) if args.verbosity < 2: dns.DNSDatagramProtocol.noisy = False server.DNSServerFactory.noisy = False try: reactor.listenUDP(port, protocol, addr) if args.tcp_server: reactor.listenTCP(port, factory, interface=addr) try: tornado.ioloop.IOLoop.instance().start() except NameError: log.msg("Tornado not found. Using twisted reactor") reactor.run() except error.CannotListenError: log.msg("Couldn't listen on " + addr + ':' + str(port)) log.msg('Check if BIND_PORT is already in use') log.msg('Try using sudo to run this program')
def main(): """ Run the server. """ argparser = ArgumentParser( description='nsshell.py HOST IP\nnsshell.py localhost 127.0.0.1', formatter_class=RawTextHelpFormatter) argparser.add_argument( 'hostname', default=str(subprocess.check_output(['hostname', '-f'])).strip(), nargs='?', help='hostname of the publicly facing server, for debugging=localhost', type=str) argparser.add_argument('ip', default='', nargs='?', help='ip addr of publicly facing server', type=str) config_args = argparser.add_argument_group(title='Config Args') config_args.add_argument('--logdir', action='store', default='', dest='logdir', help='set logging directory') if len(sys.argv) <= 2: argparser.print_help() sys.exit(1) args = vars(argparser.parse_args()) # check to see if logging has been disabled if args['logdir'].lower() in config.CLI_NO: config.LOG_DIR = None elif args['logdir']: config.LOG_DIR = os.path.realpath(args['logdir']) if config.LOG_DIR and not os.path.exists(config.LOG_DIR): os.makedirs(config.LOG_DIR) hostname = args['hostname'] ip = args['ip'] if len(ip) > 15: sys.stderr.write("Must be ipv4:" + args['ip']) sys.exit(1) print("Starting nsshell - DO NOT DISTRIBUTE") print("using hostname: " + hostname) print("using IP: " + ip) if config.LOG_DIR: print("logging to: " + config.LOG_DIR) load = loader(hostname, ip) payload_count = len(load.payloads) #payload_count is used to prevent session IDs and payloads from sharing the same keys. sessionhandler = session_handler(payload_count) sr = ShellResolver(sessionhandler, ip, hostname, load) console_handler = Console() console_handler.setSession(sessionhandler) #The torando DNS server will throw a harmless exception when scanned by nmap. #We are overriding gotResolverResponse with a lambda to avoid this exception: #File "/usr/lib/python2.7/dist-packages/twisted/names/server.py", line 263, in gotResolverResponse # def gotResolverResponse(self, (ans, auth, add), protocol, message, address): #exceptions.TypeError: 'NoneType' object is not iterable server.gotResolverResponse = lambda *x: False factory = server.DNSServerFactory( clients=[sr] #We don't want to be an open resolver: #, client.Resolver(resolv='/etc/resolv.conf')] ) protocol = dns.DNSDatagramProtocol(controller=factory) print("binding udp/53") reactor.listenUDP(53, protocol) print("binding tcp/53") reactor.listenTCP(53, factory) with open('payloads.txt', 'w') as f: for payload in load.build_payloads(): f.write(payload + "\n") print("wrote connect-back payloads to:payloads.txt") stdio.StandardIO(console_handler) reactor.run()