Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
451 lines (387 loc) · 15.7 KB
/
Copy pathProgram.cs
File metadata and controls
451 lines (387 loc) · 15.7 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
using DiscUtils;
using DiscUtils.Iso9660;
using DiscUtils.Streams;
using DiscUtils.Udf;
using DiscUtils.Wim;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DiscUtilsRegistryHive = DiscUtils.Registry.RegistryHive;
using DiscUtilsRegistryKey = DiscUtils.Registry.RegistryKey;
using Microsoft.Win32;
using Microsoft.Management.Infrastructure;
using System.Reflection;
#pragma warning disable IDE0079 // Remove unnecessary suppression
#pragma warning disable CA1416 // Validate platform compatibility
#pragma warning disable IDE0057 // Use range operator
namespace LTR.GetProductKey;
public static class Program
{
private static readonly object _syncObj = new();
static Program()
{
DiscUtils.Complete.SetupHelper.SetupComplete();
}
private static string FormatMessage(this Exception ex) =>
#if DEBUG
ex.ToString();
#else
ex.GetBaseException().Message;
#endif
public static int Main(params string[] args)
{
try
{
UnsafeMain(args);
return 0;
}
catch (Exception ex)
{
Console.BackgroundColor = ConsoleColor.Red;
Console.Error.WriteLine(ex.FormatMessage());
Console.ResetColor();
return ex.HResult;
}
}
public static void UnsafeMain(params string[] args)
{
if (args is not null && args.Length == 1 && args[0].Equals("/?", StringComparison.Ordinal))
{
Console.WriteLine(@"GetProductKey
A tool to show Windows installation information including product key.
Copyright (c) Olof Lagerkvist, LTR Data, 2021-2026
http://ltr-data.se https://github.com/LTRData
Syntax to query current machine (Windows only):
GetProductKey
Syntax to query another machine on network (Windows only):
GetProductKey \\machinename
Syntax for an offline Windows installation on an attached external harddisk
GetProductKey D:\
GetProductKey /mnt/external
Syntax for a virtual machine image (supports vhd, vhdx, vmdk and vdi):
GetProductKey D:\path\image.vhd
GetProductKey /path/image.vhd
Syntax for a setup ISO or WIM image:
GetProductKey D:\path\windows_setup.iso
GetProductKey /path/windows_setup.iso");
return;
}
var online_root_keys = new ConcurrentBag<RegistryKey>();
Task<string?>? hardware_product_key = null;
var offline_root_keys = new ConcurrentBag<DiscUtilsRegistryKey>();
var value_getters = new ConcurrentBag<KeyValuePair<string, Func<string, object?>>>();
var disposables = new ConcurrentBag<IDisposable>();
if (args is null || args.Length == 0)
{
var key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64).OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
if (key is not null)
{
disposables.Add(key);
online_root_keys.Add(key);
value_getters.Add(new($@"\\{Environment.MachineName}", key.GetValue));
}
hardware_product_key = Task.Run(() =>
{
using var cimSession = CimSession.Create(null);
using var cim = cimSession?.EnumerateInstances(@"root\cimv2", "SoftwareLicensingService").FirstOrDefault();
return cim?.CimInstanceProperties["OA3xOriginalProductKey"].Value as string;
});
}
else
{
Parallel.ForEach(args, arg =>
{
try
{
if (arg.StartsWith(@"\\", StringComparison.Ordinal) &&
arg.IndexOf('\\', 2) < 0)
{
using var remotehive = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, arg, RegistryView.Registry64);
var key = remotehive?.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
if (key is not null)
{
disposables.Add(key);
online_root_keys.Add(key);
value_getters.Add(new(arg, key.GetValue));
}
}
else if (Directory.Exists(arg))
{
var path = Path.Combine(arg, @"Windows\system32\config\SOFTWARE");
var hive = new DiscUtilsRegistryHive(File.OpenRead(path), ownership: Ownership.Dispose);
disposables.Add(hive);
var key = hive.Root.OpenSubKey(@"Microsoft\Windows NT\CurrentVersion");
offline_root_keys.Add(key);
value_getters.Add(new(arg, key.GetValue));
}
else if (File.Exists(arg) && Path.GetExtension(arg).Equals(".iso", StringComparison.OrdinalIgnoreCase))
{
var file = File.OpenRead(arg);
disposables.Add(file);
DiscFileSystem iso;
if (UdfReader.Detect(file))
{
iso = new UdfReader(file);
}
else
{
iso = new CDReader(file, joliet: true);
}
var wiminfo = iso.GetFileInfo(@"sources\install.wim");
if (!wiminfo.Exists)
{
wiminfo = iso.GetFileInfo(@"sources\boot.wim");
if (!wiminfo.Exists)
{
throw new FileNotFoundException(@$"Cannot find sources{Path.DirectorySeparatorChar}install.wim in image");
}
}
var image = new WimFile(wiminfo.OpenRead());
foreach (var fs in image.EnumerateWimImages())
{
var hive = new DiscUtilsRegistryHive(fs.Value, FileAccess.Read);
var key = hive.Root.OpenSubKey(@"Microsoft\Windows NT\CurrentVersion");
offline_root_keys.Add(key);
value_getters.Add(new(@$"{arg}{Path.DirectorySeparatorChar}{wiminfo.FullName} index {fs.Key}", name =>
{
lock (file)
{
return key.GetValue(name);
}
}));
}
}
else if (File.Exists(arg) && Path.GetExtension(arg).Equals(".wim", StringComparison.OrdinalIgnoreCase))
{
var file = File.OpenRead(arg);
disposables.Add(file);
var image = new WimFile(file);
foreach (var fs in image.EnumerateWimImages())
{
var hive = new DiscUtilsRegistryHive(fs.Value, FileAccess.Read);
var key = hive.Root.OpenSubKey(@"Microsoft\Windows NT\CurrentVersion");
offline_root_keys.Add(key);
value_getters.Add(new($"{arg} index {fs.Key}", name =>
{
lock (file)
{
return key.GetValue(name);
}
}));
}
}
else
{
var image = VirtualDisk.OpenDisk(arg, FileAccess.Read)
?? (File.Exists(arg) ? new DiscUtils.Raw.Disk(arg, FileAccess.Read) : throw new FileNotFoundException($"File '{arg}' not found"));
disposables.Add(image);
foreach (var fs in image.EnumerateVirtualDiskImageFileSystems())
{
var hive = new DiscUtilsRegistryHive(fs.Value, FileAccess.Read);
var key = hive.Root.OpenSubKey(@"Microsoft\Windows NT\CurrentVersion");
offline_root_keys.Add(key);
value_getters.Add(new($"{arg} partition {fs.Key}", name =>
{
lock (image)
{
return key.GetValue(name);
}
}));
}
}
}
catch (Exception ex)
{
lock (_syncObj)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine($"Error opening '{arg}': {ex.FormatMessage()}");
Console.ResetColor();
}
}
});
}
Parallel.ForEach(value_getters, obj =>
{
try
{
var sb = new StringBuilder()
.AppendLine(obj.Key)
.AppendLine($"Product name: {obj.Value("ProductName")}")
.AppendLine($"Product Id: {obj.Value("ProductId")}")
.AppendLine($"Edition: {obj.Value("EditionID")}")
.AppendLine($"Installation type: {obj.Value("InstallationType")}")
.AppendLine($"Version: {GetVersion(obj.Value)}")
.AppendLine($"Type: {obj.Value("CurrentType")}")
.AppendLine($"Product key: {DecodeProductKey(obj.Value("DigitalProductId") as byte[])}")
.AppendLine($"Install time (UTC): {GetInstallTime(obj.Value)}")
.AppendLine($"Registered owner: {obj.Value("RegisteredOwner")}")
.AppendLine($"Registered organization: {obj.Value("RegisteredOrganization")}");
if (hardware_product_key is not null)
{
try
{
sb.AppendLine($"Hardware product key: {hardware_product_key.Result}");
}
catch (Exception ex)
{
sb.AppendLine($"Failed to get hardware product key: {ex.GetBaseException().Message}");
}
}
var msg = sb.ToString();
lock (_syncObj)
{
Console.WriteLine(msg);
}
}
catch (Exception ex)
{
lock (_syncObj)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine($"Error reading '{obj.Key}': {ex.FormatMessage()}");
Console.ResetColor();
}
}
});
Parallel.ForEach(disposables.OfType<IDisposable>(), obj => obj.Dispose());
}
private static string GetVersion(Func<string, object?> value)
{
var currentMajor = value("CurrentMajorVersionNumber");
if (currentMajor is not null)
{
return $"{currentMajor}.{value("CurrentMinorVersionNumber")}.{value("CurrentBuildNumber")} {value("DisplayVersion")}";
}
else
{
return $"{value("CurrentVersion")}.{value("CurrentBuildNumber")} {value("CSDVersion")} {value("CSDBuildNumber")}";
}
}
private static DateTime? GetInstallTime(Func<string, object?> value)
{
if (value("InstallTime") is long time &&
time != 0)
{
return DateTime.FromFileTimeUtc(time);
}
if (value("InstallDate") is int date &&
date != 0)
{
return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(date);
}
return null;
}
public static IEnumerable<KeyValuePair<int, DiscFileInfo>> EnumerateWimImages(this WimFile wim)
{
for (var i = 0; i < wim.ImageCount; i++)
{
var fs = wim.GetImage(i);
var hive = fs.GetFileInfo(@"Windows\system32\config\SOFTWARE");
if (hive is not null && hive.Exists)
{
yield return new(i + 1, hive);
}
}
}
public static IEnumerable<KeyValuePair<int, DiscFileInfo>> EnumerateVirtualDiskImageFileSystems(this VirtualDisk image)
{
if (image.Partitions is { Count: > 0 } partitions)
{
for (var i = 0; i < partitions.Count; i++)
{
var partition = partitions[i];
var raw = partition.Open();
var fsrec = FileSystemManager.DetectFileSystems(raw);
DiscFileSystem fs;
try
{
if (fsrec.Count > 0)
{
fs = fsrec[0].Open(raw);
}
else
{
continue;
}
}
catch
{
continue;
}
var hive = fs.GetFileInfo(@"Windows\system32\config\SOFTWARE");
if (hive is null || !hive.Exists)
{
hive = fs.GetFileInfo(@"WINNT\system32\config\SOFTWARE");
}
if (hive is not null && hive.Exists)
{
yield return new(i + 1, hive);
}
}
}
else
{
var raw = image.Content;
var fsrec = FileSystemManager.DetectFileSystems(raw);
if (fsrec.Count > 0)
{
var fs = fsrec[0].Open(raw);
var hive = fs.GetFileInfo(@"Windows\system32\config\SOFTWARE");
if (hive is null || !hive.Exists)
{
hive = fs.GetFileInfo(@"WINNT\system32\config\SOFTWARE");
}
if (hive is not null && hive.Exists)
{
yield return new(0, hive);
}
}
}
}
public static string? DecodeProductKey(ReadOnlySpan<byte> data)
{
Span<char> productKey = stackalloc char[29];
if (DecodeProductKey(data, productKey))
{
return productKey.ToString();
}
return null;
}
public static bool DecodeProductKey(ReadOnlySpan<byte> data, Span<char> destination)
{
if (data.Length < 67)
{
return false;
}
Span<byte> valueDataBuffer = stackalloc byte[15];
data.Slice(52, 15).CopyTo(valueDataBuffer);
var productKey = destination.Slice(0, 29);
var o = productKey.Length;
const string chars = "BCDFGHJKMPQRTVWXY2346789";
for (var i = 24; i >= 0; i--)
{
var r = 0;
for (var j = 14; j >= 0; j--)
{
r = (r << 8) | valueDataBuffer[j];
valueDataBuffer[j] = (byte)(r / 24);
r %= 24;
}
productKey[--o] = chars[r];
if ((i % 5) == 0 && i != 0)
{
productKey[--o] = '-';
}
}
if (MemoryExtensions.Equals(productKey, "BBBBB-BBBBB-BBBBB-BBBBB-BBBBB".AsSpan(), StringComparison.Ordinal))
{
return false;
}
return true;
}
}