Exemplo n.º 1
0
        public override string ToString()
        {
            var stateOutput = new StringBuilder();

            stateOutput.AppendFormat("Foundation URL Key: {0}\r\n",
                                     string.IsNullOrWhiteSpace(FoundationUrlKey) ? "Not Found!" : FoundationUrlKey);
            stateOutput.AppendFormat("Foundation ID: {0}\r\n",
                                     FoundationId >= 0 ? "Not Found!" : FoundationId.ToString(CultureInfo.CurrentCulture));
            stateOutput.AppendFormat("Foundation Process ID: {0}\r\n",
                                     ProcessId >= 0 ? "Not Selected!" : ProcessId.ToString(CultureInfo.CurrentCulture));
            stateOutput.AppendFormat("Base Directory: {0}\r\n",
                                     string.IsNullOrWhiteSpace(BaseDirectory) ? "Not Found!" : BaseDirectory);
            stateOutput.AppendFormat("File Mask {0}\r\n", FileMask);
            stateOutput.AppendFormat("Total File Count: {0}\r\n", Files != null ? Files.Count : 0);
            stateOutput.AppendFormat("Total Byte Count: {0}\r\n", TotalSize);
            stateOutput.AppendFormat("Sequester Path: {0}\r\n",
                                     string.IsNullOrWhiteSpace(SequesterPath) ? "Not Set" : SequesterPath);
            stateOutput.AppendFormat("Sequester Exclusion Patterns {0}\r\n",
                                     SequesterExclusionPatterns == null ? "None" : string.Join(";", SequesterExclusionPatterns));
            stateOutput.AppendFormat("Sequester File Count: {0}\r\n", SequesterFiles != null ? SequesterFiles.Count : 0);
            stateOutput.AppendFormat("Output Directory: {0}\r\n",
                                     string.IsNullOrWhiteSpace(OutputDirectory) ? "Not Set" : OutputDirectory);


            return(stateOutput.ToString());
        }
Exemplo n.º 2
0
        public string GetLocalizedText(string variable)
        {
            AmeisenBotLogger.Instance.Log($"[{ProcessId.ToString("X", CultureInfo.InvariantCulture.NumberFormat)}]\tReading Lua variable \"{variable}\"", LogLevel.Verbose);
            if (variable.Length > 0)
            {
                byte[]           bytes    = Encoding.UTF8.GetBytes(variable);
                MemoryAllocation memAlloc = TrashMem.AllocateMemory(bytes.Length + 1);
                if (memAlloc == null)
                {
                    return("");
                }

                TrashMem.WriteBytes(memAlloc.Address, bytes);

                string[] asmLocalText = new string[]
                {
                    $"CALL 0x{OffsetList.FunctionGetActivePlayerObject.ToString("X")}",
                    "MOV ECX, EAX",
                    "PUSH -1",
                    $"PUSH 0x{memAlloc.Address.ToString("X")}",
                    $"CALL 0x{OffsetList.FunctionGetLocalizedText.ToString("X")}",
                    "RETN",
                };

                string result = Encoding.UTF8.GetString(InjectAndExecute(asmLocalText, true));
                TrashMem.FreeMemory(memAlloc);
                return(result);
            }
            return("");
        }
Exemplo n.º 3
0
        private static void LogEvent(TraceEventType type, string code, string description, TraceRecord trace, Exception exception, object source)
        {
            StringBuilder traceString = new StringBuilder(SR.Format(SR.EventLogValue,
                                                                    ProcessName,
                                                                    ProcessId.ToString(CultureInfo.CurrentCulture),
                                                                    code,
                                                                    description));

            if (source != null)
            {
                traceString.AppendLine(SR.Format(SR.EventLogSourceValue, CreateSourceString(source)));
            }

            if (exception != null)
            {
                traceString.AppendLine(SR.Format(SR.EventLogExceptionValue, exception.ToString()));
            }

            if (trace != null)
            {
                traceString.AppendLine(SR.Format(SR.EventLogEventIdValue, trace.EventId));
                traceString.AppendLine(SR.Format(SR.EventLogTraceValue, trace.ToString()));
            }

            LogEvent(type, traceString.ToString(), false);
        }
Exemplo n.º 4
0
        private void DisposeHook()
        {
            if (IsWoWHooked)
            {
                AmeisenBotLogger.Instance.Log($"[{ProcessId.ToString("X", CultureInfo.InvariantCulture.NumberFormat)}]\tDisposing Hook", LogLevel.Verbose);
                TrashMem.WriteBytes(EndsceneAddress, originalEndsceneBytes);

                if (CodecaveForCheck != null)
                {
                    TrashMem.FreeMemory(CodecaveForCheck);
                }

                if (CodecaveForExecution != null)
                {
                    TrashMem.FreeMemory(CodecaveForExecution);
                }

                if (CodeToExecuteAddress != null)
                {
                    TrashMem.FreeMemory(CodeToExecuteAddress);
                }

                if (ReturnValueAddress != null)
                {
                    TrashMem.FreeMemory(ReturnValueAddress);
                }
            }
        }
Exemplo n.º 5
0
        /// <summary>
        ///     If lock file not yet IsAquired and not exists - try to create and get lock over it
        /// </summary>
        public void Reset()
        {
            if (IsAquired)
            {
                return;
            }
            //data loss protection
            if (Directory.Exists(PidFilePath))
            {
                throw new Exception("given lock file name is name of existed directory");
            }
            if (!File.Exists(PidFilePath))
            {
                try {
                    Directory.CreateDirectory(Path.GetDirectoryName(PidFilePath));
                    str = new FileStream(PidFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.Read);

                    using (var sw = new StreamWriter(str, Encoding.ASCII, 8, true)) {
                        sw.Write(ProcessId.ToString());
                        sw.Flush();
                    }

                    IsAquired = true;
                }
                catch {
                }
            }
        }
Exemplo n.º 6
0
        /// <inheritdoc />
        public override string GetAttributeValueImpl(string attributeName)
        {
            var    name  = attributeName.ToLowerInvariant();
            string value = null;

            if (name.Equals("href"))
            {
                UtilityClass.TryActionIgnoreException(() => value = Url);
            }
            else if (name.Equals("title"))
            {
                UtilityClass.TryActionIgnoreException(() => value = Title);
            }
            else if (name.Equals("hwnd"))
            {
                UtilityClass.TryActionIgnoreException(() => value = hWnd.ToString());
            }
            else if (name.Equals("process"))
            {
                int ProcessId;
                NativeMethods.GetWindowThreadProcessId(hWnd, out ProcessId);
                UtilityClass.TryActionIgnoreException(() => value = ProcessId.ToString());
            }
            else
            {
                throw new InvalidAttributeException(attributeName, "IE");
            }

            return(value);
        }
 private void ShutdownTracing()
 {
     if ((this.TraceSource != null) && !this.calledShutdown)
     {
         try
         {
             if (this.Level != SourceLevels.Off)
             {
                 if (this.ShouldTrace(TraceEventType.Information))
                 {
                     Dictionary <string, string> dictionary = new Dictionary <string, string>(3);
                     dictionary["AppDomain.FriendlyName"] = AppDomain.CurrentDomain.FriendlyName;
                     dictionary["ProcessName"]            = ProcessName;
                     dictionary["ProcessId"] = ProcessId.ToString(CultureInfo.CurrentCulture);
                     this.TraceEvent(TraceEventType.Information, 0x20001, GenerateMsdnTraceCode("System.ServiceModel.Diagnostics", "AppDomainUnload"), TraceSR.GetString("TraceCodeAppDomainUnload"), new DictionaryTraceRecord(dictionary), null, null);
                 }
                 this.calledShutdown = true;
                 this.TraceSource.Flush();
             }
         }
         catch (Exception exception)
         {
             if (Fx.IsFatal(exception))
             {
                 throw;
             }
             this.LogTraceFailure(null, exception);
         }
     }
 }
Exemplo n.º 8
0
 private static void ShutdownTracing()
 {
     if (null != TraceSource)
     {
         try
         {
             if (Level != SourceLevels.Off)
             {
                 if (Information)
                 {
                     Dictionary <string, string> values = new Dictionary <string, string>(3);
                     values["AppDomain.FriendlyName"] = string.Empty; // AppDomain.CurrentDomain.FriendlyName;
                     values["ProcessName"]            = ProcessName;
                     values["ProcessId"] = ProcessId.ToString(CultureInfo.CurrentCulture);
                     TraceEvent(TraceEventType.Information, DiagnosticTraceCode.AppDomainUnload, SR.TraceCodeAppDomainUnloading,
                                new DictionaryTraceRecord(values), null, ref EmptyGuid, false, null);
                 }
                 s_calledShutdown = true;
                 TraceSource.Flush();
             }
         }
         catch (OutOfMemoryException)
         {
             throw;
         }
         catch (Exception exception)
         {
             LogTraceFailure(null, exception);
         }
     }
 }
Exemplo n.º 9
0
        public void LuaDoString(string command)
        {
            AmeisenBotLogger.Instance.Log($"[{ProcessId.ToString("X", CultureInfo.InvariantCulture.NumberFormat)}]\tExecuting Lua \"{command}\"", LogLevel.Verbose);
            if (command.Length > 0)
            {
                byte[]           bytes    = Encoding.UTF8.GetBytes(command);
                MemoryAllocation memAlloc = TrashMem.AllocateMemory(bytes.Length + 1);
                if (memAlloc == null)
                {
                    return;
                }

                TrashMem.WriteBytes(memAlloc.Address, bytes);

                if (memAlloc.Address == 0)
                {
                    return;
                }

                string[] asm = new string[]
                {
                    $"MOV EAX, 0x{memAlloc.Address.ToString("X")}",
                    "PUSH 0",
                    "PUSH EAX",
                    "PUSH EAX",
                    $"CALL 0x{OffsetList.FunctionLuaDoString.ToString("X")}",
                    "ADD ESP, 0xC",
                    "RETN",
                };

                InjectAndExecute(asm, false);
                TrashMem.FreeMemory(memAlloc);
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Perform a complete backup generating a CAB
        /// </summary>
        /// <returns></returns>
        public int BackupCompleteCAB(String BackupFileName)
        {
            int ProcessId;

            try
            {
                // first verify connection
                if (!this.Connected)
                {
                    throw new Exception("Galaxy not connected");
                }

                log.Debug("Checking and correcting filename " + BackupFileName + " to use .CAB");
                // Inspect the filename.  Correct the extension if necessary
                BackupFileName = System.IO.Path.ChangeExtension(BackupFileName, ".CAB");

                // Check for file exists.  Bail if the file already exists and we don't want to overwrite
                if (CheckandLogFileExists(BackupFileName))
                {
                    return(0);
                }

                // Get the current PID
                ProcessId = System.Diagnostics.Process.GetCurrentProcess().Id;
                log.Debug("Got Process ID " + ProcessId.ToString());

                if (ProcessId == 0)
                {
                    log.Error("Inavlid ProcessID");
                    return(-2);
                }


                var obj = _galaxy.GetGalaxyConfiguration();


                log.Info("Starting CAB Backup to " + BackupFileName);

                // Call complete backup routine
                _galaxy.Backup(ProcessId, BackupFileName, this.GRNodeName, _galaxy.Name);

                if (_galaxy.CommandResult.Successful)
                {
                    log.Info("Backup CAB Complete");
                    return(0);
                }
                else
                {
                    log.Error(_galaxy.CommandResult.Text);
                    return(-1);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 11
0
        public UnitReaction GetUnitReaction(WowUnit wowUnitA, WowUnit wowUnitB)
        {
            AmeisenBotLogger.Instance.Log($"[{ProcessId.ToString("X", CultureInfo.InvariantCulture.NumberFormat)}]\tGetting relation of: {wowUnitA.Name} to {wowUnitB.Name}", LogLevel.Verbose);
            UnitReaction reaction = UnitReaction.Unknown;

            if (SharedCacheManager.Instance.ReactionCache.ContainsKey((wowUnitA.FactionTemplate, wowUnitB.FactionTemplate)))
            {
                AmeisenBotLogger.Instance.Log($"[{ProcessId.ToString("X", CultureInfo.InvariantCulture.NumberFormat)}]\tCached relation of: {wowUnitA.Name} to {wowUnitB.Name} is {SharedCacheManager.Instance.ReactionCache[(wowUnitA.FactionTemplate, wowUnitB.FactionTemplate)].ToString()}", LogLevel.Verbose);
                return(SharedCacheManager.Instance.ReactionCache[(wowUnitA.FactionTemplate, wowUnitB.FactionTemplate)]);
Exemplo n.º 12
0
 public override string ToString()
 {
     return("FileName   = " + Application + Environment.NewLine +
            "Arguments  = " + Arguments + Environment.NewLine +
            "Process ID = " + ProcessId.ToString() + Environment.NewLine +
            "Runtime    = " + Runtime.TotalSeconds.ToString() + " seconds" + Environment.NewLine +
            "MaxRuntime = " + MaxRuntime.TotalSeconds.ToString() + " seconds" + Environment.NewLine +
            "Memory     = " + (MemoryUsage / Math.Pow(2d, 20d)).ToString() + " MB" + Environment.NewLine +
            "MaxMemory  = " + (MaxMemoryUsage / Math.Pow(2d, 20d)).ToString() + " MB");
 }
        public void Add(IInfoAccumulator query)
        {
            var q = query.WithPrefix("proc_");

            q.Add("64", Process64Bit);
            q.Add("guid", ProcessGuid);
            q.Add("id_hash", Utilities.Sha256TruncatedBase64(ProcessId.ToString(), 6));

            q.Add("working_set_mb", Environment.WorkingSet / 1000000);

            // TODO: check for mismatched assemblies?
        }
Exemplo n.º 14
0
        public override string ToString()
        {
            object names = new {
                ThreadHashCode  = ThreadHashCode.ToString(),
                ThreadId        = ThreadId.ToString(),
                ApplicationName = ApplicationName,
                ProcessId       = ProcessId.ToString(),
                UtcShortDate    = Utc.ToShortDateString(),
                UtcShortTime    = Utc.ToShortTimeString(),
                Message         = Message
            };

            return(NamedMessageFormat.NamedFormat(names));
        }
Exemplo n.º 15
0
 private void p_Exited()
 {
     if (VerboseLogging)
     {
         EPSEventLog.WriteEntry("Process Stopped" + Environment.NewLine +
                                "Runtime    = " + Runtime.TotalSeconds.ToString() + " seconds" + Environment.NewLine +
                                "FileName   = " + Application + Environment.NewLine +
                                "Arguments  = " + Arguments + Environment.NewLine +
                                "Process ID = " + ProcessId.ToString() + Environment.NewLine +
                                "Exit Code  = " + p.ExitCode.ToString(), System.Diagnostics.EventLogEntryType.Information);
     }
     isRunning = false;
     p.Dispose();
     p = null;
     OnStopped();
 }
Exemplo n.º 16
0
        private void _processHandler()
        {
            try
            {
                using (var proc = new Process())
                {
                    CreateAndStartService();

                    var sb = new StringBuilder();

                    sb.Append("--processor-guid ");
                    sb.Append(ProcessId.ToString());
                    sb.Append(' ');

                    AugmentArguments(sb);

                    if (LoggerProcessor != null)
                    {
                        sb.Append("--logger-processor ");
                        sb.Append(LoggerProcessor.ProcessId.ToString());
                        sb.Append(' ');
                    }

                    var startArgs = sb.ToString();

                    proc.StartInfo.UseShellExecute = false;
                    proc.StartInfo.FileName        = LoadFile;
                    proc.StartInfo.CreateNoWindow  = true;
                    proc.StartInfo.Environment.Add("VRWORLDS_GRPC_ACCESS_TOKEN", AccessToken.ToString());
                    proc.StartInfo.Environment.Add("VRWORLDS_BROWSER_SESSION", ProcessHandler.BrowserSession.ToString());
                    proc.StartInfo.Arguments = startArgs;

                    proc.Start();

                    UnityEngine.Debug.Log("Process Started: " + LoadFile);

                    ProcessorStart();

                    ProcessorLoop();  // Must not let this exit, or we will shutdown

                    ProcessorShutdown();
                }
            }
            catch (Exception ex) {
                UnityEngine.Debug.Log("Error: " + ex.Message);
            }
        }
        public async Task <DequeueResponse> Handle(DequeueCommand request, CancellationToken cancellationToken)
        {
            ArgumentNullException.ThrowIfNull(request, nameof(request));

            _logger.LogProcess("Dequeue", _correlationContext.Id, request.MarketOperator);

            var bundleId  = new Uuid(request.BundleId);
            var recipient = Guid.TryParse(request.MarketOperator, out var actorId)
                ? new ActorId(actorId)
                : new LegacyActorId(new GlobalLocationNumber(request.MarketOperator));

            var(canAcknowledge, bundle) = await _marketOperatorDataDomainService
                                          .CanAcknowledgeAsync(recipient, bundleId)
                                          .ConfigureAwait(false);

            if (!canAcknowledge)
            {
                _logger.LogProcess("Dequeue", "Unacknowledged", _correlationContext.Id, request.MarketOperator, request.BundleId);
                return(new DequeueResponse(false));
            }

            var marketOperator = recipient is LegacyActorId legacyActor
#pragma warning disable CS0618
                ? new LegacyActorIdDto(legacyActor.Value)
#pragma warning restore CS0618
                : new ActorIdDto(Guid.Parse(recipient.Value));

            var dequeueNotification = new DequeueNotificationDto(
                bundle !.ProcessId.ToString(),
                marketOperator);

            await _dequeueNotificationSender
            .SendAsync(bundle.ProcessId.ToString(), dequeueNotification, (DomainOrigin)bundle.Origin)
            .ConfigureAwait(false);

            await _marketOperatorDataDomainService
            .AcknowledgeAsync(bundle)
            .ConfigureAwait(false);

            _logger.LogProcess("Dequeue", "Acknowledged", _correlationContext.Id, request.MarketOperator, request.BundleId);
            return(new DequeueResponse(true));
        }
Exemplo n.º 18
0
        public void Format(LogEvent logEvent, TextWriter output)
        {
            try
            {
                var(Category, Application, Identity, ClassType, MethodName, ActivityId, ProcessId, ThreadId, Stacktrace, Properties) = Helper.ExtractEventInfo(logEvent);

                using (var properties = new StringWriter())
                    using (var messageText = new StringWriter())
                    {
                        MessageFormatter.Format(logEvent, messageText);
                        PropertyFormatter.Format(Properties, properties);

                        // Output the text.

                        output.WriteLine(string.Format("{0} {1} {2} {3} {4} {5} {6} {7} - {8} - {9} - {10}",
                                                       logEvent.Timestamp.ToString("dd/MM/yyyy HH:mm:ss,fff").PadRight(24),
                                                       MessageLogLevelMap[logEvent.Level].PadRight(13),
                                                       MessageCategoryMap[Category].PadRight(14),
                                                       Identity.PadRight(15),
                                                       ProcessId.ToString().PadRight(6),
                                                       ThreadId.ToString().PadRight(6),
                                                       ActivityId.PadRight(40),
                                                       ClassType,
                                                       MethodName,
                                                       messageText.ToString(),
                                                       properties.ToString()));

                        if (null != logEvent.Exception)
                        {
                            output.Write(logEvent.Exception.ToFormattedString());
                        }

                        if (!String.IsNullOrWhiteSpace(Stacktrace))
                        {
                            output.WriteLine(Stacktrace);
                        }
                    }
            }
            catch (Exception)
            {
            }
        }
 private static void ShutdownTracing()
 {
     if (TraceSource != null)
     {
         try
         {
             if (Level != SourceLevels.Off)
             {
                 if (Information)
                 {
                     Dictionary <string, string> dictionary = new Dictionary <string, string>(3);
                     dictionary["AppDomain.FriendlyName"] = AppDomain.CurrentDomain.FriendlyName;
                     dictionary["ProcessName"]            = ProcessName;
                     dictionary["ProcessId"] = ProcessId.ToString(CultureInfo.CurrentCulture);
                     TraceEvent(TraceEventType.Information, "http://msdn.microsoft.com/TraceCodes/System/ActivityTracing/2004/07/Diagnostics/AppDomainUnload", System.Transactions.SR.GetString("TraceCodeAppDomainUnloading"), new DictionaryTraceRecord(dictionary), null, ref EmptyGuid, false, null);
                 }
                 calledShutdown = true;
                 TraceSource.Flush();
             }
         }
         catch (OutOfMemoryException)
         {
             throw;
         }
         catch (StackOverflowException)
         {
             throw;
         }
         catch (ThreadAbortException)
         {
             throw;
         }
         catch (Exception exception)
         {
             LogTraceFailure(null, exception);
         }
     }
 }
Exemplo n.º 20
0
        public void Add(IInfoAccumulator query)
        {
            var q = query.WithPrefix("proc_");

            q.Add("64", Process64Bit);
            q.Add("guid", ProcessGuid);
            q.Add("sys_dotnet", DotNetVersionInstalled);
            q.Add("iis", IisVer);
            q.Add("integrated_pipeline", IntegratedPipeline);
            q.Add("id_hash", Utilities.Sha256TruncatedBase64(ProcessId.ToString(), 6));

            q.Add("asyncmodule", Config.Current.Pipeline.UsingAsyncMode);
            q.Add("default_commands", Config.Current.get("pipeline.defaultCommands", null));
            q.Add("working_set_mb", Environment.WorkingSet / 1000000);
            q.Add("git_commit", Assembly.GetAssembly(this.GetType()).GetShortCommit());
            q.Add("info_version", Assembly.GetAssembly(this.GetType()).GetInformationalVersion());
            q.Add("file_version", Assembly.GetAssembly(this.GetType()).GetFileVersion());

            if (HostingEnvironment.ApplicationPhysicalPath != null)
            {
                q.Add("apppath_hash", Utilities.Sha256TruncatedBase64(HostingEnvironment.ApplicationPhysicalPath, 6));
            }

            // Add HttpModule class names without prefixing
            SetModules(HttpContext.Current?.ApplicationInstance?.Modules);
            if (HttpModules != null)
            {
                foreach (var name in HttpModules)
                {
                    query.Add("mod", name);
                }
            }



            // TODO: check for mismatched assemblies?
        }
Exemplo n.º 21
0
 public void Start()
 {
     if (IsRunning)
     {
         throw new Exception("Process is already running.");
     }
     p = new System.Diagnostics.Process();
     System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(Application, Arguments);
     p.StartInfo = startInfo;
     p.Start();
     startTime = DateTime.Now;
     isRunning = true;
     Monitor();
     p.PriorityClass = Priority;
     if (VerboseLogging)
     {
         EPSEventLog.WriteEntry("Process Started" + Environment.NewLine +
                                "FileName   = " + Application + Environment.NewLine +
                                "Arguments  = " + Arguments + Environment.NewLine +
                                "Process ID = " + ProcessId.ToString() + Environment.NewLine +
                                "Priority   = " + Priority.ToString(), System.Diagnostics.EventLogEntryType.Information);
     }
     OnStarted();
 }
Exemplo n.º 22
0
        public byte[] InjectAndExecute(string[] asm, bool readReturnBytes, [CallerMemberName] string callingFunction = "")
        {
            AmeisenBotLogger.Instance.Log($"[{ProcessId.ToString("X", CultureInfo.InvariantCulture.NumberFormat)}]\tInjecting ASM into Hook [asm = {JsonConvert.SerializeObject(asm)}, readReturnBytes = {readReturnBytes}, callingFunction = {callingFunction}]", LogLevel.Verbose);
            List <byte> returnBytes = new List <byte>();

            if (!IsWorldLoaded)
            {
                return(returnBytes.ToArray());
            }

            try
            {
                int timeoutCounter = 0;
                // wait for the code to be executed
                while (IsInjectionUsed)
                {
                    if (timeoutCounter == 500)
                    {
                        return(Array.Empty <byte>());
                    }

                    timeoutCounter++;
                    Thread.Sleep(1);
                }

                IsInjectionUsed = true;
                // preparing to inject the given ASM
                TrashMem.Asm.Clear();
                // add all lines
                foreach (string s in asm)
                {
                    TrashMem.Asm.AddLine(s);
                }

                // now there is code to be executed
                TrashMem.Write(CodeToExecuteAddress.Address, 1);
                // inject it
                TrashMem.Asm.Inject(CodecaveForExecution.Address);

                timeoutCounter = 0;
                // wait for the code to be executed
                while (TrashMem.ReadInt32(CodeToExecuteAddress.Address) > 0)
                {
                    if (timeoutCounter == 500)
                    {
                        return(Array.Empty <byte>());
                    }

                    timeoutCounter++;
                    IsInjectionUsed = false;
                    Thread.Sleep(1);
                }

                // if we want to read the return value do it otherwise we're done
                if (readReturnBytes)
                {
                    byte buffer;
                    try
                    {
                        uint dwAddress = TrashMem.ReadUnmanaged <uint>(ReturnValueAddress.Address);

                        // read all parameter-bytes until we the buffer is 0
                        buffer = TrashMem.ReadChar(dwAddress);
                        while (buffer != 0)
                        {
                            returnBytes.Add(buffer);
                            dwAddress++;
                            buffer = TrashMem.ReadChar(dwAddress);
                        }
                    }
                    catch (Exception e)
                    {
                        AmeisenBotLogger.Instance.Log($"[{ProcessId.ToString("X", CultureInfo.InvariantCulture.NumberFormat)}]\tCrash at reading the return bytes: \n{e}", LogLevel.Error);
                    }
                }
                IsInjectionUsed = false;
            }
            catch (Exception e)
            {
                AmeisenBotLogger.Instance.Log($"[{ProcessId.ToString("X", CultureInfo.InvariantCulture.NumberFormat)}]\tCrash at injecting: \n{e}", LogLevel.Error);
                // now there is no more code to be executed
                TrashMem.ReadUnmanaged <uint>(CodeToExecuteAddress.Address, 0);
                IsInjectionUsed = false;
            }

            return(returnBytes.ToArray());
        }
Exemplo n.º 23
0
 public IWorker Create()
 {
     return(new Worker(CounterPath, OutPath, ProcessId.ToString()));
 }
Exemplo n.º 24
0
        private static void InitializeAppInfo()
        {
            RaiseApplyFrxParamsOverrides();

            try
            {
                EntryAssemblyLocation = ChoAssembly.GetEntryAssembly().Location;
                EntryAssemblyFileName = System.IO.Path.GetFileName(EntryAssemblyLocation);
            }
            catch (System.Security.SecurityException ex)
            {
                // This security exception will occur if the caller does not have
                // some undefined set of SecurityPermission flags.
                Trace(ChoTrace.ChoSwitch.TraceError, ex.ToString());
            }

            if (!ServiceInstallation)
            {
                if (ChoGlobalApplicationSettings.Me.ApplicationBehaviourSettings.SingleInstanceApp)
                {
                    Func <bool> verifyAnotherInstanceRunning = VerifyAnotherInstanceRunning;
                    if (verifyAnotherInstanceRunning != null)
                    {
                        bool instanceExists = verifyAnotherInstanceRunning();
                        if (instanceExists)
                        {
                            RaiseErrorOrActivateFirstInstance();
                        }
                    }
                    else
                    {
                        bool createdNew = true;
                        _singleInstanceMutex = new Mutex(true, ChoGlobalApplicationSettings.Me.ApplicationName, out createdNew);
                        if (!createdNew)
                        {
                            RaiseErrorOrActivateFirstInstance();
                        }
                    }
                }

                if (!ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.TurnOn)
                {
                    if (ChoGlobalApplicationSettings.Me.ApplicationBehaviourSettings.HideWindow)
                    {
                        ChoWindowsManager.Hide();
                    }
                    else
                    {
                        ChoWindowsManager.Show();

                        ChoWindowsManager.AlwaysOnTop(ChoGlobalApplicationSettings.Me.ApplicationBehaviourSettings.AlwaysOnTop);

                        if (!ChoGlobalApplicationSettings.Me.ApplicationBehaviourSettings.AlwaysOnTop)
                        {
                            if (ChoGlobalApplicationSettings.Me.ApplicationBehaviourSettings.BringWindowToTop)
                            {
                                ChoWindowsManager.BringWindowToTop();
                            }
                        }
                        //ChoWindowManager.ShowInTaskbar(ChoGlobalApplicationSettings.Me.ApplicationBehaviourSettings.ShowInTaskbar);
                    }
                }

                if (ChoApplicationHost.ApplicationContext != null)
                {
                    ChoApplicationHost.ApplicationContext.Visible = ChoGlobalApplicationSettings.Me.TrayApplicationBehaviourSettings.TurnOn;
                }
            }

            #region Check for Unmanaged Code Permission Available

            // check whether the unmanaged code permission is available to avoid three potential stack walks
            SecurityPermission unmanagedCodePermission = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
            // avoid a stack walk by checking for the permission on the current assembly. this is safe because there are no
            // stack walk modifiers before the call.
            if (SecurityManager.IsGranted(unmanagedCodePermission))
            {
                try
                {
                    unmanagedCodePermission.Demand();
                    UnmanagedCodePermissionAvailable = true;
                }
                catch (SecurityException ex)
                {
                    Trace(ChoTrace.ChoSwitch.TraceError, ex.ToString());
                }
            }

            #endregion Check for Unmanaged Code Permission Available

            #region Get AppDomainName

            try
            {
                AppDomainName = AppDomain.CurrentDomain.FriendlyName;
            }
            catch (Exception ex)
            {
                Trace(ChoTrace.ChoSwitch.TraceError, ex.ToString());
            }

            #endregion Get AppDomainName

            #region Get ProcessId, ProcessName

            if (UnmanagedCodePermissionAvailable)
            {
                try
                {
                    ProcessId = ChoKernel32Core.GetCurrentProcessId();
                }
                catch (Exception ex)
                {
                    Trace(ChoTrace.ChoSwitch.TraceError, ex.ToString());

                    try
                    {
                        ProcessId = Process.GetCurrentProcess().Id;
                    }
                    catch { }
                }

                try
                {
                    ProcessFilePath = GetProcessName();
                }
                catch (Exception ex)
                {
                    Trace(ChoTrace.ChoSwitch.TraceError, ex.ToString());
                }
            }
            else
            {
                try
                {
                    ProcessId = Process.GetCurrentProcess().Id;
                }
                catch { }

                Trace(ChoTrace.ChoSwitch.TraceError, "Failed to retrieve value due to unmanaged code permission denied.");
            }

            #endregion Get ProcessId, ProcessName

            ApplicationLogDirectory = ChoGlobalApplicationSettings.Me.ApplicationLogDirectory;

            if (!ChoGlobalApplicationSettings.Me.ApplicationBehaviourSettings.SingleInstanceApp)
            {
                if (ChoGlobalApplicationSettings.Me.DoAppendProcessIdToLogDir)
                {
                    ApplicationLogDirectory = Path.Combine(ApplicationLogDirectory, ProcessId.ToString());
                }
            }

            Directory.CreateDirectory(ApplicationLogDirectory);
        }
Exemplo n.º 25
0
 public override string ToString()
 {
     return(ProcessId.ToString() + "." + SeqNumber.ToString());
 }
Exemplo n.º 26
0
 public override string ToString() => ProcessId.ToString() + "@" + StartTime.ToString("o");
Exemplo n.º 27
0
 private void ShutdownTraceSource()
 {
     try
     {
         if (TraceCore.AppDomainUnloadIsEnabled(this))
         {
             TraceCore.AppDomainUnload(this, AppDomain.CurrentDomain.FriendlyName, ProcessName, ProcessId.ToString(CultureInfo.CurrentCulture));
         }
         this.TraceSource.Flush();
     }
     catch (Exception exception)
     {
         if (Fx.IsFatal(exception))
         {
             throw;
         }
         this.LogTraceFailure(null, exception);
     }
 }
Exemplo n.º 28
0
        private void SetupEndsceneHook()
        {
            // first thing thats 5 bytes big is here
            // we are going to replace this 5 bytes with
            // our JMP instruction (JMP (1 byte) + Address (4 byte))
            EndsceneAddress += ENDSCENE_HOOK_OFFSET;

            // if WoW is already hooked, unhook it
            if (IsWoWHooked)
            {
                DisposeHook();
            }
            else
            {
                originalEndsceneBytes = TrashMem.ReadChars(EndsceneAddress, 5);
            }

            // if WoW is now/was unhooked, hook it
            if (!IsWoWHooked)
            {
                AmeisenBotLogger.Instance.Log($"[{ProcessId.ToString("X", CultureInfo.InvariantCulture.NumberFormat)}]\tHooking EndScene at \"0x{EndsceneAddress.ToString("X", CultureInfo.InvariantCulture.NumberFormat)}\"", LogLevel.Verbose);

                // the address that we will return to after
                // the jump wer'e going to inject
                EndsceneReturnAddress = EndsceneAddress + 0x5;

                // integer to check if there is code waiting to be executed
                CodeToExecuteAddress = TrashMem.AllocateMemory(4);
                TrashMem.Write(CodeToExecuteAddress.Address, 0);

                // integer to save the address of the return value
                ReturnValueAddress = TrashMem.AllocateMemory(4);
                TrashMem.Write(ReturnValueAddress.Address, 0);

                // codecave to check if we need to execute something
                CodecaveForCheck = TrashMem.AllocateMemory(128);
                AmeisenBotLogger.Instance.Log($"[{ProcessId.ToString("X", CultureInfo.InvariantCulture.NumberFormat)}]\tCCCheck is at \"0x{CodecaveForCheck.Address.ToString("X", CultureInfo.InvariantCulture.NumberFormat)}\"", LogLevel.Verbose);
                // codecave for the code we wa't to execute
                CodecaveForExecution = TrashMem.AllocateMemory(2048);
                AmeisenBotLogger.Instance.Log($"[{ProcessId.ToString("X", CultureInfo.InvariantCulture.NumberFormat)}]\tCCExecution is at \"0x{CodecaveForExecution.Address.ToString("X", CultureInfo.InvariantCulture.NumberFormat)}\"", LogLevel.Verbose);

                TrashMem.Asm.Clear();
                // save registers
                TrashMem.Asm.AddLine("PUSHFD");
                TrashMem.Asm.AddLine("PUSHAD");

                // check for code to be executed
                TrashMem.Asm.AddLine($"MOV EBX, [0x{CodeToExecuteAddress.Address.ToString("X")}]");
                TrashMem.Asm.AddLine("TEST EBX, 1");
                TrashMem.Asm.AddLine("JE @out");

                // execute our stuff and get return address
                TrashMem.Asm.AddLine($"MOV EDX, 0x{CodecaveForExecution.Address.ToString("X")}");
                TrashMem.Asm.AddLine("CALL EDX");
                TrashMem.Asm.AddLine($"MOV [0x{ReturnValueAddress.Address.ToString("X")}], EAX");

                // finish up our execution
                TrashMem.Asm.AddLine("@out:");
                TrashMem.Asm.AddLine("MOV EDX, 0");
                TrashMem.Asm.AddLine($"MOV [0x{CodeToExecuteAddress.Address.ToString("X")}], EDX");

                // restore registers
                TrashMem.Asm.AddLine("POPAD");
                TrashMem.Asm.AddLine("POPFD");

                byte[] asmBytes = TrashMem.Asm.Assemble();

                // needed to determine the position where the original
                // asm is going to be placed
                int asmLenght = asmBytes.Length;

                // inject the instructions into our codecave
                TrashMem.Asm.Inject(CodecaveForCheck.Address);
                // ---------------------------------------------------
                // End of the code that checks if there is asm to be
                // executed on our hook
                // ---------------------------------------------------

                // Prepare to replace the instructions inside WoW
                TrashMem.Asm.Clear();

                // do the original EndScene stuff after we restored the registers
                // and insert it after our code
                TrashMem.WriteBytes(CodecaveForCheck.Address + (uint)asmLenght, originalEndsceneBytes);

                // return to original function after we're done with our stuff
                TrashMem.Asm.AddLine($"JMP 0x{EndsceneReturnAddress.ToString("X")}");
                TrashMem.Asm.Inject(CodecaveForCheck.Address + (uint)asmLenght + 5);
                TrashMem.Asm.Clear();
                // ---------------------------------------------------
                // End of doing the original stuff and returning to
                // the original instruction
                // ---------------------------------------------------

                // modify original EndScene instructions to start the hook
                TrashMem.Asm.AddLine($"JMP 0x{CodecaveForCheck.Address.ToString("X")}");
                TrashMem.Asm.Inject(EndsceneAddress);
                AmeisenBotLogger.Instance.Log($"[{ProcessId.ToString("X", CultureInfo.InvariantCulture.NumberFormat)}]\tInjected Hook [IsWoWHooked = {IsWoWHooked}]", LogLevel.Verbose);
                // we should've hooked WoW now
            }
        }
        private static void LogEvent(TraceEventType type, string code, string description, TraceRecord trace, Exception exception, object source)
        {
            StringBuilder builder = new StringBuilder(System.Transactions.SR.GetString("EventLogValue", new object[] { ProcessName, ProcessId.ToString(CultureInfo.CurrentCulture), code, description }));

            if (source != null)
            {
                builder.AppendLine(System.Transactions.SR.GetString("EventLogSourceValue", new object[] { CreateSourceString(source) }));
            }
            if (exception != null)
            {
                builder.AppendLine(System.Transactions.SR.GetString("EventLogExceptionValue", new object[] { exception.ToString() }));
            }
            if (trace != null)
            {
                builder.AppendLine(System.Transactions.SR.GetString("EventLogEventIdValue", new object[] { trace.EventId }));
                builder.AppendLine(System.Transactions.SR.GetString("EventLogTraceValue", new object[] { trace.ToString() }));
            }
            LogEvent(type, builder.ToString(), false);
        }
Exemplo n.º 30
0
        public HttpResponseMessage SaveWorkerRule()
        {
            try
            {
                var    s    = HttpContext.Current.Request.Form.GetValues("model");
                string json = s[0];
                if (string.IsNullOrEmpty(json))
                {
                    throw new HttpResponseException(HttpStatusCode.BadRequest);//throws when request without content
                }
                dynamic stuff = JsonConvert.DeserializeObject(json);
                int?    ProcessId;
                ProcessId = stuff.ProcessId;

                if (HKTDC.Utils.AuthorizationUtil.CheckApiAuthorized("workflow/worker-rules", "HttpPost", getCurrentUser(Request), ProcessId.ToString()))
                {
                    Tuple <bool, string> response = this.workerRuleService.SaveWorkerRule(getCurrentUser(Request), stuff);
                    if (response.Item1)
                    {
                        return(new HttpResponseMessage {
                            Content = new StringContent("{\"Success\":\"1\", \"Msg\":\"" + response.Item2 + "\"}", System.Text.Encoding.UTF8, "application/json")
                        });
                    }
                    else
                    {
                        return(new HttpResponseMessage {
                            Content = new StringContent("{\"Success\":\"0\", \"Msg\":\"" + response.Item2 + "\"}", System.Text.Encoding.UTF8, "application/json")
                        });
                    }
                }
                else
                {
                    throw new UnauthorizedAccessException();
                }
            }
            catch (Exception ex)
            {
                var err = this.workerRuleService.ErrorLog(ex, getCurrentUser(Request));

                throw new HttpResponseException(Request.CreateErrorResponse(err.Code, err.Message));
            }
        }