-
Notifications
You must be signed in to change notification settings - Fork 10
/
utils.py
388 lines (323 loc) · 13.6 KB
/
utils.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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
import datetime
import difflib
import re
import subprocess as subp
from configparser import RawConfigParser
from os.path import isdir, isfile, join, basename, split
from random import randint
from shutil import copy2, copytree
import pexpect
import sys
from SCAutolib import env_logger, base_logger
from SCAutolib.src import read_env, env
from SCAutolib.src.exceptions import *
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import NameOID
from decouple import UndefinedValueError
from time import sleep
SERVICES = {"sssd": "/etc/sssd/sssd.conf", "krb": "/etc/krb5.conf"}
def show_file_diff(original, new):
differ = difflib.Differ()
with open(original, "r") as f:
data_original = f.readlines()
with open(new, "r") as f:
data_new = f.readlines()
with open("/var/log/scautolib/edited_files.log", "a") as f:
f.write("\n================\n")
f.writelines(differ.compare(data_original, data_new))
f.write("================\n")
def edit_config(config_path: str, section: str, key: str, value: str = "",
restore=False, *restart):
"""
Decorator for editing config file. Before editing, config file is saved.
Args:
config_path: path to config file to be updated
section: section in config file where a key is placed
key: key to by updated
value: value to be set for a given key
restore: if true, original file would be restored after function is finished
Returns:
decorated function
"""
def wrapper(test):
def inner_wrapper(*args, **kwargs):
target = backup_(file_path=config_path)
edit_config_(config_path, section, key, value)
show_file_diff(config_path, target)
for service in restart:
restart_service(service)
test(*args, **kwargs)
if restore:
restore_file_(target, config_path)
return inner_wrapper
return wrapper
def backup(*restart, file_path: str, name: str = None, restore=True,):
"""
Decorator for backup the file into BACKUP directory. Can restore the file
after execution of function and restart given service.
Args:
file_path: path to file to be saved
name: name for backup file (optional)
restore: specifies if given file should be restored after function execution
Returns:
decorated function
"""
if name is None:
# if no name is given, than original name of the file would be used
name = split(file_path)[1]
def wrapper(test):
def inner_wrapper(*args, **kwargs):
destination = backup_(file_path)
test(*args, **kwargs)
if restore:
restore_file_(file_path, destination)
for service in restart:
restart_service(service)
return inner_wrapper
return wrapper
def restore_file_(source, destination):
"""
Restoring file from BACKUP directory to target. Target has to be a file.
"""
copy2(source, destination)
env.run(["restorecon", "-v", destination])
base_logger.debug(f"File from {source} is restored to {destination}")
def backup_(file_path):
"""
Backup the file given in file_path to BACKUP directory.
Args:
file_path: path to file to be saved
Returns:
Path to copied file/directory
"""
target = join(read_env('BACKUP'), basename(file_path) + ".bak")
if isfile(file_path):
target = copy2(file_path, target)
elif isdir(file_path):
target = copytree(file_path, target)
env.run(f"restorecon -v {target}")
base_logger.debug(f"Source from {file_path} is copied to {target}")
return target
def edit_config_(conf: str, section: str, key: str, value: str = ""):
"""
Function for actual editing the config file.
Args:
conf: path to config file
key: key to be updated
value: value to be set for key
section: section where a key is placed.
"""
cnf = RawConfigParser()
cnf.optionxform = str
with open(conf, "r") as file:
cnf.read_file(file)
if section not in cnf.sections():
base_logger.error(
f"Section {section} is not present in config file {conf}")
raise UnknownOption(
msg=f"Section {section} is not present in config file {conf}")
cnf.set(section, key, value)
with open(conf, "w") as file:
cnf.write(file)
base_logger.debug(f"Value for key {key} in section {section} is set to {value} "
f"in file {conf}")
def restart_service(service: str) -> int:
"""
Restart given service and wait 5 sec
Args:
service: service name
Returns:
return code of systemctl restart
"""
if service is not None:
try:
result = env.run(
["systemctl", "restart", f"{service}"])
sleep(5)
env_logger.debug(f"Service {service} is restarted")
return result.returncode
except subp.CalledProcessError as e:
env_logger.error(
f"Command {' '.join(e.cmd)} is ended with non-zero return code ({e.returncode})")
env_logger.error(f"stdout:\n{e.stdout}")
env_logger.error(f"stderr:\n{e.stderr}")
return e.returncode
return 0
def generate_cert(username=None):
"""
Function for generating the root CA certificate with keys
Returns:
tuple with path to the certificate and to the key files.
"""
tmp = read_env("TMP")
prefix = username if username == "root" else "User"
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
serial = randint(1, 1000)
cert_path = f"{tmp}/rootCA{serial}.pem"
key_path = f"{tmp}/private-key-{serial}.pem"
subject = issuer = ""
basic_constraints = x509.BasicConstraints(ca=True, path_length=None)
builder = x509.CertificateBuilder()
with open(key_path, "wb") as f:
f.write(key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()))
if username == "root":
key_usage = x509.KeyUsage(
digital_signature=True, content_commitment=False,
key_encipherment=False, data_encipherment=False,
key_agreement=False, key_cert_sign=True,
crl_sign=True, encipher_only=False,
decipher_only=False)
subject = issuer = x509.Name([
x509.NameAttribute(NameOID.ORGANIZATION_NAME, f"root-{serial}"),
x509.NameAttribute(
NameOID.ORGANIZATIONAL_UNIT_NAME, f"root-{serial} Test"),
x509.NameAttribute(NameOID.COMMON_NAME, f"root-{serial} Test Ca"),
])
else:
key_usage = x509.KeyUsage(
digital_signature=False, content_commitment=False,
key_encipherment=False, data_encipherment=False,
key_agreement=False, key_cert_sign=False,
crl_sign=False, encipher_only=False,
decipher_only=False)
try:
root_cert_path = join(read_env("CA_DIR"), "rootCA.pem")
with open(root_cert_path, "rb") as f:
root_crt = x509.load_pem_x509_certificate(f.read())
issuer = root_crt.issuer
subject = x509.Name([
x509.NameAttribute(NameOID.ORGANIZATION_NAME,
f"{prefix}-{serial}"),
x509.NameAttribute(
NameOID.ORGANIZATIONAL_UNIT_NAME, f"{prefix}-{serial} Test"),
x509.NameAttribute(NameOID.COMMON_NAME,
f"{prefix}-{serial} Test Ca"),
])
except UndefinedValueError:
base_logger.error("You are trying to generate user certificate, but .env "
"file do not have name for certificate issuer."
"Did you generate self-signed CA certificate?")
subject_key = x509.SubjectKeyIdentifier.from_public_key(key.public_key())
authority_key = x509.AuthorityKeyIdentifier.from_issuer_subject_key_identifier(
subject_key)
env_logger.debug("Type of subject is " + str(type(subject)))
builder = builder \
.subject_name(subject) \
.issuer_name(issuer) \
.public_key(key.public_key()) \
.serial_number(serial) \
.not_valid_before(datetime.datetime.utcnow()) \
.not_valid_after(datetime.datetime.utcnow() + datetime.timedelta(days=365)) \
.add_extension(basic_constraints, critical=True) \
.add_extension(key_usage, critical=True) \
.add_extension(subject_key, critical=True) \
.add_extension(authority_key, critical=True) \
.sign(key, hashes.SHA256())
with open(cert_path, "wb") as f:
f.write(builder.public_bytes(serialization.Encoding.PEM))
return cert_path, key_path
def run_cmd(cmd: str = None, pin: bool = True, passwd: str = None, shell=None,
return_val: str = "stdout"):
"""
Run to create a child from current shell to run cmd. Try to assert
expect pattern in the output of the cmd. If cmd require, provide
login wth given PIN or password. Hitting reject pattern during cmd
execution cause fail.
Args:
cmd: shell command to be executed
pin: specify if passwd is a smart card PIN or a password for the
user_fnc. Base on this, corresponding pattern would be matched
in login output.
passwd: smart card PIN or user_fnc password if login is needed
shell: shell child where command need to be execute.
return_val: return shell (shell) or stdout (stdout - default) or both (all)
Returns:
stdout of executed command (cmd; see above)
"""
try:
if shell is None and cmd is not None:
cmd = ["-c", f'{cmd} ; echo "RC:$?"']
shell = pexpect.spawn("/bin/bash", cmd, encoding='utf-8')
shell.logfile = sys.stdout
if passwd is not None:
pattern = "PIN for " if pin else "Password"
out = shell.expect([pexpect.TIMEOUT, pattern], timeout=10)
if out != 1:
if out == 0:
base_logger.error("Timed out on password / PIN waiting")
raise PatternNotFound(f"Pattern '{pattern}' is not "
f"found in the output.")
shell.sendline(passwd)
except PatternNotFound:
base_logger.error(f"Command: {cmd}")
base_logger.error(f"Output:\n{str(shell.before)}\n")
raise
if return_val == "stdout":
return shell.read()
elif return_val == "shell":
return shell
elif return_val == "all":
return shell, shell.read()
else:
raise UnknownOption(option_val=return_val, option_name="return_val")
def check_output(output: str, expect = None, reject = None,
zero_rc: bool = False, check_rc: bool = False):
"""
Check "output" for presence of expected and unexpected patterns.
Check for presence of expected (required) and unexpected (disallowed)
patterns in the text and raise exceptions if required pattern is missing
or if any of disallowed patterns is present. Check also presence of
pattern "RC:[0-9]+" that in current implementation of run_cmd represents
exit value of executed command and raise an exception in case of
non-zero value.
Args:
output: string where to look for expect/reject patterns. If check_rc
and zero_rc are True, than string has to contain substring
RC:<rc> where <rc> is a return value of the command. NOTE:
substring with return value is automatically added by run_cmd
function.
expect: pattern or list of patterns to be matched in the output
reject: pattern or list of patterns that cause failure if matched in
the output
check_rc: if True, return code of the command will be checked. If False,
(default), return code is not checked.
zero_rc: applicable only with check_rc = True. If zero_rc = True, return
code of the command has to ve 0, otherwise an exception
NonZeroReturnCode would be raise. If False (default), warning
would be added to logs instead of raising an exception.
"""
# TODO: add switch and functionality
# to check patterns in specified order
if reject is None:
reject = []
elif type(reject) == str:
reject = [reject]
if expect is None:
expect = []
elif type(expect) == str:
expect = [expect]
for pattern in reject:
compiled = re.compile(pattern)
if compiled.search(output) is not None:
raise DisallowedPatternFound(f"Disallowed pattern '{pattern}' "
f"was found in the output")
for pattern in expect:
compiled = re.compile(pattern)
if compiled.search(output) is None:
base_logger.error(f"Pattern: {pattern} not found in output")
base_logger.error(f"Output:\n{output}\n")
raise PatternNotFound(f"Pattern '{expect}' is not "
f"found in the output.")
if check_rc:
if "RC:0" not in output:
msg = f"Non zero return code indicated"
if zero_rc:
raise NonZeroReturnCode(msg)
else:
base_logger.warning(msg)
return True