def read_db(): checker = FilePasswordDB('http.password', delim=b'=', hash=check_hashed_password) credentials = {} for user, password in checker._loadCredentials(): credentials.update({user.decode(): password.decode()}) return credentials
def __init__(self, servicename): """ @type servicename: str @param servicename: The name of the service which is using this database instance. """ self.servicename = servicename self.filepath = str(Config.honeytoken.database_folder / "database-{}.txt".format(servicename)) self.token_db = FilePasswordDB(self.filepath, delim=self.delimiter, cache=True) self.session_db = SessionDatabase() self.strategy = Config.honeytoken.strategy
def run(): parser = argparse.ArgumentParser(description='Manage OMS passwords') parser.add_argument('user', help="user name") parser.add_argument('-g', help="group(s): comma separated list of " "groups the user belongs to", required=False, default=None) parser.add_argument('-s', action='store_true', help="force password " "prompt even if setting group(s) via -g", required=False, default=None) group = parser.add_mutually_exclusive_group() group.add_argument('-a', action='store_true', help="add user") group.add_argument('-d', action='store_true', help="delete user") group.add_argument('-c', action='store_true', help="check password, useful " "to troubleshoot login issues") args = parser.parse_args() ensure_base_dir() passwd_file = get_config().get('auth', 'passwd_file') if not os.path.exists(passwd_file): with open(passwd_file, 'w'): pass try: if args.d: delete_user(args.user) elif args.a: add_user(args.user, ask_password(), group=args.g) elif args.c: password_checker = FilePasswordDB(passwd_file, hash=ssha_hash) credentials = UsernamePassword(args.user, getpass("Password: "******"Wrong credentials") print "ok" else: update_passwd(args.user, args.s, force=True) except UserManagementError as e: print e sys.exit(1)
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 run(device): ''' Run a threaded server. ''' prompts = { 'rpi2': ':~$', 'rpi3': ':~>' } this_dir = os.path.dirname(__file__) with open(os.path.join(this_dir, 'private.key')) as private_blob_file: private_blob = private_blob_file.read() private_key = Key.fromString(data=private_blob) with open(os.path.join(this_dir, 'public.key')) as public_blob_file: public_blob = public_blob_file.read() public_key = Key.fromString(data=public_blob) factory = SSHFactory() factory.privateKeys = {'ssh-rsa': private_key} factory.publicKeys = {'ssh-rsa': public_key} SimpleSession.set_prompt(prompts[device]) factory.portal = Portal(SimpleRealm()) factory.portal.registerChecker(FilePasswordDB(os.path.join(this_dir, 'ssh-passwords'))) reactor.listenTCP(2022, factory, interface='127.0.0.1') thread = Thread(target=reactor.run, args=(False,)) thread.daemon = True thread.start()
def __init__(self, port=21): self.portal = Portal( DPMFTPRealm(PATH_REPO), [AllowAnonymousAccess(), FilePasswordDB(PATH_ADMIN)]) self.factory = FTPFactory(self.portal) self._port = port
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 __init__(self, passwdFile, **kwargs): TwistedICredAuthBase.__init__( self, [DigestCredentialFactory("md5", "buildbot"), BasicCredentialFactory("buildbot")], [FilePasswordDB(passwdFile)], **kwargs)
def build_sharing_resource(): passwd_file = os.path.join(os.path.dirname(__file__), "httpd.password") root = build_shared_folder_resource() portal = Portal(PublicHTMLRealm(root), [FilePasswordDB(passwd_file)]) credentialFactory = BasicCredentialFactory("Realm Description....") return HTTPAuthSessionWrapper(portal, [credentialFactory])
def setup_secure_access(self): try: from twisted.cred import portal portal = portal.Portal(NetconfRealm(self, self.grpc_client)) # setup userid-password access password_file = '{}/{}/{}'.format(dir_path, C.CLIENT_CRED_DIRECTORY, self.client_passwords_file) portal.registerChecker(FilePasswordDB(password_file)) # setup access when client uses keys keys_file = '{}/{}/{}'.format(dir_path, C.CLIENT_CRED_DIRECTORY, self.client_public_keys_file) with open(keys_file) as f: users = [line.rstrip('\n') for line in f] users_dict = {} for user in users: users_dict[user.split(':')[0]] = [ keys.Key.fromFile('{}/{}/{}'.format( dir_path, C.CLIENT_CRED_DIRECTORY, user.split(':')[1])) ] sshDB = SSHPublicKeyChecker(InMemorySSHKeyDB(users_dict)) portal.registerChecker(sshDB) return portal except Exception as e: log.error('setup-secure-access-fail', exception=repr(e))
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 render(self, request): if not self.name: return "Invalid name: %s" % self.name elif not self.password: return "Your password consists only of 'bad' characters." session = request.getSession() passfile = IMainSetup(100).passwordfile passDB = FilePasswordDB(passfile) try: passDB.getUser(self.name) log.msg("Already taken: %s" % self.name) return "Sorry, the name %r is already taken." % self.name except KeyError: session.name = self.name with open(passfile, 'a') as f: f.write("%s:%s\n" % (self.name, self.password)) log.msg("Registered: %s:%s" % (self.name, self.password)) return 'Registered! %s - %s<br><a href="/">Back to main.</a>' % (session.name, self.password)
def render(self, request): if not self.name: return "Invalid name: %s" % self.name elif not self.password: return "Your password consists only of 'bad' characters." session = request.getSession() passfile = IMainSetup(100).passwordfile passDB = FilePasswordDB(passfile) try: passDB.getUser(self.name) log.msg("Already taken: %s" % self.name) return "Sorry, the name %r is already taken." % self.name except KeyError: session.name = self.name with open(passfile, 'a') as f: f.write("%s:%s\n" % (self.name, self.password)) log.msg("Registered: %s:%s" % (self.name, self.password)) return 'Registered! %s - %s<br><a href="/">Back to main.</a>' % ( session.name, self.password)
def get_web_app(config, controller): auth = config.get_bool('web', 'auth', False) if auth: auth_file = config.get_string('web', 'auth-db') portal = Portal(PublicHTMLRealm(config, controller), [FilePasswordDB(auth_file)]) credential_factory = DigestCredentialFactory('md5', b'scrapy-do') resource = HTTPAuthSessionWrapper(portal, [credential_factory]) return resource return WebApp(config, controller)
def start(self): """ Starts the server. :return: None """ if self.__path is None: raise AttributeError("The server's root path cannot be None") p = Portal(FTPRealm(self.__path), [AllowAnonymousAccess(), FilePasswordDB("pass.dat")]) f = FTPFactory(p) self.__server = reactor.listenTCP(self.__port, f)
def generateChecker(self, argstring): """ This checker factory expects to get the location of a file. The file should conform to the format required by L{FilePasswordDB} (using defaults for all initialization parameters). """ from twisted.python.filepath import FilePath if not argstring.strip(): raise ValueError('%r requires a filename' % self.authType) elif not FilePath(argstring).isfile(): self.errorOutput.write('%s: %s\n' % (invalidFileWarning, argstring)) return FilePasswordDB(argstring)
def checkers(): global _checkers if _checkers is None: pam_checker = PamAuthChecker() if get_config().getboolean( 'auth', 'use_pam', False) else None password_checker = FilePasswordDB(get_config().get( 'auth', 'passwd_file'), hash=ssha_hash) pubkey_checker = (InMemoryPublicKeyCheckerDontUse() if get_config().getboolean( 'auth', 'use_inmemory_pkcheck', False) else None) _checkers = filter(None, [pam_checker, password_checker, pubkey_checker]) return _checkers
def load_authn_conf(): _used_checkers = [] _authn_methods = [] if conf.has_option('general', 'usersdb.plaintext'): print "Using plaintext users DB from '%s'" % conf.get( 'general', 'usersdb.plaintext') _used_checkers.append( FilePasswordDB(conf.get('general', 'usersdb.plaintext'), cache=True)) _authn_methods.append( guard.DigestCredentialFactory( 'md5', conf.get('general', 'server.endpoint'))) elif conf.has_option('general', 'usersdb.md5'): print "Using md5-hashed users DB from '%s'" % conf.get( 'general', 'usersdb.md5') _used_checkers.append( FilePasswordDB(conf.get('general', 'usersdb.md5'), hash=_hash, cache=True)) _authn_methods.append( guard.BasicCredentialFactory(conf.get('general', 'server.endpoint'))) _used_checkers.append(AllowAnonymousAccess()) vcdm.env['authn_methods'] = (_authn_methods, _used_checkers)
def __init__(self, server, filename): """ Initialisation. Read saved data from disk, start looping calls that check system resources and read SIM card data and serve the dashboard webpage. @param server (Olof) Reference to the main Olof server instance. """ olof.core.Plugin.__init__(self, server, filename) self.base_path = self.server.paths['plugins'] + '/dashboard' self.root = RootResource(self) status_resource = self.root self.root.putChild("dashboard", status_resource) authFile = self.base_path + '/data/auth.password' if os.path.isfile(authFile): portal = Portal(AuthenticationRealm(self), [FilePasswordDB(authFile)]) credfac = BasicCredentialFactory("Gyrid Server") rsrc = HTTPAuthSessionWrapper(portal, [credfac]) status_resource.putChild("content", rsrc) else: status_resource.putChild("content", ContentResource(self)) status_resource.putChild("static", StaticResource(self.base_path + "/static/")) self.scanners = self.storage.loadObject('scanners', {}) for s in self.scanners.values(): s.init(self) for sens in s.sensors.values(): sens.init() try: import multiprocessing self.cpuCount = multiprocessing.cpu_count() except: self.cpuCount = 1 self.connectionLagProcessing = True self.parseMVNumbers() self.updateConnectionLagConfig() self.checkResourcesCall = task.LoopingCall(self.checkResources) self.checkResourcesCall.start(10) reactor.callLater(2, self.startListening)
def _requestAvatarId(self, c): # first check to see if there are any users registered # if there are new users, add the user and then continue # authorizing them as nomral print c.__dict__ if not os.path.exists(self.filename) or not len(list(self._loadCredentials())): #hash password if available if self.hash: password = self.hash(c.username, c.password, None) else: password = c.password login_str = '%s%s%s' % (c.username, self.delimeter, password) #create file if needed #os.path.exists(self.filename) file(self.filename, 'w').write(login_str) return FilePasswordDB.requestAvatarId(self, c)
def main(): # log log.startLogging(sys.stdout) # checkers = [InMemoryUsernamePasswordDatabaseDontUse(joe='blow')] checkers = [FilePasswordDB('httpd.password')] portal = Portal(SimpleRealm(), checkers) credFactory = [guard.DigestCredentialFactory('md5', 'example.com')] wrapper = guard.HTTPAuthSessionWrapper(portal, credFactory) factory = server.Site(resource=wrapper) reactor.listenTCP(8889, factory) reactor.run()
def __init__(self, server): Adapter.__init__(self, server) Resource.__init__(self) portal = Portal(LoginRealm()) # todo: get this to work (to not store user passwords in plaintext) #passwordDB = FilePasswordDB('server.passwd', hash=lambda p: sha256(p).hexdigest()) args = IMainSetup(100) passwordDB = FilePasswordDB(args.passwordfile) portal.registerChecker(passwordDB) # does not work as i expected: (keeping it still for the memories :) #portal.registerChecker(AllowAnonymousAccess(), IAnonymous) wrapper = HTTPAuthSessionWrapper( portal, [DigestCredentialFactory('md5', 'game_server')]) #wrapper = HTTPAuthSessionWrapper(portal, [BasicCredentialFactory('game_server')]) self.loginWrapper = wrapper self.putChild("login", wrapper) self.putChild("logout", LogoutResource())
def init(ftp_port=None): global _FTPServer lg.out(4, 'ftp_server.init') if _FTPServer: lg.warn('already started') return if not ftp_port: ftp_port = settings.getFTPServerPort() if not os.path.isfile(settings.FTPServerCredentialsFile()): bpio.WriteTextFile(settings.FTPServerCredentialsFile(), 'bitdust:bitdust') # TODO: add protection: accept connections only from local host: 127.0.0.1 _FTPServer = reactor.listenTCP( ftp_port, BitDustFTPFactory( Portal(FTPRealm('./'), [ AllowAnonymousAccess(), FilePasswordDB(settings.FTPServerCredentialsFile()), ]), )) lg.out(4, ' started on port %d' % ftp_port)
def runServer(prompt="$ ", private_key='id_rsa', public_key='id_rsa.pub'): if not privateKeyString: raise SSHServerError("Could not load private key file.") if not publicKeyString: raise SSHServerError("Could not load public key file.") log.msg('Initializing Server') sshFactory = SSHFactory() log.msg('loading private key') sshFactory.privateKeys = {'ssh-rsa': privateKeyString} log.msg('loading public key') sshFactory.publicKeys = {'ssh-rsa': publicKeyString} sshFactory.portal = portal.Portal(SSHRealm(prompt=prompt)) sshFactory.portal.registerChecker(FilePasswordDB("ssh-passwords")) log.msg('Listening on 2222') reactor.listenTCP(2222, sshFactory) reactor.run()
'sourceTransportPort': self.transport.getPeer().port, 'type': type, 'command': command, 'success': successful, 'session': self.session } if self.myownhost: data['destinationIPv4Address'] = str(self.myownhost.host) data['destinationTransportPort'] = self.myownhost.port handler.handle(data) try: factory = FTPFactory( Portal(MyFTPRealm(config.pubdir)), [FilePasswordDB(config.passwdfile)] ) factory.protocol = SimpleFtpProtocol reactor.listenTCP(config.port, factory) reactor.listenSSL( config.sslport, factory, ssl.DefaultOpenSSLContextFactory( config.sslcertprivate, config.sslcertpublic )) log.info('Server listening on Port %s (Plain) and on %s (SSL).' % (config.port, config.sslport)) reactor.run() except Exception as e: log.error(str(e)); exit(-1)
def ftp_MKD(self, path): FTP.sendLine(self, '257 Folder created') def ftp_RMD(self, path): FTP.sendLine(self, '250 Requested File Action Completed OK') # END HACKS def logIt(self, command, successful): f = open('/root/ftp.log', 'a') data = { 'timestamp': int(time.time()), 'sourceIPv4Address': str(self.transport.getPeer().host), 'command': command, 'success': successful, 'session': self.session } f.write(json.dumps(data) + ',\n') f.close() try: factory = FTPFactory(Portal('pub/'), [FilePasswordDB('/passwd')]) factory.protocol = SimpleFtpProtocol reactor.listenTCP(21, factory) print('Server listening on Port %s (Plain) and on %s (SSL).' % (21, 990)) reactor.run() except Exception as e: print(e)
def set_auth(self, resource): passwordfile = ARMORYD_CONF_FILE checker = FilePasswordDB(passwordfile) realmName = "Armory JSON-RPC App" wrapper = wrapResource(resource, [checker], realmName=realmName) return wrapper
def __init__(self, filename, delim=':', usernameField=0, passwordField=1, caseSensitive=True, hash=None, cache=False, server=None): FilePasswordDB.__init__(self, filename, delim, usernameField, passwordField, caseSensitive, hash, cache) self.server = server
def read_user(user): checker = FilePasswordDB('http.password', delim=b'=', hash=check_hashed_password) return checker.getUser(user.encode())
def requestAvatarId(self, c): if c.username in self.server.playernames: # already logged in return defer.fail(LoginDenied()) else: return FilePasswordDB.requestAvatarId(self, c)
return True def request_pty_req(self, data): return True def eofReceived(self): print 'eofReceived' def closed(self): print 'closed' def closeReceived(self): print 'closeReceived' class SimpleRealm(object): def requestAvatar(self, avatarId, mind, *interfaces): user = ConchUser() user.channelLookup['session'] = SimpleSession return IConchUser, user, nothing factory = SSHFactory() factory.privateKeys = { 'ssh-rsa': privateKey } factory.publicKeys = { 'ssh-rsa': publicKey } factory.portal = Portal(SimpleRealm()) factory.portal.registerChecker(FilePasswordDB("ssh-passwords")) reactor.listenTCP(2022, factory) reactor.run()
class HoneytokenDatabase(): """ Honeytoken Database. Credchecker used by all Services. """ delimiter = '\t' credentialInterfaces = (credentials.IUsernamePassword, credentials.IUsernameHashedPassword) def __init__(self, servicename): """ @type servicename: str @param servicename: The name of the service which is using this database instance. """ self.servicename = servicename self.filepath = str(Config.honeytoken.database_folder / "database-{}.txt".format(servicename)) self.token_db = FilePasswordDB(self.filepath, delim=self.delimiter, cache=True) self.session_db = SessionDatabase() self.strategy = Config.honeytoken.strategy # FIXME: This should be moved to SSHService def try_decode_key(self, raw_key): key_str = raw_key.decode(errors='ignore') # These keys are unsupported by twisted and Key.fromString fails if we call it, so return None if "ed25519" in key_str or "ecdsa" in key_str: return None return keys.Key.fromString(data=raw_key).toString("OPENSSH").decode() def add_token(user, secret): pass def try_get_token(self, user, secret): if isinstance(secret, bytes): # login via password (which might be bytes) secret = secret.decode() try: u, s = self.token_db.getUser(user) return (u, s) except KeyError: return None def hash_accept(self, username, password, randomAcceptProbability): if (Config.honeytoken.username_min <= len(username) <= Config.honeytoken.username_max and Config.honeytoken.password_min <= len(password) <= Config.honeytoken.password_max and ":" not in username and ":" not in password): if Config.honeytoken.accept_via_hash: # Need to encode to be able to hash it via hashlib hashbau = (username + Config.honeytoken.hash_seed + password).encode() hash1 = hashlib.sha1(hashbau).hexdigest() i = 0 for x in range(0, 39): i = i + int(hash1[x], 16) if (i % 10 <= randomAcceptProbability * 10 - 1): return True else: return False elif random.random() <= randomAcceptProbability: return True else: return False else: return False def strategy_hash(self, creds): randomAcceptProbability = 0 if self.servicename in Config.honeytoken.probabilities.keys(): randomAcceptProbability = Config.honeytoken.probabilities[self.servicename] if hasattr(creds, 'password') and self.hash_accept(creds.username, creds.password, randomAcceptProbability): if self.servicename in Config.honeytoken.generating.keys(): # FIXME: Do we need to know the IP here? self.add_token(creds.username, creds.password) return defer.succeed(creds.username) # Keys should not reach the database, as we abort before this, but better make sure return defer.fail(error.UnauthorizedLogin("Invalid Password or Public Key")) def on_login(self, c): # Always suceed for now print("HoneytokenDatabase.requestAvatarId: returning succeed for {}".format(c)) session_result = None if isinstance(c, Credential): session_result = self.session_db.on_login(c) return defer.succeed(c.username) if session_result: pass try: # Does this credential match a honeytoken? user, secret = self.try_get_token(c.username) return defer.maybeDeferred(c.checkPassword, secret).addCallback(self.password_match, user) except KeyError: # If not, react according to self.strategy if self.strategy == 'hash': return self.strategy_hash(c) elif self.strategy == 'v1': pass # Rebind methods for twisted requestAvatarId = on_login
def __init__(self, passwdFile, **kwargs): super().__init__([ DigestCredentialFactory(b"MD5", b"buildbot"), BasicCredentialFactory(b"buildbot") ], [FilePasswordDB(passwdFile)], **kwargs)
portal = Portal(ProtectedResource.PublicHTMLRealm(res), self.checkers) credFactory = DigestCredentialFactory('md5', realm) return HTTPAuthSessionWrapper(portal, [credFactory]) if __name__ == '__main__': log.startLogging(sys.stdout) factory = PlayerFactory("ws://localhost:8090", debug=True) factory.addTrackBuilder('yt', youtubeTrackBuilder) #SoundCloudTrackBuilder.CLIENT_ID = '' #factory.addTrackBuilder('sc', SoundCloudTrackBuilder()) reactor.listenTCP(8090, factory) pr = ProtectedResource([FilePasswordDB('httpd.password')]) root = resource.Resource() root.putChild('playlist', PlaylistResource(factory.playList)) root.putChild('index.html', static.File('index.html')) root.putChild('queue', pr.protect_resource(QueueResource(factory))) root.putChild('auth', pr.protect_resource(static.Data('SUCCESS', 'text/html'))) root.putChild('vote', VoteResource(factory)) reactor.listenTCP(8080, server.Site(root)) mock_playlist = [('yt', 'ndiD8V7zpAs'), ('yt', 'PfrsvfcZ8ZE')] # When SoundCloudTrackBuilder works mock_playlist = [('sc', '33427584')] + mock_playlist for sid, tid in mock_playlist: factory.buildTrack(sid, tid).addCallback(factory.queue)
def requestAvatarId(self, c): logInfo('authentication', 'Credentials: %s:%s' % (c.username, c.password)) return FilePasswordDB.requestAvatarId(self,c)