Exemplo n.º 1
0
 def __init__(self, conf):
     self._init_keys(conf)
     config = cwconfig.instance_configuration(conf.get('cubicweb-instance'))
     repo = Repository(config, TasksManager(), vreg=None)
     portal = Portal(CubicWebSFTPRealm(repo, conf))
     portal.registerChecker(CubicWebCredentialsChecker(repo))
     self.portal = portal
Exemplo n.º 2
0
 def setUp(self):
     self.realm = Realm()
     portal = Portal(self.realm)
     portal.registerChecker(MockChecker())
     self.authServer = userauth.SSHUserAuthServer()
     self.authServer.transport = FakeTransport(portal)
     self.authServer.serviceStarted()
Exemplo n.º 3
0
    def test_unencryptedConnectionWithoutPasswords(self):
        """
        If the L{SSHUserAuthServer} is not advertising passwords, then an
        unencrypted connection should not cause any warnings or exceptions.
        This is a white box test.
        """
        # create a Portal without password authentication
        portal = Portal(self.realm)
        portal.registerChecker(PrivateKeyChecker())

        # no encryption
        clearAuthServer = userauth.SSHUserAuthServer()
        clearAuthServer.transport = FakeTransport(portal)
        clearAuthServer.transport.isEncrypted = lambda x: False
        clearAuthServer.serviceStarted()
        clearAuthServer.serviceStopped()
        self.assertEqual(clearAuthServer.supportedAuthentications,
                          ['publickey'])

        # only encrypt incoming (the direction the password is sent)
        halfAuthServer = userauth.SSHUserAuthServer()
        halfAuthServer.transport = FakeTransport(portal)
        halfAuthServer.transport.isEncrypted = lambda x: x == 'in'
        halfAuthServer.serviceStarted()
        halfAuthServer.serviceStopped()
        self.assertEqual(clearAuthServer.supportedAuthentications,
                          ['publickey'])
Exemplo n.º 4
0
def main_ssh2http():
    portal = Portal(ExampleRealm())
    c_port = 5022
    factory = SSH2HTTPConverterFactory(c_port)
    portal.registerChecker(factory)
    SSH2HTTPConverterFactory.portal = portal
    reactor.listenTCP(c_port, factory)
Exemplo n.º 5
0
 def createPortal(self, realmFactory=None):
     if realmFactory is None:
         realmFactory = SillyRealm
     r = realmFactory()
     p = Portal(r)
     p.registerChecker(AllowAnonymousAccess(), IAnonymous)
     return p
Exemplo n.º 6
0
def PBServerFactoryFromTaskController(taskController):
    #### TODO: Real authentication here
    portal = Portal(IPythonRealm(taskController))
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser("guest", "guest")
    portal.registerChecker(checker)
    return pb.PBServerFactory(portal)
Exemplo n.º 7
0
def _get_portal(checker):
    '''
    creates portal and adds realm and checker
    '''
    portal = Portal(HoneyRealm())
    portal.registerChecker(checker)
    return portal
Exemplo n.º 8
0
    def test_unencryptedConnectionWithoutPasswords(self):
        """
        If the L{SSHUserAuthServer} is not advertising passwords, then an
        unencrypted connection should not cause any warnings or exceptions.
        This is a white box test.
        """
        # create a Portal without password authentication
        portal = Portal(self.realm)
        portal.registerChecker(PrivateKeyChecker())

        # no encryption
        clearAuthServer = userauth.SSHUserAuthServer()
        clearAuthServer.transport = FakeTransport(portal)
        clearAuthServer.transport.isEncrypted = lambda x: False
        clearAuthServer.serviceStarted()
        clearAuthServer.serviceStopped()
        self.assertEqual(clearAuthServer.supportedAuthentications,
                         [b'publickey'])

        # only encrypt incoming (the direction the password is sent)
        halfAuthServer = userauth.SSHUserAuthServer()
        halfAuthServer.transport = FakeTransport(portal)
        halfAuthServer.transport.isEncrypted = lambda x: x == 'in'
        halfAuthServer.serviceStarted()
        halfAuthServer.serviceStopped()
        self.assertEqual(clearAuthServer.supportedAuthentications,
                         [b'publickey'])
 def __init__(self, conf):
     self._init_keys(conf)
     config = cwconfig.instance_configuration(conf.get('cubicweb-instance'))
     repo = Repository(config, TasksManager(), vreg=None)
     portal = Portal(CubicWebSFTPRealm(repo, conf))
     portal.registerChecker(CubicWebCredentialsChecker(repo))
     self.portal = portal
Exemplo n.º 10
0
    def setUp(self):
        super(RootTests, self).setUp()

        self.docroot = self.mktemp()
        os.mkdir(self.docroot)

        RootResource.CheckSACL = FakeCheckSACL(sacls={"calendar": ["dreid"]})

        directory = XMLDirectoryService({"xmlFile" : xmlFile})
        augment.AugmentService = augment.AugmentXMLDB(
            xmlFiles=(augmentsFile.path,)
        )

        principals = DirectoryPrincipalProvisioningResource(
            "/principals/",
            directory
        )

        root = RootResource(self.docroot, principalCollections=[principals])

        root.putChild("principals",
                      principals)

        portal = Portal(auth.DavRealm())
        portal.registerChecker(directory)

        self.root = auth.AuthenticationWrapper(
            root,
            portal,
            credentialFactories=(basic.BasicCredentialFactory("Test realm"),),
            loginInterfaces=(auth.IPrincipal,))

        self.site = server.Site(self.root)
Exemplo n.º 11
0
def main_ssh2http():
    portal = Portal(ExampleRealm())
    c_port = 5022
    factory = SSH2HTTPConverterFactory(c_port)
    portal.registerChecker(factory)
    SSH2HTTPConverterFactory.portal = portal
    reactor.listenTCP(c_port, factory)
Exemplo n.º 12
0
 def setUp(self):
     self.realm = Realm()
     portal = Portal(self.realm)
     portal.registerChecker(MockChecker())
     self.authServer = userauth.SSHUserAuthServer()
     self.authServer.transport = FakeTransport(portal)
     self.authServer.serviceStarted()
Exemplo n.º 13
0
def deploy(iface, port, dbLocation, dbType, dbUsername=None, dbPassword=None,
           ssl=False, sslRedirect=False, sslPrivate=None, sslCert=None,
           sslPort=None):

    if dbUsername and dbPassword:
        searchService = searchServices[dbType](
            dbLocation, dbUsername, dbPassword)
    else:
        searchService = searchServices[dbType](dbLocation)

    portal = Portal(PublicHTMLRealm(searchService), [AllowAnonymousAccess()])
    portal.registerChecker(QuasselChecker(searchService), IUsernameHashedPassword)
    portal.registerChecker(SessionChecker(), ISessionCredentials)

    application = service.Application("Querryl")
    site = server.Site(BasicWrapper(portal, []))
    site.sessionFactory = LongSession

    if ssl:
        ctx = DefaultOpenSSLContextFactory(sslPrivate, sslCert)
        ssl_sv = internet.SSLServer(sslPort, site, ctx, interface=iface)
        ssl_sv.setServiceParent(application)

        if sslRedirect:
            site = server.Site(RedirectFromRequest(port=sslPort))

    sv = internet.TCPServer(port, site, interface=iface)
    sv.setServiceParent(application)
    return sv
Exemplo n.º 14
0
 def portal(self):
   portal = Portal(self.realm())
   for checker in self.auth_checkers():
     portal.registerChecker(checker)
   if len(self.auth_checkers()) == 0:
     portal.registerChecker(checkers.AllowAnonymousAccess())
   return portal
	def listen(self, port):
		'''
		Starts listening on the specified port.
		'''
		portal = Portal(credentials.Realm())
		portal.registerChecker(credentials.PasswordChecker(self.__passwd))
		reactor.listenTCP(port, ServerProtocolFactory(portal, self.userlist))
Exemplo n.º 16
0
def main(application=None):
    """
    SMTP daemon for receiving DSN (Delivery Status Notification)

    :param application: optional Application instance (if used inside twistd)
    :type application: twisted.application.service.Application
    """
    parser = argparse.ArgumentParser(
        description='Start the SMTPD process for CloudMailing.')
    parser.add_argument('-p',
                        '--port',
                        type=int,
                        default=25,
                        help='port number for SMTP (default: 25)')
    parser.add_argument('-u', '--uid', help='Change the UID of this process')
    parser.add_argument('-g', '--gid', help='Change the GID of this process')

    args = parser.parse_args()

    # Need to open TCP port early, before to switch user and configure log
    portal = Portal(SimpleRealm())
    portal.registerChecker(AllowAnonymousAccess())

    factory = ReturnPathSMTPFactory(portal)
    if application:
        smtpd = internet.TCPServer(args.port, factory)
        smtpd.setServiceParent(application)
    else:
        smtpd = reactor.listenTCP(args.port, factory)

    if args.uid or args.gid:
        uid = args.uid and pwd.getpwnam(args.uid).pw_uid or None
        gid = args.gid and grp.getgrnam(args.gid).gr_gid or None
        # for fname in os.listdir(settings.LOG_PATH):
        #     fullname = os.path.join(settings.LOG_PATH, fname)
        #     print fullname
        #     if args.uid:
        #         os.chown(fullname, args.uid, args.gid)
        switchUID(uid, gid)

    configure_logging("smtpd", settings.CONFIG_PATH, settings.LOG_PATH,
                      settings.DEFAULT_LOG_FORMAT, False)

    ##Twisted logs
    observer = PythonLoggingObserver()
    observer.start()

    log = logging.getLogger("smtpd")

    log.info(
        "****************************************************************")
    log.info("Starting CloudMailing SMTPD version %s" % VERSION)
    log.info("Serial: %s" % settings.SERIAL)
    log.info("Twisted version %s", twisted.version.short())
    log.info(
        "****************************************************************")

    Db.getInstance(settings.MASTER_DATABASE)

    log.info("CM SMTPD started on port %d", args.port)
Exemplo n.º 17
0
def setupManhole(application, config):
    """Setup an SSH manhole for the API service.

    The manhole port is taken from the C{manhole-port} option in the config
    file. If this option is not provided the api port plus 100 is used.

    @param application: The fluidinfo API L{Application} object.
    @param config: The configuration object.
    """
    servicePort = config.getint('service', 'port')
    if config.has_option('service', 'manhole-port'):
        manholePort = config.getint('service', 'manhole-port')
    else:
        manholePort = servicePort + 100

    def getManhole(_):
        manhole = Manhole(globals())
        ps1 = 'fluidinfo-api [%d] > ' % servicePort
        ps2 = '... '.rjust(len(ps1))
        manhole.ps = (ps1, ps2)
        return manhole

    realm = TerminalRealm()
    realm.chainedProtocolFactory.protocolFactory = getManhole
    portal = Portal(realm)
    portal.registerChecker(SSHPublicKeyDatabase())
    factory = ConchFactory(portal)
    manholeService = TCPServer(manholePort, factory, interface='127.0.0.1')
    manholeService.setServiceParent(application)
Exemplo n.º 18
0
def makeService(config):
    components.registerAdapter(
        GitSession,
        GitAvatar,
        session.ISession)

    with open(config['conf']) as f:
        conf = yaml.load(f.read())

    port = int(conf.get('port', 22))
    host_key = conf.get('host_key')
    driver_key = conf.get('driver', 'example')

    log.msg('Using driver: \'%s\'' % driver_key)

    mgr = driver.DriverManager(
        namespace='gitserver.driver',
        name=driver_key,
        invoke_on_load=False
    )

    portal = Portal(GitRealm(mgr))
    portal.registerChecker(GitPublicKeyChecker(mgr))

    # factory.SSHFactory takes no arguments, so unlike the
    # websocket server, we will assign portal on the class
    # rather than through the constructor.
    # TypeError: this constructor takes no arguments
    # is raised if we pass portal GitFactory(portal)
    GitFactory.portal = portal
    GitSession.driver_key = driver_key

    return internet.TCPServer(port, GitFactory(host_key=host_key))
Exemplo n.º 19
0
 def createPortal(self, realmFactory=None):
     if realmFactory is None:
         realmFactory = SillyRealm
     r = realmFactory()
     p = Portal(r)
     p.registerChecker(AllowAnonymousAccess(), IAnonymous)
     return p
Exemplo n.º 20
0
def makeService(config):
    components.registerAdapter(GitSession, GitAvatar, session.ISession)

    with open(config['conf']) as f:
        conf = yaml.load(f.read())

    port = int(conf.get('port', 22))
    host_key = conf.get('host_key')
    driver_key = conf.get('driver', 'example')

    log.msg('Using driver: \'%s\'' % driver_key)

    mgr = driver.DriverManager(namespace='gitserver.driver',
                               name=driver_key,
                               invoke_on_load=False)

    portal = Portal(GitRealm(mgr))
    portal.registerChecker(GitPublicKeyChecker(mgr))

    # factory.SSHFactory takes no arguments, so unlike the
    # websocket server, we will assign portal on the class
    # rather than through the constructor.
    # TypeError: this constructor takes no arguments
    # is raised if we pass portal GitFactory(portal)
    GitFactory.portal = portal
    GitSession.driver_key = driver_key

    return internet.TCPServer(port, GitFactory(host_key=host_key))
Exemplo n.º 21
0
    def makeService(self, options):
        class LongSession(Session):
            sessionTimeout = 3600

        if options['steamkey'] is None:
            raise ValueError('Must specify steam API key.')
        if options['strport'] is None:
            raise ValueError('Must specify strport description.')
        if options['dbdir'] is None:
            raise ValueError('Must specify database path.')
        steamAPI = API(key=options['steamkey'])

        store = Store(options['dbdir'])
        keyPath = FilePath(options['dbdir']).child('fernet.key')

        database = Database(store)

        loginRedirect = '/'
        portal = Portal(MapListRealm(database, options['bundle-path'],
                                     steamAPI, loginRedirect))
        portal.registerChecker(PreauthenticatedChecker())
        portal.registerChecker(AllowAnonymousAccess())

        root = HTTPOpenIDAuthSessionWrapper(portal, [], loginRedirect, keyPath,
                                            database)

        site = Site(root)
        site.sessionFactory = LongSession
        return strports.service(options['strport'], site)
Exemplo n.º 22
0
def create_portal(a):
    """I'm responsible for creating the authenticated portal"""
    realm = AggregatorRealm(a)
    portal = Portal(realm)
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser(version.apiversion, a.getPassword())
    portal.registerChecker(checker)
    return portal
Exemplo n.º 23
0
def makeService(options):
    """
    Makes a new swftp-ftp service. The only option is the config file
    location. The config file has the following options:
     - host
     - port
     - auth_url
     - num_persistent_connections
     - connection_timeout
     - welcome_message
    """
    from twisted.protocols.ftp import FTPFactory
    from twisted.web.client import HTTPConnectionPool
    from twisted.cred.portal import Portal

    from swftp.ftp.server import SwiftFTPRealm
    from swftp.auth import SwiftBasedAuthDB
    from swftp.utils import print_runtime_info

    print('Starting SwFTP-ftp %s' % VERSION)

    c = get_config(options['config_file'], options)
    ftp_service = service.MultiService()

    # Add statsd service
    if c.get('ftp', 'log_statsd_host'):
        try:
            from swftp.statsd import makeService as makeStatsdService
            makeStatsdService(
                c.get('ftp', 'log_statsd_host'),
                c.getint('ftp', 'log_statsd_port'),
                sample_rate=c.getfloat('ftp', 'log_statsd_sample_rate'),
                prefix=c.get('ftp', 'log_statsd_metric_prefix')
            ).setServiceParent(ftp_service)
        except ImportError:
            log.err('Missing Statsd Module. Requires "txstatsd"')

    pool = HTTPConnectionPool(reactor, persistent=True)
    pool.maxPersistentPerHost = c.getint('ftp', 'num_persistent_connections')
    pool.cachedConnectionTimeout = c.getint('ftp', 'connection_timeout')

    authdb = SwiftBasedAuthDB(auth_url=c.get('ftp', 'auth_url'),
                              verbose=c.getboolean('ftp', 'verbose'))

    ftpportal = Portal(SwiftFTPRealm())
    ftpportal.registerChecker(authdb)
    ftpfactory = FTPFactory(ftpportal)
    ftpfactory.welcomeMessage = c.get('ftp', 'welcome_message')
    ftpfactory.allowAnonymous = False

    signal.signal(signal.SIGUSR1, print_runtime_info)
    signal.signal(signal.SIGUSR2, print_runtime_info)

    internet.TCPServer(
        c.getint('ftp', 'port'),
        ftpfactory,
        interface=c.get('ftp', 'host')).setServiceParent(ftp_service)
    return ftp_service
Exemplo n.º 24
0
def adminWrapper(data):
    """Ties it together"""
    p = Portal(AdminRealm(data))    # found in twisted.cred.Portal
    p.registerChecker(AllowAnonymousAccess(), IAnonymous)
    p.registerChecker(data.players, IUsernamePassword)
    upw = guard.UsernamePasswordWrapper(p, callback=dumbRedirect)
    r = guard.SessionWrapper(upw)
    r.sessionLifetime = 12 * 3600
    return r
Exemplo n.º 25
0
class OpenRukoSSHServer(SSHFactory):


    def __init__(self, settings):
        self.settings = settings
        self.portal = Portal(OpenRukoRealm(settings))
        self.portal.registerChecker(OpenRukoCredentialChecker(settings))
        self.privateKeys = {'ssh-rsa': Key.fromFile(settings['private_key'])}
        self.publicKeys = {'ssh-rsa': Key.fromFile(settings['public_key'])}
Exemplo n.º 26
0
class OpenRukoSSHServer(SSHFactory):


    def __init__(self, settings):
        self.settings = settings
        self.portal = Portal(OpenRukoRealm(settings))
        self.portal.registerChecker(OpenRukoCredentialChecker(settings))
        self.privateKeys = {'ssh-rsa': Key.fromFile(settings['gitmouth_private_key'])}
        self.publicKeys = {'ssh-rsa': Key.fromFile(settings['gitmouth_public_key'])}
Exemplo n.º 27
0
    def createDocumentRoot(self):
        docroot = self.mktemp()
        os.mkdir(docroot)

        userResource = TestDAVPrincipalResource("/principals/users/user01")
        userResource.writeDeadProperty(TwistedPasswordProperty("user01"))

        principalCollection = TestPrincipalsCollection(
            "/principals/",
            children={"users": TestPrincipalsCollection(
                    "/principals/users/",
                    children={"user01": userResource})})

        rootResource = self.resource_class(
            docroot, principalCollections=(principalCollection,))

        portal = Portal(DavRealm())
        portal.registerChecker(TwistedPropertyChecker())

        credentialFactories = (basic.BasicCredentialFactory(""),)

        loginInterfaces = (IPrincipal,)

        self.site = Site(AuthenticationWrapper(
            rootResource,
            portal,
            credentialFactories,
            credentialFactories,
            loginInterfaces
        ))

        rootResource.setAccessControlList(self.grant(element.All()))

        for name, acl in (
            ("none"       , self.grant()),
            ("read"       , self.grant(element.Read())),
            ("read-write" , self.grant(element.Read(), element.Write())),
            ("unlock"     , self.grant(element.Unlock())),
            ("all"        , self.grant(element.All())),
        ):
            filename = os.path.join(docroot, name)
            if not os.path.isfile(filename):
                file(filename, "w").close()
            resource = self.resource_class(filename)
            resource.setAccessControlList(acl)

        for name, acl in (
            ("nobind" , self.grant()),
            ("bind"   , self.grant(element.Bind())),
            ("unbind" , self.grant(element.Bind(), element.Unbind())),
        ):
            dirname = os.path.join(docroot, name)
            if not os.path.isdir(dirname):
                os.mkdir(dirname)
            resource = self.resource_class(dirname)
            resource.setAccessControlList(acl)
        return docroot
Exemplo n.º 28
0
def main():
    from twisted.cred.portal import Portal
    from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
    portal = Portal(SimpleRealm())
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser("benchmark", "benchmark")
    portal.registerChecker(checker)
    reactor.listenTCP(8787, pb.PBServerFactory(portal))
    reactor.run()
Exemplo n.º 29
0
def StartServices(username,password):
    from md5 import md5
    password = md5(password).digest()
    
    portal = Portal(SimpleRealm())
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser(username,password)
    portal.registerChecker(checker)
    reactor.listenTCP(7001,pb.PBServerFactory(portal))
Exemplo n.º 30
0
    def createDocumentRoot(self):
        docroot = self.mktemp()
        os.mkdir(docroot)

        userResource = TestDAVPrincipalResource("/principals/users/user01")
        userResource.writeDeadProperty(TwistedPasswordProperty("user01"))

        principalCollection = TestPrincipalsCollection(
            "/principals/",
            children={"users": TestPrincipalsCollection(
                    "/principals/users/",
                    children={"user01": userResource})})

        rootResource = self.resource_class(
            docroot, principalCollections=(principalCollection,))

        portal = Portal(DavRealm())
        portal.registerChecker(TwistedPropertyChecker())

        credentialFactories = (basic.BasicCredentialFactory(""),)

        loginInterfaces = (IPrincipal,)

        self.site = Site(AuthenticationWrapper(
            rootResource,
            portal,
            credentialFactories,
            credentialFactories,
            loginInterfaces
        ))

        rootResource.setAccessControlList(self.grant(element.All()))

        for name, acl in (
            ("none"       , self.grant()),
            ("read"       , self.grant(element.Read())),
            ("read-write" , self.grant(element.Read(), element.Write())),
            ("unlock"     , self.grant(element.Unlock())),
            ("all"        , self.grant(element.All())),
        ):
            filename = os.path.join(docroot, name)
            if not os.path.isfile(filename):
                file(filename, "w").close()
            resource = self.resource_class(filename)
            resource.setAccessControlList(acl)

        for name, acl in (
            ("nobind" , self.grant()),
            ("bind"   , self.grant(element.Bind())),
            ("unbind" , self.grant(element.Bind(), element.Unbind())),
        ):
            dirname = os.path.join(docroot, name)
            if not os.path.isdir(dirname):
                os.mkdir(dirname)
            resource = self.resource_class(dirname)
            resource.setAccessControlList(acl)
        return docroot
Exemplo n.º 31
0
def adminWrapper(data):
    """Ties it together"""
    p = Portal(AdminRealm(data))
    p.registerChecker(AllowAnonymousAccess(), IAnonymous)
    p.registerChecker(data.players, IUsernamePassword)
    upw = guard.UsernamePasswordWrapper(p, callback=dumbRedirect)
    r = guard.SessionWrapper(upw)
    r.sessionLifetime = 12 * 3600
    return r
Exemplo n.º 32
0
def main():
    from twisted.internet import reactor
    from twisted.cred.portal import Portal
    from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
    portal = Portal(SimpleRealm())
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser("guest", "guest")
    portal.registerChecker(checker)
    reactor.listenTCP(pb.portno, pb.PBServerFactory(portal))
    reactor.run()
Exemplo n.º 33
0
    def __init__(self, soledad_sessions, *args, **kw):

        LEAPIMAPServer.__init__(self, *args, **kw)

        realm = LocalSoledadIMAPRealm(soledad_sessions)
        portal = Portal(realm)
        checker = IMAPTokenChecker(soledad_sessions)
        self.checker = checker
        self.portal = portal
        portal.registerChecker(checker)
Exemplo n.º 34
0
def StartServices():
    #fire up the World Stuff
    portal = Portal(SimpleRealm())
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    from md5 import md5
    password = md5("daemon").digest()
    for x in range(0, 100):
        checker.addUser(str(x), password)
    portal.registerChecker(checker)
    reactor.listenTCP(7000, pb.PBServerFactory(portal))
def StartServices():
    #fire up the World Stuff
    portal = Portal(SimpleRealm())
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    from md5 import md5
    password = md5("daemon").digest()
    for x in range(0,100):
        checker.addUser(str(x), password)
    portal.registerChecker(checker)
    reactor.listenTCP(7000,pb.PBServerFactory(portal))
Exemplo n.º 36
0
def main():
    from twisted.internet import reactor
    from twisted.cred.portal import Portal
    from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
    portal = Portal(SimpleRealm())
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser("guest", "guest")
    portal.registerChecker(checker)
    reactor.listenTCP(pb.portno, pb.PBServerFactory(portal))
    reactor.run()
Exemplo n.º 37
0
    def __init__(self, account, *args, **kw):

        LEAPIMAPServer.__init__(self, *args, **kw)

        realm = TestRealm(account)
        portal = Portal(realm)
        checker = TestCredentialsChecker()
        self.checker = checker
        self.portal = portal
        portal.registerChecker(checker)
Exemplo n.º 38
0
    def __init__(self, soledad_sessions, *args, **kw):

        LEAPIMAPServer.__init__(self, *args, **kw)

        realm = LocalSoledadIMAPRealm(soledad_sessions)
        portal = Portal(realm)
        checker = IMAPTokenChecker(soledad_sessions)
        self.checker = checker
        self.portal = portal
        portal.registerChecker(checker)
Exemplo n.º 39
0
 def startService(self):
     Plugin.startService(self)
     if not self._inputs == []:
         portal = Portal(CollectorRealm(self))
         portal.registerChecker(AllowAnonymousAccess())
         factory = PBServerFactory(portal)
         self._listener = reactor.listenTCP(self._port, factory, interface=self._address)
         logger.info("[%s] listening for remote messages on %s:%i" % (self.name,self._address,self._port))
     else:
         logger.info("[%s] no inputs configured" % self.name)
Exemplo n.º 40
0
    def __init__(self, account, *args, **kw):

        LEAPIMAPServer.__init__(self, *args, **kw)

        realm = TestRealm(account)
        portal = Portal(realm)
        checker = TestCredentialsChecker()
        self.checker = checker
        self.portal = portal
        portal.registerChecker(checker)
Exemplo n.º 41
0
def setup():
    from twisted.internet import reactor
    from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse


    portal = Portal(SimpleRealm())
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser("guest", "password")
    portal.registerChecker(checker)

    reactor.listenTCP(7777, ConsoleSMTPFactory(portal))
Exemplo n.º 42
0
    def setServiceParent(self, parent):
        service.MultiService.setServiceParent(self, parent)

        portal = Portal(PbRealm(parent))

        checker = InMemoryUsernamePasswordDatabaseDontUse()
        checker.addUser("guest", "guest")
        portal.registerChecker(checker)

        s = strports.service("unix:%s" % self.socket, pb.PBServerFactory(portal))
        s.setServiceParent(self)
Exemplo n.º 43
0
class SSHFactory(factory.SSHFactory):
    def __init__(self, settings):
        self.settings = settings
        self.portal = Portal(Realm(settings))
        self.portal.registerChecker(Checker(settings))
        self.privateKeys = {
            'ssh-rsa': Key.fromFile(settings['hadoukngit']['private_key']),
        }
        self.publicKeys = {
            'ssh-rsa': Key.fromFile(settings['hadoukngit']['public_key']),
        }
Exemplo n.º 44
0
    def __init__(self, soledad_sessions, keymanager_sessions, sendmail_opts,
                 encrypted_only=False):
        realm = LocalSMTPRealm(
            keymanager_sessions, soledad_sessions, sendmail_opts,
            encrypted_only)
        portal = Portal(realm)

        checker = SMTPTokenChecker(soledad_sessions)
        self.checker = checker
        self.portal = portal
        portal.registerChecker(checker)
Exemplo n.º 45
0
    def __init__(self,
                 outgoing_sessions,
                 soledad_sessions,
                 encrypted_only=False):
        realm = LocalSMTPRealm(outgoing_sessions, encrypted_only)
        portal = Portal(realm)

        checker = SMTPTokenChecker(soledad_sessions)
        self.checker = checker
        self.portal = portal
        portal.registerChecker(checker)
Exemplo n.º 46
0
class CleanerSite(Site, Loggable):
    def __init__(self, firewall):
        self.user = cattivo.config.get("cleaner", "user")
        self.passwd_file = cattivo.config.get("cleaner", "passwd-file")
        checker = FilePasswordDB(self.passwd_file)
        self.realm = CleanerRealm()
        self.portal = Portal(self.realm)
        self.portal.registerChecker(checker)
        self.firewall = firewall
        Site.__init__(self, CleanerResource(self.portal))
        Loggable.__init__(self)
Exemplo n.º 47
0
    def __init__(self, soledad_sessions, keymanager_sessions, sendmail_opts,
                 encrypted_only=False):
        realm = LocalSMTPRealm(
            keymanager_sessions, soledad_sessions, sendmail_opts,
            encrypted_only)
        portal = Portal(realm)

        checker = SMTPTokenChecker(soledad_sessions)
        self.checker = checker
        self.portal = portal
        portal.registerChecker(checker)
Exemplo n.º 48
0
def StartServices(callback):
    global IMPCONNECTED_CALLBACK
    IMPCONNECTED_CALLBACK = callback
    #fire up the World Stuff
    portal = Portal(SimpleRealm())
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    from md5 import md5
    password = md5("imp").digest()
    for x in range(0, 100):
        checker.addUser(str(x), password)
    portal.registerChecker(checker)
    reactor.listenTCP(7005, pb.PBServerFactory(portal))
Exemplo n.º 49
0
Arquivo: pb.py Projeto: isotoma/boiler
    def __init__(self, port=8787):
        BaseService.__init__(self)

        boiler = None
        portal = Portal(PbRealm(boiler))

        checker = InMemoryUsernamePasswordDatabaseDontUse()
        checker.addUser("guest", "guest")
        portal.registerChecker(checker)

        service = strports.service("tcp:%d" % port, pb.PBServerFactory(portal))
        service.setServiceParent(self)
Exemplo n.º 50
0
def guardedWrapper(realm, checkers):
    ptl = Portal(realm)
    ptl.registerChecker(AllowAnonymousAccess(), IAnonymous)
    for checker in checkers:
        ptl.registerChecker(checker)
    # FIXME - this should be another wrapper, which returns a SessionWrapper,
    # which has persistentCookies set or not.  for now, all cookies are
    # persistent for a week
    wrap = guard.SessionWrapper(ptl)
    wrap.persistentCookies = True
    wrap.sessionLifetime = 3600 * 24 * 7
    return wrap
Exemplo n.º 51
0
    def __init__(self):
        super(SSHService, self).__init__()

        self._name = Config.ssh.name
        self._port = Config.ssh.port

        p = Portal(SSHRealm())
        p.registerChecker(SSHService.honeytokendb)

        self._fService = factory.SSHFactory()
        self._fService.services[b'ssh-userauth'] = groveUserAuth

        self._limiter = Limiter(self._fService, Config.ssh.name,
                                Config.ssh.connections_per_host)

        self._fService.portal = p

        # self.protocol = SSHProtocol
        # self._fService.protocol = self.protocol
        home = expanduser('~')

        # XXX: These paths should be configurable
        privateKeyPath = home + '/.ssh/id_honeygrove'
        publicKeyPath = home + '/.ssh/id_honeygrove.pub'

        # Generate RSA keys if they don't exist
        if not (exists(privateKeyPath) and exists(publicKeyPath)):
            key = keys.rsa.generate_private_key(public_exponent=65537,
                                                key_size=4096,
                                                backend=default_backend())
            private_key = key.private_bytes(
                serialization.Encoding.PEM,
                serialization.PrivateFormat.TraditionalOpenSSL,
                serialization.NoEncryption())
            public_key = key.public_key().public_bytes(
                serialization.Encoding.OpenSSH,
                serialization.PublicFormat.OpenSSH)

            # make .ssh directory, if it doesn't exist
            os.makedirs(dirname(publicKeyPath), exist_ok=True)

            with open(privateKeyPath, 'w') as f:
                f.write(private_key.decode())
            with open(publicKeyPath, 'w') as f:
                f.write(public_key.decode())

        self._fService.privateKeys = {
            b'ssh-rsa': keys.Key.fromFile(privateKeyPath)
        }
        self._fService.publicKeys = {
            b'ssh-rsa': keys.Key.fromFile(publicKeyPath)
        }
Exemplo n.º 52
0
    def __init__(self, port):
        realm = FTPRealm(get_poppy_root())
        portal = Portal(realm)
        portal.registerChecker(PoppyAccessCheck())
        factory = ftp.FTPFactory(portal)

        factory.tld = get_poppy_root()
        factory.protocol = ftp.FTP
        factory.welcomeMessage = "Launchpad upload server"
        factory.timeOut = config.poppy.idle_timeout

        self.ftpfactory = factory
        self.portno = port
Exemplo n.º 53
0
 def startService(self):
     Plugin.startService(self)
     if not self._inputs == []:
         portal = Portal(CollectorRealm(self))
         portal.registerChecker(AllowAnonymousAccess())
         factory = PBServerFactory(portal)
         self._listener = reactor.listenTCP(self._port,
                                            factory,
                                            interface=self._address)
         logger.info("[%s] listening for remote messages on %s:%i" %
                     (self.name, self._address, self._port))
     else:
         logger.info("[%s] no inputs configured" % self.name)
Exemplo n.º 54
0
def main():
    from twisted.application import internet
    from twisted.application import service

    portal = Portal(SimpleRealm())
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser("guest", "guest")
    portal.registerChecker(checker)

    app = service.Application("SES Relay SMTP Server")
    internet.TCPServer(8080, SESRelaySMTPFactory(portal)).setServiceParent(app)

    return app
Exemplo n.º 55
0
 def setUp(self):
     self.service_calls = []
     self.encoder = pdu_encoding.PDUEncoder()
     self.smpp_config = SMPPServerConfig(msgHandler=self._serviceHandler,
                                         systems={'userA': {"max_bindings": 2}}
                                         )
     portal = Portal(self.SmppRealm())
     credential_checker = InMemoryUsernamePasswordDatabaseDontUse()
     credential_checker.addUser('userA', 'valid')
     portal.registerChecker(credential_checker)
     self.factory = SMPPServerFactory(self.smpp_config, auth_portal=portal)
     self.proto = self.factory.buildProtocol(('127.0.0.1', 0))
     self.tr = proto_helpers.StringTransport()
     self.proto.makeConnection(self.tr)
Exemplo n.º 56
0
    def setUp(self):
        TestCase.setUp(self)

        gooduser = TestDAVPrincipalResource("/users/gooduser")
        gooduser.writeDeadProperty(TwistedPasswordProperty("goodpass"))

        baduser = TestDAVPrincipalResource("/users/baduser")
        baduser.writeDeadProperty(TwistedPasswordProperty("badpass"))

        rootresource = TestPrincipalsCollection(
            "/", {
                "users":
                TestResource("/users/", {
                    "gooduser": gooduser,
                    "baduser": baduser
                })
            })

        protected = TestResource("/protected",
                                 principalCollections=[rootresource])

        protected.setAccessControlList(
            davxml.ACL(
                davxml.ACE(davxml.Principal(davxml.HRef("/users/gooduser")),
                           davxml.Grant(davxml.Privilege(davxml.All())),
                           davxml.Protected())))

        rootresource.children["protected"] = protected

        portal = Portal(DavRealm())
        portal.registerChecker(TwistedPropertyChecker())

        credentialFactories = (basic.BasicCredentialFactory(""), )

        loginInterfaces = (IPrincipal, )

        self.rootresource = rootresource
        self.site = Site(
            AuthenticationWrapper(
                self.rootresource,
                portal,
                credentialFactories,
                credentialFactories,
                loginInterfaces,
            ))