def checkOptions(self): """ Call processTest and processOptions methods of each NetTestCase """ test_classes = set([]) for test_class, test_method in self.testCases: test_classes.add(test_class) for klass in test_classes: options = self.usageOptions() options.parseOptions(self.options) if options: klass.localOptions = options test_instance = klass() if test_instance.requiresRoot: checkForRoot() test_instance._checkRequiredOptions() test_instance._checkValidOptions() inputs = test_instance.getInputProcessor() if not inputs: inputs = [None] klass.inputs = inputs
def startSniffing(self): """ Start sniffing with Scapy. Exits if required privileges (root) are not available. """ from ooni.utils.txscapy import ScapyFactory, ScapySniffer try: checkForRoot() except errors.InsufficientPrivileges: print "[!] Includepcap options requires root priviledges to run" print " you should run ooniprobe as root or disable the options in ooniprobe.conf" reactor.stop() sys.exit(1) print "Starting sniffer" config.scapyFactory = ScapyFactory(config.advanced.interface) if os.path.exists(config.reports.pcap): print "Report PCAP already exists with filename %s" % config.reports.pcap print "Renaming files with such name..." pushFilenameStack(config.reports.pcap) if self.sniffer: config.scapyFactory.unRegisterProtocol(self.sniffer) self.sniffer = ScapySniffer(config.reports.pcap) config.scapyFactory.registerProtocol(self.sniffer)
def runWithDirector(): """ Instance the director, parse command line options and start an ooniprobe test! """ global_options = parseOptions() config.global_options = global_options config.set_paths() config.read_config_file() log.start(global_options['logfile']) if config.privacy.includepcap: try: checkForRoot() except errors.InsufficientPrivileges: log.err("Insufficient Privileges to capture packets." " See ooniprobe.conf privacy.includepcap") sys.exit(2) # contains (test_cases, options, cmd_line_options) test_list = [] director = Director() d = director.start() if global_options['list']: print "# Installed nettests" for net_test_id, net_test in director.netTests.items(): print "* %s (%s/%s)" % (net_test['name'], net_test['category'], net_test['id']) print " %s" % net_test['description'] sys.exit(0) #XXX: This should mean no bouncer either! if global_options['no-collector']: log.msg("Not reporting using a collector") collector = global_options['collector'] = None global_options['bouncer'] = None deck = Deck() deck.bouncer = global_options['bouncer'] try: if global_options['testdeck']: deck.loadDeck(global_options['testdeck']) else: log.debug("No test deck detected") test_file = nettest_to_path(global_options['test_file']) net_test_loader = NetTestLoader(global_options['subargs'], test_file=test_file) deck.insert(net_test_loader) except errors.MissingRequiredOption, option_name: log.err('Missing required option: "%s"' % option_name) print net_test_loader.usageOptions().getUsage() sys.exit(2)
def setUp(self): super(TestRunDirector, self).setUp() if not is_internet_connected(): self.skipTest("You must be connected to the internet to run this test") try: checkForRoot() except InsufficientPrivileges: self.skipTest("You must be root to run this test") config.tor.socks_port = 9050 config.tor.control_port = None self.filenames = ['example-input.txt'] with open('example-input.txt', 'w+') as f: f.write('http://torproject.org/\n') f.write('http://bridges.torproject.org/\n') f.write('http://blog.torproject.org/\n')
def runWithDirector(): """ Instance the director, parse command line options and start an ooniprobe test! """ global_options = parseOptions() config.global_options = global_options config.set_paths() config.read_config_file() log.start(global_options["logfile"]) if config.privacy.includepcap: try: checkForRoot() except errors.InsufficientPrivileges: log.err("Insufficient Privileges to capture packets." " See ooniprobe.conf privacy.includepcap") sys.exit(2) # contains (test_cases, options, cmd_line_options) test_list = [] director = Director() d = director.start() # XXX: This should mean no bouncer either! if global_options["no-collector"]: log.msg("Not reporting using a collector") collector = global_options["collector"] = None global_options["bouncer"] = None deck = Deck() deck.bouncer = global_options["bouncer"] try: if global_options["testdeck"]: deck.loadDeck(global_options["testdeck"]) else: log.debug("No test deck detected") test_file = nettest_to_path(global_options["test_file"]) net_test_loader = NetTestLoader( global_options["subargs"], test_file=test_file, global_options=global_options ) deck.insert(net_test_loader) except errors.MissingRequiredOption, option_name: log.err('Missing required option: "%s"' % option_name) print net_test_loader.usageOptions().getUsage() sys.exit(2)
def runWithDirector(): """ Instance the director, parse command line options and start an ooniprobe test! """ global_options = parseOptions() config.global_options = global_options config.set_paths() config.read_config_file() log.start(global_options["logfile"]) if config.privacy.includepcap: try: checkForRoot() except errors.InsufficientPrivileges: log.err("Insufficient Privileges to capture packets." " See ooniprobe.conf privacy.includepcap") sys.exit(2) # contains (test_cases, options, cmd_line_options) test_list = [] if global_options["no-collector"]: log.msg("Not reporting using a collector") global_options["collector"] = None if global_options["testdeck"]: test_deck = yaml.safe_load(open(global_options["testdeck"])) for test in test_deck: test_list.append(NetTestLoader(test["options"]["subargs"], test_file=test["options"]["test_file"])) else: log.debug("No test deck detected") test_list.append(NetTestLoader(global_options["subargs"], test_file=global_options["test_file"])) # check each test's usageOptions for net_test_loader in test_list: try: net_test_loader.checkOptions() except MissingRequiredOption, option_name: log.err('Missing required option: "%s"' % option_name) print net_test_loader.usageOptions().getUsage() sys.exit(2) except usage.UsageError, e: log.err(e) print net_test_loader.usageOptions().getUsage() sys.exit(2)
def checkOptions(self): """ Call processTest and processOptions methods of each NetTestCase """ for klass in self.testClasses: options = self.usageOptions() options.parseOptions(self.options) if options: klass.localOptions = options test_instance = klass() if test_instance.requiresRoot: checkForRoot() if test_instance.requiresTor: self.requiresTor = True test_instance.requirements() test_instance._checkRequiredOptions() test_instance._checkValidOptions()
def checkOptions(self): """ Call processTest and processOptions methods of each NetTestCase """ for klass in self.testClasses: options = self.usageOptions() try: options.parseOptions(self.options) except usage.UsageError: tb = sys.exc_info()[2] raise e.OONIUsageError(self), None, tb if options: klass.localOptions = options test_instance = klass() if test_instance.requiresRoot: checkForRoot() if test_instance.requiresTor: self.requiresTor = True test_instance.requirements() test_instance._checkRequiredOptions() test_instance._checkValidOptions()
try: log.debug("processing options") tmp_test_case_object = obj() tmp_test_case_object._checkRequiredOptions() except usage.UsageError, e: test_name = tmp_test_case_object.name log.err("There was an error in running %s!" % test_name) log.err("%s" % e) options.opt_help() raise usage.UsageError("Error in parsing command line args for %s" % test_name) if obj.requiresRoot: try: checkForRoot() except NotRootError: log.err("%s requires root to run" % obj.name) sys.exit(1) return obj def isTestCase(obj): try: return issubclass(obj, NetTestCase) except TypeError: return False def findTestClassesFromFile(cmd_line_options):
def askTraceroute(self): """ Perform a UDP traceroute to determine the probes IP address. """ checkForRoot() raise NotImplemented
def runWithDirector(logging=True, start_tor=True, check_incoherences=True): """ Instance the director, parse command line options and start an ooniprobe test! """ global_options = parseOptions() config.global_options = global_options config.set_paths() config.initialize_ooni_home() try: config.read_config_file(check_incoherences=check_incoherences) except errors.ConfigFileIncoherent: sys.exit(6) if global_options['verbose']: config.advanced.debug = True if not start_tor: config.advanced.start_tor = False if logging: log.start(global_options['logfile']) if config.privacy.includepcap: try: checkForRoot() from ooni.utils.txscapy import ScapyFactory config.scapyFactory = ScapyFactory(config.advanced.interface) except errors.InsufficientPrivileges: log.err("Insufficient Privileges to capture packets." " See ooniprobe.conf privacy.includepcap") sys.exit(2) director = Director() if global_options['list']: print "# Installed nettests" for net_test_id, net_test in director.getNetTests().items(): print "* %s (%s/%s)" % (net_test['name'], net_test['category'], net_test['id']) print " %s" % net_test['description'] sys.exit(0) elif global_options['printdeck']: del global_options['printdeck'] print "# Copy and paste the lines below into a test deck to run the specified test with the specified arguments" print yaml.safe_dump([{'options': global_options}]).strip() sys.exit(0) if global_options.get('annotations') is not None: annotations = {} for annotation in global_options["annotations"].split(","): pair = annotation.split(":") if len(pair) == 2: key = pair[0].strip() value = pair[1].strip() annotations[key] = value else: log.err("Invalid annotation: %s" % annotation) sys.exit(1) global_options["annotations"] = annotations if global_options['no-collector']: log.msg("Not reporting using a collector") global_options['collector'] = None start_tor = False else: start_tor = True deck = Deck(no_collector=global_options['no-collector']) deck.bouncer = global_options['bouncer'] if global_options['collector']: start_tor |= True try: if global_options['testdeck']: deck.loadDeck(global_options['testdeck']) else: log.debug("No test deck detected") test_file = nettest_to_path(global_options['test_file'], True) net_test_loader = NetTestLoader(global_options['subargs'], test_file=test_file) if global_options['collector']: net_test_loader.collector = global_options['collector'] deck.insert(net_test_loader) except errors.MissingRequiredOption as option_name: log.err('Missing required option: "%s"' % option_name) incomplete_net_test_loader = option_name.net_test_loader print incomplete_net_test_loader.usageOptions().getUsage() sys.exit(2) except errors.NetTestNotFound as path: log.err('Requested NetTest file not found (%s)' % path) sys.exit(3) except errors.OONIUsageError as e: log.err(e) print e.net_test_loader.usageOptions().getUsage() sys.exit(4) except Exception as e: if config.advanced.debug: log.exception(e) log.err(e) sys.exit(5) start_tor |= deck.requiresTor d = director.start(start_tor=start_tor, check_incoherences=check_incoherences) def setup_nettest(_): try: return deck.setup() except errors.UnableToLoadDeckInput as error: return defer.failure.Failure(error) def director_startup_handled_failures(failure): log.err("Could not start the director") failure.trap(errors.TorNotRunning, errors.InvalidOONIBCollectorAddress, errors.UnableToLoadDeckInput, errors.CouldNotFindTestHelper, errors.CouldNotFindTestCollector, errors.ProbeIPUnknown, errors.InvalidInputFile, errors.ConfigFileIncoherent) if isinstance(failure.value, errors.TorNotRunning): log.err("Tor does not appear to be running") log.err("Reporting with the collector %s is not possible" % global_options['collector']) log.msg( "Try with a different collector or disable collector reporting with -n") elif isinstance(failure.value, errors.InvalidOONIBCollectorAddress): log.err("Invalid format for oonib collector address.") log.msg( "Should be in the format http://<collector_address>:<port>") log.msg("for example: ooniprobe -c httpo://nkvphnp3p6agi5qq.onion") elif isinstance(failure.value, errors.UnableToLoadDeckInput): log.err("Unable to fetch the required inputs for the test deck.") log.msg( "Please file a ticket on our issue tracker: https://github.com/thetorproject/ooni-probe/issues") elif isinstance(failure.value, errors.CouldNotFindTestHelper): log.err("Unable to obtain the required test helpers.") log.msg( "Try with a different bouncer or check that Tor is running properly.") elif isinstance(failure.value, errors.CouldNotFindTestCollector): log.err("Could not find a valid collector.") log.msg( "Try with a different bouncer, specify a collector with -c or disable reporting to a collector with -n.") elif isinstance(failure.value, errors.ProbeIPUnknown): log.err("Failed to lookup probe IP address.") log.msg("Check your internet connection.") elif isinstance(failure.value, errors.InvalidInputFile): log.err("Invalid input file \"%s\"" % failure.value) elif isinstance(failure.value, errors.ConfigFileIncoherent): log.err("Incoherent config file") if config.advanced.debug: log.exception(failure) def director_startup_other_failures(failure): log.err("An unhandled exception occurred while starting the director!") log.exception(failure) # Wait until director has started up (including bootstrapping Tor) # before adding tests def post_director_start(_): for net_test_loader in deck.netTestLoaders: # Decks can specify different collectors # for each net test, so that each NetTest # may be paired with a test_helper and its collector # However, a user can override this behavior by # specifying a collector from the command-line (-c). # If a collector is not specified in the deck, or the # deck is a singleton, the default collector set in # ooniprobe.conf will be used collector = None if not global_options['no-collector']: if global_options['collector']: collector = global_options['collector'] elif 'collector' in config.reports \ and config.reports['collector']: collector = config.reports['collector'] elif net_test_loader.collector: collector = net_test_loader.collector if collector and collector.startswith('httpo:') \ and (not (config.tor_state or config.tor.socks_port)): raise errors.TorNotRunning test_details = net_test_loader.testDetails test_details['annotations'] = global_options['annotations'] director.startNetTest(net_test_loader, global_options['reportfile'], collector) return director.allTestsDone def start(): d.addCallback(setup_nettest) d.addCallback(post_director_start) d.addErrback(director_startup_handled_failures) d.addErrback(director_startup_other_failures) return d return start()
def runWithDirector(logging=True, start_tor=True): """ Instance the director, parse command line options and start an ooniprobe test! """ global_options = parseOptions() config.global_options = global_options config.set_paths() config.read_config_file() if not start_tor: config.advanced.start_tor = False if logging: log.start(global_options['logfile']) if config.privacy.includepcap: try: checkForRoot() except errors.InsufficientPrivileges: log.err("Insufficient Privileges to capture packets." " See ooniprobe.conf privacy.includepcap") sys.exit(2) director = Director() if global_options['list']: print "# Installed nettests" for net_test_id, net_test in director.getNetTests().items(): print "* %s (%s/%s)" % (net_test['name'], net_test['category'], net_test['id']) print " %s" % net_test['description'] sys.exit(0) elif global_options['printdeck']: del global_options['printdeck'] print "# Copy and paste the lines below into a test deck to run the specified test with the specified arguments" print yaml.safe_dump([{'options': global_options}]).strip() sys.exit(0) #XXX: This should mean no bouncer either! if global_options['no-collector']: log.msg("Not reporting using a collector") collector = global_options['collector'] = None global_options['bouncer'] = None deck = Deck() deck.bouncer = global_options['bouncer'] start_tor = deck.requiresTor if global_options['bouncer']: start_tor = True if global_options['collector']: start_tor = True try: if global_options['testdeck']: deck.loadDeck(global_options['testdeck']) else: log.debug("No test deck detected") test_file = nettest_to_path(global_options['test_file']) net_test_loader = NetTestLoader(global_options['subargs'], test_file=test_file) deck.insert(net_test_loader) except errors.MissingRequiredOption, option_name: log.err('Missing required option: "%s"' % option_name) print net_test_loader.usageOptions().getUsage() sys.exit(2)
pcap_filename = yamloo_filename + ".pcap" if os.path.exists(yamloo_filename): print "Report already exists with filename %s" % yamloo_filename print "Renaming it to %s" % yamloo_filename + '.old' os.rename(yamloo_filename, yamloo_filename + '.old') if os.path.exists(pcap_filename): print "Report PCAP already exists with filename %s" % pcap_filename print "Renaming it to %s" % pcap_filename + '.old' os.rename(pcap_filename, pcap_filename + '.old') classes = runner.findTestClassesFromConfig(cmd_line_options) test_cases, options = runner.loadTestsAndOptions(classes, cmd_line_options) if config.privacy.includepcap: try: checkForRoot() except NotRootError: print "[!] Includepcap options requires root priviledges to run" print " you should run ooniprobe as root or disable the options in ooniprobe.conf" sys.exit(1) print "Starting sniffer" net.capturePackets(pcap_filename) log.start(cmd_line_options['logfile']) tests_d = runner.runTestCases(test_cases, options, cmd_line_options, yamloo_filename) tests_d.addBoth(testsEnded) reactor.run()
def processTest(obj, cmd_line_options): """ Process the parameters and :class:`twisted.python.usage.Options` of a :class:`ooni.nettest.Nettest`. :param obj: An uninstantiated old test, which should be a subclass of :class:`ooni.plugoo.tests.OONITest`. :param cmd_line_options: A configured and instantiated :class:`twisted.python.usage.Options` class. """ input_file = obj.inputFile if obj.requiresRoot: try: checkForRoot() except NotRootError: log.err("%s requires root to run" % obj.name) sys.exit(1) if obj.optParameters or input_file \ or obj.usageOptions or obj.optFlags: if not obj.optParameters: obj.optParameters = [] if input_file: obj.optParameters.append(input_file) if obj.usageOptions: if input_file: obj.usageOptions.optParameters.append(input_file) options = obj.usageOptions() elif obj.optParameters: log.debug("Got optParameters") class Options(usage.Options): optParameters = obj.optParameters if obj.optFlags: log.debug("Got optFlags") optFlags = obj.optFlags options = Options() if options: options.parseOptions(cmd_line_options['subArgs']) obj.localOptions = options if input_file and options: log.debug("Got input file") obj.inputFile = options[input_file[0]] try: log.debug("processing options") tmp_test_case_object = obj() tmp_test_case_object._processOptions(options) except usage.UsageError, e: test_name = tmp_test_case_object.name print "There was an error in running %s!" % test_name print "%s" % e options.opt_help() raise usage.UsageError("Error in parsing command line args for %s" % test_name)