-
Notifications
You must be signed in to change notification settings - Fork 3
/
check_gmp.py
1511 lines (1174 loc) · 47.8 KB
/
check_gmp.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
# -*- coding: utf-8 -*-
# GMP Nagios Command Plugin
#
# Description: A nagios command plugin for the Greenbone Management Protocol
#
# Authors:
# Raphael Grewe <[email protected]>
#
# Copyright:
# Copyright (C) 2017 Greenbone Networks GmbH
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import argparse
import logging
import os
import sys
import sqlite3
import tempfile
import signal
from argparse import RawTextHelpFormatter
from datetime import datetime
from lxml import etree
from gmp.gvm_connection import (SSHConnection,
TLSConnection,
UnixSocketConnection)
__version__ = '1.0.5'
logger = logging.getLogger(__name__)
help_text = """
Check-GMP Nagios Command Plugin {version} (C) 2017 Greenbone Networks GmbH
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
""".format(version=__version__)
NAGIOS_OK = 0
NAGIOS_WARNING = 1
NAGIOS_CRITICAL = 2
NAGIOS_UNKNOWN = 3
NAGIOS_MSG = ['OK', 'WARNING', 'CRITICAL', 'UNKNOWN']
MAX_RUNNING_INSTANCES = 10
global args
args = None
global conn
conn = None
global im
im = None
tmp_path = '%s/check_gmp/' % tempfile.gettempdir()
tmp_path_db = tmp_path + 'reports.db'
class InstanceManager:
'''Class that manage instances of this plugin
All new reports will be cached in a sqlite database.
The first call with a unknown host takes longer,
because the gvm has to generate the report.
Second call will retrieve the data from the database if the scanend
time not differs.
Addtionally this class handles all instances of check_gmp. No more than
MAX_RUNNING_INSTANCES can run simultaneously. Other instances are stopped
and wait for continuation.
'''
def __init__(self, path):
'''Initialise the sqlite database.
Create it if it does not exist else connect to it.
Arguments:
path {string} -- Path to the database
'''
self.cursor = None
self.con_db = None
self.path = path
self.pid = os.getpid()
# Try to read file with informations about cached reports
# First check whether the file exist or not
exist = os.path.isfile(path)
logger.debug('DB file exist?: %s ' % exist)
if not exist:
os.makedirs(os.path.dirname(path), exist_ok=True)
# Create the db file
open(path, 'a').close()
# Connect to db
self.connect_db()
# Create the tables
self.cursor.execute('''CREATE TABLE Report(
host text,
scan_end text,
params_used text,
report text
)''')
self.cursor.execute('''CREATE TABLE Instance(
created_at text,
pid integer,
pending integer default 0
)''')
logger.debug('Tables created')
else:
self.connect_db()
def connect_db(self):
'''Connect to the databse
Simply connect to the database at location <path>
'''
try:
logger.debug('connect db: %s' % self.path)
self.con_db = sqlite3.connect(self.path)
self.cursor = self.con_db.cursor()
logger.debug(sqlite3.sqlite_version)
except Exception as e:
logger.debug(e)
def close_db(self):
'''Close database
'''
self.con_db.close()
def set_host(self, host):
'''Sets the host variable
Arguments:
host {string} -- Given ip or hostname of target
'''
self.host = host
def old_report(self, last_scan_end, params_used):
'''Decide whether the current report is old or not
At first the last scanend and the params that were used are fetched
from the database. If no report is fetched, then True will be returned.
The next step is to compare the old and the new scanend.
If the scanends matches, then return False, because it is the same
report. Else the old report will be deleted.
Arguments:
last_scan_end {string} -- Last scan end of report
params_used {string} -- Params used for this check
Returns:
bool -- True: An old report or empty, False: It is the same report
'''
# Before we do anything here, check existing instance
# Retrieve the scan_end value
self.cursor.execute('SELECT scan_end, params_used FROM Report WHERE'
' host=?', (self.host,))
db_entry = self.cursor.fetchone()
logger.debug('%s %s' % (db_entry, last_scan_end))
if not db_entry:
return True
else:
old = parse_date(db_entry[0])
new = parse_date(last_scan_end)
logger.debug(
'Old time (from db): %s\n'
'New time (from rp): %s' % (old, new))
if new <= old and params_used == db_entry[1]:
return False
else:
# Report is newer. Delete old entry.
logger.debug('Delete old report for host %s' % self.host)
self.delete_report()
return True
def load_local_report(self):
'''Load report from local database
Select the report from the database according due the hostname or ip.
Returns:
[obj] -- lxml object
'''
self.cursor.execute(
'SELECT report FROM Report WHERE host=?', (self.host,))
db_entry = self.cursor.fetchone()
if db_entry:
return etree.fromstring(db_entry[0])
else:
logger.debug('Report from host %s is not in the db' % self.host)
def add_report(self, scan_end, params_used, report):
'''Create new entry with the lxml report
Create a string from the lxml object and add it to the database.
Additional data is the scanend and the params used.
Arguments:
scan_end {string} -- Scan end of the report
params_used {string} -- Params used for this check
report {obj} -- lxml object
'''
data = etree.tostring(report)
logger.debug(
'add_report: %s, %s, %s' % (self.host, scan_end, params_used))
# Insert values
self.cursor.execute('INSERT INTO Report VALUES (?, ?, ?, ?)',
(self.host, scan_end, params_used, data))
# Save the changes
self.con_db.commit()
def delete_report(self):
'''Delete report from database
'''
self.cursor.execute('DELETE FROM Report WHERE host=?', (self.host,))
# Save the changes
self.con_db.commit()
def delete_entry_with_ip(self, ip):
'''Delete report from database with given ip
Arguments:
ip {string} -- IP-Adress
'''
logger.debug('Delete entry with ip: %s' % ip)
self.cursor.execute('DELETE FROM Report WHERE host=?', (ip,))
self.cursor.execute('VACUUM')
# Save the changes
self.con_db.commit()
def delete_older_entries(self, days):
'''Delete reports from database older than given days
Arguments:
days {int} -- Number of days in past
'''
logger.debug('Delete entries older than: %s days' % days)
self.cursor.execute('DELETE FROM Report WHERE scan_end <= '
'date("now", "-%s day")' % days)
self.cursor.execute('VACUUM')
# Save the changes
self.con_db.commit()
def has_entries(self, pending):
'''Return number of instance entries
Return the number of pending or non pending instances entries.
'''
self.cursor.execute(
'SELECT count(*) FROM Instance WHERE pending=?', (pending,))
res = self.cursor.fetchone()
return res[0]
def check_instances(self):
'''This method check the status of check_gmp instances
Check whether instances are pending or not and start instances
according to the number saved in the MAX_RUNNING_INSTANCES variable.
'''
# Need to check whether any instances are in the database that were
# killed f.e. because a restart of nagios
self.clean_orphaned_instances()
# How many processes are currently running?
number_instances = self.has_entries(pending=0)
# How many pending entries are waiting?
number_pending_instances = self.has_entries(pending=1)
logger.debug('check_instances: %i %i' % (
number_instances, number_pending_instances))
if number_instances < MAX_RUNNING_INSTANCES and \
number_pending_instances == 0:
# Add entry for running process and go on
logger.debug('Fall 1')
self.add_instance(pending=0)
elif number_instances < MAX_RUNNING_INSTANCES and \
number_pending_instances > 0:
# Change pending entries and wake them up until enough instances
# are running
logger.debug('Fall 2')
while (number_instances < MAX_RUNNING_INSTANCES and
number_pending_instances > 0):
pending_entries = self.get_oldest_pending_entries(
MAX_RUNNING_INSTANCES - number_instances)
logger.debug('Oldest pending pids: %s' % (pending_entries))
for entry in pending_entries:
created_at = entry[0]
pid = entry[1]
# Change status to not pending and continue the process
self.update_pending_status(created_at, False)
self.start_process(pid)
# Refresh number of instances for next while loop
number_instances = self.has_entries(pending=0)
number_pending_instances = self.has_entries(pending=1)
# TODO: Check if this is really necessary
# self.add_instance(pending=0)
# if number_instances >= MAX_RUNNING_INSTANCES:
# self.stop_process(self.pid)
elif number_instances >= MAX_RUNNING_INSTANCES and \
number_pending_instances == 0:
# There are running enough instances and no pending instances
# Add new entry with pending status true and stop this instance
logger.debug('Fall 3')
self.add_instance(pending=1)
self.stop_process(self.pid)
elif number_instances >= MAX_RUNNING_INSTANCES and \
number_pending_instances > 0:
# There are running enough instances and there are min one
# pending instance
# Add new entry with pending true and stop this instance
logger.debug('Fall 4')
self.add_instance(pending=1)
self.stop_process(self.pid)
# If an entry is pending and the same params at another process is
# starting, then exit with gmp pending since data
# if self.has_pending_entries():
# Check if an pending entry is the same as this process
# If hostname
# date = datetime.now()
# end_session('GMP PENDING: since %s' % date, NAGIOS_OK)
# end_session('GMP RUNNING: since', NAGIOS_OK)
def add_instance(self, pending):
'''Add new instance entry to database
Retrieve the current time in ISO 8601 format. Create a new entry with
pending status and the dedicated pid
Arguments:
pending {int} -- State of instance
'''
current_time = datetime.now().isoformat()
# Insert values
self.cursor.execute('INSERT INTO Instance VALUES (?, ?, ?)',
(current_time, self.pid, pending))
# Save the changes
self.con_db.commit()
def get_oldest_pending_entries(self, number):
'''Return the oldest last entries of pending entries from database
Return the oldest instances with status pending limited by the variable
<number>
'''
self.cursor.execute('SELECT * FROM Instance WHERE pending=1 ORDER BY '
'created_at LIMIT ? ', (number,))
return self.cursor.fetchall()
def update_pending_status(self, date, status):
'''Update pending status of instance
The date variable works as a primary key for the instance table.
The entry with date get his pending status updated.
Arguments:
date {string} -- Date of creation for entry
status {int} -- Status of instance
'''
self.cursor.execute('UPDATE Instance SET pending=? WHERE created_at=?',
(status, date))
# Save the changes
self.con_db.commit()
def delete_instance(self, pid=0):
'''Delete instance from database
If a pid different from zero is given, then delete the entry with
given pid. Else delete the entry with the pid stored in this class
instance.
Keyword Arguments:
pid {number} -- Process Indentificattion Number (default: {0})
'''
if not pid:
pid = self.pid
logger.debug('Delete entry with pid: %i' % (pid))
self.cursor.execute('DELETE FROM Instance WHERE pid=?', (pid,))
# Save the changes
self.con_db.commit()
def clean_orphaned_instances(self):
'''Delete non existing instance entries
This method check whether a pid exist on the os and if not then delete
the orphaned entry from database.
'''
self.cursor.execute('SELECT pid FROM Instance')
pids = self.cursor.fetchall()
for pid in pids:
if not self.check_pid(pid[0]):
self.delete_instance(pid[0])
def wake_instance(self):
'''Wake up a pending instance
This method is called at the end of any session from check_gmp.
Get the oldest pending entries and wake them up.
'''
# How many processes are currently running?
number_instances = self.has_entries(pending=0)
# How many pending entries are waiting?
number_pending_instances = self.has_entries(pending=1)
if (number_instances < MAX_RUNNING_INSTANCES and
number_pending_instances > 0):
pending_entries = self.get_oldest_pending_entries(
MAX_RUNNING_INSTANCES - number_instances)
logger.debug('wake_instance: %i %i' % (
number_instances, number_pending_instances))
for entry in pending_entries:
created_at = entry[0]
pid = entry[1]
# Change status to not pending and continue the process
self.update_pending_status(created_at, False)
self.start_process(pid)
def start_process(self, pid):
'''Continue a stopped process
Send a continue signal to the process with given pid
Arguments:
pid {int} -- Process Identification Number
'''
logger.debug('Continue pid: %i' % (pid))
os.kill(pid, signal.SIGCONT)
def stop_process(self, pid):
'''Stop a running process
Send a stop signal to the process with given pid
Arguments:
pid {int} -- Process Identification Number
'''
os.kill(pid, signal.SIGSTOP)
def check_pid(self, pid):
'''Check for the existence of a process.
Arguments:
pid {int} -- Process Identification Number
'''
try:
os.kill(pid, 0)
except OSError:
return False
else:
return True
def main():
parser = argparse.ArgumentParser(
prog='check_gmp',
description=help_text,
formatter_class=RawTextHelpFormatter,
add_help=False,
epilog="""
usage: check_gmp [-h] [--version] [connection_type] ...
or: check_gmp connection_type --help""")
subparsers = parser.add_subparsers(metavar='[connection_type]')
subparsers.required = False
subparsers.dest = 'connection_type'
parser.add_argument(
'-h', '--help', action='help',
help='Show this help message and exit.')
parser.add_argument(
'-V', '--version', action='version',
version='%(prog)s {version}'.format(version=__version__),
help='Show program\'s version number and exit')
parser.add_argument(
'-I', '--max-running-instances', default=10, type=int,
help='Set the maximum simultaneous processes of check_gmp')
parser.add_argument(
'--cache', nargs='?', default=tmp_path_db,
help='Path to cache file. Default: %s.' % tmp_path_db)
parser.add_argument(
'--clean', action='store_true',
help='Activate to clean the database.')
group = parser.add_mutually_exclusive_group(required=False)
group.add_argument(
'--days', type=int, help='Delete database entries that are older than'
' given days.')
group.add_argument(
'--ip', help='Delete database entry for given ip.')
# TODO: Werror: Turn status UNKNOWN into status CRITICAL
parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.add_argument(
'-u', '--gmp-username', help='GMP username.', required=False)
parent_parser.add_argument(
'-w', '--gmp-password', help='GMP password.', required=False)
parent_parser.add_argument(
'-F', '--hostaddress', required=False, default='',
help='Report last report status of host <ip>.')
parent_parser.add_argument(
'-T', '--task', required=False,
help='Report status of task <task>.')
group = parent_parser.add_mutually_exclusive_group(required=False)
group.add_argument(
'--ping', action='store_true',
help='Ping the gsm appliance.')
group.add_argument(
'--status', action='store_true',
help='Report status of task.')
group = parent_parser.add_mutually_exclusive_group(required=False)
group.add_argument(
'--trend', action='store_true',
help='Report status by trend.')
group.add_argument(
'--last-report', action='store_true',
help='Report status by last report.')
parent_parser.add_argument(
'--apply-overrides', action='store_true',
help='Apply overrides.')
parent_parser.add_argument(
'--overrides', action='store_true',
help='Include overrides.')
parent_parser.add_argument(
'-d', '--details', action='store_true',
help='Include connection details in output.')
parent_parser.add_argument(
'-l', '--report-link', action='store_true',
help='Include URL of report in output.')
parent_parser.add_argument(
'--dfn', action='store_true',
help='Include DFN-CERT IDs on vulnerabilities in output.')
parent_parser.add_argument(
'--oid', action='store_true',
help='Include OIDs of NVTs finding vulnerabilities in output.')
parent_parser.add_argument(
'--descr', action='store_true',
help='Include descriptions of NVTs finding vulnerabilities in output.')
parent_parser.add_argument(
'--showlog', action='store_true',
help='Include log messages in output.')
parent_parser.add_argument(
'--show-ports', action='store_true',
help='Include port of given vulnerable nvt in output.')
parent_parser.add_argument(
'--scanend', action='store_true',
help='Include timestamp of scan end in output.')
parent_parser.add_argument(
'--autofp', type=int, choices=[0, 1, 2], default=0,
help='Trust vendor security updates for automatic false positive'
' filtering (0=No, 1=full match, 2=partial).')
parent_parser.add_argument(
'-e', '--empty-as-unknown', action='store_true',
help='Respond with UNKNOWN on empty results.')
parent_parser.add_argument(
'-A', '--use-asset-management', action='store_true',
help='Request host status via Asset Management.')
parser_ssh = subparsers.add_parser(
'ssh', help='Use SSH connection for gmp service.',
parents=[parent_parser])
parser_ssh.add_argument(
'--hostname', '-H', required=True, help='Hostname or IP-Address.')
parser_ssh.add_argument(
'--port', required=False, default=22, help='Port. Default: 22.')
parser_ssh.add_argument(
'--ssh-user', default='gmp', help='SSH Username. Default: gmp.')
parser_tls = subparsers.add_parser(
'tls', help='Use TLS secured connection for gmp service.',
parents=[parent_parser])
parser_tls.add_argument(
'--hostname', '-H', required=True, help='Hostname or IP-Address.')
parser_tls.add_argument(
'--port', required=False, default=9390, help='Port. Default: 9390.')
parser_socket = subparsers.add_parser(
'socket', help='Use UNIX-Socket connection for gmp service.',
parents=[parent_parser])
parser_socket.add_argument(
'--sockpath', nargs='?', default='/usr/local/var/run/openvasmd.sock',
help='UNIX-Socket path. Default: /usr/local/var/run/openvasmd.sock.')
# Set arguments that every parser should have
for p in [parser, parser_ssh, parser_socket, parser_tls]:
p.add_argument(
'--timeout', required=False, default=60, type=int,
help='Wait <seconds> for response. Default: 60')
p.add_argument(
'--log', nargs='?', dest='loglevel', const='INFO',
choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
help='Activates logging. Default level: INFO.')
global args
args = parser.parse_args()
# Set the max running instances variable
if args.max_running_instances:
global MAX_RUNNING_INSTANCES
MAX_RUNNING_INSTANCES = args.max_running_instances
# Sets the logging
if args.loglevel is not None:
# level = logging.getLevelName(args.loglevel)
logging.basicConfig(filename='check_gmp.log', level=args.loglevel)
# Set the report manager
global im
im = InstanceManager(args.cache)
# Check if command holds clean command
if args.clean:
if args.ip:
logger.info('Delete entry with ip %s' % args.ip)
im.delete_entry_with_ip(args.ip)
elif args.days:
logger.info('Delete entries older than %s days' % args.days)
im.delete_older_entries(args.days)
sys.exit(1)
# Set the host
im.set_host(args.hostaddress)
# Check if no more than 10 instances of check_gmp runs simultaneously
im.check_instances()
try:
global conn
conn = connect(args.hostname, args.port)
except Exception as e:
end_session('GMP CRITICAL: %s' % str(e), NAGIOS_CRITICAL)
if args.ping:
ping()
# Get the gmp version number, so i can choose the right functions
version = conn.get_version().xpath('version/text()')
if version:
version = float(version[0])
else:
version = 6.0
try:
conn.authenticate(args.gmp_username, args.gmp_password)
except Exception as e:
end_session('GMP CRITICAL: %s' % str(e), NAGIOS_CRITICAL)
if args.status:
status(version)
conn.close()
def connect(hostname, port):
'''Connect to gvm
According due the chosen connection type, this method will connect
to the manager.
Arguments:
hostname {string} -- Hostname or ip
port {int} -- Port
Returns:
GVMConnection -- Instance from GVMConnection class
'''
if 'socket' in args.connection_type:
try:
return UnixSocketConnection(
sockpath=args.sockpath, shell_mode=True, timeout=args.timeout)
except OSError as e:
end_session(
'GMP CRITICAL: %s: %s' %
(str(e), args.sockpath), NAGIOS_CRITICAL)
elif 'tls' in args.connection_type:
try:
return TLSConnection(hostname=args.hostname, port=args.port,
timeout=args.timeout, shell_mode=True)
except OSError as e:
end_session(
'GMP CRITICAL: %s: Host: %s Port: %s' %
(str(e), args.hostname, args.port), NAGIOS_CRITICAL)
elif 'ssh' in args.connection_type:
try:
return SSHConnection(hostname=args.hostname, port=args.port,
timeout=args.timeout, ssh_user=args.ssh_user,
ssh_password='', shell_mode=True)
except Exception as e:
end_session(
'GMP CRITICAL: %s: Host: %s Port: %s' %
(str(e), args.hostname, args.port), NAGIOS_CRITICAL)
def ping():
'''Checks for connectivity
This function sends the get_version command and checks whether the status
is ok or not.
'''
version = conn.get_version()
status = version.xpath('@status')
if '200' in status:
end_session('GMP OK: Ping successful', NAGIOS_OK)
else:
end_session('GMP CRITICAL: Machine dead?', NAGIOS_CRITICAL)
def status(version):
'''Returns the current status of a host
This functions return the current state of a host.
Either directly over the asset management or within a task.
For a task you can explicitly ask for the trend.
Otherwise the last report of the task will be filtered.
In the asset management the report id in the details is taken
as report for the filter.
If the asset information contains any vulnerabilities, then will the
report be filtered too. With additional parameters it is possible to add
more information about the vulnerabilities.
* DFN-Certs
* Logs
* Autofp
* Scanend
* Overrides
'''
params_used = 'task=%s autofp=%i overrides=%i apply_overrides=%i' \
% (args.task, args.autofp, int(args.overrides), int(args.apply_overrides))
if args.use_asset_management:
report = conn.get_reports(
type='assets', host=args.hostaddress,
filter='sort-reverse=id result_hosts_only=1 min_cvss_base= '
'min_qod= levels=hmlgd autofp=%s notes=0 apply_overrides=%s overrides=%s'
' first=1 rows=-1 delta_states=cgns'
% (args.autofp, int(args.apply_overrides), int(args.overrides)))
report_id = report.xpath(
'report/report/host/detail/name[text()="report/@id"]/../value/'
'text()')
last_scan_end = report.xpath('report/report/host/end/text()')
if last_scan_end:
last_scan_end = last_scan_end[0]
if report_id:
report_id = report_id[0]
else:
end_session('GMP UNKNOWN: Failed to get report_id'
' via Asset Management', NAGIOS_UNKNOWN)
low_count = int(report.xpath(
'report/report/host/detail/name[text()="report/result_count/'
'low"]/../value/text()')[0])
medium_count = int(report.xpath(
'report/report/host/detail/name[text()="report/result_count/'
'medium"]/../value/text()')[0])
high_count = int(report.xpath(
'report/report/host/detail/name[text()="report/result_count/'
'high"]/../value/text()')[0])
if medium_count + high_count == 0:
print('GMP OK: %i vulnerabilities found - High: 0 Medium: 0 '
'Low: %i' % (low_count, low_count))
if args.report_link:
print('https://%s/omp?cmd=get_report&report_id=%s' %
(args.hostname, report_id))
if args.scanend:
end = report.xpath('//end/text()')
if end:
end = end[0]
else:
end = 'Scan still in progress...'
print('SCAN_END: %s' % end)
end_session('|High=%i Medium=%i Low=%i' %
(high_count, medium_count, low_count), NAGIOS_OK)
else:
full_report = None
# if last_scan_end is newer then add the report to db
if im.old_report(last_scan_end, params_used):
levels = ''
autofp = ''
if not args.showlog:
levels = 'levels=hml'
if args.autofp:
autofp = 'autofp=%i' % args.autofp
full_report = conn.get_reports(
report_id=report_id,
filter='sort-reverse=id result_hosts_only=1 '
'min_cvss_base= min_qod= notes=0 apply_overrides=%s overrides=%s '
'first=1 rows=-1 delta_states=cgns %s %s =%s'
% (int(args.apply_overrides), int(args.overrides), autofp, levels,
args.hostaddress))
full_report = full_report.xpath('report/report')
if not full_report:
end_session('GMP UNKNOWN: Failed to get results list.',
NAGIOS_UNKNOWN)
full_report = full_report[0]
im.add_report(last_scan_end, params_used, full_report)
logger.debug('Report added to db')
else:
full_report = im.load_local_report()
filter_report(full_report)
if args.task:
task = conn.get_tasks(filter='permission=any owner=any rows=1 '
'name=\"%s\"' % args.task)
if args.trend:
trend = task.xpath('task/trend/text()')
if not trend:
end_session('GMP UNKNOWN: Trend is not available.',
NAGIOS_UNKNOWN)
trend = trend[0]
if trend in ['up', 'more']:
end_session(
'GMP CRITICAL: Trend is %s.' % trend, NAGIOS_CRITICAL)
elif trend in ['down', 'same', 'less']:
end_session(
'GMP OK: Trend is %s.' % trend, NAGIOS_OK)
else:
end_session(
'GMP UNKNOWN: Trend is unknown: %s' % trend,
NAGIOS_UNKNOWN)
else:
last_report_id = task.xpath('task/last_report/report/@id')
if not last_report_id:
end_session('GMP UNKNOWN: Report is not available',
NAGIOS_UNKNOWN)
last_report_id = last_report_id[0]
# pretty(task)
last_scan_end = task.xpath(
'task/last_report/report/scan_end/text()')
if last_scan_end:
last_scan_end = last_scan_end[0]
else:
last_scan_end = ''
if im.old_report(last_scan_end, params_used):
autofp = ''
if args.autofp:
autofp = 'autofp=%i' % args.autofp
# When i add the ip address in the filter by a big report with
# a lot vulns, then the filtering is quick. But when the
# report did not contain the host, then it takes a lot longer.
# I dont know why. I add a check for the result count.
# If > 500 then add the host else without host
#
# <debug>0</debug>
# <hole>413</hole>
# <info>380</info>
# <log>9490</log>
# <warning>2332</warning>
# <false_positive>842</false_positive>
result_count = task.xpath(
'task/last_report/report/result_count')
result_count = result_count[0]
# sum_results = result_count.xpath(
# 'sum(hole/text() | warning/text() | info/text())')
# host = ''
# Host must be setted, otherwise we get results of other hosts in the reports
# if sum_results > 200:
host = args.hostaddress
full_report = conn.get_reports(
report_id=last_report_id,
filter='sort-reverse=id result_hosts_only=1 '
'min_cvss_base= min_qod= levels=hmlgd autofp=%s '
'notes=0 apply_overrides=%s overrides=%s first=1 rows=-1 '
'delta_states=cgns host=%s'