本文整理汇总了Python中esapi.core.ESAPI类的典型用法代码示例。如果您正苦于以下问题:Python ESAPI类的具体用法?Python ESAPI怎么用?Python ESAPI使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ESAPI类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: add_cookie
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: set_remember_token
def set_remember_token(self, password, max_age, domain, path, request=None, response=None):
if request is None:
request = self.current_request
if response is None:
response = self.current_response
user = ESAPI.authenticator().current_user
try:
self.kill_cookie(self.REMEMBER_TOKEN_COOKIE_NAME, request, response)
# Seal already contains random data
clear_token = user.account_name + "|" + password
expiry = datetime.now() + timedelta(seconds=max_age)
crypt_token = ESAPI.encryptor().seal(clear_token, expiry)
morsel = Cookie.Morsel()
morsel.value = crypt_token
morsel['max-age'] = max_age
morsel['domain'] = domain
morsel['path'] = path
response.cookies[self.REMEMBER_TOKEN_COOKIE_NAME] = morsel
self.logger.info( Logger.SECURITY_SUCCESS,
_("Enabled remember me token for %(user)s") %
{'user' : user.account_name} )
return crypt_token
except IntegrityException, extra:
self.logger.warning( Logger.SECURITY_FAILURE,
_("Attempt to set remember me token failed for %(user)s") %
{'user' : user.account_name}, extra )
示例3: test_is_authorized_for_function
def test_is_authorized_for_function(self):
instance = ESAPI.access_controller()
auth = ESAPI.authenticator()
auth.current_user = auth.get_user("ACAlice")
self.assertTrue(instance.is_authorized_for_function("/FunctionA"))
self.assertFalse(instance.is_authorized_for_function("/FunctionAdeny"))
self.assertFalse(instance.is_authorized_for_function("/FunctionB"))
self.assertFalse(instance.is_authorized_for_function("/FunctionBdeny"))
self.assertTrue(instance.is_authorized_for_function("/FunctionC"))
self.assertFalse(instance.is_authorized_for_function("/FunctionCdeny"))
auth.current_user = auth.get_user("ACBob")
self.assertFalse(instance.is_authorized_for_function("/FunctionA"))
self.assertFalse(instance.is_authorized_for_function("/FunctionAdeny"))
self.assertTrue(instance.is_authorized_for_function("/FunctionB"))
self.assertFalse(instance.is_authorized_for_function("/FunctionBdeny"))
self.assertTrue(instance.is_authorized_for_function("/FunctionD"))
self.assertFalse(instance.is_authorized_for_function("/FunctionDdeny"))
auth.current_user = auth.get_user("ACMitch")
self.assertTrue(instance.is_authorized_for_function("/FunctionA"))
self.assertFalse(instance.is_authorized_for_function("/FunctionAdeny"))
self.assertTrue(instance.is_authorized_for_function("/FunctionB"))
self.assertFalse(instance.is_authorized_for_function("/FunctionBdeny"))
self.assertTrue(instance.is_authorized_for_function("/FunctionC"))
self.assertFalse(instance.is_authorized_for_function("/FunctionCdeny"))
instance.assert_authorized_for_function("/FunctionA")
self.assertRaises(AccessControlException, instance.assert_authorized_for_function, "/FunctionDdeny" )
示例4: validate_roles
def validate_roles(self, roles):
"""
Checks that the roles passed in contain only letters, numbers, and
underscores. Also checks that roles are no more than 10 characters long.
If a role does not pass validation, it is not included in the list of
roles returned by this method. A log warning is also generated for any
invalid roles.
@param roles: the list of roles to validate according to the criteria
stated above.
@return: a list of roles that are valid according to the criteria
stated above.
"""
ret = []
for role in roles:
canonical = ''
try:
stripped = role.strip()
canonical = ESAPI.encoder().canonicalize(stripped)
except EncodingException, extra:
self.logger.warning( Logger.SECURITY_FAILURE,
_("Failed to canonicalize role: %(role)s") %
{'role' : stripped},
extra )
if not ESAPI.validator().is_valid_input(
"Roles in FileBasedAccessController",
canonical,
"AccessControlRule", 200, False ):
self.logger.warning( Logger.SECURITY_FAILURE,
_("Role is invalid, and was not added to the list of roles for this rule: %(role)s") %
{'role' : stripped} )
else:
示例5: add_exception
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: test_is_authorized_for_service
def test_is_authorized_for_service(self):
instance = ESAPI.access_controller()
auth = ESAPI.authenticator()
auth.current_user = auth.get_user("ACAlice")
self.assertTrue(instance.is_authorized_for_service("/services/ServiceA"))
self.assertFalse(instance.is_authorized_for_service("/services/ServiceB"))
self.assertTrue(instance.is_authorized_for_service("/services/ServiceC"))
self.assertFalse(instance.is_authorized_for_service("/test/ridiculous"))
auth.current_user = auth.get_user("ACBob")
self.assertFalse(instance.is_authorized_for_service("/services/ServiceA"))
self.assertTrue(instance.is_authorized_for_service("/services/ServiceB"))
self.assertFalse(instance.is_authorized_for_service("/services/ServiceF"))
self.assertFalse(instance.is_authorized_for_service("/test/ridiculous"))
auth.current_user = auth.get_user("ACMitch")
self.assertTrue(instance.is_authorized_for_service("/services/ServiceA"))
self.assertTrue(instance.is_authorized_for_service("/services/ServiceB"))
self.assertFalse(instance.is_authorized_for_service("/services/ServiceE"))
self.assertFalse(instance.is_authorized_for_service("/test/ridiculous"))
instance.assert_authorized_for_service("/services/ServiceD")
self.assertRaises(AccessControlException, instance.assert_authorized_for_service, "/test/ridiculous" )
示例7: log
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)
示例8: test_is_valid_dir_path
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))
示例9: test_encode_for_base64
def test_encode_for_base64(self):
instance = ESAPI.encoder()
self.assertEquals(None, instance.encode_for_base64(None))
self.assertEquals(None, instance.decode_from_base64(None))
for i in range(100):
random_string = ESAPI.randomizer().get_random_string( 20, Encoder.CHAR_SPECIALS )
encoded = instance.encode_for_base64( random_string )
decoded = instance.decode_from_base64( encoded )
self.assertEquals( random_string, decoded )
示例10: __init__
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"
示例11: test_add_exception
def test_add_exception(self):
ESAPI.intrusion_detector().add_exception( RuntimeError('message') )
ESAPI.intrusion_detector().add_exception(
ValidationException("user message", "log message") )
ESAPI.intrusion_detector().add_exception(
IntrusionException("user message", "log message") )
username = "testAddException"
password = "addException"
auth = ESAPI.authenticator()
user = auth.create_user(username, password, password)
user.enable()
request = MockHttpRequest()
response = MockHttpResponse()
ESAPI.http_utilities().set_current_http(request, response)
user.login_with_password(password)
# Generate some exceptions to disable the account
for i in range(15):
IntegrityException(
"IntegrityException %s" % i,
"IntegrityException %s" % i )
self.assertFalse(user.is_logged_in())
self.assertTrue(user.is_locked())
示例12: test_is_authorized_for_data
def test_is_authorized_for_data(self):
instance = ESAPI.access_controller()
auth = ESAPI.authenticator()
adminR = "java.util.ArrayList"
adminRW = "java.lang.Math"
userW = "java.util.Date"
userRW = "java.lang.String"
anyR = "java.io.BufferedReader"
userAdminR = "java.util.Random"
userAdminRW = "java.awt.event.MouseWheelEvent"
undefined = "java.io.FileWriter"
# test User
auth.current_user = auth.get_user("ACAlice")
self.assertTrue(instance.is_authorized_for_data("read", userRW))
self.assertFalse(instance.is_authorized_for_data("read", undefined))
self.assertFalse(instance.is_authorized_for_data("write", undefined))
self.assertFalse(instance.is_authorized_for_data("read", userW))
self.assertFalse(instance.is_authorized_for_data("read", adminRW))
self.assertTrue(instance.is_authorized_for_data("write", userRW))
self.assertTrue(instance.is_authorized_for_data("write", userW))
self.assertFalse(instance.is_authorized_for_data("write", anyR))
self.assertTrue(instance.is_authorized_for_data("read", anyR))
self.assertTrue(instance.is_authorized_for_data("read", userAdminR))
self.assertTrue(instance.is_authorized_for_data("write", userAdminRW))
# test Admin
auth.current_user = auth.get_user("ACBob")
self.assertTrue(instance.is_authorized_for_data("read", adminRW))
self.assertFalse(instance.is_authorized_for_data("read", undefined))
self.assertFalse(instance.is_authorized_for_data("write", undefined))
self.assertFalse(instance.is_authorized_for_data("read", userRW))
self.assertTrue(instance.is_authorized_for_data("write", adminRW))
self.assertFalse(instance.is_authorized_for_data("write", anyR))
self.assertTrue(instance.is_authorized_for_data("read", anyR))
self.assertTrue(instance.is_authorized_for_data("read", userAdminR))
self.assertTrue(instance.is_authorized_for_data("write", userAdminRW))
# test User/Admin
auth.current_user = auth.get_user("ACMitch")
self.assertTrue(instance.is_authorized_for_data("read", userRW))
self.assertFalse(instance.is_authorized_for_data("read", undefined))
self.assertFalse(instance.is_authorized_for_data("write", undefined))
self.assertFalse(instance.is_authorized_for_data("read", userW))
self.assertTrue(instance.is_authorized_for_data("read", adminR))
self.assertTrue(instance.is_authorized_for_data("write", userRW))
self.assertTrue(instance.is_authorized_for_data("write", userW))
self.assertFalse(instance.is_authorized_for_data("write", anyR))
self.assertTrue(instance.is_authorized_for_data("read", anyR))
self.assertTrue(instance.is_authorized_for_data("read", userAdminR))
self.assertTrue(instance.is_authorized_for_data("write", userAdminRW))
instance.assert_authorized_for_data("read", userRW)
self.assertRaises(AccessControlException, instance.assert_authorized_for_data, "write", adminR )
示例13: set_header
def set_header(self, name, value, response=None):
if response is None:
response = self.current_response
try:
safe_name = ESAPI.validator().get_valid_input("setHeader", name.strip(), "HTTPHeaderName", 20, False)
safe_value = ESAPI.validator().get_valid_input("setHeader", value.strip(), "HTTPHeaderValue", 500, False)
response[safe_name] = safe_value
except ValidationException, extra:
self.logger( Logger.SECURITY_FAILURE,
_("Attempt to set invalid header denied"),
extra )
示例14: test_add_csrf_token
def test_add_csrf_token(self):
instance = ESAPI.authenticator()
username = "addCSRFUser"
password = 'addCSRFToken'
user = instance.create_user(username, password, password)
instance.current_user = user
csrf1 = ESAPI.http_utilities().add_csrf_token('/test1')
self.assertTrue(csrf1.find('?') > -1)
csrf2 = ESAPI.http_utilities().add_csrf_token('test1?one=two')
self.assertTrue(csrf2.find('?') > -1)
示例15: test_decode_from_base64
def test_decode_from_base64(self):
instance = ESAPI.encoder()
for i in range(100):
random_string = ESAPI.randomizer().get_random_string( 20, Encoder.CHAR_SPECIALS )
encoded = instance.encode_for_base64( random_string )
decoded = instance.decode_from_base64( encoded )
self.assertEqual( random_string, decoded )
for i in range(100):
random_string = ESAPI.randomizer().get_random_string( 20, Encoder.CHAR_SPECIALS )
encoded = ESAPI.randomizer().get_random_string(1, Encoder.CHAR_ALPHANUMERICS) + instance.encode_for_base64( random_string )
decoded = instance.decode_from_base64( encoded )
self.assertFalse( random_string == decoded )