-
Notifications
You must be signed in to change notification settings - Fork 2
/
eopeers.py
321 lines (288 loc) · 10.2 KB
/
eopeers.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
#!/usr/bin/env python
# This file is part of misc-tools.
# Copyright (C) 2014-2016 Sequent Tech Inc <legal@sequentech.io>
# misc-tools is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License.
# misc-tools 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 Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with misc-tools. If not, see <http://www.gnu.org/licenses/>.
import argparse
import os
import json
import shutil
import subprocess
try:
CONFIG = json.load(open('/etc/eoconf.json'))
except:
print("/etc/eoconf.json not found, using default vars")
CONFIG = {
"PEER_LIST": "/etc/eopeers",
"VERSION": 1,
"PUBLIC_IP_ADDRESS": "192.168.0.1",
"PRIVATE_IP_ADDRESS": "192.168.0.1",
"HOSTNAME": "election-orchestra",
"PORT": 5000,
"KEYSTORE_PASS": "supersecret"
}
PEER_LIST = CONFIG['PEER_LIST']
VERSION = CONFIG['VERSION']
PUBLIC_IP_ADDRESS = CONFIG['PUBLIC_IP_ADDRESS']
PRIVATE_IP_ADDRESS = CONFIG['PRIVATE_IP_ADDRESS']
HOSTNAME = CONFIG['HOSTNAME']
PORT = CONFIG['PORT']
def _validate_package(el_json):
'''
Validates a package
'''
check_list = [
dict(
key="ssl_certificate",
existence="required",
checks=[
lambda val: isinstance(val, basestring) and len(val) < 10000
]
),
dict(
key="ip_address",
existence="required",
checks=[
lambda val: isinstance(val, basestring) and len(val) < 100
]
),
dict(
key="hostname",
existence="required",
checks=[
lambda val: isinstance(val, basestring) and len(val) < 100
]
),
dict(
key="port",
existence="optional",
checks=[
lambda val: isinstance(val, int) and val > 0 and val < 65536
]
),
dict(
key="version",
existence="optional",
checks=[
lambda val: isinstance(val, int) and val > 0 and val < 10000,
lambda val: val <= VERSION or\
"Package from a incompatible version (package is version "\
"%d, eopeers is version %d)" % (VERSION, val)
]
)
]
valid_keys = set([check['key'] for check in check_list])
unknown_keys = valid_keys.difference(set(el_json.keys()))
if len(unknown_keys) > 0:
print("Unknown keys: %s" % ", ".join(list(unknown_keys)))
for check in check_list:
if check['key'] not in el_json.keys():
if check['existence'] == 'required':
print("missing required key: %s" % check['key'])
exit(1)
else:
continue
data = el_json[check['key']]
for check_f in check['checks']:
check_ret = check_f(data)
if check_ret == True:
continue
if isinstance(check_ret, basestring):
print(check_ret)
exit(1)
else:
print("Invalid data for key %s: %s" % (check['key'], str(data)[:100]))
exit(1)
def install(PEER_LIST, path, keystore=None):
'''
install the peer package by path
'''
if not os.path.exists(PEER_LIST):
os.mkdir(PEER_LIST)
if not os.path.isfile(path):
print("Could not read file: %s" % path)
exit(1)
try:
with open(path, 'r') as f:
el_json = json.loads(f.read())
_validate_package(el_json)
except:
print("error loading file: %s" % path)
import traceback
traceback.print_exc()
exit(1)
# check it's not already installed
bname = el_json['hostname']
if os.path.exists(os.path.join(PEER_LIST, bname)):
print("package for hostname %s already installed" % bname)
exit(1)
# add to hosts if needed
with open("/etc/hosts", "r") as f:
hosts_data = f.read()
hostline = "\n%s %s" % (el_json['ip_address'], el_json["hostname"])
if hostline not in hosts_data:
subprocess.call("echo '%s' >> /etc/hosts" % hostline, shell=True)
# add to ssl certs
with open("/srv/certs/selfsigned/calist", "r") as f:
calist_data = f.read().strip()
if el_json["ssl_certificate"] not in calist_data:
subprocess.call("echo '%s' >> /srv/certs/selfsigned/calist" %
el_json["ssl_certificate"], shell=True)
try:
shutil.copyfile("/srv/certs/selfsigned/calist", "/home/eorchestra/election-orchestra/certs/selfsigned/calist")
except:
# It's not critical if the eorchestra is not installed. This is
# optional
pass
# save peer package
path = os.path.join(PEER_LIST, el_json['hostname'] + ".package")
with open(path, 'w') as f:
f.write(json.dumps(el_json))
if keystore:
keystore = keystore[0]
# adding the key to the keystore
temppem = "/tmp/eopeers-auth.pem"
with open(temppem, "w") as f:
f.write(el_json["ssl_certificate"])
#keytool --delete mykey -keystore keystore.jks
subprocess.call("keytool -noprompt -import -file %s -keystore %s -storepass '%s' -alias %s" % (temppem, keystore, CONFIG['KEYSTORE_PASS'], bname), shell=True)
os.unlink(temppem)
def uninstall(PEER_LIST, hostname, keystore=None):
'''
uninstall the peer package by hostname
'''
# check it's not already installed
path = os.path.join(PEER_LIST, hostname + ".package")
if not os.path.exists(path):
print("package for hostname %s is not installed" % hostname)
exit(1)
try:
with open(path, 'r') as f:
el_json = json.loads(f.read())
_validate_package(el_json)
except:
print("error loading file: %s" % path)
import traceback
traceback.print_exc()
exit(1)
# remove hostname from hosts
with open('/etc/hosts', 'r') as f:
data = f.read()
hostline = "\n%s %s" % (el_json['ip_address'], el_json["hostname"])
data = data.replace(hostline, "")
with open('/etc/hosts', 'w') as f:
f.write(data)
# remove from ssl certs
with open('/srv/certs/selfsigned/calist', 'r') as f:
data = f.read()
data = data.replace(el_json["ssl_certificate"], "")
with open('/srv/certs/selfsigned/calist', 'w') as f:
f.write(data)
try:
shutil.copyfile("/srv/certs/selfsigned/calist", "/home/eorchestra/election-orchestra/certs/selfsigned/calist")
except:
# It's not critical if the eorchestra is not installed. This is
# optional
pass
# finally remove the package
os.unlink(path)
if keystore:
keystore = keystore[0]
# removing the key from the keystore
subprocess.call("keytool -noprompt -delete -alias %s -keystore %s -storepass '%s'" % (hostname, keystore, CONFIG['KEYSTORE_PASS']), shell=True)
def showmine(pargs):
'''
install the peer package by path
'''
with open('/srv/certs/selfsigned/cert.pem', 'r') as f:
ssl_certificate = f.read()
ip = PRIVATE_IP_ADDRESS if pargs.private_ip else PUBLIC_IP_ADDRESS
us = {
"ssl_certificate": ssl_certificate,
"ip_address": ip,
"hostname": HOSTNAME,
"port": PORT,
"version": VERSION
}
print(json.dumps(us))
def listall(PEER_LIST):
'''
return a list of peer packagers loaded in json
'''
if not os.path.isdir(PEER_LIST):
return []
l = os.listdir(PEER_LIST)
if len(l) == 0:
return []
ret = []
for el in l:
path = os.path.join(PEER_LIST, el)
try:
with open(path, 'r') as f:
ret.append(json.loads(f.read()))
except:
print("error loading: %s" % el)
import traceback
traceback.print_exc()
exit(1)
return ret
def show_pkg(hostname):
'''
show the content of a peer package referred by hostname
'''
# check it's not already installed
path = os.path.join(PEER_LIST, hostname + ".package")
if not os.path.exists(path):
print("package for hostname %s is not installed" % hostname)
exit(1)
try:
with open(path, 'r') as f:
print(f.read())
except:
print("error loading file: %s" % path)
import traceback
traceback.print_exc()
exit(1)
def main():
'''
Main function
'''
parser = argparse.ArgumentParser(prog='eopeers')
parser.add_argument("--list", help="list installed peer packages by hostname", action="store_true")
parser.add_argument('--install', nargs='+', help='install a peer package')
parser.add_argument('--uninstall', nargs='+', help='uninstall peer package(s) by hostname')
parser.add_argument('--show-mine', help='show our peer package', action="store_true")
parser.add_argument('--private-ip', help='together with --show-mine, uses '
'private ip instead of the public one', action="store_true")
parser.add_argument('--show', help="show the content of an installed package "
"by hostname")
parser.add_argument('--keystore', nargs=1, help='The keystore path '
'to add or remove with keytool')
pargs = parser.parse_args()
if pargs.list:
l = listall(PEER_LIST)
if len(l) == 0:
print("No peer package installed.")
exit(0)
print("Packages in %s:" % PEER_LIST)
for el in l:
print(" * %s" % el['hostname'])
elif pargs.install:
for path in pargs.install:
install(PEER_LIST, path, pargs.keystore)
elif pargs.uninstall:
for path in pargs.uninstall:
uninstall(PEER_LIST, path, pargs.keystore)
elif pargs.show_mine:
showmine(pargs)
elif pargs.show:
show_pkg(pargs.show)
if __name__ == "__main__":
main()