-
Notifications
You must be signed in to change notification settings - Fork 14
/
ash_linux.py
317 lines (256 loc) · 10.3 KB
/
ash_linux.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
# -*- coding: utf-8 -*-
"""
Provide custom modules for ash-linux.
:maintainer: Loren Gordon <[email protected]>
"""
import os
import re
try:
from salt.utils.files import fopen
except ImportError:
from salt.utils import fopen
__virtualname__ = "ash"
def __virtual__():
if __grains__.get("kernel", "") == "Linux":
return __virtualname__
return False, "ash_linux module works only on Linux systems"
def _move_boot_kernel(restore_bak):
"""
Create/restore backup of boot-kernel file.
Args:
restore_bak: (`obj`: `bool`)
True if restoring backup of boot-kernel. False to create a backup.
"""
if restore_bak:
filename = "initramfs-" + os.uname()[2] + ".img.bak"
new_path = os.path.join("/boot", filename[:-4])
else:
filename = "initramfs-" + os.uname()[2] + ".img"
new_path = os.path.join("/boot", filename + ".bak")
old_path = os.path.join("/boot", filename)
if os.path.exists(old_path):
__salt__["file.move"](old_path, new_path)
return old_path
def _get_default_kernel():
"""Obtain default kernel from grubby command."""
cmd = "grubby --default-kernel"
return __salt__["cmd.run"](cmd, python_shell=True, output_loglevel="quiet")
def _get_boot_path():
"""Obtain path that kernel is located in."""
boot_path = _get_default_kernel()
return boot_path[: boot_path.rindex("/")] or "/"
def _get_boot_mount(boot_path):
"""Obtain mount to path that kernel is located in."""
cmd = "findmnt -no source -T " + boot_path
return __salt__["cmd.run"](cmd, python_shell=True, output_loglevel="quiet")
def _modify_grub_file(rmv_fips_arg):
"""
Insert/remove fips argument from GRUB file in /etc/default.
Args:
rmv_fips_arg: (`obj`: `bool`)
True if removing fips argument. False to add it.
"""
filepath = "/etc/default/grub"
if rmv_fips_arg:
result = __salt__["file.replace"](filepath, "fips=1[ ]", "")
else:
grub_marker = 'GRUB_CMDLINE_LINUX="'
grub_args = []
check = __salt__["file.search"](filepath, "boot=")
if not check:
# No boot= in grub, so find mount where kernel is located.
# Add boot= argument if a boot path exists.
boot_mount = _get_boot_mount(_get_boot_path())
if boot_mount != _get_boot_mount("/"):
grub_args.append("boot={0} ".format(boot_mount))
check = __salt__["file.search"](filepath, "fips=1")
if not check:
grub_args.append("fips=1 ")
if grub_args:
result = __salt__["file.replace"](
filepath, grub_marker, "{0}{1}".format(grub_marker, "".join(grub_args))
)
else:
result = None
return result
def _is_fips_in_kernel():
"""Check image file for fips module."""
filename = "initramfs-" + os.uname()[2] + ".img"
filepath = os.path.join("/boot", filename)
cmd = "lsinitrd -m {0} | grep fips".format(filepath)
result = (
__salt__["cmd.run"](cmd, python_shell=True, output_loglevel="quiet") == "fips"
)
return result
def _get_installed_dracutfips_pkgs():
"""
Return list of available dracut-fips pkgs to install.
We currently resort to using an actual call to yum as Salt's
pkg.list_repo_pkgs() does not look in repos that have been enabled
like "enabled = 1" instead of "enabled=1". Once that has been
addressed in Salt, we can update this to use Salt's command.
"""
cmd = "yum list installed"
available_pkgs = __salt__["cmd.run"](cmd, python_shell=False)
return re.findall(r"\bdracut-fips[^.]*", available_pkgs)
def _get_grub_args():
"""Obtain arguments line in grubby command."""
cmd = "grubby --info=" + _get_default_kernel() + " | grep args="
return __salt__["cmd.run"](cmd, python_shell=True, output_loglevel="quiet")
def _rollback_fips_disable(installed_fips_pkgs):
"""
Rollback the actions of fips_disable() upon a thrown error.
Args:
installed_fips_pkgs: (`obj`: `list`)
List of installed dracut-fips packages that were removed
during the process of running fips_disable().
"""
__salt__["pkg.install"](installed_fips_pkgs)
if not _is_fips_in_kernel():
_move_boot_kernel(True)
grub_bak = "/etc/default/grub.bak"
if os.path.exists(grub_bak):
__salt__["file.move"](grub_bak, "/etc/default/grub")
__salt__["cmd.run"]("grubby --update-kernel=ALL --args=fips=1", python_shell=False)
def fips_disable(): # pylint: disable=too-many-branches,inconsistent-return-statements
"""
Disables FIPS on RH/CentOS system.
Note: you must reboot the system in order for FIPS to be disabled.
This routine prepares the system to disable FIPS.
CLI Example:
.. code-block:: bash
salt '*' ash.fips_disable
"""
installed_fips_pkgs = _get_installed_dracutfips_pkgs()
ret = {"result": True}
old = {}
new = {}
try:
# Remove dracut-fips installations.
installed_fips_pkgs = _get_installed_dracutfips_pkgs()
if "dracut-fips" in installed_fips_pkgs:
__salt__["pkg.remove"]("dracut-fips")
old["Packages"] = installed_fips_pkgs
# If fips is in kernel, create a new boot-kernel.
if _is_fips_in_kernel():
_move_boot_kernel(False)
__salt__["cmd.run"]("dracut -f", python_shell=False)
# Update grub.cfg file to remove the fips argument.
grub_args = _get_grub_args()
if "fips=1" in grub_args:
cmd = "grubby --update-kernel=ALL --remove-args=fips=1"
__salt__["cmd.run"](cmd, python_shell=False)
new["grubby"] = cmd
# Update GRUB command line entry to remove fips.
diff = _modify_grub_file(True)
if diff:
new["/etc/default/grub"] = diff
except Exception: # pylint: disable=broad-exception-caught
_rollback_fips_disable(installed_fips_pkgs)
ret["result"] = False
ret["changes"] = {}
ret["comment"] = "Unable to change state of system to FIPS-disabled."
else:
if old:
ret["changes"] = {"old": old}
ret["comment"] = "FIPS has been toggled to off."
if new:
if "changes" in ret:
ret["changes"].update({"new": new})
else:
ret["changes"] = {"new": new}
ret["comment"] = "FIPS has been toggled to off."
if fips_status() == "enabled":
msg = " Reboot system to place into FIPS-disabled state."
if "comment" in ret:
ret["comment"] = ret["comment"] + msg
else:
ret["comment"] = msg[1:]
if "changes" not in ret and "comment" not in ret:
ret["comment"] = "FIPS mode is already disabled. No changes."
finally:
return ret # pylint: disable=lost-exception,return-in-finally
def _rollback_fips_enable():
"""Rollback the actions of fips_enable() upon a thrown error."""
__salt__["pkg.remove"]("dracut-fips")
if _is_fips_in_kernel():
_move_boot_kernel(True)
grub_bak = "/etc/default/grub.bak"
if os.path.exists(grub_bak):
__salt__["file.move"](grub_bak, "/etc/default/grub")
__salt__["cmd.run"](
"grubby --update-kernel=ALL --remove-args=fips=1", python_shell=False
)
def fips_enable(): # pylint: disable=too-many-branches,inconsistent-return-statements
"""
Enable FIPS on RH/CentOS system.
Note: You must reboot the system in order for FIPS to be disabled.
This routine prepares the system to disable FIPS.
CLI Example:
.. code-block:: bash
salt '*' ash.fips_enable
"""
ret = {"result": True}
new = {}
try:
# Install dracut-fips package.
installed_fips_pkgs = _get_installed_dracutfips_pkgs()
if "dracut-fips" not in installed_fips_pkgs:
__salt__["pkg.install"]("dracut-fips")
installed_fips_pkgs = _get_installed_dracutfips_pkgs()
new["Packages"] = installed_fips_pkgs
# If fips is not in kernel, create a new boot-kernel.
if not _is_fips_in_kernel():
_move_boot_kernel(False)
__salt__["cmd.run"]("dracut -f", python_shell=False)
# Update grub.cfg file to add the fips and boot agurments.
grubby_args = []
grub_args = _get_grub_args()
if "fips=1" not in grub_args:
grubby_args.append("fips=1")
# Add boot= argument if a boot path exists.
boot_mount = _get_boot_mount(_get_boot_path())
if "boot=" not in grub_args and boot_mount != _get_boot_mount("/"):
grubby_args.append("boot={0}".format(boot_mount))
if grubby_args:
cmd = 'grubby --update-kernel=ALL --args="{0}"'.format(
" ".join(grubby_args)
)
__salt__["cmd.run"](cmd, python_shell=False)
new["grubby"] = cmd
# Update GRUB command line entry to add fips.
diff = _modify_grub_file(False)
if diff:
new["/etc/default/grub"] = diff
except Exception: # pylint: disable=broad-exception-caught
_rollback_fips_enable()
ret["result"] = False
ret["comment"] = "Unable to change state of system to FIPS-enabled."
else:
if new:
ret["changes"] = {"new": new}
ret["comment"] = "FIPS has been toggled to on."
if fips_status() == "disabled":
msg = " Reboot system to place into FIPS-enabled state."
if "comment" in ret:
ret["comment"] = ret["comment"] + msg
else:
ret["comment"] = msg[1:]
if "changes" not in ret and "comment" not in ret:
ret["comment"] = "FIPS mode is already enabled. No changes."
finally:
return ret # pylint: disable=lost-exception,return-in-finally
def fips_status():
"""
Return the status of fips on the currently running system.
Returns a `str` of "enabled" if FIPS is enabled. Otherwise,
returns a `str` of "disabled".
CLI Example:
.. code-block:: bash
salt '*' ash.fips_status
"""
try:
with fopen("/proc/sys/crypto/fips_enabled", "r") as fle:
return "enabled" if fle.read().strip() == "1" else "disabled"
except (IOError, FileNotFoundError):
return "disabled"