Set write permissions for all users for my program folder - c#

I have build a program in Visual Studio. The program creates a logfile and writes into it while the program is running. Therefore I constructed an installer (setup-project), that should set write permissions for my program-folder regardless which user works with the program.
currently it looks like this:
// ...
}
InitializeComponent();
string folder = Directory.GetCurrentDirectory();
DirectorySecurity ds = Directory.GetAccessControl(folder);
ds.AddAccessRule(new FileSystemAccessRule("Everyone", //Everyone is important
//because rights for all users!
FileSystemRights.Read | FileSystemRights.Write, AccessControlType.Allow));
}
// ...
In the last two rows I get a System.SystemException: “Die Vertrauensstellung zwischen der primären Domäne und der vertrauenswürdigen Domäne konnte nicht hergestellt werden.“
[Translation: "The trust relationship between the primary domain and the trusted domain could not be established."]
The stacktrace reads like this:
bei System.Security.Principal.NTAccount.TranslateToSids(IdentityReferenceCollection sourceAccounts, Boolean& someFailed)
bei System.Security.Principal.NTAccount.Translate(IdentityReferenceCollection sourceAccounts, Type targetType, Boolean& someFailed)
bei System.Security.Principal.NTAccount.Translate(IdentityReferenceCollection sourceAccounts, Type targetType, Boolean forceSuccess)
bei System.Security.Principal.NTAccount.Translate(Type targetType)
bei System.Security.AccessControl.CommonObjectSecurity.ModifyAccess(AccessControlModification modification, AccessRule rule, Boolean& modified)
bei System.Security.AccessControl.CommonObjectSecurity.AddAccessRule(AccessRule rule)
bei System.Security.AccessControl.FileSystemSecurity.AddAccessRule(FileSystemAccessRule rule)
Have you an idea what I can do?
thanks

Perhaps the best answer isn't what you've asked for. There's a good reason for not writing to the program files directory. Log data in particular is transient and shouldn't be written here.
It's a much better idea to write log data to the directory specified by the TEMP environment variable. If you do this you'll save your users a few troubles and prevent them cursing your software in the future. Please check out this answer which covers the same topic:
Allow access permission to write in Program Files of Windows 7

Aren't you missing the statement where you actually set the access control back to the directory?
Directory.SetAccessControl(Directory.GetCurrentDirectory(), ds);

This previously asked question should point you in the right direction. Basically, you do NOT want any user writing to the Program Files folder. UAC, security and other measures are there to try and prevent this as much as possible.
Essentially, if you want a single file which will be written to by all users, you will want it in the ProgramData folder, accessible through the %ALLUSERSPROFILE%, rather than the individual users' temporary folder, which is definitely what you want to do with a log file. Remember that the temporary folder's content should be considered volatile, and could be deleted at any time, such as by the Disk Cleanup Wizard.

Related

Run a program as user identity but with elevated privileges

Scenario:
An administrator will install the application. The application has some kernel level operations so, it has to run with privileged mode. But the user does not have administrator credentials to run the application in elevated mode.
So, what are the best possibility to solve the above scenario.
Solution one (tried):
While installing the application through administrator, we would create an admin where we know his user name and password. So, when the user tries to perform any operation, we will run the application as elevated mode using the functions processstartinfo() and process.start() in c#. But, the application runs in admin name, so the mapped drives for the user are not visible as this admin is not in the ACL list. So, this method is getting ruled out.
Can there be a solution where elevating the user it self as admin till the operation is completed using c# application?
I'm stuck and I don't find any articles to read upon on this.
Edit :
At an enterprise level, the windows doesn't ask for admin creds for using bitlocker. So, we want to achieve the same type of functionality.
Is it possible?
Can anyone please help?
Thank you.
The solution that I did was to separate the program into two parts. One part runs as a service that is run using admin privileges and the other part runs using normal privileges.
The communication between the two programs can run via Ethernet or using shared memory.
I think you might be stuck because you are dealing with two functions that have permissions features, and both are required to properly run your application.
I have noted that you have these two:
File System Path. Only the logged-on user has access to this (the admin account does not).
Application Processes. Only the admin account can run these processes (the logged-on user will be prompted with user elevation).
To illustrate this...
| File System Path | Application Process
User | OK | --
Admin | -- | OK
The solution needs to look like this...
| File System Path | Application Process
Service | OK | OK
If possible, I would say this is the most straight-forward way, whereby you create a service account that has permissions to do both.
You could try creating a parallel thread that has admin privileges in order to execute the kernel operations. This way your whole program is contained in one executable.
What you can do is use COM+ Component Services. With .NET the easiest way is use Enterprise Services's ServicedComponent which has all sorts of wrappers and utility classes to interop with COM+ Component services.
So here are steps to do it:
1) Create a .NET Framework Class Library.
2) Add it a strong name and sign it with it
3) Add it a class like this for example (I've also put some utility method to diagnose things)
[ComVisible(true)]
public class AdminClass : ServicedComponent
{
public int DoSomethingAsAdmin()
{
// test something that a normal user shouldn't see
return Directory.GetFiles(Path.Combine(Environment.SystemDirectory, "config")).Length;
}
public string WindowsIdentityCurrentName => WindowsIdentity.GetCurrent().Name;
public string CurrentProcessFilePath => Process.GetCurrentProcess().MainModule.FileName;
// depending on how you call regsvcs, you can run as a 32 or 64 bit surrogate dllhost.exe
public bool Is64BitProcess => Environment.Is64BitProcess;
}
4) Add the following to AssemblyInfo.cs
[assembly: ApplicationName("AdminApp")]
[assembly: SecurityRole("AdminAppUser")]
[assembly: ApplicationActivation(ActivationOption.Server)]
What this does is define a COM+ application named "AdminApp", add a role named "AdminAppUser" to it, and declare the app will run as a "server" which means "out-of-process".
5) Compile that and run this command as admin
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\regsvcs.exe AdminApp.dll
or this command:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\regsvcs.exe AdminApp.dll
Both commands will create the the COM + application, and host the .NET library DLL in a surrogate .exe (dllhost.exe). If you choose the first, the hosted process will run as x64, and if you run the second, the hosted process will run as x86.
You can check the result of this registration if you run Component Services (from Windows/Run):
6) Right-click the app and you'll see a whole bunch of cool things you can configure. Note you can even run this as a service (in the 'Activation' tab), etc. What you must do is configure the identity which will run this process, something like this:
Here, I've used a custom admin account. You don't want to use any of the other builtin choices.
7) Now, since default security has been enabled, basically nobody can calls this component. So we just have to add a user to the role "AdminAppUser" we created earlier. You can of course do this using the UI as shown here:
but here is a piece of code that does this programmatically (we use the COM+ administration objects) :
AddUserInRole("AdminApp", "AdminAppUser", #"SMO01\simon");
....
static void AddUserInRole(string appName, string roleName, string userName)
{
dynamic catalog = Activator.CreateInstance(Type.GetTypeFromProgID("COMAdmin.COMAdminCatalog"));
// the list of collection hierarchy : https://learn.microsoft.com/en-us/windows/desktop/cossdk/com--administration-collections
var apps = catalog.GetCollection("Applications");
var app = GetCollectionItem(apps, appName);
if (app == null)
throw new Exception("Application '" + appName + "' was not found.");
var roles = apps.GetCollection("Roles", app.Key);
var role = GetCollectionItem(roles, roleName);
if (role == null)
throw new Exception("Role '" + roleName + "' was not found.");
// UsersInRole collection
// https://learn.microsoft.com/en-us/windows/desktop/cossdk/usersinrole
var users = roles.GetCollection("UsersInRole", role.Key);
var user = GetCollectionItem(users, userName);
if (user == null)
{
user = users.Add();
user.Value["User"] = userName;
users.SaveChanges();
}
}
static dynamic GetCollectionItem(dynamic collection, string name)
{
collection.Populate();
for (int i = 0; i < collection.Count; i++)
{
var item = collection.Item(i);
if (item.Name == name)
return item;
}
return null;
}
The result should be like this:
8) Now, for the client app, using the AdminApp facilities is easy. Don't reference the .DLL as a standard .NET reference, but use it as any other external COM component. You could reference the .TLB file that was created by regsvcs, or just use the magic dynamic keyword as I demonstrate here (the drawback is you don't get autocompletion):
using System;
using System.Security.Principal;
namespace UserApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Is64BitProcess " + Environment.Is64BitProcess);
Console.WriteLine("Running As " + WindowsIdentity.GetCurrent().Name);
var type = Type.GetTypeFromProgID("AdminApp.AdminClass");
dynamic trustedClass = Activator.CreateInstance(type);
Console.WriteLine("Admin App Process Path: " + trustedClass.CurrentProcessFilePath);
Console.WriteLine("Admin App Running As: " + trustedClass.WindowsIdentityCurrentName);
Console.WriteLine("Admin App Is64BitProcess: " + trustedClass.Is64BitProcess);
Console.WriteLine("Admin App DoSomethingAsAdmin: " + trustedClass.DoSomethingAsAdmin());
}
}
}
Now, when you run it for example as "simon", you should see something like this, it works:
Is64BitProcess False
Running As SMO01\simon
Admin App Process Path: C:\WINDOWS\system32\dllhost.exe
Admin App Running As: SMO01\myAdmin
Admin App Is64BitProcess: True
Admin App DoSomethingAsAdmin: 71
and when you run it for example as "bob" who's not configured in the role, you should see something like this with an access denied, this is expected:
Is64BitProcess False
Running As SMO01\bob
Unhandled Exception: System.UnauthorizedAccessException: Retrieving the COM class factory for component with CLSID {0DC1F11A-A187-3B6D-9888-17E635DB0974} failed due to the following error: 80070005 Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)).
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Activator.CreateInstance(Type type)
at UserApp.Program.Main(String[] args) in C:\Users\simon\source\repos\TrustedSystem\UserApp\Program.cs:line 14
Note we've created a trusted system without setting any password anywhere. And, I've only scratched the surface of what you can do with COM+ component. For example, you can export the app as an .MSI for easy deployment, etc.

Why do I need any Saga storage?

I'm struggling with an error message I'm getting from the NServiceBus.Host during startup and not sure where I'm going wrong. I initially encountered the problem within a large project but I seem to be able to reproduce this from scratch.
In VS2012, start with a new C# Class Library project, set for .NET 4.6.2. Then add NuGet packages - NServiceBus (6.0.0), NServiceBus.Host (7.0.1) and NServiceBus.NHibernate (7.2.0).
Then edit the EndpointConfiguration class to be as follows:
using NServiceBus.Features;
using NServiceBus.Persistence;
namespace NSB6_Pure
{
using NServiceBus;
public class EndpointConfig : IConfigureThisEndpoint
{
public void Customize(EndpointConfiguration endpointConfiguration)
{
//TODO: NServiceBus provides multiple durable storage options, including SQL Server, RavenDB, and Azure Storage Persistence.
// Refer to the documentation for more details on specific options.
endpointConfiguration.UsePersistence<NHibernatePersistence, StorageType.Timeouts>();
endpointConfiguration.DisableFeature<MessageDrivenSubscriptions>();
endpointConfiguration.DisableFeature<Sagas>();
// NServiceBus will move messages that fail repeatedly to a separate "error" queue. We recommend
// that you start with a shared error queue for all your endpoints for easy integration with ServiceControl.
endpointConfiguration.SendFailedMessagesTo("error");
// NServiceBus will store a copy of each successfully process message in a separate "audit" queue. We recommend
// that you start with a shared audit queue for all your endpoints for easy integration with ServiceControl.
endpointConfiguration.AuditProcessedMessagesTo("audit");
}
}
}
Then compile (in this case a debug build) and, from a command prompt, try to run NServiceBus.Host.exe in the bin\Debug directory. In my case, I get this output, most of it in Red:
2017-04-28 12:46:11.876 INFO DefaultFactory Logging to 'C:\blah\bin\Debug\' with level Info
2017-04-28 12:46:13.446 FATAL NServiceBus.LicenseManager Your license has expire
d! You can renew it at https://particular.net/licensing.
2017-04-28 12:46:13.561 ERROR NServiceBus.GenericHost Exception when starting en
dpoint.
System.InvalidOperationException: In order to use NServiceBus with NHibernate yo
u need to provide at least one connection string. You can do it via (in order of
precedence):
* specifying 'NServiceBus/Persistence/NHibernate/Saga' connection string for th
e Saga persister
* specifying 'NServiceBus/Persistence' connection string that applies to all pe
rsisters
* specifying 'NServiceBus/Persistence/connection.connection_string' or 'NServic
eBus/Persistence/connection.connection_string_name' value in AppSettings or your
NHibernate configuration file.
For most scenarios the 'NServiceBus/Persistence' connection string is the best o
ption.
at NServiceBus.Persistence.NHibernate.NHibernateConfigurationBuilder.Validate
ConfigurationViaConfigFile(Configuration configuration, String configPrefix) in
C:\BuildAgent\work\5135de308b2f3016\src\NServiceBus.NHibernate\Internal\NHiberna
teConfigurationBuilder.cs:line 130
at NServiceBus.Features.NHibernateStorageSession.Setup(FeatureConfigurationCo
ntext context) in C:\BuildAgent\work\5135de308b2f3016\src\NServiceBus.NHibernate
\SynchronizedStorage\NHibernateStorageSession.cs:line 45
at NServiceBus.Features.FeatureActivator.ActivateFeature(FeatureInfo featureI
nfo, List`1 featuresToActivate, IConfigureComponents container, PipelineSettings
pipelineSettings) in C:\Build\src\NServiceBus.Core\Features\FeatureActivator.cs
:line 194
at NServiceBus.Features.FeatureActivator.SetupFeatures(IConfigureComponents c
ontainer, PipelineSettings pipelineSettings) in C:\Build\src\NServiceBus.Core\Fe
atures\FeatureActivator.cs:line 57
at NServiceBus.InitializableEndpoint.<Initialize>d__1.MoveNext() in C:\Build\
src\NServiceBus.Core\InitializableEndpoint.cs:line 50
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNot
ification(Task task)
at NServiceBus.GenericHost.<Start>d__1.MoveNext() in C:\BuildAgent\work\fc89e
968acb99302\src\NServiceBus.Hosting.Windows\GenericHost.cs:line 48
2017-04-28 12:46:13.582 ERROR NServiceBus.Hosting.Windows.WindowsHost Start fail
ure
System.InvalidOperationException: In order to use NServiceBus with NHibernate yo
u need to provide at least one connection string. You can do it via (in order of
precedence):
* specifying 'NServiceBus/Persistence/NHibernate/Saga' connection string for th
e Saga persister
* specifying 'NServiceBus/Persistence' connection string that applies to all pe
rsisters
* specifying 'NServiceBus/Persistence/connection.connection_string' or 'NServic
eBus/Persistence/connection.connection_string_name' value in AppSettings or your
NHibernate configuration file.
For most scenarios the 'NServiceBus/Persistence' connection string is the best o
ption.
at NServiceBus.Persistence.NHibernate.NHibernateConfigurationBuilder.Validate
ConfigurationViaConfigFile(Configuration configuration, String configPrefix) in
C:\BuildAgent\work\5135de308b2f3016\src\NServiceBus.NHibernate\Internal\NHiberna
teConfigurationBuilder.cs:line 130
at NServiceBus.Features.NHibernateStorageSession.Setup(FeatureConfigurationCo
ntext context) in C:\BuildAgent\work\5135de308b2f3016\src\NServiceBus.NHibernate
\SynchronizedStorage\NHibernateStorageSession.cs:line 45
at NServiceBus.Features.FeatureActivator.ActivateFeature(FeatureInfo featureI
nfo, List`1 featuresToActivate, IConfigureComponents container, PipelineSettings
pipelineSettings) in C:\Build\src\NServiceBus.Core\Features\FeatureActivator.cs
:line 194
at NServiceBus.Features.FeatureActivator.SetupFeatures(IConfigureComponents c
ontainer, PipelineSettings pipelineSettings) in C:\Build\src\NServiceBus.Core\Fe
atures\FeatureActivator.cs:line 57
at NServiceBus.InitializableEndpoint.<Initialize>d__1.MoveNext() in C:\Build\
src\NServiceBus.Core\InitializableEndpoint.cs:line 50
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNot
ification(Task task)
at NServiceBus.GenericHost.<Start>d__1.MoveNext() in C:\BuildAgent\work\fc89e
968acb99302\src\NServiceBus.Hosting.Windows\GenericHost.cs:line 54
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNot
ification(Task task)
at NServiceBus.Hosting.Windows.WindowsHost.Start() in C:\BuildAgent\work\fc89
e968acb99302\src\NServiceBus.Hosting.Windows\WindowsHost.cs:line 33
And the bit I'm focussing on is here:
In order to use NServiceBus with NHibernate you need to provide at least one connection string. You can do it via (in order of precedence):
specifying 'NServiceBus/Persistence/NHibernate/Saga' connection string for the Saga persister
I've checked the NServiceBus code - this isn't a generic message. If the issue was the lack of config for Timeouts1, I'm sure it would be talking about it rather than Saga, since that part of the error message is parameterized.
But I don't want to use Sagas in this particular project. I'd have thought DisableFeature<Sagas> would be sufficient to indicate to NServiceBus that I don't want to use sagas here, but apparently not.
So why is NServiceBus trying to configure Saga storage and, more importantly, how do I stop it from doing so?
1Of course, I am expecting such an error to occur since I haven't done anything such as even adding an app.config to the class library yet. So even once the Saga issue is resolved, I'm expecting this code to still produce errors. Just hopefully ones I can work out how to fix for myself.
(The rationale behind my wanting to avoid configuring any storage is that the real work to do is to upgrade some existing endpoints that have dedicated databases for each feature (Timeouts/Subscriptions/Sagas) and although I've been recommending for a while that we ought to merge these databases, and could thus just configure a NServiceBus/Persistence database for each endpoint, that's not been approved. But I'm loath to add another database for some of these endpoints when they only use timeouts at present)
I'm Dennis van der Stelt, a developer at Particular Software, makers of NServiceBus. I replied on your support case already, but wanted to update this question as well, so that others can find this as well. Evk mentioned most of it already, I just wanted to mention the GH issue and the complete code.
The following code configuration makes sure it doesn't complain about the saga connectionstring.
endpointConfiguration.DisableFeature<NHibernateStorageSession>();
endpointConfiguration.DisableFeature<MessageDrivenSubscriptions>();
endpointConfiguration.DisableFeature<Sagas>();
endpointConfiguration.UsePersistence<NHibernatePersistence, StorageType.Timeouts>();
Then just provide a connectionstring for timeouts
<add name="NServiceBus/Persistence/NHibernate/Timeout" connectionString="server=.\sqlexpress;database=nservicebus; Trusted_Connection=True;" />
That will make it work properly and as expected.
The reason why disabling the NHibernateStorageSession is necessary is because it is a feature inside the persister that is enabled. More information can be found in a GitHub issue I've created based on this case, which can be found here.
I must admit I have not much knowledge about NServiceBus, I just feel obliged to try to help people with high reputation when they ask questions :) So I don't have an explanation why it works like this, only where it fails. In stack trace you can see NHibernateStorageSession.Setup, and NHibernateStorageSession is one of the features. So it fails when trying to activate that feature. Setup starts like this:
protected override void Setup(FeatureConfigurationContext context)
{
NHibernateConfiguration config = new NHibernateConfigurationBuilder(context.Settings, "Saga", new string[1]
{
"StorageConfiguration"
}).Build();
// the rest
}
Where second parameter is connection string suffix. In this case it is hardcoded to "Saga", and as you see - there is no check that Sagas feature is enabled or not. NHibernateConfigurationBuilder then tries to find a connection string for saga (or any more general connection string) and fails to do so with the exception message you observe.
So easy solution is to disable that feature via
endpointConfiguration.DisableFeature<NHibernateStorageSessio‌​n>();
However you should take care of course and ensure functionality you need is not dependent on that feature. It's not entirely clear for me what this feature is for, and I didn't found any documentation for it (though of course its name tells us something about its purpose).
You can do it via (in order of precedence):
It just means the first point would take precedence over the other, if you need to set Saga, but otherwise just do one of the other points:
specifying 'NServiceBus/Persistence' connection string that applies to all persisters
specifying 'NServiceBus/Persistence/connection.connection_string' or 'NServiceBus/Persistence/connection.connection_string_name' value in AppSettings or your NHibernate configuration file.
For most scenarios the 'NServiceBus/Persistence' connection string is the best option.
So you are not required to setup Saga, but it looks like you will not avoid setting a connection string somewhere.

Strange error while impersonating other user

this is next step after
How to run wpf(c#) application by service account and integrated security
I created impersonation successfully, but i am getting some really strange error.
Let me explain situation:
My app is WPF
I have 2 users, my local account (localUser) and service account (saUser).
I am using Frame.Navigate() function to show diferent modules in my frame
I open app with localuser and then impersonate saUser
When i run my app with localUser it works OK (with local admin rights and without)
When i run my app with saUser i am getting this error, no mather if saUser is local admin or not, and the funniest thing is i get error when Navigate(...) is called 2nd time!, first time it works normal... :)
Requested registry access is not allowed.
stackTrace:
at Microsoft.Win32.RegistryKey.OpenSubKey(String name, Boolean writable)
at System.Windows.Application.GetSystemSound(String soundName)
at System.Windows.Application.PlaySound(String soundName)
at System.Windows.Application.FireNavigating(NavigatingCancelEventArgs e, Boolean isInitialNavigation)
at System.Windows.Navigation.NavigationService.FireNavigating(Uri source, Object bp, Object navState, WebRequest request)
at System.Windows.Navigation.NavigationService.HandleNavigating(Uri source, Object content, Object navState, WebRequest newRequest, Boolean navigateOnSourceChanged)
at System.Windows.Navigation.NavigationService.Navigate(Uri source, Object navigationState, Boolean sandboxExternalContent, Boolean navigateOnSourceChanged)
at System.Windows.Navigation.NavigationService.Refresh()
at MyApp.MyNavigation.Navigate(Module modul, Boolean reverse) -> my function
Guyz help, any suggestions? i don't know what is going on...
If i wasn't clear enough ask me...
EDIT:
I am adding some code like asked, just small peace of it where error happens:
I have public static class for navigation
MainWindow mainWin = Application.Current.Windows.Cast<Window>().FirstOrDefault(window => window is MainWindow) as MainWindow;
current <- currentlly selected module
mainFrame <- frame that is showing all pages
// if current module if already selected refresh frame content
if (current.Link == mainWin.mainFrame.NavigationService.CurrentSource.ToString()) mainWin.mainFrame.Refresh();
// else show page content in frame
else mainWin.mainFrame.NavigationService.Navigate(new Uri(current.acLink, UriKind.Relative));
Error happens on Refresh() and Navigate().
I am facing same issue. Is there any solution to this?
There is an article related to how to access HKCU reg key, however it applies to code owned by us & not applicable to for WPF since its code is owned by Microsoft.
[Edit]
My observation is that if WPF user control/Window is initialized prior to impersonation then later on after impersonation there is no issue about how many times they get created; no error is thrown. Can this be done as a workaround?.

add security groups to folder issue / System.Security.Principal.IdentityNotMappedException:

I am struggling with strange issue and I wonder if some one can help me please.
At some point of my program I like to add security groups with appropriate permissions to folder. Steps look like that.
Create Folder
Create Domain Local Security Group
Create Global Security group
Add Global Group to local group
Add Domain Local security group to folder "\domain\dfs\folder"
I got below piece of code to do this from Microsoft page
public static void AddDirectorySecurity(string DirectoryName, string Group, FileSystemRights Rights, InheritanceFlags iFlag, PropagationFlags pFlag, AccessControlType ControlType)
{
// Create a new DirectoryInfo object.
DirectoryInfo dInfo = new DirectoryInfo(DirectoryName);
// Get a DirectorySecurity object that represents the
// current security settings.
DirectorySecurity dSecurity = dInfo.GetAccessControl();
// Add the FileSystemAccessRule to the security settings.
dSecurity.AddAccessRule(new FileSystemAccessRule(Group,Rights,iFlag,pFlag,ControlType));
// Set the new access settings.
dInfo.SetAccessControl(dSecurity); //
}
procedure of adding looks like that:
path = #"\\domain\dfs\folder"
gRDL_RW = "RDL-group-RW"
AddDirectorySecurity(path, gRDL_RW, FileSystemRights.Modify, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow);
It is working fine in my test environment but when I like to run it in production environment I am getting error:
************** Exception Text **************
System.Security.Principal.IdentityNotMappedException: Some or all identity references could not be translated.
at System.Security.Principal.NTAccount.Translate(IdentityReferenceCollection sourceAccounts, Type targetType, Boolean forceSuccess)
at System.Security.Principal.NTAccount.Translate(Type targetType)
at System.Security.AccessControl.CommonObjectSecurity.ModifyAccess(AccessControlModification modification, AccessRule rule, Boolean& modified)
at System.Security.AccessControl.CommonObjectSecurity.AddAccessRule(AccessRule rule)
at Program_dev_1.Form1.button1_Click(Object sender, EventArgs e) in c:\Users\?????????\Documents\Visual Studio 2012\Projects\brite_dev_1\brite_dev_1\Form1.cs:line 191
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
Is it a problem with "Admin rights"? I have God like permissions in production environment.
So what is going on?
I have feeling that for some reason all those user friendly names such as "FileSystemRights.Modify" can not be translated. I check locale on test and prod environment and both are this same.
Is it possible to use raw numbers that are hiding behind those user friendly names?
Maybe there is a other way to add security groups to folder? All I really like to have is a working solution.
Application was crushing when groups were tried to be add to folder because newly created groups were not know to all domain controllers immediately. I had to create procedure that check if newly create groups have been synchronized across whole estate before progressing with the rest of the code. It is not possible or I could not find a method of specifying domain controller used when adding groups to folder permission.

C# Application being blocked by Anti-Virus?

I have a Payroll System that is written using Visual C# Express. I have actually finished coding it already and published it. But whenever I install it on the laptop it is being blocked by Avast! Antivirus as suspicious and stops the process. After that the applciation cannot be started event though it was installed saying that a file is missing. It has this in its details :
PLATFORM VERSION INFO
Windows : 6.1.7601.65536 (Win32NT)
Common Language Runtime : 4.0.30319.296
System.Deployment.dll : 4.0.30319.1 (RTMRel.030319-0100)
clr.dll : 4.0.30319.296 (RTMGDR.030319-2900)
dfdll.dll : 4.0.30319.1 (RTMRel.030319-0100)
dfshim.dll : 4.0.31106.0 (Main.031106-0000)
SOURCES
Deployment url : file:///C:/Users/John%20Jayson/AppData/Roaming/Microsoft/Windows/Start%20Menu/Programs/IT%20Box%20Incorporated/Payroll%20System.appref-ms%7C
ERROR SUMMARY
Below is a summary of the errors, details of these errors are listed later in the log.
* Activation of C:\Users\John Jayson\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\IT Box Incorporated\Payroll System.appref-ms| resulted in exception. Following failure messages were detected:
+ Activation failed.
+ The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
COMPONENT STORE TRANSACTION FAILURE SUMMARY
No transaction error was detected.
WARNINGS
There were no warnings during this operation.
OPERATION PROGRESS STATUS
* [2/15/2013 12:39:05 PM] : Activation of C:\Users\John Jayson\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\IT Box Incorporated\Payroll System.appref-ms| has started.
* [2/15/2013 12:39:05 PM] : Performing necessary update check as specified by the deployment.
ERROR DETAILS
Following errors were detected during this operation.
* [2/15/2013 12:39:05 PM] System.Deployment.Application.DeploymentException (Activation)
- Activation failed.
- Source: System.Deployment
- Stack trace:
at System.Deployment.Application.ComponentStore.ActivateApplication(DefinitionAppId appId, String activationParameter, Boolean useActivationParameter)
at System.Deployment.Application.SubscriptionStore.ActivateApplication(DefinitionAppId appId, String activationParameter, Boolean useActivationParameter)
at System.Deployment.Application.ApplicationActivator.Activate(DefinitionAppId appId, AssemblyManifest appManifest, String activationParameter, Boolean useActivationParameter)
at System.Deployment.Application.ApplicationActivator.ProcessOrFollowShortcut(String shortcutFile, String& errorPageUrl, TempFile& deployFile)
at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivation(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl)
at System.Deployment.Application.ApplicationActivator.ActivateDeploymentWorker(Object state)
--- Inner Exception ---
System.IO.FileNotFoundException
- The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
- Source: System.Deployment
- Stack trace:
at System.Deployment.Application.NativeMethods.CorLaunchApplication(UInt32 hostType, String applicationFullName, Int32 manifestPathsCount, String[] manifestPaths, Int32 activationDataCount, String[] activationData, PROCESS_INFORMATION processInformation)
at System.Deployment.Application.ComponentStore.ActivateApplication(DefinitionAppId appId, String activationParameter, Boolean useActivationParameter)
COMPONENT STORE TRANSACTION DETAILS
No transaction information is available.
So before the window saying Application cannot be started pops up A notification windows from Avast says that it is a Win32:Evo-gen threat.
What should I do?
It also happened with me, I have project in c#, I am using external Ribbon35 control in my project which has option in tabs like creating, scanning, processing etc. When I added 4 new tabs and added buttons on tabs it suddenly shows [Win32:Evo-gen] and exe was blocked. Please remember I did not rename Tab Names instead they were on its default names like [RibbonTab1, captiontext = Scanning] I though Antivirus would have thinking this as malicious behavior from my application, I rename all tabs as like its behavior and problem gone.
(May be hackers don't care about naming controls as their behaviors)
I also faced this problem while working on a project using VB.NET, Then I changed my recent updates back to identify the problem. The problem was with an "Insert" statement where I used below code to get the date value from a Datetimepicker Control directly.
dtpJD.Value.ToString("yyyy/MM/dd HH:mm:ss")
Then I replaced it with a Variable in Insert statement and everything was fine.
parJDDate = dtpJD.Value.ToString("yyyy/MM/dd HH:mm:ss")
found one clue..
-when my application run from folder with foreign characters in the name
then Avast will block it.
-After I renamed folder to contains only eng chars. Problem was solved.
Buddy, it detects as a virus becouse it contains payment, and it thinks you got a ransomware, you can add to exclusions i think, but i never used avast, it's not the best antivirus, if u want a free antivirus with good protection use comodo, or if u want best: kaspersky, or you should use another method, but i prefer to uninstall avast and install a better antivirus software, check the site of the AV Test
and choose the best protection level what you need
Regards

Categories