Exemple #1
0
        internal static void CopyValues(this VirtualRegistry virtualRegistry, VirtualKey sourceKey, KeyInfo sourceKeyInfo, VirtualKey destinationKey)
        {
            using (HGlobalPtr lpValueName = new HGlobalPtr((sourceKeyInfo.MaxValueNameLength + 1) * sizeof(char)),
                   lpcValueName = new HGlobalPtr(sizeof(int)),
                   lpReserved = new HGlobalPtr(IntPtr.Zero),
                   lpdwType = new HGlobalPtr(sizeof(int)),
                   lpvData = new HGlobalPtr(sourceKeyInfo.MaxValueLength),
                   lpcData = new HGlobalPtr(sizeof(int)))
            {
                for (uint i = 0; i < sourceKeyInfo.ValuesNumber; ++i)
                {
                    Marshal.WriteInt32(lpcValueName.Ptr, unchecked ((int)sourceKeyInfo.MaxValueNameLength) + 1);
                    Marshal.WriteInt32(lpcData.Ptr, unchecked ((int)sourceKeyInfo.MaxValueLength));
                    sourceKey.EnumValue(i, lpValueName.Ptr, lpcValueName.Ptr, lpReserved.Ptr, lpdwType.Ptr, lpvData.Ptr,
                                        lpcData.Ptr);

                    Win32Api.RegValueType valueType = (Win32Api.RegValueType)Marshal.ReadInt32(lpdwType.Ptr);

                    int currentValueLength     = Marshal.ReadInt32(lpcData.Ptr);
                    int currentValueNameLength = Marshal.ReadInt32(lpcValueName.Ptr);

                    string currentValueName = Marshal.PtrToStringUni(lpValueName.Ptr, currentValueNameLength);

                    destinationKey.SetValue(null, currentValueName, 0, valueType, lpvData.Ptr, currentValueLength);
                }
            }
        }
Exemple #2
0
        public void SetValue(
            string lpValueName,
            Win32Api.RegValueType dwType,
            IntPtr lpData,
            int cbData)
        {
            int result;

            if (!DoUni2AnsiConversion ||
                !DataTransformer.IsStringType(dwType))
            {
                result = OffRegHive.CatchException(() =>
                                                   key_.SetValueUnmanaged(lpValueName, (OffregLib.RegValueType)dwType, lpData, cbData));
                hive_.MarkAsModified();
                Win32Exception.CheckResult(result);
                return;
            }
            string str = Marshal.PtrToStringAnsi(lpData, cbData);

            using (HGlobalPtr pStr =
                       new HGlobalPtr(Marshal.StringToHGlobalUni(str)))
            {
                result = OffRegHive.CatchException(() =>
                                                   key_.SetValueUnmanaged(lpValueName, (OffregLib.RegValueType)dwType,
                                                                          pStr.Ptr, cbData * sizeof(char)));
                hive_.MarkAsModified();
                Win32Exception.CheckResult(result);
            }
        }
Exemple #3
0
 public void CopyTo(IntPtr dst, StringFormat dstFormat)
 {
     using (HGlobalPtr pStr =
                new HGlobalPtr(dstFormat == StringFormat.Ansi ?
                               Marshal.StringToHGlobalAnsi(value_) :
                               Marshal.StringToHGlobalUni(value_)))
     {
         PInvokeHelper.Copy(pStr.Ptr, dst, Length * Data.BytesPerChar(dstFormat));
     }
 }
Exemple #4
0
 public int Read(IntPtr pData, int cbData)
 {
     using (HGlobalPtr pcbData = new HGlobalPtr(sizeof(int)))
     {
         if (!Win32Api.ReadFile(hFile_, pData, unchecked ((uint)cbData),
                                pcbData.Ptr, IntPtr.Zero))
         {
             throw Win32Exception.Create(unchecked ((int)Win32Api.GetLastError()));
         }
         return(Marshal.ReadInt32(pcbData.Ptr));
     }
 }
Exemple #5
0
 public override int Read(byte[] buffer, int offset, int count)
 {
     if (offset != 0)
     {
         throw new NotImplementedException();
     }
     using (HGlobalPtr pBuffer = new HGlobalPtr(count))
     {
         int cbRead = reader_.Read(pBuffer.Ptr, count);
         Marshal.Copy(pBuffer.Ptr, buffer, 0, cbRead);
         return(cbRead);
     }
 }
Exemple #6
0
 public bool Handle(WindowsKey key)
 {
     if (!KeyIdentity.IsPredefined(key.Handle))
     {
         return Win32Exception.CheckIfFoundAndNoError(
             Win32Api.NtQueryKey(key.Handle, KeyInformationClass_, KeyInformation_, Length_,
             out ResultLength_));
     }
     // Predefined key handle values are valid only on the advapi32.dll level
     // on the ntdll.dll level we have to replace them with appropriate ntdll.dll handles
     IntPtr hNtKey = IntPtr.Zero;
     string objectName = KeyIdentity.GetSystemBasePath(key.Handle);
     Win32Api.UNICODE_STRING usObjectName = new Win32Api.UNICODE_STRING();
     usObjectName.Length = unchecked((ushort)(sizeof(char) * objectName.Length));
     usObjectName.MaximumLength = usObjectName.Length;
     using (HGlobalPtr pObjectNameBuffer = new HGlobalPtr(Marshal.StringToHGlobalUni(objectName)))
     {
         usObjectName.Buffer = pObjectNameBuffer.Ptr;
         using (HGlobalPtr pObjectName = new HGlobalPtr(Marshal.SizeOf(typeof(Win32Api.UNICODE_STRING))))
         {
             Marshal.StructureToPtr(usObjectName, pObjectName.Ptr, false);
             Win32Api.OBJECT_ATTRIBUTES oa = new Win32Api.OBJECT_ATTRIBUTES();
             oa.Length = unchecked((uint)Marshal.SizeOf(typeof(Win32Api.OBJECT_ATTRIBUTES)));
             oa.RootDirectory = IntPtr.Zero;
             oa.ObjectName = pObjectName.Ptr;
             oa.Attributes = (uint)Win32Api.ObjectAttributes.OBJ_CASE_INSENSITIVE;
             oa.SecurityDescriptor = IntPtr.Zero;
             oa.SecurityQualityOfService = IntPtr.Zero;
             using (HGlobalPtr pOA = new HGlobalPtr(Marshal.SizeOf(typeof(Win32Api.OBJECT_ATTRIBUTES))))
             {
                 Marshal.StructureToPtr(oa, pOA.Ptr, false);
                 if (!Win32Exception.CheckIfFoundAndNoError(
                     Win32Api.NtOpenKey(out hNtKey, (uint)Win32Api.KeySecurity.KEY_QUERY_VALUE, pOA.Ptr)))
                 {
                     return false;
                 }
                 try
                 {
                     return Win32Exception.CheckIfFoundAndNoError(
                         Win32Api.NtQueryKey(hNtKey, KeyInformationClass_, KeyInformation_, Length_,
                         out ResultLength_));
                 }
                 finally
                 {
                     Win32Api.NtClose(hNtKey);
                 }
             }
         }
     }
 }
Exemple #7
0
        internal static KeyNameAndClass[] GetSubKeysInformation(this VirtualKey key, KeyInfo keyInfo)
        {
            uint maxKeyNameLength = keyInfo.MaxSubKeyLength;
            uint maxClassLength   = keyInfo.MaxClassLength;

            uint subKeysNumber = keyInfo.SubKeysNumber;

            if (subKeysNumber == 0)
            {
                return(new KeyNameAndClass[0]);
            }

            var result = new KeyNameAndClass[subKeysNumber];

            using (HGlobalPtr lpName = new HGlobalPtr((maxKeyNameLength + 1) * sizeof(char)),
                   lpcName = new HGlobalPtr(sizeof(int)),
                   lpReserved = new HGlobalPtr(IntPtr.Zero),
                   lpClass = new HGlobalPtr((maxClassLength + 1) * sizeof(char)),
                   lpcClass = new HGlobalPtr(sizeof(int)),
                   lpftLastWriteTime = new HGlobalPtr(IntPtr.Zero))
            {
                for (uint i = 0; i < subKeysNumber; ++i)
                {
                    Marshal.WriteInt32(lpcName.Ptr, unchecked ((int)maxKeyNameLength) + 1);
                    Marshal.WriteInt32(lpcClass.Ptr, unchecked ((int)maxClassLength) + 1);

                    key.EnumKey(
                        i,
                        lpName.Ptr,
                        lpcName.Ptr,
                        lpReserved.Ptr,
                        lpClass.Ptr,
                        lpcClass.Ptr,
                        lpftLastWriteTime.Ptr);

                    KeyNameAndClass currentInfo;

                    int currentNameLength  = Marshal.ReadInt32(lpcName.Ptr);
                    int currentClassLength = Marshal.ReadInt32(lpcClass.Ptr);
                    currentInfo.Name  = Marshal.PtrToStringUni(lpName.Ptr, currentNameLength);
                    currentInfo.Class = Marshal.PtrToStringUni(lpClass.Ptr, currentClassLength);

                    result[i] = currentInfo;
                }
            }

            Array.Sort(result, (left, right) => String.CompareOrdinal(left.Name, right.Name));
            return(result);
        }
Exemple #8
0
 public override void Write(byte[] buffer, int offset, int count)
 {
     if (offset != 0)
     {
         throw new NotImplementedException();
     }
     using (HGlobalPtr pBuffer = new HGlobalPtr(count))
     {
         Marshal.Copy(buffer, 0, pBuffer.Ptr, count);
         int cbWritten = writer_.Write(pBuffer.Ptr, count);
         if (cbWritten < count)
         {
             throw new IOException("IWrite interface written less bytes than expected");
         }
     }
 }
Exemple #9
0
        // ATTENTION: pcchAnsiStr contains number of characters, NOT bytes
        internal Uni2AnsiConverter(Data ansiStr, bool doConvert = true)
        {
            ansiStr_   = ansiStr;
            doConvert_ = doConvert;
            if (!doConvert)
            {
                return;
            }
            int cchAnsiStr = 0;

            if (ansiStr.PCount != IntPtr.Zero)
            {
                cchAnsiStr = Marshal.ReadInt32(ansiStr.PCount);
            }
            // Here using the feature of HGlobalPtr that its pointer
            // is assigned IntPtr.Zero if size passed to ctor is zero.
            unicodeStr_ = new HGlobalPtr(sizeof(char) * cchAnsiStr);
        }
Exemple #10
0
 internal void MarkKeyAsDeleted(KeyIdentity identity)
 {
     try
     {
         string[] subkeys = identity.SplitPath();
         int      existingLevels, nonRemovableLevels;
         CalcNonRemovableLevels(null, identity, out existingLevels, out nonRemovableLevels);
         if (subkeys.Length <= nonRemovableLevels)
         {
             // We can't mark root keys as deleted
             return;
         }
         using (HGlobalPtr pData = new HGlobalPtr(Marshal.SizeOf(typeof(int))))
         {
             Marshal.WriteInt32(pData.Ptr, 1);
             // Conciously suppressing errors
             OffRegKey key = null;
             try
             {
                 key = new OffRegKey(this, hive_,
                                     KeyIdentity.Build(identity.BaseKey, subkeys, subkeys.Length - 1), null,
                                     Win32Api.RegOption.REG_OPTION_NON_VOLATILE, IntPtr.Zero,
                                     IntPtr.Zero);
                 key.SetValue(DELETED_PREFIX + subkeys[subkeys.Length - 1],
                              Win32Api.RegValueType.REG_DWORD,
                              pData.Ptr, Marshal.SizeOf(typeof(int)));
             }
             catch (Win32Exception)
             {
                 // Suppressing errors because there might be access issues
                 // or may be other stuff
                 if (key != null)
                 {
                     key.Close();
                 }
             }
         }
     }
     catch (FileNotFoundException)
     {
         // We don't know anything about the key, so we can't mark it as deleted
         return;
     }
 }
Exemple #11
0
        private static bool GetNativeHKeyName(IntPtr hKey, out KeyIdentity identity)
        {
            identity = null;
            uint cbData;
            int  result = Win32Api.NtQueryKey(hKey,
                                              Win32Api.KeyInformationClass.KeyNameInformation,
                                              IntPtr.Zero, 0, out cbData);

            if (result != (int)Win32Api.Status.STATUS_BUFFER_TOO_SMALL)
            {
                DebugLogger.WriteLine("Error querying key name {0}", result);
                return(false);
            }
            using (HGlobalPtr pData = new HGlobalPtr(cbData))
            {
                result = Win32Api.NtQueryKey(hKey,
                                             Win32Api.KeyInformationClass.KeyNameInformation,
                                             pData.Ptr, cbData, out cbData);
                if (result != 0)
                {
                    DebugLogger.WriteLine("Error querying key name {0}", result);
                    return(false);
                }
                cbData = (uint)Marshal.ReadInt32(pData.Ptr);
                string name = Marshal.PtrToStringUni(
                    (IntPtr)(pData.Ptr.ToInt64() + Marshal.SizeOf(typeof(uint))),
                    (int)cbData / sizeof(char));

                foreach (KeyValuePair <string, IntPtr> m in HKeySysNameMappings)
                {
                    if (name.StartsWith(m.Key, StringComparison.CurrentCultureIgnoreCase))
                    {
                        identity = new KeyIdentity(m.Value, RemovePrefix(name, m.Key.Length));
                        return(true);
                    }
                }
                DebugLogger.WriteLine("Can't interpret key name {0}", name);
            }
            return(false);
        }
Exemple #12
0
        internal static bool TryAlterData(IntPtr pdwType, Data dst,
                                          Operation operation, Condition condition, Transformer transformer)
        {
            // We call operation in original way to handle all the cases other
            // than when the altering condition is true
            // But if we call original operation, then we might not know some condition
            // params like data type if user provided null pointers, for instance
            using (HGlobalPtr newpdwType = new HGlobalPtr(Marshal.SizeOf(typeof(uint))),
                   newpcbData = new HGlobalPtr(Marshal.SizeOf(typeof(uint))))
            {
//                Marshal.WriteInt32(newpcbData.Ptr, 0);
                Marshal.WriteInt32(newpcbData.Ptr, -1);
                int result = operation(newpdwType.Ptr, new Data(IntPtr.Zero, newpcbData.Ptr, Data.CountIn.Bytes));
                int type   = Marshal.ReadInt32(newpdwType.Ptr);
                // if pcbData == IntPtr.Zero => pData too - data is not to be read
                if (dst.PCount == IntPtr.Zero || !condition(unchecked ((Win32Api.Error)result),
                                                            unchecked ((Win32Api.RegValueType)type)))
                {
                    return(Win32Exception.CheckIfFoundAndNoError(operation(pdwType, dst)));
                }
                if (pdwType != IntPtr.Zero)
                {
                    Marshal.WriteInt32(pdwType, type);
                }
                using (HGlobalPtr newpData = new HGlobalPtr(Marshal.ReadInt32(newpcbData.Ptr)))
                {
                    // The full value is retrieved even if pData == IntPtr.Zero
                    // because length of new value may depend on the contents of original
                    // one like in path modification feature
                    if (!Win32Exception.CheckIfFoundAndNoError(
                            operation(IntPtr.Zero, new Data(newpData.Ptr, newpcbData.Ptr, Data.CountIn.Bytes))))
                    {
                        return(false);
                    }
                    return(Win32Exception.CheckIfFoundAndNoError(
                               transformer(unchecked ((Win32Api.RegValueType)type),
                                           newpData.Ptr, Marshal.ReadInt32(newpcbData.Ptr))));
                }
            }
        }
Exemple #13
0
        internal static KeyInfo QueryInfo(this IKey key)
        {
            using (HGlobalPtr lpcClass = new HGlobalPtr(Marshal.SizeOf(typeof(int))))
            {
                Marshal.WriteInt32(lpcClass.Ptr, 0);
                try
                {
                    key.QueryInfo(IntPtr.Zero, lpcClass.Ptr, IntPtr.Zero, IntPtr.Zero,
                                  IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero,
                                  IntPtr.Zero, IntPtr.Zero);
                }
                catch (Win32Exception ex)
                {
                    if (ex.ErrorCode != (int)Win32Api.Error.ERROR_MORE_DATA)
                    {
                        throw;
                    }
                }
                int cClass = Marshal.ReadInt32(lpcClass.Ptr) + 1;
                Marshal.WriteInt32(lpcClass.Ptr, cClass);
                using (HGlobalPtr lpClass = new HGlobalPtr(cClass * sizeof(char)),
                       lpReserved = new HGlobalPtr(IntPtr.Zero),
                       lpcSubKeys = new HGlobalPtr(sizeof(int)),
                       lpcMaxSubKeyLen = new HGlobalPtr(sizeof(int)),
                       lpcMaxClassLen = new HGlobalPtr(sizeof(int)),
                       lpcValues = new HGlobalPtr(sizeof(int)),
                       lpcMaxValueNameLen = new HGlobalPtr(sizeof(int)),
                       lpcMaxValueLen = new HGlobalPtr(sizeof(int)),
                       lpcSecurityDescriptor = new HGlobalPtr(sizeof(int)),
                       lpftLastWriteTime = new HGlobalPtr(2 * sizeof(int)))
                {
                    key.QueryInfo(
                        lpClass.Ptr,
                        lpcClass.Ptr,
                        lpReserved.Ptr,
                        lpcSubKeys.Ptr,
                        lpcMaxSubKeyLen.Ptr,
                        lpcMaxClassLen.Ptr,
                        lpcValues.Ptr,
                        lpcMaxValueNameLen.Ptr,
                        lpcMaxValueLen.Ptr,
                        lpcSecurityDescriptor.Ptr,
                        lpftLastWriteTime.Ptr);

                    int classLength = Marshal.ReadInt32(lpcClass.Ptr);
                    Win32Api.FILETIME lastWriteTime =
                        (Win32Api.FILETIME)Marshal.PtrToStructure(lpftLastWriteTime.Ptr,
                                                                  typeof(Win32Api.FILETIME));

                    KeyInfo info;

                    info.Class                    = DataTransformer.PtrToString(lpClass.Ptr, classLength);
                    info.SubKeysNumber            = unchecked ((uint)Marshal.ReadInt32(lpcSubKeys.Ptr));
                    info.MaxSubKeyLength          = unchecked ((uint)Marshal.ReadInt32(lpcMaxSubKeyLen.Ptr));
                    info.MaxClassLength           = unchecked ((uint)Marshal.ReadInt32(lpcMaxClassLen.Ptr));
                    info.ValuesNumber             = unchecked ((uint)Marshal.ReadInt32(lpcValues.Ptr));
                    info.MaxValueNameLength       = unchecked ((uint)Marshal.ReadInt32(lpcMaxValueNameLen.Ptr));
                    info.MaxValueLength           = unchecked ((uint)Marshal.ReadInt32(lpcMaxValueLen.Ptr));
                    info.SecurityDescriptorLength = unchecked ((uint)Marshal.ReadInt32(lpcSecurityDescriptor.Ptr));
                    info.LastWriteTime            = lastWriteTime;

                    return(info);
                }
            }
        }