-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathCertificateInstallationForm.cs
362 lines (301 loc) · 12.5 KB
/
CertificateInstallationForm.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
namespace X509CertificateTool
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using System.Windows.Forms;
public partial class CertificateInstallationForm : Form
{
public CertificateInstallationForm()
{
InitializeComponent();
SetupListbox(listBoxCurrentUserMy, new CertLocation(StoreLocation.CurrentUser, StoreName.My));
SetupListbox(listBoxCurrentUserAddressBook, new CertLocation(StoreLocation.CurrentUser, StoreName.AddressBook));
SetupListbox(listBoxCurrentUserTrustedPeople, new CertLocation(StoreLocation.CurrentUser, StoreName.TrustedPeople));
SetupListbox(listBoxCurrentUserRoot, new CertLocation(StoreLocation.CurrentUser, StoreName.Root));
SetupListbox(listBoxLocalMachineMy, new CertLocation(StoreLocation.LocalMachine, StoreName.My));
SetupListbox(listBoxLocalMachineAddressBook, new CertLocation(StoreLocation.LocalMachine, StoreName.AddressBook));
SetupListbox(listBoxLocalMachineTrustedPeople, new CertLocation(StoreLocation.LocalMachine, StoreName.TrustedPeople));
SetupListbox(listBoxLocalMachineRoot, new CertLocation(StoreLocation.LocalMachine, StoreName.Root));
}
private void SetupListbox(ListBox listBox, CertLocation certLocation)
{
Debug.Assert(null != listBox, "null != listBox");
Debug.Assert(null != certLocation, "null != certLocation");
listBox.Tag = certLocation;
listBox.HorizontalScrollbar = true;
listBox.AllowDrop = true;
listBox.SelectionMode = SelectionMode.MultiExtended;
listBox.DragDrop += new DragEventHandler(this.ListBox_DragDrop);
listBox.DragEnter += new DragEventHandler(this.ListBox_DragEnter);
listBox.DragEnter += new DragEventHandler(this.ListBox_DragEnterColoring);
listBox.DragLeave += new EventHandler(ListBox_DragLeaveColoring);
listBox.MouseDown += new MouseEventHandler(ListBoxInstalledCerts_MouseDown);
ListCurrentCertificates(listBox, null);
}
static readonly ReadOnlyCollection<string> certExtensions =
new List<string>() { ".pfx", ".p12", ".cer" }.AsReadOnly();
static bool IsCertificateFile(string filename)
{
Debug.Assert(!string.IsNullOrEmpty(filename), "!string.IsNullOrEmpty(filename)");
return certExtensions.Any(filename.EndsWith);
//foreach (string certExtension in certExtensions)
//{
// if (filename.EndsWith(certExtension))
// {
// return true;
// }
//}
//return false;
}
static bool ContainsCertificateFiles(string[] filenames)
{
return filenames.Any(IsCertificateFile);
//foreach (string filename in filenames)
//{
// if (IsCertificateFile(filename))
// {
// return true;
// }
//}
//return false;
}
private void ListBox_DragEnterColoring(object sender, DragEventArgs e)
{
ListBox listBox = sender as ListBox;
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] names = (string[])e.Data.GetData(DataFormats.FileDrop, false);
if (ContainsCertificateFiles(names))
{
listBox.BackColor = GetColorFromFiles(names);
e.Effect = DragDropEffects.Copy;
return;
}
}
}
private static Color GetColorFromFiles(string[] files)
{
bool containsCerts = false;
bool containsContainers = false;
foreach (string file in files)
{
if (!containsCerts && file.EndsWith(".cer")) containsCerts = true;
if (!containsContainers && file.EndsWith(".p12")) containsContainers = true;
if (!containsContainers && file.EndsWith(".pfx")) containsContainers = true;
if (containsCerts && containsContainers) break;
}
if (containsCerts && !containsContainers) return Color.Green;
if (containsCerts && containsContainers) return Color.Orange;
if (!containsCerts && containsContainers) return Color.Yellow;
Debug.Assert(false);
return SystemColors.Window;
}
void ListBox_DragLeaveColoring(object sender, EventArgs e)
{
ListBox listBox = sender as ListBox;
listBox.BackColor = SystemColors.Window;
}
private void ListBox_DragEnter(object sender, DragEventArgs e)
{
ListBox listBox = sender as ListBox;
CertLocation loc = listBox.Tag as CertLocation;
// listBox.Items.Add(loc.ToString());
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] names = (string[])e.Data.GetData(DataFormats.FileDrop, false);
if (ContainsCertificateFiles(names))
{
e.Effect = DragDropEffects.Copy;
return;
}
}
e.Effect = DragDropEffects.None;
}
private void ListBox_DragDrop(object sender, DragEventArgs e)
{
ListBox listBox = (ListBox) sender;
CertLocation loc = (CertLocation) listBox.Tag;
string[] names = (string[])e.Data.GetData(DataFormats.FileDrop, false);
foreach (string name in names)
{
if (IsCertificateFile(name))
{
try
{
InstallCertificate(listBox, loc, name);
}
catch (CryptographicException cex)
{
MessageBox.Show(cex.Message, "Cryptography problem",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
ListBox_DragLeaveColoring(sender, e);
}
private static void ListBoxInstalledCerts_MouseDown(object sender, MouseEventArgs e)
{
if (sender is not ListBox senderListbox) return;
int draggedIndex = senderListbox.IndexFromPoint(e.X, e.Y);
if (draggedIndex == -1)
{
return;
}
_ = senderListbox.Tag as CertLocation;
List<string> exportedFilenames = [];
string exportFolder = Path.GetTempPath(); // Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
foreach (CertData certData in senderListbox.SelectedItems)
{
string exportedFilename = CertificateUtilMainForm.ExportCertToFolder(certData, exportFolder, "exported");
exportedFilenames.Add(exportedFilename);
}
DataObject dto = new(DataFormats.FileDrop, exportedFilenames.ToArray());
senderListbox.DoDragDrop(dto, DragDropEffects.Move);
}
private void ListBoxCertFiles_MouseDown(object sender, MouseEventArgs e)
{
int draggedIndex = listBoxCertFiles.IndexFromPoint(e.X, e.Y);
if (draggedIndex == -1)
{
return;
}
string path = textBoxFolder.Text;
List<string> filenames = [];
foreach (string filename in listBoxCertFiles.SelectedItems)
{
filenames.Add(path + Path.DirectorySeparatorChar + filename);
}
DataObject dto = new(DataFormats.FileDrop, filenames.ToArray());
listBoxCertFiles.DoDragDrop(dto, DragDropEffects.Copy);
}
private static void InstallCertificate(ListBox listBox, CertLocation certLocation, string name)
{
X509Store store = null;
try
{
store = new X509Store(certLocation.StoreName, certLocation.StoreLocation);
store.Open(OpenFlags.ReadWrite);
using X509Certificate2 cert = new(); // TODO
cert.Import(name, "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
store.Add(cert);
listBox.Items.Insert(0, new CertData(cert.RawData));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Installation problem",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
store?.Close();
}
}
private void Button1_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowNewFolderButton = false;
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
textBoxFolder.Text = folderBrowserDialog1.SelectedPath;
}
}
private void ListCertificates(string p)
{
listBoxCertFiles.Items.Clear();
DirectoryInfo di = new DirectoryInfo(p);
foreach (FileInfo fi in di.GetFiles())
{
if (IsCertificateFile(fi.FullName))
{
listBoxCertFiles.Items.Add(fi.Name);
}
}
}
private void TextBoxFolder_TextChanged(object sender, EventArgs e)
{
string potentialDir = textBoxFolder.Text;
if (Directory.Exists(potentialDir))
{
ListCertificates(potentialDir);
}
}
private void TextBoxFilterDisplay_TextChanged(object sender, EventArgs e)
{
List<ListBox> listBoxes = new List<ListBox>() {
listBoxCurrentUserMy, listBoxCurrentUserAddressBook,
listBoxCurrentUserTrustedPeople, listBoxCurrentUserRoot,
listBoxLocalMachineMy, listBoxLocalMachineAddressBook,
listBoxLocalMachineTrustedPeople, listBoxLocalMachineRoot};
#region RegEx compile
string regexText = this.textBoxFilterDisplay.Text.Trim();
if (regexText.Length == 0)
{
this.textBoxFilterDisplay.Text = ".";
regexText = ".";
}
Regex regex;
try
{
regex = new Regex(regexText, RegexOptions.IgnoreCase);
}
catch (Exception)
{
return;
}
#endregion
foreach (ListBox listBox in listBoxes)
{
ListCurrentCertificates(listBox, regex);
}
}
internal bool IsRegexMatch(Regex regex, X509Certificate2 cert)
{
return
regex.IsMatch(cert.Subject) ||
regex.IsMatch(cert.Issuer);
}
private void ListCurrentCertificates(ListBox listBox, Regex regex)
{
CertLocation certLocation = (CertLocation)listBox.Tag;
listBox.Items.Clear();
X509Store store = null;
try
{
store = new X509Store(certLocation.StoreName, certLocation.StoreLocation);
store.Open(OpenFlags.ReadOnly);
foreach (X509Certificate2 cert in store.Certificates)
{
if (regex == null ||
IsRegexMatch(regex, cert))
{
listBox.Items.Add(new CertData(cert.RawData));
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
store?.Close();
}
}
}
internal record CertLocation
{
public readonly StoreLocation StoreLocation;
public readonly StoreName StoreName;
public CertLocation(StoreLocation storeLocation, StoreName storeName) => (StoreLocation, StoreName) = (storeLocation, storeName);
public override string ToString()
{
return $"Certificate store {Enum.GetName(typeof(StoreLocation), this.StoreLocation)}/{Enum.GetName(typeof(StoreName), this.StoreName)}";
}
}
}