Create ~/.ssh with a specific permissions (ansible#84286)

pull/84289/head
spyinx 2 weeks ago
parent 9d249432c4
commit 7511152548

@ -0,0 +1,3 @@
bugfixes:
- Create ~/.ssh/ with a specific permissions for security if it's not exist (https://github.com/ansible/ansible/issues/84286)
- Optimize code for _save_ssh_host_keys() in paramiko_ssh.py to reduce duplicate code

@ -605,25 +605,26 @@ class Connection(ConnectionBase):
return return
path = os.path.expanduser("~/.ssh") path = os.path.expanduser("~/.ssh")
makedirs_safe(path) makedirs_safe(path, mode=0o700)
with open(filename, 'w') as f: with open(filename, 'w') as f:
keys_added_by_ansible = []
for hostname, keys in self.ssh._host_keys.items(): for hostname, keys in self.ssh._host_keys.items():
for keytype, key in keys.items(): for keytype, key in keys.items():
# was f.write # was f.write
added_this_time = getattr(key, '_added_by_ansible_this_time', False) added_this_time = getattr(key, '_added_by_ansible_this_time', False)
line_data = (hostname, keytype, key.get_base64())
if not added_this_time: if not added_this_time:
f.write("%s %s %s\n" % (hostname, keytype, key.get_base64())) f.write("%s %s %s\n" % line_data)
else:
keys_added_by_ansible.append(line_data)
for hostname, keys in self.ssh._host_keys.items(): for line_data in keys_added_by_ansible:
for keytype, key in keys.items(): f.write("%s %s %s\n" % line_data)
added_this_time = getattr(key, '_added_by_ansible_this_time', False)
if added_this_time:
f.write("%s %s %s\n" % (hostname, keytype, key.get_base64()))
def reset(self) -> None: def reset(self) -> None:
if not self._connected: if not self._connected:
@ -650,7 +651,7 @@ class Connection(ConnectionBase):
# that are starting up.) # that are starting up.)
lockfile = self.keyfile.replace("known_hosts", ".known_hosts.lock") lockfile = self.keyfile.replace("known_hosts", ".known_hosts.lock")
dirname = os.path.dirname(self.keyfile) dirname = os.path.dirname(self.keyfile)
makedirs_safe(dirname) makedirs_safe(dirname, mode=0o700)
KEY_LOCK = open(lockfile, 'w') KEY_LOCK = open(lockfile, 'w')
fcntl.lockf(KEY_LOCK, fcntl.LOCK_EX) fcntl.lockf(KEY_LOCK, fcntl.LOCK_EX)

Loading…
Cancel
Save