Esempio n. 1
0
        /*
         * // TODO: Fix 1000=232 Bug
         * /// <summary>
         * /// Obtain the remaining number of Rearms for Microsoft Windows via DLL
         * /// </summary>
         * /// <returns>Remaining Rearm Count Number</returns>
         * public static int GetRearmCountDLL()
         * {
         *  // Microsoft Windows Application ID
         *  Guid windowsAppID = new Guid("55c92734-d682-4d71-983e-d6ec3f16059f");
         *
         *  // Handles
         *  IntPtr sppHandle = IntPtr.Zero;
         *
         *  // Open Handle to Microsoft Windows Software Licensing Service
         *  NativeMethods.SPPOpen(ref sppHandle);
         *
         *  // Get Microsoft Office Remaining Rearm Count from SPP
         *  uint descSize = 4;
         *  byte[] descBuffer = new byte[descSize];
         *  NativeMethods.SLDATATYPE slDataType = NativeMethods.SLDATATYPE.SL_DATA_DWORD;
         *  NativeMethods.SPPGetApplicationInformation(sppHandle, ref windowsAppID, "RemainingRearmCount", ref slDataType, ref descSize, ref descBuffer);
         *
         *  // Close Handle to Microsoft Windows Software Licensing Service
         *  NativeMethods.SPPClose(sppHandle);
         *
         *  // Return Rearm Count
         *  return descBuffer[0];
         * }
         */

        /// <summary>
        /// Rearm Microsoft Windows
        /// </summary>
        /// <returns>Output of Rearm Result and Any Errors</returns>
        public static string Rearm()
        {
            try
            {
                // Perform Rearm
                using (ManagementObject classInstance = new ManagementObject(@"root\CIMV2", "SoftwareLicensingService.Version='" + OSVersion.GetSPPSVCVersion() + "'", null))
                {
                    classInstance.InvokeMethod("ReArmWindows", null, null);
                }

                // Restart SPPSVC
                Services.StopSPPSVC();
                Services.StartSPPSVC();

                // On Windows 7 and Earlier, we don't need to reboot.
                if (OSVersion.GetWindowsNumber() < 6.2)
                {
                    return("<Microsoft Windows rearm successful.>");
                }
                return("<Microsoft Windows rearm successful.>" + Environment.NewLine + "You need to reboot for the rearm to take effect or Windows to work properly.");
            }
            catch (COMException ex)
            {
                return("<Microsoft Windows rearm failed>" + Environment.NewLine + LicenseErrorCode.GetErrorDescription("0x" + ex.ErrorCode.ToString("X8")));
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Uninstall KMS Server Service and Remove Windows Service Registration
        /// </summary>
        /// <returns>Output of Uninstallation Process</returns>
        public static string UninstallKMSServerService()
        {
            using (StringWriter output = new StringWriter())
            {
                // Get Program File Path
                try
                {
                    _kmsServerServiceInstallPath = GetKMSServerServicePath();
                }
                catch (Exception)
                {
                    output.WriteLine("Failed to access KMS Server Service installation path!");
                    return(output.ToString());
                }

                // Delete Program File
                try
                {
                    Services.StopService(KMSServerServiceName, KMSServerServiceProcessName);
                    CommonUtilities.FileDelete(_kmsServerServiceInstallPath + Path.DirectorySeparatorChar + KMSServerServiceFileName);
                    output.WriteLine("Deleted " + _kmsServerServiceInstallPath + Path.DirectorySeparatorChar + KMSServerServiceFileName);
                }
                catch (Exception)
                {
                    output.WriteLine("Failed to delete " + _kmsServerServiceInstallPath + Path.DirectorySeparatorChar + KMSServerServiceFileName);
                }

                // Delete Windows Service Registration
                try
                {
                    DeleteKMSServerServiceRegistration();
                    output.WriteLine("Deleted KMS Server Service Registration");
                }
                catch (Exception)
                {
                    output.WriteLine("Failed to delete KMS Server Service Registration");
                }

                // Remove Windows Defender Exclusion
                if (OSVersion.GetWindowsNumber() >= 10.0)
                {
                    CommonUtilities.ExecuteCommand("powershell.exe Remove-MpPreference -ExclusionPath " + CommonUtilities.EscapePath(_kmsServerServiceInstallPath) + " -Force", true);
                }

                if (output.ToString().Contains("Failed"))
                {
                    output.Write("KMS Server Service failed to uninstall!");
                }
                else
                {
                    // Delete Install Folder If Empty
                    CommonUtilities.DeleteEmptyFolders(_kmsServerServiceInstallPath + Path.DirectorySeparatorChar);

                    output.Write("KMS Server Service was succesfully uninstalled.");
                }
                return(output.ToString());
            }
        }
Esempio n. 3
0
 /// <summary>
 /// Stop the Microsoft Windows Software Licensing Service
 /// </summary>
 public static void StopSPPSVC()
 {
     if (OSVersion.GetWindowsNumber() >= 6.1)
     {
         StopService("SPPSVC");
         DisableService("SPPSVC");
     }
     else if (Math.Abs(OSVersion.GetWindowsNumber() - 6.0) < Double.Epsilon)
     {
         StopService("SLSVC");
         DisableService("SLSVC");
     }
 }
Esempio n. 4
0
        /// <summary>
        /// Attempt Activation on each License in a List
        /// </summary>
        /// <param name="licenses">List of all Licenses</param>
        /// <param name="minimalOutput">Reduce the Amount of Output During Activation</param>
        /// <param name="wmiInfo">WMI Provider and associated data to attempt 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 Licenses</returns>
        private static string AttemptActivation(LicenseList licenses, string wmiInfo, bool minimalOutput = false, 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")
        {
            using (StringWriter output = new StringWriter())
            {
                // Show Activation Errors if No Licenses or Keys Exist
                if (licenses.GetListUnlicensed().Count == 0 && licenses.GetListLicensed().Count == 0)
                {
                    return(LicenseErrorCode.ErrBroken);
                }
                if (licenses.GetListUnlicensed().Count > 0 && licenses.GetListLicensed().Count == 0)
                {
                    return(LicenseErrorCode.ErrKeyless);
                }

                // Get Firewall Parameters
                string programName     = CommonUtilities.EscapePath(System.Reflection.Assembly.GetEntryAssembly().GetName().Name);
                string programLocation = CommonUtilities.EscapePath(Process.GetCurrentProcess().MainModule.FileName);

                // Delete Block Firewall Rules
                CommonUtilities.ExecuteCommand("netsh advfirewall firewall delete rule name=all program=" + programLocation, true);
                CommonUtilities.ExecuteCommand("netsh advfirewall firewall delete rule name=all localport=" + kmsPort, true);

                // Add Allow Firewall Rules
                CommonUtilities.ExecuteCommand("netsh advfirewall firewall add rule name=" + programName + " dir=in program=" + programLocation + " localport=" + kmsPort + " protocol=TCP action=allow remoteip=any", true);
                CommonUtilities.ExecuteCommand("netsh advfirewall firewall add rule name=" + programName + " dir=out program=" + programLocation + " localport=" + kmsPort + " protocol=TCP action=allow remoteip=any", true);

                // Setup Localhost Bypass for KMS V6
                if (OSVersion.GetWindowsNumber() >= 6.3 && ((licenses is LicenseListOffice && OfficeVersion.GetOfficeNumber() >= 15) || (licenses is LicenseListWindows)))
                {
                    // Disable KMS Online Validation
                    KMSConnection.DisableKMSGenuineChecks();

                    // Use Localhost Bypass for Loopback IP Addresses or Machine Name
                    if (Regex.IsMatch(kmsServer.ToLower(), @"^(127(\.\d+){1,3}|[0:]+1|localhost)$") || String.Compare(kmsServer, Environment.MachineName, StringComparison.InvariantCultureIgnoreCase) == 0)
                    {
                        if (useDLLInjection)
                        {
                            // Disable Other Bypasses
                            useTAPAdapter = false;
                            useWinDivert  = false;

                            try
                            {
                                KMSDLLInjection.Initialize(localHostBypassIPAddress);

                                /*
                                 * if (!KMSDLLInjection.LoadDLL())
                                 * {
                                 *  output.WriteLine("Failed to inject LocalHost Bypass DLL.");
                                 * }
                                 * else
                                 * {
                                 *  kmsServer = localHostBypassIPAddress;
                                 * }
                                 */
                                KMSDLLInjection.LoadDLLIFEO();
                                kmsServer = localHostBypassIPAddress;
                            }
                            catch (Exception ex)
                            {
                                output.WriteLine("Failed to inject LocalHost Bypass DLL.");
                                output.WriteLine(ex.Message);
                            }
                        }
                        else if (useTAPAdapter)
                        {
                            // Disable Other Bypasses
                            useWinDivert = false;

                            // Check Installed TAP Adapter Count
                            if (KMSTAPDriver.GetTAPDeviceCount() > 1)
                            {
                                output.WriteLine("WARNING: You have more than 1 TAP Adapter installed.");
                            }

                            // Initialize TAP Driver
                            KMSTAPDriver.Initialize(localHostBypassIPAddress, localHostBypassIPSubnet);

                            // Check and Set IP Address
                            string tapIP     = KMSTAPDriver.GetTAPDeviceIPAddress();
                            string tapSubnet = KMSTAPDriver.GetTAPDeviceIPSubnet();
                            if (tapIP == string.Empty || Regex.IsMatch(tapIP, @"^(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]))$"))
                            {
                                output.WriteLine("Failed to set IP Address on TAP Adapter. It may already be in use.");
                            }
                            else if (tapIP != localHostBypassIPAddress || tapSubnet != localHostBypassIPSubnet)
                            {
                                KMSTAPDriver.SetTAPDeviceIPConfiguration(localHostBypassIPAddress, localHostBypassIPSubnet);
                                output.WriteLine("Failed to update IP Address Configuration on TAP Adapter.");
                            }
                            else
                            {
                                // Set KMS Server to Valid TAP IP Address
                                kmsServer = KMSTAPDriver.GetTAPDeviceUsableIPAddress();

                                // Start TAP Listener
                                KMSTAPDriver.Start();
                            }
                        }
                        else if (useWinDivert)
                        {
                            // Start WinDivert
                            KMSWinDivert.StartWinDivertClient(localHostBypassIPAddress, localHostBypassIPSubnet);
                            kmsServer = localHostBypassIPAddress;
                        }
                    }
                    else
                    {
                        // Disable Localhost Bypass
                        useDLLInjection = false;
                        useTAPAdapter   = false;
                        useWinDivert    = false;
                    }
                }
                else
                {
                    // Disable Localhost Bypass
                    useDLLInjection = false;
                    useTAPAdapter   = false;
                    useWinDivert    = false;
                }

                // Set KMS Server
                try
                {
                    if (licenses is LicenseListOffice)
                    {
                        KMSConnection.SetKMSHostOffice(licenses, kmsServer);
                    }
                    else if (licenses is LicenseListWindows)
                    {
                        KMSConnection.SetKMSHostWindows(licenses, kmsServer);
                    }
                }
                catch (Exception ex)
                {
                    output.WriteLine("Failed to set KMS Host!");
                    output.WriteLine(ex.Message);
                }

                // Set KMS Port
                try
                {
                    if (licenses is LicenseListOffice)
                    {
                        KMSConnection.SetKMSPortOffice(licenses, kmsPort.ToString(CultureInfo.InvariantCulture));
                    }
                    else if (licenses is LicenseListWindows)
                    {
                        KMSConnection.SetKMSPortWindows(licenses, kmsPort.ToString(CultureInfo.InvariantCulture));
                    }
                }
                catch (Exception ex)
                {
                    output.WriteLine("Failed to set KMS Port");
                    output.WriteLine(ex.Message);
                }

                // Start KMSEmulator
                if (useKMSEmulator)
                {
                    try
                    {
                        // Set KMS Server Settings
                        KMSServerSettings settings = new KMSServerSettings {
                            KillProcessOnPort = killProcessOnPort, Port = kmsPort
                        };

                        // Handle KMS PID Generation
                        if (kmsPid == "ReuseKMSPID")
                        {
                            // Check Licenses for Existing KMS PID
                            foreach (LicenseInstance license in licenses.GetListLicensed())
                            {
                                if (!String.IsNullOrWhiteSpace(license.KMSServerExtendedPID))
                                {
                                    // Found Existing KMS PID
                                    kmsPid = license.KMSServerExtendedPID;
                                    settings.DefaultKMSPID        = license.KMSServerExtendedPID;
                                    settings.GenerateRandomKMSPID = false;
                                    break;
                                }
                            }

                            // Did Not Find Existing KMS PID
                            if (kmsPid == "ReuseKMSPID")
                            {
                                // Generate Random KMS PID
                                settings.GenerateRandomKMSPID = true;
                            }
                        }
                        else if (kmsPid == "RandomKMSPID")
                        {
                            // Generate Random KMS PID
                            settings.GenerateRandomKMSPID = true;
                        }
                        else
                        {
                            // Use Static KMS PID
                            settings.GenerateRandomKMSPID = false;

                            // Set Static KMS PID if it is not Default KMS PID
                            if (kmsPid != "DefaultKMSPID")
                            {
                                settings.DefaultKMSPID = kmsPid;
                            }
                        }

                        // Handle KMS HWID
                        settings.DefaultKMSHWID = kmsHwid;

                        // Handle Client Count
                        if (licenses is LicenseListOffice || OSVersion.IsWindowsServer())
                        {
                            settings.CurrentClientCount = 5;
                        }
                        else
                        {
                            settings.CurrentClientCount = 25;
                        }

                        // Start KMS Server
                        KMSServer.Start(null, settings);
                    }
                    catch (SocketException)
                    {
                        output.WriteLine("Failed to start KMS Emulator!");
                        output.WriteLine("KMS Port may be in use.");
                    }
                    catch (Exception ex)
                    {
                        output.WriteLine("Failed to start KMS Emulator!");
                        output.WriteLine(ex.Message);
                    }
                }

                // Attempt Activation on Each License
                if (minimalOutput == false)
                {
                    output.WriteLine("---Processing--------------------------");
                    output.WriteLine("----------------------------------------");
                }

                bool firstLine = true;
                foreach (LicenseInstance license in licenses.GetListLicensed())
                {
                    // Add Extra Line if Needed
                    if (firstLine)
                    {
                        firstLine = false;
                    }
                    else
                    {
                        output.WriteLine();
                    }

                    if (minimalOutput == false)
                    {
                        output.WriteLine("Installed product key detected - attempting to activate the following product:");
                        output.WriteLine("Name: " + license.LicenseName);
                        output.WriteLine("Description: " + license.LicenseDescription);
                        output.WriteLine("Family: " + license.LicenseFamily);
                        output.WriteLine("SKU ID: " + license.SKUID);
                        output.WriteLine("Last 5 characters of installed product key: " + license.PartialProductKey);
                    }
                    else
                    {
                        output.WriteLine("Attempting to Activate " + license.LicenseFamily);
                    }

                    using (ManagementObject classInstance = new ManagementObject("root\\CIMV2", wmiInfo + "'" + license.SKUID + "'", null))
                    {
                        string errorCode = string.Empty;
                        for (int i = 0; i < 10; i++)
                        {
                            try
                            {
                                classInstance.InvokeMethod("Activate", null, null);
                                output.WriteLine("<Product activation successful>");
                                output.Write("----------------------------------------");
                                errorCode = string.Empty;
                                break;
                            }
                            catch (COMException ex)
                            {
                                // Get Activation Error
                                errorCode = "0x" + ex.ErrorCode.ToString("X8");

                                if (errorCode == "0xC004F074" && (useDLLInjection || useTAPAdapter || useWinDivert))
                                {
                                    if (useDLLInjection)
                                    {
                                        // Kill KMS Connection Broker
                                        CommonUtilities.KillProcess("SppExtComObj");
                                    }
                                    continue;
                                }
                                break;
                            }
                        }

                        // Show Activation Error
                        if (errorCode != string.Empty)
                        {
                            output.WriteLine("ERROR CODE: " + errorCode);
                            output.WriteLine("ERROR TEXT: " + LicenseErrorCode.GetErrorDescription(errorCode));
                            if (errorCode == "0xC004F059" || errorCode == "0xC004F035")
                            {
                                output.WriteLine("WARNING: It will be impossible to activate via KMS due to OEM BIOS issues.");
                            }
                            output.WriteLine("<Product activation failed>");
                            output.Write("----------------------------------------");
                        }
                    }
                }

                // Stop LocalHost Bypass
                if (useDLLInjection)
                {
                    /*
                     * if (!KMSDLLInjection.UnloadDLL())
                     * {
                     *  output.Write(Environment.NewLine + "Failed to eject LocalHost Bypass DLL.");
                     * }
                     */
                    try
                    {
                        KMSDLLInjection.UnloadDLLIFEO();
                    }
                    catch (Exception ex)
                    {
                        output.Write(Environment.NewLine + "Failed to eject LocalHost Bypass DLL.");
                        output.Write(Environment.NewLine + ex.Message);
                    }
                }
                else if (useTAPAdapter)
                {
                    KMSTAPDriver.Unload();
                }
                else if (useWinDivert)
                {
                    KMSWinDivert.StopWinDivertClient();
                }

                // Stop KMSEmulator
                if (useKMSEmulator)
                {
                    try
                    {
                        KMSServer.Stop();
                    }
                    catch (Exception ex)
                    {
                        output.WriteLine("Failed to stop KMS Emulator!");
                        output.WriteLine(ex.Message);
                    }
                }

                // Remove KMS Server
                if (removeKMSConnection)
                {
                    // Remove KMS Host
                    try
                    {
                        if (licenses is LicenseListOffice)
                        {
                            KMSConnection.RemoveKMSHostOffice(licenses);
                        }
                        else if (licenses is LicenseListWindows)
                        {
                            KMSConnection.RemoveKMSHostWindows(licenses);
                        }
                    }
                    catch (Exception ex)
                    {
                        output.WriteLine("Failed to remove KMS Host from registry!");
                        output.WriteLine(ex.Message);
                    }

                    // Remove KMS Port
                    try
                    {
                        if (licenses is LicenseListOffice)
                        {
                            KMSConnection.RemoveKMSPortOffice(licenses);
                        }
                        else if (licenses is LicenseListWindows)
                        {
                            KMSConnection.RemoveKMSPortWindows(licenses);
                        }
                    }
                    catch (Exception ex)
                    {
                        output.WriteLine("Failed to remove KMS Port from registry!");
                        output.WriteLine(ex.Message);
                    }
                }

                // Delete Allow Firewall Rules
                CommonUtilities.ExecuteCommand("netsh advfirewall firewall delete rule name=" + programName, true);

                // Read WinDivert Log
                if (useWinDivert && KMSWinDivert.Log != string.Empty)
                {
                    return(KMSWinDivert.Log + output);
                }

                return(output.ToString());
            }
        }
Esempio n. 5
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());
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Uninstall AutoKMS and Remove Scheduled Task
        /// </summary>
        /// <returns>Output of Uninstallation Process</returns>
        public static string UninstallAutoKMS()
        {
            using (StringWriter output = new StringWriter())
            {
                // Get Program File Path
                try
                {
                    AutoKMSInstallPath = GetAutoKMSPath();
                }
                catch (Exception)
                {
                    output.WriteLine("Failed to access AutoKMS installation path!");
                    return(output.ToString());
                }

                // Delete Program File
                try
                {
                    CommonUtilities.FileDelete(AutoKMSInstallPath + Path.DirectorySeparatorChar + AutoKMSFileName);
                    output.WriteLine("Deleted " + AutoKMSInstallPath + Path.DirectorySeparatorChar + AutoKMSFileName);
                }
                catch (Exception)
                {
                    output.WriteLine("Failed to delete " + AutoKMSInstallPath + Path.DirectorySeparatorChar + AutoKMSFileName);
                }

                // Delete Program Log
                try
                {
                    CommonUtilities.FileDelete(AutoKMSInstallPath + Path.DirectorySeparatorChar + AutoKMSLogFileName);
                    output.WriteLine("Deleted " + AutoKMSInstallPath + Path.DirectorySeparatorChar + AutoKMSLogFileName);
                }
                catch (Exception)
                {
                    output.WriteLine("Failed to delete " + AutoKMSInstallPath + Path.DirectorySeparatorChar + AutoKMSLogFileName);
                }

                // Delete Scheduled Tasks
                try
                {
                    if (IsAutoKMSCustomTaskInstalled())
                    {
                        DeleteAutoKMSCustomTask();
                    }
                    else
                    {
                        DeleteAutoKMSNormalTask();
                    }
                    output.WriteLine("Deleted AutoKMS Scheduled Task");
                }
                catch (Exception)
                {
                    output.WriteLine("Failed to delete AutoKMS Scheduled Task");
                }

                // Remove Windows Defender Exclusion
                if (OSVersion.GetWindowsNumber() >= 10.0)
                {
                    CommonUtilities.ExecuteCommand("powershell.exe Remove-MpPreference -ExclusionPath " + CommonUtilities.EscapePath(AutoKMSInstallPath) + " -Force", true);
                }

                if (output.ToString().Contains("Failed"))
                {
                    output.Write("AutoKMS failed to uninstall!");
                }
                else
                {
                    // Delete Install Folder If Empty
                    CommonUtilities.DeleteEmptyFolders(AutoKMSInstallPath);

                    output.Write("AutoKMS was succesfully uninstalled.");
                }
                return(output.ToString());
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Install AutoKMS and Setup Scheduled Task
        /// </summary>
        /// <param name="installPath">Path to write Program File</param>
        /// <param name="autoKMS">Byte Array representation of AutoKMS Program File </param>
        /// <returns>Output of Installation Process</returns>
        public static string InstallAutoKMS(string installPath, byte[] autoKMS)
        {
            using (StringWriter output = new StringWriter())
            {
                // Create Program File
                try
                {
                    try
                    {
                        AutoKMSInstallPath = installPath;

                        // Create Windows Defender Exclusion
                        if (OSVersion.GetWindowsNumber() >= 10.0)
                        {
                            CommonUtilities.ExecuteCommand("powershell.exe Add-MpPreference -ExclusionPath " + CommonUtilities.EscapePath(AutoKMSInstallPath) + " -Force", true);
                        }

                        // Create AutoKMS
                        CommonUtilities.FileCreate(AutoKMSFileName, autoKMS, AutoKMSInstallPath);
                        output.WriteLine("Created " + AutoKMSInstallPath + Path.DirectorySeparatorChar + AutoKMSFileName);
                    }
                    catch (Exception)
                    {
                        AutoKMSInstallPath = Environment.GetEnvironmentVariable("windir") + Path.DirectorySeparatorChar + AutoKMSProcessName;
                        output.WriteLine("Could not access AutoKMS path set in Settings, using default installation path.");
                        CommonUtilities.FileCreate(AutoKMSFileName, autoKMS, AutoKMSInstallPath);
                        output.WriteLine("Created " + AutoKMSInstallPath + Path.DirectorySeparatorChar + AutoKMSFileName);
                    }
                }
                catch (Exception)
                {
                    // Remove Windows Defender Exclusion
                    if (OSVersion.GetWindowsNumber() >= 10.0)
                    {
                        CommonUtilities.ExecuteCommand("powershell.exe Remove-MpPreference -ExclusionPath " + CommonUtilities.EscapePath(AutoKMSInstallPath) + " -Force", true);
                    }

                    output.WriteLine("Failed to create " + AutoKMSInstallPath + Path.DirectorySeparatorChar + AutoKMSFileName);
                    output.Write("AutoKMS failed to install!");
                    return(output.ToString());
                }

                // Create Scheduled Tasks
                try
                {
                    MakeAutoKMSNormalTask();
                    output.WriteLine("Created AutoKMS Scheduled Task");
                }
                catch (Exception ex)
                {
                    output.WriteLine("Failed to create AutoKMS Scheduled Task");
                    output.WriteLine(ex.Message);
                    output.WriteLine("Cleaning up as AutoKMS is partially installed");

                    // Delete Program File
                    try
                    {
                        CommonUtilities.FileDelete(AutoKMSInstallPath + Path.DirectorySeparatorChar + AutoKMSFileName);
                        output.WriteLine("Deleted " + AutoKMSInstallPath + Path.DirectorySeparatorChar + AutoKMSFileName);
                    }
                    catch (Exception)
                    {
                        output.WriteLine("Failed to delete " + AutoKMSInstallPath + Path.DirectorySeparatorChar + AutoKMSFileName);
                    }

                    // Remove Windows Defender Exclusion
                    if (OSVersion.GetWindowsNumber() >= 10.0)
                    {
                        CommonUtilities.ExecuteCommand("powershell.exe Remove-MpPreference -ExclusionPath " + CommonUtilities.EscapePath(AutoKMSInstallPath) + " -Force", true);
                    }

                    output.Write("AutoKMS failed to install!");
                    return(output.ToString());
                }

                output.Write("AutoKMS was succesfully installed.");
                return(output.ToString());
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Uninstall AutoRearm and Remove Scheduled Task
        /// </summary>
        /// <returns>Output of Uninstallation Process</returns>
        public static string UninstallAutoRearm()
        {
            using (StringWriter output = new StringWriter())
            {
                // Get Program File Path
                try
                {
                    AutoRearmInstallPath = GetAutoRearmPath();
                }
                catch (Exception)
                {
                    output.WriteLine("Failed to access AutoRearm installation path!");
                    return(output.ToString());
                }

                // Restore AutoRearm Backup
                try
                {
                    string restoreoutput = LicenseBackup.RestoreOfficeTrustedStore("AutoRearmBackup", AutoRearmInstallPath + "Backups\\" + OfficeVersion.GetOfficeName() + Path.DirectorySeparatorChar);

                    if (restoreoutput.Contains("Failed"))
                    {
                        throw new Exception();
                    }
                    output.WriteLine("Restored License Backup from when you installed AutoRearm");
                }
                catch (Exception)
                {
                    output.WriteLine("Failed to Restore License Backup from when you installed AutoRearm");
                }

                // Delete AutoRearm Backups folder
                try
                {
                    CommonUtilities.FolderDelete(AutoRearmInstallPath + "Backups\\" + OfficeVersion.GetOfficeName() + Path.DirectorySeparatorChar);
                    output.WriteLine("Deleted " + AutoRearmInstallPath + "Backups\\" + OfficeVersion.GetOfficeName() + Path.DirectorySeparatorChar);
                }
                catch (Exception)
                {
                    output.WriteLine("Failed to delete AutoRearm Backups directory");
                }

                // Delete Program File
                try
                {
                    CommonUtilities.FileDelete(AutoRearmInstallPath + Path.DirectorySeparatorChar + AutoRearmFileName);
                    output.WriteLine("Deleted " + AutoRearmInstallPath + Path.DirectorySeparatorChar + AutoRearmFileName);
                }
                catch (Exception)
                {
                    output.WriteLine("Failed to delete " + AutoRearmInstallPath + Path.DirectorySeparatorChar + AutoRearmFileName);
                }

                // Delete Program Log
                try
                {
                    CommonUtilities.FileDelete(AutoRearmInstallPath + Path.DirectorySeparatorChar + AutoRearmLogFileName);
                    output.WriteLine("Deleted " + AutoRearmInstallPath + Path.DirectorySeparatorChar + AutoRearmLogFileName);
                }
                catch (Exception)
                {
                    output.WriteLine("Failed to delete " + AutoRearmInstallPath + Path.DirectorySeparatorChar + AutoRearmLogFileName);
                }

                // Delete Scheduled Tasks
                try
                {
                    DeleteAutoRearmNormalTask();
                    output.WriteLine("Deleted AutoRearm Scheduled Tasks");
                }
                catch (Exception)
                {
                    output.WriteLine("Failed to delete AutoRearm Scheduled Tasks");
                }

                // Remove Windows Defender Exclusion
                if (OSVersion.GetWindowsNumber() >= 10.0)
                {
                    CommonUtilities.ExecuteCommand("powershell.exe Remove-MpPreference -ExclusionPath " + CommonUtilities.EscapePath(AutoRearmInstallPath) + " -Force", true);
                }

                if (output.ToString().Contains("Failed"))
                {
                    output.Write("AutoRearm failed to uninstall!");
                }
                else
                {
                    // Delete Install Folder If Empty
                    CommonUtilities.DeleteEmptyFolders(AutoRearmInstallPath + Path.DirectorySeparatorChar);

                    output.Write("AutoRearm was succesfully uninstalled.");
                }
                return(output.ToString());
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Install AutoRearm and Setup Scheduled Task
        /// </summary>
        /// <param name="installPath">Path to write Program File</param>
        /// <param name="autoRearm">Byte Array representation of AutoRearm Program File</param>
        /// <returns>Output of Installation Process</returns>
        public static string InstallAutoRearm(string installPath, byte[] autoRearm)
        {
            using (StringWriter output = new StringWriter())
            {
                LicenseList licenses = new LicenseListOffice();

                // Show Activation Errors if No Licenses or Keys Exist
                if (licenses.GetListUnlicensed().Count == 0 && licenses.GetListLicensed().Count == 0)
                {
                    output.WriteLine(LicenseErrorCode.ErrBroken);
                    return(output.ToString());
                }
                if (licenses.GetListUnlicensed().Count > 0 && licenses.GetListLicensed().Count == 0)
                {
                    output.WriteLine(LicenseErrorCode.ErrKeyless);
                    return(output.ToString());
                }

                // Get Rearm Count
                try
                {
                    int rearmCount = RearmOffice.GetRearmCount();
                    if (rearmCount < 1)
                    {
                        output.Write("You must have at least 1 available rearm to use this tool." + Environment.NewLine + "You have " + rearmCount + " rearms.");
                        return(output.ToString());
                    }
                    output.WriteLine("You have " + rearmCount + " rearms.");
                }
                catch (Exception)
                {
                    output.Write("Failed to check rearm count. AutoRearm cannot be installed");
                    return(output.ToString());
                }

                // Create Program File
                try
                {
                    try
                    {
                        AutoRearmInstallPath = installPath;

                        // Create Windows Defender Exclusion
                        if (OSVersion.GetWindowsNumber() >= 10.0)
                        {
                            CommonUtilities.ExecuteCommand("powershell.exe Add-MpPreference -ExclusionPath " + CommonUtilities.EscapePath(AutoRearmInstallPath) + " -Force", true);
                        }

                        // Create AutoRearm
                        CommonUtilities.FileCreate(AutoRearmFileName, autoRearm, AutoRearmInstallPath);
                        output.WriteLine("Created " + AutoRearmInstallPath + Path.DirectorySeparatorChar + AutoRearmFileName);
                    }
                    catch (Exception)
                    {
                        AutoRearmInstallPath = Environment.GetEnvironmentVariable("windir") + Path.DirectorySeparatorChar + AutoRearmProcessName;
                        output.WriteLine("Could not access AutoRearm path set in Settings, using default installation path.");
                        CommonUtilities.FileCreate(AutoRearmFileName, autoRearm, AutoRearmInstallPath);
                        output.WriteLine("Created " + AutoRearmInstallPath + Path.DirectorySeparatorChar + AutoRearmFileName);
                    }
                }
                catch (Exception)
                {
                    // Remove Windows Defender Exclusion
                    if (OSVersion.GetWindowsNumber() >= 10.0)
                    {
                        CommonUtilities.ExecuteCommand("powershell.exe Remove-MpPreference -ExclusionPath " + CommonUtilities.EscapePath(AutoRearmInstallPath) + " -Force", true);
                    }

                    output.WriteLine("Failed to create " + AutoRearmInstallPath + Path.DirectorySeparatorChar + AutoRearmFileName);
                    output.Write("AutoRearm failed to install!");
                    return(output.ToString());
                }

                // Create Scheduled Tasks
                try
                {
                    MakeAutoRearmNormalTask();
                    output.WriteLine("Created AutoRearm Scheduled Tasks");
                }
                catch (Exception ex)
                {
                    output.WriteLine("Failed to create AutoRearm Scheduled Tasks");
                    output.WriteLine(ex.Message);
                    output.WriteLine("Cleaning up as AutoRearm is partially installed");

                    // Delete Program File
                    try
                    {
                        CommonUtilities.FileDelete(AutoRearmInstallPath + Path.DirectorySeparatorChar + AutoRearmFileName);
                        output.WriteLine("Deleted " + AutoRearmInstallPath + Path.DirectorySeparatorChar + AutoRearmFileName);
                    }
                    catch (Exception)
                    {
                        output.WriteLine("Failed to delete " + AutoRearmInstallPath + Path.DirectorySeparatorChar + AutoRearmFileName);
                    }

                    // Remove Windows Defender Exclusion
                    if (OSVersion.GetWindowsNumber() >= 10.0)
                    {
                        CommonUtilities.ExecuteCommand("powershell.exe Remove-MpPreference -ExclusionPath " + CommonUtilities.EscapePath(AutoRearmInstallPath) + " -Force", true);
                    }

                    output.Write("AutoRearm failed to install!");
                    return(output.ToString());
                }

                // Make License Backup
                try
                {
                    LicenseBackup.Backup("AutoRearmBackup", AutoRearmInstallPath + "\\Backups\\" + OfficeVersion.GetOfficeName() + Path.DirectorySeparatorChar, licenses);
                    output.WriteLine("Created License Backup Of Current Configuration");
                }
                catch (Exception)
                {
                    output.WriteLine("Failed to create License Backup Of Current Configuration");
                    output.WriteLine("Cleaning up as AutoRearm is partially installed");

                    // Delete Program File
                    try
                    {
                        CommonUtilities.FileDelete(AutoRearmInstallPath + Path.DirectorySeparatorChar + AutoRearmFileName);
                        output.WriteLine("Deleted " + AutoRearmInstallPath + Path.DirectorySeparatorChar + AutoRearmFileName);
                    }
                    catch (Exception)
                    {
                        output.WriteLine("Failed to delete " + AutoRearmInstallPath + Path.DirectorySeparatorChar + AutoRearmFileName);
                    }

                    // Delete Scheduled Tasks
                    try
                    {
                        DeleteAutoRearmNormalTask();
                        output.WriteLine("Deleted AutoRearm Scheduled Tasks");
                    }
                    catch (Exception)
                    {
                        output.WriteLine("Failed to delete AutoRearm Scheduled Tasks");
                    }

                    // Remove Windows Defender Exclusion
                    if (OSVersion.GetWindowsNumber() >= 10.0)
                    {
                        CommonUtilities.ExecuteCommand("powershell.exe Remove-MpPreference -ExclusionPath " + CommonUtilities.EscapePath(AutoRearmInstallPath) + " -Force", true);
                    }

                    output.Write("AutoRearm failed to install!");
                    return(output.ToString());
                }

                output.Write("AutoRearm was succesfully installed.");
                return(output.ToString());
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Install KMS Server Service and Setup Windows Service Registration
        /// </summary>
        /// <param name="installPath">Path to write Program File</param>
        /// <param name="kmsServerService">Byte Array representation of KMS Server Service Program File </param>
        /// <returns>Output of Installation Process</returns>
        public static string InstallKMSServerService(string installPath, byte[] kmsServerService)
        {
            using (StringWriter output = new StringWriter())
            {
                // Create Program File
                try
                {
                    try
                    {
                        _kmsServerServiceInstallPath = installPath;

                        // Create Windows Defender Exclusion
                        if (OSVersion.GetWindowsNumber() >= 10.0)
                        {
                            CommonUtilities.ExecuteCommand("powershell.exe Add-MpPreference -ExclusionPath " + CommonUtilities.EscapePath(_kmsServerServiceInstallPath) + " -Force", true);
                        }

                        // Create KMS Server Service
                        CommonUtilities.FileCreate(KMSServerServiceFileName, kmsServerService, _kmsServerServiceInstallPath);
                        output.WriteLine("Created " + _kmsServerServiceInstallPath + Path.DirectorySeparatorChar + KMSServerServiceFileName);
                    }
                    catch (Exception)
                    {
                        _kmsServerServiceInstallPath = Environment.GetEnvironmentVariable("windir") + Path.DirectorySeparatorChar + KMSServerServiceName;
                        output.WriteLine("Could not access KMS Server Service path set in Settings, using default installation path.");
                        CommonUtilities.FileCreate(KMSServerServiceFileName, kmsServerService, _kmsServerServiceInstallPath);
                        output.WriteLine("Created " + _kmsServerServiceInstallPath + Path.DirectorySeparatorChar + KMSServerServiceFileName);
                    }
                }
                catch (Exception)
                {
                    // Remove Windows Defender Exclusion
                    if (OSVersion.GetWindowsNumber() >= 10.0)
                    {
                        CommonUtilities.ExecuteCommand("powershell.exe Remove-MpPreference -ExclusionPath " + CommonUtilities.EscapePath(_kmsServerServiceInstallPath) + " -Force", true);
                    }

                    output.WriteLine("Failed to create " + _kmsServerServiceInstallPath + Path.DirectorySeparatorChar + KMSServerServiceFileName);
                    output.Write("KMS Server Service failed to install!");
                    return(output.ToString());
                }

                // Create Windows Service Registration
                try
                {
                    MakeKMSServerServiceRegistration();
                    output.WriteLine("Created KMS Server Service Registration");
                }
                catch (Exception ex)
                {
                    output.WriteLine("Failed to create KMS Server Service Registration");
                    output.WriteLine(ex.Message);
                    output.WriteLine("Cleaning up as KMS Server Service is partially installed");

                    // Delete Program File
                    try
                    {
                        CommonUtilities.FileDelete(_kmsServerServiceInstallPath + Path.DirectorySeparatorChar + KMSServerServiceFileName);
                        output.WriteLine("Deleted " + _kmsServerServiceInstallPath + Path.DirectorySeparatorChar + KMSServerServiceFileName);
                    }
                    catch (Exception)
                    {
                        output.WriteLine("Failed to delete " + _kmsServerServiceInstallPath + Path.DirectorySeparatorChar + KMSServerServiceFileName);
                    }

                    // Remove Windows Defender Exclusion
                    if (OSVersion.GetWindowsNumber() >= 10.0)
                    {
                        CommonUtilities.ExecuteCommand("powershell.exe Remove-MpPreference -ExclusionPath " + CommonUtilities.EscapePath(_kmsServerServiceInstallPath) + " -Force", true);
                    }

                    output.Write("KMS Server Service failed to install!");
                    return(output.ToString());
                }

                output.Write("KMS Server Service was succesfully installed.");
                Services.StartService(KMSServerServiceName);
                return(output.ToString());
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Run a PIDX Check on a Microsoft Product Key
        /// </summary>
        /// <param name="key">Microsoft Product Key</param>
        /// <param name="pkeyconfig">Byte Array of a PkeyConfig.xrm-ms</param>
        /// <returns>String Representation of a PIDX Check Report</returns>
        public static string CheckKey(string key, byte[] pkeyconfig)
        {
            try
            {
                // Create PIDGENX DLL File
                if (File.Exists(Environment.GetEnvironmentVariable("temp") + Path.DirectorySeparatorChar + PidgenxFileName) == false)
                {
                    if (!Environment.Is64BitProcess)
                    {
                        if (OSVersion.GetWindowsNumber() < 6.0)
                        {
                            CommonUtilities.FileCreate(PidgenxFileName, Resources.pidgenx32_xp, Environment.GetEnvironmentVariable("temp"));
                        }
                        else
                        {
                            CommonUtilities.FileCreate(PidgenxFileName, Resources.pidgenx32, Environment.GetEnvironmentVariable("temp"));
                        }
                    }
                    else
                    {
                        if (OSVersion.GetWindowsNumber() < 6.0)
                        {
                            CommonUtilities.FileCreate(PidgenxFileName, Resources.pidgenx64_xp, Environment.GetEnvironmentVariable("temp"));
                        }
                        else
                        {
                            CommonUtilities.FileCreate(PidgenxFileName, Resources.pidgenx64, Environment.GetEnvironmentVariable("temp"));
                        }
                    }
                }

                // Create PkeyConfig.xrm-ms File
                CommonUtilities.FileCreate(PkeyConfigFileName, pkeyconfig, Environment.GetEnvironmentVariable("temp"));

                // Set Path to Files
                string dllPath  = Environment.GetEnvironmentVariable("temp") + Path.DirectorySeparatorChar + PidgenxFileName;
                string pKeyPath = Environment.GetEnvironmentVariable("temp") + Path.DirectorySeparatorChar + PkeyConfigFileName;

                // Do PIDX Check
                IntPtr dllHandle = NativeMethods.LoadLibrary(dllPath);

                byte[] gpid = new byte[0x32];
                byte[] opid = new byte[0xA4];
                byte[] npid = new byte[0x04F8];

                IntPtr pid   = Marshal.AllocHGlobal(0x32);
                IntPtr dpid  = Marshal.AllocHGlobal(0xA4);
                IntPtr dpid4 = Marshal.AllocHGlobal(0x04F8);

                const string mspid = "XXXXX";

                gpid[0] = 0x32;
                opid[0] = 0xA4;
                npid[0] = 0xF8;
                npid[1] = 0x04;

                Marshal.Copy(gpid, 0, pid, 0x32);
                Marshal.Copy(opid, 0, dpid, 0xA4);
                Marshal.Copy(npid, 0, dpid4, 0x04F8);

                int retID = NativeMethods.PidGenX(key, pKeyPath, mspid, 0, pid, dpid, dpid4);

                using (StringWriter output = new StringWriter())
                {
                    switch (retID)
                    {
                    case 0:
                    {
                        Marshal.Copy(pid, gpid, 0, gpid.Length);
                        Marshal.Copy(dpid4, npid, 0, npid.Length);
                        string keypid = GetString(gpid, 0x0000);
                        string eid    = GetString(npid, 0x0008);
                        string aid    = GetString(npid, 0x0088);
                        string edi    = GetEditionType(pKeyPath, "{" + aid + "}");
                        string sub    = GetString(npid, 0x0378);
                        string lit    = GetString(npid, 0x03F8);
                        string lic    = GetString(npid, 0x0478);
                        string cid    = GetCryptoID(pKeyPath, "{" + aid + "}").Trim();
                        string prd    = GetProductDescription(pKeyPath, "{" + aid + "}", edi);

                        output.WriteLine("Product Key: " + key);
                        output.WriteLine("Validity: Valid");
                        output.WriteLine("Product ID: " + keypid);
                        output.WriteLine("Advanced PID: " + eid);
                        output.WriteLine("Activation ID: " + aid);
                        output.WriteLine("Product Description: " + prd);
                        output.WriteLine("Edition Type: " + edi);
                        output.WriteLine("Edition ID: " + sub);
                        output.WriteLine("Key Type: " + lit);
                        output.WriteLine("Eula: " + lic);
                        output.Write("Crypto ID: " + cid);

                        if (lit.ToUpper().Contains("MAK"))
                        {
                            try
                            {
                                string remainingUses = GetRemainingActivations(eid);
                                output.WriteLine();
                                output.Write("Remaining Activation Count: " + remainingUses);
                            }
                            catch (Exception ex)
                            {
                                output.WriteLine();
                                output.Write("Remaining Activation Count: Couldn't determine due to error: " + ex.Message);
                            }
                        }
                    }
                    break;

                    case -2147024809:
                        output.WriteLine("Invalid Arguments");
                        break;

                    case -1979645695:
                        output.WriteLine("Invalid Key");
                        break;

                    case -2147024894:
                        output.WriteLine("pkeyconfig.xrm-ms file is not found");
                        break;

                    default:
                        output.WriteLine("Invalid input!!!");
                        break;
                    }
                    Marshal.FreeHGlobal(pid);
                    Marshal.FreeHGlobal(dpid);
                    Marshal.FreeHGlobal(dpid4);

                    NativeMethods.FreeLibrary(dllHandle);

                    // Delete PkeyConfig
                    CommonUtilities.FileDelete(pKeyPath);

                    return(output.ToString().Trim());
                }
            }
            catch (Exception ex)
            {
                return("<Key Check Failed>" + Environment.NewLine + ex.Message);
            }
        }