-
Notifications
You must be signed in to change notification settings - Fork 1
/
ros-tls.py
215 lines (145 loc) · 6.31 KB
/
ros-tls.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
#!/bin/env python3
import datetime
import OpenSSL
from colorama import init, Fore, Style
from paramiko.client import SSHClient
import paramiko
import requests
import os.path
import shutil
import subprocess
import re
import json
import sys
import ssl
init()
#
# Configuration
#
def read_config():
try:
with open('config.json') as f:
return json.load(f)
except IOError:
raise Exception("create a config.json - see config.json.example")
#
# Here be dragons!
#
__VERSION__ = '0.0.0.1'
paramiko.util.log_to_file('ssh.log')
MATCH_CERTIFICATE = re.compile('certificate=(\\S+)')
def run_command(client, command):
_, stdout, stderr = client.exec_command(command)
print(''.join(stdout.readlines()))
print(''.join(stderr.readlines()))
def renew_certificate(host, lego_exe_path, email):
"""Use the lego client to request a new Let's Encrypt certificate."""
result = subprocess.call(
[lego_exe_path, '--domains', host, '--email', email, '--accept-tos', '--dns', 'route53', 'run'])
if result == 0:
print(Fore.GREEN + '--> Renewed certificate!' + Fore.RESET)
return True
else:
print(Fore.RED + '--> Failed to renew certificate!' + Fore.RESET)
return False
def connect_via_ssh(host, ssh_user, ssh_key_path):
client = SSHClient()
client.load_system_host_keys()
client.connect(host, username=ssh_user, key_filename=ssh_key_path, allow_agent=False, look_for_keys=False)
return client
def upload_certificate(host, sftp_client, certificate_path):
print('--> Uploading certificate')
with open(certificate_path, 'r') as cert:
with sftp_client.open(host + '.crt', 'w') as remote_cert:
remote_cert.write(cert.read())
print('--> Uploaded certificate')
def upload_key(host, sftp_client, private_key_path):
print('--> Uploading private key')
with open(private_key_path, 'r') as private_key:
with sftp_client.open(host + '.key', 'w') as remote_key:
remote_key.write(private_key.read())
print('--> Uploaded private key')
def get_current_certificate(client):
_, stdout, stderr = client.exec_command('/ip service print detail where name=www-ssl')
output = ''.join(stdout.readlines())
certificates = MATCH_CERTIFICATE.findall(output)
if len(certificates) == 0:
print('--> No current certificate found')
return None
else:
if certificates[0] != '*1' and certificates[0] != 'none':
print('--> Configured to use certificate "%s"' % certificates[0])
return certificates[0]
else:
return None
def delete_certificate(client, certificate):
print('--> Deleting certificate %s' % certificate)
run_command(client, '/certificate remove ' + certificate)
crl_path = certificate.replace('crt', 'crl')
print('--> Deleting certificate revocation list %s' % certificate)
run_command(client, '/certificate remove ' + crl_path)
def import_certificate(host, client):
certificate_path = host + '.crt'
print('--> Importing certificate')
run_command(client, '/certificate import passphrase="" file-name=' + certificate_path)
print('--> Imported certificate')
def import_key(host, client):
key_path = host + '.key'
print('--> Importing private key')
run_command(client, '/certificate import passphrase="" file-name=' + key_path)
print('--> Imported private key')
def set_new_certificate(host, client):
new_certificate_name = host + '.crt_0'
print('--> Setting new certificate to %s' % new_certificate_name)
run_command(client, '/ip service set www-ssl certificate=' + new_certificate_name)
print('--> New certificate installed')
def replace_certificate(host, ssh_user, ssh_key_path):
"""Upload an X509 certificate to the RouterOS device."""
certificate_path = os.path.join('.lego', 'certificates', host + '.crt')
private_key_path = os.path.join('.lego', 'certificates', host + '.key')
if os.path.exists(certificate_path) and os.path.exists(private_key_path):
client = connect_via_ssh(host, ssh_user, ssh_key_path)
sftp_client = client.open_sftp()
upload_certificate(host, sftp_client, certificate_path)
upload_key(host, sftp_client, private_key_path)
current_certificate = get_current_certificate(client)
if current_certificate:
delete_certificate(client, current_certificate)
import_certificate(host, client)
import_key(host, client)
set_new_certificate(host, client)
client.close()
else:
print(Fore.RED + '--> Could not find certificate' + Fore.RESET)
def check_hosts():
print('ros-tls ' + Style.BRIGHT + 'v' + __VERSION__ + Style.RESET_ALL)
if sys.version_info[0] != 3:
exit(Fore.RED + 'python 3 is required')
config = read_config()
lego_exe_path = shutil.which('lego')
if lego_exe_path is None:
exit(Fore.RED + 'lego command not found - is it installed?')
for host in config['hosts']:
print('-> Checking for valid certificate on %s' % host)
try:
requests.get('https://' + host)
certificate = ssl.get_server_certificate((host, 443))
parsed_certificate = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, certificate)
not_after = datetime.datetime.strptime(parsed_certificate.get_notAfter().decode('utf-8'), "%Y%m%d%H%M%SZ")
now = datetime.datetime.now()
if not_after - now <= datetime.timedelta(days=15):
print('-> Certificate needs renewing (expires soon)')
renewed = renew_certificate(host, lego_exe_path, config['adminEmail'])
if renewed:
replace_certificate(host, config['sshUser'], config['sshKeyPath'])
else:
print('-> Certificate appears to be OK - doing nothing')
except requests.exceptions.SSLError:
print('-> Certificate needs renewing (or other SSL error)')
renewed = renew_certificate(host, lego_exe_path, config['adminEmail'])
if renewed:
replace_certificate(host, config['sshUser'], config['sshKeyPath'])
except requests.exceptions.ConnectionError as e:
print(e)
exit((Fore.RED + 'Failed to connect to host %s!' + Fore.RESET) % host)
check_hosts()