Beispiel #1
0
        public void RegisterAgent(String agentid, IAgentInstance agent)
        {
            agentList.Add(agentid, agent);
            AgentInstance agentInstance = dbcontext.Agents.FirstOrDefault <AgentInstance>(s => s.agentid.Equals(agentid));

            if (agentInstance == null)
            {
                AgentInstance agentinstance = new AgentInstance
                {
                    agentid    = agentid,
                    address    = ((AgentInstanceHttp)agent).GetAddress(),
                    port       = ((AgentInstanceHttp)agent).GetPort(),
                    profileid  = ((AgentInstanceHttp)agent).GetProfileid(),
                    framework  = ((AgentInstanceHttp)agent).TargetFramework,
                    sessionkey = ((AgentInstanceHttp)agent).AesManager.Key,
                    sessioniv  = ((AgentInstanceHttp)agent).AesManager.IV
                };

                if (agent.Pivoter != null)
                {
                    agentinstance.agentPivotid = agent.Pivoter.AgentId;
                }

                dbcontext.Agents.Add(agentinstance);
                dbcontext.SaveChanges();
            }
        }
        private void loadEndPoints()
        {
            List<string> endPoints = XMLUtils.DeSerilize<List<string>>(m_EndPointsFilePath);
            IRestartService restartService = null;
            AgentInstance agentInstance = null;
            Stopwatch sw = new Stopwatch();
            sw.Start();
            string fullEndPoint = string.Empty;
            LogManager.Instance.WriteInfo("CreateChannel operation on endpoints started");
            foreach (string endpoint in endPoints)
            {
                try
                {
                    fullEndPoint = "http://" + endpoint + ":5050/RestartService";
                    restartService = WCFUtils.ServiceFactory<IRestartService>.GetService(fullEndPoint);
                    agentInstance = new AgentInstance(restartService);
                    agentInstance.UpdateInstanceInfo();
                    m_Agents.Add(agentInstance.IP, agentInstance);
                    LogManager.Instance.WriteInfo("[Endpoint]: " + fullEndPoint + " Added");

                }
                catch (Exception ex)
                {
                    SystemLogManager.Instance.Log(eLogType.Error, "TryingCreateChannel", fullEndPoint, string.Empty, ex.Message, string.Empty);
                    LogManager.Instance.WriteError("Error while trying to CreateChannel , [Endpoint]: " + fullEndPoint + " [Exception]: " + ex.Message);
                }
            }
            sw.Stop();
            LogManager.Instance.WriteInfo("CreateChannel operation on endpoints ended, elapsed: " + sw.Elapsed);
        }
Beispiel #3
0
        public void Log(eLogType i_LogType, AgentInstance i_AgentInstance, string i_Info, string i_Elapsed)
        {
            string machineName = i_AgentInstance.ComputerName;
            string IP          = i_AgentInstance.IP;

            Log(i_LogType, machineName, IP, string.Empty, i_Info, i_Elapsed);
        }
 public static void StopAgentInstanceRemoveResources(AgentInstance agentInstance, IDictionary <string, object> terminationProperties, EPServicesContext servicesContext, bool isStatementStop, bool leaveLocksAcquired)
 {
     if (terminationProperties != null)
     {
         var contextProperties = (MappedEventBean)agentInstance.AgentInstanceContext.ContextProperties;
         contextProperties.Properties.PutAll(terminationProperties);
     }
     StatementAgentInstanceUtil.Stop(agentInstance.StopCallback, agentInstance.AgentInstanceContext, agentInstance.FinalView, servicesContext, isStatementStop, leaveLocksAcquired, true);
 }
 private void Start()
 {
     try
     {
         agent = GetComponent <AgentInstance>();
     }
     catch
     {
         throw new Exception("AgentDebug: Error while fetching required components for debugging.");
     }
 }
        private static void Process(
            AgentInstance agentInstance,
            EPServicesContext servicesContext,
            IEnumerable <FilterHandle> callbacks,
            EventBean theEvent)
        {
            var agentInstanceContext = agentInstance.AgentInstanceContext;

            using (agentInstanceContext.AgentInstanceLock.AcquireWriteLock())
            {
                try
                {
                    servicesContext.VariableService.SetLocalVersion();

                    // sub-selects always go first
                    foreach (var handle in callbacks)
                    {
                        var callback = (EPStatementHandleCallback)handle;
                        if (callback.AgentInstanceHandle != agentInstanceContext.EpStatementAgentInstanceHandle)
                        {
                            continue;
                        }
                        callback.FilterCallback.MatchFound(theEvent, null);
                    }

                    agentInstanceContext.EpStatementAgentInstanceHandle.InternalDispatch();
                }
                catch (Exception ex)
                {
                    servicesContext.ExceptionHandlingService.HandleException(
                        ex, agentInstanceContext.EpStatementAgentInstanceHandle, ExceptionHandlerExceptionType.PROCESS,
                        theEvent);
                }
                finally
                {
                    if (agentInstanceContext.StatementContext.EpStatementHandle.HasTableAccess)
                    {
                        agentInstanceContext.TableExprEvaluatorContext.ReleaseAcquiredLocks();
                    }
                }
            }
        }
        public void TakeActionOnAllAgents(eOperationType i_OperationType)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            ThreadPool.SetMaxThreads(5, 5);
            LogManager.Instance.WriteInfo(Enum.GetName(i_OperationType.GetType(),i_OperationType)+" action on all agents started.");
            AgentInstance agent = null;
            bool finalResult = false;
            int numOfOperations = 0;
            int faultedOperations = 0;
            Task task = null;
            List<Task> tasks = new List<Task>();
            foreach (var keyvalueAgent in m_Agents)
            {

                task = new Task(() =>
                {
                    AgentInstance agente = keyvalueAgent.Value;

                    foreach (var service in agente.Services)
                    {
                        numOfOperations++;
                        finalResult = TakeAction(agente.ComputerName, agente.IP, service.Value, service.Key, i_OperationType);
                        if (!finalResult)
                        {
                            faultedOperations++;
                        }
                    }
                });
                task.Start();
                tasks.Add(task);
            }

                Task.WaitAll(tasks.ToArray());
                LogManager.Instance.WriteInfo(Enum.GetName(i_OperationType.GetType(),i_OperationType)+" action on all agents ended, elapsed: " + sw.Elapsed);
                LogManager.Instance.WriteInfo("Results : " + faultedOperations + "  out of " + numOfOperations + " operations failed");
        }
        public ActionResult <string> Post()
        {
            //Console.WriteLine("[*] Post request");
            //Step 1 agent
            if (string.IsNullOrEmpty(GetCookieValue("sessionid")))
            {
                StreamReader reader = new StreamReader(Request.Body, System.Text.Encoding.UTF8);
                return(StepOne(reader));
            }
            else
            {
                // Request has a cookie
                // Must be RC4 encrypted with serverkey
                // No other sec check over the cookie
                // Body must be entrcypted with session shared key iv pair

                try
                {
                    string decriptedAgentid = DecryptMessage(RedPeanutC2.server.GetServerKey(), GetCookieValue("sessionid"));

                    //Check if agentid exists in any state
                    IAgentInstance agent = null;
                    if (RedPeanutC2.server.GetAgents().ContainsKey(decriptedAgentid))
                    {
                        // Agent registered as active check message type Response, AgentIdReqMsg,
                        StreamReader reader = new StreamReader(Request.Body, System.Text.Encoding.UTF8);
                        agent = RedPeanutC2.server.GetAgents().GetValueOrDefault(decriptedAgentid);

                        return(PostResponse(reader, agent));
                    }
                    else
                    {
                        if (RedPeanutC2.server.GetInboundAgents().ContainsKey(decriptedAgentid))
                        {
                            // Cookie present and agent is in inboud queue post need to be Aes ChekIn
                            StreamReader reader = new StreamReader(Request.Body, System.Text.Encoding.UTF8);
                            agent = RedPeanutC2.server.GetInboundAgents().GetValueOrDefault(decriptedAgentid);
                            return(CheckIn(reader, agent));
                        }
                        else
                        {
                            //Check if agent is orfaned
                            AgentInstance agentInstance = dbContext.Agents.FirstOrDefault <AgentInstance>(s => s.agentid.Equals(decriptedAgentid));
                            if (agentInstance != null)
                            {
                                //
                                agent = CreateAgentInstance(RedPeanutC2.server, agentInstance.agentid,
                                                            agentInstance.agentPivotid, RedPeanutC2.server.GetServerKey(), agentInstance.address, agentInstance.port,
                                                            agentInstance.framework, Profileid, agentInstance.sessionkey, agentInstance.sessioniv);
                                AgentInstanceHttp agenthttp = (AgentInstanceHttp)agent;
                                agenthttp.Cookie = GetCookieValue("sessionid");
                                StreamReader reader = new StreamReader(Request.Body, System.Text.Encoding.UTF8);

                                return(CheckIn(reader, agenthttp));
                            }
                            else
                            {
                                // Agent does not exeists corrupted session or request not legitimate
                                Console.WriteLine("[x] Agent does not exeists corrupted session or request not legitimate");
                                Program.GetMenuStack().Peek().RePrintCLI();
                                httpContextAccessor.HttpContext.Response.Headers.Add("Connection", "Close");
                                return(NotFound());
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    // Operation error
                    Console.WriteLine("[x] Operation error {0}", e.Message);
                    Program.GetMenuStack().Peek().RePrintCLI();
                    httpContextAccessor.HttpContext.Response.Headers.Add("Connection", "Close");
                    return(NotFound());
                }
            }
        }
        private static void EvaluateEventForStatementInternal(EPServicesContext servicesContext, EventBean theEvent, IList <AgentInstance> agentInstances)
        {
            // context was created - reevaluate for the given event
            var callbacks = new ArrayDeque <FilterHandle>(2);

            servicesContext.FilterService.Evaluate(theEvent, callbacks);   // evaluates for ALL statements
            if (callbacks.IsEmpty())
            {
                return;
            }

            // there is a single callback and a single context, if they match we are done
            if (agentInstances.Count == 1 && callbacks.Count == 1)
            {
                var agentInstance = agentInstances[0];
                if (agentInstance.AgentInstanceContext.StatementId == callbacks.First.StatementId)
                {
                    Process(agentInstance, servicesContext, callbacks, theEvent);
                }
                return;
            }

            // use the right sorted/unsorted Map keyed by AgentInstance to sort
            var isPrioritized = servicesContext.ConfigSnapshot.EngineDefaults.Execution.IsPrioritized;
            IDictionary <AgentInstance, object> stmtCallbacks;

            if (!isPrioritized)
            {
                stmtCallbacks = new Dictionary <AgentInstance, object>();
            }
            else
            {
                stmtCallbacks = new SortedDictionary <AgentInstance, object>(AgentInstanceComparator.INSTANCE);
            }

            // process all callbacks
            foreach (var filterHandle in callbacks)
            {
                // determine if this filter entry applies to any of the affected agent instances
                var           statementId        = filterHandle.StatementId;
                AgentInstance agentInstanceFound = null;
                foreach (var agentInstance in agentInstances)
                {
                    if (agentInstance.AgentInstanceContext.StatementId == statementId)
                    {
                        agentInstanceFound = agentInstance;
                        break;
                    }
                }
                if (agentInstanceFound == null)
                {   // when the callback is for some other stmt
                    continue;
                }

                var handleCallback = (EPStatementHandleCallback)filterHandle;
                var handle         = handleCallback.AgentInstanceHandle;

                // Self-joins require that the internal dispatch happens after all streams are evaluated.
                // Priority or preemptive settings also require special ordering.
                if (handle.CanSelfJoin || isPrioritized)
                {
                    var stmtCallback = stmtCallbacks.Get(agentInstanceFound);
                    if (stmtCallback == null)
                    {
                        stmtCallbacks.Put(agentInstanceFound, handleCallback);
                    }
                    else if (stmtCallback is ICollection <FilterHandle> )
                    {
                        var collection = (ICollection <FilterHandle>)stmtCallback;
                        if (!collection.Contains(handleCallback)) // De-duplicate for Filter OR expression paths
                        {
                            collection.Add(handleCallback);
                        }
                    }
                    else
                    {
                        var deque = new ArrayDeque <FilterHandle>(4);
                        deque.Add((EPStatementHandleCallback)stmtCallback);
                        if (stmtCallback != handleCallback) // De-duplicate for Filter OR expression paths
                        {
                            deque.Add(handleCallback);
                        }
                        stmtCallbacks.Put(agentInstanceFound, deque);
                    }
                    continue;
                }

                // no need to be sorted, process
                Process(agentInstanceFound, servicesContext, Collections.SingletonList <FilterHandle>(handleCallback), theEvent);
            }

            if (stmtCallbacks.IsEmpty())
            {
                return;
            }

            // Process self-join or sorted prioritized callbacks
            foreach (var entry in stmtCallbacks)
            {
                var agentInstance = entry.Key;
                var callbackList  = entry.Value;
                if (callbackList is ICollection <FilterHandle> )
                {
                    Process(agentInstance, servicesContext, (ICollection <FilterHandle>)callbackList, theEvent);
                }
                else
                {
                    Process(agentInstance, servicesContext, Collections.SingletonList <FilterHandle>((FilterHandle)callbackList), theEvent);
                }
                if (agentInstance.AgentInstanceContext.EpStatementAgentInstanceHandle.IsPreemptive)
                {
                    return;
                }
            }
        }
        public void EvaluateEventForStatement(
            EventBean theEvent,
            IList<AgentInstance> agentInstances,
            AgentInstanceContext agentInstanceContextCreate)
        {
            // context was created - reevaluate for the given event
            ArrayDeque<FilterHandle> callbacks = new ArrayDeque<FilterHandle>(2);
            agentInstanceContextCreate.FilterService.Evaluate(theEvent, callbacks, agentInstanceContextCreate); // evaluates for ALL statements
            if (callbacks.IsEmpty()) {
                return;
            }

            // there is a single callback and a single context, if they match we are done
            if (agentInstances.Count == 1 && callbacks.Count == 1) {
                AgentInstance agentInstance = agentInstances[0];
                AgentInstanceContext agentInstanceContext = agentInstance.AgentInstanceContext;
                FilterHandle callback = callbacks.First;
                if (agentInstanceContext.StatementId == callback.StatementId &&
                    agentInstanceContext.AgentInstanceId == callback.AgentInstanceId) {
                    Process(agentInstance, callbacks, theEvent);
                }

                return;
            }

            // use the right sorted/unsorted Map keyed by AgentInstance to sort
            bool isPrioritized = agentInstanceContextCreate.RuntimeSettingsService.ConfigurationRuntime.Execution
                .IsPrioritized;
            IDictionary<AgentInstance, object> stmtCallbacks;
            if (!isPrioritized) {
                stmtCallbacks = new Dictionary<AgentInstance, object>();
            }
            else {
                stmtCallbacks = new OrderedListDictionary<AgentInstance, object>(AgentInstanceComparator.INSTANCE);
            }

            // process all callbacks
            foreach (FilterHandle filterHandle in callbacks) {
                EPStatementHandleCallbackFilter handleCallback = (EPStatementHandleCallbackFilter) filterHandle;

                // determine if this filter entry applies to any of the affected agent instances
                int statementId = filterHandle.StatementId;
                AgentInstance agentInstanceFound = null;
                foreach (AgentInstance agentInstance in agentInstances) {
                    AgentInstanceContext agentInstanceContext = agentInstance.AgentInstanceContext;
                    if (agentInstanceContext.StatementId == statementId &&
                        agentInstanceContext.AgentInstanceId == handleCallback.AgentInstanceId) {
                        agentInstanceFound = agentInstance;
                        break;
                    }
                }

                if (agentInstanceFound == null) { // when the callback is for some other stmt
                    continue;
                }

                EPStatementAgentInstanceHandle handle = handleCallback.AgentInstanceHandle;

                // Self-joins require that the internal dispatch happens after all streams are evaluated.
                // Priority or preemptive settings also require special ordering.
                if (handle.IsCanSelfJoin || isPrioritized) {
                    var stmtCallback = stmtCallbacks.Get(agentInstanceFound);
                    if (stmtCallback == null) {
                        stmtCallbacks.Put(agentInstanceFound, handleCallback);
                    }
                    else if (stmtCallback is ArrayDeque<FilterHandle> callbackFilterDeque) {
                        if (!callbackFilterDeque.Contains(handleCallback)) {
                            // De-duplicate for Filter OR expression paths
                            callbackFilterDeque.Add(handleCallback);
                        }
                    }
                    else {
                        var filterDeque = new ArrayDeque<FilterHandle>(4);
                        filterDeque.Add((FilterHandle) stmtCallback);
                        if (stmtCallback != handleCallback) { // De-duplicate for Filter OR expression paths
                            filterDeque.Add(handleCallback);
                        }

                        stmtCallbacks.Put(agentInstanceFound, filterDeque);
                    }

                    continue;
                }

                // no need to be sorted, process
                Process(agentInstanceFound, Collections.SingletonList<FilterHandle>(handleCallback), theEvent);
            }

            if (stmtCallbacks.IsEmpty()) {
                return;
            }

            // Process self-join or sorted prioritized callbacks
            foreach (KeyValuePair<AgentInstance, object> entry in stmtCallbacks) {
                AgentInstance agentInstance = entry.Key;
                object callbackList = entry.Value;
                if (callbackList is ICollection<FilterHandle> filterHandleCollection) {
                    Process(agentInstance, filterHandleCollection, theEvent);
                }
                else {
                    Process(
                        agentInstance,
                        Collections.SingletonList<FilterHandle>((FilterHandle) callbackList),
                        theEvent);
                }

                if (agentInstance.AgentInstanceContext.EpStatementAgentInstanceHandle.IsPreemptive) {
                    return;
                }
            }
        }