-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
422 lines (365 loc) · 21.7 KB
/
main.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
#Import the necessary libraries
import sys, os
import pandas as pd
from PyQt6.QtWidgets import *
from PyQt6 import uic
from PyQt6.QtCore import QTimer
from PyQt6.QtGui import QIcon, QColor
class Interface(QMainWindow):
def __init__(self):
super().__init__()
# Interface connection
uic.loadUi(self.resolve_route('interface.ui'), self)
#Icon
icon_path = self.resolve_route('icon.ico')
app_icon = QIcon(icon_path)
self.setWindowIcon(app_icon)
# Setting title
self.setWindowTitle("Vulnerability Status Checker")
# Table UI
self.table = self.findChild(QTableWidget, 'tableWidget')
self.table.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
#Lcds UI
self.lcd_solved = self.findChild(QLCDNumber, 'lcdNumber_2')
self.lcd_total = self.findChild(QLCDNumber, 'lcdNumber_3')
self.lcd_vulnerabilities = self.findChild(QLCDNumber, 'lcdNumber')
#Search Engine UI
self.search_engine = self.findChild(QLineEdit, 'lineEdit')
self.search_engine.textChanged.connect(self.query_table)
#Buttons UI
self.btn_file1 = self.findChild(QPushButton, 'pushButton')
self.btn_file2 = self.findChild(QPushButton, 'pushButton_2')
self.btn_run = self.findChild(QPushButton, 'pushButton_3')
self.btn_show_daily = self.findChild(QPushButton, 'pushButton_4')
self.btn_show_database = self.findChild(QPushButton, 'pushButton_5')
self.btn_show_new_assets_cves = self.findChild(QPushButton, 'pushButton_6')
self.btn_export_new_cves = self.findChild(QPushButton, 'pushButton_7')
self.bnt_save_changes = self.findChild(QPushButton, 'pushButton_8')
#LineEdit
self.line_ed_search = self.findChild(QLineEdit, 'lineEdit')
self.line_ed_status = self.findChild(QLineEdit, 'lineEdit_2')
#CheckBox
self.cbox_filter = self.findChild(QCheckBox, 'checkBox')
self.cbox_filter.setEnabled(False)
#Connections UI
self.btn_file1.clicked.connect(lambda: self.import_file('Open File 1 - Daily'))
self.btn_file2.clicked.connect(lambda: self.import_file('Open File 2 - Database'))
self.btn_run.clicked.connect(lambda: self.run_check())
self.btn_show_daily.clicked.connect(lambda: self.show_table(self.btn_show_daily.text()))
self.btn_show_database.clicked.connect(lambda: self.show_table(self.btn_show_database.text()))
self.btn_show_new_assets_cves.clicked.connect(lambda: self.show_table(self.btn_show_new_assets_cves.text()))
self.btn_export_new_cves.clicked.connect(lambda: self.export_new_cves())
self.bnt_save_changes.clicked.connect(lambda: self.save_database_changes())
self.cbox_filter.stateChanged.connect(self.toggle_columns)
# Variables
self.file_type = ''
self.status = ['File exported successfully', 'File uploaded successfully']
self.columns_to_filter = None
self.green_color = QColor(204, 255, 204)
self.red_color = QColor(255, 204, 204)
self.aux_filter = ''
# Resolve route
def resolve_route(self, ruta_relativa):
if hasattr(sys, '_MEIPASS'):
return os.path.join(sys._MEIPASS, ruta_relativa)
return os.path.join(os.path.abspath('.'), ruta_relativa)
# Ajuste de widgets
def resizeEvent(self, event):
table_width = self.width() - 20
table_height = self.height() -188
self.table.setGeometry(10, 178, table_width, table_height)
def show_table(self, option):
self.cbox_filter.setChecked(False)
self.cbox_filter.setEnabled(False)
self.aux_filter = ''
self.line_ed_search.setText("")
#Show daily file
if option == 'Show Daily':
# Reading file
try:
self.aux_filter = 'filter_daily'
self.line_ed_status.setText("")
df_daily = self.df_daily
self.rows = df_daily.shape[0]
self.columns = df_daily.shape[1]
# UI table settings
self.table.setRowCount(self.rows)
self.table.setColumnCount(self.columns)
self.name_columns = list(df_daily.columns)
self.table.setHorizontalHeaderLabels(self.name_columns)
self.fill_table(df_daily, self.rows, self.columns)
self.line_ed_status.setStyleSheet(f'background-color: {self.green_color.name()}')
self.line_ed_status.setText(f"Displaying daily archive information")
self.cbox_filter.setEnabled(True)
except Exception as e:
self.table.setRowCount(0)
self.table.setColumnCount(0)
self.line_ed_status.setStyleSheet(f'background-color: {self.red_color.name()}')
self.line_ed_status.setText(f'Error: {type(e).__name__}. Description: {str(e)}')
#Show database file
elif option == 'Show Database':
self.line_ed_status.setText("")
# Reading file
try:
self.aux_filter = 'filter_database'
df_database = self.df_database
self.rows = df_database.shape[0]
self.columns = df_database.shape[1]
# UI table settings
self.table.setRowCount(self.rows)
self.table.setColumnCount(self.columns)
self.name_columns = list(df_database.columns)
self.table.setHorizontalHeaderLabels(self.name_columns)
self.fill_table(df_database, self.rows, self.columns)
self.line_ed_status.setStyleSheet(f'background-color: {self.green_color.name()}')
self.line_ed_status.setText(f"Displaying database archive information")
self.cbox_filter.setEnabled(True)
except Exception as e:
self.table.setRowCount(0)
self.table.setColumnCount(0)
self.line_ed_status.setStyleSheet(f'background-color: {self.red_color.name()}')
self.line_ed_status.setText(f'Error: {type(e).__name__}. Description: {str(e)}')
#Show new assets and cves file
elif option == 'Show Assets':
self.line_ed_status.setText("")
# Reading file
try:
self.aux_filter = 'filter_new_cves'
#df_new_cves = pd.read_csv(self.file_name, sep=';', encoding='latin-1')
df_new_cves = pd.read_excel(self.file_name)
self.rows = df_new_cves.shape[0]
self.columns = df_new_cves.shape[1]
# UI table settings
self.table.setRowCount(self.rows)
self.table.setColumnCount(self.columns)
self.name_columns = list(df_new_cves.columns)
self.table.setHorizontalHeaderLabels(self.name_columns)
self.fill_table(df_new_cves, self.rows, self.columns)
self.line_ed_status.setStyleSheet(f'background-color: {self.green_color.name()}')
self.line_ed_status.setText(f"Displaying assets and cves archive information")
self.cbox_filter.setEnabled(True)
except Exception as e:
self.table.setRowCount(0)
self.table.setColumnCount(0)
self.line_ed_status.setStyleSheet(f'background-color: {self.red_color.name()}')
self.line_ed_status.setText(f'Error: {type(e).__name__}. Description: {str(e)}')
# Show check run
elif option == 'Run Check':
# Reading file
try:
self.aux_filter = 'filter_run'
df_database = self.df_database
self.rows = df_database.shape[0]
self.columns = df_database.shape[1]
# UI table settings
self.table.setRowCount(self.rows)
self.table.setColumnCount(self.columns)
self.name_columns = list(df_database.columns)
self.table.setHorizontalHeaderLabels(self.name_columns)
self.fill_table(df_database, self.rows, self.columns)
self.cbox_filter.setEnabled(True)
except Exception as e:
self.table.setRowCount(0)
self.table.setColumnCount(0)
self.line_ed_status.setStyleSheet(f'background-color: {self.red_color.name()}')
self.line_ed_status.setText(f'Error: {type(e).__name__}. Desc: {str(e)}')
# Llenado de la tabla según sea el caso
def fill_table(self, df, rows, columns):
for row in range(rows):
for column in range(columns):
data = str(df.iloc[row,column])
self.table.setItem(row, column, QTableWidgetItem(data))
# Cargado del archivo Daily y el archivo Database
def import_file(self, file_type):
self.cbox_filter.setChecked(False)
self.cbox_filter.setEnabled(False)
self.line_ed_search.setText("")
file_path, _ = QFileDialog.getOpenFileName(self, f"{file_type}", "", "Archivos de Excel (*.xlsx *.xls)")
if file_path:
try:
if file_type == "Open File 1 - Daily":
#self.df_daily = pd.read_csv(file_path, sep=';', encoding='latin-1')
self.df_daily = pd.read_excel(file_path, dtype={'Device name': str, 'Vulnerability ID': str})
self.line_ed_status.setStyleSheet(f'background-color: {self.green_color.name()}')
self.line_ed_status.setText(f"Daily file successfully uploaded")
self.lcd_vulnerabilities.display('0')
self.lcd_solved.display('0')
self.lcd_total.display('0')
self.table.setRowCount(0)
self.table.setColumnCount(0)
elif file_type == "Open File 2 - Database":
self.df_database = pd.read_excel(file_path, dtype={'Device name': str, 'Vulnerability ID': str})
self.line_ed_status.setStyleSheet(f'background-color: {self.green_color.name()}')
self.line_ed_status.setText(f"Database file successfully uploaded")
self.lcd_vulnerabilities.display('0')
self.lcd_solved.display('0')
self.lcd_total.display('0')
self.table.setRowCount(0)
self.table.setColumnCount(0)
except Exception as e:
self.table.setRowCount(0)
self.table.setColumnCount(0)
self.line_ed_status.setStyleSheet(f'background-color: {self.red_color.name()}')
self.line_ed_status.setText(f'Error: {type(e).__name__}. Description: {str(e)}')
# Ejecución del chequeo del estado de las vulnerabildades
def run_check(self):
try:
self.temp_df = self.df_daily[['Device name', 'Vulnerability ID']].apply(lambda x: x.str.lower().str.strip()).merge(
self.df_database[['Device name', 'Vulnerability ID']].apply(lambda x: x.str.lower().str.strip()),
on=['Device name', 'Vulnerability ID'],
how='outer',
indicator='indicador'
)
self.temp_df_unique = self.df_daily[['Vulnerability ID']].apply(lambda x: x.str.lower().str.strip()).merge(
self.df_database[['Vulnerability ID']].apply(lambda x: x.str.lower().str.strip()),
on=['Vulnerability ID'],
how='outer',
indicator='indicador'
)
self.temp_df_assets = self.df_daily[['Device name']].apply(lambda x: x.str.lower().str.strip()).merge(
self.df_database[['Device name']].apply(lambda x: x.str.lower().str.strip()),
on=['Device name'],
how='outer',
indicator='indicador'
)
self.unique_cves = self.temp_df_unique[self.temp_df_unique['indicador']=='left_only']
self.unique_cves['Vulnerability ID'] = self.unique_cves['Vulnerability ID'].astype(str)
print(f"UNIQUES CVES: {self.unique_cves['Vulnerability ID'].info}")
self.unique_assets = self.temp_df_assets[self.temp_df_assets['indicador']=='left_only']
self.unique_assets['Device name'] = self.unique_assets['Device name'].astype(str)
print(f"UNIQues asstes: {self.unique_assets['Device name'].info}")
# Clasificación de las vulnerabilidades
self.only_daily = self.temp_df[self.temp_df['indicador']=='left_only'][['Device name', 'Vulnerability ID']]
self.only_database = self.temp_df[self.temp_df['indicador']=='right_only'][['Device name', 'Vulnerability ID']]
self.only_same = self.temp_df[self.temp_df['indicador']=='both'][['Device name', 'Vulnerability ID']]
# Crear una nueva columna que combine activo y cve_id
self.temp_database = self.df_database.copy()
self.temp_database = self.temp_database[['Device name', 'Vulnerability ID']].apply(lambda x: x.str.lower().str.strip())
self.temp_database['key'] = self.temp_database['Device name'] + '_' + self.temp_database['Vulnerability ID']
self.only_daily['key'] = self.only_daily['Device name'] + '_' + self.only_daily['Vulnerability ID']
self.only_database['key'] = self.only_database['Device name'] + '_' + self.only_database['Vulnerability ID']
self.only_same['key'] = self.only_same['Device name'] + '_' + self.only_same['Vulnerability ID']
# Actualización del estado Solucionado
format = "%d/%m/%Y" #pd.Timestamp("today").strftime()
today = pd.to_datetime('today').date().strftime(format)
self.df_database.loc[(self.temp_database['key'].isin(self.only_database['key'])), 'actualizacion_interlan'] = 'Solucionado'
self.df_database.loc[(self.temp_database['key'].isin(self.only_database['key'])), 'Fecha actualizacion'] = today
# Actualización del estado Vulnerable
self.df_database.loc[(self.temp_database['key'].isin(self.only_same['key'])), 'actualizacion_interlan'] = 'Vulnerable'
self.df_database.loc[(self.temp_database['key'].isin(self.only_same['key'])), 'Fecha actualizacion'] = today
self.line_ed_status.setStyleSheet(f'background-color: {self.green_color.name()}')
self.line_ed_status.setText("Verification has been successfully completed")
self.set_labels(self.df_database)
return self.show_table(self.btn_run.text())
except Exception as e:
self.table.setRowCount(0)
self.table.setColumnCount(0)
self.line_ed_status.setStyleSheet(f'background-color: {self.red_color.name()}')
self.line_ed_status.setText(f'Error: {type(e).__name__}. Description: {str(e)}')
# Exportación del archivo que contiene los activos y sus respectivos cves que no estan relacionados en la base de datos principal
def export_new_cves(self):
try:
self.cbox_filter.setChecked(False)
self.cbox_filter.setEnabled(False)
self.line_ed_search.setText("")
self.file_name, _ = QFileDialog.getSaveFileName(self,"Save new assets","","Archivos de Excel (*.xlsx *.xls)")
self.file_name_unique, _ = QFileDialog.getSaveFileName(self,"Save new cves","","Archivos de Excel (*.xlsx *.xls)")
if self.file_name:
# Archivo unicos de assets
self.temp_df_daily = self.df_daily.copy()
self.temp_df_daily[['Device name', 'Vulnerability ID']] = self.temp_df_daily[['Device name', 'Vulnerability ID']].astype(str)
self.temp_df_daily[['Device name', 'Vulnerability ID']] = self.temp_df_daily[['Device name', 'Vulnerability ID']].apply(lambda x: x.str.lower().str.strip())
self.unique_assets['Device name'] = self.unique_assets['Device name'].apply(lambda x: str(x).lower().strip())
self.temp_df_daily = self.temp_df_daily[self.temp_df_daily['Device name'].isin(self.unique_assets['Device name'])]
#Generación de archivo de activos
self.temp_df_daily.to_excel(self.file_name, index = False)
# Archivo unico de cves
self.temp_df_daily_unique = self.df_daily.copy()
self.temp_df_daily_unique[['Device name', 'Vulnerability ID']] = self.temp_df_daily_unique[['Device name', 'Vulnerability ID']].astype(str)
self.temp_df_daily_unique[['Device name', 'Vulnerability ID']] = self.temp_df_daily_unique[['Device name', 'Vulnerability ID']].apply(lambda x: x.str.lower().str.strip())
self.unique_cves['Device name'] = self.unique_cves['Vulnerability ID'].apply(lambda x: str(x).lower().strip())
self.temp_df_daily_unique = self.temp_df_daily_unique[self.temp_df_daily_unique['Vulnerability ID'].isin(self.unique_cves['Vulnerability ID'])]
#Generación de archivo de CVEs nuevos
self.temp_df_daily_unique.to_excel(self.file_name_unique, index= False )
# Vaciado de tabla
self.table.setRowCount(0)
self.table.setColumnCount(0)
self.line_ed_status.setStyleSheet(f'background-color: {self.green_color.name()}')
self.line_ed_status.setText(f'File exported successfully: {self.file_name}')
except Exception as e:
self.table.setRowCount(0)
self.table.setColumnCount(0)
self.line_ed_status.setStyleSheet(f'background-color: {self.red_color.name()}')
self.line_ed_status.setText(f'Error: {type(e).__name__}. Descripción: {str(e)}')
# Guardado de la base de datos modificada
def save_database_changes(self):
try:
self.cbox_filter.setChecked(False)
self.cbox_filter.setEnabled(False)
self.line_ed_search.setText("")
self.file_changes, _ = QFileDialog.getSaveFileName(self,"Save changes as","","Archivos de Excel (*.xlsx *.xls)")
if (self.file_changes and len(self.temp_df)>0):
#Se genera el archivo con las modificaciones de la verificación en la base de datos original
self.df_database.to_excel(self.file_changes, index= False)
self.table.setRowCount(0)
self.table.setColumnCount(0)
self.line_ed_status.setStyleSheet(f'background-color: {self.green_color.name()}')
self.line_ed_status.setText(f'File saved successfully: {self.file_changes}')
except Exception as e:
self.table.setRowCount(0)
self.table.setColumnCount(0)
self.line_ed_status.setStyleSheet(f'background-color: {self.red_color.name()}')
self.line_ed_status.setText(f'Error: {type(e).__name__}. Descripción: {str(e)}')
# Motor de consultas en la tabla
def query_table(self, query):
# Obtener el modelo de datos de la tabla
model = self.table.model()
# Iterar sobre las filas del modelo
for row in range(model.rowCount()):
# Concatenar el contenido de la fila en una cadena
row_data = []
for column in range(model.columnCount()):
index = model.index(row, column)
data = str(model.data(index))
row_data.append(data)
row_content = ''.join(row_data)
# Ocultar o mostrar la fila según la consulta de búsqueda
match = query.lower() in row_content.lower()
self.table.setRowHidden(row, not match)
# Actualizar la vista de la tabla
self.table.update()
def toggle_columns(self, checked):
try:
if (self.aux_filter == 'filter_daily' or self.aux_filter == 'filter_new_cves'):
self.columns_to_filter = [0, 1, 3, 4, 6, 7, 8, 12]
for i in range(self.table.columnCount()):
self.table.setColumnHidden(i, i not in self.columns_to_filter and checked)
self.table.resizeColumnsToContents()
elif (self.aux_filter == 'filter_database' or self.aux_filter == 'filter_run'):
self.columns_to_filter = [0, 10, 28, 29]
for i in range(self.table.columnCount()):
self.table.setColumnHidden(i, i not in self.columns_to_filter and checked)
self.table.resizeColumnsToContents()
except Exception as e:
self.line_ed_status.setStyleSheet(f'background-color: {self.red_color.name()}')
self.line_ed_status.setText(f'Error: {type(e).__name__}. Description: {str(e)}')
# Visualización de las variables en los lcds
def set_labels(self, database):
num_vulnerabilities = self.get_number_vulnerabilities(database)
num_solved = self.get_number_solved(database)
self.lcd_vulnerabilities.display(num_vulnerabilities)
self.lcd_solved.display(num_solved)
self.lcd_total.display(num_solved + num_vulnerabilities)
# Cálculo de las vulnerabilidades a mostrar en lcd
def get_number_vulnerabilities(self, database):
num_vulnerabilities = database[database['actualizacion_interlan']=='Vulnerable'].shape[0]
return num_vulnerabilities
# Cálculo de los casos solucionados a mostrar en lcd
def get_number_solved(self, database):
num_solved = database[database['actualizacion_interlan']=='Solucionado'].shape[0]
return num_solved
if __name__ == '__main__':
app = QApplication(sys.argv)
frame = Interface()
frame.show()
sys.exit(app.exec())