微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我确定了两种可能的方法

1.以root身份启动Mono,并调用secuid等libc例程

通过设置/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:这应该以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);
    }
}
}

原文地址:https://www.jb51.cc/csharp/99509.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐