forked from hiviah/TrezorPass
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdialogs.py
1072 lines (910 loc) · 37.5 KB
/
dialogs.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
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import os
import base64
import hashlib
from shutil import copyfile
import time
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog, QDialogButtonBox
from PyQt5.QtWidgets import QMessageBox, QFileDialog, QLineEdit, QShortcut
from PyQt5.QtWidgets import QAbstractItemView, QTableWidgetItem
from PyQt5.QtWidgets import QMenu, QAction, QHeaderView
from PyQt5.QtGui import QPixmap, QKeySequence, QTextDocument, QStandardItem
from PyQt5.QtGui import QStandardItemModel
from PyQt5.QtCore import QT_VERSION_STR, QTimer, QDir, Qt, QVariant
from PyQt5.QtCore import QSortFilterProxyModel, QItemSelectionModel
from PyQt5.Qt import PYQT_VERSION_STR
from trezorlib.client import CallException
from ui_initialize_dialog import Ui_InitializeDialog
from ui_add_group_dialog import Ui_AddGroupDialog
from ui_add_password_dialog import Ui_AddPasswordDialog
from ui_main_window import Ui_MainWindow
import basics
import encoding
"""
This code should cover the GUI of the business logic of the application.
Code should work on both Python 2.7 as well as 3.4.
Requires PyQt5.
(Old version supported PyQt4.)
"""
class InitializeDialog(QDialog, Ui_InitializeDialog):
def __init__(self):
super(InitializeDialog, self).__init__()
# Set up the user interface from Designer.
self.setupUi(self)
# Make some local modifications.
self.masterEdit1.textChanged.connect(self.validate)
self.masterEdit2.textChanged.connect(self.validate)
self.pwFileEdit.textChanged.connect(self.validate)
self.pwFileButton.clicked.connect(self.selectPwFile)
self.validate()
def setPw1(self, pw):
self.masterEdit1.setText(encoding.normalize_nfc(pw))
def setPw2(self, pw):
self.masterEdit2.setText(encoding.normalize_nfc(pw))
def pw1(self):
return encoding.normalize_nfc(self.masterEdit1.text())
def pw2(self):
return encoding.normalize_nfc(self.masterEdit2.text())
def pwFile(self):
return encoding.normalize_nfc(self.pwFileEdit.text())
def validate(self):
"""
Enable OK button only if both master and backup are repeated
without typo and some password file is selected.
"""
same = self.pw1() == self.pw2()
fileSelected = (self.pwFileEdit.text() != u'')
button = self.buttonBox.button(QDialogButtonBox.Ok)
button.setEnabled(same and fileSelected)
def selectPwFile(self):
"""
Show file dialog and return file user chose to store the
encrypted password database.
"""
path = QDir.currentPath()
dialog = QFileDialog(self, u"Select password database file",
path, "(*"+basics.PWDB_FILEEXT+")")
dialog.setAcceptMode(QFileDialog.AcceptSave)
res = dialog.exec_()
if not res:
return
fname = dialog.selectedFiles()[0]
self.pwFileEdit.setText(fname)
class AddGroupDialog(QDialog, Ui_AddGroupDialog):
def __init__(self, groups, settings):
super(AddGroupDialog, self).__init__()
self.setupUi(self)
self.newGroupEdit.textChanged.connect(self.validate)
self.groups = groups
self.settings = settings
# disabled for empty string
button = self.buttonBox.button(QDialogButtonBox.Ok)
button.setEnabled(False)
def newGroupName(self):
return encoding.normalize_nfc(self.newGroupEdit.text())
def setNewGroupName(self, text):
self.newGroupEdit.setText(encoding.normalize_nfc(text))
def validate(self):
"""
Validates input if name is not empty and is different from
existing group names.
"""
valid = True
text = self.newGroupName()
if text == u'':
valid = False
if text in self.groups:
self.settings.mlogger.log('Group "%s" already exists. Cannot have '
'duplicate group names. Try a different name.' % (text),
logging.DEBUG, "Arguments")
valid = False
button = self.buttonBox.button(QDialogButtonBox.Ok)
button.setEnabled(valid)
class AddPasswordDialog(QDialog, Ui_AddPasswordDialog):
def __init__(self, trezor, settings):
super(AddPasswordDialog, self).__init__()
self.setupUi(self)
self.pwEdit1.textChanged.connect(self.validatePw)
self.pwEdit2.textChanged.connect(self.validatePw)
self.showHideButton.clicked.connect(self.switchPwVisible)
self.generatePasswordButton.clicked.connect(self.generatePassword)
self.trezor = trezor
self.settings = settings
def key(self):
return encoding.normalize_nfc(self.keyEdit.text())
def pw1(self):
return encoding.normalize_nfc(self.pwEdit1.text())
def pw2(self):
return encoding.normalize_nfc(self.pwEdit2.text())
def comments(self):
doc = self.commentsEdit.document().toPlainText()
if doc is None:
doc = u''
else:
doc = encoding.normalize_nfc(doc)
return doc
def validatePw(self):
same = self.pw1() == self.pw2()
button = self.buttonBox.button(QDialogButtonBox.Ok)
button.setEnabled(same)
def switchPwVisible(self):
pwMode = self.pwEdit1.echoMode()
if pwMode == QLineEdit.Password:
newMode = QLineEdit.Normal
else:
newMode = QLineEdit.Password
self.pwEdit1.setEchoMode(newMode)
self.pwEdit2.setEchoMode(newMode)
def generatePassword(self):
trezor_entropy = self.trezor.get_entropy(32)
urandom_entropy = os.urandom(32)
passwdBytes = hashlib.sha256(trezor_entropy + urandom_entropy).digest()
# base85 encoding not yet implemented in Python 2.7, (requires Python 3+)
# so we use base64 encoding
# remove the base64 buffer char =, remove easily confused chars 0 and O, as well as I and l
passwdB64bytes = base64.urlsafe_b64encode(passwdBytes)
passwdB64bytes.replace(b'=', '')
passwdB64bytes.replace(b'0', '')
passwdB64bytes.replace(b'O', '')
passwdB64bytes.replace(b'I', '')
passwdB64bytes.replace(b'l', '')
# print "bin =", passwdBin, ", base =", passwdB64, " binlen =", len(passwdBin), "baselen =", len(passwdB64)
# instead of setting the values, we concatenate them to the existing values
# This way, by clicking the "Generate password" button one can create an arbitrary long random password.
self.pwEdit1.setText(self.pw1() + encoding.normalize_nfc(passwdB64bytes))
self.pwEdit2.setText(self.pw2() + encoding.normalize_nfc(passwdB64bytes))
class MainWindow(QMainWindow, Ui_MainWindow):
"""
Main window for the application with groups and password lists
"""
KEY_IDX = 0 # column where key is shown in password table
PASSWORD_IDX = 1 # column where password is shown in password table
COMMENTS_IDX = 2 # column where comments is shown in password table
NO_OF_PASSWDTABLE_COLUMNS = 3 # 3 columns: key + value/passwd/secret + comments
CACHE_IDX = 0 # column of QWidgetItem in whose data we cache decrypted passwords+comments
def __init__(self, pwMap, settings, dbFilename):
"""
@param pwMap: a PasswordMap instance with encrypted passwords
@param dbFilename: file name for saving pwMap
"""
super(MainWindow, self).__init__()
self.setupUi(self)
self.logger = settings.logger
self.settings = settings
self.pwMap = pwMap
self.selectedGroup = None
self.modified = False # modified flag for "Save?" question on exit
self.dbFilename = dbFilename
self.groupsModel = QStandardItemModel(parent=self)
self.groupsModel.setHorizontalHeaderLabels([u"Password group"])
self.groupsFilter = QSortFilterProxyModel(parent=self)
self.groupsFilter.setSourceModel(self.groupsModel)
self.groupsTree.setModel(self.groupsFilter)
self.groupsTree.setContextMenuPolicy(Qt.CustomContextMenu)
self.groupsTree.customContextMenuRequested.connect(self.showGroupsContextMenu)
# Dont use e following line, it would cause loadPasswordsBySelection
# to be called twice on mouse-click.
# self.groupsTree.clicked.connect(self.loadPasswordsBySelection)
self.groupsTree.selectionModel().selectionChanged.connect(self.loadPasswordsBySelection)
self.groupsTree.setSortingEnabled(True)
self.passwordTable.setContextMenuPolicy(Qt.CustomContextMenu)
self.passwordTable.customContextMenuRequested.connect(self.showPasswdContextMenu)
self.passwordTable.setSelectionBehavior(QAbstractItemView.SelectRows)
self.passwordTable.setSelectionMode(QAbstractItemView.SingleSelection)
shortcut = QShortcut(QKeySequence(u"Ctrl+C"), self.passwordTable, self.copyPasswordFromSelection)
shortcut.setContext(Qt.WidgetShortcut)
self.actionQuit.triggered.connect(self.close)
self.actionQuit.setShortcut(QKeySequence(u"Ctrl+Q"))
self.actionExport.triggered.connect(self.exportCsv)
self.actionImport.triggered.connect(self.importCsv)
self.actionBackup.triggered.connect(self.saveBackup)
self.actionAbout.triggered.connect(self.printAbout)
self.actionSave.triggered.connect(self.saveDatabase)
self.actionSave.setShortcut(QKeySequence(u"Ctrl+S"))
# headerKey = QTableWidgetItem(u"Key")
# headerValue = QTableWidgetItem(u"Password/Value")
# headerComments = QTableWidgetItem(u"Comments")
# self.passwordTable.setColumnCount(self.NO_OF_PASSWDTABLE_COLUMNS)
# self.passwordTable.setHorizontalHeaderItem(self.KEY_IDX, headerKey)
# self.passwordTable.setHorizontalHeaderItem(self.PASSWORD_IDX, headerValue)
# self.passwordTable.setHorizontalHeaderItem(self.COMMENTS_IDX, headerComments)
#
# self.passwordTable.resizeRowsToContents()
# self.passwordTable.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
# self.passwordTable.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeToContents)
# self.passwordTable.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeToContents)
self.searchEdit.textChanged.connect(self.filterGroups)
if pwMap is not None:
self.setPwMap(pwMap)
self.clipboard = QApplication.clipboard()
self.timer = QTimer(parent=self)
self.timer.timeout.connect(self.clearClipboard)
def setPwMap(self, pwMap):
""" if not done in __init__ pwMap can be supplied later """
self.pwMap = pwMap
groupNames = self.pwMap.groups.keys()
for groupName in groupNames:
item = QStandardItem(groupName)
self.groupsModel.appendRow(item)
self.groupsTree.sortByColumn(0, Qt.AscendingOrder)
self.settings.mlogger.log("pwMap was initialized.",
logging.DEBUG, "GUI IO")
def setModified(self, modified):
"""
Sets the modified flag so that user is notified when exiting
with unsaved changes.
"""
self.modified = modified
self.setWindowTitle("TrezorPass" + "*" * int(self.modified))
def showGroupsContextMenu(self, point):
"""
Show context menu for group management.
@param point: point in self.groupsTree where click occured
"""
self.addGroupMenu = QMenu(self)
newGroupAction = QAction('Add group', self)
editGroupAction = QAction('Rename group', self)
deleteGroupAction = QAction('Delete group', self)
self.addGroupMenu.addAction(newGroupAction)
self.addGroupMenu.addAction(editGroupAction)
self.addGroupMenu.addAction(deleteGroupAction)
# disable deleting if no point is clicked on
proxyIdx = self.groupsTree.indexAt(point)
itemIdx = self.groupsFilter.mapToSource(proxyIdx)
item = self.groupsModel.itemFromIndex(itemIdx)
if item is None:
deleteGroupAction.setEnabled(False)
action = self.addGroupMenu.exec_(self.groupsTree.mapToGlobal(point))
if action == newGroupAction:
self.createGroupWithCheck()
elif action == editGroupAction:
self.editGroupWithCheck(item)
elif action == deleteGroupAction:
self.deleteGroupWithCheck(item)
def showPasswdContextMenu(self, point):
"""
Show context menu for password management
@param point: point in self.passwordTable where click occured
"""
self.passwdMenu = QMenu(self)
showPasswordAction = QAction('Show password', self)
copyPasswordAction = QAction('Copy password', self)
copyPasswordAction.setShortcut(QKeySequence("Ctrl+C"))
showCommentsAction = QAction('Show comments', self)
copyCommentsAction = QAction('Copy comments', self)
showAllAction = QAction('Show all of group', self)
newItemAction = QAction('New item', self)
deleteItemAction = QAction('Delete item', self)
editItemAction = QAction('Edit item', self)
self.passwdMenu.addAction(showPasswordAction)
self.passwdMenu.addAction(copyPasswordAction)
self.passwdMenu.addSeparator()
self.passwdMenu.addAction(showCommentsAction)
self.passwdMenu.addAction(copyCommentsAction)
self.passwdMenu.addSeparator()
self.passwdMenu.addAction(showAllAction)
self.passwdMenu.addSeparator()
self.passwdMenu.addAction(newItemAction)
self.passwdMenu.addAction(deleteItemAction)
self.passwdMenu.addAction(editItemAction)
# disable creating if no group is selected
if self.selectedGroup is None:
newItemAction.setEnabled(False)
showAllAction.setEnabled(False)
# disable deleting if no point is clicked on
item = self.passwordTable.itemAt(point.x(), point.y())
if item is None:
deleteItemAction.setEnabled(False)
showPasswordAction.setEnabled(False)
copyPasswordAction.setEnabled(False)
showCommentsAction.setEnabled(False)
copyCommentsAction.setEnabled(False)
editItemAction.setEnabled(False)
action = self.passwdMenu.exec_(self.passwordTable.mapToGlobal(point))
if action == newItemAction:
self.createPassword()
elif action == deleteItemAction:
self.deletePassword(item)
elif action == editItemAction:
self.editPassword(item)
elif action == copyPasswordAction:
self.copyPasswordFromItem(item)
elif action == showPasswordAction:
self.showPassword(item)
elif action == copyCommentsAction:
self.copyCommentsFromItem(item)
elif action == showCommentsAction:
self.showComments(item)
elif action == showAllAction:
self.showAll()
def createGroup(self, groupName, group=None):
"""
Slot to create a password group.
"""
newItem = QStandardItem(groupName)
self.groupsModel.appendRow(newItem)
self.pwMap.addGroup(groupName)
if group is not None:
self.pwMap.replaceGroup(groupName, group)
# make new item selected to save a few clicks
itemIdx = self.groupsModel.indexFromItem(newItem)
proxyIdx = self.groupsFilter.mapFromSource(itemIdx)
self.groupsTree.selectionModel().select(proxyIdx,
QItemSelectionModel.ClearAndSelect | QItemSelectionModel.Rows)
self.groupsTree.sortByColumn(0, Qt.AscendingOrder)
# Make item's passwords loaded so new key-value entries can be created
# right away - better from UX perspective.
self.loadPasswords(newItem)
self.setModified(True)
self.settings.mlogger.log("Group '%s' was created." % (groupName),
logging.DEBUG, "GUI IO")
def createGroupWithCheck(self):
"""
Slot to create a password group.
"""
dialog = AddGroupDialog(self.pwMap.groups, self.settings)
if not dialog.exec_():
return
groupName = dialog.newGroupName()
self.createGroup(groupName)
def createRenamedGroupWithCheck(self, groupNameOld, groupNameNew):
"""
Creates a copy of a group by name as utf-8 encoded string
with a new group name.
A more appropriate name for the method would be:
createRenamedGroup().
Since the entries inside the group are encrypted
with the groupName, we cannot simply make a copy.
We must decrypt with old name and afterwards encrypt
with new name.
If the group has many entries, each entry would require a 'Confirm'
press on Trezor. So, to mkae it faster and more userfriendly
we use the backup key to decrypt. This requires a single
Trezor 'Confirm' press independent of how many entries there are
in the group.
@param groupNameOld: name of group to copy and rename
@type groupNameOld: string
@param groupNameNew: name of group to be created
@type groupNameNew: string
"""
if groupNameOld not in self.pwMap.groups:
raise KeyError("Password group does not exist")
# with less than 3 rows dont bother the user with a pop-up
rowCount = len(self.pwMap.groups[groupNameOld].entries)
if rowCount < 3:
self.pwMap.createRenamedGroupSecure(groupNameOld, groupNameNew)
return
msgBox = QMessageBox(parent=self)
msgBox.setText("Do you want to use the more secure way?")
msgBox.setIcon(QMessageBox.Question)
msgBox.setWindowTitle("How to decrypt?")
msgBox.setDetailedText("The more secure way requires pressing 'Confirm' "
"on Trezor once for each entry in the group. %d presses in this "
"case. This is recommended. "
"Select 'Yes'.\n\n"
"The less secure way requires only a single 'Confirm' click on the "
"Trezor. This is not recommended. "
"Select 'No'." % (rowCount))
msgBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
msgBox.setDefaultButton(QMessageBox.Yes)
res = msgBox.exec_()
if res == QMessageBox.Yes:
moreSecure = True
else:
moreSecure = False
groupNew = self.pwMap.createRenamedGroup(groupNameOld, groupNameNew, moreSecure)
self.settings.mlogger.log("Copy of group '%s' with new name '%s' "
"was created the %s way." %
(groupNameOld, groupNameNew, 'secure' if moreSecure else 'fast'),
logging.DEBUG, "GUI IO")
return(groupNew)
def editGroup(self, item, groupNameOld, groupNameNew):
"""
Slot to edit name a password group.
"""
groupNew = self.createRenamedGroupWithCheck(groupNameOld, groupNameNew)
self.deleteGroup(item)
self.createGroup(groupNameNew, groupNew)
self.settings.mlogger.log("Group '%s' was renamed to '%s'." % (groupNameOld, groupNameNew),
logging.DEBUG, "GUI IO")
def editGroupWithCheck(self, item):
"""
Slot to edit name a password group.
"""
groupNameOld = encoding.normalize_nfc(item.text())
dialog = AddGroupDialog(self.pwMap.groups, self.settings)
dialog.setWindowTitle("Edit group name")
dialog.groupNameLabel.setText("New name for group")
dialog.setNewGroupName(groupNameOld)
if not dialog.exec_():
return
groupNameNew = dialog.newGroupName()
self.editGroup(item, groupNameOld, groupNameNew)
def deleteGroup(self, item): # without checking user
groupName = encoding.normalize_nfc(item.text())
self.selectedGroup = None
del self.pwMap.groups[groupName]
itemIdx = self.groupsModel.indexFromItem(item)
self.groupsModel.takeRow(itemIdx.row())
self.passwordTable.setRowCount(0)
self.groupsTree.clearSelection()
self.setModified(True)
self.settings.mlogger.log("Group '%s' was deleted." % (groupName),
logging.DEBUG, "GUI IO")
def deleteGroupWithCheck(self, item):
msgBox = QMessageBox(text="Are you sure about delete?", parent=self)
msgBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
res = msgBox.exec_()
if res != QMessageBox.Yes:
return
self.deleteGroup(item)
def deletePassword(self, item):
msgBox = QMessageBox(text="Are you sure about delete?", parent=self)
msgBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
res = msgBox.exec_()
if res != QMessageBox.Yes:
return
row = self.passwordTable.row(item)
self.passwordTable.removeRow(row)
group = self.pwMap.groups[self.selectedGroup]
group.removeEntry(row)
self.passwordTable.resizeRowsToContents()
self.passwordTable.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
self.passwordTable.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeToContents)
self.passwordTable.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeToContents)
self.setModified(True)
self.settings.mlogger.log("Row '%d' was deleted." % (row),
logging.DEBUG, "GUI IO")
def logCache(self, row):
item = self.passwordTable.item(row, self.CACHE_IDX)
cachedTuple = item.data(Qt.UserRole)
if cachedTuple is None:
cachedPassword, cachedComments = (None, None)
else:
cachedPassword, cachedComments = cachedTuple
if cachedPassword is not None:
cachedPassword = u'***'
if cachedComments is not None:
cachedComments = cachedComments[0:3] + u'...'
self.settings.mlogger.log("Cache holds '%s' and '%s'." %
(cachedPassword, cachedComments), logging.DEBUG, "Cache")
def cachePasswordComments(self, row, password, comments):
item = self.passwordTable.item(row, self.CACHE_IDX)
item.setData(Qt.UserRole, QVariant((password, comments)))
def cachedPassword(self, row):
"""
Retrieve cached password for given row of currently selected group.
Returns password as string or None if no password cached.
"""
item = self.passwordTable.item(row, self.CACHE_IDX)
cachedTuple = item.data(Qt.UserRole)
if cachedTuple is None:
cachedPassword, cachedComments = (None, None)
else:
cachedPassword, cachedComments = cachedTuple
return cachedPassword
def cachedComments(self, row):
"""
Retrieve cached comments for given row of currently selected group.
Returns comments as string or None if no coments cached.
"""
item = self.passwordTable.item(row, self.CACHE_IDX)
cachedTuple = item.data(Qt.UserRole)
if cachedTuple is None:
cachedPassword, cachedComments = (None, None)
else:
cachedPassword, cachedComments = cachedTuple
return cachedComments
def cachedOrDecryptPassword(self, row):
"""
Try retrieving cached password for item in given row, otherwise
decrypt with Trezor.
"""
cached = self.cachedPassword(row)
if cached is not None:
return cached
else: # decrypt with Trezor
group = self.pwMap.groups[self.selectedGroup]
pwEntry = group.entry(row)
encPwComments = pwEntry[1]
decryptedPwComments = self.pwMap.decryptPassword(encPwComments, self.selectedGroup)
lngth = int(decryptedPwComments[0:4])
decryptedPassword = decryptedPwComments[4:4+lngth]
decryptedComments = decryptedPwComments[4+lngth:]
# while we are at it, cache the comments too
self.cachePasswordComments(row, decryptedPassword, decryptedComments)
self.settings.mlogger.log("Decrypted password and comments "
"for '%s', row '%d'." % (pwEntry[0], row),
logging.DEBUG, "GUI IO")
return decryptedPassword
def cachedOrDecryptComments(self, row):
"""
Try retrieving cached comments for item in given row, otherwise
decrypt with Trezor.
"""
cached = self.cachedComments(row)
if cached is not None:
return cached
else: # decrypt with Trezor
group = self.pwMap.groups[self.selectedGroup]
pwEntry = group.entry(row)
encPwComments = pwEntry[1]
decryptedPwComments = self.pwMap.decryptPassword(encPwComments, self.selectedGroup)
lngth = int(decryptedPwComments[0:4])
decryptedPassword = decryptedPwComments[4:4+lngth]
decryptedComments = decryptedPwComments[4+lngth:]
self.cachePasswordComments(row, decryptedPassword, decryptedComments)
self.settings.mlogger.log("Decrypted password and comments "
"for '%s', row '%d'." % (pwEntry[0], row),
logging.DEBUG, "GUI IO")
return decryptedComments
def showPassword(self, item):
# check if this password has been decrypted, use cached version
row = self.passwordTable.row(item)
self.logCache(row)
try:
decryptedPassword = self.cachedOrDecryptPassword(row)
except CallException:
return
item = QTableWidgetItem(decryptedPassword)
self.passwordTable.setItem(row, self.PASSWORD_IDX, item)
def showComments(self, item):
# check if these comments has been decrypted, use cached version
row = self.passwordTable.row(item)
try:
decryptedComments = self.cachedOrDecryptComments(row)
except CallException:
return
item = QTableWidgetItem(decryptedComments)
self.passwordTable.setItem(row, self.COMMENTS_IDX, item)
def showAllSecure(self):
rowCount = self.passwordTable.rowCount()
for row in range(rowCount):
try:
decryptedPassword = self.cachedOrDecryptPassword(row)
except CallException:
return
item = QTableWidgetItem(decryptedPassword)
self.passwordTable.setItem(row, self.PASSWORD_IDX, item)
try:
decryptedComments = self.cachedOrDecryptComments(row)
except CallException:
return
item = QTableWidgetItem(decryptedComments)
self.passwordTable.setItem(row, self.COMMENTS_IDX, item)
self.settings.mlogger.log("Showed all entries for group '%s' the secure way." %
(self.selectedGroup), logging.DEBUG, "GUI IO")
def showAllFast(self):
try:
privateKey = self.pwMap.backupKey.unwrapPrivateKey()
except CallException:
return
group = self.pwMap.groups[self.selectedGroup]
row = 0
for key, _, bkupPw in group.entries:
decryptedPwComments = self.pwMap.backupKey.decryptPassword(bkupPw, privateKey)
lngth = int(decryptedPwComments[0:4])
password = decryptedPwComments[4:4+lngth]
comments = decryptedPwComments[4+lngth:]
item = QTableWidgetItem(key)
pwItem = QTableWidgetItem(password)
commentsItem = QTableWidgetItem(comments)
self.passwordTable.setItem(row, self.KEY_IDX, item)
self.passwordTable.setItem(row, self.PASSWORD_IDX, pwItem)
self.passwordTable.setItem(row, self.COMMENTS_IDX, commentsItem)
self.cachePasswordComments(row, password, comments)
row = row+1
self.passwordTable.resizeRowsToContents()
self.passwordTable.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
self.passwordTable.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeToContents)
self.passwordTable.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeToContents)
self.settings.mlogger.log("Showed all entries for group '%s' the fast way." %
(self.selectedGroup), logging.DEBUG, "GUI IO")
def showAll(self):
"""
show all passwords and comments in plaintext in GUI
can be called without any password selectedGroup
a group must be selected
"""
# with less than 3 rows dont bother the user with a pop-up
if self.passwordTable.rowCount() < 3:
self.showAllSecure()
return
msgBox = QMessageBox(parent=self)
msgBox.setText("Do you want to use the more secure way?")
msgBox.setIcon(QMessageBox.Question)
msgBox.setWindowTitle("How to decrypt?")
msgBox.setDetailedText("The more secure way requires pressing 'Confirm' "
"on Trezor once for each entry in the group. %d presses in this "
"case. This is recommended. "
"Select 'Yes'.\n\n"
"The less secure way requires only a single 'Confirm' click on the "
"Trezor. This is not recommended. "
"Select 'No'." % (self.passwordTable.rowCount()))
msgBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
msgBox.setDefaultButton(QMessageBox.Yes)
res = msgBox.exec_()
if res == QMessageBox.Yes:
self.showAllSecure()
else:
self.showAllFast()
def createPassword(self):
"""
Slot to create key-value password entry.
"""
if self.selectedGroup is None:
return
group = self.pwMap.groups[self.selectedGroup]
dialog = AddPasswordDialog(self.pwMap.trezor, self.settings)
if not dialog.exec_():
return
plainPw = dialog.pw1()
plainComments = dialog.comments()
if len(plainPw) + len(plainComments) > basics.MAX_SIZE_OF_PASSWDANDCOMMENTS:
self.settings.mlogger.log("Password and/or comments too long. "
"Combined they must not be larger than %d." %
basics.MAX_SIZE_OF_PASSWDANDCOMMENTS,
logging.CRITICAL, "User IO")
return
row = self.passwordTable.rowCount()
self.passwordTable.setRowCount(row+1)
item = QTableWidgetItem(dialog.key())
pwItem = QTableWidgetItem("*****")
commentsItem = QTableWidgetItem("*****")
self.passwordTable.setItem(row, self.KEY_IDX, item)
self.passwordTable.setItem(row, self.PASSWORD_IDX, pwItem)
self.passwordTable.setItem(row, self.COMMENTS_IDX, commentsItem)
plainPwComments = ("%4d" % len(plainPw)) + plainPw + plainComments
encPw = self.pwMap.encryptPassword(plainPwComments, self.selectedGroup)
bkupPw = self.pwMap.backupKey.encryptPassword(plainPwComments)
group.addEntry(dialog.key(), encPw, bkupPw)
self.cachePasswordComments(row, plainPw, plainComments)
self.passwordTable.resizeRowsToContents()
self.passwordTable.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
self.passwordTable.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeToContents)
self.passwordTable.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeToContents)
self.setModified(True)
self.settings.mlogger.log("Password and comments entry "
"for '%s', row '%d' was created." % (dialog.key(), row),
logging.DEBUG, "GUI IO")
def editPassword(self, item):
row = self.passwordTable.row(item)
group = self.pwMap.groups[self.selectedGroup]
try:
decrypted = self.cachedOrDecryptPassword(row)
decryptedComments = self.cachedOrDecryptComments(row)
except CallException:
return
dialog = AddPasswordDialog(self.pwMap.trezor, self.settings)
entry = group.entry(row)
dialog.keyEdit.setText(encoding.normalize_nfc(entry[0]))
dialog.pwEdit1.setText(encoding.normalize_nfc(decrypted))
dialog.pwEdit2.setText(encoding.normalize_nfc(decrypted))
doc = QTextDocument(encoding.normalize_nfc(decryptedComments), parent=self)
dialog.commentsEdit.setDocument(doc)
if not dialog.exec_():
return
item = QTableWidgetItem(dialog.key())
pwItem = QTableWidgetItem("*****")
commentsItem = QTableWidgetItem("*****")
self.passwordTable.setItem(row, self.KEY_IDX, item)
self.passwordTable.setItem(row, self.PASSWORD_IDX, pwItem)
self.passwordTable.setItem(row, self.COMMENTS_IDX, commentsItem)
plainPw = dialog.pw1()
plainComments = dialog.comments()
if len(plainPw) + len(plainComments) > basics.MAX_SIZE_OF_PASSWDANDCOMMENTS:
self.settings.mlogger.log("Password and/or comments too long. "
"Combined they must not be larger than %d." %
basics.MAX_SIZE_OF_PASSWDANDCOMMENTS,
logging.CRITICAL, "User IO")
return
plainPwComments = ("%4d" % len(plainPw)) + plainPw + plainComments
encPw = self.pwMap.encryptPassword(plainPwComments, self.selectedGroup)
bkupPw = self.pwMap.backupKey.encryptPassword(plainPwComments)
group.updateEntry(row, dialog.key(), encPw, bkupPw)
self.cachePasswordComments(row, plainPw, plainComments)
self.setModified(True)
self.settings.mlogger.log("Password and comments entry "
"for '%s', row '%d' was edited." % (dialog.key(), row),
logging.DEBUG, "GUI IO")
def copyPasswordFromSelection(self):
"""
Copy selected password to clipboard. Password is decrypted if
necessary.
"""
indexes = self.passwordTable.selectedIndexes()
if not indexes:
return
# there will be more indexes as the selection is on a row
row = indexes[0].row()
item = self.passwordTable.item(row, self.PASSWORD_IDX)
self.copyPasswordFromItem(item)
def copyPasswordFromItem(self, item):
row = self.passwordTable.row(item)
try:
decryptedPassword = self.cachedOrDecryptPassword(row)
except CallException:
return
self.clipboard.setText(decryptedPassword)
# Do not log contents of clipboard, contains secrets!
self.settings.mlogger.log("Copied text to clipboard.", logging.DEBUG,
"Clipboard")
if basics.CLIPBOARD_TIMEOUT_IN_SEC > 0:
self.timer.start(basics.CLIPBOARD_TIMEOUT_IN_SEC*1000) # cancels previous timer
def copyCommentsFromItem(self, item):
row = self.passwordTable.row(item)
try:
decryptedComments = self.cachedOrDecryptComments(row)
except CallException:
return
self.clipboard.setText(decryptedComments)
# Do not log contents of clipboard, contains secrets!
self.settings.mlogger.log("Copied text to clipboard.", logging.DEBUG,
"Clipboard")
if basics.CLIPBOARD_TIMEOUT_IN_SEC > 0:
self.timer.start(basics.CLIPBOARD_TIMEOUT_IN_SEC*1000) # cancels previous timer
def clearClipboard(self):
self.clipboard.clear()
self.timer.stop() # cancels previous timer
self.settings.mlogger.log("Clipboard cleared.", logging.DEBUG,
"Clipboard")
def loadPasswords(self, item):
"""
Slot that should load items for group that has been clicked on.
"""
self.passwordTable.clear() # clears cahce, but also clears the header, the 3 titles
headerKey = QTableWidgetItem(u"Key")
headerValue = QTableWidgetItem(u"Password/Value")
headerComments = QTableWidgetItem(u"Comments")
self.passwordTable.setColumnCount(self.NO_OF_PASSWDTABLE_COLUMNS)
self.passwordTable.setHorizontalHeaderItem(self.KEY_IDX, headerKey)
self.passwordTable.setHorizontalHeaderItem(self.PASSWORD_IDX, headerValue)
self.passwordTable.setHorizontalHeaderItem(self.COMMENTS_IDX, headerComments)
groupName = encoding.normalize_nfc(item.text())
self.selectedGroup = groupName
group = self.pwMap.groups[groupName]
self.passwordTable.setRowCount(len(group.entries))
i = 0
for key, encValue, bkupValue in group.entries:
item = QTableWidgetItem(key)
pwItem = QTableWidgetItem("*****")
commentsItem = QTableWidgetItem("*****")
self.passwordTable.setItem(i, self.KEY_IDX, item)
self.passwordTable.setItem(i, self.PASSWORD_IDX, pwItem)
self.passwordTable.setItem(i, self.COMMENTS_IDX, commentsItem)
i = i+1
self.passwordTable.resizeRowsToContents()
self.passwordTable.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
self.passwordTable.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeToContents)
self.passwordTable.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeToContents)
self.settings.mlogger.log("Loaded password group '%s'." % (groupName),
logging.DEBUG, "GUI IO")
def loadPasswordsBySelection(self):
proxyIdx = self.groupsTree.currentIndex()
itemIdx = self.groupsFilter.mapToSource(proxyIdx)
selectedItem = self.groupsModel.itemFromIndex(itemIdx)
if not selectedItem:
return
self.loadPasswords(selectedItem)
def filterGroups(self, substring):
"""
Filter groupsTree view to have items containing given substring.
"""
self.groupsFilter.setFilterFixedString(substring)
self.groupsTree.sortByColumn(0, Qt.AscendingOrder)
def printAbout(self):
"""
Show window with about and version information.
"""
msgBox = QMessageBox(QMessageBox.Information, "About",
"About <b>TrezorPass</b>: <br><br>TrezorPass is a safe " +
"Password Manager application for people owning a Trezor who prefer to " +
"keep their passwords local and not on the cloud. All passwords are " +
"stored locally in a single file.<br><br>" +
"<b>" + basics.NAME + " Version: </b>" + basics.VERSION_STR +
" from " + basics.VERSION_DATE_STR +
"<br><br><b>Python Version: </b>" + sys.version.replace(" \n", "; ") +
"<br><br><b>Qt Version: </b>" + QT_VERSION_STR +
"<br><br><b>PyQt Version: </b>" + PYQT_VERSION_STR, parent=self)
msgBox.setIconPixmap(QPixmap("icons/TrezorPass.svg"))
msgBox.exec_()
def saveBackup(self):
"""
First it saves any pending changes to the pwdb database file. Then it uses an operating system call
to copy the file appending a timestamp at the end of the file name.
"""
if self.modified:
self.saveDatabase()
backupFilename = self.settings.dbFilename + u"." + time.strftime('%Y%m%d%H%M%S')
copyfile(self.settings.dbFilename, backupFilename)
self.settings.mlogger.log("Backup of the encrypted database file has been created "
"and placed into file \"%s\" (%d bytes)." % (backupFilename, os.path.getsize(backupFilename)),
logging.INFO, "User IO")
def importCsv(self):
"""
Read a properly formated CSV file from disk
and add its contents to the current entries.
Import format in CSV should be : group, key, password, comments
There is no error checking, so be extra careful.
Make a backup first.
Entries from CSV will be *added* to existing pwdb. If this is not desired
create an empty pwdb file first.
GroupNames are unique, so if a groupname exists then
key-password-comments tuples are added to the already existing group.
If a group name does not exist, a new group is created and the
key-password-comments tuples are added to the newly created group.
Keys are not unique. So key-password-comments are always added.
If a key with a given name existed before and the CSV file contains a
key with the same name, then the key-password-comments is added and
after the import the given group has 2 keys with the same name.
Both keys exist then, the old from before the import, and the new one from the import.
Examples of valid CSV file format: Some example lines
First Bank account,login,myloginname, # no comment
foo@gmail.com,2-factor-authentication key,abcdef12345678,seed to regenerate 2FA codes # with comment
foo@gmail.com,recovery phrase,"passwd with 2 commas , ,", # with comma