def start_tor():
        config = txtorcon.TorConfig()
        config.DataDirectory = tor_data

        def get_random_tor_ports():
            d2 = txtorcon.util.available_tcp_port(reactor)
            d2.addCallback(lambda port: config.__setattr__('SocksPort', port))
            d2.addCallback(lambda _: txtorcon.util.available_tcp_port(reactor))
            d2.addCallback(
                lambda port: config.__setattr__('ControlPort', port))
            return d2

        def launch_and_get_protocol(ignore):
            d2 = txtorcon.launch_tor(config, reactor, stdout=sys.stdout)
            d2.addCallback(
                lambda tpp: txtorcon.TorState(tpp.tor_protocol).post_bootstrap)
            d2.addCallback(lambda state: state.protocol)
            return d2

        d3 = get_random_tor_ports().addCallback(launch_and_get_protocol)

        def change_torrc(result):
            config.UseEntryGuards = 0
            d2 = config.save()
            d2.addCallback(lambda ign: result)
            return d2

        d3.addCallback(change_torrc)
        d3.addCallback(lambda protocol: TorState.from_protocol(protocol))
        return d3
Exemple #2
0
def main(progress_updates=updates, data_directory=None):
    """
    Start logging, apaf services, and tor.

    :param progress_updates: a callback fired during tor's bootstrap.
    :ret: a twisted Deferred object for setting up callbacks in case of
          sucess/errors.
    """
    ## start the logger. ##
    log.startLogging(sys.stdout)
    torconfig = txtorcon.TorConfig()

    ## start apaf. ##
    panel.start_panel(torconfig)
    core.start_services(torconfig)

    torconfig.HiddenServices = [x.hs for x in apaf.hiddenservices]
    torconfig.save()

    ## start tor. ##
    try:
        return txtorcon.launch_tor(
            torconfig,
            reactor,
            progress_updates=progress_updates,
            data_directory=data_directory,
            tor_binary=config.tor_binary,
        )
    except OSError as exc:
        print >> sys.stderr, "Failing to launch tor executable (%s)" % ecx
        sys.exit(1)  # return error status.
Exemple #3
0
    def _connect(self, reactor, update_status):
        # create a new Tor
        config = self.config = txtorcon.TorConfig()
        if self._data_directory:
            # The default is for launch_tor to create a tempdir itself, and
            # delete it when done. We only need to set a DataDirectory if we
            # want it to be persistent. This saves some startup time, because
            # we cache the descriptors from last time. On one of my hosts,
            # this reduces connect from 20s to 15s.
            if not os.path.exists(self._data_directory):
                # tor will mkdir this, but txtorcon wants to chdir to it
                # before spawning the tor process, so (for now) we need to
                # mkdir it ourselves. TODO: txtorcon should take
                # responsibility for this.
                os.mkdir(self._data_directory)
            config.DataDirectory = self._data_directory

        #config.ControlPort = allocate_tcp_port() # defaults to 9052
        config.SocksPort = allocate_tcp_port()
        socks_desc = "tcp:127.0.0.1:%d" % config.SocksPort
        self._socks_desc = socks_desc # stash for tests
        socks_endpoint = clientFromString(reactor, socks_desc)

        with add_context(update_status, "launching Tor"):
            tpp = yield txtorcon.launch_tor(config, reactor,
                                            tor_binary=self._tor_binary)
        #print "launched"
        # gives a TorProcessProtocol with .tor_protocol
        self._tor_protocol = tpp.tor_protocol
        returnValue(socks_endpoint)
Exemple #4
0
def main(reactor):
    config = txtorcon.TorConfig()
    config.ORPort = 0
    config.SocksPort = 9998
    try:
        os.mkdir('tor-data')
    except OSError:
        pass
    config.DataDirectory = './tor-data'

    try:
        process = yield txtorcon.launch_tor(
            config, reactor, progress_updates=progress
        )
    except Exception as e:
        print("Error launching tor:", e)
        return

    protocol = process.tor_protocol
    print("Tor has launched.")
    print("Protocol:", protocol)
    info = yield protocol.get_info('traffic/read', 'traffic/written')
    print(info)

    # explicitly stop tor by either disconnecting our protocol or the
    # Twisted IProcessProtocol (or just exit our program)
    print("Killing our tor, PID={pid}".format(pid=process.transport.pid))
    yield process.transport.signalProcess('TERM')
Exemple #5
0
def main(reactor):
    config = txtorcon.TorConfig()
    config.OrPort = 1234
    config.SocksPort = 9999
    try:
        yield txtorcon.launch_tor(config, reactor, stdout=stdout)

    except RuntimeError as e:
        print "Error:", e
        return

    proto = config.protocol
    print "Connected to Tor version", proto.version

    state = yield txtorcon.TorState.from_protocol(proto)
    print "This Tor has PID", state.tor_pid
    print "This Tor has the following %d Circuits:" % len(state.circuits)
    for c in state.circuits.values():
        print c

    print "Changing our config (SOCKSPort=9876)"
    config.SOCKSPort = 9876
    yield config.save()

    print "Querying to see it changed:"
    socksport = yield proto.get_conf("SOCKSPort")
    print "SOCKSPort", socksport
    def _create_my_own_tor(self):
        _start_launch = self._timing.add_event("launch tor")
        start = time.time()
        config = self.config = txtorcon.TorConfig()
        if 0:
            # The default is for launch_tor to create a tempdir itself, and
            # delete it when done. We only need to set a DataDirectory if we
            # want it to be persistent.
            import tempfile
            datadir = tempfile.mkdtemp()
            config.DataDirectory = datadir

        #config.ControlPort = allocate_tcp_port() # defaults to 9052
        #print("setting config.ControlPort to", config.ControlPort)
        config.SocksPort = allocate_tcp_port()
        self._tor_socks_port = config.SocksPort
        print("setting config.SocksPort to", config.SocksPort)

        tpp = yield txtorcon.launch_tor(config, self._reactor,
                                        #tor_binary=
                                        )
        # gives a TorProcessProtocol with .tor_protocol
        self._tor_protocol = tpp.tor_protocol
        print("tp:", self._tor_protocol)
        print("elapsed:", time.time() - start)
        self._timing.finish_event(_start_launch)
        returnValue(True)
Exemple #7
0
    def run(self, options, mainoptions, proto):
        "ICarmlCommand API"

        config = txtorcon.TorConfig(proto)
        yield config.post_bootstrap

        socks = yield proto.get_info('net/listeners/socks')
        socks = socks['net/listeners/socks']
        socks_host, socks_port = socks.split(':')

        args = options['service'].split(':')
        onion = args[1]
        cookie = args[2].split('=')[1]
        ep = txtorcon.TorClientEndpoint(onion,
                                        80,
                                        socks_hostname=socks_host,
                                        socks_port=int(socks_port))

        auth = '%s %s' % (onion, cookie)
        if auth not in config.HidServAuth:
            config.HidServAuth.append(auth)
        yield config.save()

        agent = Agent.usingEndpointFactory(reactor, EndpointFactory(ep))
        res = yield agent.request('GET', 'http://%s/' % onion)
        print("Response:", res.code)
        print("bytes:", res.length)
        data = yield receive(res)
        print(data)
Exemple #8
0
def setup_hidden_service(tor_process_protocol):
    config = txtorcon.TorConfig(tor_process_protocol.tor_protocol)
    public_port = 80
    hs_endpoint = txtorcon.TCPHiddenServiceEndpoint(reactor, config,
                                                    public_port)

    ## the important thing here is that "site" implements
    ## IProtocolFactory -- this could be any service at all,
    ## obviously.
    hs_endpoint.listen(site).addCallback(setup_complete).addErrback(setup_failed)
Exemple #9
0
def get_bridge_config(addresses, ports=None):
    #XXX: how we do pluggable transports? which ports they get?
    torconfig = txtorcon.TorConfig()
    for address in addresses:
        if not ports: ports = get_port_list(address, [9001, 443, 80])
        torconfig.OrPort = ["%s:%s" % (address, str(port)) for port in ports]
    torconfig.ControlPort = get_available_port('localhost')
    torconfig.BridgeRelay = 1
    torconfig.ExitPolicy = "reject *:*"
    torconfig.SocksPort = 0
    return torconfig
Exemple #10
0
    def run_tor(self):
        def progress(percent, tag, summary):
            ticks = int((percent/100.0) * 10.0)
            prog = (ticks * '#') + ((10 - ticks) * '.')
            print '%s %s' % (prog, summary)

        config = txtorcon.TorConfig()
        config.SocksPort = self.conf.tor.socks_port
        config.ControlPort = self.conf.tor.control_port
        d = txtorcon.launch_tor(config, reactor, progress_updates=progress)
        return d
Exemple #11
0
    def setUp(self):
        """
        Set up an asyncronous get trasport.
        """
        torconfig = txtorcon.TorConfig()
        self.service = panel.PanelService()

        # for simplicity, disable xrcf cookies
        self.service.factory.settings['xsrf_cookies'] = False

        add_service(torconfig, self.service, 6660)
        self.addCleanup(self.service.tcp.loseConnection)
Exemple #12
0
    def test_full_tor_connection(self):
        config = txtorcon.TorConfig()
        config.ControlPort = net.randomFreePort()
        config.SocksPort = net.randomFreePort()
        config.DataDirectory = self.tor_datadir
        log.msg("Connecting to tor %s" % (onion.tor_details['version']))

        config.log = ['notice stdout', 'notice file %s' % self.tor_logfile]
        config.save()

        def updates(prog, tag, summary):
            log.msg("Progress is at: %s%%" % (prog))
            self.report['tor_progress'] = int(prog)
            self.report['tor_progress_tag'] = tag
            self.report['tor_progress_summary'] = summary

        d = txtorcon.launch_tor(config,
                                reactor,
                                tor_binary=onion.find_tor_binary(),
                                timeout=self.timeout,
                                progress_updates=updates)

        @d.addCallback
        def setup_complete(proto):
            try:
                proto.transport.signalProcess('TERM')
            except error.ProcessExitedAlready:
                proto.transport.loseConnection()
            log.msg("Successfully connected to Tor")
            self.report['success'] = True

        @d.addErrback
        def setup_failed(failure):
            log.msg("Failed to connect to Tor")
            self.report['success'] = False
            self.report['error'] = 'timeout-reached'
            return

        @d.addCallback
        def write_log(_):
            with open(self.tor_logfile) as f:
                self.report['tor_log'] = f.read()
            os.remove(self.tor_logfile)
            try:
                shutil.rmtree(self.tor_datadir)
            except:
                pass

        return d
Exemple #13
0
def get_bridge_configs(allocatable):
    """
    produces a set of bridge configs, distributing the addresses
    round-robin style
    """
    #XXX: how we do obfsproxy?
    #XXX: how we do make sure we listen on ports 443, 80, etc??
    # round-robin allocate address:port to bridges
    #XXX: might want to try and keep 1 ip per bridge, rather than
    # round robin ip:port across several bridges?
    #XXX: if we come up with several different allocator types, there
    # should be a more general way to express the concept of an allocator
    configs = []
    for bridge in xrange(hc.NUM_BRIDGES):
        configs.append(txtorcon.TorConfig())

    #XXX: ghetto, need to fix something with _ListWrapper in txtorcon
    fuckthis = dict()
    # set up the defaults
    for config in configs:
        config.ControlPort = get_available_port('127.0.0.1')
        config.BridgeRelay = 1
        config.ExitPolicy = "reject *:*"
        config.SocksPort = 0
        #XXX: ok great, this is f*****g broken.
        # why the f**k can't append be called?
        # f**k f**k f**k
        config.OrPort = []
        fuckthis[config] = []

    # allocate those ports!
    i = 0
    for address, ports in allocatable:
        for port in ports:
            if isinstance(address, IPv6Address):
                orport = "[%s]:%s" % (address, port)
            else:
                orport = "%s:%s" % (address, port)
            config = configs[i % len(configs)]
            fuckthis[config].append(orport)
            i += 1
    #XXX: f*****g ghetto hack
    for config in configs:
        config.OrPort = fuckthis[config]
    return configs
Exemple #14
0
def _launch_tor(reactor, tor_executable, private_dir, txtorcon):
    # TODO: handle default tor-executable
    # TODO: it might be a good idea to find exactly which Tor we used,
    # and record it's absolute path into tahoe.cfg . This would protect
    # us against one Tor being on $PATH at create-node time, but then a
    # different Tor being present at node startup. OTOH, maybe we don't
    # need to worry about it.
    tor_config = txtorcon.TorConfig()
    tor_config.DataDirectory = data_directory(private_dir)

    if True:  # unix-domain control socket
        tor_config.ControlPort = "unix:" + os.path.join(
            private_dir, "tor.control")
        tor_control_endpoint_desc = tor_config.ControlPort
    else:
        # we allocate a new TCP control port each time
        tor_config.ControlPort = allocate_tcp_port()
        tor_control_endpoint_desc = "tcp:127.0.0.1:%d" % tor_config.ControlPort

    tor_config.SOCKSPort = allocate_tcp_port()

    tpp = yield txtorcon.launch_tor(
        tor_config,
        reactor,
        tor_binary=tor_executable,
        # can be useful when debugging; mirror Tor's output to ours
        # stdout=sys.stdout,
        # stderr=sys.stderr,
    )

    # now tor is launched and ready to be spoken to
    # as a side effect, we've got an ITorControlProtocol ready to go
    tor_control_proto = tpp.tor_protocol

    # How/when to shut down the new process? for normal usage, the child
    # tor will exit when it notices its parent (us) quit. Unit tests will
    # mock out txtorcon.launch_tor(), so there will never be a real Tor
    # process. So I guess we don't need to track the process.

    # If we do want to do anything with it, we can call tpp.quit()
    # (because it's a TorProcessProtocol) which returns a Deferred
    # that fires when Tor has actually exited.

    returnValue((tor_control_endpoint_desc, tor_control_proto))
Exemple #15
0
def main(progress_updates=updates,
         data_directory=None,
         connection_creator=None):
    """
    Start logging, apaf services, and tor.

    :param progress_updates: a callback fired during tor's bootstrap.
    :ret: a twisted Deferred object for setting up callbacks in case of
          sucess/errors.


    XXX: for versions of txtorcon greater that 0.6 it is possible to set the
    data_directory argument directly in the toconfig, and removing from
    launch_tor. See issue #15 of txtorcon and #40 of APAF.
    """
    ## start the logger. ##
    log.startLogging(sys.stdout)
    torconfig = txtorcon.TorConfig()
    if data_directory is not None:
        config.DataDirectory = data_directory

    ## start apaf. ##
    panel.start_panel(torconfig)
    core.start_services(torconfig)

    # torconfig.DataDirectory = data_directory
    torconfig.HiddenServices = [x.hs for x in apaf.hiddenservices]
    torconfig.save()

    ## start tor. ##
    try:
        return txtorcon.launch_tor(torconfig,
                                   reactor,
                                   progress_updates=progress_updates,
                                   tor_binary=config.tor_binary,
                                   connection_creator=connection_creator)
    except OSError as exc:
        print >> sys.stderr, "Failing to launch tor executable (%s)" % ecx
        sys.exit(1)  # return error status.
Exemple #16
0
def main():
    """
    Start the apaf.
    """
    ## start the logger. ##
    log.startLogging(sys.stdout)
    torconfig = txtorcon.TorConfig()

    ## start apaf. ##
    panel.start_panel(torconfig)
    core.start_services(torconfig)

    torconfig.HiddenServices = [x.hs for x in apaf.hiddenservices]
    torconfig.save()

    start_tor(torconfig)

    ##  Start the reactor. ##
    #if config.platform == 'darwin':
    #    reactor.interleave(AppHelper.callAfter)
    #else:
    reactor.run()
Exemple #17
0
def main(reactor, tor_binary):
    config = txtorcon.TorConfig()
    config.ORPort = 0
    config.SOCKSPort = 0
    config.Tor2WebMode = 1
    # leaving ControlPort unset; launch_tor will choose one

    print("Launching tor...", tor_binary)
    try:
        yield txtorcon.launch_tor(config,
                                  reactor,
                                  tor_binary=tor_binary,
                                  stdout=sys.stdout)
        print("success! We support Tor2Web mode")

    except RuntimeError as e:
        print("There was a problem:", str(e))
        print("We do NOT support Tor2Web mode")
        return

    print("quitting in 5 seconds")
    reactor.callLater(5, lambda: reactor.stop())
    yield Deferred()  # wait forever because we never .callback()
Exemple #18
0
def start_mock_apaf(tor, *services):
    """
    Start the apaf for testing purposes.
    XXX. how to handle cleanup? Currently the reactor is left unclean
    :ret: None.
    """
    torconfig = txtorcon.TorConfig()

    ## start apaf. ##
    panel.start_panel(torconfig)

    for service in services:
            service = imp.load_module(
                      service, *imp.find_module(service, [config.services_dir])
                      ).ServiceDescriptor
    torconfig.HiddenServices = [x.hs for x in apaf.hiddenservices]
    torconfig.save()


    if tor:
        txtorcon.launch_tor(torconfig, reactor,
                            progress_updates=progress_updates,
                            tor_binary=config.tor_binary)
hs_temp = tempfile.mkdtemp(prefix='torhiddenservice')

## register something to clean up our tempdir
reactor.addSystemEventTrigger(
    'before', 'shutdown',
    functools.partial(txtorcon.util.delete_file_or_tree, hs_temp))

## configure the hidden service we want.
## obviously, we'd want a more-persistent place to keep the hidden
## service directory for a "real" setup. If the directory is empty at
## startup as here, Tor creates new keys etcetera (which IS the .onion
## address). That is, every time you run this script you get a new
## hidden service URI, which is probably not what you want.
## The launch_tor method adds other needed config directives to give
## us a minimal config.
config = txtorcon.TorConfig()
config.HiddenServices = [
    txtorcon.HiddenService(
        config, hs_temp, [str(hs_public_port) + " 127.0.0.1:" + str(hs_port)])
]
config.save()

## next we set up our service to listen on hs_port which is forwarded
## (via the HiddenService options) from the hidden service address on
## port hs_public_port
site = server.Site(Simple())
hs_endpoint = TCP4ServerEndpoint(reactor, hs_port)
hs_endpoint.listen(site)

## we've got our Twisted service listening locally and our options
## ready to go, so we now launch Tor. Once it's done (see above
    def test_full_tor_connection(self):
        config = txtorcon.TorConfig()
        config.ControlPort = random.randint(2**14, 2**16)
        config.SocksPort = random.randint(2**14, 2**16)
        log.msg("Connecting to %s with tor %s" %
                (self.bridge, onion.tor_details['version']))

        transport_name = onion.transport_name(self.bridge)

        if transport_name:
            self.report['transport_name'] = transport_name

        if transport_name and transport_name == 'fte' and self.fteproxy_bin:
            config.ClientTransportPlugin = "%s exec %s --managed" % (
                transport_name, self.fteproxy_bin)
            log.debug("Using fte from %s" % self.fteproxy_bin)
            self.report['bridge_address'] = self.bridge.split(' ')[1]
        elif transport_name and transport_name == 'fte'\
                and not self.fteproxy_bin:
            log.err("Unable to test bridge because fteproxy is not installed")
            self.report['error'] = 'missing-fteproxy'
            return
        elif transport_name and self.pyobfsproxy_bin:
            config.ClientTransportPlugin = (
                "%s exec %s --log-min-severity info "
                "--log-file %s managed") % (transport_name,
                                            self.pyobfsproxy_bin,
                                            self.obfsproxy_logfile)
            if onion.OBFSProxyVersion(
                    '0.2') > onion.obfsproxy_details['version']:
                log.err(
                    "The obfsproxy version you are using appears to be outdated."
                )
                self.report['error'] = 'old-obfsproxy'
                return
            log.debug("Using pyobfsproxy from %s" % self.pyobfsproxy_bin)
            self.report['bridge_address'] = self.bridge.split(' ')[1]
        elif transport_name and not self.pyobfsproxy_bin:
            log.err(
                "Unable to test bridge because pyobfsproxy is not installed")
            self.report['error'] = 'missing-pyobfsproxy'
            return
        else:
            self.report['bridge_address'] = self.bridge.split(' ')[0]

        if transport_name and transport_name == 'scramblesuit' and \
                onion.TorVersion('0.2.5.1') > onion.tor_details['version']:
            self.report['error'] = 'unsupported-tor-version'
            log.err("Unsupported Tor version.")
            return
        elif transport_name and \
                onion.TorVersion('0.2.4.1') > onion.tor_details['version']:
            self.report['error'] = 'unsupported-tor-version'
            log.err("Unsupported Tor version.")
            return

        config.Bridge = self.bridge
        config.UseBridges = 1
        config.log = ['notice stdout', 'notice file %s' % self.tor_logfile]
        config.save()

        def updates(prog, tag, summary):
            log.msg("%s: %s%%" % (self.bridge, prog))
            self.report['tor_progress'] = int(prog)
            self.report['tor_progress_tag'] = tag
            self.report['tor_progress_summary'] = summary

        d = txtorcon.launch_tor(config,
                                reactor,
                                timeout=self.timeout,
                                progress_updates=updates)

        @d.addCallback
        def setup_complete(proto):
            try:
                proto.transport.signalProcess('TERM')
            except error.ProcessExitedAlready:
                proto.transport.loseConnection()
            log.msg("Successfully connected to %s" % self.bridge)
            self.report['success'] = True

        @d.addErrback
        def setup_failed(failure):
            log.msg("Failed to connect to %s" % self.bridge)
            self.report['success'] = False
            self.report['error'] = 'timeout-reached'
            return

        @d.addCallback
        def write_log(_):
            with open(self.tor_logfile) as f:
                self.report['tor_log'] = f.read()
            os.remove(self.tor_logfile)
            with open(self.obfsproxy_logfile) as f:
                self.report['obfsproxy_log'] = f.read()
            os.remove(self.obfsproxy_logfile)

        return d
Exemple #21
0
def setup_failed(arg):
    print "SETUP FAILED", arg
    reactor.stop()


def setup_complete(port):
    print "I have set up a hidden service, advertised at:"
    print "http://%s:%d" % (port.onion_uri, port.onion_port)
    print "locally listening on", port.getHost()


def setup_hidden_service(tor_process_protocol):
    config = txtorcon.TorConfig(tor_process_protocol.tor_protocol)
    public_port = 80
    hs_endpoint = txtorcon.TCPHiddenServiceEndpoint(reactor, config,
                                                    public_port)

    ## the important thing here is that "site" implements
    ## IProtocolFactory -- this could be any service at all,
    ## obviously.
    hs_endpoint.listen(site).addCallback(setup_complete).addErrback(setup_failed)


def updates(prog, tag, summary):
    print "%d%%: %s" % (prog, summary)

d = txtorcon.launch_tor(txtorcon.TorConfig(), reactor, progress_updates=updates)
d.addCallback(setup_hidden_service)
d.addErrback(setup_failed)
reactor.run()
Exemple #22
0
    def startHTTPHiddenService(self,
                               serviceDir,
                               servicePort=8080,
                               hiddenserviceDir=None,
                               hiddenservicePort=80,
                               serviceInterface='127.0.0.1',
                               socksPort=9152,
                               orPort=9000):
        if is_valid_ipv4_address(
                serviceInterface) == False and is_valid_ipv6_address(
                    serviceInterface) == False:
            pluginException = PluginException(
                message=
                'The Service Interface is invalid. Try to use the default value without specify the parameter "serviceInterface" ',
                trace=
                "startHTTPHiddenService with args serviceDir=%s , servicePort=%s , hiddenserviceDir=%s , hiddenservicePort=%s , serviceInterface=%s , socksPort=%s , orPort=%s"
                % (serviceDir, str(servicePort), hiddenserviceDir,
                   str(hiddenservicePort), serviceInterface, str(socksPort),
                   str(orPort)),
                plugin="maliciousHiddenServicePlugin",
                method="startHTTPHiddenService")
            if self.runFromInterpreter:
                showTrace(pluginException)
                return
            else:
                print '[-] The Service Interface is invalid. Try to use the default value without specify the parameter "serviceInterface". '
                raise pluginException

        if is_valid_port(hiddenservicePort) == False:
            pluginException = PluginException(
                message='The hidden service port is invalid.',
                trace=
                "startHTTPHiddenService with args serviceDir=%s , servicePort=%s , hiddenserviceDir=%s , hiddenservicePort=%s , serviceInterface=%s , socksPort=%s , orPort=%s"
                % (serviceDir, str(servicePort), hiddenserviceDir,
                   str(hiddenservicePort), serviceInterface, str(socksPort),
                   str(orPort)),
                plugin="maliciousHiddenServicePlugin",
                method="startHTTPHiddenService")
            if self.runFromInterpreter:
                showTrace(pluginException)
                return
            else:
                print "[-] The hidden service port is invalid. "
                raise pluginException

        if is_valid_port(socksPort) == False:
            pluginException = PluginException(
                message='The socks port is invalid.',
                trace=
                "startHTTPHiddenService with args serviceDir=%s , servicePort=%s , hiddenserviceDir=%s , hiddenservicePort=%s , serviceInterface=%s , socksPort=%s , orPort=%s"
                % (serviceDir, str(servicePort), hiddenserviceDir,
                   str(hiddenservicePort), serviceInterface, str(socksPort),
                   str(orPort)),
                plugin="maliciousHiddenServicePlugin",
                method="startHTTPHiddenService")
            if self.runFromInterpreter:
                showTrace(pluginException)
                return
            else:
                print "[-] The socks port is invalid. "
                raise pluginException

        if is_valid_port(orPort) == False:
            pluginException = PluginException(
                message='The OR port is invalid.',
                trace=
                "startHTTPHiddenService with args serviceDir=%s , servicePort=%s , hiddenserviceDir=%s , hiddenservicePort=%s , serviceInterface=%s , socksPort=%s , orPort=%s"
                % (serviceDir, str(servicePort), hiddenserviceDir,
                   str(hiddenservicePort), serviceInterface, str(socksPort),
                   str(orPort)),
                plugin="maliciousHiddenServicePlugin",
                method="startHTTPHiddenService")
            if self.runFromInterpreter:
                showTrace(pluginException)
                return
            else:
                print "[-] The OR port is invalid. "
                raise pluginException

        if is_valid_port(servicePort) == False:
            pluginException = PluginException(
                message='The Service port is invalid.',
                trace=
                "startHTTPHiddenService with args serviceDir=%s , servicePort=%s , hiddenserviceDir=%s , hiddenservicePort=%s , serviceInterface=%s , socksPort=%s , orPort=%s"
                % (serviceDir, str(servicePort), hiddenserviceDir,
                   str(hiddenservicePort), serviceInterface, str(socksPort),
                   str(orPort)),
                plugin="maliciousHiddenServicePlugin",
                method="startHTTPHiddenService")
            if self.runFromInterpreter:
                showTrace(pluginException)
                return
            else:
                print "[-] The Service port is invalid. "
                raise pluginException

        self.hiddenservicePort = hiddenservicePort
        config = txtorcon.TorConfig()
        config.SOCKSPort = socksPort
        config.ORPort = orPort
        if hiddenserviceDir is None:
            print "[+] HiddenServiceDir not specified... Generating a temporal file."
            hiddenserviceDir = self.__createTemporal()

        if os.path.exists(hiddenserviceDir) == False:
            print "[+] The HiddenServiceDir specified does not exists... Generating a temporal file."
            hiddenserviceDir = self.__createTemporal()

        if serviceDir is None or os.path.exists(serviceDir) == False:
            pluginException = PluginException(
                "The specified Server directory is not valid.",
                trace=
                "startHTTPHiddenService with args serviceDir=%s , servicePort=%s , hiddenserviceDir=%s , hiddenservicePort=%s , serviceInterface=%s , socksPort=%s , orPort=%s"
                % (serviceDir, str(servicePort), hiddenserviceDir,
                   str(hiddenservicePort), serviceInterface, str(socksPort),
                   str(orPort)),
                plugin="maliciousHiddenServicePlugin",
                method="startHTTPHiddenService")
            if self.runFromInterpreter:
                showTrace(pluginException)
                return
            else:
                print "[-] The specified Server directory is not valid. You must specify a valid directory where resources like HTML pages, images, CSS and stuff like that are located. The directory will be used to start a simple HTTP Server."
                raise pluginException

        config.HiddenServices = [
            txtorcon.HiddenService(config, hiddenserviceDir, [
                "%s %s:%s" %
                (str(hiddenservicePort), serviceInterface, str(servicePort))
            ])
        ]
        config.save()

        root = static.File(serviceDir)
        root.putChild("gatherUserInfo", GatherInformation())
        site = server.Site(root)
        hs_endpoint = TCP4ServerEndpoint(reactor,
                                         servicePort,
                                         interface=serviceInterface)
        hs_endpoint.listen(site)
        try:
            d = txtorcon.launch_tor(
                config,
                reactor,
                progress_updates=self.__updates,
            )
        except txtorcon.TorNotFound as torBinaryNotFound:
            print "[-] Tor binary not found in the system path. Using the property 'torExecutablePath' located in the config/config.py file."
            d = txtorcon.launch_tor(
                config,
                reactor,
                tor_binary=tortazoConfig.torExecutablePath,
                progress_updates=self.__updates,
            )

        d.addCallback(functools.partial(self.__setup_complete, config))
        d.addErrback(self.__setup_failed)
        reactor.run()
        return True
Exemple #23
0
    def test_full_tor_connection(self):
        config = txtorcon.TorConfig()
        config.ControlPort = random.randint(2**14, 2**16)
        config.SocksPort = random.randint(2**14, 2**16)
        config.DataDirectory = self.tor_datadir
        log.msg(
            "Connecting to %s with tor %s" %
            (self.bridge, onion.tor_details['version']))

        transport_name = onion.transport_name(self.bridge)
        if transport_name == None:
            self.report['bridge_address'] = self.bridge.split(' ')[0]
        else:
            self.report['bridge_address'] = self.bridge.split(' ')[1]
            self.report['transport_name'] = transport_name

            try:
                config.ClientTransportPlugin = \
                        onion.bridge_line(transport_name, self.obfsproxy_logfile)
            except onion.UnrecognizedTransport:
                log.err("Unable to test bridge because we don't recognize "
                        "the %s transport" % transport_name)
                self.report['error'] = "unrecognized-transport"
                return
            except onion.UninstalledTransport:
                bin_name = onion.transport_bin_name.get(transport_name)
                log.err("Unable to test bridge because %s is not installed" %
                        bin_name)
                self.report['error'] = "missing-%s" % bin_name
                return
            except onion.OutdatedObfsproxy:
                log.err("The obfsproxy version you are using " \
                        "appears to be outdated.")
                self.report['error'] = 'old-obfsproxy'
                return
            except onion.OutdatedTor:
                log.err("Unsupported Tor version.")
                self.report['error'] = 'unsupported-tor-version'
                return

            log.debug("Using ClientTransportPlugin '%s'" % \
                      config.ClientTransportPlugin)

        config.Bridge = self.bridge
        config.UseBridges = 1
        config.log = ['notice stdout', 'notice file %s' % self.tor_logfile]
        config.save()

        def updates(prog, tag, summary):
            log.msg("%s: %s%%" % (self.bridge, prog))
            self.report['tor_progress'] = int(prog)
            self.report['tor_progress_tag'] = tag
            self.report['tor_progress_summary'] = summary

        d = txtorcon.launch_tor(config, reactor, timeout=self.timeout,
                                progress_updates=updates)

        @d.addCallback
        def setup_complete(proto):
            try:
                proto.transport.signalProcess('TERM')
            except error.ProcessExitedAlready:
                proto.transport.loseConnection()
            log.msg("Successfully connected to %s" % self.bridge)
            self.report['success'] = True

        @d.addErrback
        def setup_failed(failure):
            log.msg("Failed to connect to %s" % self.bridge)
            self.report['success'] = False
            self.report['error'] = 'timeout-reached'
            return

        @d.addCallback
        def write_log(_):
            with open(self.tor_logfile) as f:
                self.report['tor_log'] = f.read()
            os.remove(self.tor_logfile)
            with open(self.obfsproxy_logfile) as f:
                self.report['obfsproxy_log'] = f.read()
            os.remove(self.obfsproxy_logfile)
            try:
                with open(os.path.join(self.tor_datadir,
                        'pt_state', 'obfs4proxy.log')) as f:
                    self.report['obfsproxy_log'] = f.read()
            except:
                pass
            finally:
                shutil.rmtree(self.tor_datadir)

        return d
Exemple #24
0
def main():
    # Parse the commandline-options
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'hd:p:')
    except getopt.GetoptError as excp:
        print(str(excp))
        print_help()
        return 1

    serve_directory = '.'  # The default directory to serve files from
    hs_public_port = 8011  # The port the hidden service is available on
    web_port = 4711  # The real server's local port
    web_host = '127.0.0.1'  # The real server is bound to localhost
    for o, a in opts:
        if o == '-d':
            serve_directory = a
        elif o == '-p':
            hs_public_port = int(a)
        elif o == '-h':
            print_help()
            return
        else:
            print('Unknown option "%s"' % (o, ))
            return 1

    # Sanitize path and set working directory there (for SimpleHTTPServer)
    serve_directory = os.path.abspath(serve_directory)
    if not os.path.exists(serve_directory):
        print('Path "%s" does not exists, can\'t serve from there...' % \
            (serve_directory, ))
        return 1
    os.chdir(serve_directory)

    # Create a new SimpleHTTPServer and serve it from another thread.
    # We create a callback to Twisted to shut it down when we exit.
    print('Serving "%s" on %s:%i' % (serve_directory, web_host, web_port))
    httpd = SocketServer.TCPServer((web_host, web_port),
                                   SimpleHTTPServer.SimpleHTTPRequestHandler)
    start_httpd(httpd)
    reactor.addSystemEventTrigger(
        'before',
        'shutdown',
        stop_httpd,
        httpd=httpd,
    )

    # Create a directory to hold our hidden service. Twisted will unlink it
    # when we exit.
    hs_temp = tempfile.mkdtemp(prefix='torhiddenservice')
    reactor.addSystemEventTrigger(
        'before', 'shutdown',
        functools.partial(txtorcon.util.delete_file_or_tree, hs_temp))

    # Add the hidden service to a blank configuration
    config = txtorcon.TorConfig()
    config.SOCKSPort = 0
    config.ORPort = 9089
    config.HiddenServices = [
        txtorcon.HiddenService(
            config,
            hs_temp,
            ports=['%i %s:%i' % (hs_public_port, web_host, web_port)])
    ]
    config.save()

    # Now launch tor
    # Notice that we use a partial function as a callback so we have a
    # reference to the config object when tor is fully running.
    tordeferred = txtorcon.launch_tor(config,
                                      reactor,
                                      progress_updates=print_tor_updates)
    tordeferred.addCallback(
        functools.partial(setup_complete, config, hs_public_port))
    tordeferred.addErrback(setup_failed)

    reactor.run()