Пример #1
0
        public void ShortNames()
        {
            NtfsFileSystem ntfs = FileSystemSource.NtfsFileSystem();

            // Check we can find a short name in the same directory
            using (Stream s = ntfs.OpenFile("ALongFileName.txt", FileMode.CreateNew)) {}
            ntfs.SetShortName("ALongFileName.txt", "ALONG~01.TXT");
            Assert.Equal("ALONG~01.TXT", ntfs.GetShortName("ALongFileName.txt"));
            Assert.True(ntfs.FileExists("ALONG~01.TXT"));

            // Check path handling
            ntfs.CreateDirectory("DIR");
            using (Stream s = ntfs.OpenFile(@"DIR\ALongFileName2.txt", FileMode.CreateNew)) { }
            ntfs.SetShortName(@"DIR\ALongFileName2.txt", "ALONG~02.TXT");
            Assert.Equal("ALONG~02.TXT", ntfs.GetShortName(@"DIR\ALongFileName2.txt"));
            Assert.True(ntfs.FileExists(@"DIR\ALONG~02.TXT"));

            // Check we can open a file by the short name
            using (Stream s = ntfs.OpenFile("ALONG~01.TXT", FileMode.Open)) { }

            // Delete the long name, and make sure the file is gone
            ntfs.DeleteFile("ALONG~01.TXT");
            Assert.False(ntfs.FileExists("ALONG~01.TXT"));

            // Delete the short name, and make sure the file is gone
            ntfs.DeleteFile(@"DIR\ALONG~02.TXT");
            Assert.False(ntfs.FileExists(@"DIR\ALongFileName2.txt"));
        }
Пример #2
0
        public void MoveLongName()
        {
            NtfsFileSystem ntfs = FileSystemSource.NtfsFileSystem();

            using (Stream s = ntfs.OpenFile("ALongFileName.txt", FileMode.CreateNew)) { }

            Assert.True(ntfs.FileExists("ALONGF~1.TXT"));

            ntfs.MoveFile("ALongFileName.txt", "ADifferentLongFileName.txt");

            Assert.False(ntfs.FileExists("ALONGF~1.TXT"));
            Assert.True(ntfs.FileExists("ADIFFE~1.TXT"));

            ntfs.CreateDirectory("ALongDirectoryName");
            Assert.True(ntfs.DirectoryExists("ALONGD~1"));

            ntfs.MoveDirectory("ALongDirectoryName", "ADifferentLongDirectoryName");
            Assert.False(ntfs.DirectoryExists("ALONGD~1"));
            Assert.True(ntfs.DirectoryExists("ADIFFE~1"));
        }
Пример #3
0
        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");
            }
        }
Пример #4
0
        protected override void DoRun()
        {
            if (!IsAdministrator())
            {
                Console.WriteLine("\nThis utility must be run as an administrator!\n");
                Environment.Exit(1);
            }

            DiskImageBuilder builder = DiskImageBuilder.GetBuilder(OutputDiskType, OutputDiskVariant);

            builder.GenericAdapterType = AdapterType;

            string[] sourceVolume = _volumes.Values;

            uint diskNumber;

            List <CloneVolume> cloneVolumes = GatherVolumes(sourceVolume, out diskNumber);


            if (!Quiet)
            {
                Console.WriteLine("Inspecting Disk...");
            }

            // Construct a stream representing the contents of the cloned disk.
            BiosPartitionedDiskBuilder contentBuilder;
            Geometry biosGeometry;
            Geometry ideGeometry;
            long     capacity;

            using (Disk disk = new Disk(diskNumber))
            {
                contentBuilder = new BiosPartitionedDiskBuilder(disk);
                biosGeometry   = disk.BiosGeometry;
                ideGeometry    = disk.Geometry;
                capacity       = disk.Capacity;
            }

            // Preserve the IDE (aka Physical) geometry
            builder.Geometry = ideGeometry;

            // Translate the BIOS (aka Logical) geometry
            GeometryTranslation translation = _translation.EnumValue;

            if (builder.PreservesBiosGeometry && translation == GeometryTranslation.Auto)
            {
                // If the new format preserves BIOS geometry, then take no action if asked for 'auto'
                builder.BiosGeometry = biosGeometry;
                translation          = GeometryTranslation.None;
            }
            else
            {
                builder.BiosGeometry = ideGeometry.TranslateToBios(0, translation);
            }

            if (translation != GeometryTranslation.None)
            {
                contentBuilder.UpdateBiosGeometry(builder.BiosGeometry);
            }


            IVssBackupComponents backupCmpnts;
            int status;

            if (Marshal.SizeOf(typeof(IntPtr)) == 4)
            {
                status = NativeMethods.CreateVssBackupComponents(out backupCmpnts);
            }
            else
            {
                status = NativeMethods.CreateVssBackupComponents64(out backupCmpnts);
            }


            Guid snapshotSetId = CreateSnapshotSet(cloneVolumes, backupCmpnts);

            if (!Quiet)
            {
                Console.Write("Copying Disk...");
            }


            foreach (var sv in cloneVolumes)
            {
                Volume sourceVol = new Volume(sv.SnapshotProperties.SnapshotDeviceObject, sv.SourceExtent.ExtentLength);

                SnapshotStream rawVolStream = new SnapshotStream(sourceVol.Content, Ownership.None);
                rawVolStream.Snapshot();

                byte[] volBitmap;
                int    clusterSize;
                using (NtfsFileSystem ntfs = new NtfsFileSystem(rawVolStream))
                {
                    ntfs.NtfsOptions.HideSystemFiles = false;
                    ntfs.NtfsOptions.HideHiddenFiles = false;
                    ntfs.NtfsOptions.HideMetafiles   = false;

                    // Remove VSS snapshot files (can be very large)
                    foreach (string filePath in ntfs.GetFiles(@"\System Volume Information", "*{3808876B-C176-4e48-B7AE-04046E6CC752}"))
                    {
                        ntfs.DeleteFile(filePath);
                    }

                    // Remove the page file
                    if (ntfs.FileExists(@"\Pagefile.sys"))
                    {
                        ntfs.DeleteFile(@"\Pagefile.sys");
                    }

                    // Remove the hibernation file
                    if (ntfs.FileExists(@"\hiberfil.sys"))
                    {
                        ntfs.DeleteFile(@"\hiberfil.sys");
                    }

                    using (Stream bitmapStream = ntfs.OpenFile(@"$Bitmap", FileMode.Open))
                    {
                        volBitmap = new byte[bitmapStream.Length];

                        int totalRead = 0;
                        int numRead   = bitmapStream.Read(volBitmap, 0, volBitmap.Length - totalRead);
                        while (numRead > 0)
                        {
                            totalRead += numRead;
                            numRead    = bitmapStream.Read(volBitmap, totalRead, volBitmap.Length - totalRead);
                        }
                    }

                    clusterSize = (int)ntfs.ClusterSize;

                    if (translation != GeometryTranslation.None)
                    {
                        ntfs.UpdateBiosGeometry(builder.BiosGeometry);
                    }
                }

                List <StreamExtent> extents          = new List <StreamExtent>(BitmapToRanges(volBitmap, clusterSize));
                SparseStream        partSourceStream = SparseStream.FromStream(rawVolStream, Ownership.None, extents);

                for (int i = 0; i < contentBuilder.PartitionTable.Partitions.Count; ++i)
                {
                    var part = contentBuilder.PartitionTable.Partitions[i];
                    if (part.FirstSector * 512 == sv.SourceExtent.StartingOffset)
                    {
                        contentBuilder.SetPartitionContent(i, partSourceStream);
                    }
                }
            }
            SparseStream contentStream = contentBuilder.Build();


            // Write out the disk images
            string dir  = Path.GetDirectoryName(_destDisk.Value);
            string file = Path.GetFileNameWithoutExtension(_destDisk.Value);

            builder.Content = contentStream;
            DiskImageFileSpecification[] fileSpecs = builder.Build(file);

            for (int i = 0; i < fileSpecs.Length; ++i)
            {
                // Construct the destination file path from the directory of the primary file.
                string outputPath = Path.Combine(dir, fileSpecs[i].Name);

                // Force the primary file to the be one from the command-line.
                if (i == 0)
                {
                    outputPath = _destDisk.Value;
                }

                using (SparseStream vhdStream = fileSpecs[i].OpenStream())
                    using (FileStream fs = new FileStream(outputPath, FileMode.Create, FileAccess.ReadWrite))
                    {
                        StreamPump pump = new StreamPump()
                        {
                            InputStream  = vhdStream,
                            OutputStream = fs,
                        };

                        long totalBytes = 0;
                        foreach (var se in vhdStream.Extents)
                        {
                            totalBytes += se.Length;
                        }

                        if (!Quiet)
                        {
                            Console.WriteLine();
                            DateTime now = DateTime.Now;
                            pump.ProgressEvent += (o, e) => { ShowProgress(fileSpecs[i].Name, totalBytes, now, o, e); };
                        }

                        pump.Run();

                        if (!Quiet)
                        {
                            Console.WriteLine();
                        }
                    }
            }


            // Complete - tidy up
            CallAsyncMethod(backupCmpnts.BackupComplete);

            long numDeleteFailed;
            Guid deleteFailed;

            backupCmpnts.DeleteSnapshots(snapshotSetId, 2 /*VSS_OBJECT_SNAPSHOT_SET*/, true, out numDeleteFailed, out deleteFailed);

            Marshal.ReleaseComObject(backupCmpnts);
        }
Пример #5
0
        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]);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
        }
Пример #6
0
        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");
            }
        }