Menu

Nakov.com logo

Thoughts on Software Engineering

C# Code for Changing Internet Explorer Security Settings and .NET Security Policy to Run Windows Forms based ActiveX with Full Trust

I am working on an ActiveX control that allows using a device for scanning personal ID cards in a Web application (based on ASP.NET). The card scanning device (called RTE reader) is accessed using a native DLL that communicates with the device through the COM port by using a proprietary protocol. It is pretty complicated to get this working in all Web browsers so we conviced the customer to use Internet Explorer only.
The typical way to implement this functionality in Internet Explorer is to write an ActiveX control. I created the ActiveX control in C# using .NET Framework 2.0, Windows Forms and few native DLLs. How to create an ActiveX in C# in another interesting story, but once I got ready with the ActiveX control, I needed to write an installation program that changes the security policy of Internet Explorer to ensure the control is allowed to run without security restrictions. The control uses native DLL calls so it needs special permissions that can be assigned by the .NET Framework 2.0 Configuration Tool or its console version (caspol.exe).
There are two steps needed to get running an ActiveX control implemented as .NET assembly without security restrictions in Internet Explorer:

  • Add the Web site to the “Trusted sites” security zone in Internet Explorer. This allows this Web site to install and run ActiveX controls.
  • Assign full trust permission set to the assembly implementing the ActiveX in the .NET Security Policy.

While the first task is less challengeable (we just need to add few registry values), the second requires to run the following command:

caspol.exe -quiet -machine -chggroup Trusted_Zone FullTrust

The caspol.exe is standard part of .NET Framework 2.0 and hence is available in any machine that has .NET 2.0, 3.0 or 3.5 (because all of the use CRL 2.0). It is typically located here:

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\caspol.exe

The following source code (implemented as Windows Forms desktop application) performs the above mentioned two steps to allow an ActiveX written in C# to run without security limitations in Internet Explorer:

public partial class FormMain : Form
{
    const int TRUSTED_SITES_ZONE = 2;
    public FormMain()
    {
        InitializeComponent();
    }
    private void ShowMessage(string msg)
    {
        this.Invoke(new MethodInvoker(delegate()
        {
            textBoxMessages.Text = textBoxMessages.Text + msg + "\r\n";
            textBoxMessages.SelectionStart = textBoxMessages.Text.Length;
            textBoxMessages.SelectionLength = 0;
            textBoxMessages.ScrollToCaret();
        }));
    }
    private void FormMain_Load(object sender, EventArgs e)
    {
        backgroundWorker.RunWorkerAsync();
    }
    private void buttonOK_Click(object sender, EventArgs e)
    {
        Close();
    }
    private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        this.Invoke(new MethodInvoker(delegate()
        {
            buttonOK.Enabled = false;
        }));
        try
        {
            ShowMessage("Installing ...");
            ShowMessage("\r\nAdding trusted Web sites in Externet Explorer ...");
            AddTrustedSitesToInternetExplorer();
            ShowMessage("\r\nChanging the .NET Framework Security Policy ...");
            ChangeDotNetSecurityPolicyForTrustedZoneAssignFullTrust();
            ShowMessage("\r\nInstallation completed successfully.");
        }
        catch (Exception ex)
        {
            ShowMessage(ex.Message);
            ShowMessage("\r\nInstallation failed.");
        }
        this.Invoke(new MethodInvoker(delegate()
        {
            buttonOK.Enabled = true;
        }));
    }
    private void AddTrustedSitesToInternetExplorer()
    {
         // Change this to your Web site hosting the ActiveX control
        AddTrustedSiteToInternetExplorer("http://www.mysite.com");
        AddTrustedSiteToInternetExplorer("https://www.mysite.com");
    }
    private void AddTrustedSiteToInternetExplorer(string url)
    {
        Match match = Regex.Match(url, @"\A(.+)://((.+)\.)?([^.]+\.[^.]+)\Z");
        string protocol = match.Groups[1].Value;
        string subdomain = match.Groups[3].Value;
        string domain = match.Groups[4].Value;
        if (domain == "")
        {
            match = Regex.Match(url, @"\A(.+)://(.+)\Z");
            protocol = match.Groups[1].Value;
            subdomain = "";
            domain = match.Groups[2].Value;
        }
        if (protocol == "" || domain == "")
        {
            throw new Exception("  Error: invalid URL " + url);
        }
        string key = "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\ZoneMap\\Domains\\" + domain;
        RegistryKey regKeyDomain = Registry.CurrentUser.CreateSubKey(key);
        using (regKeyDomain)
        {
            if (subdomain == "")
            {
                regKeyDomain.SetValue(protocol, TRUSTED_SITES_ZONE);
            }
            else
            {
                RegistryKey regKeySubdomain = regKeyDomain.CreateSubKey(subdomain);
                using (regKeySubdomain)
                {
                    regKeySubdomain.SetValue(protocol, TRUSTED_SITES_ZONE);
                }
            }
        }
        ShowMessage("  The site " + url + " is added to the Internet Explorer trusted zone.");
    }
    private void ChangeDotNetSecurityPolicyForTrustedZoneAssignFullTrust()
    {
        // Get .NET Framework Runtime location in the file system
        Assembly systemAssembly = Assembly.GetAssembly(typeof(System.String));
        string netFrameworkPath = Path.GetDirectoryName(systemAssembly.Location);
        // Allow assemblies coming from trusted Web sites to run with full permissions
        // by executing caspol.exe -quiet -machine -chggroup Trusted_Zone FullTrust
        string caspolPath = netFrameworkPath + Path.DirectorySeparatorChar + "caspol.exe";
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.FileName = caspolPath;
        startInfo.Arguments = "-quiet -machine -chggroup Trusted_Zone FullTrust";
        startInfo.ErrorDialog = false;
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        Process process = Process.Start(startInfo);
        if (process != null)
        {
            ShowMessage("  Added .NET security policy to run all assemblies coming from trusted Web sites with no security restrictions.");
        }
        else
        {
            throw new Exception("  Error: caspol.exe could not be executed.");
        }
    }
}
Comments (10)

10 Responses to “C# Code for Changing Internet Explorer Security Settings and .NET Security Policy to Run Windows Forms based ActiveX with Full Trust”

  1. Wirach says:

    Thank you for Sample code.

    I create windows form as ActiveX run on Web Site.
    But have Error runtime permission “System.net.WebPermission”
    I want solution for this Error.

  2. demir says:

    thank you for sharing
    your code is very usefull

  3. Kishor says:

    How to unregister a site from caspol using C#?

  4. varsha says:

    I need to programitically change the settings in IE so that i can allow scripts to run which are not marked for safe.

    • nakov says:

      You may find these settings in the registry: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Internet Settings

  5. […] I am trying to make a windows application that adds a URL too the “Trusted sites” of IE. this part works. solution – http://www.nakov.com/blog/2009/05/15/c-code-for-changing-internet-explorer-security-settings-and-net… […]

  6. safari dubai says:

    Do you have a spam problem on this blog; I also am a blogger, and I was curious about yyour situation;we have developed
    some nice methods and wwe are looking to trad strategies with other folks,
    please shooit me an e-mail if interested.

    Also visit myy web site … safari dubai

  7. My family members always say that I am killing my time here at net, however I know I am getting familiarity every
    day by reading such nice articles or reviews.

    Also visit my blog: bbc documentary

RSS feed for comments on this post. TrackBack URL

LEAVE A COMMENT