/// <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!"); } }
/// <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!"); } }
/// <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; } }
/// <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; } }
/// <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)); }
/// <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!"); } }
/// <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()); } }
/// <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); }