Using C# code to set internet options [duplicate] - c#

Any idea how do I do the following using C#?
Going to Tools -> Internet Options -> Security
Select the Security tab
Click the Custom Level button
In the Miscellaneous section change Display mixed content to Enable

The "cheat" way to do this is to change the value
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet
Settings\Zones\0\1609
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet
Settings\Zones\1\1609
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet
Settings\Zones\2\1609
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet
Settings\Zones\3\1609
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet
Settings\Zones\4\1609
Where 0-4 are Zone identifiers and the value is 0 to Allow, 1 to Prompt, and 3 to Block. Keep in mind that if your code does this on anyone's machine but your own, you're likely to find your code blocked as malware.
The "proper" way to do this is to use the APIs to create an IInternetZoneManager and call SetZoneActionPolicy to adjust the settings for URLACTION_HTML_MIXED_CONTENT in the zones you want to adjust.

You aren't supposed to do this "programmatically". That's why there isn't an API for it. Only the user can change their security settings, and they do it using the built-in interface that you've already discovered.
The poor IE team has been working overtime trying to tighten up the security of their browser. They're not going to throw in something like this that would nullify all of their efforts in a matter of seconds.
Recall that even once this option is selected, there's a confirmation dialog presented. How do you propose to "click" that programmatically? (Hmm, on second thought, don't tell me. That's probably the next question you'll be asking.)
Give up on trying to do this programmatically, and ask the user to do it themselves. Provide a complete help file or other documentation that explains why you're requesting that they make this change, what features will be unavailable if they do not choose to make this change, and what the possible security risks of making such a change are. And, of course, specific instructions on how the change is made.
Or, better yet, redesign your app so that it doesn't require a system-wide modification of IE's security settings. It's hard to imagine a legitimate case for this. A better solution might be asking the user to add your site to their "trusted sites". Remember that local pages have different security settings than remote pages by default.

Also do not forget Group Policies. Most (if not all) IE settings may also be specified in Group Policies.
According to Local group policy setting for IE security page vs Internet options security page
the Group Policy settings override user-defined settings.
So, on my home PC (works without domain controller) I have a choice to define IE settings either via Local Group Policy Editor or via Internet Options. For example, if I run gpedit.msc to open Local Group Policy Editor, select
Computer Configuration\Windows Components\Internet Explorer\Internet Control Panel\Security Page\Internet Zone
change "Display mixed content" setting to "Enabled", then select "Enable" in drop down box, click Apply,
then open Security Settings for Internet Zone in IE - I will see that "Display mixed content" changed to Enable and
the selection is disabled because it is overriden by Policy.
For the entire list of supported policies download WindowsServer2012andWindows8GroupPolicySettings.xlsx
from
http://www.microsoft.com/en-us/download/details.aspx?id=25250
Now back to the question how to change settings programmatically.
EricLaw correctly suggested using SetZoneActionPolicy from IInternetZoneManager.
But it is hard to find samples for calling it from C#.
I ended up copying
http://www.pinvoke.net/default.aspx/Interfaces.IInternetZoneManager
into my code and then doing:
//This will disable "Download signed ActiveX" (IE setting # 0x1001) for Internet Zone (zone #3)
IInternetZoneManager izm = Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("7b8a2d95-0ac9-11d1-896c-00c04Fb6bfc4"))) as IInternetZoneManager;
IntPtr pPolicy = Marshal.AllocHGlobal(4);
Marshal.Copy(new int[] { 3 }, 0, pPolicy, 1);//3 means "Disable"
int result = izm.SetZoneActionPolicy((uint)UrlZone.Internet, (uint)0x1001, pPolicy, 4, (uint)UrlZoneReg.CurrentUserKey);
Marshal.ReleaseComObject(izm);
Marshal.FreeHGlobal(pPolicy);
I also tried changing group policy programmatically.
I used library from
https://bitbucket.org/MartinEden/local-policy
and then:
//This will disable "Download signed ActiveX controls" computer policy for Internet Zone (zone #3)
const string keyPath = #"SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\3";
var gpo = new LocalPolicy.ComputerGroupPolicyObject();
using (var machine = gpo.GetRootRegistryKey(LocalPolicy.GroupPolicySection.Machine))
{
using (var terminalServicesKey = machine.CreateSubKey(keyPath))
{
terminalServicesKey.SetValue("1001", 3, Microsoft.Win32.RegistryValueKind.DWord);
}
}
gpo.Save();
After successfully testing the code above on Win7 SP1 with IE 11 I decided to go back to the original suggestion from EricLaw: modify
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\*\1001
directly because this is what Microsoft is recommending. See, for example How to strengthen the security settings for the Local Machine zone in Internet Explorer or Enhanced Browsing Security

I am not sure but I think you can find all these settings in "registry". You need to find out the appropriate key. And to change those values you need to have proper rights. Registry can be accessed from .net code

Related

google chrome browser - read/write settings in C#

I need to build a console program to read and update the chrome browser setting.
Where should I start?
Check if you can modify the following file.
Location - c:\Users\\AppData\Local\Google\Chrome\User Data\Default\Preferences
This file contains a few settings. I have never done this so not sure if you can modify the file. But looks like a good start. Also, not sure if chrome rebuilds the file. (It was updated when I opened chrome while this file was open on my machine).
Chrome settings are stored in the registry, so here to read/write the registry and here for the list of available settings.
RegistryKey key = Registry.CurrentUser.CreateSubKey(#"SOFTWARE\OurSettings");
/// Reading value
var value = key.GetValue("Setting1");
/// Setting value
key.SetValue("Setting1", "This is our setting 1");
Be aware by Google's warning if you are not developing this for internal use :
These policies are strictly intended to be used to configure instances of Google Chrome internal to your organization. Use of these policies outside of your organization (for example, in a publicly distributed program) is considered malware and will likely be labeled as malware by Google and anti-virus vendors.

Run internet explorer as different user using Selenium

I want to launch single Internet explorer instane as different user with Selenium. I referred to the following post but not getting anywhere.
How can I run Internet Explorer Selenium tests as a specific domain user?
Can you point me in the right direction how it can be achieved?
You can achieve that using URI authentication. For Google Chrome that behavior works without any additional changes, but for IE it blocked by default. You can unlock it by:
Set the DWORD value's value data to 1 in one of the following registry keys.
For all users of the program, set the value in the following registry
key: HKEY_LOCAL_MACHINE\Software\Microsoft\Internet
Explorer\Main\FeatureControl\FEATURE_HTTP_USERNAME_PASSWORD_DISABLE
For the current user of the program only, set the value in the
following registry key: HKEY_CURRENT_USER\Software\Microsoft\Internet
Explorer\Main\FeatureControl\FEATURE_HTTP_USERNAME_PASSWORD_DISABLE
After that you will be able to use next URI to achieve your needs:
http://username:password#host/
If you want to provide domain name, you need encode that like http://domain%5Cusername:password#host/
Source https://support.microsoft.com/en-us/kb/834489

Change Browser download folder using C#

Is there a way I could change the download folder of the default web browser using c#.
Concurring with other's comments, you can only do it in a desktop app if you have the right permissions.
Here's some sample code to find out the default browser of the system (from this post):
private string getDefaultBrowser()
{
string browser = string.Empty;
RegistryKey key = null;
try
{
key = Registry.ClassesRoot.OpenSubKey(#"HTTP\shell\open\command", false);
//trim off quotes
browser = key.GetValue(null).ToString().ToLower().Replace("\"", "");
if (!browser.EndsWith("exe"))
{
//get rid of everything after the ".exe"
browser = browser.Substring(0, browser.LastIndexOf(".exe")+4);
}
}
finally
{
if (key != null) key.Close();
}
return browser;
}
However, things get tricky from here. Different browsers have different ways of saving the default location.
E.g.,
IE may store it in registry (usually under HKEY_CURRENT_USER\ Software\ Microsoft\ Internet Explorer)
FF stores it in prefs.js in Profile folder (checkout this post to get to it via code)
Not sure about Chrome and Safari
but you get the idea.
Not sure what your end goal is, but from a UX standpoint, I think the best thing to do would be to ask user to specify the Download directory (in other words, you expose a Setting in your App for the default download location).
To expand on Ash's comment - if you're within a web app, no. If you're a desktop app, and you have sufficient permissions (i.e. running as Administrator), probably. But you'd need to find the default browser (from the registry presumably) and know how to set the download folder for each popular browser, or every browser you want to work with.
Where are you trying to do this from? If you mean "someone hits our website and ...", the answer is no, as anything you run is in a security context. You can certainly suggest the user changes the folder, but you are stuck.
Assuming you are not a web application, you have options. The main user download directory is located at X under the key {374DE290-123F-4565-9164-39C4925E467B}. Yeah, that sounds like a lot of fun. You can learn how to hack the registry programatically here. But, the user can specify a specific folder in the browser, as well. This means you have to know what browser the user is using and hack it, or you can attempt to hack all.
The bad news is the app, running (most likely) in the user context, may not have administrator rights and be able to whack the registry keys to change the folder.

Connecting to a network drive programmatically and caching credentials

I'm finally set up to be able to work from home via VPN (using Shrew as a client), and I only have one annoyance. We use some batch files to upload config files to a network drive. Works fine from work, and from my team lead's laptop, but both of those machines are on the domain. My home system is not, and won't be, so when I run the batch file, I get a ton of "invalid drive" errors because I'm not a domain user.
The solution I've found so far is to make a batch file with the following:
explorer \\MACHINE1
explorer \\MACHINE2
explorer \\MACHINE3
Then manually login to each machine using my domain credentials as they pop up. Unfortunately, there are around 10 machines I may need to use, and it's a pain to keep entering the password if I missed one that a batch file requires.
I'm looking into using the answer to this question to make a little C# app that'll take the login info once and login programmatically. Will the authentication be shared automatically with Explorer, or is there anything special I need to do? If it does work, how long are the credentials cached?
Is there an app that does something like this automatically?
Unfortunately, domain authentication via the VPN isn't an option, according to our admin.
EDIT: If there's a way to pass login info to Explorer via the command line, that would be even easier using Ruby and highline.
EDIT: In case anyone else has the same problem, here's the solution I wound up using. It requires Ruby and the Highline gem.
require "highline/import"
domain = ask("Domain: ")
username = ask("Username: ")
password = ask("Password: ") { |q| q.echo = false }
machines = [
'\\MACHINE1\SHARE',
'\\MACHINE2\SHARE',
'\\MACHINE3\SHARE',
'\\MACHINE4\SHARE',
'\\MACHINE5\SHARE'
]
drives = ('f'..'z').to_a[-machines.length..-1]
drives.each{|d| system("net use #{d}: /delete >nul 2>nul"); }
machines.zip(drives).each{|machine, drive| system("net use #{drive}: #{machine} #{password} /user:#{domain}\\#{username} >nul 2>nul")}
It'll figure out how many mapped drives I need, then start mapping them to the requested shares. In this case, it maps them from V: to Z:, and assumes I don't have anything shared with those drive letters.
If you already have an Explorer window open to one of the shares, it may give an error, so before I ran the Ruby script, I ran:
net use * /delete
That cleared up the "multiple connections to a share not permitted" error, and allowed me to connect with no problems.
You could create a batch file that uses "NET USE" to connect to your shares. You'd need to use a drive letter for each share, but it'd be super simple to implement.
Your batch file would look like this:
net use h: \\MACHINE1 <password> /user:<domain>\<user>
net use i: \\MACHINE2 <password> /user:<domain>\<user>
net use j: \\MACHINE3 <password> /user:<domain>\<user>
UPDATE
Whether the connection remains or not depends upon what you specified for the /persistent switch. If you specified yes, then it will attempt to reconnect upon your next logon. If you specified no then it won't. The worrying this is the documentation says that it defaults to the value that you used last!
If you specified no, the connection will remain until you next reboot. If you drop your VPN connection the drive would be unavailable (but if you reconnect to the VPN the drive should be available as long as you haven't removed it).
I don't know of a way to use it without mapping to a drive letter, the documentation would lead you to believe that it isn't possible.
I understand your problem, that you're just trying to give explorer the correct credentials so it stops nagging you with login boxes. Using mapped drives though not perfect will at least alleviate your pain.
to pass credential by command line to the explorer you should take a look into the command net use
Use API WNetAddConnection2() via P/Invoke.

Change internet explorer security settings

HI,
How can i change internet explorer security settings by code.
i want to do the steps below but by code:
Tools -> Internet Options -> Security tab -> Custom Level -> and change the logon type to Anonymous logon.
I think that it can be changed from the registry file but i can't found it.
Microsoft has rather extensive documentation on the registry keys used by the Internet Zones here.
The settings are located under the key HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Zones[Zone Number], where [Zone Number] is one of 0 = My Computer, 1 = Local, 2 = Trusted Sites, 3 = Internet, 4 = Restricted. To make the change you listed above, you would need to set the value 1A00 to 0x00030000. (Sorry I can't help with registry manipulation in C#).

Categories