Exemple #1
0
def create_proxy_client(host, port, proxy_spec, instance):
    """
    host:
    the host of the final destination
    port:
    the port number of the final destination
    proxy_spec:
    the address of the proxy server as a urlparse.SplitResult
    instance:
    is the instance to be associated with the endpoint

    Returns a deferred that will fire when the connection to the SOCKS server has been established.
    """

    # Inline import so that txsocksx is an optional dependency.
    from twisted.internet.endpoints import HostnameEndpoint
    from txsocksx.client import SOCKS4ClientEndpoint, SOCKS5ClientEndpoint
    from obfsproxy.network.http import HTTPConnectClientEndpoint

    TCPPoint = HostnameEndpoint(reactor, proxy_spec.hostname, proxy_spec.port)
    username = proxy_spec.username
    password = proxy_spec.password

    # Do some logging
    log.debug("Connecting via %s proxy %s:%d",
              proxy_spec.scheme, log.safe_addr_str(proxy_spec.hostname), proxy_spec.port)
    if username or password:
        log.debug("Using %s:%s as the proxy credentials",
                  log.safe_addr_str(username), log.safe_addr_str(password))

    if proxy_spec.scheme in ["socks4a", "socks5"]:
        if proxy_spec.scheme == "socks4a":
            if username:
                assert(password == None)
                SOCKSPoint = SOCKS4ClientEndpoint(host, port, TCPPoint, user=username)
            else:
                SOCKSPoint = SOCKS4ClientEndpoint(host, port, TCPPoint)
        elif proxy_spec.scheme == "socks5":
            if username and password:
                SOCKSPoint = SOCKS5ClientEndpoint(host, port, TCPPoint,
                                                  methods={'login': (username, password)})
            else:
                assert(username == None and password == None)
                SOCKSPoint = SOCKS5ClientEndpoint(host, port, TCPPoint)
        d = SOCKSPoint.connect(instance)
        return d
    elif proxy_spec.scheme == "http":
        if username and password:
            HTTPPoint = HTTPConnectClientEndpoint(host, port, TCPPoint,
                                                  username, password)
        else:
            assert(username == None and password == None)
            HTTPPoint = HTTPConnectClientEndpoint(host, port, TCPPoint)
        d = HTTPPoint.connect(instance)
        return d
    else:
        # Should *NEVER* happen
        raise RuntimeError("Invalid proxy scheme %s" % proxy_spec.scheme)
 def build_irc(self):
     """The main starting method that creates a protocol object
     according to the config variables, ready for whenever
     the reactor starts running.
     """
     wlog('building irc')
     if self.tx_irc_client:
         raise Exception('irc already built')
     if self.usessl.lower() == 'true' and not self.socks5.lower() == 'true':
         factory = TxIRCFactory(self)
         ctx = ClientContextFactory()
         reactor.connectSSL(self.serverport[0], self.serverport[1], factory,
                            ctx)
     elif self.socks5.lower() == 'true':
         factory = TxIRCFactory(self)
         #str() casts needed else unicode error
         torEndpoint = TCP4ClientEndpoint(reactor, str(self.socks5_host),
                                          self.socks5_port)
         ircEndpoint = SOCKS5ClientEndpoint(str(self.serverport[0]),
                                            self.serverport[1], torEndpoint)
         if self.usessl.lower() == 'true':
             ctx = ClientContextFactory()
             tlsEndpoint = TLSWrapClientEndpoint(ctx, ircEndpoint)
             tlsEndpoint.connect(factory)
         else:
             ircEndpoint.connect(factory)
     else:
         try:
             factory = TxIRCFactory(self)
             wlog('build_irc: ', self.serverport[0], self.serverport[1],
                  self.channel)
             self.tcp_connector = reactor.connectTCP(
                 self.serverport[0], self.serverport[1], factory)
         except Exception as e:
             wlog('error in buildirc: ' + repr(e))
Exemple #3
0
def get_endpoint(target_host, target_port, target_ssl, socks_config=None):

    # Imports go here to allow mocking for tests
    from twisted.internet.endpoints import SSL4ClientEndpoint, TCP4ClientEndpoint
    from txsocksx.client import SOCKS5ClientEndpoint
    from txsocksx.tls import TLSWrapClientEndpoint
    from twisted.internet.interfaces import IOpenSSLClientConnectionCreator

    if socks_config is not None:
        sock_host = socks_config['host']
        sock_port = int(socks_config['port'])
        methods = {'anonymous': ()}
        if 'username' in socks_config and 'password' in socks_config:
            methods['login'] = (socks_config['username'],
                                socks_config['password'])
        tcp_endpoint = TCP4ClientEndpoint(reactor, sock_host, sock_port)
        socks_endpoint = SOCKS5ClientEndpoint(target_host,
                                              target_port,
                                              tcp_endpoint,
                                              methods=methods)
        if target_ssl:
            endpoint = TLSWrapClientEndpoint(ClientTLSContext(),
                                             socks_endpoint)
        else:
            endpoint = socks_endpoint
    else:
        if target_ssl:
            endpoint = SSL4ClientEndpoint(reactor, target_host, target_port,
                                          ClientTLSContext())
        else:
            endpoint = TCP4ClientEndpoint(reactor, target_host, target_port)
    return endpoint
Exemple #4
0
def main(reactor):
    torEndpoint = TCP4ClientEndpoint(reactor, '127.0.0.1', 9050)
    proxiedEndpoint = SOCKS5ClientEndpoint('api.externalip.net', 80, torEndpoint)
    d = proxiedEndpoint.connect(TerribleHTTPClientFactory())
    d.addCallback(lambda proto: proto.deferred)
    d.addCallback(print)
    return d
Exemple #5
0
 def connect(self):
     #Generate a random int between 0 and 4 (include) to know which Tor Host we will use.
     index= random.randint(0,4)
     torEndpoint = TCP4ClientEndpoint(reactor, TOR_HOSTS[index][0], TOR_HOSTS[index][1])
     proxiedEndpoint = SOCKS5ClientEndpoint(self.active_host.hostname.encode("ascii"), self.current_port, torEndpoint)
     d = proxiedEndpoint.connect(PortScannerClientFactory(self))
     d.addCallback(gotProtocol, self)
     d.addErrback(gotErr, self)
Exemple #6
0
def main(reactor):
    torEndpoint = TCP4ClientEndpoint(reactor, '127.0.0.1', 9050)
    # freenode's tor endpoint
    ircEndpoint = SOCKS5ClientEndpoint('lgttsalmpw3qo4no.onion', 6667,
                                       torEndpoint)
    d = ircEndpoint.connect(SpewingFactory(TorIRCFactory()))
    d.addCallback(lambda proto: proto.wrappedProtocol.deferred)
    return d
Exemple #7
0
 def connect(self):
     torEndpoint = TCP4ClientEndpoint(reactor, TOR_HOST, TOR_PORT)
     proxiedEndpoint = SOCKS5ClientEndpoint(
         self.active_host.hostname.encode("ascii"), self.current_port,
         torEndpoint)
     d = proxiedEndpoint.connect(PortScannerClientFactory(self))
     d.addCallback(gotProtocol, self)
     d.addErrback(gotErr, self)
Exemple #8
0
 def hint_to_endpoint(self, hint, reactor, update_status):
     mo = HINT_RE.search(hint)
     if not mo:
         raise InvalidHintError("unrecognized hint, wanted TYPE:HOST:PORT")
     host, port = mo.group(1), int(mo.group(2))
     # note: txsockx does not expose a way to provide the reactor
     ep = SOCKS5ClientEndpoint(host, port, self._proxy_endpoint)
     return ep, host
Exemple #9
0
def make_proxied_connection(protocol_factory,
                            target_host,
                            target_port,
                            use_ssl,
                            socks_config=None,
                            log_id=None,
                            http_error_transport=None):
    from twisted.internet.endpoints import SSL4ClientEndpoint, TCP4ClientEndpoint
    from txsocksx.client import SOCKS5ClientEndpoint
    from txsocksx.tls import TLSWrapClientEndpoint
    from pappyproxy.pappy import session

    if socks_config is not None:
        log("Connecting to socks proxy", id=log_id)
        sock_host = socks_config['host']
        sock_port = int(socks_config['port'])
        methods = {'anonymous': ()}
        if 'username' in socks_config and 'password' in socks_config:
            methods['login'] = (socks_config['username'],
                                socks_config['password'])
        tcp_endpoint = TCP4ClientEndpoint(reactor, sock_host, sock_port)
        socks_endpoint = SOCKS5ClientEndpoint(target_host,
                                              target_port,
                                              tcp_endpoint,
                                              methods=methods)
        if use_ssl:
            log("Using SSL over proxy to connect to %s:%d ssl=%s" %
                (target_host, target_port, use_ssl),
                id=log_id)
            endpoint = TLSWrapClientEndpoint(ssl.ClientContextFactory(),
                                             socks_endpoint)
        else:
            log("Using TCP over proxy to connect to %s:%d ssl=%s" %
                (target_host, target_port, use_ssl),
                id=log_id)
            endpoint = socks_endpoint
    else:
        log("Connecting directly to host", id=log_id)
        if use_ssl:
            log("Using SSL to connect to %s:%d ssl=%s" %
                (target_host, target_port, use_ssl),
                id=log_id)
            #context = BrowserLikePolicyForHTTPS().creatorForNetloc(target_host, target_port)
            context = ssl.ClientContextFactory()
            endpoint = SSL4ClientEndpoint(reactor, target_host, target_port,
                                          context)
        else:
            log("Using TCP to connect to %s:%d ssl=%s" %
                (target_host, target_port, use_ssl),
                id=log_id)
            endpoint = TCP4ClientEndpoint(reactor, target_host, target_port)

    connection_deferred = endpoint.connect(protocol_factory)
    if http_error_transport:
        connection_deferred.addErrback(connection_error_http_response,
                                       http_error_transport, log_id)
Exemple #10
0
    def TLS_TOR_conn(self, bar_server, bar_port):
        # Connect to TOR network
        torServerEndpoint = TCP4ClientEndpoint(reactor, "127.0.0.1", 9050)
        torEndpoint = SOCKS5ClientEndpoint(bar_server, bar_port,
                                           torServerEndpoint)

        #Use SSL - TLS to encrypt the connection between You and the server
        tlsEndpoint = TLSWrapClientEndpoint(ssl.ClientContextFactory(),
                                            torEndpoint)
        return tlsEndpoint
Exemple #11
0
def test_no_tcp():
    from twisted.internet.endpoints import SSL4ClientEndpoint, TCP4ClientEndpoint
    from txsocksx.client import SOCKS5ClientEndpoint
    from txsocksx.tls import TLSWrapClientEndpoint
    with pytest.raises(NotImplementedError):
        SSL4ClientEndpoint('aasdfasdf.sdfwerqwer')
    with pytest.raises(NotImplementedError):
        TCP4ClientEndpoint('aasdfasdf.sdfwerqwer')
    with pytest.raises(NotImplementedError):
        SOCKS5ClientEndpoint('aasdfasdf.sdfwerqwer')
    with pytest.raises(NotImplementedError):
        TLSWrapClientEndpoint('asdf.2341')
Exemple #12
0
def get_endpoint(target_host,
                 target_port,
                 target_ssl,
                 socks_config=None,
                 use_http_proxy=False,
                 debugid=None):
    # Imports go here to allow mocking for tests
    from twisted.internet.endpoints import SSL4ClientEndpoint, TCP4ClientEndpoint
    from txsocksx.client import SOCKS5ClientEndpoint
    from txsocksx.tls import TLSWrapClientEndpoint
    from pappyproxy.pappy import session

    log("Getting endpoint for host '%s' on port %d ssl=%s, socks_config=%s, use_http_proxy=%s"
        % (target_host, target_port, target_ssl, str(socks_config),
           use_http_proxy),
        id=debugid,
        verbosity_level=3)

    if session.config.http_proxy and use_http_proxy:
        target_host = session.config.http_proxy['host']
        target_port = session.config.http_proxy['port']
        target_ssl = False  # We turn on ssl after CONNECT request if needed
        log("Connecting to http proxy at %s:%d" % (target_host, target_port),
            id=debugid,
            verbosity_level=3)

    if socks_config is not None:
        sock_host = socks_config['host']
        sock_port = int(socks_config['port'])
        methods = {'anonymous': ()}
        if 'username' in socks_config and 'password' in socks_config:
            methods['login'] = (socks_config['username'],
                                socks_config['password'])
        tcp_endpoint = TCP4ClientEndpoint(reactor, sock_host, sock_port)
        socks_endpoint = SOCKS5ClientEndpoint(target_host,
                                              target_port,
                                              tcp_endpoint,
                                              methods=methods)
        if target_ssl:
            endpoint = TLSWrapClientEndpoint(ssl.ClientContextFactory(),
                                             socks_endpoint)
        else:
            endpoint = socks_endpoint
    else:
        if target_ssl:
            endpoint = SSL4ClientEndpoint(reactor, target_host, target_port,
                                          ssl.ClientContextFactory())
        else:
            endpoint = TCP4ClientEndpoint(reactor, target_host, target_port)
    return endpoint
Exemple #13
0
    def connect(self, protocolfactory):
        last_error = None
        kwargs = dict()
        if self.socks_username is not None and self.socks_password is not None:
            kwargs['methods'] = dict(
                login=(self.socks_username, self.socks_password),
            )
        if self.socks_endpoint is not None:
            args = (self.host, self.port, self.socks_endpoint)
            socks_ep = SOCKS5ClientEndpoint(*args, **kwargs)
            if self.tls:
                context = optionsForClientTLS(unicode(self.host))
                socks_ep = TLSWrapClientEndpoint(context, socks_ep)
            proto = yield socks_ep.connect(protocolfactory)
            defer.returnValue(proto)
        else:
            for socks_port in self._socks_port_iter:
                tor_ep = TCP4ClientEndpoint(
                    reactor,
                    "127.0.0.1",
                    socks_port,
                )
                args = (self.host, self.port, tor_ep)
                socks_ep = SOCKS5ClientEndpoint(*args, **kwargs)
                if self.tls:
                    # XXX only twisted 14+
                    context = optionsForClientTLS(unicode(self.host))
                    socks_ep = TLSWrapClientEndpoint(context, socks_ep)

                try:
                    proto = yield socks_ep.connect(protocolfactory)
                    defer.returnValue(proto)

                except error.ConnectError as e0:
                    last_error = e0
            if last_error is not None:
                raise last_error
Exemple #14
0
def run(nodeScanList, scanDate, exitRouteList, configDic, dictionarylookup):
	internalConn = db2.dbConnectz(configDic["db_host"],configDic["db_user"],configDic["db_pass"],configDic["db_name"])		
	try:
		ipPre=checkCurrentIP(configDic["torportsock"])
		print "Scanning with ip", ipPre
	except Exception as e:
		print "[!!!] Error in checkdns ip ", e
		sys.exit(-1)

	du=[]
	dd=[]
	i=0
	TCPPoint = TCP4ClientEndpoint(reactor, "127.0.0.1", configDic["torportsock"])
	print "..:: Starting ::.."
	for dst_addr in nodeScanList:
		#tmp_string="Now I'm scanning:  "+dst_addr[1]+ ":"+dst_addr[2]+"\n"
		#sys.stdout.write(str(tmp_string))
		SOCKSPoint = SOCKS5ClientEndpoint(dst_addr[1], int(dst_addr[2]), TCPPoint)					
		f = SScanFactory(dst_addr[0], dst_addr[1], dst_addr[2], scanDate, internalConn)
		dd.append(f)
		du.append(SOCKSPoint.connect(f))
		du[i].addErrback(_gotError, f)
		i=i+1
	reactor.callLater(int(configDic['scantimeout']), reactor.stop)
	reactor.run() #installSignalHandlers=0

	ipPost=checkCurrentIP(configDic["torportsock"])
	
	# if i haven't changed ip
	if (ipPost==ipPre):
		print "- IP isn't changed during the scan: OK!"
		realIpPost=ipPost.pop()
		if (realIpPost in exitRouteList):
			print "- The ip we used is in the selected list, OK!"
			fingerprintExit=dictionarylookup[realIpPost]
			print "-> Saving data to db"
			for i in dd:
				i.currentlyExit=fingerprintExit
				db2.insertData(internalConn, i)
			return #ok
		else:
			print "[!] The ip is not in the exitrouteList!!!"
			return
	else:
		print "The exit route has changed during scan. Throw up all the results"
		sys.exit()
Exemple #15
0
 def _getEndpoint(self, scheme, host, port):
     kwargs = {}
     if self._connectTimeout is not None:
         kwargs['timeout'] = self._connectTimeout
     kwargs['bindAddress'] = self._bindAddress
     if scheme == 'http':
         return TCP4ClientEndpoint(self._reactor, host, port, **kwargs)
     elif scheme == 'shttp' or scheme == 'httpo':
         socksProxy = TCP4ClientEndpoint(self._reactor, self._sockshost,
                                         self._socksport)
         return SOCKS5ClientEndpoint(host, port, socksProxy)
     elif scheme == 'https':
         return SSL4ClientEndpoint(self._reactor, host, port,
                                   self._wrapContextFactory(host, port),
                                   **kwargs)
     else:
         raise SchemeNotSupported("Unsupported scheme: %r" % (scheme, ))
    def alter_do_connections(self,tunnel_route,port,torused):
        linking_list = [None]*(len(tunnel_route)+1)

        for idx in range(len(linking_list)):
            if idx==0:
                if torused:
                    linking_list[idx] = clientFromString(reactor, "unix:/var/run/tor/control")
                else:
                    linking_list[idx] = TCP4ClientEndpoint(reactor, '127.0.0.1', 8080)

            else:
                proxy_data = tunnel_route[idx-1]
                linking_list[idx] = SOCKS5ClientEndpoint( proxy_data.ip_address, proxy_data.port, linking_list[idx-1], methods={'login': (str(proxy_data.user), str(proxy_data.password))})
                #SOCKS4ClientEndpoint(proxy_data.ip_address, proxy_data.port, linking_list[idx-1])
 
        if torused:
            tor = yield txtorcon.connect(reactor,linking_list[-1:][0])
            config = yield tor.get_config()
            config.SOCKSPort = [str(port)]
            yield config.save()

        else:
            linking_list[-1:][0].connect(ProxyFactory('127.0.0.1',port))
Exemple #17
0
def sendmail(to_address, subject, body):
    """
    Sends an email using SMTPS/SMTP+TLS and torify the connection

    @param to_address: the to address field of the email
    @param subject: the mail subject
    @param body: the mail body
    @param event: the event description, needed to keep track of failure/success
    """
    try:
        if GLSettings.disable_mail_notification:
            return defer.succeed(None)

        if to_address == "":
            return

        result_deferred = defer.Deferred()

        def errback(reason, *args, **kwargs):
            # TODO: here it should be written a complete debugging of the possible
            #       errors by writing clear log lines in relation to all the stack:
            #       e.g. it should debugged all errors related to: TCP/SOCKS/TLS/SSL/SMTP/SFIGA
            if isinstance(reason, Failure):
                log.err("SMTP connection failed (Exception: %s)" %
                        reason.value)
                log.debug(reason)

            return result_deferred.errback(reason)

        authentication_username = GLSettings.memory_copy.notif_username
        authentication_password = GLSettings.memory_copy.notif_password
        from_address = GLSettings.memory_copy.notif_source_email
        smtp_host = GLSettings.memory_copy.notif_server
        smtp_port = GLSettings.memory_copy.notif_port
        security = GLSettings.memory_copy.notif_security

        message = MIME_mail_build(GLSettings.memory_copy.notif_source_name,
                                  GLSettings.memory_copy.notif_source_email,
                                  to_address, to_address, subject, body)

        log.debug('Sending email to %s using SMTP server [%s:%d] [%s]' %
                  (to_address, smtp_host, smtp_port, security))

        if security != "PLAIN":
            context_factory = GLClientContextFactory()
        else:
            context_factory = ClientContextFactory()

        esmtp_deferred = defer.Deferred()
        esmtp_deferred.addCallbacks(result_deferred.callback, errback)

        condition = True
        if authentication_username == "" or authentication_password == "":
            condition = False

        alter_condition = False
        if security == "TLS":
            alter_condition = True

        factory = ESMTPSenderFactory(authentication_username.encode('utf-8'),
                                     authentication_password.encode('utf-8'),
                                     from_address,
                                     to_address,
                                     message,
                                     esmtp_deferred,
                                     contextFactory=context_factory,
                                     requireAuthentication=condition,
                                     requireTransportSecurity=alter_condition,
                                     retries=0,
                                     timeout=GLSettings.mail_timeout)

        if security == "SSL":
            factory = tls.TLSMemoryBIOFactory(context_factory, True, factory)

        if GLSettings.testing:
            #  Hooking the test down to here is a trick to be able to test all the above code :)
            return defer.succeed(None)

        if security != "PLAIN":
            if not GLSettings.disable_mail_torification:
                socksProxy = TCP4ClientEndpoint(
                    reactor,
                    GLSettings.socks_host,
                    GLSettings.socks_port,
                    timeout=GLSettings.mail_timeout)
                endpoint = SOCKS5ClientEndpoint(smtp_host.encode('utf-8'),
                                                smtp_port, socksProxy)
            else:
                endpoint = TCP4ClientEndpoint(reactor,
                                              smtp_host.encode('utf-8'),
                                              smtp_port,
                                              timeout=GLSettings.mail_timeout)

            d = endpoint.connect(factory)
            d.addErrback(errback)
        else:
            reactor.connectTCP(smtp_host, smtp_port, factory)

        return result_deferred

    except Exception as excep:
        # we strongly need to avoid raising exception inside email logic to avoid chained errors
        log.err("Unexpected exception in sendmail: %s" % str(excep))
        return defer.fail()
Exemple #18
0
def sendmail(authentication_username,
             authentication_password,
             from_address,
             to_address,
             message_file,
             smtp_host,
             smtp_port,
             security,
             event=None):
    """
    Sends an email using SSLv3 over SMTP

    @param authentication_username: account username
    @param authentication_secret: account password
    @param from_address: the from address field of the email
    @param to_address: the to address field of the email
    @param message_file: the message content its a StringIO
    @param smtp_host: the smtp host
    @param smtp_port: the smtp port
    @param security: may need to be STRING, here is converted at start
    @param event: the event description, needed to keep track of failure/success
    """
    def printError(reason, event):

        # XXX is catch a wrong TCP port, but not wrong SSL protocol, here
        if event:
            log.err("** failed notification within event %s" % event.type)
        # TODO Enhance with retry
        # TODO specify a ticket - make event an Obj instead of a namedtuple
        # TODO It's defined in plugin/base.py

        if isinstance(reason, Failure):
            log.err("Failed to contact %s:%d (Sock Error %s)" %
                    (smtp_host, smtp_port, reason.type))
            log.debug(reason)

    def handle_error(reason, *args, **kwargs):
        # XXX event is not an argument here ?
        printError(reason, event)
        return result_deferred.errback(reason)

    def protocolConnectionLost(self, reason=protocol.connectionDone):
        """We are no longer connected"""
        if isinstance(reason, Failure):
            if not isinstance(reason.value, error.ConnectionDone):
                log.err("Failed to contact %s:%d (ConnectionLost Error %s)" %
                        (smtp_host, smtp_port, reason.type))
                log.debug(reason)

        self.setTimeout(None)
        self.mailFile = None

    def sendError(self, exc):
        if exc.code and exc.resp:
            error = re.match(r'^([0-9\.]+) ', exc.resp)
            error_str = ""
            if error:
                error_str = error.group(1)
                key = str(exc.code) + " " + error.group(1)
                if key in smtp_errors:
                    error_str += " " + smtp_errors[key]

            log.err("Failed to contact %s:%d (SMTP Error: %.3d %s)" %
                    (smtp_host, smtp_port, exc.code, error_str))
            log.debug("Failed to contact %s:%d (SMTP Error: %.3d %s)" %
                      (smtp_host, smtp_port, exc.code, exc.resp))
        SMTPClient.sendError(self, exc)

    try:
        security = str(security)
        result_deferred = Deferred()
        context_factory = ClientContextFactory()
        context_factory.method = SSL.SSLv3_METHOD

        if security != "SSL":
            requireTransportSecurity = True
        else:
            requireTransportSecurity = False

        esmtp_deferred = Deferred()
        esmtp_deferred.addErrback(handle_error, event)
        esmtp_deferred.addCallback(result_deferred.callback)

        factory = ESMTPSenderFactory(
            authentication_username,
            authentication_password,
            from_address,
            to_address,
            message_file,
            esmtp_deferred,
            contextFactory=context_factory,
            requireAuthentication=(authentication_username
                                   and authentication_password),
            requireTransportSecurity=requireTransportSecurity)

        factory.protocol.sendError = sendError
        factory.protocol.connectionLost = protocolConnectionLost

        if security == "SSL":
            factory = tls.TLSMemoryBIOFactory(context_factory, True, factory)

        if GLSetting.tor_socks_enable:
            socksProxy = TCP4ClientEndpoint(reactor, GLSetting.socks_host,
                                            GLSetting.socks_port)
            endpoint = SOCKS5ClientEndpoint(smtp_host.encode('utf-8'),
                                            smtp_port, socksProxy)
        else:
            endpoint = TCP4ClientEndpoint(reactor, smtp_host, smtp_port)

        d = endpoint.connect(factory)
        d.addErrback(handle_error, event)

    except Exception as excep:
        # we strongly need to avoid raising exception inside email logic to avoid chained errors
        log.err("unexpected exception in sendmail: %s" % str(excep))
        return fail()

    return result_deferred
Exemple #19
0
def sendmail(to_address, subject, body):
    """
    Sends an email using SMTPS/SMTP+TLS and torify the connection

    @param to_address: the to address field of the email
    @param subject: the mail subject
    @param body: the mail body
    @param event: the event description, needed to keep track of failure/success
    """
    try:
        if not to_address:
            return

        result_deferred = defer.Deferred()

        def errback(reason, *args, **kwargs):
            # TODO: here it should be written a complete debugging of the possible
            #       errors by writing clear log lines in relation to all the stack:
            #       e.g. it should debugged all errors related to: TCP/SOCKS/TLS/SSL/SMTP/SFIGA
            if isinstance(reason, Failure):
                log.err("SMTP connection failed (Exception: %s)", reason.value)
                log.debug(reason)

            return result_deferred.errback(reason)

        result_deferred.addErrback(errback)

        authentication_username = State.tenant_cache[1].notif.username
        authentication_password = State.tenant_cache[1].private.smtp_password
        from_address = State.tenant_cache[1].notif.source_email
        smtp_host = State.tenant_cache[1].notif.server
        smtp_port = State.tenant_cache[1].notif.port
        security = State.tenant_cache[1].notif.security

        message = MIME_mail_build(State.tenant_cache[1].notif.source_name,
                                  State.tenant_cache[1].notif.source_email,
                                  to_address, to_address, subject, body)

        log.debug('Sending email to %s using SMTP server [%s:%d] [%s]',
                  to_address, smtp_host, smtp_port, security)

        context_factory = TLSClientContextFactory()

        factory = ESMTPSenderFactory(
            authentication_username.encode('utf-8'),
            authentication_password.encode('utf-8'),
            from_address,
            to_address,
            message,
            result_deferred,
            contextFactory=context_factory,
            requireAuthentication=True,
            requireTransportSecurity=(security != 'SSL'),
            retries=0,
            timeout=Settings.mail_timeout)

        if security == "SSL":
            factory = tls.TLSMemoryBIOFactory(context_factory, True, factory)

        if State.tenant_cache[1].anonymize_outgoing_connections:
            socksProxy = TCP4ClientEndpoint(reactor,
                                            Settings.socks_host,
                                            Settings.socks_port,
                                            timeout=Settings.mail_timeout)
            endpoint = SOCKS5ClientEndpoint(smtp_host.encode('utf-8'),
                                            smtp_port, socksProxy)
        else:
            endpoint = TCP4ClientEndpoint(reactor,
                                          smtp_host.encode('utf-8'),
                                          smtp_port,
                                          timeout=Settings.mail_timeout)

        if Settings.testing:
            #  Hooking the test down to here is a trick to be able to test all the above code :)
            return defer.succeed(None)

        d = endpoint.connect(factory)
        d.addErrback(errback)

        return result_deferred

    except Exception as excep:
        # we strongly need to avoid raising exception inside email logic to avoid chained errors
        log.err("Unexpected exception in sendmail: %s", str(excep))
        return defer.fail()
Exemple #20
0
        print "Joined %s." % (channel, )

    def privmsg(self, user, channel, msg):
        print msg
        if msg == "discover":
            self.msg(channel, "network discover code goes here")
        elif msg == "attack":
            self.msg(channel, "attack code here")


class MomBotFactory(protocol.ClientFactory):
    protocol = MomBot

    def __init__(self, channel, nickname):
        self.channel = channel
        self.nickname = nickname

    def clientConnectionLost(self, connector, reason):
        print "Lost connection (%s), reconnecting." % (reason, )
        connector.connect()

    def clientConnectionFailed(self, connector, reason):
        print "Could not connect: %s" % (reason, )


clientName = 'bot' + str(random.randrange(1, 1000000))
puttyEndPoint = TCP4ClientEndpoint(reactor, '127.0.0.1', 9050)
point = SOCKS5ClientEndpoint('p6ncbp3wozslmdlc.onion', 6667, puttyEndPoint)
d = point.connect(MomBotFactory('#' + 'aa', clientName))
reactor.run()
Exemple #21
0
def sendmail(to_address, subject, body):
    """
    Send an email using SMTPS/SMTP+TLS and maybe torify the connection.

    @param to_address: the 'To:' field of the email
    @param subject: the mail subject
    @param body: the mail body

    @return: a {Deferred} that returns a success {bool} if the message was passed
             to the server.
    """
    try:
        if not to_address:
            return

        authentication_username = State.tenant_cache[1].notif.username
        authentication_password = State.tenant_cache[1].private.smtp_password
        from_address = State.tenant_cache[1].notif.source_email
        smtp_host = State.tenant_cache[1].notif.server
        smtp_port = State.tenant_cache[1].notif.port
        security = State.tenant_cache[1].notif.security

        message = MIME_mail_build(State.tenant_cache[1].notif.source_name,
                                  State.tenant_cache[1].notif.source_email,
                                  to_address, to_address, subject, body)

        log.debug('Sending email to %s using SMTP server [%s:%d] [%s]',
                  to_address, smtp_host, smtp_port, security)

        context_factory = TLSClientContextFactory()

        smtp_deferred = defer.Deferred()

        factory = ESMTPSenderFactory(
            authentication_username.encode('utf-8'),
            authentication_password.encode('utf-8'),
            from_address,
            to_address,
            message,
            smtp_deferred,
            contextFactory=context_factory,
            requireAuthentication=True,
            requireTransportSecurity=(security != 'SSL'),
            retries=0,
            timeout=Settings.mail_timeout)

        if security == "SSL":
            factory = tls.TLSMemoryBIOFactory(context_factory, True, factory)

        if State.tenant_cache[1].anonymize_outgoing_connections:
            socksProxy = TCP4ClientEndpoint(reactor,
                                            Settings.socks_host,
                                            Settings.socks_port,
                                            timeout=Settings.mail_timeout)
            endpoint = SOCKS5ClientEndpoint(smtp_host.encode('utf-8'),
                                            smtp_port, socksProxy)
        else:
            endpoint = TCP4ClientEndpoint(reactor,
                                          smtp_host.encode('utf-8'),
                                          smtp_port,
                                          timeout=Settings.mail_timeout)

        if Settings.testing:
            # during unit testing do not try to send the mail
            return defer.succeed(True)

        conn_deferred = endpoint.connect(factory)

        final = defer.DeferredList([conn_deferred, smtp_deferred],
                                   fireOnOneErrback=True,
                                   consumeErrors=True)

        def failure_cb(failure):
            """
            @param failure {Failure {twisted.internet.FirstError {Failure}}}
            """
            log.err("SMTP connection failed (Exception: %s)",
                    failure.value.subFailure.value)
            log.debug(failure)
            return False

        def success_cb(results):
            """
            @param results {list of (success, return_val) tuples}
            """
            return True

        final.addCallback(success_cb)
        final.addErrback(failure_cb)

        return final

    except Exception as excep:
        # avoids raising an exception inside email logic to avoid chained errors
        log.err("Unexpected exception in sendmail: %s", str(excep))
        return defer.succeed(False)
Exemple #22
0
def sendmail(authentication_username,
             authentication_password,
             from_address,
             to_address,
             message_file,
             smtp_host,
             smtp_port,
             security,
             event=None):
    """
    Sends an email using SMTPS/SMTP+TLS and torify the connection

    @param authentication_username: account username
    @param authentication_password: account password
    @param from_address: the from address field of the email
    @param to_address: the to address field of the email
    @param message_file: the message content its a StringIO
    @param smtp_host: the smtp host
    @param smtp_port: the smtp port
    @param security: may need to be STRING, here is converted at start
    @param event: the event description, needed to keep track of failure/success
    """

    notif_retries = 2
    notif_timeout = 10

    def printError(method, reason, event):
        if event:
            log.err("** failed notification within event %s" % event.type)

        if isinstance(reason, Failure):
            log.err(
                "Failed to connect to %s:%d (Sock Error: %s) (Method: %s)" %
                (smtp_host, smtp_port, reason.value, method))
            log.debug(reason)

    def esmtp_errback(reason, *args, **kwargs):
        printError("ESMTP", reason, event)
        return result_deferred.errback(reason)

    def socks_errback(reason, *args, **kwargs):
        printError("SOCKS5", reason, event)
        return result_deferred.errback(reason)

    def tcp4_errback(reason, *args, **kwargs):
        printError("TCP4", reason, event)
        return result_deferred.errback(reason)

    def result_errback(reason, *args, **kwargs):
        """To not report an error as unexpected in the log files"""
        return True

    def esmtp_sendError(self, exc):
        if exc.code and exc.resp:
            error_str = ""

            error = re.match(r'^([0-9\.]+) ', exc.resp)
            if error:
                key = str(exc.code) + " " + error.group(1)
                if key in smtp_errors:
                    error_str += " " + smtp_errors[key]

            verb = '[unknown]'
            if 'authentication' in exc.resp:
                verb = 'autenticate'
            if 'not support secure' in exc.resp:
                verb = 'negotiate TLS'

            log.err("Failed to %s to %s:%d (SMTP Code: %.3d) (%s)" %
                    (verb, smtp_host, smtp_port, exc.code, error_str))

        SMTPClient.sendError(self, exc)

    def esmtp_connectionLost(self, reason=protocol.connectionDone):
        """We are no longer connected"""
        if isinstance(reason, Failure):
            if not isinstance(reason.value, error.ConnectionDone):
                verb = 'unknown_verb'
                if 'OpenSSL' in str(reason.type):
                    verb = 'negotiate SSL'

                log.err("Failed to %s to %s:%d (%s)" %
                        (verb, smtp_host, smtp_port, reason.type))
                log.debug(reason)

        self.setTimeout(None)
        self.mailFile = None

    # TODO: validation?
    if from_address == '' or to_address == '':
        log.err(
            "Failed to init sendmail to %s:%s (Invalid from/to addresses)" %
            (from_address, to_address))
        return

    if security != "SSL" and security != "disabled":
        requireTransportSecurity = True
    else:
        requireTransportSecurity = False

    try:
        security = str(security)
        result_deferred = Deferred()
        result_deferred.addErrback(result_errback, event)

        context_factory = ClientContextFactory()

        # evilaliv3:
        #   this is the same solution I applied to tor2web:
        #     as discussed on https://trac.torproject.org/projects/tor/ticket/11598
        #     there is no way of enabling all TLS methods excluding SSL.
        #     the problem lies in the fact that SSL.TLSv1_METHOD | SSL.TLSv1_1_METHOD | SSL.TLSv1_2_METHOD
        #     is denied by OpenSSL.
        #
        #     As spotted by nickm the only good solution right now is to enable SSL.SSLv23_METHOD then explicitly
        #     use options: SSL_OP_NO_SSLv2 and SSL_OP_NO_SSLv3
        #
        #     This trick make openssl consider valid all TLS methods.
        #
        context_factory.method = SSL.SSLv23_METHOD

        esmtp_deferred = Deferred()
        esmtp_deferred.addErrback(esmtp_errback, event)
        esmtp_deferred.addCallback(result_deferred.callback)
    except Exception as excep:
        log.err(
            "Error in Twisted objects init - unexpected exception in sendmail: %s"
            % str(excep))
        return fail()

    try:
        factory = ESMTPSenderFactory(
            authentication_username,
            authentication_password,
            from_address,
            to_address,
            message_file,
            esmtp_deferred,
            contextFactory=context_factory,
            requireAuthentication=(authentication_username
                                   and authentication_password),
            requireTransportSecurity=requireTransportSecurity,
            retries=notif_retries,
            timeout=notif_timeout)

        factory.protocol.sendError = esmtp_sendError
        factory.protocol.connectionLost = esmtp_connectionLost

        if security == "SSL":
            factory = tls.TLSMemoryBIOFactory(context_factory, True, factory)

    except Exception as excep:
        log.err(
            "Error in factory init - unexpected exception in sendmail: %s" %
            str(excep))
        return fail()

    try:
        if not GLSettings.disable_mail_torification and GLSettings.memory_copy.notif_uses_tor:
            socksProxy = TCP4ClientEndpoint(reactor,
                                            GLSettings.socks_host,
                                            GLSettings.socks_port,
                                            timeout=notif_timeout)
            endpoint = SOCKS5ClientEndpoint(smtp_host.encode('utf-8'),
                                            smtp_port, socksProxy)
            d = endpoint.connect(factory)
            d.addErrback(socks_errback, event)
        else:
            endpoint = TCP4ClientEndpoint(reactor,
                                          smtp_host,
                                          smtp_port,
                                          timeout=notif_timeout)
            d = endpoint.connect(factory)
            d.addErrback(tcp4_errback, event)
    except Exception as excep:
        # we strongly need to avoid raising exception inside email logic to avoid chained errors
        log.err("unexpected exception in sendmail: %s" % str(excep))
        return fail()

    return result_deferred
Exemple #23
0
def sendmail(tid,
             username,
             password,
             smtp_host,
             smtp_port,
             security,
             from_name,
             from_address,
             to_address,
             subject,
             body,
             anonymize=True,
             socks_host='127.0.0.1',
             socks_port=9050):
    """
    Send an email using SMTPS/SMTP+TLS and maybe torify the connection.

    @param to_address: the 'To:' field of the email
    @param subject: the mail subject
    @param body: the mail body

    @return: a {Deferred} that returns a success {bool} if the message was passed
             to the server.
    """
    try:
        timeout = 30

        message = MIME_mail_build(from_name, from_address, to_address,
                                  to_address, subject, body)

        log.debug('Sending email to %s using SMTP server [%s:%d] [%s]',
                  to_address,
                  smtp_host,
                  smtp_port,
                  security,
                  tid=tid)

        context_factory = TLSClientContextFactory()

        smtp_deferred = defer.Deferred()

        factory = ESMTPSenderFactory(
            username.encode('utf-8'),
            password.encode('utf-8'),
            from_address,
            to_address,
            message,
            smtp_deferred,
            contextFactory=context_factory,
            requireAuthentication=True,
            requireTransportSecurity=(security != 'SSL'),
            retries=0,
            timeout=timeout)

        if security == "SSL":
            factory = tls.TLSMemoryBIOFactory(context_factory, True, factory)

        if anonymize:
            socksProxy = TCP4ClientEndpoint(reactor,
                                            socks_host,
                                            socks_port,
                                            timeout=timeout)
            endpoint = SOCKS5ClientEndpoint(smtp_host.encode('utf-8'),
                                            smtp_port, socksProxy)
        else:
            endpoint = TCP4ClientEndpoint(reactor,
                                          smtp_host.encode('utf-8'),
                                          smtp_port,
                                          timeout=timeout)

        conn_deferred = endpoint.connect(factory)

        final = defer.DeferredList([conn_deferred, smtp_deferred],
                                   fireOnOneErrback=True,
                                   consumeErrors=True)

        def failure_cb(failure):
            """
            @param failure {Failure {twisted.internet.FirstError {Failure}}}
            """
            log.err("SMTP connection failed (Exception: %s)",
                    failure.value.subFailure.value,
                    tid=tid)
            log.debug(failure)
            return False

        def success_cb(results):
            """
            @param results {list of (success, return_val) tuples}
            """
            return True

        final.addCallback(success_cb)
        final.addErrback(failure_cb)

        return final

    except Exception as excep:
        # avoids raising an exception inside email logic to avoid chained errors
        log.err("Unexpected exception in sendmail: %s", str(excep), tid=tid)
        return defer.succeed(False)