在Windows 2008上编程创建漫游用户配置文件

3

问题:

通过LoadUserProfile API为漫游用户登录和加载配置文件时,无法创建正确的配置文件。这只会在Windows 2008(UAC开启或关闭)下发生。使用标准的Windows登录方式可以正常工作,同样的代码在Windows 2003上也可以正常工作。

日志:

  1. http://drop.io/6t2b3f3 通过以下命令创建的用户配置文件服务的ETL: logman -start profile -p {eb7428f5-ab1f-4322-a4cc-1f1a9b2c5e98} 255 3 –ets 需要由能够访问源代码的人分析该文件,并希望能够解决为什么配置文件始终加载为临时文件的问题。

环境:

  1. Windows 2008模式域/森林
  2. 服务器fs001 - Windows 2008 Standard SP2 x86盒子
  3. 在fs001上的文件共享“Share”,Everyone+SYSTEM在共享和ntfs上都有完全控制权限。

复现步骤:

  1. 创建带有漫游配置文件设置为\fs001\Share\tuser1\profile的域用户tuser1
  2. 使用任何域管理员和fs001上的本地管理员帐户运行此程序(如果UAC开启,请以管理员身份运行),会在c:\users\temp*中加载临时用户配置文件,而不是c:\users\tuser1。

ETL可能是这里最好的方法,将提供最快的诊断。对于用户配置文件服务svchost实例和跟踪系统级别的登录的Procmon并没有揭示出太多有关出错原因的信息(如果需要我可以提供更多信息,但这是一个死胡同)。Windows 2003上的userenv.log会有所帮助,但ETL只能由MSFT的某个人分析。

有什么想法吗?

谢谢, Alex

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;

namespace consoleLogon {
  class Program {
    #region Helpers for setting privilegies functionality
    [StructLayout(LayoutKind.Sequential, Pack = 4)]
    public struct LUID_AND_ATTRIBUTES {
        public long Luid;
        public int Attributes;
    }

    [StructLayout(LayoutKind.Sequential, Pack = 4)]
    public struct TOKEN_PRIVILEGES {
        public int PrivilegeCount;
        public LUID_AND_ATTRIBUTES Privileges;
    }

    [DllImport("advapi32.dll", SetLastError = true)]
    public static extern bool AdjustTokenPrivileges(
        IntPtr TokenHandle,
        bool DisableAllPrivileges,
        ref TOKEN_PRIVILEGES NewState,
        int BufferLength,
        IntPtr PreviousState,
        IntPtr ReturnLength
        );

    [DllImport("advapi32.dll", SetLastError = true)]
    public static extern bool LookupPrivilegeValue(
        string lpSystemName,
        string lpName,
        ref long lpLuid
        );

    [DllImport("advapi32.dll", SetLastError = true)]
    public static extern bool OpenProcessToken(
        IntPtr ProcessHandle,
        int DesiredAccess,
        ref IntPtr TokenHandle
        );

    public const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
    public const int TOKEN_QUERY = 0x00000008;
    public const int TOKEN_DUPLICATE = 0x00000002;
    public const int TOKEN_IMPERSONATE = 0x00000004;
    public const int SE_PRIVILEGE_ENABLED = 0x00000002;
    public const string SE_RESTORE_NAME = "SeRestorePrivilege";
    public const string SE_BACKUP_NAME = "SeBackupPrivilege";

    [DllImport("advapi32.dll", SetLastError = true)]
    static public extern bool LogonUser(String lpszUsername, String lpszDomain,
        String lpszPassword,
        int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

    [DllImport("Userenv.dll", CallingConvention = CallingConvention.Winapi, SetLastError = true, CharSet = CharSet.Auto)]
    public static extern bool LoadUserProfile(
        IntPtr hToken,               // user token
        ref PROFILEINFO lpProfileInfo  // profile
        );

    [DllImport("Userenv.dll", CallingConvention = CallingConvention.Winapi, SetLastError = true, CharSet = CharSet.Auto)]
    public static extern bool UnloadUserProfile(
        IntPtr hToken,   // user token
        IntPtr hProfile  // handle to registry key
        );

    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private extern static bool DuplicateToken(
        IntPtr ExistingTokenHandle,
        int SECURITY_IMPERSONATION_LEVEL,
        ref IntPtr DuplicateTokenHandle
        );


    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    public struct PROFILEINFO {
        public static readonly int SizeOf = Marshal.SizeOf(typeof(PROFILEINFO));

        public int dwSize;                 // Set to sizeof(PROFILEINFO) before calling
        public int dwFlags;                // See PI_ flags defined in userenv.h
        public string lpUserName;          // User name (required)
        public string lpProfilePath;       // Roaming profile path (optional, can be NULL)
        public string lpDefaultPath;       // Default user profile path (optional, can be NULL)
        public string lpServerName;        // Validating domain controller name in netbios format (optional, can be NULL but group NT4 style policy won't be applied)
        public string lpPolicyPath;        // Path to the NT4 style policy file (optional, can be NULL)
        public IntPtr hProfile;            // Filled in by the function.  Registry key handle open to the root.
    }
    #endregion

    static void Main(string[] args) {
        string domain = "dev1";
        string userName = "tuser1";
        string password = "asd!234";
        string profilePath = @"\\fs001\TestProfiles\tuser9\profile";

        bool retVal = false;
        IntPtr primaryToken = IntPtr.Zero;
        IntPtr dupeToken = IntPtr.Zero;
        PROFILEINFO profileInfo = new PROFILEINFO();
        try {
            // Add RESTORE AND BACUP privileges to process primary token, this is needed for LoadUserProfile function
            IntPtr processToken = IntPtr.Zero;

            OpenProcessToken(System.Diagnostics.Process.GetCurrentProcess().Handle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref processToken);

            long luidRestore = 0;
            long luidBackup = 0;
            retVal = LookupPrivilegeValue(null, SE_RESTORE_NAME, ref luidRestore);
            retVal = LookupPrivilegeValue(null, SE_BACKUP_NAME, ref luidBackup);

            TOKEN_PRIVILEGES tpRestore = new TOKEN_PRIVILEGES();
            TOKEN_PRIVILEGES tpBackup = new TOKEN_PRIVILEGES();

            tpRestore.PrivilegeCount = 1;
            tpRestore.Privileges = new LUID_AND_ATTRIBUTES();
            tpRestore.Privileges.Attributes = SE_PRIVILEGE_ENABLED;
            tpRestore.Privileges.Luid = luidRestore;

            tpBackup.PrivilegeCount = 1;
            tpBackup.Privileges = new LUID_AND_ATTRIBUTES();
            tpBackup.Privileges.Attributes = SE_PRIVILEGE_ENABLED;
            tpBackup.Privileges.Luid = luidBackup;

            retVal = AdjustTokenPrivileges(processToken, false, ref tpRestore, 0, IntPtr.Zero, IntPtr.Zero);
            if (false == retVal) {
                throw new Win32Exception();
            }
            retVal = AdjustTokenPrivileges(processToken, false, ref tpBackup, 0, IntPtr.Zero, IntPtr.Zero);
            if (false == retVal) {
                throw new Win32Exception();
            }

            // Logon as user + password in clear text for sake of simple sample (protocol transitioning is better).
            retVal = LogonUser(userName, domain, password, 3 /* LOGON32_LOGON_NETWORK */, 0 /*LOGON32_PROVIDER_DEFAULT */, ref primaryToken);
            if (false == retVal) {
                throw new Win32Exception();
            }

            // Duplicate primary token.
            // LoadUserProfile needs a token with TOKEN_IMPERSONATE and TOKEN_DUPLICATE access flags.
            retVal = DuplicateToken(primaryToken, 2 /* securityimpersonation */, ref dupeToken);
            if (false == retVal) {
                throw new Win32Exception();
            }

            // Load user profile for roaming profile
            profileInfo.dwSize = PROFILEINFO.SizeOf;
            profileInfo.lpUserName = domain + @"\" + userName;
            profileInfo.lpProfilePath = profilePath;

            Console.WriteLine("UserName: {0}", profileInfo.lpUserName);
            Console.WriteLine("ProfilePath: {0}", profileInfo.lpProfilePath);

            retVal = LoadUserProfile(dupeToken, ref profileInfo);
            if (false == retVal) {
                throw new Win32Exception();
            }

            // What should happen
            // 1.  Local new profile in c:\users\tuser1.dev1 folder with copy from default.
            // 2.  Valid user registry hive ntuser.dat
            // 3.  Loaded profile session entry in the registry entry
            //     HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\SID of tuser1\
            //     State bit mask should have new local profile (x004), new central profile (x008), 
            //     update the central profile (0010).
            //
            //       "State"=dword:0000021c
            //       "CentralProfile"="\\fs001\Share\tuser1\profile.V2"
            //       "ProfileImagePath"="C:\Users\tuser1"
            //
            //     See http://technet.microsoft.com/en-us/library/cc775560(WS.10).aspx fpr more info
            //     Roaming Profile - New User section.
            // 
            // What actually happens:
            // 1.  Temp profile is loaded in c:\users\temp
            // 2.  Registry entry ProfieList/SID is showing temporary profile
            //       "State"=dword:00000a04
            //       "CentralProfile"="\\fs001\Share\tuser1\profile.V2"
            //       "ProfileImagePath"="C:\Users\TEMP"

            Console.WriteLine("Profile loaded, hit enter to unload profile");
            Console.ReadLine();
        }
        catch (Exception e) {
            Console.WriteLine(e.ToString());
            Console.ReadLine();
        }
        finally {
            // Unload profile properly.
            if (IntPtr.Zero != dupeToken) {
                retVal = UnloadUserProfile(dupeToken, profileInfo.hProfile);
                if (false == retVal) {
                    throw new Win32Exception();
                }
            }
        }
    }
}

}


当您获取用户令牌时,我没有看到TOKEN_IMPERSONATE和TOKEN_DUPLICATE被请求为特权...有时它们存在,但明确请求它们可能会在该点引发故障,从而指引您朝正确的方向前进。 - Brandon Langley
此外,如果这些基于bool的函数在执行时失败,它们通常不会获取Win32最后的错误信息,因此无法提供有用的信息。请查看此博客文章,了解如何快速获取错误信息的示例:http://blogs.msdn.com/b/adam_nathan/archive/2003/04/25/56643.aspx - Brandon Langley
1个回答

2
我已经追踪了同一个问题数月,最终找到了答案。我在互联网上没有看到过这个答案。它也可以将LoadUserProfile的处理时间缩短5到10秒。这些注释仅适用于使用漫游配置文件的情况。
PROFILEINFO中的lpUserName字段在Windows 2008 R2中不仅用于活动目录用户验证。它还用于构建漫游配置文件路径和本地配置文件路径。如果lpUserName包含域名(例如mydomain\myusername),则使用的路径也包含该域名。但是,如果您将lpUserName更改为不包括域,则LoadUserProfile调用将失败。
但是,如果您在lpUserName中仅使用用户名,并在lpServerName中提供NetBIOS域名,则可以正常工作。NetBIOS名称通常是域名的最高级别(例如mydomain.parent.com,名称为mydomain),填充或修剪为15个字符加上第16个字符的十六进制1B(\u001B在C#字符串中)。
您可以在HKLM\Software\Microsoft\Windows NT\CurrentVersion\ProfileList{sid}的CentralProfile字符串中自行查看问题。只有在尝试使用LoadUserProfile进行漫游配置文件时,才会出现CentralProfile。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接