/
HIBPOfflineColumnProv.cs
354 lines (284 loc) · 12 KB
/
HIBPOfflineColumnProv.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
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
using KeePass.Forms;
using KeePass.Plugins;
using KeePass.UI;
using KeePass.Util.Spr;
using KeePassLib;
using KeePassLib.Security;
using System.Net;
namespace HIBPOfflineCheck
{
public sealed class HIBPOfflineColumnProv : ColumnProvider
{
private string Status { get; set; }
private PwEntry PasswordEntry { get; set; }
public IPluginHost Host { private get; set; }
public Options PluginOptions { private get; set; }
private bool insecureWarning;
private bool passwordEdited;
public HIBPOfflineColumnProv()
{
HIBPOfflineCheckExt.Host.MainWindow.EntryContextMenu.Opening += ContextMenuStrip_Opening;
}
public override string[] ColumnNames
{
get { return new string[] { PluginOptions.ColumnName }; }
}
public override bool SupportsCellAction(string strColumnName)
{
return (strColumnName == PluginOptions.ColumnName);
}
private void GetOnlineStatus()
{
var pwdSha = GetPasswordSHA();
var truncatedSha = pwdSha.Substring(0, 5);
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
var url = "https://api.pwnedpasswords.com/range/" + truncatedSha;
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.UserAgent = "KeePass-HIBP-plug/1.0";
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
{
Status = "HIBP API error";
return;
}
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
string responseFromServer = reader.ReadToEnd();
var lines = responseFromServer.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
Status = PluginOptions.SecureText;
foreach (var line in lines)
{
string fullSha = truncatedSha + line;
var compare = string.Compare(pwdSha, fullSha.Substring(0, pwdSha.Length), StringComparison.Ordinal);
if (compare == 0)
{
var tokens = line.Split(':');
Status = PluginOptions.InsecureText;
insecureWarning = true;
if (PluginOptions.BreachCountDetails)
{
Status += " (password count: " + tokens[1].Trim() + ")";
}
break;
}
}
reader.Close();
stream.Close();
}
}
}
catch
{
Status = "HIBP API error";
}
}
private string GetPasswordSHA()
{
using (var sha1 = new SHA1CryptoServiceProvider())
{
var context = new SprContext(PasswordEntry, Host.Database, SprCompileFlags.All);
var password = SprEngine.Compile(PasswordEntry.Strings.GetSafe(PwDefs.PasswordField).ReadString(), context);
var pwdShaBytes = sha1.ComputeHash(Encoding.UTF8.GetBytes(password));
var sb = new StringBuilder(2 * pwdShaBytes.Length);
foreach (var b in pwdShaBytes)
{
sb.AppendFormat("{0:X2}", b);
}
return sb.ToString();
}
}
private void GetPasswordStatus()
{
if (PluginOptions.CheckMode == Options.CheckModeType.Offline)
{
GetOfflineStatus();
}
else if (PluginOptions.CheckMode == Options.CheckModeType.Online)
{
GetOnlineStatus();
}
}
private void GetOfflineStatus()
{
string pwdShaStr = GetPasswordSHA();
var latestFile = PluginOptions.HIBPFileName;
if (!File.Exists(latestFile))
{
Status = "HIBP file not found";
return;
}
using (var fs = File.OpenRead(latestFile))
using (var sr = new StreamReader(fs))
{
try
{
Status = PluginOptions.SecureText;
var shaLen = pwdShaStr.Length;
var low = 0L;
var high = fs.Length;
while (low <= high)
{
var middle = (low + high + 1) / 2;
fs.Seek(middle, SeekOrigin.Begin);
// Resync with base stream after seek
sr.DiscardBufferedData();
var line = sr.ReadLine();
if (sr.EndOfStream) break;
// We may have read only a partial line so read again to make sure we get a full line
if (middle > 0) line = sr.ReadLine() ?? string.Empty;
if (line != null)
{
var compare = string.Compare(pwdShaStr, line.Substring(0, shaLen), StringComparison.Ordinal);
if (compare < 0)
{
high = middle - 1;
}
else if (compare > 0)
{
low = middle + 1;
}
else
{
var tokens = line.Split(':');
Status = PluginOptions.InsecureText;
insecureWarning = true;
if (PluginOptions.BreachCountDetails)
{
Status += " (password count: " + tokens[1].Trim() + ")";
}
break;
}
}
}
}
catch
{
Status = "Failed to read HIBP file";
}
}
}
public override void PerformCellAction(string strColumnName, PwEntry pe)
{
if (strColumnName == null || pe == null) { Debug.Assert(false); return; }
if (strColumnName != PluginOptions.ColumnName) { return; }
PasswordEntry = pe;
GetPasswordStatus();
UpdateStatus();
}
private void PwdTouchedHandler(object sender, ObjectTouchedEventArgs e)
{
PwEntry pe = sender as PwEntry;
if (e.Modified)
{
passwordEdited = true;
PerformCellAction(PluginOptions.ColumnName, pe);
}
}
public override string GetCellData(string strColumnName, PwEntry pe)
{
if (pe == null) return string.Empty;
pe.Touched -= PwdTouchedHandler;
pe.Touched += PwdTouchedHandler;
return pe.Strings.GetSafe(PluginOptions.ColumnName).ReadString();
}
private void UpdateStatus()
{
MainForm mainForm = HIBPOfflineCheckExt.Host.MainWindow;
ListView lv = (mainForm.Controls.Find("m_lvEntries", true)[0] as ListView);
UIScrollInfo scroll = UIUtil.GetScrollInfo(lv, true);
PasswordEntry.Strings.Set(PluginOptions.ColumnName, new ProtectedString(true, Status));
mainForm.UpdateUI(false, null, false, null, true, null, true);
UIUtil.Scroll(lv, scroll, true);
if (insecureWarning && passwordEdited && PluginOptions.WarningDialog)
{
MessageBox.Show(PluginOptions.WarningDialogText,
"HIBP Offline Check", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
insecureWarning = false;
passwordEdited = false;
}
private void ContextMenuStrip_Opening(object sender, CancelEventArgs e)
{
MainForm mainForm = HIBPOfflineCheckExt.Host.MainWindow;
ToolStripItem[] items = mainForm.EntryContextMenu.Items.Find("m_ctxEntryMassModify", true);
if (items.Length > 0)
{
ToolStripMenuItem ctxEntryMassModify = items[0] as ToolStripMenuItem;
if (ctxEntryMassModify != null)
{
ToolStripItem[] hibpItems = ctxEntryMassModify.DropDownItems.Find("m_ctxEntryHIBP", true);
if (hibpItems.Length == 0)
{
ToolStripSeparator separator = new ToolStripSeparator();
ctxEntryMassModify.DropDownItems.Add(separator);
ToolStripMenuItem hibpMenuItem = new ToolStripMenuItem()
{
Name = "m_ctxEntryHIBP",
Text = "Have I been pwned?"
};
hibpMenuItem.Click += OnMenuHIBP;
ctxEntryMassModify.DropDownItems.Add(hibpMenuItem);
ToolStripMenuItem hibpClearMenuItem = new ToolStripMenuItem()
{
Name = "m_ctxEntryHIBPClear",
Text = "Clear pwned status"
};
hibpClearMenuItem.Click += OnMenuHIBPClear;
ctxEntryMassModify.DropDownItems.Add(hibpClearMenuItem);
}
}
}
}
public void PasswordCheckWorker()
{
GetPasswordStatus();
if (PluginOptions.CheckMode == Options.CheckModeType.Online)
{
System.Threading.Thread.Sleep(1600);
}
}
private async void OnMenuHIBP(object sender, EventArgs e)
{
var progressDisplay = new ProgressDisplay();
progressDisplay.Show();
MainForm mainForm = HIBPOfflineCheckExt.Host.MainWindow;
PwEntry[] selectedEntries = mainForm.GetSelectedEntries();
for (int j = 0; j < selectedEntries.Length; j++)
{
PasswordEntry = selectedEntries[j];
await System.Threading.Tasks.Task.Run(() => PasswordCheckWorker());
UpdateStatus();
progressDisplay.progressBar.Value = (j + 1) * 100 / selectedEntries.Length;
if (progressDisplay.UserTerminated)
{
progressDisplay.Close();
break;
}
}
progressDisplay.Close();
}
private void OnMenuHIBPClear(object sender, EventArgs e)
{
MainForm mainForm = HIBPOfflineCheckExt.Host.MainWindow;
PwEntry[] selectedEntries = mainForm.GetSelectedEntries();
foreach (PwEntry pwEntry in selectedEntries)
{
pwEntry.Strings.Remove(PluginOptions.ColumnName);
}
mainForm.UpdateUI(false, null, false, null, true, null, true);
}
}
}