Browse Source

initial commit

master
Shannon Barrett 6 years ago
parent
commit
82fe34358b
17 changed files with 1804 additions and 0 deletions
  1. +818
    -0
      Program.cs
  2. +17
    -0
      Properties/AssemblyInfo.cs
  3. +63
    -0
      Properties/Resources.Designer.cs
  4. +120
    -0
      Properties/Resources.resx
  5. BIN
      Registry.ico
  6. +122
    -0
      Win32Security/AccessToken.cs
  7. +29
    -0
      Win32Security/DisposableObject.cs
  8. +22
    -0
      Win32Security/Luid.cs
  9. +78
    -0
      Win32Security/TokenPrivilege.cs
  10. +50
    -0
      Win32Security/TokenPrivileges.cs
  11. +179
    -0
      Win32Security/Win32Enums.cs
  12. +116
    -0
      Win32Security/Win32Interop.cs
  13. +40
    -0
      Win32Security/Win32Structs.cs
  14. +3
    -0
      app.config
  15. +125
    -0
      win6x_registry_tweak.csproj
  16. +2
    -0
      win6x_registry_tweak.csproj.DotSettings
  17. +20
    -0
      win6x_registry_tweak.sln

+ 818
- 0
Program.cs View File

@ -0,0 +1,818 @@

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;
using Microsoft.Win32;
using Microsoft.Win32.Security;
namespace install_wim_tweak
{
class Program
{
const string HIVE_MOUNT_DIR = "windows6_x_software";
static string _pkgDirectory = HIVE_MOUNT_DIR + "\\Microsoft\\Windows\\CurrentVersion\\Component Based Servicing\\";
const string HIVE_MOUNT_POINT = "HKLM\\" + HIVE_MOUNT_DIR;
const string REGISTRY_PATH = "Windows\\system32\\config\\SOFTWARE";
static readonly string ProgramHeader =
"-------------------------------------------\n" +
"--------Registry Tweak Tool v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version + "-------\n" +
"---------------for Windows 6.x-------------\n" +
"---------Created by Michał Wnuowski--------\n" +
"-----Concept by Aviv00@msfn / lite8@MDL----\n" +
"-----------Modified by Legolash2o----------\n" +
"-------------------------------------------\n\n";
const String PROGRAM_HELP_INFO =
"USAGE : \n" +
" install_wim_tweak [/p <Path>] [/c <PackageName> (optional)] [/?]\n\n" +
"REMARKS : \n" +
" /p<Path> Use '/p' switch to provide path to mounted install.wim\n" +
" /o Use '/o' to run on current Windows\n" +
" /c <ComponentName> Use '/c' to show a specific package\n" +
" /? Use '/?' switch to display this info\n" +
" /l Outputs all packages to \"Packages.txt\"\n" +
"EXAMPLE : \n" +
" install_wim_tweak /p C:\\temp files\\mount\n" +
" install_wim_tweak /c Microsoft-Hyper-V-Common-Drivers-Package";
static bool _failed;
static string _bkpFile;
static string _hiveFileInfo;
static string _comp = "";
static Dictionary<char, string> _cmdLineArgs;
static bool _online;
static readonly string PackLog = Environment.CurrentDirectory + "\\Packages.txt";
static string _cr = "";
static bool _vis;
//static Sid SysUser = new Sid();
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.White;
Console.Write(ProgramHeader);
Console.ResetColor();
try
{
_cmdLineArgs = ProcessCmdArgs(args, new char[] { 'p', '?', 'c', 'o', 'l', 'r', 'n', 'h', 'd' });
if (_cmdLineArgs.ContainsKey('?'))
{
Console.Write(PROGRAM_HELP_INFO);
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write("\nPlease make sure you use lowercase for the /p, /c, /o and /l");
Console.ResetColor();
Environment.Exit(1);
}
if (_cmdLineArgs.ContainsKey('c'))
{
if (!string.IsNullOrEmpty(_cmdLineArgs['c']))
{
_comp = Path.Combine(_cmdLineArgs['c'], "");
}
else
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Type the name of the package, if nothing is entered all packages will be made visible :");
Console.ForegroundColor = ConsoleColor.Cyan;
_comp = Path.Combine(Console.ReadLine(), "");
}
Console.ResetColor();
}
if (_cmdLineArgs.ContainsKey('o'))
{
_hiveFileInfo = Path.Combine(System.IO.Path.GetPathRoot(Environment.SystemDirectory), REGISTRY_PATH);
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("MountPath : Online");
Console.ResetColor();
_pkgDirectory = _pkgDirectory.Replace("windows6_x_software", "Software");
_online = true;
}
if (_cmdLineArgs.ContainsKey('h'))
{
_vis = true;
}
if (!_cmdLineArgs.ContainsKey('o'))
{
if (!_cmdLineArgs.ContainsKey('p'))
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Type path to mounted install.wim :");
Console.ForegroundColor = ConsoleColor.Cyan;
_hiveFileInfo = Path.Combine(Console.ReadLine(), REGISTRY_PATH);
if (_hiveFileInfo.Substring(0, _hiveFileInfo.Length - REGISTRY_PATH.Length).Length == 3)
{
Console.WriteLine("MountPath : Online");
_pkgDirectory = _pkgDirectory.Replace("windows6_x_software", "Software");
_online = true;
}
else
{
Console.WriteLine("MountPath : {0}", "\"" + _hiveFileInfo.Substring(0, _hiveFileInfo.Length - REGISTRY_PATH.Length) + "\"");
_online = false;
}
Console.ResetColor();
}
else
{
_hiveFileInfo = Path.Combine(_cmdLineArgs['p'], REGISTRY_PATH);
Console.ForegroundColor = ConsoleColor.Cyan;
if (_cmdLineArgs['p'].Length == 3)
{
Console.WriteLine("MountPath : Online");
_pkgDirectory = _pkgDirectory.Replace("windows6_x_software", "Software");
_online = true;
}
else
{
Console.WriteLine("MountPath : {0}", "\"" + _cmdLineArgs['p'] + "\"");
_online = false;
}
Console.ResetColor();
}
}
if (string.IsNullOrEmpty(_hiveFileInfo))
Environment.Exit(-2);
if (!File.Exists(_hiveFileInfo))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Registry file not found, please make sure your mount path is correct!");
Console.ResetColor();
_failed = true;
Environment.Exit(-532459699);
}
if (!string.IsNullOrEmpty(_comp))
{
string T = _comp;
while (T.Contains("~"))
{
T = T.Substring(0, T.Length - 1);
}
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("Component : " + "\"" + T + "\"");
Console.ResetColor();
}
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("\n------------------Starting-----------------");
Console.ResetColor();
if (_online == false)
{
if (!_cmdLineArgs.ContainsKey('l') && !_cmdLineArgs.ContainsKey('n'))
{
Console.Write("Creating BKP of registry file... ");
_bkpFile = Path.Combine(Environment.CurrentDirectory, "SOFTWAREBKP");
if (!File.Exists(_bkpFile))
{
File.Copy(_hiveFileInfo, _bkpFile, true);
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("OK");
Console.ResetColor();
}
Console.Write("Mounting registry file... ");
if (!Contains<string[], string>(Registry.LocalMachine.GetSubKeyNames(), HIVE_MOUNT_DIR))
{
if (!LoadHive(_hiveFileInfo, HIVE_MOUNT_POINT))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("FAIL");
Console.ResetColor();
_failed = true;
Ending();
}
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("OK");
Console.ResetColor();
}
if (_cmdLineArgs.ContainsKey('l'))
{
Console.Write("Writing to Log (Packages.txt) ");
if (File.Exists(PackLog)) { File.Delete(PackLog); }
ListComponentSubkeys(_pkgDirectory + "Packages\\");
Console.ForegroundColor = ConsoleColor.Green;
Console.Write("OK");
Console.ResetColor();
Ending();
}
Console.Write("Taking Ownership... ");
var myProcToken = new AccessTokenProcess(Process.GetCurrentProcess().Id, TokenAccessType.TOKEN_ALL_ACCESS | TokenAccessType.TOKEN_ADJUST_PRIVILEGES);
myProcToken.EnablePrivilege(new TokenPrivilege(TokenPrivilege.SE_TAKE_OWNERSHIP_NAME, true));
if (Win32.GetLastError() != 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("FAIL");
Console.WriteLine("You must be logged as Administrator.");
Console.ResetColor();
_failed = true;
Ending();
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("OK");
Console.ResetColor();
Console.Write("Editing \'Packages\' subkeys ");
try
{
if (CleanComponentSubkeys(_pkgDirectory + "Packages\\", _comp))
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("OK");
Console.ResetColor();
}
}
catch { }
if (_online == false)
{
Console.Write("Editing \'PackagesPending\' subkeys ");
try
{
if (CleanComponentSubkeys(_pkgDirectory + "PackagesPending\\", _comp))
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("OK");
Console.ResetColor();
}
}
catch { }
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Modifying registry completed sucessfully.");
Console.ResetColor();
if (_cmdLineArgs.ContainsKey('r'))
{
if (Contains<string[], string>(Microsoft.Win32.Registry.LocalMachine.GetSubKeyNames(), HIVE_MOUNT_DIR))
{
Console.Write("Unmounting key... ");
if (!UnloadHive(HIVE_MOUNT_POINT))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("FAIL");
Console.WriteLine("You must unmount registry hive manually.");
Console.WriteLine("Hit any key to close.");
Console.ResetColor();
Console.ReadKey();
Environment.Exit(-3);
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("OK");
Console.ResetColor();
}
Console.Write("Removing \'Packages\'... ");
if (RemoveComponentSubkeys(_pkgDirectory + "Packages\\", _comp))
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("OK");
Console.WriteLine("Removed packages successfully.");
Console.ResetColor();
}
Console.Write("Removing \'PackagesPending\'... ");
if (RemoveComponentSubkeys(_pkgDirectory + "Packages\\", _comp))
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("OK");
Console.WriteLine("Removed packages successfully.");
Console.ResetColor();
}
}
Ending();
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("FAIL");
Console.WriteLine("Unhandled error occured.");
Console.ResetColor();
Console.WriteLine(ex.Message);
_failed = true;
Ending();
}
}
static bool RemoveComponentSubkeys(string registryPath, string Comp)
{
int consoleX = 0; int consoleY = 0;
try
{
consoleX = Console.CursorLeft; consoleY = Console.CursorTop;
}
catch { }
int count = 1;
int tot = 0;
string PackL = _hiveFileInfo;
while (!PackL.EndsWith("\\Windows\\"))
{
PackL = PackL.Substring(0, PackL.Length - 1);
}
PackL = PackL.Replace("Windows\\", "");
foreach (string subkeyname in _cr.Split(Environment.NewLine.ToCharArray()))
{
if (Comp != null && (subkeyname.StartsWith(Comp) && !string.IsNullOrEmpty(Comp)))
{
tot += 1;
}
}
foreach (string subkeyname in _cr.Split(Environment.NewLine.ToCharArray()))
{
if (subkeyname.StartsWith(Comp) && !string.IsNullOrEmpty(Comp))
{
CorrectConsolePostion(tot, consoleY, consoleX);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Write("{0}/{1}", count, tot);
Console.ResetColor();
try
{
Process RC = new Process();
RC.StartInfo.FileName = "pkgmgr.exe";
if (_online == false)
{
RC.StartInfo.Arguments = "/o:" + "\"" + PackL + ";" + PackL + "Windows" + "\"" + " /up:" + subkeyname + " /norestart /quiet";
}
else
{
RC.StartInfo.Arguments = "/up:" + subkeyname + " /norestart /quiet";
}
RC.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
RC.Start();
RC.WaitForExit();
}
catch (Exception Ex) { Console.WriteLine(Ex.Message); }
count++;
}
}
return true;
}
static bool ListComponentSubkeys(string registryPath)
{
int consoleX = 0; int consoleY = 0;
try
{
consoleX = Console.CursorLeft; consoleY = Console.CursorTop;
}
catch { }
RegistryKey MyKey = Registry.LocalMachine.OpenSubKey(registryPath);
int count = 1;
int tot = 0;
string PackL = "";
foreach (string subkeyname in MyKey.GetSubKeyNames())
{
if (!subkeyname.StartsWith("Package"))
{
tot += 1;
}
}
foreach (string subkeyname in MyKey.GetSubKeyNames())
{
if (!subkeyname.StartsWith("Package"))
{
CorrectConsolePostion(tot, consoleY, consoleX);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Write("{0}/{1}", count, tot);
Console.ResetColor();
PackL += subkeyname + Environment.NewLine;
count++;
}
}
MyKey.Close();
try
{
StreamWriter SW = new StreamWriter(PackLog, true);
SW.WriteLine(PackL);
SW.Close();
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("FAIL");
Console.ResetColor();
}
return true;
}
static bool CleanComponentSubkeys(string registryPath, string CN)
{
int consoleX = 0; int consoleY = 0;
try
{
consoleX = Console.CursorLeft; consoleY = Console.CursorTop;
}
catch { }
try
{
RegistryKey MyKey = Registry.LocalMachine.OpenSubKey(registryPath);
IdentityReference CurUser = System.Security.Principal.WindowsIdentity.GetCurrent().User;
int count = 1;
int tot = 0;
foreach (string subkeyname in MyKey.GetSubKeyNames())
{
if (subkeyname.Contains(CN)) { tot += 1; }
}
Debug.Assert(MyKey != null, "myKey != null");
foreach (string subkeyname in MyKey.GetSubKeyNames())
{
if (subkeyname.Contains(CN))
{
try
{
if (!_cr.Contains(subkeyname)) { _cr += subkeyname + Environment.NewLine; }
CorrectConsolePostion(tot, consoleY, consoleX);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Write("{0}/{1}", count, tot);
Console.ResetColor();
if (!RegSetOwneship(MyKey, subkeyname, CurUser))
{
MyKey.Close();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("FAIL");
Console.WriteLine("Error at setting key privileges.");
Console.ResetColor();
_failed = true;
Ending();
}
RegistryAccessRule ntmp = RegSetFullAccess(MyKey, subkeyname, CurUser);
RegistryKey nSubKey = MyKey.OpenSubKey(subkeyname, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl);
try
{
if (Contains<string[], string>(nSubKey.GetValueNames(), "Visibility"))
{
if (_vis == false)
{
if (!Contains<string[], string>(nSubKey.GetValueNames(), "DefVis")) { nSubKey.SetValue("DefVis", nSubKey.GetValue("Visibility"), RegistryValueKind.DWord); }
nSubKey.SetValue("Visibility", 0x00000001, RegistryValueKind.DWord);
}
else
{
if (Contains<string[], string>(nSubKey.GetValueNames(), "DefVis")) { nSubKey.SetValue("Visibility", nSubKey.GetValue("DefVis"), RegistryValueKind.DWord); }
}
}
if (!_cmdLineArgs.ContainsKey('d'))
{
if (Contains<string[], string>(nSubKey.GetSubKeyNames(), "Owners"))
{
RegSetOwneship(MyKey, subkeyname + "\\Owners", CurUser);
RegSetFullAccess(MyKey, subkeyname + "\\Owners", CurUser);
nSubKey.DeleteSubKey("Owners");
}
}
}
catch (Exception Ex) { Console.WriteLine(Ex.Message); }
nSubKey.Close();
RegRemoveAccess(MyKey, subkeyname, CurUser, ntmp);
}
catch { }
count++;
}
}
MyKey.Close();
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(" FAIL - Key not exist");
Console.ResetColor();
return false;
}
return true;
}
static void Ending()
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("\n-------------------Ending------------------");
Console.ResetColor();
if (_online == false)
{
if (Contains<string[], string>(Microsoft.Win32.Registry.LocalMachine.GetSubKeyNames(), HIVE_MOUNT_DIR))
{
Console.Write("Unmounting key... ");
if (!UnloadHive(HIVE_MOUNT_POINT))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("FAIL");
Console.WriteLine("You must unmount registry hive manually.");
Console.WriteLine("Hit any key to close.");
Console.ResetColor();
Console.ReadKey();
Environment.Exit(-1);
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("OK");
Console.ResetColor();
}
if (File.Exists(_bkpFile) && _failed && !_cmdLineArgs.ContainsKey('n'))
{
Console.Write("Restoring Backup... ");
File.Copy(_bkpFile, _hiveFileInfo, true);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("OK");
Console.ResetColor();
try
{
Console.Write("Removing Backup file... ");
File.Delete(_bkpFile);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("OK");
Console.ResetColor();
if (_cmdLineArgs.Count == 0)
{
Console.WriteLine("Hit any key to close.");
Console.ReadKey();
}
}
catch
{ }
}
}
Environment.Exit(0);
}
static void RegRemoveAccess(RegistryKey nParentKey, string nkey, IdentityReference nuser, RegistryAccessRule nacc)
{
RegistryKey nSubKey = nParentKey.OpenSubKey(nkey, RegistryKeyPermissionCheck.ReadWriteSubTree,
RegistryRights.ChangePermissions | RegistryRights.ReadKey);
RegistrySecurity nSubKeySec = nSubKey.GetAccessControl(AccessControlSections.Access);
nSubKeySec.RemoveAccessRule(nacc);
nSubKey.SetAccessControl(nSubKeySec);
nSubKey.Close();
}
static RegistryAccessRule RegSetFullAccess(RegistryKey nParentKey, string nkey, IdentityReference nuser)
{
RegistryKey nSubKey = null;
try
{
nSubKey = nParentKey.OpenSubKey(nkey, RegistryKeyPermissionCheck.ReadWriteSubTree,
RegistryRights.ReadKey | RegistryRights.ChangePermissions | RegistryRights.ReadPermissions);
RegistrySecurity nSubKeySec = nSubKey.GetAccessControl(AccessControlSections.Access);
RegistryAccessRule nAccRule = new RegistryAccessRule(nuser, RegistryRights.FullControl, AccessControlType.Allow);
nSubKeySec.AddAccessRule(nAccRule);
//nSubKeySec.RemoveAccessRul
nSubKey.SetAccessControl(nSubKeySec);
nSubKey.Close();
return nAccRule;
}
catch
{
nSubKey?.Close();
return null;
}
}
static bool RegSetOwneship(RegistryKey nParentKey, string nkey, IdentityReference nuser)
{
RegistryKey nSubKey = null;
try
{
nSubKey = nParentKey.OpenSubKey(nkey, RegistryKeyPermissionCheck.ReadWriteSubTree,
RegistryRights.TakeOwnership | RegistryRights.ReadKey | RegistryRights.ReadPermissions);
RegistrySecurity nSubKeySec = nSubKey.GetAccessControl(AccessControlSections.Owner);
nSubKeySec.SetOwner(nuser);
nSubKey.SetAccessControl(nSubKeySec);
nSubKey.Close();
return true;
}
catch
{
if (nSubKey != null)
nSubKey.Close();
return false;
}
}
static bool Contains<typeColl, typeKey>(typeColl collection, typeKey val)
where typeColl : IEnumerable<typeKey>
where typeKey : IComparable
{
foreach (typeKey subelement in collection)
{
if (subelement.CompareTo(val) == 0)
return true;
}
return false;
}
static void InitProcess(Process nproc)
{
nproc.StartInfo.UseShellExecute = false;
nproc.StartInfo.RedirectStandardError = true;
nproc.StartInfo.RedirectStandardOutput = true;
nproc.StartInfo.RedirectStandardInput = true;
nproc.StartInfo.CreateNoWindow = true;
}
static bool LoadHive(string nfile, string nkeyname)
{
return RunReg(string.Format("LOAD {0} {1}", nkeyname, "\"" + nfile + "\""));
}
static bool UnloadHive(string nkeyname)
{
return RunReg(string.Format("UNLOAD {0}", nkeyname));
}
static bool RunReg(string nArguments)
{
Process reg = new Process();
InitProcess(reg);
reg.StartInfo.FileName = "reg.exe";
reg.StartInfo.Arguments = nArguments;
reg.Start();
reg.WaitForExit();
string RegOutput = reg.StandardOutput.ReadToEnd();
string RegError = reg.StandardError.ReadToEnd();
if ((RegOutput.Length < 1) || (RegError.Length > 1))
{
return false;
}
else
{
return true;
}
}
private static void CorrectConsolePostion(int tot, int consoleY, int consoleX)
{
try
{
Console.CursorLeft = consoleX;
Console.CursorTop = consoleY;
if (tot < 10)
{
Console.CursorLeft = consoleX;
Console.CursorTop = consoleY;
}
if (tot > 9 && tot < 100)
{
Console.CursorLeft = consoleX - 2;
Console.CursorTop = consoleY;
}
if (tot > 99 && tot < 1000)
{
Console.CursorLeft = consoleX - 4;
Console.CursorTop = consoleY;
}
if (tot > 999 && tot < 10000)
{
Console.CursorLeft = consoleX - 6;
Console.CursorTop = consoleY;
}
}
catch
{
}
}
static Dictionary<char, string> ProcessCmdArgs(string[] args, char[] allowedArgs)
{
Dictionary<char, string> tmp = new Dictionary<char, string>();
string curV = "";
string argtmp;
char curK = ' ';
foreach (string arg in args)
{
argtmp = arg.Trim();
if (argtmp[0] == '/')
{
if (Contains<char[], char>(allowedArgs, argtmp[1]))
{
if (curK != ' ')
tmp.Add(curK, curV.Trim());
curK = arg[1];
curV = "";
}
else
{
tmp.Clear();
tmp.Add('?', "");
return tmp;
}
}
else
{
if (curK == ' ')
{
tmp.Clear();
tmp.Add('?', "");
return tmp;
}
curV += " " + argtmp;
}
}
tmp.Add(curK, curV.Trim());
return tmp;
}
}
}
#region License
/* Copyright (c) 2008 Michał Wnuowski
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Contact
/*
* Michał Wnuowski
* Email: wnuku1@hotmail.com
*/
#endregion

+ 17
- 0
Properties/AssemblyInfo.cs View File

@ -0,0 +1,17 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
[assembly: ComVisible(false)]
[assembly: Guid("b0d40713-7d6f-427a-a79f-72d9ef92c6c8")]
[assembly: AssemblyTitleAttribute("win6.x_registry_tweak")]
[assembly: AssemblyDescriptionAttribute("Shows all packages in Windows Vista/7")]
[assembly: AssemblyCompanyAttribute("Modified by Legolash2o")]
[assembly: AssemblyProductAttribute("win6.x_registry_tweak")]
[assembly: AssemblyCopyrightAttribute("Copyright (c) 2008-2011 Michał Wnuowski")]
[assembly: AssemblyTrademarkAttribute("Michał Wnuowski")]
[assembly: AssemblyFileVersion("1.4.7.0")]
[assembly: NeutralResourcesLanguageAttribute("en-GB")]
[assembly: AssemblyVersion("1.4.7.0")]

+ 63
- 0
Properties/Resources.Designer.cs View File

@ -0,0 +1,63 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.235
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace install_wim_tweak.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("install_wim_tweak.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}

+ 120
- 0
Properties/Resources.resx View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

BIN
Registry.ico View File

Before After

+ 122
- 0
Win32Security/AccessToken.cs View File

@ -0,0 +1,122 @@
using System;
using System.Runtime.InteropServices;
namespace Microsoft.Win32.Security
{
using DWORD = UInt32;
using BOOL = Int32;
/// <summary>
/// Encapsulation of a Win32 token handle.
/// The object is disposable because it maintains the Win32 handle.
/// </summary>
public abstract class AccessToken : DisposableObject
{
/// The win32 token handle.
private IntPtr _handle;
protected internal AccessToken(IntPtr handle)
{
_handle = handle;
}
protected override void Dispose(bool disposing)
{
if (_handle != IntPtr.Zero)
{
// We don't want to throw an exception here, because there's not
// much we can do when failing to close a handle.
BOOL rc = Win32.CloseHandle(_handle);
if (rc != Win32.FALSE)
_handle = IntPtr.Zero;
}
}
/// <summary>
/// Enable a single privilege on the process.
/// </summary>
/// <param name="privilege"></param>
/// <exception cref="">Throws an exception if the privilege is not present
/// in the privilege list of the process</exception>
public void EnablePrivilege(TokenPrivilege privilege)
{
var privs = new TokenPrivileges {privilege};
EnableDisablePrivileges(privs);
}
private void EnableDisablePrivileges(TokenPrivileges privileges)
{
UnsafeEnableDisablePrivileges(privileges);
}
private unsafe void UnsafeEnableDisablePrivileges(TokenPrivileges privileges)
{
byte[] privBytes = privileges.GetNativeTokenPrivileges();
fixed (byte* priv = privBytes)
{
UInt32 cbLength;
Win32.SetLastError(Win32.SUCCESS);
BOOL rc = Win32.AdjustTokenPrivileges(
_handle,
Win32.FALSE,
(IntPtr) priv,
0,
IntPtr.Zero,
out cbLength);
Win32.CheckCall(rc);
// Additional check: privilege can't be added, and in that case,
// rc indicates a success, but GetLastError() has a specific meaning.
if (Marshal.GetLastWin32Error() == Win32.ERROR_NOT_ALL_ASSIGNED)
Win32.ThrowLastError();
}
}
}
/// <summary>
/// Access token for a process
/// </summary>
public class AccessTokenProcess : AccessToken
{
public AccessTokenProcess(int pid, TokenAccessType desiredAccess)
: base(OpenProcessToken(pid, desiredAccess))
{
}
private static IntPtr TryOpenProcessToken(int pid, TokenAccessType desiredAccess)
{
IntPtr processHandle = Win32.OpenProcess(
ProcessAccessType.PROCESS_QUERY_INFORMATION,
Win32.FALSE,
(uint) pid);
if (processHandle == IntPtr.Zero)
return IntPtr.Zero;
Win32.CheckCall(processHandle);
try
{
IntPtr handle;
BOOL rc = Win32.OpenProcessToken(processHandle, desiredAccess, out handle);
if (rc == Win32.FALSE)
return IntPtr.Zero;
return handle;
}
finally
{
Win32.CloseHandle(processHandle);
}
}
private static IntPtr OpenProcessToken(int pid, TokenAccessType desiredAccess)
{
IntPtr handle = TryOpenProcessToken(pid, desiredAccess);
if (handle == IntPtr.Zero)
Win32.ThrowLastError();
return handle;
}
}
}

+ 29
- 0
Win32Security/DisposableObject.cs View File

@ -0,0 +1,29 @@
using System;
namespace Microsoft.Win32.Security
{
/// <summary>
/// Abstract base class for any disposable object.
/// Handle the finalizer and the call the Gc.SuppressFinalize.
/// Derived classes must implement "Dispose(bool disposing)".
/// </summary>
public abstract class DisposableObject : IDisposable
{
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
~DisposableObject()
{
Dispose(false);
}
protected abstract void Dispose(bool disposing);
}
}

+ 22
- 0
Win32Security/Luid.cs View File

@ -0,0 +1,22 @@
using Microsoft.Win32.Security.Win32Structs;
namespace Microsoft.Win32.Security
{
/// <summary>
/// Summary description for Luid.
/// </summary>
public class Luid
{
private readonly LUID _luid;
public Luid(LUID luid)
{
_luid = luid;
}
internal LUID GetNativeLUID()
{
return _luid;
}
}
}

+ 78
- 0
Win32Security/TokenPrivilege.cs View File

@ -0,0 +1,78 @@
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32.Security.Win32Structs;
namespace Microsoft.Win32.Security
{
using HANDLE = IntPtr;
using DWORD = UInt32;
using BOOL = Int32;
using LPVOID = IntPtr;
using PSID = IntPtr;
/// <summary>
/// Summary description for TokenPrivilege.
/// </summary>
public class TokenPrivilege
{
public const string SE_CREATE_TOKEN_NAME = "SeCreateTokenPrivilege";
public const string SE_ASSIGNPRIMARYTOKEN_NAME = "SeAssignPrimaryTokenPrivilege";
public const string SE_LOCK_MEMORY_NAME = "SeLockMemoryPrivilege";
public const string SE_INCREASE_QUOTA_NAME = "SeIncreaseQuotaPrivilege";
public const string SE_UNSOLICITED_INPUT_NAME = "SeUnsolicitedInputPrivilege";
public const string SE_MACHINE_ACCOUNT_NAME = "SeMachineAccountPrivilege";
public const string SE_TCB_NAME = "SeTcbPrivilege";
public const string SE_SECURITY_NAME = "SeSecurityPrivilege";
public const string SE_TAKE_OWNERSHIP_NAME = "SeTakeOwnershipPrivilege";
public const string SE_LOAD_DRIVER_NAME = "SeLoadDriverPrivilege";
public const string SE_SYSTEM_PROFILE_NAME = "SeSystemProfilePrivilege";
public const string SE_SYSTEMTIME_NAME = "SeSystemtimePrivilege";
public const string SE_PROF_SINGLE_PROCESS_NAME = "SeProfileSingleProcessPrivilege";
public const string SE_INC_BASE_PRIORITY_NAME = "SeIncreaseBasePriorityPrivilege";
public const string SE_CREATE_PAGEFILE_NAME = "SeCreatePagefilePrivilege";
public const string SE_CREATE_PERMANENT_NAME = "SeCreatePermanentPrivilege";
public const string SE_BACKUP_NAME = "SeBackupPrivilege";
public const string SE_RESTORE_NAME = "SeRestorePrivilege";
public const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";
public const string SE_DEBUG_NAME = "SeDebugPrivilege";
public const string SE_AUDIT_NAME = "SeAuditPrivilege";
public const string SE_SYSTEM_ENVIRONMENT_NAME = "SeSystemEnvironmentPrivilege";
public const string SE_CHANGE_NOTIFY_NAME = "SeChangeNotifyPrivilege";
public const string SE_REMOTE_SHUTDOWN_NAME = "SeRemoteShutdownPrivilege";
public const string SE_UNDOCK_NAME = "SeUndockPrivilege";
public const string SE_SYNC_AGENT_NAME = "SeSyncAgentPrivilege";
public const string SE_ENABLE_DELEGATION_NAME = "SeEnableDelegationPrivilege";
public const string SE_MANAGE_VOLUME_NAME = "SeManageVolumePrivilege";
private readonly PrivilegeAttributes _attributes;
private readonly Luid _luid;
public TokenPrivilege(string systemName, string privilege, bool enabled)
{
LUID luid;
BOOL rc = Win32.LookupPrivilegeValue(systemName, privilege, out luid);
Win32.CheckCall(rc);
_luid = new Luid(luid);
_attributes = (enabled ? PrivilegeAttributes.Enabled : 0);
}
public TokenPrivilege(string privilege, bool enabled) :
this(null, privilege, enabled)
{
}
public unsafe byte[] GetNativeLUID_AND_ATTRIBUTES()
{
LUID_AND_ATTRIBUTES la;
la.Luid = _luid.GetNativeLUID();
la.Attributes = (uint) _attributes;
var res = new byte[Marshal.SizeOf(typeof (LUID_AND_ATTRIBUTES))];
fixed (byte* luida = res)
{
Marshal.StructureToPtr(la, (IntPtr) luida, false);
}
return res;
}
}
}

+ 50
- 0
Win32Security/TokenPrivileges.cs View File

@ -0,0 +1,50 @@
using System;
using System.Collections;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Win32.Security.Win32Structs;
namespace Microsoft.Win32.Security
{
/// <summary>
/// Summary description for TokenPrivileges.
/// </summary>
public class TokenPrivileges : CollectionBase
{
public TokenPrivilege this[int index]
{
get { return (TokenPrivilege) base.InnerList[index]; }
}
public void Add(TokenPrivilege privilege)
{
base.InnerList.Add(privilege);
}
public unsafe byte[] GetNativeTokenPrivileges()
{
Debug.Assert(Marshal.SizeOf(typeof (TOKEN_PRIVILEGES)) == 4);
TOKEN_PRIVILEGES tp;
tp.PrivilegeCount = (uint) Count;
int cbLength =
Marshal.SizeOf(typeof (TOKEN_PRIVILEGES)) +
Marshal.SizeOf(typeof (LUID_AND_ATTRIBUTES))*Count;
var res = new byte[cbLength];
fixed (byte* privs = res)
{
Marshal.StructureToPtr(tp, (IntPtr) privs, false);
}
int resOffset = Marshal.SizeOf(typeof (TOKEN_PRIVILEGES));
for (int i = 0; i < Count; i++)
{
byte[] luida = this[i].GetNativeLUID_AND_ATTRIBUTES();
Array.Copy(luida, 0, res, resOffset, luida.Length);
resOffset += luida.Length;
}
return res;
}
}
}

+ 179
- 0
Win32Security/Win32Enums.cs View File

@ -0,0 +1,179 @@
using System;
namespace Microsoft.Win32.Security
{
[Flags]
public enum AccessType : uint
{
DELETE = 0x00010000,
READ_CONTROL = 0x00020000,
WRITE_DAC = 0x00040000,
WRITE_OWNER = 0x00080000,
SYNCHRONIZE = 0x00100000,
STANDARD_RIGHTS_REQUIRED = 0x000F0000,
STANDARD_RIGHTS_READ = READ_CONTROL,
STANDARD_RIGHTS_WRITE = READ_CONTROL,
STANDARD_RIGHTS_EXECUTE = READ_CONTROL,
STANDARD_RIGHTS_ALL = 0x001F0000,
SPECIFIC_RIGHTS_ALL = 0x0000FFFF,
//
// AccessSystemAcl access type
//
ACCESS_SYSTEM_SECURITY = 0x01000000,
//
// MaximumAllowed access type
//
MAXIMUM_ALLOWED = 0x02000000,
//
// These are the generic rights.
//
GENERIC_READ = 0x80000000,
GENERIC_WRITE = 0x40000000,
GENERIC_EXECUTE = 0x20000000,
GENERIC_ALL = 0x10000000,
}
[Flags]
public enum TokenAccessType : uint
{
TOKEN_ASSIGN_PRIMARY = 0x0001,
TOKEN_DUPLICATE = 0x0002,
TOKEN_IMPERSONATE = 0x0004,
TOKEN_QUERY = 0x0008,
TOKEN_QUERY_SOURCE = 0x0010,
TOKEN_ADJUST_PRIVILEGES = 0x0020,
TOKEN_ADJUST_GROUPS = 0x0040,
TOKEN_ADJUST_DEFAULT = 0x0080,
TOKEN_ADJUST_SESSIONID = 0x0100,
TOKEN_ALL_ACCESS =
AccessType.STANDARD_RIGHTS_REQUIRED |
TOKEN_ASSIGN_PRIMARY |
TOKEN_DUPLICATE |
TOKEN_IMPERSONATE |
TOKEN_QUERY |
TOKEN_QUERY_SOURCE |
TOKEN_ADJUST_PRIVILEGES |
TOKEN_ADJUST_GROUPS |
TOKEN_ADJUST_DEFAULT |
TOKEN_ADJUST_SESSIONID,
TOKEN_READ =
AccessType.STANDARD_RIGHTS_READ |
TOKEN_QUERY,
TOKEN_WRITE =
AccessType.STANDARD_RIGHTS_WRITE |
TOKEN_ADJUST_PRIVILEGES |
TOKEN_ADJUST_GROUPS |
TOKEN_ADJUST_DEFAULT,
TOKEN_EXECUTE =
AccessType.STANDARD_RIGHTS_EXECUTE,
}
[Flags]
public enum ProcessAccessType : uint
{
DELETE = 0x00010000,
READ_CONTROL = 0x00020000,
WRITE_DAC = 0x00040000,
WRITE_OWNER = 0x00080000,
SYNCHRONIZE = 0x00100000,
STANDARD_RIGHTS_REQUIRED = 0x000F0000,
STANDARD_RIGHTS_READ = READ_CONTROL,
STANDARD_RIGHTS_WRITE = READ_CONTROL,
STANDARD_RIGHTS_EXECUTE = READ_CONTROL,
STANDARD_RIGHTS_ALL = 0x001F0000,
SPECIFIC_RIGHTS_ALL = 0x0000FFFF,
//
// AccessSystemAcl access type
//
ACCESS_SYSTEM_SECURITY = 0x01000000,
//
// MaximumAllowed access type
//
MAXIMUM_ALLOWED = 0x02000000,
//
// These are the generic rights.
//
GENERIC_READ = 0x80000000,
GENERIC_WRITE = 0x40000000,
GENERIC_EXECUTE = 0x20000000,
GENERIC_ALL = 0x10000000,
// PROCESS specific
PROCESS_TERMINATE = 0x0001,
PROCESS_CREATE_THREAD = 0x0002,
PROCESS_SET_SESSIONID = 0x0004,
PROCESS_VM_OPERATION = 0x0008,
PROCESS_VM_READ = 0x0010,
PROCESS_VM_WRITE = 0x0020,
PROCESS_DUP_HANDLE = 0x0040,
PROCESS_CREATE_PROCESS = 0x0080,
PROCESS_SET_QUOTA = 0x0100,
PROCESS_SET_INFORMATION = 0x0200,
PROCESS_QUERY_INFORMATION = 0x0400,
PROCESS_SUSPEND_RESUME = 0x0800,
PROCESS_ALL_ACCESS =
AccessType.STANDARD_RIGHTS_REQUIRED |
AccessType.SYNCHRONIZE |
0xFFF,
}
[Flags]
public enum PrivilegeAttributes : uint
{
/*
SE_PRIVILEGE_DISABLED = 0,
SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x00000001,
SE_PRIVILEGE_ENABLED = 0x00000002,
SE_PRIVILEGE_USED_FOR_ACCESS = 0x80000000,
*/
Disabled = 0,
EnabledByDefault = 0x00000001,
Enabled = 0x00000002,
UsedForAccess = 0x80000000,
}
[Flags]
public enum SecurityDescriptorControlFlags : ushort // WORD
{
SE_OWNER_DEFAULTED = 0x0001,
SE_GROUP_DEFAULTED = 0x0002,
SE_DACL_PRESENT = 0x0004,
SE_DACL_DEFAULTED = 0x0008,
SE_SACL_PRESENT = 0x0010,
SE_SACL_DEFAULTED = 0x0020,
SE_DACL_AUTO_INHERIT_REQ = 0x0100,
SE_SACL_AUTO_INHERIT_REQ = 0x0200,
SE_DACL_AUTO_INHERITED = 0x0400,
SE_SACL_AUTO_INHERITED = 0x0800,
SE_DACL_PROTECTED = 0x1000,
SE_SACL_PROTECTED = 0x2000,
SE_RM_CONTROL_VALID = 0x4000,
SE_SELF_RELATIVE = 0x8000,
}
}

+ 116
- 0
Win32Security/Win32Interop.cs View File

@ -0,0 +1,116 @@
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32.Security.Win32Structs;
namespace Microsoft.Win32.Security
{
using HANDLE = IntPtr;
using DWORD = UInt32;
using BOOL = Int32;
using LPVOID = IntPtr;
using PACL = IntPtr;
using PTOKEN_PRIVILEGES = IntPtr;
using PSECURITY_DESCRIPTOR = IntPtr;
using SECURITY_DESCRIPTOR_CONTROL = SecurityDescriptorControlFlags;
using LPCTSTR = String;
using HKEY = IntPtr;
using LONG = Int32;
/// <summary>
/// Summary description for Win32Interop.
/// </summary>
public class Win32
{
public const BOOL FALSE = 0;
public const BOOL TRUE = 1;
public const int SUCCESS = 0;
public const int ERROR_SUCCESS = 0;
public const int ERROR_INSUFFICIENT_BUFFER = 122;
public const int ERROR_NOT_ALL_ASSIGNED = 1300;
public const int ERROR_NONE_MAPPED = 1332;
private const string Kernel32 = "kernel32.dll";
private const string Advapi32 = "Advapi32.dll";
public static DWORD GetLastError()
{
return (DWORD) Marshal.GetLastWin32Error();
}
public static void ThrowLastError()
{
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
public static void CheckCall(bool funcResult)
{
if (! funcResult)
{
ThrowLastError();
}
}
public static void CheckCall(BOOL funcResult)
{
CheckCall(funcResult != 0);
}
public static void CheckCall(HANDLE funcResult)
{
CheckCall(!IsNullHandle(funcResult));
}
public static bool IsNullHandle(HANDLE ptr)
{
return (ptr == IntPtr.Zero);
}
///////////////////////////////////////////////////////////////////////////////
///
/// KERNEL32.DLL
///
[DllImport(Kernel32, CallingConvention = CallingConvention.Winapi)]
public static extern void SetLastError(DWORD dwErrCode);
/*
[DllImport(Kernel32, CallingConvention=CallingConvention.Winapi, SetLastError=true, CharSet=CharSet.Auto)]
public static extern HANDLE CreateEvent(
[In, Out, MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(SecurityAttributesMarshaler))]
SecurityAttributes lpEventAttributes, // SA
BOOL bManualReset, // reset type
BOOL bInitialState, // initial state
string lpName // object name
);
*/
[DllImport(Kernel32, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
public static extern HANDLE OpenProcess(ProcessAccessType dwDesiredAccess, BOOL bInheritHandle,
DWORD dwProcessId);
[DllImport(Kernel32, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
public static extern BOOL CloseHandle(HANDLE handle);
///////////////////////////////////////////////////////////////////////////////
///
/// ADVAPI32.DLL
///
[DllImport(Advapi32, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
public static extern BOOL OpenProcessToken(HANDLE hProcess, TokenAccessType dwDesiredAccess, out HANDLE hToken);
[DllImport(Advapi32, CallingConvention = CallingConvention.Winapi, SetLastError = true, CharSet = CharSet.Auto)]
public static extern BOOL LookupPrivilegeValue(string lpSystemName, string lpName, out LUID Luid);
[DllImport(Advapi32, CallingConvention = CallingConvention.Winapi, SetLastError = true, CharSet = CharSet.Auto)]
public static extern BOOL AdjustTokenPrivileges(
HANDLE TokenHandle,
BOOL DisableAllPrivileges,
PTOKEN_PRIVILEGES NewState,
DWORD BufferLength,
PTOKEN_PRIVILEGES PreviousState,
out DWORD ReturnLength);
}
}

+ 40
- 0
Win32Security/Win32Structs.cs View File

@ -0,0 +1,40 @@
using System;
using System.Runtime.InteropServices;
namespace Microsoft.Win32.Security.Win32Structs
{
using HANDLE = IntPtr;
using DWORD = UInt32;
using LONG = Int32;
using UCHAR = Byte;
using BOOL = Int32;
using LARGE_INTEGER = Int64;
using PACL = IntPtr;
using PSID = IntPtr;
using GUID = Guid;
using PVOID = IntPtr;
using LPWSTR = String;
[StructLayout(LayoutKind.Sequential)]
public struct LUID
{
public DWORD LowPart;
public LONG HighPart;
}
[StructLayout(LayoutKind.Sequential)]
public struct TOKEN_PRIVILEGES
{
public DWORD PrivilegeCount;
// Followed by this:
//LUID_AND_ATTRIBUTES Privileges[ANYSIZE_ARRAY];
}
[StructLayout(LayoutKind.Sequential)]
public struct LUID_AND_ATTRIBUTES
{
public LUID Luid;
public DWORD Attributes;
}
}

+ 3
- 0
app.config View File

@ -0,0 +1,3 @@
<?xml version="1.0"?>
<configuration>
<startup><supportedRuntime version="v2.0.50727"/></startup></configuration>

+ 125
- 0
win6x_registry_tweak.csproj View File

@ -0,0 +1,125 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.21022</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{D31788D0-EF2C-49B4-B444-1A6A90E0DFA7}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>install_wim_tweak</RootNamespace>
<AssemblyName>install_wim_tweak</AssemblyName>
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<FileUpgradeFlags>
</FileUpgradeFlags>
<UpgradeBackupLocation>
</UpgradeBackupLocation>
<OldToolsVersion>3.5</OldToolsVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup>
<ApplicationIcon>Registry.ico</ApplicationIcon>
</PropertyGroup>
<PropertyGroup>
<StartupObject />
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Win32Security\AccessToken.cs" />
<Compile Include="Win32Security\DisposableObject.cs" />
<Compile Include="Win32Security\Luid.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="Win32Security\TokenPrivilege.cs" />
<Compile Include="Win32Security\TokenPrivileges.cs" />
<Compile Include="Win32Security\Win32Enums.cs" />
<Compile Include="Win32Security\Win32Interop.cs" />
<Compile Include="Win32Security\Win32Structs.cs" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include="Microsoft.Net.Client.3.5">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">
<Visible>False</Visible>
<ProductName>Windows Installer 3.1</ProductName>
<Install>true</Install>
</BootstrapperPackage>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<Content Include="Registry.ico" />
</ItemGroup>
<ItemGroup>
<Folder Include="Resources\" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

+ 2
- 0
win6x_registry_tweak.csproj.DotSettings View File

@ -0,0 +1,2 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:String x:Key="/Default/CodeEditing/Localization/Localizable/@EntryValue">No</s:String></wpf:ResourceDictionary>

+ 20
- 0
win6x_registry_tweak.sln View File

@ -0,0 +1,20 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "win6x_registry_tweak", "win6x_registry_tweak.csproj", "{D31788D0-EF2C-49B4-B444-1A6A90E0DFA7}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{D31788D0-EF2C-49B4-B444-1A6A90E0DFA7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D31788D0-EF2C-49B4-B444-1A6A90E0DFA7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D31788D0-EF2C-49B4-B444-1A6A90E0DFA7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D31788D0-EF2C-49B4-B444-1A6A90E0DFA7}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

Loading…
Cancel
Save