Esempio n. 1
0
    def setUp(self):
        self.real_getfqdn = socket.getfqdn
        socket.getfqdn = mock_socket.getfqdn
        # temporarily replace sys.stdout to capture DebuggingServer output
        self.old_stdout = sys.stdout
        self.output = io.StringIO()
        sys.stdout = self.output

        self.serv_evt = threading.Event()
        self.client_evt = threading.Event()
        # Capture SMTPChannel debug output
        self.old_DEBUGSTREAM = smtpd.DEBUGSTREAM
        smtpd.DEBUGSTREAM = io.StringIO()
        # Pick a random unused port by passing 0 for the port number
        self.serv = smtpd.DebuggingServer((HOST, 0), ('nowhere', -1))
        # Keep a note of what port was assigned
        self.port = self.serv.socket.getsockname()[1]
        serv_args = (self.serv, self.serv_evt, self.client_evt)
        self.thread = threading.Thread(target=debugging_server, args=serv_args)
        self.thread.start()

        # wait until server thread has assigned a port number
        self.serv_evt.wait()
        self.serv_evt.clear()
#!/usr/bin/env python
import smtpd
import asyncore
import logging

logging.basicConfig(level=logging.DEBUG)

if __name__ == "__main__":
    smtp_server = smtpd.DebuggingServer(('0.0.0.0', 1025), None)
    try:
        asyncore.loop()
    except KeyboardInterrupt:
        smtp_server.close()
Esempio n. 3
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import smtpd
import asyncore

server = smtpd.DebuggingServer(('127.0.0.1', 1025), None)

asyncore.loop()
import smtpd
import asyncore

d = smtpd.DebuggingServer(('0.0.0.0', 25), None)

try:
    asyncore.loop()
except KeyboardInterrupt:
    pass
Esempio n. 5
0
 def __init__(self, addr='localhost', port=1025):
     threading.Thread.__init__(self)
     self.server = smtpd.DebuggingServer((addr, port), None)
Esempio n. 6
0
 def setUpClass(cls):
     # Launch SMPT debbug server
     smtpd.DebuggingServer(('localhost',1025), None )
     executor = concurrent.futures.ThreadPoolExecutor(1)
     executor.submit(asyncore.loop)
Esempio n. 7
0
import smtpd
import asyncore

server = smtpd.DebuggingServer(('localhost', 1025), None)

asyncore.loop()
Esempio n. 8
0
    def test_scan_radom_sites(self):
        # This test might be illegal in your country
        
        # Get list of Wordpress sites if not already downloaded
        filename='/tmp/wp_sites'
        if not os.path.isfile(filename):
            myfile = requests.get(SOURCE)
            open(filename, 'wb').write(myfile.content)

        # Select X from the 50M
        idxs = random.sample(range(50000), HOW_MANY)
        urls=[linecache.getline(filename, i) for i in idxs]

        # Prepare scan config
        CONFIG1="""
[wpwatcher]
wp_sites=%s
smtp_server=localhost:1025
[email protected]
email_to=["*****@*****.**"]
wpscan_args=["--rua", "--stealthy", "--format", "cli", "--no-banner", "--disable-tls-checks"]
false_positive_strings=["You can get a free API token with 50 daily requests by registering at https://wpvulndb.com/users/sign_up"]
send_email_report=Yes
log_file=./TEST-wpwatcher.log.conf
wp_reports=./TEST-wp_reports.json.conf
asynch_workers=10
follow_redirect=Yes
wpscan_output_folder=./TEST-wpscan-results/
send_infos=Yes
"""%json.dumps([{'url':s.strip()} for s in urls])

        # Select X from the 50M
        idxs = random.sample(range(50000), HOW_MANY)
        urls=[linecache.getline(filename, i) for i in idxs]

        # Prepare scan config
        CONFIG2="""
[wpwatcher]
wp_sites=%s
smtp_server=localhost:1025
[email protected]
email_to=["*****@*****.**"]
wpscan_args=["--rua", "--stealthy", "--format", "json", "--no-banner", "--disable-tls-checks"]
false_positive_strings=["You can get a free API token with 50 daily requests by registering at https://wpvulndb.com/users/sign_up"]
send_email_report=Yes
log_file=./TEST-wpwatcher.log.conf
wp_reports=./TEST-wp_reports.json.conf
asynch_workers=10
follow_redirect=Yes
wpscan_output_folder=./TEST-wpscan-results/
attach_wpscan_output=Yes
send_infos=Yes
send_errors=Yes
email_errors_to=["admins@domain"]
# prescan_without_api_token=Yes
"""%json.dumps([{'url':s.strip()} for s in urls])

        # Select X from the 50M
        idxs = random.sample(range(50000), HOW_MANY)
        urls=[linecache.getline(filename, i) for i in idxs]

        # Prepare scan config
        CONFIG3="""
[wpwatcher]
wp_sites=%s
smtp_server=localhost:1025
[email protected]
email_to=["*****@*****.**"]
wpscan_args=["--rua", "--stealthy", "--format", "json", "--no-banner", "--disable-tls-checks"]
false_positive_strings=["You can get a free API token with 50 daily requests by registering at https://wpvulndb.com/users/sign_up"]
send_email_report=Yes
log_file=./TEST-wpwatcher.log.conf
wp_reports=./TEST-wp_reports.json.conf
asynch_workers=10
follow_redirect=Yes
wpscan_output_folder=./TEST-wpscan-results/
attach_wpscan_output=Yes
send_warnings=No
send_errors=Yes
fail_fast=Yes
"""%json.dumps([{'url':s.strip()} for s in urls])
        
        # Launch SMPT debbug server
        smtpd.DebuggingServer(('localhost',1025), None )
        executor = concurrent.futures.ThreadPoolExecutor(1)
        executor.submit(asyncore.loop)

        # Init WPWatcher
        w1 = WPWatcher(WPWatcherConfig(string=CONFIG1).build_config()[0])

        # Run scans
        res1=w1.run_scans_and_notify()

        # Init WPWatcher
        w2 = WPWatcher(WPWatcherConfig(string=CONFIG2).build_config()[0])

        # Run scans
        res2=w2.run_scans_and_notify()

        # Init WPWatcher
        w3 = WPWatcher(WPWatcherConfig(string=CONFIG3).build_config()[0])

        # Run scans
        res3=w3.run_scans_and_notify()

        # Close mail server
        asyncore.close_all()

        self.assertEqual(type(res1), tuple, "run_scans_and_notify returned an invalied result")
Esempio n. 9
0
def main():
    '''
        Main part of command line utility
    '''
    arguments = docopt.docopt(__doc__, version='Naval Fate 2.0')

    if arguments['show_diag']:
        diag.show()

    if arguments['show_reporting']:
        diag.reporting()
        diag.show()

    if arguments['ping_couchdb']:
        try:
            if couchdb.ping():
                print 'OK'
            else:
                print 'KO'
        except:
            print 'KO'

    if arguments['get_admin']:
        (username, password) = couchdb.get_admin()
        print 'Username: {}'.format(username)
        print 'Password: {}'.format(password)

    if arguments['get_couchdb_admins']:
        admins = couchdb.get_couchdb_admins()
        print 'CouchDB admins:'
        for admin in admins:
            print '- {}'.format(admin)

    if arguments['delete_token']:
        couchdb.delete_token()

    if arguments['create_token']:
        print couchdb.create_token()

    if arguments['create_cozy_db']:
        if arguments['--name']:
            db_name = arguments.get('<name>', 'cozy')
        else:
            db_name = 'cozy'
        couchdb.create_cozy_db(db_name)
        print '{} DB is ready'.format(db_name)

    if arguments['reset_token']:
        couchdb.reset_token()
        print 'New tokens:'
        print couchdb.get_admin()[0]

    if arguments['get_cozy_param']:
        print couchdb.get_cozy_param(arguments['<name>'])

    if arguments['normalize_cert_dir']:
        ssl.normalize_cert_dir()

    if arguments['get_crt_common_name']:
        filename = arguments['<filename>']
        if filename:
            print ssl.get_crt_common_name(filename)
        else:
            print ssl.get_crt_common_name()

    if arguments['clean_links']:
        ssl.clean_links()

    if arguments['make_links']:
        ssl.make_links(arguments['<common_name>'])

    if arguments['generate_certificate']:
        common_name = arguments['<common_name>']

        if arguments['--size']:
            key_size = int(arguments['<size>'])
        else:
            key_size = ssl.DEFAULT_KEY_SIZE

        if arguments['--digest']:
            digest = arguments['<digest>']
        else:
            digest = ssl.DEFAULT_DIGEST

        print 'Generate certificate for {} with {} key size and {} digest'.format(
            common_name, key_size, digest)
        ssl.generate_certificate(common_name, key_size, digest)

    if arguments['sign_certificate']:
        common_name = arguments['<common_name>']

        print "Sign certificate for {} with Let's Encrypt".format(common_name)
        ssl.acme_sign_certificate(common_name)

    if arguments['regenerate_dhparam']:
        if arguments['--size']:
            size = int(arguments['<size>'])
        else:
            size = ssl.DEFAULT_DHPARAM_SIZE

        print 'Regenerate dhparam with {} size'.format(size)
        ssl.regenerate_dhparam(size)

    if arguments['compare_version']:
        current = arguments['<current>']
        operator = arguments['<operator>']
        reference = arguments['<reference>']
        compare_version.compare(current, operator, reference)

    if arguments['is_cozy_registered']:
        print couchdb.is_cozy_registered()

    if arguments['unregister_cozy']:
        couchdb.unregister_cozy()

    if arguments['fix_oom_scores']:
        process.fix_oom_scores()

    if arguments['get_oom_scores']:
        process.get_oom_scores()

    if arguments['rebuild_app']:
        if arguments['--not-force']:
            force = False
        else:
            force = True
        if arguments['--restart']:
            restart = True
        else:
            restart = False
        migration.rebuild_app(arguments['<app>'], force=force, restart=restart)

    if arguments['rebuild_all_apps']:
        if arguments['--not-force']:
            force = False
        else:
            force = True
        if arguments['--restart']:
            restart = True
        else:
            restart = False
        migration.rebuild_all_apps(force=force, restart=restart)

    if arguments['migrate_2_node4']:
        migration.migrate_2_node4()

    if arguments['install_requirements']:
        migration.install_requirements()

    if arguments['install_cozy']:
        migration.install_cozy()

    if arguments['wait_couchdb']:
        helpers.wait_couchdb()

    if arguments['wait_cozy_stack']:
        helpers.wait_cozy_stack()

    if arguments['check_lsb_codename']:
        sys.exit(diag.check_lsb_codename())

    if arguments['emulate_smtp']:
        ip = '127.0.0.1'
        port = '25'
        if arguments['--bind']:
            ip = arguments['<ip>']
        if arguments['--port']:
            if arguments['<port>']:  # a bug in docopt?
                port = arguments['<port>']
            else:
                port = arguments['<ip>']

        print 'Emulate SMTP server on {}:{}'.format(ip, port)
        smtpd.DebuggingServer(tuple([ip, int(port)]), None)
        asyncore.loop()

    if arguments['backup']:
        if arguments['<backup_filename>']:
            backup_filename = arguments['<backup_filename>']
        else:
            backup_filename = None
        backup.backup(backup_filename)

    if arguments['restore']:
        backup.restore(arguments['<backup_filename>'])

    if arguments['install_weboob'] or arguments['update_weboob']:
        weboob.install()

    if arguments['update_weboob_modules']:
        weboob.update()
Esempio n. 10
0
def runmail():
    smtpd.DebuggingServer(('127.0.0.1', 2048), None)
    asyncore.loop()
Esempio n. 11
0
 def inner_run():
     print "Now accepting mail at %s:%s" % (addr, port)
     server = smtpd.DebuggingServer((addr, port), None)
     asyncore.loop()
Esempio n. 12
0
import smtpd
import asyncore

server = smtpd.DebuggingServer(("127.0.0.1", 1025), None)
asyncore.loop()
Esempio n. 13
0
# Helper script to run a dummy SMTP server on port 1025

import asyncore
import smtpd

server = smtpd.DebuggingServer(("localhost", 1025), None)
asyncore.loop()
Esempio n. 14
0
import smtpd
import asyncore

IP, PORT = '127.0.0.1', 1025

server = smtpd.DebuggingServer((IP, PORT), None)
print('Debugging SMTP server is listening at: %s:%s' % (IP, str(PORT)))

asyncore.loop()

Esempio n. 15
0
        # mailfrom - The message envelope's From infromation.
        # rcpttos - List of message recipients from the message envelope.
        # data - the full RFC 2882 message body.
        # The default implementation of process_message() raises a NotImplementedError
        # This example defines a sublclss that overrides the method to print information about the messages it receives.
        server = CustomSMTPServer(("192.168.1.150", 1025), None)

        # SMTPServer requires asyncore, so to run the server we cal; asyncore.loop()
        asyncore.loop()

    if results.section == 2:
        logger = logging.getLogger("13.2.2 Debugging Server")
        # The previous example shows the arguments to process_message(), but smtpd also includes a server specifically
        # designed for more complete debugging, called DebuggingServer.  It prints the entrie incoming message to the
        # console, then stops processing (it doesn't proxy the message to a real mail server)
        server = smtpd.DebuggingServer(("192.168.1.150", 1025), None)
        asyncore.loop()

    if results.section == 3:
        logger = logging.getLogger("13.2.3 Proxy Server")
        # The PureProxy class implements a straightforward proxy server.  incoming messages are forwarded upstream to
        # the server given as an argument to the constructor.
        # WARNING: Running this has a good chance to make you into an open relay.
        server = smtpd.PureProxy(("192.168.1.150", 1025),
                                 ('192.168.1.160', 1025))
        asyncore.loop()

else:
    # If the command isn't recognized because it wasn't given, show the help.
    if not results.section:
        parser.parse_args(['-h'])
Esempio n. 16
0
# Handle custom key
keyfile = basename + '.key'
if len(sys.argv) > 3:
    keyfile = sys.argv[3]

try:
    ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
except AttributeError:
    ssl_ctx = None
    if HAS_TLS:
        print('Python ssl library does not support SSLContext, hence starttls and TLS are not supported.')
    import smtpd

if HAS_TLS and ssl_ctx is not None:
    print('Using %s and %s' % (certfile, keyfile))
    ssl_ctx.load_cert_chain(certfile=certfile, keyfile=keyfile)

    print('Start SMTP server on port', port1)
    smtp_server1 = smtpd_tls.DebuggingServer(('127.0.0.1', port1), None, ssl_ctx=ssl_ctx, starttls=True)
    if port2:
        print('Start TLS SMTP server on port', port2)
        smtp_server2 = smtpd_tls.DebuggingServer(('127.0.0.1', port2), None, ssl_ctx=ssl_ctx, starttls=False)
else:
    print('Start SMTP server on port', port1)
    smtp_server1 = smtpd.DebuggingServer(('127.0.0.1', port1), None)
    if port2:
        print('WARNING: TLS is NOT supported on this system, not listening on port %s.' % port2)

asyncore.loop()