2015-03-06 19:22:28 +01:00
|
|
|
#!/usr/bin/python
|
2014-09-30 15:08:26 +02:00
|
|
|
|
|
|
|
"""
|
|
|
|
Ansible module to manage the ssh known_hosts file.
|
|
|
|
Copyright(c) 2014, Matthew Vernon <mcv21@cam.ac.uk>
|
|
|
|
|
|
|
|
This module is free software: you can redistribute it and/or modify
|
|
|
|
it under the terms of the GNU General Public License as published by
|
|
|
|
the Free Software Foundation, either version 3 of the License, or
|
|
|
|
(at your option) any later version.
|
|
|
|
|
|
|
|
This module is distributed in the hope that it will be useful,
|
|
|
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
GNU General Public License for more details.
|
|
|
|
|
|
|
|
You should have received a copy of the GNU General Public License
|
|
|
|
along with this module. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
"""
|
|
|
|
|
|
|
|
DOCUMENTATION = '''
|
|
|
|
---
|
|
|
|
module: known_hosts
|
|
|
|
short_description: Add or remove a host from the C(known_hosts) file
|
|
|
|
description:
|
2016-05-23 16:35:03 +02:00
|
|
|
- The M(known_hosts) module lets you add or remove a host keys from the C(known_hosts) file.
|
|
|
|
- Starting at Ansible 2.2, multiple entries per host are allowed, but only one for each key type supported by ssh.
|
|
|
|
This is useful if you're going to want to use the M(git) module over ssh, for example.
|
|
|
|
- If you have a very large number of host keys to manage, you will find the M(template) module more useful.
|
2015-03-28 20:20:30 +01:00
|
|
|
version_added: "1.9"
|
2014-09-30 15:08:26 +02:00
|
|
|
options:
|
2015-03-06 19:22:28 +01:00
|
|
|
name:
|
|
|
|
aliases: [ 'host' ]
|
2014-09-30 15:08:26 +02:00
|
|
|
description:
|
|
|
|
- The host to add or remove (must match a host specified in key)
|
|
|
|
required: true
|
|
|
|
default: null
|
|
|
|
key:
|
|
|
|
description:
|
2016-07-25 21:41:41 +02:00
|
|
|
- The SSH public host key, as a string (required if state=present, optional when state=absent, in which case all keys for the host are removed). The key must be in the right format for ssh (see sshd(1), section "SSH_KNOWN_HOSTS FILE FORMAT")
|
2015-03-06 19:22:28 +01:00
|
|
|
required: false
|
2014-09-30 15:08:26 +02:00
|
|
|
default: null
|
|
|
|
path:
|
|
|
|
description:
|
|
|
|
- The known_hosts file to edit
|
|
|
|
required: no
|
|
|
|
default: "(homedir)+/.ssh/known_hosts"
|
|
|
|
state:
|
|
|
|
description:
|
2016-05-23 16:33:52 +02:00
|
|
|
- I(present) to add the host key, I(absent) to remove it.
|
2014-09-30 15:08:26 +02:00
|
|
|
choices: [ "present", "absent" ]
|
|
|
|
required: no
|
|
|
|
default: present
|
|
|
|
requirements: [ ]
|
2015-06-16 20:32:39 +02:00
|
|
|
author: "Matthew Vernon (@mcv21)"
|
2014-09-30 15:08:26 +02:00
|
|
|
'''
|
|
|
|
|
|
|
|
EXAMPLES = '''
|
|
|
|
# Example using with_file to set the system known_hosts file
|
|
|
|
- name: tell the host about our servers it might want to ssh to
|
|
|
|
known_hosts: path='/etc/ssh/ssh_known_hosts'
|
2015-07-25 14:11:03 +02:00
|
|
|
name='foo.com.invalid'
|
2014-09-30 15:08:26 +02:00
|
|
|
key="{{ lookup('file', 'pubkeys/foo.com.invalid') }}"
|
|
|
|
'''
|
|
|
|
|
|
|
|
# Makes sure public host keys are present or absent in the given known_hosts
|
|
|
|
# file.
|
|
|
|
#
|
|
|
|
# Arguments
|
|
|
|
# =========
|
2015-03-06 19:22:28 +01:00
|
|
|
# name = hostname whose key should be added (alias: host)
|
2014-09-30 15:08:26 +02:00
|
|
|
# key = line(s) to add to known_hosts file
|
|
|
|
# path = the known_hosts file to edit (default: ~/.ssh/known_hosts)
|
|
|
|
# state = absent|present (default: present)
|
|
|
|
|
2015-03-06 19:22:28 +01:00
|
|
|
import os
|
|
|
|
import os.path
|
|
|
|
import tempfile
|
|
|
|
import errno
|
2016-05-23 16:33:52 +02:00
|
|
|
import re
|
2016-06-03 15:23:55 +02:00
|
|
|
from ansible.module_utils.pycompat24 import get_exception
|
|
|
|
from ansible.module_utils.basic import *
|
2014-09-30 15:08:26 +02:00
|
|
|
|
|
|
|
def enforce_state(module, params):
|
|
|
|
"""
|
|
|
|
Add or remove key.
|
|
|
|
"""
|
|
|
|
|
2015-05-04 21:57:40 +02:00
|
|
|
host = params["name"]
|
2014-09-30 15:08:26 +02:00
|
|
|
key = params.get("key",None)
|
|
|
|
port = params.get("port",None)
|
2016-05-08 11:33:54 +02:00
|
|
|
path = params.get("path")
|
2015-03-06 19:22:28 +01:00
|
|
|
state = params.get("state")
|
|
|
|
#Find the ssh-keygen binary
|
|
|
|
sshkeygen = module.get_bin_path("ssh-keygen",True)
|
2014-09-30 15:08:26 +02:00
|
|
|
|
2015-11-03 03:49:46 +01:00
|
|
|
# Trailing newline in files gets lost, so re-add if necessary
|
|
|
|
if key and key[-1] != '\n':
|
2014-09-30 15:08:26 +02:00
|
|
|
key+='\n'
|
|
|
|
|
|
|
|
if key is None and state != "absent":
|
|
|
|
module.fail_json(msg="No key specified when adding a host")
|
|
|
|
|
2015-03-06 19:22:28 +01:00
|
|
|
sanity_check(module,host,key,sshkeygen)
|
2014-09-30 15:08:26 +02:00
|
|
|
|
2016-05-23 16:33:52 +02:00
|
|
|
found,replace_or_add,found_line=search_for_host_key(module,host,key,path,sshkeygen)
|
2014-09-30 15:08:26 +02:00
|
|
|
|
2016-05-23 16:33:52 +02:00
|
|
|
#We will change state if found==True & state!="present"
|
|
|
|
#or found==False & state=="present"
|
|
|
|
#i.e found XOR (state=="present")
|
2014-09-30 15:08:26 +02:00
|
|
|
#Alternatively, if replace is true (i.e. key present, and we must change it)
|
|
|
|
if module.check_mode:
|
2016-05-23 16:33:52 +02:00
|
|
|
module.exit_json(changed = replace_or_add or (state=="present") != found)
|
2014-09-30 15:08:26 +02:00
|
|
|
|
|
|
|
#Now do the work.
|
|
|
|
|
2016-05-23 16:33:52 +02:00
|
|
|
#Only remove whole host if found and no key provided
|
|
|
|
if found and key is None and state=="absent":
|
|
|
|
module.run_command([sshkeygen,'-R',host,'-f',path], check_rc=True)
|
2014-09-30 15:08:26 +02:00
|
|
|
params['changed'] = True
|
2016-05-23 16:33:52 +02:00
|
|
|
|
2014-09-30 15:08:26 +02:00
|
|
|
#Next, add a new (or replacing) entry
|
2016-05-23 16:33:52 +02:00
|
|
|
if replace_or_add or found != (state=="present"):
|
2014-09-30 15:08:26 +02:00
|
|
|
try:
|
|
|
|
inf=open(path,"r")
|
2016-06-03 15:23:55 +02:00
|
|
|
except IOError:
|
2016-06-30 15:42:14 +02:00
|
|
|
e = get_exception()
|
2014-09-30 15:08:26 +02:00
|
|
|
if e.errno == errno.ENOENT:
|
|
|
|
inf=None
|
|
|
|
else:
|
|
|
|
module.fail_json(msg="Failed to read %s: %s" % \
|
|
|
|
(path,str(e)))
|
|
|
|
try:
|
2015-04-19 03:50:06 +02:00
|
|
|
outf=tempfile.NamedTemporaryFile(dir=os.path.dirname(path))
|
2014-09-30 15:08:26 +02:00
|
|
|
if inf is not None:
|
2016-05-23 16:33:52 +02:00
|
|
|
for line_number, line in enumerate(inf, start=1):
|
|
|
|
if found_line==line_number and (replace_or_add or state=='absent'):
|
|
|
|
continue # skip this line to replace its key
|
2014-09-30 15:08:26 +02:00
|
|
|
outf.write(line)
|
|
|
|
inf.close()
|
2016-05-23 16:33:52 +02:00
|
|
|
if state == 'present':
|
|
|
|
outf.write(key)
|
2015-04-19 03:50:06 +02:00
|
|
|
outf.flush()
|
2014-09-30 15:08:26 +02:00
|
|
|
module.atomic_move(outf.name,path)
|
2016-06-03 15:23:55 +02:00
|
|
|
except (IOError,OSError):
|
|
|
|
e = get_exception()
|
2014-09-30 15:08:26 +02:00
|
|
|
module.fail_json(msg="Failed to write to file %s: %s" % \
|
|
|
|
(path,str(e)))
|
2015-04-19 03:50:06 +02:00
|
|
|
|
|
|
|
try:
|
|
|
|
outf.close()
|
|
|
|
except:
|
|
|
|
pass
|
|
|
|
|
2014-09-30 15:08:26 +02:00
|
|
|
params['changed'] = True
|
2015-04-02 02:44:28 +02:00
|
|
|
|
2014-09-30 15:08:26 +02:00
|
|
|
return params
|
|
|
|
|
2015-03-06 19:22:28 +01:00
|
|
|
def sanity_check(module,host,key,sshkeygen):
|
2014-09-30 15:08:26 +02:00
|
|
|
'''Check supplied key is sensible
|
|
|
|
|
|
|
|
host and key are parameters provided by the user; If the host
|
|
|
|
provided is inconsistent with the key supplied, then this function
|
|
|
|
quits, providing an error to the user.
|
2015-03-06 19:22:28 +01:00
|
|
|
sshkeygen is the path to ssh-keygen, found earlier with get_bin_path
|
2014-09-30 15:08:26 +02:00
|
|
|
'''
|
|
|
|
#If no key supplied, we're doing a removal, and have nothing to check here.
|
|
|
|
if key is None:
|
|
|
|
return
|
|
|
|
#Rather than parsing the key ourselves, get ssh-keygen to do it
|
|
|
|
#(this is essential for hashed keys, but otherwise useful, as the
|
|
|
|
#key question is whether ssh-keygen thinks the key matches the host).
|
|
|
|
|
|
|
|
#The approach is to write the key to a temporary file,
|
|
|
|
#and then attempt to look up the specified host in that file.
|
|
|
|
try:
|
2015-04-19 03:50:06 +02:00
|
|
|
outf=tempfile.NamedTemporaryFile()
|
2014-09-30 15:08:26 +02:00
|
|
|
outf.write(key)
|
2015-04-19 03:50:06 +02:00
|
|
|
outf.flush()
|
2016-06-03 15:23:55 +02:00
|
|
|
except IOError:
|
|
|
|
e = get_exception()
|
2014-09-30 15:08:26 +02:00
|
|
|
module.fail_json(msg="Failed to write to temporary file %s: %s" % \
|
|
|
|
(outf.name,str(e)))
|
2015-03-06 19:22:28 +01:00
|
|
|
rc,stdout,stderr=module.run_command([sshkeygen,'-F',host,
|
2014-09-30 15:08:26 +02:00
|
|
|
'-f',outf.name],
|
|
|
|
check_rc=True)
|
2015-04-19 03:50:06 +02:00
|
|
|
try:
|
|
|
|
outf.close()
|
|
|
|
except:
|
|
|
|
pass
|
|
|
|
|
2014-09-30 15:08:26 +02:00
|
|
|
if stdout=='': #host not found
|
|
|
|
module.fail_json(msg="Host parameter does not match hashed host field in supplied key")
|
|
|
|
|
2015-03-06 19:22:28 +01:00
|
|
|
def search_for_host_key(module,host,key,path,sshkeygen):
|
2016-05-23 16:33:52 +02:00
|
|
|
'''search_for_host_key(module,host,key,path,sshkeygen) -> (found,replace_or_add,found_line)
|
2014-09-30 15:08:26 +02:00
|
|
|
|
2016-05-23 16:33:52 +02:00
|
|
|
Looks up host and keytype in the known_hosts file path; if it's there, looks to see
|
2014-09-30 15:08:26 +02:00
|
|
|
if one of those entries matches key. Returns:
|
2016-05-23 16:33:52 +02:00
|
|
|
found (Boolean): is host found in path?
|
|
|
|
replace_or_add (Boolean): is the key in path different to that supplied by user?
|
|
|
|
found_line (int or None): the line where a key of the same type was found
|
|
|
|
if found=False, then replace is always False.
|
2015-03-06 19:22:28 +01:00
|
|
|
sshkeygen is the path to ssh-keygen, found earlier with get_bin_path
|
2014-09-30 15:08:26 +02:00
|
|
|
'''
|
|
|
|
if os.path.exists(path)==False:
|
2016-05-23 16:33:52 +02:00
|
|
|
return False, False, None
|
2015-03-31 18:19:11 +02:00
|
|
|
#openssh >=6.4 has changed ssh-keygen behaviour such that it returns
|
|
|
|
#1 if no host is found, whereas previously it returned 0
|
2015-03-06 19:22:28 +01:00
|
|
|
rc,stdout,stderr=module.run_command([sshkeygen,'-F',host,'-f',path],
|
2015-03-31 18:19:11 +02:00
|
|
|
check_rc=False)
|
|
|
|
if stdout=='' and stderr=='' and (rc==0 or rc==1):
|
2016-05-23 16:33:52 +02:00
|
|
|
return False, False, None #host not found, no other errors
|
2015-03-31 18:19:11 +02:00
|
|
|
if rc!=0: #something went wrong
|
|
|
|
module.fail_json(msg="ssh-keygen failed (rc=%d,stdout='%s',stderr='%s')" % (rc,stdout,stderr))
|
2014-09-30 15:08:26 +02:00
|
|
|
|
2016-05-23 16:33:52 +02:00
|
|
|
#If user supplied no key, we don't want to try and replace anything with it
|
2014-09-30 15:08:26 +02:00
|
|
|
if key is None:
|
2016-05-23 16:33:52 +02:00
|
|
|
return True, False, None
|
2014-09-30 15:08:26 +02:00
|
|
|
|
|
|
|
lines=stdout.split('\n')
|
2016-05-23 16:33:52 +02:00
|
|
|
new_key = normalize_known_hosts_key(key, host)
|
|
|
|
|
2014-09-30 15:08:26 +02:00
|
|
|
for l in lines:
|
2016-05-23 16:33:52 +02:00
|
|
|
if l=='':
|
2014-09-30 15:08:26 +02:00
|
|
|
continue
|
2016-05-23 16:33:52 +02:00
|
|
|
elif l[0]=='#': # info output from ssh-keygen; contains the line number where key was found
|
|
|
|
try:
|
|
|
|
# This output format has been hardcoded in ssh-keygen since at least OpenSSH 4.0
|
|
|
|
# It always outputs the non-localized comment before the found key
|
|
|
|
found_line = int(re.search(r'found: line (\d+)', l).group(1))
|
2016-06-03 15:23:55 +02:00
|
|
|
except IndexError:
|
|
|
|
e = get_exception()
|
2016-05-23 16:33:52 +02:00
|
|
|
module.fail_json(msg="failed to parse output of ssh-keygen for line number: '%s'" % l)
|
|
|
|
else:
|
|
|
|
found_key = normalize_known_hosts_key(l,host)
|
|
|
|
if new_key==found_key: #found a match
|
|
|
|
return True, False, found_line #found exactly the same key, don't replace
|
|
|
|
elif new_key['type'] == found_key['type']: # found a different key for the same key type
|
|
|
|
return True, True, found_line
|
|
|
|
#No match found, return found and replace, but no line
|
|
|
|
return True, True, None
|
|
|
|
|
|
|
|
def normalize_known_hosts_key(key, host):
|
|
|
|
'''
|
|
|
|
Transform a key, either taken from a known_host file or provided by the
|
|
|
|
user, into a normalized form.
|
|
|
|
The host part (which might include multiple hostnames or be hashed) gets
|
|
|
|
replaced by the provided host. Also, any spurious information gets removed
|
|
|
|
from the end (like the username@host tag usually present in hostkeys, but
|
|
|
|
absent in known_hosts files)
|
|
|
|
'''
|
|
|
|
k=key.strip() #trim trailing newline
|
|
|
|
k=key.split()
|
|
|
|
d = dict()
|
|
|
|
#The optional "marker" field, used for @cert-authority or @revoked
|
|
|
|
if k[0][0] == '@':
|
|
|
|
d['options'] = k[0]
|
|
|
|
d['host']=host
|
|
|
|
d['type']=k[2]
|
|
|
|
d['key']=k[3]
|
|
|
|
else:
|
|
|
|
d['host']=host
|
|
|
|
d['type']=k[1]
|
|
|
|
d['key']=k[2]
|
|
|
|
return d
|
2014-09-30 15:08:26 +02:00
|
|
|
|
|
|
|
def main():
|
|
|
|
|
|
|
|
module = AnsibleModule(
|
|
|
|
argument_spec = dict(
|
2015-03-06 19:22:28 +01:00
|
|
|
name = dict(required=True, type='str', aliases=['host']),
|
|
|
|
key = dict(required=False, type='str'),
|
2016-05-08 11:33:54 +02:00
|
|
|
path = dict(default="~/.ssh/known_hosts", type='path'),
|
2014-09-30 15:08:26 +02:00
|
|
|
state = dict(default='present', choices=['absent','present']),
|
|
|
|
),
|
|
|
|
supports_check_mode = True
|
|
|
|
)
|
|
|
|
|
|
|
|
results = enforce_state(module,module.params)
|
|
|
|
module.exit_json(**results)
|
|
|
|
|
|
|
|
main()
|