internal static RegistryKey OpenKey( string key, RegistryKeyPermissionCheck permissionCheck )
        {
            var root = OpenRoot( key );

            var path = key.Replace( root.Name, string.Empty ).Trim( '\\' );
            if ( string.IsNullOrEmpty( path ) )
            {
                return root;
            }

            using ( root )
            {
                return root.CreateSubKey( path, permissionCheck );
            }
        }
Example #2
0
        /// <summary>
        /// Function to create a new SubKey in the Windows Registry
        /// </summary>
        /// <param name="KeyPermissions">RegistryKepPermissionCheck -> Specifies permissions of the SubKey to be created</param>
        /// <returns>True (Succeeded)/False (Failed)</returns>
        /// <remarks>Created 22DEC07 -> Richard L. McCutchen</remarks>
        public bool CreateRegistrySubKey(RegistryKeyPermissionCheck KeyPermissions)
        {
            try
            {
                MainKey.CreateSubKey(Key, KeyPermissions);
                return true;
            }
            catch (Exception ex)
            {
                //since an exception occurred we need to let the user know
                MessageBox.Show(ex.Message, "Error: Creating SubKey", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //set our success variable to false since it failed
                return false;
            }

            //return the value to the calling method
            return IsSuccessful;
        }
Example #3
0
        private RegistryKey?InternalOpenSubKeyCore(string name, RegistryKeyPermissionCheck permissionCheck, int rights)
        {
            int ret = Interop.Advapi32.RegOpenKeyEx(_hkey, name, 0, (rights | (int)_regView), out SafeRegistryHandle result);

            if (ret == 0 && !result.IsInvalid)
            {
                RegistryKey key = new RegistryKey(result, (permissionCheck == RegistryKeyPermissionCheck.ReadWriteSubTree), false, _remoteKey, false, _regView);
                key._keyName   = _keyName + "\\" + name;
                key._checkMode = permissionCheck;
                return(key);
            }

            if (ret == Interop.Errors.ERROR_ACCESS_DENIED || ret == Interop.Errors.ERROR_BAD_IMPERSONATION_LEVEL)
            {
                // We need to throw SecurityException here for compatibility reason,
                // although UnauthorizedAccessException will make more sense.
                throw new SecurityException(SR.Security_RegistryPermission);
            }

            // Return null if we didn't find the key.
            return(null);
        }
Example #4
0
        public RegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCheck permissionCheck, RegistryOptions registryOptions)
        {
            ValidateKeyOptions(registryOptions);
            ValidateKeyName(subkey);
            ValidateKeyMode(permissionCheck);
            EnsureWriteable();
            subkey = FixupName(subkey); // Fixup multiple slashes to a single slash

            // only keys opened under read mode is not writable
            if (!_remoteKey)
            {
                RegistryKey?key = InternalOpenSubKeyWithoutSecurityChecks(subkey, (permissionCheck != RegistryKeyPermissionCheck.ReadSubTree));
                if (key != null)
                {
                    // Key already exits
                    key._checkMode = permissionCheck;
                    return(key);
                }
            }

            return(CreateSubKeyInternalCore(subkey, permissionCheck, registryOptions));
        }
        private static int GetRegistryKeyAccess(RegistryKeyPermissionCheck mode)
        {
            int winAccess = 0;

            switch (mode)
            {
            case RegistryKeyPermissionCheck.ReadSubTree:
            case RegistryKeyPermissionCheck.Default:
                winAccess = Interop.Advapi32.RegistryOperations.KEY_READ;
                break;

            case RegistryKeyPermissionCheck.ReadWriteSubTree:
                winAccess = Interop.Advapi32.RegistryOperations.KEY_READ | Interop.Advapi32.RegistryOperations.KEY_WRITE;
                break;

            default:
                Debug.Fail("unexpected code path");
                break;
            }

            return(winAccess);
        }
Example #6
0
        public static RegistryKey OpenRegistryKey(string name, RegistryKeyPermissionCheck registryKeyPermissionCheck, RegistryRights registryRights)
        {
            ThrowIfNullEmptyOrWhiteSpace(name, nameof(name));

            string originalName = name;

            string registryKeyName;

            if (name.Contains(WinCopies.IO.Path.PathSeparator, out int result))
            {
                registryKeyName = name.Substring(0, result);

                name = name.Length == 1 ? "" : name.Substring(result + 1);
            }

            else
            {
                registryKeyName = name;

                name = "";
            }

            FieldInfo[] fields = typeof(Microsoft.Win32.Registry).GetFields();

            var registryKeys = new KeyValuePair <RegistryKey, string> [fields.Length];

            RegistryKey item;

            for (int i = 0; i < fields.Length; i++)
            {
                item = (RegistryKey)fields[i].GetValue(null);

                registryKeys[i] = new KeyValuePair <RegistryKey, string>(item, item.Name);
            }

            if (If(ComparisonType.Or, ComparisonMode.Logical, Comparison.Equal, out RegistryKey registryKey, registryKeyName, registryKeys))
            {
                return(name.Length > 0 ? registryKey.OpenSubKey(name, registryKeyPermissionCheck, registryRights) : registryKey);
            }
Example #7
0
        private unsafe RegistryKey CreateSubKeyInternalCore(string subkey, RegistryKeyPermissionCheck permissionCheck, RegistryOptions registryOptions)
        {
            Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default;

            // By default, the new key will be writable.
            int ret = Interop.Advapi32.RegCreateKeyEx(_hkey,
                                                      subkey,
                                                      0,
                                                      null,
                                                      (int)registryOptions /* specifies if the key is volatile */,
                                                      GetRegistryKeyAccess(permissionCheck != RegistryKeyPermissionCheck.ReadSubTree) | (int)_regView,
                                                      ref secAttrs,
                                                      out SafeRegistryHandle result,
                                                      out int _);

            if (ret == 0 && !result.IsInvalid)
            {
                RegistryKey key = new RegistryKey(result, (permissionCheck != RegistryKeyPermissionCheck.ReadSubTree), false, _remoteKey, false, _regView);
                key._checkMode = permissionCheck;

                if (subkey.Length == 0)
                {
                    key._keyName = _keyName;
                }
                else
                {
                    key._keyName = _keyName + "\\" + subkey;
                }
                return(key);
            }
            else if (ret != 0)                             // syscall failed, ret is an error code.
            {
                Win32Error(ret, _keyName + "\\" + subkey); // Access denied?
            }

            Debug.Fail("Unexpected code path in RegistryKey::CreateSubKey");
            return(null);
        }
Example #8
0
        static RegistryKey SwallowRegKey(RegistryKey root, string key, RegistryKeyPermissionCheck newPermission)
        {
            string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
            //MessageBox.Show("swallow1");
            RegistryKey rk = root.OpenSubKey(key, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.ChangePermissions | RegistryRights.ReadKey);//Get the registry key desired with ChangePermissions Rights.

            if (rk == null)
            {
                return(null);
            }
            RegistrySecurity rs = new RegistrySecurity();

            rs.AddAccessRule(new RegistryAccessRule(userName, RegistryRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow)); //Create access rule giving full control to the Administrator user.
            rk.SetAccessControl(rs);                                                                                                                                                                                   //Apply the new access rule to this Registry Key.
            rk.Close();
            //rk = root.OpenSubKey(key, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl); // Opens the key again with full control.
            //rs.SetOwner(new NTAccount(userName));// Set the securitys owner to be Administrator
            //rk.SetAccessControl(rs);// Set the key with the changed permission so Administrator is now owner.
            //rk.Close();
            rk = root.OpenSubKey(key, newPermission, RegistryRights.FullControl);
            //MessageBox.Show("swallow2");
            return(rk);
        }
        private static bool TryGetCategoryKey(out RegistryKey registryKey)
        {
            const string keyName =
                PsConstants.DefaultRegistryRoot + @"\\FontAndColors\\{358463D0-D084-400F-997E-A34FC570BC72}";

            try
            {
                const RegistryKeyPermissionCheck keyPermissionCheck = RegistryKeyPermissionCheck.ReadSubTree;
                const RegistryRights             registryRights     = RegistryRights.QueryValues | RegistryRights.ReadKey;
                registryKey = Registry.CurrentUser.OpenSubKey(keyName, keyPermissionCheck, registryRights);
                if (registryKey != null)
                {
                    return(true);
                }
                registryKey = Registry.LocalMachine.OpenSubKey(keyName, keyPermissionCheck, registryRights);
                return(registryKey != null);
            }
            catch (SecurityException)
            {
                // nothing I can do
                registryKey = null;
                return(false);
            }
        }
Example #10
0
        public static bool Emulate(uint version)
        {
            string name = new FileInfo(Application.ExecutablePath).Name;
            RegistryKeyPermissionCheck readwrite = RegistryKeyPermissionCheck.ReadWriteSubTree;
            //RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true);
            RegistryKey key = Registry.CurrentUser.CreateSubKey("Software", readwrite).CreateSubKey("Microsoft", readwrite).CreateSubKey("Internet Explorer", readwrite)
                              .CreateSubKey("Main", readwrite).CreateSubKey("FeatureControl", readwrite).CreateSubKey("FEATURE_BROWSER_EMULATION", readwrite);

            if (!key.GetValueNames().Contains(name))
            {
                key.SetValue(name, version, RegistryValueKind.DWord);
                return(false);
            }
            else
            {
                uint currVal = Convert.ToUInt32(key.GetValue(name));
                if (currVal == version)
                {
                    return(true);
                }
                key.SetValue(name, version, RegistryValueKind.DWord);
                return(false);
            }
        }
 public RegistryKey OpenSubKey(string name, RegistryKeyPermissionCheck permissionCheck, System.Security.AccessControl.RegistryRights rights)
 {
   return default(RegistryKey);
 }
Example #12
0
		public RegistryKey OpenSubKey (string name, RegistryKeyPermissionCheck permissionCheck, RegistryRights rights)
		{
			throw new NotImplementedException ();
		}
Example #13
0
		public RegistryKey OpenSubKey (string name, RegistryKeyPermissionCheck permissionCheck, RegistryRights rights)
		{
			return OpenSubKey (name, permissionCheck == RegistryKeyPermissionCheck.ReadWriteSubTree);
		}
Example #14
0
		public RegistryKey CreateSubKey (string subkey, RegistryKeyPermissionCheck permissionCheck, RegistryOptions options)
		{
			AssertKeyStillValid ();
			AssertKeyNameNotNull (subkey);
			AssertKeyNameLength (subkey);

			if (!IsWritable)
				throw new UnauthorizedAccessException ("Cannot write to the registry key.");

			return RegistryApi.CreateSubKey (this, subkey, options);
		}
        private unsafe TransactedRegistryKey CreateSubKeyInternal(String subkey, RegistryKeyPermissionCheck permissionCheck, object registrySecurityObj)
        {
            ValidateKeyName(subkey);
            // RegCreateKeyTransacted requires a non-empty key name, so let's deal with that here.
            if (string.Empty == subkey)
            {
                throw new ArgumentException(RegistryProviderStrings.Arg_RegKeyStrEmpty);
            }

            ValidateKeyMode(permissionCheck);
            EnsureWriteable();
            subkey = FixupName(subkey); // Fixup multiple slashes to a single slash

            // only keys opened under read mode is not writable
            TransactedRegistryKey existingKey = InternalOpenSubKey(subkey, (permissionCheck != RegistryKeyPermissionCheck.ReadSubTree));
            if (existingKey != null)
            { // Key already exits
                CheckSubKeyWritePermission(subkey);
                CheckSubTreePermission(subkey, permissionCheck);
                existingKey._checkMode = permissionCheck;
                return existingKey;
            }

            CheckSubKeyCreatePermission(subkey);

            Win32Native.SECURITY_ATTRIBUTES secAttrs = null;
            TransactedRegistrySecurity registrySecurity = registrySecurityObj as TransactedRegistrySecurity;
            // For ACL's, get the security descriptor from the RegistrySecurity.
            if (registrySecurity != null)
            {
                secAttrs = new Win32Native.SECURITY_ATTRIBUTES();
                secAttrs.nLength = (int)Marshal.SizeOf(secAttrs);

                byte[] sd = registrySecurity.GetSecurityDescriptorBinaryForm();
                // We allocate memory on the stack to improve the speed.
                // So this part of code can't be refactored into a method.
                byte* pSecDescriptor = stackalloc byte[sd.Length];
                Microsoft.PowerShell.Commands.Internal.Buffer.memcpy(sd, 0, pSecDescriptor, 0, sd.Length);
                secAttrs.pSecurityDescriptor = pSecDescriptor;
            }
            int disposition = 0;

            // By default, the new key will be writable.
            SafeRegistryHandle result = null;
            int ret = 0;
            SafeTransactionHandle safeTransactionHandle = GetTransactionHandle();

            ret = Win32Native.RegCreateKeyTransacted(_hkey,
                subkey,
                0,
                null,
                0,
                GetRegistryKeyAccess(permissionCheck != RegistryKeyPermissionCheck.ReadSubTree),
                secAttrs,
                out result,
                out disposition,
                safeTransactionHandle,
                IntPtr.Zero
                );

            if (ret == 0 && !result.IsInvalid)
            {
                TransactedRegistryKey key = new TransactedRegistryKey(result, (permissionCheck != RegistryKeyPermissionCheck.ReadSubTree), false,
                                                                      Transaction.Current, safeTransactionHandle);
                CheckSubTreePermission(subkey, permissionCheck);
                key._checkMode = permissionCheck;

                if (subkey.Length == 0)
                    key._keyName = _keyName;
                else
                    key._keyName = _keyName + "\\" + subkey;
                return key;
            }
            else if (ret != 0) // syscall failed, ret is an error code.
                Win32Error(ret, _keyName + "\\" + subkey);  // Access denied?

            BCLDebug.Assert(false, "Unexpected code path in RegistryKey::CreateSubKey");
            return null;
        }
        private static int GetRegistryKeyAccess(RegistryKeyPermissionCheck mode)
        {
            int winAccess = 0;
            switch (mode)
            {
                case RegistryKeyPermissionCheck.ReadSubTree:
                case RegistryKeyPermissionCheck.Default:
                    winAccess = Win32Native.KEY_READ;
                    break;

                case RegistryKeyPermissionCheck.ReadWriteSubTree:
                    winAccess = Win32Native.KEY_READ | Win32Native.KEY_WRITE;
                    break;

                default:
                    BCLDebug.Assert(false, "unexpected code path");
                    break;
            }
            return winAccess;
        }
Example #17
0
        public static RegistryKey OpenKeyImpl(string baseKeyPath, string suffix, bool localMachine, RegistryKeyPermissionCheck permissions)
        {
            // Add the suffix
            string keyPath;

            if (string.IsNullOrEmpty(suffix))
            {
                keyPath = baseKeyPath;
            }
            else
            {
                keyPath = CombineKeys(baseKeyPath, suffix);
            }

            // Open the key.
            using (RegistryKey hive = RegistryKey.OpenBaseKey(localMachine ? RegistryHive.LocalMachine : RegistryHive.CurrentUser, RegistryView.Registry64))
            {
                RegistryKey key = hive.OpenSubKey(keyPath, permissions);
                if (key == null)
                {
                    // Try creating it if writeable
                    if (permissions == RegistryKeyPermissionCheck.ReadWriteSubTree)
                    {
                        key = hive.CreateSubKey(keyPath, permissions);
                    }
                }
                return(key);
            }
        }
Example #18
0
 public static extern IntPtr SetupDiOpenDevRegKey(IntPtr hDeviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData, int scope, int hwProfile, DevKeyType keyType, RegistryKeyPermissionCheck samDesired);
 /// <inheritdoc />
 public IRegistryKey OpenSubKey(string name, RegistryKeyPermissionCheck permissionCheck)
 {
     return(OpenSubKey(name, permissionCheck, RegistryRights.FullControl));
 }
 /// <inheritdoc />
 public IRegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCheck permissionCheck)
 {
     return(CreateSubKey(subkey, permissionCheck, new RegistrySecurity()));
 }
Example #21
0
        public RegistryKey OpenSubKey(string name, RegistryKeyPermissionCheck permissionCheck)
        {
            ValidateKeyMode(permissionCheck);

            return(OpenSubKey(name, permissionCheck, (RegistryRights)GetRegistryKeyAccess(permissionCheck)));
        }
Example #22
0
 public RegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCheck permissionCheck, RegistrySecurity registrySecurity)
 {
     return(CreateSubKey(subkey, permissionCheck, RegistryOptions.None));
 }
Example #23
0
 public RegistryKey OpenSubKey(string name, RegistryKeyPermissionCheck permissionCheck, RegistryRights rights)
 {
     return(OpenSubKey(name, permissionCheck == RegistryKeyPermissionCheck.ReadWriteSubTree));
 }
 public RegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCheck permissionCheck)
 {
   return default(RegistryKey);
 }
Example #25
0
 public RegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCheck permissionCheck)
 {
     return(CreateSubKey(subkey));
 }
 private static int GetRegistryKeyAccess(RegistryKeyPermissionCheck mode)
 {
     throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry);
 }
 public TransactedRegistryKey CreateSubKey(String subkey, RegistryKeyPermissionCheck permissionCheck)
 {
     return CreateSubKeyInternal(subkey, permissionCheck, (TransactedRegistrySecurity)null);
 }
 private RegistryKey CreateSubKeyInternalCore(string subkey, RegistryKeyPermissionCheck permissionCheck, object registrySecurityObj, RegistryOptions registryOptions)
 {
     throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry);
 }
 public TransactedRegistryKey OpenSubKey(String name, RegistryKeyPermissionCheck permissionCheck, RegistryRights rights)
 {
     return InternalOpenSubKey(name, permissionCheck, (int)rights);
 }
 private RegistryKey InternalOpenSubKeyCore(string name, RegistryKeyPermissionCheck permissionCheck, int rights, bool throwOnPermissionFailure)
 {
     throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry);
 }
Example #31
0
		public RegistryKey OpenSubKey (string name, RegistryKeyPermissionCheck permissionCheck, RegistryRights rights)
		{
			return OpenSubKey (name);
		}
Example #32
0
 public static RegistryKey GetRegistryKey(string regPath, RegistryKeyPermissionCheck check, RegistryRights rights)
 {
     GetRootAndSubRegPath(regPath, out RegistryKey root, out string keyPath);
     using (root) return(root.OpenSubKey(keyPath, check, rights));
 }
Example #33
0
		public RegistryKey CreateSubKey (string subkey, RegistryKeyPermissionCheck permissionCheck, RegistryOptions registryOptions,
			RegistrySecurity registrySecurity)
		{
			return CreateSubKey (subkey, permissionCheck, registryOptions);
		}
Example #34
0
 /// <inheritdoc />
 public IRegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCheck permissionCheck, RegistrySecurity registrySecurity)
 {
     return(new WindowsRegistryKey(_registryKey.CreateSubKey(subkey, permissionCheck, registrySecurity)));
 }
Example #35
0
		public RegistryKey CreateSubKey (string subkey, RegistryKeyPermissionCheck permissionCheck, RegistrySecurity registrySecurity)
		{
			throw new NotImplementedException ();
		}
Example #36
0
 protected RegistryKeyBase(RegistryKeyPermissionCheck permissionCheck)
 {
     CheckMode = permissionCheck;
 }
 public RegistryKey OpenSubKey(string name, RegistryKeyPermissionCheck permissionCheck)
 {
   return default(RegistryKey);
 }
Example #38
0
 public virtual RegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCheck permissionCheck, RegistrySecurity registrySecurity)
 {
     return(this.CreateSubKey(subkey, permissionCheck, RegistryOptions.None, registrySecurity));
 }
 public RegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCheck permissionCheck, RegistryOptions registryOptions, System.Security.AccessControl.RegistrySecurity registrySecurity)
 {
   return default(RegistryKey);
 }
Example #40
0
 public virtual RegistryKey OpenSubKey(string name, RegistryKeyPermissionCheck permissionCheck)
 {
     return(this.OpenSubKey(name, permissionCheck, GetRegistryKeyAccess(permissionCheck)));
 }
Example #41
0
        /// <inheritdoc />
        public IRegistryKey OpenSubKey(string name, RegistryKeyPermissionCheck permissionCheck, RegistryRights rights)
        {
            var subkey = _registryKey.OpenSubKey(name, permissionCheck, rights);

            return(subkey != null ? new WindowsRegistryKey(subkey) : null);
        }
 private void CheckOpenSubKeyPermission(string subkeyName, RegistryKeyPermissionCheck subKeyCheck)
 {
     if (subKeyCheck == RegistryKeyPermissionCheck.Default)
     {
         if (_checkMode == RegistryKeyPermissionCheck.Default)
         {
             CheckSubKeyReadPermission(subkeyName);
         }
     }
     CheckSubTreePermission(subkeyName, subKeyCheck);
 }
Example #43
0
 public abstract RegistryKey OpenSubKey(string name, RegistryKeyPermissionCheck permissionCheck, RegistryRights rights);
Example #44
0
 private void CheckPermission(RegistryInternalCheck check, string item, bool subKeyWritable, RegistryKeyPermissionCheck subKeyCheck)
 {
     // TODO: Cleanup
 }
Example #45
0
 public virtual RegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCheck permissionCheck, RegistryOptions options)
 {
     return(this.CreateSubKey(subkey, permissionCheck, options, null));
 }
Example #46
0
 static private void ValidateKeyMode(RegistryKeyPermissionCheck mode) {
     if( mode < RegistryKeyPermissionCheck.Default || mode > RegistryKeyPermissionCheck.ReadWriteSubTree) {
         ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidRegistryKeyPermissionCheck, ExceptionArgument.mode);  
     }            
 }
Example #47
0
 public abstract RegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCheck permissionCheck, RegistryOptions registryOptions, RegistrySecurity registrySecurity);
Example #48
0
 public RegistryKey CreateSubKey(String subkey, RegistryKeyPermissionCheck permissionCheck, RegistryOptions options) 
 {
     return CreateSubKeyInternal(subkey, permissionCheck, null, options);
 }
 protected virtual RegistryKey _RegistryLocalMachineCreateSubKey(string key, RegistryKeyPermissionCheck permissionCheck)
 {
     return(Registry.LocalMachine.CreateSubKey(key, permissionCheck));
 }
Example #50
0
 public unsafe RegistryKey CreateSubKey(String subkey, RegistryKeyPermissionCheck permissionCheck,  RegistryOptions registryOptions, RegistrySecurity registrySecurity) 
 {
     return CreateSubKeyInternal(subkey, permissionCheck, registrySecurity, registryOptions);
 }        
 private void CheckSubTreePermission(string subkeyName, RegistryKeyPermissionCheck subKeyCheck)
 {
     if (subKeyCheck == RegistryKeyPermissionCheck.ReadSubTree)
     {
         if (_checkMode == RegistryKeyPermissionCheck.Default)
         {
             CheckSubTreeReadPermission(subkeyName);
         }
     }
     else if (subKeyCheck == RegistryKeyPermissionCheck.ReadWriteSubTree)
     {
         if (_checkMode != RegistryKeyPermissionCheck.ReadWriteSubTree)
         {
             CheckSubTreeReadWritePermission(subkeyName);
         }
     }
 }
Example #52
0
        private unsafe RegistryKey CreateSubKeyInternal(String subkey, RegistryKeyPermissionCheck permissionCheck, object registrySecurityObj, RegistryOptions registryOptions)
        {
            ValidateKeyOptions(registryOptions);
            ValidateKeyName(subkey);
            ValidateKeyMode(permissionCheck);            
            EnsureWriteable();
            subkey = FixupName(subkey); // Fixup multiple slashes to a single slash
            
            // only keys opened under read mode is not writable
            if (!remoteKey) {
                RegistryKey key = InternalOpenSubKey(subkey, (permissionCheck != RegistryKeyPermissionCheck.ReadSubTree));
                if (key != null)  { // Key already exits
                    CheckPermission(RegistryInternalCheck.CheckSubKeyWritePermission, subkey, false, RegistryKeyPermissionCheck.Default);
                    CheckPermission(RegistryInternalCheck.CheckSubTreePermission, subkey, false, permissionCheck);
                    key.checkMode = permissionCheck;
                    return key;
                }
            }

            CheckPermission(RegistryInternalCheck.CheckSubKeyCreatePermission, subkey, false, RegistryKeyPermissionCheck.Default);      
            
            Win32Native.SECURITY_ATTRIBUTES secAttrs = null;
#if FEATURE_MACL
            RegistrySecurity registrySecurity = (RegistrySecurity)registrySecurityObj;
            // For ACL's, get the security descriptor from the RegistrySecurity.
            if (registrySecurity != null) {
                secAttrs = new Win32Native.SECURITY_ATTRIBUTES();
                secAttrs.nLength = (int)Marshal.SizeOf(secAttrs);

                byte[] sd = registrySecurity.GetSecurityDescriptorBinaryForm();
                // We allocate memory on the stack to improve the speed.
                // So this part of code can't be refactored into a method.
                byte* pSecDescriptor = stackalloc byte[sd.Length];
                Buffer.Memcpy(pSecDescriptor, 0, sd, 0, sd.Length);
                secAttrs.pSecurityDescriptor = pSecDescriptor;
            }
#endif
            int disposition = 0;

            // By default, the new key will be writable.
            SafeRegistryHandle result = null;
            int ret = Win32Native.RegCreateKeyEx(hkey,
                subkey,
                0,
                null,
                (int)registryOptions /* specifies if the key is volatile */,
                GetRegistryKeyAccess(permissionCheck != RegistryKeyPermissionCheck.ReadSubTree) | (int)regView,
                secAttrs,
                out result,
                out disposition);

            if (ret == 0 && !result.IsInvalid) {
                RegistryKey key = new RegistryKey(result, (permissionCheck != RegistryKeyPermissionCheck.ReadSubTree), false, remoteKey, false, regView);                
                CheckPermission(RegistryInternalCheck.CheckSubTreePermission, subkey, false, permissionCheck);                
                key.checkMode = permissionCheck;
                
                if (subkey.Length == 0)
                    key.keyName = keyName;
                else
                    key.keyName = keyName + "\\" + subkey;
                return key;
            }
            else if (ret != 0) // syscall failed, ret is an error code.
                Win32Error(ret, keyName + "\\" + subkey);  // Access denied?

            BCLDebug.Assert(false, "Unexpected code path in RegistryKey::CreateSubKey");
            return null;
        }
 private static void ValidateKeyMode(RegistryKeyPermissionCheck mode)
 {
     if (mode < RegistryKeyPermissionCheck.Default || mode > RegistryKeyPermissionCheck.ReadWriteSubTree)
     {
         throw new ArgumentException(RegistryProviderStrings.Argument_InvalidRegistryKeyPermissionCheck);
     }
 }
Example #54
0
        [System.Security.SecurityCritical]  // auto-generated
        private RegistryKey InternalOpenSubKey(String name, RegistryKeyPermissionCheck permissionCheck, int rights) {
            ValidateKeyName(name);
            ValidateKeyMode(permissionCheck);            

            ValidateKeyRights(rights);

            EnsureNotDisposed();
            name = FixupName(name); // Fixup multiple slashes to a single slash

            CheckPermission(RegistryInternalCheck.CheckOpenSubKeyPermission, name, false, permissionCheck);                        
            CheckPermission(RegistryInternalCheck.CheckSubTreePermission, name, false, permissionCheck);
            SafeRegistryHandle result = null;
            int ret = Win32Native.RegOpenKeyEx(hkey, name, 0, (rights | (int)regView), out result);
            if (ret == 0 && !result.IsInvalid) {
                RegistryKey key = new RegistryKey(result, (permissionCheck == RegistryKeyPermissionCheck.ReadWriteSubTree), false, remoteKey, false, regView);
                key.keyName = keyName + "\\" + name;
                key.checkMode = permissionCheck;
                return key;
            }

            // Return null if we didn't find the key.
            if (ret == Win32Native.ERROR_ACCESS_DENIED || ret == Win32Native.ERROR_BAD_IMPERSONATION_LEVEL) {
                // We need to throw SecurityException here for compatiblity reason,
                // although UnauthorizedAccessException will make more sense.
                ThrowHelper.ThrowSecurityException(ExceptionResource.Security_RegistryPermission);                
            }
            
            return null;                        
        }    
 public unsafe TransactedRegistryKey CreateSubKey(String subkey, RegistryKeyPermissionCheck permissionCheck, TransactedRegistrySecurity registrySecurity)
 {
     return CreateSubKeyInternal(subkey, permissionCheck, registrySecurity);
 }
 internal static RegistryKey CloneKey( RegistryKey source, RegistryKeyPermissionCheck permissionCheck )
 {
     RegistryKey clone = OpenKey( source.Name, permissionCheck );
     return clone;
 }
 public TransactedRegistryKey OpenSubKey(String name, RegistryKeyPermissionCheck permissionCheck)
 {
     ValidateKeyMode(permissionCheck);
     return InternalOpenSubKey(name, permissionCheck, GetRegistryKeyAccess(permissionCheck));
 }
 private RegistryKey GetKey( string sectionName, RegistryKeyPermissionCheck permissionCheck )
 {
     RegistryKey key;
     if ( Root.Name.EndsWith( ( sectionName ) ) )
     {
         key = CloneKey( Root, permissionCheck );
     }
     else
     {
         string trimmed = sectionName.Replace( Root.Name, string.Empty ).Trim( '\\' );
         key = Root.CreateSubKey( trimmed, permissionCheck );
     }
     return key;
 }
        private TransactedRegistryKey InternalOpenSubKey(String name, RegistryKeyPermissionCheck permissionCheck, int rights)
        {
            ValidateKeyName(name);
            ValidateKeyMode(permissionCheck);
            ValidateKeyRights(rights);
            EnsureNotDisposed();
            name = FixupName(name); // Fixup multiple slashes to a single slash

            CheckOpenSubKeyPermission(name, permissionCheck);
            SafeRegistryHandle result = null;
            int ret = 0;

            SafeTransactionHandle safeTransactionHandle = GetTransactionHandle();

            ret = RegOpenKeyTransactedWrapper(_hkey, name, 0, rights, out result, safeTransactionHandle, IntPtr.Zero);

            if (ret == 0 && !result.IsInvalid)
            {
                TransactedRegistryKey key = new TransactedRegistryKey(result, (permissionCheck == RegistryKeyPermissionCheck.ReadWriteSubTree), false,
                                                                      Transaction.Current, safeTransactionHandle);
                key._keyName = _keyName + "\\" + name;
                key._checkMode = permissionCheck;
                return key;
            }

            // Return null if we didn't find the key.
            if (ret == Win32Native.ERROR_ACCESS_DENIED || ret == Win32Native.ERROR_BAD_IMPERSONATION_LEVEL)
            {
                // We need to throw SecurityException here for compatibility reason,
                // although UnauthorizedAccessException will make more sense.
                throw new SecurityException(RegistryProviderStrings.Security_RegistryPermission);
            }

            return null;
        }
 private RegistryKey GetKey( string subKey, ref string sectionName, RegistryKeyPermissionCheck permissionCheck )
 {
     RegistryKey key;
     if ( string.Equals( subKey, Root.Name ) )
     {
         sectionName = Root.Name.Substring( Root.Name.LastIndexOf( '\\' ) + 1 );
         key = CloneKey( Root, permissionCheck );
     }
     else
     {
         key = Root.OpenSubKey( sectionName, permissionCheck );
     }
     return key;
 }