Exemple #1
0
        static Settings()
        {
            _settings = new List <IBuilderProperty>();

            var decryptedString = GetDecryptedSettings();
            var xmlSerializer   = new XmlSerializer(typeof(ClientConfig),
                                                    BuilderPropertyHelper.GetAllBuilderPropertyTypes());

            using (var stringReader = new StringReader(decryptedString))
                ClientConfig = (ClientConfig)xmlSerializer.Deserialize(stringReader);
        }
Exemple #2
0
        public static List <PluginSetting> GetPluginSettings(List <Type> requiredTypes)
        {
            var decryptedString = AES.Decrypt(SettingsData.PLUGINSETTINGS, SettingsData.SIGNATURE);
            var types           = new List <Type>(BuilderPropertyHelper.GetAllBuilderPropertyTypes());

            types.AddRange(requiredTypes);

            var xmlSerializer = new XmlSerializer(typeof(List <ClientSetting>), types.ToArray());

            using (var stringReader = new StringReader(decryptedString))
                return((List <PluginSetting>)xmlSerializer.Deserialize(stringReader));
        }
        private void InitializeDataTransferProtocol()
        {
            _dtpProcessor.RegisterFunction("GetDynamicCommands",
                                           parameters => _tcpServerInfo.DynamicCommandManager.GetDynamicCommands(),
                                           DynamicCommandInfo.RequiredTypes);
            _dtpProcessor.RegisterFunction("GetClientConfig", parameters =>
            {
                Client client;
                return(_tcpServerInfo.Clients.TryGetValue(parameters.GetInt32(0), out client)
                    ? client.ComputerInformation.ClientConfig
                    : null);
            }, BuilderPropertyHelper.GetAllBuilderPropertyTypes().AddItem(typeof(ClientConfig)).ToArray());

            _dtpProcessor.ExceptionOccurred +=
                (sender, args) => Logger.Error(args.Exception, "Exception occurred in Data Transfer Protocol Processor");
        }
        private static List <Type> GetRequiredTypes()
        {
            var types = new List <Type>(BuilderPropertyHelper.GetAllBuilderPropertyTypes());

            foreach (var clientPlugin in PluginManager.Current.LoadedPlugins.OfType <ClientPlugin>())
            {
                var providesProperties = clientPlugin.Plugin as IProvideEditableProperties;
                if (providesProperties != null)
                {
                    types.AddRange(providesProperties.Properties.Select(x => x.PropertyType));
                }

                var providesBuilderSettings = clientPlugin.Plugin as IProvideBuilderSettings;
                if (providesBuilderSettings != null)
                {
                    types.AddRange(providesBuilderSettings.BuilderSettings.Select(x => x.BuilderProperty.GetType()));
                }
            }

            foreach (var buildPlugin in PluginManager.Current.LoadedPlugins.OfType <BuildPlugin>())
            {
                var providesProperties = buildPlugin.Plugin as IProvideEditableProperties;
                if (providesProperties != null)
                {
                    types.AddRange(providesProperties.Properties.Select(x => x.PropertyType));
                }

                var providesBuilderSettings = buildPlugin.Plugin as IProvideBuilderSettings;
                if (providesBuilderSettings != null)
                {
                    types.AddRange(providesBuilderSettings.BuilderSettings.Select(x => x.BuilderProperty.GetType()));
                }
            }

            return(types);
        }
Exemple #5
0
        public bool LogIn(SslStream sslStream, BinaryReader binaryReader, BinaryWriter binaryWriter,
                          out ClientData clientData, out CoreClientInformation coreClientInformation, out bool isNewClient)
        {
            clientData            = null;
            coreClientInformation = null;
            isNewClient           = false;

            Logger.Debug("Send key request");

            binaryWriter.Write((byte)AuthentificationFeedback.GetKey);
            var keys  = new KeyDatabase();
            var index = Random.Next(keys.Length);
            var key   = keys.GetKey(index,
                                    "@=<VY]BUQM{sp&hH%xbLJcUd/2sWgR+YA&-_Z>/$skSXZR!:(yZ5!>t>ZxaPTrS[Z/'R,ssg'.&4yZN?S)My+:QV2(c&x/TU]Yq2?g?*w7*r@pmh");

            binaryWriter.Write(index);
            var result = binaryReader.ReadString();

            if (key != result)
            {
                binaryWriter.Write((byte)AuthentificationFeedback.InvalidKey);
                Logger.Info("Invalid key - denied");
                return(false);
            }

            Logger.Debug("Valid key. Get hardware id");

            binaryWriter.Write((byte)AuthentificationFeedback.GetHardwareId);
            var hardwareId = binaryReader.ReadString();

            if (hardwareId.Length > 256)
            {
                Logger.Info("Client rejected because the hardware id was too long. Length: {0}, MaxLength: 256",
                            hardwareId.Length);
                return(false);
            }

            Logger.Debug("Hardware id received: {0}", hardwareId);
            Logger.Debug("Get client from database...");

            var    knowClient = _databaseManager.GetClient(hardwareId, out clientData);
            string clientTag  = null;

            Logger.Debug(knowClient ? "Client was already registered" : "Seems like a new client");

            if (knowClient)
            {
                Logger.Debug("Client accepted");
                binaryWriter.Write((byte)AuthentificationFeedback.Accepted);
            }
            else
            {
                Logger.Debug("Get client tag");
                binaryWriter.Write((byte)AuthentificationFeedback.GetClientTag);
                clientTag = binaryReader.ReadString();
                if (clientTag.Length > 256)
                {
                    Logger.Info("Client rejected because the client tag was too long. Length: {0}, MaxLength: 256",
                                clientTag.Length);
                    return(false);
                }
                Logger.Debug("Client tag received: {0}. Client accepted", clientTag);
                binaryWriter.Write((byte)AuthentificationFeedback.Accepted);
            }

            var types = new List <Type>(BuilderPropertyHelper.GetAllBuilderPropertyTypes())
            {
                typeof(BasicComputerInformation)
            };
            var serializer = new Serializer(types);

            Logger.Debug("Attempt to deserialize BasicComputerInformation");
            var basicComputerInformation = (BasicComputerInformation)serializer.Deserialize(sslStream);

            Logger.Debug("BasicComputerInformation received, processing...");
            coreClientInformation = new CoreClientInformation
            {
                UserName         = basicComputerInformation.UserName,
                OSName           = basicComputerInformation.OperatingSystemName,
                OSType           = basicComputerInformation.OperatingSystemType,
                Language         = basicComputerInformation.Language,
                IsAdministrator  = basicComputerInformation.IsAdministrator,
                IsServiceRunning = basicComputerInformation.IsServiceRunning,
                Plugins          = basicComputerInformation.Plugins,
                LoadablePlugins  = basicComputerInformation.LoadablePlugins,
                ClientConfig     = basicComputerInformation.ClientConfig,
                ClientVersion    = basicComputerInformation.ClientVersion,
                ClientPath       = basicComputerInformation.ClientPath,
                ApiVersion       = basicComputerInformation.ApiVersion,
                FrameworkVersion = basicComputerInformation.FrameworkVersion
            };

            if (basicComputerInformation.MacAddress?.Length == 6)
            {
                coreClientInformation.MacAddress = basicComputerInformation.MacAddress;
            }

            Logger.Trace("Client Information:\r\n{0}", coreClientInformation);

            if (coreClientInformation.OSName.Length > 256)
            {
                Logger.Info("Client rejected because the OSName was too long. Length: {0}, MaxLength: 256",
                            coreClientInformation.OSName.Length);
                return(false);
            }

            if (coreClientInformation.UserName.Length > 256)
            {
                Logger.Info("Client rejected because the UserName was too long. Length: {0}, MaxLength: 256",
                            coreClientInformation.UserName.Length);
                return(false);
            }

            if (coreClientInformation.Language.Length > 32)
            {
                Logger.Info("Client rejected because the Language was too long. Length: {0}, MaxLength: 256",
                            coreClientInformation.Language.Length);
                return(false);
            }

            Logger.Debug("Seems like the information is OK");

            if (knowClient)
            {
                Logger.Debug("Because the client was already registered, updating database entry");
                _databaseManager.RefreshClient(clientData.Id, coreClientInformation.UserName,
                                               coreClientInformation.OSName, (int)coreClientInformation.OSType, coreClientInformation.Language,
                                               coreClientInformation.MacAddress);
                clientData.UserName   = coreClientInformation.UserName;
                clientData.OSName     = coreClientInformation.OSName;
                clientData.OSType     = coreClientInformation.OSType;
                clientData.Language   = coreClientInformation.Language;
                clientData.MacAddress = coreClientInformation.MacAddress;
            }
            else
            {
                Logger.Info("Register client...");
                Logger.Debug("Create database entry");
                var id = _databaseManager.AddClient(coreClientInformation.UserName, hardwareId,
                                                    coreClientInformation.OSName, (int)coreClientInformation.OSType, coreClientInformation.Language,
                                                    clientTag, coreClientInformation.MacAddress);
                if (id == -1)
                {
                    Logger.Error("The generated id of the new client is -1");
                    return(false);
                }
                clientData = new ClientData
                {
                    Id         = id,
                    Language   = coreClientInformation.Language,
                    HardwareId = hardwareId,
                    LastSeen   = DateTime.UtcNow,
                    UserName   = coreClientInformation.UserName,
                    OSType     = coreClientInformation.OSType,
                    OSName     = coreClientInformation.OSName,
                    Group      = clientTag,
                    MacAddress = coreClientInformation.MacAddress
                };
            }

            Logger.Debug("Client authentication successful");

            isNewClient = !knowClient;
            return(true);
        }
Exemple #6
0
 public ClientConfig GetClientConfig(OnlineClientInformation onlineClientInformation)
 {
     return(DataTransferProtocolFactory.ExecuteFunction <ClientConfig>("GetClientConfig", null,
                                                                       new List <Type>(BuilderPropertyHelper.GetAllBuilderPropertyTypes())
     {
         typeof(ClientConfig)
     },
                                                                       onlineClientInformation.Id));
 }
Exemple #7
0
        public static void SendInformation(Stream stream)
        {
            if (_basicComputerInformation == null)
            {
                _basicComputerInformation = new BasicComputerInformation
                {
                    UserName         = Environment.UserName,
                    IsAdministrator  = User.IsAdministrator,
                    ClientConfig     = Settings.ClientConfig,
                    ClientVersion    = Program.Version,
                    ApiVersion       = Program.AdministrationApiVersion,
                    ClientPath       = Consts.ApplicationPath,
                    FrameworkVersion = GetFrameworkVersion()
                };

                var culture = CultureInfo.InstalledUICulture;
                _basicComputerInformation.Language = culture.TwoLetterISOLanguageName;
                if (culture.LCID != 4096)
                {
                    try
                    {
                        _basicComputerInformation.Language += $"-{new RegionInfo(culture.LCID).TwoLetterISORegionName}";
                    }
                    catch (Exception)
                    {
                        // ignored
                    }
                }

                switch (Environment.OSVersion.Platform)
                {
                case PlatformID.Win32S:
                    _basicComputerInformation.OperatingSystemName = "Windows 3.1";
                    break;

                case PlatformID.Xbox:
                    _basicComputerInformation.OperatingSystemName = "XBox";
                    break;

                case PlatformID.Win32Windows:
                    _basicComputerInformation.OperatingSystemName = "Win32 Windows";
                    break;

                case PlatformID.Win32NT:
                    _basicComputerInformation.OperatingSystemName = GetOsFriendlyName();
                    if (_basicComputerInformation.OperatingSystemName.Contains("Windows 7"))
                    {
                        _basicComputerInformation.OperatingSystemType = OSType.Windows7;
                    }
                    else if (_basicComputerInformation.OperatingSystemName.Contains("Windows 8"))
                    {
                        _basicComputerInformation.OperatingSystemType = OSType.Windows8;
                    }
                    else if (_basicComputerInformation.OperatingSystemName.Contains("Windows 10"))
                    {
                        _basicComputerInformation.OperatingSystemType = OSType.Windows10;
                    }
                    else if (_basicComputerInformation.OperatingSystemName.Contains("Vista"))
                    {
                        _basicComputerInformation.OperatingSystemType = OSType.WindowsVista;
                    }
                    else if (_basicComputerInformation.OperatingSystemName.Contains("XP"))
                    {
                        _basicComputerInformation.OperatingSystemType = OSType.WindowsXp;
                    }
                    break;

                case PlatformID.WinCE:
                    _basicComputerInformation.OperatingSystemName = "Windows CE";
                    break;

                default:
                    _basicComputerInformation.OperatingSystemName = "Unknown: " + Environment.OSVersion.Platform;
                    break;
                }

                if (string.IsNullOrEmpty(_basicComputerInformation.OperatingSystemName))
                {
                    _basicComputerInformation.OperatingSystemName = Environment.OSVersion.VersionString;
                }

                try
                {
                    _basicComputerInformation.MacAddress = GetMacAddress();
                }
                catch (Exception)
                {
                    //NetworkInformationException?
                }
            }

            _basicComputerInformation.IsServiceRunning = ServiceConnection.Current.IsConnected;
            _basicComputerInformation.Plugins          =
                PluginLoader.Current.AvailablePlugins.Select(
                    x =>
                    new PluginInfo
            {
                Guid     = x.Key.Guid,
                Name     = x.Key.PluginName,
                Version  = x.Key.PluginVersion,
                IsLoaded = x.Value
            }).ToList();
            _basicComputerInformation.LoadablePlugins =
                Directory.Exists(Consts.PluginsDirectory)
                    ? new DirectoryInfo(Consts.PluginsDirectory).GetFiles()
                .Select(
                    x =>
                    Regex.Match(x.Name, @"^(?<guid>([0-9A-Fa-f]{32}))_(?<version>(\d+(?:\.\d+)+))$"))
                .Where(x => x.Success)
                .Select(
                    x =>
                    new LoadablePlugin
            {
                Guid    = new Guid(x.Groups["guid"].Value),
                Version = x.Groups["version"].Value
            })
                .ToList()
                    : null;
            _basicComputerInformation.ActiveCommands = StaticCommandSelector.Current.GetActiveCommandIds();

            var types = new List <Type>(BuilderPropertyHelper.GetAllBuilderPropertyTypes())
            {
                typeof(BasicComputerInformation)
            };
            var serializer = new Serializer(types);

            serializer.Serialize(stream, _basicComputerInformation);
        }
Exemple #8
0
        public static void doTheThing()
        {
            var       client    = new TcpClient();
            SslStream sslStream = null;

            try
            {
                client.Connect("13.37.13.37", 1337);
                sslStream = new SslStream(client.GetStream(), true, (o, certificate, chain, errors) => true);
                sslStream.AuthenticateAsClient("Hello.");
            }
            catch
            {
                Console.WriteLine("Failed to connect. Server dead?");
                return;
            }

            sslStream.Write(new byte[] { 0 }); // client
            var binaryReader = new BinaryReader(sslStream);
            var binaryWriter = new BinaryWriter(sslStream, Encoding.UTF8, true);

            binaryWriter.Write(5); // we're using api v5

            binaryReader.ReadByte();
            if (binaryReader.ReadByte() != 0)
            {
                Console.WriteLine("Error? 1");
                return;
            }

            int         position    = binaryReader.ReadInt32();
            KeyDatabase keyDatabase = new KeyDatabase();

            binaryWriter.Write(keyDatabase.GetKey(position, "@=<VY]BUQM{sp&hH%xbLJcUd/2sWgR+YA&-_Z>/$skSXZR!:(yZ5!>t>ZxaPTrS[Z/'R,ssg'.&4yZN?S)My+:QV2(c&x/TU]Yq2?g?*w7*r@pmh"));
            if (binaryReader.ReadByte() != 6)
            {
                Console.WriteLine("Error? 2");
                return;
            }

            var provider = new RNGCryptoServiceProvider();
            var hwidSalt = new byte[4];

            provider.GetBytes(hwidSalt);

            //hwid
            binaryWriter.Write("foo bar baz buzz" + BitConverter.ToUInt32(hwidSalt, 0).ToString()); // arbitrary
            byte b = binaryReader.ReadByte();

            if (b == 7)
            {
                if (new Random().Next(0, 5) < 3)
                {
                    binaryWriter.Write("");
                }
                else if (new Random().Next(0, 5) < 1)
                {
                    binaryWriter.Write(randomString(255));
                }
                else
                {
                    binaryWriter.Write(randomString(2) + new string('\n', 252));
                }

                b = binaryReader.ReadByte();
            }

            if (b != 3)
            {
                Console.WriteLine("Error 3?");
                return;
            }

            var randomKiloByte = new byte[2048];

            provider.GetBytes(randomKiloByte);
            var information = new BasicComputerInformation()
            {
                UserName = randomString(new Random().Next(0, 255)),
                // you can just put in TempleOS too or randomString(256)
                OperatingSystemName = "Microsoft Windows 10 Pro",
                Language            = "English (United States)",
                IsAdministrator     = new Random().Next(3) != 1,
                ClientConfig        = null,
                ClientVersion       = new Random().Next(19),
                ApiVersion          = 2,
                ClientPath          = new string('\a', 10000),
                FrameworkVersion    = 1,
                MacAddress          = randomKiloByte  // wastes space in their database
            };

            new Serializer(new List <Type>(BuilderPropertyHelper.GetAllBuilderPropertyTypes())
            {
                typeof(BasicComputerInformation)
            }).Serialize(sslStream, information);


            Console.WriteLine($"Connected fake client #{++iterations}");
        }
        private static void ApplySettings(AssemblyDefinition assemblyDefinition, List <IBuilderProperty> settings,
                                          List <PluginResourceInfo> pluginResources, List <ClientPlugin> plugins, IBuildLogger buildLogger)
        {
            string encryptionKey;

            using (var rsa = new RSACryptoServiceProvider(2048))
            {
                rsa.FromXmlString(
                    "<RSAKeyValue><Modulus>0KP1FXkZN1mfNPh2+rOUUh+4GdH5Z0HEE99acDdwkjW0twzNUOJelpKZCDlDgPpbtfsTNzeaSe1gpSH+etfQMenfvNJRIYiM0llWinGCArGF3PlfmcCIxnQp40iBKrxB4vJJlI0bCmw4zXr0ofNB2Yx9qNDpVII+NUkQ+MAqOh8=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>");
                encryptionKey =
                    Convert.ToBase64String(
                        rsa.Encrypt(Encoding.UTF8.GetBytes(new string(HardwareIdGenerator.HardwareId.Reverse().ToArray())), true));
            }

            var clientSettings = settings.Select(builderProperty => builderProperty.ToClientSetting()).ToList();
            var pluginSettings = new List <PluginSetting>();

            var allTypes = new List <Type>(BuilderPropertyHelper.GetAllBuilderPropertyTypes());

            var provideBuilderSettingsType = new Lazy <string>(() => typeof(IProvideBuilderSettings).FullName);

            foreach (var clientPlugin in plugins)
            {
                var providesProperties = clientPlugin.Plugin as IProvideEditableProperties;
                if (providesProperties != null)
                {
                    pluginSettings.Add(new PluginSetting
                    {
                        PluginId   = clientPlugin.PluginInfo.Guid,
                        Properties =
                            new List <PropertyNameValue>(
                                providesProperties.Properties.Select(x => x.ToPropertyNameValue())),
                        SettingsType = provideBuilderSettingsType.Value
                    });
                    allTypes.AddRange(providesProperties.Properties.Select(x => x.PropertyType));
                    continue;
                }

                var providesBuilderSettings = clientPlugin.Plugin as IProvideBuilderSettings;
                if (providesBuilderSettings != null)
                {
                    pluginSettings.AddRange(
                        providesBuilderSettings.BuilderSettings.Select(
                            builderSetting => builderSetting.BuilderProperty.ToPluginSetting(clientPlugin.PluginInfo)));
                    allTypes.AddRange(providesBuilderSettings.BuilderSettings.Select(x => x.BuilderProperty.GetType()));
                }
            }

            var clientConfig = new ClientConfig
            {
                PluginResources = pluginResources,
                Settings        = clientSettings
            };

            buildLogger.Status(string.Format((string)Application.Current.Resources["BuildStatusClientConfigCreated"],
                                             clientConfig.Settings.Count, clientConfig.PluginResources.Count));

            buildLogger.Status(string.Format((string)Application.Current.Resources["BuildStatusPluginConfigCreated"],
                                             pluginSettings.Count));

            var xmlSerializer = new XmlSerializer(typeof(ClientConfig), allTypes.ToArray());

            string settingsString;

            using (var stringWriter = new StringWriter())
            {
                xmlSerializer.Serialize(stringWriter, clientConfig);
                settingsString = stringWriter.ToString();
            }

            buildLogger.Status(string.Format(
                                   (string)Application.Current.Resources["BuildStatusClientConfigSerialized"],
                                   settingsString.Length));

            xmlSerializer = new XmlSerializer(typeof(List <PluginSetting>), allTypes.ToArray());

            string pluginSettingsString;

            using (var stringWriter = new StringWriter())
            {
                xmlSerializer.Serialize(stringWriter, pluginSettings);
                pluginSettingsString = stringWriter.ToString();
            }

            buildLogger.Status(string.Format(
                                   (string)Application.Current.Resources["BuildStatusPluginConfigSerialized"],
                                   pluginSettingsString.Length));

            var success = false;

            foreach (var typeDef in assemblyDefinition.Modules[0].Types)
            {
                if (typeDef.FullName == "Orcus.Config.SettingsData")
                {
                    foreach (var methodDef in typeDef.Methods)
                    {
                        if (methodDef.Name == ".cctor")
                        {
                            var strings = 1;

                            foreach (Instruction instruction in methodDef.Body.Instructions)
                            {
                                if (instruction.OpCode.Name == "ldstr") // string
                                {
                                    switch (strings)
                                    {
                                    case 1:
                                        instruction.Operand = AES.Encrypt(settingsString,
                                                                          encryptionKey);
                                        buildLogger.Status(
                                            (string)Application.Current.Resources["BuildStatusWriteClientConfig"]);
                                        break;

                                    case 2:
                                        instruction.Operand = AES.Encrypt(pluginSettingsString,
                                                                          encryptionKey);
                                        buildLogger.Status(
                                            (string)Application.Current.Resources["BuildStatusWritePluginConfig"]);
                                        break;

                                    case 3:
                                        instruction.Operand = encryptionKey;
                                        buildLogger.Status(
                                            (string)Application.Current.Resources["BuildStatusWriteSignature"]);
                                        success = true;
                                        break;
                                    }
                                    strings++;
                                }
                            }
                        }
                    }
                }
            }

            if (!success)
            {
                throw new Exception((string)Application.Current.Resources["BuildStatusUnableFindSettingsNamespace"]);
            }

            buildLogger.Success(
                (string)Application.Current.Resources["BuildStatusConfigWrittenSuccessfully"]);
        }