-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathdb.py
698 lines (555 loc) · 21.5 KB
/
db.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
# -*- coding: utf-8 -*-
# SPDX-FileCopyrightText: 2014-2023 Greenbone AG
#
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Access management for redis-based OpenVAS Scanner Database."""
import logging
import sys
import time
from typing import List, NewType, Optional, Iterable, Iterator, Tuple, Callable
from urllib import parse
import redis
from ospd.errors import RequiredArgument
from ospd_openvas.errors import OspdOpenvasError
from ospd_openvas.openvas import Openvas
SOCKET_TIMEOUT = 60 # in seconds
LIST_FIRST_POS = 0
LIST_LAST_POS = -1
LIST_ALL = 0
# Possible positions of nvt values in cache list.
NVT_META_FIELDS = [
"NVT_FILENAME_POS",
"NVT_REQUIRED_KEYS_POS",
"NVT_MANDATORY_KEYS_POS",
"NVT_EXCLUDED_KEYS_POS",
"NVT_REQUIRED_UDP_PORTS_POS",
"NVT_REQUIRED_PORTS_POS",
"NVT_DEPENDENCIES_POS",
"NVT_TAGS_POS",
"NVT_CVES_POS",
"NVT_BIDS_POS",
"NVT_XREFS_POS",
"NVT_CATEGORY_POS",
"NVT_FAMILY_POS",
"NVT_NAME_POS",
]
# Name of the namespace usage bitmap in redis.
DBINDEX_NAME = "GVM.__GlobalDBIndex"
logger = logging.getLogger(__name__)
# Types
RedisCtx = NewType('RedisCtx', redis.Redis)
class OpenvasDB:
"""Class to connect to redis, to perform queries, and to move
from a KB to another."""
_db_address = None
@classmethod
def get_database_address(cls) -> Optional[str]:
if not cls._db_address:
if not Openvas.check():
logger.error(
'openvas executable not available. Please install openvas'
' into your PATH.'
)
sys.exit(1)
settings = Openvas.get_settings()
cls._db_address = settings.get('db_address')
if cls._db_address:
# translate openvas tcp:// configuration to redis://
cls._db_address = cls._db_address.replace("tcp://", "redis://")
# translate non scheme to unix://
if not parse.urlparse(cls._db_address).scheme:
cls._db_address = "unix://" + cls._db_address
if cls._db_address.startswith("redis://"):
logger.warning(
"A Redis TCP connection is being used. "
"This feature is experimental and insecure. "
"It is not recommended in production environments."
)
return cls._db_address
@classmethod
def create_context(
cls, dbnum: int = 0, encoding: str = 'latin-1'
) -> RedisCtx:
"""Connect to redis to the given database or to the default db 0 .
Arguments:
dbnum: The db number to connect to.
encoding: The encoding to be used to read and write.
Return a new redis context on success.
"""
tries = 5
while tries:
try:
ctx = redis.Redis.from_url(
url=cls.get_database_address(),
db=dbnum,
socket_timeout=SOCKET_TIMEOUT,
encoding=encoding,
decode_responses=True,
)
ctx.keys("test")
except (redis.exceptions.ConnectionError, FileNotFoundError) as err:
logger.debug(
'Redis connection lost: %s. Trying again in 5 seconds.', err
)
tries = tries - 1
time.sleep(5)
continue
break
if not tries:
logger.error('Redis Error: Not possible to connect to the kb.')
sys.exit(1)
return ctx
@classmethod
def find_database_by_pattern(
cls, pattern: str, max_database_index: int
) -> Tuple[Optional[RedisCtx], Optional[int]]:
"""Search a pattern inside all kbs up to max_database_index.
Returns the redis context for the db and its index as a tuple or
None, None if the db with the pattern couldn't be found.
"""
for i in range(0, max_database_index):
ctx = cls.create_context(i)
if ctx.keys(pattern):
return (ctx, i)
return (None, None)
@staticmethod
def select_database(ctx: RedisCtx, kbindex: str):
"""Use an existent redis connection and select a redis kb.
Arguments:
ctx: Redis context to use.
kbindex: The new kb to select
"""
if not ctx:
raise RequiredArgument('select_database', 'ctx')
if not kbindex:
raise RequiredArgument('select_database', 'kbindex')
ctx.execute_command('SELECT ' + str(kbindex))
@staticmethod
def get_list_item(
ctx: RedisCtx,
name: str,
start: Optional[int] = LIST_FIRST_POS,
end: Optional[int] = LIST_LAST_POS,
) -> Optional[list]:
"""Returns the specified elements from `start` to `end` of the
list stored as `name`.
Arguments:
ctx: Redis context to use.
name: key name of a list.
start: first range element to get.
end: last range element to get.
Return List specified elements in the key.
"""
if not ctx:
raise RequiredArgument('get_list_item', 'ctx')
if not name:
raise RequiredArgument('get_list_item', 'name')
return ctx.lrange(name, start, end)
@staticmethod
def get_last_list_item(ctx: RedisCtx, name: str) -> str:
if not ctx:
raise RequiredArgument('get_last_list_item', 'ctx')
if not name:
raise RequiredArgument('get_last_list_item', 'name')
return ctx.rpop(name)
@staticmethod
def pop_list_items(ctx: RedisCtx, name: str) -> List[str]:
if not ctx:
raise RequiredArgument('pop_list_items', 'ctx')
if not name:
raise RequiredArgument('pop_list_items', 'name')
pipe = ctx.pipeline()
pipe.lrange(name, LIST_FIRST_POS, LIST_LAST_POS)
pipe.delete(name)
results, redis_return_code = pipe.execute()
# The results are left-pushed. To preserver the order
# the result list must be reversed.
if redis_return_code:
results.reverse()
else:
results = []
return results
@staticmethod
def get_key_count(ctx: RedisCtx, pattern: Optional[str] = None) -> int:
"""Get the number of keys matching with the pattern.
Arguments:
ctx: Redis context to use.
pattern: pattern used as filter.
"""
if not pattern:
pattern = "*"
if not ctx:
raise RequiredArgument('get_key_count', 'ctx')
return len(ctx.keys(pattern))
@staticmethod
def remove_list_item(ctx: RedisCtx, key: str, value: str):
"""Remove item from the key list.
Arguments:
ctx: Redis context to use.
key: key name of a list.
value: Value to be removed from the key.
"""
if not ctx:
raise RequiredArgument('remove_list_item ', 'ctx')
if not key:
raise RequiredArgument('remove_list_item', 'key')
if not value:
raise RequiredArgument('remove_list_item ', 'value')
ctx.lrem(key, count=LIST_ALL, value=value)
@staticmethod
def get_single_item(
ctx: RedisCtx,
name: str,
index: Optional[int] = LIST_FIRST_POS,
) -> Optional[str]:
"""Get a single KB element.
Arguments:
ctx: Redis context to use.
name: key name of a list.
index: index of the element to be return.
Defaults to the first element in the list.
Return the first element of the list or None if the name couldn't be
found.
"""
if not ctx:
raise RequiredArgument('get_single_item', 'ctx')
if not name:
raise RequiredArgument('get_single_item', 'name')
return ctx.lindex(name, index)
@staticmethod
def add_single_list(ctx: RedisCtx, name: str, values: Iterable):
"""Add a single KB element with one or more values.
The values can be repeated. If the key already exists will
be removed an completely replaced.
Arguments:
ctx: Redis context to use.
name: key name of a list.
value: Elements to add to the key.
"""
if not ctx:
raise RequiredArgument('add_single_list', 'ctx')
if not name:
raise RequiredArgument('add_single_list', 'name')
if not values:
raise RequiredArgument('add_single_list', 'value')
pipe = ctx.pipeline()
pipe.delete(name)
pipe.rpush(name, *values)
pipe.execute()
@staticmethod
def add_single_item(
ctx: RedisCtx, name: str, values: Iterable, lpush: bool = False
):
"""Add a single KB element with one or more values. Don't add
duplicated values during this operation, but if the the same
values already exists under the key, this will not be overwritten.
Arguments:
ctx: Redis context to use.
name: key name of a list.
value: Elements to add to the key.
"""
if not ctx:
raise RequiredArgument('add_single_item', 'ctx')
if not name:
raise RequiredArgument('add_single_item', 'name')
if not values:
raise RequiredArgument('add_single_item', 'value')
if lpush:
ctx.lpush(name, *set(values))
return
ctx.rpush(name, *set(values))
@staticmethod
def set_single_item(ctx: RedisCtx, name: str, value: Iterable):
"""Set (replace) a single KB element. If the same key exists
in the kb, it is completed removed. Values added are unique.
Arguments:
ctx: Redis context to use.
name: key name of a list.
value: New elements to add to the key.
"""
if not ctx:
raise RequiredArgument('set_single_item', 'ctx')
if not name:
raise RequiredArgument('set_single_item', 'name')
if not value:
raise RequiredArgument('set_single_item', 'value')
pipe = ctx.pipeline()
pipe.delete(name)
pipe.rpush(name, *set(value))
pipe.execute()
@staticmethod
def get_pattern(ctx: RedisCtx, pattern: str) -> List:
"""Get all items stored under a given pattern.
Arguments:
ctx: Redis context to use.
pattern: key pattern to match.
Return a list with the elements under the matched key.
"""
if not ctx:
raise RequiredArgument('get_pattern', 'ctx')
if not pattern:
raise RequiredArgument('get_pattern', 'pattern')
items = ctx.keys(pattern)
elem_list = []
for item in items:
elem_list.append(
[
item,
ctx.lrange(item, start=LIST_FIRST_POS, end=LIST_LAST_POS),
]
)
return elem_list
@classmethod
def get_keys_by_pattern(cls, ctx: RedisCtx, pattern: str) -> List[str]:
"""Get all items with index 'index', stored under
a given pattern.
Arguments:
ctx: Redis context to use.
pattern: key pattern to match.
Return a sorted list with the elements under the matched key
"""
if not ctx:
raise RequiredArgument('get_elem_pattern_by_index', 'ctx')
if not pattern:
raise RequiredArgument('get_elem_pattern_by_index', 'pattern')
return sorted(ctx.keys(pattern))
@classmethod
def get_filenames_and_oids(
cls, ctx: RedisCtx, pattern: str, parser: Callable[[str], str]
) -> Iterable[Tuple[str, str]]:
"""Get all items with index 'index', stored under
a given pattern.
Arguments:
ctx: Redis context to use.
pattern: Pattern used for searching the keys
parser: Callable method to remove the pattern from the keys.
Return an iterable where each single tuple contains the filename
as first element and the oid as the second one.
"""
if not ctx:
raise RequiredArgument('get_filenames_and_oids', 'ctx')
if not pattern:
raise RequiredArgument('get_filenames_and_oids', 'pattern')
if not parser:
raise RequiredArgument('get_filenames_and_oids', 'parser')
items = cls.get_keys_by_pattern(ctx, pattern)
return ((ctx.lindex(item, 0), parser(item)) for item in items)
@staticmethod
def exists(ctx: RedisCtx, key: str) -> bool:
"""Check that the given key exists in the given context.
Arguments:
ctx: Redis context to use.
patternkey: key to check.
Return a True if exists, False otherwise.
"""
if not ctx:
raise RequiredArgument('exists', 'ctx')
return ctx.exists(key) == 1
class BaseDB:
def __init__(self, kbindex: int, ctx: Optional[RedisCtx] = None):
if ctx is None:
self.ctx = OpenvasDB.create_context(kbindex)
else:
self.ctx = ctx
self.index = kbindex
def flush(self):
"""Flush the database"""
self.ctx.flushdb()
class BaseKbDB(BaseDB):
def _add_single_item(
self, name: str, values: Iterable, utf8_enc: Optional[bool] = False
):
"""Changing the encoding format of an existing redis context
is not possible. Therefore a new temporary redis context is
created to store key-values encoded with utf-8."""
if utf8_enc:
ctx = OpenvasDB.create_context(self.index, encoding='utf-8')
OpenvasDB.add_single_item(ctx, name, values)
else:
OpenvasDB.add_single_item(self.ctx, name, values)
def _set_single_item(self, name: str, value: Iterable):
"""Set (replace) a single KB element.
Arguments:
name: key name of a list.
value: New elements to add to the key.
"""
OpenvasDB.set_single_item(self.ctx, name, value)
def _get_single_item(self, name: str) -> Optional[str]:
"""Get a single KB element.
Arguments:
name: key name of a list.
"""
return OpenvasDB.get_single_item(self.ctx, name)
def _get_list_item(
self,
name: str,
) -> Optional[List]:
"""Returns the specified elements from `start` to `end` of the
list stored as `name`.
Arguments:
name: key name of a list.
Return List specified elements in the key.
"""
return OpenvasDB.get_list_item(self.ctx, name)
def _pop_list_items(self, name: str) -> List:
return OpenvasDB.pop_list_items(self.ctx, name)
def _remove_list_item(self, key: str, value: str):
"""Remove item from the key list.
Arguments:
key: key name of a list.
value: Value to be removed from the key.
"""
OpenvasDB.remove_list_item(self.ctx, key, value)
def get_result(self) -> Optional[str]:
"""Get and remove the oldest result from the list.
Return the oldest scan results
"""
return self._pop_list_items("internal/results")
def get_status(self, openvas_scan_id: str) -> Optional[str]:
"""Return the status of the host scan"""
return self._get_single_item(f'internal/{openvas_scan_id}')
def __repr__(self):
return f'<{self.__class__.__name__} index={self.index}>'
class ScanDB(BaseKbDB):
"""Database for a scanning a single host"""
def select(self, kbindex: int) -> "ScanDB":
"""Select a redis kb.
Arguments:
kbindex: The new kb to select
"""
OpenvasDB.select_database(self.ctx, kbindex)
self.index = kbindex
return self
class KbDB(BaseKbDB):
def get_scan_databases(self) -> Iterator[ScanDB]:
"""Returns an iterator yielding corresponding ScanDBs
The returned Iterator can't be converted to an Iterable like a List.
Each yielded ScanDB must be used independently in a for loop. If the
Iterator gets converted into an Iterable all returned ScanDBs will use
the same redis context pointing to the same redis database.
"""
dbs = self._get_list_item('internal/dbindex')
scan_db = ScanDB(self.index)
for kbindex in dbs:
if kbindex == self.index:
continue
yield scan_db.select(kbindex)
def add_scan_id(self, scan_id: str):
self._add_single_item(f'internal/{scan_id}', ['new'])
self._add_single_item('internal/scanid', [scan_id])
def add_scan_preferences(self, openvas_scan_id: str, preferences: Iterable):
self._add_single_item(
f'internal/{openvas_scan_id}/scanprefs', preferences
)
def add_credentials_to_scan_preferences(
self, openvas_scan_id: str, preferences: Iterable
):
"""Force the usage of the utf-8 encoding, since some credentials
contain special chars not supported by latin-1 encoding."""
self._add_single_item(
f'internal/{openvas_scan_id}/scanprefs',
preferences,
utf8_enc=True,
)
def add_scan_process_id(self, pid: int):
self._add_single_item('internal/ovas_pid', [pid])
def get_scan_process_id(self) -> Optional[str]:
return self._get_single_item('internal/ovas_pid')
def remove_scan_database(self, scan_db: ScanDB):
self._remove_list_item('internal/dbindex', scan_db.index)
def target_is_finished(self, scan_id: str) -> bool:
"""Check if a target has finished."""
status = self._get_single_item(f'internal/{scan_id}')
if status is None:
logger.error(
"%s: Target set as finished because redis returned None as "
"scanner status.",
scan_id,
)
return status == 'finished' or status is None
def stop_scan(self, openvas_scan_id: str):
self._set_single_item(f'internal/{openvas_scan_id}', ['stop_all'])
def scan_is_stopped(self, scan_id: str) -> bool:
"""Check if the scan should be stopped"""
status = self._get_single_item(f'internal/{scan_id}')
return status == 'stop_all'
def get_scan_status(self) -> List:
"""Get and remove the oldest host scan status from the list.
Return a string which represents the host scan status.
"""
return self._pop_list_items("internal/status")
class MainDB(BaseDB):
"""Main Database"""
DEFAULT_INDEX = 0
def __init__(self, ctx=None):
super().__init__(self.DEFAULT_INDEX, ctx)
self._max_dbindex = None
@property
def max_database_index(self):
"""Set the number of databases have been configured into kbr struct."""
if self._max_dbindex is None:
resp = self.ctx.config_get('databases')
if len(resp) == 1:
self._max_dbindex = int(resp.get('databases'))
else:
raise OspdOpenvasError(
'Redis Error: Not possible to get max_dbindex.'
) from None
return self._max_dbindex
def try_database(self, index: int) -> bool:
"""Check if a redis db is already in use. If not, set it
as in use and return.
Arguments:
ctx: Redis object connected to the kb with the
DBINDEX_NAME key.
index: Number intended to be used.
Return True if it is possible to use the db. False if the given db
number is already in use.
"""
_in_use = 1
try:
resp = self.ctx.hsetnx(DBINDEX_NAME, index, _in_use)
except:
raise OspdOpenvasError(
f'Redis Error: Not possible to set {DBINDEX_NAME}.'
) from None
return resp == 1
def get_new_kb_database(self) -> Optional[KbDB]:
"""Return a new kb db to an empty kb."""
for index in range(1, self.max_database_index):
if self.try_database(index):
kbdb = KbDB(index)
kbdb.flush()
return kbdb
return None
def find_kb_database_by_scan_id(
self, scan_id: str
) -> Tuple[Optional[str], Optional["KbDB"]]:
"""Find a kb db by via a scan id"""
for index in range(1, self.max_database_index):
ctx = OpenvasDB.create_context(index)
if OpenvasDB.get_key_count(ctx, f'internal/{scan_id}'):
return KbDB(index, ctx)
return None
def check_consistency(self, scan_id) -> Tuple[Optional[KbDB], int]:
"""Check if the current scan id already exists in a kb.
Return a tuple with the kb or none, and an error code, being 0 if
the db is clean, -1 on old finished scan, -2 on still running scan.
"""
err = 0
kb = self.find_kb_database_by_scan_id(scan_id)
current_status = None
if kb:
current_status = kb.get_status(scan_id)
if current_status == "finished":
err = -1
elif current_status == "stop_all" or current_status == "ready":
err = -2
return (kb, err)
def release_database(self, database: BaseDB):
self.release_database_by_index(database.index)
database.flush()
def release_database_by_index(self, index: int):
self.ctx.hdel(DBINDEX_NAME, index)
def release(self):
self.release_database(self)