【问题标题】:Change current Linux user in a C# application running with Mono?在运行 Mono 的 C# 应用程序中更改当前 Linux 用户?
【发布时间】:2013-04-29 22:04:01
【问题描述】:

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

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

1.以 root 身份启动 Mono 并 P/invoke libc 例程,如 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 进程的有效用户?

谢谢!

【问题讨论】:

    标签: c# linux mono


    【解决方案1】:

    以下适用于我的盒子:)

    编辑 #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);
        }
    }
    }
    

    【讨论】:

    • 我不知道 Mono 将 WindowsIdentity 实现为可用的东西 - 感谢您指出!使用示例代码,我仍然遇到使用 seteuid() 时遇到的分段错误。无论如何都接受这个答案。
    • 您使用的是哪个版本的单声道?我在 x64 系统上运行单声道 3.0.7-1 并针对框架 4.0。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    • 2023-04-01
    相关资源
    最近更新 更多