def check_resolver(self, resolver): runner = test.runner.get_runner() if test.runner.Torrc.PORT not in runner.get_options(): self.skipTest('(no control port)') return elif resolver not in system_resolvers(): self.skipTest('(resolver unavailable on this platform)') return with runner.get_tor_socket(): connections = get_connections(resolver, process_pid=runner.get_pid()) for conn in connections: if conn.local_address == '127.0.0.1' and conn.local_port == test.runner.CONTROL_PORT: return resolver_command = RESOLVER_COMMAND[resolver].format( pid=runner.get_pid()) resolver_output = stem.util.system.call(resolver_command) self.fail( 'Unable to find our controller connection with %s (%s). Connections found were...\n\n%s\n\nCommand output was...\n\n%s' % (resolver, resolver_command, '\n'.join(map( str, connections)), resolver_output))
def connections(): global controller args = StaticInfo.args control_port = StaticInfo.control_port controller = StaticInfo.controller if not (controller.is_alive()): return desc = controller.get_network_status(default = None) pid = StaticInfo.pid policy = controller.get_exit_policy() relays = {} # address => [orports...] for desc in controller.get_network_statuses(): relays.setdefault(desc.address, []).append(desc.or_port) exit_connections = {} # port => [connections] for conn in get_connections(resolver = args.resolver, process_pid = pid): global categories if conn.protocol == 'udp': continue if conn.local_port in controller.get_ports(Listener.OR, []): categories['INBOUND_OR'].append(conn) elif conn.local_port in controller.get_ports(Listener.DIR, []): categories['INBOUND_DIR'].append(conn) elif conn.local_port in controller.get_ports(Listener.CONTROL, []): categories['INBOUND_CONTROL'].append(conn) elif conn.remote_port in relays.get(conn.remote_address, []): categories['OUTBOUND'].append(conn) elif policy.can_exit_to(conn.remote_address, conn.remote_port): categories['EXIT'].append(conn) exit_connections.setdefault(conn.remote_port, []).append(conn) else: categories['OUTBOUND'].append(conn) circ = controller.get_circuits([]) for conn in circ: categories['CIRCUIT'].append(conn) if exit_connections: total_ipv4, total_ipv6 = 0, 0 for port in sorted(exit_connections): connections = exit_connections[port] ipv4_count = len([conn for conn in connections if is_valid_ipv4_address(conn.remote_address)]) ipv6_count = len(connections) - ipv4_count total_count = len(connections) total_ipv4, total_ipv6 = total_ipv4 + ipv4_count, total_ipv6 + ipv6_count usage = port_usage(port) label = '%s (%s)' % (port, usage) if usage else port
def get_entry_ip(): resolvers = system_resolvers() # check avaiable resolvers tor_pids = pid_by_name('tor', multiple=True) # gets tor's PID if len(resolvers) > 0 and len(tor_pids) > 0: picked_resolver = resolvers[0] # getting the first one try: process_pid = tor_pids[0] # getting the first, if we are running tor only as a service it must have just one PID cons = get_connections(picked_resolver, process_pid, process_name='tor') return cons except ValueError, IOError: print "Error getting connections to entry point"
def check_resolver(self, resolver): runner = test.runner.get_runner() if test.runner.Torrc.PORT not in runner.get_options(): self.skipTest('(no control port)') return elif resolver not in system_resolvers(): self.skipTest('(resolver unavailable on this platform)') return with runner.get_tor_socket(): connections = get_connections(resolver, process_pid = runner.get_pid()) for conn in connections: if conn.local_address == '127.0.0.1' and conn.local_port == test.runner.CONTROL_PORT: return self.fail('Unable to find localhost connection with %s:\n%s' % (resolver, '\n'.join(connections)))
def check_resolver(self, resolver): runner = test.runner.get_runner() if test.runner.Torrc.PORT not in runner.get_options(): self.skipTest('(no control port)') return elif resolver not in system_resolvers(): self.skipTest('(resolver unavailable on this platform)') return with runner.get_tor_socket(): connections = get_connections(resolver, process_pid=runner.get_pid()) for conn in connections: if conn.local_address == '127.0.0.1' and conn.local_port == test.runner.CONTROL_PORT: return self.fail('Unable to find localhost connection with %s:\n%s' % (resolver, '\n'.join(connections)))
def Inbound(self): if not (controller.is_alive()): return global inbound_y global inbound_databuffer inbound_count = 0 for conn in get_connections(resolver=args.resolver, process_pid=pid): if conn.protocol == 'udp': continue if conn.local_port in controller.get_ports(Listener.OR, []): inbound_count += 1 elif conn.local_port in controller.get_ports(Listener.DIR, []): inbound_count += 1 elif conn.local_port in controller.get_ports(Listener.CONTROL, []): inbound_count += 1 inbound_databuffer.append(inbound_count) inbound_y[:] = inbound_databuffer self.ui.Inbound_Conn1.setText(str(inbound_count) + " /Sec") self.ui.inbound_curve.setData(inbound_x, inbound_y)
def test_get_connections(self): runner = test.runner.get_runner() if not test.runner.Torrc.PORT in runner.get_options(): test.runner.skip(self, '(no control port)') return elif not test.runner.get_runner().is_ptraceable(): test.runner.skip(self, '(DisableDebuggerAttachment is set)') return for resolver in get_system_resolvers(): with runner.get_tor_socket(): tor_pid = test.runner.get_runner().get_pid() connections = get_connections(resolver, process_pid = tor_pid) for conn in connections: if conn.local_address == '127.0.0.1' and conn.local_port == test.runner.CONTROL_PORT: return self.fail('Unable to find localhost connection with %s:\n%s' % (resolver, '\n'.join(connections)))
def Outbound(self): if not (controller.is_alive()): return global outbound_y global outbound_databuffer global relays outbound_count = 0 for conn in get_connections(resolver=args.resolver, process_pid=pid): if conn.protocol == 'udp': continue if conn.remote_port in relays.get(conn.remote_address, []): outbound_count += 1 elif self.policy.can_exit_to(conn.remote_address, conn.remote_port): outbound_count += 1 else: outbound_count += 1 self.ui.Outbound_Conn1.setText(str(outbound_count) + " /Sec") outbound_databuffer.append(outbound_count) outbound_y[:] = outbound_databuffer self.ui.outbound_curve.setData(outbound_x, outbound_y)
def _task(self, process_pid, process_name): if self._custom_resolver: resolver = self._custom_resolver is_default_resolver = False elif self._resolvers: resolver = self._resolvers[0] is_default_resolver = True else: return False # nothing to resolve with try: start_time = time.time() new_connections, new_start_times = [], {} for conn in connection.get_connections(resolver, process_pid = process_pid, process_name = process_name): conn_start_time, is_legacy = self._start_times.get(conn, (start_time, self._is_first_run)) new_start_times[conn] = (conn_start_time, is_legacy) new_connections.append(Connection(conn_start_time, is_legacy, *conn)) self._connections = new_connections self._start_times = new_start_times self._is_first_run = False runtime = time.time() - start_time if is_default_resolver: self._failure_count = 0 # Reduce our rate if connection resolution is taking a long time. This is # most often an issue for extremely busy relays. min_rate = 100 * runtime if self.get_rate() < min_rate: self._rate_too_low_count += 1 if self._rate_too_low_count >= 3: min_rate += 1 # little extra padding so we don't frequently update this self.set_rate(min_rate) self._rate_too_low_count = 0 log.debug('tracker.lookup_rate_increased', seconds = "%0.1f" % min_rate) else: self._rate_too_low_count = 0 return True except IOError as exc: log.info('wrap', text = exc) # Fail over to another resolver if we've repeatedly been unable to use # this one. if is_default_resolver: self._failure_count += 1 if self._failure_count >= 3: self._resolvers.pop(0) self._failure_count = 0 if self._resolvers: log.notice( 'tracker.unable_to_use_resolver', old_resolver = resolver, new_resolver = self._resolvers[0], ) else: log.notice('tracker.unable_to_use_all_resolvers') return False
def _task(self, process_pid, process_name): if self._custom_resolver: resolver = self._custom_resolver is_default_resolver = False elif self._resolvers: resolver = self._resolvers[0] is_default_resolver = True else: return False # nothing to resolve with try: start_time = time.time() new_connections, new_start_times = [], {} if resolver == CustomResolver.INFERENCE: # provide connections going to a relay or one of our tor ports connections = [] controller = tor_controller() consensus_tracker = get_consensus_tracker() for conn in proc.connections(user = controller.get_user(None)): if conn.remote_port in consensus_tracker.get_relay_fingerprints(conn.remote_address): connections.append(conn) # outbound to another relay elif conn.local_port in controller.get_ports(stem.control.Listener.OR, []): connections.append(conn) # inbound to our ORPort elif conn.local_port in controller.get_ports(stem.control.Listener.DIR, []): connections.append(conn) # inbound to our DirPort elif conn.local_port in controller.get_ports(stem.control.Listener.CONTROL, []): connections.append(conn) # controller connection else: connections = connection.get_connections(resolver, process_pid = process_pid, process_name = process_name) for conn in connections: conn_start_time, is_legacy = self._start_times.get(conn, (start_time, self._is_first_run)) new_start_times[conn] = (conn_start_time, is_legacy) new_connections.append(Connection(conn_start_time, is_legacy, *conn)) self._connections = new_connections self._start_times = new_start_times self._is_first_run = False runtime = time.time() - start_time if is_default_resolver: self._failure_count = 0 # Reduce our rate if connection resolution is taking a long time. This is # most often an issue for extremely busy relays. min_rate = 100 * runtime if self.get_rate() < min_rate: self._rate_too_low_count += 1 if self._rate_too_low_count >= 3: min_rate += 1 # little extra padding so we don't frequently update this self.set_rate(min_rate) self._rate_too_low_count = 0 log.debug('tracker.lookup_rate_increased', seconds = "%0.1f" % min_rate) else: self._rate_too_low_count = 0 return True except IOError as exc: log.info('wrap', text = exc) # Fail over to another resolver if we've repeatedly been unable to use # this one. if is_default_resolver: self._failure_count += 1 if self._failure_count >= 3: self._resolvers.pop(0) self._failure_count = 0 if self._resolvers: log.notice( 'tracker.unable_to_use_resolver', old_resolver = resolver, new_resolver = self._resolvers[0], ) else: log.notice('tracker.unable_to_use_all_resolvers') return False
from stem.util.system import pid_by_name resolvers = system_resolvers() if not resolvers: print("Stem doesn't support any connection resolvers on our platform.") sys.exit(1) picked_resolver = resolvers[0] # lets just opt for the first print('Our platform supports connection resolution via: %s (picked %s)' % (', '.join(resolvers), picked_resolver)) tor_pids = pid_by_name('tor', multiple=True) if not tor_pids: print("Unable to get tor's pid. Is it running?") sys.exit(1) elif len(tor_pids) > 1: print("You're running %i instances of tor, picking the one with pid %i" % (len(tor_pids), tor_pids[0])) else: print('Tor is running with pid %i' % tor_pids[0]) print('\nConnections:\n') for conn in get_connections(picked_resolver, process_pid=tor_pids[0], process_name='tor'): print(' %s:%s => %s:%s' % (conn.local_address, conn.local_port, conn.remote_address, conn.remote_port))
def main(args=None): parser = argparse.ArgumentParser() parser.add_argument('--ctrlport', help='default: 9051 or 9151') parser.add_argument('--resolver', help='default: autodetected') args = parser.parse_args(args) control_port = int(args.ctrlport) if args.ctrlport else 'default' controller = stem.connection.connect(control_port=('127.0.0.1', control_port)) if not controller: return desc = controller.get_network_status(default=None) pid = controller.get_pid() print( HEADER_LINE.format( version=str(controller.get_version()).split()[0], uptime=stem.util.str_tools.short_time_label( time.time() - stem.util.system.start_time(pid)), flags=', '.join(desc.flags if desc else ['none']), )) policy = controller.get_exit_policy() relays = {} # address => [orports...] for desc in controller.get_network_statuses(): relays.setdefault(desc.address, []).append(desc.or_port) # categorize our connections categories = collections.OrderedDict(( (INBOUND_ORPORT, []), (INBOUND_DIRPORT, []), (INBOUND_CONTROLPORT, []), (OUTBOUND_ORPORT, []), (OUTBOUND_EXIT, []), (OUTBOUND_UNKNOWN, []), )) exit_connections = {} # port => [connections] for conn in get_connections(resolver=args.resolver, process_pid=pid): if conn.protocol == 'udp': continue if conn.local_port in controller.get_ports(Listener.OR, []): categories[INBOUND_ORPORT].append(conn) elif conn.local_port in controller.get_ports(Listener.DIR, []): categories[INBOUND_DIRPORT].append(conn) elif conn.local_port in controller.get_ports(Listener.CONTROL, []): categories[INBOUND_CONTROLPORT].append(conn) elif conn.remote_port in relays.get(conn.remote_address, []): categories[OUTBOUND_ORPORT].append(conn) elif policy.can_exit_to(conn.remote_address, conn.remote_port): categories[OUTBOUND_EXIT].append(conn) exit_connections.setdefault(conn.remote_port, []).append(conn) else: categories[OUTBOUND_UNKNOWN].append(conn) print(DIV) print(COLUMN % ('Type', 'IPv4', 'IPv6')) print(DIV) total_ipv4, total_ipv6 = 0, 0 for label, connections in categories.items(): if len(connections) == 0: continue ipv4_count = len([ conn for conn in connections if is_valid_ipv4_address(conn.remote_address) ]) ipv6_count = len(connections) - ipv4_count total_ipv4, total_ipv6 = total_ipv4 + ipv4_count, total_ipv6 + ipv6_count print(COLUMN % (label, ipv4_count, ipv6_count)) print(DIV) print(COLUMN % ('Total', total_ipv4, total_ipv6)) print(DIV) print('') if exit_connections: print(DIV) print(COLUMN % ('Exit Port', 'IPv4', 'IPv6')) print(DIV) total_ipv4, total_ipv6 = 0, 0 for port in sorted(exit_connections): connections = exit_connections[port] ipv4_count = len([ conn for conn in connections if is_valid_ipv4_address(conn.remote_address) ]) ipv6_count = len(connections) - ipv4_count total_ipv4, total_ipv6 = total_ipv4 + ipv4_count, total_ipv6 + ipv6_count usage = port_usage(port) label = '%s (%s)' % (port, usage) if usage else port print(COLUMN % (label, ipv4_count, ipv6_count)) print(DIV) print(COLUMN % ('Total', total_ipv4, total_ipv6)) print(DIV) print('')
def main(): parser = argparse.ArgumentParser() parser.add_argument('--ctrlport', type=int, help='default: 9051', default=9051) parser.add_argument('--resolver', help='default: autodetect', default='') args = parser.parse_args() with Controller.from_port(port=args.ctrlport) as controller: controller.authenticate() try: ORPort = None ORPort6 = None for address, port in controller.get_listeners(Listener.OR): if is_valid_ipv4_address(address): ORPort = port else: ORPort6 = port except Exception as Exc: print('Woops, control ports aren\'t configured') print(Exc) return relays = {} # address => [orports...] relays = parse_consensus(relays, '/var/lib/tor/data/cached-consensus') relays = parse_consensus(relays, '/var/lib/tor/data2/cached-consensus') MaxOpened = {} # hold the maximum amount of opened ports MaxClosed = {} # hold the maximum amount of closed ports MaxAll = {} # hold the maximum amount of overall ports Curr = {} # the current network connections of Tor # avoid useless calculation of mean immediately after start # first = True while True: # read in all allowed exit ports # exit_ports = [] for filename in glob.glob('/etc/tor/torrc.d/*') + ( glob.glob('/etc/tor/*')): if os.path.isfile(filename): inputfile = open(filename) lines = inputfile.readlines() inputfile.close() for line in lines: if line.startswith('ExitPolicy *accept '): accept = line.split()[2] if ':' in accept: port = accept.split(':')[1] if '-' in port: min = port.split('-')[0] max = port.split('-')[1] for port in range(int(min), int(max)): exit_ports.append(port) else: exit_ports.append(port) try: t1 = time.time() pid = controller.get_info('process/pid') connections = get_connections(resolver=args.resolver, process_pid=pid, process_name='tor') t2 = time.time() policy = controller.get_exit_policy() if not first: Prev = Curr.copy() Curr.clear() my_ipv4 = '5.9.158.75' my_ipv6 = ipaddress.IPv6Address( '2a01:4f8:190:514a::2').exploded for conn in connections: laddr, raddr = conn.local_address, conn.remote_address lport, rport = conn.local_port, conn.remote_port # ignore incoming connections # if conn.is_ipv6: if lport == ORPort6: if laddr == my_ipv6: continue else: if lport == ORPort: if laddr == my_ipv4: continue if raddr in relays: if rport in relays[raddr]: continue if not policy.can_exit_to(raddr, rport): continue # store the connections itself instead just counting them here # b/c we have to calculate the diff of 2 sets later too # Curr.setdefault(rport, []).append(str(lport) + ':' + raddr) dt = t2 - t1 os.system('clear') print( ' port # opened closed max ( %s:%s, %i conns %.2f sec )' % (args.resolver, args.ctrlport, len(connections), dt)) if first: Prev = Curr.copy() ports = sorted( set( list(Curr.keys()) + list(Prev.keys()) + list(MaxAll.keys()))) for port in ports: c = set({}) p = set({}) if port in Prev: p = set(Prev[port]) if port in Curr: c = set(Curr[port]) n_curr = len(c) n_opened = len(c - p) n_closed = len(p - c) MaxAll.setdefault(port, 0) MaxOpened.setdefault(port, 0) MaxClosed.setdefault(port, 0) if not first: if MaxAll[port] < n_curr: MaxAll[port] = n_curr if MaxOpened[port] < n_opened: MaxOpened[port] = n_opened if MaxClosed[port] < n_closed: MaxClosed[port] = n_closed stri = ' %5i %5i %6i %6i %6i %6i %6i (%s)' % ( port, n_curr, n_opened, n_closed, MaxAll[port], MaxOpened[port], MaxClosed[port], port_usage(port)) print(stri.replace(' 0', ' ')) first = False except KeyboardInterrupt: break except Exception: continue
def main(): ctrlport = 9051 resolver = 'proc' #handler = logging.FileHandler('/tmp/stem_debug') #handler.setFormatter(logging.Formatter( #fmt = '%(asctime)s [%(levelname)s] %(message)s', #datefmt = '%m/%d/%Y %H:%M:%S', #)) #log = stem.util.log.get_logger() #log.setLevel(logging.DEBUG) #log.addHandler(handler) #stem.util.connection.LOG_CONNECTION_RESOLUTION = True parser = argparse.ArgumentParser() parser.add_argument("--ctrlport", help="default: " + str(ctrlport)) parser.add_argument("--resolver", help="default: " + resolver) args = parser.parse_args() if args.ctrlport: ctrlport = int(args.ctrlport) if args.resolver: resolver= str(args.resolver) with Controller.from_port(port=ctrlport) as controller: controller.authenticate() try: ControlPort = int(controller.get_conf("ControlPort")) ORPort = None ORPort6 = None DirPort = None DirPort6 = None for address, port in controller.get_listeners(Listener.OR): if is_valid_ipv4_address(address): ORPort = port else: ORPort6 = port for address, port in controller.get_listeners(Listener.DIR): if is_valid_ipv4_address(address): DirPort = port else: DirPort6 = port except Exception as Exc: print ("Woops, control ports aren't configured") return # our version, uptime and flags # version = str(controller.get_version()).split()[0] uptime = 0 flags = '' try: descriptor = controller.get_server_descriptor() uptime = descriptor.uptime flags = controller.get_network_status(relay=descriptor.fingerprint).flags except Exception as Exc: print (Exc) print (" %s %s %s" % (version, datetime.timedelta(seconds=uptime), " ".join(flags))) policy = controller.get_exit_policy() pid = controller.get_info("process/pid") connections = get_connections(resolver=resolver,process_pid=pid,process_name='tor') print (" resolver=%s pid=%s conns=%i" % (resolver, pid, len(connections))) relaysOr = {} relaysDir = {} for s in controller.get_network_statuses(): relaysOr.setdefault(s.address, []).append(s.or_port) relaysDir.setdefault(s.address, []).append(s.dir_port) # classify network connections by port and relationship to the Tor relay # ports_int = {} ports_ext = {} def inc_ports (ports, t): v4, v6 = ports.get(t,(0,0)) if conn.is_ipv6: ports[t] = (v4, v6+1) else: ports[t] = (v4+1, v6) def inc_ports_int (description): t = (description) inc_ports (ports_int, t) def inc_ports_ext (description): t = (description, rport) inc_ports (ports_ext, t) # classify each connection # for conn in connections: if conn.protocol == 'udp': continue laddr, raddr = conn.local_address, conn.remote_address lport, rport = conn.local_port, conn.remote_port if raddr in relaysOr: if (lport == ORPort and not conn.is_ipv6) or (lport == ORPort6 and conn.is_ipv6): inc_ports_int('ORPort <= relay') elif (lport == DirPort and not conn.is_ipv6) or (lport == DirPort6 and conn.is_ipv6): inc_ports_int('DirPort <= relay') elif rport in relaysOr[raddr]: inc_ports_int('=> relay ORPort') elif rport in relaysDir[raddr]: inc_ports_int('=> relay DirPort') else: # a system hosts beside a Tor relay another service too # inc_ports_ext ('=> relay port') elif policy.can_exit_to(raddr, rport): inc_ports_ext ('=> exit') else: if (lport == ORPort and not conn.is_ipv6) or (lport == ORPort6 and conn.is_ipv6): inc_ports_int('ORPort <= outer') elif (lport == DirPort and not conn.is_ipv6) or (lport == DirPort6 and conn.is_ipv6): inc_ports_int('DirPort <= outer') elif lport == ControlPort: inc_ports_int('CtrlPort <= local') else: inc_ports_ext ('=> non exit port') print () print (' description port ipv4 ipv6 servicename') print (' ----------------- ----- ---- ---- -------------') sum4 = 0 sum6 = 0 for t in sorted(ports_int): description = t v4, v6 = ports_int[t] sum4 += v4 sum6 += v6 print (" %-17s %5s %5s %5s" % (description, '', str(v4) if v4 > 0 else '', str(v6) if v6 > 0 else '')) print ("") exit4 = 0 exit6 = 0 for t in sorted(ports_ext): description, port = t v4, v6 = ports_ext[t] sum4 += v4 sum6 += v6 if description == '=> exit': exit4 += v4 exit6 += v6 print (" %-17s %5i %5s %5s %s" % (description, port, str(v4) if v4 > 0 else '', str(v6) if v6 > 0 else '', port_usage(port))) print ("") print (" %17s %5s %5i %5i" % ('sum', '', sum4, sum6)) print (" %17s %5s %5i %5i" % ('exits among them', '', exit4, exit6))
def _task(self, process_pid, process_name): if self._custom_resolver: resolver = self._custom_resolver is_default_resolver = False elif self._resolvers: resolver = self._resolvers[0] is_default_resolver = True else: return False # nothing to resolve with try: start_time = time.time() new_connections, new_start_times = [], {} if resolver == CustomResolver.INFERENCE: # provide connections going to a relay or one of our tor ports connections = [] controller = tor_controller() consensus_tracker = get_consensus_tracker() relay_ports = set( controller.get_ports(stem.control.Listener.OR, [])) relay_ports.update( controller.get_ports(stem.control.Listener.DIR, [])) relay_ports.update( controller.get_ports(stem.control.Listener.CONTROL, [])) for conn in proc.connections(user=controller.get_user(None)): if conn.remote_port in consensus_tracker.get_relay_fingerprints( conn.remote_address): connections.append(conn) # outbound to another relay elif conn.local_port in relay_ports: connections.append(conn) else: connections = connection.get_connections( resolver, process_pid=process_pid, process_name=process_name) for conn in connections: conn_start_time, is_legacy = self._start_times.get( conn, (start_time, self._is_first_run)) new_start_times[conn] = (conn_start_time, is_legacy) new_connections.append( Connection(conn_start_time, is_legacy, *conn)) self._connections = new_connections self._start_times = new_start_times self._is_first_run = False runtime = time.time() - start_time if is_default_resolver: self._failure_count = 0 # Reduce our rate if connection resolution is taking a long time. This is # most often an issue for extremely busy relays. min_rate = 100 * runtime if self.get_rate() < min_rate: self._rate_too_low_count += 1 if self._rate_too_low_count >= 3: min_rate += 1 # little extra padding so we don't frequently update this self.set_rate(min_rate) self._rate_too_low_count = 0 stem.util.log.debug( 'connection lookup time increasing to %0.1f seconds per call' % min_rate) else: self._rate_too_low_count = 0 return True except IOError as exc: stem.util.log.info(str(exc)) # Fail over to another resolver if we've repeatedly been unable to use # this one. if is_default_resolver: self._failure_count += 1 if self._failure_count >= 3: self._resolvers.pop(0) self._failure_count = 0 if self._resolvers: stem.util.log.notice( 'Unable to query connections with %s, trying %s' % (resolver, self._resolvers[0])) else: stem.util.log.notice(UNABLE_TO_USE_ANY_RESOLVER_MSG) return False
import sys from stem.util.connection import get_connections, system_resolvers from stem.util.system import pid_by_name resolvers = system_resolvers() if not resolvers: print("Stem doesn't support any connection resolvers on our platform.") sys.exit(1) picked_resolver = resolvers[0] # lets just opt for the first print("Our platform supports connection resolution via: %s (picked %s)" % (', '.join(resolvers), picked_resolver)) tor_pids = pid_by_name('tor', multiple = True) if not tor_pids: print("Unable to get tor's pid. Is it running?") sys.exit(1) elif len(tor_pids) > 1: print("You're running %i instances of tor, picking the one with pid %i" % (len(tor_pids), tor_pids[0])) else: print("Tor is running with pid %i" % tor_pids[0]) print("\nConnections:\n") for conn in get_connections(picked_resolver, process_pid = tor_pids[0], process_name = 'tor'): print(" %s:%s => %s:%s" % (conn.local_address, conn.local_port, conn.remote_address, conn.remote_port))
def main(): ctrlport = 9051 resolver = 'proc' parser = argparse.ArgumentParser() parser.add_argument("--ctrlport", help="default: " + str(ctrlport)) parser.add_argument("--resolver", help="default: " + resolver) args = parser.parse_args() if args.ctrlport: ctrlport = int(args.ctrlport) if args.resolver: resolver= str(args.resolver) with Controller.from_port(port=ctrlport) as controller: controller.authenticate() try: ControlPort = int(controller.get_conf("ControlPort")) ORPort = None ORPort6 = None DirPort = None DirPort6 = None for address, port in controller.get_listeners(Listener.OR): if is_valid_ipv4_address(address): ORPort = port else: ORPort6 = port for address, port in controller.get_listeners(Listener.DIR): if is_valid_ipv4_address(address): DirPort = port else: DirPort6 = port except Exception as Exc: print ("Woops, control ports aren't configured") print (Exc) return # we will ignore changes of relays during the runtime of this script # relays = {} for s in controller.get_network_statuses(): relays.setdefault(s.address, []).append(s.or_port) MaxOpened = {} # hold the maximum amount of opened ports MaxClosed = {} # hold the maximum amount of closed ports MaxAll = {} # hold the maximum amount of overall ports Curr = {} # the current network connections of Tor # avoid useless calculation of mean immediately after start # first = 1 while True: # read in all allowed exit ports # exit_ports = [] for filename in glob.glob("/etc/tor/torrc.d/*") + (glob.glob("/etc/tor/*")): if os.path.isfile(filename): inputfile = open(filename) lines = inputfile.readlines() inputfile.close() for line in lines: if line.startswith("ExitPolicy accept "): for word in line.split(): if '*:' in word: # do consider classX ports port = int (word.split(':')[1]) exit_ports.append(port) try: t1 = time.time() Prev = Curr.copy() Curr.clear() pid = controller.get_info("process/pid") connections = get_connections(resolver=resolver, process_pid=pid,process_name='tor') t2 = time.time() policy = controller.get_exit_policy() for conn in connections: laddr, raddr = conn.local_address, conn.remote_address lport, rport = conn.local_port, conn.remote_port # ignore incoming connections # if (lport == ORPort and laddr == '5.9.158.75') or (lport == ORPort6 and laddr == '2a01:4f8:190:514a::2'): continue if (lport == DirPort and laddr == '5.9.158.75') or (lport == DirPort6 and laddr == '2a01:4f8:190:514a::2'): continue if raddr in relays: if rport in relays[raddr]: continue if not policy.can_exit_to(raddr, rport): continue # store the connections itself instead just counting them here # b/c we have to calculate the diff of 2 sets later # Curr.setdefault(rport, []).append(str(lport)+':'+raddr) if first == 1: Prev = Curr.copy() dt = t2-t1 os.system('clear') print (" port # opened closed max ( %s:%s, %i conns %.2f sec ) " % (resolver, ctrlport, len(connections), dt)) lines = 0; ports = set(list(Curr.keys()) + list(Prev.keys()) + list(MaxAll.keys())) for port in sorted(ports): if port in Prev: p = set(Prev[port]) else: p = set({}) if port in Curr: c = set(Curr[port]) else: c = set({}) n_curr = len(c) n_opened = len(c-p) n_closed = len(p-c) MaxAll.setdefault(port, 0) MaxOpened.setdefault(port, 0) MaxClosed.setdefault(port, 0) if first == 0: if MaxAll[port] < n_curr: MaxAll[port] = n_curr if MaxOpened[port] < n_opened: MaxOpened[port] = n_opened if MaxClosed[port] < n_closed: MaxClosed[port] = n_closed stri = " %5i %5i %6i %6i %6i %6i %6i (%s)" % (port, n_curr, n_opened, n_closed, MaxAll[port], MaxOpened[port], MaxClosed[port], port_usage(port)) print (stri.replace(' 0', ' ')) lines += 1 if lines % 5 == 0: print first = 0 except KeyboardInterrupt: break