c - 允许程序特权在启动时从任何帐户更改 PC 名称?

标签 c windows startup uac impersonation

我正在编写一个基本程序,在启动时将 PC 的事件 NIC 发送到服务器并适本地更改 PC 的主机名。该过程概述如下。

程序执行过程:

  1. 由任何帐户自动启动
  2. 收集事件的 NIC 地址
  3. 向服务器发送 NIC 地址
  4. 接收分配的 PC 主机名
  5. 比较当前和分配的主机名
  6. 必要时更改主机名

我让程序按照设计完美地执行步骤 1-5。它能够收集事件的 NIC 地址,为服务器准备数据包并接收响应。问题是当程序到达第 6 步时。在 Windows XP 上,如果仅以管理员身份登录,程序会毫无问题地更改主机名。在 Windows Vista、7 和 8 上,该程序无法更改计算机主机名(由于需要 UAC 提升),或者如果登录到没有管理员权限的用户帐户,则它缺少必要的权限。

在向程序添加应用程序 list 以向用户和 Windows 发出程序需要管理员权限的信号后,程序无法启动,因为 Windows Vista 及更高版本不会启动需要管理员权限的程序。

在前面的 list 修改之后,我在机器上创建了一个单独的管理员用户帐户,这样程序就可以模拟管理员帐户并拥有对计算机的完全访问权限,而无需事件用户是管理员。在 Windows XP 上它再次完美运行。在 Windows 7 上,该程序会抛出“权限被拒绝”消息。我已经尝试使用 advapi32.dll 和 userenv.dll 进行 Process.Start 和 C Sharp 模拟,如下所示。

允许程序特权在启动时从任何帐户更改 PC 名称的最佳方法是什么?

process.start方法

ProcessStartInfo myProcess = new ProcessStartInfo(path);
myProcess.UserName = username;
myProcess.Password = MakeSecureString(password);
myProcess.WorkingDirectory = @"C:\Windows\System32";
myProcess.UseShellExecute = false;
myProcess.Verb = "runas";
Process.Start(myProcess);

模拟方法

static void Imp()
        {
            WindowsImpersonationContext m_ImpersonationContext = null;
            WindowsIdentity m_ImpersonatedUser;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;
            const int SecurityImpersonation = 2;
            const int TokenType = 1;
            const int LOGON32_LOGON_INTERACTIVE = 2;
            const int LOGON32_PROVIDER_DEFAULT = 0;

            try
            {
                if (RevertToSelf())
                {
                    Console.WriteLine("Before impersonation: " +
                                      WindowsIdentity.GetCurrent().Name);

                    String userName = "sfadmin";
                    //IntPtr password = GetPassword();

                    if (LogonUser(userName, Environment.MachineName,
                                  "d31ux3", LOGON32_LOGON_INTERACTIVE,
                                  LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                    {
                        if (DuplicateToken(token, SecurityImpersonation, ref tokenDuplicate) != 0)
                        {
                            m_ImpersonatedUser = new WindowsIdentity(tokenDuplicate);
                            using (m_ImpersonationContext = m_ImpersonatedUser.Impersonate())
                            {
                                if (m_ImpersonationContext != null)
                                {
                                    Console.WriteLine("After Impersonation succeeded: " +
                                        Environment.NewLine +
                                        "User Name: " +
                                        WindowsIdentity.GetCurrent(
                                           TokenAccessLevels.MaximumAllowed).Name +
                                        Environment.NewLine +
                                        "SID: " +
                                        WindowsIdentity.GetCurrent(
                                           TokenAccessLevels.MaximumAllowed).User.Value);

                                    #region LoadUserProfile
                                    // Load user profile
                                    ProfileInfo profileInfo = new ProfileInfo();
                                    profileInfo.dwSize = Marshal.SizeOf(profileInfo);
                                    profileInfo.lpUserName = userName;
                                    profileInfo.dwFlags = 1;
                                    Boolean loadSuccess =
                                            LoadUserProfile(tokenDuplicate, ref profileInfo);

                                    if (!loadSuccess)
                                    {
                                        Console.WriteLine("LoadUserProfile() failed with error code: " +
                                                          Marshal.GetLastWin32Error());
                                        throw new Win32Exception(Marshal.GetLastWin32Error());
                                    }

                                    if (profileInfo.hProfile == IntPtr.Zero)
                                    {
                                        Console.WriteLine(
                                            "LoadUserProfile() failed - HKCU handle " +
                                            "was not loaded. Error code: " +
                                            Marshal.GetLastWin32Error());
                                        throw new Win32Exception(Marshal.GetLastWin32Error());
                                    }
                                    #endregion

                                    CloseHandle(token);
                                    CloseHandle(tokenDuplicate);

                                    // Do tasks after impersonating successfully
                                    //AccessFileSystem();

                                    RunAs("SolarFrost.exe", "sfadmin", "d31ux3");


                                    // Access HKCU after loading user's profile
                                    //AccessHkcuRegistry(profileInfo.hProfile);

                                    // Unload user profile
                                    // MSDN remarks
                                    // http://msdn.microsoft.com/en-us/library/bb762282(VS.85).aspx
                                    // Before calling UnloadUserProfile you should
                                    // ensure that all handles to keys that you have opened in the
                                    // user's registry hive are closed. If you do not
                                    // close all open registry handles, the user's profile fails
                                    // to unload. For more information, see Registry Key
                                    // Security and Access Rights and Registry Hives.
                                    UnloadUserProfile(tokenDuplicate, profileInfo.hProfile);

                                    // Undo impersonation
                                    m_ImpersonationContext.Undo();
                                }
                            }
                        }
                        else
                        {
                            Console.WriteLine("DuplicateToken() failed with error code: " +
                                              Marshal.GetLastWin32Error());
                            throw new Win32Exception(Marshal.GetLastWin32Error());
                        }
                    }
                }
            }
            catch (Exception Ex)
            {
                System.IO.File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "log.txt", Ex.ToString() + "\r\n");
            }
            finally
            {
                if (token != IntPtr.Zero) CloseHandle(token);
                if (tokenDuplicate != IntPtr.Zero) CloseHandle(tokenDuplicate);

                Console.WriteLine("After finished impersonation: " +
                                  WindowsIdentity.GetCurrent().Name);
            }

最佳答案

您可以使用 Task Scheduler 设置任务在 Windows 中。将任务设置为在启动时运行,无论是否有人登录。还要确保任务在 highest privilege 处运行(复选框)。这应该可以解决您的问题。

关于c - 允许程序特权在启动时从任何帐户更改 PC 名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18048063/

相关文章:

c - 如何使用过滤器驱动程序(内核)捕获文件访问尝试并提供对话框以允许/拒绝(用户)?

windows - 如何将 Windows 更新设置为从不使用 PowerShell 检查更新?

c++ - 用于读取输入文件的内存映射文件有多安全?

c++ - C++ 可以在全局范围内拥有代码吗?

database - Freebase:我公司的整个数据库都基于它值得吗?

windows - 使用批处理添加一个exe启动

c - 如何确保套接字 I/O 的 NULL 终止字符串 C 编程

c - 如何将矩阵应用于opencv中的图像?

c - 添加滚动功能

c - fscanf 无法工作 - 程序正在抛出错误