示例#1
0
        public static WindowsIdentity GetProcessWindowsIdentity(Process process)
        {
            IntPtr tokenHandle = IntPtr.Zero;
            WindowsIdentity wi = null;
            try
            {
                tokenHandle = GetProcessTokenHandle(process);
                wi = new WindowsIdentity(tokenHandle);
            }
            catch
            {
                if (wi != null)
                {
                    wi.Dispose();
                }

                return null;
            }
            finally
            {
                if (tokenHandle != IntPtr.Zero)
                {
                    NativeMethods.CloseHandle(tokenHandle);
                }
            }

            return wi;
        }
示例#2
0
        string GetUpnFromWindowsIdentity(WindowsIdentity windowsIdentity)
        {
            string downlevelName = null;
            string upnName = null;
 
            try
            {
                downlevelName = windowsIdentity.Name;
 
                if (IsMachineJoinedToDomain())
                {
                    upnName = GetUpnFromDownlevelName(downlevelName);
                }
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }
             }
 
            // if the AD cannot be queried for the fully qualified domain name,
            // fall back to the downlevel UPN name
            return upnName ?? downlevelName;
        }
示例#3
0
        public WindowsPrincipal (WindowsIdentity ntIdentity) {
            if (ntIdentity == null)
                throw new ArgumentNullException("ntIdentity"); 
            Contract.EndContractBlock();
 
            m_identity = ntIdentity; 
        }
        string GetUpnFromWindowsIdentity(WindowsIdentity windowsIdentity)
        {
            string downlevelName = null;
            string upnName = null;

            try
            {
                downlevelName = windowsIdentity.Name;

                if (this.IsMachineJoinedToDomain())
                {
                    upnName = GetUpnFromDownlevelName(downlevelName);
                }
            }
#pragma warning suppress 56500 // covered by FxCOP
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }

                DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
            }

            // if the AD cannot be queried for the fully qualified domain name,
            // fall back to the downlevel UPN name
            return upnName ?? downlevelName;
        }
示例#5
0
        public void Impersonate(string domainName, string userName, string password)
        {
            try
            {
                const int logon32ProviderDefault = 0;
                const int logon32LogonInteractive = 2;
                TokenHandle = IntPtr.Zero;
                var returnValue = LogonUser(
                                    userName,
                                    domainName,
                                    password,
                                    logon32LogonInteractive,
                                    logon32ProviderDefault,
                                    ref TokenHandle);

                if (false == returnValue)
                {
                    int ret = Marshal.GetLastWin32Error();
                    Console.WriteLine("LogonUser call failed with error code : " + ret);
                    throw new System.ComponentModel.Win32Exception(ret);
                }
                NewId = new WindowsIdentity(TokenHandle);
                ImpersonatedUser = NewId.Impersonate();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception occurred. " + ex.Message);
            }
        }
        public void Enter()
        {
            if (this.IsInContext)
            {
                return;
            }

            this.token = new IntPtr(0);
            try
            {
                this.token = IntPtr.Zero;
                bool logonSuccessfull = NativeMethods.LogonUser(
                   this.username,
                   this.domain,
                   this.password,
                   Logon32LogonInteractive,
                   Logon32ProviderDefault,
                   ref this.token);
                if (logonSuccessfull == false)
                {
                    int error = Marshal.GetLastWin32Error();
                    throw new Win32Exception(error);
                }

                var identity = new WindowsIdentity(this.token);
                this.context = identity.Impersonate();
            }
            catch
            {
                // Catch exceptions here
            }
        }
        internal AutoWebProxyScriptEngine(WebProxy proxy, bool useRegistry)
        {
            GlobalLog.Assert(proxy != null, "'proxy' must be assigned.");
            webProxy = proxy;
            m_UseRegistry = useRegistry;

#if !FEATURE_PAL
            m_AutoDetector = AutoDetector.CurrentAutoDetector;
            m_NetworkChangeStatus = m_AutoDetector.NetworkChangeStatus;

            SafeRegistryHandle.RegOpenCurrentUser(UnsafeNclNativeMethods.RegistryHelper.KEY_READ, out hkcu);
            if (m_UseRegistry)
            {
                ListenForRegistry();

                // Keep track of the identity we used to read the registry, in case we need to read it again later.
                m_Identity = WindowsIdentity.GetCurrent();
            }

#endif // !FEATURE_PAL

            // In Win2003 winhttp added a Windows Service handling the auto-proxy discovery. In XP using winhttp
            // APIs will load, compile and execute the wpad file in-process. This will also load COM, since
            // WinHttp requires COM to compile the file. For these reasons, we don't use WinHttp on XP, but
            // only on newer OS versions where the "WinHTTP Web Proxy Auto-Discovery Service" exists.
            webProxyFinder = new HybridWebProxyFinder(this);
        }
示例#8
0
 public void Impersonate()
 {
     //create identity
     WindowsIdentity newId = new WindowsIdentity(this.tokenHandle);
     //start impersonating
     this.impersonatedUser = newId.Impersonate();
 }
示例#9
0
        public bool Evaluate(EvaluationContext evaluationContext, ref object state)
        {
            try
            {
                X509Certificate2 cert       = ((X509CertificateClaimSet)evaluationContext.ClaimSets[0]).X509Certificate;
                string           thumbPrint = cert.Thumbprint;
                string           acct       = System.Configuration.ConfigurationManager.AppSettings[thumbPrint];


                var winId = new System.Security.Principal.WindowsIdentity(acct);


                var wClaimSet = new WindowsClaimSet(winId);

                evaluationContext.Properties["Principal"] = new WindowsPrincipal(winId);

                evaluationContext.AddClaimSet(this, wClaimSet);



                return(true);
            }
            catch (Exception e)
            {
                Console.Write(e.Message);
                return(false);
            }
        }
        private static readonly string WebApiExampleUrl = "http://localhost:47503/api/Products/GetAllProducts";     /* check ProductsApp.csproj properties, "Web" tab, "IIS Express" settings if there is an issue */

        public static void Main(string[] args)
        {
            try
            {
                System.Security.Principal.WindowsIdentity ident = System.Security.Principal.WindowsIdentity.GetCurrent();
                if (null != ident)
                {
                    Console.WriteLine("Will the Identity '{0}' Show up in IdentityWhiteListAuthorizationAttribute ???", ident.Name);
                }

                RunHttpClientExample();
                RunWebClientExample();
                RunWebClientWicExample();
            }
            catch (Exception ex)
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                Exception exc = ex;
                while (null != exc)
                {
                    sb.Append(exc.GetType().Name + System.Environment.NewLine);
                    sb.Append(exc.Message + System.Environment.NewLine);
                    exc = exc.InnerException;
                }

                Console.WriteLine(sb.ToString());
            }

            Console.WriteLine("Press ENTER to exit");
            Console.ReadLine();
        }
 protected void btnBrowseDBUser_Click(object sender, EventArgs e)
 {
     try
     {
         IAzManDBUser[] selectedDBUsers = (IAzManDBUser[])this.Session["selectedDBUsers"];
         if (selectedDBUsers.Length > 1)
         {
             this.ShowError("Please choose only one DB User");
         }
         if (selectedDBUsers.Length == 1)
         {
             this.wid = null;
             this.dbuser = selectedDBUsers[0];
             this.txtDBUser.Text = this.dbuser.UserName;
         }
         this.rbDBUser.Checked = true;
         this.txtWindowsUser.Text = String.Empty;
     }
     catch (Exception ex)
     {
         this.ShowError(ex.Message);
     }
     finally
     {
         this.Session["selectedDBUsers"] = null;
     }
 }
示例#12
0
        private static string GetKey(MySqlConnectionStringBuilder settings)
        {
            var key = settings.ConnectionString;

#if !CF
            if (settings.IntegratedSecurity && !settings.ConnectionReset)
            {
                try
                {
                    // Append SID to the connection string to generate a key
                    // With Integrated security different Windows users with the same
                    // connection string may be mapped to different MySQL accounts.
//          var id =
//            WindowsIdentity.GetCurrent();
                    System.Security.Principal.WindowsIdentity id =
                        System.Security.Principal.WindowsIdentity.GetCurrent();

                    key += ";" + id.User;
                }
                catch (SecurityException ex)
                {
                    // Documentation for WindowsIdentity.GetCurrent() states
                    // SecurityException can be thrown. In this case the
                    // connection can only be pooled if reset is done.
                    throw new MySqlException(Resources.NoWindowsIdentity, ex);
                }
            }
#endif
            return(key);
        }
示例#13
0
        public bool Impersonate(string userName, string domain, string password)
        {
            var token = IntPtr.Zero;
            var tokenDuplicate = IntPtr.Zero;

            if(RevertToSelf())
            {
                if(LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out token))
                {
                    if(DuplicateToken(token, 2, out tokenDuplicate) != 0)
                    {
                        var tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                        _impersonationContext = tempWindowsIdentity.Impersonate();
                        if(_impersonationContext != null)
                        {
                            CloseHandle(token);
                            CloseHandle(tokenDuplicate);
                            return true;
                        }
                    }
                }
            }
            if(token != IntPtr.Zero)
            {
                CloseHandle(token);
            }
            if(tokenDuplicate != IntPtr.Zero)
            {
                CloseHandle(tokenDuplicate);
            }
            return false;
        }
        internal static SecurityContext Capture(System.Threading.ExecutionContext currThreadEC, ref StackCrawlMark stackMark)
        {
            if (IsFlowSuppressed())
            {
                return(null);
            }
            if (CurrentlyInDefaultFTSecurityContext(currThreadEC))
            {
                return(null);
            }
            SecurityContext context = new SecurityContext {
                isNewCapture = true
            };

            if (!IsWindowsIdentityFlowSuppressed())
            {
                System.Security.Principal.WindowsIdentity currentWI = GetCurrentWI(currThreadEC);
                if (currentWI != null)
                {
                    context._windowsIdentity = new System.Security.Principal.WindowsIdentity(currentWI.TokenHandle);
                }
            }
            else
            {
                context._disableFlow = SecurityContextDisableFlow.WI;
            }
            context.CompressedStack = System.Threading.CompressedStack.GetCompressedStack(ref stackMark);
            return(context);
        }
 public void Enter()
 {
     if (this.IsInContext) return;
     m_Token = new IntPtr(0);
     try
     {
         m_Token = IntPtr.Zero;
         bool logonSuccessfull = LogonUser(
            m_Username,
            m_Domain,
            m_Password,
            LOGON32_LOGON_INTERACTIVE,
            LOGON32_PROVIDER_DEFAULT,
            ref m_Token);
         if (logonSuccessfull == false)
         {
             int error = Marshal.GetLastWin32Error();
             throw new Win32Exception(error);
         }
         WindowsIdentity identity = new WindowsIdentity(m_Token);
         m_Context = identity.Impersonate();
     }
     catch (Exception exception)
     {
         // Catch exceptions here
     }
 }
示例#16
0
 protected override void ProcessIdentity(WindowsIdentity identity)
 {
     using (var hToken = new SafeTokenHandle(identity.Token, false))
     {
         Utils.AdjustTokenPrivileges(hToken, Privileges);
     }
 }
示例#17
0
 public static bool RunAsAdministrator(string[] Args)
 {
     //获得当前登录的Windows用户标示
     System.Security.Principal.WindowsIdentity  identity  = System.Security.Principal.WindowsIdentity.GetCurrent();
     System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
     //判断当前登录用户是否为管理员
     if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
     {
         return(true);
     }
     else
     {
         //创建启动对象
         System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
         //设置运行文件
         startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;
         //设置启动参数
         startInfo.Arguments = String.Join(" ", Args);
         //设置启动动作,确保以管理员身份运行
         startInfo.Verb = "runas";
         //如果不是管理员,则启动UAC
         System.Diagnostics.Process.Start(startInfo);
         //退出
         System.Windows.Forms.Application.Exit();
         return(false);
     }
 }
 //Public Sub PerformImpersonatedTask(ByVal username As String, ByVal domain As String, ByVal password As String, ByVal logonType As Integer, ByVal logonProvider As Integer, ByVal methodToPerform As Action)
 public void PerformImpersonatedTask(string username, string domain, string password, int logonType, int logonProvider, Action methodToPerform)
 {
     IntPtr token = IntPtr.Zero;
     if (RevertToSelf())
     {
         if (LogonUser(username, domain, password, logonType, logonProvider, ref token) != 0)
         {
             dynamic identity = new WindowsIdentity(token);
             dynamic impersonationContext = identity.Impersonate();
             if (impersonationContext != null)
             {
                 methodToPerform.Invoke();
                 impersonationContext.Undo();
             }
             // do logging
         }
         else
         {
         }
     }
     if (token != IntPtr.Zero)
     {
         CloseHandle(token);
     }
 }
        protected override void ProcessIdentity(WindowsIdentity identity)
        {
            bool result = true;

            if (this.ParameterSetName == PARAMSET_NAME)
            {
                if (!TranslateGroupNames())
                {
                    result = false;
                }
            }

            if (result)
            {
                foreach (var reference in _references)
                {
                    // ReSharper disable PossibleNullReferenceException
                    if (!identity.Groups.Contains(reference))
                    // ReSharper restore PossibleNullReferenceException
                    {
                        result = false;
                        break;
                    }
                }
            }
            WriteObject(result);
        }
 private static HashSet<string> GetHashedRoles(WindowsIdentity id)
 {
     lock (s_Lock)
     {
         HashSet<string> result;
         if (!s_RoleCache.TryGetValue(id.Name, out result))
         {
             result = new HashSet<string>();
             if (id.Groups != null)
             {
                 IdentityReferenceCollection identityReferenceCollection = id.Groups.Translate(typeof(NTAccount));
                 if (identityReferenceCollection != null)
                 {
                     IEnumerable<string> groups =
                         identityReferenceCollection
                             .AsEnumerable()
                             .Select(x => x.Value);
                     foreach (string @group in groups)
                     {
                         string[] items = @group.Split('\\');
                         result.Add(items.Length != 2 ? @group : items[1]);
                     }
                 }
             }
             s_RoleCache.Add(id.Name, result);
         }
         return result;
     }
 }
示例#21
0
            public static bool CheckUserRights(string userLogin, string rightName)
            {
                string programName = WebConfigurationManager.AppSettings["progName"];
                bool flag = false;

                SqlParameter pProgramName = new SqlParameter() { ParameterName = "program_name", Value = programName, DbType = DbType.AnsiString };
                SqlParameter pRightName = new SqlParameter() { ParameterName = "sys_name", Value = rightName, DbType = DbType.AnsiString };

                DataTable dt = new DataTable();

                dt = ExecuteQueryStoredProcedure(sp, "getUserGroupSid", pProgramName, pRightName);

                if (dt.Rows.Count > 0)
                {
                    DataRow dr = dt.Rows[0];

                    string sid = dr["sid"].ToString();

                    try
                    {
                        WindowsIdentity wi = new WindowsIdentity(userLogin);
                        WindowsPrincipal wp = new WindowsPrincipal(wi);
                        SecurityIdentifier grpSid = new SecurityIdentifier(sid);

                        flag = wp.IsInRole(grpSid);
                    }
                    catch (Exception ex)
                    {
                        flag = false;
                    }
                }

                return flag;
            }
        private static bool TryCreateWindowsSidClaim(System.Security.Principal.WindowsIdentity windowsIdentity, out Claim claim)
        {
            SafeHGlobalHandle invalidHandle = SafeHGlobalHandle.InvalidHandle;

            try
            {
                uint num;
                invalidHandle = GetTokenInformation(windowsIdentity.Token, System.IdentityModel.TokenInformationClass.TokenUser, out num);
                SID_AND_ATTRIBUTES sid_and_attributes = (SID_AND_ATTRIBUTES)Marshal.PtrToStructure(invalidHandle.DangerousGetHandle(), typeof(SID_AND_ATTRIBUTES));
                uint num2 = 0x10;
                if (sid_and_attributes.Attributes == 0)
                {
                    claim = Claim.CreateWindowsSidClaim(new SecurityIdentifier(sid_and_attributes.Sid));
                    return(true);
                }
                if ((sid_and_attributes.Attributes & num2) == 0x10)
                {
                    claim = Claim.CreateDenyOnlyWindowsSidClaim(new SecurityIdentifier(sid_and_attributes.Sid));
                    return(true);
                }
            }
            finally
            {
                invalidHandle.Close();
            }
            claim = null;
            return(false);
        }
示例#23
0
        public bool ImpersonateValidUser(String userName, String domain, String password)
        {
            System.Security.Principal.WindowsIdentity tempWindowsIdentity;
            IntPtr token          = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            if (RevertToSelf())
            {
                if (LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                {
                    if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                    {
                        tempWindowsIdentity  = new System.Security.Principal.WindowsIdentity(tokenDuplicate);
                        impersonationContext = tempWindowsIdentity.Impersonate();
                        if (impersonationContext != null)
                        {
                            CloseHandle(token);
                            CloseHandle(tokenDuplicate);
                            return(true);
                        }
                    }
                }
            }
            if (token != IntPtr.Zero)
            {
                CloseHandle(token);
            }
            if (tokenDuplicate != IntPtr.Zero)
            {
                CloseHandle(tokenDuplicate);
            }
            _Token = token;
            return(false);
        }
示例#24
0
        public Guid login_Using_WindowsAuthentication(WindowsIdentity identity)
        {
            var userName = "";
            if (identity != null && identity.IsAuthenticated && identity.ImpersonationLevel == TokenImpersonationLevel.Impersonation)
                userName = identity.Name;
            else
            {
                // not sure how to test the one bellow since it needs a valid HttpContext
                userName = HttpContextFactory.Current.field("_context")
                                             .field("_wr")
                                             .invoke("GetServerVariable", "LOGON_USER") as string;
            }

            if (userName.valid())
            {
                var tmUser = userName.tmUser();
                if(tmUser.isNull())
                {
                    TM_UserData.Current.logTBotActivity("Windows Authentication", "Creating User: {0}".format(userName));
                    tmUser = userName.newUser().tmUser();
                }
                if (tmUser.GroupID != (int)calculateUserGroupBasedOnWindowsIdentity(identity))
                {
                    tmUser.GroupID = (int)calculateUserGroupBasedOnWindowsIdentity(identity);
                    tmUser.save();
                    TM_UserData.Current.logTBotActivity("Windows Authentication", "Created session for User: {0}".format(userName));
                }
                return tmUser.login("WindowsAuth");
            }
            return Guid.Empty;
        }
示例#25
0
		// case sensitivity versus number of groups
		// http://groups.google.ca/groups?q=WindowsPrincipal+m_roles&hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=%23JEMHsMQCHA.1916%40tkmsftngp13&rnum=5

		public WindowsPrincipal (WindowsIdentity ntIdentity)
		{
			if (ntIdentity == null)
				throw new ArgumentNullException ("ntIdentity");

			_identity = ntIdentity;
		}
示例#26
0
 public void Impersonate(string domainName, string userName, string password){
     //try
     {
         // Use the unmanaged LogonUser function to get the user token for
         // the specified user, domain, and password.
         const int LOGON32_PROVIDER_DEFAULT = 0;
         // Passing this parameter causes LogonUser to create a primary token.
         const int LOGON32_LOGON_INTERACTIVE = 2;
         tokenHandle = IntPtr.Zero;
         // ---- Step - 1
         // Call LogonUser to obtain a handle to an access token.
         bool returnValue = LogonUser(
                                 userName,
                                 domainName,
                                 password,
                                 LOGON32_LOGON_INTERACTIVE,
                                 LOGON32_PROVIDER_DEFAULT,
                                 ref tokenHandle); // tokenHandle - new security token
         if (false == returnValue){
             int ret = Marshal.GetLastWin32Error();
             throw new System.ComponentModel.Win32Exception(ret);
         }
         // ---- Step - 2
         WindowsIdentity newId = new WindowsIdentity(tokenHandle);
         // ---- Step - 3
         {
             impersonatedUser = newId.Impersonate();
         }
     }
 }
        // This method is used to perform action delegate remotely on CIFS Share
        public static void PerformActionRemotely(Action action, ServerConnectionCredentials serverCreds)
        {
            WindowsIdentity wid_current = WindowsIdentity.GetCurrent();
            WindowsImpersonationContext wic = null;
            try
            {
                IntPtr admin_token = new IntPtr();
                if (LogonUser(serverCreds.Username, ".", serverCreds.Password, 9, 0, ref admin_token) != 0)
                {
                    wic = new WindowsIdentity(admin_token).Impersonate();

                    action();
                }
            }
            catch (Exception se)
            {
                int ret = Marshal.GetLastWin32Error();
                Logger.LogError("Invoking action on remote machine failed with Error code " + ret.ToString(), serverCreds.IP, se);
                return;
            }
            finally
            {
                if (wic != null)
                {
                    wic.Undo();
                }
            }
        }
 public ServerReportSoapProxy(System.Security.Principal.WindowsIdentity impersonationUser, string reportServerLocation, IEnumerable <string> headers, IEnumerable <Cookie> cookies, EndpointVersion version)
     : base(reportServerLocation, version)
 {
     m_impersonationUser = impersonationUser;
     m_headers           = headers;
     m_cookies           = cookies;
 }
示例#29
0
        /// <summary>
        /// 사용자를 가장합니다.
        /// </summary>
        /// <param name="userName">사용자 이름 입니다.</param>
        /// <param name="domain">도메인 이름 입니다.</param>
        /// <param name="password">암호 입니다.</param>
        /// /// <exception cref="SecurityException">가장이 실패할 경우 <c>SecurityException</c>를 던집니다.</exception>
        public void Impersonate(string userName, string domain, string password)
        {
            WindowsIdentity tempWindowsIdentity;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            if (RevertToSelf())
            {
                if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
                    LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                {
                    if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                    {
                        tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                        impersonationContext = tempWindowsIdentity.Impersonate();
                        if (impersonationContext != null)
                        {
                            CloseHandle(token);
                            CloseHandle(tokenDuplicate);
                            return;
                        }
                    }
                }
            }

            if (token != IntPtr.Zero) CloseHandle(token);
            if (tokenDuplicate != IntPtr.Zero) CloseHandle(tokenDuplicate);

            throw new SecurityException("사용자를 가장하는데 실패했습니다.");
        }
        /// <summary>
        /// 模擬特定使用者帳號
        /// 
        /// reference : http://www.dotblogs.com.tw/puma/archive/2009/02/24/7281.aspx
        /// </summary>
        /// <param name="domain"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns>表示模擬作業前的 Windows 使用者</returns>
        /// <remarks>
        /// Response.Write("CurrentUserName: "******"localhost", "Administrator", "AccountPass");
        /// Response.Write("CurrentUserName: "******"CurrentUserName: " + WindowsIdentity.GetCurrent().Name);
        /// </remarks>
        public WindowsImpersonationContext Impersonate(string domain, string userName, string password)
        {
            WindowsImpersonationContext impersonationContext = null;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            try
            {
                if (RevertToSelf())
                {
                    if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
                        LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                    {
                        if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                        {
                            WindowsIdentity tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                            impersonationContext = tempWindowsIdentity.Impersonate();
                        }
                    }
                }
            }
            catch
            {
                ;
            }
            finally
            {
                if (token != IntPtr.Zero)
                    CloseHandle(token);
                if (tokenDuplicate != IntPtr.Zero)
                    CloseHandle(tokenDuplicate);
            }

            return impersonationContext;
        }
示例#31
0
 /// <summary>
 ///   Constructor. Starts the impersonation with the given credentials. Please note that the account that instantiates the Impersonator class needs to have the 'Act as part of operating system' privilege set.
 /// </summary>
 /// <param name="userName"> The name of the user to act as. </param>
 /// <param name="domainName"> The domain name of the user to act as. </param>
 /// <param name="password"> The password of the user to act as. </param>
 public WindowsImpersonatedIdentity(string userName, string domainName, string password)
 {
     var token = IntPtr.Zero;
     var tokenDuplicate = IntPtr.Zero;
     try {
         if (string.IsNullOrEmpty(userName) && string.IsNullOrEmpty(domainName) && string.IsNullOrEmpty(password)) {
             identity = WindowsIdentity.GetCurrent();
         } else {
             if (LogonUser(userName, domainName, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0) {
                 if (DuplicateToken(token, 2, ref tokenDuplicate) != 0) {
                     identity = new WindowsIdentity(tokenDuplicate);
                     impersonationContext = identity.Impersonate();
                 } else {
                     throw new Win32Exception(Marshal.GetLastWin32Error());
                 }
             } else {
                 throw new Win32Exception(Marshal.GetLastWin32Error());
             }
         }
     } finally {
         if (token != IntPtr.Zero) {
             CloseHandle(token);
         }
         if (tokenDuplicate != IntPtr.Zero) {
             CloseHandle(tokenDuplicate);
         }
     }
 }
        public PerformanceCounterRetriever(string server, string domain, string user, string password)
        {
            if (string.IsNullOrWhiteSpace(server))
                throw new ArgumentException($"Null/blank {nameof(server)} specified");
            if (string.IsNullOrWhiteSpace(domain))
                throw new ArgumentException($"Null/blank {nameof(domain)} specified");
            if (string.IsNullOrWhiteSpace(user))
                throw new ArgumentException($"Null/blank {nameof(user)} specified");
            if (password == null)
                throw new ArgumentNullException(nameof(password));

            try
            {
                var userHandle = new IntPtr(0);
                var logonSuccess = LogonUser(user, domain, password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_WINNT50, ref userHandle);
                if (!logonSuccess)
                    throw new Exception("LogonUser failed");
                _identity = new WindowsIdentity(userHandle);
                _context = _identity.Impersonate();
                _server = server;
                _disposed = false;
            }
            finally
            {
                Dispose();
            }
        }
示例#33
0
        private WindowsIdentity Logon()
        {
            IntPtr handle = new IntPtr(0);
            handle = IntPtr.Zero;

            const int LOGON32_LOGON_NEW_CREDENTIALS = 8;
            const int LOGON32_PROVIDER_DEFAULT = 0;

            // attempt to authenticate domain user account 
            bool logonSucceeded = LogonUser(this.username, this.domain, this.password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref handle);

            if (!logonSucceeded)
            {
                // if the logon failed, get the error code and throw an exception 
                int errorCode = Marshal.GetLastWin32Error();
                throw new Exception("User logon failed. Error Number: " + errorCode.ToString());
            }

            // if logon succeeds, create a WindowsIdentity instance 
            WindowsIdentity winIdentity = new WindowsIdentity(handle);

            // close the open handle to the authenticated account 
            CloseHandle(handle);

            return winIdentity;
        }
 internal void frmCheckAccessTest_Load(object sender, EventArgs e)
 {
     this.DialogResult = DialogResult.None;
     ImageList clonedImageList = new ImageList();
     foreach (Image image in this.imageListItemHierarchyView.Images)
     {
         clonedImageList.Images.Add((Image)image.Clone());
     }
     this.checkAccessTestTreeView.ImageList = clonedImageList;
     /*Application.DoEvents();*/
     NetSqlAzMan.SnapIn.Globalization.ResourcesManager.CollectResources(this);
     this.lblUPNUser.Text = "([email protected])";
     this.wid = ((System.Threading.Thread.CurrentPrincipal.Identity as WindowsIdentity) ?? WindowsIdentity.GetCurrent());
     NTAccount nta = (NTAccount)this.wid.User.Translate(typeof(NTAccount));
     string currentUpnName = nta.Value;
     if (currentUpnName.IndexOf('\\') != -1)
     {
         currentUpnName = currentUpnName.Substring(currentUpnName.IndexOf('\\') + 1);
     }
     this.lblMessage.Text = "...";
     this.btnBrowseWindowsUser.Text = "...";
     this.btnBrowseDBUser.Text = "...";
     this.chkCache.Text = "UserPermissionCache";
     this.chkStorageCache.Text = "StorageCache";
     this.groupBox1.Text = " " + Globalization.MultilanguageResource.GetString("frmCheckAccessTest.Text") + " ";
     this.dtValidFor.Value = DateTime.Now;
     this.rbCheckedChanged();
     this.txtWindowsUser.Text = currentUpnName;
     this.FormValidate();
 }
示例#35
0
        //public void Page_Load(Object s, EventArgs e)
        //{
        //    if (impersonateValidUser("username", "domain", "password"))
        //    {
        //        //Insert your code that runs under the security context of a specific user here.
        //        undoImpersonation();
        //    }
        //    else
        //    {
        //        //Your impersonation failed. Therefore, include a fail-safe mechanism here.
        //    }
        //}

        /// <summary>
        /// 模擬使用者
        /// </summary>
        /// <param name="userName">使用者名稱</param>
        /// <param name="domain">網域名稱</param>
        /// <param name="password">密碼</param>
        /// <returns>True:模擬成功;False:模擬失敗</returns>
        public static bool impersonateValidUser(String userName, 
                                                String domain, 
                                                String password
                                                )
        {
            WindowsIdentity tempWindowsIdentity;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            if (RevertToSelf())
            {
                if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
                    LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                {
                    if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                    {
                        tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                        impersonationContext = tempWindowsIdentity.Impersonate();
                        if (impersonationContext != null)
                        {
                            CloseHandle(token);
                            CloseHandle(tokenDuplicate);
                            return true;
                        }
                    }
                }
            }
            if (token != IntPtr.Zero)
                CloseHandle(token);
            if (tokenDuplicate != IntPtr.Zero)
                CloseHandle(tokenDuplicate);
            return false;
        }
 public static bool CheckUserGroup(string userName, string userGroup)
 {
     var wi = new WindowsIdentity(userName);
     var wp = new WindowsPrincipal(wi);
     bool inRole = wp.IsInRole(userGroup);
     return inRole;
 }
示例#37
0
        static void Main(string[] args)
        {
            Console.WriteLine(AuthenticationHelper.IsUserInAdminGroup());
            System.Security.Principal.WindowsIdentity wid2 = System.Security.Principal.WindowsIdentity.GetCurrent();
            WindowsPrincipal wip = new WindowsPrincipal(wid2);

            Console.WriteLine(wip.IsInRole(WindowsBuiltInRole.Administrator));
            // Console.WriteLine(IsAdminRole());
        }
 internal X509WindowsSecurityToken(X509Certificate2 certificate, System.Security.Principal.WindowsIdentity windowsIdentity, string authenticationType, string id, bool clone) : base(certificate, id, clone)
 {
     if (windowsIdentity == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("windowsIdentity");
     }
     this.authenticationType = authenticationType;
     this.windowsIdentity    = clone ? System.IdentityModel.SecurityUtils.CloneWindowsIdentityIfNecessary(windowsIdentity, authenticationType) : windowsIdentity;
 }
示例#39
0
 internal void CopyFrom(ReportServerCredentials other)
 {
     m_impersonationUser  = other.m_impersonationUser;
     m_networkCredentials = other.m_networkCredentials;
     m_formsCookie        = other.m_formsCookie;
     m_formsUserName      = other.m_formsUserName;
     m_formsPassword      = other.m_formsPassword;
     m_formsAuthority     = other.m_formsAuthority;
 }
示例#40
0
        private static System.Collections.Specialized.StringCollection GetRights(System.Security.Principal.WindowsIdentity identity)
        {
            System.Collections.Specialized.StringCollection rights = new System.Collections.Specialized.StringCollection();

            LSA_OBJECT_ATTRIBUTES objectAttributes = CreateLSAObjectAttributes();
            IntPtr policyHandle = IntPtr.Zero;

            LSA_UNICODE_STRING SystemName = new LSA_UNICODE_STRING();

            /*
             * SystemName.Length = (ushort)(System.Environment.MachineName.Length * System.Text.UnicodeEncoding.CharSize);
             * SystemName.MaximumLength = (ushort)((System.Environment.MachineName.Length + 1) * System.Text.UnicodeEncoding.CharSize);
             * SystemName.Buffer = System.Environment.MachineName; // Marshal.StringToHGlobalUni(System.Environment.MachineName);
             */


            // Open a policy handle on the remote PC.
            uint ret = LsaOpenPolicy(ref SystemName, ref objectAttributes, (int)POLICY_ALL_ACCESS, out policyHandle);

            if (ret == 0)
            {
                //long winErrorCode = 0;
                //IntPtr sid = IntPtr.Zero;
                //int sidSize = 0;
                //System.Text.StringBuilder domainName = new System.Text.StringBuilder();
                //int nameSize = 0;
                //int accountType = 0;
                long winErrorCode = 0;

                IntPtr userRightsPtr = IntPtr.Zero;
                int    countOfRights = 0;

                byte[] accountSidBytes = new byte[identity.User.BinaryLength];
                identity.User.GetBinaryForm(accountSidBytes, 0);
                int result = LsaEnumerateAccountRights(policyHandle, accountSidBytes, out userRightsPtr, out countOfRights);

                winErrorCode = LsaNtStatusToWinError(result);
                if (winErrorCode == 0)
                {
                    long current = userRightsPtr.ToInt64();
                    LSA_UNICODE_STRING userRight;

                    for (int i = 0; i < countOfRights; i++)
                    {
                        userRight = (LSA_UNICODE_STRING)Marshal.PtrToStructure(new IntPtr(current), typeof(LSA_UNICODE_STRING));
                        string userRightStr = Marshal.PtrToStringAuto(userRight.Buffer);
                        rights.Add(userRightStr);
                        current += Marshal.SizeOf(userRight);
                    }
                }

                LsaClose(policyHandle);
            }

            return(rights);
        }
示例#41
0
 public SoapReportExecutionService(System.Security.Principal.WindowsIdentity impersonationUser, Uri reportServerUrl, IReportServerCredentials reportServerCredentials, TrustedUserHeader trustedUserHeader, IEnumerable <string> headers, IEnumerable <Cookie> cookies, int timeout)
 {
     m_impersonationUser       = impersonationUser;
     m_reportServerUrl         = reportServerUrl;
     m_reportServerCredentials = reportServerCredentials;
     m_trustedUserHeader       = trustedUserHeader;
     m_headers = headers;
     m_cookies = cookies;
     m_timeout = timeout;
 }
        public ImpersonationContext(string username, string domain, string password)
        {
            var result = NativeMethods.LogonUser(username, domain, password, (int)LogonType.NewCredentials, (int)LogonProvider.WinNT50, out _safeTokenHandle);

            if (!result)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
            _windowsImpersonationContext = new System.Security.Principal.WindowsIdentity(_safeTokenHandle.DangerousGetHandle()).Impersonate();
        }
 internal WindowsClaimSet(System.Security.Principal.WindowsIdentity windowsIdentity, string authenticationType, bool includeWindowsGroups, DateTime expirationTime, bool clone)
 {
     if (windowsIdentity == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("windowsIdentity");
     }
     this.windowsIdentity      = clone ? System.IdentityModel.SecurityUtils.CloneWindowsIdentityIfNecessary(windowsIdentity, authenticationType) : windowsIdentity;
     this.includeWindowsGroups = includeWindowsGroups;
     this.expirationTime       = expirationTime;
     this.authenticationType   = authenticationType;
 }
示例#44
0
 public virtual void Dispose()
 {
     if (!this.disposed)
     {
         this.disposed = true;
         if (this.windowsIdentity != null)
         {
             this.windowsIdentity.Dispose();
             this.windowsIdentity = null;
         }
     }
 }
        /// <summary>
        /// This method will be called before an opration to login.
        /// </summary>
        /// <param name="Username"></param>
        /// <param name="password"></param>
        /// <param name="domain"></param>
        /// <returns></returns>
        private static WindowsImpersonationContext Login(string Username, string password, string domain)
        {
            IntPtr tokenHandle = new IntPtr(0);
            bool   ret         = LogonUser(Username, domain, password, 9, 0, ref tokenHandle);


            if (!ret)
            {
                throw new Exception("Logon at networkshare failed.");
            }

            System.Security.Principal.WindowsIdentity wid = new System.Security.Principal.WindowsIdentity(tokenHandle);
            return(wid.Impersonate());
        }
示例#46
0
 private void OnCredentialsChanged(IReportServerCredentials credentials)
 {
     if (credentials != null)
     {
         m_serverIdentity = credentials.ImpersonationUser;
     }
     else
     {
         m_serverIdentity = null;
     }
     m_serverCredentials = credentials;
     m_service           = null;
     ClearSession();
 }
示例#47
0
        // GET: LoginInfo
        public ActionResult Index()
        {
            System.Security.Principal.WindowsIdentity identity = System.Web.HttpContext.Current.Request.LogonUserIdentity;
            var ntid    = identity.Name.Split('\\')[1];
            var details = "http://adpgintranet2.web.analog.com/webApi/api/GetUser?ntid=" + ntid;

            System.Diagnostics.Debug.WriteLine(details);



            //IdentityReferenceCollection irc = identity.Groups;
            //foreach (IdentityReference ir in irc)
            //    System.Diagnostics.Debug.WriteLine(ir);
            return(View());
        }
示例#48
0
 protected void Initialize(string id, string authenticationType, DateTime effectiveTime, DateTime expirationTime, System.Security.Principal.WindowsIdentity windowsIdentity, bool clone)
 {
     if (windowsIdentity == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("windowsIdentity");
     }
     if (id == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("id");
     }
     this.id = id;
     this.authenticationType = authenticationType;
     this.effectiveTime      = effectiveTime;
     this.expirationTime     = expirationTime;
     this.windowsIdentity    = clone ? System.IdentityModel.SecurityUtils.CloneWindowsIdentityIfNecessary(windowsIdentity, authenticationType) : windowsIdentity;
 }
        private static void RunWebClientWicExample()
        {
            /* some articles said that HttpClient could not pass over the credentials because of async operations, these were some "experiments" using the older WebClient.  Stick with HttpClient if you can */
            System.Security.Principal.WindowsIdentity ident = System.Security.Principal.WindowsIdentity.GetCurrent();
            WindowsImpersonationContext wic = ident.Impersonate();

            try
            {
                WebClient webClient = new WebClient();
                webClient.UseDefaultCredentials = true;
                string serviceUrl = WebApiExampleUrl;
                string json       = webClient.DownloadString(serviceUrl);
                IEnumerable <Product> returnItems = JsonConvert.DeserializeObject <IEnumerable <Product> >(json);
                ShowProducts(returnItems);
            }
            finally
            {
                wic.Undo();
            }
        }
示例#50
0
        static void Main(string[] args)
        {
            System.Security.Principal.WindowsIdentity  wid        = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal printcipal = new System.Security.Principal.WindowsPrincipal(wid);
            Console.WriteLine(printcipal.Identity.AuthenticationType);

            using (Impersonator i = new Impersonator("andy2", ".", "andy2"))
            {
                Console.WriteLine(WindowsIdentity.GetCurrent().Name);
                System.Security.Principal.WindowsIdentity  wid2        = System.Security.Principal.WindowsIdentity.GetCurrent();
                System.Security.Principal.WindowsPrincipal printcipal2 = new System.Security.Principal.WindowsPrincipal(wid2);
                Console.WriteLine(printcipal2.Identity.AuthenticationType);
                bool isAdmin = (printcipal2.IsInRole(@"BUILTIN\Administrators"));
                Console.WriteLine(isAdmin);
            }
            //WindowsIdentity.Impersonate(IntPtr.Zero);
            //Console.WriteLine(WindowsIdentity.GetCurrent().Name);

            //System.Security.Principal.WindowsIdentity wid = System.Security.Principal.WindowsIdentity.GetCurrent();
            // System.Security.Principal.WindowsPrincipal printcipal = new System.Security.Principal.WindowsPrincipal(wid);
            // bool isAdmin = (printcipal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator));
            // Console.WriteLine(isAdmin);
        }
示例#51
0
文件: fcomm.cs 项目: nettitude/PoshC2
 static bool ihInteg()
 {
     System.Security.Principal.WindowsIdentity  identity  = System.Security.Principal.WindowsIdentity.GetCurrent();
     System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
     return(principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator));
 }
示例#52
0
        /// <span class="code-SummaryComment"><summary></span>
        /// Supply the path to the file or directory and a user or group.
        /// Access checks are done
        /// during instantiation to ensure we always have a valid object
        /// <span class="code-SummaryComment"></summary></span>
        /// <span class="code-SummaryComment"><param name="path"></param></span>
        /// <span class="code-SummaryComment"><param name="principal"></param></span>
        public UserFileAccessRights(string path,
                                    System.Security.Principal.WindowsIdentity principal)
        {
            this._path      = path;
            this._principal = principal;

            try
            {
                System.IO.FileInfo          fi  = new System.IO.FileInfo(_path);
                AuthorizationRuleCollection acl = fi.GetAccessControl().GetAccessRules
                                                      (true, true, typeof(SecurityIdentifier));
                for (int i = 0; i < acl.Count; i++)
                {
                    System.Security.AccessControl.FileSystemAccessRule rule =
                        (System.Security.AccessControl.FileSystemAccessRule)acl[i];
                    if (_principal.User.Equals(rule.IdentityReference))
                    {
                        if (System.Security.AccessControl.AccessControlType.Deny.Equals
                                (rule.AccessControlType))
                        {
                            if (contains(FileSystemRights.AppendData, rule))
                            {
                                _denyAppendData = true;
                            }
                            if (contains(FileSystemRights.ChangePermissions, rule))
                            {
                                _denyChangePermissions = true;
                            }
                            if (contains(FileSystemRights.CreateDirectories, rule))
                            {
                                _denyCreateDirectories = true;
                            }
                            if (contains(FileSystemRights.CreateFiles, rule))
                            {
                                _denyCreateFiles = true;
                            }
                            if (contains(FileSystemRights.Delete, rule))
                            {
                                _denyDelete = true;
                            }
                            if (contains(FileSystemRights.DeleteSubdirectoriesAndFiles,
                                         rule))
                            {
                                _denyDeleteSubdirectoriesAndFiles = true;
                            }
                            if (contains(FileSystemRights.ExecuteFile, rule))
                            {
                                _denyExecuteFile = true;
                            }
                            if (contains(FileSystemRights.FullControl, rule))
                            {
                                _denyFullControl = true;
                            }
                            if (contains(FileSystemRights.ListDirectory, rule))
                            {
                                _denyListDirectory = true;
                            }
                            if (contains(FileSystemRights.Modify, rule))
                            {
                                _denyModify = true;
                            }
                            if (contains(FileSystemRights.Read, rule))
                            {
                                _denyRead = true;
                            }
                            if (contains(FileSystemRights.ReadAndExecute, rule))
                            {
                                _denyReadAndExecute = true;
                            }
                            if (contains(FileSystemRights.ReadAttributes, rule))
                            {
                                _denyReadAttributes = true;
                            }
                            if (contains(FileSystemRights.ReadData, rule))
                            {
                                _denyReadData = true;
                            }
                            if (contains(FileSystemRights.ReadExtendedAttributes, rule))
                            {
                                _denyReadExtendedAttributes = true;
                            }
                            if (contains(FileSystemRights.ReadPermissions, rule))
                            {
                                _denyReadPermissions = true;
                            }
                            if (contains(FileSystemRights.Synchronize, rule))
                            {
                                _denySynchronize = true;
                            }
                            if (contains(FileSystemRights.TakeOwnership, rule))
                            {
                                _denyTakeOwnership = true;
                            }
                            if (contains(FileSystemRights.Traverse, rule))
                            {
                                _denyTraverse = true;
                            }
                            if (contains(FileSystemRights.Write, rule))
                            {
                                _denyWrite = true;
                            }
                            if (contains(FileSystemRights.WriteAttributes, rule))
                            {
                                _denyWriteAttributes = true;
                            }
                            if (contains(FileSystemRights.WriteData, rule))
                            {
                                _denyWriteData = true;
                            }
                            if (contains(FileSystemRights.WriteExtendedAttributes, rule))
                            {
                                _denyWriteExtendedAttributes = true;
                            }
                        }
                        else if (System.Security.AccessControl.AccessControlType.
                                 Allow.Equals(rule.AccessControlType))
                        {
                            if (contains(FileSystemRights.AppendData, rule))
                            {
                                _allowAppendData = true;
                            }
                            if (contains(FileSystemRights.ChangePermissions, rule))
                            {
                                _allowChangePermissions = true;
                            }
                            if (contains(FileSystemRights.CreateDirectories, rule))
                            {
                                _allowCreateDirectories = true;
                            }
                            if (contains(FileSystemRights.CreateFiles, rule))
                            {
                                _allowCreateFiles = true;
                            }
                            if (contains(FileSystemRights.Delete, rule))
                            {
                                _allowDelete = true;
                            }
                            if (contains(FileSystemRights.DeleteSubdirectoriesAndFiles,
                                         rule))
                            {
                                _allowDeleteSubdirectoriesAndFiles = true;
                            }
                            if (contains(FileSystemRights.ExecuteFile, rule))
                            {
                                _allowExecuteFile = true;
                            }
                            if (contains(FileSystemRights.FullControl, rule))
                            {
                                _allowFullControl = true;
                            }
                            if (contains(FileSystemRights.ListDirectory, rule))
                            {
                                _allowListDirectory = true;
                            }
                            if (contains(FileSystemRights.Modify, rule))
                            {
                                _allowModify = true;
                            }
                            if (contains(FileSystemRights.Read, rule))
                            {
                                _allowRead = true;
                            }
                            if (contains(FileSystemRights.ReadAndExecute, rule))
                            {
                                _allowReadAndExecute = true;
                            }
                            if (contains(FileSystemRights.ReadAttributes, rule))
                            {
                                _allowReadAttributes = true;
                            }
                            if (contains(FileSystemRights.ReadData, rule))
                            {
                                _allowReadData = true;
                            }
                            if (contains(FileSystemRights.ReadExtendedAttributes, rule))
                            {
                                _allowReadExtendedAttributes = true;
                            }
                            if (contains(FileSystemRights.ReadPermissions, rule))
                            {
                                _allowReadPermissions = true;
                            }
                            if (contains(FileSystemRights.Synchronize, rule))
                            {
                                _allowSynchronize = true;
                            }
                            if (contains(FileSystemRights.TakeOwnership, rule))
                            {
                                _allowTakeOwnership = true;
                            }
                            if (contains(FileSystemRights.Traverse, rule))
                            {
                                _allowTraverse = true;
                            }
                            if (contains(FileSystemRights.Write, rule))
                            {
                                _allowWrite = true;
                            }
                            if (contains(FileSystemRights.WriteAttributes, rule))
                            {
                                _allowWriteAttributes = true;
                            }
                            if (contains(FileSystemRights.WriteData, rule))
                            {
                                _allowWriteData = true;
                            }
                            if (contains(FileSystemRights.WriteExtendedAttributes, rule))
                            {
                                _allowWriteExtendedAttributes = true;
                            }
                        }
                    }
                }

                IdentityReferenceCollection groups = _principal.Groups;
                for (int j = 0; j < groups.Count; j++)
                {
                    for (int i = 0; i < acl.Count; i++)
                    {
                        System.Security.AccessControl.FileSystemAccessRule rule =
                            (System.Security.AccessControl.FileSystemAccessRule)acl[i];
                        if (groups[j].Equals(rule.IdentityReference))
                        {
                            if (System.Security.AccessControl.AccessControlType.
                                Deny.Equals(rule.AccessControlType))
                            {
                                if (contains(FileSystemRights.AppendData, rule))
                                {
                                    _denyAppendData = true;
                                }
                                if (contains(FileSystemRights.ChangePermissions, rule))
                                {
                                    _denyChangePermissions = true;
                                }
                                if (contains(FileSystemRights.CreateDirectories, rule))
                                {
                                    _denyCreateDirectories = true;
                                }
                                if (contains(FileSystemRights.CreateFiles, rule))
                                {
                                    _denyCreateFiles = true;
                                }
                                if (contains(FileSystemRights.Delete, rule))
                                {
                                    _denyDelete = true;
                                }
                                if (contains(FileSystemRights.
                                             DeleteSubdirectoriesAndFiles, rule))
                                {
                                    _denyDeleteSubdirectoriesAndFiles = true;
                                }
                                if (contains(FileSystemRights.ExecuteFile, rule))
                                {
                                    _denyExecuteFile = true;
                                }
                                if (contains(FileSystemRights.FullControl, rule))
                                {
                                    _denyFullControl = true;
                                }
                                if (contains(FileSystemRights.ListDirectory, rule))
                                {
                                    _denyListDirectory = true;
                                }
                                if (contains(FileSystemRights.Modify, rule))
                                {
                                    _denyModify = true;
                                }
                                if (contains(FileSystemRights.Read, rule))
                                {
                                    _denyRead = true;
                                }
                                if (contains(FileSystemRights.ReadAndExecute, rule))
                                {
                                    _denyReadAndExecute = true;
                                }
                                if (contains(FileSystemRights.ReadAttributes, rule))
                                {
                                    _denyReadAttributes = true;
                                }
                                if (contains(FileSystemRights.ReadData, rule))
                                {
                                    _denyReadData = true;
                                }
                                if (contains(FileSystemRights.
                                             ReadExtendedAttributes, rule))
                                {
                                    _denyReadExtendedAttributes = true;
                                }
                                if (contains(FileSystemRights.ReadPermissions, rule))
                                {
                                    _denyReadPermissions = true;
                                }
                                if (contains(FileSystemRights.Synchronize, rule))
                                {
                                    _denySynchronize = true;
                                }
                                if (contains(FileSystemRights.TakeOwnership, rule))
                                {
                                    _denyTakeOwnership = true;
                                }
                                if (contains(FileSystemRights.Traverse, rule))
                                {
                                    _denyTraverse = true;
                                }
                                if (contains(FileSystemRights.Write, rule))
                                {
                                    _denyWrite = true;
                                }
                                if (contains(FileSystemRights.WriteAttributes, rule))
                                {
                                    _denyWriteAttributes = true;
                                }
                                if (contains(FileSystemRights.WriteData, rule))
                                {
                                    _denyWriteData = true;
                                }
                                if (contains(FileSystemRights.
                                             WriteExtendedAttributes, rule))
                                {
                                    _denyWriteExtendedAttributes = true;
                                }
                            }
                            else if (System.Security.AccessControl.AccessControlType.
                                     Allow.Equals(rule.AccessControlType))
                            {
                                if (contains(FileSystemRights.AppendData, rule))
                                {
                                    _allowAppendData = true;
                                }
                                if (contains(FileSystemRights.ChangePermissions, rule))
                                {
                                    _allowChangePermissions = true;
                                }
                                if (contains(FileSystemRights.CreateDirectories, rule))
                                {
                                    _allowCreateDirectories = true;
                                }
                                if (contains(FileSystemRights.CreateFiles, rule))
                                {
                                    _allowCreateFiles = true;
                                }
                                if (contains(FileSystemRights.Delete, rule))
                                {
                                    _allowDelete = true;
                                }
                                if (contains(FileSystemRights.
                                             DeleteSubdirectoriesAndFiles, rule))
                                {
                                    _allowDeleteSubdirectoriesAndFiles = true;
                                }
                                if (contains(FileSystemRights.ExecuteFile, rule))
                                {
                                    _allowExecuteFile = true;
                                }
                                if (contains(FileSystemRights.FullControl, rule))
                                {
                                    _allowFullControl = true;
                                }
                                if (contains(FileSystemRights.ListDirectory, rule))
                                {
                                    _allowListDirectory = true;
                                }
                                if (contains(FileSystemRights.Modify, rule))
                                {
                                    _allowModify = true;
                                }
                                if (contains(FileSystemRights.Read, rule))
                                {
                                    _allowRead = true;
                                }
                                if (contains(FileSystemRights.ReadAndExecute, rule))
                                {
                                    _allowReadAndExecute = true;
                                }
                                if (contains(FileSystemRights.ReadAttributes, rule))
                                {
                                    _allowReadAttributes = true;
                                }
                                if (contains(FileSystemRights.ReadData, rule))
                                {
                                    _allowReadData = true;
                                }
                                if (contains(FileSystemRights.
                                             ReadExtendedAttributes, rule))
                                {
                                    _allowReadExtendedAttributes = true;
                                }
                                if (contains(FileSystemRights.ReadPermissions, rule))
                                {
                                    _allowReadPermissions = true;
                                }
                                if (contains(FileSystemRights.Synchronize, rule))
                                {
                                    _allowSynchronize = true;
                                }
                                if (contains(FileSystemRights.TakeOwnership, rule))
                                {
                                    _allowTakeOwnership = true;
                                }
                                if (contains(FileSystemRights.Traverse, rule))
                                {
                                    _allowTraverse = true;
                                }
                                if (contains(FileSystemRights.Write, rule))
                                {
                                    _allowWrite = true;
                                }
                                if (contains(FileSystemRights.WriteAttributes, rule))
                                {
                                    _allowWriteAttributes = true;
                                }
                                if (contains(FileSystemRights.WriteData, rule))
                                {
                                    _allowWriteData = true;
                                }
                                if (contains(FileSystemRights.WriteExtendedAttributes,
                                             rule))
                                {
                                    _allowWriteExtendedAttributes = true;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                //Deal with IO exceptions if you want
                throw e;
            }
        }
示例#53
0
 protected void Initialize(string id, DateTime effectiveTime, DateTime expirationTime, System.Security.Principal.WindowsIdentity windowsIdentity, bool clone)
 {
     this.Initialize(id, null, effectiveTime, expirationTime, windowsIdentity, clone);
 }
示例#54
0
        public WindowsSecurityToken(System.Security.Principal.WindowsIdentity windowsIdentity, string id, string authenticationType)
        {
            DateTime utcNow = DateTime.UtcNow;

            this.Initialize(id, authenticationType, utcNow, DateTime.UtcNow.AddHours(10.0), windowsIdentity, true);
        }
示例#55
0
 public WindowsSecurityToken(System.Security.Principal.WindowsIdentity windowsIdentity, string id) : this(windowsIdentity, id, null)
 {
 }
示例#56
0
 public WindowsSecurityToken(System.Security.Principal.WindowsIdentity windowsIdentity) : this(windowsIdentity, SecurityUniqueId.Create().Value)
 {
 }
示例#57
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            if (mutex.WaitOne(TimeSpan.Zero, true))
            {
#if DEBUG
                Global.isDebug = true;
#endif
                Global.Initialize();
                string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                Directory.SetCurrentDirectory(path);
                string logiDll = Path.Combine(path, "LogitechLed.dll");
                if (File.Exists(logiDll))
                {
                    File.Delete(logiDll);
                }
                StringBuilder systeminfo_sb = new StringBuilder(string.Empty);
                systeminfo_sb.Append("\r\n========================================\r\n");

                try
                {
                    var    win_reg     = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
                    string productName = (string)win_reg.GetValue("ProductName");

                    systeminfo_sb.AppendFormat("Operation System: {0}\r\n", productName);
                }
                catch (Exception exc)
                {
                    systeminfo_sb.AppendFormat("Operation System: Could not be retrieved. [Exception: {0}]\r\n", exc.Message);
                }

                systeminfo_sb.AppendFormat("System Architecture: " + (Environment.Is64BitOperatingSystem ? "64 bit" : "32 bit") + "\r\n");

                systeminfo_sb.AppendFormat("Environment OS Version: {0}\r\n", Environment.OSVersion);

                systeminfo_sb.AppendFormat("System Directory: {0}\r\n", Environment.SystemDirectory);
                systeminfo_sb.AppendFormat("Executing Directory: {0}\r\n", Global.ExecutingDirectory);
                systeminfo_sb.AppendFormat("Launch Directory: {0}\r\n", Directory.GetCurrentDirectory());
                systeminfo_sb.AppendFormat("Processor Count: {0}\r\n", Environment.ProcessorCount);
                //systeminfo_sb.AppendFormat("User DomainName: {0}\r\n", Environment.UserDomainName);
                //systeminfo_sb.AppendFormat("User Name: {0}\r\n", Environment.UserName);

                systeminfo_sb.AppendFormat("SystemPageSize: {0}\r\n", Environment.SystemPageSize);
                systeminfo_sb.AppendFormat("Environment Version: {0}\r\n", Environment.Version);

                System.Security.Principal.WindowsIdentity  identity  = System.Security.Principal.WindowsIdentity.GetCurrent();
                System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
                systeminfo_sb.AppendFormat("Is Elevated: {0}\r\n", principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator));
                systeminfo_sb.AppendFormat("Aurora Assembly Version: {0}\r\n", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);
                systeminfo_sb.AppendFormat("Aurora File Version: {0}\r\n", System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).FileVersion);

                systeminfo_sb.Append("========================================\r\n");

                Global.logger.Info(systeminfo_sb.ToString());

                string arg = "";

                for (int arg_i = 0; arg_i < e.Args.Length; arg_i++)
                {
                    arg = e.Args[arg_i];

                    switch (arg)
                    {
                    case ("-debug"):
                        Global.isDebug = true;
                        Global.logger.Info("Program started in debug mode.");
                        break;

                    case ("-silent"):
                        isSilent = true;
                        Global.logger.Info("Program started with '-silent' parameter");
                        break;

                    case ("-ignore_update"):
                        ignore_update = true;
                        Global.logger.Info("Program started with '-ignore_update' parameter");
                        break;

                    case ("-delay"):
                        isDelayed = true;

                        if (arg_i + 1 < e.Args.Length && int.TryParse(e.Args[arg_i + 1], out delayTime))
                        {
                            arg_i++;
                        }
                        else
                        {
                            delayTime = 5000;
                        }

                        Global.logger.Info("Program started with '-delay' parameter with delay of " + delayTime + " ms");

                        break;

                    case ("-install_logitech"):
                        Global.logger.Info("Program started with '-install_logitech' parameter");

                        try
                        {
                            InstallLogitech();
                        }
                        catch (Exception exc)
                        {
                            System.Windows.MessageBox.Show("Could not patch Logitech LED SDK. Error: \r\n\r\n" + exc, "Aurora Error");
                        }

                        Environment.Exit(0);
                        break;
                    }
                }

                AppDomain currentDomain = AppDomain.CurrentDomain;
                if (!Global.isDebug)
                {
                    currentDomain.UnhandledException += CurrentDomain_UnhandledException;
                }

                if (isDelayed)
                {
                    System.Threading.Thread.Sleep((int)delayTime);
                }

                this.ShutdownMode = ShutdownMode.OnExplicitShutdown;
                //AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit);

                if (Environment.Is64BitProcess)
                {
                    currentDomain.AppendPrivatePath("x64");
                }
                else
                {
                    currentDomain.AppendPrivatePath("x86");
                }

                Global.StartTime = Utils.Time.GetMillisecondsSinceEpoch();

                Global.dev_manager = new DeviceManager();
                Global.effengine   = new Effects();

                //Load config
                Global.logger.Info("Loading Configuration");
                try
                {
                    Global.Configuration = ConfigManager.Load();
                }
                catch (Exception exc)
                {
                    Global.logger.Error("Exception during ConfigManager.Load(). Error: " + exc);
                    System.Windows.MessageBox.Show("Exception during ConfigManager.Load().Error: " + exc.Message + "\r\n\r\n Default configuration loaded.", "Aurora - Error");

                    Global.Configuration = new Configuration();
                }

                Global.Configuration.PropertyChanged += (sender, eventArgs) => {
                    ConfigManager.Save(Global.Configuration);
                };

                Process.GetCurrentProcess().PriorityClass = Global.Configuration.HighPriority ? ProcessPriorityClass.High : ProcessPriorityClass.Normal;

                if (Global.Configuration.updates_check_on_start_up && !ignore_update)
                {
                    string updater_path = System.IO.Path.Combine(Global.ExecutingDirectory, "Aurora-Updater.exe");

                    if (File.Exists(updater_path))
                    {
                        try
                        {
                            ProcessStartInfo updaterProc = new ProcessStartInfo();
                            updaterProc.FileName  = updater_path;
                            updaterProc.Arguments = "-silent";
                            Process.Start(updaterProc);
                        }
                        catch (Exception exc)
                        {
                            Global.logger.Error("Could not start Aurora Updater. Error: " + exc);
                        }
                    }
                }

                Global.logger.Info("Loading Plugins");
                (Global.PluginManager = new PluginManager()).Initialize();

                Global.logger.Info("Loading KB Layouts");
                Global.kbLayout = new KeyboardLayoutManager();
                Global.kbLayout.LoadBrandDefault();

                Global.logger.Info("Loading Input Hooking");
                Global.InputEvents = new InputEvents();
                Global.Configuration.PropertyChanged += SetupVolumeAsBrightness;
                SetupVolumeAsBrightness(Global.Configuration,
                                        new PropertyChangedEventArgs(nameof(Global.Configuration.UseVolumeAsBrightness)));
                Utils.DesktopUtils.StartSessionWatch();

                Global.key_recorder = new KeyRecorder(Global.InputEvents);

                Global.logger.Info("Loading RazerSdkManager");
                if (RzHelper.IsSdkVersionSupported(RzHelper.GetSdkVersion()))
                {
                    try
                    {
                        Global.razerSdkManager = new RzSdkManager()
                        {
                            KeyboardEnabled = true,
                            MouseEnabled    = true,
                            MousepadEnabled = true,
                            AppListEnabled  = true,
                        };

                        Global.logger.Info("RazerSdkManager loaded successfully!");
                    }
                    catch (Exception exc)
                    {
                        Global.logger.Fatal("RazerSdkManager failed to load!");
                        Global.logger.Fatal(exc.ToString());
                    }
                }
                else
                {
                    Global.logger.Warn("Currently installed razer sdk version \"{0}\" is not supported by the RazerSdkManager!", RzHelper.GetSdkVersion());
                }

                Global.logger.Info("Loading Applications");
                (Global.LightingStateManager = new LightingStateManager()).Initialize();

                if (Global.Configuration.GetPointerUpdates)
                {
                    Global.logger.Info("Fetching latest pointers");
                    Task.Run(() => Utils.PointerUpdateUtils.FetchDevPointers("master"));
                }

                Global.logger.Info("Loading Device Manager");
                Global.dev_manager.RegisterVariables();
                Global.dev_manager.Initialize();

                /*Global.logger.LogLine("Starting GameEventHandler", Logging_Level.Info);
                 * Global.geh = new GameEventHandler();
                 * if (!Global.geh.Init())
                 * {
                 *  Global.logger.LogLine("GameEventHander could not initialize", Logging_Level.Error);
                 *  return;
                 * }*/

                Global.logger.Info("Starting GameStateListener");
                try
                {
                    Global.net_listener = new NetworkListener(9088);
                    Global.net_listener.NewGameState            += new NewGameStateHandler(Global.LightingStateManager.GameStateUpdate);
                    Global.net_listener.WrapperConnectionClosed += new WrapperConnectionClosedHandler(Global.LightingStateManager.ResetGameState);
                }
                catch (Exception exc)
                {
                    Global.logger.Error("GameStateListener Exception, " + exc);
                    System.Windows.MessageBox.Show("GameStateListener Exception.\r\n" + exc);
                    Environment.Exit(0);
                }

                if (!Global.net_listener.Start())
                {
                    Global.logger.Error("GameStateListener could not start");
                    System.Windows.MessageBox.Show("GameStateListener could not start. Try running this program as Administrator.\r\nExiting.");
                    Environment.Exit(0);
                }

                Global.logger.Info("Listening for game integration calls...");

                Global.logger.Info("Loading ResourceDictionaries...");
                this.Resources.MergedDictionaries.Add(new ResourceDictionary {
                    Source = new Uri("Themes/MetroDark/MetroDark.MSControls.Core.Implicit.xaml", UriKind.Relative)
                });
                this.Resources.MergedDictionaries.Add(new ResourceDictionary {
                    Source = new Uri("Themes/MetroDark/MetroDark.MSControls.Toolkit.Implicit.xaml", UriKind.Relative)
                });
                Global.logger.Info("Loaded ResourceDictionaries");


                Global.logger.Info("Loading ConfigUI...");

                MainWindow = new ConfigUI();
                ((ConfigUI)MainWindow).Display();

                //Debug Windows on Startup
                if (Global.Configuration.BitmapWindowOnStartUp)
                {
                    Window_BitmapView.Open();
                }
                if (Global.Configuration.HttpWindowOnStartUp)
                {
                    Window_GSIHttpDebug.Open();
                }
            }
            else
            {
                try
                {
                    NamedPipeClientStream client = new NamedPipeClientStream(".", "aurora\\interface", PipeDirection.Out);
                    client.Connect(30);
                    if (!client.IsConnected)
                    {
                        throw new Exception();
                    }
                    byte[] command = System.Text.Encoding.ASCII.GetBytes("restore");
                    client.Write(command, 0, command.Length);
                    client.Close();
                }
                catch
                {
                    //Global.logger.LogLine("Aurora is already running.", Logging_Level.Error);
                    System.Windows.MessageBox.Show("Aurora is already running.\r\nExiting.", "Aurora - Error");
                }
            }
        }
示例#58
0
文件: LRUpload.cs 项目: rpwillis/mlg
        void submitButton_Click(object sender, EventArgs e)
        {
            byte[]     contents            = null;
            string     fullDirPath         = string.Empty;
            string     fullFilePath        = string.Empty;
            bool       overWrite           = false;
            string     xmlMetadataFilePath = String.Empty;
            string     destinationUrl      = String.Empty;
            Hashtable  metadata            = null;
            bool       shouldReturn        = false;
            SPListItem fileItem            = null;


            System.Security.Principal.WindowsIdentity currentIdentity = System.Security.Principal.WindowsIdentity.GetCurrent();

            try
            {
                if (IsValidFile())
                {
                    FileUpload uploadControl = (FileUpload)this.FindControl(UploadFileID);
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        //DownloadFile
                        string parentPath = Path.Combine(Path.GetTempPath(), "LRUpload");
//                           string parentPath = Path.Combine(Environment.CurrentDirectory, "LRUpload");
                        //The directory that will hold the zip file and the extracted files
                        //The directory is named by the filename
                        fullDirPath = Path.Combine(parentPath, Path.GetFileNameWithoutExtension(uploadControl.FileName));
                        //the full zip file path
                        fullFilePath = Path.Combine(fullDirPath, Path.GetFileName(uploadControl.FileName));


                        //Get requried permissions for the temp directory
                        FileIOPermission perm = new FileIOPermission(FileIOPermissionAccess.AllAccess, parentPath);
                        perm.Assert();

                        //Create the directory and save the file
                        Directory.CreateDirectory(fullDirPath);
                        uploadControl.PostedFile.SaveAs(fullFilePath);



                        //Unzip
                        try
                        {
                            Compression.Unzip(new FileInfo(fullFilePath), new DirectoryInfo(fullDirPath));
                        }
                        catch (CompressionException)
                        {
                            ShowMessage(LoadResource("InvalidFile"));
                            shouldReturn = true;
                            return;
                        }
                        //Look for the file

                        try
                        {
                            xmlMetadataFilePath = GetXmlMetadataFile(fullDirPath);
                        }

                        catch (FileNotFoundException)
                        {
                            Directory.Delete(fullDirPath, true);
                            ShowMessage(LoadResource("InvalidPackage"));
                            shouldReturn = true;
                            return;
                        }


                        destinationUrl = Path.GetFileName(fullFilePath);
                        //destinationUrl = SourceDocumentLibrary.TrimEnd('/') + "/" + Path.GetFileName(fullFilePath);

                        overWrite = ((CheckBox)this.FindControl(CheckOverrideID)).Checked;
                        //Check if existing files exist
                        if (!overWrite)
                        {
                            if (FileExistsInDocumentLibrary(destinationUrl))
                            {
                                Directory.Delete(fullDirPath, true);
                                ShowMessage(LoadResource("FileAlreadyExists"));
                                shouldReturn = true;
                                return;
                            }
                        }
                        //Read the file contents
                        contents = ReadFileContents(fullFilePath);
                        //Populate file metadata
                        metadata = PopulateMetadata(GetContentTypeByID(GetSelectedContentType()), xmlMetadataFilePath);
                    });

                    if (!shouldReturn)
                    {
                        //Re-impersonate the current user
                        currentIdentity.Impersonate();
                        fileItem = UploadFile(contents, destinationUrl, overWrite).Item;
                        UpdateDocLibItem(fileItem, metadata);
                    }
                    else
                    {
                        return;
                    }

                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        Directory.Delete(fullDirPath, true);
                    });

                    ShowMessage(LoadResource("FileUploaded"));
                }
            }
            catch (Exception ex)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    if (Directory.Exists(fullDirPath))
                    {
                        Directory.Delete(fullDirPath, true);
                    }
                });
                ShowError(ex);
            }
        }
示例#59
-1
        //private static readonly byte[] _genericIv = ConvertEx.FromBase16String("C9DCF37AED8574A1441FD82DB743765C");

        /// <summary>
        /// Impersonates the windows user.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <param name="domain">The domain.</param>
        /// <param name="password">The password.</param>
        /// <returns></returns>
        public static WindowsImpersonationContext ImpersonateWindowsUser(string userName, string domain, string password)
        {
            var token = IntPtr.Zero;
            var tokenDuplicate = IntPtr.Zero;
            try
            {
                if (CoreExtensions.RevertToSelf())
                    if (CoreExtensions.LogonUserA(userName, domain, password, CoreExtensions.LOGON32_LOGON_INTERACTIVE, CoreExtensions.LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                        if (CoreExtensions.DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                        {
                            var tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                            var impersonationContext = tempWindowsIdentity.Impersonate();
                            if (impersonationContext != null)
                            {
                                CoreExtensions.CloseHandle(token);
                                CoreExtensions.CloseHandle(tokenDuplicate);
                                return impersonationContext;
                            }
                        }
            }
            finally
            {
                if (token != IntPtr.Zero)
                    CoreExtensions.CloseHandle(token);
                if (tokenDuplicate != IntPtr.Zero)
                    CoreExtensions.CloseHandle(tokenDuplicate);
            }
            throw new Exception("Unable to login.");
        }
示例#60
-1
        public WindowsImpersonationContext SetImpersonatedUser(string userName, string domainName, string password)
        {
            WindowsImpersonationContext impersonatedUser = null;
            const int LOGON32_PROVIDER_DEFAULT = 0;
            ////This parameter causes LogonUser to create a primary token.
            const int LOGON32_LOGON_INTERACTIVE = 2;

            try
            {
                SafeTokenHandle safeTokenHandle;
                //// Call LogonUser to obtain a handle to an access token.
                bool returnValue = LogonUser(userName, domainName, password,LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,out safeTokenHandle);

                using (safeTokenHandle)
                {
                    //// Check the identity.
                    Console.WriteLine("Before impersonation: "
                        + WindowsIdentity.GetCurrent().Name);
                    //// Use the token handle returned by LogonUser.
                    WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle());
                    impersonatedUser = newId.Impersonate();
                }

                return impersonatedUser;
            }
            catch (Exception ex)
            {
                logger.Error(string.Format("SetImpersonatedUser - {0}", ex.Message));
                return impersonatedUser;
            }
        }