Example #1
0
 /// <summary>
 /// Set security using a named object.
 /// </summary>
 /// <param name="name">The name of the object.</param>
 /// <param name="type">The type of named object.</param>
 /// <param name="security_information">The security information to set.</param>
 /// <param name="security_descriptor">The security descriptor to set.</param>
 /// <param name="throw_on_error">True to throw on error.</param>
 /// <returns>The NT status code.</returns>
 public static NtStatus SetSecurityInfo(string name, SeObjectType type,
                                        SecurityInformation security_information,
                                        SecurityDescriptor security_descriptor, bool throw_on_error)
 {
     return(Win32NativeMethods.SetNamedSecurityInfo(
                name, type, security_information,
                security_descriptor.Owner?.Sid.ToArray(),
                security_descriptor.Group?.Sid.ToArray(),
                security_descriptor.Dacl?.ToByteArray(),
                security_descriptor.Sacl?.ToByteArray()).ToNtException(throw_on_error));
 }
 /// <summary>
 /// Convert an SDDL SID string to a Sid
 /// </summary>
 /// <param name="sddl">The SDDL SID string</param>
 /// <returns>The converted Sid</returns>
 /// <exception cref="NtException">Thrown if cannot convert from a SDDL string.</exception>
 public static Sid SidFromSddl(string sddl)
 {
     if (!Win32NativeMethods.ConvertStringSidToSid(sddl, out SafeLocalAllocHandle handle))
     {
         throw new NtException(NtStatus.STATUS_INVALID_SID);
     }
     using (handle)
     {
         return(new Sid(handle.DangerousGetHandle()));
     }
 }
Example #3
0
 /// <summary>
 /// Convert an SDDL SID string to a Sid
 /// </summary>
 /// <param name="sddl">The SDDL SID string</param>
 /// <returns>The converted Sid</returns>
 /// <exception cref="NtException">Thrown if cannot convert from a SDDL string.</exception>
 public static Sid SidFromSddl(string sddl)
 {
     if (!Win32NativeMethods.ConvertStringSidToSid(sddl, out SafeLocalAllocHandle handle))
     {
         throw new NtException(NtObjectUtils.MapDosErrorToStatus());
     }
     using (handle)
     {
         return(new Sid(handle.DangerousGetHandle()));
     }
 }
        public static NtResult <SafeRpcBindingHandle> Create(string string_binding, bool throw_on_error)
        {
            var status = Win32NativeMethods.RpcBindingFromStringBinding(string_binding, out SafeRpcBindingHandle binding);

            if (status != Win32Error.SUCCESS)
            {
                return(status.CreateResultFromDosError <SafeRpcBindingHandle>(throw_on_error));
            }
            binding._cracked_binding = new CrackedBindingString(string_binding);
            return(binding.CreateResult());
        }
Example #5
0
        public static SafeRpcBindingHandle Create(string string_binding)
        {
            int status = Win32NativeMethods.RpcBindingFromStringBinding(string_binding, out SafeRpcBindingHandle binding);

            if (status != 0)
            {
                throw new SafeWin32Exception(status);
            }
            binding._cracked_binding = new CrackedBindingString(string_binding);
            return(binding);
        }
Example #6
0
        internal DbgHelpSymbolResolver(NtProcess process, string dbghelp_path, string symbol_path)
        {
            Process      = process.Duplicate();
            _dbghelp_lib = SafeLoadLibraryHandle.LoadLibrary(dbghelp_path);
            GetFunc(ref _sym_init);
            GetFunc(ref _sym_cleanup);
            GetFunc(ref _sym_from_name);
            GetFunc(ref _sym_set_options);
            GetFunc(ref _sym_enum_modules);
            GetFunc(ref _sym_from_addr);
            GetFunc(ref _sym_get_module_info);
            GetFunc(ref _sym_load_module);
            GetFunc(ref _sym_refresh_module_list);
            GetFunc(ref _sym_enum_types);
            GetFunc(ref _sym_get_type_from_name);
            GetFunc(ref _sym_enum_types_by_name);
            GetFunc(ref _sym_get_type_info);
            GetFunc(ref _sym_get_type_info_dword, "SymGetTypeInfo");
            GetFunc(ref _sym_get_type_info_ptr, "SymGetTypeInfo");
            GetFunc(ref _sym_get_type_info_var, "SymGetTypeInfo");
            GetFunc(ref _sym_get_type_info_long, "SymGetTypeInfo");
            GetFunc(ref _sym_from_index);
            GetFunc(ref _sym_enum_symbols);
            GetFunc(ref _sym_set_context);

            _sym_set_options(SymOptions.INCLUDE_32BIT_MODULES | SymOptions.UNDNAME | SymOptions.DEFERRED_LOADS);

            if (!_sym_init(Handle, symbol_path, true))
            {
                // If SymInitialize failed then we'll have to bootstrap modules manually.
                if (!_sym_init(Handle, symbol_path, false))
                {
                    throw new Win32Exception();
                }

                IntPtr[] modules = new IntPtr[1024];
                if (Win32NativeMethods.EnumProcessModulesEx(Handle, modules, modules.Length * IntPtr.Size, out int return_length,
                                                            process.Is64Bit ? EnumProcessModulesFilter.LIST_MODULES_64BIT : EnumProcessModulesFilter.LIST_MODULES_32BIT))
                {
                    foreach (IntPtr module in modules.Take(return_length / IntPtr.Size))
                    {
                        StringBuilder dllpath = new StringBuilder(260);
                        if (Win32NativeMethods.GetModuleFileNameEx(Handle, module, dllpath, dllpath.Capacity) > 0)
                        {
                            if (_sym_load_module(Handle, IntPtr.Zero, dllpath.ToString(),
                                                 Path.GetFileNameWithoutExtension(dllpath.ToString()), module.ToInt64(), GetImageSize(module)) == 0)
                            {
                                System.Diagnostics.Debug.WriteLine($"Couldn't load {dllpath}");
                            }
                        }
                    }
                }
            }
        }
Example #7
0
        /// <summary>
        /// Convert a security descriptor to SDDL string
        /// </summary>
        /// <param name="sd">The security descriptor</param>
        /// <param name="security_information">Indicates what parts of the security descriptor to include</param>
        /// <returns>The SDDL string</returns>
        /// <exception cref="NtException">Thrown if cannot convert to a SDDL string.</exception>
        public static string SecurityDescriptorToSddl(byte[] sd, SecurityInformation security_information)
        {
            if (!Win32NativeMethods.ConvertSecurityDescriptorToStringSecurityDescriptor(sd,
                                                                                        1, security_information, out SafeLocalAllocHandle handle, out int return_length))
            {
                throw new NtException(NtObjectUtils.MapDosErrorToStatus());
            }

            using (handle)
            {
                return(Marshal.PtrToStringUni(handle.DangerousGetHandle()));
            }
        }
Example #8
0
 static void FreeMemoryAtEndOfPager(byte *adjacentBlockAddress)
 {
     if (adjacentBlockAddress == null || adjacentBlockAddress == (byte *)0)
     {
         return;
     }
     if (StorageEnvironmentOptions.RunningOnPosix)
     {
         Syscall.munmap(new IntPtr(adjacentBlockAddress), 16);
         return;
     }
     Win32NativeMethods.VirtualFree(adjacentBlockAddress, UIntPtr.Zero, Win32NativeMethods.FreeType.MEM_RELEASE);
 }
 public override string ToString()
 {
     if (!IsInvalid && !IsClosed)
     {
         if (Win32NativeMethods.RpcBindingToStringBinding(handle, out SafeRpcStringHandle str) == 0)
         {
             using (str)
             {
                 return(str.ToString());
             }
         }
     }
     return(string.Empty);
 }
Example #10
0
        private void LoadLibraries()
        {
            string destDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "FfmpegNativeLibraries");

            Win32NativeMethods.LoadLibrary(Path.Combine(destDirectory, "avutil-51.dll"));
            Win32NativeMethods.LoadLibrary(Path.Combine(destDirectory, "avcodec-53.dll"));
            Win32NativeMethods.LoadLibrary(Path.Combine(destDirectory, "avformat-53.dll"));

            Win32NativeMethods.LoadLibrary(Path.Combine(destDirectory, "swresample-0.dll"));
            Win32NativeMethods.LoadLibrary(Path.Combine(destDirectory, "swscale-2.dll"));
            Win32NativeMethods.LoadLibrary(Path.Combine(destDirectory, "avfilter-2.dll"));
            Win32NativeMethods.LoadLibrary(Path.Combine(destDirectory, "avdevice-53.dll"));
            Win32NativeMethods.LoadLibrary(Path.Combine(destDirectory, "postproc-52.dll"));



            //a = Win32NativeMethods.LoadLibrary(Path.Combine(destDirectory, "Aforge.Video.dll"));
            //a = Win32NativeMethods.LoadLibrary(Path.Combine(destDirectory, "Aforge.Video.FFMPEG.dll"));

            //Assembly assemblyVideo = Assembly.LoadFrom(Path.Combine(destDirectory, "AForge.Video.dll"));

            /*Assembly assemblyFfmpeg = Assembly.LoadFrom(Path.Combine(destDirectory, "AForge.Video.FFMPEG.dll"));
             *
             * Type vw = assemblyFfmpeg.GetType("AForge.Video.FFMPEG.VideoFileWriter");
             * Type codec = assemblyFfmpeg.GetType("AForge.Video.FFMPEG.VideoCodec");
             * var aa = codec.GetProperties();
             *
             *
             * var cc = codec.GetEnumValues();
             * foreach ( var c in cc) {
             *  var ff = c;
             * }
             *
             * var ccc = codec.GetField("MPEG4");
             *
             * //var c = vw.GetConstructor(new Type[] { }).Invoke(new object[]{});
             * object obj = Activator.CreateInstance(vw);
             * var methods = vw.GetMethods();
             * var bb = codec.GetField("MPEG4").GetValue(obj);
             *
             * PropertyInfo[] myFields = vw.GetProperties(BindingFlags.Public | BindingFlags.Instance);
             * foreach (var g in myFields)
             * {
             *  if (g.GetIndexParameters().Length == 0)
             *  {
             *      string name = g.Name;
             *      var s = g.GetValue(obj, null);
             *  }
             * }*/
        }
        public static NtResult <SafeRpcBindingHandle> Create(string objuuid, string protseq, string networkaddr, string endpoint, string options, bool throw_on_error)
        {
            var status = Win32NativeMethods.RpcStringBindingCompose(objuuid, protseq,
                                                                    networkaddr, endpoint, options, out SafeRpcStringHandle binding);

            if (status != Win32Error.SUCCESS)
            {
                return(status.CreateResultFromDosError <SafeRpcBindingHandle>(throw_on_error));
            }
            using (binding)
            {
                return(Create(binding.ToString(), throw_on_error));
            }
        }
        /// <summary>
        /// Get the Win32 services for the SCM.
        /// </summary>
        /// <param name="service_state">The state of the services to return.</param>
        /// <param name="service_types">The types of services to return.</param>
        /// <param name="throw_on_error">True throw on error.</param>
        /// <returns>The list of services.</returns>
        /// <remarks>SCM must have been opened with EnumerateService access.</remarks>
        public NtResult <IEnumerable <Win32Service> > GetServices(ServiceState service_state, ServiceType service_types, bool throw_on_error)
        {
            SERVICE_STATE state;

            switch (service_state)
            {
            case ServiceState.All:
                state = SERVICE_STATE.SERVICE_STATE_ALL;
                break;

            case ServiceState.Active:
                state = SERVICE_STATE.SERVICE_ACTIVE;
                break;

            case ServiceState.InActive:
                state = SERVICE_STATE.SERVICE_INACTIVE;
                break;

            default:
                throw new ArgumentException("Invalid service state", nameof(service_state));
            }

            List <Win32Service> ret_services = new List <Win32Service>();
            const int           Length       = 32 * 1024;

            using (var buffer = new SafeHGlobalBuffer(Length))
            {
                int resume_handle = 0;
                while (true)
                {
                    bool ret = Win32NativeMethods.EnumServicesStatusEx(_handle, SC_ENUM_TYPE.SC_ENUM_PROCESS_INFO,
                                                                       service_types, state, buffer, buffer.Length, out int bytes_needed, out int services_returned,
                                                                       ref resume_handle, null);
                    Win32Error error = Win32Utils.GetLastWin32Error();
                    if (!ret && error != Win32Error.ERROR_MORE_DATA)
                    {
                        return(error.CreateResultFromDosError <IEnumerable <Win32Service> >(throw_on_error));
                    }

                    ENUM_SERVICE_STATUS_PROCESS[] services = new ENUM_SERVICE_STATUS_PROCESS[services_returned];
                    buffer.ReadArray(0, services, 0, services_returned);
                    ret_services.AddRange(services.Select(s => new Win32Service(_machine_name, s)));
                    if (ret)
                    {
                        break;
                    }
                }
            }
            return(ret_services.CreateResult().Cast <IEnumerable <Win32Service> >());
        }
Example #13
0
        public static SafeRpcBindingHandle Create(string objuuid, string protseq, string networkaddr, string endpoint, string options)
        {
            int status = Win32NativeMethods.RpcStringBindingCompose(objuuid, protseq,
                                                                    networkaddr, endpoint, options, out SafeRpcStringHandle binding);

            if (status != 0)
            {
                throw new SafeWin32Exception(status);
            }
            using (binding)
            {
                return(Create(binding.ToString()));
            }
        }
Example #14
0
        /// <summary>
        /// Convert an SDDL string to a binary security descriptor
        /// </summary>
        /// <param name="sddl">The SDDL string</param>
        /// <returns>The binary security descriptor</returns>
        /// <exception cref="NtException">Thrown if cannot convert from a SDDL string.</exception>
        public static byte[] SddlToSecurityDescriptor(string sddl)
        {
            if (!Win32NativeMethods.ConvertStringSecurityDescriptorToSecurityDescriptor(sddl, 1,
                                                                                        out SafeLocalAllocHandle handle, out int return_length))
            {
                throw new NtException(NtObjectUtils.MapDosErrorToStatus());
            }

            using (handle)
            {
                byte[] ret = new byte[return_length];
                Marshal.Copy(handle.DangerousGetHandle(), ret, 0, return_length);
                return(ret);
            }
        }
Example #15
0
 private void LoadLibrary()
 {
     lock (_criticalSection)
     {
         if (_dllHandle.Equals(IntPtr.Zero))
         {
             var dllPath = IntPtr.Size == 8 ? DllLocation64Bit : DllLocation32Bit;
             _dllHandle = Win32NativeMethods.LoadLibraryW(dllPath);
             if (_dllHandle.Equals(IntPtr.Zero))
             {
                 throw new Exception(string.Format("Could not load '{0}'\nMake sure the dll exists.", dllPath));
             }
         }
     }
 }
Example #16
0
        /// <summary>
        /// Convert an SDDL string to a binary security descriptor
        /// </summary>
        /// <param name="sddl">The SDDL string</param>
        /// <param name="throw_on_error">True to throw on error.</param>
        /// <returns>The binary security descriptor</returns>
        /// <exception cref="NtException">Thrown if cannot convert from a SDDL string.</exception>
        public static NtResult <byte[]> SddlToSecurityDescriptor(string sddl, bool throw_on_error)
        {
            if (!Win32NativeMethods.ConvertStringSecurityDescriptorToSecurityDescriptor(sddl, 1,
                                                                                        out SafeLocalAllocHandle handle, out int return_length))
            {
                return(NtObjectUtils.MapDosErrorToStatus().CreateResultFromError <byte[]>(throw_on_error));
            }

            using (handle)
            {
                byte[] ret = new byte[return_length];
                Marshal.Copy(handle.DangerousGetHandle(), ret, 0, return_length);
                return(ret.CreateResult());
            }
        }
Example #17
0
 byte *AllocateMemoryAtEndOfPager(long totalAllocationSize)
 {
     if (StorageEnvironmentOptions.RunningOnPosix)
     {
         var p = Syscall.mmap(new IntPtr(Env.Options.DataPager.PagerState.MapBase + totalAllocationSize), 16,
                              MmapProts.PROT_READ | MmapProts.PROT_WRITE, MmapFlags.MAP_ANONYMOUS, -1, 0);
         if (p.ToInt64() == -1)
         {
             return(null);
         }
         return((byte *)p.ToPointer());
     }
     return(Win32NativeMethods.VirtualAlloc(Env.Options.DataPager.PagerState.MapBase + totalAllocationSize, new UIntPtr(16),
                                            Win32NativeMethods.AllocationType.RESERVE, Win32NativeMethods.MemoryProtection.EXECUTE_READWRITE));
 }
        internal /*int*/ IntPtr Subscribe(int hookId, HookCallback hookCallback)
        {
            /*int*/ IntPtr hookHandle = Win32NativeMethods.SetWindowsHookEx(
                hookId,
                hookCallback,
                Process.GetCurrentProcess().MainModule.BaseAddress,
                0);

            if (hookHandle == IntPtr.Zero)
            {
                ThrowLastUnmanagedErrorAsException();
            }

            return(hookHandle);
        }
        internal NtResult <SecurityDescriptor> GetSecurityDescriptor(
            string type_name, SecurityInformation security_information, bool throw_on_error)
        {
            security_information &= DEFAULT_SECURITY_INFORMATION;

            if (IsInvalid || IsClosed)
            {
                return(NtStatus.STATUS_INVALID_HANDLE.CreateResultFromError <SecurityDescriptor>(throw_on_error));
            }

            byte[] sd = new byte[8192];
            return(Win32NativeMethods.QueryServiceObjectSecurity(this, security_information,
                                                                 sd, sd.Length, out _).CreateWin32Result(throw_on_error,
                                                                                                         () => new SecurityDescriptor(sd, NtType.GetTypeByName(type_name))));
        }
Example #20
0
 // protected int HookCallback(int nCode, Int32 wParam, IntPtr lParam)
 protected int HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
 {
     if (nCode >= 0)
     {
         //send input to other machine
         if (ProcessCallback(wParam, lParam) == false)
         {
             throw new Exception("Couldn't process the correct keyboard input");
         }
         if (blockLocalInput)
         {
             return(-1);
         }
     }
     return(Win32NativeMethods.CallNextHookEx(HookHandle, nCode, wParam, lParam));
 }
        /// <summary>
        /// Get the source of inherited ACEs.
        /// </summary>
        /// <param name="name">The name of the resource.</param>
        /// <param name="type">The type of the resource.</param>
        /// <param name="container">Whether the resource is a container.</param>
        /// <param name="object_types">Optional list of object types.</param>
        /// <param name="security_descriptor">The security descriptor for the resource.</param>
        /// <param name="sacl">True to check the SACL otherwise checks the DACL.</param>
        /// <param name="generic_mapping">Generic mapping for the resource.</param>
        /// <param name="query_security">Query security descriptors for sources.</param>
        /// <param name="throw_on_error">True to throw on error.</param>
        /// <returns>The list of inheritance sources.</returns>
        public static NtResult <IEnumerable <SecurityDescriptorInheritanceSource> > GetInheritanceSource(
            string name,
            SeObjectType type,
            bool container,
            Guid[] object_types,
            SecurityDescriptor security_descriptor,
            bool sacl,
            GenericMapping generic_mapping,
            bool query_security,
            bool throw_on_error)
        {
            Acl acl = sacl ? security_descriptor.Sacl : security_descriptor.Dacl;

            if (acl == null || acl.NullAcl)
            {
                return(NtStatus.STATUS_INVALID_ACL.CreateResultFromError <IEnumerable <SecurityDescriptorInheritanceSource> >(throw_on_error));
            }

            using (var list = new DisposableList())
            {
                SafeGuidArrayBuffer guids = SafeGuidArrayBuffer.Null;
                if (object_types?.Length > 0)
                {
                    guids = list.AddResource(new SafeGuidArrayBuffer(object_types));
                }

                NtType native_type = GetNativeType(type);

                INHERITED_FROM[] inherited_from = new INHERITED_FROM[acl.Count];
                NtStatus         status         = NtStatus.STATUS_INVALID_PARAMETER;
                try
                {
                    status = Win32NativeMethods.GetInheritanceSource(name, type, sacl ? SecurityInformation.Sacl : SecurityInformation.Dacl,
                                                                     container, guids, guids.Count, acl.ToByteArray(), IntPtr.Zero, ref generic_mapping, inherited_from).MapDosErrorToStatus();
                    return(status.CreateResult(throw_on_error, () => (IEnumerable <SecurityDescriptorInheritanceSource>)inherited_from
                                               .Select((s, i) => new SecurityDescriptorInheritanceSource(acl[i], s, type,
                                                                                                         native_type, container, query_security, sacl)).Where(s => s.Depth != -1).ToArray()));
                }
                finally
                {
                    if (status.IsSuccess())
                    {
                        Win32NativeMethods.FreeInheritedFromArray(inherited_from, (ushort)inherited_from.Length, IntPtr.Zero);
                    }
                }
            }
        }
Example #22
0
        /// <summary>
        /// Query ELAM information from a driver's resource section.
        /// </summary>
        /// <param name="path">The path to the file.</param>
        /// <param name="throw_on_error">True to throw on error.</param>
        /// <returns>The ELAM information if present.</returns>
        public static NtResult <IReadOnlyList <ElamInformation> > GetElamInformation(string path, bool throw_on_error)
        {
            using (var lib = SafeLoadLibraryHandle.LoadLibrary(path, LoadLibraryFlags.LoadLibraryAsDataFile, throw_on_error))
            {
                if (!lib.IsSuccess)
                {
                    return(lib.Cast <IReadOnlyList <ElamInformation> >());
                }
                var ptr = Win32NativeMethods.FindResource(lib.Result, "MicrosoftElamCertificateInfo", "MSElamCertInfoID");
                if (ptr == IntPtr.Zero)
                {
                    return(Win32Utils.GetLastWin32Error().CreateResultFromDosError <IReadOnlyList <ElamInformation> >(throw_on_error));
                }

                IntPtr hResource = Win32NativeMethods.LoadResource(lib.Result, ptr);
                IntPtr buf       = Win32NativeMethods.LockResource(hResource);
                int    size      = Win32NativeMethods.SizeofResource(lib.Result, ptr);

                if (size <= 0)
                {
                    return(NtStatus.STATUS_INVALID_BUFFER_SIZE.CreateResultFromError <IReadOnlyList <ElamInformation> >(throw_on_error));
                }

                byte[] elam_info = new byte[size];

                Marshal.Copy(buf, elam_info, 0, size);
                MemoryStream stm    = new MemoryStream(elam_info);
                BinaryReader reader = new BinaryReader(stm, Encoding.Unicode);
                try
                {
                    List <ElamInformation> ret = new List <ElamInformation>();
                    int count = reader.ReadUInt16();
                    for (int i = 0; i < count; ++i)
                    {
                        string        cert_hash = reader.ReadNulTerminated();
                        HashAlgorithm algorithm = (HashAlgorithm)reader.ReadUInt16();
                        string[]      ekus      = reader.ReadNulTerminated().Split(';');
                        ret.Add(new ElamInformation(cert_hash, algorithm, ekus));
                    }
                    return(ret.AsReadOnly().CreateResult().Cast <IReadOnlyList <ElamInformation> >());
                }
                catch (EndOfStreamException)
                {
                    return(NtStatus.STATUS_END_OF_FILE.CreateResultFromError <IReadOnlyList <ElamInformation> >(throw_on_error));
                }
            }
        }
Example #23
0
        private string GetSymbolName(long module_base, int type_index)
        {
            IntPtr ptr = IntPtr.Zero;

            try {
                if (!_sym_get_type_info_ptr(Handle, module_base, type_index, IMAGEHLP_SYMBOL_TYPE_INFO.TI_GET_SYMNAME, out ptr))
                {
                    return(string.Empty);
                }
                return(Marshal.PtrToStringUni(ptr));
            } finally {
                if (ptr != IntPtr.Zero)
                {
                    Win32NativeMethods.LocalFree(ptr);
                }
            }
        }
Example #24
0
        public void WhenInitialFileSizeIsNotSetTheFileSizeForDataFileAndScratchFileShouldBeSetToSystemAllocationGranularity()
        {
            Win32NativeMethods.SYSTEM_INFO systemInfo;
            Win32NativeMethods.GetSystemInfo(out systemInfo);

            var options = StorageEnvironmentOptions.ForPath(path);

            options.InitialFileSize = null;

            using (new StorageEnvironment(options))
            {
                var dataFile    = Path.Combine(path, Constants.DatabaseFilename);
                var scratchFile = Path.Combine(path, StorageEnvironmentOptions.ScratchBufferName(0));

                Assert.Equal(systemInfo.allocationGranularity, new FileInfo(dataFile).Length);
                Assert.Equal(systemInfo.allocationGranularity, new FileInfo(scratchFile).Length);
            }
        }
Example #25
0
        public void WhenInitialFileSizeIsSetTheFileSizeForDataFileAndScratchFileShouldBeSetAccordinglyAndItWillBeRoundedToTheNearestGranularity()
        {
            Win32NativeMethods.SYSTEM_INFO systemInfo;
            Win32NativeMethods.GetSystemInfo(out systemInfo);

            var options = StorageEnvironmentOptions.ForPath(path);

            options.InitialFileSize = systemInfo.allocationGranularity * 2 + 1;

            using (new StorageEnvironment(options))
            {
                var dataFile    = Path.Combine(path, Constants.DatabaseFilename);
                var scratchFile = Path.Combine(path, "scratch.buffers");

                Assert.Equal(systemInfo.allocationGranularity * 3, new FileInfo(dataFile).Length);
                Assert.Equal(systemInfo.allocationGranularity * 3, new FileInfo(scratchFile).Length);
            }
        }
Example #26
0
        public static string PtrToStringUTF8(IntPtr ptr)
        {
            if (ptr == IntPtr.Zero)
            {
                return(null);
            }

            int nb = Win32NativeMethods.lstrlenA(ptr);

            if (nb == 0)
            {
                return(null);
            }

            byte[] buffer = new byte[nb];
            Marshal.Copy(ptr, buffer, 0, buffer.Length);
            return(Encoding.UTF8.GetString(buffer));
        }
        /// <summary>
        /// Get the security descriptor for a named resource.
        /// </summary>
        /// <param name="name">The name of the resource.</param>
        /// <param name="type">The type of the resource.</param>
        /// <param name="security_information">The security information to get.</param>
        /// <param name="throw_on_error">True to throw on error.</param>
        /// <returns>The security descriptor.</returns>
        public static NtResult <SecurityDescriptor> GetSecurityInfo(
            string name,
            SeObjectType type,
            SecurityInformation security_information,
            bool throw_on_error)
        {
            using (var result = Win32NativeMethods.GetNamedSecurityInfo(name, type,
                                                                        security_information, null,
                                                                        null, null, null, out SafeLocalAllocBuffer sd).MapDosErrorToStatus().CreateResult(throw_on_error, () => sd))
            {
                if (!result.IsSuccess)
                {
                    return(result.Cast <SecurityDescriptor>());
                }

                return(SecurityDescriptor.Parse(result.Result, GetNativeType(type), throw_on_error));
            }
        }
Example #28
0
        /// <summary>
        /// Lookup a privilege display name.
        /// </summary>
        /// <param name="system_name">The system name to do the lookup on.</param>
        /// <param name="privilege_name">The privilege name.</param>
        /// <returns>The display name. Empty string on error.</returns>
        public static string LookupPrivilegeDisplayName(string system_name, string privilege_name)
        {
            int name_length = 0;

            Win32NativeMethods.LookupPrivilegeDisplayName(system_name, privilege_name, null, ref name_length, out int lang_id);
            if (name_length <= 0)
            {
                return(string.Empty);
            }

            StringBuilder builder = new StringBuilder(name_length + 1);

            name_length = builder.Capacity;
            if (Win32NativeMethods.LookupPrivilegeDisplayName(system_name, privilege_name, builder, ref name_length, out lang_id))
            {
                return(builder.ToString());
            }
            return(string.Empty);
        }
        /// <summary>
        /// Open an instance of the SCM.
        /// </summary>
        /// <param name="machine_name">The machine name for the SCM.</param>
        /// <param name="database_name">The database name. Specify SERVICES_ACTIVE_DATABASE or SERVICES_FAILED_DATABASE.
        /// If null then SERVICES_ACTIVE_DATABASE is used.</param>
        /// <param name="desired_access">The desired access for the SCM connection.</param>
        /// <param name="throw_on_error">True to throw on error.</param>
        /// <returns>The SCM instance.</returns>
        public static NtResult <ServiceControlManager> Open(string machine_name, string database_name,
                                                            ServiceControlManagerAccessRights desired_access, bool throw_on_error)
        {
            if (machine_name == string.Empty)
            {
                machine_name = null;
            }
            if (database_name == string.Empty)
            {
                database_name = null;
            }
            SafeServiceHandle scm = Win32NativeMethods.OpenSCManager(machine_name, database_name, desired_access);

            if (!scm.IsInvalid)
            {
                return(new ServiceControlManager(scm, machine_name, desired_access).CreateResult());
            }
            return(Win32Utils.CreateResultFromDosError <ServiceControlManager>(throw_on_error));
        }
Example #30
0
        private IntPtr GetWindowHandleFromPoint(int xPoint, int yPoint)
        {
            var handle = Win32NativeMethods.WindowFromPoint(xPoint, yPoint);

            if (IsInterestingWindow(handle))
            {
                return(handle);
            }
            var parentHandle = Win32NativeMethods.GetParent(handle);

            while (parentHandle != IntPtr.Zero)
            {
                if (IsInterestingWindow(parentHandle))
                {
                    return(parentHandle);
                }
                parentHandle = Win32NativeMethods.GetParent(parentHandle);
            }
            return(IntPtr.Zero);
        }