def test_credentials(self): logging.debug('') logging.debug('test_credentials') # Basic form. owner = Credentials() if sys.platform == 'win32' and not HAVE_PYWIN32: self.assertEqual('%s' % owner, owner.user + ' (transient)') else: self.assertEqual('%s' % owner, owner.user) # Comparison. user = Credentials() self.assertEqual(user, owner) user.user = '******' self.assertNotEqual(user, owner) self.assertNotEqual(user, 'xyzzy') # Thread storage. try: del threading.current_thread().credentials # Ensure empty. except AttributeError: pass self.assertEqual(get_credentials(), owner) # Sign/verify. encoded = owner.encode() Credentials.verify(encoded, allowed_users=None) # 'First sighting'. Credentials.verify(encoded, allowed_users=None) # Cached verification. data, signature, client_creds = encoded encoded = (data[:1], signature, client_creds) assert_raises(self, 'Credentials.verify(encoded, None)', globals(), locals(), CredentialsError, 'Invalid data') encoded = (data[:-1], signature, client_creds) assert_raises(self, 'Credentials.verify(encoded, None)', globals(), locals(), CredentialsError, 'Invalid signature') encoded = (data, signature[:-1], client_creds) assert_raises(self, 'Credentials.verify(encoded, None)', globals(), locals(), CredentialsError, 'Invalid signature') newline = data.find('\n') # .user newline = data.find('\n', newline + 1) # .transient # Expecting '-' mangled = data[:newline + 1] + '*' + data[newline + 2:] encoded = (mangled, signature, client_creds) assert_raises(self, 'Credentials.verify(encoded, None)', globals(), locals(), CredentialsError, 'Invalid key') # Detect mismatched key. get_key_pair(owner.user, overwrite_cache=True) spook = Credentials() encoded = spook.encode() assert_raises(self, 'Credentials.verify(encoded, None)', globals(), locals(), CredentialsError, 'Public key mismatch') # Check if remote access. self.assertFalse(remote_access())
def test_keyfile(self): logging.debug('') logging.debug('test_keyfile') # Force a key generation. key_file = os.path.expanduser(os.path.join('~', '.openmdao', 'keys')) if os.path.exists(key_file): os.remove(key_file) user = '******' % (getpass.getuser(), socket.gethostname()) if user in _KEY_CACHE: del _KEY_CACHE[user] key_pair = get_key_pair(user, logging.getLogger(), ignore_ssh=True) # Again, this time with insecure key file. if sys.platform != 'win32': os.chmod(key_file, 0644) del _KEY_CACHE[user] key_pair = get_key_pair(user, logging.getLogger(), ignore_ssh=True) # Revert to normal (try ssh) scheme for any other tests. del _KEY_CACHE[user] # Check privacy. if sys.platform != 'win32' or HAVE_PYWIN32: self.assertTrue(is_private(key_file)) if sys.platform == 'win32': public_file = os.environ['COMSPEC'] else: public_file = '/bin/sh' self.assertFalse(is_private(public_file))
def test_keyfile(self): logging.debug('') logging.debug('test_keyfile') # Force a key generation, but save existing data. prefix = os.path.expanduser(os.path.join('~', '.openmdao')) key_file = os.path.join(prefix, 'keys') id_file = os.path.join(prefix, 'id_rsa.pub') for name in (key_file, id_file): if os.path.exists(name): saved = name + '.saved' if os.path.exists(saved): os.remove(saved) os.rename(name, saved) try: user = '******' % (getpass.getuser(), socket.gethostname()) if user in _KEY_CACHE: del _KEY_CACHE[user] key_pair = get_key_pair(user, logging.getLogger(), ignore_ssh=True) # Again, this time with insecure key file. if sys.platform != 'win32': os.chmod(key_file, 0644) del _KEY_CACHE[user] key_pair = get_key_pair(user, logging.getLogger(), ignore_ssh=True) # Revert to normal (try ssh) scheme for any other tests. del _KEY_CACHE[user] # Check privacy. if sys.platform != 'win32' or HAVE_PYWIN32: self.assertTrue(is_private(key_file)) if sys.platform == 'win32': public_file = os.environ['COMSPEC'] else: public_file = '/bin/sh' self.assertFalse(is_private(public_file)) # We've clobbered the existing credentials key data, so be # sure no stale credentials are in use. try: del threading.current_thread().credentials except AttributeError: pass finally: # Restore key data. for name in (key_file, id_file): saved = name + '.saved' if os.path.exists(saved): if os.path.exists(name): os.remove(name) os.rename(saved, name)
def test_keyfile(self): logging.debug('') logging.debug('test_keyfile') # Force a key generation, but save existing data. prefix = os.path.expanduser(os.path.join('~', '.openmdao')) key_file = os.path.join(prefix, 'keys') id_file = os.path.join(prefix, 'id_rsa.pub') for name in (key_file, id_file): if os.path.exists(name): saved = name+'.saved' if os.path.exists(saved): os.remove(saved) os.rename(name, saved) try: user = '******' % (getpass.getuser(), socket.gethostname()) if user in _KEY_CACHE: del _KEY_CACHE[user] key_pair = get_key_pair(user, logging.getLogger(), ignore_ssh=True) # Again, this time with insecure key file. if sys.platform != 'win32': os.chmod(key_file, 0644) del _KEY_CACHE[user] key_pair = get_key_pair(user, logging.getLogger(), ignore_ssh=True) # Revert to normal (try ssh) scheme for any other tests. del _KEY_CACHE[user] # Check privacy. if sys.platform != 'win32' or HAVE_PYWIN32: self.assertTrue(is_private(key_file)) if sys.platform == 'win32': public_file = os.environ['COMSPEC'] else: public_file = '/bin/sh' self.assertFalse(is_private(public_file)) # We've clobbered the existing credentials key data, so be # sure no stale credentials are in use. try: del threading.current_thread().credentials except AttributeError: pass finally: # Restore key data. for name in (key_file, id_file): saved = name+'.saved' if os.path.exists(saved): if os.path.exists(name): os.remove(name) os.rename(saved, name)
def test_3_access(self): logging.debug('') logging.debug('test_access') # This 'spook' creation is only for testing. # Normally the protector would run with regular credentials # in effect at the proprietary site. user = '******'+socket.gethostname() key_pair = get_key_pair(user) data = '\n'.join([user, '0', key_pair.publickey().exportKey()]) hash = hashlib.sha256(data).digest() signature = key_pair.sign(hash, get_random_bytes) spook = Credentials((data, signature, None)) credentials = get_credentials() allowed_users = {credentials.user: credentials.public_key, spook.user: spook.public_key} factory = self.start_factory(allowed_users=allowed_users) # Create model and run it. saved = get_credentials() set_credentials(spook) box = factory.create(_MODULE+'.ProtectedBox', allowed_users=allowed_users) set_credentials(saved) model = set_as_top(Model(box)) model.run() # Check results. for width in range(1, 2): for height in range(1, 3): for depth in range(1, 4): case = model.driver.recorders[0].cases.pop(0) self.assertEqual(case.outputs[0][2], width*height*depth)
def __init__(self, encoded=None): # We don't use cPickle to create or parse .data because we'd rather not # have to trust a source until after we've checked their credentials. self.remote = False if encoded is None: # Create our credentials. self.user = Credentials.user_host self.transient = (sys.platform == 'win32') and not HAVE_PYWIN32 key_pair = get_key_pair(self.user) self.public_key = key_pair.publickey() self.data = '\n'.join([ self.user, str(int(self.transient)), self.public_key.exportKey() ]) hash = hashlib.sha256(self.data).digest() self.signature = pk_sign(hash, key_pair) self.client_creds = None else: # Recreate remote user credentials. data, signature, client_creds = encoded lines = data.split('\n') if len(lines) < 3: raise CredentialsError('Invalid data') self.user = lines[0] self.transient = bool(int(lines[1])) try: self.public_key = RSA.importKey('\n'.join(lines[2:])) except Exception: raise CredentialsError('Invalid key') self.data = data hash = hashlib.sha256(data).digest() valid = False try: valid = pk_verify(hash, signature, self.public_key) except Exception as exc: raise CredentialsError('Invalid signature: %r' % exc) if not valid: raise CredentialsError('Invalid signature') self.signature = signature self.client_creds = client_creds
def __init__(self, encoded=None): # We don't use cPickle to create or parse .data because we'd rather not # have to trust a source until after we've checked their credentials. self.remote = False if encoded is None: # Create our credentials. self.user = Credentials.user_host self.transient = (sys.platform == 'win32') and not HAVE_PYWIN32 key_pair = get_key_pair(self.user) self.public_key = key_pair.publickey() self.data = '\n'.join([self.user, str(int(self.transient)), self.public_key.exportKey()]) hash = hashlib.sha256(self.data).digest() self.signature = pk_sign(hash, key_pair) self.client_creds = None else: # Recreate remote user credentials. data, signature, client_creds = encoded lines = data.split('\n') if len(lines) < 3: raise CredentialsError('Invalid data') self.user = lines[0] self.transient = bool(int(lines[1])) try: self.public_key = RSA.importKey('\n'.join(lines[2:])) except Exception: raise CredentialsError('Invalid key') self.data = data hash = hashlib.sha256(data).digest() valid = False try: valid = pk_verify(hash, signature, self.public_key) except Exception as exc: raise CredentialsError('Invalid signature: %r' % exc) if not valid: raise CredentialsError('Invalid signature') self.signature = signature self.client_creds = client_creds
def test_3_access(self): logging.debug('') logging.debug('test_access') # This 'spook' creation is only for testing. # Normally the protector would run with regular credentials # in effect at the proprietary site. user = '******'+socket.gethostname() key_pair = get_key_pair(user) data = '\n'.join([user, '0', key_pair.publickey().exportKey()]) hash = hashlib.sha256(data).digest() signature = key_pair.sign(hash, get_random_bytes) spook = Credentials((data, signature, None)) credentials = get_credentials() allowed_users = {credentials.user: credentials.public_key, spook.user: spook.public_key} factory = self.start_factory(allowed_users=allowed_users) # Create model and run it. saved = get_credentials() set_credentials(spook) box = factory.create(_MODULE+'.ProtectedBox', allowed_users=allowed_users) set_credentials(saved) model = set_as_top(Model(box)) model.run() # Check results. for width in range(1, 2): for height in range(1, 3): for depth in range(1, 4): case = model.driver.recorder.cases.pop(0) self.assertEqual(case.outputs[0][2], width*height*depth) # Check access protections. try: i = model.box.secret except RemoteError as exc: msg = "RoleError: No __getattribute__ access to 'secret' by role 'user'" logging.debug('msg: %s', msg) logging.debug('exc: %s', exc) self.assertTrue(msg in str(exc)) else: self.fail('Expected RemoteError') try: model.box.proprietary_method() except RemoteError as exc: msg = "RoleError: proprietary_method(): No access for role 'user'" logging.debug('msg: %s', msg) logging.debug('exc: %s', exc) self.assertTrue(msg in str(exc)) else: self.fail('Expected RemoteError') saved = get_credentials() set_credentials(spook) try: i = model.box.secret model.box.proprietary_method() finally: # Reset credentials to allow factory shutdown. set_credentials(saved)
def test_credentials(self): logging.debug('') logging.debug('test_credentials') # Basic form. owner = Credentials() if sys.platform == 'win32' and not HAVE_PYWIN32: self.assertEqual('%s' % owner, owner.user+' (transient)') else: self.assertEqual('%s' % owner, owner.user) # Comparison. user = Credentials() self.assertEqual(user, owner) user.user = '******' self.assertNotEqual(user, owner) self.assertNotEqual(user, 'xyzzy') # Thread storage. try: del threading.current_thread().credentials # Ensure empty. except AttributeError: pass self.assertEqual(get_credentials(), owner) # Sign/verify. encoded = owner.encode() Credentials.verify(encoded, allowed_users=None) # 'First sighting'. Credentials.verify(encoded, allowed_users=None) # Cached verification. data, signature, client_creds = encoded encoded = (data[:1], signature, client_creds) assert_raises(self, 'Credentials.verify(encoded, None)', globals(), locals(), CredentialsError, 'Invalid data') encoded = (data[:-1], signature, client_creds) assert_raises(self, 'Credentials.verify(encoded, None)', globals(), locals(), CredentialsError, 'Invalid signature') encoded = (data, signature[:-1], client_creds) assert_raises(self, 'Credentials.verify(encoded, None)', globals(), locals(), CredentialsError, 'Invalid signature') newline = data.find('\n') # .user newline = data.find('\n', newline+1) # .transient # Expecting '-' mangled = data[:newline+1] + '*' + data[newline+2:] encoded = (mangled, signature, client_creds) assert_raises(self, 'Credentials.verify(encoded, None)', globals(), locals(), CredentialsError, 'Invalid key') # Detect mismatched key. get_key_pair(owner.user, overwrite_cache=True) spook = Credentials() encoded = spook.encode() assert_raises(self, 'Credentials.verify(encoded, None)', globals(), locals(), CredentialsError, 'Public key mismatch') # Check if remote access. self.assertFalse(remote_access())