Completed
Push — master ( 35711c...f569cf )
by Juan José
20s
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
# Description:
3
# Provide functions to handle NVT Info Cache
4
#
5
# Authors:
6
# Juan José Nicola <[email protected]>
7
#
8
# Copyright:
9
# Copyright (C) 2018 Greenbone Networks GmbH
10
#
11
# This program is free software; you can redistribute it and/or
12
# modify it under the terms of the GNU General Public License
13
# as published by the Free Software Foundation; either version 2
14
# of the License, or (at your option) any later version.
15
#
16
# This program is distributed in the hope that it will be useful,
17
# but WITHOUT ANY WARRANTY; without even the implied warranty of
18
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
# GNU General Public License for more details.
20
#
21
# You should have received a copy of the GNU General Public License
22
# along with this program; if not, write to the Free Software
23
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
24
25
""" Functions related to the NVT information. """
26
27
# Needed to say that when we import ospd, we mean the package and not the
28
# module in that directory.
29
from __future__ import absolute_import
30
from __future__ import print_function
31
32
import xml.etree.ElementTree as ET
0 ignored issues
show
Unused Code introduced by
Unused xml.etree.ElementTree imported as ET
Loading history...
33
import ospd_openvas.openvas_db as openvas_db
34
35
36
NVTICACHE_STR = 'nvticache1.0.0'
37
QoD_TYPES = {
0 ignored issues
show
Coding Style Naming introduced by
The name QoD_TYPES does not conform to the constant naming conventions ((([A-Z_][A-Z0-9_]*)|(__.*__))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
38
    'exploit': '100',
39
    'remote_vul': '99',
40
    'remote_app': '98',
41
    'package': '97',
42
    'registry': '97',
43
    'remote_active': '95',
44
    'remote_banner': '80',
45
    'executable_version': '80',
46
    'remote_analysis': '70',
47
    'remote_probe': '50',
48
    'remote_banner_unreliable': '30',
49
    'executable_version_unreliable': '30',
50
    'general_note': '1',
51
    'default': '70',
52
}
53
54
55
def get_feed_version():
56
    """ Get feed version.
57
    """
58
    return openvas_db.item_get_single(NVTICACHE_STR)
59
60
def get_oids():
61
    """ Get the list of NVT OIDs.
62
    """
63
    return openvas_db.get_elem_pattern_by_index('filename:*')
64
65 View Code Duplication
def get_nvt_params(oid):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
66
    """ Get NVT's preferences.
67
        @Return dictonary with preferences and timeout.
68
    """
69
    ctx = openvas_db.get_kb_context()
70
    prefs = get_nvt_prefs(ctx, oid)
71
    timeout = get_nvt_timeout(ctx, oid)
72
73
    vt_params = {}
74
    if int(timeout) > 0:
75
        vt_params['timeout'] = dict()
76
        vt_params['timeout']['type'] = 'entry'
77
        vt_params['timeout']['name'] = 'timeout'
78
        vt_params['timeout']['description'] = 'Script Timeout'
79
        vt_params['timeout']['default'] = timeout
80
81
    if prefs:
82
        for nvt_pref in prefs:
83
            elem = nvt_pref.split('|||')
84
            vt_params[elem[0]] = dict()
85
            vt_params[elem[0]]['type'] = elem[1]
86
            vt_params[elem[0]]['name'] = elem[0]
87
            vt_params[elem[0]]['description'] = 'Description'
88
            if elem[2]:
89
                vt_params[elem[0]]['default'] = elem[2]
90
            else:
91
                vt_params[elem[0]]['default'] = ''
92
93
    return vt_params
94
95 View Code Duplication
def get_nvt_metadata(oid):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
96
    """ Get a full NVT. Returns an XML tree with the NVT metadata.
97
    """
98
    ctx = openvas_db.get_kb_context()
99
    resp = ctx.lrange("nvt:%s" % oid,
100
                      openvas_db.nvt_meta_fields.index("NVT_FILENAME_POS"),
101
                      openvas_db.nvt_meta_fields.index("NVT_NAME_POS"))
102
    if (isinstance(resp, list) and resp) is False:
103
        return None
104
105
    subelem = ['file_name', 'required_keys', 'mandatory_keys',
106
               'excluded_keys', 'required_udp_ports', 'required_ports',
107
               'dependencies', 'tag', 'cve', 'bid', 'xref', 'category',
108
               'timeout', 'family', 'name', ]
109
110
    custom = dict()
111
    for child, res in zip(subelem, resp):
112
        if child not in ['cve', 'bid', 'xref', 'tag',] and res:
113
            custom[child] = res
114
        elif child == 'tag':
115
            tags = res.split('|')
116
            for tag in tags:
117
                try:
118
                    _tag, _value = tag.split('=', 1)
119
                except ValueError:
120
                    logger.error('Tag %s in %s has no value.' % (_tag, oid))
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable logger does not seem to be defined.
Loading history...
Comprehensibility Best Practice introduced by
Undefined variable 'logger'
Loading history...
121
                    continue
122
                custom[_tag] = _value
123
124
    return custom
125
126 View Code Duplication
def get_nvt_refs(oid):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
127
    """ Get a full NVT. Returns an XML tree with the NVT references.
128
    """
129
    ctx = openvas_db.get_kb_context()
130
    resp = ctx.lrange("nvt:%s" % oid,
131
                      openvas_db.nvt_meta_fields.index("NVT_CVES_POS"),
132
                      openvas_db.nvt_meta_fields.index("NVT_XREFS_POS"))
133
    if (isinstance(resp, list) and resp) is False:
134
        return None
135
136
    subelem = ['cve', 'bid', 'xref',]
137
138
    refs = dict()
139
    for child, res in zip(subelem, resp):
140
        refs[child] = res.split(", ")
141
142
    return refs
143
144
def get_nvt_name(ctx, oid):
145
    """ Get the NVT name of the given OID."""
146
    return ctx.lindex('nvt:%s' % oid,
147
                      openvas_db.nvt_meta_fields.index('NVT_NAME_POS'))
148
149
def get_nvt_family(ctx, oid):
150
    """ Get the NVT family of the given OID."""
151
    return ctx.lindex('nvt:%s' % oid,
152
                      openvas_db.nvt_meta_fields.index('NVT_FAMILY_POS'))
153
154
def get_nvt_prefs(ctx, oid):
155
    """ Get NVT preferences. """
156
    prefs = ctx.smembers('oid:%s:prefs' % oid)
157
    return prefs
158
159
def get_nvt_timeout(ctx, oid):
160
    """ Get NVT timeout"""
161
    timeout = ctx.lindex('nvt:%s' % oid,
162
                         openvas_db.nvt_meta_fields.index("NVT_TIMEOUT_POS"))
163
    return timeout
164
165
def get_nvt_tag(ctx, oid):
166
    """ Get a dictionary with the NVT Tags of the given OID."""
167
    tag = ctx.lindex('nvt:%s' % oid,
168
                      openvas_db.nvt_meta_fields.index('NVT_TAGS_POS'))
0 ignored issues
show
Coding Style introduced by
Wrong continued indentation (remove 1 space).
Loading history...
169
    tags = tag.split('|')
170
171
    return dict([item.split('=', 1) for item in tags])
172
173 View Code Duplication
def get_nvt_qod(ctx, tag=None, oid=None):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
174
    """ Get the NVT QoD from a tag or from the given OID.
175
    @in tag A dictionary with the NVT tags
176
    @in oid The NVT OID
177
    @return QoD value as string.
178
    """
179
    if not tag:
180
        if oid:
181
            tag = get_nvt_tag(ctx, oid)
182
        else:
183
            return 0
184
185
    if tag and 'qod_type' in tag:
186
        qodtype = tag['qod_type']
187
        return QoD_TYPES[qodtype]
188
    elif tag and 'qod' in tag:
189
        return tag['qod']
190
191
    return QoD_TYPES['default']
192
193 View Code Duplication
def get_nvt_severity(ctx, tag=None, oid=None):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
194
    """ Get the NVT Severity from a tag or from the given OID.
195
    @in tag A dictionary with the NVT tags
196
    @in oid The NVT OID
197
    @return Severity (cvess_base) value as string.
198
199
    """
200
    if not tag:
201
        if oid:
202
            tag = get_nvt_tag(ctx, oid)
203
        else:
204
            return '10'
205
206
    if tag and 'cvss_base' in tag:
207
        return tag['cvss_base']
208
209
    return ''
210