-
Notifications
You must be signed in to change notification settings - Fork 2
/
monitor.py
executable file
·1624 lines (1347 loc) · 67.3 KB
/
monitor.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/local/anaconda3/envs/musicode/bin/python
# Licensed under GPL v3
# Copyright 2011 VPAC <http://www.vpac.org>
# Copyright 2012-2016 Marcus Furlong <[email protected]>
try:
import ConfigParser as configparser
except ImportError:
import configparser
try:
from ipaddr import IPAddress as ip_address
from ipaddr import IPv6Address
except ImportError:
from ipaddress import ip_address, IPv6Address
# this might go to the config file as well
REQUIRE_LOGIN=False
import socket
import re
import argparse
import sys
import GeoIP
import sys
import os
import cgi
import warnings
#import cgitb
#cgitb.enable()
from datetime import datetime
from humanize import naturalsize
import humanize
from collections import OrderedDict, deque
from pprint import pformat
from semantic_version import Version as semver
import Pyro5, Pyro5.api, Pyro5.errors
import threading
from datetime import datetime
import json, requests
from bottle import run, template, request, route, redirect
from bottle import response, get, post, static_file, default_app
import mupif as mp
Pyro5.config.SERIALIZER="serpent"
Pyro5.config.SERVERTYPE="multiplex"
Pyro5.config.COMMTIMEOUT = 0.3 # 1.5 seconds
# to be decoded from session_id, if provided
userid = ""
def output(s):
global wsgi, wsgi_output
if not wsgi:
print(s)
else:
wsgi_output += s
def info(*objs):
print("INFO:", *objs, file=sys.stderr)
def warning(*objs):
print("WARNING:", *objs, file=sys.stderr)
def debug(*objs):
print("DEBUG:\n", *objs, file=sys.stderr)
def get_date(date_string, uts=False):
if not uts:
return datetime.strptime(date_string, "%a %b %d %H:%M:%S %Y")
else:
return datetime.fromtimestamp(float(date_string))
def get_str(s):
if s is None: return None
return s.encode('ascii','xmlcharrefreplace').decode('utf-8')
class ConfigLoader(object):
def __init__(self, config_file):
self.settings = {}
self.vpns = OrderedDict()
config = configparser.RawConfigParser()
contents = config.read(config_file)
if not contents and config_file == './openvpn-monitor.conf':
warning(f'Config file does not exist or is unreadable: {config_file!s}')
if sys.prefix == '/usr':
conf_path = '/etc/'
else:
conf_path = sys.prefix + '/etc/'
config_file = conf_path + 'openvpn-monitor.conf'
contents = config.read(config_file)
if contents:
info(f'Using config file: {config_file!s}')
else:
warning(f'Config file does not exist or is unreadable: {config_file!s}')
self.load_default_settings()
for section in config.sections():
if section == 'OpenVPN-Monitor':
self.parse_global_section(config)
else:
self.parse_vpn_section(config, section)
def load_default_settings(self):
info('Using default settings => localhost:5555')
self.settings = {'site': 'Default Site',
'geoip_data': '/usr/share/GeoIP/GeoIPCity.dat',
'datetime_format': '%d/%m/%Y %H:%M:%S'}
self.vpns['Default VPN'] = {'name': 'default',
'host': 'localhost',
'port': '5555',
'show_disconnect': False}
def parse_global_section(self, config):
global_vars = ['site', 'logo', 'latitude', 'longitude', 'maps', 'geoip_data', 'datetime_format', 'vpn_type']
for var in global_vars:
try:
self.settings[var] = config.get('OpenVPN-Monitor', var)
except configparser.NoOptionError:
pass
if args.debug:
debug(f"=== begin section\n{self.settings!s}\n=== end section")
def parse_vpn_section(self, config, section):
self.vpns[section] = {}
vpn = self.vpns[section]
options = config.options(section)
for option in options:
try:
vpn[option] = config.get(section, option)
if vpn[option] == -1:
warning(f'CONFIG: skipping {option!s}')
except configparser.Error as e:
warning(f'CONFIG: {e!s} on option {option!s}: ')
vpn[option] = None
if 'show_disconnect' in vpn and vpn['show_disconnect'] == 'True':
vpn['show_disconnect'] = True
else:
vpn['show_disconnect'] = False
if args.debug:
debug(f"=== begin section\n{vpn!s}\n=== end section")
class MupifConfigLoader(object):
def __init__(self, config_file):
self.mupif = {}
self.jobmans = OrderedDict()
config = configparser.RawConfigParser()
contents = config.read(config_file)
if not contents and config_file == './mupif-monitor.conf':
warning(f'Config file does not exist or is unreadable: {config_file!s}')
if sys.prefix == '/usr':
conf_path = '/etc/'
else:
conf_path = sys.prefix + '/etc/'
config_file = conf_path + 'mupif-monitor.conf'
contents = config.read(config_file)
if contents:
info(f'Using config file: {config_file!s}')
else:
warning(f'Config file does not exist or is unreadable: {config_file!s}')
self.load_default_settings()
for section in config.sections():
if section == 'mupif':
self.parse_mupif_section(config)
else:
pass
# self.parse_jobman_section(config, section)
def load_default_settings(self):
info('Using default settings')
self.mupif = {'nameserver_ip': '127.0.0.1',
'nameserver_port': '9090',
'mupifdb_ip': '127.0.0.1', # mupifDB rest API
'mupifdb_port': '8005'}
def parse_mupif_section(self, config):
global_vars = ['nameserver_ip', 'nameserver_port', 'mupifdb_ip', 'mupifdb_port']
for var in global_vars:
try:
self.mupif[var] = config.get('mupif', var)
except configparser.NoOptionError:
pass
if args.debug:
debug(f"=== begin section\n{self.settings!s}\n=== end section")
def parse_jobman_section(self, config, section):
self.jobmans[section] = {}
jobman = self.jobmans[section]
options = config.options(section)
for option in options:
try:
jobman[option] = config.get(section, option)
if jobman[option] == -1:
warning(f'CONFIG: skipping {option!s}')
except configparser.Error as e:
warning(f'CONFIG: {e!s} on option {option!s}: ')
jobman[option] = None
if args.debug:
debug(f"=== begin section\n{jobman!s}\n=== end section")
class mupifMonitor(object):
def __init__(self, cfg):
self.ns = None
self.cfg = cfg.mupif
self.jobmans = cfg.jobmans
self.scheds = {}
self.collect_data()
if False:
if (self.ns):
for key, jobman in list(self.jobmans.items()):
self.collect_jobman_data(jobman)
else:
self.jobmans={}
# collect all registered jobmans from nameserver using jobman metadata tag
if self.ns is not None:
queryJobman = self.ns.yplookup(meta_any={"type:jobmanager"}) # XXX this is to be tested more
querySched = self.ns.yplookup(meta_any={"type:scheduler"})
info(queryJobman)
info(querySched)
threads = []
start = datetime.now()
for name, uri in queryJobman.items():
self.jobmans[name] = {}
jobmanRec=self.jobmans[name];
jobmanRec['uri']=uri[0] # yplookup returns (URI, metadata) tuple
#self.collect_jobman_data(name, uri, jobmanRec)
thread = threading.Thread(target=self.collect_jobman_data, args=(name, uri[0], jobmanRec))
threads.append(thread)
for name, (uri,metadata) in querySched.items():
self.scheds[name]={}
self.scheds[name]['uri']=uri
thread=threading.Thread(target=self.collect_sched_data,args=(name,uri,self.scheds[name]))
threads.append(thread)
for t in threads:
t.start()
for t in threads:
t.join()
end = datetime.now()
#print ("Request time: %s"%str(end-start))
def collect_data(self):
# print('collect_data called')
# print (str(self.cfg))
self.ns_socket_connect(nshost=self.cfg['nameserver_ip'], nsport=self.cfg['nameserver_port'])
try:
# print("Querying mupifDB status:\n")
ip = self.cfg['mupifdb_ip']
req = 'http://'+(f'[{ip}]' if ':' in ip else ip)+":"+self.cfg['mupifdb_port']+'/status/'
# print(req)
r = requests.get(req)
# print("url:", r.url)
# print("Text:", r.text)
status = r.json()
# print(status)
self.cfg['mupifdb_status'] = status
except:
self.cfg['mupifdb_status'] = {}
def collect_jobman_data(self, name, uri, jobmanRec):
s = datetime.now()
jobmanRec['status'] = 'Failed'
jobmanRec['note'] = ''
jobmanRec['numberofrunningjobs'] = ''
jobmanRec['showJobs'] = 'ON'
jobmanRec['totalJobs'] = '? total'
try:
j = Pyro5.api.Proxy(uri)
# j._pyroHmacKey = hmackey
sig = j.getApplicationSignature()
try:
statusex = j.getStatusExtended()
status = statusex['currJobs']
jobmanRec['totalJobs'] = str(statusex['totalJobs'])+' total'
# older JobManager without getStatusExtended
except AttributeError:
status = j.getStatus()
# sig = 'KO'
jobmanRec['status'] = "OK"
jobmanRec['note'] = sig
# status = j.getStatus()
# info(status)
# print(status)
jobmanRec['numberofrunningjobs'] = len(status)
except Pyro5.errors.CommunicationError:
jobmanRec['note'] = f"Cannot connect to jobManager {name}"
jobmanRec['note'] += "["+str(datetime.now()-s)+"]"
return
def ns_socket_connect(self, nshost, nsport):
timeout = 3
self.s = False
self.cfg['error'] = ""
try:
self.s = socket.create_connection((nshost, nsport), timeout)
if self.s:
self.cfg['ns_status'] = 'OK'
self.s.shutdown(socket.SHUT_RDWR)
self.s.close()
except socket.timeout as e:
self.cfg['error'] = f"{e!s}{nshost + ':' + nsport!s}"
warning(f'socket timeout: {e!s}')
self.cfg['ns_status'] = 'Failed'
if self.s:
self.s.shutdown(socket.SHUT_RDWR)
self.s.close()
except socket.error as e:
self.cfg['error'] = f'{e.strerror!s}'
warning(f'socket error: {e!s}')
self.cfg['ns_status'] = 'Failed'
return
except Exception as e:
self.cfg['error'] = f'{e!s}'
warning(f'unexpected error: {e!s}')
self.cfg['ns_status'] = 'Failed'
return
try:
self.ns = Pyro5.api.locate_ns(host=nshost, port=int(nsport))
self.cfg['ns_status'] = "OK"
except Exception:
self.cfg['ns_status'] = "Failed"
self.cfg['error'] = f"Pyro5.api.locate_ns failed for NameServer on {nshost}:{nsport}"
def _socket_recv(self, length):
return self.s.recv(length).decode('utf-8')
def collect_sched_data(self, name, uri, schedRec):
schedRec['note'] = ''
schedRec['status'] = 'failed'
s = datetime.now()
try:
j = Pyro5.api.Proxy(uri)
schedRec['status'] = 'OK'
schedRec['stats'] = j.getStatistics()
except Pyro5.errors.CommunicationError:
schedRec['status'] = 'Failed'
except Exception as e:
schedRec['status'] = 'Failed'
schedRec['note'] += "["+str(datetime.now()-s)+"]"
class WireguardMgmtInterface(object):
def __init__(self,cfg):
self.vpns=cfg.vpns
geoip_data = cfg.settings['geoip_data']
self.gi = GeoIP.open(geoip_data, GeoIP.GEOIP_STANDARD)
for iface,vpn in self.vpns.items():
self.collect_data(iface,vpn)
def collect_data(self,iface,vpn):
import json,subprocess
numver=open('/sys/module/wireguard/version').read()[:-1]
vpn['type']='wireguard'
vpn['version'] = 'Wireguard '+numver
vpn['semver'] = semver(numver)
vpn['socket_connected']=True
peerMapJson=vpn.get('peer_map',None)
peerMap=(json.load(open(peerMapJson,'r')) if peerMapJson else {})
try:
dta=json.loads(subprocess.check_output(['sudo','/usr/share/doc/wireguard-tools/examples/json/wg-json']))
except subprocess.CalledProcessError:
warnings.warn('Calling wg-json failed. You might need to add the line "ALL ALL=NOPASSWD: /usr/share/doc/wireguard-tools/examples/json/wg-json" to /etc/sudoers.d/10-wireguard-show.conf (and run chmod 0440 /etc/sudoers.d/10-wireguard-show.conf) to get wireguard information as regular user.')
vpn['socket_connected']=False
return
dta=dta[iface]
import netifaces
ifaceip=netifaces.ifaddresses(iface)
if netifaces.AF_INET in ifaceip: local_ip=ip_address(ifaceip[netifaces.AF_INET][0]['addr'])
elif netifaces.AF_INET6 in ifaceip: local_ip=ip_address(ifaceip[netifaces.AF_INET6][0]['addr'])
else: local_ip='?'
vpn['state']={
'up_since':datetime.utcfromtimestamp(0),
'connected':'?',
'success':'?',
'local_ip':local_ip,
'remote_ip':'',
'mode':'Server' # Client or Server
}
#import pprint
#pprint.pprint(dta)
activePeers=dict([(peerKey,peerData) for peerKey,peerData in dta['peers'].items() if 'transferRx' in peerData])
vpn['stats']={
'nclients':len(dta['peers']),
'bytesin':sum([p['transferTx'] for p in activePeers.values()]),
'bytesout':sum([p['transferRx'] for p in activePeers.values()]),
}
vpn['sessions']={}
for peerKey,peerData in dta['peers'].items():
session=vpn['sessions'][peerKey]={}
cli=session['Client']={}
cli['tuntap_read']=cli['tuntap_write']=cli['auth_read']=0
cli['tcpudp_read']=peerData.get('transferRx',0)
cli['tcpudp_write']=peerData.get('transferTx',0)
if 0:
print(1000*'#')
from pprint import pprint
pprint(peerKey)
pprint(peerData)
if 'endpoint' in peerData:
# print(peerData['endpoint'])
remote_str=peerData['endpoint']
# copied from the OpeVPN monitor; ugly!
if remote_str.count(':') == 1:
remote, port = remote_str.split(':')
elif '(' in remote_str:
remote, port = remote_str.split('(')
port = port[:-1]
else: remote=remote_str
remote_ip=ip_address(remote)
if isinstance(remote_ip, IPv6Address) and remote_ip.ipv4_mapped is not None:
session['remote_ip'] = remote_ip.ipv4_mapped
else:
session['remote_ip'] = remote_ip
if session['remote_ip'].is_private:
session['location'] = 'RFC1918'
else:
try:
gir = self.gi.record_by_addr(str(session['remote_ip']))
except SystemError:
gir = None
if gir is not None:
session['location'] = get_str(gir['country_code'])
session['city'] = get_str(gir['city'])
session['country_name'] = gir['country_name']
session['longitude'] = gir['longitude']
session['latitude'] = gir['latitude']
else: session['remote_ip']='<unknown>'
session['local_ip']=(peerData['allowedIps'][0:1] or ['???'])[0]
session['bytes_recv']=peerData.get('transferRx',0)
session['bytes_sent']=peerData.get('transferTx',0)
session['connected_since']=datetime.utcfromtimestamp(0)
# TODO: read wireguard config and put friendly name here
# don't use unicode ellipsis as it renders incorrectly in the HTML
if peerKey in peerMap: session['username']=peerMap[peerKey]+'<br>'+peerKey[:10]+'...'
else: session['username']=peerKey[:10]+'...'
# the timestamp from wg-json is in local time, not UTC
session['last_seen']=datetime.fromtimestamp(peerData.get('latestHandshake',0))
class OpenvpnMgmtInterface(object):
def __init__(self, cfg, **kwargs):
self.vpns = cfg.vpns
if 'vpn_id' in kwargs:
vpn = self.vpns[kwargs['vpn_id']]
self._socket_connect(vpn)
if vpn['socket_connected']:
version = self.send_command('version\n')
sem_ver = semver(self.parse_version(version).split(' ')[1])
if sem_ver.minor == 4 and 'port' not in kwargs:
command = f"client-kill {kwargs['client_id']!s}\n"
else:
command = f"kill {kwargs['ip']!s}:{kwargs['port']!s}\n"
info(f'Sending command: {command!s}')
self.send_command(command)
self._socket_disconnect
geoip_data = cfg.settings['geoip_data']
self.gi = GeoIP.open(geoip_data, GeoIP.GEOIP_STANDARD)
for key, vpn in list(self.vpns.items()):
self._socket_connect(vpn)
if vpn['socket_connected']:
self.collect_data(vpn)
self._socket_disconnect()
def collect_data(self, vpn):
version = self.send_command('version\n')
vpn['type']='OpenVPN'
vpn['version'] = self.parse_version(version)
vpn['semver'] = semver(vpn['version'].split(' ')[1])
state = self.send_command('state\n')
vpn['state'] = self.parse_state(state)
stats = self.send_command('load-stats\n')
vpn['stats'] = self.parse_stats(stats)
status = self.send_command('status 3\n')
vpn['sessions'] = self.parse_status(status, self.gi, vpn['semver'])
def _socket_send(self, command):
self.s.send(bytes(command, 'utf-8'))
def _socket_recv(self, length):
return self.s.recv(length).decode('utf-8')
def _socket_connect(self, vpn):
host = vpn['host']
port = int(vpn['port'])
timeout = 3
self.s = False
try:
self.s = socket.create_connection((host, port), timeout)
if self.s:
vpn['socket_connected'] = True
data = ''
while 1:
socket_data = self._socket_recv(1024)
data += socket_data
if data.endswith('\r\n'):
break
except socket.timeout as e:
vpn['error'] = f'{e!s}'
warning(f'socket timeout: {e!s}')
vpn['socket_connected'] = False
if self.s:
self.s.shutdown(socket.SHUT_RDWR)
self.s.close()
except socket.error as e:
vpn['error'] = f'{e.strerror!s}'
warning(f'socket error: {e!s}')
vpn['socket_connected'] = False
except Exception as e:
vpn['error'] = f'{e!s}'
warning(f'unexpected error: {e!s}')
vpn['socket_connected'] = False
def _socket_disconnect(self):
self._socket_send('quit\n')
self.s.shutdown(socket.SHUT_RDWR)
self.s.close()
def send_command(self, command):
self._socket_send(command)
data = ''
if command.startswith('kill') or command.startswith('client-kill'):
return
while 1:
socket_data = self._socket_recv(1024)
socket_data = re.sub('>INFO(.)*\r\n', '', socket_data)
data += socket_data
if command == 'load-stats\n' and data != '':
break
elif data.endswith("\nEND\r\n"):
break
if args.debug:
debug(f"=== begin raw data\n{data!s}\n=== end raw data")
return data
@staticmethod
def parse_state(data):
state = {}
for line in data.splitlines():
parts = line.split(',')
if args.debug:
debug(f"=== begin split line\n{parts!s}\n=== end split line")
if parts[0].startswith('>INFO') or \
parts[0].startswith('END') or \
parts[0].startswith('>CLIENT'):
continue
else:
state['up_since'] = get_date(date_string=parts[0], uts=True)
state['connected'] = parts[1]
state['success'] = parts[2]
if parts[3]:
state['local_ip'] = ip_address(parts[3])
else:
state['local_ip'] = ''
if parts[4]:
state['remote_ip'] = ip_address(parts[4])
state['mode'] = 'Client'
else:
state['remote_ip'] = ''
state['mode'] = 'Server'
return state
@staticmethod
def parse_stats(data):
stats = {}
line = re.sub('SUCCESS: ', '', data)
parts = line.split(',')
if args.debug:
debug(f"=== begin split line\n{parts!s}\n=== end split line")
stats['nclients'] = int(re.sub('nclients=', '', parts[0]))
stats['bytesin'] = int(re.sub('bytesin=', '', parts[1]))
stats['bytesout'] = int(re.sub('bytesout=', '', parts[2]).replace('\r\n', ''))
return stats
@staticmethod
def parse_status(data, gi, version):
client_section = False
routes_section = False
sessions = {}
client_session = {}
for line in data.splitlines():
parts = deque(line.split('\t'))
if args.debug:
debug(f"=== begin split line\n{parts!s}\n=== end split line")
if parts[0].startswith('END'):
break
if parts[0].startswith('TITLE') or \
parts[0].startswith('GLOBAL') or \
parts[0].startswith('TIME'):
continue
if parts[0] == 'HEADER':
if parts[1] == 'CLIENT_LIST':
client_section = True
routes_section = False
if parts[1] == 'ROUTING_TABLE':
client_section = False
routes_section = True
continue
if parts[0].startswith('TUN') or \
parts[0].startswith('TCP') or \
parts[0].startswith('Auth'):
parts = parts[0].split(',')
if parts[0] == 'TUN/TAP read bytes':
client_session['tuntap_read'] = int(parts[1])
continue
if parts[0] == 'TUN/TAP write bytes':
client_session['tuntap_write'] = int(parts[1])
continue
if parts[0] == 'TCP/UDP read bytes':
client_session['tcpudp_read'] = int(parts[1])
continue
if parts[0] == 'TCP/UDP write bytes':
client_session['tcpudp_write'] = int(parts[1])
continue
if parts[0] == 'Auth read bytes':
client_session['auth_read'] = int(parts[1])
sessions['Client'] = client_session
continue
if client_section:
session = {}
parts.popleft()
common_name = parts.popleft()
remote_str = parts.popleft()
if remote_str.count(':') == 1:
remote, port = remote_str.split(':')
elif '(' in remote_str:
remote, port = remote_str.split('(')
port = port[:-1]
else:
remote = remote_str
port = None
remote_ip = ip_address(remote)
if isinstance(remote_ip, IPv6Address) and \
remote_ip.ipv4_mapped is not None:
session['remote_ip'] = remote_ip.ipv4_mapped
else:
session['remote_ip'] = remote_ip
if port:
session['port'] = int(port)
else:
session['port'] = ''
if session['remote_ip'].is_private:
session['location'] = 'RFC1918'
else:
try:
gir = gi.record_by_addr(str(session['remote_ip']))
except SystemError:
gir = None
if gir is not None:
session['location'] = get_str(gir['country_code'])
session['city'] = get_str(gir['city'])
session['country_name'] = gir['country_name']
session['longitude'] = gir['longitude']
session['latitude'] = gir['latitude']
local_ipv4 = parts.popleft()
if local_ipv4:
session['local_ip'] = ip_address(local_ipv4)
else:
session['local_ip'] = ''
if version.minor == 4:
local_ipv6 = parts.popleft()
if local_ipv6:
session['local_ip'] = ip_address(local_ipv6)
session['bytes_recv'] = int(parts.popleft())
session['bytes_sent'] = int(parts.popleft())
parts.popleft()
session['connected_since'] = get_date(parts.popleft(), uts=True)
try:
username = parts.popleft()
except:
username='UNDEF';
if username != 'UNDEF':
session['username'] = username
else:
session['username'] = common_name
if version.minor == 4:
session['client_id'] = parts.popleft()
session['peer_id'] = parts.popleft()
sessions[str(session['local_ip'])] = session
if routes_section:
local_ip = parts[1]
last_seen = parts[5]
if local_ip in sessions:
sessions[local_ip]['last_seen'] = get_date(last_seen, uts=True)
if args.debug:
if sessions:
pretty_sessions = pformat(sessions)
debug(f"=== begin sessions\n{pretty_sessions!s}\n=== end sessions")
else:
debug("no sessions")
return sessions
@staticmethod
def parse_version(data):
for line in data.splitlines():
if line.startswith('OpenVPN'):
return line.replace('OpenVPN Version: ', '')
class OpenvpnHtmlPrinter(object):
def __init__(self, cfg, monitor, mupifMon):
self.init_vars(cfg.settings, monitor, mupifMon)
self.print_html_header()
for key, vpn in self.vpns:
if vpn['socket_connected']:
self.print_vpn(key, vpn)
else:
self.print_unavailable_vpn(vpn)
self.print_mupif_status(self.mupif_monitor)
if self.maps:
self.print_maps_html(self.mupif_monitor)
self.print_html_footer()
def init_vars(self, settings, monitor, mupifMon):
self.vpns = list(monitor.vpns.items())
self.mupif_monitor = mupifMon;
self.site = 'Example'
if 'site' in settings:
self.site = settings['site']
self.logo = None
if 'logo' in settings:
self.logo = settings['logo']
self.maps = False
if 'maps' in settings and settings['maps'] == 'True':
self.maps = True
self.latitude = -37.8067
self.longitude = 144.9635
if 'latitude' in settings:
self.latitude = settings['latitude']
if 'longitude' in settings:
self.longitude = settings['longitude']
self.datetime_format = settings['datetime_format']
def print_html_header(self):
global wsgi
if not wsgi:
output("Content-Type: text/html\n")
output('<!doctype html>')
output('<html><head>')
output('<meta charset="utf-8">')
output('<meta name="viewport" content="width=device-width, initial-scale=1">')
output(f'<title>{self.site!s} VPN Status Monitor</title>')
output('<meta http-equiv="refresh" content="300" />')
output('<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">')
output('<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>')
output('<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>')
output('<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.1/js/jquery.tablesorter.js"></script>')
output('<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.1/js/jquery.tablesorter.widgets.js"></script>')
# css
# output('<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous" />')
# output('<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous" />')
# output('<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.28.4/css/theme.bootstrap.min.css" integrity="sha256-cerl+DYHeG2ZhV/9iueb8E+s7rubli1gsnKuMbKDvho=" crossorigin="anonymous" />')
if self.maps:
output('<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.2/leaflet.css" integrity="sha256-9mfj77orHLh2GsN7CbMvpjO/Wny/ZZhR7Pu7hy0Yig4=" crossorigin="anonymous" />')
output('<script src="//cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.2/leaflet.js" integrity="sha256-RS5bDpN9YmmUIdtdu8ESPjNp1Bg/Fqu90PwN3uawdSQ=" crossorigin="anonymous"></script>')
#output('var List0_Icon = L.icon({')
#output(' iconUrl: \'/images/logos/template.png\',')
#output('')
#output(' iconSize: [38, 95], // size of the icon')
#output(' iconAnchor: [22, 94], // point of the icon which will correspond to marker\'s location')
#output(' popupAnchor: [-3, -76] // point from which the popup should open relative to the iconAnchor')
#output(' });')
output('</head><body>')
############local storage
output('<script>')
# output('$(document).ready(()=>{console.log(localStorage.panels)});')
output('$(document).ready(()=>{')
output('$(".panel .panel-collapse").on("shown.bs.collapse", function ()')
output('{')
output('var active = $(this).attr(\'id\');')
output('console.log(active);')
output('var panels= localStorage.panels === undefined ? new Array() : JSON.parse(localStorage.panels);')
output('if ($.inArray(active,panels)==-1) //check that the element is not in the array')
output('panels.push(active);')
output('localStorage.panels=JSON.stringify(panels);')
output('});')
output('$(".collapse").on(\'hidden.bs.collapse\', function ()')
output('{')
output('var active = $(this).attr(\'id\');')
output('var panels= localStorage.panels === undefined ? new Array() : JSON.parse(localStorage.panels);')
output('var elementIndex=$.inArray(active,panels);')
output('if (elementIndex!==-1) //check the array')
output('{')
output('panels.splice(elementIndex,1); //remove item from array')
output('}')
output('localStorage.panels=JSON.stringify(panels); //save array on localStorage')
output('});')
output('var panels=localStorage.panels === undefined ? new Array() : JSON.parse(localStorage.panels); //get all panels')
output('for (var i in panels){ //<-- panel is the name of the cookie')
output('if ($("#"+panels[i]).hasClass(\'panel-collapse\')) // check if this is a panel')
output('{')
output('$("#"+panels[i]).collapse("show");')
output('}')
output('}')
output('$("#searchVpnTable").on("keyup", function() {')
output('var value = $(this).val().toLowerCase();')
output('$("#vpnSessions tbody").children(\'tr\').filter(function() {')
output('$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)')
output('});')
output('});')
output('$("#searchJobManTable").on("keyup", function() {')
output('var value = $(this).val().toLowerCase();')
output('$("#jobManSessions tbody").children(\'tr\').filter(function() {')
output('$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)')
output('});')
output('});')
output('$("#vpnSessions").tablesorter();')
output('$("#jobManSessions").tablesorter();')
#end of document ready
output('});')
output('</script>')
output('<nav class="navbar navbar-inverse">')
output('<div class="container-fluid">')
output('<div class="navbar-header">')
output('<button type="button" class="navbar-toggle" ')
output('data-toggle="collapse" data-target="#myNavbar">')
output('<span class="icon-bar"></span>')
output('<span class="icon-bar"></span>')
output('<span class="icon-bar"></span>')
output('</button>')
output('<a class="navbar-brand" href="#">')
output(f'{self.site!s} VPN Status Monitor</a>')
output('</div><div class="collapse navbar-collapse" id="myNavbar">')
output('<ul class="nav navbar-nav"><li class="dropdown">')
output('<a class="dropdown-toggle" data-toggle="dropdown" href="#">VPN')
output('<span class="caret"></span></a>')
output('<ul class="dropdown-menu">')
for key, vpn in self.vpns:
if vpn['name']:
anchor = vpn['name'].lower().replace(' ', '_')
output(f"<li><a href=\"#{anchor!s}\">{vpn['name']!s}</a></li>")
output('</ul></li>')
if self.maps:
output('<li><a href="#map_canvas">Map View</a></li>')
if REQUIRE_LOGIN:
from keycloak import KeycloakOpenID
import keycloak
# if session_key defined
# display user + logout
# else display login
keycloak_conf = json.loads(open('keycloak.json').read())
global userid
keycloak_openid = KeycloakOpenID(server_url=keycloak_conf['auth-server-url'] + "/", realm_name=keycloak_conf['realm'],client_id=keycloak_conf['resource'],client_secret_key=keycloak_conf['credentials']['secret'])
#config_well_know = keycloak_openid.well_know()
#print(config_well_know)
#print(sys.argv)
arguments = cgi.FieldStorage()
if ('code' in arguments):
code = arguments.getvalue('code')
#print(code)
#print('-----------------------------------------------')
token = keycloak_openid.token(grant_type="authorization_code", code=code, redirect_uri="http://mech2018.fsv.cvut.cz/mupif/openvpn-monitor2/monitor.py")
#token = keycloak_openid.token(grant_type="authorization_code", code=code, redirect_uri="http://172.30.0.1/mupif/openvpn-monitor2/monitor.py")
userinfo = keycloak_openid.userinfo(token['access_token'])
userid = userinfo['preferred_username']
#print(userid)
else:
login_url = keycloak_openid.auth_url("http://mech2018.fsv.cvut.cz/mupif/openvpn-monitor2/monitor.py")
#login_url = keycloak_openid.auth_url("http://172.30.0.1/mupif/openvpn-monitor2/monitor.py")
#print ('<br> Welcome Anonymous !')
#print ('<a href="'+login_url+'"> Login here </a>')
#print ('<br>')
#userinfo = keycloak_openid.userinfo(token['access_token'])
#try:
# token = keycloak_openid.token('user', 'password')
#except keycloak.exceptions.KeycloakAuthenticationError:
# userid = ''
#token = keycloak_openid.token("user", "password", totp="012345")
#token = keycloak_openid.token(grant_type="authorization_code", code=code)
# if 'code' in request.query.keys():
# code = request.query['code']
# Get WellKnow
# Get Token
#token = keycloak_openid.token("user", "password")
# Get Userinfo