/// <summary>
        ///     The main function for relaying C2 communications
        /// </summary>
        /// <exception cref="T:System.Exception"></exception>
        public void Go()
        {
            try
            {
                if (!Initialize())
                {
                    throw new Exception("C2 connector was not initialized...");
                }

                if (!ServerChannel.Connected)
                {
                    throw new Exception("Server Channel is not connected");
                }

                if (!BeaconChannel.Connected)
                {
                    throw new Exception("Beacon Channel is not connected");
                }

                Started = true;
                while (true)
                {
                    if (!BeaconChannel.ReadAndSendTo(ServerChannel))
                    {
                        break;
                    }
                    if (!ServerChannel.ReadAndSendTo(BeaconChannel))
                    {
                        break;
                    }
                }
                Console.WriteLine("[!] Stopping loop, no bytes received");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[!] Exception occured: {ex.Message}");
            }
            finally
            {
                Stop();
            }
        }
Exemple #2
0
        //Allow a user to join Server
        public async Task JoinServerAsync(string userEmail, string ServerKey)
        {
            ApplicationUser user = await _UserManager.FindByEmailAsync(userEmail);

            ServerChannel server = await _Context.ServerChannels.FindAsync(ServerKey);

            if (user == null || server == null)
            {
                return;
            }
            try{
                await CreateServerMapAsync(ServerKey, user.Id);

                IEnumerable <MessageChannel> messageChannels = await GetMessageChannelAsync(ServerKey);
                await JoinMessageChannelsAsync(messageChannels, user.Id, server.Name);
            }
            catch (Exception e) {
                Console.WriteLine(e);  //Change it to log later
            }
        }
Exemple #3
0
        public async Task <CreateMessageChannelObject> CreateMessageGroupAsync(string ChannelName, string serverKey)
        {
            ServerChannel serverChannel = await _Context.ServerChannels.FindAsync(serverKey);

            if (serverChannel == null)
            {
                return(new CreateMessageChannelObject {
                    IsSuccess = false,
                    Errors = new[] { "Couldn't find the server" }
                });
            }
            MessageChannel messageChannel = new MessageChannel()
            {
                Key       = Guid.NewGuid().ToString(),
                Name      = ChannelName,
                ServerKey = serverKey
            };

            try{
                await _Context.messageChannels.AddAsync(messageChannel);

                await _Context.SaveChangesAsync();
                await CreateGroupMapAsync(serverKey, messageChannel.Key);//Make a map to server users to this message channel

                return(new CreateMessageChannelObject {
                    IsSuccess = true,
                    Errors = null,
                    MessageChannelKey = messageChannel.Key,
                    MessageChannelName = messageChannel.Name
                });
            }
            catch (Exception e) {
                Console.WriteLine(e); // change it to log later
                return(new CreateMessageChannelObject {
                    IsSuccess = false,
                    Errors = new[] { e.Message }
                });
            }
        }
        private async Task EstablishChannelAsync(ServerChannel channel, CancellationToken cancellationToken)
        {
            var compressionOptions = channel
                                     .Transport
                                     .GetSupportedCompression()
                                     .Intersect(_options.Value.EnabledCompressionOptions)
                                     .ToArray();

            var encryptionOptions = channel
                                    .Transport
                                    .GetSupportedEncryption()
                                    .Intersect(_options.Value.EnabledEncryptionOptions)
                                    .ToArray();

            await channel.EstablishSessionAsync(
                compressionOptions,
                encryptionOptions,
                _options.Value.SchemeOptions,
                (identity, authentication, c) => _options.Value.AuthenticationHandler(identity, authentication, c),
                (node, serverChannel, c) => _options.Value.RegistrationHandler(node, serverChannel, c),
                cancellationToken);
        }
Exemple #5
0
        //Create a GroupMap
        private async Task CreateGroupMapAsync(string ServerKey, string messageChannelKey)
        {
            ServerChannel serverChannel = await _Context.ServerChannels.FindAsync(ServerKey);

            MessageChannel messageChannel = await _Context.messageChannels.FindAsync(messageChannelKey);

            // Check , that they both exist
            if (messageChannel == null || serverChannel == null)
            {
                return;
            }
            //Get the users who have joined the server
            IEnumerable <ServerChannelMap> maps = _Context.serverChannelMaps.Select(val => val).Where(pre => pre.ServerChannelKey == ServerKey);
            List <GroupMap> groupMaps           = new List <GroupMap>(); //Map them to the group

            foreach (var m in maps)
            {
                GroupMap gmap = new GroupMap {
                    Key               = Guid.NewGuid().ToString(),
                    UserId            = m.UserId,
                    MessageChannelKey = messageChannelKey,
                    ServerName        = serverChannel.Name,
                };
                groupMaps.Add(gmap);
            }
            try
            {
                await _Context.GroupMaps.AddRangeAsync(groupMaps);

                await _Context.SaveChangesAsync();
            }
            catch (Exception e)
            {
                Console.WriteLine(e); // Change it to log later
            }
        }
 public string[] GetUrlsForUri(string objectUri)
 {
     return(ServerChannel != null?ServerChannel.GetUrlsForUri(objectUri) : new string[0]);
 }
 private void StopIPCServer()
 {
     ServerChannel?.StopListening(null);
     ServerChannel = null;
 }
Exemple #8
0
        public async Task StartAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            await ListenerSemaphore.WaitAsync(cancellationToken);

            await _transportListener.StartAsync();

            ProducerConsumer.CreateAsync(
                c => _transportListener.AcceptTransportAsync(c),
                async transport =>
            {
                await transport.OpenAsync(null, _cts.Token);

                var serverChannel = new ServerChannel(
                    Guid.NewGuid().ToString(),
                    new Node("postmaster", "msging.net", "instance"),
                    transport,
                    TimeSpan.FromSeconds(60),
                    autoReplyPings: true);

                await serverChannel.EstablishSessionAsync(
                    new[] { SessionCompression.None },
                    new[] { SessionEncryption.None },
                    new[]
                {
                    AuthenticationScheme.Guest,
                    AuthenticationScheme.Key,
                    AuthenticationScheme.Plain,
                    AuthenticationScheme.Transport,
                    AuthenticationScheme.External
                },
                    (n, a) =>
                {
                    Authentications.Enqueue(a);
                    return(new AuthenticationResult(null, n).AsCompletedTask());
                }, _cts.Token);

                var channelListener = new ChannelListener(
                    m =>
                {
                    Messages.Enqueue(m);
                    return(TaskUtil.TrueCompletedTask);
                },
                    n =>
                {
                    Notifications.Enqueue(n);
                    return(TaskUtil.TrueCompletedTask);
                },
                    async c =>
                {
                    Commands.Enqueue(c);
                    if (c.Status == CommandStatus.Pending)
                    {
                        await serverChannel.SendCommandAsync(
                            new Command(c.Id)
                        {
                            Status = CommandStatus.Success,
                            Method = c.Method
                        },
                            _cts.Token);
                    }
                    return(true);
                });

                channelListener.Start(serverChannel);
                Channels.Enqueue(serverChannel);

                return(true);
            },
                _cts.Token);
        }
Exemple #9
0
 public void Stop()
 {
     _workerGroup.ShutdownGracefullyAsync().Wait();
     ServerChannel?.CloseAsync().Wait();
 }
Exemple #10
0
 public void UpdateHeartbeat(ServerChannel channel, byte[] rawBuffer, int offset, int length)
 {
     m_RecvMills = TimeUtils.Get1970ToNowMilliseconds();
     channel.Send(rawBuffer, offset, length);
 }