malwaredb 0.3.2

Service for storing malicious, benign, or unknown files and related metadata and relationships.
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
// SPDX-License-Identifier: Apache-2.0

#![allow(unused_imports)]
// Slint generates code which imports (and doesn't use) `r#TextStyle`, making Clippy angry.

// Slint uses signed integers, but MalwareDB does not, so convert where appropriate and not get yelled at by Clippy for it
#![allow(
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::cast_sign_loss
)]

use crate::cli::config::Config;
use malwaredb_server::State;

use std::process::ExitCode;
use std::rc::Rc;
use std::sync::Arc;

use anyhow::{ensure, Context, Result};
use clap::{Args, ValueHint};
use slint::{Model, ModelRc, SharedString, StandardListViewItem, VecModel};
use tracing::{debug, error};

slint::include_modules!();

const NO_PARENT_OPTION: &str = "--NONE--";

#[derive(Clone, Debug, Args, PartialEq)]
pub struct AdminGui {
    /// Path to a Malware DB config file for access to a database
    #[arg(value_name = "FILE", value_hint = ValueHint::FilePath)]
    config_file: std::path::PathBuf,
}

impl AdminGui {
    #[allow(clippy::too_many_lines)]
    pub async fn execute(&self) -> Result<ExitCode> {
        let state = Arc::new(Config::from_file(&self.config_file)?.into_state().await?);

        let gui = AdminWindow::new()?;
        self.load_gui(&state, &gui).await?;

        let ui_handle = gui.as_weak();
        let users_state = state.clone();
        gui.on_users_save_button_pressed(move || {
            let gui = ui_handle.upgrade().unwrap();
            gui.set_user_status("".into());
            let uid = gui.get_users_index();
            let uname = gui.get_user_name();
            let fname = gui.get_user_fname();
            let lname = gui.get_user_lname();
            let email = gui.get_user_email();
            let readonly = gui.get_user_readonly();

            if uid < 0 {
                gui.set_user_status("uid should never be negative".into());
                error!("uid should never be negative");
                return;
            }
            if uname.len() < 3 {
                gui.set_user_status("username too short".into());
                error!("username too short");
                return;
            }
            if fname.len() < 3 {
                gui.set_user_status("first name too short".into());
                error!("first name too short");
                return;
            }
            if lname.len() < 3 {
                gui.set_user_status("last name too short".into());
                error!("last name too short");
                return;
            }
            if email.len() < 6 {
                gui.set_user_status("email too short".into());
                error!("email too short");
                return;
            }
            if !email.contains('@') {
                gui.set_user_status("email doesn't appear valid".into());
                error!("email doesn't appear valid");
                return;
            }

            if readonly && uid == 0 {
                gui.set_user_status("cowardly refusing to set admin to be read-only".into());
                error!("cowardly refusing to set admin to be read-only");
                return;
            }

            let handle = tokio::runtime::Handle::current();
            let _ = handle.enter();
            futures::executor::block_on(
                users_state
                    .db_type
                    .edit_user(uid as u32, &uname, &fname, &lname, &email, readonly),
            )
            .expect("failed to update database");

            let password = gui.get_user_password();
            if password.len() > 1 {
                futures::executor::block_on(users_state.db_type.set_password(&uname, &password))
                    .expect("failed to update password");
                debug!("Set new password for {uid}!");
            } else {
                debug!(
                    "Not setting password for {uid}, {} is too short",
                    password.len()
                );
            }

            // Update the GUI controls after DB update
            let users_list = gui.get_users_list();
            users_list.set_row_data(uid as usize, StandardListViewItem::from(uname.clone()));

            let users = gui.get_users();
            if let Some(mut row) = users.row_data(uid as usize) {
                row.uname = uname;
                row.fname = fname;
                row.lname = lname;
                row.email = email;
                users.set_row_data(uid as usize, row);
            }
        });

        let group_state = state.clone();
        let ui_handle = gui.as_weak();
        gui.on_groups_save_button_pressed(move || {
            let gui = ui_handle.upgrade().unwrap();
            gui.set_group_status("".into());
            let gid = gui.get_groups_index();
            let gname = gui.get_group_name();
            let gdesc = gui.get_group_description();
            let gparent = gui.get_group_parent();

            // Keep a copy for future GUI control update
            let gparent_orig = gparent.clone();

            let gparent = if gparent == NO_PARENT_OPTION {
                None
            } else {
                let handle = tokio::runtime::Handle::current();
                let _ = handle.enter();
                let gparent_id =
                    futures::executor::block_on(group_state.db_type.group_id_from_name(&gparent))
                        .expect("failed to get group's parent id from database");

                if gid == gparent_id {
                    gui.set_group_status("group cannot be self-parent".into());
                    error!("group cannot be self-parent");
                    return;
                }

                Some(gparent_id)
            };

            let handle = tokio::runtime::Handle::current();
            let _ = handle.enter();
            futures::executor::block_on(group_state.db_type.edit_group(
                gid as u32,
                &gname,
                &gdesc,
                gparent.map(|p| p as u32),
            ))
            .expect("failed to edit the group");

            // Update the GUI controls after DB update
            let groups_list = gui.get_groups_list();
            groups_list.set_row_data(gid as usize, StandardListViewItem::from(gname.clone()));

            let groups = gui.get_groups();
            if let Some(mut row) = groups.row_data(gid as usize) {
                row.name = gname;
                row.description = gdesc;
                row.parent = gparent_orig;
                groups.set_row_data(gid as usize, row);
            }
        });

        let label_state = state.clone();
        let ui_handle = gui.as_weak();
        gui.on_label_save_button_pressed(move || {
            let gui = ui_handle.upgrade().unwrap();
            gui.set_label_status("".into());

            let label_id: u64 = if let Ok(id) = gui.get_label_id().parse() {
                id
            } else {
                gui.set_label_status("Label id not an integer".into());
                error!("Label id not an integer");
                return;
            };
            let label_name = gui.get_label_name();
            let label_parent = gui.get_label_parent();
            // Keep a copy for future GUI control update
            let lparent_orig = label_parent.clone();

            if label_parent == label_name {
                gui.set_label_status("Label cannot have itself as a parent".into());
                error!("Label cannot have itself as a parent");
                return;
            }

            let label_parent = if label_parent == NO_PARENT_OPTION {
                None
            } else {
                let handle = tokio::runtime::Handle::current();
                let _ = handle.enter();
                let lparent_id = futures::executor::block_on(
                    label_state.db_type.label_id_from_name(&label_parent),
                )
                .expect("failed to get label parent id from database");

                if label_id == lparent_id {
                    gui.set_group_status("label cannot be self-parent".into());
                    error!("label cannot be self-parent");
                    return;
                }
                Some(lparent_id)
            };

            let handle = tokio::runtime::Handle::current();
            let _ = handle.enter();
            futures::executor::block_on(label_state.db_type.edit_label(
                label_id,
                &label_name,
                label_parent,
            ))
            .expect("failed to edit the label");

            let lid = gui.get_labels_index();
            let labels = gui.get_labels();
            if let Some(mut row) = labels.row_data(lid as usize) {
                row.name = label_name.clone();
                row.parent = lparent_orig;
                labels.set_row_data(lid as usize, row);
            }
            // Update the GUI controls after DB update
            let labels = gui.get_labels_list();
            labels.set_row_data(lid as usize, StandardListViewItem::from(label_name));
        });

        gui.run().unwrap();

        Ok(ExitCode::SUCCESS)
    }

    async fn load_gui(&self, state: &State, gui: &AdminWindow) -> Result<()> {
        self.load_gui_sources(state, gui).await?;
        self.load_gui_labels(state, gui).await?;

        let users = state
            .db_type
            .list_users()
            .await
            .context("failed to list users")?;

        let gui_usernames: Vec<StandardListViewItem> = users
            .iter()
            .map(|u| StandardListViewItem::from(SharedString::from(u.uname.clone())))
            .collect();

        let gui_usernames = VecModel::from(gui_usernames);

        let gui_users: Vec<GuiUser> = users
            .iter()
            .map(|u| GuiUser {
                id: u.id as i32,
                uname: u.uname.clone().into(),
                email: u.email.clone().into(),
                fname: u.fname.clone().into(),
                lname: u.lname.clone().into(),
                active: u.has_api_key,
                readonly: u.is_readonly,
            })
            .collect();

        let groups = state
            .db_type
            .list_groups()
            .await
            .context("failed to list groups")?;

        let mut gui_groupnames_strings_parent: Vec<SharedString> = groups
            .iter()
            .map(|g| SharedString::from(g.name.clone()))
            .collect();

        // Add the option of no parent.
        gui_groupnames_strings_parent.insert(0, SharedString::from(NO_PARENT_OPTION.to_string()));

        let gui_groupnames_strings: Vec<SharedString> = groups
            .iter()
            .map(|g| SharedString::from(g.name.clone()))
            .collect();
        let gui_groupnames: Vec<StandardListViewItem> = gui_groupnames_strings
            .iter()
            .map(|g| StandardListViewItem::from(g.clone()))
            .collect();

        let gui_groupnames = VecModel::from(gui_groupnames);
        let gui_groupnames_strings_parent = VecModel::from(gui_groupnames_strings_parent);
        let gui_groups: Vec<GuiGroup> = groups
            .iter()
            .map(|g| GuiGroup {
                id: g.id as i32,
                name: g.name.clone().into(),
                description: g.description.clone().unwrap_or_default().into(),
                parent: g
                    .parent
                    .clone()
                    .unwrap_or(NO_PARENT_OPTION.into())
                    .clone()
                    .into(),
                files: g.files as i32,
                users: g.members.len() as i32,
                sources: g.sources.len() as i32,
            })
            .collect();

        ensure!(gui_users[0].id == 0, "the first user should be ID 0");
        ensure!(
            gui_users[0].uname == "admin",
            "the admin user should be ID 0"
        );
        ensure!(gui_groups[0].id == 0, "the first group should be ID 0");
        ensure!(
            gui_groups[0].name == "admin",
            "the admin group should be ID 0"
        );

        let gui_users = VecModel::from(gui_users);
        let gui_groups = VecModel::from(gui_groups);

        gui.set_users_list(ModelRc::new(gui_usernames));
        gui.set_groups_list(ModelRc::new(gui_groupnames));

        let gui_users = ModelRc::from(Rc::new(gui_users));
        gui.set_users(gui_users);

        let gui_groups = ModelRc::from(Rc::new(gui_groups));
        gui.set_groups(gui_groups);

        let gui_groupnames_strings = VecModel::from(gui_groupnames_strings);
        gui.set_groups_strings(ModelRc::new(gui_groupnames_strings));
        gui.set_groups_strings_parent(ModelRc::new(gui_groupnames_strings_parent));

        Ok(())
    }

    async fn load_gui_sources(&self, state: &State, gui: &AdminWindow) -> Result<()> {
        let sources = state
            .db_type
            .list_sources()
            .await
            .context("failed to list sources")?;

        let gui_source_names: Vec<StandardListViewItem> = sources
            .iter()
            .map(|s| StandardListViewItem::from(SharedString::from(s.name.clone())))
            .collect();

        let gui_source_names = VecModel::from(gui_source_names);
        gui.set_sources_list(ModelRc::new(gui_source_names));

        let mut gui_sourcenames_strings_parent: Vec<SharedString> = sources
            .iter()
            .map(|g| SharedString::from(g.name.clone()))
            .collect();

        // Add the option of no parent.
        gui_sourcenames_strings_parent.insert(0, SharedString::from(NO_PARENT_OPTION.to_string()));
        let gui_sourcenames_strings_parent = VecModel::from(gui_sourcenames_strings_parent);
        gui.set_sources_strings_parent(ModelRc::new(gui_sourcenames_strings_parent));

        let gui_sources: Vec<GuiSource> = sources
            .iter()
            .map(|s| GuiSource {
                id: s.id as i32,
                name: s.name.clone().into(),
                description: s.description.clone().unwrap_or_default().into(),
                url: s.url.clone().unwrap_or_default().into(),
                parent: s
                    .parent
                    .clone()
                    .unwrap_or(NO_PARENT_OPTION.into())
                    .clone()
                    .into(),
                files: s.files as i32,
                groups: s.groups as i32,
                malicious: s.malicious.unwrap_or_default(),
            })
            .collect();

        let gui_sources = VecModel::from(gui_sources);
        gui.set_sources(ModelRc::new(gui_sources));

        Ok(())
    }

    async fn load_gui_labels(&self, state: &State, gui: &AdminWindow) -> Result<()> {
        let labels = state
            .db_type
            .get_labels()
            .await
            .context("failed to list sources")?;

        let mut gui_labels_strings_parent: Vec<SharedString> = labels
            .0
            .iter()
            .map(|l| SharedString::from(l.name.clone()))
            .collect();
        gui_labels_strings_parent.insert(0, SharedString::from(NO_PARENT_OPTION.to_string()));

        let gui_label_names: Vec<StandardListViewItem> = labels
            .0
            .iter()
            .map(|s| StandardListViewItem::from(SharedString::from(s.name.clone())))
            .collect();

        let gui_label_names = VecModel::from(gui_label_names);
        gui.set_labels_list(ModelRc::new(gui_label_names));

        let gui_labels: Vec<GuiLabel> = labels
            .0
            .iter()
            .map(|l| GuiLabel {
                id: l.id as i32,
                name: l.name.clone().into(),
                parent: l
                    .parent
                    .clone()
                    .unwrap_or(NO_PARENT_OPTION.into())
                    .clone()
                    .into(),
            })
            .collect();

        let gui_labels_strings_parent = VecModel::from(gui_labels_strings_parent);
        gui.set_labels_strings_parent(ModelRc::new(gui_labels_strings_parent));

        let gui_labels = VecModel::from(gui_labels);
        gui.set_labels(ModelRc::new(gui_labels));

        Ok(())
    }
}