I have an application that should be able to run explicit tasks in another users context, so that within the application, a less privileged user is able to do some tasks, he is not allowed to.
I used for this an impersonation and it works fine with the acutal code, but I can not make it work with a Folderbrowser Dialog. I think the browser is executed within the context of the correct user, but uses other windows functions which override the user context.
My code that does not work is:
private void tb_customRoot_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
ImpersonationHelper.Impersonate("STARK", VSSFileExplorer.Properties.Settings.Default.FS_User, BASE64.Base64Decode(VSSFileExplorer.Properties.Settings.Default.FS_Password), delegate
{
VistaFolderBrowserDialog myFancyFolderDialog = new VistaFolderBrowserDialog();
DirectoryInfo rootDir = new DirectoryInfo(#"C:\");
try
{
rootDir = new DirectoryInfo(VSSFileExplorer.Properties.Settings.Default.CustomRoot);
}
catch
{ throw; }
myFancyFolderDialog.SelectedPath = rootDir.ToString();
myFancyFolderDialog.ShowDialog();
tb_customRoot.Text = myFancyFolderDialog.SelectedPath;
});
}
The problem is, that after opening the browser dialog, windows opens a "Enter network credentials" login prompt. The user should not know this credentials.
Is there a way to run a Folderbrowserdialog with another users rights?
I also build a function which will generate the correct path from some Tools in the GUI, but I am really interested if this is possible.
Thanks in advance.
Related
I'm writing an app which needs a permission for accessing a text file cuz without permission it throws an exception "access denied".
I added to the Package.appxmanifest specific lines
xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities
"IgnorableNamespaces="uap mp rescap"
And
<rescap:Capability Name="broadFileSystemAccess" />
But still it doesn't work. Is there any other way to access specific file with picker?
Yes the behavior changed between the April 2018 and October 2018 releases, and the default is now Disabled. This is a privacy constraint - we're very focused on maintaining the user's privacy. The documentation for this is up-to-date: https://learn.microsoft.com/en-us/windows/uwp/files/file-access-permissions#accessing-additional-locations. As of right now, if you want to detect whether the setting is enabled or disabled, you can simply try to access some file/folder to which this setting would grant you permission if enabled and deny permission if disabled (eg, "C:\"). If disabled, you can then launch the Settings app on the File System privacy page. For example:
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
try
{
StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(#"C:\");
// do work
}
catch
{
MessageDialog dlg = new MessageDialog(
"It seems you have not granted permission for this app to access the file system broadly. " +
"Without this permission, the app will only be able to access a very limited set of filesystem locations. " +
"You can grant this permission in the Settings app, if you wish. You can do this now or later. " +
"If you change the setting while this app is running, it will terminate the app so that the " +
"setting can be applied. Do you want to do this now?",
"File system permissions");
dlg.Commands.Add(new UICommand("Yes", new UICommandInvokedHandler(InitMessageDialogHandler), 0));
dlg.Commands.Add(new UICommand("No", new UICommandInvokedHandler(InitMessageDialogHandler), 1));
dlg.DefaultCommandIndex = 0;
dlg.CancelCommandIndex = 1;
await dlg.ShowAsync();
}
}
private async void InitMessageDialogHandler(IUICommand command)
{
if ((int)command.Id == 0)
{
await Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-broadfilesystemaccess"));
}
}
You can use the methods on the AppCapability class to query the state of the capability for the app and request access, which, may prompt the user depending on a number of geopolitical constraints that are subject to change over time. The CheckAccess() method will provide the status of the capability at the time of the call. The app can adjust it's behavior based on the results. Ideally the app would display some sort of indication to the user if it is operating in a reduced functionality mode, with a link to more details and instructions on how to enable the full functionality.
my app was working ok and it would execute on startup before.
I added a notify icon and in my code,there are some places that this icon changes.I added all required icons in the root folder of my app,and everything is working fine with the icons,except the startup boot of my app.
I can see my app's address in the "run" part of the registry(I mean everything is the same as when my app booted at startup properly).but my app won't run at startup anymore.
any advice on my matter?
PS:I thought I should explain my work a little bit and I wrote a little piece of app that has the exact same problem
public Icon[] icons = new Icon[2] { new Icon("icon1.ico"), new Icon("icon2.ico") };
public int counter = 0;
private void button1_Click(object sender, EventArgs e)
{
notifyIcon1.Visible = true;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
counter %= 2;
notifyIcon1.Icon = icons[counter];
counter++;
As you can see,the app changes the icon of the notifyicon in every tick.with this code,the app won't run at startup.but if I remove the iconchanging feature of the app,it will actually run at startup
This requires psychic debugging, I'll guess that you are loading these icons using their relative path name. Something like new Icon("foo.ico").
This can only work correctly if the default working directory of your program is set where you hope it will be. It usually is, certainly when you start your program from Visual Studio or start it from a desktop shortcut. But not when you added it to the Run registry key. Environment.CurrentDirectory will be set elsewhere, typically the Windows directory.
You must always use the full path name of files. An easy way to get that path is:
var home = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
var path = System.IO.Path.Combine(home, "foo.ico");
var icon = new Icon(path);
But there's certainly a better way than storing icons as files, you can embed them in your program. Project + Properties, Resources tab. Click the arrow on the Add Resource button, Add Existing File and navigate to your .ico file. Now the icon is embedded in your program, you'll never lose track of it and can't forget to copy it when you deploy your program on another machine. And the code is simpler as well:
var icon = Properties.Resources.foo;
i cannot create file in my windows service
and this is error
error In onstart method Access to the path 'C:\Windows\system32\BridgeServiceLog.txt' is denied.
protected override void OnStart(string[] args)
{
try
{
Logger.InitLogFile("BridgeServiceLog.txt");
Trace.WriteLine(Logger.logSwitch.TraceInfo, "Trace Started");
Trace.WriteLineIf(Logger.logSwitch.TraceInfo, "OnStart Started");
_bridgeServiceEventLog.WriteEntry("new OnStart");
if (Vytru.Platform.Bridge.Configuration.LicenseValidetor.ValidCountAndTypeDevices())
{
SharedData.InitializeBridge();
// WsInitializeBridge();
}
else
{
this.Stop();
_bridgeServiceEventLog.WriteEntry("LicenseValidetor Error");
}
_bridgeServiceEventLog.WriteEntry("end Start");
}
catch (Exception e)
{
Trace.WriteLineIf(Logger.logSwitch.TraceError, e.Message);
_bridgeServiceEventLog.WriteEntry("error In onstart method " + e.Message);
}
Trace.WriteLineIf(Logger.logSwitch.TraceInfo, "OnStart Ended");
}
The service user account probably doesn't have access to write to C:\Windows\System32 (which is the working directory of a Windows service).
Anyway, you shouldn't write to that folder. It is for the operating system - not your service.
You can use Environment.GetFolderPath to get a suitable path for writing files like log files in a way that will work any computer, not just your own computer. Here is an example.
var companyPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
"MyCompany"
);
var productPath = Path.Combine(companyPath, "MyProduct");
var logFilePath = Path.Combine(productPath, "BridgeServiceLog.txt");
You should of course use suitable values for MyCompany and MyProduct.
When running a Windows Service the default working folder is <System drive>:\Windows\System32\.
Fortunately, not everyone can just access that folder.
There are two ways about this; write your file to another folder to which you do have rights, or run your service with administrator rights.
I would recommend the first option.
The easiest solution is to go the folder where you want to save a file, right click, properties, security, add a new user IIS_Users and give permission to write.
Use LocalSystem account on ProjectInstaller
I made an app that allows windows users to spoof Mac Address .
It works by adding "NetworkAdapter": "00ff00ff00ff" key/value pair to registry of the users selected nic.
The problem is that every time the app tries to make changes to windows registry Windows pop's up a warning dialog, e.g.:
but clicking continue will add the registry values successfully and the app functions normally.
What can i do/or add changes in my code to make the dialog box disappear or can i do it in a better way?
The app requires Admin Privileges
here's the git repo of the app
here's the method:
public void SetMac(string macAddress)
{
const string Name = #"SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002bE10318}";
using (RegistryKey key0 = Registry.LocalMachine.OpenSubKey(Name, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl))
{
string[] x = key0.GetSubKeyNames();
foreach (string name in x)
{
var var1 = Registry.LocalMachine.OpenSubKey(Name,RegistryKeyPermissionCheck.ReadWriteSubTree,RegistryRights.FullControl);
var v = var1.OpenSubKey(name, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl);
var z = v.GetValue("DriverDesc");
if (comboBox1.Text == z.ToString() )
{
v.SetValue("NetworkAddress",comboBox2.Text);
MessageBox.Show(z.ToString());
}
v.Close();
var1.Close();
}
key0.Close();
}
}
You need to run your app under elevated privileges, see Requested registry access is not allowed.
The problem here is that the user does not have permission to open the target key for writing. As abatishchev has already suggested, you need to run the application elevated so that the user actually has Administrators group membership when the code is executed.
The reason that this looks like a CAS permission error is a design flaw in the RegistryKey.OpenSubKey method. It ought to throw an UnauthorizedAccessException when the target key cannot be opened for writing due to inadequate user permissions, but it actually throws a SecurityException instead. The problem ends up appearing to be due to insuffience CAS permissions when it is really the user, not the code, that lacks permissions to edit the key.
I recently upgraded an MSTest project to .NET 4.0 and VS 2010. Several of the tests query an outside vendor service and thus prompt the user for necessary credentials to communicate through our corporate web proxy. This used to work fine in vs2008 but after the upgrade the dialog will only display if the user switches focus from VS to another app immediately after kicking off the tests. Is there anything special that needs to be done when displaying the dialog? The best I can figure is that there is some WPF caveat that got introduced with the redesign of VS.
The code in question
private void PromptUser()
{
if (!credentialsSet)
{
using (CredentialsDialog dialog = new CredentialsDialog(true))
{
Process process = Process.GetCurrentProcess();
IWin32Window window = Control.FromHandle(process.MainWindowHandle);
DialogResult dr = dialog.ShowDialog(window);
if (dr == DialogResult.Cancel)
{
throw new InvalidOperationException("Credentials not entered");
}
credentials = dialog.Credentials;
user = dialog.Username;
password = dialog.Password;
domain = dialog.Domain;
}
credentialsSet = true;
}
}
I would sugest that requiring the credentials is bad practice. Have you conidered adding your credentials in an excrypted fasion to the config of the test assembly.
You will run into a lot of problems if you try to setup this for automated build.
You may need to activate the dialog in order to get it to pop up over whatever programs you have active.
using (CredentialsDialog dialog = new CredentialsDialog(true))
{
Process process = Process.GetCurrentProcess();
IWin32Window window = Control.FromHandle(process.MainWindowHandle);
dialog.Activate();
DialogResult dr = dialog.ShowDialog(window);
// ...
}
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.activate.aspx