def validate_authentication(self, username, password, handler): try: resp = self.exchange_jwt({ 'req': 'auth', 'user': username, 'pass': password }) except Exception as e: logger.warning("Error comunicating with remote: %s", e) raise AuthenticationFailed( "Error communicating with authentication server") from e if resp.get('auth', None): try: resp = self.exchange_jwt({'req': 'info', 'user': username}) except Exception as e: logger.warning("Error comunicating with remote: %s", e) raise AuthenticationFailed( "Error communicating with authentication server") from e home = resp.get('home', None) perm = resp.get('perm', None) if home is not None and perm is not None: self.users[username] = User(username, resp['perm'], resp['home']) else: logger.warning("Mangled response from auth service: %s", e) raise AuthenticationFailed( "Error communicating with authentication server") else: raise AuthenticationFailed("Authentication failed")
def validate_authentication(self, username, apikey, handler): """Raises AuthenticationFailed if supplied username and password don't match the stored credentials, else return None. """ msg = "Authentication failed." if apikey == 'anonymous': return if apikey != 'anonymous': user = None if self.cfg['web']['local_endpoint']: user_req = requests.get(self.cfg['web']['local_endpoint'] + '/api/info/apikey/' + apikey) if not user_req.status_code == 200: raise AuthenticationFailed( 'Wrong or failed authentication') user = user_req.json() else: user = BmajUser.get_user_by_apikey(apikey) bank = self.db.banks.find_one({'name': username}) if not bank: logging.error('Bank not found: ' + username) raise AuthenticationFailed('Bank does not exists') if bank['properties']['visibility'] != 'public': if user['id'] != bank['properties']['owner']: if 'members' not in bank['properties'] or user[ 'id'] not in bank['properties']['members']: raise AuthenticationFailed( 'Not allowed to access to this bank') if len(bank['production']) == 0: raise AuthenticationFailed('No production release available') self.bank = bank
def oss_check(self, bucket_name, default_endpoint, access_key_id, access_key_secret): if bucket_name in self.bucket_endpoints: endpoint = self.bucket_endpoints[bucket_name] try: bucket = oss2.Bucket(oss2.Auth(access_key_id, access_key_secret), endpoint, bucket_name, connect_timeout=5.0, app_name=defaults.app_name) res = bucket.get_bucket_acl() except oss2.exceptions.OssError as e: raise AuthenticationFailed("access bucket:%s using specified \ endpoint:%s failed. request_id:%s, status:%s, code:%s, message:%s" % (bucket_name, endpoint, e.request_id, unicode(e.status), e.code, e.message)) return endpoint try: #print(access_key_id) #print(access_key_secret) #print(default_endpoint) logger = logging.getLogger('pyftpdlib') logger.info("oss info access_key_id: %s, access_key_secret: %s, default_endpoint: %s, bucketname: %s" % (access_key_id, access_key_secret, default_endpoint, bucket_name)) service = oss2.Service(oss2.Auth(access_key_id, access_key_secret), default_endpoint, app_name=defaults.app_name) res = service.list_buckets(prefix=bucket_name) logger.info("res_list_buckets: %s" % (vars(res))) except oss2.exceptions.AccessDenied as e: raise AuthenticationFailed("can't list buckets, check your access_key.request_id:%s, status:%s, code:%s, message:%s"% (e.request_id, unicode(e.status), e.code, e.message)) except oss2.exceptions.OssError as e: raise AuthenticationFailed("list buckets error. request_id:%s, status:%s, code:%s, message:%s" % (e.request_id, unicode(e.status), e.code, e.message)) logger = logging.getLogger('pyftpdlib') logger.info("bucket_name: %s" % (bucket_name)) bucket_list = res.buckets for bucket in bucket_list: logger.info("bucket_list, name: %s" % (bucket.name)) if bucket.name == bucket_name: # endpoint = self.get_endpoint(bucket_name, bucket.location.decode('utf-8'), access_key_id, access_key_secret) endpoint = default_endpoint return endpoint raise AuthenticationFailed("can't find the bucket %s when list buckets." % bucket_name)
def validate_authentication(self, username, password, handler): msg = "Authentication failed." device = ZensorDevice.get_device(username) if device is None: raise AuthenticationFailed(msg) elif device.password != password: raise AuthenticationFailed(msg)
def obs_bucket_auth(self, bucket_name, default_endpoint, access_key_id, access_key_secret): logger = logging.getLogger('pyftpdlib') try: service = obsadapter.ObsClient(access_key_id=access_key_id, secret_access_key=access_key_secret, server=default_endpoint) res_location = service.getBucketLocation(bucket_name) logger.info("location message is %s" % res_location.body.location) except service.status is 403: raise AuthenticationFailed( "can't Get bucket Location, check your access_key.request_id:%s, status:%s, code:%s, message:%s" % (service.requestId, unicode( service.status), service.errorCode, service.errorMessage)) except res_location.status >= 300: raise AuthenticationFailed( "get buckets Location error. request_id:%s, status:%s, code:%s, message:%s" % (res_location.requestId, unicode(res_location.status), res_location.errorCode, res_location.errorMessage)) # get the bucket Region endpoint if res_location.body.location != '': endpoint = Constants.transmode + "obs." + res_location.body.location + ".myhuaweicloud.com" logger.info("the endpoint is %s" % endpoint) return endpoint else: raise AuthenticationFailed( "can't find the OBS bucket's endpoint %s when query buckets in server." % bucket_name)
def validate_authentication(self, username, password, handler): msg = 'Authentication Failed' app_and_username_and_target = username.lower().split('|') if len(app_and_username_and_target) != 4: raise AuthenticationFailed('Invalid username') app_name = app_and_username_and_target[0] username = app_and_username_and_target[1] target = app_and_username_and_target[2] obj_id = app_and_username_and_target[3] try: # Meta is going to be anything that will assist us in identifying the target application = Application.objects.get(name__iexact=app_name) except Application.DoesNotExist: raise AuthenticationFailed(msg) response = requests.post(application.auth_url, data={ 'username': username, 'password': password }) if 199 < response.status_code < 300: setattr(handler, 'target', target) setattr(handler, 'user', username) setattr(handler, 'obj_id', obj_id) setattr(handler, 'application', application) setattr(handler, 'user_home', str(app_name) + str(username) + str(target)) return None raise AuthenticationFailed(msg)
def validate_authentication(self, username, password, handler): msg = "Authentication failed." user = self.get_user(username) if user is None: raise AuthenticationFailed(msg) password = password.encode("utf-8") if not bcrypt.checkpw(password, user["password"].encode("utf-8")): raise AuthenticationFailed(msg)
def validate_authentication(self, username, password, handler): """Validate authentication with hashed password""" msg = "Authentication failed." if not self.has_user(username): raise AuthenticationFailed(msg) if username != 'anonymous': if not bcrypt.verify(password, self.user_table[username]['pwd']): raise AuthenticationFailed(msg)
def validate_authentication(self, username, password, handler): try: pw1 = self.user_table[username]["pwd"] pw2 = crypt.crypt(password, pw1) except KeyError: # no such username raise AuthenticationFailed("No such user") else: if pw1 != pw2: raise AuthenticationFailed("Wrong password")
def validate_authentication(self, username, password, handler): """authenticate user with password""" if not authenticate(username=username, password=password): raise AuthenticationFailed("Authentication failed.") try: return User.objects.get(username=username) except User.DoesNotExist: raise AuthenticationFailed("Authentication failed.")
def oss_check(self, bucket_name, default_endpoint, access_key_id, access_key_secret): # 1. when specify bucket endpoints if bucket_name in self.bucket_endpoints: endpoint = self.bucket_endpoints[bucket_name] try: bucket = oss2.Bucket(oss2.Auth(access_key_id, access_key_secret), endpoint, bucket_name, connect_timeout=5.0, app_name=defaults.app_name) faked_obj_name = "test-faked-objname-to-check-ak-if-right" res = bucket.get_object(faked_obj_name) except oss2.exceptions.NoSuchKey as e: pass except oss2.exceptions.AccessDenied as e: raise AuthenticationFailed( "get random object was denied, check your access_key/access_id.request_id:%s, status:%s, code:%s, message:%s" % (e.request_id, unicode(e.status), e.code, e.message)) except oss2.exceptions.OssError as e: raise AuthenticationFailed( "access bucket:%s using specified \ endpoint:%s failed. request_id:%s, status:%s, code:%s, message:%s" % (bucket_name, endpoint, e.request_id, unicode( e.status), e.code, e.message)) return endpoint # 2. when not specify bucket endpoints try: service = oss2.Service(oss2.Auth(access_key_id, access_key_secret), default_endpoint, app_name=defaults.app_name) res = service.list_buckets(prefix=bucket_name) except oss2.exceptions.AccessDenied as e: raise AuthenticationFailed( "can't list buckets, check your access_key.request_id:%s, status:%s, code:%s, message:%s" % (e.request_id, unicode(e.status), e.code, e.message)) except oss2.exceptions.OssError as e: raise AuthenticationFailed( "list buckets error. request_id:%s, status:%s, code:%s, message:%s" % (e.request_id, unicode(e.status), e.code, e.message)) # 3. internal_endpoint or public_endpoint bucket_list = res.buckets for bucket in bucket_list: if bucket.name == bucket_name: endpoint = self.get_endpoint(bucket_name, bucket.location.decode('utf-8'), access_key_id, access_key_secret) return endpoint raise AuthenticationFailed( "can't find the bucket %s when list buckets." % bucket_name)
def validate_authentication(self, username, password, handler): """Raises AuthenticationFailed if supplied username and password don't match the stored credentials, else return None. """ hash = md5(password).hexdigest() msg = "Authentication failed." if not self.has_user(username): if username == 'anonymous': msg = "Anonymous access not allowed." raise AuthenticationFailed(msg) if username != 'anonymous': if self.user_table[username]['pwd'] != hash: raise AuthenticationFailed(msg)
def validate_authentication(self, username, password, handler): """Raises AuthenticationFailed if supplied username and password don't match the stored credentials, else return None. """ res = requests.post(settings.CGSERVER_AUTH_URL, data={ 'username': username, 'password': password, 'peerip': handler.socket.getpeername()[0], 'client_secret': settings.CLIENT_SECRET, }) res.raise_for_status() data = res.json() if data['error']: if username == 'anonymous': msg = 'Anonymous access not allowed.' else: msg = 'Authentication failed.' raise AuthenticationFailed(msg) cgperms = data['perms'] localuser = dict(home=os.path.normcase(self.base_dir), perm='', operms={}, cgperms={}, msg_login='******', msg_quit='Goodbye.') for apath, perm in cgperms.items(): allowed = os.path.normcase( os.path.realpath(os.path.join(self.base_dir, apath))) if self._issubpath(allowed, os.path.normcase(self.base_dir)): localuser['cgperms'][allowed] = perm self.user_table[username] = localuser
def validate_authentication(self, username, apikey, handler): """Raises AuthenticationFailed if supplied username and password don't match the stored credentials, else return None. """ # msg = "Authentication failed." #anonymous user : we defined the user as anonymous proxy = Utils.get_service_endpoint(self.cfg, 'user') if username == "biomaj_default": user = {} user['id'] = "BMJ_default" elif proxy: user_req = requests.get(proxy + '/api/user/info/apikey/' + apikey) if not user_req.status_code == 200: raise AuthenticationFailed('Wrong or failed authentication') user = user_req.json() else: user = BmajUser.get_user_by_apikey(apikey) if not user: self.logger.error('User not found: ' + username) raise AuthenticationFailed('User does not exists') #Determining the authorized path dict_bank = {} for db_entry in self.db.banks.find(): home_dir = self.get_home_dir(username, db_entry) dict_bank[home_dir] = [ db_entry['properties']['visibility'], db_entry['properties']['owner'] ] self.bank = dict_bank #Create a new user for biomaj server with specific permission if not self.has_user(username): self.add_user(username, apikey, self.get_home_dir(username)) for directory in dict_bank: if dict_bank[directory][0] == "public": perm = "elr" self.override_perm(username, directory, perm, recursive=True) elif dict_bank[directory][ 1] == username and dict_bank[directory][0] != "public": perm = "elr" self.override_perm(username, directory, perm, recursive=True) elif username == "biomaj_default" or dict_bank[directory][ 0] != "public": #biomaj_default user and private bank perm = "" self.override_perm(username, directory, perm, recursive=True) return
def validate_authentication(self, username, password, handler): """ Modified to check the database for username and passwords instead of a dict. """ msg = "Authentication failed." if not self.has_user(username): if username == 'anonymous': msg = "Anonymous access not allowed." raise AuthenticationFailed(msg) if username != 'anonymous': self.users.connect() user_pw = self.users.pull_where(self.username, str(username), '=', [self.password])[0][0] user_salt = self.users.pull_where(self.username, str(username), '=', [self.salt])[0][0] self.users.disconnect() password = gen_hash(password, user_salt) if user_pw != password: raise AuthenticationFailed(user_pw)
def validate_authentication(self, username, password, handler): """authenticate user with password """ user = authenticate(**{ self.username_field: username, 'password': password }) account = self.get_account(username) if not (user and account): raise AuthenticationFailed("Authentication failed.")
def validate_authentication(self, username, password, handler): initdb() wh = "ftpusername='******' and password('{}')=`password`".format( username, password) say = app.kayitsayisi("ftpaccounts", wh) #print wh,say if say == 0: raise AuthenticationFailed("") else: print "validate_authentication: Login OK... "
def validate_authentication(self, user_name, password, handler): """ 使用api里harbor提供的api,进行认证 认证完对本次登录的权限问题进行处理 """ flag, perm, msg = FtpHarborManager().ftp_authenticate( user_name, password) if not flag: raise AuthenticationFailed(msg) perms = 'elradfmwMT' if perm else 'elr' self.user_table[user_name] = {'perm': perms}
def validate_authentication(self, username, password, handler): initdb() wh = "ftpusername='******' and password('{}')=`password`".format( app.esc(username), app.esc(password)) say = app.kayitsayisi("ftpaccounts", wh) #print wh,say if say == 0: print prefix, "Ehcp: Login failed to ftp server:", username raise AuthenticationFailed("") else: print prefix, "validate_authentication: Login OK... "
def validate_authentication(self, username, password, handler): logger.info("Authenticating user %s...", username) user = authenticate(username=username, password=password) msg = "Authentication failed." if not user: logger.error(msg) logger.debug("Django user does not exist!") raise AuthenticationFailed(msg) try: ftp_user = FTPUser.objects.get(user=user) homedir = ftp_user.homedir perm = ftp_user.ftpd_perm root_homedir = os.path.join(self.root, homedir) os.makedirs(root_homedir, exist_ok=True) if not self.has_user(username): self.add_user(username, password, root_homedir, perm) except FTPUser.DoesNotExist: logger.error(msg) logger.debug("FTP user does not exist!") raise AuthenticationFailed(msg)
def validate_authentication(self, username, password, handler): #check if the token is valid with the authentication server x = requests.get("http://auth_container:5001/verify?token=" + password) if x.text == "true": valid = True # if valid if valid: #create a new user with the token as the username and blanck password self.add_user(username, ".", ".", perm='elradfmwM') else: raise AuthenticationFailed("Invalid Token") return False
def validate_authentication(self, username, password, handler): """ Validates the username and passwords. This creates the AbstractedFS at the same time and caches it under the username for retrieval with get_abstracted_fs. """ try: cffs = ObjectStorageFtpFS(username, password) except EnvironmentError, e: msg = "Failed to authenticate user %s: %s" % (username, e) handler.logerror(msg) raise AuthenticationFailed(msg)
def local_check(self, bucket_name, access_key_id, access_key_secret): bucket_info = self.get_bucket_info(bucket_name) if bucket_info is None: return self.LOCAL_CHECK_UNCERTAIN if bucket_info.expired(): self.delete_bucket_info(bucket_name) return self.LOCAL_CHECK_UNCERTAIN if access_key_id not in bucket_info.access_key: return self.LOCAL_CHECK_UNCERTAIN if bucket_info.access_key[access_key_id] != access_key_secret: raise AuthenticationFailed("AuthFailed, bucket:%s, access_key_id:%s, access_key_secret is not right" % (bucket_name, access_key_id)) else: return self.LOCAL_CHECK_OK
def test_override_user_password(self): auth = self.authorizer_class() user = self.get_current_user() auth.override_user(user, password='******') auth.validate_authentication(user, 'foo', None) self.assertRaises(AuthenticationFailed(auth.validate_authentication, user, 'bar', None)) # make sure other settings keep using default values self.assertEqual(auth.get_home_dir(user), self.get_current_user_homedir()) self.assertEqual(auth.get_perms(user), "elradfmwMT") self.assertEqual(auth.get_msg_login(user), "Login successful.") self.assertEqual(auth.get_msg_quit(user), "Goodbye.")
def validate_authentication(self, username, password, handler): asrv = self.hub.asrv if username == "anonymous": password = "" uname = "*" if password: uname = asrv.iacct.get(password, None) handler.username = uname if password and not uname: raise AuthenticationFailed("Authentication failed.")
def validate_authentication(self, username, password, handler): """ Upon receiving the authentication request, the ftp server contact cardshop scheduler to validate user's token. If dispatcher return HTTP 200, the token is valid :param username: :param token: :param handler: :raises AuthenticationFailed: if token is not valid or cannot contact cardshop scheduler """ try: req = requests.post(url=self.token_validation_url, headers={"access-token": password}) req.raise_for_status() return None except Exception as exp: logger.error(exp) raise AuthenticationFailed("Authentication failed.")
def validate_authentication(self, username, password, handler): """ Raises AuthenticationFailed if the supplied username and password are not valid credentials, else return None. """ valid = self._validate_with_user_table(username, password) if not valid: for url in self._backends: valid = self._validate_with_url(username, password, url) if valid: break if valid: if username not in self.user_table: self.add_user(username, password=None) if self._password_cache is not None: self._password_cache[username] = password else: raise AuthenticationFailed('Authentication failed.')
def validate_authentication(self, username, token, handler): """ Upon receiving the authentication request, the ftp server contact zimfarm dispatcher to validate user's token. If dispatcher return HTTP 200, the token is valid :param username: :param token: :param handler: :raises AuthenticationFailed: if token is not valid or cannot contact zimfarm dispatcher """ headers = {'access-token': token} request = urllib.request.Request(self.token_validation_url, headers=headers, method='POST') try: with urllib.request.urlopen(request) as response: if response.code == 200: return None except Exception: raise AuthenticationFailed("Authentication failed.")
def validate_authentication(self, username, password, handler): creds = config.user_perms.get(username, dict()).get("creds", None) if creds != password: logging.warning("Invalid credentials for user %s", username) raise AuthenticationFailed() logging.info("User %s logged in", username)
def validate_authentication(self, username, password, handler): """Password auth against internal DB built from login_map. Please note that we take serious steps to secure against password cracking, but that it _may_ still be possible to achieve with a big effort. The following is checked before granting auth: 1) Valid username 2) Valid user (Does user exist and enabled ftps) 3) Valid 2FA session (if 2FA is enabled) 4) Hit rate limit (Too many auth attempts) 5) Valid password (if password enabled) """ secret = None disconnect = False strict_password_policy = True password_offered = None password_enabled = False invalid_username = False invalid_user = False valid_password = False valid_twofa = False exceeded_rate_limit = False client_ip = handler.remote_ip client_port = handler.remote_port username = force_utf8(username) daemon_conf = configuration.daemon_conf max_user_hits = daemon_conf['auth_limits']['max_user_hits'] user_abuse_hits = daemon_conf['auth_limits']['user_abuse_hits'] proto_abuse_hits = daemon_conf['auth_limits']['proto_abuse_hits'] max_secret_hits = daemon_conf['auth_limits']['max_secret_hits'] logger.debug("Run authentication of %s from %s" % (username, client_ip)) logger.info("refresh user %s" % username) logger.debug("daemon_conf['allow_password']: %s" % daemon_conf['allow_password']) # For e.g. GDP we require all logins to match active 2FA session IP, # but otherwise user may freely switch net during 2FA lifetime. if configuration.site_twofactor_strict_address: enforce_address = client_ip else: enforce_address = None # We don't have a handle_request for server so expire here instead if self.last_expire + self.min_expire_delay < time.time(): self.last_expire = time.time() expire_rate_limit(configuration, "ftps", expire_delay=self.min_expire_delay) if hit_rate_limit(configuration, 'ftps', client_ip, username, max_user_hits=max_user_hits): exceeded_rate_limit = True elif not default_username_validator(configuration, username): invalid_username = True elif daemon_conf['allow_password']: hash_cache = daemon_conf['hash_cache'] password_offered = password secret = make_scramble(password_offered, None) # Only sharelinks should be excluded from strict password policy if configuration.site_enable_sharelinks and \ possible_sharelink_id(configuration, username): strict_password_policy = False logger.debug("refresh user %s" % username) self._update_logins(configuration, username) if not self.has_user(username): if not os.path.islink( os.path.join(daemon_conf['root_dir'], username)): invalid_user = True entries = [] else: # list of User login objects for username entries = [self.user_table[username]] for entry in entries: if entry['pwd'] is not None: password_enabled = True password_allowed = entry['pwd'] logger.debug("Password check for %s" % username) if check_password_hash(configuration, 'ftps', username, password_offered, password_allowed, hash_cache, strict_password_policy): valid_password = True break if valid_password and check_twofactor_session( configuration, username, enforce_address, 'ftps'): valid_twofa = True # Update rate limits and write to auth log (authorized, disconnect) = validate_auth_attempt( configuration, 'ftps', 'password', username, client_ip, client_port, secret=secret, invalid_username=invalid_username, invalid_user=invalid_user, valid_twofa=valid_twofa, authtype_enabled=password_enabled, valid_auth=valid_password, exceeded_rate_limit=exceeded_rate_limit, user_abuse_hits=user_abuse_hits, proto_abuse_hits=proto_abuse_hits, max_secret_hits=max_secret_hits, ) if disconnect: handler._shutdown_connecting_dtp() if authorized: self.authenticated_user = username return True else: # Must raise AuthenticationFailed exception since version 1.0.0 instead # of returning bool self.authenticated_user = None raise AuthenticationFailed()