Example #1
0
    /// <summary>
    /// Causes the system to begin scanning for contexts.
    /// Should be called when an order is about to be issued.
    /// </summary>
    /// <param name="_faction">Determines the current faction being ordered.</param>
    public void Activate(FactionSettings _faction)
    {
        Deactivate();

        current_context.current_faction = _faction;
        InvokeRepeating("ScanContext", 0, scan_interval);
    }
Example #2
0
    /// <summary>
    /// Constructs an individual squaddie with the passed faction settings.
    /// </summary>
    /// <param name="_faction">The faction of the squaddie.</param>
    /// <param name="_pos">The location the squaddie should be placed.</param>
    /// <returns>A reference to the instantiated squaddie.</returns>
    public SquaddieAI CreateSquaddie(FactionSettings _faction, Vector3 _pos)
    {
        GameObject clone    = Instantiate(squaddie_prefab, _pos, Quaternion.identity);
        SquaddieAI squaddie = clone.GetComponent <SquaddieAI>();

        squaddie.Init(_faction);

        return(squaddie);
    }
Example #3
0
    public static bool SameFaction(SquaddieAI _a, FactionSettings _b)
    {
        if (_a == null || _b == null)
        {
            return(false);
        }

        return(SameFaction(_a.stats.faction_settings, _b));
    }
Example #4
0
 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
 {
     if (!optionsBuilder.IsConfigured)
     {
         FactionSettings config           = Utility.GetConfiguration();
         string          connectionString = $"Host={config.POSTGRES_HOST};Database={config.POSTGRES_DATABASE};Username={config.POSTGRES_USERNAME};Password={config.POSTGRES_PASSWORD}";
         optionsBuilder.UseNpgsql(connectionString);
         optionsBuilder.EnableSensitiveDataLogging();
     }
 }
Example #5
0
    /// <summary>
    /// Must be called after a squaddie is created to initialise key variables.
    /// </summary>
    /// <param name="_faction">The faction settings of the squaddie.</param>
    public void Init(FactionSettings _faction)
    {
        stats.faction_settings = _faction;
        squaddie_canvas.Init(_faction);

        foreach (MeshRenderer renderer in meshes)
        {
            renderer.material = _faction.base_material;
        }

        SetSelected(false);
    }
Example #6
0
    /// <summary>
    /// Creates a new squad with the passed faction settings.
    /// The squaddies are arranged in a circular pattern at the passed position, based on the squad size.
    /// </summary>
    /// <param name="_faction">The faction of the squad.</param>
    /// <param name="_num_squaddies">The size of the squad.</param>
    /// <param name="_pos">The where the squad should be arranged.</param>
    /// <returns>A reference to the instantiated squad.</returns>
    public SquadManager CreateSquad(FactionSettings _faction, int _num_squaddies, Vector3 _pos)
    {
        SquadManager squad_manager = new SquadManager(_faction);

        for (int i = 0; i < _num_squaddies; ++i)
        {
            SquaddieAI squaddie = CreateSquaddie(_faction, _pos);
            squaddie.transform.position = JHelper.PosToCirclePos(_pos, _num_squaddies, i, _num_squaddies * 0.5f);

            squad_manager.AddSquaddie(squaddie);
        }

        return(squad_manager);
    }
Example #7
0
    public static bool SameFaction(FactionSettings _a, FactionSettings _b)
    {
        if (_a == null || _b == null)
        {
            return(false);
        }

        if (_a.faction == _b.faction)
        {
            return(true);
        }

        return(false);
    }
Example #8
0
        public static void Main(string[] args)
        {
            FactionSettings factionSettings  = Utility.GetConfiguration();
            string          connectionString = $"Host={factionSettings.POSTGRES_HOST};Database={factionSettings.POSTGRES_DATABASE};Username={factionSettings.POSTGRES_USERNAME};Password={factionSettings.POSTGRES_PASSWORD}";

            var host = new HostBuilder()
                       .ConfigureAppConfiguration((hostingContext, config) =>
            {
                // config.AddJsonFile("appsettings.json", optional: true);
            })
                       .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                logging.AddConsole();
                logging.AddFilter("Microsoft.EntityFrameworkCore.Database.Command", LogLevel.Warning);
            })
                       .ConfigureServices((hostContext, services) =>
            {
                services.AddEntityFrameworkNpgsql().AddDbContext <FactionDbContext>(options =>
                                                                                    options.UseNpgsql(connectionString)
                                                                                    );

                // Open a connection to RabbitMQ and register it with DI
                services.AddSingleton <IRabbitMQPersistentConnection>(options =>
                {
                    var factory = new ConnectionFactory()
                    {
                        HostName = factionSettings.RABBIT_HOST,
                        UserName = factionSettings.RABBIT_USERNAME,
                        Password = factionSettings.RABBIT_PASSWORD
                    };
                    return(new DefaultRabbitMQPersistentConnection(factory));
                });

                services.AddSingleton <FactionRepository>();

                // Register the RabbitMQ EventBus with all the supporting Services (Event Handlers) with DI
                RegisterEventBus(services);

                // Configure the above registered EventBus with all the Event to EventHandler mappings
                ConfigureEventBus(services);

                // Ensure the DB is initalized and seeding data
                // SeedData(services);
                bool dbLoaded = false;
                Console.WriteLine("Checking if database is ready");
                using (var context = new FactionDbContext())
                {
                    while (!dbLoaded)
                    {
                        try {
                            var language = context.Language.CountAsync();
                            language.Wait();
                            dbLoaded = true;
                            Console.WriteLine("Database is ready");
                        }
                        catch {
                            Console.WriteLine("Database not ready, waiting for 5 seconds");
                            Task.Delay(5000).Wait();
                        }
                    }
                }

                var sp = services.BuildServiceProvider();
                FactionRepository dbRepository = sp.GetService <FactionRepository>();

                Loader.LoadSelf(dbRepository);
                Loader.LoadAgents(dbRepository);
                Loader.LoadModules(dbRepository);
            })
                       .Build();;

            host.Start();
        }
        public async Task Handle(NewAgentCheckin agentCheckinMsg, string replyTo, string correlationId)
        {
            Console.WriteLine($"[i] Got AgentCheckin Message.");


            Transport transport = _taskRepository.GetTransport(agentCheckinMsg.TransportId);


            // Check in agent
            Agent agent = _taskRepository.GetAgent(agentCheckinMsg.AgentName);

            agent.TransportId = agentCheckinMsg.TransportId;
            agent.ExternalIp  = agentCheckinMsg.SourceIp;
            agent.LastCheckin = DateTime.UtcNow;

            if (!agent.Visible)
            {
                agent.Visible = true;
                AgentUpdated update = new AgentUpdated();
                update.Success = true;
                update.Agent   = agent;
                _eventBus.Publish(update);
            }
            _taskRepository.Update(agent.Id, agent);

            AgentCheckinAnnouncement agentCheckinAnnouncement = new AgentCheckinAnnouncement();

            agentCheckinAnnouncement.Id            = agent.Id;
            agentCheckinAnnouncement.SourceIp      = agentCheckinMsg.SourceIp;
            agentCheckinAnnouncement.TransportId   = agentCheckinMsg.TransportId;
            agentCheckinAnnouncement.TransportName = transport.Name;
            agentCheckinAnnouncement.Received      = agent.LastCheckin.Value;
            _eventBus.Publish(agentCheckinAnnouncement);

            // Decode and Decrypt AgentTaskResponse
            if (!String.IsNullOrEmpty(agentCheckinMsg.Message))
            {
                AgentCheckin agentCheckin = new AgentCheckin();
                agentCheckin.SourceIp    = agentCheckinMsg.SourceIp;
                agentCheckin.TransportId = agentCheckinMsg.TransportId;
                agentCheckin.HMAC        = agentCheckinMsg.HMAC;
                agentCheckin.IV          = agentCheckinMsg.IV;
                agentCheckin.Message     = agentCheckinMsg.Message;
                agentCheckin.AgentId     = agent.Id;
                agentCheckin.Agent       = agent;
                _taskRepository.Add(agentCheckin);

                // Decrypt Message from Agent
                string decryptedMessage = Crypto.Decrypt(agentCheckin);
                Console.WriteLine($"Got response {decryptedMessage}");
                if (!agent.Visible)
                {
                    agent.Visible = true;
                    _taskRepository.Update(agent.Id, agent);
                }
                // Process taskResults
                // TODO: Probably a better way to check if the message is blank.
                if ((decryptedMessage != "[]") || (!String.IsNullOrEmpty(decryptedMessage)))
                {
                    List <AgentTaskUpdate> taskUpdates = JsonConvert.DeserializeObject <List <AgentTaskUpdate> >(decryptedMessage);
                    foreach (AgentTaskUpdate taskUpdate in taskUpdates)
                    {
                        taskUpdate.AgentTask = _taskRepository.GetAgentTask(taskUpdate.TaskName);
                        taskUpdate.AgentId   = taskUpdate.AgentTask.AgentId;
                        taskUpdate.Received  = DateTime.UtcNow;

                        foreach (IOC ioc in taskUpdate.IOCs)
                        {
                            ioc.UserId            = taskUpdate.AgentTask.ConsoleMessage.UserId.Value;
                            ioc.AgentTaskUpdateId = taskUpdate.Id;
                        }
                        _taskRepository.Add(taskUpdate);

                        if (taskUpdate.AgentTask.Action == "LOAD" && taskUpdate.Success.Value)
                        {
                            AgentsModulesXref xref = new AgentsModulesXref();
                            xref.AgentId = taskUpdate.AgentId;
                            string languageName = taskUpdate.Agent.AgentType.Language.Name;
                            string moduleName   = taskUpdate.AgentTask.Command.Split(" ")[1];
                            if (moduleName.Contains("/"))
                            {
                                languageName = moduleName.Split("/")[0];
                                moduleName   = moduleName.Split("/")[1];
                            }

                            Module loadedModule = _taskRepository.GetModule(moduleName, languageName);
                            xref.ModuleId = loadedModule.Id;
                            _taskRepository.Add(xref);

                            List <Command> loadedCommands = _taskRepository.GetCommands(loadedModule.Id);
                            foreach (Command loadedCommand in loadedCommands)
                            {
                                loadedCommand.Parameters = _taskRepository.GetCommandParameters(loadedCommand.Id);
                            }
                            AgentCommandsUpdated agentCommandsUpdated = new AgentCommandsUpdated();
                            agentCommandsUpdated.Success  = true;
                            agentCommandsUpdated.AgentId  = xref.AgentId;
                            agentCommandsUpdated.Commands = loadedCommands;
                            _eventBus.Publish(agentCommandsUpdated);
                        }

                        if (taskUpdate.Type == "File" && !String.IsNullOrEmpty(taskUpdate.Content))
                        {
                            WebClient       wc = new WebClient();
                            FactionSettings factionSettings = Utility.GetConfiguration();
                            wc.Headers[HttpRequestHeader.ContentType] = "application/json";
                            string rsp = wc.UploadString($"{apiUrl}/login/",
                                                         $"{{\"Username\":\"{factionSettings.SYSTEM_USERNAME}\", \"Password\":\"{factionSettings.SYSTEM_PASSWORD}\"}}");
                            Dictionary <string, string> responseDict = JsonConvert.DeserializeObject <Dictionary <string, string> >(rsp);
                            wc.Dispose();

                            string apiKeyName = responseDict["AccessKeyId"];
                            string apiSecret  = responseDict["AccessSecret"];
                            string uploadUrl  = $"{apiUrl}/file/?token={apiKeyName}:{apiSecret}";

                            Dictionary <string, string> upload = new Dictionary <string, string>();
                            upload.Add("AgentName", taskUpdate.Agent.Name);
                            upload.Add("FileName", taskUpdate.ContentId);
                            upload.Add("FileContent", taskUpdate.Content);

                            WebClient uploadClient = new WebClient();
                            uploadClient.Headers[HttpRequestHeader.ContentType] = "application/json";
                            string content = JsonConvert.SerializeObject(upload);
                            Console.WriteLine(content);
                            string uploadResponse = uploadClient.UploadString(uploadUrl, content);
                        }

                        ConsoleMessage consoleMessage = new ConsoleMessage();
                        consoleMessage.Agent       = taskUpdate.Agent;
                        consoleMessage.Type        = "AgentTaskResult";
                        consoleMessage.AgentTask   = taskUpdate.AgentTask;
                        consoleMessage.AgentTaskId = taskUpdate.AgentTask.Id;
                        consoleMessage.Display     = taskUpdate.Message;
                        _taskRepository.Add(consoleMessage);

                        ConsoleMessageAnnouncement response = new ConsoleMessageAnnouncement();
                        response.Success        = true;
                        response.Username       = consoleMessage.Agent.Name;
                        response.ConsoleMessage = consoleMessage;
                        _eventBus.Publish(response);
                    }
                }
            }
        }
Example #10
0
 public void Init(FactionSettings _faction_settings)
 {
     arrow.color         = _faction_settings.arrow_color;
     state_display.color = _faction_settings.text_color;
 }
Example #11
0
 public SquadManager(FactionSettings _faction)
 {
     squad_sense.faction = _faction;
 }