How to block downloads in .NET WebBrowser control?

2019-01-14 03:33发布

I need to prevent the .NET WebBrowser control from showing any "Do you want to open or save this file?" and "Save As" dialogs. Instead, I want to display a message box telling users that file downloads are disabled for security reasons.

I started with the FileDownload event of WebBrowser, but it does not allow cancellation. Then, I used the approach from CodeProject: Extended .NET 2.0 WebBrowser Control to implement my own event based on the original COM call using the interface DWebBrowserEvents2. When I fixed the code according to an MS knowledge base entry about a bug with the FileDownload signature, the event handler was called and I was able to cancel the download.

This does not work with all downloads, though: download URLs pointing to an URL including .exe raise the event and can be cancelled before the dialog appears - but for others (like .do), the event handler is not called until the user clicks Open, Save or Cancel in the dialog.

A possible solution might be to intercept WH_CALLWNDPROCRET messages and 'answer' the dialog before it is shown to the user, but it sounds like much effort and I also would prefer a cleaner solution...

Does anybody know how to reliably block all downloads?

3条回答
We Are One
2楼-- · 2019-01-14 03:37

The only reliable way seems to be to hook into the Windows event queue and suppress the dialog boxes (as all sorts of things can get the user access). This is what our helper class does:

    void ListenForDialogCreation()
    {
        // Listen for name change changes across all processes/threads on current desktop...
        _WinEventHook = WinAPI.SetWinEventHook(WinAPI.EVENT_OBJECT_CREATE, procDelegate);
    }
    void StopListeningForDialogCreation()
    {
        WinAPI.UnhookWinEvent(_WinEventHook);
    }

    void WinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
    {
        const uint OBJID_WINDOW = 0;
        const uint CHILDID_SELF = 0;

        // filter out non-HWND, and things not children of the current application
        if (idObject != OBJID_WINDOW || idChild != CHILDID_SELF)
            return;

        //Get the window class name
        StringBuilder ClassName = new StringBuilder(100);
        WinAPI.GetClassName(hwnd, ClassName, ClassName.Capacity);

        // Send close message to any dialog
        if (ClassName.ToString() == "#32770")
        {
            WinAPI.SendMessage(hwnd, WinAPI.WM.CLOSE, IntPtr.Zero, IntPtr.Zero);
            if (OnDialogCancelled != null)
                OnDialogCancelled();
        }
        if (ClassName.ToString() == "#32768")
        {
            WinAPI.SendMessage(hwnd, WinAPI.WM.CLOSE, IntPtr.Zero, IntPtr.Zero);
            if (OnDialogCancelled != null)
                OnDialogCancelled();
        }

    }

    public delegate void OnDialogCancelledEvent();
    public event OnDialogCancelledEvent OnDialogCancelled;
  • #32770 is the Dialog class
  • #32768 is the pop-up menu
  • the WinAPI namespace is our pinvoke wrappers.

If you don't want to block all Dialogs you'll want to add in some additional filters once you've caught the class. It depends how secure you need to be. At $WORK we needed to block all uploads and downloads.

Suppressing the pop-up menu is necessary as it gives access to the Help application, which gives links to microsoft's website, which enables a full instance of IE to be launched. Then they can do whatever they want.

查看更多
\"骚年 ilove
3楼-- · 2019-01-14 03:41

You could use Navigating event which allows cancellation.

Inside of this event, you could try to connect to URL that's being navigated yourself, inspect http response headers and cancel navigating if inappropriate ContentType is detected.

System.Net.WebRequest request = System.Net.WebRequest.Create(e.Url);

// we need only header part of http response
request.Method = "HEAD";

System.Net.WebResponse response = request.GetResponse();

// only text/html, text/xml, text/plain are allowed... extend as required
if (!response.ContentType.StartsWith("text/"))
{
  e.Cancel = true;
  MessageBox.Show("Not allowed for security resons...");
}

Obviously this is not bullet-proof solution but can give you an idea how to get started (if you don't mind extra tiny roundtrip just to retrieve http response headers).

Jens Bannmann wrote:

This is not ideal, as I'm dealing with web applications where the extra request might trigger an action being carried out twice :-(

Then I would create some simple proxy server that would inspect all received data and would filter out all http responses that could trigger "Save as" dialog in your web-browser control.

Simply, don't let your web-browser control directly access the internet but delegate all http requests to your special proxy server that will filter out all unsafe responses from the web.

查看更多
来,给爷笑一个
4楼-- · 2019-01-14 03:43

This project - http://www.codeproject.com/Articles/157329/Http-Monitor-for-Webbrowser-Control allows intercepting and inspecting HTTP traffic from WebBrowser control.

Then you can filter data by MIME and allow only html, images, scripts etc.

查看更多
登录 后发表回答