Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
if parameter.startswith('file:') or parameter.startswith('body:'):
file_name = parameter[5:]
if file_name not in ConnectCommand.attachment_cache:
attachment = None
if record.attachments:
for atta in record.attachments:
if file_name == atta['id'] or file_name.lower() in [atta[x].lower() for x in ['name', 'title'] if x in atta]:
attachment = atta
break
if not attachment:
logging.error('Attachment file \"%s\" not found', file_name)
return None
body = ConnectCommand.load_attachment_file(params, attachment, record)
if body:
ConnectCommand.attachment_cache[file_name] = body
if file_name not in ConnectCommand.attachment_cache:
logging.error('Attachment file \"%s\" not found', file_name)
return None
body = ConnectCommand.attachment_cache[file_name] # type: bytes
if parameter.startswith('file:'):
tf = tempfile.NamedTemporaryFile(delete=False)
tf.write(body)
tf.flush()
temp_files.append(tf.name)
tf.close()
return tf.name
else:
return body.decode('utf-8')
elif parameter.startswith('text:') or parameter.startswith('mask:'):
var_name = parameter[5:]
val = non_shared.get(var_name)
if val is None:
p = m.group(1)
val = ConnectCommand.get_parameter_value(params, record, p, temp_files, non_shared)
if not val:
raise Exception('Add ssh-key. Failed to resolve key parameter: {0}'.format(p))
parsed_values.append(val)
cf_value = cf_value[m.end():]
if len(parsed_values) > 0:
cf_value = cf_value.strip()
if cf_value:
parsed_values.append(cf_value)
private_key = RSA.importKey(parsed_values[0], parsed_values[1] if len(parsed_values) > 0 else None)
with ConnectSshAgent(ssh_socket_path) as fd:
payload = SSH2_AGENTC_ADD_IDENTITY.to_bytes(1, byteorder='big')
payload += ConnectCommand.ssh_agent_encode_str('ssh-rsa')
payload += ConnectCommand.ssh_agent_encode_long(private_key.n)
payload += ConnectCommand.ssh_agent_encode_long(private_key.e)
payload += ConnectCommand.ssh_agent_encode_long(private_key.d)
payload += ConnectCommand.ssh_agent_encode_long(int(Integer(private_key.q).inverse(private_key.p)))
payload += ConnectCommand.ssh_agent_encode_long(private_key.p)
payload += ConnectCommand.ssh_agent_encode_long(private_key.q)
payload += ConnectCommand.ssh_agent_encode_str(key_name)
# windows ssh implementation does not support constrained identities
#payload += SSH_AGENT_CONSTRAIN_LIFETIME.to_bytes(1, byteorder='big')
#payload += int(10).to_bytes(4, byteorder='big')
recv_payload = fd.send(payload)
if recv_payload and recv_payload[0] == SSH_AGENT_FAILURE:
raise Exception('Add ssh-key. Failed to add ssh key \"{0}\" to ssh-agent'.format(key_name))
payload = ConnectCommand.ssh_agent_encode_str('ssh-rsa')
payload += ConnectCommand.ssh_agent_encode_long(private_key.e)
if len(parsed_values) > 0:
cf_value = cf_value.strip()
if cf_value:
parsed_values.append(cf_value)
private_key = RSA.importKey(parsed_values[0], parsed_values[1] if len(parsed_values) > 0 else None)
with ConnectSshAgent(ssh_socket_path) as fd:
payload = SSH2_AGENTC_ADD_IDENTITY.to_bytes(1, byteorder='big')
payload += ConnectCommand.ssh_agent_encode_str('ssh-rsa')
payload += ConnectCommand.ssh_agent_encode_long(private_key.n)
payload += ConnectCommand.ssh_agent_encode_long(private_key.e)
payload += ConnectCommand.ssh_agent_encode_long(private_key.d)
payload += ConnectCommand.ssh_agent_encode_long(int(Integer(private_key.q).inverse(private_key.p)))
payload += ConnectCommand.ssh_agent_encode_long(private_key.p)
payload += ConnectCommand.ssh_agent_encode_long(private_key.q)
payload += ConnectCommand.ssh_agent_encode_str(key_name)
# windows ssh implementation does not support constrained identities
#payload += SSH_AGENT_CONSTRAIN_LIFETIME.to_bytes(1, byteorder='big')
#payload += int(10).to_bytes(4, byteorder='big')
recv_payload = fd.send(payload)
if recv_payload and recv_payload[0] == SSH_AGENT_FAILURE:
raise Exception('Add ssh-key. Failed to add ssh key \"{0}\" to ssh-agent'.format(key_name))
payload = ConnectCommand.ssh_agent_encode_str('ssh-rsa')
payload += ConnectCommand.ssh_agent_encode_long(private_key.e)
payload += ConnectCommand.ssh_agent_encode_long(private_key.n)
payload = SSH2_AGENTC_REMOVE_IDENTITY.to_bytes(1, byteorder='big') + ConnectCommand.ssh_agent_encode_bytes(payload)
rs.append(payload)
return rs
def get_parameter_value(params, record, parameter, temp_files, non_shared):
# type: (KeeperParams, Record, str, list, dict) -> str or None
if parameter.startswith('file:') or parameter.startswith('body:'):
file_name = parameter[5:]
if file_name not in ConnectCommand.attachment_cache:
attachment = None
if record.attachments:
for atta in record.attachments:
if file_name == atta['id'] or file_name.lower() in [atta[x].lower() for x in ['name', 'title'] if x in atta]:
attachment = atta
break
if not attachment:
logging.error('Attachment file \"%s\" not found', file_name)
return None
body = ConnectCommand.load_attachment_file(params, attachment, record)
if body:
ConnectCommand.attachment_cache[file_name] = body
if file_name not in ConnectCommand.attachment_cache:
logging.error('Attachment file \"%s\" not found', file_name)
return None
body = ConnectCommand.attachment_cache[file_name] # type: bytes
if parameter.startswith('file:'):
tf = tempfile.NamedTemporaryFile(delete=False)
tf.write(body)
tf.flush()
temp_files.append(tf.name)
tf.close()
return tf.name
else:
return body.decode('utf-8')
elif parameter.startswith('text:') or parameter.startswith('mask:'):
cmndr = non_shared.get('commander') or {}
non_shared = cmndr if not new_data else {}
try:
command = record.get('connect:' + endpoint + ':pre')
if command:
command = ConnectCommand.get_command_string(params, record, command, temp_files, non_shared)
if command:
os.system(command)
command = record.get('connect:' + endpoint)
if command:
command = ConnectCommand.get_command_string(params, record, command, temp_files, non_shared)
if command:
added_keys = ConnectCommand.add_ssh_keys(params, endpoint, record, temp_files, non_shared)
added_envs = ConnectCommand.add_environment_variables(params, endpoint, record, temp_files, non_shared)
logging.info('Connecting to %s...', endpoint)
os.system(command)
if added_keys:
ConnectCommand.delete_ssh_keys(added_keys)
if added_envs:
for name in added_envs:
os.putenv(name, '')
command = record.get('connect:' + endpoint + ':post')
if command:
command = ConnectCommand.get_command_string(params, record, command, temp_files, non_shared)
if command:
os.system(command)
finally:
for file in temp_files:
# type: (KeeperParams, str, Record, [str], dict) -> [str]
rs = [] # type: [str]
key_prefix = 'connect:{0}:env:'.format(endpoint)
for cf in record.custom_fields:
cf_name = cf['name'] # type: str
if cf_name.startswith(key_prefix):
key_name = cf_name[len(key_prefix):]
if not key_name:
continue
cf_value = cf['value'] # type: str
while True:
m = endpoint_parameter_pattern.search(cf_value)
if not m:
break
p = m.group(1)
val = ConnectCommand.get_parameter_value(params, record, p, temp_files, non_shared)
if not val:
raise Exception('Add environment variable. Failed to resolve key parameter: {0}'.format(p))
cf_value = cf_value[:m.start()] + val + cf_value[m.end():]
if cf_value:
rs.append(key_name)
os.putenv(key_name, cf_value)
return rs
def find_endpoints(params):
# type: (KeeperParams) -> None
if ConnectCommand.LastRevision < params.revision:
ConnectCommand.LastRevision = params.revision
ConnectCommand.Endpoints.clear()
for record_uid in params.record_cache:
record = api.get_record(params, record_uid)
if record.custom_fields:
endpoints = []
endpoints_desc = {}
for field in record.custom_fields:
if 'name' in field:
field_name = field['name']
m = endpoint_pattern.match(field_name)
if m:
endpoints.append(m[1])
else:
m = endpoint_desc_pattern.match(field_name)
if m:
endpoints_desc[m[1]] = field.get('value') or ''
def ssh_agent_encode_str(s): # type: (str) -> bytes
return ConnectCommand.ssh_agent_encode_bytes(s.encode('utf-8'))
if n.lower().startswith(name) and len(name) < len(n):
if extra.get('escape_space'):
n = n.replace(' ', '\\ ')
d = n
if len(d) > 39:
d = d[:29] + '...' + d[-7:]
yield Completion(n, display=d, start_position=-len(name))
elif context == 'command':
cmd = extra['prefix']
for c in itertools.chain(commands.keys(), enterprise_commands.keys()):
if c.startswith(cmd):
yield Completion(c, display=c, start_position=-len(cmd))
elif context == 'connect':
ConnectCommand.find_endpoints(self.params)
cmd = extra['prefix']
for ep in ConnectCommand.Endpoints:
c = ep.name or ''
if c.startswith(cmd):
yield Completion(c, display=c, start_position=-len(cmd))
except Exception as e:
pass
def register_commands(commands):
commands['sync-down'] = SyncDownCommand()
commands['delete-all'] = RecordDeleteAllCommand()
commands['whoami'] = WhoamiCommand()
commands['login'] = LoginCommand()
commands['logout'] = LogoutCommand()
commands['check-enforcements'] = CheckEnforcementsCommand()
commands['connect'] = ConnectCommand()
commands['echo'] = EchoCommand()
commands['set'] = SetCommand()
commands['help'] = HelpCommand()