Repository navigation
Expand file tree
/
Copy pathpfsense_syslogng.py
More file actions
246 lines (212 loc) · 9.06 KB
/
Copy pathpfsense_syslogng.py
File metadata and controls
246 lines (212 loc) · 9.06 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
#!/usr/bin/python
# Copyright (c) 2026, Orion Poplawski <orion@nwra.com>
# 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_syslogng
short_description: Manage pfSense syslog-ng general settings
version_added: "0.1.0"
description:
- Manage general settings for the installed pfSense syslog-ng package.
- Omitted options preserve their existing settings. A new configuration uses the package's defaults.
options:
enable:
description: Whether to enable the syslog-ng service.
type: bool
interfaces:
description:
- Nonempty list of assigned interfaces for the default listener.
- Accepts pfSense interface IDs, display names, and C(lo0) or C(loopback).
type: list
elements: str
default_protocol:
description: Transport protocol for the default listener.
choices: [udp, tcp, tls]
type: str
dca:
description:
- TLS certificate authority by pfSense reference ID or description.
- Set to an empty string to clear the selection.
type: str
certificate:
description:
- TLS server certificate with a private key, by pfSense reference ID or description.
- Required when the resulting protocol is C(tls). Set to an empty string to clear the selection when using another protocol.
type: str
default_port:
description: Port number from 1 to 65535 for the default listener.
type: int
default_logdir:
description: Absolute log directory without a trailing slash. C(/var/log) is reserved for pfSense.
type: str
default_logfile:
description: File name for the default log inside O(default_logdir).
type: str
archive_frequency:
description: How frequently to rotate log files.
choices: [daily, weekly, monthly]
type: str
compress_archives:
description: Whether to compress archived logs.
type: bool
compress_type:
description: Compression format for archived logs.
choices: [gz, bz2]
type: str
max_archives:
description: Number of rotated logs to retain. Zero keeps no rotated logs.
type: int
include_scl:
description: Whether to include the syslog-ng standard configuration library.
type: bool
author: Orion Poplawski (@opoplawski)
"""
EXAMPLES = r"""
- name: Listen for syslog messages on LAN and loopback
pfsensible.syslogng.pfsense_syslogng:
enable: true
interfaces: [LAN, lo0]
default_protocol: tcp
default_port: 5140
default_logdir: /var/syslog-ng
default_logfile: default.log
archive_frequency: daily
compress_archives: true
compress_type: gz
max_archives: 30
include_scl: true
- name: Enable TLS on the default listener
pfsensible.syslogng.pfsense_syslogng:
default_protocol: tls
default_port: 6514
dca: Internal CA
certificate: Firewall syslog
"""
RETURN = r"""
commands:
description: Pseudo-CLI commands that describe the applied or proposed changes.
returned: always
type: list
elements: str
sample: ["update syslogng set default_port='6514'"]
"""
import posixpath
import re
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.pfsensible.core.plugins.module_utils.module_config_base import PFSenseModuleConfigBase
from ansible_collections.pfsensible.syslogng.plugins.module_utils.syslogng import DEFAULT_SETTINGS, RESYNC, validate_config
SYSLOGNG_ARGUMENT_SPEC = dict(
enable=dict(type="bool"),
interfaces=dict(type="list", elements="str"),
default_protocol=dict(type="str", choices=["udp", "tcp", "tls"]),
dca=dict(type="str"),
certificate=dict(type="str"),
default_port=dict(type="int"),
default_logdir=dict(type="str"),
default_logfile=dict(type="str"),
archive_frequency=dict(type="str", choices=["daily", "weekly", "monthly"]),
compress_archives=dict(type="bool"),
compress_type=dict(type="str", choices=["gz", "bz2"]),
max_archives=dict(type="int"),
include_scl=dict(type="bool"),
)
INVALID_PATH_CHARS = re.compile(r"""[?*:;{}\\'"\x00-\x1f\x7f]""")
def parse_interfaces(self, name, params, obj):
if not params[name]:
self.module.fail_json(msg="interfaces must contain at least one interface")
interfaces = []
for item in params[name]:
if item.lower() in ("lo0", "loopback"):
interface = "lo0"
else:
interface = self.pfsense.parse_interface(item, with_virtual=False, fail=False)
if interface is None or not self.pfsense.is_interface_port(interface):
self.module.fail_json(msg=f"{item!r} is not an assigned pfSense interface")
if interface not in interfaces:
interfaces.append(interface)
obj[name] = ",".join(interfaces)
def certificate_ref(module, pfsense, field, value, by_description=False):
tag = "ca" if field == "dca" else "cert"
entries = pfsense.root.findall(tag)
matches = [entry for entry in entries if entry.findtext("refid") == value]
if not matches and by_description:
matches = [entry for entry in entries if entry.findtext("descr") == value and entry.findtext("refid")]
if len(matches) != 1:
module.fail_json(msg=f"{field} must match a unique pfSense {tag} reference: {value!r}")
entry = matches[0]
if not entry.findtext("crt") or (tag == "cert" and not entry.findtext("prv")):
module.fail_json(msg=f"{field} must reference a certificate with certificate data and, for a server certificate, a private key")
return entry.findtext("refid")
def parse_certificate(self, name, params, obj):
value = params[name]
obj[name] = certificate_ref(self.module, self.pfsense, name, value, by_description=True) if value else ""
SYSLOGNG_ARG_ROUTE = dict(
interfaces=dict(parse=parse_interfaces),
dca=dict(parse=parse_certificate),
certificate=dict(parse=parse_certificate),
)
class PFSensesyslogngModule(PFSenseModuleConfigBase):
"""Manage the package's general settings."""
@staticmethod
def get_argument_spec():
return SYSLOGNG_ARGUMENT_SPEC
def __init__(self, module, pfsense=None):
super().__init__(
module,
pfsense,
package="syslog-ng",
name="pfsense_syslogng",
root="syslogng",
create_root=True,
node="config",
arg_route=SYSLOGNG_ARG_ROUTE,
bool_values=dict.fromkeys(("enable", "compress_archives", "include_scl"), ("off", "on")),
update_php=RESYNC,
)
def _params_to_obj(self):
obj = super()._params_to_obj()
# pfsensible.core 0.7.2 does not apply create_default to single-section modules.
if self.root_elt.find(self.node) is None:
return {**DEFAULT_SETTINGS, **obj}
return obj
def _validate_params(self):
port = self.params.get("default_port")
if port is not None and not 1 <= port <= 65535:
self.module.fail_json(msg="default_port must be between 1 and 65535")
archives = self.params.get("max_archives")
if archives is not None and not 0 <= archives <= 2147483647:
self.module.fail_json(msg="max_archives must be between 0 and 2147483647")
logdir = self.params.get("default_logdir")
if logdir is not None:
if not logdir.startswith("/") or logdir.endswith("/") or INVALID_PATH_CHARS.search(logdir) or ".." in logdir.split("/"):
self.module.fail_json(msg="default_logdir must be an absolute path without a trailing slash, parent traversal or special characters")
if posixpath.normpath("/" + logdir.lstrip("/")) in ("/", "/var/log"):
self.module.fail_json(msg="default_logdir cannot be / or /var/log")
logfile = self.params.get("default_logfile")
if logfile is not None and (not logfile.strip() or logfile in (".", "..") or "/" in logfile or INVALID_PATH_CHARS.search(logfile)):
self.module.fail_json(msg="default_logfile must be a file name without a directory or special characters")
def _run_post(self):
if not self.result["changed"]:
return
if self.obj.get("default_protocol") == "tls":
cert = self.obj.get("certificate")
if not cert:
self.module.fail_json(msg="certificate is required when default_protocol is tls")
certificate_ref(self.module, self.pfsense, "certificate", cert)
if self.obj.get("dca"):
certificate_ref(self.module, self.pfsense, "dca", self.obj["dca"])
before = self.diff["before"]
listener_changed = any(before.get(field) != self.obj.get(field) for field in ("enable", "interfaces", "default_protocol", "default_port"))
validate_config(self.module, self.pfsense, check_listener=listener_changed)
@staticmethod
def fvalue_bool(value):
return str(value == "on")
def main():
module = AnsibleModule(argument_spec=SYSLOGNG_ARGUMENT_SPEC, supports_check_mode=True)
pfmodule = PFSensesyslogngModule(module)
pfmodule.run(module.params)
pfmodule.commit_changes()
if __name__ == "__main__":
main()