Skip to content

Commit d7bb1dd

Browse files
committed
Restore know host file management for CentOS6
The OpenSSH version in CentOS6 doesn't support the Match directive that allows to conditionally disable the StrictHostKeyChecking parameter Signed-off-by: Luca Carrogu <[email protected]>
1 parent ab276b2 commit d7bb1dd

File tree

3 files changed

+128
-1
lines changed

3 files changed

+128
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ This file is used to list changes made in each version of the aws-parallelcluste
77
-----
88

99
**CHANGES**
10-
- Remove logic that was adding compute nodes identity to known_hosts file.
10+
- Remove logic that was adding compute nodes identity to known_hosts file for all OSs except CentOS6
1111

1212
2.5.1
1313
-----

src/common/ssh_keyscan.py

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
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+
)

src/sqswatcher/sqswatcher.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import collections
1414
import json
1515
import logging
16+
import platform
1617
from collections import OrderedDict
1718
from datetime import datetime
1819

@@ -22,6 +23,7 @@
2223
from configparser import ConfigParser
2324
from retrying import retry
2425

26+
from common.ssh_keyscan import update_ssh_known_hosts
2527
from common.time_utils import seconds
2628
from common.utils import (
2729
CriticalError,
@@ -336,6 +338,11 @@ def _process_sqs_messages(
336338

337339

338340
def update_cluster(instance_properties, max_cluster_size, scheduler_module, sqs_config, update_events):
341+
# Centos6 - Managing SSH host keys for the nodes joining and leaving the cluster
342+
# All other OSs support disabling StrictHostKeyChecking conditionally through ssh_config Match directive
343+
if ".el6." in platform.platform():
344+
update_ssh_known_hosts(update_events, sqs_config.cluster_user)
345+
339346
try:
340347
failed_events, succeeded_events = scheduler_module.update_cluster(
341348
max_cluster_size, sqs_config.cluster_user, update_events, instance_properties

0 commit comments

Comments
 (0)