/// <summary>
        /// Checks the integrity of an NTFS file system held in a stream.
        /// </summary>
        /// <param name="reportOutput">A report on issues found</param>
        /// <param name="levels">The amount of detail to report</param>
        /// <returns><c>true</c> if the file system appears valid, else <c>false</c></returns>
        public override bool Check(TextWriter reportOutput, ReportLevels levels)
        {
            _context           = new NtfsContext();
            _context.RawStream = _target;
            _context.Options   = new NtfsOptions();

            _report         = reportOutput;
            _reportLevels   = levels;
            _levelsDetected = ReportLevels.None;

            try
            {
                DoCheck();
            }
            catch (AbortException ae)
            {
                ReportError("File system check aborted: " + ae.ToString());
                return(false);
            }
            catch (Exception e)
            {
                ReportError("File system check aborted with exception: " + e.ToString());
                return(false);
            }

            return((_levelsDetected & _levelsConsideredFail) == 0);
        }
        /// <summary>
        /// Checks the integrity of an NTFS file system held in a stream.
        /// </summary>
        /// <param name="reportOutput">A report on issues found</param>
        /// <param name="levels">The amount of detail to report</param>
        /// <returns><c>true</c> if the file system appears valid, else <c>false</c></returns>
        public override bool Check(TextWriter reportOutput, ReportLevels levels)
        {
            _context = new NtfsContext();
            _context.RawStream = _target;
            _context.Options = new NtfsOptions();

            _report = reportOutput;
            _reportLevels = levels;
            _levelsDetected = ReportLevels.None;

            try
            {
                DoCheck();
            }
            catch (AbortException ae)
            {
                ReportError("File system check aborted: " + ae.ToString());
                return false;
            }
            catch (Exception e)
            {
                ReportError("File system check aborted with exception: " + e.ToString());
                return false;
            }

            return (_levelsDetected & _levelsConsideredFail) == 0;
        }
        /// <summary>
        /// Gets an object that can convert between clusters and files.
        /// </summary>
        /// <returns>The cluster map</returns>
        public ClusterMap BuildClusterMap()
        {
            _context           = new NtfsContext();
            _context.RawStream = _target;
            _context.Options   = new NtfsOptions();

            _context.RawStream.Position = 0;
            byte[] bytes = Utilities.ReadFully(_context.RawStream, 512);

            _context.BiosParameterBlock = BiosParameterBlock.FromBytes(bytes, 0);

            _context.Mft = new MasterFileTable(_context);
            File mftFile = new File(_context, _context.Mft.GetBootstrapRecord());

            _context.Mft.Initialize(mftFile);
            return(_context.Mft.GetClusterMap());
        }
Beispiel #4
0
        public NtfsFileSystem Format(Stream stream)
        {
            _context                      = new NtfsContext();
            _context.Options              = new NtfsOptions();
            _context.RawStream            = stream;
            _context.AttributeDefinitions = new AttributeDefinitions();

            string localAdminString = (ComputerAccount == null)
                    ? "LA"
                    : new SecurityIdentifier(WellKnownSidType.AccountAdministratorSid, ComputerAccount).ToString();

            using (new NtfsTransaction())
            {
                _clusterSize     = 4096;
                _mftRecordSize   = 1024;
                _indexBufferSize = 4096;

                long totalClusters = ((SectorCount - 1) * Sizes.Sector) / _clusterSize;

                // Allocate a minimum of 8KB for the boot loader, but allow for more
                int numBootClusters = Utilities.Ceil(Math.Max((int)(8 * Sizes.OneKiB), BootCode == null ? 0 : BootCode.Length), _clusterSize);

                // Place MFT mirror in the middle of the volume
                _mftMirrorCluster = totalClusters / 2;
                uint numMftMirrorClusters = 1;

                // The bitmap is also near the middle
                _bitmapCluster = _mftMirrorCluster + 13;
                int numBitmapClusters = (int)Utilities.Ceil((totalClusters / 8), _clusterSize);

                // The MFT bitmap goes 'near' the start - approx 10% in - but ensure we avoid the bootloader
                long mftBitmapCluster     = Math.Max(3 + (totalClusters / 10), numBootClusters);
                int  numMftBitmapClusters = 1;

                // The MFT follows it's bitmap
                _mftCluster = mftBitmapCluster + numMftBitmapClusters;
                int numMftClusters = 8;

                if (_mftCluster + numMftClusters > _mftMirrorCluster ||
                    _bitmapCluster + numBitmapClusters >= totalClusters)
                {
                    throw new IOException("Unable to determine initial layout of NTFS metadata - disk may be too small");
                }

                CreateBiosParameterBlock(stream, numBootClusters * _clusterSize);

                _context.Mft = new MasterFileTable(_context);
                File mftFile = _context.Mft.InitializeNew(_context, mftBitmapCluster, (ulong)numMftBitmapClusters, (long)_mftCluster, (ulong)numMftClusters);

                File bitmapFile = CreateFixedSystemFile(MasterFileTable.BitmapIndex, _bitmapCluster, (ulong)numBitmapClusters, true);
                _context.ClusterBitmap = new ClusterBitmap(bitmapFile);
                _context.ClusterBitmap.MarkAllocated(0, numBootClusters);
                _context.ClusterBitmap.MarkAllocated(_bitmapCluster, numBitmapClusters);
                _context.ClusterBitmap.MarkAllocated(mftBitmapCluster, numMftBitmapClusters);
                _context.ClusterBitmap.MarkAllocated(_mftCluster, numMftClusters);
                _context.ClusterBitmap.SetTotalClusters(totalClusters);
                bitmapFile.UpdateRecordInMft();

                File mftMirrorFile = CreateFixedSystemFile(MasterFileTable.MftMirrorIndex, _mftMirrorCluster, numMftMirrorClusters, true);

                File logFile = CreateSystemFile(MasterFileTable.LogFileIndex);
                using (Stream s = logFile.OpenStream(AttributeType.Data, null, FileAccess.ReadWrite))
                {
                    s.SetLength(Math.Min(Math.Max(2 * Sizes.OneMiB, (totalClusters / 500) * (long)_clusterSize), 64 * Sizes.OneMiB));
                    byte[] buffer = new byte[1024 * 1024];
                    for (int i = 0; i < buffer.Length; ++i)
                    {
                        buffer[i] = 0xFF;
                    }

                    long totalWritten = 0;
                    while (totalWritten < s.Length)
                    {
                        int toWrite = (int)Math.Min(s.Length - totalWritten, buffer.Length);
                        s.Write(buffer, 0, toWrite);
                        totalWritten += toWrite;
                    }
                }

                File       volumeFile    = CreateSystemFile(MasterFileTable.VolumeIndex);
                NtfsStream volNameStream = volumeFile.CreateStream(AttributeType.VolumeName, null);
                volNameStream.SetContent(new VolumeName(Label ?? "New Volume"));
                NtfsStream volInfoStream = volumeFile.CreateStream(AttributeType.VolumeInformation, null);
                volInfoStream.SetContent(new VolumeInformation(3, 1, VolumeInformationFlags.None));
                SetSecurityAttribute(volumeFile, "O:" + localAdminString + "G:BAD:(A;;0x12019f;;;SY)(A;;0x12019f;;;BA)");
                volumeFile.UpdateRecordInMft();

                _context.GetFileByIndex = delegate(long index) { return(new File(_context, _context.Mft.GetRecord(index, false))); };
                _context.AllocateFile   = delegate(FileRecordFlags frf) { return(new File(_context, _context.Mft.AllocateRecord(frf, false))); };

                File attrDefFile = CreateSystemFile(MasterFileTable.AttrDefIndex);
                _context.AttributeDefinitions.WriteTo(attrDefFile);
                SetSecurityAttribute(attrDefFile, "O:" + localAdminString + "G:BAD:(A;;FR;;;SY)(A;;FR;;;BA)");
                attrDefFile.UpdateRecordInMft();

                File bootFile = CreateFixedSystemFile(MasterFileTable.BootIndex, 0, (uint)numBootClusters, false);
                SetSecurityAttribute(bootFile, "O:" + localAdminString + "G:BAD:(A;;FR;;;SY)(A;;FR;;;BA)");
                bootFile.UpdateRecordInMft();

                File badClusFile = CreateSystemFile(MasterFileTable.BadClusIndex);
                badClusFile.CreateStream(AttributeType.Data, "$Bad");
                badClusFile.UpdateRecordInMft();

                File secureFile = CreateSystemFile(MasterFileTable.SecureIndex, FileRecordFlags.HasViewIndex);
                secureFile.RemoveStream(secureFile.GetStream(AttributeType.Data, null));
                _context.SecurityDescriptors = SecurityDescriptors.Initialize(secureFile);
                secureFile.UpdateRecordInMft();

                File upcaseFile = CreateSystemFile(MasterFileTable.UpCaseIndex);
                _context.UpperCase = UpperCase.Initialize(upcaseFile);
                upcaseFile.UpdateRecordInMft();

                File objIdFile = File.CreateNew(_context, FileRecordFlags.IsMetaFile | FileRecordFlags.HasViewIndex, FileAttributeFlags.None);
                objIdFile.RemoveStream(objIdFile.GetStream(AttributeType.Data, null));
                objIdFile.CreateIndex("$O", (AttributeType)0, AttributeCollationRule.MultipleUnsignedLongs);
                objIdFile.UpdateRecordInMft();

                File reparseFile = File.CreateNew(_context, FileRecordFlags.IsMetaFile | FileRecordFlags.HasViewIndex, FileAttributeFlags.None);
                reparseFile.CreateIndex("$R", (AttributeType)0, AttributeCollationRule.MultipleUnsignedLongs);
                reparseFile.UpdateRecordInMft();

                File quotaFile = File.CreateNew(_context, FileRecordFlags.IsMetaFile | FileRecordFlags.HasViewIndex, FileAttributeFlags.None);
                Quotas.Initialize(quotaFile);

                Directory extendDir = CreateSystemDirectory(MasterFileTable.ExtendIndex);
                extendDir.AddEntry(objIdFile, "$ObjId", FileNameNamespace.Win32AndDos);
                extendDir.AddEntry(reparseFile, "$Reparse", FileNameNamespace.Win32AndDos);
                extendDir.AddEntry(quotaFile, "$Quota", FileNameNamespace.Win32AndDos);
                extendDir.UpdateRecordInMft();

                Directory rootDir = CreateSystemDirectory(MasterFileTable.RootDirIndex);
                rootDir.AddEntry(mftFile, "$MFT", FileNameNamespace.Win32AndDos);
                rootDir.AddEntry(mftMirrorFile, "$MFTMirr", FileNameNamespace.Win32AndDos);
                rootDir.AddEntry(logFile, "$LogFile", FileNameNamespace.Win32AndDos);
                rootDir.AddEntry(volumeFile, "$Volume", FileNameNamespace.Win32AndDos);
                rootDir.AddEntry(attrDefFile, "$AttrDef", FileNameNamespace.Win32AndDos);
                rootDir.AddEntry(rootDir, ".", FileNameNamespace.Win32AndDos);
                rootDir.AddEntry(bitmapFile, "$Bitmap", FileNameNamespace.Win32AndDos);
                rootDir.AddEntry(bootFile, "$Boot", FileNameNamespace.Win32AndDos);
                rootDir.AddEntry(badClusFile, "$BadClus", FileNameNamespace.Win32AndDos);
                rootDir.AddEntry(secureFile, "$Secure", FileNameNamespace.Win32AndDos);
                rootDir.AddEntry(upcaseFile, "$UpCase", FileNameNamespace.Win32AndDos);
                rootDir.AddEntry(extendDir, "$Extend", FileNameNamespace.Win32AndDos);
                SetSecurityAttribute(rootDir, "O:" + localAdminString + "G:BUD:(A;OICI;FA;;;BA)(A;OICI;FA;;;SY)(A;OICIIO;GA;;;CO)(A;OICI;0x1200a9;;;BU)(A;CI;LC;;;BU)(A;CIIO;DC;;;BU)(A;;0x1200a9;;;WD)");
                rootDir.UpdateRecordInMft();

                // A number of records are effectively 'reserved'
                for (long i = MasterFileTable.ExtendIndex + 1; i <= 15; i++)
                {
                    File f = CreateSystemFile(i);
                    SetSecurityAttribute(f, "O:S-1-5-21-1708537768-746137067-1060284298-1003G:BAD:(A;;0x12019f;;;SY)(A;;0x12019f;;;BA)");
                    f.UpdateRecordInMft();
                }
            }

            // XP-style security permissions setup
            NtfsFileSystem ntfs = new NtfsFileSystem(stream);

            ntfs.SetSecurity(@"$MFT", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;FR;;;SY)(A;;FR;;;BA)"));
            ntfs.SetSecurity(@"$MFTMirr", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;FR;;;SY)(A;;FR;;;BA)"));
            ntfs.SetSecurity(@"$LogFile", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;FR;;;SY)(A;;FR;;;BA)"));
            ntfs.SetSecurity(@"$Bitmap", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;FR;;;SY)(A;;FR;;;BA)"));
            ntfs.SetSecurity(@"$BadClus", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;FR;;;SY)(A;;FR;;;BA)"));
            ntfs.SetSecurity(@"$UpCase", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;FR;;;SY)(A;;FR;;;BA)"));
            ntfs.SetSecurity(@"$Secure", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;0x12019f;;;SY)(A;;0x12019f;;;BA)"));
            ntfs.SetSecurity(@"$Extend", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;0x12019f;;;SY)(A;;0x12019f;;;BA)"));
            ntfs.SetSecurity(@"$Extend\$Quota", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;0x12019f;;;SY)(A;;0x12019f;;;BA)"));
            ntfs.SetSecurity(@"$Extend\$ObjId", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;0x12019f;;;SY)(A;;0x12019f;;;BA)"));
            ntfs.SetSecurity(@"$Extend\$Reparse", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;0x12019f;;;SY)(A;;0x12019f;;;BA)"));

            ntfs.CreateDirectory("System Volume Information");
            ntfs.SetAttributes("System Volume Information", FileAttributes.Hidden | FileAttributes.System | FileAttributes.Directory);
            ntfs.SetSecurity("System Volume Information", new RawSecurityDescriptor("O:BAG:SYD:(A;OICI;FA;;;SY)"));

            using (Stream s = ntfs.OpenFile(@"System Volume Information\MountPointManagerRemoteDatabase", FileMode.Create))
            {
            }

            ntfs.SetAttributes(@"System Volume Information\MountPointManagerRemoteDatabase", FileAttributes.Hidden | FileAttributes.System | FileAttributes.Archive);
            ntfs.SetSecurity(@"System Volume Information\MountPointManagerRemoteDatabase", new RawSecurityDescriptor("O:BAG:SYD:(A;;FA;;;SY)"));
            return(ntfs);
        }
        /// <summary>
        /// Initializes a new instance of the NtfsFileSystem class.
        /// </summary>
        /// <param name="stream">The stream containing the NTFS file system</param>
        public NtfsFileSystem(Stream stream)
            : base(new NtfsOptions())
        {
            _context = new NtfsContext();
            _context.RawStream = stream;
            _context.Options = NtfsOptions;

            _context.GetFileByIndex = GetFile;
            _context.GetFileByRef = GetFile;
            _context.GetDirectoryByRef = GetDirectory;
            _context.GetDirectoryByIndex = GetDirectory;
            _context.AllocateFile = AllocateFile;
            _context.ForgetFile = ForgetFile;
            _context.ReadOnly = !stream.CanWrite;

            _fileCache = new ObjectCache<long, File>();

            stream.Position = 0;
            byte[] bytes = Utilities.ReadFully(stream, 512);

            _context.BiosParameterBlock = BiosParameterBlock.FromBytes(bytes, 0);

            if (NtfsOptions.ReadCacheEnabled)
            {
                BlockCacheSettings cacheSettings = new BlockCacheSettings();
                cacheSettings.BlockSize = _context.BiosParameterBlock.BytesPerCluster;
                _context.RawStream = new BlockCacheStream(SparseStream.FromStream(stream, Ownership.None), Ownership.None, cacheSettings);
            }

            // Bootstrap the Master File Table
            _context.Mft = new MasterFileTable(_context);
            File mftFile = new File(_context, _context.Mft.GetBootstrapRecord());
            _fileCache[MasterFileTable.MftIndex] = mftFile;
            _context.Mft.Initialize(mftFile);

            // Get volume information (includes version number)
            File volumeInfoFile = GetFile(MasterFileTable.VolumeIndex);
            _volumeInfo = volumeInfoFile.GetStream(AttributeType.VolumeInformation, null).GetContent<VolumeInformation>();

            // Initialize access to the other well-known metadata files
            _context.ClusterBitmap = new ClusterBitmap(GetFile(MasterFileTable.BitmapIndex));
            _context.AttributeDefinitions = new AttributeDefinitions(GetFile(MasterFileTable.AttrDefIndex));
            _context.UpperCase = new UpperCase(GetFile(MasterFileTable.UpCaseIndex));

            if (_volumeInfo.Version >= VolumeInformation.VersionW2k)
            {
                _context.SecurityDescriptors = new SecurityDescriptors(GetFile(MasterFileTable.SecureIndex));
                _context.ObjectIds = new ObjectIds(GetFile(GetDirectoryEntry(@"$Extend\$ObjId").Reference));
                _context.ReparsePoints = new ReparsePoints(GetFile(GetDirectoryEntry(@"$Extend\$Reparse").Reference));
                _context.Quotas = new Quotas(GetFile(GetDirectoryEntry(@"$Extend\$Quota").Reference));
            }
#if false
            byte[] buffer = new byte[1024];
            for (int i = 0; i < buffer.Length; ++i)
            {
                buffer[i] = 0xFF;
            }

            using (Stream s = OpenFile("$LogFile", FileMode.Open, FileAccess.ReadWrite))
            {
                while (s.Position != s.Length)
                {
                    s.Write(buffer, 0, (int)Math.Min(buffer.Length, s.Length - s.Position));
                }
            }
#endif
        }
        /// <summary>
        /// Gets an object that can convert between clusters and files.
        /// </summary>
        /// <returns>The cluster map</returns>
        public ClusterMap BuildClusterMap()
        {
            _context = new NtfsContext();
            _context.RawStream = _target;
            _context.Options = new NtfsOptions();

            _context.RawStream.Position = 0;
            byte[] bytes = Utilities.ReadFully(_context.RawStream, 512);

            _context.BiosParameterBlock = BiosParameterBlock.FromBytes(bytes, 0);

            _context.Mft = new MasterFileTable(_context);
            File mftFile = new File(_context, _context.Mft.GetBootstrapRecord());
            _context.Mft.Initialize(mftFile);
            return _context.Mft.GetClusterMap();
        }