def test_encrypt_new(self): ciphertext = splunksecrets.encrypt_new( splunk_secret, "temp1234", iv=six.b("i5dKMGaSIRNpJty4") ) self.assertEqual(ciphertext, "$7$aTVkS01HYVNJUk5wSnR5NIu4GXLhj2Qd49n2B6Y8qmA/u1CdL9JYxQ==")
def test_encrypt_new(self): ciphertext = splunksecrets.encrypt_new(splunk_secret, "temp1234", iv=six.b("i5dKMGaSIRNpJty4")) self.assertEqual( ciphertext, "$7$aTVkS01HYVNJUk5wSnR5NKR+EdOfT4t84WSiXvPFHGHsfHtbgPIL3g==")
def test_encrypt_new_and_decrypt_use_only_first_254(self): splunk_secret1 = base64.b64encode(os.urandom(512))[:300] splunk_secret2 = splunk_secret1[:254] plaintext1 = base64.b64encode(os.urandom(255))[:24].decode() ciphertext = splunksecrets.encrypt_new(splunk_secret1, plaintext1) plaintext2 = splunksecrets.decrypt(splunk_secret2, ciphertext) self.assertEqual(plaintext2, plaintext1)
def handleList(self, confInfo): facility = config_file + '_list' logger = setup_logger(app_config["log_level"], setup_log, facility) confDict = self.readConf(config_file) credentials = {} logger.info(config_file + " list handler started") try: session_key = self.getSessionKey() entity = en.getEntity('/server', 'settings', namespace='-', sessionKey=session_key, owner='-') splunkd_port = entity["mgmtHostPort"] service = client.connect(token=session_key, port=splunkd_port) # Get all credentials for this app storage_passwords = service.storage_passwords for credential in storage_passwords: if credential.access.app == app: credentials[credential._state.title] = { 'username': credential.content.get('username'), 'password': credential.content.get('clear_password'), 'realm': credential.content.get('realm') } except BaseException as e: logger.exception('Could not connect to service: %s' % e) raise (e) if None != confDict: for stanza, settings in list(confDict.items()): for k, v in list(settings.items()): if stanza != 'default': logger.debug("%s stanza: %s, key: %s, value: %s", facility, stanza, k, v) if k.lower( ) in password_options and v is not None and len( v) > 0 and not '$7$' in v: v = encrypt_new(splunk_secret, v) if 'credential' in k: if v in list(credentials.keys()): confInfo[stanza].append( k + '_username', credentials[v]['username']) confInfo[stanza].append( k + '_realm', credentials[v]['realm']) confInfo[stanza].append( k + '_password', credentials[v]['password']) confInfo[stanza].append(k, v)
def handleEdit(self, confInfo): facility = config_file + '_edit' logger = setup_logger(app_config["log_level"], setup_log, facility) logger.debug(config_file + " edit handler started") config_id = self.callerArgs.id config = self.callerArgs.data logger.debug("Config: %s/%s" % (config_id, config)) new_config = {} for k, v in list(config.items()): try: if isinstance(v, list) and len(v) == 1: v = v[0] # Dynamic stanza name - GUIDs only guid_pattern = r'^([0-9A-Fa-f]{8}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{12})$' if k == 'stanza' and re.match(guid_pattern, str(v)): config_id = v logger.debug("Setting stanza to %s" % v) else: if v is None: logger.debug('%s Setting %s to blank', facility, k) new_config[k] = '' else: #logger.debug('%s Setting %s to %s', facility, k, v) if k.lower() in password_options and not '$7$' in v: logger.debug( '%s Value has an unencrypted password. Encrypting.', facility) try: v = encrypt_new(splunk_secret, v) except BaseException as e: logger.error( "%s Error saving encrypted password for %s: %s", facility, v, repr(e)) continue new_config[k] = v except BaseException as e: logger.exception("Error parsing config value \"%s\": %s" % (v, repr(e))) logger.debug("%s Writing new config for %s: %s", facility, config_id, str(new_config)) try: # Write the config stanza self.writeConf(config_file, config_id, new_config) except BaseException as e: logger.exception("%s Error writing config: %s", facility, e)
def test_end_to_end_new(self): splunk_secret = base64.b64encode(os.urandom(255))[:255] plaintext1 = base64.b64encode(os.urandom(255))[:24].decode() ciphertext = splunksecrets.encrypt_new(splunk_secret, plaintext1) plaintext2 = splunksecrets.decrypt(splunk_secret, ciphertext) self.assertEqual(plaintext2, plaintext1)
def handleEdit(self, confInfo): self.capabilityWrite = 'write_kvst_config' try: cfg = cli.getConfStanza('kvstore_tools','settings') except BaseException as e: raise Exception("Could not read configuration: " + repr(e)) # Facility info - prepended to log lines facility = os.path.basename(__file__) facility = os.path.splitext(facility)[0] try: logger = setup_logger(cfg["log_level"], 'kvstore_tools.log', facility) except BaseException as e: raise Exception("Could not create logger: " + repr(e)) logger.debug('KV Store Tools Settings handler started (Edit)') # Check for permissions to read the configuration session_key = self.getSessionKey() content = rest.simpleRequest('/services/authentication/current-context?output_mode=json', sessionKey=session_key, method='GET')[1] content = json.loads(content) current_user = content['entry'][0]['content']['username'] current_user_capabilities = content['entry'][0]['content']['capabilities'] if self.capabilityWrite in current_user_capabilities: logger.debug("User %s is authorized" % current_user) # Read the splunk.secret file with open(os.path.join(os.getenv('SPLUNK_HOME'), 'etc', 'auth', 'splunk.secret'), 'r') as ssfh: splunk_secret = ssfh.readline() config = self.callerArgs.data new_config = {} for k, v in list(config.items()): if isinstance(v, list) and len(v) == 1: v = v[0] if v is None: logger.debug('Setting %s to blank' % k) new_config[k] = '' else: logger.debug('Setting %s to %s' % (k, v)) if k[:10] == 'credential' and not '$7$' in v: logger.debug('Value has an unencrypted password. Encrypting.') # Split the value into alias/username/password hostname, username, password = v.split(':') try: v = hostname + ":" + username + ":" + encrypt_new(splunk_secret, password) except BaseException as e: logger.error("Error saving encrypted password for %s: %s" % (hostname, repr(e))) continue logger.debug('Encrypted') new_config[k] = v logger.debug('applied to configuration dict') try: if 'compression' in list(new_config.keys()): if str2bool(config['compression'][0]): new_config['compression'][0] = '1' else: new_config['compression'][0] = '0' if 'default_path' in list(new_config.keys()): if config['default_path'][0] in [None, '']: new_config['default_path'][0] = None if 'backup_batch_size' in list(new_config.keys()): if config['backup_batch_size'][0] in [None, '']: new_config['backup_batch_size'][0] = None logger.debug("Writing configuration") except BaseException as e: logger.critical("Error parsing configuration: %s" % repr(e)) # Write the config stanza self.writeConf('kvstore_tools', 'settings', new_config) else: raise Exception("User %s is unauthorized. Has the write_kvst_config capability been granted?" % current_user)
def test_encrypt_new_raises_value_error_short_secret(self): with self.assertRaises(ValueError): splunk_secret = base64.b64encode(os.urandom(255))[:253] splunksecrets.encrypt_new(splunk_secret, "temp1234")