本文整理汇总了Python中esapi.core.ESAPI.security_configuration方法的典型用法代码示例。如果您正苦于以下问题:Python ESAPI.security_configuration方法的具体用法?Python ESAPI.security_configuration怎么用?Python ESAPI.security_configuration使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类esapi.core.ESAPI
的用法示例。
在下文中一共展示了ESAPI.security_configuration方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: add_cookie
# 需要导入模块: from esapi.core import ESAPI [as 别名]
# 或者: from esapi.core.ESAPI import security_configuration [as 别名]
def add_cookie(self, response=None, **kwargs):
if response is None:
response = self.current_response
if not kwargs.has_key('secure'):
if ESAPI.security_configuration().get_force_secure_cookies():
kwargs['secure'] = True
if not kwargs.has_key('httponly'):
if ESAPI.security_configuration().get_force_http_only_cookies():
kwargs['httponly'] = True
# Validate the key and value
errors = ValidationErrorList()
safe_key = ESAPI.validator().get_valid_input("cookie name",
kwargs['key'], "HTTPCookieName", 50, False, errors)
safe_value = ESAPI.validator().get_valid_input("cookie value",
kwargs['value'], "HTTPCookieValue", 5000, False, errors)
kwargs['key'] = safe_key
kwargs['value'] = safe_value
# If no errors, set the cookie
if len(errors) == 0:
response.set_cookie(**kwargs)
return
# Error!
self.logger.warning( Logger.SECURITY_FAILURE,
_("Attempt to add unsafe data to cookie (skip mode). Skipping cookie and continuing.") )
示例2: test_is_valid_dir_path
# 需要导入模块: from esapi.core import ESAPI [as 别名]
# 或者: from esapi.core.ESAPI import security_configuration [as 别名]
def test_is_valid_dir_path(self):
encoder_class = ESAPI.security_configuration().get_class_for_interface('encoder')
validator_class = ESAPI.security_configuration().get_class_for_interface('validator')
encoder = encoder_class([HTMLEntityCodec()])
instance = validator_class(encoder)
if os.name == 'nt': # Windows
# Windows paths that don't exist and thus should fail
self.assertFalse(instance.is_valid_directory_path("test", "c:\\ridiculous", "c:\\", False))
self.assertFalse(instance.is_valid_directory_path("test", "c:\\jeff", "c:\\", False))
self.assertFalse(instance.is_valid_directory_path("test", "c:\\temp\\..\\etc", "c:\\", False))
# When the parent directory doesn't exist, these should fail
self.assertFalse(instance.is_valid_directory_path("test", "c:\\", "c:\\ridiculous", False))
self.assertFalse(instance.is_valid_directory_path("test", "c:\\", None, False))
# Windows paths that should pass
self.assertTrue(instance.is_valid_directory_path("test", "C:\\", "C:\\", False)) # Windows root directory
self.assertTrue(instance.is_valid_directory_path("test", "C:\\Windows", "C:\\", False)) # Windows always exist directory
# Should fail for files
self.assertFalse(instance.is_valid_directory_path("test", "C:\\Windows\\System32\\cmd.exe", "C:\\", False)) # Windows command shell
# Testing case insensitivity between input and parent_dir
self.assertTrue(instance.is_valid_directory_path("test", "C:\\", "c:\\", False)) # Windows root directory
self.assertTrue(instance.is_valid_directory_path("test", "c:\\Windows", "C:\\", False)) # Windows always exist directory
# Testing the verification of the parent directory
self.assertFalse(instance.is_valid_directory_path("test", "c:\\", "C:\\windows", False)) # Windows always exist directory
self.assertFalse(instance.is_valid_directory_path("test", "C:\\", "C:\\windows", False)) # Windows always exist directory
# Unix specific paths should not pass
self.assertFalse(instance.is_valid_directory_path("test", "/tmp", "/", False)) # Unix Temporary directory
self.assertFalse(instance.is_valid_directory_path("test", "/bin/sh", "/", False)) # Unix Standard shell
self.assertFalse(instance.is_valid_directory_path("test", "/etc/config", "/", False))
# Unix specific paths that should not exist or work
self.assertFalse(instance.is_valid_directory_path("test", "/etc/ridiculous", "/", False))
self.assertFalse(instance.is_valid_directory_path("test", "/tmp/../etc", "/", False))
else:
# Windows paths should fail
self.assertFalse(instance.is_valid_directory_path("test", "c:\\ridiculous", "c:\\", False))
self.assertFalse(instance.is_valid_directory_path("test", "c:\\temp\\..\\etc", "c:\\", False))
# Standard Windows locations should fail
self.assertFalse(instance.is_valid_directory_path("test", "c:\\", "c:\\", False))
self.assertFalse(instance.is_valid_directory_path("test", "c:\\Windows\\temp", "c:\\", False))
self.assertFalse(instance.is_valid_directory_path("test", "c:\\Windows\\System32\\cmd.exe", "c:\\", False))
# Unix specific paths should pass
# Root
self.assertTrue(instance.is_valid_directory_path("test", "/", "/", False))
# /bin
self.assertTrue(instance.is_valid_directory_path("test", "/bin", "/", False))
# Unix specific paths that should not exist or work
self.assertFalse(instance.is_valid_directory_path("test", "/etc/ridiculous", "/", False))
self.assertFalse(instance.is_valid_directory_path("test", "/tmp/../etc", "/", False))
示例3: __init__
# 需要导入模块: from esapi.core import ESAPI [as 别名]
# 或者: from esapi.core.ESAPI import security_configuration [as 别名]
def __init__(self):
Encryptor.__init__(self)
self.logger = ESAPI.logger("DefaultEncryptor")
# Hashing
self.hash_algorithm = ESAPI.security_configuration().get_hash_algorithm()
self.hash_iterations = ESAPI.security_configuration().get_hash_iterations()
# Encryption
self.encrypt_algorithm = ESAPI.security_configuration().get_encryption_algorithm()
if self.encrypt_algorithm not in self.VALID_ENCRYPTION_ALGOS:
raise EncryptionException(
_("Encryption Failure - Unknown algorithm for encryption: %(algorithm)s") %
{'algorithm' : self.encrypt_algorithm} )
self.encryption_key_length = ESAPI.security_configuration().get_encryption_key_length()
self.master_salt = ESAPI.security_configuration().get_master_salt()
# Public key crypto
self.signing_algorithm = ESAPI.security_configuration().get_digital_signature_algorithm()
if self.signing_algorithm not in self.VALID_SIGNING_ALGOS:
raise EncryptionException(
_("Failure to encrypt"),
_("Encryption Failure - Unknown algorithm for signing: %(algorithm)s") %
{'algorithm' : self.signing_algorithm} )
self.signing_key_length = ESAPI.security_configuration().get_digital_signature_key_length()
# Key locations
self.keys_location = os.path.realpath(ESAPI.security_configuration().get_encryption_keys_location()) + '/'
self.keys_symmetric_location = self.keys_location + "symmetric"
self.keys_asymmetric_private_location = self.keys_location + "asymmetric-private"
self.keys_asymmetric_public_location = self.keys_location + "asymmetric-public"
示例4: __init__
# 需要导入模块: from esapi.core import ESAPI [as 别名]
# 或者: from esapi.core.ESAPI import security_configuration [as 别名]
def __init__(self):
self.logger = ESAPI.logger("Executor")
self.working_dir = ESAPI.security_configuration().get_working_directory()
self.max_running_time = ESAPI.security_configuration().get_max_running_time()
if os.name == "nt":
self.logger.warning(
Logger.SECURITY_SUCCESS,
_("Using WindowsCodec for Executor. If this is not running on Windows, this could allow for injection"),
)
self.codec = WindowsCodec()
else:
self.logger.warning(
Logger.SECURITY_SUCCESS,
_("Using UnixCodec for Executor. If this is not running on Unix, this could allow injection"),
)
self.codec = UnixCodec()
示例5: add_exception
# 需要导入模块: from esapi.core import ESAPI [as 别名]
# 或者: from esapi.core.ESAPI import security_configuration [as 别名]
def add_exception(self, exception):
# Log the exception
if hasattr(exception, 'get_log_message'):
self.logger.warning( Logger.SECURITY_FAILURE,
exception.get_log_message(),
exception )
else:
self.logger.warning( Logger.SECURITY_FAILURE,
exception.message,
exception )
if isinstance(exception, IntrusionException):
return
# Add the exception to the current user, which may trigger a
# dector
user = ESAPI.authenticator().current_user
event_name = exception.__class__.__name__
try:
self.add_security_event(user, event_name)
except IntrusionException, extra:
quota = ESAPI.security_configuration().get_quota(event_name)
for action in quota.actions:
message = (_("User exceeded quota of %(count)s per %(interval)s seconds for event %(event_name)s. Taking actions %(actions)s") %
{'count' : quota.count,
'interval' : quota.interval,
'event_name' : event_name,
'actions' : quota.actions,})
self.take_security_action(action, message)
示例6: log
# 需要导入模块: from esapi.core import ESAPI [as 别名]
# 或者: from esapi.core.ESAPI import security_configuration [as 别名]
def log(self, level, event_type, message, exception=None):
"""
Log the message after optionally encoding any special characters
that might be dangerous when viewed by an HTML based log viewer.
Also encode any carriage returns and line feeds to prevent log
injection attacks. This logs all the supplied parameters plus the
user ID, user's source IP, a logging specific session ID, and the
current date/time.
It will only log the message if the current logging level is
enabled, otherwise it will discard the message.
@param level: the severity level of the security event
@param event_type: the event_type of the event
(SECURITY, FUNCTIONALITY, etc.)
@param message: the message
@param exception: an exception
"""
# Before we waste all kinds of time preparing this event for the
# log, let check to see if its loggable
if not self.pyLogger.isEnabledFor(level):
return
user = ESAPI.authenticator().current_user
# create a random session number for the user to represent the
# user's 'session', if it doesn't exist already
sid = _("unknown")
request = ESAPI.http_utilities().current_request
if request is not None:
session = request.session
if session is not None:
sid = session.get('ESAPI_SESSION', None)
# if there is no session id for the user yet, create one
# and store it in the user's session
if sid is None:
sid = str(ESAPI.randomizer().get_random_integer(0, 1000000))
session['ESAPI_SESSION'] = sid
# ensure there's something to log
if message is None:
message = ""
# ensure no CRLF injection into logs for forging records
clean = message.replace('\n', '_').replace('\r', '_')
if ESAPI.security_configuration().get_log_encoding_required():
clean = ESAPI.encoder().encode_for_html(message)
if message != clean:
clean += " (Encoded)"
extra = {
'eventType' : str(event_type),
'eventSuccess' : [_("SUCCESS"),_("FAILURE")][event_type.is_success()],
'user' : user.account_name,
'hostname' : user.last_host_address,
'sessionID' : sid,
}
self.pyLogger.log(level, clean, extra=extra)
示例7: make_file_validator
# 需要导入模块: from esapi.core import ESAPI [as 别名]
# 或者: from esapi.core.ESAPI import security_configuration [as 别名]
def make_file_validator(self):
if DefaultValidator.file_validator is not None:
return
DefaultValidator.file_validator = 'fail'
file_codecs = [HTMLEntityCodec(), PercentCodec()]
encoder_class = ESAPI.security_configuration().get_class_for_interface('encoder')
file_encoder = encoder_class(file_codecs)
DefaultValidator.file_validator = DefaultValidator( file_encoder )
示例8: get_valid_input
# 需要导入模块: from esapi.core import ESAPI [as 别名]
# 或者: from esapi.core.ESAPI import security_configuration [as 别名]
def get_valid_input(self, context, input_, type_, max_length, allow_none, error_list=None):
rvr = StringValidationRule( type_, self.encoder )
pattern = ESAPI.security_configuration().get_validation_pattern(type_)
if pattern is not None:
rvr.add_whitelist_pattern(pattern)
else:
rvr.add_whitelist_pattern(type_)
rvr.set_maximum_length(max_length)
rvr.set_allow_none(allow_none)
return rvr.get_valid(context, input_, error_list)
示例9: login_with_password
# 需要导入模块: from esapi.core import ESAPI [as 别名]
# 或者: from esapi.core.ESAPI import security_configuration [as 别名]
def login_with_password(self, password):
if password is None:
self.last_failed_login_time = datetime.now()
self.increment_failed_login_count()
raise AuthenticationLoginException( _("Login failed"),
_("Missing password: %(account_name)s") %
{'account_name' : self.account_name})
# Don't let disabled users log in
if not self.is_enabled():
self.last_failed_login_time = datetime.now()
self.increment_failed_login_count()
raise AuthenticationLoginException( _("Login failed"),
_("Disabled user attempt to login: %(account_name)s") %
{'account_name' : self.account_name})
# Don't let locked users log in
if self.is_locked():
self.last_failed_login_time = datetime.now()
self.increment_failed_login_count()
raise AuthenticationLoginException( _("Login failed"),
_("Locked user attempt to login: %(account_name)s") %
{'account_name' : self.account_name})
# Don't let expired users log in
if self.is_expired():
self.last_failed_login_time = datetime.now()
self.increment_failed_login_count()
raise AuthenticationLoginException( _("Login failed"),
_("Expired user attempt to login: %(account_name)s") %
{'account_name' : self.account_name})
self.logout()
if self.verify_password( password ):
self._logged_in = True
ESAPI.http_utilities().change_session_identifier( ESAPI.current_request() )
ESAPI.authenticator().current_user = self
self.last_login_time = datetime.now()
self.last_host_address = ESAPI.http_utilities().get_current_request().remote_host
self.logger.trace(Logger.SECURITY_SUCCESS,
_("User logged in: %(account_name)s") %
{'account_name' : self.account_name})
else:
self._logged_in = False
self.last_failed_login_time = datetime.now()
self.increment_failed_login_count()
if self.get_failed_login_count() >= ESAPI.security_configuration().get_allowed_login_attempts():
self.lock()
raise AuthenticationLoginException( _("Login failed"),
_("Incorrect password provided for %(account_name)s") %
{'account_name' : self.account_name})
示例10: get_valid_file_content
# 需要导入模块: from esapi.core import ESAPI [as 别名]
# 或者: from esapi.core.ESAPI import security_configuration [as 别名]
def get_valid_file_content(self, context, input_, max_bytes, allow_none, errors=None ):
"""
This implementation only verifies that the file size is less than or
equal to the max_bytes specified in the parameter and less than the
max bytes specified in ESAPI.conf.settings.
"""
try:
if self.is_empty(input_):
if allow_none:
return None
raise ValidationException( _("%(context)s: Input required") %
{'context' : context},
_("Input required: context=%(context)s, input=%(input)s") %
{'context' : context,
'input' : input_},
context )
esapi_max_bytes = ESAPI.security_configuration().get_allowed_file_upload_size()
if len(input_) > esapi_max_bytes:
raise ValidationException(
_("%(context)s: Invalid file content can not exceed %(max_bytes)s bytes") %
{'context' : context,
'max_bytes' : esapi_max_bytes},
_("Exceeded ESAPI max length of %(max_bytes) bytes by %(exceeded)s bytes") %
{'max_bytes' : esapi_max_bytes,
'exceeded' : len(input_) - esapi_max_bytes},
context )
if len(input_) > max_bytes:
raise ValidationException(
_("%(context)s: Invalid file content can not exceed %(max_bytes)s bytes") %
{'context' : context,
'max_bytes' : max_bytes},
_("Exceeded max_bytes of %(max_bytes)s bytes by %(exceeded)s bytes") %
{'max_bytes' : max_bytes,
'exceeded' : len(input_) - max_bytes},
context )
return input_
except ValidationException, extra:
if errors is not None:
errors[context] = extra
else:
raise
示例11: add_security_event
# 需要导入模块: from esapi.core import ESAPI [as 别名]
# 或者: from esapi.core.ESAPI import security_configuration [as 别名]
def add_security_event(self, user, event_name):
"""
Adds a security event to the user. These events are used to check
that the user has not reached the security thresholds set in the
SecurityConfiguration.
@param user: the user tha caused the event
@param event_name: the name of the event that occurred.
"""
if user.is_anonymous():
return
threshold = ESAPI.security_configuration().get_quota(event_name)
if threshold is not None:
event = user.event_map.get(event_name)
if event is None:
event = self.Event(event_name)
user.event_map[event_name] = event
event.increment(threshold.count, threshold.interval)
示例12: add_event
# 需要导入模块: from esapi.core import ESAPI [as 别名]
# 或者: from esapi.core.ESAPI import security_configuration [as 别名]
def add_event(self, event_name, log_message):
self.logger.warning( Logger.SECURITY_FAILURE,
_("Security event %(name)s received: %(message)s") %
{'name' : event_name,
'message' : log_message,} )
# Add the event to the current user, which may trigger a detector
user = ESAPI.authenticator().current_user
try:
self.add_security_event(user, "event_" + event_name)
except IntrusionException, extra:
quota = ESAPI.security_configuration().get_quota("event_" + event_name)
for action in quota.actions:
message = (_("User exceeded quota of %(count)s per %(interval)s seconds for event %(event_name)s. Taking actions %(actions)s") %
{'count' : quota.count,
'interval' : quota.interval,
'event_name' : event_name,
'actions' : quota.actions,})
self.take_security_action(action, message)
示例13: get_valid_filename
# 需要导入模块: from esapi.core import ESAPI [as 别名]
# 或者: from esapi.core.ESAPI import security_configuration [as 别名]
def get_valid_filename( self, context, input_, allow_none, error_list=None, allowed_extensions=None):
try:
if self.is_empty(input_):
if allow_none:
return None
raise ValidationException( _("%(context)s: Input file name required") %
{'context' : context},
_("Input required: context=%(context)s, input=%(input)s") %
{'context' : context,
'input' : input_},
context )
# Do basic validation
self.get_valid_input(context, input_, "Filename", 255, True)
# Verify extensions
if not allowed_extensions:
allowed_extensions = ESAPI.security_configuration().get_allowed_file_extensions()
file_ext = os.path.splitext(input_)[1]
file_ext = file_ext.lower()
if file_ext in allowed_extensions:
return input_
else:
raise ValidationException(
_("%(context)s: Invalid file name does not have valid extension ( %(allowed_extensions)s )") %
{'context' : context,
'allowed_extensions' : allowed_extensions},
_("Invalid file name does not have valid extension ( %(allowed_extensions)s ): context=%(context)s, input=%(input)s") %
{'allowed_extensions' : allowed_extensions,
'context' : context,
'input' : input_},
context )
except ValidationException, extra:
if error_list is not None:
error_list[context] = extra
else:
raise
示例14: get_cc_rule
# 需要导入模块: from esapi.core import ESAPI [as 别名]
# 或者: from esapi.core.ESAPI import security_configuration [as 别名]
def get_cc_rule(self, encoder):
pattern = ESAPI.security_configuration().get_validation_pattern("CreditCard")
ccr = StringValidationRule("ccrule", encoder, pattern)
ccr.set_maximum_length(CC_MAX_LENGTH)
ccr.set_allow_none(False)
return ccr
示例15: load_rules
# 需要导入模块: from esapi.core import ESAPI [as 别名]
# 或者: from esapi.core.ESAPI import security_configuration [as 别名]
def load_rules(self, rule_file):
"""
Loads the access rules by storing them in a dictionary. This method
reads the file specified by the rule_file parameter, ignoring any lines
that begin with the '#' character as comments. Sections of the access
rules file are split by the '|' character. The method loads all paths,
replacing '\\\\' characters with '/' for uniformity, then loads the list
of comma separated roles. The roles are validated to be sure they are
within the length and character set limitations specified in the
validate_roles method. Then the permissions are stored for each item
in the rules list.
If the word 'allow' appears on the line, the specified roles are
granted access to the data - otherwise, they will be denied access.
Each path may only appear once in the access rules file. Any entry,
after the first, containing the same path will be logged and ignored.
@param rule_file: the name of the file that contains the access rules
@return: a dictionary mapping path -> Rule object
"""
ret = {}
input_file = None
try:
filename = ESAPI.security_configuration().get_resource_file(rule_file)
input_file = open(filename, 'r')
line = ESAPI.validator().safe_read_line(input_file, 500)
while line != '':
line = line.strip()
if len(line) > 0 and line[0] != '#':
rule = Rule()
parts = line.split('|')
rule.path = parts[0].strip().replace("\\\\", "/")
roles = parts[1].strip().lower().split(',')
roles = self.validate_roles(roles)
for role in roles:
rule.roles.append(role.strip())
action = parts[2].strip().lower()
if action == 'allow' or action == 'deny':
rule.allow = action == 'allow'
else:
for act in action.split(','):
rule.actions.append(act.strip())
if ret.has_key(rule.path):
self.logger.warning( Logger.SECURITY_FAILURE,
_("Problem in access control file. Duplicate rule ignored: %(rule)s") %
{'rule' : rule} )
else:
ret[rule.path] = rule
line = ESAPI.validator().safe_read_line(input_file, 500)
except Exception, extra:
raise
self.logger.warning( Logger.SECURITY_FAILURE,
_("Problem in access control file: %(file)s") %
{'file' : rule_file},