Completed
Push — master ( f07019...0c998d )
by
unknown
18s queued 13s
created

start-alert-scan.gmp.check_args()   A

Complexity

Conditions 2

Size

Total Lines 16
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nop 1
dl 0
loc 16
rs 10
c 0
b 0
f 0
1
# -*- coding: utf-8 -*-
2
# Copyright (C) 2018 Henning Häcker
3
#
4
# SPDX-License-Identifier: GPL-3.0-or-later
5
#
6
# This program is free software: you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation, either version 3 of the License, or
9
# (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, see <http://www.gnu.org/licenses/>.
18
19
20
def check_args(args):
21
    len_args = len(args.script) - 1
22
    message = """
23
        This script makes an alert scan.
24
        It needs two parameters after the script name.
25
26
        1. <sender_email>     -- E-Mail of the sender
27
        2. <receiver_email>   -- E-Mail of the receiver
28
        
29
        Example:
30
            $ gvm-script --gmp-username name --gmp-password pass \
31
ssh --hostname <gsm> scripts/start-alert-scan.gmp.py <sender_email> <receiver_email>
32
    """
33
    if len_args != 2:
34
        print(message)
35
        quit()
36
37
38
# returns a list containing all port_list names
39
def get_port_list_names(gmp):
40
    res = gmp.get_port_lists()
41
    port_names_list = [""]
42
    for name in res.findall("port_list/name"):
43
        port_names_list.append(str(name.text))
44
    return port_names_list
45
46
47 View Code Duplication
def get_config(gmp, debug=False):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
48
    # get all configs of the openvas instance
49
    res = gmp.get_configs()
50
51
    # configurable template
52
    template = "fast"
53
54
    # match the config abbreviation to accepted config names
55
    config_list = [
56
        'Full and fast',
57
        'Full and fast ultimate',
58
        'Full and very deep',
59
        'Full and very deep ultimate',
60
        'System Discovery',
61
    ]
62
    template_abbreviation_mapper = {
63
        "fast": config_list[0],
64
        "fast-ulti": config_list[1],
65
        "deep": config_list[2],
66
        "deep-ulti": config_list[3],
67
        "discovery": config_list[4],
68
    }
69
70
    config_id = "-"
71
    for conf in res.xpath('config'):
72
        cid = conf.xpath('@id')[0]
73
        name = conf.xpath('name/text()')[0]
74
75
        # get the config id of the desired template
76
        if template_abbreviation_mapper.get(template, "-") == name:
77
            config_id = cid
78
            if debug:
79
                print(name + ": " + config_id)
80
            break
81
82
    # check for existence of the desired config
83
    if config_id == "-":
84
        print(
85
            "error: could not recognize template '%s'"
86
            "\nvalid template names are: %s\n" % (template, config_list)
87
        )
88
        exit()
89
90
    return config_id
91
92
93
def get_target(gmp, debug=False):
94
    # find a targetName
95
    targets = gmp.get_targets()
96
    counter = 0
97
    exists = True
98
    # iterate over existing targets and find a vacant targetName
99
    while exists:
100
        exists = False
101
        target_name = "targetName" + str(counter)
102
        for target in targets.xpath('target'):
103
            name = target.xpath('name/text()')[0]
104
            if name == target_name:
105
                exists = True
106
                break
107
        counter += 1
108
109
    if debug:
110
        print("target name: " + target_name)
0 ignored issues
show
introduced by
The variable target_name does not seem to be defined in case the while loop on line 99 is not entered. Are you sure this can never be the case?
Loading history...
111
112
    # iterate over existing port lists and find a vacant name
113
    new_port_list_name = "portlistName"
114
    counter = 0
115
    while True:
116
        portlist_name = str(new_port_list_name + str(counter))
117
        if portlist_name not in get_port_list_names(gmp):
118
            break
119
        counter += 1
120
121
    # configurable port string
122
    port_string = "T:80-80"
123
    # create port list
124
    portlist = gmp.create_port_list(portlist_name, port_string)
125
    portlist_id = portlist.xpath('@id')[0]
126
    if debug:
127
        print("Portlist-name:\t" + str(portlist_name))
128
        print("Portlist-id:\t" + str(portlist_id))
129
130
    # configurable hosts
131
    hosts = ["localhost"]
132
133
    # integrate port list id into create_target
134
    res = gmp.create_target(target_name, hosts=hosts, port_list_id=portlist_id)
135
    return res.xpath('@id')[0]
136
137
138
def get_alert(gmp, sender_email, recipient_email, debug=False):
139
    # configurable alert name
140
    alert_name = recipient_email
141
142
    # create alert if necessary
143
    alert_object = gmp.get_alerts(filter='name=%s' % alert_name)
144
    alert_id = None
145
    alert = alert_object.xpath('alert')
146
147 View Code Duplication
    if len(alert) == 0:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
148
        print("creating alert")
149
        gmp.create_alert(
150
            alert_name,
151
            event=gmp.types.AlertEvent.TASK_RUN_STATUS_CHANGED,
152
            event_data={"status": "Done"},
153
            condition=gmp.types.AlertCondition.ALWAYS,
154
            method=gmp.types.AlertMethod.EMAIL,
155
            method_data={
156
                """Task '$n': $e
157
158
After the event $e,
159
the following condition was met: $c
160
161
This email escalation is configured to attach report format '$r'.
162
Full details and other report formats are available on the scan engine.
163
164
$t
165
166
Note:
167
This email was sent to you as a configured security scan escalation.
168
Please contact your local system administrator if you think you
169
should not have received it.
170
""": "message",
171
                "2": "notice",
172
                sender_email: "from_address",
173
                "[OpenVAS-Manager] Task": "subject",
174
                "c402cc3e-b531-11e1-9163-406186ea4fc5": "notice_attach_format",
175
                recipient_email: "to_address",
176
            },
177
        )
178
179
        alert_object = gmp.get_alerts(filter='name=%s' % recipient_email)
180
        alert = alert_object.xpath('alert')
181
        alert_id = alert[0].get('id', 'no id found')
182
    else:
183
        alert_id = alert[0].get('id', 'no id found')
184
        if debug:
185
            print("alert_id: " + str(alert_id))
186
187
    return alert_id
188
189
190
def get_scanner(gmp):
191
    res = gmp.get_scanners()
192
    scanner_ids = res.xpath('scanner/@id')
193
    return scanner_ids[1]  # default scanner
194
195
196 View Code Duplication
def create_and_start_task(
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
197
    gmp, config_id, target_id, scanner_id, alert_id, debug=False
198
):
199
    # Create the task
200
    tasks = gmp.get_tasks(filter="name~ScanDoneAlert")
201
    task_name = "ScanDoneAlert{0}".format(len(tasks.xpath('tasks/@id')))
202
    task_comment = "Scan Done Alert"
203
    res = gmp.create_task(
204
        task_name,
205
        config_id,
206
        target_id,
207
        scanner_id,
208
        alert_ids=[alert_id],
209
        comment=task_comment,
210
    )
211
212
    # Start the task
213
    task_id = res.xpath('@id')[0]
214
    gmp.start_task(task_id)
215
216
    print('Task started: ' + task_name)
217
218
    if debug:
219
        # Stop the task (for performance reasons)
220
        gmp.stop_task(task_id)
221
        print('Task stopped')
222
223
224
def main(gmp, args):
225
    # pylint: disable=undefined-variable
226
227
    check_args(args)
228
229
    sender_email = args.script[1]
230
    recipient_email = args.script[2]
231
232
    config_id = get_config(gmp)
233
    target_id = get_target(gmp)
234
    alert_id = get_alert(gmp, sender_email, recipient_email)
235
    scanner_id = get_scanner(gmp)
236
237
    create_and_start_task(gmp, config_id, target_id, scanner_id, alert_id)
238
239
    print("\nScript finished\n")
240
241
242
if __name__ == '__gmp__':
243
    main(gmp, args)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable gmp does not seem to be defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable args does not seem to be defined.
Loading history...
244