forked from CCob/Volumiser
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
405 lines (321 loc) · 18 KB
/
Program.cs
File metadata and controls
405 lines (321 loc) · 18 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
using Amazon.Runtime;
using Amazon.Runtime.CredentialManagement;
using DiscUtils;
using DiscUtils.Ebs;
using DiscUtils.Setup;
using DiscUtils.Streams;
using DiscUtils.Ntfs;
using Mono.Options;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Text;
namespace DiscImage.EbsDiscTest {
class Program {
static string CurrentPath = "";
static DiscFileSystem CurrentFileSystem;
static VolumeManager VolumeManager;
static Volumiser.UI UI;
static IEnumerable<string> Volumes;
static Task DownloadTask;
static string PathSeparator;
static VirtualDisk GetEBSDiskImage(string snapshotId, string profile, string awsAccessKey, string awsSecret, string region) {
AWSCredentials credentials = null;
if(profile != null) {
var chain = new CredentialProfileStoreChain();
if (!chain.TryGetAWSCredentials(profile, out credentials)) {
throw new ArgumentException($"[!] Failed to find profile with name {profile}");
}
}else if(awsAccessKey != null) {
credentials = new BasicAWSCredentials(awsAccessKey, awsSecret);
}
var result = new Disk(snapshotId, region, credentials);
return result;
}
static VirtualDisk GetLocalDiskImage(string path) {
return VirtualDisk.OpenDisk(path, FileAccess.Read);
}
static void Main(string[] args) {
bool showHelp = false;
string profile = null;
string awsAccessKey = null;
string awsAccessSecret = null;
string awsRegion = null;
string command = null;
string image = null;
string path = "";
OptionSet option_set = new OptionSet()
.Add("h|help", "Display this help", v => showHelp = v != null)
.Add("awsprofile=", "AWS profile to use", v => profile = v)
.Add("awskey=", "AWS access key to use", v => awsAccessKey = v)
.Add("awssecret=", "AWS secret", v => awsAccessSecret = v)
.Add("awsregion=", "AWS region", v => awsRegion = v)
.Add("command=", "The command to execute: [volumes|file_list|ls|extract]", v => command = v)
.Add("image=", @"The path to the virtual disk, e.g. C:\temp\backup.vhdx or ebs://snapshotid", v => image = v)
.Add("path=", @"Volume and path to query within the virtual disk filesystem ", v => path = v);
try {
option_set.Parse(args);
if(image == null) {
Console.WriteLine("[!] Image path not specified");
showHelp = true;
}
if (showHelp) {
option_set.WriteOptionDescriptions(Console.Out);
return;
}
} catch (Exception e) {
Console.WriteLine($"[!] Failed to parse arguments: {e.Message}");
option_set.WriteOptionDescriptions(Console.Out);
return;
}
if (showHelp) {
option_set.WriteOptionDescriptions(Console.Out);
return;
}
DiscUtils.Containers.SetupHelper.SetupContainers();
DiscUtils.FileSystems.SetupHelper.SetupFileSystems();
SetupHelper.RegisterAssembly(typeof(DiskImageFile).Assembly);
VirtualDisk disk;
try {
if (image.StartsWith("ebs://")) {
disk = GetEBSDiskImage(image.Substring(6), profile, awsAccessKey, awsAccessSecret, awsRegion);
var ebsDisk = (Disk)disk;
} else if (image.StartsWith(@"\\.\")) {
disk = new DiscUtils.RawDisk.Disk(image);
} else {
disk = GetLocalDiskImage(image);
}
if (disk == null) {
Console.WriteLine($"[!] Failed to open disk {image}");
return;
}
VolumeManager = new VolumeManager(disk);
if (command != null) {
Console.WriteLine($"[+] Opened disk image, Size: {GetHumanSize(disk.Capacity)}");
if (command == "volumes") {
foreach (var volume in VolumeManager.GetLogicalVolumes()) {
var volumeStream = volume.Open();
var fsType = FileSystemManager.DetectFileSystems(volumeStream);
try {
Console.WriteLine($"\tVolume ID: {volume.Identity}, Size: {GetHumanSize(volume.Length)}, Type: {(fsType.Count > 0 ? fsType[0].Description : "Unknown")}");
} catch (Exception) { }
}
} else if (command == "ls" || command == "extract") {
var pathStart = path.LastIndexOf(":");
var volumePath = path.Substring(0, pathStart);
var filePath = path.Substring(pathStart + 1);
var volume = VolumeManager.GetVolume(volumePath);
var sparseStream = volume.Open();
Console.WriteLine($"[+] Opened volume with ID {volumePath}");
var fsInfo = FileSystemManager.DetectFileSystems(sparseStream);
var fs = fsInfo[0].Open(sparseStream);
if (fs is NtfsFileSystem)
{
((NtfsFileSystem)fs).NtfsOptions.HideHiddenFiles = false;
((NtfsFileSystem)fs).NtfsOptions.HideSystemFiles = false;
}
if (command == "ls") {
foreach (var file in fs.GetDirectories(filePath)) {
var dirInfo = fs.GetDirectoryInfo(file);
Console.WriteLine($"{dirInfo.LastWriteTimeUtc} {"DIR",-15} {Path.GetFileName(file)}");
}
foreach (var file in fs.GetFiles(filePath)) {
var fileInfo = fs.GetFileInfo(file);
Console.WriteLine($"{fileInfo.LastWriteTimeUtc} { $"{GetHumanSize(fileInfo.Length)}",-16} {Path.GetFileName(file)}");
}
} else {
var fileStream = fs.OpenFile(filePath, FileMode.Open, FileAccess.Read);
Console.WriteLine($"[+] Opened file with path {filePath} for with size: {GetHumanSize(fileStream.Length)}");
File.WriteAllBytes(Path.GetFileName(filePath), StreamUtilities.ReadExactly(fileStream, (int)fileStream.Length));
}
} else if (command == "file_list") {
foreach (var volume in VolumeManager.GetLogicalVolumes()) {
using (var sparseStream = volume.Open()) {
var fsInfo = FileSystemManager.DetectFileSystems(sparseStream);
if (fsInfo != null && fsInfo.Count > 0) {
DiscFileSystem fileSystem = fsInfo[0].Open(sparseStream);
if (fileSystem is NtfsFileSystem) {
((NtfsFileSystem)fileSystem).NtfsOptions.HideHiddenFiles = false;
((NtfsFileSystem)fileSystem).NtfsOptions.HideSystemFiles = false;
}
List<string> entries = new List<string>();
List<string> dirs = new List<string>();
dirs.Add("");
while (dirs.Count > 0) {
if (dirs.First() == "" || (fileSystem.Exists(dirs.First()) && (fileSystem.GetAttributes(dirs.First()) & FileAttributes.Directory) == FileAttributes.Directory)) {
entries = fileSystem.GetFileSystemEntries(dirs.First()).ToList();
dirs.RemoveAt(0);
dirs.InsertRange(0, entries);
foreach (string f in entries) {
Console.WriteLine($"{volume.Identity}:{f}");
}
} else {
dirs.RemoveAt(0);
}
}
}
}
}
}
} else {
Volumes = VolumeManager.GetLogicalVolumes().Select(v => v.Identity);
UI = new Volumiser.UI();
UI.ItemSelected += Ui_ItemSelected;
UI.ItemChanged += UI_ItemChanged;
UI.UpdateCurrentPathItems(Volumes.ToList());
if (Volumes.Count() > 0)
UI_ItemChanged(Volumes.First());
UI.Run();
}
}catch(Exception e) {
Console.WriteLine($"[!] {e.Message}");
}
}
private static void UI_ItemChanged(string itemValue) {
string itemLabel;
if (itemValue != ".." && CurrentPath != null && CurrentFileSystem != null) {
itemLabel = $" | Path: {CurrentPath}\\{itemValue}";
bool isNotDirectory = (CurrentFileSystem.GetAttributes($"{CurrentPath}\\{itemValue}") & FileAttributes.Directory) != FileAttributes.Directory;
bool isNotReparsePoint = (CurrentFileSystem.GetAttributes($"{CurrentPath}\\{itemValue}") & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint;
if (CurrentFileSystem.Exists($"{CurrentPath}\\{itemValue}") && isNotDirectory && isNotReparsePoint) {
var fileLen = CurrentFileSystem.GetFileLength($"{CurrentPath}\\{itemValue}");
itemLabel += $" | Size: {GetHumanSize(fileLen)}";
if(fileLen < 10240 && fileLen > 0 && (itemValue.EndsWith(".txt") || itemValue.EndsWith(".log") || itemValue.EndsWith(".config") || itemValue.EndsWith(".ini") || itemValue.EndsWith(".xml"))) {
using (var fileStream = CurrentFileSystem.OpenFile($"{CurrentPath}\\{itemValue}", FileMode.Open, FileAccess.Read)) {
var fileData = StreamUtilities.ReadExactly(fileStream, (int)fileLen);
var encoding = Encoding.UTF8;
if((fileData[0] == 0xff && fileData[1] == 0xfe) || fileData[1] == 0) {
encoding = Encoding.Unicode;
fileData = fileData.Skip(2).ToArray();
} else if(fileData[0] == 0xfe && fileData[1] == 0xff) {
encoding = Encoding.BigEndianUnicode;
fileData = fileData.Skip(2).ToArray();
}
UI.PreviewText = encoding.GetString(fileData);
}
} else {
UI.PreviewText = "";
}
} else {
UI.PreviewText = "";
}
} else {
if (CurrentFileSystem == null) {
var volume = VolumeManager.GetVolume(itemValue);
itemLabel = $" | Path: {volume.Identity}";
using (var sparseStream = volume.Open()) {
var fsInfo = FileSystemManager.DetectFileSystems(sparseStream);
if (fsInfo != null && fsInfo.Count > 0) {
var fileSystem = fsInfo[0].Open(sparseStream);
CurrentPath = "";
UI.VolumeLabel = $"Volume: {fileSystem.FriendlyName} {GetHumanSize(fileSystem.Size)}";
} else {
UI.VolumeLabel = $"Volume: Unknown {GetHumanSize(volume.Length)}";
}
}
} else {
if(CurrentPath == "") {
itemLabel = "";
} else {
itemLabel = $" | Path: {CurrentPath}";
}
}
}
UI.ItemLabel = itemLabel.Replace("\\",PathSeparator);
}
static private async Task DownloadFile(string volumePath) {
using (var fileStream = CurrentFileSystem.OpenFile(volumePath, FileMode.Open, FileAccess.Read)) {
using (var outputStream = new FileStream(Path.GetFileName(volumePath), FileMode.OpenOrCreate, FileAccess.ReadWrite)) {
byte[] buffer = new byte[512 * 1024];
long totalRead = 0;
while (fileStream.Position < fileStream.Length) {
int readSize = await fileStream.ReadAsync(buffer, 0, buffer.Length);
await outputStream.WriteAsync(buffer, 0, readSize);
totalRead += readSize;
float progress = (totalRead / (float)fileStream.Length) * 100;
UI.DownloadLabel = $"Downloading ({progress:0.0}%): {volumePath}";
}
}
}
}
private static void Ui_ItemSelected(string itemValue) {
if (CurrentFileSystem == null) {
var volume = VolumeManager.GetVolume(itemValue);
using (var sparseStream = volume.Open()) {
var fsInfo = FileSystemManager.DetectFileSystems(sparseStream);
if (fsInfo != null && fsInfo.Count > 0) {
CurrentFileSystem = fsInfo[0].Open(sparseStream);
CurrentPath = "";
UI.VolumeLabel = $"Volume: {CurrentFileSystem.FriendlyName} {GetHumanSize(CurrentFileSystem.Size)}";
if (CurrentFileSystem is NtfsFileSystem)
{
((NtfsFileSystem)CurrentFileSystem).NtfsOptions.HideHiddenFiles = false;
((NtfsFileSystem)CurrentFileSystem).NtfsOptions.HideSystemFiles = false;
}
UpdateView();
}
}
} else {
if (itemValue == ".." && CurrentPath == "") {
UI.UpdateCurrentPathItems(Volumes.ToList());
CurrentFileSystem = null;
CurrentPath = null;
var volumes = VolumeManager.GetLogicalVolumes();
UI.ItemLabel = $" | Path: {volumes[0].Identity}";
} else {
if (itemValue != "..") {
if (CurrentFileSystem.FriendlyName == "Microsoft NTFS" || CurrentFileSystem.FriendlyName.Contains("FAT")) {
PathSeparator = "\\";
} else {
PathSeparator = "/";
}
if ((CurrentFileSystem.GetAttributes($"{CurrentPath}\\{itemValue}") & FileAttributes.Directory) == FileAttributes.Directory) {
CurrentPath += $"\\{itemValue}";
UpdateView();
} else {
var selectedFile = $"{CurrentPath}\\{itemValue}";
var fileInfo = CurrentFileSystem.GetFileInfo(selectedFile);
if(UI.ShowDownloadDialog(itemValue, GetHumanSize(fileInfo.Length))) {
if(DownloadTask != null) {
DownloadTask = DownloadTask.ContinueWith(t => DownloadFile(selectedFile)).ContinueWith(t => {
DownloadTask = null;
UI.DownloadLabel = "Downloads Complete";
});
} else {
DownloadTask = DownloadFile(selectedFile).ContinueWith(t => {
DownloadTask = null;
UI.DownloadLabel = "Downloads Complete";
});
}
}
}
} else {
UI.ItemLabel = "";
CurrentPath = CurrentPath.Substring(0, CurrentPath.LastIndexOf('\\'));
UpdateView();
}
}
}
}
static string GetHumanSize(long size) {
if (size < 1024) {
return $"{size}B";
} else if (size < 1024L * 1024L) {
return $"{size / 1024.0:0.00}KB";
} else if (size < 1024L * 1024L * 1024L) {
return $"{size / 1024.0 / 1024.0:0.00}MB";
} else if (size < 1024L * 1024L * 1024L * 1024L) {
return $"{size / 1024.0 / 1024.0 / 1024.0:0.00}GB";
} else {
return $"{size / 1024.0 / 1024.0 / 1024.0 / 1024.0:0.00}TB";
}
}
private static void UpdateView() {
UI.UpdateCurrentPathItems(new string[] { ".." }
.Concat(CurrentFileSystem.GetFileSystemEntries(CurrentPath).Select(pi => Path.GetFileName(pi)))
.ToList());
}
}
}