Пример #1
0
        /// <summary>
        /// Obtain Path to OSPPC.dll for Microsoft Office
        /// </summary>
        /// <returns>Path to OSPPC.dll</returns>
        private static string GetOSPPCPath()
        {
            switch (OfficeVersion.GetOfficeNumber())
            {
            case 14:
            case 15:
            case 16:
                switch (Architecture.GetOfficeArch())
                {
                case Architecture.X86:
                {
                    return(Environment.ExpandEnvironmentVariables("%CommonProgramFiles%\\microsoft shared\\OfficeSoftwareProtectionPlatform\\osppc.dll"));
                }

                case Architecture.WOW:
                case Architecture.X64:
                {
                    return(Environment.ExpandEnvironmentVariables("%CommonProgramW6432%\\microsoft shared\\OfficeSoftwareProtectionPlatform\\osppc.dll"));
                }

                default:
                {
                    return(string.Empty);
                }
                }

            default:
                throw new ApplicationException("Unsupported Microsoft Office Edition!");
            }
        }
Пример #2
0
        private static IEnumerable <Entry> LoadIds(OfficeVersion officeVersion, OfficeApplication officeApplication)
        {
            var folder = Path.Combine(
                Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                "OfficeData",
                officeVersion.ToString());

            var files = new DirectoryInfo(folder).GetFiles("*.xlsx")
                        .Where(f => f.Name.StartsWith(officeApplication.ToString(), StringComparison.OrdinalIgnoreCase));

            foreach (var file in files)
            {
                using (var package = new ExcelPackage(file))
                {
                    var ws = package.Workbook.Worksheets.First();
                    for (var r = 2; r <= ws.Dimension.End.Row; r++)
                    {
                        yield return(new Entry
                        {
                            Completion = new Completion(ws.Cells[r, 1].GetValue <string>()),
                            ControlType = ws.Cells[r, 2].GetValue <string>(),
                            TabSet = ws.Cells[r, 3].GetValue <string>(),
                            Tab = ws.Cells[r, 4].GetValue <string>(),
                            Group = ws.Cells[r, 5].GetValue <string>(),
                            ParentControl = ws.Cells[r, 6].GetValue <string>(),
                        });
                    }
                }
            }
        }
Пример #3
0
        /// <summary>
        /// Obtain a Byte Array Representing PkeyConfig for Microsoft Office PIDX Check from Program
        /// </summary>
        /// <param name="useBuiltIn">Load PkeyConfig from Installed Microsoft Office</param>
        /// <param name="product">Name of Microsoft Office Product to Choose based on selection</param>
        /// <returns>Byte Array Representation of PkeyConfig.xrm-ms</returns>
        public static byte[] GetPkeyConfigOffice(bool useBuiltIn = false, string product = "")
        {
            // Load PkeyConfig from System
            if (useBuiltIn)
            {
                return(GetBuiltInPkeyConfigOffice());
            }
            // Choose by Product if Provided
            if (product != string.Empty)
            {
                switch (product)
                {
                case OfficeVersion.Office14:
                    return(Resources.pkeyconfig_office2010);

                case OfficeVersion.Office15:
                    return(Resources.pkeyconfig_office2013);
                }
            }

            // Get PkeyConfig based on Microsoft Office Edition
            switch (OfficeVersion.GetOfficeNumber())
            {
            case 14:
                return(Resources.pkeyconfig_office2010);

            case 15:
                return(Resources.pkeyconfig_office2013);

            default:
                throw new ApplicationException("No PkeyConfig Matching this Product!");
            }
        }
Пример #4
0
        /// <summary>
        ///      Implements the OnConnection method of the IDTExtensibility2 interface.
        ///      Receives notification that the Add-in is being loaded.
        /// </summary>
        /// <param term='application'>
        ///      Root object of the host application.
        /// </param>
        /// <param term='connectMode'>
        ///      Describes how the Add-in is being loaded.
        /// </param>
        /// <param term='addInInst'>
        ///      Object representing this Add-in.
        /// </param>
        /// <seealso class='IDTExtensibility2' />
        public virtual void OnConnection(object application, Extensibility.ext_ConnectMode connectMode, object addInInst, ref System.Array custom)
        {
            this._application = new LateBindingObject(application);

            // read Office version info
            int version;

            using (new UILanguageHelper())
            {
                int.TryParse(_application.GetString("Version"),
                             NumberStyles.Float,
                             CultureInfo.InvariantCulture,
                             out version);
                _officeVersion = (OfficeVersion)version;
            }

            Application.EnableVisualStyles();

            this.SetUICulture();

            this.DialogBoxTitle = _addinLib.GetString("OdfConverterTitle");

            LateBindingObject addInInstance = new LateBindingObject(addInInst);

            addInInstance.Set("Object", (object)this);

            if (connectMode != Extensibility.ext_ConnectMode.ext_cm_Startup)
            {
                OnStartupComplete(ref custom);
            }
        }
Пример #5
0
    internal static string ToFormattedString(this OfficeVersion version)
    {
        if (version == OfficeVersion.None)
        {
            return("None");
        }

        return((version == OfficeVersion.Microsoft365 ? string.Empty : "Office ") + version.ToString().Substring(version == OfficeVersion.Microsoft365 ? 0 : "Office".Length));
    }
Пример #6
0
 /// <summary>
 /// Attempt Phone Activation on an individual Microsoft Office License
 /// </summary>
 /// <param name="confirmationID">Activation Code obtained from Phone Activation</param>
 /// <param name="offlineInstallationID">OfflineInstallationID of the License</param>
 /// <param name="skuid">SKUID of the License</param>
 /// <returns>True if Activation was successfull, False if it failed</returns>
 private static bool PhoneActivationOffice(string confirmationID, string offlineInstallationID, string skuid)
 {
     // Call Windows if Microsoft Office uses Windows Licensing Services
     if (OfficeVersion.IsOfficeSPP())
     {
         return(PhoneActivationWindows(confirmationID, offlineInstallationID, skuid));
     }
     return(PhoneActivation(confirmationID, offlineInstallationID, "OfficeSoftwareProtectionProduct.ID=" + "'" + skuid + "'", "SELECT ID, LicenseStatus FROM OfficeSoftwareProtectionProduct", skuid));
 }
Пример #7
0
 /// <summary>
 /// Attempt Activation on each Microsoft Office 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="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 Microsoft Office Licenses</returns>
 public static string AttemptActivationOffice(LicenseList licenses, 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")
 {
     // Call Windows if Microsoft Office uses Windows Licensing Services
     if (OfficeVersion.IsOfficeSPP())
     {
         return(AttemptActivation(licenses, "SoftwareLicensingProduct.ID=", minimalOutput, kmsServer, kmsPort, kmsPid, kmsHwid, useKMSEmulator, removeKMSConnection, killProcessOnPort, useDLLInjection, useTAPAdapter, useWinDivert, localHostBypassIPAddress, localHostBypassIPSubnet));
     }
     return(AttemptActivation(licenses, "OfficeSoftwareProtectionProduct.ID=", minimalOutput, kmsServer, kmsPort, kmsPid, kmsHwid, useKMSEmulator, removeKMSConnection, killProcessOnPort, useDLLInjection, useTAPAdapter, useWinDivert, localHostBypassIPAddress, localHostBypassIPSubnet));
 }
Пример #8
0
 /// <summary>
 /// Stop the Microsoft Office Software Licensing Service
 /// </summary>
 public static void StopOSPPSVC()
 {
     switch (OfficeVersion.GetOfficeNumber())
     {
     case 14:
     case 15:
         StopService("OSPPSVC");
         DisableService("OSPPSVC");
         break;
     }
 }
Пример #9
0
 /// <summary>
 /// Start the Microsoft Office Software Licensing Service
 /// </summary>
 public static void StartOSPPSVC()
 {
     switch (OfficeVersion.GetOfficeNumber())
     {
     case 14:
     case 15:
         EnableService("OSPPSVC");
         StartService("OSPPSVC");
         break;
     }
 }
Пример #10
0
        public static IWindowContextManager Create(OfficeVersion officeVersion)
        {
            switch (officeVersion)
            {
            case OfficeVersion.v2010:
                return(new WindowContextManager2010());

            case OfficeVersion.v2013:
                return(new WindowContextManager2013());

            default:
                throw new InvalidOperationException("Not Supported Office Version");
            }
        }
Пример #11
0
        public static IEnumerable <Completion> GetMsoImagesFromCache(OfficeVersion officeVersion)
        {
            if (_msoImages == null)
            {
                _msoImages = new Dictionary <OfficeVersion, IEnumerable <Completion> >();
            }

            if (!_msoImages.ContainsKey(officeVersion))
            {
                _msoImages[officeVersion] = LoadGlyphsFromFile(officeVersion).OrderBy(e => e.DisplayText).ToList();
            }

            return(_msoImages[officeVersion]);
        }
Пример #12
0
        /// <summary>
        /// Obtain a Byte Array List Representing PkeyConfig for Microsoft Office PIDX Check from Program
        /// </summary>
        /// <param name="product">Name of Microsoft Office Product to Choose based on selection</param>
        /// <returns>Byte Array Representations of PkeyConfig.xrm-ms files</returns>
        public static List <byte[]> GetPkeyConfigOffice(string product = "")
        {
            // Choose by Product if Provided
            if (String.IsNullOrWhiteSpace(product))
            {
                // Get Microsoft Office Edition
                product = OfficeVersion.GetOfficeName();
            }

            // Choose PkeyConfigs based on Microsoft Office Edition
            switch (product)
            {
            case OfficeVersion.Office2010:
                return(new List <byte[]>
                {
                    Resources.pkeyconfig_office2010,
                    Resources.pkeyconfig_office2010csvlk,
                    Resources.pkeyconfig_office2010web
                });

            case OfficeVersion.Office2013:
                return(new List <byte[]>
                {
                    Resources.pkeyconfig_office2013,
                    Resources.pkeyconfig_office2013csvlk,
                    Resources.pkeyconfig_office2013web
                });

            case OfficeVersion.Office2016:
                return(new List <byte[]>
                {
                    Resources.pkeyconfig_office2016,
                    Resources.pkeyconfig_office2016csvlk,
                    Resources.pkeyconfig_office2016web
                });

            case OfficeVersion.Office2019:
                return(new List <byte[]>
                {
                    Resources.pkeyconfig_office2019,
                    Resources.pkeyconfig_office2019csvlk
                    //Resources.pkeyconfig_office2019web
                });

            default:
                throw new ApplicationException("No PkeyConfig Matching this Product!");
            }
        }
Пример #13
0
        public static IEnumerable <Entry> GetIdsFromCache(OfficeVersion officeVersion, OfficeApplication officeApplication)
        {
            if (_entries == null)
            {
                _entries = new Dictionary <OfficeVersion, IDictionary <OfficeApplication, IEnumerable <Entry> > >();
            }

            if (!_entries.ContainsKey(officeVersion))
            {
                _entries[officeVersion] = new Dictionary <OfficeApplication, IEnumerable <Entry> >();
            }

            var versionEntries = _entries[officeVersion];

            if (!versionEntries.ContainsKey(officeApplication))
            {
                versionEntries[officeApplication] = LoadIds(officeVersion, officeApplication).OrderBy(e => e.Completion.DisplayText).ToList();
            }

            return(versionEntries[officeApplication]);
        }
Пример #14
0
        private static IEnumerable <Completion> LoadGlyphsFromFile(OfficeVersion officeVersion)
        {
            var folder = Path.Combine(
                Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                "OfficeData",
                officeVersion.ToString());

            var files = new DirectoryInfo(folder).GetFiles("*.zip");

            foreach (var file in files)
            {
                using (var stream = File.OpenRead(file.FullName))
                    using (var zip = new ZipArchive(stream))
                    {
                        // Iterate through all of the glyphs in this dictionary
                        foreach (var glyph in zip.Entries)
                        {
                            var name = Path.GetFileNameWithoutExtension(glyph.Name);

                            using (var glyphStream = glyph.Open())
                                using (var ms = new MemoryStream())
                                {
                                    glyphStream.CopyTo(ms);

                                    // Generate the Glyph
                                    var bitmap = new BitmapImage();
                                    bitmap.BeginInit();
                                    bitmap.StreamSource = ms;
                                    bitmap.CacheOption  = BitmapCacheOption.OnLoad;
                                    bitmap.EndInit();
                                    bitmap.Freeze();

                                    // Add it to the collection (under the specific library)
                                    yield return(new Completion(name, name, name, bitmap, name));
                                }
                        }
                    }
            }
        }
Пример #15
0
        /// <summary>
        /// Obtain a Byte Array Representing PkeyConfig for Microsoft Office PIDX Check from System
        /// </summary>
        /// <returns>Byte Array Representation of PkeyConfig.xrm-ms</returns>
        private static byte[] GetBuiltInPkeyConfigOffice()
        {
            string pkeyconfig   = string.Empty;
            string officeArch   = Architecture.GetOfficeArch();
            int    officeNumber = OfficeVersion.GetOfficeNumber();

            switch (officeNumber)
            {
            case 14:
            case 15:
                switch (officeArch)
                {
                case Architecture.X86:
                {
                    pkeyconfig = Environment.ExpandEnvironmentVariables("%CommonProgramFiles%\\microsoft shared\\OFFICE" + officeNumber + "\\Office Setup Controller\\pkeyconfig-office.xrm-ms");
                    break;
                }

                case Architecture.WOW:
                {
                    pkeyconfig = Environment.ExpandEnvironmentVariables("%CommonProgramFiles(x86)%\\microsoft shared\\OFFICE" + officeNumber + "\\Office Setup Controller\\pkeyconfig-office.xrm-ms");
                    break;
                }

                case Architecture.X64:
                {
                    pkeyconfig = Environment.ExpandEnvironmentVariables("%CommonProgramW6432%\\microsoft shared\\OFFICE" + officeNumber + "\\Office Setup Controller\\pkeyconfig-office.xrm-ms");
                    break;
                }
                }
                break;

            default:
                throw new ApplicationException("Could not find Built-In PkeyConfig");
            }
            return(File.ReadAllBytes(pkeyconfig));
        }
Пример #16
0
        /// <summary>
        /// Obtain Path to OSPPREARM.exe for Microsoft Office
        /// </summary>
        /// <returns>Path to OSPPREARM.exe</returns>
        private static string GetRearmToolPath()
        {
            switch (OfficeVersion.GetOfficeNumber())
            {
            case 14:
                switch (Architecture.GetOfficeArch())
                {
                case Architecture.X86:
                {
                    return(CommonUtilities.EscapePath(Environment.ExpandEnvironmentVariables("%CommonProgramFiles%\\microsoft shared\\OfficeSoftwareProtectionPlatform\\OSPPREARM.exe")));
                }

                case Architecture.WOW:
                {
                    return(CommonUtilities.EscapePath(Environment.ExpandEnvironmentVariables("%CommonProgramFiles(x86)%\\microsoft shared\\OfficeSoftwareProtectionPlatform\\OSPPREARM.exe")));
                }

                case Architecture.X64:
                {
                    return(CommonUtilities.EscapePath(Environment.ExpandEnvironmentVariables("%CommonProgramW6432%\\microsoft shared\\OfficeSoftwareProtectionPlatform\\OSPPREARM.exe")));
                }

                default:
                {
                    return(string.Empty);
                }
                }

            case 15:
            case 16:
                return(CommonUtilities.EscapePath(OfficeVersion.GetInstallationPath() + "OSPPREARM.exe"));

            default:
                throw new ApplicationException("Unsupported Microsoft Office Edition!");
            }
        }
Пример #17
0
        /// <summary>
        /// Launch AutoKMS
        /// </summary>
        public void RunAutoKMS()
        {
            // Start Logging
            string logPath = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + AutoKMSInstaller.AutoKMSInstaller.AutoKMSLogFileName;

            // Delete Log if Greater than 10MB
            FileInfo logFile = new FileInfo(logPath);

            if (logFile.Exists && logFile.Length >= 10485760)
            {
                CommonUtilities.FileDelete(logPath);
            }

            // Access Log
            using (_log = new StreamWriter(logPath, true))
            {
                WriteLine("----------------------------------------");

                // Get the Program File Version
                FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetEntryAssembly().Location);
                WriteLine("AutoKMS " + myFileVersionInfo.FileVersion + " Ran At " + DateTime.Now + ".");

                // Check for Recent BSOD
                if (BSODTest() && Settings.Default.LocalHostBypassUseDLLInjection)
                {
                    // Log Early Termination
                    WriteLine("A recent unexpected shutdown or BSOD occured.");
                    WriteLine("AutoKMS will not continue until the next Scheduled run.");
                    WriteLine("----------------------------------------");

                    // Remake AutoKMS Tasks
                    if (AutoKMSInstaller.AutoKMSInstaller.IsAutoKMSCustomTaskInstalled() == false)
                    {
                        AutoKMSInstaller.AutoKMSInstaller.AutoKMSInstallPath = Environment.CurrentDirectory;
                        AutoKMSInstaller.AutoKMSInstaller.MakeAutoKMSNormalTask();
                    }
                    return;
                }

                // EZ-Activator Check
                bool     ezActivator = false;
                String[] arguments   = Environment.GetCommandLineArgs();
                foreach (string argument in arguments)
                {
                    if (String.Compare(argument, "/EZActivator", StringComparison.InvariantCultureIgnoreCase) == 0)
                    {
                        ezActivator = true;
                        break;
                    }
                }

                // Show Splash Screen
                Thread splashScreenThread = null;
                if (ezActivator)
                {
                    splashScreenThread = new Thread(ShowSplashScreen);
                    splashScreenThread.Start();
                }

                // Activate Microsoft Office
                if (OfficeVersion.IsOfficeSupported())
                {
                    // Only Activate KMS Licenses
                    LicenseList licenses = new LicenseListOffice();
                    if (!ezActivator)
                    {
                        licenses.List = licenses.GetListLicensed();
                        licenses.List = licenses.GetListKMS();
                    }
                    else
                    {
                        licenses.List = licenses.GetListKMS();
                    }

                    if (licenses.List.Count > 0)
                    {
                        // Handle KMS Server Service
                        if (Regex.IsMatch(Settings.Default.KMSServerOffice, @"^(127(\.\d+){1,3}|[0:]+1|localhost)$") || String.Compare(Settings.Default.KMSServerOffice, Environment.MachineName, StringComparison.InvariantCultureIgnoreCase) == 0)
                        {
                            if (KMSServerServiceInstaller.KMSServerServiceInstaller.IsKMSServerServiceInstalled())
                            {
                                Services.StartService(KMSServerServiceInstaller.KMSServerServiceInstaller.KMSServerServiceName);
                                Settings.Default.UseKMSEmulator = false;
                                WriteLine("Using KMS Server Service.");
                            }
                            else if (Settings.Default.UseKMSEmulator)
                            {
                                WriteLine("Using built-in KMS Server Emulator.");
                            }
                            else
                            {
                                WriteLine("WARNING: Attempting LocalHost KMS Activation without KMS Server Service or built-in KMS Server Emulator!");
                            }
                        }
                        else
                        {
                            WriteLine("Using KMS Server over the Network.");
                        }

                        if (!ezActivator)
                        {
                            WriteLine("Attempting To Activate Microsoft Office");
                            Write(ActivationState.AttemptActivationOffice(licenses, true, Settings.Default.KMSServerOffice, Settings.Default.KMSPortOffice, Settings.Default.KMSPIDOffice, Settings.Default.KMSHardwareID, Settings.Default.UseKMSEmulator, Settings.Default.RemoveKMSConnection, Settings.Default.KillProcessOnPort, Settings.Default.LocalHostBypassUseDLLInjection, Settings.Default.LocalHostBypassUseTAPAdapter, Settings.Default.LocalHostBypassUseWinDivertClient, Settings.Default.LocalHostBypassIPAddress, Settings.Default.LocalHostBypassIPSubnet));
                            WriteLine(string.Empty);
                        }
                        else
                        {
                            Write(EZActivator.RunEZActivator(licenses, true, Settings.Default.KMSServerOffice, Settings.Default.KMSPortOffice, Settings.Default.KMSPIDOffice, Settings.Default.KMSHardwareID, Settings.Default.UseKMSEmulator, Settings.Default.RemoveKMSConnection, Settings.Default.KillProcessOnPort, Settings.Default.LocalHostBypassUseDLLInjection, Settings.Default.LocalHostBypassUseTAPAdapter, Settings.Default.LocalHostBypassUseWinDivertClient, Settings.Default.LocalHostBypassIPAddress, Settings.Default.LocalHostBypassIPSubnet));
                            WriteLine(string.Empty);
                        }
                    }
                }
                // Activate Microsoft Windows
                if (OSVersion.IsWindowsSupported())
                {
                    // Only Activate KMS Licenses
                    LicenseList licenses = new LicenseListWindows();
                    if (!ezActivator)
                    {
                        licenses.List = licenses.GetListLicensed();
                        licenses.List = licenses.GetListKMS();
                    }
                    else
                    {
                        licenses.List = licenses.GetListKMS();
                    }

                    if (licenses.List.Count > 0)
                    {
                        // Handle KMS Server Service
                        if (Regex.IsMatch(Settings.Default.KMSServerWindows, @"^(127(\.\d+){1,3}|[0:]+1|localhost)$") || String.Compare(Settings.Default.KMSServerWindows, Environment.MachineName, StringComparison.InvariantCultureIgnoreCase) == 0)
                        {
                            if (KMSServerServiceInstaller.KMSServerServiceInstaller.IsKMSServerServiceInstalled())
                            {
                                Services.StartService(KMSServerServiceInstaller.KMSServerServiceInstaller.KMSServerServiceName);
                                Settings.Default.UseKMSEmulator = false;
                                WriteLine("Using KMS Server Service.");
                            }
                            else if (Settings.Default.UseKMSEmulator)
                            {
                                WriteLine("Using built-in KMS Server Emulator.");
                            }
                            else
                            {
                                WriteLine("WARNING: Attempting LocalHost KMS Activation without KMS Server Service or built-in KMS Server Emulator!");
                            }
                        }
                        else
                        {
                            WriteLine("Using KMS Server over the Network.");
                        }

                        if (!ezActivator)
                        {
                            WriteLine("Attempting To Activate Microsoft Windows");
                            Write(ActivationState.AttemptActivationWindows(licenses, true, Settings.Default.KMSServerWindows, Settings.Default.KMSPortWindows, Settings.Default.KMSPIDWindows, Settings.Default.KMSHardwareID, Settings.Default.UseKMSEmulator, Settings.Default.RemoveKMSConnection, Settings.Default.KillProcessOnPort, Settings.Default.LocalHostBypassUseDLLInjection, Settings.Default.LocalHostBypassUseTAPAdapter, Settings.Default.LocalHostBypassUseWinDivertClient, Settings.Default.LocalHostBypassIPAddress, Settings.Default.LocalHostBypassIPSubnet));
                            WriteLine(string.Empty);
                        }
                        else
                        {
                            Write(EZActivator.RunEZActivator(licenses, true, Settings.Default.KMSServerWindows, Settings.Default.KMSPortWindows, Settings.Default.KMSPIDWindows, Settings.Default.KMSHardwareID, Settings.Default.UseKMSEmulator, Settings.Default.RemoveKMSConnection, Settings.Default.KillProcessOnPort, Settings.Default.LocalHostBypassUseDLLInjection, Settings.Default.LocalHostBypassUseTAPAdapter, Settings.Default.LocalHostBypassUseWinDivertClient, Settings.Default.LocalHostBypassIPAddress, Settings.Default.LocalHostBypassIPSubnet));
                            WriteLine(string.Empty);
                        }
                    }
                }

                // Hide Splash Screen
                if (ezActivator)
                {
                    splashScreenThread.Abort();
                }
            }

            // Remake AutoKMS Tasks
            if (AutoKMSInstaller.AutoKMSInstaller.IsAutoKMSCustomTaskInstalled() == false)
            {
                AutoKMSInstaller.AutoKMSInstaller.AutoKMSInstallPath = Environment.CurrentDirectory;
                AutoKMSInstaller.AutoKMSInstaller.MakeAutoKMSNormalTask();
            }
        }
Пример #18
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());
            }
        }
Пример #19
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());
            }
        }
Пример #20
0
        /// <summary>
        /// Launch AutoRearm
        /// </summary>
        public void RunAutoRearm()
        {
            // Start Logging
            string logPath = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + AutoRearmInstaller.AutoRearmInstaller.AutoRearmLogFileName;

            // Delete Log if Greater than 10MB
            FileInfo logFile = new FileInfo(logPath);

            if (logFile.Exists && logFile.Length >= 10485760)
            {
                CommonUtilities.FileDelete(logPath);
            }

            // Access Log
            using (_log = new StreamWriter(logPath, true))
            {
                // Get Lowest Grace Period
                if (OfficeVersion.IsOfficeSupported())
                {
                    // Rearm if we only have 5 days left
                    LicenseList licenses = new LicenseListOffice();
                    if (RearmBase.LowestGraceDays(licenses) < 6)
                    {
                        // Get the Program File Version
                        FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetEntryAssembly().Location);
                        WriteLine("------------------------------------" + Environment.NewLine + "AutoRearm " + myFileVersionInfo.FileVersion + " Ran At " + DateTime.Now + ".");

                        // Rearm if Possible, Restore Backup if Rearm Fails
                        WriteLine("Rearming Office because grace period is almost expired.");
                        if (RearmOffice.Rearm().Contains("failed"))
                        {
                            WriteLine("Failed to Rearm. Restoring License Backup.");

                            string restoreoutput = LicenseBackup.RestoreOfficeTrustedStore("AutoRearmBackup", Environment.CurrentDirectory + "\\Backups\\" + OfficeVersion.GetOfficeName() + Path.DirectorySeparatorChar);
                            if (restoreoutput.Contains("Failed") == false)
                            {
                                WriteLine("Successfully Restored License Backup. Rearming Office.");

                                // Wait and Cycle OSPPSVC
                                Services.StopOSPPSVC();
                                Thread.Sleep(2000);
                                Services.StartOSPPSVC();
                                Thread.Sleep(2000);
                                if (RearmOffice.Rearm().Contains("failed"))
                                {
                                    WriteLine("Failed to Rearm.");
                                }
                                else
                                {
                                    WriteLine("Successfully Rearmed.");
                                }
                            }
                        }
                        else
                        {
                            WriteLine("Successfully Rearmed.");
                        }
                    }
                }
                else
                {
                    WriteLine("Office Is Not Installed!");
                }
            }
            // Remake AutoRearm Tasks
            AutoRearmInstaller.AutoRearmInstaller.AutoRearmInstallPath = Environment.CurrentDirectory;
            //AutoRearmInstaller.AutoRearmInstaller.DeleteAutoRearmNormalTask();
            AutoRearmInstaller.AutoRearmInstaller.MakeAutoRearmNormalTask();
        }
Пример #21
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());
            }
        }
Пример #22
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());
            }
        }
Пример #23
0
        /// <summary>
        /// Rearm Microsoft Office
        /// </summary>
        /// <returns>Output of Rearm Result and Any Errors</returns>
        public static string Rearm()
        {
            try
            {
                using (StringWriter output = new StringWriter())
                {
                    // Get Rearm Tool Path
                    if (String.IsNullOrWhiteSpace(_ospprearm))
                    {
                        _ospprearm = GetRearmToolPath();
                    }

                    // Rearm with SKUIDs if Microsoft Office uses Windows Licensing Services
                    if (OfficeVersion.IsOfficeSPP())
                    {
                        LicenseList licenses = new LicenseListOffice();

                        output.WriteLine("---Processing--------------------------");
                        output.Write("----------------------------------------");
                        foreach (LicenseInstance license in licenses.GetListLicensed())
                        {
                            output.WriteLine();
                            output.WriteLine("Installed license detected - attempting to rearm the following product:");
                            output.WriteLine("Name: " + license.LicenseName);
                            output.WriteLine("Description: " + license.LicenseDescription);
                            output.WriteLine("SKU ID: " + license.SKUID);
                            Result result = CommonUtilities.ExecuteCommand(_ospprearm + " {" + license.SKUID + "}", true, true);

                            if (result.HasError)
                            {
                                // Show Rearm Error
                                string errorCode = Regex.Match(result.Error, "[0][x][A-Fa-f0-9]{8}").ToString().ToUpper().Replace("X", "x");
                                output.WriteLine("ERROR CODE: " + errorCode);
                                output.WriteLine("ERROR TEXT: " + LicenseErrorCode.GetErrorDescription(errorCode));
                                output.Write("<Product rearm failed>" + Environment.NewLine + "----------------------------------------");
                            }
                            else
                            {
                                output.Write("<Product rearm successful>" + Environment.NewLine + "----------------------------------------");
                            }
                        }
                    }
                    // Rearm without SKUIDs
                    else
                    {
                        Result result = CommonUtilities.ExecuteCommand(_ospprearm, true, true);

                        if (result.HasError)
                        {
                            output.WriteLine("<Microsoft Office rearm failed.>");
                            // Show Rearm Error
                            string errorCode = Regex.Match(result.Error, "[0][x][A-Fa-f0-9]{8}").ToString().ToUpper().Replace("X", "x");
                            output.WriteLine("ERROR CODE: " + errorCode);
                            output.WriteLine("ERROR TEXT: " + LicenseErrorCode.GetErrorDescription(errorCode));
                        }
                        else
                        {
                            output.WriteLine("<Microsoft Office rearm successful.>");
                        }
                    }
                    return(output.ToString());
                }
            }
            catch (COMException ex)
            {
                return("<Microsoft Office rearm failed>" + Environment.NewLine + LicenseErrorCode.GetErrorDescription("0x" + ex.ErrorCode.ToString("X8")));
            }
        }
Пример #24
0
        /// <summary>
        /// Obtain the remaining number of Rearms for Microsoft Office
        /// </summary>
        /// <returns>Remaining Rearm Count Number</returns>
        public static int GetRearmCount()
        {
            // Rearm Count
            int rearmCount;

            // Microsoft Office Application ID
            Guid officeAppID = Guid.Empty;

            // Initialize Microsoft Office Application Specific Information
            if (OfficeVersion.GetOfficeNumber() == 14)
            {
                officeAppID = new Guid("59a52881-a989-479d-af46-f275c6370663");
            }
            else if (OfficeVersion.GetOfficeNumber() >= 15)
            {
                officeAppID = new Guid("0ff1ce15-a989-479d-af46-f275c6370663");
            }

            // Target the desired Software Licensing Service
            if (!OfficeVersion.IsOfficeSPP())
            {
                // Load Library
                IntPtr osppDllHandle = NativeMethods.LoadLibrary(GetOSPPCPath());

                // Handles
                IntPtr osppHandle = IntPtr.Zero;

                // Open Handle to Microsoft Office Software Licensing Service
                NativeMethods.OSPPOpen(ref osppHandle);

                // Get Microsoft Office Remaining Rearm Count from OSPP // TODO: Broken?
                uint   descSize   = 4;
                byte[] descBuffer = new byte[descSize];
                NativeMethods.SLDATATYPE slDataType = NativeMethods.SLDATATYPE.SL_DATA_DWORD;
                NativeMethods.OSPPGetApplicationInformation(osppHandle, ref officeAppID, "RemainingRearmCount", ref slDataType, ref descSize, ref descBuffer);
                rearmCount = descBuffer[0];

                // Close Handle to Microsoft Office Software Licensing Service
                NativeMethods.OSPPClose(osppHandle);
                NativeMethods.FreeLibrary(osppDllHandle);
            }
            else
            {
                // 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 officeAppID, "RemainingRearmCount", ref slDataType, ref descSize, ref descBuffer);
                rearmCount = descBuffer[0];

                // Close Handle to Microsoft Windows Software Licensing Service
                NativeMethods.SPPClose(sppHandle);
            }

            // Return Rearm Count
            return(rearmCount);
        }