Changeset 6730 for TI12-security/trunk/NDGSecurity
- Timestamp:
- 16/03/10 08:37:55 (11 years ago)
- Location:
- TI12-security/trunk/NDGSecurity/python
- Files:
-
- 4 added
- 11 deleted
- 7 edited
Legend:
- Unmodified
- Added
- Removed
-
TI12-security/trunk/NDGSecurity/python/ndg_security_common/ndg/security/common/authz/xacml/__init__.py
r6673 r6730 1 class XACMLError(Exception): 2 """Base class for XACML package exception types""" 3 4 5 class XMLParseError(XACMLError): 6 """XACML package XML Parsing error""" 7 8 1 9 class PolicyComponent(object): 2 10 """Base class for Policy and Policy subelements""" -
TI12-security/trunk/NDGSecurity/python/ndg_security_common/ndg/security/common/authz/xacml/policy.py
r6643 r6730 39 39 40 40 class Policy(PolicyComponent): 41 """NDG MSI Policy.""" 41 """NDG MSI Policy.""" 42 POLICY_ID_ATTRIB_NAME = "PolicyId" 43 RULE_COMBINING_ALG_ID_ATTRIB_NAME = "RuleCombiningAlgId" 44 42 45 DESCRIPTION_LOCALNAME = "Description" 43 46 TARGET_LOCALNAME = "Target" 47 POLICY_DEFAULTS_LOCALNAME = "PolicyDefaults" 48 OBLIGATIONS_LOCALNAME = "Obligations" 49 RULE_LOCALNAME = "Rule" 44 50 45 51 # Plan to support permit overrides in a future release -
TI12-security/trunk/NDGSecurity/python/ndg_security_common/ndg/security/common/credentialwallet.py
r6673 r6730 16 16 import os 17 17 import warnings 18 import traceback19 18 20 19 # Check Attribute Certificate validity times … … 26 25 from ndg.saml.saml2.core import Assertion 27 26 28 # Access Attribute Authority's web service using ZSI - allow pass if not29 # loaded since it's possible to make AttributeAuthority instance locally30 # without using the WS31 aaImportError = True32 try:33 # AttributeAuthority client package resides with CredentialWallet module in34 # ndg.security.common35 from ndg.security.common.attributeauthority import (36 AttributeAuthorityClient, AttributeAuthorityClientError,37 AttributeRequestDenied, NoMatchingRoleInTrustedHosts)38 aaImportError = False39 except ImportError:40 pass41 42 # Likewise - may not want to use WS and use AttributeAuthority locally in which43 # case no need to import it44 try:45 from ndg.security.server.attributeauthority import (AttributeAuthority,46 AttributeAuthorityError, AttributeAuthorityAccessDenied)47 aaImportError = False48 except ImportError:49 pass50 51 if aaImportError:52 raise ImportError("Either AttributeAuthority or AttributeAuthorityClient "53 "classes must be present to allow interoperation with "54 "Attribute Authorities: %s" % traceback.format_exc())55 56 # Authentication X.509 Certificate57 from ndg.security.common.X509 import X509Cert58 from M2Crypto import X509, BIO, RSA59 60 # Authorisation - attribute certificate61 from ndg.security.common.AttCert import AttCert, AttCertError62 from ndg.security.common.wssecurity.signaturehandler.dom import SignatureHandler63 64 # generic parser to read INI/XML properties file65 from ndg.security.common.utils.configfileparsers import \66 INIPropertyFileWithValidation67 68 from ndg.security.common.utils import TypedList69 27 from ndg.security.common.utils.configfileparsers import ( 70 28 CaseSensitiveConfigParser,) … … 178 136 __slots__ = tuple(["__%s" % n for n in __ATTRIBUTE_NAMES]) 179 137 180 def __init__(self, type=None):138 def __init__(self, _type=None): 181 139 self.__type = None 182 self.type = type140 self.type = _type 183 141 184 142 self.__id = -1 … … 700 658 701 659 def __init__(self, propFilePath=None, dbPPhrase=None, **prop): 702 pass660 """Null Credential Repository __init__ placeholder""" 703 661 704 662 def addUser(self, userId): 705 pass663 """Null Credential Repository addUser placeholder""" 706 664 707 665 def auditCredentials(self, **attCertValidKeys): 708 pass666 """Null Credential Repository addUser placeholder""" 709 667 710 668 def getCredentials(self, userId): 669 """Null Credential Repository getCredentials placeholder""" 711 670 return [] 712 671 713 672 def addCredentials(self, userId, attCertList): 714 pass673 """Null Credential Repository addCredentials placeholder""" -
TI12-security/trunk/NDGSecurity/python/ndg_security_common/ndg/security/common/utils/__init__.py
r5870 r6730 76 76 77 77 return super(TypedList, self).append(item) 78 79 class RestrictedKeyNamesDict(dict): 80 """Utility class for holding a constrained list of key names 81 """ 82 83 def __init__(self, *arg, **kw): 84 """Alter standard dict() initialisation to fix key names set at 85 initialisation 86 """ 87 super(RestrictedKeyNamesDict, self).__init__(*arg, **kw) 88 self.__keyNames = self.keys() 89 90 def __setitem__(self, key, val): 91 if key not in self.__keyNames: 92 raise KeyError('Key name %r not recognised. Valid key names ' 93 'are: %r' % (key, self.__keyNames)) 94 95 dict.__setitem__(self, key, val) 96 97 def update(self, d, **kw): 98 for dictArg in (d, kw): 99 for k in dictArg: 100 if k not in self.__keyNames: 101 raise KeyError('Key name "%s" not recognised. Valid ' 102 'key names are: %s' % 103 self.__keyNames) 104 105 dict.update(self, d, **kw) -
TI12-security/trunk/NDGSecurity/python/ndg_security_server/ndg/security/server/attributeauthority.py
r6721 r6730 38 38 from ndg.security.common.saml_utils.esg import EsgSamlNamespaces 39 39 from ndg.security.common.X509 import X500DN 40 from ndg.security.common.utils import TypedList 40 from ndg.security.common.utils import TypedList, RestrictedKeyNamesDict 41 41 from ndg.security.common.utils.classfactory import instantiateClass 42 42 from ndg.security.common.utils.configfileparsers import ( … … 93 93 ISSUER_NAME_OPTNAME = 'issuerName' 94 94 ASSERTION_LIFETIME_OPTNAME = 'assertionLifetime' 95 DN_SEPARATOR_OPTNAME = 'dnSeparator'96 95 97 96 ATTRIBUTE_INTERFACE_OPTPREFIX = 'attributeInterface' … … 113 112 ISSUER_NAME_OPTNAME: '', 114 113 ASSERTION_LIFETIME_OPTNAME: -1, 115 DN_SEPARATOR_OPTNAME: '/',116 114 ATTRIBUTE_INTERFACE_OPTPREFIX: ATTRIBUTE_INTERFACE_PROPERTY_DEFAULTS 117 115 } … … 119 117 __slots__ = ( 120 118 '__assertionLifetime', 121 '__dnSeparator',122 119 '__propFilePath', 123 120 '__propFileSection', … … 133 130 # Initial config file property based attributes 134 131 self.__assertionLifetime = None 135 self.__dnSeparator = None136 132 137 133 self.__propFilePath = None … … 139 135 self.__propPrefix = '' 140 136 141 self.__attributeInterfaceCfg = {} 137 self.__attributeInterfaceCfg = RestrictedKeyNamesDict( 138 AttributeAuthority.ATTRIBUTE_INTERFACE_PROPERTY_DEFAULTS) 142 139 143 140 def __getstate__(self): … … 189 186 doc="Settings for Attribute Interface " 190 187 "initialisation") 191 192 def _get_dnSeparator(self):193 return self.__dnSeparator194 195 def _set_dnSeparator(self, value):196 if not isinstance(value, basestring):197 raise TypeError('Expecting string type for "dnSeparator"; got '198 '%r' % type(value))199 self.__dnSeparator = value200 201 dnSeparator = property(fget=_get_dnSeparator,202 fset=_set_dnSeparator,203 doc="Distinguished Name separator character used "204 "with X.509 Certificate issuer certificate")205 188 206 189 def setPropFilePath(self, val=None): -
TI12-security/trunk/NDGSecurity/python/ndg_security_test/ndg/security/test/config/attributeauthority/sitea/site-a.ini
r6721 r6730 47 47 # Lifetime is measured in seconds 48 48 attributeAuthority.assertionLifetime: 28800 49 50 attributeAuthority.dnSeparator:/51 49 52 50 # Settings for custom AttributeInterface derived class to get user roles for given -
TI12-security/trunk/NDGSecurity/python/ndg_security_test/ndg/security/test/unit/credentialwallet/test_credentialwallet.py
r6615 r6730 1 1 #!/usr/bin/env python 2 """Unit tests for Credential Wallet class es2 """Unit tests for Credential Wallet class 3 3 4 4 NERC DataGrid Project … … 10 10 __contact__ = "Philip.Kershaw@stfc.ac.uk" 11 11 __revision__ = '$Id: $' 12 import logging 13 logging.basicConfig(level=logging.DEBUG) 12 14 13 15 import unittest 14 import os, sys, getpass, re 15 import traceback 16 import os 16 17 17 18 from string import Template … … 23 24 from time import sleep 24 25 from datetime import datetime, timedelta 26 25 27 from ndg.saml.utils import SAMLDateTime 26 28 from ndg.saml.xml.etree import AssertionElementTree 27 29 28 30 from ndg.security.test.unit import BaseTestCase 31 from ndg.security.common.utils.etree import prettyPrint 32 from ndg.security.common.credentialwallet import SAMLCredentialWallet 29 33 30 from ndg.security.common.utils.configfileparsers import (31 CaseSensitiveConfigParser)32 from ndg.security.common.utils.etree import prettyPrint33 from ndg.security.common.X509 import X509CertParse34 from ndg.security.common.credentialwallet import (NDGCredentialWallet,35 CredentialWalletAttributeRequestDenied, SAMLCredentialWallet)36 from ndg.security.server.attributeauthority import AttributeAuthority37 38 from os.path import expandvars as xpdVars39 from os.path import join as jnPath40 mkPath = lambda file: jnPath(os.environ['NDGSEC_CREDWALLET_UNITTEST_DIR'], file)41 42 import logging43 logging.basicConfig(level=logging.DEBUG)44 45 46 class NDGCredentialWalletTestCase(BaseTestCase):47 """Unit test case for48 ndg.security.common.credentialwallet.NDGCredentialWallet class.49 """50 THIS_DIR = os.path.dirname(__file__)51 PICKLE_FILENAME = 'NDGCredentialWalletPickle.dat'52 PICKLE_FILEPATH = os.path.join(THIS_DIR, PICKLE_FILENAME)53 54 def __init__(self, *arg, **kw):55 super(NDGCredentialWalletTestCase, self).__init__(*arg, **kw)56 self.startAttributeAuthorities()57 58 def setUp(self):59 super(NDGCredentialWalletTestCase, self).setUp()60 61 if 'NDGSEC_INT_DEBUG' in os.environ:62 import pdb63 pdb.set_trace()64 65 if 'NDGSEC_CREDWALLET_UNITTEST_DIR' not in os.environ:66 os.environ['NDGSEC_CREDWALLET_UNITTEST_DIR'] = \67 os.path.abspath(os.path.dirname(__file__))68 69 self.cfg = CaseSensitiveConfigParser()70 configFilePath = jnPath(os.environ['NDGSEC_CREDWALLET_UNITTEST_DIR'],71 "credWalletTest.cfg")72 self.cfg.read(configFilePath)73 74 self.userX509CertFilePath=self.cfg.get('setUp', 'userX509CertFilePath')75 self.userPriKeyFilePath=self.cfg.get('setUp', 'userPriKeyFilePath')76 77 78 def test01ReadOnlyClassVariables(self):79 80 try:81 NDGCredentialWallet.accessDenied = 'yes'82 self.fail("accessDenied class variable should be read-only")83 except Exception, e:84 print("PASS - accessDenied class variable is read-only")85 86 try:87 NDGCredentialWallet.accessGranted = False88 self.fail("accessGranted class variable should be read-only")89 except Exception, e:90 print("PASS - accessGranted class variable is read-only")91 92 assert(not NDGCredentialWallet.accessDenied)93 assert(NDGCredentialWallet.accessGranted)94 95 96 def test02SetAttributes(self):97 98 credWallet = NDGCredentialWallet()99 credWallet.userX509Cert=open(xpdVars(self.userX509CertFilePath)).read()100 print("userX509Cert=%s" % credWallet.userX509Cert)101 credWallet.userId = 'ndg-user'102 print("userId=%s" % credWallet.userId)103 104 try:105 credWallet.blah = 'blah blah'106 self.fail("Attempting to set attribute not in __slots__ class "107 "variable should fail")108 except AttributeError:109 print("PASS - expected AttributeError when setting attribute "110 "not in __slots__ class variable")111 112 credWallet.caCertFilePathList=None113 credWallet.attributeAuthorityURI='http://localhost/AttributeAuthority'114 115 credWallet.attributeAuthority = None116 credWallet._credentialRepository = None117 credWallet.mapFromTrustedHosts = False118 credWallet.rtnExtAttCertList = True119 credWallet.attCertRefreshElapse = 7200120 121 122 def test03GetAttCertWithUserId(self):123 124 credWallet = NDGCredentialWallet(cfg=self.cfg.get('setUp',125 'cfgFilePath'))126 attCert = credWallet.getAttCert()127 128 # No user X.509 cert is set so the resulting Attribute Certificate129 # user ID should be the same as that set for the wallet130 assert(attCert.userId == credWallet.userId)131 print("Attribute Certificate:\n%s" % attCert)132 133 def test04GetAttCertWithUserX509Cert(self):134 135 credWallet = NDGCredentialWallet(cfg=self.cfg.get('setUp',136 'cfgFilePath'))137 138 # Set a test individual user certificate to override the client139 # cert. and private key in WS-Security settings in the config file140 credWallet.userX509Cert=open(xpdVars(self.userX509CertFilePath)).read()141 credWallet.userPriKey=open(xpdVars(self.userPriKeyFilePath)).read()142 attCert = credWallet.getAttCert()143 144 # A user X.509 cert. was set so this cert's DN should be set in the145 # userId field of the resulting Attribute Certificate146 assert(attCert.userId == str(credWallet.userX509Cert.dn))147 print("Attribute Certificate:\n%s" % attCert)148 149 def test05GetAttCertRefusedWithUserX509Cert(self):150 151 # Keyword mapFromTrustedHosts overrides any setting in the config file152 # This flag prevents role mapping from a trusted AA and so in this case153 # forces refusal of the request154 credWallet = NDGCredentialWallet(cfg=self.cfg.get('setUp',155 'cfgFilePath'),156 mapFromTrustedHosts=False)157 credWallet.userX509CertFilePath = self.userX509CertFilePath158 credWallet.userPriKeyFilePath = self.userPriKeyFilePath159 160 # Set AA URI AFTER user PKI settings so that these are picked in the161 # implicit call to create a new AA Client when the URI is set162 credWallet.attributeAuthorityURI = self.cfg.get('setUp',163 'attributeAuthorityURI')164 try:165 attCert = credWallet.getAttCert()166 except CredentialWalletAttributeRequestDenied, e:167 print("ok - obtained expected result: %s" % e)168 return169 170 self.fail("Request allowed from Attribute Authority where user is NOT "171 "registered!")172 173 def test06GetMappedAttCertWithUserId(self):174 175 # Call Site A Attribute Authority where user is registered176 credWallet = NDGCredentialWallet(cfg=self.cfg.get('setUp',177 'cfgFilePath'))178 attCert = credWallet.getAttCert()179 180 # Use Attribute Certificate cached in wallet to get a mapped181 # Attribute Certificate from Site B's Attribute Authority182 siteBURI = self.cfg.get('setUp', 'attributeAuthorityURI')183 attCert = credWallet.getAttCert(attributeAuthorityURI=siteBURI)184 185 print("Mapped Attribute Certificate from Site B Attribute "186 "Authority:\n%s" % attCert)187 188 def test07GetAttCertFromLocalAAInstance(self):189 thisSection = 'test07GetAttCertFromLocalAAInstance'190 aaPropFilePath = self.cfg.get(thisSection,191 'attributeAuthorityPropFilePath')192 193 credWallet = NDGCredentialWallet(cfg=self.cfg.get('setUp',194 'cfgFilePath'))195 credWallet.attributeAuthority = AttributeAuthority.fromPropertyFile(196 propFilePath=aaPropFilePath)197 attCert = credWallet.getAttCert()198 199 # No user X.509 cert is set so the resulting Attribute Certificate200 # user ID should be the same as that set for the wallet201 assert(attCert.userId == credWallet.userId)202 print("Attribute Certificate:\n%s" % attCert)203 204 def test08Pickle(self):205 credWallet = NDGCredentialWallet(cfg=self.cfg.get('setUp',206 'cfgFilePath'))207 208 outFile = open(NDGCredentialWalletTestCase.PICKLE_FILEPATH, 'w')209 pickle.dump(credWallet, outFile)210 outFile.close()211 212 inFile = open(NDGCredentialWalletTestCase.PICKLE_FILEPATH)213 unpickledCredWallet = pickle.load(inFile)214 self.assert_(unpickledCredWallet.userId == credWallet.userId)215 216 34 217 35 class SAMLCredentialWalletTestCase(BaseTestCase):
Note: See TracChangeset
for help on using the changeset viewer.