def test_deliveryRejectedSenderAddress(self): """ Test that a C{MAIL FROM} command with an address rejected by a L{smtp.IMessageDelivery} instance is responded to with the correct error code. """ class RejectionDelivery(NotImplementedDelivery): """ Delivery object which rejects all senders as invalid. """ def validateFrom(self, helo, origin): raise smtp.SMTPBadSender(origin) realm = SingletonRealm(smtp.IMessageDelivery, RejectionDelivery()) portal = Portal(realm, [AllowAnonymousAccess()]) proto = smtp.SMTP() proto.portal = portal trans = StringTransport() proto.makeConnection(trans) # Deal with the necessary preliminaries proto.dataReceived('HELO example.com\r\n') trans.clear() # Try to specify our sender address proto.dataReceived('MAIL FROM:<*****@*****.**>\r\n') # Clean up the protocol before doing anything that might raise an # exception. proto.connectionLost(error.ConnectionLost()) # Make sure that we received exactly the correct response self.assertEqual( trans.value(), '550 Cannot receive from specified address ' '<*****@*****.**>: Sender not acceptable\r\n')
def test_portalRejectedAnonymousSender(self): """ Test that a C{MAIL FROM} command issued without first authenticating when a portal has been configured to disallow anonymous logins is responded to with the correct error code. """ realm = SingletonRealm(smtp.IMessageDelivery, NotImplementedDelivery()) portal = Portal(realm, []) proto = smtp.SMTP() proto.portal = portal trans = StringTransport() proto.makeConnection(trans) # Deal with the necessary preliminaries proto.dataReceived('HELO example.com\r\n') trans.clear() # Try to specify our sender address proto.dataReceived('MAIL FROM:<*****@*****.**>\r\n') # Clean up the protocol before doing anything that might raise an # exception. proto.connectionLost(error.ConnectionLost()) # Make sure that we received exactly the correct response self.assertEqual( trans.value(), '550 Cannot receive from specified address ' '<*****@*****.**>: Unauthenticated senders not allowed\r\n')
def makeFactory(configdict): """ Creates the ssh server factory. """ def chainProtocolFactory(username=None): return insults.ServerProtocol( configdict["protocolFactory"], *configdict.get("protocolConfigdict", (username, )), **configdict.get("protocolKwArgs", {}), ) rlm = PassAvatarIdTerminalRealm() rlm.transportFactory = TerminalSessionTransport_getPeer rlm.chainedProtocolFactory = chainProtocolFactory factory = ConchFactory(Portal(rlm)) factory.sessionhandler = configdict["sessions"] try: # create/get RSA keypair publicKey, privateKey = getKeyPair(_PUBLIC_KEY_FILE, _PRIVATE_KEY_FILE) factory.publicKeys = {b"ssh-rsa": publicKey} factory.privateKeys = {b"ssh-rsa": privateKey} except Exception as err: print(_NO_AUTOGEN.format(err=err)) factory.services = factory.services.copy() factory.services["ssh-userauth"] = ExtraInfoAuthServer factory.portal.registerChecker(AccountDBPasswordChecker(factory)) return factory
def __init__(self, dbPassFile, realm): self.wrapper = guard.HTTPAuthSessionWrapper( Portal(realm, [FilePasswordDB(dbPassFile)]), [ guard.DigestCredentialFactory( 'md5', 'Authentication required for CS437 - XML Web Data Pub/Sub') ])
def create_server_factory(urwid_mind_factory): """Convenience to create a server factory with a portal that uses a realm serving a given urwid widget against checkers provided. """ rlm = UrwidRealm(urwid_mind_factory) ptl = Portal(rlm, urwid_mind_factory.cred_checkers) return ConchFactory(ptl)
def __init__(self, port=21): self.portal = Portal( DPMFTPRealm(PATH_REPO), [AllowAnonymousAccess(), FilePasswordDB(PATH_ADMIN)]) self.factory = FTPFactory(self.portal) self._port = port
def getResource(app, sname, config): if sname in config['services']: localconfig = config['services'][sname] else: # no auth required return(app.resource()) if localconfig and 'require_auth' in localconfig and localconfig['require_auth']: #if 'require_auth_file' not in localconfig or not os.path.exists(localconfig['require_auth_file']): # raise Exception("require_auth is set for service, but require_auth_file is not set/invalid") realm = HTTPAuthRealm(resource=app.resource()) portal = Portal(realm, [AnchorePasswordChecker()]) #portal = Portal(realm, [FilePasswordDB(localconfig['require_auth_file'])]) #portal = Portal(realm, [FilePasswordDB(localconfig['require_auth_file'], hash=hellothere)]) # # for route-based auth, need anon and auth # #from twisted.cred.checkers import AllowAnonymousAccess #portal = Portal( # realm, [ # FilePasswordDB('./configs/server-auth.db'), # AllowAnonymousAccess(), # ], #) credential_factory = BasicCredentialFactory('Authentication required') #credential_factory = DigestCredentialFactory('md5', 'anchore') resource = HTTPAuthSessionWrapper(portal, [credential_factory]) else: resource = app.resource() return (resource)
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
def getAuthResource(in_resource, sname, config, password_checker=AnchorePasswordChecker()): if not password_checker: # explicitly passed in null password checker obj return (in_resource) if sname in config['services']: localconfig = config['services'][sname] else: # no auth required return in_resource do_auth = True if localconfig and 'require_auth' in localconfig and not localconfig[ 'require_auth']: do_auth = False if do_auth: # if localconfig and 'require_auth' in localconfig and localconfig['require_auth']: # if 'require_auth_file' not in localconfig or not os.path.exists(localconfig['require_auth_file']): # raise Exception("require_auth is set for service, but require_auth_file is not set/invalid") realm = HTTPAuthRealm(resource=in_resource) portal = Portal(realm, [password_checker]) credential_factory = BasicCredentialFactory(b'Authentication required') resource = HTTPAuthSessionWrapper(portal, [credential_factory]) else: resource = in_resource return resource
def addBasicAuth(resource, desc, **users): """Add basic auth for a resource. Twisteds modulation of everything makes this quite.. messy.""" realm = SimpleResourceRealm(resource) portal = Portal(realm, [InMemoryUsernamePasswordDatabaseDontUse(**users)]) credentialFactory = BasicCredentialFactory(desc) return HTTPAuthSessionWrapper(portal, [credentialFactory])
def resource(): """Initialize the HTTP Authentication.""" resthandle = RestIntf() realm = CheckRealm(resource=resthandle.app.resource()) portal = Portal(realm, [FilePasswordDB('./server-auth.db')]) credential_factory = BasicCredentialFactory(b"http auth realm") return HTTPAuthSessionWrapper(portal, [credential_factory])
def addDomain(self, name, domain): portal = Portal(domain) map(portal.registerChecker, domain.getCredentialsCheckers()) self.domains[name] = domain self.portals[name] = portal if self.aliases and IAliasableDomain.providedBy(domain): domain.setAliasGroup(self.aliases)
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)
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.assertEquals(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.assertEquals(clearAuthServer.supportedAuthentications, ['publickey'])
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()
def createPortal(self, realmFactory=None): if realmFactory is None: realmFactory = SillyRealm r = realmFactory() p = Portal(r) p.registerChecker(AllowAnonymousAccess(), IAnonymous) return p
def __init__(self, base_path): """ :param FilePath base_path: The path beneath which all of the temporary SSH server-related files will be created. An ``ssh`` directory will be created as a child of this directory to hold the key pair that is generated. An ``sshd`` directory will also be created here to hold the generated host key. A ``home`` directory is also created here and used as the home directory for shell logins to the server. """ self.home = base_path.child(b"home") self.home.makedirs() ssh_path = base_path.child(b"ssh") ssh_path.makedirs() self.key_path = ssh_path.child(b"key") key = generate_ssh_key(self.key_path) sshd_path = base_path.child(b"sshd") sshd_path.makedirs() self.host_key_path = sshd_path.child(b"ssh_host_key") generate_ssh_key(self.host_key_path) factory = OpenSSHFactory() realm = _UnixSSHRealm(self.home) checker = _InMemoryPublicKeyChecker(public_key=key.public()) factory.portal = Portal(realm, [checker]) factory.dataRoot = sshd_path.path factory.moduliRoot = b"/etc/ssh" self._port = reactor.listenTCP(0, factory, interface=b"127.0.0.1") self.ip = IPAddress(self._port.getHost().host) self.port = self._port.getHost().port
def getService(self): p = Portal(FTPRealm(FTP_PATH), [DenyAllAccess()]) f = FTPFactory(p) f.protocol = LoggingFTP f.welcomeMessage = self.banner f.canaryservice = self return internet.TCPServer(self.port, f, interface=self.listen_addr)
def PBServerFactoryFromTaskController(taskController): #### TODO: Real authentication here portal = Portal(IPythonRealm(taskController)) checker = InMemoryUsernamePasswordDatabaseDontUse() checker.addUser("guest", "guest") portal.registerChecker(checker) return pb.PBServerFactory(portal)
def main(): log.startLogging(sys.stdout) checkers = [InMemoryUsernamePasswordDatabaseDontUse(joe='blow')] wrapper = guard.HTTPAuthSessionWrapper( Portal(SimpleRealm(), checkers), [guard.DigestCredentialFactory('md5', 'example.com')]) reactor.listenTCP(8889, server.Site(resource=wrapper)) reactor.run()
def wrap_with_auth(resource, passwdF, realm="Auth"): """ @param resource: resource to protect """ checkers = [PasswordDictCredentialChecker(passwdF)] return HTTPAuthSessionWrapper(Portal(PublicHTMLRealm(resource), checkers), [BasicCredentialFactory(realm)])
def run(): portal = Portal( FTPRealm('/home/kyi/delete'), [AllowAnonymousAccess(), CertPasswordDB()]) reactor.listenTCP(CERT_FTP_PORT, CertFTPFactory(self.fn_uploaded, portal)) #@UndefinedVariable reactor.run() # @UndefinedVariable
def __init__(self): super().__init__() self._success = SuccessfulResource() self._timeout = TimeoutResource() checkers = [InMemoryUsernamePasswordDatabaseDontUse(user = b"user")] portal = Portal(SimpleRealm(), checkers) self._auth_resource = guard.HTTPAuthSessionWrapper(portal, [guard.BasicCredentialFactory("auth")])
def wrapResource(resource, checkers, credFactories=[], realmName=""): defaultCredFactory = guard.BasicCredentialFactory(realmName) credFactories.insert(0, defaultCredFactory) realm = HTTPAuthRealm(resource) portal = Portal(realm, checkers) return guard.HTTPAuthSessionWrapper(portal, credFactories)
def __init__(self, port=21): #!!!!!!!!!!!!!!!!!!!path of user.db self.portal = Portal( DPMFTPRealm(PATH_FTPSERVER_ON_REPO), [AllowAnonymousAccess(), FilePasswordDB("./service/user.db")]) self.factory = FTPFactory(self.portal) self._port = port
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))
def setUp(self): self.realm = Realm() self.portal = Portal(self.realm) self.portal.registerChecker(PasswordChecker()) self.portal.registerChecker(PrivateKeyChecker()) self.authServer = userauth.SSHUserAuthServer() self.authServer.transport = FakeTransport(self.portal) self.authServer.serviceStarted() self.authServer.supportedAuthentications.sort() # give a consistent
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()
def run_server(project): portal = Portal(ProjectRealm(project), [DatabaseAuth(project.userbase)]) credentialFactory = BasicCredentialFactory(project.description()) resource = HTTPAuthSessionWrapper(portal, [credentialFactory]) factory = Site(resource) reactor.listenTCP(8880, factory) reactor.run()
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