Ejemplo n.º 1
0
def main():
    hostname = raw_input("IMAP4 Server Hostname: ")
    port = raw_input("IMAP4 Server Port (the default is 143, 993 uses SSL): ")

    # Usernames are bytes.
    username = raw_input("IMAP4 Username: "******"ascii")

    # Passwords are bytes.
    password = util.getPassword("IMAP4 Password: "******"ascii")

    onConn = (defer.Deferred().addCallback(
        cbServerGreeting, username,
        password).addErrback(ebConnection).addBoth(cbClose))

    factory = SimpleIMAP4ClientFactory(username, onConn)

    if not port:
        port = 143
    else:
        port = int(port)

    from twisted.internet import reactor

    endpoint = endpoints.HostnameEndpoint(reactor, hostname, port)

    if port == 993:
        if isinstance(hostname, bytes):
            # This is python 2
            hostname = hostname.decode("utf-8")

        contextFactory = ssl.optionsForClientTLS(hostname=hostname, )
        endpoint = endpoints.wrapClientTLS(contextFactory, endpoint)

    endpoint.connect(factory)
    reactor.run()
Ejemplo n.º 2
0
def main():
    hostname = raw_input('IMAP4 Server Hostname: ')
    port = raw_input('IMAP4 Server Port (the default is 143, 993 uses SSL): ')
    username = raw_input('IMAP4 Username: '******'IMAP4 Password: '******'utf-8'))
        endpoint = endpoints.wrapClientTLS(contextFactory, endpoint)

    endpoint.connect(factory)
    reactor.run()
Ejemplo n.º 3
0
    def start(self):
        log.msg("WARNING: Beta version of new hpfeeds enabled. This will become hpfeeds in a future release.")

        if CONFIG.has_option('output_hpfeeds', 'channel'):
            self.channel = CONFIG.get('output_hpfeeds', 'channel')

        if CONFIG.has_option('output_hpfeeds', 'endpoint'):
            endpoint = CONFIG.get('output_hpfeeds', 'endpoint')
        else:
            server = CONFIG.get('output_hpfeeds', 'server')
            port = CONFIG.getint('output_hpfeeds', 'port')

            if CONFIG.has_option('output_hpfeeds', 'tlscert'):
                with open(CONFIG.get('output_hpfeeds', 'tlscert')) as fp:
                    authority = ssl.Certificate.loadPEM(fp.read())
                options = ssl.optionsForClientTLS(server, authority)
                endpoint = endpoints.SSL4ClientEndpoint(reactor, server, port, options)
            else:
                endpoint = endpoints.HostnameEndpoint(reactor, server, port)

        ident = CONFIG.get('output_hpfeeds', 'identifier')
        secret = CONFIG.get('output_hpfeeds', 'secret')

        self.meta = {}

        self.client = ClientSessionService(endpoint, ident, secret)
        self.client.startService()
Ejemplo n.º 4
0
    def connect(self):
        """Connect and authenticate with the IMAP server
        """
        if self.connecting:
            defer.returnValue(None)

        self.connecting = True

        endpoint = endpoints.HostnameEndpoint(reactor, self.host, self.port)

        if self.ssl:
            contextFactory = ssl.optionsForClientTLS(
                hostname=self.host.decode('utf-8'))
            endpoint = endpoints.wrapClientTLS(contextFactory, endpoint)

        de = defer.Deferred()
        factory = IMAP4ClientFactory(self.user, de)
        factory.debug = self.debug

        yield endpoint.connect(factory)
        self.proto = yield de

        yield self.proto.authenticate(self.password)

        self.connected = True
        self.connecting = False
Ejemplo n.º 5
0
    def _get_new(self):
        """
        Get new mails from IMAP server. This will define the `main loop` of
        the IMAP service.
        """
        onConn = defer.Deferred().addCallback(
            self.cb_server_greeting
        ).addErrback(
            self.eb_server_greeting
        )

        # Connect with endpoints. Connect and disconnect from time to time
        # (defined by the service's interval) instead of establishing a
        # persistent connection
        factory = SimpleIMAP4ClientFactory(self.username, onConn)

        from twisted.internet import reactor
        endpoint = endpoints.HostnameEndpoint(reactor, self.host, self.port)

        contextFactory = ssl.optionsForClientTLS(
            hostname=self.host.decode('utf-8')
        )
        endpoint = endpoints.wrapClientTLS(contextFactory, endpoint)

        log.debug("IMAP:: Connecting to Google's IMAP servers.")
        endpoint.connect(factory)
Ejemplo n.º 6
0
    def start(self):
        log.msg(
            "WARNING: Beta version of new hpfeeds enabled. This will become hpfeeds in a future release."
        )

        if CowrieConfig.has_option("output_hpfeeds3", "channel"):
            self.channel = CowrieConfig.get("output_hpfeeds3", "channel")

        if CowrieConfig.has_option("output_hpfeeds3", "endpoint"):
            endpoint = CowrieConfig.get("output_hpfeeds3", "endpoint")
        else:
            server = CowrieConfig.get("output_hpfeeds3", "server")
            port = CowrieConfig.getint("output_hpfeeds3", "port")

            if CowrieConfig.has_option("output_hpfeeds3", "tlscert"):
                with open(CowrieConfig.get("output_hpfeeds3",
                                           "tlscert")) as fp:
                    authority = ssl.Certificate.loadPEM(fp.read())
                options = ssl.optionsForClientTLS(server, authority)
                endpoint = endpoints.SSL4ClientEndpoint(
                    reactor, server, port, options)
            else:
                endpoint = endpoints.HostnameEndpoint(reactor, server, port)

        ident = CowrieConfig.get("output_hpfeeds3", "identifier")
        secret = CowrieConfig.get("output_hpfeeds3", "secret")

        self.meta = {}

        self.client = ClientSessionService(endpoint, ident, secret)
        self.client.startService()
Ejemplo n.º 7
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 = NEW_STYLE_HINT_RE.search(hint)
     if not mo:
         raise InvalidHintError("unrecognized TCP hint")
     host, port = mo.group(1), int(mo.group(2))
     host = host.lstrip("[").rstrip("]")
     return endpoints.HostnameEndpoint(reactor, host, port), host
Ejemplo n.º 8
0
 def _make_endpoint(self, url):
     p = urlparse(url)
     tls = (p.scheme == "wss")
     port = p.port or (443 if tls else 80)
     if self._tor:
         return self._tor.stream_via(p.hostname, port, tls=tls)
     if tls:
         return endpoints.clientFromString(self._reactor,
                                           "tls:%s:%s" % (p.hostname, port))
     return endpoints.HostnameEndpoint(self._reactor, p.hostname, port)
Ejemplo n.º 9
0
def main(reactor):
    factory = protocol.Factory.forProtocol(StartTLSClient)
    certData = getModule(__name__).filePath.sibling("server.pem").getContent()
    factory.options = ssl.optionsForClientTLS(
        "example.com", ssl.PrivateCertificate.loadPEM(certData))
    endpoint = endpoints.HostnameEndpoint(reactor, "localhost", 8000)
    startTLSClient = yield endpoint.connect(factory)

    done = defer.Deferred()
    startTLSClient.connectionLost = lambda reason: done.callback(None)
    yield done
Ejemplo n.º 10
0
 def _endpoint_from_hint_obj(self, hint):
     if self._tor_manager:
         if isinstance(hint, (DirectTCPV1Hint, TorTCPV1Hint)):
             # our TorManager will return None for non-public IPv4
             # addresses and any IPv6 address
             return self._tor_manager.get_endpoint_for(
                 hint.hostname, hint.port)
         return None
     if isinstance(hint, DirectTCPV1Hint):
         return endpoints.HostnameEndpoint(self._reactor, hint.hostname,
                                           hint.port)
     return None
Ejemplo n.º 11
0
def _endpoint_from_config(reactor, factory, transport_config, options):
    # XXX might want some Crossbar code here? e.g. if we allow
    # "transport_config" to be a dict etc.

    # ... passing in the Factory is weird, but that's what parses all
    # the options and the URL currently

    if factory.isSecure:
        # create default client SSL context factory when none given
        from twisted.internet import ssl
        context_factory = ssl.optionsForClientTLS(factory.host)

    if factory.proxy is not None:
        factory.contextFactory = context_factory
        endpoint = endpoints.HostnameEndpoint(
            reactor,
            factory.proxy['host'],
            factory.proxy['port'],
            # timeout,  option?
        )
    else:
        if factory.isSecure:
            from twisted.internet import ssl
            endpoint = endpoints.SSL4ClientEndpoint(
                reactor,
                factory.host,
                factory.port,
                context_factory,
                # timeout,  option?
            )
        else:
            endpoint = endpoints.HostnameEndpoint(  # XXX right? not TCP4ClientEndpoint
                reactor,
                factory.host,
                factory.port,
                # timeout,  option?
                # attemptDelay,  option?
            )
    return endpoint
Ejemplo n.º 12
0
 def _endpoint_from_hint_obj(self, hint):
     if self._tor:
         if isinstance(hint, (DirectTCPV1Hint, TorTCPV1Hint)):
             # this Tor object will throw ValueError for non-public IPv4
             # addresses and any IPv6 address
             try:
                 return self._tor.stream_via(hint.hostname, hint.port)
             except ValueError:
                 return None
         return None
     if isinstance(hint, DirectTCPV1Hint):
         return endpoints.HostnameEndpoint(self._reactor,
                                           hint.hostname, hint.port)
     return None
Ejemplo n.º 13
0
 def _endpoint_from_hint(self, hint):
     # TODO: use parse_hint_tcp
     if ":" not in hint:
         return None
     pieces = hint.split(":")
     hint_type = hint.split(":")[0]
     if hint_type == "tor" and self._tor_manager:
         return self._tor_manager.get_endpoint_for(pieces[1], int(pieces[2]))
     if hint_type != "tcp":
         return None
     pieces = hint.split(":")
     if self._tor_manager:
         # our TorManager will return None for non-public IPv4 addresses
         # and any IPv6 address
         return self._tor_manager.get_endpoint_for(pieces[1], int(pieces[2]))
     return endpoints.HostnameEndpoint(self._reactor, pieces[1],
                                       int(pieces[2]))
Ejemplo n.º 14
0
def main():
    hostname = 'imap.126.com'
    port = 143

    username = '******'.encode('ascii')
    password = '******'.encode('ascii')

    onConn = defer.Deferred().addCallback(
        cbServerGreeting, username,
        password).addErrback(ebConnection).addBoth(cbClose)

    factory = SimpleIMAP4ClientFactory(username, onConn)

    port = int(port)

    from twisted.internet import reactor

    endpoint = endpoints.HostnameEndpoint(reactor, hostname, port)

    endpoint.connect(factory)
    reactor.run()
Ejemplo n.º 15
0
    def start(self):
        self.channel = CONFIG.get('output_hpfeed',
                                  'channel',
                                  fallback='elasticpot')

        if CONFIG.has_option('output_hpfeed', 'endpoint'):
            endpoint = CONFIG.get('output_hpfeed', 'endpoint')
        else:
            server = CONFIG.get('output_hpfeed', 'server')
            port = CONFIG.getint('output_hpfeed', 'port')

            if CONFIG.has_option('output_hpfeed', 'tlscert'):
                with open(CONFIG.get('output_hpfeed', 'tlscert')) as fp:
                    authority = ssl.Certificate.loadPEM(fp.read())
                options = ssl.optionsForClientTLS(server, authority)
                endpoint = endpoints.SSL4ClientEndpoint(
                    reactor, server, port, options)
            else:
                endpoint = endpoints.HostnameEndpoint(reactor, server, port)

        try:
            self.tags = [
                tag.strip()
                for tag in CONFIG.get('output_hpfeed', 'tags').split(',')
            ]
        except Exception as e:
            self.tags = []

        ident = CONFIG.get('output_hpfeed', 'identifier')
        secret = CONFIG.get('output_hpfeed', 'secret')

        reported_ip = CONFIG.get('output_hpfeed', 'reported_ip')
        if reported_ip and reported_ip != '':
            self.reported_ip = reported_ip
        else:
            self.reported_ip = None

        self.client = ClientSessionService(endpoint, ident, secret)
        self.client.startService()
Ejemplo n.º 16
0
def makeService(config):
    # finger on port 79
    s = service.MultiService()
    f = FingerService(config["file"])
    h = strports.service("tcp:1079", IFingerFactory(f))
    h.setServiceParent(s)

    # website on port 8000
    r = resource.IResource(f)
    r.templateDirectory = config["templates"]
    site = server.Site(r)
    j = strports.service("tcp:8000", site)
    j.setServiceParent(s)

    # ssl on port 443
    #    if config.get('ssl'):
    #        k = strports.service(
    #            "ssl:port=443:certKey=cert.pem:privateKey=key.pem", site
    #        )
    #        k.setServiceParent(s)

    # irc fingerbot
    if "ircnick" in config:
        i = IIRCClientFactory(f)
        i.nickname = config["ircnick"]
        ircserver = config["ircserver"]
        b = internet.ClientService(
            endpoints.HostnameEndpoint(reactor, ircserver, 6667), i)
        b.setServiceParent(s)

    # Pespective Broker on port 8889
    if "pbport" in config:
        m = internet.StreamServerEndpointService(
            endpoints.TCP4ServerEndpoint(reactor, int(config["pbport"])),
            pb.PBServerFactory(IPerspectiveFinger(f)),
        )
        m.setServiceParent(s)

    return s
Ejemplo n.º 17
0
    def start(self):
        log.msg("WARNING: Beta version of new hpfeeds enabled. This will become hpfeeds in a future release.")

        if CowrieConfig().has_option('output_hpfeeds3', 'channel'):
            self.channel = CowrieConfig().get('output_hpfeeds3', 'channel')

        if CowrieConfig().has_option('output_hpfeeds3', 'endpoint'):
            endpoint = CowrieConfig().get('output_hpfeeds3', 'endpoint')
        else:
            server = CowrieConfig().get('output_hpfeeds3', 'server')
            port = CowrieConfig().getint('output_hpfeeds3', 'port')

            if CowrieConfig().has_option('output_hpfeeds3', 'tlscert'):
                with open(CowrieConfig().get('output_hpfeeds3', 'tlscert')) as fp:
                    authority = ssl.Certificate.loadPEM(fp.read())
                options = ssl.optionsForClientTLS(server, authority)
                endpoint = endpoints.SSL4ClientEndpoint(reactor, server, port, options)
            else:
                endpoint = endpoints.HostnameEndpoint(reactor, server, port)

        try:
            self.tags = [tag.strip() for tag in CowrieConfig().get('output_hpfeeds3', 'tags').split(',')]
        except Exception as e:
            self.tags = []

        if CowrieConfig().has_option('output_hpfeeds3', 'reported_ip'):
            self.reported_ip = CowrieConfig().get('output_hpfeeds3', 'reported_ip')
            if self.reported_ip == 'UNSET_REPORTED_IP':
                self.reported_ip = None

        ident = CowrieConfig().get('output_hpfeeds3', 'identifier')
        secret = CowrieConfig().get('output_hpfeeds3', 'secret')

        self.meta = {}

        self.client = ClientSessionService(endpoint, ident, secret)
        self.client.startService()
Ejemplo n.º 18
0
def sendMail(username, password, host, port, msg):
    """
    Send an email message using authenticated and encrypted SMTP.

    @param username: Username to use.
    @param password: Password to use.
    @param host: SMTP server's hostname or IP address.
    @param port: The port to connect to for SMTP.
    @param msg: Email to send.
    @type msg: L{email.message.Message}

    @return: A L{Deferred} that fires with the result of the email being
             sent.
    """
    resultDeferred = defer.Deferred()

    fp = StringIO(msg.as_string(unixfrom=True))

    senderFactory = ESMTPSenderFactory(username, password, msg.get("From"),
        msg.get("To"), fp, resultDeferred)

    endpoints.HostnameEndpoint(reactor, host, port).connect(senderFactory)

    return resultDeferred
Ejemplo n.º 19
0
 def _make_endpoint(self, hostname, port):
     if self._tor:
         # TODO: when we enable TLS, maybe add tls=True here
         return self._tor.stream_via(hostname, port)
     return endpoints.HostnameEndpoint(self._reactor, hostname, port)
Ejemplo n.º 20
0
                                        self.onFinish)
        protocol.factory = self
        return protocol

    def clientConnectionFailed(self, connector, reason):
        print('Connection failed.')


# TODO(breakds): And a more graceful (singal handling) way to terminate the program.
def clean_up(unused):
    from twisted.internet import reactor
    reactor.stop()
    print('All workd done!')


if __name__ == '__main__':
    # FIXME: Make these configurable
    hostname = 'mail.breakds.org'
    username = '******'.encode('ascii')
    pass_store_entry = 'mail.breakds.org/bds'
    port = 143

    from twisted.internet import reactor
    endpoint = endpoints.HostnameEndpoint(reactor, hostname, port)

    factory = ScannerRelayProtocolFactory(username,
                                          PassStoreFetcher(pass_store_entry),
                                          clean_up)
    endpoint.connect(factory)
    reactor.run()
Ejemplo n.º 21
0
 def _make_endpoint(self, hostname, port):
     if self._tor_manager:
         return self._tor_manager.get_endpoint_for(hostname, port)
     return endpoints.HostnameEndpoint(self._reactor, hostname, port)
Ejemplo n.º 22
0
    def __init__(
            self, parent=None, searchables=None, xmldir=None,
            network='lan', cloud_user=None, cloud_servers=[],
            logger=None, uid=None, messager=None):
        self.connected = False
        self.messager = messager
        self.app_paused = False
        self.fail_count = 0
        if not logger:
            self.log = Logger()
        else:
            self.log = logger
        self.log.debug('UPnP controller starts')
        self.xmldir = xmldir
        self.devices = {}
        self._services = {}
        self.parent = parent
#         self.amp = ControllerAmp(self)
        if uid:
            self.uuid = uid
        else:
            self.uuid = str(
                uuid.uuid5(
                    uuid.NAMESPACE_DNS,
                    socket.gethostname() + 'onDemand_Controller'))
        if searchables:
            for typ in searchables:
                self.searchables.update({typ[0]: typ[1]})
#                 print(self.searchables)
        else:
            self.searchables = {'upnp:rootdevice': self.log.debug}
        if network in ('lan', 'both'):
            self.log.debug('UPnP classic enabled')
            self.lan = True
            self.listener = ssdp.SSDP_Listener(self)
            self.mcast = internet.MulticastServer(  # @UndefinedVariable
                SSDP_PORT,
                self.listener,
                listenMultiple=True,
                interface=SSDP_ADDR_V4)
            self.mcast.setServiceParent(self)
            self.ssdp_cli = ssdp.SSDP_Client(
                self, get_default_v4_address(), device=False)
            self.ucast = internet.UDPServer(  # @UndefinedVariable
                0, self.ssdp_cli, self.ssdp_cli.interface)
            self.ucast.setServiceParent(self)
#             self.agent = Agent(reactor)
        if network in ('cloud', 'both'):
            if cloud_user:
                self.log.debug('UPnP Cloud enabled')
                self.cloud = True
                self._jid, secret = cloud_user
                self.users = {self._jid: {'state': True}}
                for user in cloud_servers:
                    self.users.update({user: {'state': False}})
                self.hosts = {}
                self.resourcepart = ''.join((
                    'urn:schemas-upnp-org:cloud-1-0:ControlPoint:1:uuid:',
                    self.uuid))
                full_jid = ''.join(
                    (self._jid, '/', self.resourcepart))
                self.jid = jid = JID(full_jid)
                self.reactor = reactor
                f = client.XMPPClientFactory(jid, secret)
                f.addBootstrap(
                    xmlstream.STREAM_CONNECTED_EVENT, self.cloud_connected)
                f.addBootstrap(
                    xmlstream.STREAM_END_EVENT, self.cloud_disconnected)
                f.addBootstrap(
                    xmlstream.STREAM_AUTHD_EVENT, self.authenticated)
                f.addBootstrap(
                    xmlstream.INIT_FAILED_EVENT, self.cloud_failed)
                self.connector = endpoints.HostnameEndpoint(
                    reactor, jid.host, 5222)
                self.factory = f
Ejemplo n.º 23
0
 def get_endpoint_for(self, host, port):
     self.endpoints.append((host, port))
     return endpoints.HostnameEndpoint(reactor, host, port)
 def stream_via(self, host, port):
     self.endpoints.append((host, port))
     return endpoints.HostnameEndpoint(reactor, host, port)
Ejemplo n.º 25
0
 def _make_endpoint(self, hostname, port):
     if self._tor_manager:
         return self._tor_manager.get_endpoint_for(hostname, port)
     # note: HostnameEndpoints have a default 30s timeout
     return endpoints.HostnameEndpoint(self._reactor, hostname, port)