initial source commit

This commit is contained in:
Gary Sharp
2013-02-01 12:35:28 +11:00
parent 543a005d31
commit 0a93429800
1103 changed files with 285609 additions and 0 deletions
@@ -0,0 +1,180 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using System.IO;
namespace Disco.ClientBootstrapper.Interop
{
public static class CertificateInterop
{
private static List<string> _tempCerts;
public static void RemoveTempCerts()
{
if (_tempCerts != null && _tempCerts.Count > 0)
{
Remove(StoreName.My, StoreLocation.LocalMachine, _tempCerts);
Remove(StoreName.CertificateAuthority, StoreLocation.LocalMachine, _tempCerts);
Remove(StoreName.Root, StoreLocation.LocalMachine, _tempCerts);
}
}
public static void AddTempCerts()
{
if (_tempCerts == null)
_tempCerts = new List<string>();
var inlineCertificateLocation = Program.InlinePath.Value;
// Root Certificates
try
{
var CertFiles = Directory.EnumerateFiles(inlineCertificateLocation, "WLAN_Cert_Root_*.*").ToList();
if (CertFiles.Count > 0)
{
foreach (var certFile in CertFiles)
{
var cert = new X509Certificate2(File.ReadAllBytes(certFile), "password");
var result = Add(StoreName.Root, StoreLocation.LocalMachine, cert);
if (result)
{
if (Path.GetFileNameWithoutExtension(certFile).ToLower().Contains("temp"))
_tempCerts.Add(cert.SerialNumber);
Program.Status.UpdateStatus(null, null, string.Format("Added Root Certificate: {0}", cert.ShortSubjectName()));
Program.SleepThread(500, false);
}
}
}
}
catch (Exception)
{
throw;
}
// Intermediate Certificates
try
{
var CertFiles = Directory.EnumerateFiles(inlineCertificateLocation, "WLAN_Cert_Intermediate_*.*").ToList();
if (CertFiles.Count > 0)
{
foreach (var certFile in CertFiles)
{
var cert = new X509Certificate2(File.ReadAllBytes(certFile), "password");
var result = Add(StoreName.CertificateAuthority, StoreLocation.LocalMachine, cert);
if (result)
{
if (Path.GetFileNameWithoutExtension(certFile).ToLower().Contains("temp"))
_tempCerts.Add(cert.SerialNumber);
Program.Status.UpdateStatus(null, null, string.Format("Added Intermediate Certificate: {0}", cert.ShortSubjectName()));
Program.SleepThread(500, false);
}
}
}
}
catch (Exception)
{
throw;
}
// Host/Personal Certificates
try
{
var CertFiles = Directory.EnumerateFiles(inlineCertificateLocation, "WLAN_Cert_Personal_*.*").ToList();
if (CertFiles.Count > 0)
{
foreach (var certFile in CertFiles)
{
var cert = new X509Certificate2(File.ReadAllBytes(certFile), "password", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
var result = Add(StoreName.My, StoreLocation.LocalMachine, cert);
if (result)
{
if (Path.GetFileNameWithoutExtension(certFile).ToLower().Contains("temp"))
_tempCerts.Add(cert.SerialNumber);
Program.Status.UpdateStatus(null, null, string.Format("Added Host Certificate: {0}", cert.ShortSubjectName()));
Program.SleepThread(500, false);
}
}
}
}
catch (Exception)
{
throw;
}
}
public static string ShortSubjectName(this X509Certificate2 Certificate)
{
string s = Certificate.Subject;
return s.Substring(s.IndexOf("=") + 1, s.IndexOf(",") - s.IndexOf("=") - 1);
}
public static bool Add(StoreName StoreName, StoreLocation StoreLocation, X509Certificate2 Certificate)
{
var certStore = new X509Store(StoreName, StoreLocation);
bool certAlreadyExists = false;
certStore.Open(OpenFlags.ReadWrite);
foreach (var cert in certStore.Certificates)
{
if (cert.SerialNumber.Equals(Certificate.SerialNumber))
{
certAlreadyExists = true;
break;
}
}
if (!certAlreadyExists)
{
certStore.Add(Certificate);
}
certStore.Close();
return !certAlreadyExists;
}
public static bool Remove(StoreName StoreName, StoreLocation StoreLocation, List<Regex> RegexMatches, string SerialException)
{
var certStore = new X509Store(StoreName, StoreLocation);
var removeCerts = new List<X509Certificate2>();
certStore.Open(OpenFlags.ReadWrite);
foreach (var cert in certStore.Certificates)
{
if (!cert.SerialNumber.Equals(SerialException))
{
foreach (var subjectRegex in RegexMatches)
{
if (subjectRegex.IsMatch(cert.Subject))
{
removeCerts.Add(cert);
break;
}
}
}
}
foreach (var cert in removeCerts)
{
certStore.Remove(cert);
}
certStore.Close();
return (removeCerts.Count > 0);
}
public static bool Remove(StoreName StoreName, StoreLocation StoreLocation, List<string> CertificateSerials)
{
var certStore = new X509Store(StoreName, StoreLocation);
var removeCerts = new List<X509Certificate2>();
certStore.Open(OpenFlags.ReadWrite);
foreach (var cert in certStore.Certificates)
{
if (CertificateSerials.Contains(cert.SerialNumber))
{
removeCerts.Add(cert);
}
}
foreach (var cert in removeCerts)
{
certStore.Remove(cert);
}
certStore.Close();
return (removeCerts.Count > 0);
}
}
}
@@ -0,0 +1,525 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.IO;
using System.Threading;
namespace Disco.ClientBootstrapper.Interop
{
public static class InstallInterop
{
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName, MoveFileFlags dwFlags);
[Flags]
enum MoveFileFlags
{
MOVEFILE_REPLACE_EXISTING = 0x00000001,
MOVEFILE_COPY_ALLOWED = 0x00000002,
MOVEFILE_DELAY_UNTIL_REBOOT = 0x00000004,
MOVEFILE_WRITE_THROUGH = 0x00000008,
MOVEFILE_CREATE_HARDLINK = 0x00000010,
MOVEFILE_FAIL_IF_NOT_TRACKABLE = 0x00000020
}
private static void Install(string RootFilesystemLocation, RegistryKey RootRegistryLocation, string FilesystemInstallLocation, string VirtualRootFilesystemLocation)
{
var SourceLocation = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
var InstallLocation = Path.Combine(RootFilesystemLocation, FilesystemInstallLocation);
var BootstrapperCmdLinePath = Path.Combine(VirtualRootFilesystemLocation, FilesystemInstallLocation, "Disco.ClientBootstrapper.exe");
var GroupPolicyScriptsIniLocation = Path.Combine(RootFilesystemLocation, "Windows\\System32\\GroupPolicy\\Machine\\Scripts\\scripts.ini");
var GroupPolicyScriptsIniBackupLocation = Path.Combine(RootFilesystemLocation, "Windows\\System32\\GroupPolicy\\Machine\\Scripts\\disco_scripts.ini");
// Create file system Location
#region "Create File System Location"
Program.Status.UpdateStatus(null, null, "Creating Installation Location");
Program.SleepThread(500, false);
if (Directory.Exists(InstallLocation))
{
// Try and Delete Directory
try
{
Directory.Delete(InstallLocation, true);
}
catch (Exception ex)
{
throw new IOException(string.Format("Unable to delete folder: ", InstallLocation), ex);
}
}
if (!Directory.Exists(InstallLocation))
{
var installDir = Directory.CreateDirectory(InstallLocation);
installDir.Attributes = installDir.Attributes | FileAttributes.Hidden;
}
#endregion
// Copy files to file system location
#region "Copy to File System"
Program.Status.UpdateStatus(null, null, "Copying Files");
Program.SleepThread(500, false);
// Copy Bootstrapper
// ie: Executing Assembly
File.Copy(System.Reflection.Assembly.GetExecutingAssembly().Location, Path.Combine(InstallLocation, "Disco.ClientBootstrapper.exe"));
foreach (var file in Directory.EnumerateFiles(SourceLocation))
{
var fileName = Path.GetFileName(file);
// Only Copy Certain Files
// Copy Wireless Certificates
if (fileName.StartsWith("WLAN_Cert_Root_", StringComparison.InvariantCultureIgnoreCase) ||
fileName.StartsWith("WLAN_Cert_Intermediate_", StringComparison.InvariantCultureIgnoreCase) ||
fileName.StartsWith("WLAN_Cert_Personal_", StringComparison.InvariantCultureIgnoreCase))
File.Copy(file, Path.Combine(InstallLocation, fileName));
// Copy Wireless Profiles
if (fileName.StartsWith("WLAN_Profile_", StringComparison.InvariantCultureIgnoreCase) &&
fileName.EndsWith(".xml", StringComparison.InvariantCultureIgnoreCase))
File.Copy(file, Path.Combine(InstallLocation, fileName));
}
#endregion
// Backup & Create Group Policy Scripts.ini
#region "Group Policy Scripts.ini"
Program.Status.UpdateStatus(null, null, "Creating Group Policy Script Entry");
Program.SleepThread(500, false);
// Backup
if (!File.Exists(GroupPolicyScriptsIniBackupLocation))
{
if (File.Exists(GroupPolicyScriptsIniLocation))
{
File.Move(GroupPolicyScriptsIniLocation, GroupPolicyScriptsIniBackupLocation);
}
}
// Create
if (File.Exists(GroupPolicyScriptsIniLocation))
File.Delete(GroupPolicyScriptsIniLocation);
if (!Directory.Exists(Path.GetDirectoryName(GroupPolicyScriptsIniLocation)))
Directory.CreateDirectory(Path.GetDirectoryName(GroupPolicyScriptsIniLocation));
using (var scriptsIniStream = File.Open(GroupPolicyScriptsIniLocation, FileMode.Create, FileAccess.Write))
{
using (var scriptsIniStreamWriter = new StreamWriter(scriptsIniStream, Encoding.Unicode))
{
scriptsIniStreamWriter.Write(string.Format("[Startup]{0}0CmdLine={1}{0}0Parameters=/AllowUninstall", Environment.NewLine, BootstrapperCmdLinePath));
scriptsIniStreamWriter.Flush();
}
}
#endregion
// Backup & Create Group Policy Registry
#region "Group Policy Registry"
Program.Status.UpdateStatus(null, null, "Creating Group Policy Registry Entries");
Program.SleepThread(500, false);
// Backup Scripts
using (var regGroupPolicy = RootRegistryLocation.OpenSubKey("Microsoft\\Windows\\CurrentVersion\\Group Policy", true))
{
if (regGroupPolicy != null && regGroupPolicy.GetSubKeyNames().Contains("Scripts") && !regGroupPolicy.GetSubKeyNames().Contains("Disco_Scripts"))
{
RegistryUtilities.RenameSubKey(regGroupPolicy, "Scripts", "Disco_Scripts");
}
}
// Create Scripts
RootRegistryLocation.CreateSubKey("Microsoft\\Windows\\CurrentVersion\\Group Policy\\Scripts\\Shutdown").Dispose();
using (var regScriptsStartup = RootRegistryLocation.CreateSubKey("Microsoft\\Windows\\CurrentVersion\\Group Policy\\Scripts\\Startup\\0"))
{
regScriptsStartup.SetValue("GPO-ID", "LocalGPO", RegistryValueKind.String);
regScriptsStartup.SetValue("SOM-ID", "Local", RegistryValueKind.String);
regScriptsStartup.SetValue("FileSysPath", Path.Combine(Environment.SystemDirectory, "GroupPolicy\\Machine"), RegistryValueKind.String);
regScriptsStartup.SetValue("DisplayName", "Local Group Policy", RegistryValueKind.String);
regScriptsStartup.SetValue("GPOName", "Local Group Policy", RegistryValueKind.String);
regScriptsStartup.SetValue("PSScriptOrder", 1, RegistryValueKind.DWord);
using (var regScriptsStartup0 = regScriptsStartup.CreateSubKey("0"))
{
regScriptsStartup0.SetValue("Script", BootstrapperCmdLinePath, RegistryValueKind.String);
regScriptsStartup0.SetValue("Parameters", "/AllowUninstall", RegistryValueKind.String);
regScriptsStartup0.SetValue("IsPowershell", 0, RegistryValueKind.DWord);
regScriptsStartup0.SetValue("ExecTime", new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, RegistryValueKind.Binary);
}
}
RootRegistryLocation.CreateSubKey("Microsoft\\Windows\\CurrentVersion\\Group Policy\\State\\Machine\\Scripts\\Shutdown").Dispose();
// Backup Scripts State
using (var regGroupPolicy = RootRegistryLocation.OpenSubKey("Microsoft\\Windows\\CurrentVersion\\Group Policy\\State\\Machine", true))
{
if (regGroupPolicy != null && regGroupPolicy.GetSubKeyNames().Contains("Scripts") && !regGroupPolicy.GetSubKeyNames().Contains("Disco_Scripts"))
{
RegistryUtilities.RenameSubKey(regGroupPolicy, "Scripts", "Disco_Scripts");
}
}
// Create Scripts State
using (var regStateScriptsStartup = RootRegistryLocation.CreateSubKey("Microsoft\\Windows\\CurrentVersion\\Group Policy\\State\\Machine\\Scripts\\Startup\\0"))
{
regStateScriptsStartup.SetValue("GPO-ID", "LocalGPO", RegistryValueKind.String);
regStateScriptsStartup.SetValue("SOM-ID", "Local", RegistryValueKind.String);
regStateScriptsStartup.SetValue("FileSysPath", Path.Combine(Environment.SystemDirectory, "GroupPolicy\\Machine"), RegistryValueKind.String);
regStateScriptsStartup.SetValue("DisplayName", "Local Group Policy", RegistryValueKind.String);
regStateScriptsStartup.SetValue("GPOName", "Local Group Policy", RegistryValueKind.String);
regStateScriptsStartup.SetValue("PSScriptOrder", 1, RegistryValueKind.DWord);
using (var regStateScriptsStartup0 = regStateScriptsStartup.CreateSubKey("0"))
{
regStateScriptsStartup0.SetValue("Script", BootstrapperCmdLinePath, RegistryValueKind.String);
regStateScriptsStartup0.SetValue("Parameters", "/AllowUninstall", RegistryValueKind.String);
regStateScriptsStartup0.SetValue("ExecTime", new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, RegistryValueKind.Binary);
}
}
#endregion
// Set Registry Startup Environment Policies
#region "Registry Startup Policies"
Program.Status.UpdateStatus(null, null, "Creating Startup Policy Registry Entries");
Program.SleepThread(500, false);
using (var regWinlogon = RootRegistryLocation.OpenSubKey("Microsoft\\Windows NT\\CurrentVersion\\Winlogon", true))
{
regWinlogon.SetValue("HideStartupScripts", 0, RegistryValueKind.DWord);
regWinlogon.SetValue("RunStartupScriptSync", 1, RegistryValueKind.DWord);
}
#endregion
}
public static void Install(string InstallLocation, string WimImageId = null)
{
Program.Status.UpdateStatus("Installing Bootstrapper", "Starting", "Please wait...", false);
if (string.IsNullOrWhiteSpace(InstallLocation))
InstallLocation = Path.Combine(Path.GetPathRoot(Environment.SystemDirectory), "Disco");
if (InstallLocation.EndsWith(".wim", StringComparison.InvariantCultureIgnoreCase))
{
// Offline File System (WIM)
Program.Status.UpdateStatus("Installing Bootstrapper (Offline)", "Installing", string.Format("Install Location: {0}", InstallLocation));
Program.SleepThread(1000, false);
// Mount WIM
int wimImageIndex = 0;
using (var wim = new Interop.WIMInterop.WindowsImageContainer(InstallLocation, WIMInterop.WindowsImageContainer.CreateFileMode.OpenExisting, WIMInterop.WindowsImageContainer.CreateFileAccess.Write))
{
if (WimImageId == null)
WimImageId = "1";
if (!int.TryParse(WimImageId, out wimImageIndex))
{
Program.Status.UpdateStatus(null, "Analysing WIM", string.Format("Looking for Image Name: {0}", WimImageId));
Program.SleepThread(500, false);
for (int i = 0; i < wim.ImageCount; i++)
{
var wimImageInfo = new System.Xml.XmlDocument();
using (var wimImage = wim[i])
wimImageInfo.LoadXml(wimImage.ImageInformation);
var wimImageInfoName = wimImageInfo.SelectSingleNode("//IMAGE/NAME");
if (wimImageInfoName != null && wimImageInfoName.InnerText.Equals(WimImageId, StringComparison.InvariantCultureIgnoreCase))
{
wimImageIndex = i + 1;
Program.Status.UpdateStatus(null, "Analysing WIM", string.Format("Found Image Id '{0}' at Index {1}", WimImageId, wimImageIndex));
Program.SleepThread(500, false);
break;
}
}
}
}
if (wimImageIndex == 0)
{
Program.Status.UpdateStatus(null, "Error", string.Format("Unable to load WIM Image Id: {0}", WimImageId));
Program.SleepThread(5000, false);
return;
}
// Get Temp Path
var wimMountPath = Path.Combine(Path.GetTempPath(), "DiscoClientBootstrapperWimMount");
if (Directory.Exists(wimMountPath))
Directory.Delete(wimMountPath, true);
Directory.CreateDirectory(wimMountPath);
var wimTempMountPath = Path.Combine(Path.GetTempPath(), "DiscoClientBootstrapperWimTempMount");
if (Directory.Exists(wimTempMountPath))
Directory.Delete(wimTempMountPath, true);
Directory.CreateDirectory(wimTempMountPath);
bool wimCommitChanges = true;
Interop.WIMInterop.WindowsImageContainer.NativeMethods.MessageCallback m_MessageCallback = null;
try
{
// Mount WIM
Program.Status.UpdateStatus(null, "Mounting WIM", string.Format("Mounting WIM Image to '{0}'", wimMountPath));
Program.SleepThread(500, false);
m_MessageCallback = new Interop.WIMInterop.WindowsImageContainer.NativeMethods.MessageCallback(WimImageEventMessagePump);
Interop.WIMInterop.WindowsImageContainer.NativeMethods.RegisterCallback(m_MessageCallback);
Interop.WIMInterop.WindowsImageContainer.NativeMethods.MountImage(wimMountPath, InstallLocation, wimImageIndex, wimTempMountPath);
// Load Local Machine Registry
var wimHivePath = Path.Combine(wimMountPath, "Windows\\System32\\config\\SOFTWARE");
Program.Status.UpdateStatus(null, "Mounting Offline Registry Hive", string.Format("Mounting Offline Registry Hive at '{0}'", wimHivePath));
Program.SleepThread(500, false);
using (var wimReg = new Interop.RegistryInterop(RegistryInterop.RegistryHives.HKEY_LOCAL_MACHINE, "DiscoClientBootstrapperWimHive", wimHivePath))
{
using (RegistryKey rootRegistryLocation = Registry.LocalMachine.OpenSubKey("DiscoClientBootstrapperWimHive", true))
{
string rootFileSystemLocation = wimMountPath;
string fileSystemInstallLocation = "Disco";
string virtualRootFileSystemLocation = "C:\\";
Install(rootFileSystemLocation, rootRegistryLocation, fileSystemInstallLocation, virtualRootFileSystemLocation);
}
// Unload Local Machine Registry
Program.Status.UpdateStatus(null, "Unmounting Offline Registry Hive", string.Format("Unmounting Offline Registry Hive at '{0}'", wimHivePath));
Program.SleepThread(500, false);
wimReg.Unload();
}
}
catch (Exception)
{
wimCommitChanges = false;
throw;
}
finally
{
// Unmount WIM
Program.Status.UpdateStatus(null, "Unmounting WIM", string.Format("Unmounting WIM Image at '{0}'", wimMountPath));
Program.SleepThread(500, false);
Interop.WIMInterop.WindowsImageContainer.NativeMethods.DismountImage(wimMountPath, InstallLocation, wimImageIndex, wimCommitChanges);
if (m_MessageCallback != null)
{
Interop.WIMInterop.WindowsImageContainer.NativeMethods.UnregisterMessageCallback(m_MessageCallback);
m_MessageCallback = null;
}
if (Directory.Exists(wimMountPath))
Directory.Delete(wimMountPath, true);
if (Directory.Exists(wimTempMountPath))
Directory.Delete(wimTempMountPath, true);
}
}
else
{
// Online File System
Program.Status.UpdateStatus("Installing Bootstrapper (Online)", "Installing", string.Format("Install Location: {0}", InstallLocation), true, -1);
Program.SleepThread(1000, false);
string rootFileSystemLocation = Path.GetPathRoot(InstallLocation);
RegistryKey rootRegistryLocation = Registry.LocalMachine.OpenSubKey("SOFTWARE", true);
string fileSystemInstallLocation = InstallLocation.Substring(rootFileSystemLocation.Length);
Install(rootFileSystemLocation, rootRegistryLocation, fileSystemInstallLocation, rootFileSystemLocation);
Program.Status.UpdateStatus(null, "Online File System Installation Complete", string.Empty, true, -1);
Program.SleepThread(1000, false);
}
Program.Status.UpdateStatus(null, "Complete", "Finished Installing Bootstrapper");
Program.SleepThread(1500, false);
}
private static uint WimImageEventMessagePump(
uint MessageId,
IntPtr wParam,
IntPtr lParam,
IntPtr UserData
)
{
uint status = (uint)Interop.WIMInterop.WindowsImageContainer.NativeMethods.WIMMessage.WIM_MSG_SUCCESS;
Interop.WIMInterop.DefaultImageEventArgs eventArgs = new Interop.WIMInterop.DefaultImageEventArgs(wParam, lParam, UserData);
//System.Diagnostics.Debug.WriteLine(MessageId);
switch ((Interop.WIMInterop.WindowsImageContainer.ImageEventMessage)MessageId)
{
case Interop.WIMInterop.WindowsImageContainer.ImageEventMessage.Progress:
case Interop.WIMInterop.WindowsImageContainer.ImageEventMessage.MountCleanupProgress:
var timeRemainingMil = eventArgs.LeftParameter.ToInt32();
string timeRemainingMessage;
if (timeRemainingMil > 0)
timeRemainingMessage = TimeSpan.FromMilliseconds(timeRemainingMil).ToString(@"hh\:mm\:ss");
else
timeRemainingMessage = "Calculating, please wait...";
var progress = eventArgs.WideParameter.ToInt32();
Program.Status.UpdateStatus(null, null, string.Format("Time remaining: {0}", timeRemainingMessage), true, progress);
break;
default:
break;
}
return status;
}
public static void Uninstall()
{
// Application Directory
var appDirectory = Program.InlinePath.Value;
if (Program.AllowUninstall && !appDirectory.StartsWith("\\\\"))
{
Program.Status.UpdateStatus("System Preparation (Bootstrapper)", "Uninstalling Bootstrapper...", string.Empty, false, 0);
Program.SleepThread(1000, true);
//var uninstallScriptLocation = System.IO.Path.Combine(appDirectory, "UninstallBootstrapper.vbs");
//if (System.IO.File.Exists(uninstallScriptLocation))
//{
// var bootstrapperPID = System.Diagnostics.Process.GetCurrentProcess().Id;
// var cscriptPath = System.IO.Path.Combine(Environment.SystemDirectory, "cscript.exe");
// var cscriptArgs = string.Format("\"{0}\" /WaitForProcessID:{1}", uninstallScriptLocation, bootstrapperPID);
// var startProc = new ProcessStartInfo(cscriptPath, cscriptArgs);
// startProc.WorkingDirectory = Environment.SystemDirectory;
// startProc.WindowStyle = ProcessWindowStyle.Hidden;
// Process.Start(startProc);
//}
// Remove Registry Entries
using (var regWinlogon = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", true))
{
regWinlogon.DeleteValue("HideStartupScripts", false);
regWinlogon.DeleteValue("RunStartupScriptSync", false);
}
Registry.LocalMachine.DeleteSubKeyTree("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Group Policy\\Scripts\\Shutdown", false);
Registry.LocalMachine.DeleteSubKeyTree("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Group Policy\\Scripts\\Startup", false);
Registry.LocalMachine.DeleteSubKeyTree("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Group Policy\\State\\Machine\\Scripts\\Shutdown", false);
Registry.LocalMachine.DeleteSubKeyTree("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Group Policy\\State\\Machine\\Scripts\\Startup", false);
// Restore Registry Backups
using (var regGroupPolicy = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Group Policy", true))
{
if (regGroupPolicy != null && regGroupPolicy.GetSubKeyNames().Contains("Disco_Scripts"))
{
regGroupPolicy.DeleteSubKeyTree("Scripts");
RegistryUtilities.RenameSubKey(regGroupPolicy, "Disco_Scripts", "Scripts");
}
}
using (var regGroupPolicy = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Group Policy\\State\\Machine", true))
{
if (regGroupPolicy != null && regGroupPolicy.GetSubKeyNames().Contains("Disco_Scripts"))
{
regGroupPolicy.DeleteSubKeyTree("Scripts");
RegistryUtilities.RenameSubKey(regGroupPolicy, "Disco_Scripts", "Scripts");
}
}
// Delete Group Policy Script File
var groupPolicyScriptsPath = Path.Combine(Environment.SystemDirectory, "GroupPolicy\\Machine\\Scripts\\scripts.ini");
if (File.Exists(groupPolicyScriptsPath))
File.Delete(groupPolicyScriptsPath);
var groupPolicyScriptsBackupPath = Path.Combine(Environment.SystemDirectory, "GroupPolicy\\Machine\\Scripts\\disco_scripts.ini");
if (File.Exists(groupPolicyScriptsBackupPath))
File.Move(groupPolicyScriptsBackupPath, groupPolicyScriptsPath);
// Queue Folder for Deletion at next startup
ForceDeleteFolder(new DirectoryInfo(appDirectory));
}
}
private static void ForceDeleteFolder(DirectoryInfo d)
{
foreach (var sd in d.GetDirectories())
ForceDeleteFolder(sd);
foreach (var f in d.GetFiles())
{
try
{
File.Delete(f.FullName);
}
catch (Exception)
{
MoveFileEx(f.FullName, null, MoveFileFlags.MOVEFILE_DELAY_UNTIL_REBOOT);
}
}
try
{
Directory.Delete(d.FullName);
}
catch (Exception)
{
MoveFileEx(d.FullName, null, MoveFileFlags.MOVEFILE_DELAY_UNTIL_REBOOT);
}
}
}
public static class RegistryUtilities
{
/// <summary>
/// Renames a subkey of the passed in registry key since
/// the Framework totally forgot to include such a handy feature.
/// </summary>
/// <param name="regKey">The RegistryKey that contains the subkey
/// you want to rename (must be writeable)</param>
/// <param name="subKeyName">The name of the subkey that you want to rename
/// </param>
/// <param name="newSubKeyName">The new name of the RegistryKey</param>
/// <returns>True if succeeds</returns>
public static bool RenameSubKey(RegistryKey parentKey,
string subKeyName, string newSubKeyName)
{
CopyKey(parentKey, subKeyName, newSubKeyName);
parentKey.DeleteSubKeyTree(subKeyName);
return true;
}
/// <summary>
/// Copy a registry key. The parentKey must be writeable.
/// </summary>
/// <param name="parentKey"></param>
/// <param name="keyNameToCopy"></param>
/// <param name="newKeyName"></param>
/// <returns></returns>
public static bool CopyKey(RegistryKey parentKey,
string keyNameToCopy, string newKeyName)
{
//Create new key
using (RegistryKey destinationKey = parentKey.CreateSubKey(newKeyName))
{
//Open the sourceKey we are copying from
using (RegistryKey sourceKey = parentKey.OpenSubKey(keyNameToCopy))
{
RecurseCopyKey(sourceKey, destinationKey);
}
}
return true;
}
private static void RecurseCopyKey(RegistryKey sourceKey, RegistryKey destinationKey)
{
//copy all the values
foreach (string valueName in sourceKey.GetValueNames())
{
object objValue = sourceKey.GetValue(valueName);
RegistryValueKind valKind = sourceKey.GetValueKind(valueName);
if (valueName == "ExecTime")
{
destinationKey.SetValue(valueName, objValue, RegistryValueKind.Binary);
}
else
{
destinationKey.SetValue(valueName, objValue, valKind);
}
}
//For Each subKey
//Create a new subKey in destinationKey
//Call myself
foreach (string sourceSubKeyName in sourceKey.GetSubKeyNames())
{
using (RegistryKey sourceSubKey = sourceKey.OpenSubKey(sourceSubKeyName))
{
using (RegistryKey destSubKey = destinationKey.CreateSubKey(sourceSubKeyName))
{
RecurseCopyKey(sourceSubKey, destSubKey);
}
}
}
}
}
}
@@ -0,0 +1,164 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
using System.Runtime.InteropServices;
namespace Disco.ClientBootstrapper.Interop
{
class NetworkAdapter
{
public uint Index { get; set; }
public string WmiPath { get; set; }
public Guid Guid { get; set; }
public string Name { get; set; }
public string NetConnectionID { get; set; }
public string MACAddress { get; set; }
public UInt64 Speed { get; set; }
public UInt16 LastConnectionStatus { get; set; }
public bool IsWireless { get; set; }
public string WirelessInterfaceDescription { get; set; }
public int LastWirelessConnectionStatus { get; set; }
public NetworkAdapter(ManagementObject wmiObject)
{
UpdateFromWmi(wmiObject);
}
private void UpdateFromWmi(ManagementObject wmiObject)
{
this.WmiPath = (string)wmiObject.GetPropertyValue("__PATH");
this.Index = (UInt32)wmiObject.GetPropertyValue("Index");
this.Guid = Guid.Parse((string)wmiObject.GetPropertyValue("GUID"));
this.MACAddress = (string)wmiObject.GetPropertyValue("MACAddress");
this.Name = (string)wmiObject.GetPropertyValue("Name");
this.NetConnectionID = (string)wmiObject.GetPropertyValue("NetConnectionID");
this.Speed = (UInt64)wmiObject.GetPropertyValue("Speed");
var connectionStatus = ConnectionStatus;
this.IsWireless = true;
try
{
var wirelessConnectionStatus = WirelessConnectionStatus;
}
catch (Exception) {
this.IsWireless = false;
};
}
public int WirelessConnectionStatus
{
get {
if (this.IsWireless)
{
IntPtr handle = IntPtr.Zero;
uint negotiatedVersion;
try
{
if (NetworkInterop.WlanOpenHandle(1, IntPtr.Zero, out negotiatedVersion, ref handle) != 0)
throw new NotSupportedException("This network adapter does not support Wireless");
IntPtr ptr = new IntPtr();
uint dataSize;
var interfaceGuid = this.Guid;
if (NetworkInterop.WlanQueryInterface(handle, ref interfaceGuid, NetworkInterop.WLAN_INTF_OPCODE.wlan_intf_opcode_interface_state, IntPtr.Zero, out dataSize, ref ptr, IntPtr.Zero) != 0)
throw new NotSupportedException("This network adapter does not support Wireless");
this.LastWirelessConnectionStatus = Marshal.ReadInt32(ptr);
NetworkInterop.WlanFreeMemory(ptr);
return this.LastWirelessConnectionStatus;
}
finally
{
if (handle != IntPtr.Zero)
NetworkInterop.WlanCloseHandle(handle, IntPtr.Zero);
}
}
else
{
throw new NotSupportedException("This network adapter does not support Wireless");
}
}
}
public string WirelessConnectionStatusMeaning(int status)
{
switch ((NetworkInterop.WLAN_INTERFACE_STATE)status)
{
case NetworkInterop.WLAN_INTERFACE_STATE.wlan_interface_state_ad_hoc_network_formed:
return "Ad Hoc Network Formed";
case NetworkInterop.WLAN_INTERFACE_STATE.wlan_interface_state_associating:
return "Associating";
case NetworkInterop.WLAN_INTERFACE_STATE.wlan_interface_state_authenticating:
return "Authenticating";
case NetworkInterop.WLAN_INTERFACE_STATE.wlan_interface_state_connected:
return "Connected";
case NetworkInterop.WLAN_INTERFACE_STATE.wlan_interface_state_disconnected:
return "Disconnected";
case NetworkInterop.WLAN_INTERFACE_STATE.wlan_interface_state_disconnecting:
return "Disconnecting";
case NetworkInterop.WLAN_INTERFACE_STATE.wlan_interface_state_discovering:
return "Discovering";
case NetworkInterop.WLAN_INTERFACE_STATE.wlan_interface_state_not_ready:
return "Not Ready";
default:
return "Unknown";
}
}
public UInt16 ConnectionStatus
{
get
{
using (var wmiObject = new ManagementObject(this.WmiPath))
{
this.LastConnectionStatus = (UInt16)wmiObject.GetPropertyValue("NetConnectionStatus");
}
return this.LastConnectionStatus;
}
}
public string ConnectionStatusMeaning(UInt16 status)
{
switch (status)
{
case (UInt16)0:
return "Disconnected";
case (UInt16)1:
return "Connecting";
case (UInt16)2:
return "Connected";
case (UInt16)3:
return "Disconnecting";
case (UInt16)4:
return "Hardware not present";
case (UInt16)5:
return "Hardware disabled";
case (UInt16)6:
return "Hardware malfunction";
case (UInt16)7:
return "Media disconnected";
case (UInt16)8:
return "Authenticating";
case (UInt16)9:
return "Authentication succeeded";
case (UInt16)10:
return "Authentication failed";
case (UInt16)11:
return "Invalid address";
case (UInt16)12:
return "Credentials required";
default:
return "Unknown";
}
}
}
}
@@ -0,0 +1,289 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.NetworkInformation;
using System.Management;
using System.Runtime.InteropServices;
using System.Xml;
namespace Disco.ClientBootstrapper.Interop
{
static class NetworkInterop
{
#region PInvoke
[DllImport("Wlanapi", EntryPoint = "WlanOpenHandle")]
public static extern uint WlanOpenHandle(uint dwClientVersion, IntPtr pReserved, [Out] out uint pdwNegotiatedVersion, ref IntPtr ClientHandle);
[DllImport("Wlanapi", EntryPoint = "WlanCloseHandle")]
public static extern uint WlanCloseHandle([In] IntPtr hClientHandle, IntPtr pReserved);
[DllImport("Wlanapi", EntryPoint = "WlanFreeMemory")]
public static extern void WlanFreeMemory([In] IntPtr pMemory);
[DllImport("Wlanapi.dll", SetLastError = true)]
public static extern uint WlanGetProfileList(IntPtr hClientHandle, ref Guid pInterfaceGuid, IntPtr pReserved, ref IntPtr ppProfileList);
[DllImport("Wlanapi.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern uint WlanSetProfile(IntPtr hClientHandle, [In] ref Guid pInterfaceGuid, uint dwFlags, string strProfileXml, string strAllUserProfileSecurity, bool bOverwrite, IntPtr pReserved, out uint pdwReasonCode);
[DllImport("Wlanapi", EntryPoint = "WlanQueryInterface")]
public static extern uint WlanQueryInterface([In] IntPtr hClientHandle,
[In] ref Guid pInterfaceGuid,
WLAN_INTF_OPCODE OpCode,
IntPtr pReserved,
[Out] out uint pdwDataSize,
ref IntPtr ppData,
IntPtr pWlanOpcodeValueType);
public enum WLAN_INTF_OPCODE
{
/// wlan_intf_opcode_autoconf_start -> 0x000000000
wlan_intf_opcode_autoconf_start = 0,
wlan_intf_opcode_autoconf_enabled,
wlan_intf_opcode_background_scan_enabled,
wlan_intf_opcode_media_streaming_mode,
wlan_intf_opcode_radio_state,
wlan_intf_opcode_bss_type,
wlan_intf_opcode_interface_state,
wlan_intf_opcode_current_connection,
wlan_intf_opcode_channel_number,
wlan_intf_opcode_supported_infrastructure_auth_cipher_pairs,
wlan_intf_opcode_supported_adhoc_auth_cipher_pairs,
wlan_intf_opcode_supported_country_or_region_string_list,
wlan_intf_opcode_current_operation_mode,
wlan_intf_opcode_supported_safe_mode,
wlan_intf_opcode_certified_safe_mode,
/// wlan_intf_opcode_autoconf_end -> 0x0fffffff
wlan_intf_opcode_autoconf_end = 268435455,
/// wlan_intf_opcode_msm_start -> 0x10000100
wlan_intf_opcode_msm_start = 268435712,
wlan_intf_opcode_statistics,
wlan_intf_opcode_rssi,
/// wlan_intf_opcode_msm_end -> 0x1fffffff
wlan_intf_opcode_msm_end = 536870911,
/// wlan_intf_opcode_security_start -> 0x20010000
wlan_intf_opcode_security_start = 536936448,
/// wlan_intf_opcode_security_end -> 0x2fffffff
wlan_intf_opcode_security_end = 805306367,
/// wlan_intf_opcode_ihv_start -> 0x30000000
wlan_intf_opcode_ihv_start = 805306368,
/// wlan_intf_opcode_ihv_end -> 0x3fffffff
wlan_intf_opcode_ihv_end = 1073741823,
}
/// <summary>
/// Defines the state of the interface. e.g. connected, disconnected.
/// </summary>
public enum WLAN_INTERFACE_STATE
{
/// <summary>
/// wlan_interface_state_not_ready -> 0
/// </summary>
wlan_interface_state_not_ready = 0,
/// <summary>
/// wlan_interface_state_connected -> 1
/// </summary>
wlan_interface_state_connected = 1,
/// <summary>
/// wlan_interface_state_ad_hoc_network_formed -> 2
/// </summary>
wlan_interface_state_ad_hoc_network_formed = 2,
/// <summary>
/// wlan_interface_state_disconnecting -> 3
/// </summary>
wlan_interface_state_disconnecting = 3,
/// <summary>
/// wlan_interface_state_disconnected -> 4
/// </summary>
wlan_interface_state_disconnected = 4,
/// <summary>
/// wlan_interface_state_associating -> 5
/// </summary>
wlan_interface_state_associating = 5,
/// <summary>
/// wlan_interface_state_discovering -> 6
/// </summary>
wlan_interface_state_discovering = 6,
/// <summary>
/// wlan_interface_state_authenticating -> 7
/// </summary>
wlan_interface_state_authenticating = 7,
}
public struct WLAN_PROFILE_INFO_LIST
{
public uint dwNumberOfItems;
public uint dwIndex;
public WLAN_PROFILE_INFO[] ProfileInfo;
public WLAN_PROFILE_INFO_LIST(IntPtr ppProfileList)
{
dwNumberOfItems = (uint)Marshal.ReadInt32(ppProfileList);
dwIndex = (uint)Marshal.ReadInt32(ppProfileList, 4);
ProfileInfo = new WLAN_PROFILE_INFO[dwNumberOfItems];
IntPtr ppProfileListTemp = new IntPtr(ppProfileList.ToInt32() + 8);
for (int i = 0; i < dwNumberOfItems; i++)
{
ppProfileList = new IntPtr(ppProfileListTemp.ToInt32() + i * Marshal.SizeOf(typeof(WLAN_PROFILE_INFO)));
ProfileInfo[i] = (WLAN_PROFILE_INFO)Marshal.PtrToStructure(ppProfileList, typeof(WLAN_PROFILE_INFO));
}
}
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct WLAN_PROFILE_INFO
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string strProfileName;
public uint dwFlags;
}
#endregion
private static List<NetworkAdapter> _networkAdapters;
public static List<NetworkAdapter> NetworkAdapters
{
get
{
if (_networkAdapters == null)
{
using (var mSearcher = new ManagementObjectSearcher("SELECT __PATH, Index, GUID, MACAddress, Name, NetConnectionID, Speed FROM Win32_NetworkAdapter WHERE PhysicalAdapter=true AND MACAddress IS NOT NULL AND Name IS NOT NULL AND NetConnectionID IS NOT NULL AND Speed IS NOT NULL"))
{
var mResults = mSearcher.Get();
_networkAdapters = new List<NetworkAdapter>(mResults.Count);
foreach (ManagementObject mResult in mResults)
{
_networkAdapters.Add(new NetworkAdapter(mResult));
}
}
}
return _networkAdapters;
}
}
public static bool PingDisco()
{
using (Ping p = new Ping())
{
try
{
PingReply pr = p.Send("disco", 2000);
if (pr.Status == IPStatus.Success)
return true;
else
return false;
}
catch (Exception)
{
return false;
}
}
}
public static void ConfigureWireless()
{
// Add Certificates
Program.Status.UpdateStatus(null, null, "Configuring Wireless Certificates");
CertificateInterop.AddTempCerts();
// Add Wireless Profiles
Program.Status.UpdateStatus(null, null, "Configuring Wireless Profiles");
var wirelessInlineProfiles = GetInlineWirelessProfiles();
if (wirelessInlineProfiles.Count > 0)
{
IntPtr wlanHandle = IntPtr.Zero;
uint negotiatedVersion;
try
{
if (WlanOpenHandle(1, IntPtr.Zero, out negotiatedVersion, ref wlanHandle) != 0)
throw new NotSupportedException("This device does not support Wireless");
// Add Profile to Each Wireless Adapter
var wirelessAdapters = NetworkAdapters.Where(na => na.IsWireless).ToList();
foreach (var na in wirelessAdapters)
{
foreach (var inlineWirelessProfile in wirelessInlineProfiles)
{
if (inlineWirelessProfile.AddProfile(wlanHandle, na.Guid))
{
Program.Status.UpdateStatus(null, null, string.Format("Added Wireless Profile: {0}", inlineWirelessProfile.ProfileName));
Program.SleepThread(500, false);
}
else
{
Program.Status.UpdateStatus(null, null, string.Format("Unable to add Wireless Profile: {0}", inlineWirelessProfile.ProfileName));
Program.SleepThread(5000, false);
}
}
}
}
finally
{
if (wlanHandle != IntPtr.Zero)
NetworkInterop.WlanCloseHandle(wlanHandle, IntPtr.Zero);
}
}
}
private class WirelessProfile
{
public string Filename { get; set; }
public string ProfileXml { get; set; }
public string ProfileName { get; set; }
public bool AddProfile(IntPtr WlanHandle, Guid interfaceGuid)
{
var pInterfaceGuid = interfaceGuid;
var pProfileXml = this.ProfileXml;
uint pFlag = 0;
uint failReason;
return (WlanSetProfile(WlanHandle, ref pInterfaceGuid, pFlag, pProfileXml, null, true, IntPtr.Zero, out failReason) == 0);
}
}
private static List<WirelessProfile> GetInlineWirelessProfiles()
{
var inlineProfileFiles = System.IO.Directory.EnumerateFiles(Program.InlinePath.Value, "WLAN_Profile_*.xml").ToList();
var inlineProfiles = new List<WirelessProfile>(inlineProfileFiles.Count);
foreach (var filename in inlineProfileFiles)
{
var profile = new WirelessProfile()
{
Filename = filename,
ProfileXml = System.IO.File.ReadAllText(filename)
};
var profileXml = new XmlDocument();
profileXml.LoadXml(profile.ProfileXml);
var profileXmlNS = new XmlNamespaceManager(profileXml.NameTable);
profileXmlNS.AddNamespace("p", "http://www.microsoft.com/networking/WLAN/profile/v1");
var profileXmlNameNode = profileXml.SelectSingleNode("/p:WLANProfile/p:name", profileXmlNS);
if (profileXmlNameNode != null)
{
profile.ProfileName = profileXmlNameNode.InnerText;
inlineProfiles.Add(profile);
}
}
return inlineProfiles;
}
private static WLAN_PROFILE_INFO_LIST GetWirelessProfiles(IntPtr WlanHandle, Guid interfaceGuid)
{
Guid pInterfaceGuid = interfaceGuid;
IntPtr ppProfileList = new IntPtr();
WlanGetProfileList(WlanHandle, ref pInterfaceGuid, new IntPtr(), ref ppProfileList);
WLAN_PROFILE_INFO_LIST wlanProfileInfoList = new WLAN_PROFILE_INFO_LIST(ppProfileList);
NetworkInterop.WlanFreeMemory(ppProfileList);
return wlanProfileInfoList;
}
}
}
@@ -0,0 +1,108 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace Disco.ClientBootstrapper.Interop
{
class RegistryInterop : IDisposable
{
[StructLayout(LayoutKind.Sequential)]
private struct LUID
{
public int LowPart;
public int HighPart;
}
[StructLayout(LayoutKind.Sequential)]
private struct TOKEN_PRIVILEGES
{
public LUID Luid;
public int Attributes;
public int PrivilegeCount;
}
[DllImport("advapi32.dll", CharSet = CharSet.Auto)]
private static extern int OpenProcessToken(int ProcessHandle, int DesiredAccess, ref int tokenhandle);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern int GetCurrentProcess();
[DllImport("advapi32.dll", CharSet = CharSet.Auto)]
private static extern int LookupPrivilegeValue(string lpsystemname, string lpname, [MarshalAs(UnmanagedType.Struct)] ref LUID lpLuid);
[DllImport("advapi32.dll", CharSet = CharSet.Auto)]
private static extern int AdjustTokenPrivileges(int tokenhandle, int disableprivs, [MarshalAs(UnmanagedType.Struct)]ref TOKEN_PRIVILEGES Newstate, int bufferlength, int PreivousState, int Returnlength);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int RegLoadKey(uint hKey, string lpSubKey, string lpFile);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int RegUnLoadKey(uint hKey, string lpSubKey);
private const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
private const int TOKEN_QUERY = 0x00000008;
private const int SE_PRIVILEGE_ENABLED = 0x00000002;
private const string SE_RESTORE_NAME = "SeRestorePrivilege";
private const string SE_BACKUP_NAME = "SeBackupPrivilege";
private const uint HKEY_USERS = 0x80000003;
private RegistryHives Hive { get; set; }
private string SubKey { get; set; }
private bool IsUnloaded { get; set; }
public enum RegistryHives : uint
{
HKEY_USERS = 0x80000003,
HKEY_LOCAL_MACHINE = 0x80000002
}
public RegistryInterop(RegistryHives hive, string subKey, string filePath)
{
int token = 0;
int retval = 0;
TOKEN_PRIVILEGES TP = new TOKEN_PRIVILEGES();
TOKEN_PRIVILEGES TP2 = new TOKEN_PRIVILEGES();
LUID RestoreLuid = new LUID();
LUID BackupLuid = new LUID();
retval = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref token);
retval = LookupPrivilegeValue(null, SE_RESTORE_NAME, ref RestoreLuid);
retval = LookupPrivilegeValue(null, SE_BACKUP_NAME, ref BackupLuid);
TP.PrivilegeCount = 1;
TP.Attributes = SE_PRIVILEGE_ENABLED;
TP.Luid = RestoreLuid;
TP2.PrivilegeCount = 1;
TP2.Attributes = SE_PRIVILEGE_ENABLED;
TP2.Luid = BackupLuid;
retval = AdjustTokenPrivileges(token, 0, ref TP, 1024, 0, 0);
retval = AdjustTokenPrivileges(token, 0, ref TP2, 1024, 0, 0);
uint regHive = (uint)hive;
this.Hive = hive;
this.SubKey = subKey;
RegLoadKey(regHive, subKey, filePath);
this.IsUnloaded = false;
}
public void Unload()
{
if (!IsUnloaded)
{
uint regHive = (uint)this.Hive;
string subKey = this.SubKey;
RegUnLoadKey(regHive, subKey);
this.IsUnloaded = true;
}
}
public void Dispose()
{
Unload();
}
}
}
@@ -0,0 +1,103 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
using System.Runtime.InteropServices;
namespace Disco.ClientBootstrapper.Interop
{
public static class ShutdownInterop
{
public static void Shutdown()
{
// 8 = Power Off
Shutdown(EWX_POWEROFF);
}
public static void Reboot()
{
// 2 = Reboot
Shutdown(EWX_REBOOT);
}
private static void Shutdown(int flag)
{
// Removed 2012-11-23 G# - Migrate to Win32 PInvoke Shutdown for better Privilege Handling
//ManagementBaseObject mboShutdown = null;
//ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem");
//mcWin32.Get();
//// You can't shutdown without security privileges
//mcWin32.Scope.Options.EnablePrivileges = true;
//ManagementBaseObject mboShutdownParams =
// mcWin32.GetMethodParameters("Win32Shutdown");
//// Flag 1 means we want to shut down the system. Use "2" to reboot.
//mboShutdownParams["Flags"] = flag;
//mboShutdownParams["Reserved"] = "0";
//foreach (ManagementObject manObj in mcWin32.GetInstances())
//{
// mboShutdown = manObj.InvokeMethod("Win32Shutdown",
// mboShutdownParams, null);
//}
// End Removed 2012-11-23 G#
// Added 2012-11-23 G# - Migrate to Win32 PInvoke Shutdown
bool result;
TokPriv1Luid tp;
IntPtr hproc = GetCurrentProcess();
IntPtr htok = IntPtr.Zero;
result = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
tp.Count = 1;
tp.Luid = 0;
tp.Attr = SE_PRIVILEGE_ENABLED;
result = LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, ref tp.Luid);
result = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
result = ExitWindowsEx(flag, 0);
// End Added 2012-11-23 G#
}
#region Win32 PInvoke Interop
[StructLayout(LayoutKind.Sequential, Pack = 1)]
private struct TokPriv1Luid
{
public int Count;
public long Luid;
public int Attr;
}
[DllImport("kernel32.dll", ExactSpelling = true)]
private static extern IntPtr GetCurrentProcess();
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
private static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
private static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall, ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
[DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]
private static extern bool ExitWindowsEx(int flg, int rea);
private const int SE_PRIVILEGE_ENABLED = 0x00000002;
private const int TOKEN_QUERY = 0x00000008;
private const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
private const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";
private const int EWX_LOGOFF = 0x00000000;
private const int EWX_SHUTDOWN = 0x00000001;
private const int EWX_REBOOT = 0x00000002;
private const int EWX_FORCE = 0x00000004;
private const int EWX_POWEROFF = 0x00000008;
private const int EWX_FORCEIFHUNG = 0x00000010;
#endregion
}
}
File diff suppressed because it is too large Load Diff