Debian Codegraph @

lib/ansible/modules/known_hosts.py

raw
1
2 # Copyright: (c) 2014, Matthew Vernon <[email protected]>
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4
5 from __future__ import annotations
6
7
8 DOCUMENTATION = r"""
9 ---
10 module: known_hosts
11 short_description: Add or remove a host from the C(known_hosts) file
12 description:
13 - The M(ansible.builtin.known_hosts) module lets you add or remove host keys from the C(known_hosts) file.
14 - Starting at Ansible 2.2, multiple entries per host are allowed, but only one for each key type supported by ssh.
15 This is useful if you're going to want to use the M(ansible.builtin.git) module over ssh, for example.
16 - If you have a very large number of host keys to manage, you will find the M(ansible.builtin.template) module more useful.
17 version_added: "1.9"
18 options:
19 name:
20 aliases: [ 'host' ]
21 description:
22 - The host to add or remove (must match a host specified in key). It will be converted to lowercase so that C(ssh-keygen) can find it.
23 - Must match with <hostname> or <ip> present in key attribute.
24 - For custom SSH port, O(name) needs to specify port as well. See example section.
25 type: str
26 required: true
27 key:
28 description:
29 - The SSH public host key, as a string.
30 - Required if O(state=present), optional when O(state=absent), in which case all keys for the host are removed.
31 - The key must be in the right format for SSH (see sshd(8), section "SSH_KNOWN_HOSTS FILE FORMAT").
32 - Specifically, the key should not match the format that is found in an SSH pubkey file, but should rather have the hostname prepended to a
33 line that includes the pubkey, the same way that it would appear in the known_hosts file. The value prepended to the line must also match
34 the value of the name parameter.
35 - Should be of format C(<hostname[,IP]> ssh-rsa <pubkey>).
36 - For custom SSH port, O(key) needs to specify port as well. See example section.
37 type: str
38 path:
39 description:
40 - The known_hosts file to edit.
41 - The known_hosts file will be created if needed. The rest of the path must exist prior to running the module.
42 default: "~/.ssh/known_hosts"
43 type: path
44 hash_host:
45 description:
46 - Hash the hostname in the known_hosts file.
47 type: bool
48 default: "no"
49 version_added: "2.3"
50 state:
51 description:
52 - V(present) to add host keys.
53 - V(absent) to remove host keys.
54 choices: [ "absent", "present" ]
55 default: "present"
56 type: str
57 attributes:
58 check_mode:
59 support: full
60 diff_mode:
61 support: full
62 platform:
63 platforms: posix
64 extends_documentation_fragment:
65 - action_common_attributes
66 author:
67 - Matthew Vernon (@mcv21)
68 """
69
70 EXAMPLES = r"""
71 - name: Tell the host about our servers it might want to ssh to
72 ansible.builtin.known_hosts:
73 path: /etc/ssh/ssh_known_hosts
74 name: foo.com.invalid
75 key: "{{ lookup('ansible.builtin.file', 'pubkeys/foo.com.invalid') }}"
76
77 - name: Another way to call known_hosts
78 ansible.builtin.known_hosts:
79 name: host1.example.com # or 10.9.8.77
80 key: host1.example.com,10.9.8.77 ssh-rsa ASDeararAIUHI324324 # some key gibberish
81 path: /etc/ssh/ssh_known_hosts
82 state: present
83
84 - name: Add host with custom SSH port
85 ansible.builtin.known_hosts:
86 name: '[host1.example.com]:2222'
87 key: '[host1.example.com]:2222 ssh-rsa ASDeararAIUHI324324' # some key gibberish
88 path: /etc/ssh/ssh_known_hosts
89 state: present
90 """
91
92 # Makes sure public host keys are present or absent in the given known_hosts
93 # file.
94 #
95 # Arguments
96 # =========
97 # name = hostname whose key should be added (alias: host)
98 # key = line(s) to add to known_hosts file
99 # path = the known_hosts file to edit (default: ~/.ssh/known_hosts)
100 # hash_host = yes|no (default: no) hash the hostname in the known_hosts file
101 # state = absent|present (default: present)
102
103 import base64
104 import copy
105 import hashlib
106 import hmac
107 import os
108 import os.path
109 import re
110 import tempfile
111
112 from ansible.module_utils.basic import AnsibleModule
113 from ansible.module_utils.common.text.converters import to_bytes, to_native
114
115
116 def enforce_state(module, params):
117 """
118 Add or remove key.
119 """
120
121 results = dict(changed=False)
122 host = params["name"].lower()
123 key = params.get("key", None)
124 path = params.get("path")
125 hash_host = params.get("hash_host")
126 state = params.get("state")
127 # Find the ssh-keygen binary
128 sshkeygen = module.get_bin_path("ssh-keygen", True)
129
130 if not key and state != "absent":
131 module.fail_json(msg="No key specified when adding a host")
132
133 if key and hash_host:
134 key = hash_host_key(host, key)
135
136 # Trailing newline in files gets lost, so re-add if necessary
137 if key and not key.endswith('\n'):
138 key += '\n'
139
140 sanity_check(module, host, key, sshkeygen)
141
142 found, replace_or_add, found_line = search_for_host_key(module, host, key, path, sshkeygen)
143
144 results['diff'] = compute_diff(path, found_line, replace_or_add, state, key)
145
146 # check if we are trying to remove a non matching key,
147 # in that case return with no change to the host
148 if state == 'absent' and not found_line and key:
149 return results
150
151 # We will change state if found==True & state!="present"
152 # or found==False & state=="present"
153 # i.e found XOR (state=="present")
154 # Alternatively, if replace is true (i.e. key present, and we must change
155 # it)
156 if module.check_mode:
157 results['changed'] = replace_or_add or (state == "present") != found
158 module.exit_json(**results)
159
160 # Now do the work.
161
162 # Only remove whole host if found and no key provided
163 if found and not key and state == "absent":
164 module.run_command([sshkeygen, '-R', host, '-f', path], check_rc=True)
165 results['changed'] = True
166
167 # Next, add a new (or replacing) entry
168 if replace_or_add or found != (state == "present"):
169 try:
170 inf = open(path, "r")
171 except FileNotFoundError:
172 inf = None
173 except OSError as ex:
174 raise Exception(f"Failed to read {path!r}.") from ex
175 try:
176 with tempfile.NamedTemporaryFile(mode='w+', dir=os.path.dirname(path), delete=False) as outf:
177 if inf is not None:
178 for line_number, line in enumerate(inf):
179 if found_line == (line_number + 1) and (replace_or_add or state == 'absent'):
180 continue # skip this line to replace its key
181 outf.write(line)
182 inf.close()
183 if state == 'present':
184 outf.write(key)
185 except OSError as ex:
186 raise Exception(f"Failed to write to file {path!r}.") from ex
187 else:
188 module.atomic_move(outf.name, path)
189
190 results['changed'] = True
191
192 return results
193
194
195 def sanity_check(module, host, key, sshkeygen):
196 """Check supplied key is sensible
197
198 host and key are parameters provided by the user; If the host
199 provided is inconsistent with the key supplied, then this function
200 quits, providing an error to the user.
201 sshkeygen is the path to ssh-keygen, found earlier with get_bin_path
202 """
203 # If no key supplied, we're doing a removal, and have nothing to check here.
204 if not key:
205 return
206 # Rather than parsing the key ourselves, get ssh-keygen to do it
207 # (this is essential for hashed keys, but otherwise useful, as the
208 # key question is whether ssh-keygen thinks the key matches the host).
209
210 # The approach is to write the key to a temporary file,
211 # and then attempt to look up the specified host in that file.
212
213 if re.search(r'\S+(\s+)?,(\s+)?', host):
214 module.fail_json(msg="Comma separated list of names is not supported. "
215 "Please pass a single name to lookup in the known_hosts file.")
216
217 with tempfile.NamedTemporaryFile(mode='w+') as outf:
218 try:
219 outf.write(key)
220 outf.flush()
221 except OSError as ex:
222 raise Exception(f"Failed to write to temporary file {outf.name!r}.") from ex
223
224 sshkeygen_command = [sshkeygen, '-F', host, '-f', outf.name]
225 rc, stdout, stderr = module.run_command(sshkeygen_command)
226
227 if stdout == '': # host not found
228 results = {
229 "msg": "Host parameter does not match hashed host field in supplied key",
230 "rc": rc,
231 }
232 if stderr:
233 results["stderr"] = stderr
234 module.fail_json(**results)
235
236
237 def search_for_host_key(module, host, key, path, sshkeygen):
238 """search_for_host_key(module,host,key,path,sshkeygen) -> (found,replace_or_add,found_line)
239
240 Looks up host and keytype in the known_hosts file path; if it's there, looks to see
241 if one of those entries matches key. Returns:
242 found (Boolean): is host found in path?
243 replace_or_add (Boolean): is the key in path different to that supplied by user?
244 found_line (int or None): the line where a key of the same type was found
245 if found=False, then replace is always False.
246 sshkeygen is the path to ssh-keygen, found earlier with get_bin_path
247 """
248 if os.path.exists(path) is False:
249 return False, False, None
250
251 sshkeygen_command = [sshkeygen, '-F', host, '-f', path]
252
253 # openssh >=6.4 has changed ssh-keygen behaviour such that it returns
254 # 1 if no host is found, whereas previously it returned 0
255 rc, stdout, stderr = module.run_command(sshkeygen_command, check_rc=False)
256 if stdout == '' and stderr == '' and (rc == 0 or rc == 1):
257 return False, False, None # host not found, no other errors
258 if rc != 0: # something went wrong
259 module.fail_json(msg="ssh-keygen failed (rc=%d, stdout='%s',stderr='%s')" % (rc, stdout, stderr))
260
261 # If user supplied no key, we don't want to try and replace anything with it
262 if not key:
263 return True, False, None
264
265 lines = stdout.split('\n')
266 new_key = normalize_known_hosts_key(key)
267
268 for lnum, l in enumerate(lines):
269 if l == '':
270 continue
271 elif l[0] == '#': # info output from ssh-keygen; contains the line number where key was found
272 try:
273 # This output format has been hardcoded in ssh-keygen since at least OpenSSH 4.0
274 # It always outputs the non-localized comment before the found key
275 found_line = int(re.search(r'found: line (\d+)', l).group(1))
276 except IndexError:
277 module.fail_json(msg="failed to parse output of ssh-keygen for line number: '%s'" % l)
278 else:
279 found_key = normalize_known_hosts_key(l)
280
281 if 'options' in found_key and found_key['options'][:15] == '@cert-authority':
282 if new_key == found_key: # found a match
283 return True, False, found_line # found exactly the same key, don't replace
284 elif 'options' in found_key and found_key['options'][:7] == '@revoke':
285 if new_key == found_key: # found a match
286 return True, False, found_line # found exactly the same key, don't replace
287 else:
288 if new_key['host'][:3] == '|1|' and found_key['host'][:3] == '|1|': # do not change host hash if already hashed
289 new_key['host'] = found_key['host']
290 if new_key == found_key: # found a match
291 return True, False, found_line # found exactly the same key, don't replace
292 elif new_key['type'] == found_key['type']: # found a different key for the same key type
293 return True, True, found_line
294
295 # No match found, return found and replace, but no line
296 return True, True, None
297
298
299 def hash_host_key(host, key):
300 hmac_key = os.urandom(20)
301 hashed_host = hmac.new(hmac_key, to_bytes(host), hashlib.sha1).digest()
302 parts = key.strip().split()
303 # @ indicates the optional marker field used for @cert-authority or @revoked
304 i = 1 if parts[0][0] == '@' else 0
305 parts[i] = '|1|%s|%s' % (to_native(base64.b64encode(hmac_key)), to_native(base64.b64encode(hashed_host)))
306 return ' '.join(parts)
307
308
309 def normalize_known_hosts_key(key):
310 """
311 Transform a key, either taken from a known_host file or provided by the
312 user, into a normalized form.
313 The host part (which might include multiple hostnames or be hashed) gets
314 replaced by the provided host. Also, any spurious information gets removed
315 from the end (like the username@host tag usually present in hostkeys, but
316 absent in known_hosts files)
317 """
318 key = key.strip() # trim trailing newline
319 k = key.split()
320 d = dict()
321 # The optional "marker" field, used for @cert-authority or @revoked
322 if k[0][0] == '@':
323 d['options'] = k[0]
324 d['host'] = k[1]
325 d['type'] = k[2]
326 d['key'] = k[3]
327 else:
328 d['host'] = k[0]
329 d['type'] = k[1]
330 d['key'] = k[2]
331 return d
332
333
334 def compute_diff(path, found_line, replace_or_add, state, key):
335 diff = {
336 'before_header': path,
337 'after_header': path,
338 'before': '',
339 'after': '',
340 }
341 try:
342 inf = open(path, "r")
343 except FileNotFoundError:
344 diff['before_header'] = '/dev/null'
345 except OSError:
346 pass
347 else:
348 diff['before'] = inf.read()
349 inf.close()
350 lines = diff['before'].splitlines(1)
351 if (replace_or_add or state == 'absent') and found_line is not None and 1 <= found_line <= len(lines):
352 del lines[found_line - 1]
353 if state == 'present' and (replace_or_add or found_line is None):
354 lines.append(key)
355 diff['after'] = ''.join(lines)
356 return diff
357
358
359 def main():
360
361 module = AnsibleModule(
362 argument_spec=dict(
363 name=dict(required=True, type='str', aliases=['host']),
364 key=dict(required=False, type='str', no_log=False),
365 path=dict(default="~/.ssh/known_hosts", type='path'),
366 hash_host=dict(required=False, type='bool', default=False),
367 state=dict(default='present', choices=['absent', 'present']),
368 ),
369 supports_check_mode=True
370 )
371
372 # TODO: deprecate returning everything that was passed in
373 results = copy.copy(module.params)
374 results.update(enforce_state(module, module.params))
375 module.exit_json(**results)
376
377
378 if __name__ == '__main__':
379 main()