Ejemplo n.º 1
0
        private (bool exists, RegisterLoad load) _getMapping(string priority_key, Type contract_type)
        {
            //Always give importance to priority key. If priority key combination is not found, the go with contract type alone.
            bool _exists = false;

            RegisterLoad _existing = new RegisterLoad();
            var          _key      = new KeyBase(contract_type, priority_key);

            //Preference to prioritykey/contract_type combination.
            if (_mappings.ContainsKey(_key))
            {
                _exists = true;
                _mappings.TryGetValue(_key, out _existing);
            }
            if (!_exists)
            {
                //Reassigning the key with contract type name.
                _key = new KeyBase(contract_type, null);
                if (_mappings.ContainsKey(_key))
                {
                    _exists = true;
                    _mappings.TryGetValue(_key, out _existing);
                }
            }

            return(_exists, _existing);
        }
Ejemplo n.º 2
0
    void Update()
    {
        if (lastIndex >= textTracks[0].Length)
        {
            CancelInvoke();
        }

        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            Ray        ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast(ray, out hit, 100f))
            {
                KeyBase key = hit.transform.GetComponent <KeyBase>();

                if (key == null)
                {
                    return;
                }

                if (key.readyToScore)
                {
                    key.GoodHit();
                }
                else
                {
                    key.BadHit();
                }
            }
        }
    }
        public async Task GetDeletedKeys()
        {
            string keyName = Recording.GenerateId();

            List <Key> createdKeys = new List <Key>();

            for (int i = 0; i < PagedKeyCount; i++)
            {
                Key Key = await Client.CreateKeyAsync(keyName + i, KeyType.EllipticCurve);

                createdKeys.Add(Key);
                await Client.DeleteKeyAsync(keyName + i);

                RegisterForCleanup(Key, delete: false);
            }

            foreach (Key deletedKey in createdKeys)
            {
                await WaitForDeletedKey(deletedKey.Name);
            }

            List <Response <DeletedKey> > allKeys = await Client.GetDeletedKeysAsync().ToEnumerableAsync();

            foreach (Key createdKey in createdKeys)
            {
                KeyBase returnedKey = allKeys.Single(s => s.Value.Name == createdKey.Name);
                AssertKeysEqual(createdKey, returnedKey);
            }
        }
Ejemplo n.º 4
0
    private void OnTriggerExit(Collider other)
    {
        KeyBase key = other.GetComponent <KeyBase>();

        if (key != null)
        {
            key.Die();
        }
    }
 private void AssertKeysEqual(KeyBase exp, KeyBase act)
 {
     Assert.AreEqual(exp.Name, act.Name);
     Assert.AreEqual(exp.Version, act.Version);
     Assert.AreEqual(exp.Managed, act.Managed);
     Assert.AreEqual(exp.RecoveryLevel, act.RecoveryLevel);
     Assert.AreEqual(exp.Expires, act.Expires);
     Assert.AreEqual(exp.NotBefore, act.NotBefore);
 }
Ejemplo n.º 6
0
        public R Execute <R, P>(KeyBase key)
            where R : ModelBase
            where P : KeyBase
        {
            var diKey    = _map[key.Key.ToString()];
            var provider = _diContainer.GetInstance <IExecute>(diKey);

            return(provider.Execute <R, P>(key));
        }
Ejemplo n.º 7
0
    private void OnTriggerEnter(Collider other)
    {
        KeyBase key = other.GetComponent <KeyBase>();

        if (key != null)
        {
            key.readyToScore = true;
        }
    }
        public void UpdateKeyArgumentValidation()
        {
            var keyOperations = new List <KeyOperations>()
            {
                KeyOperations.Sign
            };
            var key = new KeyBase("name");

            Assert.ThrowsAsync <ArgumentException>(() => Client.UpdateKeyAsync(null, null));
            Assert.ThrowsAsync <ArgumentException>(() => Client.UpdateKeyAsync(null, keyOperations));
            Assert.ThrowsAsync <ArgumentException>(() => Client.UpdateKeyAsync(key, null));
        }
Ejemplo n.º 9
0
        public void HelloWorldSync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL");

            // Instantiate a key client that will be used to call the service. Notice that the client is using default Azure
            // credentials. To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
            // 'AZURE_CLIENT_KEY' and 'AZURE_TENANT_ID' are set with the service principal credentials.
            var client = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential());

            // Let's create a RSA key valid for 1 year. If the key
            // already exists in the Key Vault, then a new version of the key is created.
            string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}";
            var    rsaKey     = new RsaKeyCreateOptions(rsaKeyName, hsm: false, keySize: 2048)
            {
                Expires = DateTimeOffset.Now.AddYears(1)
            };

            client.CreateRsaKey(rsaKey);

            // Let's Get the Cloud RSA Key from the Key Vault.
            Key cloudRsaKey = client.GetKey(rsaKeyName);

            Debug.WriteLine($"Key is returned with name {cloudRsaKey.Name} and type {cloudRsaKey.KeyMaterial.KeyType}");

            // After one year, the Cloud RSA Key is still required, we need to update the expiry time of the key.
            // The update method can be used to update the expiry attribute of the key.
            cloudRsaKey.Expires.Value.AddYears(1);
            KeyBase updatedKey = client.UpdateKey(cloudRsaKey, cloudRsaKey.KeyMaterial.KeyOps);

            Debug.WriteLine($"Key's updated expiry time is {updatedKey.Expires}");

            // We need the Cloud RSA key with bigger key size, so you want to update the key in Key Vault to ensure
            // it has the required size.
            // Calling CreateRsaKey on an existing key creates a new version of the key in the Key Vault
            // with the new specified size.
            var newRsaKey = new RsaKeyCreateOptions(rsaKeyName, hsm: false, keySize: 4096)
            {
                Expires = DateTimeOffset.Now.AddYears(1)
            };

            client.CreateRsaKey(newRsaKey);

            // The Cloud RSA Key is no longer needed, need to delete it from the Key Vault.
            client.DeleteKey(rsaKeyName);

            // To ensure key is deleted on server side.
            Assert.IsTrue(WaitForDeletedKey(client, rsaKeyName));

            // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged.
            client.PurgeDeletedKey(rsaKeyName);
        }
Ejemplo n.º 10
0
        private void BtnEnterKeyClick(object sender, EventArgs e)
        {
            // Uppercase and Add Dashes
            string input = txtEnterKey1.Text.ToUpper() + "-" + txtEnterKey2.Text.ToUpper() + "-" + txtEnterKey3.Text.ToUpper() + "-" + txtEnterKey4.Text.ToUpper() + "-" + txtEnterKey5.Text.ToUpper();

            // Check if Key is Valid
            if (KeyBase.IsValidKey(input) == false)
            {
                // Set error colors.
                txtEnterKey1.BackColor = Color.Red;
                txtEnterKey1.ForeColor = Color.White;
                txtEnterKey2.BackColor = Color.Red;
                txtEnterKey2.ForeColor = Color.White;
                txtEnterKey3.BackColor = Color.Red;
                txtEnterKey3.ForeColor = Color.White;
                txtEnterKey4.BackColor = Color.Red;
                txtEnterKey4.ForeColor = Color.White;
                txtEnterKey5.BackColor = Color.Red;
                txtEnterKey5.ForeColor = Color.White;

                MessageBox.Show("The key has an invalid format" + Environment.NewLine + "The correct format is: XXXXX-XXXXX-XXXXX-XXXXX-XXXXX");
                return;
            }
            if (input.Substring(input.Length - 5, 5) != PartialProductKeyLabel.Text)
            {
                // Set error colors.
                txtEnterKey1.BackColor = Color.Red;
                txtEnterKey1.ForeColor = Color.White;
                txtEnterKey2.BackColor = Color.Red;
                txtEnterKey2.ForeColor = Color.White;
                txtEnterKey3.BackColor = Color.Red;
                txtEnterKey3.ForeColor = Color.White;
                txtEnterKey4.BackColor = Color.Red;
                txtEnterKey4.ForeColor = Color.White;
                txtEnterKey5.BackColor = Color.Red;
                txtEnterKey5.ForeColor = Color.White;

                MessageBox.Show("This key is not the right key as it does not match the last 5 digits!");
            }
            else
            {
                // Assign
                KeyToSave = input;

                // Close Form
                Close();
            }
        }
        public void BackupAndRestoreSync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL");

            // Instantiate a key client that will be used to call the service. Notice that the client is using default Azure
            // credentials. To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
            // 'AZURE_CLIENT_KEY' and 'AZURE_TENANT_ID' are set with the service principal credentials.
            var client = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential());

            // Let's create a RSA key valid for 1 year. If the key
            // already exists in the Key Vault, then a new version of the key is created.
            string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}";
            var    rsaKey     = new RsaKeyCreateOptions(rsaKeyName, hsm: false, keySize: 2048)
            {
                Expires = DateTimeOffset.Now.AddYears(1)
            };

            Key storedKey = client.CreateRsaKey(rsaKey);

            // Backups are good to have if in case keys get accidentally deleted by you.
            // For long term storage, it is ideal to write the backup to a file, disk, database, etc.
            // For the purposes of this sample, we are storing the bakup in a temporary memory area.
            byte[] backupKey = client.BackupKey(rsaKeyName);

            using (var memoryStream = new MemoryStream())
            {
                memoryStream.Write(backupKey, 0, backupKey.Length);

                // The storage account key is no longer in use, so you delete it.
                client.DeleteKey(rsaKeyName);

                // To ensure the key is deleted on server side.
                Assert.IsTrue(WaitForDeletedKey(client, rsaKeyName));

                // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged.
                client.PurgeDeletedKey(rsaKeyName);

                // After sometime, the key is required again. We can use the backup value to restore it in the Key Vault.
                KeyBase restoredKey = client.RestoreKey(memoryStream.ToArray());

                AssertKeysEqual((KeyBase)storedKey, restoredKey);
            }
        }
Ejemplo n.º 12
0
        public async Task GetKeysVersions()
        {
            string keyName = Recording.GenerateId();

            List <Key> createdKeys = new List <Key>();

            for (int i = 0; i < PagedKeyCount; i++)
            {
                Key Key = await Client.CreateKeyAsync(keyName, KeyType.EllipticCurve);

                createdKeys.Add(Key);
            }
            RegisterForCleanup(createdKeys.First());

            List <Response <KeyBase> > allKeys = await Client.GetKeyVersionsAsync(keyName).ToEnumerableAsync();

            foreach (Key createdKey in createdKeys)
            {
                KeyBase returnedKey = allKeys.Single(s => s.Value.Version == createdKey.Version);
                AssertKeysEqual(createdKey, returnedKey);
            }
        }
Ejemplo n.º 13
0
        private bool _register(RegisterLoad register_load, MappingLoad mapping_load)
        {
            //Validate if the contract type is alredy registered. If so, against correct concrete type.
            bool _exists = _validateExistence(register_load);

            //If it already exists and we should not over write, then do not proceed.
            if (_exists && (!overwrite_if_registered))
            {
                return(false);
            }

            //Validate if the concrete type can be registered
            _validateConcreteType(register_load.concrete_type);

            //Generate instance only if the provided value is null and also singleton. Only if it is singleton, we create an instance and store. Else we store only the concrete type and save instance as it is (even if is null).
            if (register_load.concrete_instance == null && register_load.mode == RegisterMode.Singleton)
            {
                ResolveLoad resolve_load = register_load.convert(null, null, ResolveMode.AsRegistered);
                register_load.concrete_instance = _createInstance(resolve_load, mapping_load); //Create instance resolving all dependencies
            }

            //Get the key to register.
            var _key = new KeyBase(register_load.contract_type, register_load.priority_key);

            //We have already validate if overwrite is required or not. If we reach this point, then overwrite is required.
            if (_exists)
            {
                //Update the existing value
                RegisterLoad _existing_value;
                _mappings.TryGetValue(_key, out _existing_value);
                _mappings.TryUpdate(_key, register_load, _existing_value); //Remember to assign the instance
            }
            else
            {
                _mappings.TryAdd(_key, register_load);
            }
            return(true);
        }
Ejemplo n.º 14
0
        public R Execute <R, P>(KeyBase key)
            where R : ModelBase
            where P : KeyBase
        {
            switch (key.Key)
            {
            case Constants.DataAccessKey.NewData:
            {
                using (var context = new TestContext(_connString))
                {
                    var newData = context.NewDatas.Include(n => n.Lis).FirstOrDefault();
                    return(new NewModel()
                        {
                            Title = newData.Title,
                            H2 = newData.H2,
                            Lis = newData.Lis.Select(l => l.LisItem).ToArray()
                        } as R);
                }
            }

            default:
                return(null);
                //{
                //    Title = "Angular Seed is a starter project that implements best practices in coding, building and testing Angular apps.",
                //    H2 = "<h2>Gezukam draga - from service</h2>",
                //    Lis = new[] {
                //        "Ready to go, statically typed build system using Gulp for working with TypeScript.",
                //        "Production and development builds.",
                //        "Sample unit tests with Jasmine and Karma including code coverage via Istanbul.",
                //        "End-to-end tests with Protractor.",
                //        "Development server with live reload.",
                //        "TypeScript definition management using Types.",
                //        "Basic Service Worker, which implements \"Cache then network strategy\"."
                //    }
                //} as R;
            }
        }
Ejemplo n.º 15
0
        public async Task RecoverDeletedKey()
        {
            string keyName = Recording.GenerateId();

            Key key = await Client.CreateKeyAsync(keyName, KeyType.EllipticCurve);

            DeletedKey deletedKey = await Client.DeleteKeyAsync(keyName);

            await WaitForDeletedKey(keyName);

            Assert.ThrowsAsync <RequestFailedException>(() => Client.GetKeyAsync(keyName));

            KeyBase recoverKeyResult = await Client.RecoverDeletedKeyAsync(keyName);

            await PollForKey(keyName);

            Key recoveredKey = await Client.GetKeyAsync(keyName);

            RegisterForCleanup(recoveredKey);

            AssertKeysEqual(key, deletedKey);
            AssertKeysEqual(key, recoverKeyResult);
            AssertKeysEqual(key, recoveredKey);
        }
Ejemplo n.º 16
0
 public R Execute <R, P>(KeyBase key)
     where R : ModelBase
     where P : KeyBase
 {
     return(_dataAccess.Execute <R, P>(key));
 }
Ejemplo n.º 17
0
        public (bool status, Type registered_type, string message, RegisterMode mode) checkIfRegistered(KeyBase key)
        {
            RegisterLoad _current_load = new RegisterLoad();

            string _message       = null;
            bool   _is_registered = false;

            if (_mappings.ContainsKey(key))
            {
                _is_registered = true;
                _mappings.TryGetValue(key, out _current_load);
                _message = $@"The key : {key} is already registered against the type {_current_load.concrete_type}.";
            }

            return(_is_registered, _current_load?.concrete_type, _message, _current_load.mode);
        }
Ejemplo n.º 18
0
        private void BtnSaveSettingsClick(object sender, EventArgs e)
        {
            // Lock Form While Saving Settings
            btnSaveSettings.Enabled = false;
            btnLoadDefaults.Enabled = false;
            tabSettings.Enabled     = false;

            // Check Set PID
            if (!KeyBase.IsValidPKEYID(KMSSettingstxtKMSPIDOffice.Text) && KMSSettingstxtKMSPIDOffice.Text != "DefaultKMSPID" && KMSSettingstxtKMSPIDOffice.Text != "RandomKMSPID" && KMSSettingstxtKMSPIDOffice.Text != "ReuseKMSPID")
            {
                tabSettings.SelectedTab = tabKMSOptions;

                // Set error colors.
                KMSSettingstxtKMSPIDOffice.BackColor = Color.Red;
                KMSSettingstxtKMSPIDOffice.ForeColor = Color.White;

                MessageBox.Show("The KMS PID has an invalid format" + Environment.NewLine + "The correct format is: XXXXX-XXXXX-XXX-XXXXXX-XX-LCID-OSBUILD.XXXX-XXXXXXX");

                btnSaveSettings.Enabled = true;
                btnLoadDefaults.Enabled = true;
                tabSettings.Enabled     = true;
                return;
            }
            if (!KeyBase.IsValidPKEYID(KMSSettingstxtKMSPIDWindows.Text) && KMSSettingstxtKMSPIDWindows.Text != "DefaultKMSPID" && KMSSettingstxtKMSPIDWindows.Text != "RandomKMSPID" && KMSSettingstxtKMSPIDWindows.Text != "ReuseKMSPID")
            {
                tabSettings.SelectedTab = tabKMSOptions;

                // Set error colors.
                KMSSettingstxtKMSPIDWindows.BackColor = Color.Red;
                KMSSettingstxtKMSPIDWindows.ForeColor = Color.White;

                MessageBox.Show("The KMS PID has an invalid format" + Environment.NewLine + "The correct format is: XXXXX-XXXXX-XXX-XXXXXX-XX-LCID-OSBUILD.XXXX-XXXXXXX");

                btnSaveSettings.Enabled = true;
                btnLoadDefaults.Enabled = true;
                tabSettings.Enabled     = true;
                return;
            }
            if (!KeyBase.IsValidPKEYID(KSStxtKMSPID.Text) && KSStxtKMSPID.Text != "RandomKMSPID")
            {
                tabSettings.SelectedTab = tabKMSServerService;

                // Set error colors.
                KSStxtKMSPID.BackColor = Color.Red;
                KSStxtKMSPID.ForeColor = Color.White;

                MessageBox.Show("The KMS PID has an invalid format" + Environment.NewLine + "The correct format is: XXXXX-XXXXX-XXX-XXXXXX-XX-LCID-OSBUILD.XXXX-XXXXXXX");

                btnSaveSettings.Enabled = true;
                btnLoadDefaults.Enabled = true;
                tabSettings.Enabled     = true;
                return;
            }

            // Check Set HWID
            if (!Regex.IsMatch(KMSSettingstxtKMSHWID.Text, "[a-fA-F0-9]{16}"))
            {
                tabSettings.SelectedTab = tabKMSOptions;

                // Set error colors.
                KMSSettingstxtKMSHWID.BackColor = Color.Red;
                KMSSettingstxtKMSHWID.ForeColor = Color.White;

                MessageBox.Show("The KMS Hardware ID has an invalid format" + Environment.NewLine + "The correct format is: XXXXXXXXXXXXXXXX (0-9, A-F, a-f)");

                btnSaveSettings.Enabled = true;
                btnLoadDefaults.Enabled = true;
                tabSettings.Enabled     = true;
                return;
            }
            if (!Regex.IsMatch(KSStxtKMSHWID.Text, "[a-fA-F0-9]{16}"))
            {
                tabSettings.SelectedTab = tabKMSServerService;

                // Set error colors.
                KSStxtKMSHWID.BackColor = Color.Red;
                KSStxtKMSHWID.ForeColor = Color.White;

                MessageBox.Show("The KMS Hardware ID has an invalid format" + Environment.NewLine + "The correct format is: XXXXXXXXXXXXXXXX (0-9, A-F, a-f)");

                btnSaveSettings.Enabled = true;
                btnLoadDefaults.Enabled = true;
                tabSettings.Enabled     = true;
                return;
            }

            // Check LocalHost Bypass IP Configuration
            bool      iperror = false;
            bool      ipaddresserror = false;
            string    iperrormessage = string.Empty;
            IPAddress ipAddress, ipSubnet;

            if (!Regex.IsMatch(LocalHostBypassIPAddress.Text, @"^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$") || !IPAddress.TryParse(LocalHostBypassIPAddress.Text, out ipAddress))
            {
                iperror        = true;
                ipaddresserror = true;
                iperrormessage = "The LocalHost Bypass IP Address is not a valid IPV4 Address!";
            }
            else if (!Regex.IsMatch(LocalHostBypassIPSubnet.Text, @"^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$") || !IPAddress.TryParse(LocalHostBypassIPSubnet.Text, out ipSubnet))
            {
                iperror        = true;
                iperrormessage = "The LocalHost Bypass Subnet Mask is not a valid IPV4 Address!";
            }
            else if (!CommonUtilities.IsValidSubnet(ipSubnet))
            {
                iperror        = true;
                iperrormessage = "The LocalHost Bypass Subnet Mask is not a valid Subnet Mask!";
            }
            else if (ipAddress.Equals(CommonUtilities.GetNetworkAddress(ipAddress, ipSubnet)))
            {
                iperror        = true;
                ipaddresserror = true;
                iperrormessage = "The LocalHost Bypass IP Address cannot be the network address!";
            }
            else if (ipAddress.Equals(CommonUtilities.GetBroadcastAddress(ipAddress, ipSubnet)))
            {
                iperror        = true;
                ipaddresserror = true;
                iperrormessage = "The LocalHost Bypass IP Address cannot be the broadcast address!";
            }
            else if (Regex.IsMatch(LocalHostBypassIPAddress.Text, @"^(169\.254\.([0,1]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])\.([0,1]?[0-9]{1,2}|2[0-4][0-9]|25[0-5]))$"))
            {
                iperror        = true;
                ipaddresserror = true;
                iperrormessage = "The LocalHost Bypass IP Address cannot be an APIPA address!";
            }
            if (iperror)
            {
                tabSettings.SelectedTab = tabLocalHostBypass;

                // Set error colors.
                if (ipaddresserror)
                {
                    LocalHostBypassIPAddress.BackColor = Color.Red;
                    LocalHostBypassIPAddress.ForeColor = Color.White;
                }
                else
                {
                    LocalHostBypassIPSubnet.BackColor = Color.Red;
                    LocalHostBypassIPSubnet.ForeColor = Color.White;
                }

                MessageBox.Show(iperrormessage);

                btnSaveSettings.Enabled = true;
                btnLoadDefaults.Enabled = true;
                tabSettings.Enabled     = true;
                return;
            }


            // Save Settings
            SaveStoredSettings();

            // Restart KMS Server Service
            if (KMSServerServiceInstaller.KMSServerServiceInstaller.IsKMSServerServiceInstalled())
            {
                Services.StopService(KMSServerServiceInstaller.KMSServerServiceInstaller.KMSServerServiceName, KMSServerServiceInstaller.KMSServerServiceInstaller.KMSServerServiceProcessName);
                Services.StartService(KMSServerServiceInstaller.KMSServerServiceInstaller.KMSServerServiceName);
            }

            // Close Form
            _clickOnSaveButton = true;
            Close();
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Load Settings
        /// </summary>
        private void LoadStoredSettings()
        {
            // KMS Server
            KMSSettingstxtKMSServerOffice.Text  = Settings.Default.KMSServerOffice;
            KMSSettingstxtKMSServerWindows.Text = Settings.Default.KMSServerWindows;

            // KMS Port
            KMSSettingstxtKMSPortOffice.Value  = Settings.Default.KMSPortOffice;
            KMSSettingstxtKMSPortWindows.Value = Settings.Default.KMSPortWindows;

            // KMS PID
            KMSSettingstxtKMSPIDOffice.Text  = Settings.Default.KMSPIDOffice;
            KMSSettingstxtKMSPIDWindows.Text = Settings.Default.KMSPIDWindows;

            // KMS Hardware ID
            KMSSettingstxtKMSHWID.Text = Settings.Default.KMSHardwareID;

            // KMS Connection
            KMSSettingscheckRemoveKMSConnection.Checked = Settings.Default.RemoveKMSConnection;
            KMSSettingscheckKillProcessOnPort.Checked   = Settings.Default.KillProcessOnPort;

            // KMS Emulator
            KMSSettingscheckUseKMSEmulator.Checked = Settings.Default.UseKMSEmulator;

            // License Display
            LicenseDisplaycheckShowCMID.Checked       = Settings.Default.ShowCMID;
            LicenseDisplaycheckShowUnlicensed.Checked = Settings.Default.ShowUnlicensed;

            // LocalHost Bypass
            LocalHostBypassIPAddress.Text             = Settings.Default.LocalHostBypassIPAddress;
            LocalHostBypassIPSubnet.Text              = Settings.Default.LocalHostBypassIPSubnet;
            LocalHostBypassUseDLLInjection.Checked    = Settings.Default.LocalHostBypassUseDLLInjection;
            LocalHostBypassUseTAPAdapter.Checked      = Settings.Default.LocalHostBypassUseTAPAdapter;
            LocalHostBypassUseWinDivertClient.Checked = Settings.Default.LocalHostBypassUseWinDivertClient;

            // Paths
            PathstxtAutoKMS.Text          = Settings.Default.AutoKMSPath;
            PathstxtAutoRearm.Text        = Settings.Default.AutoRearmPath;
            PathstxtKMSServerService.Text = Settings.Default.KMSServerServicePath;
            PathstxtLicenseBackups.Text   = Settings.Default.LicenseBackupsPath;

            // Handle KMS Server Service
            if (!KMSServerServiceInstaller.KMSServerServiceInstaller.IsKMSServerServiceInstalled())
            {
                KSScheckKillProcessOnPort.Checked = true;
                KSStxtKMSPID.Text                 = "RandomKMSPID";
                KSStxtKMSHWID.Text                = "364F463A8863D35F";
                KSStxtKMSPort.Value               = 1688;
                KSStxtActivationInterval.Value    = 120;
                KSStxtRenewalInterval.Value       = 10080;
                KSScheckKillProcessOnPort.Enabled = false;
                KSStxtKMSPID.Enabled              = false;
                KSStxtKMSHWID.Enabled             = false;
                KSStxtKMSPort.Enabled             = false;
                KSStxtActivationInterval.Enabled  = false;
                KSStxtRenewalInterval.Enabled     = false;
                btnKSSMoreSettings.Enabled        = false;
            }
            else
            {
                // Get KMS Server Service Parameters
                using (RegistryKey registry = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64).OpenSubKey("SYSTEM\\CurrentControlSet\\Services\\KMSServerService\\Parameters", true))
                {
                    if (registry != null)
                    {
                        // Get KMS PID
                        string kmsPid = Convert.ToString(registry.GetValue("KMSPID"));
                        if (kmsPid == "RandomKMSPID" || KeyBase.IsValidPKEYID(kmsPid))
                        {
                            KSStxtKMSPID.Text = kmsPid;
                        }

                        // Get KMS HWID
                        string kmsHwid = Convert.ToString(registry.GetValue("KMSHWID"));
                        if (Regex.IsMatch(kmsHwid, "[a-fA-F0-9]{16}"))
                        {
                            KSStxtKMSHWID.Text = kmsHwid;
                        }

                        // Get KMS Port
                        int kmsPort = Convert.ToInt32(registry.GetValue("KMSPort"));
                        if (kmsPort >= 1 && kmsPort <= 65535)
                        {
                            KSStxtKMSPort.Value = kmsPort;
                        }

                        // Get KMS Activation Interval
                        int kmsActivationInterval = Convert.ToInt32(registry.GetValue("VLActivationInterval"));
                        if (kmsActivationInterval >= 15 && kmsActivationInterval <= 43200)
                        {
                            KSStxtActivationInterval.Value = kmsActivationInterval;
                        }

                        // Get KMS Renewal Interval
                        int kmsRenewalInterval = Convert.ToInt32(registry.GetValue("VLRenewalInterval"));
                        if (kmsRenewalInterval >= 15 && kmsActivationInterval <= 43200)
                        {
                            KSStxtRenewalInterval.Value = kmsRenewalInterval;
                        }

                        // Get Free TCP/IP Port
                        if (registry.GetValue("KillProcessOnPort") != null)
                        {
                            KSScheckKillProcessOnPort.Checked = Convert.ToBoolean(registry.GetValue("KillProcessOnPort"));
                        }
                        else
                        {
                            KSScheckKillProcessOnPort.Checked = true;
                        }
                    }
                }
            }
        }
Ejemplo n.º 20
0
 public void UpdateText(KeyBase key)
 {
     key.UpdateText(ref currentText);
     UpdatePreviewText();
 }
Ejemplo n.º 21
0
        /// <summary>
        /// Install KMS Keys Automatically and Perform Activation of All KMS Licenses
        /// </summary>
        /// <param name="licenses">List of all Licenses</param>
        /// <param name="minimalOutput">Reduce the Amount of Output During Activation</param>
        /// <param name="kmsServer">KMS Host to Connect To</param>
        /// <param name="kmsPort">KMS Port to Connect To</param>
        /// <param name="kmsPid">KMS PID to apply to KMSEmulator</param>
        /// <param name="kmsHwid">KMS Hardware ID to apply to KMSEmulator</param>
        /// <param name="useKMSEmulator">Start a KMSEmulator Process</param>
        /// <param name="removeKMSConnection">Remove KMS Host and Port after Activation</param>
        /// <param name="killProcessOnPort">Force Start KMSEmulator by Killing Other Processes usign the KMS Port</param>
        /// <param name="useDLLInjection">Use DLL Injection to Force Localhost KMS Activation</param>
        /// <param name="useTAPAdapter">Use TAP Adapter to Force Localhost KMS Activation</param>
        /// <param name="useWinDivert">Use WinDivert Client to Force Localhost KMS Activation</param>
        /// <param name="localHostBypassIPAddress">IP Address of TAP Adapter NIC or WinDivert Client</param>
        /// <param name="localHostBypassIPSubnet">Subnet Mask for TAP Adapter or WinDivert Client Network</param>
        /// <returns>Activation Result of all KMS Licenses</returns>
        public static string RunEZActivator(LicenseList licenses, bool minimalOutput = true, string kmsServer = "127.0.0.2", int kmsPort = 1688, string kmsPid = "RandomKMSPID", string kmsHwid = "364F463A8863D35F", bool useKMSEmulator = true, bool removeKMSConnection = false, bool killProcessOnPort = false, bool useDLLInjection = false, bool useTAPAdapter = false, bool useWinDivert = false, string localHostBypassIPAddress = "10.3.0.1", string localHostBypassIPSubnet = "255.255.255.0")
        {
            // Show Activation Errors if No Licenses Exist
            if (licenses.GetListUnlicensed().Count == 0 && licenses.GetListLicensed().Count == 0)
            {
                return(LicenseErrorCode.ErrBroken);
            }
            // Show Activation Errors if No KMS Licenses Exist
            if (licenses.GetListKMS().Count == 0)
            {
                return(LicenseErrorCode.ErrNoKMS);
            }

            using (StringWriter output = new StringWriter())
            {
                // Activated Windows Check
                if (licenses is LicenseListWindows && licenses.GetListPermanentlyActivated().Count > 0)
                {
                    output.WriteLine("----------------------------------------");
                    output.WriteLine("Windows is already permanently activated.");
                    output.WriteLine("----------------------------------------");
                    return(output.ToString());
                }

                // Get All Possible KMS Keys
                KeyList keys = new KeyList();
                if (licenses is LicenseListOffice)
                {
                    keys = KeyBase.GetApplicableKeysList(OfficeVersion.GetOfficeName());
                }
                else if (licenses is LicenseListWindows)
                {
                    keys = KeyBase.GetApplicableKeysList(OSVersion.GetWindowsName());
                }

                // Remove Trial Keys
                bool removedTrialKeys = false;
                output.WriteLine("----------------------------------------");
                output.WriteLine("Removing Any Trial/Grace Keys.");
                foreach (LicenseInstance licenseKeys in licenses.GetListLicensed())
                {
                    if (licenseKeys.LicenseDescription.ToUpper().Contains("TRIAL") || licenseKeys.LicenseDescription.ToUpper().Contains("GRACE"))
                    {
                        if (licenses is LicenseListOffice)
                        {
                            KeyInstaller.UnInstallKeyByKeyOffice(licenseKeys.PartialProductKey);
                            output.WriteLine("Removed Key for: " + licenseKeys.LicenseFamily + " (" + licenseKeys.PartialProductKey + ").");
                            removedTrialKeys = true;
                        }
                        else if (licenses is LicenseListWindows)
                        {
                            KeyInstaller.UnInstallKeyByKeyOffice(licenseKeys.PartialProductKey);
                            output.WriteLine("Removed Key for: " + licenseKeys.LicenseFamily + " (" + licenseKeys.PartialProductKey + ").");
                            removedTrialKeys = true;
                        }
                    }
                }
                if (removedTrialKeys)
                {
                    licenses.Refresh();
                }

                // Install Uninstalled KMS Keys by SKUID Match
                bool installedKMSKeys = false;
                output.WriteLine("----------------------------------------");
                output.WriteLine("Installing Any Matching Volume Keys.");
                if (licenses is LicenseListWindows && OSVersion.GetWindowsNumber() >= 10 && OSVersion.GetWindowsBuildNumber() >= 14393)
                {
                    // Determine KMS Key
                    if (licenses.GetListLicensed().Count > 0)
                    {
                        // SKU Match Existing Key
                        foreach (LicenseInstance license in licenses.GetListLicensed())
                        {
                            string editionId = license.LicenseFamily;
                            try
                            {
                                // Check Key
                                bool          installKey       = true;
                                List <string> skuidListMatched = keys.GetSKUIDs(editionId);
                                foreach (LicenseInstance licensed in licenses.GetListLicensed())
                                {
                                    if (skuidListMatched.Contains(licensed.SKUID))
                                    {
                                        installKey = false;
                                        break;
                                    }
                                }

                                // Install Key
                                if (installKey)
                                {
                                    // Get All SKUIDs
                                    List <string> skuidListAll = new List <string>();
                                    foreach (LicenseInstance licensed in licenses.GetListFull())
                                    {
                                        skuidListAll.Add(licensed.SKUID);
                                    }

                                    // Get Matched Key
                                    foreach (string skuid in skuidListMatched)
                                    {
                                        if (skuidListAll.Contains(skuid))
                                        {
                                            output.WriteLine("Installing " + keys.GetProductName(skuid) + " KMS Key (" + keys.GetProductKey(skuid) + ").");
                                            KeyInstaller.InstallKeyWindows(keys.GetProductKey(skuid));
                                            output.WriteLine("<Product key installation successful>");
                                            installedKMSKeys = true;
                                            break;
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                output.WriteLine(ex.Message);
                            }
                        }
                    }
                    else
                    {
                        // Edition ID Check
                        using (RegistryKey registrySubKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64).OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", true))
                        {
                            if (registrySubKey != null && registrySubKey.GetValue("EditionID") != null)
                            {
                                string editionId = registrySubKey.GetValue("EditionID").ToString();
                                try
                                {
                                    if (keys.GetProductKey(editionId) != string.Empty)
                                    {
                                        output.WriteLine("Installing " + keys.GetProductName(editionId) + " KMS Key (" + keys.GetProductKey(editionId) + ").");
                                        KeyInstaller.InstallKeyWindows(keys.GetProductKey(editionId));
                                        output.WriteLine("<Product key installation successful>");
                                        installedKMSKeys = true;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    output.WriteLine(ex.Message);
                                }
                            }
                        }
                    }
                }
                else
                {
                    foreach (LicenseInstance license in licenses.GetListUnlicensed())
                    {
                        if (keys.GetSKUIDs().Contains(license.SKUID))
                        {
                            try
                            {
                                output.WriteLine("Installing " + keys.GetProductName(license.SKUID) + " KMS Key (" + keys.GetProductKey(license.SKUID) + ").");
                                if (licenses is LicenseListOffice)
                                {
                                    KeyInstaller.InstallKeyOffice(keys.GetProductKey(license.SKUID));
                                    output.WriteLine("<Product key installation successful>");
                                    installedKMSKeys = true;
                                }
                                else if (licenses is LicenseListWindows)
                                {
                                    KeyInstaller.InstallKeyWindows(keys.GetProductKey(license.SKUID));
                                    output.WriteLine("<Product key installation successful>");
                                    installedKMSKeys = true;
                                }
                            }
                            catch (Exception ex)
                            {
                                output.WriteLine(ex.Message);
                            }
                        }
                    }
                }
                output.WriteLine("----------------------------------------");
                if (installedKMSKeys)
                {
                    licenses.Refresh();
                }

                // Perform Activation
                if (licenses is LicenseListOffice)
                {
                    output.WriteLine("Attempting To Activate Microsoft Office");
                    output.Write(ActivationState.AttemptActivationOffice(licenses, minimalOutput, kmsServer, kmsPort, kmsPid, kmsHwid, useKMSEmulator, removeKMSConnection, killProcessOnPort, useDLLInjection, useTAPAdapter, useWinDivert, localHostBypassIPAddress, localHostBypassIPSubnet));
                }
                else if (licenses is LicenseListWindows)
                {
                    output.WriteLine("Attempting To Activate Microsoft Windows");
                    output.Write(ActivationState.AttemptActivationWindows(licenses, minimalOutput, kmsServer, kmsPort, kmsPid, kmsHwid, useKMSEmulator, removeKMSConnection, killProcessOnPort, useDLLInjection, useTAPAdapter, useWinDivert, localHostBypassIPAddress, localHostBypassIPSubnet));
                }

                return(output.ToString());
            }
        }
Ejemplo n.º 22
0
        public static void AddEntry(this EnvCryptDat toDatPoco,
                                    string categoryName, string entryName,
                                    KeyBase key, IList <byte[]> segments, bool overwriteIfEntryExists = false)
        {
            Contract.Requires <ArgumentException>(!string.IsNullOrEmpty(categoryName), "categoryName");
            Contract.Requires <ArgumentException>(!string.IsNullOrEmpty(entryName), "entryName");
            Contract.Requires <ArgumentNullException>(key != null, "key");
            Contract.Requires <ArgumentNullException>(segments != null, "segments");
            //
            var isNewEntry = true;
            var entryToAdd = new Entry();

            var isNewCategory   = true;
            var categoryToAddTo = new Category()
            {
                Name    = categoryName,
                Entries = new List <Entry>()
            };


            // Search for entries with the same name in the desired category
            {
                Category foundCategory;
                if (toDatPoco.SearchForCategory(categoryName, out foundCategory))
                {
                    isNewCategory   = false;
                    categoryToAddTo = foundCategory;
                }
            }

            if (!isNewCategory)
            {
                Entry foundEntry;
                if (categoryToAddTo.SearchForEntry(entryName, out foundEntry))
                {
                    if (overwriteIfEntryExists)
                    {
                        isNewEntry = false;
                        entryToAdd = foundEntry;
                        toDatPoco.RemoveEntry(categoryName, entryName);
                    }
                    else
                    {
                        throw new EnvCryptException(
                                  "the entry '{0}' already exists in the category '{1}' and the option to overwrite was not chosen",
                                  entryName, categoryName);
                    }
                }
            }

            entryToAdd.Name                = entryName;
            entryToAdd.KeyName             = key.Name;
            entryToAdd.KeyHash             = key.GetHashCode();
            entryToAdd.EncryptionAlgorithm = key.Algorithm;
            entryToAdd.EncryptedValue      = segments;

            categoryToAddTo.Entries.Add(entryToAdd);

            if (isNewCategory || !isNewEntry)
            {
                toDatPoco.Categories.Add(categoryToAddTo);
            }
        }