protected override void DoRun() { VolumeManager volMgr = new VolumeManager(); foreach (var path in _inFiles.Values) { volMgr.AddDisk(VirtualDisk.OpenDisk(path, FileAccess.Read, UserName, Password)); } Console.WriteLine("PHYSICAL VOLUMES"); foreach (var physVol in volMgr.GetPhysicalVolumes()) { Console.WriteLine(" Identity: " + physVol.Identity); Console.WriteLine(" Type: " + physVol.VolumeType); Console.WriteLine(" Disk Id: " + physVol.DiskIdentity); Console.WriteLine(" Disk Sig: " + physVol.DiskSignature.ToString("X8")); Console.WriteLine(" Part Id: " + physVol.PartitionIdentity); Console.WriteLine(" Length: " + physVol.Length + " bytes"); Console.WriteLine(" Disk Geometry: " + physVol.PhysicalGeometry); Console.WriteLine(" First Sector: " + physVol.PhysicalStartSector); Console.WriteLine(); } Console.WriteLine("LOGICAL VOLUMES"); foreach (var logVol in volMgr.GetLogicalVolumes()) { Console.WriteLine(" Identity: " + logVol.Identity); Console.WriteLine(" Length: " + logVol.Length + " bytes"); Console.WriteLine(" Disk Geometry: " + logVol.PhysicalGeometry); Console.WriteLine(" First Sector: " + logVol.PhysicalStartSector); Console.WriteLine(); } }
public void Patch() { var length = DetectLength(); var disk = StreamFormatter.CreateDisk(outputHDI, sysDisk, length, patchData.SysFiles); var dstStream = disk.Partitions[0].Open(); var dstFat = new PC98FatFileSystem(dstStream); foreach (var img in _sourceImages) { if (IsFloppy(img)) { using (var source = VirtualDisk.OpenDisk(img, FileAccess.Read)) { using (var fs = new PC98FatFileSystem(source.Content)) { CopyFiles(fs, dstFat); } } } else if (img.ToLower().EndsWith(".hdi")) { using (var srcDisk = Disk.OpenDisk(img, FileAccess.Read)) { using (var srcStream = srcDisk.Partitions[0].Open()) { using (var srcFat = new PC98FatFileSystem(srcStream)) { CopyFiles(srcFat, dstFat); } } } } } }
internal static void ApplyDiff(string BaseVHD, string DiffVHD, string OutVHD = null, bool DifferencingOut = false, Tuple <int, int> Partition = null) { var DiffDisk = VirtualDisk.OpenDisk(DiffVHD, FileAccess.Read); VirtualDisk OutDisk; if (DifferencingOut) { using (var BaseDisk = VirtualDisk.OpenDisk(BaseVHD, FileAccess.Read)) { if (OutVHD == null || OutVHD.Equals(String.Empty)) { throw new ArgumentNullException("OutVHD", "OutVHD may not be null or empty when DifferencingOut is 'true'."); } OutDisk = BaseDisk.CreateDifferencingDisk(OutVHD); } } else { if (OutVHD != null) { File.Copy(BaseVHD, OutVHD); } else { OutVHD = BaseVHD; } OutDisk = VirtualDisk.OpenDisk(OutVHD, FileAccess.ReadWrite); } using (DiffDisk) using (OutDisk) if (Partition != null) { var Base = OutDisk.Partitions[Partition.Item1]; var Diff = DiffDisk.Partitions[Partition.Item2]; ApplyPartDiff(Base, Diff); } else { if (OutDisk.Partitions.Count != DiffDisk.Partitions.Count) { throw new ArgumentException( "Input disks do not have the same number of partitions. To apply the diff for specific partitions on mismatched disks, provide the 'Partition' parameter."); } for (int i = 0; i < OutDisk.Partitions.Count; i++) { if (OutDisk.Partitions[i].BiosType != DiffDisk.Partitions[i].BiosType) { throw new InvalidFileSystemException( String.Format( "Filesystem of partition {0} in '{1}' does not match filesystem type of partition {0} in '{2}'. Unable to apply diff.", i, DiffVHD, OutVHD)); } ApplyPartDiff(OutDisk.Partitions[i], DiffDisk.Partitions[i]); } } }
protected override void DoRun() { using (var disk = VirtualDisk.OpenDisk(_dmg.Value, FileAccess.Read)) { // Find the first (and supposedly, only, HFS partition) foreach (var volume in VolumeManager.GetPhysicalVolumes(disk)) { foreach (var fileSystem in FileSystemManager.DetectFileSystems(volume)) { if (fileSystem.Name == "HFS+") { using (HfsPlusFileSystem hfs = (HfsPlusFileSystem)fileSystem.Open(volume)) { var source = hfs.GetDirectoryInfo(_folder.Value); var target = new DirectoryInfo(Path.Combine(Environment.CurrentDirectory, source.Name)); if (target.Exists) { target.Delete(true); } target.Create(); CopyDirectory(source, target, _recursive.IsPresent); } break; } } } } }
public WindowsStreamBlockDevice(string path) { long diskSize = 30 * 1024 * 1024; //30MB _disk = VirtualDisk.OpenDisk(path, FileAccess.ReadWrite); Stream = _disk.Content; Stream.Position = 0; }
public void Read() { var path = @"d:\temp\mbr.img"; DiscUtils.Containers.SetupHelper.SetupContainers(); DiscUtils.FileSystems.SetupHelper.SetupFileSystems(); var disk = VirtualDisk.OpenDisk(path, FileAccess.ReadWrite); var fs = new FatFileSystem(disk.Partitions[0].Open()); var directories = fs.GetDirectories(""); var files = fs.GetFiles(""); }
private bool GetDiskCapacityImage(out string error) { error = string.Empty; string filename = m_textBoxFile.Text; FileInfo info = new FileInfo(filename); ImageLength = info.Length > 0 ? (ulong)info.Length : 0; if (IsWIM) { try { using (FileStream wimstream = new FileStream(filename, FileMode.Open, FileAccess.Read)) { WimFile wimDisk = new WimFile(wimstream); string manifest = wimDisk.Manifest; Wim_Manifest wimManifest = (Wim_Manifest)Tools.Deserialize(manifest, typeof(Wim_Manifest)); DiskCapacity = wimManifest.Image[wimDisk.BootImage].TotalBytes; //image data size return(true); } } catch (Exception) { error = Messages.IMAGE_SELECTION_PAGE_ERROR_CORRUPT_FILE; return(false); } } try { using (VirtualDisk vd = VirtualDisk.OpenDisk(filename, FileAccess.Read)) { DiskCapacity = (ulong)vd.Capacity; return(true); } } catch (IOException ioe) { error = ioe.Message.Contains("Invalid VMDK descriptor file") ? Messages.IMAGE_SELECTION_PAGE_ERROR_INVALID_VMDK_DESCRIPTOR : Messages.IMAGE_SELECTION_PAGE_ERROR_INVALID_FILE_TYPE; return(false); } catch (Exception) { error = Messages.IMAGE_SELECTION_PAGE_ERROR_CORRUPT_FILE; return(false); } }
protected override void DoRun() { VolumeManager volMgr = new VolumeManager(); foreach (string disk in _diskFiles.Values) { volMgr.AddDisk(VirtualDisk.OpenDisk(disk, _diskType.IsPresent ? _diskType.Value : null, FileAccess.Read, UserName, Password)); } VolumeInfo volInfo = null; if (!string.IsNullOrEmpty(VolumeId)) { volInfo = volMgr.GetVolume(VolumeId); } else if (Partition >= 0) { volInfo = volMgr.GetPhysicalVolumes()[Partition]; } else { volInfo = volMgr.GetLogicalVolumes()[0]; } DiscUtils.FileSystemInfo fsInfo = FileSystemManager.DetectDefaultFileSystems(volInfo)[0]; using (DiscFileSystem fs = fsInfo.Open(volInfo)) { using (Stream source = fs.OpenFile(_inFilePath.Value, FileMode.Open, FileAccess.Read)) { using (FileStream outFile = new FileStream(_outFilePath.Value, FileMode.Create, FileAccess.ReadWrite)) { PumpStreams(source, outFile); } if (_hexDump.IsPresent) { source.Position = 0; HexDump.Generate(source, Console.Out); } } } }
protected override void DoRun() { using (var disk = VirtualDisk.OpenDisk(_dmg.Value, FileAccess.Read)) using (HfsPlusFileSystem hfs = new HfsPlusFileSystem(disk.Partitions[3].Open())) { var source = hfs.GetDirectoryInfo(_folder.Value); var target = new DirectoryInfo(Path.Combine(Environment.CurrentDirectory, source.Name)); if (target.Exists) { target.Delete(true); } target.Create(); CopyDirectory(source, target, _recursive.IsPresent); } }
private void LoadContainer(string filePath) { disk = VirtualDisk.OpenDisk(filePath, FileAccess.ReadWrite); Debug.WriteLine(disk.Capacity + ", " + disk.DiskTypeInfo.Name); volume = VolumeManager.GetPhysicalVolumes(disk.Content)[0]; fsInfo = FileSystemManager.DetectFileSystems(volume)[0]; discFs = fsInfo.Open(volume); tmpFiles = new List <string>(); Debug.WriteLine(fsInfo.Name + " - " + fsInfo.Description); fsHandler = new FileSystemHandler.FileSystemHandler(this); }
public virtual Result <Media> GetReadableMedia(IEnumerable <IPhysicalDrive> physicalDrives, string path, bool allowPhysicalDrive = true) { var physicalDrive = physicalDrives.FirstOrDefault(x => x.Path.Equals(path, StringComparison.OrdinalIgnoreCase)); if (!allowPhysicalDrive && physicalDrive != null) { return(new Result <Media>(new Error("Physical drive is not allowed"))); } if (physicalDrive != null) { return(new Result <Media>(new Media(path, physicalDrive.Model, physicalDrive.Size, Media.MediaType.Raw, true, physicalDrive.Open()))); } if (string.IsNullOrWhiteSpace(path) || !File.Exists(path)) { return(new Result <Media>(new PathNotFoundError($"Path '{path ?? "null"}' not found", nameof(path)))); } if (string.IsNullOrWhiteSpace(path) || !File.Exists(path)) { return(new Result <Media>(new PathNotFoundError($"Path '{path ?? "null"}' not found", nameof(path)))); } var model = Path.GetFileName(path); if (!IsVhd(path)) { return(new Result <Media>(new Media(path, model, new FileInfo(path).Length, Media.MediaType.Raw, false, File.Open(path, FileMode.Open, FileAccess.Read)))); } DiscUtils.Containers.SetupHelper.SetupContainers(); DiscUtils.FileSystems.SetupHelper.SetupFileSystems(); var vhdDisk = VirtualDisk.OpenDisk(path, FileAccess.Read); vhdDisk.Content.Position = 0; return(new Result <Media>(new VhdMedia(path, model, vhdDisk.Capacity, Media.MediaType.Vhd, false, vhdDisk))); }
public static void Generate() { string rootPath = Path.Combine(Bootstrap.Root, @"Root"); string vhdxPath = Path.Combine(Bootstrap.Root, @"Hyper-V\Virtual Hard Disks\Disk.vhdx"); using (VirtualDisk virtualDisk = VirtualDisk.OpenDisk(vhdxPath, FileAccess.ReadWrite)) { // Get system partition PartitionInfo partition = virtualDisk.Partitions.Partitions.FirstOrDefault(); // Open FAT partition using (SparseStream partitionStream = partition.Open()) using (FatFileSystem fatFileSystem = new FatFileSystem(partitionStream)) { // Clean partition string[] fileSystemEntries = fatFileSystem.GetFileSystemEntries(""); } } }
public async Task ConvertVhdToImg(string vhdPath, Stream imgStream) { DiscUtils.Containers.SetupHelper.SetupContainers(); DiscUtils.FileSystems.SetupHelper.SetupFileSystems(); using var vhdDisk = VirtualDisk.OpenDisk(vhdPath, FileAccess.Read); vhdDisk.Content.Position = 0; var buffer = new byte[bufferSize]; int bytesRead; do { bytesRead = await vhdDisk.Content.ReadAsync(buffer, 0, bufferSize); await imgStream.WriteAsync(buffer, 0, bytesRead); OnDataTransferred(bytesRead); } while (bytesRead == buffer.Length); }
protected override void DoRun() { VolumeManager volMgr = new VolumeManager(); foreach (string disk in _diskFiles.Values) { volMgr.AddDisk(VirtualDisk.OpenDisk(disk, FileAccess.Read, UserName, Password)); } Stream partitionStream = null; if (!string.IsNullOrEmpty(VolumeId)) { partitionStream = volMgr.GetVolume(VolumeId).Open(); } else if (Partition >= 0) { partitionStream = volMgr.GetPhysicalVolumes()[Partition].Open(); } else { partitionStream = volMgr.GetLogicalVolumes()[0].Open(); } SparseStream cacheStream = SparseStream.FromStream(partitionStream, Ownership.None); cacheStream = new BlockCacheStream(cacheStream, Ownership.None); NtfsFileSystem fs = new NtfsFileSystem(cacheStream); fs.NtfsOptions.HideHiddenFiles = !_showHidden.IsPresent; fs.NtfsOptions.HideSystemFiles = !_showSystem.IsPresent; fs.NtfsOptions.HideMetafiles = !_showMeta.IsPresent; fs.Dump(Console.Out, ""); }
protected override void DoRun() { if (DiskSize <= 0) { DisplayHelp(); return; } using (VirtualDisk sourceDisk = VirtualDisk.OpenDisk(_sourceFile.Value, FileAccess.Read, UserName, Password)) using (VirtualDisk destDisk = VirtualDisk.CreateDisk(OutputDiskType, OutputDiskVariant, _destFile.Value, DiskParameters, UserName, Password)) { if (destDisk is DiscUtils.Vhd.Disk) { ((DiscUtils.Vhd.Disk)destDisk).AutoCommitFooter = false; } // Copy the MBR from the source disk, and invent a new signature for this new disk destDisk.SetMasterBootRecord(sourceDisk.GetMasterBootRecord()); destDisk.Signature = new Random().Next(); SparseStream sourcePartStream = SparseStream.FromStream(sourceDisk.Partitions[0].Open(), Ownership.None); NtfsFileSystem sourceNtfs = new NtfsFileSystem(sourcePartStream); // Copy the OS boot code into memory, so we can apply it when formatting the new disk byte[] bootCode; using (Stream bootStream = sourceNtfs.OpenFile("$Boot", FileMode.Open, FileAccess.Read)) { bootCode = new byte[bootStream.Length]; int totalRead = 0; while (totalRead < bootCode.Length) { totalRead += bootStream.Read(bootCode, totalRead, bootCode.Length - totalRead); } } // Partition the new disk with a single NTFS partition BiosPartitionTable.Initialize(destDisk, WellKnownPartitionType.WindowsNtfs); VolumeManager volMgr = new VolumeManager(destDisk); string label = _labelSwitch.IsPresent ? _labelSwitch.Value : sourceNtfs.VolumeLabel; using (NtfsFileSystem destNtfs = NtfsFileSystem.Format(volMgr.GetLogicalVolumes()[0], label, bootCode)) { destNtfs.SetSecurity(@"\", sourceNtfs.GetSecurity(@"\")); destNtfs.NtfsOptions.ShortNameCreation = ShortFileNameOption.Disabled; sourceNtfs.NtfsOptions.HideHiddenFiles = false; sourceNtfs.NtfsOptions.HideSystemFiles = false; CopyFiles(sourceNtfs, destNtfs, @"\", true); if (destNtfs.FileExists(@"\boot\BCD")) { // Force all boot entries in the BCD to point to the newly created NTFS partition - does _not_ cope with // complex multi-volume / multi-boot scenarios at all. using (Stream bcdStream = destNtfs.OpenFile(@"\boot\BCD", FileMode.Open, FileAccess.ReadWrite)) { using (RegistryHive hive = new RegistryHive(bcdStream)) { Store store = new Store(hive.Root); foreach (var obj in store.Objects) { foreach (var elem in obj.Elements) { if (elem.Format == DiscUtils.BootConfig.ElementFormat.Device) { elem.Value = DiscUtils.BootConfig.ElementValue.ForDevice(elem.Value.ParentObject, volMgr.GetPhysicalVolumes()[0]); } } } } } } } } }
protected override void DoRun() { VolumeManager volMgr = new VolumeManager(); foreach (string disk in _diskFiles.Values) { volMgr.AddDisk(VirtualDisk.OpenDisk(disk, FileAccess.Read, UserName, Password)); } VolumeInfo volInfo = null; if (!string.IsNullOrEmpty(VolumeId)) { volInfo = volMgr.GetVolume(VolumeId); } else if (Partition >= 0) { volInfo = volMgr.GetPhysicalVolumes()[Partition]; } else { volInfo = volMgr.GetLogicalVolumes()[0]; } using (NtfsFileSystem fs = new NtfsFileSystem(volInfo.Open())) { MasterFileTable mft = fs.GetMasterFileTable(); if (_recoverFile.IsPresent) { MasterFileTableEntry entry = mft[long.Parse(_recoverFile.Value)]; IBuffer content = GetContent(entry); if (content == null) { Console.WriteLine("Sorry, unable to recover content"); Environment.Exit(1); } string outFile = _recoverFile.Value + "__recovered.bin"; if (File.Exists(outFile)) { Console.WriteLine("Sorry, the file already exists: " + outFile); Environment.Exit(1); } using (FileStream outFileStream = new FileStream(outFile, FileMode.CreateNew, FileAccess.Write)) { Pump(content, outFileStream); } Console.WriteLine("Possible file contents saved as: " + outFile); Console.WriteLine(); Console.WriteLine("Caution! It is rare for the file contents of deleted files to be intact - most"); Console.WriteLine("likely the contents recovered are corrupt as the space has been reused."); } else { foreach (var entry in mft.GetEntries(EntryStates.NotInUse)) { // Skip entries with no attributes, they've probably never been used. We're certainly // not going to manage to recover any useful data from them. if (entry.Attributes.Count == 0) { continue; } // Skip directories - any useful files inside will be found separately if ((entry.Flags & MasterFileTableEntryFlags.IsDirectory) != 0) { continue; } long size = GetSize(entry); string path = GetPath(mft, entry); if (!_showMeta.IsPresent && path.StartsWith(@"<root>\$Extend")) { continue; } if (!_showZeroSize.IsPresent && size == 0) { continue; } Console.WriteLine("Index: {0,-4} Size: {1,-8} Path: {2}", entry.Index, Utilities.ApproximateDiskSize(size), path); } } } }
public static void GetDirListing(string VMDKpath, string directory) { if (File.Exists(VMDKpath)) { try { using (VirtualDisk vhdx = VirtualDisk.OpenDisk(VMDKpath, FileAccess.Read)) { if (vhdx.Partitions.Count > 1) { Console.WriteLine("Target has more than one partition"); for (var i = 0; i <= vhdx.Partitions.Count; i++) { NtfsFileSystem vhdbNtfs = new NtfsFileSystem(vhdx.Partitions[i].Open()); if (vhdbNtfs.DirectoryExists("\\\\" + directory)) { string[] filelist = vhdbNtfs.GetFiles(vhdbNtfs.Root.FullName + directory); string[] dirlist = vhdbNtfs.GetDirectories(vhdbNtfs.Root.FullName + directory); foreach (var file in filelist) { Console.WriteLine("[F] {0}", file); } foreach (var dir in dirlist) { Console.WriteLine("[D] {0}", dir); } } else { Console.WriteLine("\r\n[*] Directory does not exist"); } } } else { NtfsFileSystem vhdbNtfs = new NtfsFileSystem(vhdx.Partitions[0].Open()); if (vhdbNtfs.DirectoryExists("\\\\" + directory)) { string[] filelist = vhdbNtfs.GetFiles(vhdbNtfs.Root.FullName + directory); string[] dirlist = vhdbNtfs.GetDirectories(vhdbNtfs.Root.FullName + directory); foreach (var file in filelist) { Console.WriteLine("[F] {0} {1}", file, vhdbNtfs.GetFileLength(file)); } foreach (var dir in dirlist) { Console.WriteLine("[D] {0}", dir); } } else { Console.WriteLine("\r\n[*] Directory does not exist"); } } } } catch (Exception ex) { Console.WriteLine("\r\n [!] Virtual Disk provided is not supported"); Console.WriteLine("\r\n [!] An exception occured: {0}", ex); Environment.Exit(1); } } else { Console.WriteLine("\r\n [!] The provided VMDK image does not exist or can not be accessed"); } }
public static void GetFile(string VMDKpath, string filepath, string destinationfile) { if (File.Exists(VMDKpath) && Directory.Exists(Path.GetDirectoryName(destinationfile))) { try { if (Path.GetFileName(destinationfile) == "") { destinationfile += Path.GetFileName(filepath); } using (VirtualDisk vhdx = VirtualDisk.OpenDisk(VMDKpath, FileAccess.Read)) { if (vhdx.Partitions.Count > 1) { Console.WriteLine("Target has more than one partition"); for (var i = 0; i <= vhdx.Partitions.Count; i++) { try { NtfsFileSystem vhdbNtfs = new NtfsFileSystem(vhdx.Partitions[i].Open()); if (vhdbNtfs.FileExists("\\\\" + filepath)) { long fileLength = vhdbNtfs.GetFileLength("\\\\" + filepath); using (Stream bootStream = vhdbNtfs.OpenFile("\\\\" + filepath, FileMode.Open, FileAccess.Read)) { byte[] file = new byte[bootStream.Length]; int totalRead = 0; while (totalRead < file.Length) { totalRead += bootStream.Read(file, totalRead, file.Length - totalRead); FileStream fileStream = File.Create(destinationfile, (int)bootStream.Length); bootStream.CopyTo(fileStream); fileStream.Write(file, 0, (int)bootStream.Length); } } long destinationLength = new FileInfo(destinationfile).Length; if (fileLength != destinationLength) { Console.WriteLine("[!] Something went wrong. Source file has size {0} and destination file has size {1}", fileLength, destinationLength); } else { Console.WriteLine("\r\n[*] File {0} was successfully copied to {1}", filepath, destinationfile); } } else { Console.WriteLine("\r\n [!] File {0} can not be found", filepath); } } catch (Exception ex) { Console.WriteLine("\r\n [!] An exception occured: {0}", ex); Environment.Exit(1); throw; } } } else { try { NtfsFileSystem vhdbNtfs = new NtfsFileSystem(vhdx.Partitions[0].Open()); if (vhdbNtfs.FileExists("\\\\" + filepath)) { //vhdbNtfs.CopyFile(); long fileLength = vhdbNtfs.GetFileLength("\\\\" + filepath); using (Stream bootStream = vhdbNtfs.OpenFile("\\\\" + filepath, FileMode.Open, FileAccess.Read)) { byte[] file = new byte[bootStream.Length]; int totalRead = 0; while (totalRead < file.Length) { totalRead += bootStream.Read(file, totalRead, file.Length - totalRead); FileStream fileStream = File.Create(destinationfile, (int)bootStream.Length); bootStream.CopyTo(fileStream); fileStream.Write(file, 0, (int)bootStream.Length); } } long destinationLength = new FileInfo(destinationfile).Length; if (fileLength != destinationLength) { Console.WriteLine("[!] Something went wrong. Source file has size {0} and destination file has size {1}", fileLength, destinationLength); } else { Console.WriteLine("\r\n[*] File {0} was successfully copied to {1}", filepath, destinationfile); } } else { Console.WriteLine("\r\n [!] File {0} can not be found", filepath); } } catch (Exception ex) { Console.WriteLine("\r\n [!] An exception occured: {0}", ex); Environment.Exit(1); throw; } } } } catch (Exception ex) { Console.WriteLine("\r\n [!] An exception occured: {0}", ex); Environment.Exit(1); throw; } } else { Console.WriteLine("\r\n [!] The provided VMDK image does not exist / can not be accessed or the destination folder does not exist"); } }
protected override void DoRun() { Console.OutputEncoding = Encoding.UTF8; List <VirtualDisk> disks = new List <VirtualDisk>(); foreach (var path in _inFiles.Values) { VirtualDisk disk = VirtualDisk.OpenDisk(path, _diskType.IsPresent ? _diskType.Value : null, FileAccess.Read, UserName, Password); disks.Add(disk); Console.WriteLine(); Console.WriteLine("DISK: " + path); Console.WriteLine(); Console.WriteLine(" Capacity: {0:X16}", disk.Capacity); Console.WriteLine(" Geometry: {0}", disk.Geometry); Console.WriteLine(" BIOS Geometry: {0}", disk.BiosGeometry); Console.WriteLine(" Signature: {0:X8}", disk.Signature); if (disk.IsPartitioned) { Console.WriteLine(" GUID: {0}", disk.Partitions.DiskGuid); } Console.WriteLine(); if (!_hideExtents.IsPresent) { Console.WriteLine(); Console.WriteLine(" Stored Extents"); Console.WriteLine(); foreach (var extent in disk.Content.Extents) { Console.WriteLine(" {0:X16} - {1:X16}", extent.Start, extent.Start + extent.Length); } Console.WriteLine(); } if (_showBootCode.IsPresent) { Console.WriteLine(); Console.WriteLine(" Master Boot Record (MBR)"); Console.WriteLine(); try { byte[] mbr = new byte[512]; disk.Content.Position = 0; disk.Content.Read(mbr, 0, 512); HexDump.Generate(mbr, Console.Out); } catch (Exception e) { Console.WriteLine(e.ToString()); } Console.WriteLine(); } Console.WriteLine(); Console.WriteLine(" Partitions"); Console.WriteLine(); if (disk.IsPartitioned) { Console.WriteLine(" T Start (bytes) End (bytes) Type"); Console.WriteLine(" == ================ ================ =================="); foreach (var partition in disk.Partitions.Partitions) { Console.WriteLine(" {0:X2} {1:X16} {2:X16} {3}", partition.BiosType, partition.FirstSector * 512, partition.LastSector * 512 + 512, partition.TypeAsString); BiosPartitionInfo bpi = partition as BiosPartitionInfo; if (bpi != null) { Console.WriteLine(" {0,-16} {1}", bpi.Start.ToString(), bpi.End.ToString()); Console.WriteLine(); } } } else { Console.WriteLine(" No partitions"); Console.WriteLine(); } } Console.WriteLine(); Console.WriteLine(); Console.WriteLine("VOLUMES"); Console.WriteLine(); VolumeManager volMgr = new VolumeManager(); foreach (var disk in disks) { volMgr.AddDisk(disk); } try { Console.WriteLine(); Console.WriteLine(" Physical Volumes"); Console.WriteLine(); foreach (var vol in volMgr.GetPhysicalVolumes()) { Console.WriteLine(" " + vol.Identity); Console.WriteLine(" Type: " + vol.VolumeType); Console.WriteLine(" BIOS Type: " + vol.BiosType.ToString("X2") + " [" + BiosPartitionTypes.ToString(vol.BiosType) + "]"); Console.WriteLine(" Size: " + vol.Length); Console.WriteLine(" Disk Id: " + vol.DiskIdentity); Console.WriteLine(" Disk Sig: " + vol.DiskSignature.ToString("X8")); Console.WriteLine(" Partition: " + vol.PartitionIdentity); Console.WriteLine(" Disk Geometry: " + vol.PhysicalGeometry); Console.WriteLine(" BIOS Geometry: " + vol.BiosGeometry); Console.WriteLine(" First Sector: " + vol.PhysicalStartSector); Console.WriteLine(); } } catch (Exception e) { Console.WriteLine(e.ToString()); } try { Console.WriteLine(); Console.WriteLine(" Logical Volumes"); Console.WriteLine(); foreach (var vol in volMgr.GetLogicalVolumes()) { Console.WriteLine(" " + vol.Identity); Console.WriteLine(" BIOS Type: " + vol.BiosType.ToString("X2") + " [" + BiosPartitionTypes.ToString(vol.BiosType) + "]"); Console.WriteLine(" Status: " + vol.Status); Console.WriteLine(" Size: " + vol.Length); Console.WriteLine(" Disk Geometry: " + vol.PhysicalGeometry); Console.WriteLine(" BIOS Geometry: " + vol.BiosGeometry); Console.WriteLine(" First Sector: " + vol.PhysicalStartSector); if (vol.Status == LogicalVolumeStatus.Failed) { Console.WriteLine(" File Systems: <unknown - failed volume>"); Console.WriteLine(); continue; } DiscUtils.FileSystemInfo[] fileSystemInfos = FileSystemManager.DetectDefaultFileSystems(vol); Console.WriteLine(" File Systems: " + string.Join <DiscUtils.FileSystemInfo>(", ", fileSystemInfos)); Console.WriteLine(); if (_showVolContent.IsPresent) { Console.WriteLine(" Binary Contents..."); try { using (Stream s = vol.Open()) { HexDump.Generate(s, Console.Out); } } catch (Exception e) { Console.WriteLine(e.ToString()); } Console.WriteLine(); } if (_showBootCode.IsPresent) { foreach (var fsi in fileSystemInfos) { Console.WriteLine(" Boot Code: {0}", fsi.Name); try { using (DiscFileSystem fs = fsi.Open(vol, FileSystemParameters)) { byte[] bootCode = fs.ReadBootCode(); if (bootCode != null) { HexDump.Generate(bootCode, Console.Out); } else { Console.WriteLine(" <file system reports no boot code>"); } } } catch (Exception e) { Console.WriteLine(" Unable to show boot code: " + e.Message); } Console.WriteLine(); } } if (_showFiles.IsPresent) { foreach (var fsi in fileSystemInfos) { using (DiscFileSystem fs = fsi.Open(vol, FileSystemParameters)) { Console.WriteLine(" {0} Volume Label: {1}", fsi.Name, fs.VolumeLabel); Console.WriteLine(" Files ({0})...", fsi.Name); ShowDir(fs.Root, 6); } Console.WriteLine(); } } } } catch (Exception e) { Console.WriteLine(e.ToString()); } try { bool foundDynDisk = false; DynamicDiskManager dynDiskManager = new DynamicDiskManager(); foreach (var disk in disks) { if (DynamicDiskManager.IsDynamicDisk(disk)) { dynDiskManager.Add(disk); foundDynDisk = true; } } if (foundDynDisk) { Console.WriteLine(); Console.WriteLine(" Logical Disk Manager Info"); Console.WriteLine(); dynDiskManager.Dump(Console.Out, " "); } } catch (Exception e) { Console.WriteLine(e.ToString()); } if (_showContent.IsPresent) { foreach (var path in _inFiles.Values) { VirtualDisk disk = VirtualDisk.OpenDisk(path, FileAccess.Read, UserName, Password); Console.WriteLine(); Console.WriteLine("DISK CONTENTS ({0})", path); Console.WriteLine(); HexDump.Generate(disk.Content, Console.Out); Console.WriteLine(); } } }
private static string RedirectISO(string filename) { string _result = null; try { if (!string.IsNullOrEmpty(filename) && File.Exists(filename)) { List <string> _candidates = new List <string>(); // open the ISO file VolumeManager volMgr = new VolumeManager(); volMgr.AddDisk(VirtualDisk.OpenDisk(filename, FileAccess.Read)); VolumeInfo volInfo = null; volInfo = volMgr.GetLogicalVolumes()[0]; DiscUtils.FileSystemInfo fsInfo = FileSystemManager.DetectDefaultFileSystems(volInfo)[0]; using (DiscFileSystem _dfs = fsInfo.Open(volInfo)) { foreach (string _fname in _dfs.GetFiles("", "*.*", SearchOption.AllDirectories)) { string _fileExt = System.IO.Path.GetExtension(_fname).ToLowerInvariant(); if (_fileExt == ".ifo" || _fileExt == ".mpls") { _candidates.Add(_fname); } } double _biggestDuration = 0d; string _tmpBRResult = ""; // select from the candidates the one that has the longest duration (if mpls skip files bigger than 10K) foreach (string _cpath in _candidates) { string _cext = Path.GetExtension(_cpath).ToLowerInvariant(); string _tmp = Helpers.GetUniqueFilename(_cext); using (FileStream _fs = new FileStream(_tmp, FileMode.Create, FileAccess.Write)) { using (Stream source = _dfs.OpenFile(_cpath, FileMode.Open, FileAccess.Read)) { source.CopyTo(_fs); } } // if it is a DVD iso if (_cext == ".ifo") { if (string.Compare(Path.GetFileNameWithoutExtension(_cpath), "video_ts", true) == 0) { File.Delete(_tmp); // skip the menu continue; } // use first ifo that is not the menu FileManager.AddToGarbageFiles(_tmp); _result = _tmp; break; } // if it is a BLURAY iso (choose biggest mpls file) if (_cext == ".mpls") { long _length = new FileInfo(_tmp).Length; if (Path.GetExtension(_cpath).ToLowerInvariant() == ".mpls" && _length > 10 * 1024) { File.Delete(_tmp); continue; // take next one, this is too big and mediainfo will hang } if (GetDurationMilliseconds(_tmp) > _biggestDuration) { // important.. add it to the garbage files //FileManager.AddToGarbageFiles(_tmp); //_result = _tmp; if (!string.IsNullOrEmpty(_tmpBRResult)) { File.Delete(_tmpBRResult); // remove previous winner and remember the current one } _tmpBRResult = _tmp; } else { File.Delete(_tmp); } } } if (string.IsNullOrEmpty(_result) && !string.IsNullOrEmpty(_tmpBRResult)) { FileManager.AddToGarbageFiles(_tmpBRResult); _result = _tmpBRResult; } } } } catch (Exception ex) { Loggy.Logger.DebugException("ISO Processing", ex); } return(_result); }
private void button2_Click(object sender, EventArgs e) { DiscUtils.VolumeManager volMgr = new VolumeManager(); volMgr.AddDisk(VirtualDisk.OpenDisk(textBox1.Text, FileAccess.Read)); Stream partitionStream = null; if (!string.IsNullOrEmpty(VolumeId)) { partitionStream = volMgr.GetVolume(VolumeId).Open(); } else if (Partition >= 0) { partitionStream = volMgr.GetPhysicalVolumes()[Partition].Open(); } else { partitionStream = volMgr.GetLogicalVolumes()[0].Open(); } SparseStream cacheStream = SparseStream.FromStream(partitionStream, Ownership.None); cacheStream = new BlockCacheStream(cacheStream, Ownership.None); fs = new NtfsFileSystem(cacheStream); fs.NtfsOptions.HideHiddenFiles = false; fs.NtfsOptions.HideSystemFiles = false; fs.NtfsOptions.HideMetafiles = false; ClusterMap clusterMap = null; try { clusterMap = fs.BuildClusterMap(); } catch (IOException ex) { // DebugConsole.LogException(ex, "Trying to build a clustermap of " + textBox1.Text); MessageBox.Show(ex.Message, "Exception"); // return; } // string[] files = null; // string[] sysfiles = fs.GetFileSystemEntries(@"\"); // string[] files = fs.GetFiles(@"\", "*.*", SearchOption.AllDirectories); // fs.Dump(Console.Out, ""); //QueuedBackgroundWorker.QueueWorkItem(QueuedBackgroundWorker.m_Queue, null, // (args) => { return fs.GetFiles(@"\", "*.*", SearchOption.AllDirectories); }, // (args) => { if (args.Result != null && args.Result is string[]) ProcessFiles((string[])args.Result); } //); BitArray ba = new BitArray((int)fs.TotalClusters); for (int i = 0; i < fs.TotalClusters; i++) { if (clusterMap.ClusterToPaths(i).Length > 0) { ba.Set(i, true); } } ClusterForm cf = new ClusterForm(); cf.Icon = Icon; cf.Text = Text + " - Cluster Map"; //cf.clusterBitmaps1.GradientStart = Color.WhiteSmoke; //cf.clusterBitmaps1.GradientEnd = Color.Black; //cf.clusterBitmaps1.GradientSteps = 8; cf.clusterBitmaps1.Clusters = ba; cf.Show(); }
/// <summary> /// /// </summary> /// <param name="OldVHD"></param> /// <param name="NewVHD"></param> /// <param name="Output">Filename to the output file. Method will fail if this already exists unless Force is passed as 'true'.</param> /// <param name="OutputType">A <see cref="VMProvisioningAgent.DiffVHD.DiskType"/> which specifies the output file format.</param> /// <param name="Force">If true, will overwrite the Output file if it already exists. Defaults to 'false'.</param> /// <param name="Partition">An int tuple which declares a specific pair of partitions to compare. The first value in the tuple will be the 0-indexed partition number from OldVHD to compare against. The second value of the tuple will be the 0-indexed parition from NewVHD to compare with.</param> /// <param name="Style"></param> /// <returns></returns> internal static void CreateDiff(string OldVHD, string NewVHD, string Output, DiskType OutputType = DiskType.VHD, bool Force = false, Tuple <int, int> Partition = null, ComparisonStyle Style = ComparisonStyle.DateTimeOnly) { if (File.Exists(Output) && !Force) { throw new ArgumentException("Output file already exists.", "Output"); } if (!File.Exists(OldVHD)) { throw new ArgumentException("Input file does not exist.", "OldVHD"); } if (!File.Exists(NewVHD)) { throw new ArgumentException("Input file does not exist.", "NewVHD"); } // byte[] CopyBuffer = new byte[1024*1024]; VirtualDisk Old, New, Out; Old = VirtualDisk.OpenDisk(OldVHD, FileAccess.Read); New = VirtualDisk.OpenDisk(NewVHD, FileAccess.Read); using (Old) using (New) using (var OutFS = new FileStream(Output, Force ? FileMode.Create : FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None)) { // Check type of filesystems being compared if (!Old.IsPartitioned) { throw new ArgumentException("Input disk is not partitioned.", "OldVHD"); } if (!New.IsPartitioned) { throw new ArgumentException("Input disk is not partitioned.", "NewVHD"); } long CapacityBuffer = 64 * Math.Max(Old.Geometry.BytesPerSector, New.Geometry.BytesPerSector); // starting with 64 sectors as a buffer for partition information in the output file long[] OutputCapacities = new long[Partition != null ? 1 : Old.Partitions.Count]; if (Partition != null) { var PartA = Old.Partitions[Partition.Item1]; var PartB = New.Partitions[Partition.Item2]; if (PartA.BiosType != PartB.BiosType) { throw new InvalidFileSystemException( String.Format( "Filesystem of partition {0} in '{1}' does not match filesystem type of partition {2} in '{3}'.", Partition.Item2, NewVHD, Partition.Item1, OldVHD)); } OutputCapacities[0] += Math.Max(PartA.SectorCount * Old.Geometry.BytesPerSector, PartB.SectorCount * New.Geometry.BytesPerSector); } else { if (Old.Partitions.Count != New.Partitions.Count) { throw new ArgumentException( "Input disks do not have the same number of partitions. To compare specific partitions on mismatched disks, provide the 'Partition' parameter."); } for (int i = 0; i < Old.Partitions.Count; i++) { if (Old.Partitions[i].BiosType != New.Partitions[i].BiosType) { throw new InvalidFileSystemException(String.Format("Filesystem of partition {0} in '{1}' does not match filesystem type of partition {0} in '{2}'.", i, NewVHD, OldVHD)); } else { OutputCapacities[i] = Math.Max(Old.Partitions[i].SectorCount * Old.Geometry.BytesPerSector, New.Partitions[i].SectorCount * New.Geometry.BytesPerSector); } } } long OutputCapacity = CapacityBuffer + OutputCapacities.Sum(); switch (OutputType) { case DiskType.VHD: Out = DiscUtils.Vhd.Disk.InitializeDynamic(OutFS, Ownership.None, OutputCapacity, Math.Max(New.BlockSize, 512 * 1024)); // the Max() is present only because there's currently a bug with blocksize < (8*sectorSize) in DiscUtils break; case DiskType.VHDX: Out = DiscUtils.Vhdx.Disk.InitializeDynamic(OutFS, Ownership.None, OutputCapacity, Math.Max(New.BlockSize, 512 * 1024)); break; default: throw new NotSupportedException("The selected disk type is not supported at this time.", new ArgumentException( "Selected DiskType not currently supported.", "OutputType")); } using (Out) { // set up the output location if (Out is DiscUtils.Vhd.Disk) { ((DiscUtils.Vhd.Disk)Out).AutoCommitFooter = false; } var OutParts = BiosPartitionTable.Initialize(Out); if (Partition != null) { OutParts.Create(GetPartitionType(Old.Partitions[Partition.Item1]), false); // there is no need (ever) for a VHD diff to have bootable partitions var OutFileSystem = Out.FormatPartition(0); DiffPart(DetectFileSystem(Old.Partitions[Partition.Item1]), DetectFileSystem(New.Partitions[Partition.Item2]), OutFileSystem, // As we made the partition spen the entire drive, it should be the only partition Style); } else // Partition == null { for (int i = 0; i < Old.Partitions.Count; i++) { var partIndex = OutParts.Create(Math.Max(Old.Partitions[i].SectorCount * Old.Parameters.BiosGeometry.BytesPerSector, New.Partitions[i].SectorCount * New.Parameters.BiosGeometry.BytesPerSector), GetPartitionType(Old.Partitions[i]), false); var OutFileSystem = Out.FormatPartition(partIndex); DiffPart(DetectFileSystem(Old.Partitions[i]), DetectFileSystem(New.Partitions[i]), OutFileSystem, Style); } } } // using (Out) }// using (Old, New, and OutFS) }
protected override PSDriveInfo NewDrive(PSDriveInfo drive) { NewDriveParameters dynParams = DynamicParameters as NewDriveParameters; if (drive == null) { WriteError(new ErrorRecord( new ArgumentNullException(nameof(drive)), "NullDrive", ErrorCategory.InvalidArgument, null)); return(null); } if (string.IsNullOrEmpty(drive.Root)) { WriteError(new ErrorRecord( new ArgumentException("drive"), "NoRoot", ErrorCategory.InvalidArgument, drive)); return(null); } string[] mountPaths = Utilities.NormalizePath(drive.Root).Split('!'); if (mountPaths.Length < 1 || mountPaths.Length > 2) { WriteError(new ErrorRecord( new ArgumentException("drive"), "InvalidRoot", ErrorCategory.InvalidArgument, drive)); //return null; } string diskPath = mountPaths[0]; string relPath = mountPaths.Length > 1 ? mountPaths[1] : ""; string user = null; string password = null; if (drive.Credential != null && drive.Credential.UserName != null) { NetworkCredential netCred = drive.Credential.GetNetworkCredential(); user = netCred.UserName; password = netCred.Password; } try { string fullPath = Utilities.DenormalizePath(diskPath); var resolvedPath = SessionState.Path.GetResolvedPSPathFromPSPath(fullPath)[0]; if (resolvedPath.Provider.Name == "FileSystem") { fullPath = resolvedPath.ProviderPath; } FileAccess access = dynParams.ReadWrite.IsPresent ? FileAccess.ReadWrite : FileAccess.Read; VirtualDisk disk = VirtualDisk.OpenDisk(fullPath, dynParams.DiskType, access, user, password); return(new VirtualDiskPSDriveInfo(drive, MakePath(Utilities.NormalizePath(fullPath) + "!", relPath), disk)); } catch (IOException ioe) { WriteError(new ErrorRecord( ioe, "DiskAccess", ErrorCategory.ResourceUnavailable, drive.Root)); return(null); } }
public static void GetFile(string DiskPath, string FilePath, string DestinationFile) { if (File.Exists(DiskPath) && Directory.Exists(Path.GetDirectoryName(DestinationFile))) { if (Path.GetFileName(DestinationFile) == "") { DestinationFile += Path.GetFileName(FilePath); } VolumeManager volMgr = new VolumeManager(); VirtualDisk disk = VirtualDisk.OpenDisk(DiskPath, FileAccess.Read); volMgr.AddDisk(disk); VolumeInfo volInfo = null; if (disk.Partitions.Count > 1) { Console.WriteLine("\r\n[*] Target has more than one partition\r\n"); foreach (var physVol in volMgr.GetPhysicalVolumes()) { Console.WriteLine(" Identity: " + physVol.Identity); Console.WriteLine(" Type: " + physVol.VolumeType); Console.WriteLine(" Disk Id: " + physVol.DiskIdentity); Console.WriteLine(" Disk Sig: " + physVol.DiskSignature.ToString("X8")); Console.WriteLine(" Part Id: " + physVol.PartitionIdentity); Console.WriteLine(" Length: " + physVol.Length + " bytes"); Console.WriteLine(" Disk Geometry: " + physVol.PhysicalGeometry); Console.WriteLine(" First Sector: " + physVol.PhysicalStartSector); Console.WriteLine(); if (!string.IsNullOrEmpty(physVol.Identity)) { volInfo = volMgr.GetVolume(physVol.Identity); } DiscUtils.FileSystemInfo fsInfo = FileSystemManager.DetectFileSystems(volInfo)[0]; using (NtfsFileSystem diskntfs = new NtfsFileSystem(physVol.Partition.Open())) { if (diskntfs.FileExists("\\\\" + FilePath)) { long fileLength = diskntfs.GetFileLength("\\\\" + FilePath); using (Stream bootStream = diskntfs.OpenFile("\\\\" + FilePath, FileMode.Open, FileAccess.Read)) { byte[] file = new byte[bootStream.Length]; int totalRead = 0; while (totalRead < file.Length) { totalRead += bootStream.Read(file, totalRead, file.Length - totalRead); FileStream fileStream = File.Create(DestinationFile, (int)bootStream.Length); bootStream.CopyTo(fileStream); fileStream.Write(file, 0, (int)bootStream.Length); } long destinationLength = new FileInfo(DestinationFile).Length; if (fileLength != destinationLength) { Console.WriteLine( "[!] Something went wrong. Source file has size {0} and destination file has size {1}", fileLength, destinationLength); } else { Console.WriteLine("\r\n[*] File {0} was successfully copied to {1}", FilePath, DestinationFile); } } } else { Console.WriteLine("\r\n [!] File {0} can not be found", FilePath); } } } } else { foreach (var physVol in volMgr.GetPhysicalVolumes()) { Console.WriteLine(" Identity: " + physVol.Identity); Console.WriteLine(" Type: " + physVol.VolumeType); Console.WriteLine(" Disk Id: " + physVol.DiskIdentity); Console.WriteLine(" Disk Sig: " + physVol.DiskSignature.ToString("X8")); Console.WriteLine(" Part Id: " + physVol.PartitionIdentity); Console.WriteLine(" Length: " + physVol.Length + " bytes"); Console.WriteLine(" Disk Geometry: " + physVol.PhysicalGeometry); Console.WriteLine(" First Sector: " + physVol.PhysicalStartSector); Console.WriteLine(); NtfsFileSystem diskntfs = new NtfsFileSystem(disk.Partitions[0].Open()); if (diskntfs.FileExists("\\\\" + FilePath)) { long fileLength = diskntfs.GetFileLength("\\\\" + FilePath); using (Stream bootStream = diskntfs.OpenFile("\\\\" + FilePath, FileMode.Open, FileAccess.Read)) { byte[] file = new byte[bootStream.Length]; int totalRead = 0; while (totalRead < file.Length) { totalRead += bootStream.Read(file, totalRead, file.Length - totalRead); FileStream fileStream = File.Create(DestinationFile, (int)bootStream.Length); bootStream.CopyTo(fileStream); fileStream.Write(file, 0, (int)bootStream.Length); } } long destinationLength = new FileInfo(DestinationFile).Length; if (fileLength != destinationLength) { Console.WriteLine( "[!] Something went wrong. Source file has size {0} and destination file has size {1}", fileLength, destinationLength); } else { Console.WriteLine("\r\n[*] File {0} was successfully copied to {1}", FilePath, DestinationFile); } } else { Console.WriteLine("\r\n [!] File {0} can not be found", FilePath); } } } } else { Console.WriteLine( "\r\n [!] The provided VMDK image does not exist / can not be accessed or the destination folder does not exist"); } }
public static void GetDirListing(string DiskPath, string directory) { if (File.Exists(DiskPath)) { try { VolumeManager volMgr = new VolumeManager(); VirtualDisk vhdx = VirtualDisk.OpenDisk(DiskPath, FileAccess.Read); volMgr.AddDisk(vhdx); VolumeInfo volInfo = null; if (vhdx.Partitions.Count > 1) { Console.WriteLine("\r\n[*] Target has more than one partition\r\n"); foreach (var physVol in volMgr.GetPhysicalVolumes()) { Console.WriteLine(" Identity: " + physVol.Identity); Console.WriteLine(" Type: " + physVol.VolumeType); Console.WriteLine(" Disk Id: " + physVol.DiskIdentity); Console.WriteLine(" Disk Sig: " + physVol.DiskSignature.ToString("X8")); Console.WriteLine(" Part Id: " + physVol.PartitionIdentity); Console.WriteLine(" Length: " + physVol.Length + " bytes"); Console.WriteLine(" Disk Geometry: " + physVol.PhysicalGeometry); Console.WriteLine(" First Sector: " + physVol.PhysicalStartSector); Console.WriteLine(); if (!string.IsNullOrEmpty(physVol.Identity)) { volInfo = volMgr.GetVolume(physVol.Identity); } using (NtfsFileSystem vhdbNtfs = new NtfsFileSystem(physVol.Partition.Open())) { if (vhdbNtfs.DirectoryExists("\\\\" + directory)) { string[] filelist = vhdbNtfs.GetFiles(vhdbNtfs.Root.FullName + directory); string[] dirlist = vhdbNtfs.GetDirectories(vhdbNtfs.Root.FullName + directory); foreach (var file in filelist) { Console.WriteLine("[F] {0} {1}", file, vhdbNtfs.GetFileLength(file)); } foreach (var dir in dirlist) { Console.WriteLine("[D] {0}", dir); } } else { Console.WriteLine("\r\n[*] Directory does not exist in partition {0}\r\n", physVol.Identity); } } } } else //No partitions { Console.WriteLine("\r\n[*] Found only one partition\r\n"); Console.WriteLine("LOGICAL VOLUMES"); foreach (var logVol in volMgr.GetLogicalVolumes()) { Console.WriteLine(" Identity: " + logVol.Identity); Console.WriteLine(" Length: " + logVol.Length + " bytes"); Console.WriteLine(" Disk Geometry: " + logVol.PhysicalGeometry); Console.WriteLine(" First Sector: " + logVol.PhysicalStartSector); Console.WriteLine(); } using (NtfsFileSystem vhdbNtfs = new NtfsFileSystem(vhdx.Partitions[0].Open())) { if (vhdbNtfs.DirectoryExists("\\\\" + directory)) { string[] filelist = vhdbNtfs.GetFiles(vhdbNtfs.Root.FullName + directory); string[] dirlist = vhdbNtfs.GetDirectories(vhdbNtfs.Root.FullName + directory); foreach (var file in filelist) { Console.WriteLine("[F] {0} {1}", file, vhdbNtfs.GetFileLength(file)); } foreach (var dir in dirlist) { Console.WriteLine("[D] {0}", dir); } } else { Console.WriteLine("\r\n[*] Directory does not exist"); } } } } catch (Exception ex) { Console.WriteLine("Exception {0}", ex); } } }
public BitArray GetClusterUsage() { if (vhd.masterBootRecord.partition[Partition].PartitionType != 7) { return(null); } try { DiscUtils.VolumeManager volMgr = new VolumeManager(); using (VirtualDisk virtualDisk = VirtualDisk.OpenDisk(vhd.footer.FileName, FileAccess.Read)) { volMgr.AddDisk(virtualDisk); using (Stream partitionStream = volMgr.GetPhysicalVolumes()[Partition].Open()) { //if (!string.IsNullOrEmpty(VolumeId)) //{ // partitionStream = volMgr.GetVolume(VolumeId).Open(); //} //else if (Partition >= 0) //{ // partitionStream = volMgr.GetPhysicalVolumes()[Partition].Open(); //} //else //{ // partitionStream = volMgr.GetLogicalVolumes()[0].Open(); //} SparseStream cacheStream = SparseStream.FromStream(partitionStream, Ownership.None); cacheStream = new BlockCacheStream(cacheStream, Ownership.None); try { fs = new NtfsFileSystem(cacheStream); } catch { cacheStream.Dispose(); return(null); } fs.NtfsOptions.HideHiddenFiles = false; fs.NtfsOptions.HideSystemFiles = false; fs.NtfsOptions.HideMetafiles = false; BitArray ba = fs.BuildClusterBitArray(); fs.Dispose(); cacheStream.Dispose(); partitionStream.Dispose(); ClusterBitArray = ba; } } } catch (VhdReadException ex) { this.vhd.vhdReadException = ex; return(null); } return(ClusterBitArray); /* * ClusterMap clusterMap = null; * try * { * clusterMap = fs.BuildClusterMap(); * } * catch (IOException ex) * { * // TODO: Need to some error notfication * // MessageBox.Show(ex.Message, "Exception"); * return null; * } * * * BitArray ba = new BitArray((int)fs.TotalClusters); */ //UsedClusters = 0; //FreeClusters = 0; //TotalClusters = fs.TotalClusters; //for (int i = 0; i < TotalClusters; i++) //{ // if (clusterMap.ClusterToPaths(i).Length > 0) // { // UsedClusters++; // ba.Set(i, true); // } // else // { // FreeClusters++; // } //} /* * ClusterForm cf = new ClusterForm(); * cf.Icon = Icon; * cf.Text = Text + " - Cluster Map"; * cf.clusterBitmaps1.Clusters = ba; * cf.Show(); */ //cf.clusterBitmaps1.GradientStart = Color.WhiteSmoke; //cf.clusterBitmaps1.GradientEnd = Color.Black; //cf.clusterBitmaps1.GradientSteps = 8; }
protected override void DoRun() { using (VirtualDisk inDisk = VirtualDisk.OpenDisk(_inFile.Value, FileAccess.Read, UserName, Password)) { VirtualDiskParameters diskParams = inDisk.Parameters; diskParams.AdapterType = AdapterType; VirtualDiskTypeInfo diskTypeInfo = VirtualDisk.GetDiskType(OutputDiskType, OutputDiskVariant); if (diskTypeInfo.DeterministicGeometry) { diskParams.Geometry = diskTypeInfo.CalcGeometry(diskParams.Capacity); } if (_translation.IsPresent && _translation.EnumValue != GeometryTranslation.None) { diskParams.BiosGeometry = diskParams.Geometry.TranslateToBios(diskParams.Capacity, _translation.EnumValue); } else if (!inDisk.DiskTypeInfo.PreservesBiosGeometry) { // In case the BIOS geometry was just a default, it's better to override based on the physical geometry // of the new disk. diskParams.BiosGeometry = Geometry.MakeBiosSafe(diskParams.Geometry, diskParams.Capacity); } using (VirtualDisk outDisk = VirtualDisk.CreateDisk(OutputDiskType, OutputDiskVariant, _outFile.Value, diskParams, UserName, Password)) { if (outDisk.Capacity < inDisk.Capacity) { Console.WriteLine("ERROR: The output disk is smaller than the input disk, conversion aborted"); } SparseStream contentStream = inDisk.Content; if (_translation.IsPresent && _translation.EnumValue != GeometryTranslation.None) { SnapshotStream ssStream = new SnapshotStream(contentStream, Ownership.None); ssStream.Snapshot(); UpdateBiosGeometry(ssStream, inDisk.BiosGeometry, diskParams.BiosGeometry); contentStream = ssStream; } StreamPump pump = new StreamPump() { InputStream = contentStream, OutputStream = outDisk.Content, SparseCopy = !_wipe.IsPresent }; if (!Quiet) { long totalBytes = contentStream.Length; if (!_wipe.IsPresent) { totalBytes = 0; foreach (var se in contentStream.Extents) { totalBytes += se.Length; } } DateTime now = DateTime.Now; pump.ProgressEvent += (o, e) => { ShowProgress("Progress", totalBytes, now, o, e); }; } pump.Run(); } } }
private VirtualDisk OpenDisk() { return(VirtualDisk.OpenDisk(_fileSystem, _path, _access)); }
private void CreateDiffDisk() { string child; PSObject parentObj = ResolveNewDiskPath(out child); PSObject baseDiskObj = SessionState.InvokeProvider.Item.Get(new string[] { BaseDisk }, false, true)[0]; VirtualDisk baseDisk = null; try { if (baseDiskObj.BaseObject is FileInfo) { baseDisk = VirtualDisk.OpenDisk(((FileInfo)baseDiskObj.BaseObject).FullName, FileAccess.Read); } else if (baseDiskObj.BaseObject is DiscFileInfo) { DiscFileInfo dfi = (DiscFileInfo)baseDiskObj.BaseObject; baseDisk = VirtualDisk.OpenDisk(dfi.FileSystem, dfi.FullName, FileAccess.Read); } else { WriteError(new ErrorRecord( new FileNotFoundException("The file specified by the BaseDisk parameter doesn't exist"), "BadBaseDiskLocation", ErrorCategory.InvalidArgument, null)); return; } VirtualDisk newDisk = null; if (parentObj.BaseObject is DirectoryInfo) { string path = Path.Combine(((DirectoryInfo)parentObj.BaseObject).FullName, child); using (baseDisk.CreateDifferencingDisk(path)) { } newDisk = new OnDemandVirtualDisk(path, FileAccess.ReadWrite); } else if (parentObj.BaseObject is DiscDirectoryInfo) { DiscDirectoryInfo ddi = (DiscDirectoryInfo)parentObj.BaseObject; string path = Path.Combine(ddi.FullName, child); using (baseDisk.CreateDifferencingDisk(ddi.FileSystem, path)) { } newDisk = new OnDemandVirtualDisk(ddi.FileSystem, path, FileAccess.ReadWrite); } else { WriteError(new ErrorRecord( new DirectoryNotFoundException("Cannot create a virtual disk in that location"), "BadDiskLocation", ErrorCategory.InvalidArgument, null)); return; } WriteObject(newDisk, false); } finally { if (baseDisk != null) { baseDisk.Dispose(); } } }
private static void GenerateFFU(string ImageFile, string FFUFile, string PlatformId, UInt32 chunkSize, string AntiTheftVersion, string Osversion, string[] excluded, UInt32 BlankSectorBufferSize) { Logging.Log("Input image: " + ImageFile); Logging.Log("Destination image: " + FFUFile); Logging.Log("Platform ID: " + PlatformId); Logging.Log(""); Stream stream; VirtualDisk destDisk = null; if (ImageFile.ToLower().Contains(@"\\.\physicaldrive")) { stream = new DeviceStream(ImageFile, FileAccess.Read); } else if (File.Exists(ImageFile) && Path.GetExtension(ImageFile).ToLowerInvariant() == ".vhd") { DiscUtils.Setup.SetupHelper.RegisterAssembly(typeof(DiscUtils.Vhd.Disk).Assembly); DiscUtils.Setup.SetupHelper.RegisterAssembly(typeof(DiscUtils.Vhdx.Disk).Assembly); destDisk = VirtualDisk.OpenDisk(ImageFile, FileAccess.Read); stream = destDisk.Content; } else if (File.Exists(ImageFile) && Path.GetExtension(ImageFile).ToLowerInvariant() == ".vhdx") { DiscUtils.Setup.SetupHelper.RegisterAssembly(typeof(DiscUtils.Vhd.Disk).Assembly); DiscUtils.Setup.SetupHelper.RegisterAssembly(typeof(DiscUtils.Vhdx.Disk).Assembly); destDisk = VirtualDisk.OpenDisk(ImageFile, FileAccess.Read); stream = destDisk.Content; } else if (File.Exists(ImageFile)) { stream = new FileStream(ImageFile, FileMode.Open); } else { Logging.Log("Unknown input specified"); return; } (FlashPart[] flashParts, ulong PlatEnd, List <GPT.Partition> partitions) = ImageSplitter.GetImageSlices(stream, chunkSize, excluded); IOrderedEnumerable <FlashingPayload> payloads = FlashingPayloadGenerator.GetOptimizedPayloads(flashParts, chunkSize, BlankSectorBufferSize).OrderBy(x => x.TargetLocations.First()); Logging.Log(""); Logging.Log("Building image headers..."); string header1 = Path.GetTempFileName(); FileStream Headerstream1 = new FileStream(header1, FileMode.OpenOrCreate); // ============================== // Header 1 start ImageHeader image = new ImageHeader(); FullFlash ffimage = new FullFlash(); Store simage = new Store(); // Todo make this read the image itself ffimage.OSVersion = Osversion; ffimage.DevicePlatformId0 = PlatformId; ffimage.AntiTheftVersion = AntiTheftVersion; simage.SectorSize = 512; simage.MinSectorCount = (UInt32)(stream.Length / 512); Logging.Log("Generating image manifest..."); string manifest = ManifestIni.BuildUpManifest(ffimage, simage, partitions); byte[] TextBytes = System.Text.Encoding.ASCII.GetBytes(manifest); image.ManifestLength = (UInt32)TextBytes.Length; byte[] ImageHeaderBuffer = new byte[0x18]; ByteOperations.WriteUInt32(ImageHeaderBuffer, 0, image.Size); ByteOperations.WriteAsciiString(ImageHeaderBuffer, 0x04, image.Signature); ByteOperations.WriteUInt32(ImageHeaderBuffer, 0x10, image.ManifestLength); ByteOperations.WriteUInt32(ImageHeaderBuffer, 0x14, image.ChunkSize); Headerstream1.Write(ImageHeaderBuffer, 0, 0x18); Headerstream1.Write(TextBytes, 0, TextBytes.Length); RoundUpToChunks(Headerstream1, chunkSize); // Header 1 stop + round // ============================== string header2 = Path.GetTempFileName(); FileStream Headerstream2 = new FileStream(header2, FileMode.OpenOrCreate); // ============================== // Header 2 start StoreHeader store = new StoreHeader(); store.WriteDescriptorCount = (UInt32)payloads.Count(); store.FinalTableIndex = (UInt32)payloads.Count() - store.FinalTableCount; store.PlatformId = PlatformId; byte[] WriteDescriptorBuffer = GetResultingBuffer(payloads); store.WriteDescriptorLength = (UInt32)WriteDescriptorBuffer.Length; foreach (FlashingPayload payload in payloads) { if (payload.TargetLocations.First() > PlatEnd) { break; } store.FlashOnlyTableIndex += 1; } Headerstream2.Write(store.GetResultingBuffer(), 0, 0xF8); Headerstream2.Write(WriteDescriptorBuffer, 0, (Int32)store.WriteDescriptorLength); RoundUpToChunks(Headerstream2, chunkSize); // Header 2 stop + round // ============================== SecurityHeader security = new SecurityHeader(); Headerstream1.Seek(0, SeekOrigin.Begin); Headerstream2.Seek(0, SeekOrigin.Begin); security.HashTableSize = 0x20 * (UInt32)((Headerstream1.Length + Headerstream2.Length) / chunkSize); foreach (FlashingPayload payload in payloads) { security.HashTableSize += payload.GetSecurityHeaderSize(); } byte[] HashTable = new byte[security.HashTableSize]; BinaryWriter bw = new BinaryWriter(new MemoryStream(HashTable)); SHA256 crypto = SHA256.Create(); for (int i = 0; i < Headerstream1.Length / chunkSize; i++) { byte[] buffer = new byte[chunkSize]; Headerstream1.Read(buffer, 0, (Int32)chunkSize); byte[] hash = crypto.ComputeHash(buffer); bw.Write(hash, 0, hash.Length); } for (int i = 0; i < Headerstream2.Length / chunkSize; i++) { byte[] buffer = new byte[chunkSize]; Headerstream2.Read(buffer, 0, (Int32)chunkSize); byte[] hash = crypto.ComputeHash(buffer); bw.Write(hash, 0, hash.Length); } foreach (FlashingPayload payload in payloads) { foreach (var chunkHash in payload.ChunkHashes) { bw.Write(chunkHash, 0, chunkHash.Length); } } bw.Close(); Logging.Log("Generating image catalog..."); byte[] catalog = GenerateCatalogFile(HashTable); security.CatalogSize = (UInt32)catalog.Length; byte[] SecurityHeaderBuffer = new byte[0x20]; ByteOperations.WriteUInt32(SecurityHeaderBuffer, 0, security.Size); ByteOperations.WriteAsciiString(SecurityHeaderBuffer, 0x04, security.Signature); ByteOperations.WriteUInt32(SecurityHeaderBuffer, 0x10, security.ChunkSizeInKb); ByteOperations.WriteUInt32(SecurityHeaderBuffer, 0x14, security.HashAlgorithm); ByteOperations.WriteUInt32(SecurityHeaderBuffer, 0x18, security.CatalogSize); ByteOperations.WriteUInt32(SecurityHeaderBuffer, 0x1C, security.HashTableSize); FileStream retstream = new FileStream(FFUFile, FileMode.CreateNew); retstream.Write(SecurityHeaderBuffer, 0, 0x20); retstream.Write(catalog, 0, (Int32)security.CatalogSize); retstream.Write(HashTable, 0, (Int32)security.HashTableSize); RoundUpToChunks(retstream, chunkSize); Headerstream1.Seek(0, SeekOrigin.Begin); Headerstream2.Seek(0, SeekOrigin.Begin); byte[] buff = new byte[Headerstream1.Length]; Headerstream1.Read(buff, 0, (Int32)Headerstream1.Length); Headerstream1.Close(); File.Delete(header1); retstream.Write(buff, 0, buff.Length); buff = new byte[Headerstream2.Length]; Headerstream2.Read(buff, 0, (Int32)Headerstream2.Length); Headerstream2.Close(); File.Delete(header2); retstream.Write(buff, 0, buff.Length); Logging.Log("Writing payloads..."); UInt64 counter = 0; DateTime startTime = DateTime.Now; foreach (FlashingPayload payload in payloads) { for (int i = 0; i < payload.StreamIndexes.Length; i++) { UInt32 StreamIndex = payload.StreamIndexes[i]; FlashPart flashPart = flashParts[StreamIndex]; Stream Stream = flashPart.Stream; Stream.Seek(payload.StreamLocations[i], SeekOrigin.Begin); byte[] buffer = new byte[chunkSize]; Stream.Read(buffer, 0, (Int32)chunkSize); retstream.Write(buffer, 0, (Int32)chunkSize); counter++; ShowProgress((UInt64)payloads.Count() * chunkSize, startTime, counter * chunkSize, counter * chunkSize, payload.TargetLocations[i] * chunkSize < PlatEnd); } } retstream.Close(); if (destDisk != null) { destDisk.Dispose(); } Logging.Log(""); }