-
Notifications
You must be signed in to change notification settings - Fork 13
/
check_opnsense.py
executable file
·240 lines (197 loc) · 7.88 KB
/
check_opnsense.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
# check_opnsense.py - A check plugin for monitoring OPNsense firewalls.
# Copyright (C) 2018 Nicolai Buchwitz <nb@tipi-net.de>
#
# Version: 0.1.0
#
# ------------------------------------------------------------------------------
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# ------------------------------------------------------------------------------
"""OPNsense monitoring check command for various monitoring systems like Icinga and others."""
import sys
from typing import Dict, Union
try:
import argparse
from enum import Enum
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
except ImportError as e:
print(f"Missing python module: {e.msg}")
sys.exit(255)
# Timeout for API requests in seconds
CHECK_API_TIMEOUT = 30
class CheckState(Enum):
"""Check return values."""
OK = 0
WARNING = 1
CRITICAL = 2
UNKNOWN = 3
class CheckOPNsense:
"""Check command for OPNsense."""
VERSION = "0.1.0"
API_URL = "https://{host}:{port}/api/{uri}"
def check_output(self) -> None:
"""Print check command output with perfdata and return code."""
message = self.check_message
if self.perfdata:
message += self.get_perfdata()
self.output(self.check_result, message)
@staticmethod
def output(rc: CheckState, message: str) -> None:
"""Print message to stdout and exit with given return code."""
prefix = rc.name
print(f"{prefix} - {message}")
sys.exit(rc.value)
def get_url(self, command: str) -> str:
"""Get API url for specific command."""
return self.API_URL.format(host=self.options.hostname, port=self.options.port, uri=command)
def request(self, url: str, method: str = "get", **kwargs: Dict) -> Union[Dict, None]:
"""Execute request against OPNsense API and return json data."""
response = None
try:
if method == "post":
response = requests.post(
url,
verify=not self.options.api_insecure,
auth=(self.options.api_key, self.options.api_secret),
data=kwargs.get("data", None),
timeout=CHECK_API_TIMEOUT,
)
elif method == "get":
response = requests.get(
url,
auth=(self.options.api_key, self.options.api_secret),
verify=not self.options.api_insecure,
params=kwargs.get("params", None),
timeout=CHECK_API_TIMEOUT,
)
else:
self.output(CheckState.CRITICAL, f"Unsupport request method: {method}")
except requests.exceptions.ConnectTimeout:
self.output(CheckState.UNKNOWN, "Could not connect to OPNsense: Connection timeout")
except requests.exceptions.SSLError:
self.output(
CheckState.UNKNOWN, "Could not connect to OPNsense: Certificate validation failed"
)
except requests.exceptions.ConnectionError:
self.output(
CheckState.UNKNOWN, "Could not connect to OPNsense: Failed to resolve hostname"
)
if response.ok:
return response.json()
else:
message = "Could not fetch data from API: "
if response.status_code == 401:
message += "Could not connection to OPNsense: invalid username or password"
elif response.status_code == 403:
message += "Access denied. Please check if API user has sufficient permissions."
else:
message += f"HTTP error code was {response.status_code}"
self.output(CheckState.UNKNOWN, message)
def get_perfdata(self) -> str:
"""Get perfdata string."""
perfdata = ""
if self.perfdata:
perfdata = "|"
perfdata += " ".join(self.perfdata)
return perfdata
def check(self) -> None:
"""Execute the real check command."""
self.check_result = CheckState.OK
if self.options.mode == "updates":
self.check_updates()
else:
message = "Check mode '{}' not known".format(self.options.mode)
self.output(CheckState.UNKNOWN, message)
self.check_output()
def parse_args(self) -> None:
"""Parse CLI arguments."""
p = argparse.ArgumentParser(description="Check command OPNsense firewall monitoring")
api_opts = p.add_argument_group("API Options")
api_opts.add_argument(
"-H", "--hostname", required=True, help="OPNsense hostname or ip address"
)
api_opts.add_argument(
"-p",
"--port",
required=False,
dest="port",
help="OPNsense https-api port",
default=443,
type=int,
)
api_opts.add_argument(
"--api-key", dest="api_key", required=True, help="API key (See OPNsense user manager)"
)
api_opts.add_argument(
"--api-secret",
dest="api_secret",
required=True,
help="API key (See OPNsense user manager)",
)
api_opts.add_argument(
"-k",
"--insecure",
dest="api_insecure",
action="store_true",
default=False,
help="Don't verify HTTPS certificate",
)
check_opts = p.add_argument_group("Check Options")
check_opts.add_argument(
"-m", "--mode", choices=("updates",), required=True, help="Mode to use."
)
check_opts.add_argument(
"-w",
"--warning",
dest="treshold_warning",
type=float,
help="Warning treshold for check value",
)
check_opts.add_argument(
"-c",
"--critical",
dest="treshold_critical",
type=float,
help="Critical treshold for check value",
)
options = p.parse_args()
self.options = options
def check_updates(self) -> None:
"""Check opnsense for system updates."""
url = self.get_url("core/firmware/status")
data = self.request(url)
if data["status"] == "ok" and data["status_upgrade_action"] == "all":
count = data["updates"]
self.check_result = CheckState.WARNING
self.check_message = "{} pending updates".format(count)
if data["upgrade_needs_reboot"]:
self.check_result = CheckState.CRITICAL
self.check_message = "{}. Subsequent reboot required.".format(self.check_message)
else:
self.check_message = "System up to date"
def __init__(self) -> None:
self.options = {}
self.perfdata = []
self.check_result = CheckState.UNKNOWN
self.check_message = ""
self.parse_args()
if self.options.api_insecure:
# disable urllib3 warning about insecure requests
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
opnsense = CheckOPNsense()
opnsense.check()