none
Security issue needs to be resolved. RRS feed

  • Question

  • public void AddFileSecurity(string fileName, string account,
                FileSystemRights rights, AccessControlType controlType)
            {
                // Adds an ACL entry on the specified file for the specified account.
                FileSecurity fSecurity = File.GetAccessControl(fileName);
                fSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, controlType));
                File.SetAccessControl(fileName, fSecurity);
            }         // AddFileSecurity

    This is how it's called:

    [PrincipalPermissionAttribute(SecurityAction.Demand, Role = @"BUILTINAdministrators")]

    case "AddFileSecurity":
                        Console.Clear();
                        Console.WriteLine("AddFileSecurity\n\n");
                        OpenFileDialog openFileDialog1 = new OpenFileDialog();
                        openFileDialog1.InitialDirectory = "c:\\";
                        openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
                        openFileDialog1.FilterIndex = 2;
                        openFileDialog1.RestoreDirectory = true;
                        openFileDialog1.ShowDialog();
                        string fName = openFileDialog1.FileName;
                        sd.AddFileSecurity(fName, @"DomainName\AccountName",
                            FileSystemRights.FullControl, AccessControlType.Allow);
                        break;

    EXCEPTION

    System.Security.SecurityException
      HResult=0x8013150A
      Message=Request for principal permission failed.
      Source=mscorlib
      StackTrace:
       at System.Security.Permissions.PrincipalPermission.ThrowSecurityException()
       at System.Security.Permissions.PrincipalPermission.Demand()
       at System.Security.PermissionSet.DemandNonCAS()
       at ComeAndGet.SecurityAndDebug.AddFileSecurity(String fileName, String account, FileSystemRights rights, AccessControlType controlType) in C:\VCSharp_Projects\ComeAndGet\ComeAndGet\SecurityAndDebug.cs:line 25
       at ComeAndGet.Form1.comboSecurity_PG9_SelectedIndexChanged(Object sender, EventArgs e) in C:\VCSharp_Projects\ComeAndGet\ComeAndGet\Form1.cs:line 7575
       at System.Windows.Forms.ComboBox.OnSelectedIndexChanged(EventArgs e)
       at System.Windows.Forms.ComboBox.WmReflectCommand(Message& m)
       at System.Windows.Forms.ComboBox.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.SendMessage(HandleRef hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at System.Windows.Forms.Control.SendMessage(Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.Control.ReflectMessageInternal(IntPtr hWnd, Message& m)
       at System.Windows.Forms.Control.WmCommand(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at System.Windows.Forms.NativeWindow.DefWndProc(Message& m)
       at System.Windows.Forms.Control.WmCommand(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ComboBox.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at ComeAndGet.Program.Main() in C:\VCSharp_Projects\ComeAndGet\ComeAndGet\Program.cs:line 16


    • Edited by MyCatAlex Saturday, January 25, 2020 4:45 PM
    Tuesday, January 21, 2020 9:35 PM

Answers

  • I googled with no avail.

    - MyCatAlex

    https://www.google.com/search?sxsrf=ACYBGNRPF0J_nqtsnvqnWC7N1qzS6Hwwjw%3A1579653001741&source=hp&ei=iZcnXpyKK4WntQaC3KGIAQ&q=request+for+principal+permission+failed.+c%23&oq=Request+forprincipal+permission+failed&gs_l=psy-ab.1.0.35i304i39j0i13l3j0i22i30l6.11544.11544..15932...3.0..0.132.132.0j1......0....2j1..gws-wiz.5L__tZwWpdw
    • Marked as answer by MyCatAlex Friday, January 24, 2020 9:50 PM
    Wednesday, January 22, 2020 12:31 AM
  • Hi MyCatAlex,
    Most of the causes of this error are web.config settings or permissions, and I find some similar issues you can refer to.
    [System.Security.SecurityException: Request for principal permission failed]
    [Request for principal permission failed - probably due windows group?]
    [Request for principal permission failed]
    Best Regards,
    Daniel Zhang


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by MyCatAlex Friday, January 24, 2020 9:50 PM
    Wednesday, January 22, 2020 2:58 AM
  • Given the call stack this is a Winforms app, not a web app so web.config answers don't really help here.

    The exception is occurring on line 23. What line is that?

    Why are you calling SetPrincipalPolicy just to enumerate the groups of the current user? It doesn't require any of this code.


    Michael Taylor http://www.michaeltaylorp3.net

    • Marked as answer by MyCatAlex Friday, January 24, 2020 9:50 PM
    Wednesday, January 22, 2020 2:53 PM
    Moderator
  • Works for me, are you trying to use this on yourself?

    using System;
    using System.Collections.Generic;
    using System.Security.Principal;
    using System.Text;
    
    namespace Examples.Classes
    {
        public class SecurityCode
        {
            public static void GetRole()
            {
                var sbld = new StringBuilder();
                AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
                WindowsIdentity curIdentity = WindowsIdentity.GetCurrent();
                WindowsPrincipal myPrincipal = new WindowsPrincipal(curIdentity);
                List<string> groups = new List<string>();
                foreach (IdentityReference irc in curIdentity.Groups)
                {
                    groups.Add(((NTAccount)irc.Translate(typeof(NTAccount))).Value);
                }
    
                sbld.Append("Name: " + curIdentity.Name + " System: curIdentity.IsSystem " + " Authenticated: " +
                            curIdentity.IsAuthenticated + "  BuiltinAdmin: " + "Identiry: " +
                            myPrincipal.IsInRole(WindowsBuiltInRole.Administrator) +
                            myPrincipal.Identity + string.Join($",\n", groups.ToArray()));
    
                Console.WriteLine($@"Name: {curIdentity.Name} System: {curIdentity.IsSystem} Authenticated: {curIdentity.IsAuthenticated} BuiltinAdmin: {(myPrincipal.IsInRole(WindowsBuiltInRole.Administrator) ? "True" : "False")} Identity: {myPrincipal.Identity} Groups: {string.Join(string.Format(",{0}tt", Environment.NewLine), groups.ToArray())}");
    
    
                try
                {
                    Console.WriteLine(Environment.NewLine);
                }
                catch (System.Security.SecurityException scx)
                {
                    Console.WriteLine($"{scx.Message} {scx.FirstPermissionThatFailed}");
                }
                Console.WriteLine(Environment.NewLine);
            }            // GetRole
        }
    }
    


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    • Marked as answer by MyCatAlex Friday, January 24, 2020 9:51 PM
    Wednesday, January 22, 2020 3:28 PM
    Moderator
  • Commenting out the permission should resolve the role issue. You're saying you're still getting an exception on the same line with the same message? Are you sure your code is actually compiling and you aren't accidentally running a previous version with that CAS thing included?

    Why do you need this permission anyway? Did you try leaving the permission there and fixing the role name, which is currently wrong? What error did you get then?


    Michael Taylor http://www.michaeltaylorp3.net

    • Marked as answer by MyCatAlex Sunday, January 26, 2020 6:31 PM
    Saturday, January 25, 2020 10:55 PM
    Moderator
  • The permission is an aspect of Code Access Security (CAS). CAS was in the original version of the framework and could be used to sandbox code. However it has long sense been all but abandoned because it doesn't really solve anything that cannot already be done better in a different way

    With your specific code all you're doing is demanding that the user who calls your method is in the Administrators role. With the advent of UAC this is neither good nor desired. Again, remove all that permission code because it isn't doing anything. If you require the user to be an admin then you should expose that via the UI. In the code the OS will naturally fail the call if there is a permissions issue so you don't need any of that explicitly.

    As for the exception you're now getting, you are passing an account name, as a string, to the method and it cannot recognize it. This is common because it needs to map that account name to a SID so it can apply the appropriate ACL. In general you should take the account information as an IdentityReference. This may either be a formal user name or the SID for such a user. To take a user name and convert it to an identity reference use the NTAccount class. This handles the conversion. If the given string is not a valid user name then you'll get the exception you specified. That means the user account is a domain account (in which case you need to use the overload) or the user account simply isn't valid. Note that the account can be a user or group so it doesn't matter.

    //Users group of local machine
    var users = new NTAccount("Users");
    
    var rule = new FileSystemAccessRule(users, ...
    Note that IdentityReference doesn't validate the user/group exists, it is just a wrapper. Validation occurs when the underlying account information is needed (such as when adding to a security rule). If an exception occurs at this point then the account is invalid.


    Michael Taylor http://www.michaeltaylorp3.net

    • Marked as answer by MyCatAlex Monday, January 27, 2020 12:58 PM
    Sunday, January 26, 2020 10:03 PM
    Moderator
  • I don't understand if you're having issues anymore or not. Once you add the call to set the access control rules then it'll show up in the UI. To test this, remove those permissions in the UI first. Note also the inheritance stuff. If it says it is inherited then the permission is coming from a parent. 

    Michael Taylor http://www.michaeltaylorp3.net

    • Marked as answer by MyCatAlex Monday, January 27, 2020 7:09 PM
    Monday, January 27, 2020 6:09 PM
    Moderator

  • (2) I would like to write a simple program eventually that will go from folder to folder and make the access rights for every file as "admin." Is it possible? Will it protect me in case of an intruder?

    Not in all cases. Common hacker/malware attacks often involve escalation of privileges.

    Privilege escalation
    https://en.wikipedia.org/wiki/Privilege_escalation

    What Is Privilege Escalation and Why Is It Important?
    https://www.netsparker.com/blog/web-security/privilege-escalation/

    - Wayne

    • Marked as answer by MyCatAlex Monday, January 27, 2020 7:08 PM
    Monday, January 27, 2020 6:53 PM

All replies

  • There are plenty of articles concerning the message, and I suggest that you use Bing or Google to possibly find a resolution/

    Request forprincipal permission failed.

    Tuesday, January 21, 2020 11:28 PM
  • I googled with no avail.

    - MyCatAlex

    Wednesday, January 22, 2020 12:12 AM
  • I googled with no avail.

    - MyCatAlex

    https://www.google.com/search?sxsrf=ACYBGNRPF0J_nqtsnvqnWC7N1qzS6Hwwjw%3A1579653001741&source=hp&ei=iZcnXpyKK4WntQaC3KGIAQ&q=request+for+principal+permission+failed.+c%23&oq=Request+forprincipal+permission+failed&gs_l=psy-ab.1.0.35i304i39j0i13l3j0i22i30l6.11544.11544..15932...3.0..0.132.132.0j1......0....2j1..gws-wiz.5L__tZwWpdw
    • Marked as answer by MyCatAlex Friday, January 24, 2020 9:50 PM
    Wednesday, January 22, 2020 12:31 AM
  • Hi MyCatAlex,
    Most of the causes of this error are web.config settings or permissions, and I find some similar issues you can refer to.
    [System.Security.SecurityException: Request for principal permission failed]
    [Request for principal permission failed - probably due windows group?]
    [Request for principal permission failed]
    Best Regards,
    Daniel Zhang


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by MyCatAlex Friday, January 24, 2020 9:50 PM
    Wednesday, January 22, 2020 2:58 AM
  • Given the call stack this is a Winforms app, not a web app so web.config answers don't really help here.

    The exception is occurring on line 23. What line is that?

    Why are you calling SetPrincipalPolicy just to enumerate the groups of the current user? It doesn't require any of this code.


    Michael Taylor http://www.michaeltaylorp3.net

    • Marked as answer by MyCatAlex Friday, January 24, 2020 9:50 PM
    Wednesday, January 22, 2020 2:53 PM
    Moderator
  • Works for me, are you trying to use this on yourself?

    using System;
    using System.Collections.Generic;
    using System.Security.Principal;
    using System.Text;
    
    namespace Examples.Classes
    {
        public class SecurityCode
        {
            public static void GetRole()
            {
                var sbld = new StringBuilder();
                AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
                WindowsIdentity curIdentity = WindowsIdentity.GetCurrent();
                WindowsPrincipal myPrincipal = new WindowsPrincipal(curIdentity);
                List<string> groups = new List<string>();
                foreach (IdentityReference irc in curIdentity.Groups)
                {
                    groups.Add(((NTAccount)irc.Translate(typeof(NTAccount))).Value);
                }
    
                sbld.Append("Name: " + curIdentity.Name + " System: curIdentity.IsSystem " + " Authenticated: " +
                            curIdentity.IsAuthenticated + "  BuiltinAdmin: " + "Identiry: " +
                            myPrincipal.IsInRole(WindowsBuiltInRole.Administrator) +
                            myPrincipal.Identity + string.Join($",\n", groups.ToArray()));
    
                Console.WriteLine($@"Name: {curIdentity.Name} System: {curIdentity.IsSystem} Authenticated: {curIdentity.IsAuthenticated} BuiltinAdmin: {(myPrincipal.IsInRole(WindowsBuiltInRole.Administrator) ? "True" : "False")} Identity: {myPrincipal.Identity} Groups: {string.Join(string.Format(",{0}tt", Environment.NewLine), groups.ToArray())}");
    
    
                try
                {
                    Console.WriteLine(Environment.NewLine);
                }
                catch (System.Security.SecurityException scx)
                {
                    Console.WriteLine($"{scx.Message} {scx.FirstPermissionThatFailed}");
                }
                Console.WriteLine(Environment.NewLine);
            }            // GetRole
        }
    }
    


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    • Marked as answer by MyCatAlex Friday, January 24, 2020 9:51 PM
    Wednesday, January 22, 2020 3:28 PM
    Moderator
  • Given the call stack this is a Winforms app, not a web app so web.config answers don't really help here.

    The exception is occurring on line 23. What line is that?

    Why are you calling SetPrincipalPolicy just to enumerate the groups of the current user? It doesn't require any of this code.


    Michael Taylor http://www.michaeltaylorp3.net

    Michael hi,

    Somehow I messed it all up. I posted in the OP a different method but the Exception for the right method. Karen correctly said "It worked for me." It worked for me too.

    I replaced now the source code for the correct one, the source code in the OP, and now everything is in sync. I profusely apologize. It still gives me an exception. BTW, the line number 23 is this

    public void AddFileSecurity(string fileName, string account,...

    that is, the first line in the method that throws the Exception..

    Sorry, - MyCatAlex.

    Friday, January 24, 2020 10:06 PM
  • So the call to `File.GetAccessControl` is throwing an exception. What exception? Please post the callstack and exception message. What is value of the file you're passing in? Is this a web app or what?

    Michael Taylor http://www.michaeltaylorp3.net

    Friday, January 24, 2020 10:14 PM
    Moderator
  • So the call to `File.GetAccessControl` is throwing an exception. What exception? Please post the callstack and exception message. What is value of the file you're passing in? Is this a web app or what?

    Michael Taylor http://www.michaeltaylorp3.net

    Michael hi, Sorry for perpetuating confusion. Somehow I wiped out the Exception when I replaced the source code. It is a WindowsForms, not a Web application. It is an old project of mine ComeAndGet, super large now. Every time I tried to use this method (AddFileSecurity) I might have selected a different file in the directory to add security, but it should not matter. Every time I had an exception. The Exception now is in the OP.

    I will try to work on this problem today. It is about time. Your help will be appreciated.

    I changed the source code this way:. As you see the name of the file is not even mentioned here.

    public void AddFileSecurity(string fileName, string account,
                FileSystemRights rights, AccessControlType controlType)
            {            
                AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
                PrincipalPermission principalPerm = new PrincipalPermission(null, "Administrators");
                principalPerm.Demand();
                Console.WriteLine("Demand succeeded.");
                /*
                // Adds an ACL entry on the specified file for the specified account.            
                FileSecurity fSecurity = File.GetAccessControl(fileName);
                fSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, controlType));
                File.SetAccessControl(fileName, fSecurity);
                */
            }         // AddFileSecurity

    As you can see, I commented the old source code out. I got the same or similar exception

    System.Security.SecurityException
      HResult=0x8013150A
      Message=Request for principal permission failed.
      Source=mscorlib
      StackTrace:
       at System.Security.Permissions.PrincipalPermission.ThrowSecurityException()
       at System.Security.Permissions.PrincipalPermission.Demand()
       at System.Security.PermissionSet.DemandNonCAS()
       at ComeAndGet.SecurityAndDebug.AddFileSecurity(String fileName, String account, FileSystemRights rights, AccessControlType controlType) in C:\VCSharp_Projects\ComeAndGet\ComeAndGet\SecurityAndDebug.cs:line 25
       at ComeAndGet.Form1.comboSecurity_PG9_SelectedIndexChanged(Object sender, EventArgs e) in C:\VCSharp_Projects\ComeAndGet\ComeAndGet\Form1.cs:line 7578
       at System.Windows.Forms.ComboBox.OnSelectedIndexChanged(EventArgs e)
       at System.Windows.Forms.ComboBox.WmReflectCommand(Message& m)
       at System.Windows.Forms.ComboBox.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.SendMessage(HandleRef hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at System.Windows.Forms.Control.SendMessage(Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.Control.ReflectMessageInternal(IntPtr hWnd, Message& m)
       at System.Windows.Forms.Control.WmCommand(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at System.Windows.Forms.NativeWindow.DefWndProc(Message& m)
       at System.Windows.Forms.Control.WmCommand(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ComboBox.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at ComeAndGet.Program.Main() in C:\VCSharp_Projects\ComeAndGet\ComeAndGet\Program.cs:line 16
    

    Thank you, -MyCatAlex



    • Edited by MyCatAlex Saturday, January 25, 2020 5:29 PM
    Saturday, January 25, 2020 2:37 PM
  • I am getting kind of desperate with this problem. I am unquestionably the only user and the Administrator on my Windows 10 computer, HP Pavilion. What else does the Windows want from me? Where is the way to fix it?

    - MyCatAlex

    Saturday, January 25, 2020 6:34 PM
  • Ah, you are explicitly putting a permission attribute on your code. Remove that line as you shouldn't need it. The issue is that your role value is wrong. It is looking for a role that doesn't exist. You shouldn't need this line at all so remove it. But if you did need it then you'd use 

    [PrincipalPermissionAttribute(SecurityAction.Demand, Role = "Administrators")]
    However with UAC turned on this isn't going to work properly unless you elevate anyway. Again, you shouldn't need this demand so I'd just remove it. If you need to lock down a portion of your app to admins only then you'll need to look into UAC and elevation of privileges, not the old school CAS stuff that has mostly gone away.


    Michael Taylor http://www.michaeltaylorp3.net

    Saturday, January 25, 2020 7:38 PM
    Moderator
  • Ah, you are explicitly putting a permission attribute on your code. Remove that line as you shouldn't need it. The issue is that your role value is wrong. It is looking for a role that doesn't exist. You shouldn't need this line at all so remove it. But if you did need it then you'd use 

    [PrincipalPermissionAttribute(SecurityAction.Demand, Role = "Administrators")]
    However with UAC turned on this isn't going to work properly unless you elevate anyway. Again, you shouldn't need this demand so I'd just remove it. If you need to lock down a portion of your app to admins only then you'll need to look into UAC and elevation of privileges, not the old school CAS stuff that has mostly gone away.


    Michael Taylor http://www.michaeltaylorp3.net

    Michael hi,

    I get exceptions anyway. I've tried many variants including what you suggested. UAC only has an option of notification, Notify me in case a software is installed or I make changes in Windows Setting. It set at the max (upper limit) in my PC. So far I have no solution.

    Thanks, - MyCatAlex

    Saturday, January 25, 2020 10:51 PM
  • Commenting out the permission should resolve the role issue. You're saying you're still getting an exception on the same line with the same message? Are you sure your code is actually compiling and you aren't accidentally running a previous version with that CAS thing included?

    Why do you need this permission anyway? Did you try leaving the permission there and fixing the role name, which is currently wrong? What error did you get then?


    Michael Taylor http://www.michaeltaylorp3.net

    • Marked as answer by MyCatAlex Sunday, January 26, 2020 6:31 PM
    Saturday, January 25, 2020 10:55 PM
    Moderator
  • Commenting out the permission should resolve the role issue. You're saying you're still getting an exception on the same line with the same message? Are you sure your code is actually compiling and you aren't accidentally running a previous version with that CAS thing included?

    Why do you need this permission anyway? Did you try leaving the permission there and fixing the role name, which is currently wrong? What error did you get then?


    Michael Taylor http://www.michaeltaylorp3.net

    Incredibly you are correct. It resolved the issue. How come? I want an explanation. I've known you for a long time, perhaps 15-20, you've helped me before. You are a genius!

    This is what I did.

     public class SecurityAndDebug
        {
      //      [PrincipalPermissionAttribute(SecurityAction.Demand, Role = "Administrators")]
     //       [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]
    
            public void AddFileSecurity(string fileName, string account,
                FileSystemRights rights, AccessControlType controlType)
            {           
                AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
                PrincipalPermission principalPerm = new PrincipalPermission(null, "Administrators");
                principalPerm.Demand();
                Console.WriteLine("Demand succeeded.");
                /*
                // Adds an ACL entry on the specified file for the specified account.            
                FileSecurity fSecurity = File.GetAccessControl(fileName);
                fSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, controlType));
                File.SetAccessControl(fileName, fSecurity);
                */
            }         // AddFileSecurity

    I got a response: "Demand succeeded."

    So, what is the next step?

    (1) does it mean that this file (a .cs file I chose at random) is protected? If so, then protected of what? Is it protected from ransomware? Or from stealing my code which I consider a possible threat also?

    Holly molly, it is amazing how little I know about computer security and how much I need to learn.

    But looking carefully, you may notice that this code is not using the file name at all! What kind of

    code is it?

    So, I've decided to comment out the upper part of the code in this method and open up the lower part. See what happened:

     public class SecurityAndDebug
        {
      //      [PrincipalPermissionAttribute(SecurityAction.Demand, Role = "Administrators")]
     //       [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]
    
            public void AddFileSecurity(string fileName, string account,
                FileSystemRights rights, AccessControlType controlType)
            {           
          /*      AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
                PrincipalPermission principalPerm = new PrincipalPermission(null, "Administrators");
                principalPerm.Demand();
                Console.WriteLine("Demand succeeded.");
                */
                // Adds an ACL entry on the specified file for the specified account.            
                FileSecurity fSecurity = File.GetAccessControl(fileName);
                fSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, controlType));
                File.SetAccessControl(fileName, fSecurity);
                
            }         // AddFileSecurity

    I got an excpetion but it is a totally different exception:

    System.Security.Principal.IdentityNotMappedException
      HResult=0x80131501
      Message=Some or all identity references could not be translated.
      Source=mscorlib
      StackTrace:
       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 ComeAndGet.SecurityAndDebug.AddFileSecurity(String fileName, String account, FileSystemRights rights, AccessControlType controlType) in C:\VCSharp_Projects\ComeAndGet\ComeAndGet\SecurityAndDebug.cs:line 32
       at ComeAndGet.Form1.comboSecurity_PG9_SelectedIndexChanged(Object sender, EventArgs e) in C:\VCSharp_Projects\ComeAndGet\ComeAndGet\Form1.cs:line 7578
       at System.Windows.Forms.ComboBox.OnSelectedIndexChanged(EventArgs e)
       at System.Windows.Forms.ComboBox.WmReflectCommand(Message& m)
       at System.Windows.Forms.ComboBox.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.SendMessage(HandleRef hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at System.Windows.Forms.Control.SendMessage(Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.Control.ReflectMessageInternal(IntPtr hWnd, Message& m)
       at System.Windows.Forms.Control.WmCommand(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at System.Windows.Forms.NativeWindow.DefWndProc(Message& m)
       at System.Windows.Forms.Control.WmCommand(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ComboBox.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at ComeAndGet.Program.Main() in C:\VCSharp_Projects\ComeAndGet\ComeAndGet\Program.cs:line 16
    

    So, it is a run around!

    Many thanks, Michael.

    - MyCatAlex



    • Edited by MyCatAlex Sunday, January 26, 2020 6:53 PM
    Sunday, January 26, 2020 6:39 PM
  • The permission is an aspect of Code Access Security (CAS). CAS was in the original version of the framework and could be used to sandbox code. However it has long sense been all but abandoned because it doesn't really solve anything that cannot already be done better in a different way

    With your specific code all you're doing is demanding that the user who calls your method is in the Administrators role. With the advent of UAC this is neither good nor desired. Again, remove all that permission code because it isn't doing anything. If you require the user to be an admin then you should expose that via the UI. In the code the OS will naturally fail the call if there is a permissions issue so you don't need any of that explicitly.

    As for the exception you're now getting, you are passing an account name, as a string, to the method and it cannot recognize it. This is common because it needs to map that account name to a SID so it can apply the appropriate ACL. In general you should take the account information as an IdentityReference. This may either be a formal user name or the SID for such a user. To take a user name and convert it to an identity reference use the NTAccount class. This handles the conversion. If the given string is not a valid user name then you'll get the exception you specified. That means the user account is a domain account (in which case you need to use the overload) or the user account simply isn't valid. Note that the account can be a user or group so it doesn't matter.

    //Users group of local machine
    var users = new NTAccount("Users");
    
    var rule = new FileSystemAccessRule(users, ...
    Note that IdentityReference doesn't validate the user/group exists, it is just a wrapper. Validation occurs when the underlying account information is needed (such as when adding to a security rule). If an exception occurs at this point then the account is invalid.


    Michael Taylor http://www.michaeltaylorp3.net

    • Marked as answer by MyCatAlex Monday, January 27, 2020 12:58 PM
    Sunday, January 26, 2020 10:03 PM
    Moderator
  • The permission is an aspect of Code Access Security (CAS). CAS was in the original version of the framework and could be used to sandbox code. However it has long sense been all but abandoned because it doesn't really solve anything that cannot already be done better in a different way

    With your specific code all you're doing is demanding that the user who calls your method is in the Administrators role. With the advent of UAC this is neither good nor desired. Again, remove all that permission code because it isn't doing anything. If you require the user to be an admin then you should expose that via the UI. In the code the OS will naturally fail the call if there is a permissions issue so you don't need any of that explicitly.

    As for the exception you're now getting, you are passing an account name, as a string, to the method and it cannot recognize it. This is common because it needs to map that account name to a SID so it can apply the appropriate ACL. In general you should take the account information as an IdentityReference. This may either be a formal user name or the SID for such a user. To take a user name and convert it to an identity reference use the NTAccount class. This handles the conversion. If the given string is not a valid user name then you'll get the exception you specified. That means the user account is a domain account (in which case you need to use the overload) or the user account simply isn't valid. Note that the account can be a user or group so it doesn't matter.

    //Users group of local machine
    var users = new NTAccount("Users");
    
    var rule = new FileSystemAccessRule(users, ...
    Note that IdentityReference doesn't validate the user/group exists, it is just a wrapper. Validation occurs when the underlying account information is needed (such as when adding to a security rule). If an exception occurs at this point then the account is invalid.


    Michael Taylor http://www.michaeltaylorp3.net

    Michael hi,

    Not claiming that I understood everything you've said, especially the abbreviations, I still made a very insignifican change and the method worked! There is no exception now.

    This is what I did:

    switch (comboSecurity_PG9.Text.Trim())
                {
                    case "AddFileSecurity":
                        Console.Clear();
                        Console.WriteLine("AddFileSecurity\n\n");
                        OpenFileDialog openFileDialog1 = new OpenFileDialog();
                        openFileDialog1.InitialDirectory = "c:\\";
                        openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
                        openFileDialog1.FilterIndex = 2;
                        openFileDialog1.RestoreDirectory = true;
                        openFileDialog1.ShowDialog();
                        string fName = openFileDialog1.FileName;
                        string AccName = @"DESKTOP-54NQG25\\Admin";  // <== I said here "Admin" instead of "Administrators"
                        sd.AddFileSecurity(fName, AccName,
                            FileSystemRights.FullControl, AccessControlType.Allow);
                        break;

    As you can see, I said "Admin" Instead of "Administrators" and that was the key. Sure it is difficult to map abstract "administrators" to anything. You think I want to claim a victory, not at all. I have now more questions than before.

    (1) I want to be able to get EXCLUSIVE rights for some files, with no "guest" access or someone else. Even the system access is not wanted.

    (2) I would like to write a simple program eventually that will go from folder to folder and make the access rights for every file as "admin." Is it possible? Will it protect me in case of an intruder?

    (3) Is it a step in the right direction?

    (4) I want to question every file programmatically and make sure the access right that I set up is there, that has been a change. Also I want to know what other access rights are there in every file.

    (5) after I ran this method there was no feedback. I want to get some feedback from the action, to see if the change has taken place.

    Many thanks, - MyCatAlex



    • Edited by MyCatAlex Monday, January 27, 2020 4:15 PM
    Monday, January 27, 2020 3:54 PM
  • With that change you are giving the user Admin on that machine the permissions you specified. This is different than Administrators which is the administrator group on the machine. If you want to give the administrators group permission then use `Administrators`, no machine name. 


    Michael Taylor http://www.michaeltaylorp3.net

    Monday, January 27, 2020 4:07 PM
    Moderator
  • I just looked at the file's properties and found that no changes appeared to have been made.

    It seems nobody has full control either.

    MyCatAlex

    Monday, January 27, 2020 5:44 PM
  • After you add the access rule(s) to the object you have to save them using the SetAccessControl method.

    Michael Taylor http://www.michaeltaylorp3.net

    Monday, January 27, 2020 5:48 PM
    Moderator
  • On Security tab for this file properties it is a different story.

    So, manually I may add or remove permissions. although I don't know if it will do me any good.

    - MyCatAlex

    • Edited by MyCatAlex Monday, January 27, 2020 5:54 PM
    Monday, January 27, 2020 5:50 PM
  • OK, I compared this file with the other files (also .cs) in this directory and it is clearly evident that I ADDED one user "hostName\\Admin" to the file with full rights. Other files do not have this user. I think it is a progress of sorts.

    - MyCatAlex


    • Edited by MyCatAlex Monday, January 27, 2020 6:08 PM
    Monday, January 27, 2020 6:06 PM
  • I don't understand if you're having issues anymore or not. Once you add the call to set the access control rules then it'll show up in the UI. To test this, remove those permissions in the UI first. Note also the inheritance stuff. If it says it is inherited then the permission is coming from a parent. 

    Michael Taylor http://www.michaeltaylorp3.net

    • Marked as answer by MyCatAlex Monday, January 27, 2020 7:09 PM
    Monday, January 27, 2020 6:09 PM
    Moderator

  • (2) I would like to write a simple program eventually that will go from folder to folder and make the access rights for every file as "admin." Is it possible? Will it protect me in case of an intruder?

    Not in all cases. Common hacker/malware attacks often involve escalation of privileges.

    Privilege escalation
    https://en.wikipedia.org/wiki/Privilege_escalation

    What Is Privilege Escalation and Why Is It Important?
    https://www.netsparker.com/blog/web-security/privilege-escalation/

    - Wayne

    • Marked as answer by MyCatAlex Monday, January 27, 2020 7:08 PM
    Monday, January 27, 2020 6:53 PM
  • I don't understand if you're having issues anymore or not. Once you add the call to set the access control rules then it'll show up in the UI. To test this, remove those permissions in the UI first. Note also the inheritance stuff. If it says it is inherited then the permission is coming from a parent. 

    Michael Taylor http://www.michaeltaylorp3.net

    Michael hello,

    Answering your question, I don't have any more issues with the OP question. I consider it to have been resolved, although I have a long path in front of me with many other questions on the horizon. :-)

    Thank you for your help, - MyCatAlex


    • Edited by MyCatAlex Thursday, January 30, 2020 2:24 PM
    Thursday, January 30, 2020 1:09 PM