This repository has been archived by the owner on Apr 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
yunomonitor.py
executable file
·1696 lines (1464 loc) · 72.2 KB
/
yunomonitor.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/python3
""" License
Copyright (C) 2019 YunoHost
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses
"""
import sys
import getopt
import os
import requests
from subprocess import Popen, PIPE
import json
import yaml
import csv
import smtplib
import logging
import glob
import time
import socket
import ssl
import dns.resolver
import dbus
import shutil
import hashlib
import re
import urllib
import spf
from requests_toolbelt.adapters import host_header_ssl
from threading import Thread
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_PKCS1_v1_5
from datetime import datetime, timedelta
# =============================================================================
# SCRIPT CONFIG VARS
# =============================================================================
# Every 8 minutes
CRON_FREQUENCY = 8
MONITORING_ERRORS = {
'NO_PING': {'level': 'critical', 'first': 3, 'minutes': 30,
'user': 'Le serveur est éteint ou injoignable',
'admin': "Le serveur '{domain}' est éteint ou injoignable"},
'NO_IPV4_PING': {'level': 'critical', 'first': 3, 'minutes': 30,
'user': "Le serveur est injoignable pour certains équipements",
'admin': "Le serveur '{domain}' est injoignable en ipv4"},
'NO_IPV6_PING': {'level': 'critical', 'first': 3, 'minutes': 30,
'user': 'Le serveur est injoignable pour certains équipements',
'admin': "Le serveur '{domain}' est injoignable en ipv6"},
'DOMAIN_UNCONFIGURED': {'level': 'critical', 'first': 2, 'minutes': 30,
'user': "Le service n’est pas joignable car le nom de domaine {domain} n’est pas correctement configuré.",
'admin': "Le nom de domaine {domain} n’est pas configuré."},
'DOMAIN_UNCONFIGURED_IN_IPV4': {'level': 'critical', 'first': 2, 'minutes': 30,
'user': "Le service n’est pas joignable par certains équipements car le nom de domaine {domain} n’est pas correctement configuré.",
'admin': "Le nom de domaine {domain} n’est pas configuré pour ipv4. Beaucoup d’équipements ne pourront pas y accéder."},
'DOMAIN_UNCONFIGURED_IN_IPV6': {'level': 'info', 'first': 2, 'minutes': 30,
'user': "",
'admin': "Le service n'est pas configuré en IPv6."},
'CERT_RENEWAL_FAILED': {'level': 'error', 'first': 1, 'minutes': 30,
'user': "Le renouvellement du certificat {protocol} de {domain} a échoué ou n’est pas pris en compte, sans intervention le service tombera en panne dans {days} jours",
'admin': "Le renouvellement du certificat {protocol} de {domain} a échoué ou n’est pas pris en compte, sans intervention le service tombera en panne dans {days} jours"},
'CERT_INVALID': {'level': 'critical', 'first': 1, 'minutes': 30,
'user': "Le service n’est pas joignable car le certificat de sécurité a expiré ou n’est pas accepté. Note: si l’adresse web auquel vous voulez accéder est une page publique (sans authentification), il est possible d’y accéder en navigation privée, en ajoutant une exception.",
'admin': "Le service n’est pas joignable car le certificat de sécurité a expiré ou n’est pas accepté. Note: si l’adresse web auquel vous voulez accéder est une page publique (sans authentification), il est possible d’y accéder en navigation privée, en ajoutant une exception."},
'PORT_CLOSED_OR_SERVICE_DOWN': {'level': 'critical', 'first': 2, 'minutes': 30,
'user': "Le service n’est pas joignable",
'admin': "Le service n’est pas joignable"},
'TIMEOUT': {'level': 'critical', 'first': 3, 'minutes': 30,
'user': "Le service n’est pas joignable",
'admin': "Le service n’est pas joignable"},
'TOO_MANY_REDIRECTS': {'level': 'critical', 'first': 2, 'minutes': 30,
'user': "Le service semble en panne",
'admin': "Le service est en panne suite à une erreur de redirection."},
'SSO_CAPTURE': {'level': 'critical', 'first': 2, 'minutes': 30,
'user': "Le service semble en panne",
'admin': "Le service semble protégé par le SSO"},
'HTTP_403': {'level': 'critical', 'first': 2, 'minutes': 30,
'user': "Le service semble en panne",
'admin': "Le service est interdit d'accès"},
'HTTP_404': {'level': 'critical', 'first': 2, 'minutes': 30,
'user': "Le service semble en panne",
'admin': "Le service renvoie une erreur 404 page non trouvée"},
'HTTP_500': {'level': 'critical', 'first': 2, 'minutes': 30,
'user': "Le service semble en panne",
'admin': "Le service est en panne suite à une erreur logicielle."},
'HTTP_502': {'level': 'critical', 'first': 2, 'minutes': 30,
'user': "Le service semble en panne",
'admin': "Le service s’est eteint"},
'HTTP_503': {'level': 'critical', 'first': 2, 'minutes': 30,
'user': "Le service semble en panne",
'admin': "Le service est injoignable"},
'DOMAIN_EXPIRATION_NOT_FOUND': {'level': 'info', 'first': 1, 'minutes': 1440,
'user': "",
'admin': ""},
'DOMAIN_WILL_EXPIRE': {'level': 'warning', 'first': 1, 'minutes': 1440,
'user': "Le nom de domaine {domain} expire dans {days} jours. Ne pas oublier de le renouveller.",
'admin': "Le nom de domaine {domain} expire dans {days} jours. Ne pas oublier de le renouveller."},
'DOMAIN_NEARLY_EXPIRE': {'level': 'error', 'first': 1, 'minutes': 1440,
'user': "Le nom de domaine {domain} expire dans {days} jours. Sans renouvellement le service ne fonctionnera plus.",
'admin': "Le nom de domaine {domain} expire dans {days} jours. Sans renouvellement le service ne fonctionnera plus."},
'DOMAIN_EXPIRE': {'level': 'critical', 'first': 3, 'minutes': 300,
'user': "Le nom de domaine {domain} expire aujourd’hui ou demain. Sans renouvellement le service ne fonctionnera plus.",
'admin': "Le nom de domaine {domain} expire aujourd’hui ou demain. Sans renouvellement le service ne fonctionnera plus."},
'BROKEN_NAMESERVER': {'level': 'critical', 'first': 3, 'minutes': 30,
'user': "Un problème de connectivité interne pourrait créer des dysfonctionnements",
'admin': "Le serveur de nom à l’adresse {ip} est injoignable"},
# 'TIMEOUT': {'level': 'critical', 'first': 3, 'minutes': 30,
# 'user': "Un problème de connectivité interne pourrait créer des dysfonctionnements",
# 'admin': "Le serveur de nom à l’adresse {ip} est trop lent"},
'NO_ANSWER': {'level': 'critical', 'first': 2, 'minutes': 30,
'user': "Le service n’est pas joignable car le nom de domaine {domain} n’est pas correctement configuré.",
'admin': "Le nom de domaine {domain} n’est pas configuré."},
'UNEXPECTED_ANSWER': {'level': 'critical', 'first': 1, 'minutes': 30,
'user': "",
'admin': ""},
'NO_MX_RECORD': {'level': 'error', 'first': 1, 'minutes': 30,
'user': "Un problème de configuration des mails a été détecté. Certains mails pourraient tombés en SPAM.",
'admin': "Aucune configuration MX pour le domaine {domain}. Certains mails pourraient être calssé en SPAM."},
'REVERSE_MISSING': {'level': 'critical', 'first': 1, 'minutes': 30,
'user': "Un problème de configuration des mails a été détecté. Certains mails pourraient tombés en SPAM.",
'admin': "Le DNS inversé n’a pas été configuré pour l’ip {ip} et le domaine {ehlo_domain}. Le serveur pourraient être blacklisté et certains mails en@{domain} pourraient être classé en SPAM"},
'REVERSE_MISMATCH': {'level': 'critical', 'first': 1, 'minutes': 30,
'user': "Un problème de configuration des mails a été détecté. Certains mails pourraient tombés en SPAM.",
'admin': "Le DNS inversé pour l’ip {ip} est configuré pour le domaine {reverse_dns} au lieu de domaine {ehlo_domain}. Le serveur pourraient être blacklisté et certains mails en @{domain} pourraient être classé en SPAM"},
'BLACKLISTED': {'level': 'critical', 'first': 1, 'minutes': 30,
'user': "L’ip du serveur a été blacklistée par {rbl}. Certains mails pourraient tombés en SPAM.",
'admin': "L’ip du serveur a été blacklistée par {rbl}. Certains mails pourraient tombés en SPAM."},
'NOT_FOUND': {'level': 'critical', 'first': 1, 'minutes': 30,
'user': "Un des programmes est en panne, des dysfonctionnements sur le service peuvent subvenir.",
'admin': "Le service {service} n’existe pas"},
'DOWN': {'level': 'critical', 'first': 2, 'minutes': 30,
'user': "Un des programmes est en panne, des dysfonctionnements sur le service peuvent subvenir.",
'admin': "Le service {service} est éteint il devrait être allumé."},
'FAILED': {'level': 'critical', 'first': 2, 'minutes': 30,
'user': "Un des programmes est en panne, des dysfonctionnements sur le service peuvent subvenir.",
'admin': "Le service {service} est tombé en panne il faut le relancer et investiguer."},
'SMART_NOT_SUPPORTED': {'level': 'warning', 'first': 1, 'minutes': 1440,
'user': "",
'admin': "Un disque dur ne supporte pas les fonctionnalités permétant le contrôle de son état de santé."},
'SMART_DISABLED': {'level': 'error', 'first': 1, 'minutes': 1440,
'user': "L’activation du contrôle de l’état de santé d’un disque dur n’a pas fonctionné.",
'admin': "L’activation du contrôle de l’état de santé d’un disque dur n’a pas fonctionné."},
'SMART_HALF_WORKING': {'level': 'error', 'first': 1, 'minutes': 1440,
'user': "Le contrôle de l’état de santé d’un disque dur n’est que partiellement activé.",
'admin': "Le contrôle de l’état de santé d’un disque dur n’est que partiellement activé."},
'DISK_FAILURE': {'level': 'critical', 'first': 1, 'minutes': 30,
'user': "Un disque dur semble sur le point de tomber en panne, il faut le changer rapidement.",
'admin': "Un disque dur semble sur le point de tomber en panne, il faut le changer rapidement."},
'NO_FREE_SPACE': {'level': 'critical', 'first': 1, 'minutes': 30,
'user': "Il n’y a plus d’espace disque sur le serveur des dysfonctionnements sont à prévoir",
'admin': "Il n’y a plus d’espace disque sur le serveur des dysfonctionnements sont à prévoir"},
'C_FREE_SPACE': {'level': 'critical', 'first': 1, 'minutes': 30,
'user': "L’espace disque sur le serveur est trop faible, si rien n’est fait rapidement des dysfonctionnements sont à prévoir",
'admin': "L’espace disque sur le serveur est trop faible, si rien n’est fait rapidement des dysfonctionnements sont à prévoir"},
'E_FREE_SPACE': {'level': 'error', 'first': 1, 'minutes': 1440,
'user': "L’espace disque sur le serveur est trop faible, si rien n’est fait des dysfonctionnements pourraient subvenir",
'admin': "L’espace disque sur le serveur est trop faible, si rien n’est fait des dysfonctionnements pourraient subvenir"},
'W_FREE_SPACE': {'level': 'warning', 'first': 1, 'minutes': 1440,
'user': "",
'admin': "L’espace disque sur le serveur est assez réduit."},
'NO_BACKUP': {'level': 'error', 'first': 2, 'minutes': 30,
'user': "Aucune sauvegarde [de {app}] n’a été trouvée sur le serveur de [sauvegarde à paris].",
'admin': "Aucune sauvegarde [de {app}] n’a été trouvée sur le serveur de [sauvegarde à paris]."},
'MISSING_BACKUP': {'level': 'error', 'first': 2, 'minutes': 30,
'user': "La dernière sauvegarde [de {app}] sur le serveur de [sauvegarde à paris] est manquante. ",
'admin': "La dernière sauvegarde [de {app}] sur le serveur de [sauvegarde à paris] est manquante. "},
'BACKUP_NOT_TRIGGERED': {'level': 'error', 'first': 2, 'minutes': 30,
'user': "La sauvegarde vers le serveur de sauvegarde à paris n’a pas été déclenchée au cours des dernières 24h.",
'admin': "La sauvegarde vers le serveur de sauvegarde à paris n’a pas été déclenchée au cours des dernières 24h."},
'BACKUP_BROKEN': {'level': 'error', 'first': 2, 'minutes': 30,
'user': "La dernière sauvegarde [de {app}] sur le serveur de sauvegarde à paris est incomplète. Une restauration manuelle resterait peut être possible.",
'admin': "La dernière sauvegarde [de {app}] sur le serveur de sauvegarde à paris est incomplète. Une restauration manuelle resterait peut être possible."},
'APP_NEED_UPGRADE': {'level': 'warning', 'first': 1, 'minutes': 1440,
'user': "",
'admin': "Une mise à jour est disponible pour l'application {app}"},
'PKG_NEED_UPGRADE': {'level': 'warning', 'first': 1, 'minutes': 1440,
'user': "",
'admin': "Une mise à jour des paquets systèmes est disponible"},
'UNKNOWN_ERROR': {'level': 'error', 'first': 3, 'minutes': 30,
'user': "",
'admin': "Une erreur non gérée par le système de monitoring est survenue"},
'HTTP_UNKNOWN_ERROR': {'level': 'error', 'first': 3, 'minutes': 30,
'user': "",
'admin': "Une erreur HTTP est survenue"},
}
# Trigger actions every 8*3 minutes of failures
ALERT_FREQUENCY = 3
# Update monitoring configuration each hours
CACHE_DURATION_IN_MINUTES = 60
WORKING_DIR = os.path.abspath(os.path.dirname(__file__))
WELL_KNOWN_URI = 'https://%s/.well-known/yunomonitor/'
REMOTE_MONITORING_CONFIG_FILE = os.path.join(WELL_KNOWN_URI, '%s.to_monitor')
REMOTE_FAILURES_FILE = os.path.join(WELL_KNOWN_URI, '%s.failures')
WELL_KNOWN_DIR = os.path.join(WORKING_DIR, 'well-known/')
PUBLISHED_FAILURES_FILE = os.path.join(WELL_KNOWN_DIR, "%s.failures")
PUBLISHED_MONITORING_CONFIG_FILE = os.path.join(WELL_KNOWN_DIR, "%s.to_monitor")
PUBLIC_KEY_URI = os.path.join(WELL_KNOWN_URI, "ssh_host_rsa_key.pub")
"""
ping:
some.domain.tld:
count: 3
messages:
- some.domain.tld no ipv4 ping
"""
CONFIG_DIR = os.path.join(WORKING_DIR, "conf/")
IGNORE_ALERT_CSV = os.path.join(CONFIG_DIR, "ignore_alert.csv")
DAILY_IGNORE_ALERT_CSV = os.path.join(CONFIG_DIR, "daily_ignore_alert.csv")
MONITORING_CONFIG_FILE = os.path.join(CONFIG_DIR, "%s.yml")
CACHE_MONITORING_CONFIG_FILE = os.path.join(CONFIG_DIR, "%s.cache.yml")
FAILURES_FILE = os.path.join(CONFIG_DIR, "%s.failures.yml")
MAIL_SUBJECT = "[{level}][{server}] {message}: {target}"
MAIL_BODY = """{admin_info}
Extra info: {extra}
"""
HTTP_TIMEOUT = 15
DEFAULT_BLACKLIST = [
('zen.spamhaus.org' , 'Spamhaus SBL, XBL and PBL' ),
('dnsbl.sorbs.net' , 'SORBS aggregated' ),
('safe.dnsbl.sorbs.net' , "'safe' subset of SORBS aggregated"),
('ix.dnsbl.manitu.net' , 'Heise iX NiX Spam' ),
('babl.rbl.webiron.net' , 'Bad Abuse' ),
('cabl.rbl.webiron.net' , 'Chronicly Bad Abuse' ),
('truncate.gbudb.net' , 'Exclusively Spam/Malware' ),
('dnsbl-1.uceprotect.net' , 'Trapserver Cluster' ),
('cbl.abuseat.org' , 'Net of traps' ),
('dnsbl.cobion.com' , 'used in IBM products' ),
('psbl.surriel.com' , 'passive list, easy to unlist' ),
('dnsrbl.org' , 'Real-time black list' ),
('db.wpbl.info' , 'Weighted private' ),
('bl.spamcop.net' , 'Based on spamcop users' ),
('dyna.spamrats.com' , 'Dynamic IP addresses' ),
('spam.spamrats.com' , 'Manual submissions' ),
('auth.spamrats.com' , 'Suspicious authentications' ),
('dnsbl.inps.de' , 'automated and reported' ),
('bl.blocklist.de' , 'fail2ban reports etc.' ),
('srnblack.surgate.net' , 'feeders' ),
('all.s5h.net' , 'traps' ),
('rbl.realtimeblacklist.com' , 'lists ip ranges' ),
('b.barracudacentral.org' , 'traps' ),
('hostkarma.junkemailfilter.com', 'Autotected Virus Senders' ),
('rbl.megarbl.net' , 'Curated Spamtraps' ),
('ubl.unsubscore.com' , 'Collected Opt-Out Addresses' ),
('0spam.fusionzero.com' , 'Spam Trap' ),
]
# =============================================================================
# Import user settings
try:
from settings_local import *
except:
pass
# =============================================================================
# GLOBAL VARS
# =============================================================================
logging.basicConfig(level=logging.WARNING)
# =============================================================================
# =============================================================================
# CORE FUNCTIONS
# =============================================================================
class IPMetaClass(type):
def __getitem__(cls, x):
return getattr(cls, x)
@property
def connected(self):
return self.v4 or self.v6
class IP(object, metaclass=IPMetaClass):
v4 = True
v6 = True
def display_help(error=0):
print('yunomonitor.py [YUNODOMAIN ...] [-m MAIL ...] [-s SMS_API ...] [-c CACHET_API ...]')
print('YunoMonitor is a one file script to monitor a server and send mail,')
print('sms or fill a cachet status page.')
sys.exit(error)
def main(argv):
start_time = time.time()
# Parse arguments
try:
opts, monitored_servers = getopt.getopt(argv, "hm:s:C:e:c:",
["mail=", "sms=", "cachet=",
"encrypt-for=", "config="])
except getopt.GetoptError:
display_help(2)
logging.debug("Given options: %s" % (opts))
logging.debug("Servers to monitor: %s" % (monitored_servers))
config_file = None
for opt, arg in opts:
if opt == '-h':
display_help()
elif opt in ("-c", "--config"):
config_file = arg
if config_file:
with open(config_file, 'r') as local_config_file:
config = yaml.load(local_config_file)
else:
config = {
'mails': [],
'sms_apis': [],
'cachet_apis': [],
'monitoring_servers': [],
'monitored_servers': monitored_servers,
}
for param in ['mails', 'sms_apis', 'cachet_apis', 'monitoring_servers', 'monitored_servers']:
config[param] = set(config[param]) if param in config else set()
for opt, arg in opts:
if opt in ("-m", "--mail"):
config['mails'].add(arg)
elif opt in ("-s", "--sms"):
config['sms_apis'].add(arg)
elif opt in ("-C", "--cachet"):
config['cachet_apis'].add(arg)
elif opt in ("-e", "--encrypt-for"):
config['monitoring_servers'].add(arg)
if config['monitored_servers'] == set():
config['monitored_servers'] = ['localhost']
levels = {
'CRITICAL': logging.CRITICAL,
'ERROR': logging.ERROR,
'WARNING': logging.WARNING,
'INFO': logging.INFO,
'DEBUG': logging.DEBUG
}
logging.getLogger().setLevel(levels[config.get('logging_level', 'WARNING')])
logging.debug("Config: %s" % (config))
# If we are offline in IPv4 and IPv6 execute only local checks
IP.v4 = not check_ping("wikipedia.org", ['v4'])
IP.v6 = socket.has_ipv6 and not check_ping("wikipedia.org", ['v6'])
if not IP.v4 and not IP.v6:
logging.debug('NO CONNECTION')
if 'localhost' not in config['monitored_servers']:
sys.exit(2)
logging.warning('ONLY LOCAL TEST WILL BE RUN')
config['monitored_servers'] = set(['localhost'])
elif not IP.v6:
logging.info('NO IPV6 ON THIS MONITORING SERVER')
# Create well-known dir
try:
os.mkdir(WELL_KNOWN_DIR)
except:
# The dir may already exist
pass
# Publish ssh pub key into well-known
publish_ssh_public_key()
# Load or download monitoring description of each server, convert
# monitoring instructions, execute it
logging.info("CHECKING EACH SERVERS...")
logging.debug('Load or download monitoring description of each server, convert monitoring instructions, execute it')
threads = [ServerMonitor(server, config['monitoring_servers']) for server in config['monitored_servers']]
for thread in threads:
thread.start()
alerts = {}
# Wait for all thread
logging.debug('Waiting for all threads')
for thread in threads:
thread.join()
alerts[thread.server]=thread.failures
# Filter by reccurence or ignored status
logging.info('FILTERING...')
filtered = {}
for server, failures in alerts.items():
filtered[server] = {}
for message, reports in failures.items():
if not message in MONITORING_ERRORS:
logging.error("ERROR MESSAGE MISSING %s" %(message))
MONITORING_ERRORS[message] = MONITORING_ERRORS['UNKNOWN_ERROR']
first = MONITORING_ERRORS[message]['first']
freq = round(MONITORING_ERRORS[message]['minutes'] / CRON_FREQUENCY)
filtered[server][message] = []
for report in reports:
logging.debug(report)
logging.debug("first: %d freq: %d" %(first, freq))
if (report['count'] - first) % freq == 0:
report['level'] = MONITORING_ERRORS[message]['level']
filtered[server][message].append(report)
if not filtered[server][message]:
del filtered[server][message]
# Trigger some actions
if config['mails']:
logging.info('MAILING...')
mail_alert(filtered, config['mails'])
if config['sms_apis']:
logging.info('ALERTING BY SMS...')
sms_alert(filtered, config['sms_apis'])
#cachet_alert(alerts, ynh_maps, config['cachet_apis'])
#if 'localhost' in alerts:
# logging.info('FILLING CACHET...')
# service_up(alerts['localhost'].get('service_up', []))
logging.debug("===================> %f s" % (start_time - time.time()))
def detect_internet_protocol():
global ip
IP.v4 = not check_ping("wikipedia.org", ['v4'])
IP.v6 = socket.has_ipv6
no_pingv6 = check_ping("wikipedia.org", ['v6'])
IP.v6 = IP.v6 and not no_pingv6
class ServerMonitor(Thread):
"""Thread to monitor one server."""
ynh_maps = {}
def __init__(self, server, monitoring_servers):
Thread.__init__(self)
self.server = server
self.monitoring_servers = monitoring_servers
self.failures = {}
def run(self):
logging.info("[%s] CONFIGURING..." % (self.server))
self.ynh_maps[self.server] = self._load_monitoring_config()
logging.info("[%s] MONITORING..." % (self.server))
self._monitor()
logging.info("[%s] COUNTING FAILURES..." % (self.server))
self._count()
logging.info("[%s] ADDING FAILURES REPORTED BY MONITORED SERVER ITSELF..." % (self.server))
self._add_remote_failures()
logging.info("[%s] SAVING FAILURES..." % (self.server))
self._save()
if self.server == "localhost":
logging.info("[%s] PUBLISHING FAILURES..." % (self.server))
self._publish()
def _load_monitoring_config(self):
""" This function loads the instructions to know what to monitor
"""
local_config = MONITORING_CONFIG_FILE % (self.server)
cache_config = CACHE_MONITORING_CONFIG_FILE % (self.server)
# If a user specific configuration is in /etc, we use it
if os.path.exists(local_config):
with open(local_config, 'r') as local_config_file:
return yaml.load(local_config_file)
else:
# If a cache configuration younger than 1h exists, we use it
if os.path.exists(cache_config):
# TODO Improve cache by using HTTP cache headers
minutes = (time.time() - os.path.getmtime(cache_config)) / 60
if minutes < CACHE_DURATION_IN_MINUTES:
with open(cache_config, 'r') as cache_config_file:
config = yaml.load(cache_config_file)
# In case the cache config is in a bad format (404 content...)
if not isinstance(config, str):
return config
# If we are on the server to monitor, generate the configuration
if self.server == 'localhost':
config = generate_monitoring_config()
# Encrypt and publish to let the monitoring server to download it
for mserver in self.monitoring_servers:
with open(PUBLISHED_MONITORING_CONFIG_FILE % get_id_host(mserver), 'wb') as publish_config_file:
publish_config_file.write(encrypt(yaml.dump(config), mserver))
# If the server to monitor is on remote, we try to download the
# configuration
else:
config_url = REMOTE_MONITORING_CONFIG_FILE % (self.server, get_id_host())
logging.info("Try to download the remote config : %s" % (config_url))
try:
r = requests.get(config_url, timeout=15)
assert r.status_code == 200, "Fail to download the configuration"
config = yaml.load(decrypt(r.content))
assert not isinstance(config, str), "Misformed downloaded configuration"
except Exception as e:
logging.warning('Unable to download autoconfiguration file of %s, the old one will be used' % (self.server))
try:
with open(cache_config, 'r') as cache_config_file:
cconfig = yaml.load(cache_config_file)
except FileNotFoundError as e:
cconfig = ''
assert not isinstance(cconfig, str), "Unable to load an old config too, yunomonitor is not able to monitor %s" % (self.server)
return cconfig
# Write the configuration in cache
with open(cache_config, 'w') as cache_config_file:
yaml.dump(config, cache_config_file, default_flow_style=False)
return config
def _monitor(self):
to_monitor = self.ynh_maps[self.server].copy()
del to_monitor['__components__']
# Remove checks that run on another machine
if self.server == 'localhost':
checks = ['dns_resolution', 'service_up', 'backuped', 'disk_health', 'free_space']
else:
checks = ['ping', 'dns_resolver', 'domain_renewal', 'https_200', 'smtp', 'smtp_sender', 'imap', 'xmpp']
to_monitor = [(check, to_monitor[check]) for check in checks if check in to_monitor]
# Check things to monitor
for category, checks in to_monitor:
for args in checks:
try:
check_name = "check_%s" % (category)
if isinstance(args, str):
args = [args]
logging.debug("[%s] Running check: %s(%s)" % (self.server, check_name, args))
start_time = time.time()
if isinstance(args, dict):
reports = globals()[check_name](**args)
else:
reports = globals()[check_name](*args)
except Exception as e:
reports = [('UNKNOWN_ERROR', {'check': category}, {'debug': str(e)})]
logging.debug("===> %f s" % (time.time() - start_time))
if reports:
logging.info("[%s] Check: %s(%s)" % (self.server, check_name, args))
logging.warning(reports)
for report in reports:
if report[0] not in self.failures:
self.failures[report[0]] = self.failures.get(report[0], [])
self.failures[report[0]].append({
'target': report[1],
'count': 1,
'extra': report[2] if len(report) >= 3 else {}
})
def _count(self):
# Extract recorded failures
failures_file = FAILURES_FILE % (self.server)
recorded_failures = {}
if os.path.exists(failures_file):
with open(failures_file) as f:
recorded_failures = json.load(f)
# Increase counter with recorded failures
for message, reports in recorded_failures.items():
if message not in self.failures:
continue
for report in reports:
r = [x for x in self.failures[message]
if x['target'] == report['target']]
if r:
r[0]['count'] += report['count']
def _add_remote_failures(self):
if self.server == 'localhost':
return
# Load internal failures
url = REMOTE_FAILURES_FILE % (self.server, get_id_host())
try:
r = requests.get(url, timeout=15)
if r is not None or r.status_code == 200:
internal_failures = json.loads(decrypt(r.content))
except Exception as e:
logging.debug('No failures files', str(e))
internal_failures = {}
# Add internal recorded failures
for message, reports in internal_failures.items():
if message not in self.failures:
self.failures[message] = reports
else:
self.failures[message] += reports
def _save(self):
failures_file = FAILURES_FILE % (self.server)
# Save failures in /etc file
with open(failures_file, "w") as f:
json.dump(self.failures, f)
def _publish(self):
# Publish failures
for mserver in self.monitoring_servers:
with open(PUBLISHED_FAILURES_FILE % get_id_host(mserver), "wb") as f:
f.write(encrypt(json.dumps(self.failures), mserver))
def publish_ssh_public_key():
if not os.path.exists(WELL_KNOWN_DIR + '/ssh_host_rsa_key.pub'):
from shutil import copyfile
copyfile('/etc/ssh/ssh_host_rsa_key.pub', WELL_KNOWN_DIR + '/ssh_host_rsa_key.pub')
def get_public_key(server):
cache_key = os.path.join(CONFIG_DIR, '%s.pub' % server)
if os.path.exists(cache_key):
with open(cache_key) as f:
key = f.read()
else:
try:
r = requests.get(PUBLIC_KEY_URI % server, timeout=15)
except Exception as e:
return None
if r is None or r.status_code != 200:
return None
key = r.text
with open(cache_key, 'w') as f:
f.write(r.text)
return key
def get_id_host(server=None):
if not server:
filename = '/etc/ssh/ssh_host_rsa_key.pub'
else:
get_public_key(server)
filename = os.path.join(CONFIG_DIR, '%s.pub' % server)
block_size = 65536
sha256 = hashlib.sha256()
with open(filename, 'rb') as f:
for block in iter(lambda: f.read(block_size), b''):
sha256.update(block)
return sha256.hexdigest()
def encrypt(message, mserver):
key = get_public_key(mserver)
return message.encode()
#key = RSA.importKey(key)
#cipher = Cipher_PKCS1_v1_5.new(key)
#return cipher.encrypt(message.encode())
def decrypt(cipher_message):
return cipher_message.decode()
#with open('/etc/ssh/ssh_host_rsa_key') as f:
# key = RSA.importKey(f.read())
#cipher = Cipher_PKCS1_v1_5.new(key)
#return cipher.decrypt(cipher_message, None).decode()
def get_local_dns_resolver():
if get_local_dns_resolver.dns_resolvers is None:
with open('/etc/resolv.dnsmasq.conf', 'r') as resolv_file:
get_local_dns_resolver.dns_resolvers = [x[11:].replace('\n', '')
for x in resolv_file.readlines()]
return get_local_dns_resolver.dns_resolvers
get_local_dns_resolver.dns_resolvers = None
def generate_monitoring_config():
https_200 = set()
service_up = set()
backuped = set()
domains = set()
is_yunohost = os.path.exists("/etc/yunohost/installed")
if is_yunohost:
with open("/etc/yunohost/current_host") as f:
current_host = f.read().strip()
domains = glob.glob('/etc/nginx/conf.d/*.*.conf')
domains = [path[18:-5] for path in domains]
dns_resolver = get_local_dns_resolver()
# TODO personalize meta components
apps = [
{
"id": "mail",
"name": "Mail",
"label": "Mail",
"services": ["rspamd", "dovecot", "postsrsd",
"dnsmasq", "slapd"] # postfix
},
{
"id": "xmpp",
"name": "XMPP",
"label": "Messagerie instantannée",
"services": ["metronome"]
},
{
"id": "ssowat",
"name": "SSOWat",
"label": "Authentification centralisée",
"uris": ["%s/yunohost/sso/" % (current_host)],
"services": ["slapd", "nslcd", "nginx", 'unscd']
},
{
"id": "admin",
"name": "Admin",
"label": "Administration",
"uris": ["%s/yunohost/admin/" % (current_host),
"%s/yunohost/api/installed" % (current_host)],
"services": ["nginx", "slapd", "ssh", "yunohost-api",
"systemd-logind"]
},
{
"id": "firewall",
"name": "Firewall",
"label": "Parefeu",
"services": ["fail2ban"] #yunohost-firewall
},
{
"id": "misc",
"name": "Base",
"label": "Système de base",
"services": ["avahi-daemon", "cron", "dbus",
"haveged", "ntp", "rsyslog", "syslog",
"systemd-journald", "systemd-udevd"]
}
]
apps_dir = glob.glob('/etc/yunohost/apps/*')
for app_dir in apps_dir:
try:
with open(os.path.join(app_dir, 'settings.yml'), 'r') as settings_file:
app_settings = yaml.load(settings_file)
with open(os.path.join(app_dir, 'manifest.json'), 'r') as manifest_file:
app_manifest = json.load(manifest_file)
except:
continue
uris = []
if 'unprotected_uris' in app_settings or 'skipped_uris' in app_settings:
if 'domain' in app_settings:
if 'path' in app_settings:
uris.append(app_settings['domain'] + app_settings['path'])
if 'unprotected_uris' in app_settings:
uris.append(app_settings['domain'] + app_settings['unprotected_uris'])
if 'skipped_uris' in app_settings:
uris.append(app_settings['domain'] + app_settings['skipped_uris'])
cmd = "grep -Ehor \"yunohost service add ([^ ]+)\""
cmd += " /etc/yunohost/apps/%s/scripts/" % app_settings['id']
cmd += " | cut -d ' ' -f4 | sed s/\$app/%s/g" % app_settings['id']
p = Popen(cmd.split(), stdout=PIPE, stderr=PIPE)
out, _ = p.communicate()
services = app_manifest['services'] if 'services' in app_manifest else []
services = set(services)
if p.returncode == 0:
services.update(out.decode("utf-8").strip().split("\n"))
app = {
"id": app_settings['id'],
"name": app_manifest['name'],
"label": app_settings['label'],
"uris": uris,
"services": []
}
if 'services' in app_manifest:
app["services"] = app_manifest['services']
if app['name'] in ["Borg", "Archivist"]:
if app['name'] == "Archivist" or app_settings['apps'] == 'all':
app['backup'] = [x[19:] for x in apps_dir]
else:
app['backup'] = app_settings['apps'].split(',')
apps.append(app)
for app in apps:
if 'uris' in app:
https_200.update(app['uris'])
if 'services' in app:
service_up.update(app['services'])
if 'backup' in app:
backuped.update([(x, app['id']) for x in app['backup']])
# List all non removable disks
devices = _get_devices()
domains = list(set(domains))
return {
"ping": domains,
"domain_renewal": domains,
"smtp": domains,
"smtp_sender": [[domain, [25,587]] for domain in domains],
"imap": domains,
"xmpp": domains,
"dns_resolver": list(set(dns_resolver)),
"disk_health": list(set(devices)),
"free_space": [{}],
"https_200": list(https_200),
"service_up": list({x if x!='' and x!='php5-fpm' else 'php7.0-fpm' for x in service_up}),
"backuped": list(backuped),
"__components__": apps,
}
def _get_devices():
devices = set()
for path in glob.glob('/sys/block/*/device/block/*/removable'):
disk_name = path.split('/')[3]
with open(path) as f:
if f.read(1) == '0':
devices.add(disk_name)
return list(devices)
# =============================================================================
# =============================================================================
# AUTOMATIC CONFIGURATION MODULES
# =============================================================================
# TODO automatic configuration module
# =============================================================================
# =============================================================================
# MONITOR PLUGINS
# =============================================================================
# IDEA Check size of mysql
# IDEA Check number of processus
# IDEA Check log
# IDEA check apt
# IDEA check average load
# IDEA Check no attack
def need_connection(func):
def wrapper(*args, **kwargs):
# Return no errors in case the monitoring server has no connection
if not IP.connected:
return []
return func(*args, **kwargs)
return wrapper
def run_on_monitored_server(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
cache = {}
# Remote checks
def check_ping(hostname, proto=['v4', 'v6']):
cmd = "timeout 4 ping -%s -c 1 -w 500 %s >/dev/null 2>&1"
errors = []
ip = {'v4': None, 'v6': None}
if hostname in check_ping.cache:
ip = check_ping.cache[hostname]
for protocol in proto:
if IP[protocol] and ip[protocol] is None:
ip[protocol] = any(os.system(cmd % (protocol[1:], hostname)) == 0 for retry in range(3))
check_ping.cache[hostname] = ip
target = {'domain': hostname}
if ip['v4'] == False and ip['v6'] == False and IP['v4'] and IP['v6']:
errors.append(('NO_PING', target))
elif ip['v4'] == False and IP['v4']:
errors.append(('NO_IPV4_PING', target))
elif ip['v6'] == False and IP['v6']:
errors.append(('NO_IPV6_PING', target))
return errors
check_ping.cache = {}
@need_connection
def check_ip_address(domain):
global cache
if domain not in cache:
# Find all ips configured for the domain of the URL
cache[domain] = {'v4': {}, 'v6': {}}
status, answers = dig(domain, 'A', resolvers="force_external")
if status == "ok":
cache[domain]['v4'] = {addr:{} for addr in answers}
status, answers = dig(domain, 'AAAA', resolvers="force_external")
if status == "ok":
cache[domain]['v6'] = {addr:{} for addr in answers}
addrs = cache[domain]
if not addrs['v4'] and not addrs['v6']:
return [('DOMAIN_UNCONFIGURED', {'domain': domain})]
if not (IP.v4 and addrs['v4']) and not (IP.v6 and addrs['v6']):
logging.warning('No connection, can\'t check HTTP')
# Error if no ip v4 address match with the domain
if not addrs['v4']:
return [('DOMAIN_MISCONFIGURED_IN_IPV4',
{'domain': domain})]
return []
@need_connection
def check_tls(domain, port=443):
global cache
errors = check_ip_address(domain)
to_report = {
'CERT_RENEWAL_FAILED': {'v4':{}, 'v6': {}},
'CERT_INVALID': {'v4':{}, 'v6': {}},
'PORT_CLOSED_OR_SERVICE_DOWN': {'v4':{}, 'v6': {}},
}
for protocol, addrs in cache[domain].items():
if not IP[protocol] or not addrs or check_ping(domain, [protocol]) != []:
continue
# Try to do the request for each ips
for addr, ports in addrs.items():
if port in ports:
continue
ports[443] = 'working'
# Check if TLS is working correctly
try:
cert = _get_cert_info(domain, addr)
notAfter = datetime.strptime(cert['notAfter'], '%b %d %H:%M:%S %Y %Z')
expire_in = notAfter - datetime.now()
if expire_in < timedelta(days_limit):
to_report['CERT_RENEWAL_FAILED'][protocol][addr] = {'remaining_days': expire_in.days}
except ssl.SSLError as e:
to_report['CERT_INVALID'][protocol][addr] = {'debug': str(e)}
ports[443] = 'notworking'
except (ConnectionError, socket.timeout) as e:
to_report['PORT_CLOSED_OR_SERVICE_DOWN'][protocol][addr] = {'debug': str(e)}
ports[443] = 'notworking'
except Exception as e:
pass
errors += _aggregate_report_by_target(to_report, domain,
{'domain': domain, 'port': port})
return errors
class MySSLContext(ssl.SSLContext):
def __new__(cls, server_hostname):
return super(MySSLContext, cls).__new__(cls, ssl.PROTOCOL_SSLv23)
def __init__(self, server_hostname):
super(MySSLContext, self).__init__(ssl.PROTOCOL_SSLv23)
self._my_server_hostname = server_hostname
def change_server_hostname(self, server_hostname):
self._my_server_hostname = server_hostname
def wrap_socket(self, *args, **kwargs):
kwargs['server_hostname'] = self._my_server_hostname
return super(MySSLContext, self).wrap_socket(*args, **kwargs)
@need_connection
def check_https_200(url):
global cache
# Find all ips configured for the domain of the URL
split_uri = url.split('/')
domain_port = split_uri[0].split(':')
domain = domain_port[0]
port = int(domain_port[1]) if len(domain_port) > 1 else 443
path = '/' + '/'.join(split_uri[1:]) if len(split_uri) > 1 else '/'
errors = check_tls(domain, port)
to_report = {msg: {'v4':{}, 'v6': {}} for msg in [
'CERT_INVALID',
'PORT_CLOSED_OR_SERVICE_DOWN',
'TIMEOUT',
'TOO_MANY_REDIRECTS',
'UNKNOWN_ERROR',
'SSO_CAPTURE'] + \
['HTTP_%d' % code for code in range(400, 499)] + \
['HTTP_%d' % code for code in range(500, 599)]
}
if not IP.v4 and not addrs['v6']:
logging.warning('No connection, can\'t check HTTP')
return []
for protocol, addrs in cache[domain].items():