public override int GetHashCode()
        {
            int hash = 1;

            if (TaskID != 0)
            {
                hash ^= TaskID.GetHashCode();
            }
            if (MaxDoneCount != 0)
            {
                hash ^= MaxDoneCount.GetHashCode();
            }
            if (TaskName.Length != 0)
            {
                hash ^= TaskName.GetHashCode();
            }
            if (TaskDesc.Length != 0)
            {
                hash ^= TaskDesc.GetHashCode();
            }
            if (FinishConditionID != 0)
            {
                hash ^= FinishConditionID.GetHashCode();
            }
            if (TargetProcess != 0)
            {
                hash ^= TargetProcess.GetHashCode();
            }
            hash ^= condStageTaskAward_.GetHashCode();
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
Exemplo n.º 2
0
        public bool Execute(ProcessSettings settings)
        {
            if (settings.IsStreamingAssets)
            {
                settings.FileName = Path.Combine(Application.streamingAssetsPath, settings.FileName);
            }
            else
            {
                if (settings.IsRelativePath)
                {
                    settings.FileName = Path.GetFullPath(settings.FileName);
                }
            }

            if (!settings.IsCommand)
            {
                if (!File.Exists(settings.FileName))
                {
                    return(false);
                }
            }

            TargetProcess = ProcessUtils.CreateProcess(settings);


            if (TargetProcess.EnableRaisingEvents)
            {
                TargetProcess.Exited += Process_Exited;
            }
            if (TargetProcess.StartInfo.RedirectStandardOutput)
            {
                TargetProcess.OutputDataReceived += Process_OutputDataReceived;
            }
            if (TargetProcess.StartInfo.RedirectStandardError)
            {
                TargetProcess.ErrorDataReceived += Process_ErrorDataReceived;
            }

            var result = TargetProcess.Start();

            if (result)
            {
                if (TargetProcess.StartInfo.RedirectStandardOutput)
                {
                    TargetProcess.BeginOutputReadLine();
                }
                if (TargetProcess.StartInfo.RedirectStandardError)
                {
                    TargetProcess.BeginErrorReadLine();
                }
                this.ProcessId   = TargetProcess.Id;
                this.ProcessName = TargetProcess.ProcessName;
            }
            else
            {
                DisposeProcess();
            }

            return(result);
        }
Exemplo n.º 3
0
        public UInt32 MapImage(string imageName, byte[] rawImage)
        {
            Log.LogInfo($"Mapping {imageName}");

            // GET HEADERS
            Tools.GetImageHeaders(rawImage, out NT.IMAGE_DOS_HEADER dosHeader, out NT.IMAGE_FILE_HEADER fileHeader, out NT.IMAGE_OPTIONAL_HEADER64 optionalHeader);

            // CREATE A MEMORY SECTION IN TARGET PROCESS
            UInt32 sectionHandle = (UInt32)TargetProcess.CreateSection(NT.MemoryProtection.ExecuteReadWrite, optionalHeader.SizeOfImage);

            // MAP THE SECTION INTO BOTH OUR OWN AND THE TARGET PROCESS
            // THIS WILL RESULT IN A MIRRORED MEMORY SECTION, WHERE EVERY CHANGE
            // TO THE LOCAL SECTION WILL ALSO CHANGE IN THE TARGET PROCESS
            // AND VICE VERSA
            UInt32 remoteImage = (UInt32)TargetProcess.MapSection(sectionHandle, NT.MemoryProtection.ExecuteReadWrite);
            UInt32 localImage  = (UInt32)Process.GetCurrentProcess().MapSection(sectionHandle, NT.MemoryProtection.ExecuteReadWrite);

            // SAVE MAPPED EXECUTABLES IN A LIST
            // SO WE CAN RECURSIVELY MAP DEPENDENCIES, AND THEIR DEPENDENCIES
            // WITHOUT BEING STUCK IN A LOOP :)
            MappedModules[imageName]   = remoteImage;
            MappedRawImages[imageName] = rawImage;

            // ADD LOADER REFERENCE
            if (imageName == Options.LoaderImagePath)
            {
                if (Options.CreateLoaderReference)
                {
                    AddLoaderEntry(imageName, remoteImage);
                }
            }
            else // ALWAYS CREATE REFERENCE FOR DEPENDENCIES
            {
                AddLoaderEntry(imageName, remoteImage);
            }

            // COPY HEADERS TO SECTION
            Marshal.Copy(rawImage, 0, (IntPtr)localImage, (int)optionalHeader.SizeOfHeaders);

            // DO THE ACTUAL MANUALMAPPING
            this.WriteImageSections(rawImage, dosHeader, localImage, fileHeader.NumberOfSections);
            this.RelocateImageByDelta(localImage, remoteImage, optionalHeader);
            this.FixImportTable(localImage, optionalHeader);

            // NUKE HEADERS
            // TODO: DONT WRITE THEM IN THE FIRST PLACE
            if (Options.EraseHeaders)
            {
                byte[] headerBuffer = new byte[(int)optionalHeader.SizeOfHeaders];
                NTM.RandomEngine.NextBytes(headerBuffer);

                Marshal.Copy(headerBuffer, 0, (IntPtr)localImage, (int)optionalHeader.SizeOfHeaders);
            }

            NT.CloseHandle(sectionHandle);
            Process.GetCurrentProcess().UnmapSection(localImage);

            return(remoteImage);
        }
Exemplo n.º 4
0
 private void KillTargetProcess()
 {
     if (TargetProcess != null)
     {
         TargetProcess.Kill();
     }
     TargetProcess = null;
 }
Exemplo n.º 5
0
        public override void Attack()
        {
            TargetProcess targetProcess = new TargetProcess();
            targetProcess.GeneralID = TagetGeneral.GeneralID;
            targetProcess.Position = TagetGeneral.Position.ToShort();
            targetProcess.Role = TagetRole;
            targetProcess.LiveNum = TagetGeneral.LifeNum;
            targetProcess.Momentum = TagetGeneral.Momentum;

            ProccessExtendAttack();
            int damageNum = GetPhysicalDamageNum(TagetGeneral);
            decimal hitPercent = 0;
            bool isHit = General.TriggerHitPercent(TagetGeneral, out hitPercent);
            ProcessLog.AddPercent(1, hitPercent);
            if (isHit)
            {

                targetProcess.IsShanBi = false;
                //普通攻击\防御加气势
                General.Momentum = MathUtils.Addition(General.Momentum, MomentumAttack, short.MaxValue);
                if (!TagetGeneral.IsJueduifangyuStatus)
                {
                    TagetGeneral.Momentum = MathUtils.Addition(TagetGeneral.Momentum, MomentumDefense, short.MaxValue);
                }
                DoTargetDefense(damageNum, targetProcess, false);
                //攻击加血
                decimal attackLife = TrumpAbilityAttack.GetEffect(General, AbilityType.AttackLife);
                if (attackLife > 0)
                {
                    ProcessLog.TrumpStatusList.Add(TrumpAbilityAttack.GetSkillprocess(AbilityType.AttackLife, -(int)(damageNum * attackLife)));
                    General.LifeNum = (int)Math.Floor(MathUtils.Addition(General.LifeNum, damageNum * attackLife, General.LifeMaxNum));
                }

                //反伤
                decimal fangShang = TrumpAbilityAttack.GetEffect(TagetGeneral, AbilityType.FanShang);
                if (fangShang > 0)
                {
                    int num = (int)(damageNum * fangShang);
                    targetProcess.TrumpStatusList.Add(TrumpAbilityAttack.GetSkillprocess(AbilityType.FanShang, num));
                    General.LifeNum = (int)Math.Floor(MathUtils.Subtraction(General.LifeNum, damageNum * fangShang));
                }
            }
            else
            {
                targetProcess.IsShanBi = true;
                TagetGeneral.TriggerShanBi();
            }
            targetProcess.Momentum = TagetGeneral.Momentum;
            targetProcess.TargetStatus = TagetGeneral.BattleStatus;
            ProcessLog.Momentum = General.Momentum;
            ProcessLog.LiveNum = General.LifeNum;
            ProcessLog.AttStatus = General.BattleStatus;
            ProcessLog.IsMove = General.IsMove;
            ProcessLog.TargetList.Add(targetProcess);
        }
Exemplo n.º 6
0
        // GOOD LUCK
        // http://i.imgur.com/7mTXRAF.jpg
        public void AddLoaderEntry(string imageName, ulong moduleHandle)
        {
            Log.LogInfo($"Linking {imageName}({moduleHandle.ToString("x2")}) to module list");

            var imagePath = Tools.FindDll(imageName) ?? imageName;

            var listBase         = TargetProcess.GetLoaderData().InLoadOrderModuleList;
            var lastEntry        = TargetProcess.Read <NT._LDR_DATA_TABLE_ENTRY>(listBase.Blink);
            var allocatedDllPath = TargetProcess.AllocateAndWrite(Encoding.Unicode.GetBytes(imagePath), NT.AllocationType.Commit, NT.MemoryProtection.ExecuteReadWrite);

            // CRAFT CUSTOM LOADER ENTRY
            var fileName = Path.GetFileName(imagePath);

            NT._LDR_DATA_TABLE_ENTRY myEntry = new NT._LDR_DATA_TABLE_ENTRY()
            {
                InLoadOrderLinks = new NT._LIST_ENTRY()
                {
                    Flink = lastEntry.InLoadOrderLinks.Flink,
                    Blink = listBase.Flink
                },
                InMemoryOrderLinks         = lastEntry.InMemoryOrderLinks,
                InInitializationOrderLinks = lastEntry.InInitializationOrderLinks,
                DllBase     = moduleHandle,
                EntryPoint  = 0,
                SizeOfImage = (ulong)MappedRawImages[imageName].Length,
                FullDllName = new NT.UNICODE_STRING(imagePath)
                {
                    Buffer = allocatedDllPath
                },
                BaseDllName = new NT.UNICODE_STRING(fileName)
                {
                    Buffer = allocatedDllPath + (ulong)imagePath.IndexOf(fileName) * 2                                            /*WIDE CHAR*/
                },
                Flags         = lastEntry.Flags,
                LoadCount     = lastEntry.LoadCount,
                TlsIndex      = lastEntry.TlsIndex,
                Reserved4     = lastEntry.Reserved4,
                CheckSum      = lastEntry.CheckSum,
                TimeDateStamp = lastEntry.TimeDateStamp,
                EntryPointActivationContext = lastEntry.EntryPointActivationContext,
                PatchInformation            = lastEntry.PatchInformation,
                ForwarderLinks  = lastEntry.ForwarderLinks,
                ServiceTagLinks = lastEntry.ServiceTagLinks,
                StaticLinks     = lastEntry.StaticLinks,
            };

            // ALLOCATE AND WRITE OUR MODULE ENTRY
            var newEntryPointer = TargetProcess.AllocateAndWrite(Tools.GetBytes(myEntry), NT.AllocationType.Commit, NT.MemoryProtection.ExecuteReadWrite);

            // SET LAST LINK IN InLoadOrderLinks CHAIN TO POINT TO OUR ENTRY
            lastEntry.InLoadOrderLinks.Flink = newEntryPointer;
            TargetProcess.Write(lastEntry, listBase.Blink);
        }
Exemplo n.º 7
0
 public void DisposeProcess()
 {
     if (TargetProcess != null)
     {
         if (!TargetProcess.HasExited)
         {
             TargetProcess.CancelErrorRead();
             TargetProcess.CancelOutputRead();
             TargetProcess.Kill();
             TargetProcess.Dispose();
         }
         TargetProcess = null;
     }
 }
Exemplo n.º 8
0
        public override void Attack()
        {
            General.Momentum = 0;
            var targetProcess = new TargetProcess();
            targetProcess.GeneralID = TagetGeneral.GeneralID;
            targetProcess.Position = TagetGeneral.Position.ToShort();
            targetProcess.Role = TagetRole;
            targetProcess.LiveNum = TagetGeneral.LifeNum;
            targetProcess.Momentum = TagetGeneral.Momentum;

            ProcessLog.AttackUnit = _ability.AttackUnit;
            ProcessLog.AttackType = _ability.AttackType;
            ProcessLog.AttackTaget = _ability.AttackTaget;
            ProcessLog.AbilityProperty = _ability.AbilityProperty;
            ProcessLog.AttEffectID = _ability.EffectID1;
            ProcessLog.TargetEffectID = _ability.EffectID2;
            ProcessLog.FntHeadID = _ability.FntHeadID;
            ProcessLog.AbilityID = _ability.AbilityID;
            ProccessExtendAttack();
            DoAbilityStatus(targetProcess);

            TagetGeneral.ForeachAbilityStatus(effectStatus =>
            {
                //增减技能不加入
                if (effectStatus.TotalBoutNum == effectStatus.BoutNum ||
                    (!effectStatus.IsZengyi && effectStatus.AbilityType != AbilityType.Qishi))
                {
                    if (effectStatus.BoutNum > 0)
                    {
                        targetProcess.DamageStatusList.Add(effectStatus.Copy());
                    }
                }
            });
            targetProcess.TargetStatus = TagetGeneral.BattleStatus;
            
            ProcessLog.TargetList.Add(targetProcess);
            ProcessLog.Momentum = General.Momentum;
            ProcessLog.LiveNum = General.LifeNum;
            ProcessLog.AttStatus = General.BattleStatus;
            ProcessLog.IsMove = General.TempAbility.IsMove;
            string[] abilityTypeArray = _ability.AbilityType.Split(',');
            foreach (var s in abilityTypeArray)
            {

                General.Momentum = s.ToInt() == AbilityType.Qishi.ToInt()
                                       ? MathUtils.Addition(General.Momentum, _ability.BaseEffectNum.ToShort())
                                       : General.Momentum;
            }
        }
Exemplo n.º 9
0
        public bool InjectImage(byte[] rawImage)
        {
            // GET CURRENTLY LINKED MODULES FOR LATER USE (SPEED BABY)
            LinkedModules = TargetProcess.GetModules();

            // MAP OUR DLL, AND DEPENDENCIES, INTO REMOTE PROCESS
            UInt32 remoteImage = MapImage(Options.LoaderImagePath, rawImage);

            Log.LogVariable("Remote Image", remoteImage.ToString("x2"));

            CallEntrypoint(rawImage, remoteImage);

            // CALL ENTRYPOINTS FOR EVERY MAPPED IMAGE (BACKWARDS, SO OUR IMAGE GETS CALLED LAST)
            // foreach (var image in MappedModules.Reverse())
            // {
            //     Log.LogInfo($"Calling {image.Key} at {image.Value.ToString("x2")}");
            //     CallEntrypoint(MappedRawImages[image.Key], image.Value);
            // }

            return(true);
        }
Exemplo n.º 10
0
        public void Run()
        {
            // Create master thread to manage running threads
            Thread t = new Thread(() =>
            {
                // Create local copies of databases to work with
                SignatureController localSignatures = this.Signatures;
                TargetProcess = Process.ProcessQueue();

                bool loadProcess = false;
                //MaxThreads = 1;
                //MaxThreads /=2;

                // While we are not canceling the whole scan...
                while (!Cancel)
                {
                    while (Pause)
                    {
                        Thread.Sleep(500);

                        // exit
                        if (Cancel == true)
                        {
                            // exit
                            return;
                        }
                    }

                    //detmine number of threads to use when scanning
                    if (Settings.ReducePriority)
                    {
                        this.MaxThreads = Environment.ProcessorCount / 2;
                    }
                    else
                    {
                        this.MaxThreads = Environment.ProcessorCount;
                    }

                    // If all scans have finished and there is nothing left to scan...
                    if (RunningThreads == 0 && TargetFiles.Count() == 0 && TargetProcess.Count() == 0)
                    {
                        // All files have been scanned... time to implement a process scanner....


                        // Attempt to raise event for scan complete
                        // Raise the event
                        ThreatScanComplete?.Invoke(this);

                        // And then exit the loop
                        break;
                    }
                    else if (TargetFiles.Count() == 0 && !loadProcess)
                    {
                        loadProcess = true;
                        // Get a queue of new process...
                        TargetProcess = Process.ProcessQueue();
                    }
                    else
                    {
                        // Check for existing dead threads in the thread list

                        //var dead = ScannerThreads.FirstOrDefault(th => th.ThreadState == ThreadState.Stopped);

                        // // while there are dead threads to remove...
                        // while (dead != null && !Cancel)
                        // {
                        //     // Remove dead thread
                        //     ScannerThreads.Remove(dead);

                        //     // Check for more
                        //     dead = ScannerThreads.FirstOrDefault(th => th.ThreadState == ThreadState.Stopped);
                        // }

                        if (ScannerThreads.Count > 0)
                        {
                            for (int i = 0; i < ScannerThreads.Count; i++)
                            {
                                //if(ScannerThreads[i].ThreadState == ThreadState.Stopped)
                                ScannerThreads[i].Join();
                                ScannerThreads.Remove(ScannerThreads[i]);
                            }
                        }

                        // Clean garbage left behind by scans...
                        GC.Collect();

                        // All target files were scanned... start a process scanning...
                        if (TargetFiles.Count == 0)
                        {
                            // Loop through the process queue time..
                            while (RunningThreads < MaxThreads && TargetProcess.Count > 0 && !Cancel)
                            {
                                // Get next process
                                var target = TargetProcess.Dequeue();

                                // Create a scanner for it..
                                Thread scan = new Thread(() =>
                                {
                                    try
                                    {
                                        // Check white list against process before scanning it
                                        if (Settings.WhiteList.Contains(NativeMethods.GetExecutablePath(target)))
                                        {
                                            return;
                                        }

                                        // Heuristically analyze file first
                                        var heur = BerzerkAPI.IO.Heuristic.Analyze(API.NativeMethods.GetExecutablePath(target));
                                        if (heur != null)
                                        {
                                            ThreatDetectedArgs args = new Controllers.ThreatDetectedArgs()
                                            {
                                                Detection = heur, FilePath = API.NativeMethods.GetExecutablePath(target)
                                            };
                                            ThreatDetected?.Invoke(this, args);
                                        }
                                        else
                                        {
                                            // create a scan of the process
                                            Signature res = Process.ScanProcess(target, ref localSignatures);

                                            // Scan the file and get results
                                            //Signature result = BerzerkAPI.IO.File.ScanFile(target, ref localSignatures, ref localCache);
                                            ScanResultArgs result = BerzerkAPI.IO.File.ScanFile(NativeMethods.GetExecutablePath(target), localSignatures);

                                            // accumulate the total scanned data in MB
                                            ScannedData += (result.Size / 1024) / 1024;

                                            // Check results
                                            if (result.Detection != null)
                                            {
                                                // Attempt to raise detection event

                                                // Create event args
                                                ThreatDetectedArgs args = new ThreatDetectedArgs()
                                                {
                                                    Detection = result.Detection, FilePath = NativeMethods.GetExecutablePath(target)
                                                };
                                                // Raise event ?
                                                ThreatDetected?.Invoke(this, args);
                                            }
                                        } // end of heuristic else

                                        // Try to scan the process
                                        //var result = BerzerkAPI.IO.Process.ScanProcess(target, ref localSignatures);

                                        //// If a threat was found in the process
                                        //if(result != null)
                                        //{
                                        //    ThreatDetectedArgs args = new Controllers.ThreatDetectedArgs()
                                        //    {
                                        //        Detection = result,
                                        //        FilePath = NativeMethods.GetExecutablePath(target)
                                        //    };

                                        //    ThreatDetected?.Invoke(this, args);
                                        //}
                                    }
                                    catch (Exception ex)
                                    {
#if DEBUG
                                        Console.WriteLine(ex.Message);
#endif
                                    }
                                    //ScannerThreads.Remove(Thread.CurrentThread);
                                });


                                // Add thread to list
                                ScannerThreads.Add(scan);

                                // Run thread in bg
                                scan.IsBackground = true;
                                scan.SetApartmentState(ApartmentState.MTA);

                                // Run the scan
                                scan.Start();
                                // scan.Join();
                            }
                        }

                        // Now that we have freed space in the thread list, we need to create new threads
                        // Loop while there is room left for more threads
                        // And while there are files left to scan
                        while (RunningThreads < MaxThreads && TargetFiles.Count > 0 && !Cancel)
                        {
                            // Get the next scannable file
                            string target = TargetFiles.Dequeue();


                            // Create new scan thrad for the next file
                            Thread scan = new Thread(() =>
                            {
                                try
                                {
                                    // Scan the file and get results
                                    //Signature result = BerzerkAPI.IO.File.ScanFile(target, ref localSignatures, ref localCache);
                                    ScanResultArgs result = BerzerkAPI.IO.File.ScanFile(target, localSignatures);

                                    // accumulate the total scanned data in MB
                                    ScannedData += (result.Size / 1024) / 1024;

                                    // Check results
                                    if (result.Detection != null)
                                    {
                                        // Attempt to raise detection event

                                        // Create event args
                                        ThreatDetectedArgs args = new ThreatDetectedArgs()
                                        {
                                            Detection = result.Detection, FilePath = target
                                        };
                                        // Raise event ?
                                        ThreatDetected?.Invoke(this, args);
                                    }

                                    // Sleep thread before ending it to provide some timeout for the cpu
                                    //Thread.Sleep(20);
                                }
                                catch (Exception ex) // debugging purposes
                                {
                                    // something went wrong...
#if DEBUG
                                    Console.WriteLine(ex.Message);
#endif
                                }
                                //ScannerThreads.Remove(Thread.CurrentThread);
                            });

                            // Add thread to list
                            ScannerThreads.Add(scan);

                            // Run thread in bg
                            scan.IsBackground = true;
                            scan.SetApartmentState(ApartmentState.MTA);

                            // Run the scan
                            scan.Start();
                            //scan.Join();
                        }
                    }
                }
            });

            // Set the thread to run in the bg and run it
            t.IsBackground = true;
            t.Start();
        }
Exemplo n.º 11
0
        /// <summary>
        /// 目标防御处理
        /// </summary>
        /// <param name="damageNum">伤害值</param>
        /// <param name="targetProcess"></param>
        /// <param name="isAbility">是否是技能伤害</param>
        protected void DoTargetDefense(int damageNum, TargetProcess targetProcess, bool isAbility)
        {
            //城市公会争斗战疲劳值
            var fatigue = General.Fatigue * GameConfigSet.Fatigue;
            if (fatigue > 0 && General.UserStatus == UserStatus.FightCombat)
            {
                damageNum = (int)Math.Floor(damageNum * (MathUtils.Subtraction(1, fatigue)));
            }

            //生命低于x%,战力加成
            double inspire = (double)TrumpAbilityAttack.GetEffect(General, AbilityType.Furious);
            if (inspire > 0)
            {
                ProcessLog.TrumpStatusList.Add(TrumpAbilityAttack.GetSkillprocess(AbilityType.Furious, 0));
                damageNum = (int)Math.Floor(damageNum * (1 + inspire));
            }

            //鼓舞加成伤害
            if (General.InspirePercent > 0)
            {
                damageNum = (int)Math.Floor(damageNum * (1 + General.InspirePercent));
            }
          
            //是否有爆击
            decimal baojiPercent;
            bool isBaoji = General.TriggerBaojiPercent(TagetGeneral, out baojiPercent);
            ProcessLog.AddPercent(2, baojiPercent);
            if (isBaoji)
            {
                targetProcess.IsBaoji = true;
                damageNum = (int)Math.Floor(damageNum * (1 + BaojiAttack + General.BishaNum));
                //暴击加成
                decimal baojiJiaCheng = TrumpAbilityAttack.GetEffect(General, AbilityType.BaoJiJiaCheng);
                if (baojiJiaCheng > 1)
                {
                    ProcessLog.TrumpStatusList.Add(TrumpAbilityAttack.GetSkillprocess(AbilityType.BaoJiJiaCheng, 0));
                    damageNum = (int)Math.Floor(damageNum * baojiJiaCheng);
                }

                //被暴击减免
                decimal baoJiReduce = TrumpAbilityAttack.GetEffect(TagetGeneral, AbilityType.IsBaoJiReduce);
                if (baoJiReduce < 1 && baoJiReduce > 0)
                {
                    targetProcess.TrumpStatusList.Add(TrumpAbilityAttack.GetSkillprocess(AbilityType.IsBaoJiReduce, 0));
                    damageNum = (int)Math.Floor(damageNum * baoJiReduce);
                }

                if (damageNum >= 0)
                {
                    damageNum = MathUtils.Subtraction(damageNum, 0, General.MinDamageNum);
                }
                else
                {
                    damageNum = -MathUtils.Subtraction(damageNum, 0, General.MinDamageNum);
                }
                //爆击职业加成气势
                CareerAdditionInfo addition = new ShareCacheStruct<CareerAdditionInfo>().FindKey(General.CareerID, AbilityType.BaoJi);
                if (addition != null && !isAbility)
                {
                    General.Momentum = MathUtils.Addition(General.Momentum, addition.MomentumNum.ToShort(), short.MaxValue);
                }
            }

            //排除静默和混乱不能触发格档
            bool isTriggerGedang = TagetGeneral.IsSilentStatus || TagetGeneral.IsHunluanStatus;


            //先触发绝对防御  法宝破盾技能为开启时触发绝对防御
            if (TagetGeneral.IsJueduifangyuStatus)
            {
                if (TrumpAbilityAttack.AttackPoDun(General, AbilityType.AttackPoDun))
                {
                    ProcessLog.TrumpStatusList.Add(TrumpAbilityAttack.GetSkillprocess(AbilityType.AttackPoDun, 0));
                }
                else
                {
                    damageNum = JueduiDefenseDamage;
                }
            }
            else if (!isTriggerGedang)
            {
                //是否产生格挡[?]
                decimal gedangPercent;
                var fangjiNum = 0;
                var isGedang = TagetGeneral.TriggerGeDangPercent(General, out gedangPercent);
                ProcessLog.AddPercent(3, gedangPercent);
                if (isGedang)
                {
                    targetProcess.IsMove = TagetGeneral.IsAttrMove;
                    targetProcess.IsGeDang = true;
                    damageNum = (int)Math.Floor(damageNum * GedangAttackPercent);
                    if (damageNum >= 0)
                    {
                        damageNum = MathUtils.Subtraction(damageNum, 0, General.MinDamageNum);
                    }
                    else
                    {
                        damageNum = -MathUtils.Subtraction(damageNum, 0, General.MinDamageNum);
                    }
                    if (TagetGeneral.CareerType != CareerType.Mofashi &&
                        TagetGeneral.CareerType != CareerType.Shenqiangshou)
                    {
                        AbilityProperty property = General.AbilityProperty;
                        //普通攻击力的50%
                        int attackNum = TagetGeneral.GetAttackNum(property);
                        int defenseNum = General.GetDefenseNum(property, TagetGeneral);
                        int minDamageNum = (int)Math.Ceiling(attackNum * ConfigEnvSet.GetDouble("Combat.MinDamagePencent"));

                        fangjiNum = MathUtils.Subtraction(attackNum, defenseNum, 0);
                        fangjiNum = (int)Math.Floor(fangjiNum * GedangAttackPercent);
                        fangjiNum = MathUtils.Subtraction(fangjiNum, 0, minDamageNum);

                        //没死才可扣反击伤害
                        if (TagetGeneral.LifeNum > damageNum)
                        {
                            General.TriggerDamageNum(fangjiNum);
                            ProcessLog.DamageNum += fangjiNum;
                            ProcessLog.LiveNum = General.LifeNum;
                            ProcessLog.AttStatus = General.BattleStatus;
                            targetProcess.IsBack = true;
                            targetProcess.BackDamageNum = fangjiNum;
                        }
                    }

                    //格挡职业加成气势
                    if (!isAbility)
                    {
                        TagetGeneral.TriggerGeDang();
                    }
                }
            }
            //扣物理攻击伤害
            TagetGeneral.TriggerDamageNum(damageNum);
            targetProcess.DamageNum = damageNum;
            //解除静默状态
            TagetGeneral.RemoveSilentStatus();

            if (TagetGeneral.IsOver)
            {
                //复活
                decimal resurrect = TrumpAbilityAttack.GetEffect(TagetGeneral, AbilityType.Resurrect);
                if (resurrect > 0)
                {
                    targetProcess.TrumpStatusList.Add(TrumpAbilityAttack.GetSkillprocess(AbilityType.Resurrect, -(int)Math.Floor(TagetGeneral.LifeMaxNum * resurrect)));
                    TagetGeneral.LifeNum = (int)Math.Floor(TagetGeneral.LifeMaxNum * resurrect);
                }
                else
                {
                    TrumpAbilityAttack.GeneralOverTrumpLift(TagetGeneral.UserID, TagetGeneral.GeneralID);  //佣兵战斗死亡扣除N点寿命
                    targetProcess.TrumpStatusList = new List<SkillInfo>();
                }
            }

            //记录日志
            targetProcess.TargetStatus = TagetGeneral.BattleStatus;
            targetProcess.Momentum = TagetGeneral.Momentum;
            targetProcess.LiveNum = TagetGeneral.LifeNum;
            TargetProcess = targetProcess;
        }
Exemplo n.º 12
0
        /// <summary>
        /// 伤害类型魂技
        /// </summary>
        /// <param name="targetProcess"></param>
        private void DoHarmAttack(TargetProcess targetProcess)
        {
            if (_ability.AttackType == AttackType.Harm)
            {
                int damageNum;
                if (_ability.AbilityProperty == AbilityProperty.Ability)
                {
                    damageNum = GetAbilityDamageNum(TagetGeneral);
                   
                   
                }
                else
                {
                    damageNum = GetPhysicalDamageNum(TagetGeneral);
                }
                DoTargetDefense(damageNum, targetProcess, true);

            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// 处理技能效果
        /// </summary>
        /// <param name="targetProcess"></param>
        /// <param name="abilityEffectStatus"></param>
        private void ProcessAbilityEffect(TargetProcess targetProcess, AbilityEffectStatus[] abilityEffectStatus)
        {
            foreach (AbilityEffectStatus effect in abilityEffectStatus)
            {
                //立即生效技能

                //没有配置技能效果,处理普通功击
                if (effect.IsSilentStatus)
                {
                    AddDeamgeStatus(effect);
                }
                else if (effect.IsInjuredStatus)
                {
                    //计算持续伤害值
                    if (effect.BoutNum > 0)
                    {
                        if (General.TempAbility.RatioIncreaseNum > 0)
                        {
                            effect.DamageNum = (int)Math.Floor(TagetGeneral.DamageNum * General.TempAbility.RatioIncreaseNum);
                        }
                        else
                        {
                            new BaseLog().SaveLog(new Exception("技能ID:" + General.TempAbility.AbilityID + "续伤害值系数为0"));
                        }
                    }
                    AddDeamgeStatus(effect);
                }
                else if (effect.AbilityType == AbilityType.Hunluan)
                {
                    AddDeamgeStatus(effect);
                }
                else if (effect.AbilityType == AbilityType.ShengMing)
                {
                    effect.BoutNum = 1;//固定一会合
                    AddDeamgeStatus(effect);
                    //加血类不扣防御方,
                    var lifeNum = GetAbilityDamageNum(null);
                    if (effect.IsIncrease)
                    {
                        TagetGeneral.LifeNum += lifeNum;
                    }
                    else
                    {
                        TagetGeneral.LifeNum -= lifeNum;
                    }
                    TagetGeneral.LifeNum = MathUtils.Subtraction(TagetGeneral.LifeNum, 0, 0);
                    TagetGeneral.LifeNum = MathUtils.Addition(TagetGeneral.LifeNum, 0, TagetGeneral.LifeMaxNum);

                    targetProcess.LiveNum = TagetGeneral.LifeNum;
                    targetProcess.DamageNum = effect.IsIncrease ? -lifeNum : lifeNum;//负数客户端是加血
                }
                else if (effect.AbilityType == AbilityType.Qishi)
                {
                    effect.BoutNum = 1;//固定一会合
                    AddDeamgeStatus(effect);
                    //固定值
                    var momentum = effect.BaseNum.ToShort();
                    if (effect.IsIncrease)
                    {
                        TagetGeneral.Momentum += momentum;
                    }
                    else
                    {
                        TagetGeneral.Momentum -= momentum;
                    }
                    TagetGeneral.Momentum = MathUtils.Subtraction(TagetGeneral.Momentum, (short)0, (short)0);
                    TagetGeneral.Momentum = MathUtils.Addition(TagetGeneral.Momentum, (short)0, CombatGeneral.MomentumOut);
                    targetProcess.Momentum = TagetGeneral.Momentum;
                    effect.DamageNum = momentum;
                }
                else if (effect.AbilityType == AbilityType.Jueduifangyu)
                {
                    //固定伤害
                    AddDeamgeStatus(effect);
                }
                else if (effect.IsZengyi)
                {
                    //增加属性效果
                    if (effect.IsIncrease)
                    {
                        ProcessLog.DamageStatusList.Add(effect.Copy());
                        if (effect.BoutNum > 0)
                        {
                            effect.BoutNum = MathUtils.Subtraction(effect.BoutNum, 1, 0);
                        }
                        General.AddDamageStatus(effect);
                    }
                    else
                    {
                        AddDeamgeStatus(effect);
                    }
                }
            }

        }
Exemplo n.º 14
0
        private void DoAbilityStatus(TargetProcess targetProcess)
        {
            //处理技能伤害
            decimal hitPercent;
            bool isHit = General.TriggerHitPercent(TagetGeneral, out hitPercent);
            AbilityEffectStatus[] tempList = General.AbilityEffectList;
            decimal effectHit = General.TempAbility.HitPercent;//技能命中概率
            bool isEffectHit = IsProcessHit(tempList);//是否要处理命中
           
            ProcessLog.AddPercent(1, hitPercent);
            if (isEffectHit && isHit)
            {
                targetProcess.IsShanBi = false;
                DoHarmAttack(targetProcess);


                //处理技能效果
                if (effectHit == 0 || RandomUtils.IsHit(effectHit))
                {
                    ProcessAbilityEffect(targetProcess, tempList);
                }

            }
            else if (isEffectHit)
            {
                targetProcess.IsShanBi = true;
            }
            else
            {
                //处理技能效果
                if (effectHit == 0 || RandomUtils.IsHit(effectHit))
                {
                    ProcessAbilityEffect(targetProcess, tempList);
                }
            }

        }
Exemplo n.º 15
0
 public ProcessViewModel(TargetProcess process)
 {
     Process = process;
 }
        public bool InjectImage(string imagePath)
        {
            Log.LogGeneral($"Injecting {imagePath} -> {TargetProcess.ProcessName}_{TargetProcess.Id}");

            // GET MODULE NAME FOR LATER USE
            string moduleName = Path.GetFileName(imagePath);

            // GET LOAD LIBRARY POINTER
            ulong loadLibraryPointer = NTM.GetModuleFunction("kernel32.dll", "LoadLibraryA");

            // ALLOCATE IMAGE PATH IN TARGET PROCESS
            var   rawImagePath       = Encoding.Default.GetBytes(imagePath);
            ulong allocatedImagePath = TargetProcess.AllocateAndWrite(rawImagePath, NT.AllocationType.Commit | NT.AllocationType.Reserve, NT.MemoryProtection.ReadWrite);

            ulong threadHandle    = 0;
            ulong moduleHandle    = 0;
            bool  injectionFailed = false;

            switch (TypeOfExecution)
            {
                #region Create Thread
            case ExecutionType.CreateThread:
                // CREATE A THREAD TO REMOTELY CALL LOADLIBRARY
                TargetProcess.CreateAndWaitForThread(loadLibraryPointer, allocatedImagePath, out threadHandle);

                // GET MODULE HANDLE FOR LATER USE
                moduleHandle = TargetProcess.GetModuleByName(moduleName);
                break;
                #endregion

                #region Hijack Thread
            case ExecutionType.HijackThread:
                byte[] shellcode = ShellcodeGenerator.CallLoadLibrary(allocatedImagePath, loadLibraryPointer);

                // ALLOCATE AND WRITE SHELLCODE TO TARGET
                ulong remoteShellcodePointer = TargetProcess.AllocateAndWrite(shellcode, NT.AllocationType.Commit | NT.AllocationType.Reserve, NT.MemoryProtection.ExecuteReadWrite);

                // GET THREAD HANDLE WITH PROPER ACCESS RIGHTS
                var usableThreads = TargetProcess.Threads.Cast <ProcessThread>().Where(
                    x => x.ThreadState == System.Diagnostics.ThreadState.Wait && x.WaitReason == ThreadWaitReason.UserRequest);
                ProcessThread targetThread = usableThreads.ElementAt(NTM.RandomEngine.Next(usableThreads.Count()));
                threadHandle = targetThread.GetNativeHandle((NT.ThreadAccess) 0x1FFFFF);

                // ELEVATE HANDLE VIA DRIVER EXPLOIT
                if (Options.ElevateHandle)
                {
                    ElevateHandle.Elevate(threadHandle, 0x1FFFFF);
                }

                Log.LogInfo($"Thread {targetThread.Id} - {targetThread.ThreadState} - {/*targetThread.WaitReason} - {targetThread.PriorityLevel} - {*/targetThread.CurrentPriority}");

                // INITIALISE THREAD CONTEXT STRUCT
                NT.CONTEXT64 ctx = new NT.CONTEXT64()
                {
                    ContextFlags = NT.CONTEXT_FLAGS.CONTEXT_FULL
                };

                // SUSPEND THE THREAD SO WE CAN MODIFY REGISTERS
                if (NT.SuspendThread(threadHandle) == uint.MaxValue /*-1*/)
                {
                    Log.LogError($"Failed to suspend thread - {Marshal.GetLastWin32Error().ToString("x2")}");
                }

                // GET CONTEXT
                if (!NT.GetThreadContext(threadHandle, ref ctx))
                {
                    throw new Win32Exception($"GetThreadContext - {Marshal.GetLastWin32Error().ToString("x2")}");
                }

                Log.LogInfo($"Stack Pointer: {ctx.Rsp.ToString("x2")} - {ctx.Rsp % 0x10}");

                // ALLOCATE 8 BYTES ON STACK
                ctx.Rsp -= sizeof(ulong);

                // 'RET' WILL CALL POP AND JUMP TO THAT VALUE
                // SO WE WRITE OLD INSTRUCTION POINTER TO THE STACK SO WE CAN RETURN
                // SO DONT F**K UP THE STACK
                // F*****G RETARD
                TargetProcess.WriteRawMemory(BitConverter.GetBytes(ctx.Rip), ctx.Rsp);

                // OVERWRITE INSTRUCTION POINTER
                ctx.Rip = remoteShellcodePointer;

                // SET THREAD CONTEXT TO APPLY CHANGES
                if (!NT.SetThreadContext(threadHandle, ref ctx))
                {
                    throw new Win32Exception($"SetThreadContext- {Marshal.GetLastWin32Error().ToString("x2")}");
                }

                // RESUME THREAD
                if (NT.ResumeThread(threadHandle) == uint.MaxValue /*-1*/)
                {
                    Log.LogError($"Failed to resume thread - {Marshal.GetLastWin32Error().ToString("x2")}");
                }

                // CLOSE THREAD HANDLE
                NT.CloseHandle(threadHandle);

                // WAIT FOR MODULE TO LOAD FULLY BEFORE FREEING SHELLCODE
                // IF WE DONT WAIT, WE MIGHT FREE BEFORE LOADLIBRARY HAS FINISHED
                // WHICH MEANS IT WILL JUMP BACK TO A NON-EXISTING MEMORY PAGE
                // ALSO WE DO LIMIT HOW LONG WE WAIT, AS WE MIGHT HAVE HIJACKED
                // A STUBBORN, RETARDED, SHITTY, USELESS, FILTHY NIGGER THREAD
                // THAT ISN'T GOING TO DO SHIT BUT SLEEP, LEAVING US HANGING
                // todo: look into stubborn threads

                Stopwatch watch = Stopwatch.StartNew();
                while (watch.ElapsedMilliseconds < 2500)
                {
                    moduleHandle = TargetProcess.GetModuleByName(moduleName);

                    if (moduleHandle != 0)
                    {
                        break;
                    }

                    Thread.Sleep(1);
                }

                // IF WE HIJACKED A STUBBORN THREAD
                // WE CAN'T JUST FREE THE SHELLCODE NOR
                // THE ALLOCATED IMAGE PATH
                // AS IT MIGHT JUST RUN IT AFTER SOME TIME
                // RAISING AN EXCEPTION
                if (!(injectionFailed = moduleHandle == 0))
                {
                    TargetProcess.FreeMemory(remoteShellcodePointer);
                }

                //Console.ReadLine();

                break;
                #endregion
            }

            // ERASE PE HEADERS
            if (Options.EraseHeaders && moduleHandle != 0)
            {
                TargetProcess.NukeMemoryPage(moduleHandle);
            }

            if (!injectionFailed)
            {
                TargetProcess.FreeMemory(allocatedImagePath);
            }

            // WE'LL HAVE TO REDO IF WE HIJACKED A STUBBORN THREAD
            return(injectionFailed ?
                   new LoadLibraryInjection(TargetProcess, TypeOfExecution, Options).InjectImage(imagePath) :
                   true);
        }
Exemplo n.º 17
0
        public void CallEntrypoint(byte[] rawImage, UInt32 moduleHandle)
        {
            // GET HEADERS
            Tools.GetImageHeaders(rawImage, out NT.IMAGE_DOS_HEADER dosHeader, out NT.IMAGE_FILE_HEADER fileHeader, out NT.IMAGE_OPTIONAL_HEADER64 optionalHeader);

            // GET DLLMAIN
            UInt32 entrypoint = moduleHandle + optionalHeader.AddressOfEntryPoint;

            if (optionalHeader.AddressOfEntryPoint == 0)
            {
                Log.LogError($"Invalid Entrypoint - skipping {moduleHandle.ToString("x2")}");
                return;
            }

            Log.LogVariable("AddressOfEntryPoint", optionalHeader.AddressOfEntryPoint.ToString("x2"));

            // GET PROPER SHELLCODE FOR EXECUTION TYPE
            byte[] shellcode = ShellcodeGenerator.CallDllMain(moduleHandle, entrypoint, TypeOfExecution == ExecutionType.HijackThread);

            // EXECUTE DLLMAIN
            switch (TypeOfExecution)
            {
                #region Create Thread
            case ExecutionType.CreateThread:
                // INJECT OUR SHELLCODE -> REMOTE PROCESS TO CALL DLLMAIN REMOTELY :)
                TargetProcess.InjectShellcode(shellcode);
                break;
                #endregion

                #region Hijack Thread
            case ExecutionType.HijackThread:
                // WRITE SHELLCODE TO TARGET MEMORY
                var remoteShellcodePointer = TargetProcess.AllocateAndWrite(shellcode, NT.AllocationType.Commit | NT.AllocationType.Reserve, NT.MemoryProtection.ExecuteReadWrite);

                // GET THREAD HANDLE WITH PROPER ACCESS RIGHTS
                // I FILTER THE THREADS LIKE THIS BECAUSE FROM
                // EXPERIENCE SOME THREADS WITH TimeCritical PRIORITY
                // ETC WILL CAUSE SOME WONKY CRASHES
                var usableThreads = TargetProcess.Threads.Cast <ProcessThread>().Where(
                    x => x.ThreadState == System.Diagnostics.ThreadState.Wait && x.WaitReason == ThreadWaitReason.UserRequest);
                ProcessThread targetThread = usableThreads.ElementAt(NTM.RandomEngine.Next(usableThreads.Count()));
                var           threadHandle = targetThread.GetNativeHandle((NT.ThreadAccess) 0x1FFFFF);

                // ELEVATE HANDLE VIA DRIVER EXPLOIT
                if (Options.ElevateHandle)
                {
                    ElevateHandle.Elevate(threadHandle, 0x1FFFFF);
                }

                Log.LogInfo($"Thread {targetThread.Id} - {targetThread.ThreadState} - {targetThread.PriorityLevel} - {targetThread.CurrentPriority}");

                // INITIALISE THREAD CONTEXT STRUCT
                NT.CONTEXT64 ctx = new NT.CONTEXT64()
                {
                    ContextFlags = NT.CONTEXT_FLAGS.CONTEXT_FULL
                };

                // SUSPEND THE THREAD SO WE CAN MODIFY REGISTERS
                if (NT.SuspendThread(threadHandle) == uint.MaxValue)
                {
                    Log.LogError($"Failed to suspend thread - {Marshal.GetLastWin32Error().ToString("x2")}");
                }

                // GET CONTEXT
                if (!NT.GetThreadContext(threadHandle, ref ctx))
                {
                    throw new Win32Exception("GetThreadContext");
                }

                // ALLOCATE 8 BYTES ON STACK
                ctx.Rsp -= sizeof(ulong);

                // 'RET' WILL CALL POP AND JUMP TO THAT VALUE
                // SO WE WRITE OLD INSTRUCTION POINTER TO THE STACK SO WE CAN RETURN
                // SO DONT F**K UP THE STACK
                // F*****G RETARD
                TargetProcess.WriteRawMemory(BitConverter.GetBytes(ctx.Rip), ctx.Rsp);

                Log.LogInfo($"{ctx.Rip.ToString("x2")} -> {remoteShellcodePointer.ToString("x2")}");

                // OVERWRITE INSTRUCTION POINTER
                ctx.Rip = remoteShellcodePointer;

                // SET THREAD CONTEXT TO APPLY CHANGES
                if (!NT.SetThreadContext(threadHandle, ref ctx))
                {
                    throw new Win32Exception("SetThreadContext");
                }

                // RESUME THREAD
                Log.LogVariable("Resumed?", NT.ResumeThread(threadHandle));
                //if ( == uint.MaxValue/*-1*/)
                //     Log.LogError($"Failed to resume thread - {Marshal.GetLastWin32Error().ToString("x2")}");

                // CLOSE THREAD HANDLE
                NT.CloseHandle(threadHandle);

                // WAIT FOR MODULE TO LOAD FULLY BEFORE FREEING SHELLCODE
                // GHETTO SLEEP
                Thread.Sleep(1000);

                // MEMORY LEAKS ARE BAD
                TargetProcess.FreeMemory(remoteShellcodePointer);
                break;
                #endregion
            }
        }