Completed
Push — master ( 71e7de...cd3918 )
by Juan José
13s
created

ospd_openvas.nvticache.get_nvt_metadata()   C

Complexity

Conditions 9

Size

Total Lines 30
Code Lines 25

Duplication

Lines 30
Ratio 100 %

Importance

Changes 0
Metric Value
eloc 25
dl 30
loc 30
rs 6.6666
c 0
b 0
f 0
cc 9
nop 1
1
# -*- coding: utf-8 -*-
2
# Copyright (C) 2018 Greenbone Networks GmbH
3
#
4
# SPDX-License-Identifier: GPL-2.0-or-later
5
#
6
# This program is free software; you can redistribute it and/or
7
# modify it under the terms of the GNU General Public License
8
# as published by the Free Software Foundation; either version 2
9
# of the License, or (at your option) any later version.
10
#
11
# This program is distributed in the hope that it will be useful,
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
# GNU General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program; if not, write to the Free Software
18
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19
20
""" Provide functions to handle NVT Info Cache. """
21
22
import xml.etree.ElementTree as ET
23
from ospd_openvas.db import NVT_META_FIELDS
24
25
LIST_FIRST_POS = 0
26
LIST_LAST_POS = -1
27
28 View Code Duplication
class NVTICache(object):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
29
30
    QoD_TYPES = {
31
        'exploit': '100',
32
        'remote_vul': '99',
33
        'remote_app': '98',
34
        'package': '97',
35
        'registry': '97',
36
        'remote_active': '95',
37
        'remote_banner': '80',
38
        'executable_version': '80',
39
        'remote_analysis': '70',
40
        'remote_probe': '50',
41
        'remote_banner_unreliable': '30',
42
        'executable_version_unreliable': '30',
43
        'general_note': '1',
44
        'default': '70',
45
    }
46
47
    NVTICACHE_STR = 'nvticache1.0.0'
48
49
    def __init__(self, openvas_db):
50
        self._openvas_db = openvas_db
51
52
    def get_feed_version(self):
53
        """ Get feed version.
54
        """
55
        return self._openvas_db.get_single_item(self.NVTICACHE_STR)
56
57
    def get_oids(self):
58
        """ Get the list of NVT OIDs.
59
        """
60
        return self._openvas_db.get_elem_pattern_by_index('filename:*')
61
62
    def get_nvt_params(self, oid):
63
        """ Get NVT's preferences.
64
            @Return dictonary with preferences and timeout.
65
        """
66
        ctx = self._openvas_db.get_kb_context()
67
        prefs = self.get_nvt_prefs(ctx, oid)
68
        timeout = self.get_nvt_timeout(ctx, oid)
69
70
        vt_params = {}
71
        if int(timeout) > 0:
72
            vt_params['timeout'] = dict()
73
            vt_params['timeout']['type'] = 'entry'
74
            vt_params['timeout']['name'] = 'timeout'
75
            vt_params['timeout']['description'] = 'Script Timeout'
76
            vt_params['timeout']['default'] = timeout
77
78
        if prefs:
79
            for nvt_pref in prefs:
80
                elem = nvt_pref.split('|||')
81
                vt_params[elem[0]] = dict()
82
                vt_params[elem[0]]['type'] = elem[1]
83
                vt_params[elem[0]]['name'] = elem[0]
84
                vt_params[elem[0]]['description'] = 'Description'
85
                if elem[2]:
86
                    vt_params[elem[0]]['default'] = elem[2]
87
                else:
88
                    vt_params[elem[0]]['default'] = ''
89
90
        return vt_params
91
92
    @staticmethod
93
    def _parse_metadata_tags(tags_str):
94
        """ Parse a string with multiple tags.
95
96
        Arguments:
97
            tags_str (str) String with tags separated by `|`.
98
99
        Return a dictionary with the tags.
100
        """
101
        tags_dict = dict()
102
        tags = tags_str.split('|')
103
        for tag in tags:
104
            try:
105
                _tag, _value = tag.split('=', 1)
106
            except ValueError:
107
                logger.error('Tag %s in %s has no value.' % (_tag, oid))
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable oid does not seem to be defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable logger does not seem to be defined.
Loading history...
108
                continue
109
            tags_dict[_tag] = _value
110
111
        return tags_dict
112
113
    def get_nvt_metadata(self, oid):
114
        """ Get a full NVT. Returns an XML tree with the NVT metadata.
115
        """
116
        ctx = self._openvas_db.get_kb_context()
117
        resp = ctx.lrange("nvt:%s" % oid,
118
                          NVT_META_FIELDS.index("NVT_FILENAME_POS"),
119
                          NVT_META_FIELDS.index("NVT_NAME_POS"))
120
        if not isinstance(resp, list) or len(resp) == 0:
121
            return None
122
123
        subelem = ['filename', 'required_keys', 'mandatory_keys',
124
                   'excluded_keys', 'required_udp_ports', 'required_ports',
125
                   'dependencies', 'tag', 'cve', 'bid', 'xref', 'category',
126
                   'timeout', 'family', 'name', ]
127
128
        custom = dict()
129
        for child, res in zip(subelem, resp):
130
            if child not in ['cve', 'bid', 'xref', 'tag',] and res:
131
                custom[child] = res
132
            elif child == 'tag':
133
                custom.update(self._parse_metadata_tags(res))
134
135
        return custom
136
137
    def get_nvt_refs(self, oid):
138
        """ Get a full NVT. Returns an XML tree with the NVT references.
139
        """
140
        ctx = self._openvas_db.get_kb_context()
141
        resp = ctx.lrange("nvt:%s" % oid,
142
                          NVT_META_FIELDS.index("NVT_CVES_POS"),
143
                          NVT_META_FIELDS.index("NVT_XREFS_POS"))
144
        if not isinstance(resp, list) or len(resp) == 0:
145
            return None
146
147
        subelem = ['cve', 'bid', 'xref',]
148
149
        refs = dict()
150
        for child, res in zip(subelem, resp):
151
            refs[child] = res.split(", ")
152
153
        return refs
154
155
    def get_nvt_prefs(self, ctx, oid):
156
        """ Get NVT preferences. """
157
        key = 'oid:%s:prefs' % oid
158
        prefs = ctx.lrange(key, start=LIST_FIRST_POS,
159
                           end=LIST_LAST_POS)
160
        return prefs
161
162
    def get_nvt_timeout(self, ctx, oid):
163
        """ Get NVT timeout"""
164
        timeout = ctx.lindex('nvt:%s' % oid,
165
                             NVT_META_FIELDS.index("NVT_TIMEOUT_POS"))
166
        return timeout
167
168
    def get_nvt_tag(self, ctx, oid):
169
        """ Get a dictionary with the NVT Tags of the given OID."""
170
        tag = ctx.lindex('nvt:%s' % oid,
171
                          NVT_META_FIELDS.index('NVT_TAGS_POS'))
172
        tags = tag.split('|')
173
174
        return dict([item.split('=', 1) for item in tags])
175