-
Notifications
You must be signed in to change notification settings - Fork 7
/
sumotoolbox.py
executable file
·1313 lines (1167 loc) · 60 KB
/
sumotoolbox.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
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
__author__ = 'Tim MacDonald'
__version__ = '0.11.1'
# Copyright 2015 Timothy MacDonald
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
import sys
import json
import csv
import pytz
import os.path
import re
from datetime import datetime
from tzlocal import get_localzone
from qtpy import QtCore, QtGui, QtWidgets, uic
import webbrowser
import pathlib
import os
import logzero
from logzero import logger
from configupdater import ConfigUpdater
import configparser
import faulthandler
import qtmodern.styles
import qtmodern.windows
import time
import importlib
#local imports
from modules.sumologic import SumoLogic
from modules.credentials import CredentialsDB
# This guy helps give more informative error messages for threads
faulthandler.enable(all_threads=True)
# detect if in Pyinstaller package and build appropriate base directory path
if getattr(sys, 'frozen', False):
basedir = sys._MEIPASS
else:
basedir = os.path.dirname(os.path.abspath(__file__))
# Setup logging
logzero.logfile("sumotoolbox.log")
logzero.loglevel(level=20) # Info Logging
# Log messages
logger.info("SumoLogicToolBox started. Version %s", __version__)
# This script uses Qt Designer files to define the UI elements which must be loaded
qtMainWindowUI = os.path.join(basedir, 'data/sumotoolbox.ui')
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtMainWindowUI)
class ShowTextDialog(QtWidgets.QDialog):
def __init__(self, title, text):
super(ShowTextDialog, self).__init__()
self.title = title
self.text = text
self.setupUi(self)
def setupUi(self, Dialog):
Dialog.setObjectName("TextDisplay")
self.setWindowTitle(self.title)
self.textedit = QtWidgets.QTextEdit()
self.textedit.setText(self.text)
self.layout = QtWidgets.QVBoxLayout()
self.layout.addWidget(self.textedit)
class NewPasswordDialog(QtWidgets.QDialog):
def __init__(self):
super(NewPasswordDialog, self).__init__()
self.objectlist = []
self.setupUi(self)
def setupUi(self, Dialog):
Dialog.setObjectName("EnterNewPassword")
Dialog.resize(320, 366)
self.setWindowTitle('Enter new password...')
self.okbutton = QtWidgets.QPushButton(Dialog)
self.okbutton.setText('OK')
self.okbutton.setGeometry(250, 320, 50, 32)
self.okbutton.setEnabled(False)
self.cancelbutton = QtWidgets.QPushButton(Dialog)
self.cancelbutton.setText('Cancel')
self.cancelbutton.setGeometry(190, 320, 50, 32)
self.cancelbutton.setEnabled(True)
self.label = QtWidgets.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(17, 7, 281, 81))
self.label.setFrameShape(QtWidgets.QFrame.Box)
self.label.setTextFormat(QtCore.Qt.PlainText)
self.label.setObjectName("label")
self.lineEditPassword1 = QtWidgets.QLineEdit(Dialog)
self.lineEditPassword1.setGeometry(QtCore.QRect(20, 240, 281, 31))
self.lineEditPassword1.setObjectName("lineEditPassword1")
self.lineEditPassword1.setEchoMode(2)
self.lineEditPassword2 = QtWidgets.QLineEdit(Dialog)
self.lineEditPassword2.setGeometry(QtCore.QRect(20, 280, 281, 34))
self.lineEditPassword2.setObjectName("lineEditPassword2")
self.lineEditPassword2.setEchoMode(2)
self.labelCount = QtWidgets.QLabel(Dialog)
self.labelCount.setGeometry(QtCore.QRect(20, 100, 281, 18))
self.labelCount.setObjectName("labelCount")
self.labelLowerCase = QtWidgets.QLabel(Dialog)
self.labelLowerCase.setGeometry(QtCore.QRect(20, 120, 281, 18))
self.labelLowerCase.setObjectName("labe1LowerCase")
self.labelUpperCase = QtWidgets.QLabel(Dialog)
self.labelUpperCase.setGeometry(QtCore.QRect(20, 140, 281, 18))
self.labelUpperCase.setObjectName("labelUpperCase")
self.labelNumeral = QtWidgets.QLabel(Dialog)
self.labelNumeral.setGeometry(QtCore.QRect(20, 160, 281, 18))
self.labelNumeral.setObjectName("labelNumeral")
self.labelNonAlphaNumeric = QtWidgets.QLabel(Dialog)
self.labelNonAlphaNumeric.setGeometry(QtCore.QRect(20, 180, 281, 18))
self.labelNonAlphaNumeric.setObjectName("labelNonAlphaNumeric")
self.labelMatch = QtWidgets.QLabel(Dialog)
self.labelMatch.setGeometry(QtCore.QRect(20, 200, 281, 18))
self.labelMatch.setObjectName("labelMatch")
self.retranslateUi(Dialog)
# self.buttonBox.accepted.connect(Dialog.accept)
# self.buttonBox.rejected.connect(Dialog.reject)
self.okbutton.clicked.connect(Dialog.accept)
self.cancelbutton.clicked.connect(Dialog.reject)
QtCore.QMetaObject.connectSlotsByName(Dialog)
self.lineEditPassword1.textEdited.connect(self.check_password)
self.lineEditPassword2.textEdited.connect(self.check_password)
self.labelCount.setStyleSheet('color: red')
self.labelLowerCase.setStyleSheet('color: red')
self.labelUpperCase.setStyleSheet('color: red')
self.labelNumeral.setStyleSheet('color: red')
self.labelNonAlphaNumeric.setStyleSheet('color: red')
self.labelMatch.setStyleSheet('color: red')
def check_password(self):
password1 = self.lineEditPassword1.text()
password2 = self.lineEditPassword2.text()
if len(password1) > 9:
self.labelCount.setStyleSheet('color: green')
count = True
else:
self.labelCount.setStyleSheet('color: red')
count = False
if re.search(r'[a-z]', password1):
self.labelLowerCase.setStyleSheet('color: green')
lower = True
else:
self.labelLowerCase.setStyleSheet('color: red')
lower = False
if re.search(r'[A-Z]', password1):
self.labelUpperCase.setStyleSheet('color: green')
upper = True
else:
self.labelUpperCase.setStyleSheet('color: red')
upper = False
if re.search(r'[0-9]', password1):
self.labelNumeral.setStyleSheet('color: green')
numeral = True
else:
self.labelNumeral.setStyleSheet('color: red')
numeral = False
if re.search(r'[,\.!?#@$]', password1):
self.labelNonAlphaNumeric.setStyleSheet('color: green')
nonalpha = True
else:
self.labelNonAlphaNumeric.setStyleSheet('color: red')
nonalpha = False
if password1 == password2:
self.labelMatch.setStyleSheet('color: green')
match = True
else:
self.labelMatch.setStyleSheet('color: red')
match = False
if count and lower and upper and numeral and nonalpha and match:
self.okbutton.setEnabled(True)
else:
self.okbutton.setEnabled(False)
def getresults(self):
return str(self.lineEditPassword1.text())
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.label.setText(_translate("Dialog", "Please enter a new password.\n"
"Once entered your password cannot\n"
"be retrieved. Remember it!\n"
"It must meet the following conditions:"))
self.labelCount.setText(_translate("Dialog", "-Have 10 or more characters"))
self.labelLowerCase.setText(_translate("Dialog", "-Contain at least 1 lowercase character"))
self.labelUpperCase.setText(_translate("Dialog", "-Contain at least 1 uppercase character"))
self.labelNumeral.setText(_translate("Dialog", "-Contain at least 1 numeral"))
self.labelNonAlphaNumeric.setText(_translate("Dialog", "-Contain at least 1 of these ,.!?#@$"))
self.labelMatch.setText(_translate("Dialog", "-Both entries must match"))
class sumotoolbox(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
QtWidgets.QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
# detect if we are running in a pyinstaller bundle and set the base directory for file loads"
if getattr(sys, 'frozen', False):
self.basedir = sys._MEIPASS
else:
self.basedir = os.path.dirname(os.path.abspath(__file__))
logger.info("basedir is: " + str(self.basedir))
self.setupUi(self)
# initialize variable to hold whether we've authenticated the cred database
self.cred_db_authenticated = False
# Load update and load the ini file into self.config
self.init_and_load_config_file()
self.initModels() # load all the comboboxes and such with values
# Configure the dropdown menu actions
self.setup_menus()
# Initially set logging level to match what is checked in the logging menu
self.change_logging_level()
# Configure the creddb buttons according to the config file settings
self.set_creddbbuttons()
# Check to see if the keystore password exists in the environmental variable "STB_PASS" and if so,
# automatically unlock the keystore. Set this up mostly for testing. DO NOT keep your keystore password
# in .bashrc or .profile or whatever file in plaintext. That is bad times.
self.tabs = [] # This has to come before the credstore loads
env_password = os.environ.get('STB_PASS')
if env_password:
logger.info('Found Password in $STB_PASS. Trying it...')
self.loadcreddb(env_password=env_password)
# Setup a threadpool for multithreading
self.threadpool = QtCore.QThreadPool()
self.threadpool.setMaxThreadCount(10) # <--- Sumo API concurrency is 10
# load additional Tabs from available modules
# find all of the tab modules and import them
modules_dir = pathlib.Path(self.basedir + '/modules')
modules_dir_contents = modules_dir.glob('*tab.py')
modules_to_load = []
for module_name in modules_dir_contents:
modules_to_load.append(str(str(module_name.name).split('.')[0]))
modules_to_load.sort()
for module_to_load in modules_to_load:
module_name = 'modules.' + module_to_load
globals()[module_name] = importlib.import_module(module_name)
# These following three lines are confusing:
# First we get the name of the class as a string from the module
# Then we use that string to get the class itself
# Then we instantiate it.
class_name = getattr(globals()[module_name], 'class_name')
class_ = getattr(globals()[module_name], class_name)
self.tabs.append(class_(self))
logger.info('[Sumotoolbox] Found and imported %s class.', module_name)
for tab in self.tabs:
self.tabWidget.addTab(tab, tab.tab_name)
logger.info('[Sumotoolbox] Added %s tab to UI.', tab.tab_name)
# disable right credential box because we always start on the search tab
# which only uses the left credentials
self.tabchange(0)
# initial clear of all stateful objects (This makes sure all of the tabs are cleared and initialized)
self.reset_stateful_objects()
# connect all of the UI button elements to their respective methods
#Set up a signal if the tabs are clicked
self.tabWidget.currentChanged.connect(self.tabchange)
#UI Buttons for Credential Store
self.pushButtonCreateCredentialDatabase.clicked.connect(self.createcredb)
self.pushButtonLoadCredentialDatabase.clicked.connect(self.loadcreddb)
self.pushButtonDeleteCredentialDatabase.clicked.connect(self.deletecreddb)
# Left Preset Buttons
self.pushButtonCreatePresetLeft.clicked.connect(lambda: self.create_preset(
self.comboBoxRegionLeft,
self.lineEditUserNameLeft,
self.lineEditPasswordLeft,
self.comboBoxPresetLeft,
'left'
))
self.comboBoxPresetLeft.currentIndexChanged.connect(lambda: self.load_preset(
str(self.comboBoxPresetLeft.currentText()),
self.comboBoxRegionLeft,
self.lineEditUserNameLeft,
self.lineEditPasswordLeft,
self.comboBoxPresetLeft,
'left'
))
# This exists for an edge case. If there is only one entry in the preset list and the user edits/modifies
# the cred text then clicking on the preset will not reload the cred because the index hasn't changed.
# This solves this problem
self.comboBoxPresetLeft.activated.connect(lambda: self.preset_activated(
str(self.comboBoxPresetLeft.currentText()),
self.comboBoxRegionLeft,
self.lineEditUserNameLeft,
self.lineEditPasswordLeft,
self.comboBoxPresetLeft,
'left'
))
self.pushButtonDeletePresetLeft.clicked.connect(lambda: self.delete_preset(
str(self.comboBoxPresetLeft.currentText()),
self.comboBoxRegionLeft,
self.lineEditUserNameLeft,
self.lineEditPasswordLeft,
self.comboBoxPresetLeft,
'left'
))
self.pushButtonUpdatePresetLeft.clicked.connect(lambda: self.update_preset(
str(self.comboBoxPresetLeft.currentText()),
str(self.comboBoxRegionLeft.currentText()),
str(self.lineEditUserNameLeft.text()),
str(self.lineEditPasswordLeft.text())
))
# Right Preset Buttons
self.pushButtonCreatePresetRight.clicked.connect(lambda: self.create_preset(
self.comboBoxRegionRight,
self.lineEditUserNameRight,
self.lineEditPasswordRight,
self.comboBoxPresetRight,
'right'
))
self.comboBoxPresetRight.currentIndexChanged.connect(lambda: self.load_preset(
str(self.comboBoxPresetRight.currentText()),
self.comboBoxRegionRight,
self.lineEditUserNameRight,
self.lineEditPasswordRight,
self.comboBoxPresetRight,
'right'
))
# This exists for an edge case. If there is only one entry in the preset list and the user edits/modifies
# the cred text then clicking on the preset will not reload the cred because the index hasn't changed.
# This solves this problem
self.comboBoxPresetRight.activated.connect(lambda: self.preset_activated(
str(self.comboBoxPresetRight.currentText()),
self.comboBoxRegionRight,
self.lineEditUserNameRight,
self.lineEditPasswordRight,
self.comboBoxPresetRight,
'Right'
))
self.pushButtonDeletePresetRight.clicked.connect(lambda: self.delete_preset(
str(self.comboBoxPresetRight.currentText()),
self.comboBoxRegionRight,
self.lineEditUserNameRight,
self.lineEditPasswordRight,
self.comboBoxPresetRight,
'right'
))
self.pushButtonUpdatePresetRight.clicked.connect(lambda: self.update_preset(
str(self.comboBoxPresetRight.currentText()),
str(self.comboBoxRegionRight.currentText()),
str(self.lineEditUserNameRight.text()),
str(self.lineEditPasswordRight.text())
))
# cred change stuff
self.comboBoxRegionLeft.currentIndexChanged.connect(lambda: self.region_change(
str(self.comboBoxRegionLeft.currentText()),
self.comboBoxPresetLeft,
side='left'
))
self.comboBoxRegionRight.currentIndexChanged.connect(lambda: self.region_change(
str(self.comboBoxRegionRight.currentText()),
self.comboBoxPresetRight,
side='right'
))
self.lineEditUserNameLeft.editingFinished.connect(lambda: self.cred_change(
side='left'
))
self.lineEditPasswordLeft.editingFinished.connect(lambda: self.cred_change(
side='left'
))
self.lineEditUserNameRight.editingFinished.connect(lambda: self.cred_change(
side='right'
))
self.lineEditPasswordRight.editingFinished.connect(lambda: self.cred_change(
side='right'
))
# UI Buttons for Search API Tab
self.pushButtonStartSearch.clicked.connect(lambda: self.runsearch(
self.loadedapiurls[str(self.comboBoxRegionLeft.currentText())],
str(self.lineEditUserNameLeft.text()),
str(self.lineEditPasswordLeft.text())
))
# method to reset all objects that are dependent on creds (such as collectors and content lists)
def reset_stateful_objects(self, side='both'):
for tab in self.tabs:
tab.reset_stateful_objects(side)
return
def cred_change(self, side='both'):
left = False
right = False
if side == 'left':
left = True
if side == 'right':
right = True
if side == 'both':
left = True
right = True
if left:
pass
if right:
pass
self.reset_stateful_objects(side=side)
def region_change(self, region_text, preset_combo_box, side='both'):
left = False
right = False
if side == 'left':
left = True
if side == 'right':
right = True
if side == 'both':
left = True
right = True
if left:
if region_text == "FILESYSTEM:":
self.lineEditUserNameLeft.setEnabled(False)
self.lineEditPasswordLeft.setEnabled(False)
self.pushButtonCreatePresetLeft.setEnabled(False)
self.pushButtonUpdatePresetLeft.setEnabled(False)
self.pushButtonDeletePresetLeft.setEnabled(False)
self.comboBoxPresetLeft.setCurrentText(' ')
else:
self.lineEditUserNameLeft.setEnabled(True)
self.lineEditPasswordLeft.setEnabled(True)
self.pushButtonCreatePresetLeft.setEnabled(True)
self.pushButtonUpdatePresetLeft.setEnabled(True)
self.pushButtonDeletePresetLeft.setEnabled(True)
if right:
if region_text == "FILESYSTEM:":
self.lineEditUserNameRight.setEnabled(False)
self.lineEditPasswordRight.setEnabled(False)
self.pushButtonCreatePresetRight.setEnabled(False)
self.pushButtonUpdatePresetRight.setEnabled(False)
self.pushButtonDeletePresetRight.setEnabled(False)
self.comboBoxPresetRight.setCurrentText(' ')
else:
self.lineEditUserNameRight.setEnabled(True)
self.lineEditPasswordRight.setEnabled(True)
self.pushButtonCreatePresetRight.setEnabled(True)
self.pushButtonUpdatePresetRight.setEnabled(True)
self.pushButtonDeletePresetRight.setEnabled(True)
self.reset_stateful_objects(side=side)
def get_current_creds(self, side):
if side == 'left':
service = self.comboBoxRegionLeft.currentText()
url = self.loadedapiurls[str(self.comboBoxRegionLeft.currentText())]
cred_id = str(self.lineEditUserNameLeft.text())
cred_key = str(self.lineEditPasswordLeft.text())
elif side == 'right':
service = self.comboBoxRegionRight.currentText()
url = self.loadedapiurls[str(self.comboBoxRegionRight.currentText())]
cred_id = str(self.lineEditUserNameRight.text())
cred_key = str(self.lineEditPasswordRight.text())
else:
raise Exception (f"Can't get creds for side: {side}")
return {'service': service,
'url': url,
'id': cred_id,
'key': cred_key}
def sumo_from_creds(self, creds):
return SumoLogic(creds['id'],
creds['key'],
endpoint=creds['url'],
log_level=self.log_level)
def clear_creds(self):
self.lineEditUserNameLeft.clear()
self.lineEditPasswordLeft.clear()
self.comboBoxPresetLeft.clear()
self.lineEditUserNameRight.clear()
self.lineEditPasswordRight.clear()
self.comboBoxPresetRight.clear()
def endpoint_lookup(self, deployment):
# there are duplicates here because most deployments have 2 names
endpoints = {'prod': 'https://api.sumologic.com/api',
'us1': 'https://api.sumologic.com/api',
'us2': 'https://api.us2.sumologic.com/api',
'eu': 'https://api.eu.sumologic.com/api',
'dub': 'https://api.eu.sumologic.com/api',
'ca': 'https://api.ca.sumologic.com/api',
'mon': 'https://api.ca.sumologic.com/api',
'de': 'https://api.de.sumologic.com/api',
'fra': 'https://api.de.sumologic.com/api',
'au': 'https://api.au.sumologic.com/api',
'syd': 'https://api.au.sumologic.com/api',
'jp': 'https://api.jp.sumologic.com/api',
'tky': 'https://api.jp.sumologic.com/api',
'in': 'https://api.in.sumologic.com/api',
'mum': 'https://api.in.sumologic.com/api',
'fed': 'https://api.fed.sumologic.com/api',
}
return endpoints[str(deployment).lower()]
# Start methods for Credential Database
def createcredb(self):
logger.info('Creating credential store')
#check to see if there is already a dbfile and ask if it should be removed to create a new one
db_file = pathlib.Path('credentials.db')
if db_file.is_file():
message = "It looks like you already have a credential database. Do you want to delete it (and it's passwords) and create a new one? If so type 'DELETE' in the box below:"
text, result = QtWidgets.QInputDialog.getText(self, 'Warning!!', message)
if (result and (str(text) == 'DELETE')):
os.remove('credentials.db')
else:
return
# get the password that will be used for the new database
dialog = NewPasswordDialog()
dialog.exec()
dialog.show()
if str(dialog.result()) == '1':
password = dialog.getresults()
if password:
try:
# We pass a username here (from the config file) just in case someone has written their own
# version of the CredentialDB class that requires both a username/id AND password
# however the version distributed with sumologictoolbox ignores the username.
self.credentialstore = CredentialsDB(password,
username=self.config['Credential Store']['username'],
create_new=True)
# restrict permissions on the db file to just the user. May not be effective on Windows
os.chmod(str(db_file), 0o600)
self.cred_db_authenticated = True
except Exception as e:
logger.exception(e)
self.errorbox("Something went wrong\n\n" + str(e))
self.set_creddbbuttons()
return
else:
return
return
def loadcreddb(self, env_password=None):
logger.info('Loading credential store')
db_file = pathlib.Path('credentials.db')
if db_file.is_file():
if type(env_password) is bool:
message = "Please enter your credentials database password."
password, result = QtWidgets.QInputDialog.getText(self, 'Enter password', message, QtWidgets.QLineEdit.Password)
else:
password = env_password
result = True
if result:
try:
# create the cred store instance
self.credentialstore = CredentialsDB(password)
self.cred_db_authenticated = True
# turn on the UI buttons
self.set_creddbbuttons()
# populate the preset dropdowns
self.populate_presets()
preset = self.comboBoxPresetLeft.currentText()
# load the first preset in the list (if it's there)
if preset:
self.load_preset(
preset,
self.comboBoxRegionLeft,
self.lineEditUserNameLeft,
self.lineEditPasswordLeft,
self.comboBoxPresetLeft,
'left'
)
self.load_preset(
preset,
self.comboBoxRegionRight,
self.lineEditUserNameRight,
self.lineEditPasswordRight,
self.comboBoxPresetLeft,
'right'
)
self.set_creddbbuttons()
# disable right region box if we are on one of the tabs that don't use it
self.tabchange(self.tabWidget.currentIndex())
except Exception as e:
logger.exception(e)
self.errorbox(str(e))
self.cred_db_authenticated = False
if hasattr(self, 'credentialstore'):
del self.credentialstore
self.set_creddbbuttons()
self.clear_creds()
self.reset_stateful_objects()
return
else:
return
else:
self.errorbox("You don't appear to have a credentials database. You must create one first.")
return
def deletecreddb(self):
db_file = pathlib.Path('credentials.db')
if db_file.is_file():
message = '''
Do you really want to delete your credential database?
If so type 'DELETE' in the box below:"
'''
text, result = QtWidgets.QInputDialog.getText(self, 'Warning!!', message)
if (result and (str(text) == 'DELETE')):
os.remove(str(db_file))
self.cred_db_authenticated = False
del self.credentialstore
self.clear_creds()
self.set_creddbbuttons()
def populate_presets(self):
logger.info('Populating presets')
self.comboBoxPresetLeft.clear()
self.comboBoxPresetRight.clear()
self.comboBoxPresetLeft.addItem(' ')
self.comboBoxPresetRight.addItem(' ')
try:
names = self.credentialstore.list_names()
names = sorted(names, key=str.lower)
for name in names:
self.comboBoxPresetLeft.addItem(name.strip())
self.comboBoxPresetRight.addItem(name.strip())
except Exception as e:
logger.exception(e)
self.errorbox('Something went wrong\n\n' + str(e))
return
def list_presets_with_creds(self):
presets_with_creds = []
preset_names = self.credentialstore.list_names()
for preset_name in preset_names:
presets_with_creds.append(self.credentialstore.get_creds(preset_name))
return presets_with_creds
def add_preset_to_combobox(self, preset):
self.comboBoxPresetLeft.addItem(preset)
self.comboBoxPresetRight.addItem(preset)
return
def remove_preset_from_combobox(self, preset):
index = self.comboBoxPresetLeft.findText(preset)
self.comboBoxPresetLeft.removeItem(index)
index = self.comboBoxPresetRight.findText(preset)
self.comboBoxPresetRight.removeItem(index)
if self.comboBoxPresetLeft.count() == 0:
self.clear_creds()
return
# call this at startup or cred db is created, opened, or deleted to set all the buttons appropriately
# (also looks config file settings and which tab is selected.)
# this works but it's a mess. There's gotta be a better way.
def set_creddbbuttons(self):
db_file = pathlib.Path('credentials.db')
if db_file.is_file():
db_file_exists = True
else:
db_file_exists = False
# The search tab only uses the left credentials, so don't enable the right ones if we are in the search tab
tab = self.tabWidget.currentIndex()
if tab == 2: # Index 2 from the tab widget is the search tab
disable_right_cred__buttons = True
else:
disable_right_cred__buttons = False
config_value = self.config['Credential Store']['credential_store_implementation']
# Turn the left and right create preset buttons on or off depending on
# 1. What our config file says
# 2. If we've authenticated against a credential store
# 3. For the right sight, whether we are in the search tab
if (config_value == 'built_in') and \
(self.cred_db_authenticated is True):
self.pushButtonCreatePresetLeft.setEnabled(True)
if disable_right_cred__buttons:
self.pushButtonCreatePresetRight.setEnabled(False)
else:
self.pushButtonCreatePresetRight.setEnabled(True)
else:
self.pushButtonCreatePresetLeft.setEnabled(False)
self.pushButtonCreatePresetRight.setEnabled(False)
# Turn the left and right update preset buttons on or off depending on
# 1. What our config file says
# 2. If we've authenticated against a credential store
# 3. For the right sight, whether we are in the search tab
if (config_value == 'built_in') and \
(self.cred_db_authenticated is True):
self.pushButtonUpdatePresetLeft.setEnabled(True)
if disable_right_cred__buttons:
self.pushButtonUpdatePresetRight.setEnabled(False)
else:
self.pushButtonUpdatePresetRight.setEnabled(True)
else:
self.pushButtonUpdatePresetLeft.setEnabled(False)
self.pushButtonUpdatePresetRight.setEnabled(False)
# Turn the left and right delete preset buttons on or off depending on
# 1. What our config file says
# 2. If we've authenticated against a credential store
# 3. For the right sight, whether we are in the search tab
if (config_value == 'built_in') and \
(self.cred_db_authenticated is True):
self.pushButtonDeletePresetLeft.setEnabled(True)
if disable_right_cred__buttons:
self.pushButtonDeletePresetRight.setEnabled(False)
else:
self.pushButtonDeletePresetRight.setEnabled(True)
else:
self.pushButtonDeletePresetLeft.setEnabled(False)
self.pushButtonDeletePresetRight.setEnabled(False)
# Turn the left and right preset dropdowns depending on
# 1. What our config file says
# 2. If we've authenticated against a credential store
# 3. For the right sight, whether we are in the search tab
if (self.cred_db_authenticated is True) and\
(config_value != 'none'):
self.comboBoxPresetLeft.setEnabled(True)
if disable_right_cred__buttons:
self.comboBoxPresetRight.setEnabled(False)
else:
self.comboBoxPresetRight.setEnabled(True)
else:
self.comboBoxPresetLeft.setEnabled(False)
self.comboBoxPresetRight.setEnabled(False)
# Turn the create and delete cred DB buttons depending on
# 1. What the config file says
# 2. if a credentials.db file exists
if (config_value == 'built_in'):
if db_file_exists:
self.pushButtonCreateCredentialDatabase.setEnabled(False)
self.pushButtonDeleteCredentialDatabase.setEnabled(True)
else:
self.pushButtonCreateCredentialDatabase.setEnabled(True)
self.pushButtonDeleteCredentialDatabase.setEnabled(False)
else:
self.pushButtonCreateCredentialDatabase.setEnabled(False)
self.pushButtonDeleteCredentialDatabase.setEnabled(False)
if (db_file_exists and config_value == 'built_in') or (config_value == 'read_only'):
self.pushButtonLoadCredentialDatabase.setEnabled(True)
else:
self.pushButtonLoadCredentialDatabase.setEnabled(False)
if config_value == 'none':
self.pushButtonCreateCredentialDatabase.setEnabled(False)
self.pushButtonLoadCredentialDatabase.setEnabled(False)
self.pushButtonDeleteCredentialDatabase.setEnabled(False)
return
# called when the create preset button is clicked
def create_preset(self, comboBoxRegion, lineEditUserName, lineEditPassword, comboBoxPreset, side):
logger.info('Creating preset in credential store.')
sumo_region = str(comboBoxRegion.currentText())
accesskeyid = str(lineEditUserName.text())
accesskey = str(lineEditPassword.text())
message = "Please type a name for the new preset."
preset_name, result = QtWidgets.QInputDialog.getText(self, 'Enter preset name', message)
if result:
if self.credentialstore.name_exists(preset_name):
self.errorbox('That name already exists in the credential database. Choose a new name or use "Update" to modify an existing entry.')
return
else:
self.create_preset_non_interactive(preset_name, sumo_region, accesskeyid, accesskey)
self.load_preset(preset_name, comboBoxRegion, lineEditUserName, lineEditPassword, comboBoxPreset, side)
return
def create_preset_non_interactive(self, preset_name, sumo_region, accesskeyid, accesskey):
if self.cred_db_authenticated == True:
deployment_conversion = { 'fra': 'DE',
'dub': 'EU',
'mum': 'IN',
'tky': 'JP',
'syd': 'AU',
'prod': 'US1',
'us2': 'US2',
'fed': 'FED',
'mon': 'CA',
'de': 'DE',
'eu': 'EU',
'in': 'IN',
'jp': 'JP',
'au': 'AU',
'us1': 'US1',
'ca': 'CA'}
if str(sumo_region).lower() in deployment_conversion:
deployment = deployment_conversion[str(sumo_region).lower()]
else:
logger.info(f'Unknown deployment: {sumo_region}')
return 'ERROR'
try:
self.credentialstore.add_creds(preset_name, deployment, accesskeyid, accesskey)
self.add_preset_to_combobox(preset_name)
except Exception as e:
logger.exception(e)
return
else:
return "NOAUTH"
# This exists for an edge case. If there is only one entry in the preset list and the user edits/modifies
# the cred text then clicking on the preset will not reload the cred because the index hasn't changed.
# This solves this problem
# called when the user selects an item from the preset dropdown
def preset_activated(self, preset, comboBoxRegion, lineEditUserName, lineEditPassword, comboBoxPreset, side):
if comboBoxPreset.count() == 1:
self.load_preset(preset, comboBoxRegion, lineEditUserName, lineEditPassword, comboBoxPreset, side)
# called when the preset combobox index changes
def load_preset(self, preset, comboBoxRegion, lineEditUserName, lineEditPassword, comboBoxPreset, side):
logger.info('Loading preset from credential store.')
# even though we're about to load a new preset we should still clear the boxes in the eventuality
# that the last preset was deleted and we've got nothing to load
lineEditUserName.clear()
lineEditPassword.clear()
if preset == ' ':
if side == 'left':
self.lineEditUserNameLeft.clear()
self.lineEditPasswordLeft.clear()
if side == 'right':
self.lineEditUserNameRight.clear()
self.lineEditPasswordRight.clear()
return
if comboBoxPreset.count() > 0:
try:
if self.credentialstore.name_exists(preset):
creds = self.credentialstore.get_creds(preset)
index = comboBoxPreset.findText(preset, QtCore.Qt.MatchFixedString)
if index >=0:
comboBoxPreset.setCurrentIndex(index)
index = comboBoxRegion.findText(creds['sumoregion'], QtCore.Qt.MatchFixedString)
if index >=0:
comboBoxRegion.setCurrentIndex(index)
lineEditUserName.setText(creds['accesskeyid'])
lineEditPassword.setText(creds['accesskey'])
# since we've changed the preset all of the stateful tabs need to be reset
# otherwise they will still be showing items from the previous preset
self.reset_stateful_objects(side=side)
else:
raise Exception('That preset is not in the database.')
except Exception as e:
logger.exception(e)
self.errorbox('Something went wrong\n\n' + str(e))
# called when the delete preset button is clicked
def delete_preset(self, preset, comboBoxRegion, lineEditUserName, lineEditPassword, comboBoxPreset, side):
logger.info('Deleting preset from credential store.')
if preset:
if self.credentialstore.name_exists(preset):
try:
result = self.credentialstore.delete_creds(preset)
self.remove_preset_from_combobox(preset)
preset = comboBoxPreset.currentText()
# load the first preset in the list (if it's there)
if preset:
self.load_preset(
preset,
comboBoxRegion,
lineEditUserName,
lineEditPassword,
comboBoxPreset,
side
)
except Exception as e:
logger.exception(e)
self.errorbox('Something went wrong\n\n' + str(e))
else:
self.errorbox('Something went wrong. That preset does not exist in the database.')
# called when the update preset button is clicked
def update_preset(self, preset, sumoregion, accesskeyid, accesskey):
logger.info('Updating preset in credential store.')
if preset:
if self.credentialstore.name_exists(preset):
try:
result = self.credentialstore.update_creds(preset, sumoregion, accesskeyid, accesskey)
except Exception as e:
logger.exception(e)
self.errorbox('Something went wrong\n\n' + str(e))
else:
self.errorbox('Something went wrong. That preset does not exist in the database.')
return
# Start Methods for Search Tab
def runsearch(self, url, id, key):
logger.info("Running a Search")
self.tableWidgetSearchResults.clear()
selectedtimezone = str(self.comboBoxTimeZone.currentText())
timezone = pytz.timezone(selectedtimezone)
starttime = str(self.dateTimeEditSearchStartTime.dateTime().toString(QtCore.Qt.ISODate))
#starttime = timezone.localize(starttime).dst()
endtime = str(self.dateTimeEditSearchEndTime.dateTime().toString(QtCore.Qt.ISODate))
searchstring = str(self.plainTextEditSearch.toPlainText())
regexprog = re.compile(r'\S+')
jobsubmitted = False
csvheaderwritten = False
savetofile = self.checkBoxSaveSearch.isChecked()
converttimefromepoch = self.checkBoxConvertTimeFromEpoch.isChecked()
jobmessages = []
jobrecords = []
if savetofile:
filenameqstring, _ = QtWidgets.QFileDialog.getSaveFileName(self, 'Save CSV', '', filter='*.csv')
filename = str(filenameqstring)
savefilepath = pathlib.Path(filename)
if (re.match(regexprog, id) != None) and (re.match(regexprog, key) != None):
sumo = SumoLogic(id, key, endpoint=url, log_level=self.log_level)
if (re.match(regexprog, searchstring)) != None:
try:
searchjob = sumo.search_job(searchstring, starttime, endtime, selectedtimezone)
jobsubmitted = True
except Exception as e:
self.errorbox("Failed to submit search job. Check credentials, endpoint, and query.")
logger.exception(e)
return
if jobsubmitted:
try:
self.labelSearchResultCount.setText('0')
jobstatus = sumo.search_job_status(searchjob)
nummessages = jobstatus['messageCount']
numrecords = jobstatus['recordCount']
self.labelSearchResultCount.setText(str(nummessages))
while jobstatus['state'] == 'GATHERING RESULTS':
jobstatus = sumo.search_job_status(searchjob)
numrecords = jobstatus['recordCount']
nummessages = jobstatus['messageCount']
self.labelSearchResultCount.setText(str(nummessages))
logger.info('Search Job finished. Downloading Results.')
except Exception as e:
logger.exception(e)
self.errorbox("Something went wrong\n\n" + str(e))
if nummessages != 0:
# return messages
if self.buttonGroupOutputType.checkedId() == -2:
iterations = nummessages // 10000 + 1
try:
for iteration in range(1, iterations + 1):
messages = sumo.search_job_messages(searchjob, limit=10000,
offset=((iteration - 1) * 10000))
logger.info('Downloaded 1 block of messages.')
if savetofile:
logger.info('Saving messages to file.')
for message in messages['messages']: