Beispiel #1
0
 public void Enter()
 {
     if (this.IsInContext)
     {
         return;
     }
     m_Token = new IntPtr(0);
     try
     {
         m_Token = IntPtr.Zero;
         bool logonSuccessfull = LogonUser(
             _username,
             _domain,
             _password,
             _type == CredentialsType.Local ? LOGON32_LOGON_INTERACTIVE : LOGON32_LOGON_NEW_CREDENTIALS,
             _type == CredentialsType.Local ? LOGON32_PROVIDER_DEFAULT : LOGON32_PROVIDER_WINNT50,
             ref m_Token);
         if (logonSuccessfull == false)
         {
             int error = Marshal.GetLastWin32Error();
             throw new ApplicationException(string.Format("Could not impersonate the elevated user.  LogonUser returned error code {0}.", error));
         }
         System.Security.Principal.WindowsIdentity identity = new System.Security.Principal.WindowsIdentity(m_Token);
         _context = identity.Impersonate();
     }
     catch (Exception e)
     {
         Console.WriteLine("Could not impersonate the elevated user. It may be invalid credentials.");
     }
 }
Beispiel #2
0
       void Init(string username, string password, string domain)  
       {  
           if (LogonUser(username, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref   token))  
           {  
               bool error = true;  
               try  
               {  
                   context = System.Security.Principal.WindowsIdentity.Impersonate(token);  
                   error = false;  
               }  
               finally  
               {  
                   if (error)  
                       CloseHandle(token);  
               }  
           }  
           else  
           {  
               int err = System.Runtime.InteropServices.Marshal.GetLastWin32Error();  
 
               IntPtr tempptr = IntPtr.Zero;  
               string msg = null;  
 
               FormatMessage(0x1300, ref   tempptr, err, 0, ref   msg, 255, ref   tempptr);  
 
               throw (new Exception(msg));  
           }  
       }  
Beispiel #3
0
        void Init(string username, string password, string domain)
        {
            if (LogonUser(username, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token))
            {
                bool error = true;
                try
                {
                    context = System.Security.Principal.WindowsIdentity.Impersonate(token);
                    error   = false;
                }
                finally
                {
                    if (error)
                    {
                        CloseHandle(token);
                    }
                }
            }
            else
            {
                int err = System.Runtime.InteropServices.Marshal.GetLastWin32Error();

                IntPtr tempptr = IntPtr.Zero;
                string msg     = null;

                FormatMessage(0x1300, ref tempptr, err, 0, ref msg, 255, ref tempptr);

                throw (new Exception(msg));
            }
        }
        } // End Function GetProcessInfoByPID

        public static void Test()
        {
            using (System.Security.Principal.WindowsIdentity wi =
                       // new System.Security.Principal.WindowsIdentity(InvalidHandle))
                       //System.Security.Principal.WindowsIdentity.GetAnonymous())
                       GetWindowsIdentity(@"domain\username")
                   )
            {
                using (System.Security.Principal.WindowsImpersonationContext context = wi.Impersonate())
                {
                    // string n; string d;
                    // string la = GetProcessInfoByPID(System.Diagnostics.Process.GetCurrentProcess().Id, out n, out d);

                    System.Console.WriteLine(IdCache.MyId);

                    string foo = GetProcessUser(System.Diagnostics.Process.GetCurrentProcess());
                    System.Console.WriteLine(foo);

                    // string bar = GetProcessOwner(System.Diagnostics.Process.GetCurrentProcess().Id);
                    // System.Console.WriteLine(bar);

                    System.Console.WriteLine(wi.Name);
                    System.Console.WriteLine(System.Environment.UserName);

                    System.Security.Principal.WindowsIdentity wai = System.Security.Principal
                                                                    .WindowsIdentity.GetCurrent(true);

                    System.Console.WriteLine(wai.User);
                } // End Using context
            }     // End Using WindowsIdentity
        }         // End Sub Test
Beispiel #5
0
        internal bool RunAsAdministrator(System.Threading.Tasks.Task <bool> taskToDo)
        {
            try {
                /// If logon fails
                if (!LogonUser(Username, DomainName, Password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out SafeTokenHandleStruct safeTokenHandle))
                {
                    Utils.Tracer.Log($"Could not logon as {Username}@{DomainName} ; error code : {Marshal.GetLastWin32Error()}", Utils.MessageVerbosity.Error);
                    return(false);
                }

                /// we're connected
                using (safeTokenHandle) {
                    Utils.Tracer.Log($"Logged in with Windows NT token \"{safeTokenHandle}\" : {Username}@{DomainName}");

                    /// Use the token handle returned by LogonUser
                    using (System.Security.Principal.WindowsImpersonationContext ctx = System.Security.Principal.WindowsIdentity.Impersonate(safeTokenHandle.DangerousGetHandle())) {
                        /// using context will let us act as the new user
                        using (taskToDo) {
                            taskToDo.Start();
                            return(taskToDo.Result);
                        }
                        /// on Dispose/Close, we switch back to previous user
                    }
                }
            }
            catch (Exception ex) {
                Utils.Tracer.Log("Error trying to run as administrator", ex);
                return(false);
            }
        }
Beispiel #6
0
        private void _get_access()
        {
            IntPtr _token = new IntPtr();

            if (Win32API.LogonUser(_user_name, _domain_name, _password,
                                   Win32API.LogonTypes.NewCredentials,
                                   Win32API.LogonProviders.Default,
                                   out _token))
            {
                _ok = true;
                Win32API.DuplicateToken(_token, 2, ref _main_token);
                _win_identity         = new System.Security.Principal.WindowsIdentity(_main_token);
                _win_identity_context = _win_identity.Impersonate();
            }
            else
            {
                _ok = false;
                try
                {
                    _error =
                        System.Runtime.InteropServices.Marshal.GetLastWin32Error().ToString();
                }
                catch (Exception ex) { }
            }
        }
Beispiel #7
0
 /// <summary>
 /// Stops impersonation.
 /// </summary>
 private void UndoImpersonation()
 {
     if (_wic != null)
     {
         _wic.Undo();
     }
     _wic = null;
 }
Beispiel #8
0
 public void Revert()
 {
     if (_impersonationContext != null)
     {
         // Revert to previous user.
         _impersonationContext.Undo();
         _impersonationContext = null;
     }
 }
Beispiel #9
0
        public Impersonation(String username, String domain, String password)
        {
            IntPtr userToken            = IntPtr.Zero;
            IntPtr userTokenDuplication = IntPtr.Zero;

            // Logon with user and get token.
            bool loggedOn = LogonUser(username, domain, password,
                                      LogonType.Interactive, LogonProvider.Default,
                                      out userToken);

            if (loggedOn)
            {
                try
                {
                    // Create a duplication of the usertoken, this is a solution
                    // for the known bug that is published under KB article Q319615.
                    if (DuplicateToken(userToken, 2, ref userTokenDuplication))
                    {
                        // Create windows identity from the token and impersonate the user.
                        System.Security.Principal.WindowsIdentity identity = new System.Security.Principal.WindowsIdentity(userTokenDuplication);
                        _impersonationContext = identity.Impersonate();
                    }
                    else
                    {
                        // Token duplication failed!
                        // Use the default ctor overload
                        // that will use Mashal.GetLastWin32Error();
                        // to create the exceptions details.
                        throw new Exception("Could not copy token");
                    }
                    GlobalVars.LOGIN_NAME = Environment.UserName.ToString();
                }
                finally
                {
                    // Close usertoken handle duplication when created.
                    if (!userTokenDuplication.Equals(IntPtr.Zero))
                    {
                        // Closes the handle of the user.
                        CloseHandle(userTokenDuplication);
                        userTokenDuplication = IntPtr.Zero;
                    }

                    // Close usertoken handle when created.
                    if (!userToken.Equals(IntPtr.Zero))
                    {
                        // Closes the handle of the user.
                        CloseHandle(userToken);
                        userToken = IntPtr.Zero;
                    }
                }
            }
            else
            {
                throw new Exception("Login failed");
                //HttpContext.Current.Response.Write("<script>alert('Username or Password is incorrect. Please try again')</script>");
            }
        }
        private List <string> GetItems()
        {
            System.Security.Principal.WindowsImpersonationContext targetImpersonationContext = null;
            List <string> list = null;
            bool          res  = false;

            System.Data.SqlClient.SqlConnectionStringBuilder bldr;

            if (m_serverInfo.windowsAuth)
            {
                try
                {
                    System.Security.Principal.WindowsIdentity wi =
                        Impersonation.GetCurrentIdentity(m_serverInfo.login, m_serverInfo.password);
                    targetImpersonationContext = wi.Impersonate();
                }
                catch (Exception ex)
                {
                    Idera.SQLsecure.Core.Logger.LogX logX = new Idera.SQLsecure.Core.Logger.LogX("Idera.SQLsecure.UI.Console.Sql.Database");
                    logX.loggerX.Error("Error Processing Impersonation for retrieving Database objects list (" + m_serverInfo.login + ")", ex);
                }
                bldr = Sql.SqlHelper.ConstructConnectionString(m_serverInfo.connectionName, null, null, Utility.Activity.TypeServerOnPremise);
            }
            else
            {
                bldr = Sql.SqlHelper.ConstructConnectionString(m_serverInfo.connectionName, m_serverInfo.login, m_serverInfo.password, Utility.Activity.TypeServerOnPremise);
            }

            switch (m_filterObject.ObjectType)
            {
            case RuleObjectType.Database:
                res = Idera.SQLsecure.UI.Console.Sql.Database.GetTargetDatabases(m_serverInfo.version, m_filterObject.ObjectScope, bldr.ConnectionString, out list);
                break;

            case RuleObjectType.Table:
                res = Idera.SQLsecure.UI.Console.Sql.Database.GetTargetTables(m_serverInfo.version, m_filterObject.ObjectScope, m_databaseFilterObject, bldr.ConnectionString, out list);
                break;

            case RuleObjectType.View:
                res = Idera.SQLsecure.UI.Console.Sql.Database.GetTargetViews(m_serverInfo.version, m_filterObject.ObjectScope, m_databaseFilterObject, bldr.ConnectionString, out list);
                break;

            case RuleObjectType.Function:
                res = Idera.SQLsecure.UI.Console.Sql.Database.GetTargetFunctions(m_serverInfo.version, m_filterObject.ObjectScope, m_databaseFilterObject, bldr.ConnectionString, out list);
                break;
            }

            if (targetImpersonationContext != null)
            {
                targetImpersonationContext.Undo();
                targetImpersonationContext.Dispose();
                targetImpersonationContext = null;
            }

            return(res ? list : new List <string>());
        }
 // ... and revert after completion of request
 partial void CoreData_ReceivedResponse(ODataReceivedState state)
 {
     if (null == _impersonationContext)
     {
         return;
     }
     _impersonationContext.Undo();
     _impersonationContext.Dispose();
     _impersonationContext = null;
 }
Beispiel #12
0
        public static void Save(SiteConfig siteConfig)
        {
            System.Security.Principal.WindowsImpersonationContext wi = Impersonation.Impersonate();

            XmlSerializer ser = new XmlSerializer(typeof(SiteConfig));

            using (StreamWriter writer = new StreamWriter(SiteConfig.GetConfigFilePathFromCurrentContext()))
            {
                ser.Serialize(writer, siteConfig);
            }

            wi.Undo();
        }
Beispiel #13
0
        public static void Save(SeoMetaTags seoConfig)
        {
            System.Security.Principal.WindowsImpersonationContext wi = Impersonation.Impersonate();

            XmlSerializer ser = new XmlSerializer(typeof(SeoMetaTags));

            using (StreamWriter writer = new StreamWriter(MetaConfigFile))
            {
                ser.Serialize(writer, seoConfig);
            }

            wi.Undo();
        }
Beispiel #14
0
        public void Leave()
        {
            if (this.IsInContext == false)
            {
                return;
            }
            _context.Undo();

            if (m_Token != IntPtr.Zero)
            {
                CloseHandle(m_Token);
            }
            _context = null;
        }
Beispiel #15
0
 public void Dispose()
 {
     if (context != null)
     {
         try
         {
             context.Undo();
         }
         finally
         {
             CloseHandle(token);
             context = null;
         }
     }
 }
Beispiel #16
0
        public static void CopyFile2RemoteFolder(string from, string to, string username, string domain, string password)
        {
            IntPtr tokenHandle = new IntPtr(0);
            int    returnValue = LogonUser(username, domain, password, 2, 0, ref tokenHandle);

            if (returnValue == -1)
            {
                throw new Exception("Logon failed.");
            }

            System.Security.Principal.WindowsImpersonationContext impersonatedUser = null;
            System.Security.Principal.WindowsIdentity             wid = new System.Security.Principal.WindowsIdentity(tokenHandle);
            impersonatedUser = wid.Impersonate();

            System.IO.File.Copy(from, to, true);
            impersonatedUser.Undo();
        }
        // set up impersonation ...
        partial void CoreData_SendingRequest(ODataSendingState state)
        {
            System.Security.Principal.WindowsIdentity identity;
            if (HttpContext.Current.User.Identity.GetType().Name == "GenericIdentity")
            {
                identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            }
            else
            {
                identity = (System.Security.Principal.WindowsIdentity) HttpContext.Current.User.Identity;
            }
            biz.dfch.CS.Utilities.Logging.Trace.WriteLine("{0}: '{1}' @{2}", Method.fn(), identity.Name, HttpContext.Current.User.Identity.GetType().Name);

            state.Request.Headers.Add("Biz-Dfch-Impersonated-User", string.Format("{0}-{1}", identity.AuthenticationType, identity.Name));
            state.Request.PreAuthenticate = true;
            state.Request.Credentials = System.Net.CredentialCache.DefaultCredentials;

            _impersonationContext = identity.Impersonate();
        }
Beispiel #18
0
        internal void Save(DataManager data)
        {
            string fullPath = data.ResolvePath(FileName);

            // We use the internal list to circumvent ignoring
            // items where IsPublic is set to false.
            if (Entries.Count == 0)
            {
                if (File.Exists(fullPath))
                {
                    File.Delete(fullPath);
                }
            }
            else
            {
                System.Security.Principal.WindowsImpersonationContext wi = Impersonation.Impersonate();

                FileStream fileStream = FileUtils.OpenForWrite(fullPath);

                if (fileStream != null)
                {
                    try
                    {
                        XmlSerializer ser = new XmlSerializer(typeof(DayEntry), Data.NamespaceURI);
                        using (StreamWriter writer = new StreamWriter(fileStream))
                        {
                            ser.Serialize(writer, this);
                        }
                    }
                    catch (Exception e)
                    {
                        ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, e);
                    }
                    finally
                    {
                        fileStream.Close();
                    }
                }

                wi.Undo();
            }
        }
Beispiel #19
0
        public bool ImpersonateValidUser(String userName, String domain, String password)
        {
            try
            {
                System.Security.Principal.WindowsIdentity tempWindowsIdentity;
                IntPtr token          = IntPtr.Zero;
                IntPtr tokenDuplicate = IntPtr.Zero;

                if (RevertToSelf())
                {
                    if (LogonUserW(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);
                }

                return(false);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
        /// <summary>
        /// 连接网络资源
        /// </summary>
        /// <param name="domain">IP/计算机名</param>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public static bool impersonateValidUser(String domain, String userName, String password)
        {
            System.Security.Principal.WindowsIdentity tempWindowsIdentity;
            IntPtr token          = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            if (RevertToSelf())
            {
                // 这里使用LOGON32_LOGON_NEW_CREDENTIALS来访问远程资源。
                // 如果要(通过模拟用户获得权限)实现服务器程序,访问本地授权数据库可
                // 以用LOGON32_LOGON_INTERACTIVE
                if (LogonUser(userName, domain, password, LOGON32_LOGON_NEW_CREDENTIALS,
                              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)
                        {
                            System.AppDomain.CurrentDomain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy.WindowsPrincipal);
                            System.Security.Principal.IPrincipal pr = System.Threading.Thread.CurrentPrincipal;
                            System.Security.Principal.IIdentity  id = pr.Identity;
                            CloseHandle(token);
                            CloseHandle(tokenDuplicate);
                            return(true);
                        }
                    }
                }
            }
            if (token != IntPtr.Zero)
            {
                CloseHandle(token);
            }
            if (tokenDuplicate != IntPtr.Zero)
            {
                CloseHandle(tokenDuplicate);
            }
            return(false);
        }
Beispiel #21
0
 public static void LogIt(string msg, string type)
 {
     //Method used for logging errors or other messages to the Event log.
     System.Security.Principal.WindowsImpersonationContext wic = null;
     try
     {
         wic = System.Security.Principal.WindowsIdentity.Impersonate(IntPtr.Zero);
         string source  = "Neudesic Mobile Application";
         string logName = "Application";
         string message = msg;
         if (!EventLog.SourceExists(source))
         {
             EventLog.CreateEventSource(source, logName);
         }
         if (type.ToLower() == "msg" || type.ToLower() == "info")
         {
             EventLog.WriteEntry(source, message, EventLogEntryType.Information);
         }
         else if (type.ToLower() == "warning")
         {
             EventLog.WriteEntry(source, message, EventLogEntryType.Warning);
         }
         else
         {
             EventLog.WriteEntry(source, message, EventLogEntryType.Error);
         }
     }
     catch (Exception ex)
     {
         LogIt(ex.ToString(), "Error");
         throw new Exception(ex.ToString());
     }
     finally
     {
         if (wic != null)
         {
             wic.Undo();
         }
     }
 }
Beispiel #22
0
        public void Impersonate(string userName, string domainName, string password, LogonType logonType, LogonProvider logonProvider)
        {
            UndoImpersonation();
            IntPtr logonToken          = IntPtr.Zero;
            IntPtr logonTokenDuplicate = IntPtr.Zero;

            try
            {
                _wic = System.Security.Principal.WindowsIdentity.Impersonate(IntPtr.Zero);
                if (Win32NativeMethods.LogonUser(userName, domainName, password, (int)logonType, (int)logonProvider, ref logonToken) != 0)
                {
                    if (Win32NativeMethods.DuplicateToken(logonToken, (int)ImpersonationLevel.SecurityImpersonation, ref logonTokenDuplicate) != 0)
                    {
                        var wi = new System.Security.Principal.WindowsIdentity(logonTokenDuplicate);
                        wi.Impersonate();
                    }
                    else
                    {
                        throw new System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error());
                    }
                }
                else
                {
                    throw new System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error());
                }
            }
            finally
            {
                if (logonToken != IntPtr.Zero)
                {
                    Win32NativeMethods.CloseHandle(logonToken);
                }
                if (logonTokenDuplicate != IntPtr.Zero)
                {
                    Win32NativeMethods.CloseHandle(logonTokenDuplicate);
                }
            }
        }
        public async Task <ActionResult> About()
        {
            AdInfo adinfo = new AdInfo();

            var apiBaseUrl      = Environment.GetEnvironmentVariable("API_URL") ?? "http://localhost:60201/";
            var idToImpersonate = User.Identity; //could also try Request.LogonUserIdentity

            using (System.Security.Principal.WindowsImpersonationContext impersonationContext =
                       ((System.Security.Principal.WindowsIdentity)idToImpersonate).Impersonate())
            {
                var client = new HttpClient(new HttpClientHandler()
                {
                    UseDefaultCredentials = true
                });
                client.BaseAddress = new Uri(apiBaseUrl);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));
                string json = await Task.Run(() => JsonConvert.SerializeObject(new UPNInfo()
                {
                    UPN = LDAPHelper.GetUPN(idToImpersonate.Name)
                }));

                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await client.PostAsync("api/values", content);

                if (response.IsSuccessStatusCode)
                {
                    string data = await response.Content.ReadAsStringAsync();

                    JavaScriptSerializer JSserializer = new JavaScriptSerializer();
                    adinfo = JSserializer.Deserialize <AdInfo>(data);
                }
            }
            return(View(adinfo));
        }
        private static void loopCrackNTPassword(ref char[] buffer, int level, string domain, string user, ref string pass, ref bool found)
        {
            int nextLevel = level + 1;

            char[] charSet = "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ0123456789".ToCharArray();
            for (int c = 0; c < charSet.Length; c++)
            {
                buffer[level] = charSet[c];
                if (nextLevel == buffer.Length)
                {
                    string strBuffer = new string(buffer);
                    //Console.WriteLine("Trying password: " + strBuffer);
                    System.Security.Principal.WindowsImpersonationContext wic = getImpersonate(domain, user, strBuffer);
                    if (wic != null)
                    {
                        wic.Undo();
                        wic.Dispose();
                        wic   = null;
                        found = true;
                        pass  = new string(buffer);
                        return;
                    }
                }
                else
                {
                    if (!found)
                    {
                        loopCrackNTPassword(ref buffer, nextLevel, domain, user, ref pass, ref found);
                    }
                    else
                    {
                        return;
                    }
                }
            }
        }
 private void _get_access()
 {
     IntPtr _token = new IntPtr();
     if (Win32API.LogonUser(_user_name, _domain_name, _password,
         Win32API.LogonTypes.NewCredentials,
         Win32API.LogonProviders.Default,
         out _token))
     {
         _ok = true;
         Win32API.DuplicateToken(_token, 2, ref _main_token);
         _win_identity = new System.Security.Principal.WindowsIdentity(_main_token);
         _win_identity_context = _win_identity.Impersonate();
     }
     else
     {
         _ok = false;
         try
         {
             _error =
                 System.Runtime.InteropServices.Marshal.GetLastWin32Error().ToString();
         }
         catch (Exception ex) { }
     }
 }
Beispiel #26
0
        public override void Execute()
        {
            try
            {
                this.Validate();
                string key     = base.Args["CompanyName"];
                string file    = base.Args["NonEncryptedFile"];
                string timeout = base.Args["Timeout"];

                string formattedString = CommandResources.GetFormattedString(CommandResources.ResourceID.Deploy, new object[] { key, file });
                base.WriteLogEntry(LogEntryType.Information, formattedString);

                // We need to show the identity used to deploy to SSO
                System.Security.Principal.WindowsIdentity identity =
                    System.Security.Principal.WindowsIdentity.GetCurrent();
                if (null != identity)
                {
                    WriteLogEntry(LogEntryType.Verbose,
                                  string.Format("Current WindowsIdentity: AuthenticationType:{0} - IsAuthenticated:{1} - Name:{2}",
                                                identity.AuthenticationType,
                                                identity.IsAuthenticated,
                                                identity.Name));
                    using (System.Security.Principal.WindowsImpersonationContext context =
                               identity.Impersonate())
                    {
                        identity = System.Security.Principal.WindowsIdentity.GetCurrent();
                        if (null != identity)
                        {
                            WriteLogEntry(LogEntryType.Verbose,
                                          string.Format("Impersonated WindowsIdentity: AuthenticationType:{0} - IsAuthenticated:{1} - Name:{2}",
                                                        identity.AuthenticationType,
                                                        identity.IsAuthenticated,
                                                        identity.Name));
                        }

                        // Deploy the non encrypted SSO XML file.
                        //System.Diagnostics.Debugger.Launch();
                        string    title;
                        DeploySSO deploy = new DeploySSO()
                        {
                            NonEncryptedFile = file, CompanyName = key
                        };
                        deploy.Overwrite = true; // We always overwrite the current SSO application settings
                        deploy.Log      += new DeploySSO.LogHandler(deploy_Log);
                        deploy.Execute(out title);

                        formattedString = CommandResources.GetFormattedString(CommandResources.ResourceID.DeploySuccess, new object[] { title });
                        base.WriteLogEntry(LogEntryType.Information, formattedString);
                    }
                }

                identity = System.Security.Principal.WindowsIdentity.GetCurrent();
                if (null != identity)
                {
                    WriteLogEntry(LogEntryType.Verbose,
                                  string.Format("After impersonation WindowsIdentity: AuthenticationType:{0} - IsAuthenticated:{1} - Name:{2}",
                                                identity.AuthenticationType,
                                                identity.IsAuthenticated,
                                                identity.Name));
                }

                base.commandResult = new CommandResult();
            }
            catch (Exception exception2)
            {
                base.ShowError(exception2);
                base.commandResult = new CommandResult(exception2);
                if ((exception2 is OutOfMemoryException) || (exception2 is StackOverflowException))
                {
                    throw;
                }
            }
        }
Beispiel #27
0
            public void doWork()
            {
                System.Security.Principal.WindowsImpersonationContext callerContext = null;

                try
                {
                    if (impersonateCaller)
                    {
                        System.Security.Permissions.SecurityPermission secPerm =
                            new System.Security.Permissions.SecurityPermission(System.Security.Permissions.PermissionState.Unrestricted);
                        secPerm.Assert();

                        //sometimes the first attempt will fail, due to what is apparently a CLR bug.
                        //Retry several times if necessary, and sleep to let things clear out.

                        int impersonationAttempt = 0;

                        while (impersonationAttempt < 25)
                        {
                            try
                            {
                                callerContext = System.Security.Principal.WindowsIdentity.Impersonate(callerIdentityToken);
                            }
                            catch (ArgumentException)
                            {
                                if (impersonationAttempt == 24)
                                {
                                    throw;
                                }
                                else
                                {
                                    Thread.Sleep(250);
                                    impersonationAttempt++;
                                    continue;
                                }
                            }

                            impersonationAttempt = 25;
                        }

                        System.Security.CodeAccessPermission.RevertAll();
                    }

                    SqlClientPermission sqlPerm =
                        new SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted);
                    sqlPerm.Assert();

                    using (SqlBulkCopy bc = new SqlBulkCopy(connectionString, copyOptions))
                    {
                        bc.DestinationTableName = destinationTable;
                        bc.BulkCopyTimeout      = 0;
                        bc.BatchSize            = batchSize;

                        if (columnMap != null)
                        {
                            foreach (SqlBulkCopyColumnMapping cm in columnMap)
                            {
                                bc.ColumnMappings.Add(cm);
                            }
                        }

                        bc.WriteToServer(this.bulkDataReader);
                    }
                }
                catch (Exception ex)
                {
                    Exception workerEx = new Exception("Exception occurred in worker", ex);
                    monitor.WorkerThreadException = workerEx;
                }
                finally
                {
                    this.threadFinishing = true;

                    if (callerContext != null)
                    {
                        callerContext.Undo();
                    }

                    monitor.SetWorkerCompleted(true);
                    this.workComplete = true;
                }
            }
Beispiel #28
0
 public void Dispose()  
 {  
     if (context != null)  
     {  
         try  
         {  
             context.Undo();  
         }  
         finally  
         {  
             CloseHandle(token);  
             context = null;  
         }  
     }  
 }  
        /// <summary>
        /// ctor
        /// </summary>
        /// <exception cref="System.Runtime.InteropServices.COMException"/>
        public OutlookManager()
        {
            var current = System.Security.Principal.WindowsIdentity.GetCurrent();
            m_impContext = current.Impersonate();

            System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("OUTLOOK");
            int collCount = processes.Length;

            if (collCount != 0)
            {
                #region comment
                //try
                //{
                //    // create an application instance of Outlook
                //    oApp = new Microsoft.Office.Interop.Outlook.Application();
                //}
                //catch (System.Exception ex)
                //{
                //    try
                //    {
                //        // get Outlook in another way
                //        oApp = Marshal.GetActiveObject("Outlook.Application") as Microsoft.Office.Interop.Outlook.Application;
                //    }
                //    catch (System.Exception ex2)
                //    {
                //        // try some other way to get the object
                //        oApp = Activator.CreateInstance(Type.GetTypeFromProgID("Outlook.Application")) as Microsoft.Office.Interop.Outlook.Application;
                //    }
                //}
                #endregion

                try
                {
                    // Outlook already running, hook into the Outlook instance
                    m_outlookApp = System.Runtime.InteropServices.Marshal.GetActiveObject("Outlook.Application") as Microsoft.Office.Interop.Outlook.Application;
                }
                catch (System.Runtime.InteropServices.COMException ex)
                {
                    if (ex.ErrorCode == -2147221021)
                        m_outlookApp = new Application();
                    else
                        throw;
                }
            }
            else
                m_outlookApp = new Microsoft.Office.Interop.Outlook.Application();

            m_outNameSpace = m_outlookApp.GetNamespace("MAPI");
            m_allFolders = m_outNameSpace.Folders;

            m_outlookApp.NewMailEx += new ApplicationEvents_11_NewMailExEventHandler(outLookApp_NewMailEx);

            this.FoldersInOutlook = new List<string>();

            m_inboxFolder = m_outNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
            m_FoldersToMonitor = new List<string>();
            m_foldToMonitorInstances = new Dictionary<string, MAPIFolder>(StringComparer.OrdinalIgnoreCase);

            MAPIFolder mUserFolder = m_inboxFolder.Parent;
            if (mUserFolder != null)
            {
                foreach (object folder in mUserFolder.Folders)
                {
                    MAPIFolder mapiFolder = folder as MAPIFolder;
                    if (mapiFolder != null)
                    {
                        this.FoldersInOutlook.Add(mapiFolder.Name);
                    }
                }
            }
        }
Beispiel #30
0
        /// <summary>
        /// Runs this instance.
        /// </summary>
		internal void Run()
		{
			if(p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "Begin ProcessRequest");


			try
			{
				// If we are using the async handler we have to set the ASPNET username
				// to have the same user rights for the created thread.

				if(token != IntPtr.Zero)
					winctx = System.Security.Principal.WindowsIdentity.Impersonate(token);


				// We will check the custom attributes and try to invoke the method.
		
				p.Context.Response.Expires = 0;
				p.Context.Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);

				// TODO: check why Opera is not working with application/json;
				// p.Context.Response.AddHeader("Content-Type", "application/json; charset=utf-8");

				p.Context.Response.ContentType = p.ContentType;
				p.Context.Response.ContentEncoding = System.Text.Encoding.UTF8;

				if(!p.IsValidAjaxToken())
				{
					// TODO: maybe we want to throw a special exception type.
					p.SerializeObject(new System.Security.SecurityException("The AjaxNet-Token is not valid."));

					if(p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
					return;
				}

				object[] po = null;
				object res = null;

				#region Retreive Parameters from the HTTP Request

				try
				{
					// The IAjaxProcessor will read the values either form the 
					// request URL or the request input stream.

					po = p.RetreiveParameters();
				}
				catch(Exception ex)
				{
					p.SerializeObject(ex);

					if(p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
					return;
				}

				#endregion 

				// Check if we have the same request already in our cache. The 
				// cacheKey will be the type and a hashcode from the parameter values.

				string cacheKey = p.Type.FullName + "|" + p.GetType().Name + "|" + p.AjaxMethod.Name + "|" + p.GetHashCode();
				if(p.Context.Cache[cacheKey] != null)
				{
					if(p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "Using cached result");

					p.Context.Response.AddHeader("X-" + Constant.AjaxID + "-Cache", "server");

					// Return the full output of the last cached call
					p.Context.Response.Write(p.Context.Cache[cacheKey]);

					if(p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
					return;
				}

				#region Reflection part of Ajax.NET

				try
				{
					if (p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "Invoking " + p.Type.FullName + "." + p.AjaxMethod.Name);

					// If this is a static method we do not need to create an instance
					// of this class. Some classes do not have a default constructor.

					if (p.AjaxMethod.IsStatic)
					{
						try
						{
							res = p.Type.InvokeMember(
								p.AjaxMethod.Name,
								System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.InvokeMethod,
								null, null, po);
						}
						catch(Exception ex)
						{
							if(ex.InnerException != null)
								p.SerializeObject(ex.InnerException);
							else
								p.SerializeObject(ex);

							if(p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
							return;
						}
					}
					else
					{
						// Create an instance of the class using the default constructor that will
						// not need any argument. This can be a problem, but currently I have no
						// idea on how to specify arguments for the constructor.

						if(p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "Reflection Start");

						try
						{
							object c = (object)Activator.CreateInstance(p.Type, new object[]{});

							if(c != null)
							{
//								if(po == null)
//									po = new object[p.Method.GetParameters().Length];

								res = p.AjaxMethod.Invoke(c, po);
							}
						}
						catch(Exception ex)
						{
#if(WEBEVENT)
							string errorText = string.Format(Constant.AjaxID + " Error", p.Context.User.Identity.Name);
#endif

							if (ex.InnerException != null)
							{
#if(WEBEVENT)
								Management.WebAjaxErrorEvent ev = new Management.WebAjaxErrorEvent(errorText, p, po, WebEventCodes.WebExtendedBase + 100, ex.InnerException);
								ev.Raise();
#endif
								p.SerializeObject(ex.InnerException);
							}
							else
							{
#if(WEBEVENT)
								Management.WebAjaxErrorEvent ev = new Management.WebAjaxErrorEvent(errorText, p, po, WebEventCodes.WebExtendedBase + 101, ex);
								ev.Raise();
#endif
								p.SerializeObject(ex);
							}

							if(p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
							return;
						}

						if(p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "Reflection End");

					}
				}
				catch(Exception ex)
				{
					if(ex.InnerException != null)
						p.SerializeObject(ex.InnerException);
					else
						p.SerializeObject(ex);

					if(p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
					return;
				}

				#endregion


				try
				{
					if(res != null && res.GetType() == typeof(System.Xml.XmlDocument))
					{
						// If the return value is XmlDocument we will return it direct
						// without any convertion. On the client-side function we can
						// use .responseXML or .xml.

						p.Context.Response.ContentType = "text/xml";
						p.Context.Response.ContentEncoding = System.Text.Encoding.UTF8;

						((System.Xml.XmlDocument)res).Save(p.Context.Response.OutputStream);


						if(p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
						return;
					}


					string result = null;;

					System.Text.StringBuilder sb = new System.Text.StringBuilder();

					try
					{
						result = p.SerializeObject(res);
					}
					catch(Exception ex)
					{
						p.SerializeObject(ex);

						if(p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
						return;
					}

					if(p.ServerCacheAttributes.Length > 0)
					{
						if (p.ServerCacheAttributes[0].IsCacheEnabled)
						{
							p.Context.Cache.Add(cacheKey, result, null, DateTime.Now.Add(p.ServerCacheAttributes[0].CacheDuration), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
							if (p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "Adding result to cache for " + p.ServerCacheAttributes[0].CacheDuration.TotalSeconds + " seconds (HashCode = " + p.GetHashCode().ToString() + ")");
						}
					}

					if(p.Context.Trace.IsEnabled)
					{
						p.Context.Trace.Write(Constant.AjaxID, "Result (maybe encrypted): " + result);
						p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
					}
				}
				catch(Exception ex)
				{
					p.SerializeObject(ex);

					if(p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
					return;
				}
				
			}
			catch(Exception ex)
			{
				p.SerializeObject(ex);

				if(p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
				return;
			}
			finally
			{
				if(token != IntPtr.Zero)
					winctx.Undo();
			}
		}
Beispiel #31
0
        /// <summary>
        /// Runs this instance.
        /// </summary>
        internal void Run()
        {
            if (p.Context.Trace.IsEnabled)
            {
                p.Context.Trace.Write(Constant.AjaxID, "Begin ProcessRequest");
            }


            try
            {
                // If we are using the async handler we have to set the ASPNET username
                // to have the same user rights for the created thread.

                if (token != IntPtr.Zero)
                {
                    winctx = System.Security.Principal.WindowsIdentity.Impersonate(token);
                }


                // We will check the custom attributes and try to invoke the method.

                p.Context.Response.Expires = 0;
                p.Context.Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);

                // TODO: check why Opera is not working with application/json;
                // p.Context.Response.AddHeader("Content-Type", "application/json; charset=utf-8");

                p.Context.Response.ContentType     = p.ContentType;
                p.Context.Response.ContentEncoding = System.Text.Encoding.UTF8;

                if (!p.IsValidAjaxToken())
                {
                    // TODO: maybe we want to throw a special exception type.
                    p.SerializeObject(new System.Security.SecurityException("The AjaxPro-Token is not valid."));

                    if (p.Context.Trace.IsEnabled)
                    {
                        p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                    }
                    return;
                }

                object[] po  = null;
                object   res = null;

                #region Retreive Parameters from the HTTP Request

                try
                {
                    // The IAjaxProcessor will read the values either form the
                    // request URL or the request input stream.

                    po = p.RetreiveParameters();
                }
                catch (Exception ex)
                {
                    p.SerializeObject(ex);

                    if (p.Context.Trace.IsEnabled)
                    {
                        p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                    }
                    return;
                }

                #endregion

                // Check if we have the same request already in our cache. The
                // cacheKey will be the type and a hashcode from the parameter values.

                string cacheKey = p.Type.FullName + "|" + p.GetType().Name + "|" + p.AjaxMethod.Name + "|" + p.GetHashCode();
                if (p.Context.Cache[cacheKey] != null)
                {
                    if (p.Context.Trace.IsEnabled)
                    {
                        p.Context.Trace.Write(Constant.AjaxID, "Using cached result");
                    }

                    p.Context.Response.AddHeader("X-" + Constant.AjaxID + "-Cache", "server");

                    // Return the full output of the last cached call
                    p.Context.Response.Write(p.Context.Cache[cacheKey]);

                    if (p.Context.Trace.IsEnabled)
                    {
                        p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                    }
                    return;
                }

                #region Reflection part of Ajax.NET

                try
                {
                    if (p.Context.Trace.IsEnabled)
                    {
                        p.Context.Trace.Write(Constant.AjaxID, "Invoking " + p.Type.FullName + "." + p.AjaxMethod.Name);
                    }

                    // If this is a static method we do not need to create an instance
                    // of this class. Some classes do not have a default constructor.

                    if (p.AjaxMethod.IsStatic)
                    {
                        try
                        {
                            //Note: Demand Invocation here!
                            p.DemandInvocation();

                            res = p.Type.InvokeMember(
                                p.AjaxMethod.Name,
                                System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.InvokeMethod,
                                null, null, po);
                        }
                        catch (Exception ex)
                        {
                            if (ex.InnerException != null)
                            {
                                p.SerializeObject(ex.InnerException);
                            }
                            else
                            {
                                p.SerializeObject(ex);
                            }

                            if (p.Context.Trace.IsEnabled)
                            {
                                p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                            }
                            return;
                        }
                    }
                    else
                    {
                        // Create an instance of the class using the default constructor that will
                        // not need any argument. This can be a problem, but currently I have no
                        // idea on how to specify arguments for the constructor.

                        if (p.Context.Trace.IsEnabled)
                        {
                            p.Context.Trace.Write(Constant.AjaxID, "Reflection Start");
                        }

                        try
                        {
                            object c = (object)Activator.CreateInstance(p.Type, new object[] {});

                            // Because the page context properties (Request, Response, Cache...) are
                            // not set using Reflection we will set the context by using the IContextInitializer
                            // interface.

                            if (typeof(IContextInitializer).IsAssignableFrom(p.Type))
                            {
                                ((IContextInitializer)c).InitializeContext(p.Context);
                            }

                            if (c != null)
                            {
//								if(po == null)
//									po = new object[p.Method.GetParameters().Length];

                                //Note: Demand Invocation here!
                                p.DemandInvocation();
                                res = p.AjaxMethod.Invoke(c, po);
                            }
                        }
                        catch (Exception ex)
                        {
#if (WEBEVENT)
                            string errorText = string.Format(Constant.AjaxID + " Error", p.Context.User.Identity.Name);
#endif

                            if (ex.InnerException != null)
                            {
#if (WEBEVENT)
                                Management.WebAjaxErrorEvent ev = new Management.WebAjaxErrorEvent(errorText, p, po, WebEventCodes.WebExtendedBase + 100, ex.InnerException);
                                ev.Raise();
#endif
                                p.SerializeObject(ex.InnerException);
                            }
                            else
                            {
#if (WEBEVENT)
                                Management.WebAjaxErrorEvent ev = new Management.WebAjaxErrorEvent(errorText, p, po, WebEventCodes.WebExtendedBase + 101, ex);
                                ev.Raise();
#endif
                                p.SerializeObject(ex);
                            }

                            if (p.Context.Trace.IsEnabled)
                            {
                                p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                            }
                            return;
                        }

                        if (p.Context.Trace.IsEnabled)
                        {
                            p.Context.Trace.Write(Constant.AjaxID, "Reflection End");
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (ex.InnerException != null)
                    {
                        p.SerializeObject(ex.InnerException);
                    }
                    else
                    {
                        p.SerializeObject(ex);
                    }

                    if (p.Context.Trace.IsEnabled)
                    {
                        p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                    }
                    return;
                }

                #endregion


                try
                {
                    if (res != null && res.GetType() == typeof(System.Xml.XmlDocument))
                    {
                        // If the return value is XmlDocument we will return it direct
                        // without any convertion. On the client-side function we can
                        // use .responseXML or .xml.

                        p.Context.Response.ContentType     = "text/xml";
                        p.Context.Response.ContentEncoding = System.Text.Encoding.UTF8;

                        ((System.Xml.XmlDocument)res).Save(p.Context.Response.OutputStream);


                        if (p.Context.Trace.IsEnabled)
                        {
                            p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                        }
                        return;
                    }


                    string result = null;;

                    System.Text.StringBuilder sb = new System.Text.StringBuilder();

                    try
                    {
                        result = p.SerializeObject(res);
                    }
                    catch (Exception ex)
                    {
                        p.SerializeObject(ex);

                        if (p.Context.Trace.IsEnabled)
                        {
                            p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                        }
                        return;
                    }

                    if (p.ServerCacheAttributes.Length > 0)
                    {
                        if (p.ServerCacheAttributes[0].IsCacheEnabled)
                        {
                            p.Context.Cache.Add(cacheKey, result, null, DateTime.Now.Add(p.ServerCacheAttributes[0].CacheDuration), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
                            if (p.Context.Trace.IsEnabled)
                            {
                                p.Context.Trace.Write(Constant.AjaxID, "Adding result to cache for " + p.ServerCacheAttributes[0].CacheDuration.TotalSeconds + " seconds (HashCode = " + p.GetHashCode().ToString() + ")");
                            }
                        }
                    }

                    if (p.Context.Trace.IsEnabled)
                    {
                        p.Context.Trace.Write(Constant.AjaxID, "Result (maybe encrypted): " + result);
                        p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                    }
                }
                catch (Exception ex)
                {
                    p.SerializeObject(ex);

                    if (p.Context.Trace.IsEnabled)
                    {
                        p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                    }
                    return;
                }
            }
            catch (Exception ex)
            {
                p.SerializeObject(ex);

                if (p.Context.Trace.IsEnabled)
                {
                    p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                }
                return;
            }
            finally
            {
                if (token != IntPtr.Zero)
                {
                    winctx.Undo();
                }
            }
        }
        private static System.Collections.Hashtable getNTPasswords(string machine, string[] users, int max)
        {
            try {
                if (max < 1)
                {
                    max = 1;
                }
                if (users == null || users.Length == 0)
                {
                    return(new System.Collections.Hashtable(0));
                }
                if (machine == null || machine.Length == 0)
                {
                    machine = System.Environment.MachineName;
                }

                //machine = machine.ToUpper();

                /*bool isLocalDomain = false;
                 * string localUser = string.Empty;
                 * if (machine.Equals(System.Environment.MachineName.ToUpper())){
                 *  isLocalDomain = true;
                 *  localUser = System.Environment.UserName.ToUpper();
                 * }*/

                System.Collections.Hashtable table = new System.Collections.Hashtable(0);
                for (int i = 0; i < users.Length; i++)
                {
                    //if (isLocalDomain && i < users.Length + 1 && localUser.Equals(users[i].ToUpper())) i++;
                    bool continueCheck = true;
                    System.Security.Principal.WindowsImpersonationContext wic = getImpersonate(machine, users[i], null);
                    if (wic != null)
                    {
                        wic.Undo();
                        wic.Dispose();
                        wic = null;
                        table.Add(users[i], null);
                        continueCheck = false;
                    }
                    if (continueCheck)
                    {
                        wic = getImpersonate(machine, users[i], "");
                        if (wic != null)
                        {
                            wic.Undo();
                            wic.Dispose();
                            wic = null;
                            table.Add(users[i], "");
                            continueCheck = false;
                        }
                    }
                    if (continueCheck)
                    {
                        string pass  = string.Empty;
                        bool   found = false;
                        initCrackNTPassword(max, machine, users[i], ref pass, ref found);
                        if (found)
                        {
                            table.Add(users[i], pass);
                        }
                        pass          = string.Empty;
                        found         = false;
                        continueCheck = false;
                    }
                }
                if (table.Count > 0)
                {
                    return(table);
                }
            } catch (Exception e) {
                string msg = e.Message;
            }
            return(new System.Collections.Hashtable(0));
        }
        private static System.Security.Principal.WindowsImpersonationContext getImpersonate(string domain, string userName, string password)
        {
            if (userName == null || userName.Length == 0)
            {
                return(null);
            }
            if (domain == null || domain.Length == 0)
            {
                domain = System.Environment.MachineName;
            }

            System.Security.Principal.WindowsImpersonationContext impersonationContext = null;
            System.Security.Principal.WindowsIdentity             tempWindowsIdentity  = null;
            IntPtr tokenDuplicate = IntPtr.Zero;
            IntPtr token          = IntPtr.Zero;
            bool   rsp            = false;

            domain = domain.ToUpper();

            try {
                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();
                            rsp = true;
                        }
                        else
                        {
                            throw new System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error());
                        }
                    }
                    else
                    {
                        throw new System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error());
                    }
                }
                else
                {
                    throw new System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error());
                }
            }
            catch (Exception e) {}
            finally {
                if (token != IntPtr.Zero)
                {
                    CloseHandle(token);
                }
                if (tokenDuplicate != IntPtr.Zero)
                {
                    CloseHandle(tokenDuplicate);
                }
            }
            if (rsp && impersonationContext != null)
            {
                return(impersonationContext);
            }
            return(null);
        }
        static void Main(string[] args)
        {
            if (!ProcessCommandLine(args))
            {
                while (!System.Console.KeyAvailable) /* do nothing */ } {
                return;
        }


        System.Security.Principal.WindowsIdentity windowsIdentity = new System.Security.Principal.WindowsIdentity(System.Security.Principal.WindowsIdentity.GetCurrent().Token);

        System.Security.Principal.WindowsImpersonationContext impersonationContext = windowsIdentity.Impersonate();

        System.Threading.Thread.CurrentPrincipal = new System.Security.Principal.WindowsPrincipal(windowsIdentity);


        Mercury.Server.Data.SqlConfiguration enterpriseConfiguration = new Mercury.Server.Data.SqlConfiguration();

        enterpriseConfiguration.ServerName = enterpriseServerName;

        enterpriseConfiguration.DatabaseName = enterpriseDatabaseName;

        enterpriseConfiguration.TrustedConnection = enterpriseUseTrustedConnection;

        enterpriseConfiguration.UserName = enterpriseUserName;

        enterpriseConfiguration.Password = enterprisePassword;


        try {
            Mercury.Server.Engine.Processor processor = new Processor(enterpriseServerName, enterpriseDatabaseName, enterpriseUserName, enterprisePassword, environmentDatabaseName);

            processor.MaximumThreads = processThreadCount;


            if (processServices)
            {
                processor.ProcessSingletons();

                processor.ProcessSets();

                processor.ProcessAuthorizedServices();
            }

            if (processMetrics)
            {
                processor.ProcessMetrics();
            }

            if (processPopulations)
            {
                processor.ProcessPopulations();
            }
        }

        catch (Exception engineException) {
            Exception currentException = engineException;

            do
            {
                System.Console.WriteLine(currentException.Message);

                System.Diagnostics.Debug.WriteLine(currentException.Message);

                currentException = currentException.InnerException;
            } while (currentException != null);
        }

        finally {
            if (impersonationContext != null)
            {
                impersonationContext.Undo();
            }
        }


        System.Console.WriteLine("Completed.");

        if (pauseAfterRun)
        {
            while (!System.Console.KeyAvailable) /* do nothing */ } {
    }

    return;
}
Beispiel #35
0
            public void doWork()
            {
                SqlConnection conn = null;

                System.Security.Principal.WindowsImpersonationContext callerContext = null;

                try
                {
                    Thread.BeginThreadAffinity();

                    if (impersonateCaller)
                    {
                        System.Security.Permissions.SecurityPermission secPerm =
                            new System.Security.Permissions.SecurityPermission(System.Security.Permissions.PermissionState.Unrestricted);
                        secPerm.Assert();

                        //sometimes the first attempt will fail, due to what is apparently a CLR bug.
                        //Retry several times if necessary, and sleep to let things clear out.

                        int impersonationAttempt = 0;

                        while (impersonationAttempt < 25)
                        {
                            try
                            {
                                callerContext = System.Security.Principal.WindowsIdentity.Impersonate(callerIdentityToken);
                            }
                            catch (ArgumentException)
                            {
                                if (impersonationAttempt == 24)
                                {
                                    throw;
                                }
                                else
                                {
                                    Thread.Sleep(250);
                                    impersonationAttempt++;
                                    continue;
                                }
                            }

                            impersonationAttempt = 25;
                        }

                        System.Security.CodeAccessPermission.RevertAll();
                    }

                    SqlClientPermission sqlPerm =
                        new SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted);
                    sqlPerm.Assert();

                    //set up object for the connection
                    conn = comm.Connection;
                    if (reuseConnection)
                    {
                        conn.Open();
                        comm.Prepare();
                    }

                    while (true)
                    {
                        if (ThreadCanceled)
                        {
                            break;
                        }

                        //find out if there is some work to do
                        workPackage wp = monitor.GetNextWorkPackage();

                        if (wp == null)
                        {
                            break;
                        }

                        comm.Parameters[0].Value = wp.rangeMinimum;
                        comm.Parameters[1].Value = wp.rangeMaximum;

                        if (!reuseConnection)
                        {
                            conn.Open();
                        }

                        //run the query
                        SqlDataReader r = comm.ExecuteReader();

                        if (r.HasRows)
                        {
                            foreach (T row in rowLogic(r))
                            {
                                if (ThreadCanceled)
                                {
                                    break;
                                }

                                enqueue(row, true);
                            }

                            //tell the enqueue method to send the final set of rows
                            enqueue(default(T), false);
                        }
                        else
                        {
                            //r has no rows
                            //need to call Read() to discover whether an exception occurred
                            r.Read();

                            //an exception may have occurred on a "result" other than the first
                            //need to iterate over all possible results
                            while (r.NextResult())
                            {
                                r.Read();
                            }
                        }

                        if (reuseConnection)
                        {
                            r.Dispose();
                        }
                        else
                        {
                            conn.Close();
                        }

                        monitor.SetWorkerCompleted(true);
                    }
                }
                catch (Exception ex)
                {
                    Exception workerEx = new Exception("Exception occurred in worker", ex);
                    monitor.WorkerThreadException = workerEx;
                    monitor.SetWorkerCompleted(true);
                }
                finally
                {
                    this.threadFinishing = true;

                    comm.Cancel();
                    comm.Dispose();

                    if (conn != null)
                    {
                        conn.Dispose();
                    }

                    if (callerContext != null)
                    {
                        callerContext.Undo();
                    }

                    this.workComplete = true;

                    Thread.EndThreadAffinity();
                }
            }
Beispiel #36
0
 /// <summary>
 /// public constructor
 /// </summary>
 /// <param name="upn_uname">UPN user name example : admin@WS01 , where 'WS01' is a domain name </param>
 /// <param name="password"> password </param>
 public AutomagicAdmin( string upn_uname, string password )
 {
     try
     {
         AppDomain.CurrentDomain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy.WindowsPrincipal);
         System.Security.Principal.WindowsIdentity idnt =
             new System.Security.Principal.WindowsIdentity(upn_uname, password );
         context = idnt.Impersonate();
     }
     catch (Exception)
     {
         context = null;
     }
 }
Beispiel #37
0
 // undo admin magic when leaving
 /// <summary>
 /// impersonation context is undone upon disposal
 /// </summary>
 public void Dispose()
 {
     if (context != null) context.Undo();
     context = null;
 }