Repository navigation
Expand file tree
/
Copy pathpfsense_autoconfigbackup.py
More file actions
370 lines (310 loc) · 14.4 KB
/
Copy pathpfsense_autoconfigbackup.py
File metadata and controls
370 lines (310 loc) · 14.4 KB
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
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2026, Romain Tiennot
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = r"""
---
module: pfsense_autoconfigbackup
short_description: Manage pfSense AutoConfigBackup settings
version_added: "0.8.0"
description:
- Manage the settings of Services > Auto Config Backup, which keeps encrypted copies of the configuration on Netgate's servers.
- Omitted options preserve existing settings.
- As the web GUI does, saving the settings installs or removes the cron jobs and creates a configuration revision, and enabling
the backups creates a random device key when none is stored.
- A cron job that does not match the settings (missing, different or left over) is a change too. The module installs, updates or
removes it, as each save in the web GUI does.
options:
enable:
description:
- Enable automatic configuration backups.
- An encryption password must be stored or given with O(encryption_password).
type: bool
frequency:
description:
- V(every) backs up after each configuration change saved by pfSense itself. Changes made with this collection do not
trigger it.
- V(cron) backs up on the schedule given by O(minute), O(hour), O(day), O(month) and O(dow), when the configuration changed.
type: str
choices: [every, cron]
minute:
description:
- Minute of the scheduled backups, as in a cron entry (digits and C(*), C(/), C(-), C(,)).
- As in the web GUI, V(0) is not used. When no minute is given or stored, a random one from 1 to 59 is stored.
type: str
hour:
description:
- Hour of the scheduled backups, a number or C(*).
- When none is given or stored, every hour.
type: str
day:
description: Day of the month of the scheduled backups, a number or C(*).
type: str
month:
description: Month of the scheduled backups, a number or C(*).
type: str
dow:
description: Day of the week of the scheduled backups, a number or C(*).
type: str
numman:
description: Number of manual backups to keep, from 0 to 50.
type: int
reverse:
description: List the backups newest first.
type: bool
hint:
description: Hint or identifier shown with the backups, up to 255 characters.
type: str
encryption_password:
description:
- Password that encrypts the backups, at least 8 characters.
- It is compared with the stored password and written when they differ. Backups already uploaded keep their password.
type: str
author: Romain Tiennot (@RomainTie)
"""
EXAMPLES = r"""
- name: Back up the configuration every day at 00:44
pfsensible.core.pfsense_autoconfigbackup:
enable: true
frequency: cron
minute: "44"
hour: "0"
day: "*"
month: "*"
dow: "*"
encryption_password: "{{ vault_acb_password }}"
- name: Disable AutoConfigBackup and retain its settings
pfsensible.core.pfsense_autoconfigbackup:
enable: false
"""
RETURN = r"""
commands:
description: Pseudo-CLI commands describing configuration changes.
returned: always
type: list
elements: str
sample: ["update autoconfigbackup acb set enable=True, frequency='cron'"]
"""
import os
import random
import re
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.pfsensible.core.plugins.module_utils.module_config_base import PFSenseModuleConfigBase
AUTOCONFIGBACKUP_ARGUMENT_SPEC = dict(
enable=dict(type="bool"),
frequency=dict(type="str", choices=["every", "cron"]),
minute=dict(type="str"),
hour=dict(type="str"),
day=dict(type="str"),
month=dict(type="str"),
dow=dict(type="str"),
numman=dict(type="int"),
reverse=dict(type="bool"),
hint=dict(type="str"),
encryption_password=dict(type="str", no_log=True),
)
# What setup_ACB() (/etc/inc/acb.inc) and the settings page do once the settings are stored.
# $new_key is set by the module: true when the backups are being enabled.
AUTOCONFIGBACKUP_PHP_COMMAND = """
require_once("services.inc");
require_once("acb.inc");
if ($new_key && function_exists("acb_generate_device_key") && function_exists("is_valid_acb_device_key") &&
!is_valid_acb_device_key(config_get_path("system/acb/device_key", ""))) {
$key = acb_generate_device_key();
if (is_valid_acb_device_key($key)) {
config_set_path("system/acb/device_key", $key);
}
}
$acb = config_get_path("system/acb", []);
install_cron_job("/usr/bin/nice -n20 /usr/local/bin/php /usr/local/sbin/execacb.php",
($acb["frequency"] ?? "") == "cron",
$acb["minute"] ?? "0",
is_numeric($acb["hour"] ?? "") ? $acb["hour"] : "*",
is_numeric($acb["day"] ?? "") ? $acb["day"] : "*",
is_numeric($acb["month"] ?? "") ? $acb["month"] : "*",
is_numeric($acb["dow"] ?? "") ? $acb["dow"] : "*");
if (file_exists("/usr/local/sbin/acbupload.php")) {
install_cron_job("/usr/bin/nice -n20 /usr/local/bin/php /usr/local/sbin/acbupload.php", ($acb["enable"] ?? "") == "yes", "*");
}
write_config("AutoConfigBackup settings updated");
"""
REDACTED = "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER"
# The commands of the cron jobs the PHP above installs, by the name the module logs them with
CRON_JOBS = dict(
backup_job="/usr/bin/nice -n20 /usr/local/bin/php /usr/local/sbin/execacb.php",
upload_job="/usr/bin/nice -n20 /usr/local/bin/php /usr/local/sbin/acbupload.php",
)
UPLOAD_SCRIPT = "/usr/local/sbin/acbupload.php"
SCHEDULE_FIELDS = ("minute", "hour", "mday", "month", "wday")
NUMBER = re.compile(r"[0-9]+")
def is_secret(field):
"""the stored passwords (including the gold_* ones of the former package) and the device key"""
return "password" in field or field == "device_key"
def php_equal(stored, wanted):
"""compare two values of a cron job as PHP's == does: two numbers are compared as numbers ("05" equals "5")"""
if isinstance(stored, str) and isinstance(wanted, str) and NUMBER.fullmatch(stored) and NUMBER.fullmatch(wanted):
return int(stored) == int(wanted)
return stored == wanted
class PFSenseAutoConfigBackupModule(PFSenseModuleConfigBase):
"""module managing pfSense AutoConfigBackup settings"""
##############################
# unit tests
#
# Must be class method for unit test usage
@staticmethod
def get_argument_spec():
"""return argument spec"""
return AUTOCONFIGBACKUP_ARGUMENT_SPEC
def __init__(self, module, pfsense=None):
super(PFSenseAutoConfigBackupModule, self).__init__(
module,
pfsense,
name="pfsense_autoconfigbackup",
root="system",
node="acb",
create_root=True,
bool_values=dict(enable=("", "yes"), reverse=("", "yes")),
)
self.new_key = False
self.cron_jobs = dict()
##############################
# params processing
#
def _stored(self, field):
acb = self.root_elt.find(self.node)
return acb.findtext(field) if acb is not None else None
def _current(self, field):
if self.params.get(field) is not None:
return self.params[field]
return self._stored(field)
def _validate_params(self):
"""do some extra checks on input parameters"""
params = self.params
if params.get("minute") is not None:
if not re.fullmatch(r"[0-9*/,-]+", params["minute"]):
self.module.fail_json(msg="minute may only contain digits and the characters * / - ,")
if re.fullmatch(r"0+", params["minute"]):
self.module.fail_json(msg="minute 0 is not used by pfSense: give 1 to 59, or omit it to get a random one")
for field in ["hour", "day", "month", "dow"]:
if params.get(field) is not None and not re.fullmatch(r"[0-9]+|\*", params[field]):
self.module.fail_json(msg="{0} must be a number or *".format(field))
numman = params.get("numman")
if numman is not None and (isinstance(numman, bool) or not 0 <= numman <= 50):
self.module.fail_json(msg="numman must be between 0 and 50")
if params.get("hint") is not None and len(params["hint"]) > 255:
self.module.fail_json(msg="hint must be at most 255 characters")
if params.get("encryption_password") is not None and len(params["encryption_password"]) < 8:
self.module.fail_json(msg="encryption_password must be at least 8 characters")
enabled = params["enable"] if params.get("enable") is not None else self._stored("enable") == "yes"
if enabled and not self._current("encryption_password"):
self.module.fail_json(msg="encryption_password is required to enable AutoConfigBackup")
def _params_to_obj(self):
"""return a dict from module params"""
obj = super(PFSenseAutoConfigBackupModule, self)._params_to_obj()
# A false option that is not stored is already false: do not add an empty element for it
for field in ["enable", "reverse"]:
if obj.get(field) == "" and self._stored(field) is None:
del obj[field]
# As setup_ACB() does, pick a random minute when there is none
if self._current("frequency") == "cron" and not self._current("minute"):
obj["minute"] = str(random.randint(1, 59))
return obj
def run(self, params):
if any(value is not None for value in params.values()):
super(PFSenseAutoConfigBackupModule, self).run(params)
##############################
# XML processing
#
@staticmethod
def _upload_script_exists():
"""the PHP installs the upload job only when its script exists"""
return os.path.isfile(UPLOAD_SCRIPT)
def _wanted_cron_jobs(self, acb):
"""the cron jobs the PHP installs for the settings acb, as install_cron_job() stores them (None for no job)"""
def number(field):
# is_numeric() in the PHP: the options only take digits or *
value = acb.get(field) or ""
return value if NUMBER.fullmatch(value) else "*"
jobs = dict(backup_job=None)
if acb.get("frequency") == "cron":
schedule = (acb.get("minute", "0"), number("hour"), number("day"), number("month"), number("dow"))
jobs["backup_job"] = dict(zip(SCHEDULE_FIELDS, schedule), who="root", command=CRON_JOBS["backup_job"])
if self._upload_script_exists():
jobs["upload_job"] = None
if acb.get("enable") == "yes":
jobs["upload_job"] = dict(dict.fromkeys(SCHEDULE_FIELDS, "*"), who="root", command=CRON_JOBS["upload_job"])
return jobs
def _stored_cron_job(self, command):
"""the cron job of command in config.xml, found as install_cron_job() finds it"""
for item in self.pfsense.root.findall("cron/item"):
if command in (item.findtext("command") or ""):
return self.pfsense.element_to_dict(item)
return None
@staticmethod
def _same_cron_job(stored, wanted):
"""install_cron_job() keeps a job that is == to the wanted one: the same fields, with values compared as PHP does"""
if stored is None or wanted is None:
return stored is wanted
return set(stored) == set(wanted) and all(php_equal(stored[field], wanted[field]) for field in wanted)
def _copy_and_update_target(self):
"""update the settings, and count a cron job that does not match them as a change: the PHP installs, updates or removes
it, as the web GUI does on each save"""
(before, changed) = super(PFSenseAutoConfigBackupModule, self)._copy_and_update_target()
for name, wanted in self._wanted_cron_jobs(self.diff["after"]).items():
stored = self._stored_cron_job(CRON_JOBS[name])
if not self._same_cron_job(stored, wanted):
self.cron_jobs[name] = (stored, wanted)
return (before, changed or bool(self.cron_jobs))
def _run_post(self):
# The web GUI creates a random device key when the backups are enabled
self.new_key = self.diff["before"].get("enable") != "yes" and self.diff["after"].get("enable") == "yes"
# The schedule of the cron jobs that change ("minute hour day month weekday")
for name, jobs in self.cron_jobs.items():
for side, job in zip(("before", "after"), jobs):
if job is not None:
self.diff[side][name] = " ".join(job.get(field, "") for field in SCHEDULE_FIELDS)
# The diff holds the whole section: hide the stored secrets
for snapshot in self.diff.values():
for field in snapshot:
if is_secret(field) and snapshot[field]:
snapshot[field] = REDACTED
##############################
# run
#
def _update(self):
"""install the cron jobs and create the revision, as the web GUI does"""
return self.pfsense.phpshell("$new_key = {0};\n{1}".format("true" if self.new_key else "false", AUTOCONFIGBACKUP_PHP_COMMAND))
##############################
# Logging
#
@staticmethod
def _get_obj_name():
"""return obj's name"""
return "acb"
@staticmethod
def fvalue_bool(value):
"""enable and reverse are stored as 'yes' when set"""
return "True" if value == "yes" else "False"
def _log_fields(self, before=None):
"""the changed options, then what happens to each cron job that changes, as install_cron_job() logs it"""
values = super(PFSenseAutoConfigBackupModule, self)._log_fields(before)
for name in sorted(self.cron_jobs):
(stored, wanted) = self.cron_jobs[name]
action = "removed" if wanted is None else "installed" if stored is None else "updated"
values += "{0}{1}={2}".format(", " if values else "", name, action)
return values
def format_cli_field(self, after, field, *args, **kwargs):
if is_secret(field) and after.get(field):
after = dict(after)
after[field] = REDACTED
return super(PFSenseAutoConfigBackupModule, self).format_cli_field(after, field, *args, **kwargs)
def main():
module = AnsibleModule(argument_spec=AUTOCONFIGBACKUP_ARGUMENT_SPEC, supports_check_mode=True)
pfmodule = PFSenseAutoConfigBackupModule(module)
# Pass params for testing framework
pfmodule.run(module.params)
pfmodule.commit_changes()
if __name__ == "__main__":
main()