Пример #1
0
        private IntPtr GetParentWindow(CoreUIParent uiParent)
        {
#if WINDOWS_APP
            // On UWP there is no need for a window handle
            return(IntPtr.Zero);
#endif

#if DESKTOP || NET5_WIN // net core doesn't reference WinForms
            if (uiParent?.OwnerWindow is IWin32Window window)
            {
                _logger.Info("[WAM Broker] Owner window specified as IWin32Window.");
                return(window.Handle);
            }
#endif

#if DESKTOP || NET5_WIN || NET_CORE
            if (uiParent?.OwnerWindow is IntPtr ptr)
            {
                _logger.Info("[WAM Broker] Owner window specified as IntPtr.");
                return(ptr);
            }

            // other MSALs prefer to default to GetForegroundWindow() but this causes issues
            // for example if the user quickly switches windows.
            // GetDesktopWindow will make the default more consistent with the embedded browser
            _logger.Info("[WAM Broker] Using desktop as a parent window.");
            IntPtr desktopWindow = WindowsNativeMethods.GetDesktopWindow();
            return(desktopWindow);
#endif
        }
Пример #2
0
        /// <summary>
        /// Account Picker APIs do not work well with console apps because the console
        /// window belongs to a different process, which causes a security exception.
        /// In general, if the parent window handle does not belong to the current process,
        /// we need to take control over the window handle by injecting a splash screen.
        /// </summary>
        private bool UseSplashScreen()
        {
            WindowsNativeMethods.GetWindowThreadProcessId(_parentHandle, out uint windowProcessId);
            uint appProcessId = WindowsNativeMethods.GetCurrentProcessId();

            return(appProcessId != windowProcessId);
        }
Пример #3
0
            public static IDisposable Create(string cloudName, string refreshToken)
            {
                var target            = $"VS Code Azure/{cloudName}";
                var credentialBlobPtr = Marshal.StringToHGlobalAnsi(refreshToken);

                var credentialData = new WindowsNativeMethods.CredentialData
                {
                    AttributeCount     = 0,
                    Attributes         = IntPtr.Zero,
                    Comment            = null,
                    CredentialBlob     = credentialBlobPtr,
                    CredentialBlobSize = (uint)refreshToken.Length,
                    Flags       = 0,
                    Persist     = WindowsNativeMethods.CRED_PERSIST.CRED_PERSIST_LOCAL_MACHINE,
                    TargetAlias = null,
                    TargetName  = $"{ExpectedServiceName}/{cloudName}",
                    Type        = WindowsNativeMethods.CRED_TYPE.GENERIC,
                    UserName    = "******"
                };

                var credentialDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(credentialData));

                try
                {
                    Marshal.StructureToPtr(credentialData, credentialDataPtr, false);
                    WindowsNativeMethods.CredWrite(credentialDataPtr);
                    return(new WindowsRefreshTokenFixture(target));
                }
                finally
                {
                    Marshal.FreeHGlobal(credentialDataPtr);
                    Marshal.FreeHGlobal(credentialBlobPtr);
                }
            }
        private IntPtr GetParentWindow(CoreUIParent uiParent)
        {
#if WINDOWS_APP
            // On UWP there is no need for a window handle
            return(IntPtr.Zero);
#endif

#if DESKTOP || NET5_WIN // net core doesn't reference WinForms
            if (uiParent?.OwnerWindow is IWin32Window window)
            {
                _logger.Info("Owner window specified as IWin32Window.");
                return(window.Handle);
            }
#endif

#if DESKTOP || NET5_WIN || NET_CORE
            if (uiParent?.OwnerWindow is IntPtr ptr)
            {
                _logger.Info("Owner window specified as IntPtr.");
                return(ptr);
            }

            IntPtr foregroundWindow = WindowsNativeMethods.GetForegroundWindow();
            return(foregroundWindow);
#endif
        }
        public void SendCommandMessage(TASKDIALOG_MESSAGES message, IntPtr wParam, IntPtr lParam)
        {
            if (this.WindowHandle == IntPtr.Zero)
            {
                throw new InvalidOperationException("windowHandle == null");
            }

            WindowsNativeMethods.SendMessage(this.WindowHandle, (uint)message, wParam, lParam);
        }
Пример #6
0
        /// <summary>
        /// Account Picker APIs do not work well with console apps because the console
        /// window belongs to a different process, which causes a security exception.
        /// In general, if the parent window handle does not belong to the current process,
        /// we need to take control over the window handle by injecting a splash screen.
        /// </summary>
        private bool UseSplashScreen()
        {
            if (_synchronizationContext == null)
            {
                return(true);
            }

            WindowsNativeMethods.GetWindowThreadProcessId(_parentHandle, out uint windowProcessId);
            uint appProcessId = WindowsNativeMethods.GetCurrentProcessId();

            return(appProcessId != windowProcessId);
        }
Пример #7
0
 private static void SendStopMessageToProcess(int pid)
 {
     for (var ptr = WindowsNativeMethods.GetTopWindow(IntPtr.Zero); ptr != IntPtr.Zero; ptr = WindowsNativeMethods.GetWindow(ptr, 2))
     {
         uint num;
         WindowsNativeMethods.GetWindowThreadProcessId(ptr, out num);
         if (pid == num)
         {
             var hWnd = new HandleRef(null, ptr);
             WindowsNativeMethods.PostMessage(hWnd, 0x12, IntPtr.Zero, IntPtr.Zero);
             return;
         }
     }
 }
Пример #8
0
 private void TriggerCrash(int pid)
 {
     try
     {
         Logger.LogInformation($"Trying to crash the process {pid}");
         var process = Process.GetProcessById(pid);
         // Calling CreateRemoteThread as 0x1 as thread function pointer should cause a crash
         WindowsNativeMethods.CreateRemoteThread(process.Handle, IntPtr.Zero, 0, (IntPtr)1, IntPtr.Zero, 0, IntPtr.Zero);
     }
     catch (Exception e)
     {
         Logger.LogInformation(e, "Exception while trying to crash the process");
     }
 }
Пример #9
0
 public static void CreateHardLink(string oldFileName,
                                   string newFileName)
 {
     if (OperatingSystem.IsWindows())
     {
         WindowsNativeMethods.CreateHardLink(oldFileName, newFileName);
     }
     else if (OperatingSystem.IsLinux())
     {
         LinuxNativeMethods.CreateHardLink(oldFileName, newFileName);
     }
     else
     {
         throw new PlatformNotSupportedException();
     }
 }
 private void SendStopMessageToProcess(int pid)
 {
     Logger.LogInformation($"Sending shutdown request to {pid}");
     for (var ptr = WindowsNativeMethods.GetTopWindow(IntPtr.Zero); ptr != IntPtr.Zero; ptr = WindowsNativeMethods.GetWindow(ptr, 2))
     {
         WindowsNativeMethods.GetWindowThreadProcessId(ptr, out var windowProcessId);
         if (pid == windowProcessId)
         {
             var hWnd = new HandleRef(null, ptr);
             if (!WindowsNativeMethods.PostMessage(hWnd, 0x12, IntPtr.Zero, IntPtr.Zero))
             {
                 throw new InvalidOperationException($"Unable to PostMessage to process {pid}. LastError: {Marshal.GetLastWin32Error()}");
             }
             return;
         }
     }
     throw new InvalidOperationException($"Unable to find main window for process {pid}");
 }
Пример #11
0
        public static void RegisterLibrariesSearchPath(string path)
        {
            path = Environment.ExpandEnvironmentVariables(path);

            switch (Environment.OSVersion.Platform)
            {
            case PlatformID.Win32NT:
            case PlatformID.Win32S:
            case PlatformID.Win32Windows:
                WindowsNativeMethods.SetDllDirectory(path);
                break;

            case PlatformID.Unix:
            case PlatformID.MacOSX:
                var currentValue = Environment.GetEnvironmentVariable(LD_LIBRARY_PATH) ?? string.Empty;
                var newValue     = string.IsNullOrEmpty(currentValue) ? path : currentValue + Path.PathSeparator + path;
                Environment.SetEnvironmentVariable(LD_LIBRARY_PATH, newValue);
                break;
            }
        }
Пример #12
0
        private void SendStopMessageToProcess(int pid)
        {
            Logger.LogInformation($"Sending shutdown request to {pid}");
            var found = false;

            WindowsNativeMethods.EnumWindows((ptr, param) => {
                WindowsNativeMethods.GetWindowThreadProcessId(ptr, out var windowProcessId);
                if (pid == windowProcessId)
                {
                    // 256 is the max length
                    var className = new StringBuilder(256);

                    if (WindowsNativeMethods.GetClassName(ptr, className, className.Capacity) == 0)
                    {
                        throw new InvalidOperationException($"Unable to get window class name: {Marshal.GetLastWin32Error()}");
                    }

                    if (!string.Equals(className.ToString(), "IISEXPRESS", StringComparison.OrdinalIgnoreCase))
                    {
                        // skip windows without IISEXPRESS class
                        return(true);
                    }

                    var hWnd = new HandleRef(null, ptr);
                    if (!WindowsNativeMethods.PostMessage(hWnd, 0x12, IntPtr.Zero, IntPtr.Zero))
                    {
                        throw new InvalidOperationException($"Unable to PostMessage to process {pid}. LastError: {Marshal.GetLastWin32Error()}");
                    }

                    found = true;
                    return(false);
                }

                return(true);
            }, IntPtr.Zero);

            if (!found)
            {
                throw new InvalidOperationException($"Unable to find main window for process {pid}");
            }
        }
Пример #13
0
        private IntPtr GetParentWindow(CoreUIParent uiParent)
        {
#if WINDOWS_APP
            // On UWP there is no need for a window handle
            return(IntPtr.Zero);
#else
            if (uiParent?.OwnerWindow is IntPtr ptr)
            {
                _logger.Info("Owner window specified as IntPtr.");
                return(ptr);
            }

            if (uiParent?.OwnerWindow is IWin32Window window)
            {
                _logger.Info("Owner window specified as IWin32Window.");
                return(window.Handle);
            }

            return(WindowsNativeMethods.GetForegroundWindow());
#endif
        }
Пример #14
0
        private void SendStopMessageToProcess(int pid)
        {
            var found        = false;
            var extraLogging = false;
            var retryCount   = 5;

            while (!found && retryCount > 0)
            {
                Logger.LogInformation($"Sending shutdown request to {pid}");

                WindowsNativeMethods.EnumWindows((ptr, param) => {
                    WindowsNativeMethods.GetWindowThreadProcessId(ptr, out var windowProcessId);
                    if (extraLogging)
                    {
                        Logger.LogDebug($"EnumWindow returned {ptr} belonging to {windowProcessId}");
                    }

                    if (pid == windowProcessId)
                    {
                        // 256 is the max length
                        var className = new StringBuilder(256);

                        if (WindowsNativeMethods.GetClassName(ptr, className, className.Capacity) == 0)
                        {
                            throw new InvalidOperationException($"Unable to get window class name: {Marshal.GetLastWin32Error()}");
                        }

                        if (!string.Equals(className.ToString(), "IISEXPRESS", StringComparison.OrdinalIgnoreCase))
                        {
                            Logger.LogDebug($"Skipping window {ptr} with class name {className}");
                            // skip windows without IISEXPRESS class
                            return(true);
                        }

                        var hWnd = new HandleRef(null, ptr);
                        if (!WindowsNativeMethods.PostMessage(hWnd, 0x12, IntPtr.Zero, IntPtr.Zero))
                        {
                            throw new InvalidOperationException($"Unable to PostMessage to process {pid}. LastError: {Marshal.GetLastWin32Error()}");
                        }

                        found = true;
                        return(false);
                    }

                    return(true);
                }, IntPtr.Zero);

                if (!found)
                {
                    Thread.Sleep(100);
                }

                // Add extra logging if first try was unsuccessful
                extraLogging = true;
                retryCount--;
            }

            if (!found)
            {
                throw new InvalidOperationException($"Unable to find main window for process {pid}");
            }
        }
Пример #15
0
 public void Dispose() => WindowsNativeMethods.CredDelete(_target, WindowsNativeMethods.CRED_TYPE.GENERIC);
    public static Int32 Main(String[] args)
    {
        if (args.Length == 0)
        {
            Console.WriteLine("Usage: ClrLibRunner.exe <NativeSharedLibrary> <Args>...");
            return(1);
        }
        String sharedLibrary = args[0];

        // TODO: might want to make this a command-line option (--dlopen or --loadlibrary)?
        // TODO: need a way to detect whether or not this mechanism is supported
        //       maybe I should use runtime reflection?
        //bool onWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
        bool onWindows = Directory.Exists("C:\\Windows\\System32");

        EntryDelegate entry;

        if (onWindows)
        {
            IntPtr moduleHandle = WindowsNativeMethods.LoadLibrary(sharedLibrary);
            if (moduleHandle == IntPtr.Zero)
            {
                Console.WriteLine("Error: LoadLibrary '{0}' failed: {1}", sharedLibrary, Marshal.GetLastWin32Error());
                return(1);
            }
            IntPtr funcPtr = WindowsNativeMethods.GetProcAddress(moduleHandle, EntryName);
            if (funcPtr == IntPtr.Zero)
            {
                Int32 errorCode = Marshal.GetLastWin32Error();
                if (errorCode == WindowsNativeMethods.ERROR_PROC_NOT_FOUND)
                {
                    Console.WriteLine("Error: library '{0}' is missing function '{1}'", sharedLibrary, EntryName);
                }
                else
                {
                    Console.WriteLine("Error: GetProcAddress '{0}' failed: {1}", EntryName, errorCode);
                }
                return(1);
            }
            entry = (EntryDelegate)Marshal.GetDelegateForFunctionPointer(funcPtr, typeof(EntryDelegate));
        }
        else
        {
            const uint RTLD_NOW     = 2;
            IntPtr     moduleHandle = LinuxNativeMethods.dlopen(sharedLibrary, RTLD_NOW);
            if (moduleHandle == IntPtr.Zero)
            {
                Console.WriteLine("Error: dlopen '{0}' failed: {1}", sharedLibrary, LinuxNativeMethods.dlerror());
                return(1);
            }
            IntPtr funcPtr = LinuxNativeMethods.dlsym(moduleHandle, EntryName);
            if (funcPtr == IntPtr.Zero)
            {
                Console.WriteLine("Error: dlsym '{0}' failed: {1}", EntryName, LinuxNativeMethods.dlerror());
                return(1);
            }
            entry = (EntryDelegate)Marshal.GetDelegateForFunctionPointer(funcPtr, typeof(EntryDelegate));
        }
        IntPtr createDelegateFuncPtr = Marshal.GetFunctionPointerForDelegate(new CreateDelegateDelegate(CreateDelegate));

        return(entry(createDelegateFuncPtr, args.Length, args));
    }