示例#1
0
        private string GetInformationUnicodeString(DriverInformationClass infoClass)
        {
            using (MemoryAlloc data = new MemoryAlloc(0x1000))
            {
                int retLength = 0;

                try
                {
                    KProcessHacker.Instance.KphQueryInformationDriver(
                        this,
                        infoClass,
                        data,
                        data.Size,
                        out retLength
                        );
                }
                catch (WindowsException)
                {
                    data.ResizeNew(retLength);

                    KProcessHacker.Instance.KphQueryInformationDriver(
                        this,
                        infoClass,
                        data,
                        data.Size,
                        out retLength
                        );
                }

                return data.ReadStruct<UnicodeString>().Read();
            }
        }
        private string GetInformationUnicodeString(DriverInformationClass infoClass)
        {
            using (MemoryAlloc data = new MemoryAlloc(0x1000))
            {
                int retLength = 0;

                //try
                //{
                //    KProcessHacker.Instance.KphQueryInformationDriver(
                //        this,
                //        infoClass,
                //        data,
                //        data.Size,
                //        out retLength
                //        );
                //}
                //catch (WindowsException)
                //{
                //    data.ResizeNew(retLength);

                //    KProcessHacker.Instance.KphQueryInformationDriver(
                //        this,
                //        infoClass,
                //        data,
                //        data.Size,
                //        out retLength
                //        );
                //}

                return data.ReadStruct<UnicodeString>().Text;
            }
        }
示例#3
0
 public PortMessage(PortMessage existingMessage, byte[] data)
 {
     using (var alloc = new MemoryAlloc(data.Length))
     {
         alloc.WriteBytes(0, data);
         this.InitializeMessage(existingMessage, alloc, (short)alloc.Size);
     }
 }
示例#4
0
        public MemoryAlloc ToMemory()
        {
            MemoryAlloc data = new MemoryAlloc(PortMessageStruct.SizeOf + _message.DataLength);

            data.WriteStruct(_message);
            data.WriteMemory(PortMessageStruct.SizeOf, _data, _message.DataLength);

            return(data);
        }
示例#5
0
        public void Request(PortMessage message)
        {
            using (MemoryAlloc messageMemory = message.ToMemory())
            {
                Win32.NtRequestPort(this, messageMemory).ThrowIf();

                message.SetHeader(messageMemory);
            }
        }
示例#6
0
        private MemoryAlloc AllocateStruct <T>(T value)
            where T : struct
        {
            MemoryAlloc alloc = new MemoryAlloc(Marshal.SizeOf(typeof(T)));

            alloc.WriteStruct <T>(0, value);

            return(alloc);
        }
示例#7
0
 public static void AppendStruct <T>(MemoryObject mo, T s)
     where T : struct
 {
     using (var data = new MemoryAlloc(Marshal.SizeOf(typeof(T))))
     {
         data.WriteStruct <T>(s);
         mo.AppendData(data.ReadBytes(data.Size));
     }
 }
示例#8
0
        private MemoryAlloc AllocateString(string value)
        {
            MemoryAlloc alloc = new MemoryAlloc((value.Length + 1) * 2);

            alloc.WriteUnicodeString(0, value);
            alloc.WriteInt16(value.Length * 2, 0);

            return(alloc);
        }
 public void Write <T>(T s)
     where T : struct
 {
     using (var data = new MemoryAlloc(Marshal.SizeOf(typeof(T))))
     {
         data.WriteStruct <T>(s);
         this.Write((MemoryRegion)data);
     }
 }
示例#10
0
        public MemoryAlloc ToMemory()
        {
            MemoryAlloc data = new MemoryAlloc(_portMessageSize + _message.DataLength);

            data.WriteStruct <PortMessageStruct>(_message);
            data.WriteMemory(_portMessageSize, _data, _message.DataLength);

            return(data);
        }
示例#11
0
        public PortMessage Listen()
        {
            using (MemoryAlloc buffer = PortMessage.AllocateBuffer())
            {
                Win32.NtListenPort(this, buffer).ThrowIf();

                return(new PortMessage(buffer));
            }
        }
示例#12
0
 public void AddPrivileges(PrivilegeSet privileges)
 {
     using (MemoryAlloc privilegeSetMemory = privileges.ToMemory())
     {
         Win32.LsaAddPrivilegesToAccount(
             this,
             privilegeSetMemory
             ).ThrowIf();
     }
 }
示例#13
0
        private MemoryAlloc AllocateArray(IntPtr[] value)
        {
            MemoryAlloc alloc = new MemoryAlloc(IntPtr.Size * value.Length);

            for (int i = 0; i < value.Length; i++)
            {
                alloc.WriteIntPtr(i * IntPtr.Size, value[i]);
            }

            return(alloc);
        }
示例#14
0
 public void RemovePrivileges(PrivilegeSet privileges)
 {
     using (MemoryAlloc privilegeSetMemory = privileges.ToMemory())
     {
         Win32.LsaRemovePrivilegesFromAccount(
             this,
             false,
             privilegeSetMemory
             ).ThrowIf();
     }
 }
示例#15
0
        public static string GetDeviceName(FileHandle fhandle)
        {
            using (MemoryAlloc data = new MemoryAlloc(600))
            {
                fhandle.IoControl(IoCtlQueryDeviceName, IntPtr.Zero, 0, data, data.Size);

                MountDevName name = data.ReadStruct <MountDevName>();

                return(data.ReadUnicodeString(MountDevName.NameOffset, name.NameLength / 2));
            }
        }
示例#16
0
        public string GetText()
        {
            int retChars;

            using (var data = new MemoryAlloc(0x200))
            {
                retChars = Win32.InternalGetWindowText(this, data, data.Size / 2);

                return(data.ReadUnicodeString(0, retChars));
            }
        }
示例#17
0
        private MemoryAlloc AllocateStructArray <T>(int size, T[] value) where T : struct
        {
            MemoryAlloc alloc = new MemoryAlloc(size * value.Length);

            for (int i = 0; i < value.Length; i++)
            {
                alloc.WriteStruct(i, size, value[i]);
            }

            return(alloc);
        }
示例#18
0
        private MemoryAlloc AllocateStructArray <T>(T[] value)
            where T : struct
        {
            MemoryAlloc alloc = new MemoryAlloc(Marshal.SizeOf(typeof(T)) * value.Length);

            for (int i = 0; i < value.Length; i++)
            {
                alloc.WriteStruct <T>(i, value[i]);
            }

            return(alloc);
        }
示例#19
0
        public static void UnpackCredentials(
            MemoryRegion buffer,
            CredPackFlags flags,
            out string domainName,
            out string userName,
            out string password
            )
        {
            using (MemoryAlloc domainNameBuffer = new MemoryAlloc(0x100))
                using (MemoryAlloc userNameBuffer = new MemoryAlloc(0x100))
                    using (MemoryAlloc passwordBuffer = new MemoryAlloc(0x100))
                    {
                        int domainNameSize = domainNameBuffer.Size / 2 - 1;
                        int userNameSize   = userNameBuffer.Size / 2 - 1;
                        int passwordSize   = passwordBuffer.Size / 2 - 1;

                        if (!Win32.CredUnPackAuthenticationBuffer(
                                flags,
                                buffer,
                                buffer.Size,
                                userNameBuffer,
                                ref userNameSize,
                                domainNameBuffer,
                                ref domainNameSize,
                                passwordBuffer,
                                ref passwordSize
                                ))
                        {
                            domainNameBuffer.ResizeNew(domainNameSize * 2 + 2);
                            userNameBuffer.ResizeNew(userNameSize * 2 + 2);
                            passwordBuffer.ResizeNew(passwordSize * 2 + 2);

                            if (!Win32.CredUnPackAuthenticationBuffer(
                                    flags,
                                    buffer,
                                    buffer.Size,
                                    userNameBuffer,
                                    ref userNameSize,
                                    domainNameBuffer,
                                    ref domainNameSize,
                                    passwordBuffer,
                                    ref passwordSize
                                    ))
                            {
                                Win32.Throw();
                            }
                        }

                        domainName = domainNameBuffer.ReadUnicodeString(0);
                        userName   = userNameBuffer.ReadUnicodeString(0);
                        password   = passwordBuffer.ReadUnicodeString(0);
                    }
        }
 private ProfileHandle(
     IntPtr handle,
     bool owned,
     IntPtr rangeBase,
     uint rangeSize,
     uint bucketSize,
     MemoryAlloc buffer
     )
     : base(handle, owned)
 {
     _buffer = buffer;
 }
示例#21
0
        public PortMessage ReplyWaitReply(PortMessage message)
        {
            using (MemoryAlloc messageMemory = message.ToMemory())
            {
                Win32.NtReplyWaitReplyPort(
                    this,
                    messageMemory
                    ).ThrowIf();

                return(new PortMessage(messageMemory));
            }
        }
示例#22
0
        public static void UnpackCredentials(
            MemoryRegion buffer,
            CredPackFlags flags,
            out string domainName,
            out string userName,
            out string password
            )
        {
            using (var domainNameBuffer = new MemoryAlloc(0x100))
            using (var userNameBuffer = new MemoryAlloc(0x100))
            using (var passwordBuffer = new MemoryAlloc(0x100))
            {
                int domainNameSize = domainNameBuffer.Size / 2 - 1;
                int userNameSize = userNameBuffer.Size / 2 - 1;
                int passwordSize = passwordBuffer.Size / 2 - 1;

                if (!Win32.CredUnPackAuthenticationBuffer(
                    flags,
                    buffer,
                    buffer.Size,
                    userNameBuffer,
                    ref userNameSize,
                    domainNameBuffer,
                    ref domainNameSize,
                    passwordBuffer,
                    ref passwordSize
                    ))
                {
                    domainNameBuffer.ResizeNew(domainNameSize * 2 + 2);
                    userNameBuffer.ResizeNew(userNameSize * 2 + 2);
                    passwordBuffer.ResizeNew(passwordSize * 2 + 2);

                    if (!Win32.CredUnPackAuthenticationBuffer(
                        flags,
                        buffer,
                        buffer.Size,
                        userNameBuffer,
                        ref userNameSize,
                        domainNameBuffer,
                        ref domainNameSize,
                        passwordBuffer,
                        ref passwordSize
                        ))
                        Win32.Throw();
                }

                domainName = domainNameBuffer.ReadUnicodeString(0);
                userName = userNameBuffer.ReadUnicodeString(0);
                password = passwordBuffer.ReadUnicodeString(0);
            }
        }
示例#23
0
        public static Sid GetWellKnownSid(WellKnownSidType sidType)
        {
            using (MemoryAlloc memory = new MemoryAlloc(Win32.SecurityMaxSidSize))
            {
                int memorySize = memory.Size;

                if (!Win32.CreateWellKnownSid(sidType, IntPtr.Zero, memory, ref memorySize))
                {
                    Win32.ThrowLastError();
                }

                return(new Sid(memory));
            }
        }
示例#24
0
        public string GetVariable(string name)
        {
            NtStatus      status;
            UnicodeString nameStr;
            UnicodeString valueStr;

            nameStr = new UnicodeString(name);

            try
            {
                using (var data = new MemoryAlloc(100))
                {
                    valueStr               = new UnicodeString();
                    valueStr.Buffer        = data;
                    valueStr.MaximumLength = (ushort)data.Size;

                    status = Win32.RtlQueryEnvironmentVariable_U(
                        this,
                        ref nameStr,
                        ref valueStr
                        );

                    if (status == NtStatus.BufferTooSmall)
                    {
                        // Resize and try again (+2 for the null terminator).
                        data.Resize(valueStr.Length + 2);
                        valueStr.Buffer        = data;
                        valueStr.MaximumLength = (ushort)(valueStr.Length + 2);

                        status = Win32.RtlQueryEnvironmentVariable_U(
                            this,
                            ref nameStr,
                            ref valueStr
                            );
                    }

                    if (status >= NtStatus.Error)
                    {
                        Win32.ThrowLastError(status);
                    }

                    return(valueStr.Read());
                }
            }
            finally
            {
                nameStr.Dispose();
            }
        }
示例#25
0
        public MemoryAlloc ToMemory()
        {
            int         requiredSize = 8 + _sizeOfLaa * _privileges.Count;
            MemoryAlloc memory       = new MemoryAlloc(requiredSize);

            memory.WriteInt32(0, _privileges.Count);
            memory.WriteInt32(4, (int)_flags);

            for (int i = 0; i < _privileges.Count; i++)
            {
                memory.WriteStruct <LuidAndAttributes>(8, i, _privileges[i].ToLuidAndAttributes());
            }

            return(memory);
        }
示例#26
0
        public bool CheckPrivileges(PrivilegeSet privileges)
        {
            bool result;

            using (MemoryAlloc privilegesMemory = privileges.ToMemory())
            {
                Win32.NtPrivilegeCheck(
                    this,
                    privilegesMemory,
                    out result
                    ).ThrowIf();

                return(result);
            }
        }
示例#27
0
        public PortMessage RequestWaitReply(PortMessage message)
        {
            using (MemoryAlloc buffer = PortMessage.AllocateBuffer())
                using (MemoryAlloc messageMemory = message.ToMemory())
                {
                    Win32.NtRequestWaitReplyPort(
                        this,
                        messageMemory,
                        buffer
                        ).ThrowIf();

                    message.SetHeader(messageMemory);

                    return(new PortMessage(buffer));
                }
        }
示例#28
0
        /// <summary>
        /// Gets the service's description.
        /// </summary>
        /// <returns>A string.</returns>
        public string GetDescription()
        {
            int retLen;

            Win32.QueryServiceConfig2(this, ServiceInfoLevel.Description, IntPtr.Zero, 0, out retLen);

            using (MemoryAlloc data = new MemoryAlloc(retLen))
            {
                if (!Win32.QueryServiceConfig2(this, ServiceInfoLevel.Description, data, retLen, out retLen))
                {
                    Win32.ThrowLastError();
                }

                return(data.ReadStruct <ServiceDescription>().Description);
            }
        }
示例#29
0
        /// <summary>
        /// Gets the service's configuration.
        /// </summary>
        public QueryServiceConfig GetConfig()
        {
            int requiredSize = 0;

            Win32.QueryServiceConfig(this, IntPtr.Zero, 0, out requiredSize);

            using (MemoryAlloc data = new MemoryAlloc(requiredSize))
            {
                if (!Win32.QueryServiceConfig(this, data, data.Size, out requiredSize))
                {
                    Win32.ThrowLastError();
                }

                return(data.ReadStruct <QueryServiceConfig>());
            }
        }
示例#30
0
        private unsafe void ScanHiddenObjects()
        {
            KVars vars = this.GetKVars();
            int   bytesRead;

            throw new NotSupportedException();

            listHiddenObjects.Items.Clear();

            using (var currentPage = new MemoryAlloc(Windows.PageSize))
            {
                for (
                    IntPtr address = vars.NonPagedPoolStart;
                    address.CompareTo(vars.NonPagedPoolStart.Increment(vars.NonPagedPoolSize)) == -1;
                    address = address.Increment(Windows.PageSize)
                    )
                {
                    try
                    {
                        KProcessHacker.Instance.KphReadVirtualMemoryUnsafe(
                            ProcessHandle.Current,
                            address.ToInt32(),
                            (IntPtr)currentPage,
                            Windows.PageSize,
                            out bytesRead
                            );
                    }
                    catch
                    {
                        continue;
                    }

                    for (
                        IntPtr inner = address;
                        inner.CompareTo(address.Increment(Windows.PageSize)) == -1;
                        inner = inner.Increment(8)
                        )
                    {
                    }

                    labelObjectsScanProgress.Text = string.Format("Scanned 0x{0:x8}", address.ToInt32());
                    Application.DoEvents();
                }
            }

            labelObjectsScanProgress.Text = "Finished.";
        }
示例#31
0
        /// <summary>
        /// Gets the token's owner.
        /// </summary>
        /// <returns>A WindowsSID instance.</returns>
        public Sid GetOwner()
        {
            int retLen;

            Win32.GetTokenInformation(this, TokenInformationClass.TokenOwner, IntPtr.Zero, 0, out retLen);

            using (MemoryAlloc data = new MemoryAlloc(retLen))
            {
                if (!Win32.GetTokenInformation(this, TokenInformationClass.TokenOwner, data,
                                               data.Size, out retLen))
                {
                    Win32.ThrowLastError();
                }

                return(new Sid(data.ReadIntPtr(0)));
            }
        }
示例#32
0
        /// <summary>
        /// Gets the token's primary group.
        /// </summary>
        /// <returns>A WindowsSID instance.</returns>
        public Sid GetPrimaryGroup()
        {
            int retLen;

            Win32.GetTokenInformation(this, TokenInformationClass.TokenPrimaryGroup, IntPtr.Zero, 0, out retLen);

            using (MemoryAlloc data = new MemoryAlloc(retLen))
            {
                if (!Win32.GetTokenInformation(this, TokenInformationClass.TokenPrimaryGroup, data,
                                               data.Size, out retLen))
                {
                    Win32.Throw();
                }

                return(new Sid(data.ReadIntPtr(0)));
            }
        }
示例#33
0
        private static void DeleteSymbolicLink(string path)
        {
            using (var data = new MemoryAlloc(MountMgrMountPoint.Size + path.Length * 2))
                using (var outData = new MemoryAlloc(1600))
                {
                    MountMgrMountPoint mountPoint = new MountMgrMountPoint();

                    mountPoint.SymbolicLinkNameLength = (ushort)(path.Length * 2);
                    mountPoint.SymbolicLinkNameOffset = MountMgrMountPoint.Size;
                    data.WriteStruct <MountMgrMountPoint>(mountPoint);
                    data.WriteUnicodeString(mountPoint.SymbolicLinkNameOffset, path);

                    using (var fhandle = OpenMountManager(FileAccess.GenericRead | FileAccess.GenericWrite))
                    {
                        fhandle.IoControl(IoCtlDeletePoints, data.Memory, data.Size, outData.Memory, outData.Size);
                    }
                }
        }
        public string GetVariable(string name)
        {
            UnicodeString nameStr = new UnicodeString(name);

            try
            {
                using (MemoryAlloc data = new MemoryAlloc(100))
                {
                    UnicodeString valueStr = new UnicodeString
                    {
                        Buffer        = data,
                        MaximumLength = (ushort)data.Size
                    };

                    NtStatus status = Win32.RtlQueryEnvironmentVariable_U(
                        this,
                        ref nameStr,
                        ref valueStr
                        );

                    if (status == NtStatus.BufferTooSmall)
                    {
                        // Resize and try again (+2 for the null terminator).
                        data.ResizeNew(valueStr.Length + 2);
                        valueStr.Buffer        = data;
                        valueStr.MaximumLength = (ushort)(valueStr.Length + 2);

                        status = Win32.RtlQueryEnvironmentVariable_U(
                            this,
                            ref nameStr,
                            ref valueStr
                            );
                    }

                    status.ThrowIf();

                    return(valueStr.Text);
                }
            }
            finally
            {
                nameStr.Dispose();
            }
        }
示例#35
0
        public static MemoryRegion PackCredentials(CredPackFlags flags, string userName, string password)
        {
            MemoryAlloc data = new MemoryAlloc(0x100);
            int size = data.Size;

            if (userName == null)
                userName = "";
            if (password == null)
                password = "";

            if (!Win32.CredPackAuthenticationBuffer(flags, userName, password, data, ref size))
            {
                data.ResizeNew(size);

                if (!Win32.CredPackAuthenticationBuffer(flags, userName, password, data, ref size))
                    Win32.Throw();
            }

            return data;
        }
示例#36
0
    public static int Main(String[] args)
    {
        if (GCSettings.IsServerGC == true)
        {
            Console.WriteLine("we are using server GC");
        }
        int iter_num = 500000;
        if (args.Length >= 1)
        {
            iter_num = int.Parse(args[0]);
            Console.WriteLine("iterating {0} times", iter_num);
        }

        // ProjectN doesn't support thread! for now just do everything on the main thread.
        //int threadCount = 8;
        //        int threadCount = 1;
        //        if (args.Length >= 2)
        //        {
        //            threadCount = int.Parse(args[1]);
        //            Console.WriteLine ("creating {0} threads", threadCount);
        //        }

        long tStart, tEnd;
        tStart = Environment.TickCount;
        //        MyThread t;
        //        ThreadStart ts;
        //        Thread[] threads = new Thread[threadCount];
        //
        //        for (int i = 0; i < threadCount; i++)
        //        {
        //            t = new MyThread(i, iter_num, old, med);
        //            ts = new ThreadStart(t.TimeTest);
        //            threads[i] = new Thread( ts );
        //            threads[i].Start();
        //        }
        //
        //        for (int i = 0; i < threadCount; i++)
        //        {
        //            threads[i].Join();
        //        }
        //

        Console.WriteLine("start with {0} gen1 GCs", s_iLastGen1Count);

        s_iLastGen0Count = GC.CollectionCount(0);
        s_iLastGen1Count = GC.CollectionCount(1);

        for (int iter = 0; iter < 1; iter++)
        {
            MemoryAlloc[] maArr = new MemoryAlloc[16];

            Rand rand = new Rand();
            for (int i = 0; i < maArr.Length; i++)
            {
                maArr[i] = new MemoryAlloc(rand.getRand(500), rand, i);
                maArr[i].AllocTest();
                //Console.WriteLine("{0} allocated", i);
                InducedGen2();

                for (int iAllocated = 0; iAllocated < i; iAllocated++)
                {
                    //Console.WriteLine("creating fragmentation in obj {0}", iAllocated);
                    maArr[iAllocated].CreateFragmentation();
                    InducedGen2();
                }
            }

            for (int i = 0; i < maArr.Length; i++)
            {
                InducedGen2();
                Console.WriteLine("steady state for " + i);
                maArr[i].SteadyState();
                Console.WriteLine("DONE: steady state for " + i);
            }
        }

        tEnd = Environment.TickCount;
        Console.WriteLine("Test completed; " + (tEnd - tStart) + "ms");
        //        Console.WriteLine("Press any key to exit.");
        //        Console.ReadLine();

        return 100;
    }
        public SymbolInformation GetSymbolFromName(string symbolName)
        {
            using (MemoryAlloc data = new MemoryAlloc(SymbolInfo.SizeOf + _maxNameLen))
            {
                SymbolInfo info = new SymbolInfo
                {
                    SizeOfStruct = SymbolInfo.SizeOf, 
                    MaxNameLen = _maxNameLen - 1
                };

                data.WriteStruct(info);

                using (Win32.DbgHelpLock.AcquireContext())
                {
                    if (!Win32.SymFromName(_handle, symbolName, data))
                        Win32.Throw();
                }

                return new SymbolInformation(data, 0);
            }
        }
示例#38
0
        public static string GetVolumeName(string deviceName)
        {
            using (MemoryAlloc data = new MemoryAlloc(MountMgrMountPoint.SizeOf + deviceName.Length * 2))
            {
                MountMgrMountPoint mountPoint = new MountMgrMountPoint
                {
                    DeviceNameLength = (ushort)(deviceName.Length*2), 
                    DeviceNameOffset = MountMgrMountPoint.SizeOf
                };

                data.WriteStruct(mountPoint);
                data.WriteUnicodeString(mountPoint.DeviceNameOffset, deviceName);

                using (var fhandle = OpenMountManager((FileAccess)StandardRights.Synchronize))
                {
                    NtStatus status;
                    int retLength;

                    using (MemoryAlloc outData = new MemoryAlloc(0x100))
                    {
                        while (true)
                        {
                            status = fhandle.IoControl(
                                IoCtlQueryPoints,
                                data.Memory,
                                data.Size,
                                outData.Memory,
                                outData.Size,
                                out retLength
                                );

                            if (status == NtStatus.BufferOverflow)
                            {
                                outData.ResizeNew(Marshal.ReadInt32(outData.Memory)); // read Size field
                                continue;
                            }
                            else
                            {
                                break;
                            }
                        }

                        status.ThrowIf();

                        MountMgrMountPoints mountPoints = outData.ReadStruct<MountMgrMountPoints>();

                        // Go through the mount points given and return the first symbolic link that seems 
                        // to be a volume name.
                        for (int i = 0; i < mountPoints.NumberOfMountPoints; i++)
                        {
                            MountMgrMountPoint mp = outData.ReadStruct<MountMgrMountPoint>(
                                MountMgrMountPoints.MountPointsOffset,
                                MountMgrMountPoint.SizeOf,
                                i
                                );

                            string symLinkName = Marshal.PtrToStringUni(
                                outData.Memory.Increment(mp.SymbolicLinkNameOffset),
                                mp.SymbolicLinkNameLength / 2
                                );

                            if (IsVolumePath(symLinkName))
                                return symLinkName;
                        }

                        return null;
                    }
                }
            }
        }
示例#39
0
        private static void Notify(bool created, string sourceVolumeName, string targetVolumeName)
        {
            using (MemoryAlloc data = new MemoryAlloc(
                MountMgrVolumeMountPoint.SizeOf +
                sourceVolumeName.Length * 2 +
                targetVolumeName.Length * 2
                ))
            {
                MountMgrVolumeMountPoint mountPoint = new MountMgrVolumeMountPoint
                {
                    SourceVolumeNameLength = (ushort)(sourceVolumeName.Length * 2), 
                    SourceVolumeNameOffset = (ushort)MountMgrVolumeMountPoint.SizeOf, 
                    TargetVolumeNameLength = (ushort)(targetVolumeName.Length * 2)
                };

                mountPoint.TargetVolumeNameOffset = (ushort)(mountPoint.SourceVolumeNameOffset + mountPoint.SourceVolumeNameLength);

                data.WriteStruct(mountPoint);
                data.WriteUnicodeString(mountPoint.SourceVolumeNameOffset, sourceVolumeName);
                data.WriteUnicodeString(mountPoint.TargetVolumeNameOffset, targetVolumeName);

                using (FileHandle fhandle = OpenMountManager(FileAccess.GenericRead | FileAccess.GenericWrite))
                {
                    fhandle.IoControl(
                        created ? IoCtlVolumeMountPointCreated : IoCtlVolumeMountPointDeleted,
                        data.Memory,
                        data.Size,
                        IntPtr.Zero,
                        0
                        );
                }
            }
        }
示例#40
0
        public static bool PromptForCredentials(
            IWin32Window parent,
            string messageText,
            string captionText,
            string targetName,
            Win32Error errorCode,
            ref string userName,
            ref string password,
            ref bool save,
            CredUiFlags flags
            )
        {
            const int maxBytes = 0x200;
            const int maxChars = (maxBytes - 2) / 2;

            Win32Error result;
            CredUiInfo info = new CredUiInfo();

            if (userName.Length > maxChars || password.Length > maxChars)
                throw new ArgumentException("The user name or password string is too long.");

            info.Size = System.Runtime.InteropServices.Marshal.SizeOf(typeof(CredUiInfo));
            info.Parent = parent != null ? parent.Handle : IntPtr.Zero;
            info.MessageText = messageText;
            info.CaptionText = captionText;

            using (var userNameAlloc = new MemoryAlloc(maxBytes))
            using (var passwordAlloc = new MemoryAlloc(maxBytes))
            {
                userNameAlloc.WriteUnicodeString(0, userName);
                userNameAlloc.WriteInt16(userName.Length * 2, 0);
                passwordAlloc.WriteUnicodeString(0, password);
                passwordAlloc.WriteInt16(password.Length * 2, 0);

                result = Win32.CredUIPromptForCredentials(
                    ref info,
                    targetName,
                    IntPtr.Zero,
                    errorCode,
                    userNameAlloc,
                    maxBytes / 2,
                    passwordAlloc,
                    maxBytes / 2,
                    ref save,
                    flags
                    );

                if (result == Win32Error.Cancelled)
                    return false;
                if (result != Win32Error.Success)
                    Win32.Throw(result);

                userName = userNameAlloc.ReadUnicodeString(0);
                password = passwordAlloc.ReadUnicodeString(0);

                return true;
            }
        }
        public MemoryRegion GetAuthData()
        {
            string lDomainName = !string.IsNullOrEmpty(_domainName) ? _domainName : string.Empty;
            string lUserName = !string.IsNullOrEmpty(_userName) ? _userName : string.Empty;
            string lPassword = !string.IsNullOrEmpty(_password) ? _password : string.Empty;

            // The structure plus the strings must be stored in the same buffer, 
            // so we have to do some computation.

            int domainNameOffset = Msv1_0_InteractiveLogon.SizeOf;
            int userNameOffset = domainNameOffset + lDomainName.Length * 2;
            int passwordOffset = userNameOffset + lUserName.Length * 2;
            int dataSize = passwordOffset + lPassword.Length * 2;

            MemoryAlloc data = new MemoryAlloc(dataSize);

            Msv1_0_InteractiveLogon info = new Msv1_0_InteractiveLogon
            {
                MessageType = Msv1_0_LogonSubmitType.Interactive
            };

            info.LogonDomainName.MaximumLength = info.LogonDomainName.Length = (ushort)(lDomainName.Length * 2);
            info.LogonDomainName.Buffer = data.Memory.Increment(domainNameOffset);
            data.WriteUnicodeString(domainNameOffset, lDomainName);

            info.UserName.MaximumLength = info.UserName.Length = (ushort)(lUserName.Length * 2);
            info.UserName.Buffer = data.Memory.Increment(userNameOffset);
            data.WriteUnicodeString(userNameOffset, lUserName);

            info.Password.MaximumLength = info.Password.Length = (ushort)(lPassword.Length * 2);
            info.Password.Buffer = data.Memory.Increment(passwordOffset);
            data.WriteUnicodeString(passwordOffset, lPassword);

            data.WriteStruct(info);

            return data;
        }
        /// <summary>
        /// Creates a copy of the security descriptor in self-relative form.
        /// </summary>
        /// <returns>A new self-relative security descriptor.</returns>
        public SecurityDescriptor ToSelfRelative()
        {
            using (MemoryAlloc data = new MemoryAlloc(Win32.SecurityDescriptorMinLength))
            {
                int retLength = data.Size;

                NtStatus status = Win32.RtlMakeSelfRelativeSD(this, data, ref retLength);

                if (status == NtStatus.BufferTooSmall)
                {
                    data.ResizeNew(retLength);
                    status = Win32.RtlMakeSelfRelativeSD(this, data, ref retLength);
                }

                status.ThrowIf();

                return new SecurityDescriptor(data);
            }
        }
示例#43
0
        public MemoryAlloc ToMemory()
        {
            MemoryAlloc data = new MemoryAlloc(PortMessageStruct.SizeOf + _message.DataLength);

            data.WriteStruct(_message);
            data.WriteMemory(PortMessageStruct.SizeOf, _data, _message.DataLength);

            return data;
        }
示例#44
0
        public MemoryAlloc ToMemory()
        {
            MemoryAlloc data = new MemoryAlloc(_portMessageSize + _message.DataLength);

            data.WriteStruct<PortMessageStruct>(_message);
            data.WriteMemory(_portMessageSize, _data, 0, _message.DataLength);

            return data;
        }
示例#45
0
        public string GetSymbolFromAddress(ulong address, out SymbolResolveLevel level, out SymbolFlags flags, out string fileName, out string symbolName, out ulong displacement)
        {
            // Assume failure (and stop the compiler from complaining).
            if (address == 0)
            {
                level = SymbolResolveLevel.Invalid;
                flags = 0;
                fileName = null;
            }

            // Allocate some memory for the symbol information.
            using (var data = new MemoryAlloc(Marshal.SizeOf(typeof(SymbolInfo)) + _maxNameLen))
            {
                var info = new SymbolInfo();

                info.SizeOfStruct = Marshal.SizeOf(info);
                info.MaxNameLen = _maxNameLen - 1;

                Marshal.StructureToPtr(info, data, false);

                // Hack for drivers, since we don't get their module sizes. 
                // Preloading modules will fix this.
                if (this.PreloadModules)
                {
                    ulong b;

                    this.GetModuleFromAddress(address, out b);

                    using (Win32.DbgHelpLock.AcquireContext())
                        Win32.SymFromAddr(_handle, b, out displacement, data);

                    Marshal.StructureToPtr(info, data, false);
                }

                // Get the symbol name.
                using (Win32.DbgHelpLock.AcquireContext())
                {
                    if (Win32.SymFromAddr(_handle, address, out displacement, data))
                    {
                        info = data.ReadStruct<SymbolInfo>();
                    }
                }

                string modFileName;
                ulong modBase;

                // Get the module name.
                if (info.ModBase == 0)
                {
                    modFileName = this.GetModuleFromAddress(address, out modBase);
                }
                else
                {
                    modBase = info.ModBase;

                    lock (_modules)
                        modFileName = _modules.Find(kvp => kvp.Key == info.ModBase).Value;
                }

                // If we don't have a module name, return an address.
                if (modFileName == null)
                {
                    level = SymbolResolveLevel.Address;
                    flags = 0;
                    fileName = null;
                    symbolName = null;

                    return Utils.FormatAddress(address);
                }

                FileInfo fi = null;

                fileName = modFileName;

                try
                {
                    fi = new FileInfo(modFileName);
                    fileName = fi.FullName;
                }
                catch
                { }

                // If we have a module name but not a symbol name, 
                // return a module plus an offset: module+offset.
                if (info.NameLen == 0)
                {
                    level = SymbolResolveLevel.Module;
                    flags = 0;
                    symbolName = null;

                    if (fi != null)
                    {
                        return fi.Name + "+0x" + (address - modBase).ToString("x");
                    }
                    else
                    {
                        var s = modFileName.Split('\\');

                        return s[s.Length - 1] + "+0x" + (address - modBase).ToString("x");
                    }
                }

                // If we have everything, return the full symbol name: module!symbol+offset.
                string name = data.ReadAnsiString(SymbolInfo.NameOffset, info.NameLen);

                level = SymbolResolveLevel.Function;
                flags = info.Flags;
                symbolName = name;

                if (displacement == 0)
                    return fi.Name + "!" + name;
                else
                    return fi.Name + "!" + name + "+0x" + displacement.ToString("x");
            }
        }
示例#46
0
 public SecurityDescriptor ToSelfRelative()
 {
     NtStatus status;
     int retLength;
     using (var data = new MemoryAlloc(Win32.SecurityDescriptorMinLength))
     {
         retLength = data.Size;
         status = Win32.RtlMakeSelfRelativeSD(this, data, ref retLength);
         if (status == NtStatus.BufferTooSmall)
         {
             data.Resize(retLength);
             status = Win32.RtlMakeSelfRelativeSD(this, data, ref retLength);
         }
         if (status >= NtStatus.Error)
             Win32.ThrowLastError(status);
         return new SecurityDescriptor(data);
     }
 }
示例#47
0
        public static bool Wait(string name, long timeout, bool relative)
        {
            using (var npfsHandle = new FileHandle(
                Win32.NamedPipePath + "\\",
                FileShareMode.ReadWrite,
                FileCreateOptions.SynchronousIoNonAlert,
                FileAccess.ReadAttributes | (FileAccess)StandardRights.Synchronize
                ))
            {
                using (var data = new MemoryAlloc(FilePipeWaitForBuffer.NameOffset + name.Length * 2))
                {
                    FilePipeWaitForBuffer info = new FilePipeWaitForBuffer();

                    info.Timeout = timeout;
                    info.TimeoutSpecified = true;
                    info.NameLength = name.Length * 2;
                    data.WriteStruct<FilePipeWaitForBuffer>(info);
                    data.WriteUnicodeString(FilePipeWaitForBuffer.NameOffset, name);

                    NtStatus status;
                    int returnLength;

                    status = npfsHandle.FsControl(FsCtlWait, data, data.Size, IntPtr.Zero, 0, out returnLength);

                    if (status == NtStatus.IoTimeout)
                        return false;

                    if (status >= NtStatus.Error)
                        Win32.ThrowLastError(status);

                    return true;
                }
            }
        }
示例#48
0
        public int Peek(IntPtr buffer, int length, out int bytesAvailable, out int bytesLeftInMessage)
        {
            using (var data = new MemoryAlloc(FilePipePeekBuffer.DataOffset + length))
            {
                NtStatus status;
                int returnLength;

                status = this.FsControl(FsCtlPeek, IntPtr.Zero, 0, data, data.Size, out returnLength);

                // If we got a buffer overflow it simply means we didn't 
                // read all of the available bytes.
                if (status == NtStatus.BufferOverflow)
                    status = NtStatus.Success;

                if (status >= NtStatus.Error)
                    Win32.ThrowLastError(status);

                FilePipePeekBuffer info = data.ReadStruct<FilePipePeekBuffer>();
                int bytesRead;

                bytesAvailable = info.ReadDataAvailable;
                bytesRead = returnLength - FilePipePeekBuffer.DataOffset;
                bytesLeftInMessage = info.MessageLength - bytesRead;

                if (buffer != IntPtr.Zero)
                    data.ReadMemory(buffer, 0, FilePipePeekBuffer.DataOffset, bytesRead);

                return bytesRead;
            }
        }
示例#49
0
        public static MibUdpTableOwnerPid GetUdpTable()
        {
            MibUdpTableOwnerPid table = new MibUdpTableOwnerPid();
            int length = 0;

            GetExtendedUdpTable(IntPtr.Zero, ref length, false, AiFamily.INet, UdpTableClass.OwnerPid, 0);

            using (MemoryAlloc mem = new MemoryAlloc(length))
            {
                GetExtendedUdpTable(mem, ref length, false, AiFamily.INet, UdpTableClass.OwnerPid, 0);
                        
                int count = mem.ReadInt32(0);

                table.NumEntries = count;
                table.Table = new MibUdpRowOwnerPid[count];

                for (int i = 0; i < count; i++)
                    table.Table[i] = mem.ReadStruct<MibUdpRowOwnerPid>(sizeof(int), i);
            }

            return table;
        }
示例#50
0
        public SymbolInformation GetSymbolFromName(string symbolName)
        {
            using (var data = new MemoryAlloc(Marshal.SizeOf(typeof(SymbolInfo)) + _maxNameLen))
            {
                var info = new SymbolInfo();

                info.SizeOfStruct = Marshal.SizeOf(info);
                info.MaxNameLen = _maxNameLen - 1;

                Marshal.StructureToPtr(info, data, false);

                using (Win32.DbgHelpLock.AcquireContext())
                {
                    if (!Win32.SymFromName(_handle, symbolName, data))
                        Win32.Throw();
                }

                return new SymbolInformation(data, 0);
            }
        }
示例#51
0
        public string GetVariable(string name)
        {
            NtStatus status;
            UnicodeString nameStr;
            UnicodeString valueStr;

            nameStr = new UnicodeString(name);

            try
            {
                using (var data = new MemoryAlloc(100))
                {
                    valueStr = new UnicodeString();
                    valueStr.Buffer = data;
                    valueStr.MaximumLength = (ushort)data.Size;

                    status = Win32.RtlQueryEnvironmentVariable_U(
                        this,
                        ref nameStr,
                        ref valueStr
                        );

                    if (status == NtStatus.BufferTooSmall)
                    {
                        // Resize and try again (+2 for the null terminator).
                        data.ResizeNew(valueStr.Length + 2);
                        valueStr.Buffer = data;
                        valueStr.MaximumLength = (ushort)(valueStr.Length + 2);

                        status = Win32.RtlQueryEnvironmentVariable_U(
                            this,
                            ref nameStr,
                            ref valueStr
                            );
                    }

                    if (status >= NtStatus.Error)
                        Win32.Throw(status);

                    return valueStr.Read();
                }
            }
            finally
            {
                nameStr.Dispose();
            }
        }
示例#52
0
        private static void DeleteSymbolicLink(string path)
        {
            using (MemoryAlloc data = new MemoryAlloc(MountMgrMountPoint.SizeOf + path.Length * 2))
            using (MemoryAlloc outData = new MemoryAlloc(1600))
            {
                MountMgrMountPoint mountPoint = new MountMgrMountPoint
                {
                    SymbolicLinkNameLength = (ushort)(path.Length*2), 
                    SymbolicLinkNameOffset = MountMgrMountPoint.SizeOf
                };

                data.WriteStruct(mountPoint);
                data.WriteUnicodeString(mountPoint.SymbolicLinkNameOffset, path);

                using (var fhandle = OpenMountManager(FileAccess.GenericRead | FileAccess.GenericWrite))
                {
                    fhandle.IoControl(IoCtlDeletePoints, data.Memory, data.Size, outData.Memory, outData.Size);
                }
            }
        }
示例#53
0
        public static string GetDeviceName(FileHandle fhandle)
        {
            using (MemoryAlloc data = new MemoryAlloc(600))
            {
                fhandle.IoControl(IoCtlQueryDeviceName, IntPtr.Zero, 0, data, data.Size);

                MountDevName name = data.ReadStruct<MountDevName>();

                return data.ReadUnicodeString(MountDevName.NameOffset, name.NameLength / 2);
            }
        }
示例#54
0
        private static string GetReparsePointTarget(FileHandle fhandle)
        {
            using (MemoryAlloc data = new MemoryAlloc(FileSystem.MaximumReparseDataBufferSize))
            {
                fhandle.IoControl(FileSystem.FsCtlGetReparsePoint, IntPtr.Zero, 0, data, data.Size);

                FileSystem.ReparseDataBuffer buffer = data.ReadStruct<FileSystem.ReparseDataBuffer>();

                // Make sure it is in fact a mount point.
                if (buffer.ReparseTag != (uint)IoReparseTag.MountPoint)
                    Win32.Throw(NtStatus.InvalidParameter);

                return data.ReadUnicodeString(
                    FileSystem.ReparseDataBuffer.MountPointPathBuffer + buffer.SubstituteNameOffset,
                    buffer.SubstituteNameLength / 2
                    );
            }
        }
示例#55
0
        public string GetSymbolFromAddress(ulong address, out SymbolResolveLevel level, out SymbolFlags flags, out string fileName, out string symbolName, out ulong displacement)
        {
            if (address == 0)
            {
                level = SymbolResolveLevel.Invalid;
                flags = 0;
                fileName = null;
            }

            using (var data = new MemoryAlloc(Marshal.SizeOf(typeof(SymbolInfo)) + _maxNameLen))
            {
                var info = new SymbolInfo();

                info.SizeOfStruct = Marshal.SizeOf(info);
                info.MaxNameLen = _maxNameLen - 1;

                Marshal.StructureToPtr(info, data, false);

                if (this.PreloadModules)
                {
                    ulong b;

                    this.GetModuleFromAddress(address, out b);

                    using (Win32.DbgHelpLock.AcquireContext())
                        Win32.SymFromAddr(_handle, b, out displacement, data);

                    Marshal.StructureToPtr(info, data, false);
                }

                using (Win32.DbgHelpLock.AcquireContext())
                {
                    if (Win32.SymFromAddr(_handle, address, out displacement, data))
                    {
                        info = data.ReadStruct<SymbolInfo>();
                    }
                }

                string modFileName;
                ulong modBase;

                if (info.ModBase == 0)
                {
                    modFileName = this.GetModuleFromAddress(address, out modBase);
                }
                else
                {
                    modBase = info.ModBase;

                    lock (_modules)
                        modFileName = _modules.Find(kvp => kvp.Key == info.ModBase).Value;
                }

                if (modFileName == null)
                {
                    level = SymbolResolveLevel.Address;
                    flags = 0;
                    fileName = null;
                    symbolName = null;

                    return Utils.FormatAddress(address);
                }

                FileInfo fi = null;

                fileName = modFileName;

                try
                {
                    fi = new FileInfo(modFileName);
                    fileName = fi.FullName;
                }
                catch
                { }

                if (info.NameLen == 0)
                {
                    level = SymbolResolveLevel.Module;
                    flags = 0;
                    symbolName = null;

                    if (fi != null)
                    {
                        return fi.Name + "+0x" + (address - modBase).ToString("x");
                    }
                    else
                    {
                        var s = modFileName.Split('\\');

                        return s[s.Length - 1] + "+0x" + (address - modBase).ToString("x");
                    }
                }

                string name = Marshal.PtrToStringAnsi(data.Memory.Increment(Win32.SymbolInfoNameOffset), info.NameLen);

                level = SymbolResolveLevel.Function;
                flags = info.Flags;
                symbolName = name;

                if (displacement == 0)
                    return fi.Name + "!" + name;
                else
                    return fi.Name + "!" + name + "+0x" + displacement.ToString("x");
            }
        }
示例#56
-1
        /// <summary>
        /// Gets the security descriptor of a kernel object.
        /// </summary>
        /// <param name="handle">A handle to a kernel object.</param>
        /// <param name="securityInformation">The information to retrieve.</param>
        /// <returns>A security descriptor.</returns>
        public static SecurityDescriptor GetSecurity(IntPtr handle, SecurityInformation securityInformation)
        {
            NtStatus status;
            int retLength;

            using (var data = new MemoryAlloc(0x100))
            {
                status = Win32.NtQuerySecurityObject(
                    handle,
                    securityInformation,
                    data,
                    data.Size,
                    out retLength
                    );

                if (status == NtStatus.BufferTooSmall)
                {
                    data.Resize(retLength);

                    status = Win32.NtQuerySecurityObject(
                        handle,
                        securityInformation,
                        data,
                        data.Size,
                        out retLength
                        );
                }

                if (status >= NtStatus.Error)
                    Win32.ThrowLastError(status);

                return new SecurityDescriptor(data);
            }
        }
        /// <summary>
        /// Gets the security descriptor of a kernel object.
        /// </summary>
        /// <param name="handle">A handle to a kernel object.</param>
        /// <param name="securityInformation">The information to retrieve.</param>
        /// <returns>A security descriptor.</returns>
        public static SecurityDescriptor GetSecurity(IntPtr handle, SecurityInformation securityInformation)
        {
            using (MemoryAlloc data = new MemoryAlloc(0x100))
            {
                int retLength;

                NtStatus status = Win32.NtQuerySecurityObject(
                    handle,
                    securityInformation,
                    data,
                    data.Size,
                    out retLength
                    );

                if (status == NtStatus.BufferTooSmall)
                {
                    data.ResizeNew(retLength);

                    Win32.NtQuerySecurityObject(
                        handle,
                        securityInformation,
                        data,
                        data.Size,
                        out retLength
                        ).ThrowIf();
                }

                status.ThrowIf();

                return new SecurityDescriptor(data);
            }
        }