|
| 1 | +# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"). |
| 4 | +# You may not use this file except in compliance with the License. |
| 5 | +# A copy of the License is located at |
| 6 | +# |
| 7 | +# http://aws.amazon.com/apache2.0/ |
| 8 | +# |
| 9 | +# or in the "LICENSE.txt" file accompanying this file. |
| 10 | +# This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied. |
| 11 | +# See the License for the specific language governing permissions and limitations under the License. |
| 12 | +import base64 |
| 13 | +import logging |
| 14 | +import os |
| 15 | +import socket |
| 16 | +from math import ceil |
| 17 | +from multiprocessing import Pool |
| 18 | + |
| 19 | +from common.utils import run_command |
| 20 | +from paramiko import HostKeys, RSAKey, Transport |
| 21 | + |
| 22 | + |
| 23 | +def _get_server_keys(hostname): |
| 24 | + |
| 25 | + server_keys = [] |
| 26 | + |
| 27 | + # key_type_list = ["ssh-ed25519", "ssh-rsa", "ecdsa-sha2-nistp256"] # default key_type used by ssh-keysca |
| 28 | + # Supported key_type for OS |
| 29 | + # alinux ssh-rsa,ssh-ed25519,ecdsa-sha2-nistp256 |
| 30 | + # ubuntu1404 ssh-rsa,ssh-ed25519,ecdsa-sha2-nistp256 |
| 31 | + # ubuntu1604 ssh-rsa,ssh-ed25519,ecdsa-sha2-nistp256 |
| 32 | + # centos7 ssh-rsa,ssh-ed25519,ecdsa-sha2-nistp256 |
| 33 | + # centos6 ssh-rsa |
| 34 | + key_type_list = ["ssh-rsa"] |
| 35 | + |
| 36 | + for key_type in key_type_list: |
| 37 | + transport = None |
| 38 | + try: |
| 39 | + sock = socket.socket() |
| 40 | + sock.settimeout(5) |
| 41 | + sock.connect((hostname, 22)) |
| 42 | + transport = Transport(sock) |
| 43 | + transport._preferred_keys = [key_type] |
| 44 | + transport.start_client() |
| 45 | + server_keys.append(transport.get_remote_server_key()) |
| 46 | + except Exception: |
| 47 | + pass |
| 48 | + finally: |
| 49 | + if transport: |
| 50 | + transport.close() |
| 51 | + |
| 52 | + if not server_keys: |
| 53 | + logging.error("Failed retrieving server key from host '%s'", hostname) |
| 54 | + |
| 55 | + return hostname, [(server_key.get_base64(), server_key.get_name()) for server_key in server_keys] |
| 56 | + |
| 57 | + |
| 58 | +def _get_server_key_on_multiple_hosts(hostnames, parallelism=25, timeout=7): |
| 59 | + if not hostnames: |
| 60 | + return {} |
| 61 | + |
| 62 | + pool = Pool(parallelism) |
| 63 | + try: |
| 64 | + r = pool.map_async(_get_server_keys, hostnames) |
| 65 | + # The pool timeout is computed by adding 2 times the command timeout for each batch of hosts that is |
| 66 | + # processed in sequence. Where the size of a batch is given by the degree of parallelism. |
| 67 | + results = r.get(timeout=int(ceil(len(hostnames) / float(parallelism)) * (2 * timeout))) |
| 68 | + return dict(results) |
| 69 | + except Exception as e: |
| 70 | + logging.error("Failed when retrieving keys from hosts %s with exception %s", ",".join(hostnames), e) |
| 71 | + return dict() |
| 72 | + finally: |
| 73 | + pool.terminate() |
| 74 | + |
| 75 | + |
| 76 | +def _add_keys_to_known_hosts(server_keys, host_keys_file): |
| 77 | + try: |
| 78 | + if not os.path.isfile(host_keys_file): |
| 79 | + host_keys = HostKeys() |
| 80 | + else: |
| 81 | + host_keys = HostKeys(filename=host_keys_file) |
| 82 | + |
| 83 | + for hostname, key_list in server_keys.items(): |
| 84 | + try: |
| 85 | + for key_tuple in key_list: |
| 86 | + key = RSAKey(data=base64.b64decode(key_tuple[0])) |
| 87 | + host_keys.add(hostname=hostname, key=key, keytype=key_tuple[1]) |
| 88 | + host_keys.add(hostname=hostname + ".*", key=key, keytype=key_tuple[1]) |
| 89 | + host_keys.add(hostname=socket.gethostbyname(hostname), key=key, keytype=key_tuple[1]) |
| 90 | + logging.info( |
| 91 | + "Adding keys to known hosts file '{0}' for host '{1}'".format(host_keys_file, hostname) |
| 92 | + ) |
| 93 | + host_keys.save(filename=host_keys_file) |
| 94 | + except Exception as e: |
| 95 | + logging.error( |
| 96 | + "Failed adding keys to known hosts file for host '{0}', with exception: {1}".format(hostname, e) |
| 97 | + ) |
| 98 | + except Exception as e: |
| 99 | + logging.error("Failed adding keys to known hosts file '{0}', with exception: {1}".format(host_keys_file, e)) |
| 100 | + |
| 101 | + |
| 102 | +def _remove_keys_from_known_hosts(hostnames, host_keys_file, user): |
| 103 | + for hostname in hostnames: |
| 104 | + command = "ssh-keygen -R " + hostname + " -f " + host_keys_file |
| 105 | + run_command(command, raise_on_error=False, execute_as_user=user) |
| 106 | + command = "ssh-keygen -R " + hostname + ". -f " + host_keys_file |
| 107 | + run_command(command, raise_on_error=False, execute_as_user=user) |
| 108 | + command = "ssh-keygen -R " + socket.gethostbyname(hostname) + " -f " + host_keys_file |
| 109 | + run_command(command, raise_on_error=False, execute_as_user=user) |
| 110 | + |
| 111 | + |
| 112 | +def update_ssh_known_hosts(events, user): |
| 113 | + host_keys_file = os.path.expanduser("~" + user) + "/.ssh/known_hosts" |
| 114 | + _remove_keys_from_known_hosts( |
| 115 | + [event.host.hostname for event in events if event.action == "REMOVE"], host_keys_file, user |
| 116 | + ) |
| 117 | + _add_keys_to_known_hosts( |
| 118 | + _get_server_key_on_multiple_hosts([event.host.hostname for event in events if event.action == "ADD"]), |
| 119 | + host_keys_file, |
| 120 | + ) |
0 commit comments