예제 #1
0
        public void GetTaskTestFromServer()
        {
            AgentTask target = AgentTask.GetStartedInstance(); // TODO: Initialize to an appropriate value
            string    xmlStr = target.GetTask();

            Assert.IsTrue(xmlStr != null);
        }
예제 #2
0
    // Utility Scoring Method, uses switch to allow passing of all Tasks into one function and sorted there.
    private float EvalUtility(AgentTask evalTask)
    {
        float score = 0;

        switch (evalTask.type)
        {
        case Tasks.Eat:
            score = ScoreEat();
            Debug.Log(score);
            break;

        case Tasks.Sleep:
            score = ScoreSleep();
            Debug.Log(score);
            break;

        case Tasks.GatherPollen:
            score = ScoreGatherPollen();
            Debug.Log(score);
            break;

        case Tasks.StorePollen:
            score = ScoreDepositPollen();
            Debug.Log(score);
            break;

        default:
            break;
        }

        return(score);
    }
예제 #3
0
 public OutboundTask(string AgentName, AgentTask agentTask)
 {
     this.Name      = agentTask.Name;
     this.AgentName = AgentName;
     this.Action    = agentTask.Action;
     this.Command   = agentTask.Command;
 }
예제 #4
0
        AgentTask GetBestTask(TaskPool pool)
        {
            AgentTask action    = null;
            float     bestValue = 0.0f;

            sb.Append("\n=====   Task Priorities   =====");

            foreach (AgentTask a in pool.AllTasks)
            {
                float value = a.Priority;
                if (a == pool.CurrentTask)
                {
                    value += 0.1f;                        // "Commitment"
                }
                sb.Append("\n" + value.ToString("N3") + " : " + a.GetType().Name);

                if (action == null || value > bestValue)
                {
                    action    = a;
                    bestValue = value;
                }
            }


            return(action);
        }
예제 #5
0
        /// <summary>
        /// Request tasks xml from server
        /// </summary>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public string RequestTasks()
        {
            // it is for test
            // var taskxml = XDocument.Load(@"F:\DFLinkReload\TaskXML.xml");
            var taskxml = AgentTask.GetStartedInstance().GetTask();

            return(taskxml);
        }
예제 #6
0
    private void Start()
    {
        attachedController = GetComponent <AgentSteering>();
        attachedBase       = GetComponent <AgentBase>();

        attachedController.SetTargetTile(attachedBase.currentTileIndex);

        currentTask = new AgentTask(Tasks.Null, attachedBase);
        PrepTaskList();

        UpdateAgent();
    }
예제 #7
0
        public void ThenStockPriceDataAppearsWithinMinutes(int amount)
        {
            var agent = ScenarioContext.Current.Get <IPriceDataAgent>();

            var count = agent.GetStockPriceCount();

            // TODO - parameterise the units (mins, secs etc)
            var periodToWait = TimeSpan.FromMinutes(amount);

            var task = new AgentTask(() => { return(agent.GetStockPriceCount() > count); }, periodToWait);

            Assert.IsTrue(task.WaitUntilDone());
        }
예제 #8
0
        public void GetTaskTest()
        {
            ICallerFactory original = AgentSetting.CallerFactory;

            AgentSetting.CallerFactory = new TestCallerFactory();

            AgentTask target = AgentTask.GetStartedInstance(); // TODO: Initialize to an appropriate value

            target.GetTask();
            AgentSetting.CallerFactory = original;

            Assert.AreEqual(AgentSetting.AddressUrl + AgentSetting.CommandTaskGet, TestCallerFactory.UrlString);
            Assert.AreEqual(@"{""LicenseKey"":""xxxxx-xxxxxx""}", TestCallerFactory.JsonString);
        }
예제 #9
0
    //Detemine next best Task for the Agent to take on based on Task Utility
    private void EvalTasks()
    {
        AgentTask bestTask  = new AgentTask(Tasks.Null, attachedBase);
        float     bestScore = 0;

        foreach (var Task in availableTasks)
        {
            Task.SetWeight(EvalUtility(Task));

            // Innocent method of just setting the Task with highest weight to be our current Task
            if (Task.weight >= bestScore)
            {
                bestScore = Task.weight;
                bestTask  = Task;
            }
        }

        currentTask  = bestTask;
        taskComplete = false;
        taskReached  = false;
        Debug.Log(currentTask.type);
    }
예제 #10
0
        public bool UpdateAgentTask(AgentTask agentTask)
        {
            var query = @"UPDATE [AgentTasks] SET [LastMessageId] = @LastMessageId, [ConversationId] = @ConversationId, [UpdatedTime] = @UpdatedTime WHERE Id = @Id";
            var param = new DynamicParameters();

            param.Add("@Id", agentTask.id);
            param.Add("@ConversationId", agentTask.ConversationId);
            param.Add("@LastMessageId", agentTask.LastMessageId);
            param.Add("@UdpatedTime", DateTime.UtcNow);
            int rowsAffected;

            using (var connection = _connectionFactory.GetConnection)
            {
                rowsAffected = SqlMapper.Execute(connection, query, param, commandType: CommandType.Text);
            }
            // CacheBase.cacheDeleteCacheSame(new List<string>() {agentTask.id });
            if (rowsAffected > 0)
            {
                return(true);
            }
            return(false);
        }
예제 #11
0
        // Update is called once per frame
        void Update()
        {
            sb = new System.Text.StringBuilder("Agent\t:: " + gameObject.name);

            sb.Append("\n===============================");

            foreach (var kvp in TaskPools.OrderBy(m => m.Key))
            {
                var pool = kvp.Value;
                sb.Append("\nPool \t:: " + kvp.Key);
                sb.Append("\n=====    Current Task     =====");

                if (pool.CurrentTask != null)
                {
                    sb.Append("\n" + pool.CurrentTask.GetType().Name + (!pool.CurrentTask.CanExit ? " [LOCKED]" : ""));
                    sb.Append("\n> " + ((pool.CurrentTask.CurrentAction != null) ? pool.CurrentTask.CurrentAction.GetType().Name : "<no action>"));
                }
                else
                {
                    sb.Append("\n<no task>\n > <no action>");
                }

                AgentTask best = GetBestTask(pool);

                if (pool.CurrentTask == null || (pool.CurrentTask != best && pool.CurrentTask.CanExit))
                {
                    pool.CurrentTask = best;
                }


                if (pool.CurrentTask)
                {
                    pool.CurrentTask.UpdateTask();
                }

                sb.Append("\n===============================");
            }
        }
예제 #12
0
        public bool CreateAgentTask(AgentTask agentTask)
        {
            var query = @"INSERT INTO AgentTasks([Id],[AgentId],[TaskId],[ConversationId],[Type],[CreatedTime]) VALUES(@Id, @AgentId, @TaskId, @ConversationId, @Type, @CreatedTime)";
            var param = new DynamicParameters();

            param.Add("@Id", agentTask.id);
            param.Add("@AgentId", agentTask.AgentId);
            param.Add("@TaskId", agentTask.TaskId);
            param.Add("@ConversationId", agentTask.ConversationId);
            param.Add("@Type", agentTask.Type);
            param.Add("@CreatedTime", agentTask.created_time);
            int rowsAffected;

            using (var connection = _connectionFactory.GetConnection)
            {
                rowsAffected = SqlMapper.Execute(connection, query, param, commandType: CommandType.Text);
            }
            //  CacheBase.cacheDeleteCacheSame(new List<string>() {agentTask.id });
            if (rowsAffected > 0)
            {
                return(true);
            }
            return(false);
        }
예제 #13
0
        private TaskResult ProcessCommand(AgentTask agentTask)
        {
            bool       success   = false;
            bool       complete  = false;
            string     result    = "Could not run task";
            List <IOC> iocs      = new List <IOC>();
            string     type      = null;
            string     content   = null;
            string     contentId = null;

            if (agentTask.Action.ToLower() == "run")
            {
#if DEBUG
                Logging.Write("CommandService", "Got RUN task");
#endif

                // Find the command we're looking for
                string taskCommand = agentTask.Command;
                int    index       = agentTask.Command.IndexOf(" ");
                if (index > 0)
                {
                    taskCommand = agentTask.Command.Substring(0, index);
                }
                var command = AvailableCommands.Find(x => x.Name == taskCommand);

                // Run the command
                if (command != null)
                {
                    Dictionary <string, string> argsDictionary = new Dictionary <string, string>();

                    if (index > 0)
                    {
                        string taskArgs = agentTask.Command.Substring(index + 1);
                        argsDictionary = JsonConvert.DeserializeObject <Dictionary <string, string> >(taskArgs);
                    }
                    try {
                        CommandOutput output = command.Execute(argsDictionary);
                        result    = output.Message;
                        success   = output.Success;
                        complete  = output.Complete;
                        iocs      = output.IOCs;
                        type      = output.Type;
                        contentId = output.ContentId;
                        content   = output.Content;
                    }
                    catch (Exception e) {
                        result   = e.Message;
                        success  = false;
                        complete = true;
                    }
                }
                else
                {
                    success  = false;
                    complete = true;
                    result   = String.Format($"Couldn't find command named: {agentTask.Command}");
                }
            }

            else if (agentTask.Action.ToLower() == "set")
            {
#if DEBUG
                Logging.Write("CommandService", $"Got SET task: {agentTask.Command}");
#endif
                result = "";
                string[] command = agentTask.Command.Split(':');
                switch (command[0].ToLower())
                {
                case "name":
                    State.Name = command[1];
                    break;

                case "beaconinterval":
                    State.Sleep = Int32.Parse(command[1]);
                    break;

                case "jitter":
                    State.Jitter = float.Parse(command[1]);
                    break;

                case "password":
                    State.Password = command[1];
                    break;

                case "payloadname":
                    State.PayloadName = null;
                    break;

                case "stagingid":
                    State.StagingId = null;
                    break;

                case "expirationdate":
                    State.ExpirationDate = DateTime.Parse(command[1]);
                    break;

                default:
                    result = $"No setting matches {command[0]}";
                    break;
                }

                complete = true;
                success  = true;
                if (String.IsNullOrEmpty(result))
                {
                    result = String.Format($"Updated {command[0]} to {command[1]}");
                }
            }

            else if (agentTask.Action.ToLower() == "load")
            {
                string[] commandParts = agentTask.Command.Split(' ');
                string   name         = commandParts[1];
                byte[]   bytes        = Convert.FromBase64String(commandParts[2]);
                if (commandParts[0].ToLower() == "module")
                {
                    TaskResult moduleResult = LoadModule(agentTask.Name, name, bytes);
                    State.ResultQueue.Add(moduleResult);
                    return(moduleResult);
                }
                if (commandParts[0].ToLower() == "transport")
                {
                    // moduleResult = LoadTransport()
                }
            }

            else if (agentTask.Action.ToLower() == "exit")
            {
                Environment.Exit(0);
            }

            TaskResult taskResult = new TaskResult();
            taskResult.Message   = result;
            taskResult.Success   = success;
            taskResult.Complete  = complete;
            taskResult.TaskName  = agentTask.Name;
            taskResult.Type      = type;
            taskResult.ContentId = contentId;
            taskResult.Content   = content;
            taskResult.IOCs      = iocs;
            State.ResultQueue.Add(taskResult);
#if DEBUG
            Logging.Write("CommandService", String.Format("Returning Results: {0}", result));
#endif
            return(taskResult);
        }
        public async Task Handle(NewConsoleMessage newConsoleMessage, string replyTo, string correlationId)
        {
            // Reset Error stuff
            error        = false;
            errorMessage = "";

            // figure out what agent we're dealing with
            Agent agent = _taskRepository.GetAgent(newConsoleMessage.AgentId);

            agent.AgentType = _taskRepository.GetAgentType(agent.AgentTypeId);

            // flesh out and save the ConsoleMessage object
            ConsoleMessage consoleMessage = new ConsoleMessage();

            consoleMessage.AgentId  = newConsoleMessage.AgentId;
            consoleMessage.UserId   = newConsoleMessage.UserId;
            consoleMessage.Agent    = agent;
            consoleMessage.User     = _taskRepository.GetUser(consoleMessage.UserId.Value);
            consoleMessage.Content  = newConsoleMessage.Content;
            consoleMessage.Display  = newConsoleMessage.Display;
            consoleMessage.Received = DateTime.UtcNow;
            consoleMessage.Type     = "AgentTask";
            _taskRepository.Add(consoleMessage);

            // Announce our new message to Rabbit
            ConsoleMessageAnnouncement messageAnnouncement = new ConsoleMessageAnnouncement();

            messageAnnouncement.Success        = true;
            messageAnnouncement.Username       = consoleMessage.User.Username;
            messageAnnouncement.ConsoleMessage = consoleMessage;
            _eventBus.Publish(messageAnnouncement);

            // These are the commands we allow. If one of these isn't the first part of a command
            List <string> allowedActions = new List <string>();

            allowedActions.Add("HELP");
            allowedActions.Add("SHOW");
            allowedActions.Add("LOAD");
            allowedActions.Add("SET");
            allowedActions.Add("USE");
            allowedActions.Add("RUN");
            allowedActions.Add("EXIT");

            // we assume that the command is a RUN command
            string action = "RUN";

            string[] consoleMessageComponents = consoleMessage.Content.Split(' ');
            if (consoleMessageComponents.Length > 0)
            {
                if (allowedActions.Contains(consoleMessageComponents[0].ToUpper()))
                {
                    action = consoleMessageComponents[0].ToUpper();
                }
            }

            // if this is a SHOW or HELP commmand, we won't be sending anything to the agent
            // so lets take care of that here:
            AgentDetails.Language         = _taskRepository.GetLanguage(consoleMessage.Agent.AgentType.LanguageId);
            AgentDetails.AvailableModules = _taskRepository.GetModules(AgentDetails.Language.Id);
            AgentDetails.LoadedModules    = _taskRepository.GetAgentModules(consoleMessage.AgentId);
            AgentDetails.AgentType        = consoleMessage.Agent.AgentType;

            if (action == "HELP")
            {
                ConsoleMessage message = ProcessHelpMessage(consoleMessage);
                _taskRepository.Add(message);

                ConsoleMessageAnnouncement response = new ConsoleMessageAnnouncement();
                response.Success        = true;
                response.Username       = "******";
                response.ConsoleMessage = message;
                _eventBus.Publish(response);
            }

            else if (action == "SHOW")
            {
                ConsoleMessage message = ProcessShowMessage(consoleMessage);
                _taskRepository.Add(message);

                ConsoleMessageAnnouncement response = new ConsoleMessageAnnouncement();
                response.Success        = true;
                response.Username       = "******";
                response.ConsoleMessage = message;
                _eventBus.Publish(response);
            }

            else
            {
                // We'll be tasking the agent to do something so lets create an agentTask
                AgentTask agentTask = new AgentTask();
                agentTask.Action           = action;
                agentTask.AgentId          = consoleMessage.AgentId;
                agentTask.ConsoleMessageId = consoleMessage.Id;
                agentTask.ConsoleMessage   = consoleMessage;
                agentTask.Agent            = consoleMessage.Agent;

                // Package the AgentTask into a envelope for seralization & encryption.
                // Then process the ACTION and populate CONTENTS appropriately
                Dictionary <String, String> outboundMessage = new Dictionary <String, String>();
                outboundMessage.Add("AgentName", agentTask.Agent.Name);
                outboundMessage.Add("Name", agentTask.Name);
                outboundMessage.Add("Action", agentTask.Action);

                // Message formats
                // * load stdlib
                // * load dotnet/stdlib
                // * load transport/dns
                if (agentTask.Action == "LOAD")
                {
                    LoadModule msg = new LoadModule();
                    if (consoleMessageComponents[1].Contains("/"))
                    {
                        msg.Language = consoleMessageComponents[1].Split("/")[0];
                        msg.Name     = consoleMessageComponents[1].Split("/")[0];
                    }
                    else
                    {
                        msg.Language = (_taskRepository.GetLanguage(consoleMessage.Agent.AgentType.LanguageId)).Name;
                        msg.Name     = consoleMessageComponents[1];
                    }

                    bool LoadSuccess = false;
                    foreach (Module module in AgentDetails.AvailableModules)
                    {
                        if (String.Equals(module.Name, msg.Name, StringComparison.CurrentCultureIgnoreCase))
                        {
                            _eventBus.Publish(msg, null, null, true);
                            string         message        = _eventBus.ResponseQueue.Take();
                            ModuleResponse moduleResponse = JsonConvert.DeserializeObject <ModuleResponse>(message);
                            outboundMessage.Add("Command", moduleResponse.Contents);
                            LoadSuccess = true;

                            AgentUpdated agentUpdated = new AgentUpdated {
                                Success = true, Agent = agentTask.Agent
                            };
                            _eventBus.Publish(agentUpdated);

                            break;
                        }
                    }

                    if (!LoadSuccess)
                    {
                        error        = true;
                        errorMessage = $"Module {msg.Name} is not a valid module. Use the 'show modules' command to view available modules";
                    }
                }

                // Message formats
                // * set beacon:5
                else if (agentTask.Action == "SET")
                {
                    outboundMessage.Add("Command", consoleMessageComponents[1]);
                }

                else if (agentTask.Action == "EXIT")
                {
                    outboundMessage.Add("Command", "exit");
                }
                // Example commands:
                // * ls
                // * ls "C:\Program Files"
                // * ls /path:"C:\Program Files"
                if (agentTask.Action == "RUN")
                {
                    string   submittedCommand = consoleMessage.Content;
                    string[] processedArgs    = null;

                    // check to see if we have parameters (for example: ls /path:foo)
                    int index = submittedCommand.IndexOf(' ');
                    if (index > 0)
                    {
                        // change submittedCommand to just the first part of the command (ex: ls)
                        submittedCommand = submittedCommand.Substring(0, index);
                        string submittedArgs = consoleMessage.Content.Substring(index + 1);
                        if (submittedArgs.Length > 0)
                        {
                            processedArgs = SplitArguments(submittedArgs);
                        }
                    }

                    // Check if command is available
                    try
                    {
                        Command commandObject = _taskRepository.GetCommand(submittedCommand);
                        if (!AgentDetails.IsModuleLoaded(commandObject.Module))
                        {
                            error        = true;
                            errorMessage = $"The module for this command isn't loaded. You can load it by running: 'load {commandObject.Module.Name}'";
                        }
                    }
                    catch
                    {
                        error        = true;
                        errorMessage = $"{submittedCommand} is not a valid command for this agent. To view available commands, run: 'show commands'";
                    }

                    if (!error)
                    {
                        FactionCommand factionCommand = ProcessCommand(submittedCommand, processedArgs);
                        string         command        = factionCommand.Command;
                        if (factionCommand.Arguments.Count > 0)
                        {
                            command = $"{factionCommand.Command} {JsonConvert.SerializeObject(factionCommand.Arguments)}";
                        }
                        outboundMessage.Add("Command", command);
                    }
                }

                // If there's an error, send it back
                if (error)
                {
                    ConsoleMessage message = new ConsoleMessage();
                    message.AgentId     = consoleMessage.AgentId;
                    message.AgentTaskId = agentTask.Id;
                    message.UserId      = 1;
                    message.Type        = "AgentTaskError";
                    message.Display     = errorMessage;
                    _taskRepository.Add(message);

                    ConsoleMessageAnnouncement response = new ConsoleMessageAnnouncement();
                    response.Success        = true;
                    response.Username       = "******";
                    response.ConsoleMessage = message;
                    _eventBus.Publish(response);
                }
                // Else, create a new task for the agent
                else
                {
                    // update agentTask with final command format and save it
                    agentTask.Command = outboundMessage["Command"];
                    _taskRepository.Add(agentTask);

                    // update the incoming consoleMessage with this task Id
                    consoleMessage.AgentTaskId = agentTask.Id;
                    _taskRepository.Update(consoleMessage.Id, consoleMessage);

                    string jsonOutboundMessage             = JsonConvert.SerializeObject(outboundMessage);
                    Dictionary <string, string> encCommand = Crypto.Encrypt(jsonOutboundMessage, agentTask.Id, agentTask.Agent.AesPassword);

                    // Create a AgentTaskMessage object with the seralized/encrypted message contents
                    AgentTaskMessage agentTaskMessage = new AgentTaskMessage();
                    agentTaskMessage.Agent       = agentTask.Agent;
                    agentTaskMessage.Message     = encCommand["encryptedMsg"];
                    agentTaskMessage.AgentId     = consoleMessage.Agent.Id;
                    agentTaskMessage.AgentTaskId = agentTask.Id;
                    agentTaskMessage.AgentTask   = agentTask;
                    agentTaskMessage.Hmac        = encCommand["hmac"];
                    agentTaskMessage.Iv          = encCommand["iv"];
                    agentTaskMessage.Sent        = false;
                    _taskRepository.Add(agentTaskMessage);
                }
            }
        }
예제 #15
0
 public void SendInvoke(ICallable function, IBindingEnvironment environment, object[] arguments)
 {
     AgentTask task = new AgentTask() { Callable = function, Environment = environment, Arguments = arguments };
     this.channel.Send(task);
 }
예제 #16
0
        /// <summary>
        /// 添加自定义任务
        /// </summary>
        /// <param name="identity">标识符</param>
        /// <param name="enableBit">占用位</param>
        /// <param name="task">任务</param>
        public void AddCustomTask(String identity, int enableBit, AgentTask task)
        {
            Job4Agent job = new Job4Agent(identity, enableBit, task);

            Scheduler.AddJob(job);
        }
        public async Task Handle(NewStagingMessage newStagingMessage, string replyTo, string correlationId)
        {
            Console.WriteLine($"[i] Got StagingMessage Message.");
            Payload payload = _taskRepository.GetPayload(newStagingMessage.PayloadName);

            if (payload.Enabled)
            {
                StagingMessage stagingMessage = new StagingMessage();
                // Decode and Decrypt AgentTaskResponse
                stagingMessage.HMAC        = newStagingMessage.HMAC;
                stagingMessage.IV          = newStagingMessage.IV;
                stagingMessage.Message     = newStagingMessage.Message;
                stagingMessage.PayloadName = newStagingMessage.PayloadName;
                stagingMessage.TransportId = newStagingMessage.TransportId;
                stagingMessage.SourceIp    = newStagingMessage.SourceIp;
                stagingMessage.Payload     = payload;
                stagingMessage.PayloadId   = stagingMessage.Payload.Id;
                _taskRepository.Add(stagingMessage);

                // Decrypt Message from Agent
                string decryptedMessage = Crypto.Decrypt(stagingMessage);
                Console.WriteLine($"Got response {decryptedMessage}");

                // Process taskResults
                // TODO: Probably a better way to check if the message is blank.
                if ((decryptedMessage != "[]") || (!String.IsNullOrEmpty(decryptedMessage)))
                {
                    Agent agent = JsonConvert.DeserializeObject <Agent>(decryptedMessage);
                    agent.Name               = Utility.GenerateSecureString(12);
                    agent.AesPassword        = Utility.GenerateSecureString(32);
                    agent.InitialCheckin     = DateTime.UtcNow;
                    agent.LastCheckin        = DateTime.UtcNow;
                    agent.BeaconInterval     = stagingMessage.Payload.BeaconInterval;
                    agent.ExternalIp         = stagingMessage.SourceIp;
                    agent.TransportId        = stagingMessage.TransportId;
                    agent.Jitter             = stagingMessage.Payload.Jitter;
                    agent.AgentType          = _taskRepository.GetAgentType(stagingMessage.Payload.AgentTypeId);
                    agent.AgentType.Language = _taskRepository.GetLanguage(agent.AgentType.LanguageId);
                    agent.AgentTypeId        = stagingMessage.Payload.AgentType.Id;
                    agent.Transport          = _taskRepository.GetTransport(stagingMessage.TransportId);
                    agent.Payload            = stagingMessage.Payload;

                    _taskRepository.Add(agent);

                    NewAgent newAgent = new NewAgent(agent);
                    _eventBus.Publish(newAgent);

                    // Create Agent tasks to setup agent
                    List <OutboundTask> stagingTasks = new List <OutboundTask>();

                    AgentTask agentNameTask = new AgentTask();
                    agentNameTask.AgentId = agent.Id;
                    agentNameTask.Action  = "SET";
                    agentNameTask.Command = $"Name:{agent.Name}";
                    _taskRepository.Add(agentNameTask);
                    stagingTasks.Add(new OutboundTask(agent.Name, agentNameTask));

                    AgentTask passwordTask = new AgentTask();
                    passwordTask.AgentId = agent.Id;
                    passwordTask.Action  = "SET";
                    passwordTask.Command = $"Password:{agent.AesPassword}";
                    _taskRepository.Add(passwordTask);
                    stagingTasks.Add(new OutboundTask(agent.Name, passwordTask));

                    AgentTask beaconTask = new AgentTask();
                    beaconTask.AgentId = agent.Id;
                    beaconTask.Action  = "SET";
                    beaconTask.Command = $"BeaconInterval:{agent.BeaconInterval.ToString()}";
                    _taskRepository.Add(beaconTask);
                    stagingTasks.Add(new OutboundTask(agent.Name, beaconTask));

                    AgentTask jitterTask = new AgentTask();
                    jitterTask.AgentId = agent.Id;
                    jitterTask.Action  = "SET";
                    jitterTask.Command = $"Jitter:{agent.Jitter.ToString()}";
                    _taskRepository.Add(jitterTask);
                    stagingTasks.Add(new OutboundTask(agent.Name, jitterTask));

                    AgentTask payloadNameTask = new AgentTask();
                    payloadNameTask.AgentId = agent.Id;
                    payloadNameTask.Action  = "SET";
                    payloadNameTask.Command = $"PayloadName:null";
                    _taskRepository.Add(payloadNameTask);
                    stagingTasks.Add(new OutboundTask(agent.Name, payloadNameTask));

                    AgentTask stagerIdTask = new AgentTask();
                    stagerIdTask.AgentId = agent.Id;
                    stagerIdTask.Action  = "SET";
                    stagerIdTask.Command = $"StagingId:null";
                    _taskRepository.Add(stagerIdTask);
                    stagingTasks.Add(new OutboundTask(agent.Name, stagerIdTask));

                    // Convert outbound message to json and encrypt with the staging message password
                    string jsonOutboundMessage             = JsonConvert.SerializeObject(stagingTasks);
                    Dictionary <string, string> encCommand = Crypto.Encrypt(jsonOutboundMessage, agent.Id, stagingMessage.Payload.Key);

                    // Create a StagingResponse object with the seralized/encrypted message contents
                    StagingResponse stagingResponse = new StagingResponse();
                    stagingResponse.Agent   = agent;
                    stagingResponse.Message = encCommand["encryptedMsg"];
                    stagingResponse.AgentId = agent.Id;
                    stagingResponse.HMAC    = encCommand["hmac"];
                    stagingResponse.IV      = encCommand["iv"];
                    stagingResponse.Sent    = false;

                    _taskRepository.Add(stagingResponse);

                    // Package for delivery
                    string stagingJson    = JsonConvert.SerializeObject(new OutboundStagingResponse(stagingResponse));
                    string encodedMessage = Convert.ToBase64String(Encoding.UTF8.GetBytes(stagingJson));
                    Dictionary <string, string> outboundMessage = new Dictionary <string, string>();
                    outboundMessage["AgentName"] = agent.StagingId;
                    outboundMessage["Message"]   = encodedMessage;
                    _eventBus.Publish(outboundMessage, replyTo, correlationId);
                }
                else
                {
                    Console.WriteLine($"[i] Payload is disabled. Staging message ignored.");
                }
            }
        }
예제 #18
0
 public bool DeleteAgentTask(AgentTask agentTask)
 {
     throw new NotImplementedException();
 }