Ejemplo n.º 1
0
        public BuilderSettingsManager()
        {
            _coreSettings = new ReadOnlyCollection <IBuilderProperty>(BuilderPropertyHelper.GetAllBuilderProperties());

            BuilderSettings =
                new ObservableCollection <BuilderPropertyViewModel>(
                    _coreSettings.Select(x => new BuilderPropertyViewModel(x)));
            _overwrittenProperties     = new List <BuilderSettingsOverwrite>();
            _externalBuilderProperties = new Dictionary <IPlugin, List <IBuilderProperty> >();
        }
Ejemplo n.º 2
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);
        }
Ejemplo n.º 3
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));
        }
Ejemplo n.º 4
0
        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");
        }
Ejemplo n.º 5
0
        public void InitializeSettings(IList <IBuilderProperty> settings)
        {
            var newSettings = new List <IBuilderProperty>(BuilderPropertyHelper.GetAllBuilderProperties());

            for (int i = 0; i < newSettings.Count; i++)
            {
                var builderProperty     = newSettings[i];
                var builderPropertyType = builderProperty.GetType();
                var existingSetting     = settings.FirstOrDefault(x => x.GetType() == builderPropertyType);

                if (existingSetting != null)
                {
                    newSettings[i] = existingSetting;
                }

                BuilderSettings[i] = new BuilderPropertyViewModel(existingSetting ?? builderProperty);
            }

            _coreSettings = new ReadOnlyCollection <IBuilderProperty>(newSettings);
            ApplyOverwrites();
        }
Ejemplo n.º 6
0
        public void UpdatePluginSettings(IPlugin plugin, List <PluginSetting> pluginSettings)
        {
            List <IBuilderProperty> pluginBuilderProperties;

            if (!_externalBuilderProperties.TryGetValue(plugin, out pluginBuilderProperties))
            {
                throw new Exception("Build plugin does not exist");
            }

            foreach (var pluginSetting in pluginSettings)
            {
                var builderSetting =
                    BuilderSettings.FirstOrDefault(
                        x =>
                        x.BuilderProperty.GetType().GetClientSettingTypeName() ==
                        pluginSetting.SettingsType);
                if (builderSetting != null)
                {
                    BuilderSettings.Remove(builderSetting);
                    pluginBuilderProperties.Remove(builderSetting.BuilderProperty);

                    var builderProperty = builderSetting.BuilderProperty.Clone();
                    BuilderPropertyHelper.ApplyProperties(
                        builderProperty, pluginSetting.Properties);
                    BuilderPropertyHelper.ApplyProperties(
                        builderSetting.BuilderProperty, pluginSetting.Properties);
                    //i know that this is ugly af, but actually these are new setting; the problem is if the user deactivates and activates the plugin because the settings from the plugin will be used and not the settings from the configuration. Perhaps I'll have to change that later
                    BuilderSettings.Add(
                        new BuilderPropertyViewModel(builderProperty)
                    {
                        IsFromPlugin = true
                    });
                    pluginBuilderProperties.Add(builderProperty);
                }
            }

            ApplyOverwrites();
        }
        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);
        }
        private void LoadSettings(IEnumerable <ClientSetting> clientSettings)
        {
            var settings = new List <IBuilderProperty>();

            foreach (var clientSetting in clientSettings)
            {
                var type = Type.GetType(clientSetting.SettingsType);
                if (type == null)
                {
                    continue;
                }

                var settingInstance = Activator.CreateInstance(type) as IBuilderProperty;
                if (settingInstance == null)
                {
                    continue;
                }

                BuilderPropertyHelper.ApplyProperties(settingInstance, clientSetting.Properties);
                settings.Add(settingInstance);
            }

            BuilderSettingsManager.InitializeSettings(settings);
        }
Ejemplo n.º 9
0
        public void LoadPlugins(List <PluginResourceInfo> plugins)
        {
            if (plugins.Count == 0)
            {
                return;
            }

            var assembly           = Assembly.GetEntryAssembly();
            var blacklistedPlugins = new[]
            {
                new Guid(new byte[]
                         { 0x74, 0x56, 0xee, 0xe6, 0x94, 0xbb, 0xc7, 0x46, 0x8b, 0xbc, 0x57, 0x29, 0xaf, 0x6e, 0x2c, 0x28 })
            };

            var clientPluginIds = new Dictionary <ClientController, Guid>();

            foreach (var plugin in plugins)
            {
                if (blacklistedPlugins.Contains(plugin.Guid))
                {
                    continue;
                }

                AvailablePlugins.Add(plugin, false);
                var stream = assembly.GetManifestResourceStream(plugin.ResourceName);
                if (stream == null)
                {
                    continue;
                }

                Assembly pluginAssembly;
                using (var memoryStream = new MemoryStream())
                {
                    stream.CopyToEx(memoryStream);
                    stream.Dispose();
                    pluginAssembly = Assembly.Load(Decompress(memoryStream.ToArray()));
                }

                try
                {
                    var types = pluginAssembly.GetTypes();
                    switch (plugin.ResourceType)
                    {
                    case ResourceType.Command:
                        var commandType = types.First(x => x.IsSubclassOf(typeof(Command)));
                        Commands.Add(commandType);
                        break;

                    case ResourceType.ClientPlugin:
                        var clientType   = types.First(x => x.IsSubclassOf(typeof(ClientController)));
                        var clientPlugin = (ClientController)Activator.CreateInstance(clientType);
                        try
                        {
                            clientPlugin.Initialize(ClientOperator.Instance);
                        }
                        catch (Exception ex)
                        {
                            ErrorReporter.Current.ReportError(ex,
                                                              "Initialize() (ClientPlugin) at plugin: \"" + clientPlugin.GetType() + "\"");
                        }
                        ClientPlugins.Add(clientPlugin);
                        Loadables.Add(clientPlugin);
                        clientPluginIds.Add(clientPlugin, plugin.Guid);
                        break;

                    case ResourceType.FactoryCommand:
                        var factoryCommandPluginType =
                            types.First(x => x.GetInterface("IFactoryClientCommand") != null);
                        var factoryCommandPlugin =
                            (IFactoryClientCommand)Activator.CreateInstance(factoryCommandPluginType);
                        FactoryCommandPlugins.Add(factoryCommandPlugin);
                        try
                        {
                            factoryCommandPlugin.Factory.Initialize(ClientOperator.Instance);
                        }
                        catch (Exception ex)
                        {
                            ErrorReporter.Current.ReportError(ex,
                                                              "Initialize() (FactoryCommand) at plugin: \"" + factoryCommandPlugin.GetType() +
                                                              "\"");
                        }
                        Loadables.Add(factoryCommandPlugin.Factory);
                        break;

                    default:
                        continue;
                    }
                    AvailablePlugins[plugin] = true;
                }
                catch (Exception ex)
                {
                    ErrorReporter.Current.ReportError(ex,
                                                      $"Error loading and creating {plugin.ResourceType} of plugin {plugin.PluginName}");
                }
            }

            var requiredTypes           = new List <Type>();
            var propertyProvider        = new List <ClientControllerProvideEditablePropertyGrid>();
            var builderPropertyProvider = new List <ClientControllerBuilderSettings>();

            foreach (var clientController in ClientPlugins)
            {
                var providesProperties = clientController as ClientControllerProvideEditablePropertyGrid;
                if (providesProperties != null)
                {
                    requiredTypes.AddRange(providesProperties.Properties.Select(x => x.PropertyType));
                    propertyProvider.Add(providesProperties);
                    continue;
                }

                var providesBuilderSettings = clientController as ClientControllerBuilderSettings;
                if (providesBuilderSettings != null)
                {
                    requiredTypes.AddRange(providesBuilderSettings.BuilderSettings.Select(x => x.BuilderProperty.GetType()));
                    builderPropertyProvider.Add(providesBuilderSettings);
                }
            }

            if (propertyProvider.Count == 0 && builderPropertyProvider.Count == 0)
            {
                return;
            }

            var pluginSettings = Settings.GetPluginSettings(requiredTypes);

            foreach (var clientController in propertyProvider)
            {
                var settings =
                    pluginSettings.FirstOrDefault(x => x.PluginId == clientPluginIds[clientController]);
                if (settings != null)
                {
                    PropertyGridExtensions.InitializeProperties(clientController, settings.Properties);
                }
            }

            foreach (var clientController in builderPropertyProvider)
            {
                var settings =
                    pluginSettings.Where(x => x.PluginId == clientPluginIds[clientController]).ToList();
                if (settings.Count > 0)
                {
                    var builderSettings = new List <IBuilderProperty>();
                    foreach (var pluginSetting in settings)
                    {
                        var type = Type.GetType(pluginSetting.SettingsType);
                        if (type == null)
                        {
                            continue;
                        }

                        var settingInstance = Activator.CreateInstance(type) as IBuilderProperty;
                        if (settingInstance == null)
                        {
                            continue;
                        }

                        BuilderPropertyHelper.ApplyProperties(settingInstance, pluginSetting.Properties);
                        builderSettings.Add(settingInstance);
                    }

                    clientController.InitializeSettings(builderSettings);
                }
            }
        }
Ejemplo n.º 10
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);
        }
Ejemplo n.º 11
0
 public ClientConfig GetClientConfig(OnlineClientInformation onlineClientInformation)
 {
     return(DataTransferProtocolFactory.ExecuteFunction <ClientConfig>("GetClientConfig", null,
                                                                       new List <Type>(BuilderPropertyHelper.GetAllBuilderPropertyTypes())
     {
         typeof(ClientConfig)
     },
                                                                       onlineClientInformation.Id));
 }
Ejemplo n.º 12
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);
        }
Ejemplo n.º 13
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"]);
        }