def main(reactor):
    # "onion:" is for Tor Onion Services, and the only required
    # argument is the public port we advertise. You can pass
    # "controlPort=9051" for example, to connect to a system Tor
    # (accepts paths, too, e.g. "controlPort=/var/run/tor/control")
    # ep = endpoints.serverFromString(reactor, "onion:80:controlPort=9151")

    # to re-create a previous hidden-service, pass the private key
    # blob you retrieved earler via port.getHost().onion_key like so:
    # ep = endpoints.serverFromString(reactor, "onion:80:privateKey=<keyblob>")
    # Beware that you have to escape the ":" after RSA1024 because of
    # reasons (the endpoint syntax uses them). For this reason, you
    # can omit the "RSA1024:" part if you wish.
    # ep = endpoints.serverFromString(reactor, "onion:80")

    # this one should be "nyfnesplt3f5nvn3.onion"

    print(default_control_port())
    ep = endpoints.serverFromString(reactor, "onion:80:controlPort={port}:privateKey=RSA1024\\:MIICWwIBAAKBgQDml0L1Btxe1QIs88mvKvcgAEd19bUorzMndfXXBbPt2y1lTjm+vGldJRCXb/RArfCb9F2q7IWL4ScuJBiUCqpKVG2aGK8yOxw4c5WKvnLW8MRf5+jAPlR3h7idBdrVGCY/9gXf9JzWfpIhMfFidM4Xq6VpzMvignss6FB6i9zhOwIDAQABAoGAXuWjVamUKabp9UwDFYbOGypiPmZ3Pp4TpErEeNBNAzdvUEDIPPnXNtEZKemWEMREwDnqDny2XSG0+SU7xDk7aQGTFxipo+NAl18QMW2XcBjWrIG5P0L9E+j58k5Nq6EEaMQ8G8X3hsnX7EwRqnJYOwUWUQ4emi6TvNScSMS251kCQQD6KJXltkSfwU3d5hOh37x3pOp4ZcpI6eKwwfgqP+1pVfOwjvXfLqLgLRf9+NtmG+cU5HRDwmf9rbJNCOE++11HAkEA6/mz/L+54NRk9tPN4vYfn969v7fz9CQndQUsTTrtArqtjg7baKts3ndagj+/itJfY6qV/OonN9XdntQXTWWGbQJAY244TmrJEfqieZ2WlhO49JFPRPWolpyoJvuiKSDpu6GXT8ky/zepM5OY4rDEe+yBR/OaJsihztn4cdgit4bvxwJAFsnZiOoXEFBSo8eWlXmBWlYPawlfxM8NBG8IdTjglKfkhNiIddZAQEe0dOmlHMnuLljV/UO7n9fGfEUtLutEDQJAC3c9gSe2of41TaZhQ+aHzQ8E9cs7fg3gXXUgWlocQK6fYq+tC0CF7dDmydShF8vI8oEcgJGhgtUAXQDwH9eD0A==".format(port=default_control_port()))

    def on_progress(percent, tag, msg):
        print('%03d: %s' % (percent, msg))
    txtorcon.IProgressProvider(ep).add_progress_listener(on_progress)
    print("Note: descriptor upload can take several minutes")

    port = yield ep.listen(server.Site(Simple()))
    print("Site listening: {}".format(port.getHost()))
    print("Private key:\n{}".format(port.getHost().onion_key))
    yield defer.Deferred()  # wait forever
def main(reactor):
    # For the "single_hop=True" below to work, the Tor we're
    # connecting to must have the following options set:
    # SocksPort 0
    # HiddenServiceSingleHopMode 1
    # HiddenServiceNonAnonymousMode 1

    tor = yield txtorcon.connect(
        reactor,
        endpoints.TCP4ClientEndpoint(reactor, "localhost", 9351),
    )
    if False:
        ep = tor.create_onion_endpoint(
            80,
            version=3,
            single_hop=True,
        )
    else:
        ep = endpoints.serverFromString(reactor, "onion:80:version=3:singleHop=true")

    def on_progress(percent, tag, msg):
        print('%03d: %s' % (percent, msg))
    txtorcon.IProgressProvider(ep).add_progress_listener(on_progress)

    port = yield ep.listen(server.Site(Simple()))
    print("Private key:\n{}".format(port.getHost().onion_key))
    hs = port.onion_service
    print("Site on http://{}".format(hs.hostname))
    yield defer.Deferred()  # wait forever
Beispiel #3
0
def main(reactor):
    tor = yield txtorcon.connect(
        reactor,
        endpoints.TCP4ClientEndpoint(reactor, "localhost", 9251),
    )
    ep = tor.create_authenticated_onion_endpoint(
        80,
        auth=AuthBasic([
            ("alice", "0GaFhnbunp0TxZuBhejhxg"),
            "bob",
        ]),
    )

    def on_progress(percent, tag, msg):
        print('%03d: %s' % (percent, msg))

    txtorcon.IProgressProvider(ep).add_progress_listener(on_progress)
    print("Note: descriptor upload can take several minutes")

    port = yield ep.listen(server.Site(Simple()))
    print("Private key:\n{}".format(port.getHost().onion_key))
    hs = port.onion_service
    print("Clients:")
    for name in hs.client_names():
        print(
            "  {}: username={} token={}".format(
                hs.get_client(name).hostname, name,
                hs.get_client(name).auth_token), )
    print("hs {}".format(hs))
    print(type(hs))
    print(dir(hs))
    yield defer.Deferred()  # wait forever
Beispiel #4
0
def main(reactor):
    # a simple Web site; could be any other listening service of course
    res = resource.Resource()
    res.putChild(
        b'',
        static.Data("<html>Hello, onion-service world!</html>", 'text/html'))

    def on_progress(percent, tag, msg):
        print('%03d: %s' % (percent, msg))

    # We are using launch() here instead of connect() because
    # filesystem services are very picky about the permissions and
    # ownership of the directories involved. If you *do* want to
    # connect to e.g. a system service or Tor Browser Bundle, it's way
    # more likely to work to use Ephemeral services

    tor = yield txtorcon.connect(
        reactor,
        endpoints.TCP4ClientEndpoint(reactor, "localhost",
                                     txtorcon.util.default_control_port()),
    )

    # NOTE: you should put these somewhere you've thought about more
    # and made proper permissions for the parent directory, etc. A
    # good choice for a system-wide Tor is /var/lib/tor/<whatever>
    # The parent directory must be mode 700
    os.mkdir("hs_parent")
    os.chmod("hs_parent", 0o700)
    hs_dir = './hs_parent/hs_dir'

    print("Creating stealth-authenticated hidden-service, keys in: {}".format(
        hs_dir))
    ep = tor.create_authenticated_filesystem_onion_endpoint(
        80,
        hs_dir=hs_dir,
        auth=txtorcon.AuthStealth(['alice', 'bob']),
        group_readable=True,
    )

    print("Note: descriptor upload can take several minutes")

    txtorcon.IProgressProvider(ep).add_progress_listener(on_progress)

    port = yield ep.listen(server.Site(res))
    hs = port.getHost().onion_service
    for name in hs.client_names():
        client = hs.get_client(name)
        print("  {}: {}".format(name, client.hostname))
        print("     auth token: {}".format(client.auth_token))
        print("    private key: {}..".format(client.private_key[:40]))
        print("    HidServAuth {} {}".format(client.hostname,
                                             client.auth_token))
    yield tor.protocol.on_disconnect
    print("disconnected")
Beispiel #5
0
def main(reactor):
    tor = yield txtorcon.connect(
        reactor,
        endpoints.TCP4ClientEndpoint(reactor, "localhost", 9251),
    )
    print(default_control_port())
    ep = tor.create_filesystem_onion_endpoint(80,
                                              "./test_prop224_service",
                                              version=3)

    def on_progress(percent, tag, msg):
        print('%03d: %s' % (percent, msg))

    txtorcon.IProgressProvider(ep).add_progress_listener(on_progress)
    print("Note: descriptor upload can take several minutes")

    port = yield ep.listen(server.Site(Simple()))
    print("Site listening: {}".format(port.getHost()))
    print("Private key:\n{}".format(port.getHost().onion_key))
    yield defer.Deferred()  # wait forever
Beispiel #6
0
    def _start_onion_service(self, factory):

        def progress(percent, tag, message):
            bar = int(percent / 10)
            log.debug('[%s%s] %s' % ('#' * bar, '.' * (10 - bar), message))

        def setup_complete(port):
            port = txtorcon.IHiddenService(port)
            self.uri = "http://%s" % (port.getHost().onion_uri)
            log.info('I have set up a hidden service, advertised at: %s'
                     % self.uri)
            log.info('locally listening on %s' % port.local_address.getHost())

        def setup_failed(args):
            log.error('onion service setup FAILED: %r' % args)

        endpoint = endpoints.serverFromString(reactor, 'onion:80')
        txtorcon.IProgressProvider(endpoint).add_progress_listener(progress)
        d = endpoint.listen(factory)
        d.addCallback(setup_complete)
        d.addErrback(setup_failed)
        return d
Beispiel #7
0
def run(reactor, cfg, tor, dry_run, once, file, count, keys):

    to_share = file.read()
    file.close()

    # stealth auth. keys
    authenticators = []
    if keys:
        for x in xrange(keys):
            authenticators.append('carml_%d' % x)

    if len(authenticators):
        print(len(to_share), "bytes to share with",
              len(authenticators), "authenticated clients.")
    else:
        print(len(to_share), "bytes to share.")
    sys.stdout.flush()

    if dry_run:
        print('Not launching a Tor, listening on 8899.')
        ep = serverFromString(reactor, 'tcp:8899:interface=127.0.0.1')
    elif True:  # connection is None:
        print("Launching Tor.")
        ep = TCPHiddenServiceEndpoint.global_tor(reactor, 80)
        txtorcon.IProgressProvider(ep).add_progress_listener(_progress)
        if keys:
            ep.stealth_auth = [
                'user_{}'.format(n)
                for n in range(keys)
            ]
    else:
        config = yield txtorcon.TorConfig.from_connection(connection)
        ep = txtorcon.TCPEphemeralHiddenServiceEndpoint(reactor, config, 80)

    root = Resource()
    data = Data(to_share, 'text/plain')
    root.putChild('', data)

    if once:
        count = 1
    port = yield ep.listen(PasteBinSite(root, max_requests=count))

    if keys == 0:
        clients = None
    else:
        # FIXME
        clients = port.tor_config.hiddenservices[0].clients

    host = port.getHost()
    if dry_run:
        print("Try it locally via http://127.0.0.1:8899")

    elif clients:
        print("You requested stealth authentication.")
        print("Tor has created %d keys; each key should be given to one person." % len(clients))
        print('They can set one using the "HidServAuth" torrc option, like so:')
        print("")
        for client in clients:
            print("  HidServAuth %s %s" % (client[0], client[1]))
        print("")
        print("Alternatively, any Twisted endpoint-aware client can be given")
        print("the following string as an endpoint:")
        print("")
        for client in clients:
            print("  tor:%s:authCookie=%s" % (client[0], client[1]))
        print("")
        print("For example, using carml:")
        print("")
        for client in clients:
            print("  carml copybin --service tor:%s:authCookie=%s" % (client[0], client[1]))

    else:
        print("People using Tor Browser Bundle can find your paste at (once the descriptor uploads):")
        print("\n   http://{0}\n".format(host.onion_uri))
        print("for example:")
        print("   torsocks curl -o data.asc http://{0}\n".format(host.onion_uri))
        if not count:
            print("Type Control-C to stop serving and shut down the Tor we launched.")
        print("If you wish to keep the hidden-service keys, they're in (until we shut down):")
        print(ep.hidden_service_dir)

    reactor.addSystemEventTrigger('before', 'shutdown',
                                  lambda: print(util.colors.red('Shutting down.')))
    # we never callback() on this, so we serve forever
    d = defer.Deferred()
    yield d
Beispiel #8
0
def main(reactor):
    # several ways to proceed here and what they mean:
    #
    # "onion:80":
    #    launch a new Tor instance, configure a hidden service on some
    #    port and pubish descriptor for port 80
    #
    # "onion:80:controlPort=9051:localPort=8080:socksPort=9089:hiddenServiceDir=/home/human/src/txtorcon/hidserv":
    #    connect to existing Tor via control-port 9051, configure a hidden
    #    service listening locally on 8080, publish a descriptor for port
    #    80 and use an explicit hiddenServiceDir (where "hostname" and
    #    "private_key" files are put by Tor). We set SOCKS port
    #    explicitly, too.
    #
    # "onion:80:localPort=8080:socksPort=9089:hiddenServiceDir=/home/human/src/txtorcon/hidserv":
    #    all the same as above, except we launch a new Tor (because no
    #    "controlPort=9051")

    ep = "onion:80:controlPort=9051:localPort=8080:socksPort=9089:hiddenServiceDir=/home/human/src/txtorcon/hidserv"
    ep = "onion:80:localPort=8080:socksPort=9089:hiddenServiceDir=/home/human/src/txtorcon/hidserv"
    ep = "onion:80"
    hs_endpoint = serverFromString(reactor, ep)

    def progress(percent, tag, message):
        bar = int(percent / 10)
        print("[{}{}] {}".format("#" * bar, "." * (10 - bar), message))
    txtorcon.IProgressProvider(hs_endpoint).add_progress_listener(progress)

    # create our Web server and listen on the endpoint; this does the
    # actual launching of (or connecting to) tor.
    site = server.Site(Simple())
    port = yield hs_endpoint.listen(site)
    # XXX new accessor in newer API
    hs = port.onion_service

    # "port" is an IAddress implementor, in this case TorOnionAddress
    # so you can get most useful information from it -- but you can
    # also access .onion_service (see below)
    print(
        "I have set up a hidden service, advertised at:\n"
        "http://{host}:{port}\n"
        "locally listening on {local_address}\n"
        "Will stop in 60 seconds...".format(
            host=port.getHost().onion_uri,  # or hs.hostname
            port=port.public_port,
            # port.local_address will be a twisted.internet.tcp.Port
            # or a twisted.internet.unix.Port -- both have .getHost()
            local_address=port.local_address.getHost(),
        )
    )

    # if you prefer, hs (port.onion_service) is an instance providing
    # IOnionService (there's no way to do authenticated services via
    # endpoints yet, but if there was then this would implement
    # IOnionClients instead)
    print("private key:\n{}".format(hs.private_key))

    def sleep(s):
        return deferLater(reactor, s, lambda: None)

    yield sleep(50)
    for i in range(10):
        print("Stopping in {}...".format(10 - i))
        yield sleep(1)

def setup_failed(arg):
    print "SETUP FAILED", arg


def setup_complete(port):
    print "Hidden serivce:", port.getHost()
    print "    locally at:", txtorcon.IHiddenService(
        port).local_address.getHost()


def progress(percent, tag, message):
    bar = int(percent / 10)
    print '[%s%s] %s' % ('#' * bar, '.' * (10 - bar), message)


hs_endpoint1 = serverFromString(reactor, "onion:80")
hs_endpoint2 = serverFromString(reactor, "onion:80")

txtorcon.IProgressProvider(hs_endpoint1).add_progress_listener(progress)
txtorcon.IProgressProvider(hs_endpoint2).add_progress_listener(progress)

d1 = hs_endpoint1.listen(site)
d2 = hs_endpoint2.listen(site)

d1.addCallback(setup_complete).addErrback(setup_failed)
d2.addCallback(setup_complete).addErrback(setup_failed)

reactor.run()
Beispiel #10
0
#!/usr/bin/env python

# This shows how to leverage the endpoints API to get a new hidden
# service up and running quickly. You can pass along this API to your
# users by accepting endpoint strings as per Twisted recommendations.
#
# http://twistedmatrix.com/documents/current/core/howto/endpoints.html#maximizing-the-return-on-your-endpoint-investment
#
# note that only the progress-updates needs the "import txtorcon" --
# you do still need it installed so that Twisted finds the endpoint
# parser plugin but code without knowledge of txtorcon can still
# launch a Tor instance using it. cool!

from __future__ import print_function
from twisted.internet import reactor, endpoints
from twisted.web import server, static
import txtorcon

res = static.Data("<html>Hello, hidden-service world!</html>", 'text/html')
ep = endpoints.serverFromString(reactor, "onion:80")
txtorcon.IProgressProvider(ep).add_progress_listener(lambda p, tag, msg: print(msg))
ep.listen(server.Site(res)).addCallback(lambda port: print(str(port.getHost()))).addErrback(print)

reactor.run()
Beispiel #11
0
    def run(self, options, mainoptions, connection):
        "ICarmlCommand API"

        to_share = None
        self.progress_dots = 0
        if options['file']:
            to_share = open(options['file'], 'r').read()
        else:
            to_share = sys.stdin.read()

        # stealth auth. keys
        authenticators = []
        if options['keys']:
            for x in xrange(options['keys']):
                authenticators.append('carml_%d' % x)

        if len(authenticators):
            print(len(to_share), "bytes to share with", len(authenticators),
                  "authenticated clients.")
        else:
            print(len(to_share), "bytes to share.")
        sys.stdout.flush()

        if options['dry-run']:
            print('Not launching a Tor, listening on 8899.')
            ep = serverFromString(reactor, 'tcp:8899:interface=127.0.0.1')
        else:
            print("Launching Tor.")
            ep = TCPHiddenServiceEndpoint.global_tor(
                reactor, 80, stealth_auth=authenticators)
            txtorcon.IProgressProvider(ep).add_progress_listener(self.progress)

        root = Resource()
        data = Data(to_share, 'text/plain')
        root.putChild('', data)

        count = 1 if options['once'] else options['count']
        port = yield ep.listen(PasteBinSite(root, max_requests=count))

        # FIXME
        clients = port.tor_config.hiddenservices[0].clients

        host = port.getHost()
        if options['dry-run']:
            print("Try it locally via http://127.0.0.1:8899")

        elif len(clients):
            print("You requested stealth authentication.")
            print(
                "Tor has created %d keys; each key should be given to one person."
                % len(clients))
            print(
                'They can set one using the "HidServAuth" torrc option, like so:'
            )
            print("")
            for client in clients:
                print("  HidServAuth %s %s" % (client[0], client[1]))
            print("")
            print(
                "Alternatively, any Twisted endpoint-aware client can be given"
            )
            print("the following string as an endpoint:")
            print("")
            for client in clients:
                print("  tor:%s:authCookie=%s" % (client[0], client[1]))
            print("")
            print("For example, using carml:")
            print("")
            for client in clients:
                print("  carml copybin --service tor:%s:authCookie=%s" %
                      (client[0], client[1]))

        else:
            print(
                "People using Tor Browser Bundle can find your paste at (once the descriptor uploads):"
            )
            print("\n   http://{0}\n".format(host.onion_uri))
            if not count:
                print(
                    "Type Control-C to stop serving and shut down the Tor we launched."
                )
            print(
                "If you wish to keep the hidden-service keys, they're in (until we shut down):"
            )
            print(ep.hidden_service_dir)

        reactor.addSystemEventTrigger(
            'before', 'shutdown',
            lambda: print(util.colors.red('Shutting down.')))
        # we never callback() on this, so we serve forever
        d = defer.Deferred()
        yield d