-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
618 lines (536 loc) · 31.1 KB
/
Program.cs
File metadata and controls
618 lines (536 loc) · 31.1 KB
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
using iTextSharp.text;
using iTextSharp.text.pdf;
using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using ZXing;
using Version = System.Version;
namespace Relock
{
static class Program
{
// Import AttachConsole and FreeConsole from Kernel32.dll
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool AttachConsole(int dwProcessId);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool FreeConsole();
// Import WriteConsoleInput to simulate input
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool WriteConsoleInput(IntPtr hConsoleInput, [In] INPUT_RECORD[] lpBuffer, uint nLength, out uint lpNumberOfEventsWritten);
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr GetStdHandle(int nStdHandle);
const int STD_INPUT_HANDLE = -10;
const int ATTACH_PARENT_PROCESS = -1;
// Define INPUT_RECORD struct for input events
struct INPUT_RECORD
{
public ushort EventType;
public KEY_EVENT_RECORD KeyEvent;
}
// Define KEY_EVENT_RECORD struct
struct KEY_EVENT_RECORD
{
public bool bKeyDown;
public ushort wRepeatCount;
public ushort wVirtualKeyCode;
public ushort wVirtualScanCode;
public char uChar;
public uint dwControlKeyState;
}
[STAThread]
private static void Main(string[] args)
{
if (args.Length > 0)
{
string drive = args[0].ToLower();
switch (drive)
{
case "/register":
RegisterInRegistry();
break;
case "/unregister":
UnregisterFromRegistry();
break;
default:
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
getRecoveryKey(drive);
lockDrive(drive);
break;
}
}
else
{
// Versioning information for display
Version version = Assembly.GetExecutingAssembly().GetName().Version;
string relockVersion = $"{version.Major}.{version.Minor}.{version.Build}";
// Attach to parent console (e.g., command line if launched from there)
AttachConsole(ATTACH_PARENT_PROCESS);
// Display version and usage information in the console
Console.WriteLine("\n\n" +
String.Format(Properties.Resources.Relock0ReLockABitlockerEnabledDrive2024ManfredMueller, relockVersion) + "\n\n" +
Properties.Resources.UsageRelockRegisterUnregister + "\n" +
"/register\t" + Properties.Resources.RegisterInTheExplorerContextMenu + "\n" +
"/unregister\t" + Properties.Resources.UnregisterFromTheExplorerContextMenu
);
// Emulate Enter key press to simulate user pressing "Enter"
SimulateEnterKeyPress();
// Ensure the console is released immediately after writing
FreeConsole();
// Exit the application cleanly
Environment.Exit(0); // Exit code 0 means success
}
}
// Method to simulate Enter key press
private static void SimulateEnterKeyPress()
{
IntPtr stdInputHandle = GetStdHandle(STD_INPUT_HANDLE);
INPUT_RECORD[] records = new INPUT_RECORD[2];
records[0].EventType = 0x0001; // KEY_EVENT
records[0].KeyEvent.bKeyDown = true;
records[0].KeyEvent.wVirtualKeyCode = 0x0D; // Virtual code for "Enter"
records[0].KeyEvent.wVirtualScanCode = 0x1C;
records[0].KeyEvent.uChar = '\r';
records[1].EventType = 0x0001; // KEY_EVENT
records[1].KeyEvent.bKeyDown = false;
records[1].KeyEvent.wVirtualKeyCode = 0x0D; // Virtual code for "Enter"
records[1].KeyEvent.wVirtualScanCode = 0x1C;
records[1].KeyEvent.uChar = '\r';
WriteConsoleInput(stdInputHandle, records, (uint)records.Length, out _);
}
public static void RegisterInRegistry()
{
string keyName = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\Drive\\shell\\relock-bde";
string shellParent = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\Drive\\shell";
string _vDefault = Properties.Resources.RelockThisDrive;
const string _vAppliesTo = "System.Volume.BitLockerProtection:=System.Volume.BitLockerProtection#On OR System.Volume.BitLockerProtection:=System.Volume.BitLockerProtection#Encrypting OR System.Volume.BitLockerProtection:=System.Volume.BitLockerProtection#Suspended";
const string _vMultiSelectModel = "Single";
string appPath = Assembly.GetExecutingAssembly().Location;
string appIcon = appPath + ",0"; // Assuming the icon is the first resource in the executable
try
{
Registry.SetValue(keyName, "", _vDefault);
Registry.SetValue(keyName, "AppliesTo", _vAppliesTo);
Registry.SetValue(keyName, "MultiSelectModel", _vMultiSelectModel);
Registry.SetValue(keyName, "Icon", appIcon);
string commandKeyName = keyName + "\\command";
string _vCommandValue = appPath + " %1";
Registry.SetValue(commandKeyName, "", _vCommandValue);
Registry.SetValue(shellParent, "", "relock-bde"); // make this verb the default (bold)
MessageBox.Show(Properties.Resources.ProgramSuccessfullyRegisteredInTheRegistry, "Relock", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(Properties.Resources.ErrorWhileUpdatingRegistry + ex.Message, "Relock", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public static void UnregisterFromRegistry()
{
try
{
RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Classes\\Drive\\shell", true);
if (key != null)
{
key.DeleteSubKeyTree("relock-bde", false);
key.Close();
MessageBox.Show(Properties.Resources.ProgramSuccessfullyUnregisteredFromTheRegistry, "Relock", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show(Properties.Resources.RegistryKeyNotFound, "Relock", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
catch (Exception ex)
{
MessageBox.Show(Properties.Resources.ErrorWhileUpdatingRegistry + ex.Message, "Relock", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public static void getRecoveryKey(string driveLetter)
{
try
{
driveLetter = driveLetter.Replace("\\", "");
var psi = new ProcessStartInfo("manage-bde", string.Format("-protectors -get {0} -Type recoverypassword", driveLetter))
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden
};
StringBuilder outputBuilder = new StringBuilder();
using (Process process = new Process())
{
process.StartInfo = psi;
process.OutputDataReceived += (sender, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
{
outputBuilder.AppendLine(e.Data);
}
};
process.ErrorDataReceived += (sender, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
{
outputBuilder.AppendLine(Properties.Resources.OutputError + e.Data);
}
};
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
}
string output = outputBuilder.ToString();
// Filter lines that end with a number and do not contain "ersion"
string[] lines = output.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
if (System.Text.RegularExpressions.Regex.IsMatch(line, @"[0-9]$") && !line.Contains("ersion"))
{
// Remove spaces and get the result
string result = line.Replace(" ", string.Empty);
// Keep original recovery key for copy/unmask
string originalRecoveryKey = result;
bool isMasked = true;
// Generate QR code image
string qrData = $"{result}";
var qrWriter = new BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Options = new ZXing.Common.EncodingOptions
{
Width = 400,
Height = 400,
Margin = 1
}
};
using (var qrImage = qrWriter.Write(qrData))
{
// Convert the icon to a bitmap
using (var iconBitmap = Properties.Resources.relock.ToBitmap())
{
using (Graphics graphics = Graphics.FromImage(qrImage))
{
// Draw the icon on the QR code, centered on the white square
int iconX = (qrImage.Width - iconBitmap.Width) / 2;
int iconY = (qrImage.Height - iconBitmap.Height) / 2;
graphics.DrawImage(iconBitmap, new Point(iconX, iconY));
}
// Create the PictureBox to display the combined image
using (var pictureBox = new PictureBox())
{
pictureBox.Image = qrImage;
pictureBox.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBox.Refresh(); // Force refresh to ensure the image is displayed
// Create the label for the recovery key
Label recoveryKeyLabel = new Label
{
AutoSize = false,
Width = pictureBox.Width,
TextAlign = ContentAlignment.MiddleCenter,
MaximumSize = new Size(pictureBox.Width, 0), // Ensure the label does not exceed the width of the PictureBox
Height = 50, // Ensure enough height to fit the text
Text = result
};
// Adjust font size to fit the label width
System.Drawing.Font font = AdjustFontToFitLabel(recoveryKeyLabel, result);
recoveryKeyLabel.Font = font;
recoveryKeyLabel.Text = MaskKey(originalRecoveryKey);
// Create the label for the drive letter
Label driveLabel = new Label
{
AutoSize = false,
Width = pictureBox.Width,
TextAlign = ContentAlignment.MiddleCenter,
MaximumSize = new Size(pictureBox.Width, 0),
Height = 30, // Height of the label above the QR code
Text = string.Format(Properties.Resources.RecoveryCodeForDrive0, driveLetter.ToUpper())
};
// Adjust font size to fit the label width
System.Drawing.Font driveFont = AdjustFontToFitLabel(driveLabel, driveLabel.Text);
driveLabel.Font = driveFont;
// Local helper to mask key
string MaskKey(string key)
{
if (string.IsNullOrEmpty(key)) return key;
if (key.Length <= 4) return new string('\u2022', key.Length);
return new string('\u2022', key.Length - 4) + key.Substring(key.Length - 4);
}
// Create the form
Form form = new Form
{
Icon = Properties.Resources.relock,
Text = Properties.Resources.RecoveryKey,
AutoSize = true,
AutoSizeMode = AutoSizeMode.GrowAndShrink,
StartPosition = FormStartPosition.CenterScreen
};
// Add controls to the form in the correct order
form.Controls.Add(driveLabel);
form.Controls.Add(pictureBox);
form.Controls.Add(recoveryKeyLabel);
// Create and configure the PrintButton
Button printButton = new Button
{
Text = Properties.Resources.Print,
AutoSize = true
};
printButton.Click += (sender, e) =>
{
var confirm = MessageBox.Show(Properties.Resources.DoYouWantToPrintTheRecoveryKey, "Relock", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (confirm != DialogResult.Yes) return;
using (PrintDocument printDocument = new PrintDocument())
{
printDocument.PrintPage += (s, ev) =>
{
float margin = 10;
float xCenter = (ev.PageBounds.Width - pictureBox.Width) / 2;
float y = margin;
ev.Graphics.DrawString(driveLabel.Text, driveLabel.Font, Brushes.Black, xCenter, y);
y += driveLabel.Height + margin;
ev.Graphics.DrawImage(pictureBox.Image, xCenter, y);
y += pictureBox.Height + margin;
ev.Graphics.DrawString(recoveryKeyLabel.Text, recoveryKeyLabel.Font, Brushes.Black, xCenter, y);
};
using (PrintDialog printDialog = new PrintDialog())
{
printDialog.Document = printDocument;
if (printDialog.ShowDialog() == DialogResult.OK)
{
printDocument.Print();
}
}
}
};
// Create and configure the SaveButton
Button saveButton = new Button
{
Text = Properties.Resources.Save,
AutoSize = true
};
saveButton.Click += (sender, e) =>
{
SaveFileDialog saveFileDialog = new SaveFileDialog
{
CreatePrompt = true,
OverwritePrompt = true,
Filter = Properties.Resources.PDFFilesPdfPNGImagePngJPEGImageJpg,
DefaultExt = "pdf",
FileName = "RecoveryKey.pdf"
};
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
string ext = Path.GetExtension(saveFileDialog.FileName).ToLowerInvariant();
if (ext == ".pdf")
{
// Create the PDF document
using (var pdfDocument = new Document())
{
PdfWriter.GetInstance(pdfDocument, new FileStream(saveFileDialog.FileName, FileMode.Create));
pdfDocument.Open();
// Add the drive label text
var driveLabelParagraph = new Paragraph(driveLabel.Text, FontFactory.GetFont("Arial", driveLabel.Font.Size, iTextSharp.text.Font.BOLD))
{
Alignment = Element.ALIGN_CENTER,
SpacingAfter = 20f
};
pdfDocument.Add(driveLabelParagraph);
// Add the QR code image
using (var qrStream = new MemoryStream())
{
qrImage.Save(qrStream, System.Drawing.Imaging.ImageFormat.Png);
var qrPdfImage = iTextSharp.text.Image.GetInstance(qrStream.ToArray());
qrPdfImage.Alignment = Element.ALIGN_CENTER;
pdfDocument.Add(qrPdfImage);
}
// Add the recovery key text
var recoveryKeyParagraph = new Paragraph(recoveryKeyLabel.Text, FontFactory.GetFont("Arial", recoveryKeyLabel.Font.Size, iTextSharp.text.Font.BOLD))
{
Alignment = Element.ALIGN_CENTER,
SpacingBefore = 20f
};
pdfDocument.Add(recoveryKeyParagraph);
pdfDocument.Close();
}
}
else if (ext == ".png" || ext == ".jpg" || ext == ".jpeg")
{
// Render combined image and save
int margin = 10;
int width = Math.Max(pictureBox.Width, 400) + margin * 2;
int height = driveLabel.Height + pictureBox.Height + recoveryKeyLabel.Height + margin * 5;
using (Bitmap bmp = new Bitmap(width, height))
{
using (Graphics g = Graphics.FromImage(bmp))
{
g.Clear(Color.White);
int x = margin + (width - margin * 2 - pictureBox.Width) / 2;
int y = margin;
// Draw drive label
using (Brush b = new SolidBrush(Color.Black))
{
g.DrawString(driveLabel.Text, driveLabel.Font, b, x, y);
}
y += driveLabel.Height + margin;
// Draw QR
g.DrawImage(qrImage, x, y);
y += pictureBox.Height + margin;
// Draw recovery key
using (Brush b = new SolidBrush(Color.Black))
{
g.DrawString(recoveryKeyLabel.Text, recoveryKeyLabel.Font, b, x, y);
}
}
if (ext == ".png")
{
bmp.Save(saveFileDialog.FileName, System.Drawing.Imaging.ImageFormat.Png);
}
else
{
bmp.Save(saveFileDialog.FileName, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
}
};
// Create and configure the CopyButton
Button copyButton = new Button
{
Text = Properties.Resources.Copy,
AutoSize = true
};
copyButton.Click += (sender, e) =>
{
// Robust clipboard copy with retries because clipboard can be busy
const int maxRetries = 5;
const int retryDelayMs = 200;
bool success = false;
for (int i = 0; i < maxRetries; i++)
{
try
{
Clipboard.SetText(originalRecoveryKey);
success = true;
break;
}
catch (Exception)
{
Thread.Sleep(retryDelayMs);
}
}
if (success)
{
MessageBox.Show(Properties.Resources.RecoveryKeyCopiedToClipboard, "Relock", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show(Properties.Resources.FailedToCopyToClipboardPleaseTryAgain, "Relock", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
};
// Create and configure the Mask/Unmask Button
Button maskButton = new Button
{
Text = Properties.Resources.Unmask,
AutoSize = true
};
maskButton.Click += (sender, e) =>
{
isMasked = !isMasked;
if (isMasked)
{
recoveryKeyLabel.Text = MaskKey(originalRecoveryKey);
maskButton.Text = Properties.Resources.Unmask;
}
else
{
recoveryKeyLabel.Text = originalRecoveryKey;
maskButton.Text = Properties.Resources.Mask;
}
};
// Create a FlowLayoutPanel to hold the buttons and center them
FlowLayoutPanel buttonsPanel = new FlowLayoutPanel
{
AutoSize = true,
AutoSizeMode = AutoSizeMode.GrowAndShrink,
FlowDirection = FlowDirection.LeftToRight,
WrapContents = false
};
buttonsPanel.Controls.Add(copyButton);
buttonsPanel.Controls.Add(maskButton);
buttonsPanel.Controls.Add(saveButton);
buttonsPanel.Controls.Add(printButton);
form.Controls.Add(buttonsPanel);
// Adjust layout
driveLabel.Location = new Point(0, 10);
pictureBox.Location = new Point(0, driveLabel.Bottom + 10);
recoveryKeyLabel.Location = new Point(0, pictureBox.Bottom + 10);
// Place the buttons panel centered under the recovery key when form is shown
form.Shown += (s, ev) =>
{
buttonsPanel.Location = new Point((form.ClientSize.Width - buttonsPanel.Width) / 2, recoveryKeyLabel.Bottom + 10);
};
form.ShowDialog();
}
}
}
break;
}
}
}
catch (Exception ex)
{
string errorMessage = string.Format(Properties.Resources.ErrorRetrievingKey, ex.Message);
MessageBox.Show(errorMessage, Properties.Resources.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
// Copy the error message to the clipboard
try
{
Clipboard.SetText(errorMessage);
}
catch { }
}
}
private static System.Drawing.Font AdjustFontToFitLabel(Label label, string text)
{
// Define the maximum font size to try
float fontSize = 20; // Initial font size
System.Drawing.Font font = new System.Drawing.Font("Arial", fontSize, FontStyle.Bold);
SizeF textSize;
// Measure text size and adjust font size
using (Graphics g = label.CreateGraphics())
{
do
{
fontSize--;
font = new System.Drawing.Font("Arial", fontSize, FontStyle.Bold);
textSize = g.MeasureString(text, font);
}
while (textSize.Width > label.Width && fontSize > 1);
}
return font;
}
public static void lockDrive(string driveLetter)
{
try
{
driveLetter = driveLetter.Replace("\\", "");
var psi = new ProcessStartInfo("manage-bde", string.Format("-lock {0} -ForceDismount", driveLetter))
{ CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden };
Process.Start(psi);
}
catch (Exception exc)
{
MessageBox.Show(string.Format( Properties.Resources.FailedToLockDriveRN0, exc.Message), "Relock",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}