forked from bashclub/checkmk-opnsense-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
opnsense_checkmk_agent.py
2587 lines (2382 loc) · 115 KB
/
opnsense_checkmk_agent.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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# vim: set fileencoding=utf-8:noet
## Copyright 2024 Bashclub https://github.com/bashclub
## BSD-2-Clause
##
## Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
##
## 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
##
## 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
## THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
## BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
## GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
## LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
## OPNsense CheckMK Agent
## to install
## copy to /usr/local/etc/rc.syshook.d/start/99-checkmk_agent and chmod +x
##
## default config file /usr/local/etc/checkmk.conf
##
## for server-side implementation of
## * smartdisk - install the mkp from https://github.com/bashclub/checkmk-smart plugins os-smart
## * squid - install the mkp from https://exchange.checkmk.com/p/squid and forwarder -> listen on loopback active
## task types2
## speedtest|proxy|ssh|nmap|domain|blocklist
##
__VERSION__ = "1.2.8"
import sys
import os
import shlex
import glob
import re
import time
import json
import socket
import signal
import struct
import subprocess
import pwd
import threading
import ipaddress
import base64
import traceback
import syslog
import requests
import hashlib
from urllib3.connection import HTTPConnection
from urllib3.connectionpool import HTTPConnectionPool
from requests.adapters import HTTPAdapter
from cryptography import x509
from cryptography.hazmat.backends import default_backend as crypto_default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from datetime import datetime
from xml.etree import cElementTree as ELementTree
from collections import Counter,defaultdict
from pprint import pprint
from socketserver import TCPServer,StreamRequestHandler
import unbound
unbound.RR_TYPE_TLSA = 52
unbound.RR_TYPE_SPF = unbound.RR_TYPE_TXT
from OpenSSL import SSL,crypto
from binascii import b2a_hex
from datetime import datetime
SCRIPTPATH = os.path.abspath(__file__)
SYSHOOK_METHOD = re.findall("rc\.syshook\.d\/(start|stop)/",SCRIPTPATH)
BASEDIR = "/usr/local/check_mk_agent"
VARDIR = "/var/lib/check_mk_agent"
CHECKMK_CONFIG = "/usr/local/etc/checkmk.conf"
MK_CONFDIR = os.path.dirname(CHECKMK_CONFIG)
LOCALDIR = os.path.join(BASEDIR,"local")
PLUGINSDIR = os.path.join(BASEDIR,"plugins")
SPOOLDIR = os.path.join(VARDIR,"spool")
TASKDIR = os.path.join(BASEDIR,"tasks")
TASKFILE_KEYS = "service|type|interval|interface|disabled|ipaddress|hostname|domain|port|piggyback|sshoptions|options|tenant"
TASKFILE_REGEX = re.compile(f"^({TASKFILE_KEYS}):\s*(.*?)(?:\s+#|$)",re.M)
MAX_SIMULATAN_THREADS = 4
for _dir in (BASEDIR, VARDIR, LOCALDIR, PLUGINSDIR, SPOOLDIR, TASKDIR):
if not os.path.exists(_dir):
try:
os.mkdir(_dir)
except:
pass
os.environ["MK_CONFDIR"] = MK_CONFDIR
os.environ["MK_LIBDIR"] = BASEDIR
os.environ["MK_VARDIR"] = BASEDIR
class object_dict(defaultdict):
def __getattr__(self,name):
return self[name] if name in self else ""
def etree_to_dict(t):
d = {t.tag: {} if t.attrib else None}
children = list(t)
if children:
dd = object_dict(list)
for dc in map(etree_to_dict, children):
for k, v in dc.items():
dd[k].append(v)
d = {t.tag: {k:v[0] if len(v) == 1 else v for k, v in dd.items()}}
if t.attrib:
d[t.tag].update(('@' + k, v) for k, v in t.attrib.items())
if t.text:
text = t.text.strip()
if children or t.attrib:
if text:
d[t.tag]['#text'] = text
else:
d[t.tag] = text
return d
def log(message,prio="notice"):
priority = {
"crit" :syslog.LOG_CRIT,
"err" :syslog.LOG_ERR,
"warning" :syslog.LOG_WARNING,
"notice" :syslog.LOG_NOTICE,
"info" :syslog.LOG_INFO,
}.get(str(prio).lower(),syslog.LOG_DEBUG)
syslog.openlog(ident="checkmk_agent",logoption=syslog.LOG_PID | syslog.LOG_NDELAY,facility=syslog.LOG_DAEMON)
syslog.syslog(priority,message)
def pad_pkcs7(message,size=16):
_pad = size - (len(message) % size)
if type(message) == str:
return message + chr(_pad) * _pad
else:
return message + bytes([_pad]) * _pad
class NginxConnection(HTTPConnection):
def __init__(self):
super().__init__("localhost")
def connect(self):
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.connect("/var/run/nginx_status.sock")
class NginxConnectionPool(HTTPConnectionPool):
def __init__(self):
super().__init__("localhost")
def _new_conn(self):
return NginxConnection()
class NginxAdapter(HTTPAdapter):
## deprecated
def get_connection(self, url, proxies=None):
return NginxConnectionPool()
def get_connection_with_tls_context(self, request, verify, proxies=None, cert=None):
return NginxConnectionPool()
def check_pid(pid):
try:
os.kill(pid,0)
return True
except OSError: ## no permission check currently root
return False
class checkmk_handler(StreamRequestHandler):
def handle(self):
with self.server._mutex:
try:
_strmsg = self.server.do_checks(remote_ip=self.client_address[0])
except Exception as e:
raise
_strmsg = str(e).encode("utf-8")
try:
self.wfile.write(_strmsg)
except:
pass
class checkmk_checker(object):
_available_sysctl_list = []
_available_sysctl_temperature_list = []
_ipaccess_log = {}
_certificate_timestamp = 0
_check_cache = {}
_datastore_mutex = threading.RLock()
_datastore = object_dict()
def encrypt_msg(self,message,password='secretpassword'):
SALT_LENGTH = 8
KEY_LENGTH = 32
IV_LENGTH = 16
PBKDF2_CYCLES = 10_000
#SALT = b"Salted__"
SALT = os.urandom(SALT_LENGTH)
_backend = crypto_default_backend()
_kdf_key = PBKDF2HMAC(
algorithm = hashes.SHA256(),
length = KEY_LENGTH + IV_LENGTH,
salt = SALT,
iterations = PBKDF2_CYCLES,
backend = _backend
).derive(password.encode("utf-8"))
_key, _iv = _kdf_key[:KEY_LENGTH],_kdf_key[KEY_LENGTH:]
_encryptor = Cipher(
algorithms.AES(_key),
modes.CBC(_iv),
backend = _backend
).encryptor()
message = message.encode("utf-8")
message = pad_pkcs7(message)
_encrypted_message = _encryptor.update(message) + _encryptor.finalize()
return pad_pkcs7(b"03",10) + SALT + _encrypted_message
def decrypt_msg(self,message,password='secretpassword'):
SALT_LENGTH = 8
KEY_LENGTH = 32
IV_LENGTH = 16
PBKDF2_CYCLES = 10_000
message = message[10:] # strip header
SALT = message[:SALT_LENGTH]
message = message[SALT_LENGTH:]
_backend = crypto_default_backend()
_kdf_key = PBKDF2HMAC(
algorithm = hashes.SHA256(),
length = KEY_LENGTH + IV_LENGTH,
salt = SALT,
iterations = PBKDF2_CYCLES,
backend = _backend
).derive(password.encode("utf-8"))
_key, _iv = _kdf_key[:KEY_LENGTH],_kdf_key[KEY_LENGTH:]
_decryptor = Cipher(
algorithms.AES(_key),
modes.CBC(_iv),
backend = _backend
).decryptor()
_decrypted_message = _decryptor.update(message)
try:
return _decrypted_message.decode("utf-8").strip()
except UnicodeDecodeError:
return ("invalid key")
def _expired_lastaccesed(self,remote_ip):
_now = time.time()
_lastaccess = self._ipaccess_log.get(remote_ip,0)
_ret = True
if _lastaccess + self.expire_inventory > _now:
_ret = False
for _ip, _time in self._ipaccess_log.items():
if _time + self.expire_inventory < _now:
del self._ipaccess_log[_ip]
self._ipaccess_log[remote_ip] = _now
return _ret
def do_checks(self,debug=False,remote_ip=None,**kwargs):
self._getosinfo()
_errors = []
_failed_sections = []
_lines = ["<<<check_mk>>>"]
_lines.append("AgentOS: {os}".format(**self._info))
_lines.append(f"Version: {__VERSION__}")
_lines.append("Hostname: {hostname}".format(**self._info))
## only tenant data
if remote_ip in self.tenants.keys():
_secret = self.tenants.get(remote_ip,None)
_lines += self.taskrunner.get_data(tenant=remote_ip)[1:] ## remove number of tasks
_lines.append("")
if _secret:
return self.encrypt_msg("\n".join(_lines),password=_secret)
return "\n".join(_lines).encode("utf-8")
if self.onlyfrom:
_lines.append("OnlyFrom: {0}".format(",".join(self.onlyfrom)))
_lines.append(f"LocalDirectory: {LOCALDIR}")
_lines.append(f"PluginsDirectory: {PLUGINSDIR}")
_lines.append(f"AgentDirectory: {MK_CONFDIR}")
_lines.append(f"SpoolDirectory: {SPOOLDIR}")
for _check in dir(self):
if _check.startswith("check_"):
_name = _check.split("_",1)[1]
if _name in self.skipcheck:
continue
try:
_lines += getattr(self,_check)()
except:
_failed_sections.append(_name)
_errors.append(traceback.format_exc())
if os.path.isdir(PLUGINSDIR):
for _plugin_file in glob.glob(f"{PLUGINSDIR}/**",recursive=True):
if os.path.isfile(_plugin_file) and os.access(_plugin_file,os.X_OK):
try:
_cachetime = int(_plugin_file.split(os.path.sep)[-2])
except:
_cachetime = 0
try:
if _cachetime > 0:
_lines.append(self._run_cache_prog(_plugin_file,_cachetime))
else:
_lines.append(self._run_prog(_plugin_file))
except:
_errors.append(traceback.format_exc())
if self._expired_lastaccesed(remote_ip):
try:
_lines += self.do_inventory()
except:
_errors.append(traceback.format_exc())
_lines.append("<<<local:sep(0)>>>")
for _check in dir(self):
if _check.startswith("checklocal_"):
_name = _check.split("_",1)[1]
if _name in self.skipcheck:
continue
try:
_lines += getattr(self,_check)()
except:
_failed_sections.append(_name)
_errors.append(traceback.format_exc())
if os.path.isdir(LOCALDIR):
for _local_file in glob.glob(f"{LOCALDIR}/**",recursive=True):
if os.path.isfile(_local_file) and os.access(_local_file,os.X_OK):
try:
_cachetime = int(_local_file.split(os.path.sep)[-2])
except:
_cachetime = 0
try:
if _cachetime > 0:
_lines.append(self._run_cache_prog(_local_file,_cachetime))
else:
_lines.append(self._run_prog(_local_file))
except:
_errors.append(traceback.format_exc())
if os.path.isdir(SPOOLDIR):
_now = time.time()
for _filename in glob.glob(f"{SPOOLDIR}/*"):
_maxage = re.search("^(\d+)_",_filename)
if _maxage:
_maxage = int(_maxage.group(1))
_mtime = os.stat(_filename).st_mtime
if _now - _mtime > _maxage:
continue
with open(_filename) as _f:
_lines.append(_f.read())
_lines += self.taskrunner.get_data()
_lines.append("")
if debug:
sys.stdout.write("\n".join(_errors))
sys.stdout.flush()
if _failed_sections:
_lines.append("<<<check_mk>>>")
_lines.append("FailedPythonPlugins: {0}".format(",".join(_failed_sections)))
if self.encrypt and not debug:
return self.encrypt_msg("\n".join(_lines),password=self.encrypt)
return "\n".join(_lines).encode("utf-8")
def do_zabbix_output(self):
self._getosinfo()
_regex_convert = re.compile("^(?P<status>[0-3P])\s(?P<servicename>\".*?\"|\w+)\s(?P<metrics>[\w=.;|]+| -)\s(?P<details>.*)")
_json = []
for _check in dir(self):
if _check.startswith("checklocal_"):
_name = _check.split("_",1)[1]
if _name in self.skipcheck:
continue
try:
for _line in getattr(self,_check)():
try:
_entry = _regex_convert.search(_line).groupdict()
_entry["servicename"] = _entry["servicename"].strip('"')
_json.append(_entry)
except:
raise
except:
raise
return json.dumps(_json)
def _get_storedata(self,section,key):
with self._datastore_mutex:
return self._datastore.get(section,{}).get(key)
def _set_storedata(self,section,key,value):
with self._datastore_mutex:
if section not in self._datastore:
self._datastore[section] = object_dict()
self._datastore[section][key] = value
def _getosinfo(self):
_info = json.load(open("/usr/local/opnsense/version/core","r"))
_changelog = json.load(open("/usr/local/opnsense/changelog/index.json","r"))
_config_modified = os.stat("/conf/config.xml").st_mtime
try:
_default_version = {'series': _info.get("product_series"), 'version': _info.get("product_version"), 'date': time.strftime('%B %d, %Y')}
_latest_series = dict(map(lambda x: (x.get("series"),x),_changelog))
_latest_versions = dict(map(lambda x: (x.get("version"),x),_changelog))
_latest_firmware = _latest_series.get(_info.get("product_series"),_default_version)
_current_firmware = _latest_versions.get(_info.get("product_version").split("_")[0],_default_version).copy()
_current_firmware["age"] = int(time.time() - time.mktime(time.strptime(_current_firmware.get("date"),"%B %d, %Y")))
_current_firmware["version"] = _info.get("product_version")
except:
#raise
_latest_firmware = {}
_current_firmware = {}
_mayor_upgrade = None
try:
_upgrade_json = json.load(open("/tmp/pkg_upgrade.json","r"))
_upgrade_packages = dict(map(lambda x: (x.get("name"),x),_upgrade_json.get("upgrade_packages")))
_mayor_upgrade = _upgrade_json.get("upgrade_major_version")
_current_firmware["version"] = _upgrade_packages.get("opnsense").get("current_version")
_latest_firmware["version"] = _upgrade_packages.get("opnsense").get("new_version")
except:
_current_firmware["version"] = _current_firmware["version"].split("_")[0]
_latest_firmware["version"] = _current_firmware["version"] ## fixme ## no upgradepckg error on opnsense ... no new version
self._info = {
"os" : _info.get("product_name"),
"os_version" : _current_firmware.get("version","unknown"),
"version_age" : _current_firmware.get("age",0),
"config_age" : int(time.time() - _config_modified) ,
"last_configchange" : time.strftime("%H:%M %d.%m.%Y",time.localtime(_config_modified)),
"product_series" : _info.get("product_series"),
"latest_version" : (_mayor_upgrade if _mayor_upgrade else _latest_firmware.get("version","unknown")),
"latest_date" : _latest_firmware.get("date",""),
"hostname" : self._run_prog("hostname").strip(" \n")
}
if os.path.exists("/usr/local/opnsense/version/core.license"):
self._info["business_expire"] = datetime.strptime(json.load(open("/usr/local/opnsense/version/core.license","r")).get("valid_to","2000-01-01"),"%Y-%m-%d")
@staticmethod
def ip2int(ipaddr):
return struct.unpack("!I",socket.inet_aton(ipaddr))[0]
@staticmethod
def int2ip(intaddr):
return socket.inet_ntoa(struct.pack("!I",intaddr))
def pidof(self,prog,default=None):
_allprogs = re.findall("(\w+)\s+(\d+)",self._run_prog("ps ax -c -o command,pid"))
return int(dict(_allprogs).get(prog,default))
def _config_reader(self,config=""):
_config = ELementTree.parse("/conf/config.xml")
_root = _config.getroot()
return etree_to_dict(_root).get("opnsense",{})
@staticmethod
def get_common_name(certrdn):
try:
return next(filter(lambda x: x.oid == x509.oid.NameOID.COMMON_NAME,certrdn)).value.strip()
except:
return str(certrdn)
def _certificate_parser(self):
self._certificate_timestamp = time.time()
self._certificate_store = {}
for _cert in self._config_reader().get("cert"):
try:
_certpem = base64.b64decode(_cert.get("crt"))
_x509cert = x509.load_pem_x509_certificate(_certpem,crypto_default_backend())
_cert["not_valid_before"] = _x509cert.not_valid_before_utc.timestamp()
_cert["not_valid_after"] = _x509cert.not_valid_after_utc.timestamp()
_cert["serial"] = _x509cert.serial_number
_cert["common_name"] = self.get_common_name(_x509cert.subject)
_cert["issuer"] = self.get_common_name(_x509cert.issuer)
except:
pass
self._certificate_store[_cert.get("refid")] = _cert
def _get_certificate(self,refid):
if time.time() - self._certificate_timestamp > 3600:
self._certificate_parser()
return self._certificate_store.get(refid)
def _get_certificate_by_cn(self,cn,caref=None):
if time.time() - self._certificate_timestamp > 3600:
self._certificate_parser()
if caref:
_ret = filter(lambda x: x.get("common_name") == cn and x.get("caref") == caref,self._certificate_store.values())
else:
_ret = filter(lambda x: x.get("common_name") == cn,self._certificate_store.values())
try:
return next(_ret)
except StopIteration:
return {}
def get_opnsense_ipaddr(self):
try:
_ret = {}
for _if,_ip,_mask in re.findall("^([\w_]+):\sflags=(?:8943|8051|8043|8863).*?inet\s([\d.]+)\snetmask\s0x([a-f0-9]+)",self._run_prog("ifconfig"),re.DOTALL | re.M):
_ret[_if] = "{0}/{1}".format(_ip,str(bin(int(_mask,16))).count("1"))
return _ret
except:
return {}
def get_opnsense_interfaces(self):
_ifs = {}
for _name,_interface in self._config_reader().get("interfaces",{}).items():
if _interface.get("enable") != "1":
continue
_desc = _interface.get("descr")
_ifs[_interface.get("if","_")] = _desc if _desc else _name.upper()
try:
_wgserver = self._config_reader().get("OPNsense").get("wireguard").get("server").get("servers").get("server")
if type(_wgserver) == dict:
_wgserver = [_wgserver]
_ifs.update(
dict(
map(
lambda x: ("wg{}".format(x.get("instance")),"Wireguard_{}".format(x.get("name").strip().replace(" ","_"))),
_wgserver
)
)
)
except:
pass
return _ifs
def checklocal_firmware(self):
if self._info.get("os_version") != self._info.get("latest_version"):
return ["1 Firmware update_available=1|last_updated={version_age:.0f}|apply_finish_time={config_age:.0f} Version {os_version} ({latest_version} available {latest_date}) Config changed: {last_configchange}".format(**self._info)]
return ["0 Firmware update_available=0|last_updated={version_age:.0f}|apply_finish_time={config_age:.0f} Version {os_version} Config changed: {last_configchange}".format(**self._info)]
def checklocal_business(self):
if self._info.get("business_expire"):
_days = (self._info.get("business_expire") - datetime.now()).days
_date = self._info.get("business_expire").strftime("%d.%m.%Y")
return [f'P "Business Licence" expiredays={_days};;;30;60; Licence Expire: {_date}']
return []
def check_label(self):
_ret = ["<<<labels:sep(0)>>>"]
_dmsg = self._run_prog("dmesg",timeout=10)
if _dmsg.lower().find("hypervisor:") > -1:
_ret.append('{"cmk/device_type":"vm"}')
return _ret
def check_net(self):
_now = int(time.time())
_opnsense_ifs = self.get_opnsense_interfaces()
_ret = ["<<<statgrab_net>>>"]
_interface_data = []
_interface_data = self._run_prog("/usr/bin/netstat -i -b -d -n -W -f link").split("\n")
_header = _interface_data[0].lower()
_header = _header.replace("pkts","packets").replace("coll","collisions").replace("errs","error").replace("ibytes","rx").replace("obytes","tx")
_header = _header.split()
_interface_stats = dict(
map(
lambda x: (x.get("name"),x),
[
dict(zip(_header,_ifdata.split()))
for _ifdata in _interface_data[1:] if _ifdata
]
)
)
_ifconfig_out = self._run_prog("ifconfig -m -v -f inet:cidr,inet6:cidr")
_ifconfig_out += "END" ## fix regex
self._all_interfaces = object_dict()
self._carp_interfaces = object_dict()
for _interface, _data in re.findall("^(?P<iface>[\w.]+):\s(?P<data>.*?(?=^\w))",_ifconfig_out,re.DOTALL | re.MULTILINE):
_interface_dict = object_dict()
_interface_dict.update(_interface_stats.get(_interface,{}))
_interface_dict["interface_name"] = _opnsense_ifs.get(_interface,_interface)
_interface_dict["up"] = "false"
#if _interface.startswith("vmx"): ## vmware fix 10GBe (as OS Support)
# _interface_dict["speed"] = "10000"
_interface_dict["systime"] = _now
for _key, _val in re.findall("^\s*(\w+)[:\s=]+(.*?)$",_data,re.MULTILINE):
if _key == "description":
_interface_dict["interface_name"] = re.sub("_\((lan|wan|opt\d+)\)$","",_val.strip().replace(" ","_"))
if _key == "groups":
_interface_dict["groups"] = _val.strip().split()
if _key == "ether":
_interface_dict["phys_address"] = _val.strip()
if _key == "status" and _val.strip() == "active":
_interface_dict["up"] = "true"
if _interface.startswith("wg") and _interface_dict.get("flags",0) & 0x01:
_interface_dict["up"] = "true"
if _key == "flags":
_interface_dict["flags"] = int(re.findall("^[a-f\d]+",_val)[0],16)
## hack pppoe no status active or pppd pid
if _interface.lower().startswith("pppoe") and _interface_dict["flags"] & 0x10 and _interface_dict["flags"] & 0x1:
_interface_dict["up"] = "true"
## http://web.mit.edu/freebsd/head/sys/net/if.h
## 0x1 UP
## 0x2 BROADCAST
## 0x8 LOOPBACK
## 0x10 POINTTOPOINT
## 0x40 RUNNING
## 0x100 PROMISC
## 0x800 SIMPLEX
## 0x8000 MULTICAST
if _key == "media":
_match = re.search("\((?P<speed>\d+G?)[Bb]ase(?:.*?<(?P<duplex>.*?)>)?",_val)
if _match:
_interface_dict["speed"] = _match.group("speed").replace("G","000")
_interface_dict["duplex"] = _match.group("duplex")
if _key == "inet":
_match = re.search("^(?P<ipaddr>[\d.]+)\/(?P<cidr>\d+).*?(?:vhid\s(?P<vhid>\d+)|$)",_val,re.M)
if _match:
_cidr = _match.group("cidr")
_ipaddr = _match.group("ipaddr")
_vhid = _match.group("vhid")
if not _vhid:
_interface_dict["cidr"] = _cidr ## cidr wenn kein vhid
## fixme ipaddr dict / vhid dict
if _key == "inet6":
_match = re.search("^(?P<ipaddr>[0-9a-f:]+)\/(?P<prefix>\d+).*?(?:vhid\s(?P<vhid>\d+)|$)",_val,re.M)
if _match:
_ipaddr = _match.group("ipaddr")
_prefix = _match.group("prefix")
_vhid = _match.group("vhid")
if not _vhid:
_interface_dict["prefix"] = _prefix
## fixme ipaddr dict / vhid dict
if _key == "carp":
_match = re.search("(?P<status>MASTER|BACKUP)\svhid\s(?P<vhid>\d+)\sadvbase\s(?P<base>\d+)\sadvskew\s(?P<skew>\d+)",_val,re.M)
if _match:
_carpstatus = _match.group("status")
_vhid = _match.group("vhid")
self._carp_interfaces[_vhid] = (_interface,_carpstatus)
_advbase = _match.group("base")
_advskew = _match.group("skew")
## fixme vhid dict
if _key == "id":
_match = re.search("priority\s(\d+)",_val)
if _match:
_interface_dict["bridge_prio"] = _match.group(1)
if _key == "member":
_member = _interface_dict.get("member",[])
_member.append(_val.split()[0])
_interface_dict["member"] = _member
if _key == "Opened":
try:
_pid = int(_val.split(" ")[-1])
if check_pid(_pid):
_interface_dict["up"] = "true"
except ValueError:
pass
_flags = _interface_dict.get("flags")
if _flags and (_flags & 0x2 or _flags & 0x10 or _flags & 0x80): ## nur broadcast oder ptp .. und noarp
self._all_interfaces[_interface] = _interface_dict
else:
continue
#if re.search("^[*]?(pflog|pfsync|lo)\d?",_interface):
# continue
if not _opnsense_ifs.get(_interface):
continue
for _key,_val in _interface_dict.items():
if _key in ("mtu","ipackets","ierror","idrop","rx","opackets","oerror","tx","collisions","drop","interface_name","up","systime","phys_address","speed","duplex"):
if type(_val) in (str,int,float):
_sanitized_interface = _interface.replace(".","_")
_ret.append(f"{_sanitized_interface}.{_key} {_val}")
return _ret
def checklocal_services(self):
_phpcode = '<?php require_once("config.inc");require_once("system.inc"); require_once("plugins.inc"); require_once("util.inc"); foreach(plugins_services() as $_service) { printf("%s;%s;%s\n",$_service["name"],$_service["description"],service_status($_service));} ?>'
_proc = subprocess.Popen(["php"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,encoding="utf-8")
_data,_ = _proc.communicate(input=_phpcode,timeout=15)
_services = []
for _service in _data.strip().split("\n"):
_services.append(_service.split(";"))
_num_services = len(_services)
_stopped_services = list(filter(lambda x: x[2] != '1',_services))
_num_stopped = len(_stopped_services)
_num_running = _num_services - _num_stopped
_stopped_services = ", ".join(map(lambda x: x[1],_stopped_services))
if _num_stopped > 0:
return [f"2 Services running_services={_num_running:.0f}|stopped_service={_num_stopped:.0f} Services: {_stopped_services} not running"]
return [f"0 Services running_services={_num_running:.0f}|stopped_service={_num_stopped:.0f} All Services running"]
def checklocal_carpstatus(self):
#sysctl net.inet.carp.demotion #TODO
_ret = []
_virtual = self._config_reader().get("virtualip")
if not _virtual:
return []
_virtual = _virtual.get("vip")
if not _virtual:
return []
if type(_virtual) != list:
_virtual = [_virtual]
for _vip in _virtual:
if _vip.get("mode") != "carp":
continue
_vhid = _vip.get("vhid")
_ipaddr = _vip.get("subnet")
_interface, _carpstatus = self._carp_interfaces.get(_vhid,(None,None))
_carpstatus_num = 1 if _carpstatus == "MASTER" else 0
_interface_name = self._all_interfaces.get(_interface,{}).get("interface_name",_interface)
if int(_vip.get("advskew")) < 50:
_status = 0 if _carpstatus == "MASTER" else 1
else:
_status = 0 if _carpstatus == "BACKUP" else 1
if not _interface:
continue
_ret.append(f"{_status} \"CARP: {_interface_name}@{_vhid}\" master={_carpstatus_num} {_carpstatus} {_ipaddr} ({_interface})")
return _ret
def check_dhcp(self):
if not os.path.exists("/var/dhcpd/var/db/dhcpd.leases"):
return []
_ret = ["<<<isc_dhcpd>>>"]
_ret.append("[general]\nPID: {0}".format(self.pidof("dhcpd",-1)))
_dhcpleases = open("/var/dhcpd/var/db/dhcpd.leases","r").read()
## FIXME
#_dhcpleases_dict = dict(map(lambda x: (self.ip2int(x[0]),x[1]),re.findall(r"lease\s(?P<ipaddr>[0-9.]+)\s\{.*?.\n\s+binding state\s(?P<state>\w+).*?\}",_dhcpleases,re.DOTALL)))
_dhcpleases_dict = dict(re.findall(r"lease\s(?P<ipaddr>[0-9.]+)\s\{.*?.\n\s+binding state\s(?P<state>active).*?\}",_dhcpleases,re.DOTALL))
_dhcpconf = open("/var/dhcpd/etc/dhcpd.conf","r").read()
_ret.append("[pools]")
for _subnet in re.finditer(r"subnet\s(?P<subnet>[0-9.]+)\snetmask\s(?P<netmask>[0-9.]+)\s\{.*?(?:pool\s\{.*?\}.*?)*}",_dhcpconf,re.DOTALL):
#_cidr = bin(self.ip2int(_subnet.group(2))).count("1")
#_available = 0
for _pool in re.finditer("pool\s\{.*?range\s(?P<start>[0-9.]+)\s(?P<end>[0-9.]+).*?\}",_subnet.group(0),re.DOTALL):
#_start,_end = self.ip2int(_pool.group(1)), self.ip2int(_pool.group(2))
#_ips_in_pool = filter(lambda x: _start < x[0] < _end,_dhcpleases_dict.items())
#pprint(_dhcpleases_dict)
#pprint(sorted(list(map(lambda x: (self._int2ip(x[0]),x[1]),_ips_in_pool))))
#_available += (_end - _start)
_ret.append("{0}\t{1}".format(_pool.group(1),_pool.group(2)))
#_ret.append("DHCP_{0}/{1} {2}".format(_subnet.group(1),_cidr,_available))
_ret.append("[leases]")
for _ip in sorted(_dhcpleases_dict.keys()):
_ret.append(_ip)
return _ret
def check_squid(self):
_squid_config = self._config_reader().get("OPNsense",{}).get("proxy",{})
if _squid_config.get("general",{}).get("enabled") != "1":
return []
_ret = ["<<<squid>>>"]
_port = _squid_config.get("forward",{}).get("port","3128")
try:
_response = requests.get(f"http://127.0.0.1:{_port}/squid-internal-mgr/5min",timeout=0.2)
if _response.status_code == 200:
_ret += _response.text.split("\n")
except:
pass
return _ret
def checklocal_pkgaudit(self):
try:
_data = json.loads(self._run_cache_prog("pkg audit -F --raw=json-compact -q",cachetime=360,ignore_error=True))
_vulns = _data.get("pkg_count",0)
if _vulns > 0:
_packages = ", ".join(_data.get("packages",{}).keys())
return [f"1 Audit issues={_vulns} Pkg: {_packages} vulnerable"]
raise
except:
pass
return ["0 Audit issues=0 OK"]
@staticmethod
def _read_from_openvpnsocket(vpnsocket,cmd):
_sock = socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)
try:
_sock.connect(vpnsocket)
assert (_sock.recv(4096).decode("utf-8")).startswith(">INFO")
cmd = cmd.strip() + "\n"
_sock.send(cmd.encode("utf-8"))
_data = ""
while True:
_socket_data = _sock.recv(4096).decode("utf-8")
_data += _socket_data
if _data.strip().endswith("END") or _data.strip().startswith("SUCCESS:") or _data.strip().startswith("ERROR:"):
break
return _data
finally:
if _sock:
_sock.send("quit\n".encode("utf-8"))
_sock.close()
_sock = None
return ""
def _get_traffic(self,modul,interface,totalbytesin,totalbytesout):
_hist_data = self._get_storedata(modul,interface)
_slot = int(time.time())
_slot -= _slot%60
_hist_slot = 0
_traffic_in = _traffic_out = 0
if _hist_data:
_hist_slot,_hist_bytesin, _hist_bytesout = _hist_data
_traffic_in = int(totalbytesin -_hist_bytesin) / max(1,_slot - _hist_slot)
_traffic_out = int(totalbytesout - _hist_bytesout) / max(1,_slot - _hist_slot)
if _hist_slot != _slot:
self._set_storedata(modul,interface,(_slot,totalbytesin,totalbytesout))
return max(0,_traffic_in),max(0,_traffic_out)
@staticmethod
def _get_dpinger_gateway(gateway):
_path = "/var/run/dpinger_{0}.sock".format(gateway)
if os.path.exists(_path):
_sock = socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)
try:
_sock.connect(_path)
_data = _sock.recv(1024).decode("utf-8").strip()
_name, _rtt, _rttsd, _loss = re.findall("(\S+)\s(\d+)\s(\d+)\s(\d+)$",_data)[0]
assert _name.strip() == gateway
return int(_rtt)/1_000_000.0,int(_rttsd)/1_000_000.0, int(_loss)
except:
raise
return -1,-1,-1
def checklocal_gateway(self):
_ret = []
_gateways = self._config_reader().get("OPNsense",{}).get("Gateways")
if not _gateways:
_gateways = self._config_reader().get("gateways")
if not _gateways:
return []
_gateway_items = _gateways.get("gateway_item",[])
if type(_gateway_items) != list:
_gateway_items = [_gateway_items] if _gateway_items else []
_interfaces = self._config_reader().get("interfaces",{})
_ipaddresses = self.get_opnsense_ipaddr()
for _gateway in _gateway_items:
if type(_gateway.get("descr")) != str:
_gateway["descr"] = _gateway.get("name")
if _gateway.get("monitor_disable") == "1" or _gateway.get("disabled") == "1":
continue
_interface = _interfaces.get(_gateway.get("interface"),{})
_gateway["realinterface"] = _interface.get("if")
if _gateway.get("ipprotocol") == "inet":
_gateway["ipaddr"] = _ipaddresses.get(_interface.get("if"))
else:
_gateway["ipaddr"] = ""
_gateway["rtt"], _gateway["rttsd"], _gateway["loss"] = self._get_dpinger_gateway(_gateway.get("name"))
_gateway["status"] = 0
if _gateway.get("loss") > 0 or _gateway.get("rtt") > 100:
_gateway["status"] = 1
if _gateway.get("loss") > 90 or _gateway.get("loss") == -1:
_gateway["status"] = 2
_ret.append("{status} \"Gateway {descr}\" rtt={rtt}|rttsd={rttsd}|loss={loss} Gateway on Interface: {realinterface} {gateway}".format(**_gateway))
return _ret
def checklocal_openvpn(self):
_ret = []
_cfr = self._config_reader().get("openvpn")
_cfn = self._config_reader().get("OPNsense").get("OpenVPN") ##TODO new Connections
if type(_cfr) != dict:
return _ret
if "openvpn-csc" in _cfr.keys():
_cso = _cfr.get("openvpn-csc") ## pre v23.7
else:
_cso = _cfn.get("Overwrites")
if type(_cso) == dict:
_cso = _cso.get("Overwrite")
_monitored_clients = {}
if type(_cso) == dict:
_cso = [_cso]
if type(_cso) == list:
_monitored_clients = dict(map(lambda x: (x.get("common_name").upper(),dict(x,current=[])),_cso))
_now = time.time()
_vpnclient = _cfr.get("openvpn-client",[])
_vpnserver = _cfr.get("openvpn-server",[])
if type(_vpnserver) != list:
_vpnserver = [_vpnserver] if _vpnserver else []
if type(_vpnclient) != list:
_vpnclient = [_vpnclient] if _vpnclient else []
for _server in _vpnserver + _vpnclient:
if _server.get("disable") == '1':
continue ## FIXME OK/WARN/SKIP
## server_tls, p2p_shared_key p2p_tls
_server["name"] = _server.get("description").strip() if _server.get("description") else "OpenVPN_{protocoll}_{local_port}".format(**_server)
_caref = _server.get("caref")
_server_cert = self._get_certificate(_server.get("certref"))
_server["status"] = 3
_server["expiredays"] = 0
_server["expiredate"] = "no certificate found"
if _server_cert:
_notvalidafter = _server_cert.get("not_valid_after",0)
_server["expiredays"] = int((_notvalidafter - _now) / 86400)
_server["expiredate"] = time.strftime("Cert Expire: %d.%m.%Y",time.localtime(_notvalidafter))
if _server["expiredays"] < 61:
_server["status"] = 2 if _server["expiredays"] < 31 else 1
else:
_server["expiredate"] = "\\n" + _server["expiredate"]
_server["type"] = "server" if _server.get("local_port") else "client"
if _server.get("mode") in ("p2p_shared_key","p2p_tls"):
_unix = "/var/etc/openvpn/{type}{vpnid}.sock".format(**_server)
try:
_server["bytesin"], _server["bytesout"] = self._get_traffic("openvpn",
"SRV_{name}".format(**_server),
*(map(lambda x: int(x),re.findall("bytes\w+=(\d+)",self._read_from_openvpnsocket(_unix,"load-stats"))))
)
_laststate = self._read_from_openvpnsocket(_unix,"state 1").strip().split("\r\n")[-2]
_timestamp, _server["connstate"], _data = _laststate.split(",",2)
if _server["connstate"] == "CONNECTED":
_data = _data.split(",")
_server["vpn_ipaddr"] = _data[1]
_server["remote_ipaddr"] = _data[2]
_server["remote_port"] = _data[3]
_server["source_addr"] = _data[4]
_server["status"] = 0 if _server["status"] == 3 else _server["status"]
_ret.append('{status} "OpenVPN Connection: {name}" connections_ssl_vpn=1;;|if_in_octets={bytesin}|if_out_octets={bytesout}|expiredays={expiredays} Connected {remote_ipaddr}:{remote_port} {vpn_ipaddr} {expiredate}\Source IP: {source_addr}'.format(**_server))
else:
if _server["type"] == "client":
_server["status"] = 2
_ret.append('{status} "OpenVPN Connection: {name}" connections_ssl_vpn=0;;|if_in_octets={bytesin}|if_out_octets={bytesout}|expiredays={expiredays} {connstate} {expiredate}'.format(**_server))
else:
_server["status"] = 1 if _server["status"] != 2 else 2
_ret.append('{status} "OpenVPN Connection: {name}" connections_ssl_vpn=0;;|if_in_octets={bytesin}|if_out_octets={bytesout}|expiredays={expiredays} waiting on Port {local_port}/{protocol} {expiredate}'.format(**_server))
except:
_ret.append('2 "OpenVPN Connection: {name}" connections_ssl_vpn=0;;|expiredays={expiredays}|if_in_octets=0|if_out_octets=0 Server down Port:/{protocol} {expiredate}'.format(**_server))
continue
else:
if not _server.get("maxclients"):
_max_clients = ipaddress.IPv4Network(_server.get("tunnel_network")).num_addresses -2
if _server.get("topology_subnet") != "yes":
_max_clients = max(1,int(_max_clients/4)) ## p2p
_server["maxclients"] = _max_clients
try:
_unix = "/var/etc/openvpn/{type}{vpnid}.sock".format(**_server)
try:
_server["bytesin"], _server["bytesout"] = self._get_traffic("openvpn",
"SRV_{name}".format(**_server),
*(map(lambda x: int(x),re.findall("bytes\w+=(\d+)",self._read_from_openvpnsocket(_unix,"load-stats"))))
)
_server["status"] = 0 if _server["status"] == 3 else _server["status"]
except:
_server["bytesin"], _server["bytesout"] = 0,0
raise
_number_of_clients = 0
_now = int(time.time())
_response = self._read_from_openvpnsocket(_unix,"status 2")
for _client_match in re.finditer("^CLIENT_LIST,(.*?)$",_response,re.M):
_number_of_clients += 1
_client_raw = list(map(lambda x: x.strip(),_client_match.group(1).split(",")))
_client = {
"server" : _server.get("name"),
"common_name" : _client_raw[0],
"remote_ip" : _client_raw[1].rsplit(":",1)[0], ## ipv6
"vpn_ip" : _client_raw[2],
"vpn_ipv6" : _client_raw[3],
"bytes_received" : int(_client_raw[4]),
"bytes_sent" : int(_client_raw[5]),
"uptime" : _now - int(_client_raw[7]),
"username" : _client_raw[8] if _client_raw[8] != "UNDEF" else _client_raw[0],
"clientid" : int(_client_raw[9]),
"cipher" : _client_raw[11].strip("\r\n")
}
if _client["username"].upper() in _monitored_clients:
_monitored_clients[_client["username"].upper()]["current"].append(_client)
_server["clientcount"] = _number_of_clients
_ret.append('{status} "OpenVPN Server: {name}" connections_ssl_vpn={clientcount};;{maxclients}|if_in_octets={bytesin}|if_out_octets={bytesout}|expiredays={expiredays} {clientcount}/{maxclients} Connections Port:{local_port}/{protocol} {expiredate}'.format(**_server))
except:
_ret.append('2 "OpenVPN Server: {name}" connections_ssl_vpn=0;;{maxclients}|expiredays={expiredays}|if_in_octets=0|if_out_octets=0 Server down Port:{local_port}/{protocol} {expiredate}'.format(**_server))
for _client in _monitored_clients.values():
_current_conn = _client.get("current",[])
if _client.get("disable") == 1:
continue
if not _client.get("description"):
_client["description"] = _client.get("common_name")
_client["description"] = _client["description"].strip(" \r\n")
_client["expiredays"] = 0
_client["expiredate"] = "no certificate found"
_client["status"] = 3
_cert = self._get_certificate_by_cn(_client.get("common_name"))
if _cert:
_notvalidafter = _cert.get("not_valid_after")
_client["expiredays"] = int((_notvalidafter - _now) / 86400)
_client["expiredate"] = time.strftime("Cert Expire: %d.%m.%Y",time.localtime(_notvalidafter))
if _client["expiredays"] < 61:
_client["status"] = 2 if _client["expiredays"] < 31 else 1
else:
_client["expiredate"] = "\\n" + _client["expiredate"]
if _current_conn:
_client["uptime"] = max(map(lambda x: x.get("uptime"),_current_conn))
_client["count"] = len(_current_conn)
_client["bytes_received"], _client["bytes_sent"] = self._get_traffic("openvpn",
"CL_{description}".format(**_client),
sum(map(lambda x: x.get("bytes_received"),_current_conn)),
sum(map(lambda x: x.get("bytes_sent"),_current_conn))