-
Notifications
You must be signed in to change notification settings - Fork 50
/
TrayTOTP_Plugin.cs
958 lines (849 loc) · 37.9 KB
/
TrayTOTP_Plugin.cs
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
using System;
using System.Linq;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;
using KeePass.App.Configuration;
using KeePass.Plugins;
using KeePass.UI;
using KeePass.Util;
using KeePass.Util.Spr;
using KeePassLib;
using KeePassLib.Utility;
using KeePassLib.Security;
using KeeTrayTOTP.Libraries;
using KeeTrayTOTP.Localization;
namespace KeeTrayTOTP
{
/// <summary>
/// Main Plugin Class
/// </summary>
public sealed partial class KeeTrayTOTPExt : Plugin
{
/// <summary>
/// Plugin host Global Reference for access to KeePass functions.
/// </summary>
internal IPluginHost PluginHost = null;
/// <summary>
/// Tray TOTP Support Email
/// </summary>
internal const string Email = "victor.rds@protonmail.ch";
/// <summary>
/// Constants (keepass form object names).
/// </summary>
internal const string keeobj_string_EntryContextMenuCopyPassword_Name = "m_ctxEntryCopyPassword";
internal const string keeobj_string_EntryContextMenuEntriesSubMenu_Name = "m_ctxEntryMassModify";
internal const string keeobj_string_EntryContextMenuEntriesSubMenuSeperator1_Name = "m_ctxEntrySelectedSep1";
/// <summary>
/// Constants (custom string key).
/// </summary>
internal const string setname_string_TimeCorrection_List = "traytotp_timecorrection_list";
/// <summary>
/// Constants (setting names).
/// </summary>
internal const string setname_bool_FirstInstall_Shown = "firstinstall_shown";
internal const string setname_bool_EntryContextCopy_Visible = "entrycontextcopy_visible";
internal const string setname_bool_EntryContextSetup_Visible = "entrycontextsetup_visible";
internal const string setname_bool_NotifyContext_Visible = "notifycontext_visible";
internal const string setname_bool_TOTPColumnCopy_Enable = "totpcolumncopy_enable";
internal const string setname_bool_TOTPColumnTimer_Visible = "totpcolumntimer_visible";
internal const string setname_bool_AutoType_Enable = "autotype_enable";
internal const string setname_string_AutoType_FieldName = "autotype_fieldname";
internal const string setname_bool_TimeCorrection_Enable = "timecorrection_enable";
internal const string setname_ulong_TimeCorrection_RefreshTime = "timecorrection_refreshtime";
internal const string setname_string_TOTPSeed_StringName = "totpseed_stringname";
internal const string setname_string_TOTPSettings_StringName = "totpsettings_stringname";
internal const string setname_bool_TrimTrayText = "traytotp_trim_tray_text";
/// <summary>
/// Constants (default settings values).
/// </summary>
internal const string setdef_string_AutoType_FieldName = "TOTP";
internal const long setdef_ulong_TimeCorrection_RefreshTime = 60;
/// <summary>
/// Constants (static settings value).
/// </summary>
internal const int setstat_int_EntryList_RefreshRate = 300;
internal const int setstat_trim_text_length = 25;
internal IReadOnlyList<string> setstat_allowed_lengths = new ReadOnlyCollection<string>(new[] { "6", "7", "8", "S" });
/// <summary>
/// Form Help Global Reference.
/// </summary>
private FormHelp _helpForm;
/// <summary>
/// Notify Icon Context Menu Title.
/// </summary>
private ToolStripMenuItem _niMenuTitle;
/// <summary>
/// Notify Icon Context Menu List.
/// </summary>
private List<ToolStripMenuItem> _niMenuList = new List<ToolStripMenuItem>();
/// <summary>
/// Notify Icon Context Menu Separator.
/// </summary>
private ToolStripSeparator _niMenuSeperator = null;
/// <summary>
/// Entries Column TOTP.
/// </summary>
private TrayTOTP_CustomColumn _liColumnTotp = null;
/// <summary>
/// Entry List Column Count.
/// </summary>
private int _liColumnsCount = 0;
/// <summary>
/// Entry List Column TOTP visibility.
/// </summary>
private bool _liColumnTotpVisible = false;
/// <summary>
/// Entry Groups last selected group.
/// </summary>
private PwGroup _liGroupsPreviousSelected = null;
/// <summary>
/// Entry Column TOTP has TOTPs.
/// </summary>
private bool _liColumnTotpContains = false;
/// <summary>
/// Entries Refresh Timer.
/// </summary>
private Timer _liRefreshTimer = new Timer();
/// <summary>
/// Entries Refresh Timer.
/// </summary>
internal int LiRefreshTimerInterval
{
set
{
_liRefreshTimer.Interval = value;
_liRefreshTimer.Enabled = true;
}
}
/// <summary>
/// Entries Refresh Timer Previous Counter to Prevent Useless Refresh.
/// </summary>
private int _liRefreshTimerPreviousCounter;
/// <summary>
/// Time Correction Collection.
/// </summary>
internal TimeCorrectionCollection TimeCorrections;
/// <summary>
/// Network status of the computer.
/// </summary>
internal bool NetworkIsConnected
{
get
{
return System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
}
}
public override ToolStripMenuItem GetMenuItem(PluginMenuType type)
{
// Provide a menu item for the main location(s)
if (type == PluginMenuType.Main)
{
var toMenuTrayTOTP = new ToolStripMenuItem(Localization.Strings.TrayTOTPPlugin);
toMenuTrayTOTP.Image = Properties.Resources.TOTP;
var toSubMenuSettings = new ToolStripMenuItem(Localization.Strings.Settings);
toSubMenuSettings.Image = Properties.Resources.TOTP_Settings;
toSubMenuSettings.Click += OnMenuSettingsClick;
toMenuTrayTOTP.DropDownItems.Add(toSubMenuSettings);
var toSubMenuSeparator1 = new ToolStripSeparator();
toMenuTrayTOTP.DropDownItems.Add(toSubMenuSeparator1);
var toSubMenuHelp = new ToolStripMenuItem(Localization.Strings.Help);
toSubMenuHelp.Image = Properties.Resources.TOTP_Help;
toSubMenuHelp.Click += OnMenuHelpClick;
toMenuTrayTOTP.DropDownItems.Add(toSubMenuHelp);
var toSubMenuAbout = new ToolStripMenuItem(Localization.Strings.About + "...");
toSubMenuAbout.Image = Properties.Resources.TOTP_Info;
toSubMenuAbout.Click += OnMenuAboutClick;
toMenuTrayTOTP.DropDownItems.Add(toSubMenuAbout);
return toMenuTrayTOTP;
}
else if (type == PluginMenuType.Entry)
{
var enMenuTrayTotp = new ToolStripMenuItem(Localization.Strings.TrayTOTPPlugin);
enMenuTrayTotp.Image = Properties.Resources.TOTP;
var enMenuCopyTotp = new ToolStripMenuItem(Localization.Strings.CopyTOTP);
enMenuCopyTotp.Image = Properties.Resources.TOTP;
enMenuCopyTotp.ShortcutKeys = (Keys)Shortcut.CtrlT;
enMenuCopyTotp.Click += OnEntryMenuTOTPClick;
var enMenuSetupTotp = new ToolStripMenuItem(Localization.Strings.SetupTOTP);
enMenuSetupTotp.Image = Properties.Resources.TOTP_Setup;
enMenuSetupTotp.ShortcutKeys = (Keys)Shortcut.CtrlShiftI;
enMenuSetupTotp.Click += OnEntryMenuSetupClick;
var enMenuShowQr = new ToolStripMenuItem(Localization.Strings.ShowQR);
enMenuShowQr.Image = Properties.Resources.TOTP_Setup;
enMenuShowQr.ShortcutKeys = (Keys)Shortcut.CtrlShiftJ;
enMenuShowQr.Click += OnEntryMenuShowQRClick;
enMenuTrayTotp.DropDownItems.Add(enMenuCopyTotp);
enMenuTrayTotp.DropDownItems.Add(enMenuSetupTotp);
enMenuTrayTotp.DropDownItems.Add(enMenuShowQr);
enMenuTrayTotp.DropDownOpening += delegate (object sender, EventArgs e)
{
enMenuCopyTotp.Enabled = false;
enMenuSetupTotp.Enabled = false;
bool boolCopy = PluginHost.CustomConfig.GetBool(setname_bool_EntryContextCopy_Visible, true);
enMenuCopyTotp.Visible = boolCopy;
if (PluginHost.MainWindow.GetSelectedEntriesCount() == 1)
{
var currentEntry = PluginHost.MainWindow.GetSelectedEntry(true);
if (SettingsCheck(currentEntry) && SeedCheck(currentEntry))
{
if (SettingsValidate(currentEntry))
{
enMenuCopyTotp.Enabled = true;
enMenuCopyTotp.Tag = currentEntry;
}
}
enMenuSetupTotp.Enabled = true;
}
bool boolSetup = PluginHost.CustomConfig.GetBool(setname_bool_EntryContextSetup_Visible, true);
enMenuSetupTotp.Visible = boolSetup;
};
enMenuTrayTotp.DropDownClosed += delegate (object sender, EventArgs e)
{
enMenuCopyTotp.Enabled = true;
};
return enMenuTrayTotp;
}
return null; // No menu items in other locations
}
/// <summary>
/// Initialization of the plugin, adding menus, handlers and forms.
/// </summary>
/// <param name="host">Plugin host for access to KeePass functions.</param>
/// <returns>Successful loading of the plugin, if not the plugin is removed.</returns>
public override bool Initialize(IPluginHost host)
{
// Internalize Host Handle.
if (host == null)
{
return false;
}
PluginHost = host;
// Instantiate Help Form.
_helpForm = new FormHelp(this);
// Register events.
PluginHost.MainWindow.Shown += MainWindow_Shown;
// Notify Icon Context Menus.
PluginHost.MainWindow.TrayContextMenu.Opening += OnNotifyMenuOpening;
_niMenuTitle = new ToolStripMenuItem(Localization.Strings.TrayTOTPPlugin);
_niMenuTitle.Image = Properties.Resources.TOTP;
PluginHost.MainWindow.TrayContextMenu.Items.Insert(0, _niMenuTitle);
_niMenuSeperator = new ToolStripSeparator();
PluginHost.MainWindow.TrayContextMenu.Items.Insert(1, _niMenuSeperator);
// Register auto-type function.
if (PluginHost.CustomConfig.GetBool(setname_bool_AutoType_Enable, true))
{
SprEngine.FilterCompile += SprEngine_FilterCompile;
SprEngine.FilterPlaceholderHints.Add(PluginHost.CustomConfig.GetString(setname_string_AutoType_FieldName, setdef_string_AutoType_FieldName).ExtWithBrackets());
}
// List Column TOTP.
_liColumnTotp = new TrayTOTP_CustomColumn(this);
PluginHost.ColumnProviderPool.Add(_liColumnTotp);
// Refresh Timer.
_liRefreshTimer.Interval = setstat_int_EntryList_RefreshRate;
_liRefreshTimer.Enabled = true;
_liRefreshTimer.Tick += OnTimerTick;
//Time Correction.
TimeCorrections = new TimeCorrectionCollection(PluginHost.CustomConfig.GetBool(setname_bool_TimeCorrection_Enable, false));
TimeCorrectionProvider.Interval = Convert.ToInt16(PluginHost.CustomConfig.GetULong(KeeTrayTOTPExt.setname_ulong_TimeCorrection_RefreshTime, KeeTrayTOTPExt.setdef_ulong_TimeCorrection_RefreshTime));
TimeCorrections.AddRangeFromList(PluginHost.CustomConfig.GetString(setname_string_TimeCorrection_List, string.Empty).Split(';').ToList());
return true;
}
/// <summary>
/// Occurs when the main window is shown.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MainWindow_Shown(object sender, EventArgs e)
{
if (!PluginHost.CustomConfig.GetBool(setname_bool_FirstInstall_Shown, false))
{
PluginHost.CustomConfig.SetBool(setname_bool_FirstInstall_Shown, true);
if (!_helpForm.Visible)
{
_helpForm = new FormHelp(this, true);
_helpForm.Show();
}
else
{
_helpForm.Focus();
}
}
}
/// <summary>
/// Tools Menu Tray TOTP Settings Click.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnMenuSettingsClick(object sender, EventArgs e)
{
var formSettings = new FormSettings(this);
UIUtil.ShowDialogAndDestroy(formSettings);
}
/// <summary>
/// Tools Menu Tray TOTP Help Click.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnMenuHelpClick(object sender, EventArgs e)
{
if (!_helpForm.Visible)
{
_helpForm.Show();
}
else
{
_helpForm.Focus();
}
}
/// <summary>
/// Tools Menu Tray TOTP About Click.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnMenuAboutClick(object sender, EventArgs e)
{
var formAbout = new FormAbout(this);
UIUtil.ShowDialogAndDestroy(formAbout);
}
/// <summary>
/// Entry Context Menu Copy Click.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnEntryMenuTOTPClick(object sender, EventArgs e)
{
PwEntry pe = PluginHost.MainWindow.GetSelectedEntry(false);
if (pe != null)
{
TOTPCopyToClipboard(pe);
}
}
/// <summary>
/// Entry Context Menu Setup Click.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnEntryMenuSetupClick(object sender, EventArgs e)
{
if (PluginHost.MainWindow.GetSelectedEntriesCount() == 1)
{
var formWizard = new SetupTOTP(this, PluginHost.MainWindow.GetSelectedEntry(true));
formWizard.ShowDialog();
PluginHost.MainWindow.RefreshEntriesList();
}
}
/// <summary>
/// Entry Context Menu Show QR Click.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnEntryMenuShowQRClick(object sender, EventArgs e)
{
if (PluginHost.MainWindow.GetSelectedEntriesCount() != 1)
{
return;
}
var entry = PluginHost.MainWindow.GetSelectedEntry(true);
if (!SeedCheck(entry))
{
return;
}
var rawSeed = this.SeedGet(entry).ReadString();
var cleanSeed = Regex.Replace(rawSeed, @"\s+", "");
var showQr = new ShowQR
{
Seed = cleanSeed,
IssuerText = { Text = entry.Strings.Get("Title").ReadString() },
UsernameText = { Text = entry.Strings.Get("UserName").ReadString() },
};
showQr.ShowDialog();
PluginHost.MainWindow.RefreshEntriesList();
}
/// <summary>
/// Notify Icon Context Menu Opening.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnNotifyMenuOpening(object sender, CancelEventArgs e)
{
foreach (var menu in _niMenuList)
{
PluginHost.MainWindow.TrayContextMenu.Items.Remove(menu);
}
_niMenuList.Clear();
if (PluginHost.CustomConfig.GetBool(setname_bool_NotifyContext_Visible, true))
{
_niMenuTitle.Visible = true;
_niMenuSeperator.Visible = true;
if (PluginHost.MainWindow.ActiveDatabase.IsOpen)
{
var trimTrayText = PluginHost.CustomConfig.GetBool(KeeTrayTOTPExt.setname_bool_TrimTrayText, false);
foreach (PwEntry entry in GetVisibleAndValidPasswordEntries())
{
var entryTitle = entry.Strings.ReadSafe(PwDefs.TitleField);
var context = new SprContext(entry, PluginHost.MainWindow.ActiveDatabase, SprCompileFlags.All, false, false);
var entryUsername = SprEngine.Compile(entry.Strings.ReadSafe(PwDefs.UserNameField), context);
string trayTitle;
if ((trimTrayText && entryTitle.Length + entryUsername.Length > setstat_trim_text_length) || (string.IsNullOrEmpty(entryUsername)))
{
trayTitle = entryTitle.ExtWithSpaceAfter();
}
else
{
trayTitle = entryTitle.ExtWithSpaceAfter() + entryUsername.ExtWithParenthesis();
}
PluginHost.CustomConfig.GetBool(KeeTrayTOTPExt.setname_bool_TrimTrayText, false);
var newMenu = new ToolStripMenuItem(trayTitle, Properties.Resources.TOTP_Key, OnNotifyMenuTOTPClick);
newMenu.Tag = entry;
if (!SettingsValidate(entry))
{
newMenu.Enabled = false;
newMenu.Image = Properties.Resources.TOTP_Error;
}
_niMenuList.Add(newMenu);
}
if (_niMenuList.Count > 0)
{
_niMenuList.Sort((p1, p2) => string.Compare(p1.Text, p2.Text, true));
for (int i = 0; i <= _niMenuList.Count - 1; i++)
{
PluginHost.MainWindow.TrayContextMenu.Items.Insert(i + 1, _niMenuList[i]);
}
}
else
{
var newMenu = new ToolStripMenuItem(Localization.Strings.NoTOTPSeedFound);
newMenu.Image = Properties.Resources.TOTP_None;
_niMenuList.Add(newMenu);
PluginHost.MainWindow.TrayContextMenu.Items.Insert(1, _niMenuList[0]);
}
CreateMenuItemForOtherDatabases(_niMenuList);
}
else
{
if (PluginHost.MainWindow.IsFileLocked(null))
{
var newMenu = new ToolStripMenuItem(Localization.Strings.DatabaseIsLocked);
newMenu.Image = Properties.Resources.TOTP_Lock;
_niMenuList.Add(newMenu);
PluginHost.MainWindow.TrayContextMenu.Items.Insert(1, _niMenuList[0]);
}
else
{
var newMenu = new ToolStripMenuItem(Localization.Strings.DatabaseIsNotOpen);
newMenu.Image = Properties.Resources.TOTP_Error;
_niMenuList.Add(newMenu);
PluginHost.MainWindow.TrayContextMenu.Items.Insert(1, _niMenuList[0]);
}
}
}
else
{
_niMenuTitle.Visible = false;
_niMenuSeperator.Visible = false;
}
}
/// <summary>
/// Get all the password entries in all groups and filter entries that are expired or have invalid TOTP settings.
/// </summary>
/// <returns></returns>
private IEnumerable<PwEntry> GetVisibleAndValidPasswordEntries()
{
var entries = PluginHost.MainWindow.ActiveDatabase.RootGroup.GetEntries(true);
return entries
.Where(entry => !entry.IsExpired())
.Where(entry => SettingsCheck(entry) && SeedCheck(entry));
}
/// <summary>
/// Creates the necessary menu items to switch to another database
/// </summary>
/// <param name="items"></param>
private void CreateMenuItemForOtherDatabases(IList<ToolStripMenuItem> items)
{
var tabcontrol = PluginHost.MainWindow.Controls.OfType<TabControl>().FirstOrDefault();
var nonSelectedTabs = tabcontrol.TabPages.OfType<TabPage>().Where(c => c != tabcontrol.SelectedTab).ToList();
int i = 1;
foreach (var tab in nonSelectedTabs)
{
var item = new ToolStripMenuItem(string.Format(Strings.SwitchTo, tab.Text))
{
Tag = tab
};
item.Click += SwitchToOtherDatabase;
items.Add(item);
PluginHost.MainWindow.TrayContextMenu.Items.Insert(i++, item);
}
}
private void SwitchToOtherDatabase(object sender, EventArgs e)
{
var tabControl = PluginHost.MainWindow.Controls.OfType<TabControl>().FirstOrDefault();
var changeDbToolStripItem = sender as ToolStripMenuItem;
if (changeDbToolStripItem != null)
{
var databaseTab = changeDbToolStripItem.Tag as TabPage;
if (databaseTab != null)
{
tabControl.SelectedTab = databaseTab;
}
}
}
/// <summary>
/// Entry Notify Menu Copy Click.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnNotifyMenuTOTPClick(object sender, EventArgs e)
{
ToolStripMenuItem tsi = sender as ToolStripMenuItem;
if (tsi == null)
{
return;
}
PwEntry pe = tsi.Tag as PwEntry;
if (pe != null)
{
TOTPCopyToClipboard(pe);
}
}
/// <summary>
/// Timer Event that occurs to refresh the entry list.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnTimerTick(object sender, EventArgs e)
{
if ((PluginHost.MainWindow.ActiveDatabase.IsOpen) && (PluginHost.MainWindow.Visible))
{
if (KeePass.Program.Config.MainWindow.EntryListColumns.Count != _liColumnsCount)
{
_liColumnTotpVisible = false;
_liColumnsCount = KeePass.Program.Config.MainWindow.EntryListColumns.Count;
foreach (var column in KeePass.Program.Config.MainWindow.EntryListColumns)
{
if (column.Type == AceColumnType.PluginExt)
{
if (column.CustomName == Localization.Strings.TOTP)
{
_liColumnTotpVisible = true;
}
}
}
}
if (_liColumnTotpVisible)
{
PwGroup selectedGroup = PluginHost.MainWindow.GetSelectedGroup();
if (selectedGroup != _liGroupsPreviousSelected)
{
_liColumnTotpContains = false;
_liGroupsPreviousSelected = selectedGroup;
foreach (var entry in selectedGroup.GetEntries(true))
{
if (SettingsCheck(entry) && SeedCheck(entry))
{
_liColumnTotpContains = true;
}
}
}
}
if ((_liColumnTotpVisible) && (_liColumnTotpContains)) //Tests if displayed entries have totps that require refreshing.
{
var currentSeconds = DateTime.Now.Second;
if (_liRefreshTimerPreviousCounter != currentSeconds)
{
PluginHost.MainWindow.RefreshEntriesList();
_liRefreshTimerPreviousCounter = currentSeconds;
}
}
}
}
/// <summary>
/// Auto-Type Function.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SprEngine_FilterCompile(object sender, SprEventArgs e)
{
if ((e.Context.Flags & SprCompileFlags.ExtActive) == SprCompileFlags.ExtActive)
{
if (e.Text.IndexOf(PluginHost.CustomConfig.GetString(setname_string_AutoType_FieldName, setdef_string_AutoType_FieldName).ExtWithBrackets(), StringComparison.InvariantCultureIgnoreCase) >= 0)
{
if (SettingsCheck(e.Context.Entry) && SeedCheck(e.Context.Entry))
{
if (SettingsValidate(e.Context.Entry))
{
string[] settings = SettingsGet(e.Context.Entry);
TOTPProvider totpGenerator = new TOTPProvider(settings, ref this.TimeCorrections);
string invalidCharacters;
if (SeedValidate(e.Context.Entry, out invalidCharacters))
{
e.Context.Entry.Touch(false);
string totp = totpGenerator.GenerateByByte(Base32.Decode(SeedGet(e.Context.Entry).ReadString().ExtWithoutSpaces()));
e.Text = StrUtil.ReplaceCaseInsensitive(e.Text, PluginHost.CustomConfig.GetString(setname_string_AutoType_FieldName, setdef_string_AutoType_FieldName).ExtWithBrackets(), totp);
}
else
{
e.Text = string.Empty;
MessageService.ShowWarning(Localization.Strings.ErrorBadSeed + invalidCharacters.ExtWithParenthesis().ExtWithSpaceBefore());
}
if (totpGenerator.TimeCorrectionError)
{
MessageService.ShowWarning(Localization.Strings.WarningBadURL);
}
}
else
{
e.Text = string.Empty;
MessageService.ShowWarning(Localization.Strings.ErrorBadSettings);
}
}
else
{
e.Text = string.Empty;
MessageService.ShowWarning(Localization.Strings.ErrorBadSettings);
}
}
}
}
/// <summary>
/// Check if specified Entry contains Settings that are not null.
/// </summary>
/// <param name="pe">Pasword Entry.</param>
/// <returns>Presence of Settings.</returns>
internal bool SettingsCheck(PwEntry pe)
{
return pe.Strings.Exists(PluginHost.CustomConfig.GetString(setname_string_TOTPSettings_StringName, Localization.Strings.TOTPSettings));
}
/// <summary>
/// Check if specified Entry's Interval and Length are valid.
/// </summary>
/// <param name="pe">Password Entry.</param>
/// <returns>Error(s) while validating Interval or Length.</returns>
internal bool SettingsValidate(PwEntry pe)
{
bool validInterval;
bool validLength;
bool validUrl; //Dummies
return SettingsValidate(pe, out validInterval, out validLength, out validUrl);
}
/// <summary>
/// Check if specified Entry's Interval and Length are valid. The URL status is available as an out boolean.
/// </summary>
/// <param name="pe">Password Entry.</param>
/// <param name="isUrlValid">Url Validity.</param>
/// <returns>Error(s) while validating Interval or Length.</returns>
internal bool SettingsValidate(PwEntry pe, out bool isUrlValid)
{
bool validInterval; bool validLength; //Dummies
return SettingsValidate(pe, out validInterval, out validLength, out isUrlValid);
}
/// <summary>
/// Check if specified Entry's Interval and Length are valid. All settings statuses are available as out booleans.
/// </summary>
/// <param name="pe">Password Entry.</param>
/// <param name="isIntervalValid">Interval Validity.</param>
/// <param name="isLengthValid">Length Validity.</param>
/// <param name="isUrlValid">Url Validity.</param>
/// <returns>Error(s) while validating Interval or Length.</returns>
internal bool SettingsValidate(PwEntry pe, out bool isIntervalValid, out bool isLengthValid, out bool isUrlValid)
{
bool settingsValid;
try
{
string[] settings = SettingsGet(pe);
isIntervalValid = IntervalIsValid(settings);
isLengthValid = LengthIsValid(settings);
settingsValid = isIntervalValid && isLengthValid;
isUrlValid = UrlIsValid(settings);
}
catch (Exception)
{
isIntervalValid = false;
isLengthValid = false;
isUrlValid = false;
settingsValid = false;
}
return settingsValid;
}
private static bool UrlIsValid(string[] settings)
{
if (settings.Length < 3)
{
return false;
}
return settings[2].StartsWith("http://") || settings[2].StartsWith("https://");
}
private bool LengthIsValid(string[] settings)
{
if (settings.Length < 2)
{
return false;
}
if (!setstat_allowed_lengths.Contains(settings[1]))
{
return false;
}
return true;
}
private bool IntervalIsValid(string[] settings)
{
if (settings.Length == 0)
{
return false;
}
short interval;
if (!short.TryParse(settings[0], out interval))
{
return false;
}
if (interval < 0 && interval < 180)
{
return false;
}
return true;
}
/// <summary>
/// Get the entry's Settings using the string name specified in the settings (or default).
/// </summary>
/// <param name="pe">Password Entry.</param>
/// <returns>String Array (Interval, Length, Url).</returns>
internal string[] SettingsGet(PwEntry pe)
{
return pe.Strings.Get(PluginHost.CustomConfig.GetString(setname_string_TOTPSettings_StringName, Localization.Strings.TOTPSettings)).ReadString().Split(';');
}
/// <summary>
/// Check if the specified Entry contains a Seed.
/// </summary>
/// <param name="pe">Password Entry.</param>
/// <returns>Presence of the Seed.</returns>
internal bool SeedCheck(PwEntry pe)
{
return pe.Strings.Exists(PluginHost.CustomConfig.GetString(setname_string_TOTPSeed_StringName, Localization.Strings.TOTPSeed));
}
/// <summary>
/// Validates the entry's Seed making sure it's a valid Base32 string.
/// </summary>
/// <param name="passwordEntry">Password Entry.</param>
/// <returns>Validity of the Seed's characters for Base32 format.</returns>
internal bool SeedValidate(PwEntry passwordEntry)
{
string invalidCharacters;
return SeedGet(passwordEntry).ReadString().ExtWithoutSpaces().ExtIsBase32(out invalidCharacters);
}
/// <summary>
/// Validates the entry's Seed making sure it's a valid Base32 string. Invalid characters are available as out string.
/// </summary>
/// <param name="passwordEntry">Password Entry.</param>
/// <param name="invalidChars">Password Entry.</param>
/// <returns>Validity of the Seed's characters.</returns>
internal bool SeedValidate(PwEntry passwordEntry, out string invalidChars)
{
return SeedGet(passwordEntry).ReadString().ExtWithoutSpaces().ExtIsBase32(out invalidChars);
}
/// <summary>
/// Get the entry's Seed using the string name specified in the settings (or default).
/// </summary>
/// <param name="pe">Password Entry.</param>
/// <returns>Protected Seed.</returns>
internal ProtectedString SeedGet(PwEntry pe)
{
return pe.Strings.Get(PluginHost.CustomConfig.GetString(setname_string_TOTPSeed_StringName, Localization.Strings.TOTPSeed));
}
/// <summary>
/// Copies the specified entry's generated TOTP to the clipboard using the KeePass's clipboard function.
/// </summary>
/// <param name="pe">Password Entry.</param>
private void TOTPCopyToClipboard(PwEntry pe)
{
if (SettingsCheck(pe) && SeedCheck(pe))
{
if (SettingsValidate(pe))
{
string[] settings = SettingsGet(pe);
TOTPProvider totpGenerator = new TOTPProvider(settings, ref this.TimeCorrections);
string invalidCharacters;
if (SeedValidate(pe, out invalidCharacters))
{
pe.Touch(false);
string totp = totpGenerator.Generate(SeedGet(pe).ReadString().ExtWithoutSpaces());
ClipboardUtil.CopyAndMinimize(totp, true, PluginHost.MainWindow, pe, PluginHost.MainWindow.ActiveDatabase);
PluginHost.MainWindow.StartClipboardCountdown();
}
else
{
MessageService.ShowWarning(Localization.Strings.ErrorBadSeed + invalidCharacters.ExtWithParenthesis().ExtWithSpaceBefore());
}
if (totpGenerator.TimeCorrectionError)
{
MessageService.ShowWarning(Localization.Strings.WarningBadURL);
}
}
else
{
MessageService.ShowWarning(Localization.Strings.ErrorBadSettings);
}
}
else
{
MessageService.ShowWarning(Localization.Strings.ErrorBadSettings);
}
}
/// <summary>
/// Removes all resources such as menus, handles and forms from KeePass.
/// </summary>
public override void Terminate()
{
// Destroy Help Form.
if (_helpForm.Visible)
{
_helpForm.Close();
}
else
{
_helpForm.Dispose();
}
// Unregister internal events.
PluginHost.MainWindow.Shown -= MainWindow_Shown;
// Remove Notify Icon menus.
PluginHost.MainWindow.TrayContextMenu.Opening -= OnNotifyMenuOpening;
PluginHost.MainWindow.TrayContextMenu.Items.Remove(_niMenuTitle);
_niMenuTitle.Dispose();
foreach (var menu in _niMenuList)
{
PluginHost.MainWindow.TrayContextMenu.Items.Remove(menu);
menu.Dispose();
}
PluginHost.MainWindow.TrayContextMenu.Items.Remove(_niMenuSeperator);
_niMenuSeperator.Dispose();
// Unregister auto-type function.
if (SprEngine.FilterPlaceholderHints.Contains(PluginHost.CustomConfig.GetString(setname_string_AutoType_FieldName, setdef_string_AutoType_FieldName).ExtWithBrackets()))
{
SprEngine.FilterCompile -= SprEngine_FilterCompile;
SprEngine.FilterPlaceholderHints.Remove(PluginHost.CustomConfig.GetString(setname_string_AutoType_FieldName, setdef_string_AutoType_FieldName).ExtWithBrackets());
}
// Remove Column provider.
PluginHost.ColumnProviderPool.Remove(_liColumnTotp);
_liColumnTotp = null;
// Remove Timer.
_liRefreshTimer.Tick -= OnTimerTick;
_liRefreshTimer.Dispose();
}
/// <summary>
/// Returns the image of the plugin to display in the KeePass plugin list.
/// </summary>
public override Image SmallIcon
{
get { return Properties.Resources.TOTP; }
}
/// <summary>
/// Returns update URL for KeepAss automatic update check. (file must be UTF-8 without BOM (support for BOM from KP 2.21))
/// </summary>
public override string UpdateUrl
{
get { return "https://raw.githubusercontent.com/KeeTrayTOTP/KeeTrayTOTP/master/version_manifest.txt"; }
}
}
}