Example #1
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)
Example #2
0
 def stream_via(self, host, port, tls=False):
     return txtorcon.TorClientEndpoint(
         host, port,
         socks_endpoint=None, # tries localhost:9050 and 9150
         tls=tls,
         reactor=self._reactor,
     )
def main(reactor):
    factory = protocol.Factory.forProtocol(other_proto.DecisionProtocol)
    ca_data = FilePath(b'ca_cert.pem').getContent()
    client_data = FilePath(b'a.client.pem').getContent()
    ca_cert = ssl.Certificate.loadPEM(ca_data)
    client_key = ssl.PrivateCertificate.loadPEM(client_data)
    options = ssl.optionsForClientTLS(u'the-authority', ca_cert, client_key)
    exampleEndpoint = txtorcon.TorClientEndpoint(ip, 8966, socks_hostname="127.0.0.1")
    tlsEndpoint = TLSWrapClientEndpoint(options, exampleEndpoint)
    deferred = yield tlsEndpoint.connect(factory)
    done = defer.Deferred()
    deferred.connectionLost = lambda reason: done.callback(None)
    yield done
Example #4
0
    def get_endpoint_for(self, host, port):
        assert isinstance(port, int)
        if self.is_non_public_numeric_address(host):
            print("ignoring non-Tor-able %s" % host)
            return None

        # txsocksx doesn't like unicode: it concatenates some binary protocol
        # bytes with the hostname when talking to the SOCKS server, so the
        # py2 automatic unicode promotion blows up
        host = host.encode("ascii")
        ep = txtorcon.TorClientEndpoint(host, port,
                                        socks_hostname="127.0.0.1",
                                        socks_port=self._tor_socks_port)
        return ep
Example #5
0
 def hint_to_endpoint(self, hint, reactor, update_status):
     # Return (endpoint, hostname), where "hostname" is what we pass to the
     # HTTP "Host:" header so a dumb HTTP server can be used to redirect us.
     mo = HINT_RE.search(hint)
     if not mo:
         raise InvalidHintError("unrecognized TCP/Tor hint")
     host, portnum = mo.group(1), int(mo.group(2))
     if is_non_public_numeric_address(host):
         raise InvalidHintError("ignoring non-Tor-able ipaddr %s" % host)
     with add_context(update_status, "connecting to a Tor"):
         socks_endpoint = yield self._maybe_connect(reactor, update_status)
     ep = txtorcon.TorClientEndpoint(host,
                                     portnum,
                                     socks_endpoint=socks_endpoint)
     returnValue((ep, host))
Example #6
0
 def hint_to_endpoint(self, hint, reactor):
     # Return (endpoint, hostname), where "hostname" is what we pass to the
     # HTTP "Host:" header so a dumb HTTP server can be used to redirect us.
     mo = HINT_RE.search(hint)
     if not mo:
         raise InvalidHintError("unrecognized TCP/Tor hint")
     host, portnum = mo.group(1), int(mo.group(2))
     if is_non_public_numeric_address(host):
         raise InvalidHintError("ignoring non-Tor-able ipaddr %s" % host)
     socks_endpoint = yield self._maybe_connect(reactor)
     # txsocksx doesn't like unicode: it concatenates some binary protocol
     # bytes with the hostname when talking to the SOCKS server, so the
     # py2 automatic unicode promotion blows up
     host = host.encode("ascii")
     ep = txtorcon.TorClientEndpoint(host, portnum,
                                     socks_endpoint=socks_endpoint)
     returnValue( (ep, host) )
Example #7
0
def create_connecting_endpoint_from_config(config, cbdir, reactor, log):
    """
    Create a Twisted stream client endpoint from a Crossbar.io transport configuration.

    See: https://twistedmatrix.com/documents/current/api/twisted.internet.interfaces.IStreamClientEndpoint.html

    :param config: The transport configuration.
    :type config: dict
    :param cbdir: Crossbar.io node directory (we need this for Unix domain socket paths and TLS key/certificates).
    :type cbdir: str
    :param reactor: The reactor to use for endpoint creation.
    :type reactor: obj

    :returns obj -- An instance implementing IStreamClientEndpoint
    """
    endpoint = None

    # a TCP endpoint
    #
    if config['type'] == 'tcp':

        # the TCP protocol version (v4 or v6)
        #
        version = int(config.get('version', 4))

        # the host to connect to
        #
        host = str(config['host'])

        # the port to connect to
        #
        port = int(config['port'])

        # connection timeout in seconds
        #
        timeout = int(config.get('timeout', 10))

        if 'tls' in config:
            # create a TLS client endpoint
            #
            if _HAS_TLS:
                # TLS client context
                context = _create_tls_client_context(config['tls'], cbdir, log)

                if version == 4:
                    endpoint = SSL4ClientEndpoint(
                        reactor,
                        host,
                        port,
                        context,
                        timeout=timeout,
                    )
                elif version == 6:
                    raise Exception("TLS on IPv6 not implemented")
                else:
                    raise Exception(
                        "invalid TCP protocol version {}".format(version))

            else:
                raise Exception(
                    "TLS transport requested, but TLS packages not available:\n{}"
                    .format(_LACKS_TLS_MSG))

        else:
            # create a non-TLS client endpoint
            #
            if version == 4:
                endpoint = TCP4ClientEndpoint(reactor,
                                              host,
                                              port,
                                              timeout=timeout)
            elif version == 6:
                endpoint = TCP6ClientEndpoint(reactor,
                                              host,
                                              port,
                                              timeout=timeout)
            else:
                raise Exception(
                    "invalid TCP protocol version {}".format(version))

    # a Unix Domain Socket endpoint
    #
    elif config['type'] == 'unix':

        # the path
        #
        path = abspath(join(cbdir, config['path']))

        # connection timeout in seconds
        #
        timeout = int(config.get('timeout', 10))

        # create the endpoint
        #
        endpoint = UNIXClientEndpoint(reactor, path, timeout=timeout)

    elif config['type'] == 'twisted':
        endpoint = clientFromString(reactor, config['client_string'])

    elif config['type'] == 'tor':
        host = config['host']
        port = config['port']
        socks_port = config['tor_socks_port']
        tls = config.get('tls', False)
        if not tls and not host.endswith('.onion'):
            log.warn(
                "Non-TLS connection traversing Tor network; end-to-end encryption advised"
            )

        socks_endpoint = TCP4ClientEndpoint(
            reactor,
            "127.0.0.1",
            socks_port,
        )
        endpoint = txtorcon.TorClientEndpoint(
            host,
            port,
            socks_endpoint=socks_endpoint,
            reactor=reactor,
            use_tls=tls,
        )

    else:
        raise Exception("invalid endpoint type '{}'".format(config['type']))

    return endpoint
def _create_transport_endpoint(reactor, endpoint_config):
    """
    Create a Twisted client endpoint for a WAMP-over-XXX transport.
    """
    if IStreamClientEndpoint.providedBy(endpoint_config):
        endpoint = IStreamClientEndpoint(endpoint_config)
    else:
        # create a connecting TCP socket
        if endpoint_config['type'] == 'tcp':

            version = endpoint_config.get('version', 4)
            if version not in [4, 6]:
                raise ValueError(
                    'invalid IP version {} in client endpoint configuration'.
                    format(version))

            host = endpoint_config['host']
            if type(host) != str:
                raise ValueError(
                    'invalid type {} for host in client endpoint configuration'
                    .format(type(host)))

            port = endpoint_config['port']
            if type(port) != int:
                raise ValueError(
                    'invalid type {} for port in client endpoint configuration'
                    .format(type(port)))

            timeout = endpoint_config.get('timeout', 10)  # in seconds
            if type(timeout) != int:
                raise ValueError(
                    'invalid type {} for timeout in client endpoint configuration'
                    .format(type(timeout)))

            tls = endpoint_config.get('tls', None)

            # create a TLS enabled connecting TCP socket
            if tls:
                if not _TLS:
                    raise RuntimeError(
                        'TLS configured in transport, but TLS support is not installed (eg OpenSSL?)'
                    )

                # FIXME: create TLS context from configuration
                if IOpenSSLClientConnectionCreator.providedBy(tls):
                    # eg created from twisted.internet.ssl.optionsForClientTLS()
                    context = IOpenSSLClientConnectionCreator(tls)

                elif isinstance(tls, dict):
                    for k in tls.keys():
                        if k not in ["hostname", "trust_root"]:
                            raise ValueError(
                                "Invalid key '{}' in 'tls' config".format(k))
                    hostname = tls.get('hostname', host)
                    if type(hostname) != str:
                        raise ValueError(
                            'invalid type {} for hostname in TLS client endpoint configuration'
                            .format(hostname))
                    trust_root = None
                    cert_fname = tls.get("trust_root", None)
                    if cert_fname is not None:
                        trust_root = Certificate.loadPEM(
                            open(cert_fname, 'r').read())
                    context = optionsForClientTLS(hostname,
                                                  trustRoot=trust_root)

                elif isinstance(tls, CertificateOptions):
                    context = tls

                elif tls is True:
                    context = optionsForClientTLS(host)

                else:
                    raise RuntimeError(
                        'unknown type {} for "tls" configuration in transport'.
                        format(type(tls)))

                if version == 4:
                    endpoint = SSL4ClientEndpoint(reactor,
                                                  host,
                                                  port,
                                                  context,
                                                  timeout=timeout)
                elif version == 6:
                    # there is no SSL6ClientEndpoint!
                    raise RuntimeError('TLS on IPv6 not implemented')
                else:
                    assert (False), 'should not arrive here'

            # create a non-TLS connecting TCP socket
            else:
                if host.endswith(".onion"):
                    # hmm, can't log here?
                    # self.log.info("{host} appears to be a Tor endpoint", host=host)
                    try:
                        import txtorcon
                        endpoint = txtorcon.TorClientEndpoint(host, port)
                    except ImportError:
                        raise RuntimeError(
                            "{} appears to be a Tor Onion service, but txtorcon is not installed"
                            .format(host, ))
                elif version == 4:
                    endpoint = TCP4ClientEndpoint(reactor,
                                                  host,
                                                  port,
                                                  timeout=timeout)
                elif version == 6:
                    try:
                        from twisted.internet.endpoints import TCP6ClientEndpoint
                    except ImportError:
                        raise RuntimeError(
                            'IPv6 is not supported (please upgrade Twisted)')
                    endpoint = TCP6ClientEndpoint(reactor,
                                                  host,
                                                  port,
                                                  timeout=timeout)
                else:
                    assert (False), 'should not arrive here'

        # create a connecting Unix domain socket
        elif endpoint_config['type'] == 'unix':
            path = endpoint_config['path']
            timeout = int(endpoint_config.get('timeout', 10))  # in seconds
            endpoint = UNIXClientEndpoint(reactor, path, timeout=timeout)

        else:
            assert (False), 'should not arrive here'

    return endpoint