在使用Mono运行的C#应用​​程序中更改当前的Linux用户?

时间:2013-04-22 02:05:45

标签: c# linux mono

我正在为Linux系统开发一个库(CLI程序集)。我想为库的用户提供一种方法来切换当前有效的用户和组。主要原因是提供访问控制(某些用户仅允许某些操作),其次是允许以特定用户身份修改文件系统。

我已经确定了两种可能的方法:

1。以root身份启动Mono,并调用libte例程,如seteuid等

通过设置/ usr / bin / mono的s位然后从我的库中设置有效用户(即Mono运行时启动后)实现此操作会导致Mono终止时崩溃:

ERROR:handles.c:1940:_wapi_handle_update_refs: assertion failed: (thr_ret == 0)

Native stacktrace:

mono2 [0x8bb6c]
  /lib/libc.so.6(__default_rt_sa_restorer_v2+0) [0x4020a5a0]
  /lib/libc.so.6(gsignal+0x40) [0x4020920c]

逻辑上我理解更改Mono的有效用户可能会遇到问题,因为它正在管理大量资源,并且可能会导致问题。

2。处理本机守护程序中的身份验证,而不是更改Mono有效用户

我不确定是否有任何现成的解决方案,但从概念上讲,我正在考虑让一个守护程序以root身份运行,库将与之通信(例如通过POSIX消息队列)执行身份验证。守护程序以root身份运行,以便能够读取/ etc / shadow。 Mono的有效用户不会被更改,但我的库将跟踪该进程正在运行的“等效用户”。不幸的是,这种方法不允许库以不同的用户身份访问文件系统。

问题

我是否坚持使用第二个选项,或者是否有某种方法可以实际更改Mono进程的有效用户?

谢谢!

1 个答案:

答案 0 :(得分:5)

以下内容适用于我的方框:)

编辑#1:这应该以root身份执行。 (摘录自:http://msdn.microsoft.com/en-us/library/w070t6ka.aspx

using System;
using System.Security.Permissions;
using System.Security.Principal;

public class ImpersonationDemo
{
// Test harness. 
// If you incorporate this code into a DLL, be sure to demand FullTrust.
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public static void Main (string[] args)
{
    try {
        // Check the identity.
        Console.WriteLine ("Before impersonation: " + WindowsIdentity.GetCurrent ().Name);

        // Impersonate a user
        using (WindowsIdentity newId = new WindowsIdentity("Your user name"))
        using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
        {
            // Check the identity.
            Console.WriteLine ("After impersonation: " + WindowsIdentity.GetCurrent ().Name);
        }

        // Releasing the context object stops the impersonation 
        // Check the identity.
        Console.WriteLine ("After closing the context: " + WindowsIdentity.GetCurrent ().Name);
    } catch (Exception ex) {
        Console.WriteLine ("Exception occurred. " + ex.Message);
    }
}
}