internal void UndoImpersonationContext() { if (_impersonationContext != null) { _impersonationContext.Undo(); _impersonationContext = null; } }
internal void SetImpersonationContext() { if (_impersonationContext == null) { _impersonationContext = new ClientImpersonationContext(this); } }
private static void SetImpersonationContext(this Session session, ImpersonationContext context) { ArgumentValidator.EnsureArgumentNotNull(session, "session"); ArgumentValidator.EnsureArgumentNotNull(context, "context"); session.Extensions.Set(context); }
/// <summary> /// Impersonates the windows user identifed by the security token. /// </summary> private void LogonUser(OperationContext context, UserNameSecurityToken securityToken) { IntPtr handle = IntPtr.Zero; const int LOGON32_PROVIDER_DEFAULT = 0; // const int LOGON32_LOGON_INTERACTIVE = 2; const int LOGON32_LOGON_NETWORK = 3; // const int LOGON32_LOGON_BATCH = 4; bool result = NativeMethods.LogonUser( securityToken.UserName, String.Empty, securityToken.Password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, ref handle); if (!result) { throw ServiceResultException.Create(StatusCodes.BadUserAccessDenied, "Login failed for user: {0}", securityToken.UserName); } WindowsIdentity identity = new WindowsIdentity(handle); ImpersonationContext impersonationContext = new ImpersonationContext(); impersonationContext.Handle = handle; impersonationContext.Context = identity.Impersonate(); lock (this.m_lock) { m_contexts.Add(context.RequestId, impersonationContext); } }
internal void RestoreImpersonation() { if (this.ctx != null) { this.ctx.Undo(); this.ctx = null; } }
internal void RestoreImpersonation() { // Restore impersonation if (ctx != null) { ctx.Undo(); ctx = null; } }
/// <summary> /// Initializes a new instance of the <see cref="ImpersonationSqlFileStream" /> class. /// </summary> public ImpersonationSqlFileStream( ) { NetworkCredential databaseCredential; ///// // Determine if an impersonation context is required. ///// using (var context = DatabaseContext.GetContext( )) { databaseCredential = context.DatabaseInfo.Credentials; } if (databaseCredential != null) { WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent( ); bool impersonate = false; if (windowsIdentity != null) { var principal = new WindowsPrincipal(windowsIdentity); string account = (( WindowsIdentity )principal.Identity).Name; if (String.Compare(CredentialHelper.GetFullyQualifiedName(databaseCredential), account, StringComparison.OrdinalIgnoreCase) != 0) { impersonate = true; } } if (impersonate) { _impersonationContext = ImpersonationContext.GetContext(databaseCredential); if (string.IsNullOrEmpty(databaseCredential.Domain)) { windowsIdentity = WindowsIdentity.GetCurrent( ); if (windowsIdentity != null) { var principal = new WindowsPrincipal(windowsIdentity); string account = (( WindowsIdentity )principal.Identity).Name; var parts = account.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 2) { databaseCredential.Domain = parts[0]; } } } } } }
public static ImpersonationContext SetTargetSQLServerImpersonationContext() { ImpersonationContext ic = m_ImpersonationContext; m_ImpersonationContext = ImpersonationContext.TargetSQLServer; if (ic != ImpersonationContext.TargetSQLServer) { using (logX.loggerX.VerboseCall()) { if (ic == ImpersonationContext.TargetComputer) { if (m_targetImpersionationContext != null) { logX.loggerX.Verbose(string.Format("Leaving Target Computer Impersonation Context: {0}", WindowsIdentity.GetCurrent().Name)); m_targetImpersionationContext.Undo(); m_targetImpersionationContext.Dispose(); m_targetImpersionationContext = null; } else { if (TargetServer != null) { logX.loggerX.Verbose(string.Format("Leaving Target Computer Bind Context: {0}", m_targetUserName)); TargetServer.Unbind(); } } } else if (ic == ImpersonationContext.Local) { logX.loggerX.Verbose(string.Format("Leaving Local Impersonation Context: {0}", WindowsIdentity.GetCurrent().Name)); //if (m_LocalImpersionationContext != null) //{ // m_LocalImpersionationContext.Undo(); // m_LocalImpersionationContext.Dispose(); // m_LocalImpersionationContext = null; //} } if (m_targetSQLServerIdentity != null) { m_targetSQLServerImpersionationContext = m_targetSQLServerIdentity.Impersonate(); logX.loggerX.Verbose(string.Format("Entering Target SQL Server Impersonation Context: {0}", WindowsIdentity.GetCurrent().Name)); } else { if (m_UserSQLAuthentication) { logX.loggerX.Verbose("Using SQL Server Credentials"); } else { logX.loggerX.Verbose("Failed to Enter Target SQL Server Impersonation Context"); logX.loggerX.Verbose(string.Format("Using Local User Context for Target SQL Server: {0}", WindowsIdentity.GetCurrent().Name)); } } } } return(ic); }
public ImpersonationController( IRhetosComponent <IUserInfo> userInfo, IRhetosComponent <ImpersonationService> impersonationService, IRhetosComponent <ImpersonationContext> rhetosImpersonationContext) { this.userInfo = userInfo.Value; this.impersonationService = impersonationService.Value; this.impersonationContext = rhetosImpersonationContext.Value; }
/// <summary> /// Impersonates the specified session. /// </summary> /// <param name="session">The session.</param> /// <param name="principal">The principal.</param> /// <returns><see cref="ImpersonationContext"/> instance.</returns> public static ImpersonationContext Impersonate(this Session session, IPrincipal principal) { ArgumentValidator.EnsureArgumentNotNull(session, "session"); ArgumentValidator.EnsureArgumentNotNull(principal, "principal"); var currentContext = session.GetImpersonationContext(); var context = new ImpersonationContext(principal, currentContext); session.Extensions.Set(context); return(context); }
/// <summary> /// This method is called at the being of the thread that processes a request. /// </summary> protected override OperationContext ValidateRequest(RequestHeader requestHeader, RequestType requestType) { OperationContext context = base.ValidateRequest(requestHeader, requestType); if (requestType == RequestType.Write) { // reject all writes if no user provided. if (context.UserIdentity.TokenType == UserTokenType.Anonymous) { // construct translation object with default text. TranslationInfo info = new TranslationInfo( "NoWriteAllowed", "en-US", "Must provide a valid windows user before calling write."); // create an exception with a vendor defined sub-code. throw new ServiceResultException(new ServiceResult( StatusCodes.BadUserAccessDenied, "NoWriteAllowed", Namespaces.UserAuthentication, new LocalizedText(info))); } #if TODO SecurityToken securityToken = context.UserIdentity.GetSecurityToken(); // check for a kerberso token. KerberosReceiverSecurityToken kerberosToken = securityToken as KerberosReceiverSecurityToken; if (kerberosToken != null) { ImpersonationContext impersonationContext = new ImpersonationContext(); impersonationContext.Context = kerberosToken.WindowsIdentity.Impersonate(); lock (this.m_lock) { m_contexts.Add(context.RequestId, impersonationContext); } } // check for a user name token. UserNameSecurityToken userNameToken = securityToken as UserNameSecurityToken; if (userNameToken != null) { LogonUser(context, userNameToken); } #endif } return(context); }
private IDisposable ImpersonateInternal(bool applyToAllThreads) { if (string.IsNullOrEmpty(Domain) || string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password)) { throw new ArgumentException("Domain, Username, and Password properties must be set before invoking impersonation."); } try { IntPtr PreviousIdentityToken = ReadThreadToken(NativeMethods.GetCurrentThread()); try { if (!NativeMethods.RevertToSelf()) { throw new Win32Exception(Marshal.GetLastWin32Error()); } ImpersonationContext Context; WindowsIdentity?Identity = null; IntPtr IdentityToken = LogonUser(Domain, Username, Password, NetOnly); try { #pragma warning disable CA2000 // Dispose objects before losing scope Identity = new WindowsIdentity(IdentityToken); #pragma warning restore CA2000 // Dispose objects before losing scope Context = new ImpersonationContext(Identity, PreviousIdentityToken, applyToAllThreads); Identity = null; } finally { Identity?.Dispose(); NativeMethods.CloseHandle(IdentityToken); } return(Context); } catch { if (PreviousIdentityToken != IntPtr.Zero) { NativeMethods.CloseHandle(PreviousIdentityToken); } throw; } } catch (Exception ImpersonateException) { throw new InvalidOperationException($"Impersonation of user [{Domain}\\{Username}] failed.", ImpersonateException); } }
/// <summary> /// Initializes a new instance of the <see cref="DatabaseImpersonationContext" /> class. /// </summary> public DatabaseImpersonationContext( ) { NetworkCredential credential; using (var context = DatabaseContext.GetContext( )) { credential = context.DatabaseInfo.Credentials; } if (credential != null) { _impersonationContext = ImpersonationContext.GetContext(credential); } }
/// <summary> /// This method is called in a finally block at the end of request processing (i.e. called even on exception). /// </summary> protected override void OnRequestComplete(OperationContext context) { ImpersonationContext impersonationContext = null; lock (m_lock) { if (m_contexts.TryGetValue(context.RequestId, out impersonationContext)) { m_contexts.Remove(context.RequestId); } } base.OnRequestComplete(context); }
internal void Open(HttpContext context, bool revertImpersonate) { if (!this.opened) { if (revertImpersonate) { this.ctx = new ApplicationImpersonationContext(); } else { this.ctx = null; } this.opened = true; } }
public static ImpersonationContext SetLocalImpersonationContext() { ImpersonationContext ic = m_ImpersonationContext; m_ImpersonationContext = ImpersonationContext.Local; if (ic != ImpersonationContext.Local) { using (logX.loggerX.VerboseCall()) { if (ic == ImpersonationContext.TargetComputer) { if (m_targetImpersionationContext != null) { logX.loggerX.Verbose(string.Format("Leaving Target Computer Impersonation Context: {0}", WindowsIdentity.GetCurrent().Name)); m_targetImpersionationContext.Undo(); m_targetImpersionationContext.Dispose(); m_targetImpersionationContext = null; } else { logX.loggerX.Verbose(string.Format("Leaving Target Computer Bind Context: {0}", m_targetUserName)); if (TargetServer != null) { TargetServer.Unbind(); } } } else if (ic == ImpersonationContext.TargetSQLServer) { if (m_targetSQLServerImpersionationContext != null) { logX.loggerX.Verbose(string.Format("Leaving Target SQL Server Impersonation Context: {0}", WindowsIdentity.GetCurrent().Name)); m_targetSQLServerImpersionationContext.Undo(); m_targetSQLServerImpersionationContext.Dispose(); m_targetSQLServerImpersionationContext = null; } } //if (m_LocalIdentity != null) //{ // m_LocalImpersionationContext = m_LocalIdentity.Impersonate(); // logX.loggerX.Verbose(string.Format("Entering Local Impersonation Context: {0}", WindowsIdentity.GetCurrent().Name)); //} logX.loggerX.Verbose(string.Format("Entering Local Impersonation Context: {0}", WindowsIdentity.GetCurrent().Name)); } } return(ic); }
private void RestoreImpersonation() { this._rqChangeImpersonationRefCount--; if (this._rqChangeImpersonationRefCount == 0) { if (this._rqIctx != null) { this._rqIctx.Undo(); this._rqIctx = null; } if (this._rqTimerThreadImpersonationIctx != null) { this._rqTimerThreadImpersonationIctx.Undo(); this._rqTimerThreadImpersonationIctx = null; } } }
private void ChangeImpersonation(HttpContext context, bool timerThread) { this._rqChangeImpersonationRefCount++; if (!this._ignoreImpersonation && (((s_configMode != SessionStateMode.SQLServer) || !((SqlSessionStateStore)this._store).KnowForSureNotUsingIntegratedSecurity) || !this._usingAspnetSessionIdManager)) { if (s_useHostingIdentity) { if (this._rqIctx == null) { this._rqIctx = new ApplicationImpersonationContext(); } } else if (timerThread) { this._rqTimerThreadImpersonationIctx = new ClientImpersonationContext(context, false); } } }
internal static void UndoImpersonation(this Session session, ImpersonationContext innerContext, ImpersonationContext outerContext) { ArgumentValidator.EnsureArgumentNotNull(session, "session"); ArgumentValidator.EnsureArgumentNotNull(innerContext, "innerContext"); // outerContext can be null var currentContext = session.GetImpersonationContext(); if (currentContext != innerContext) { return; } session.ClearImpersonationContext(); if (outerContext != null) { session.SetImpersonationContext(outerContext); } }
internal void Open (HttpContext context, bool revertImpersonate) { if (opened) return; // Already opened // // Revert client impersonation if required // if (revertImpersonate) { ctx = new ApplicationImpersonationContext(); } else { ctx = null; } opened = true; // Open worked! }
internal void Open(HttpContext context, bool revertImpersonate) { if (opened) { return; // Already opened } // // Revert client impersonation if required // if (revertImpersonate) { ctx = new ApplicationImpersonationContext(); } else { ctx = null; } opened = true; // Open worked! }
/// <summary> /// This method is called in a finally block at the end of request processing (i.e. called even on exception). /// </summary> protected override void OnRequestComplete(OperationContext context) { ImpersonationContext impersonationContext = null; lock (this.m_lock) { if (m_contexts.TryGetValue(context.RequestId, out impersonationContext)) { m_contexts.Remove(context.RequestId); } } if (impersonationContext != null) { impersonationContext.Context.Undo(); impersonationContext.Dispose(); } base.OnRequestComplete(context); }
private void Dispose(bool xiDisposing) { lock (DisposedSyncRoot) { try { if (!Disposed) { if (xiDisposing) { if (ImpersonationContext != null) { ImpersonationContext.Undo(); ImpersonationContext.Dispose(); } } } } finally { Disposed = true; } } }
private void ResetPerRequestFields() { this._rqSessionState = null; this._rqId = null; this._rqSessionItems = null; this._rqStaticObjects = null; this._rqIsNewSession = false; this._rqSessionStateNotFound = true; this._rqReadonly = false; this._rqItem = null; this._rqContext = null; this._rqAr = null; this._rqLockId = null; this._rqInCallback = 0; this._rqLastPollCompleted = DateTime.MinValue; this._rqExecutionTimeout = TimeSpan.Zero; this._rqAddedCookie = false; this._rqIdNew = false; this._rqActionFlags = SessionStateActions.None; this._rqIctx = null; this._rqChangeImpersonationRefCount = 0; this._rqTimerThreadImpersonationIctx = null; this._rqSupportSessionIdReissue = false; }
protected virtual bool ValidateAccount(ref ImpersonationContext winImpCtx, ref Exception error) { try { lock (SyncRoot) { Log(LogLevel.DEBUG, "Check need impersonation"); if (string.IsNullOrEmpty(domain) || string.IsNullOrEmpty(user)) { Log(LogLevel.DEBUG, "Empty username, no need to impersonate"); return true; } winImpCtx = AccountValidator.ValidateAccount(domain, user, password, ref error); if (winImpCtx != null) { Log(LogLevel.DEBUG, "Impersonation successful"); return true; } throw error ?? new Exception("Impersonation failed with unknown reason: Location(" + location + "), Domain(" + domain + "), User(" + user + ")"); } } catch (Exception e) { error = e; Log(LogLevel.DEBUG, "Error while checking remote location access:" + e); } return false; }
protected virtual bool OnBeforeDestroyWinImpersonationContext(ref ImpersonationContext winImpCtx, ref Exception error) { return true; }
private IQueryable <Customer> GetCustomers(ImpersonationContext context, QueryEndpoint query) { return(query.All <Customer>() .Where(c => c.Branch == Branch)); }
private void timer1_Tick(object sender, System.Timers.ElapsedEventArgs e) { try { timer1.Enabled = false; //Process(@"o:\tmp\system2.txt"); L.Log(LogType.FILE, LogLevel.DEBUG, "EventLogFileAuditRecorder in timer1_Tick -->> Timer is Started"); var info = user == null ? null : user.Split('\\'); if (info != null && info.Length >= 2) { domain = string.IsNullOrEmpty(info[0]) ? null : info[0]; ip = info.Length == 2 ? remoteHost : (string.IsNullOrEmpty(info[1]) ? null : info[1]); domainUser = string.IsNullOrEmpty(info[info.Length - 1]) ? null : info[info.Length - 1]; if (!string.IsNullOrEmpty(domain) && !string.IsNullOrEmpty(domainUser)) { Exception error = null; var localWic = AccountValidator.ValidateAccount(domain, domainUser, password, ref error); if (localWic != null) { DisposeHelper.Close(wic); wic = null; wic = localWic; } else { L.Log(LogType.FILE, LogLevel.ERROR, " EventLogFileAuditRecorder In timer1_Tick() --> Impersonation Failed: " + user + ". Error:" + error); return; } } } if (location.EndsWith("/") || location.EndsWith("\\")) { L.Log(LogType.FILE, LogLevel.DEBUG, " EventLogFileAuditRecorder In timer1_Tick() --> Directory | " + location); L.Log(LogType.FILE, LogLevel.DEBUG, " EventLogFileAuditRecorder In timer1_Tick() --> lastFile: " + lastFile); ParseFileNameLocal(); } else { ReadLocal(location); } } catch (Exception exception) { L.Log(LogType.FILE, LogLevel.ERROR, "EventLogFileAuditRecorder in timer1_Tick -->> Error : " + exception.ToString()); } finally { timer1.Enabled = true; L.Log(LogType.FILE, LogLevel.INFORM, "EventLogFileAuditRecorder in timer1_Tick -->> Timer is finished."); } }
void ResetPerRequestFields() { Debug.Assert(_rqIctx == null, "_rqIctx == null"); Debug.Assert(_rqChangeImpersonationRefCount == 0, "_rqChangeImpersonationRefCount == 0"); _rqSessionState = null; _rqId = null; _rqSessionItems = null; _rqStaticObjects = null; _rqIsNewSession = false; _rqSessionStateNotFound = true; _rqReadonly = false; _rqItem = null; _rqContext = null; _rqAr = null; _rqLockId = null; _rqInCallback = 0; _rqLastPollCompleted = DateTime.MinValue; _rqExecutionTimeout = TimeSpan.Zero; _rqAddedCookie = false; _rqIdNew = false; _rqActionFlags = 0; _rqIctx = null; _rqChangeImpersonationRefCount = 0; _rqTimerThreadImpersonationIctx = null; _rqSupportSessionIdReissue = false; }
internal void SetImpersonationContext() { if (_impersonationContext == null) _impersonationContext = new ClientImpersonationContext(this); }
private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out ImpersonationContext.SafeTokenHandle phToken);
private static IQueryable <VipCustomer> GetVipCustomers(ImpersonationContext context, QueryEndpoint query) { return(query.All <VipCustomer>().Where(v => v.Reason != "Relative")); }
private static IQueryable <Customer> GetCustomers(ImpersonationContext context, QueryEndpoint query) { return(query.All <Customer>()); }
protected virtual void DestoryWinImpersonationContext(ref ImpersonationContext winImpCtx, ref Exception error) { if (winImpCtx != null) { if (OnBeforeDestroyWinImpersonationContext(ref winImpCtx, ref error)) { try { winImpCtx.Dispose(); } catch { } winImpCtx = null; OnAfterDestroyWinImpersonationContext(); } } }
private static IQueryable <Customer> GetCustomers(ImpersonationContext context, QueryEndpoint query) { return(query.All <Customer>() .Where(c => c.IsAutomobileIndustry)); }
void ChangeImpersonation(HttpContext context, bool timerThread) { #if !FEATURE_PAL // FEATURE_PAL doesn't enable impersonation _rqChangeImpersonationRefCount++; if (_ignoreImpersonation) { return; } // If SQL store isn't using integrated security, and we're using our own session id module, // we know we don't care about impersonation in our all session state store read/write // and session id read/write. if (s_configMode == SessionStateMode.SQLServer && ((SqlSessionStateStore)_store).KnowForSureNotUsingIntegratedSecurity && _usingAspnetSessionIdManager) { return; } // Please note that there are two types of calls coming in. One is from a request thread, // where timerThread==false; the other is from PollLockedSessionCallback, where // timerThread==true. if (s_useHostingIdentity) { // If we're told to use Application Identity, in each case we should impersonate, // if not called yet. if (_rqIctx == null) { _rqIctx = new ApplicationImpersonationContext(); } } else { if (timerThread) { // For the timer thread, we should explicity impersonate back to what the HttpContext was // orginally impersonating. _rqTimerThreadImpersonationIctx = new ClientImpersonationContext(context, false); } else { // For a request thread, if we're told to not use hosting id, there's no need // to do anything special. Debug.Assert(_rqIctx == null, "_rqIctx == null"); return; } } #endif // !FEATURE_PAL }
void RestoreImpersonation() { Debug.Assert(_rqChangeImpersonationRefCount != 0, "_rqChangeImpersonationRefCount != 0"); _rqChangeImpersonationRefCount--; if (_rqChangeImpersonationRefCount == 0) { Debug.Assert(!(_rqIctx != null && _rqTimerThreadImpersonationIctx != null), "Should not have mixed mode of impersonation"); if (_rqIctx != null) { _rqIctx.Undo(); _rqIctx = null; } if (_rqTimerThreadImpersonationIctx != null) { Debug.Assert(_rqContext != null, "_rqContext != null"); _rqTimerThreadImpersonationIctx.Undo(); _rqTimerThreadImpersonationIctx = null; } } }
/// <summary> /// Deploys the specified database. /// </summary> /// <param name="dacpacPath">The DacPac path.</param> /// <param name="serverName">Name of the server.</param> /// <param name="databaseName">Name of the database.</param> /// <param name="filePrefix">The file prefix.</param> /// <param name="dbUser">The database user.</param> /// <param name="dbPassword">The database password.</param> /// <param name="mdfDirectory">The MDF directory.</param> /// <param name="ldfDirectory">The LDF directory.</param> /// <param name="logger">The logger.</param> /// <exception cref="System.ArgumentNullException">dacpacPath</exception> /// <exception cref="System.IO.FileNotFoundException">Specified DacPac file does not exist</exception> /// <exception cref="System.IO.DirectoryNotFoundException"></exception> /// <remarks> /// Both the mdfPath and ldfPath values have to be set to invoke the DatabaseCreationLocationModifier. /// </remarks> public static void DeployDatabase(string dacpacPath, string serverName = "localhost", string databaseName = "SoftwarePlatform", string filePrefix = "SoftwarePlatform", string dbUser = null, string dbPassword = null, string mdfDirectory = null, string ldfDirectory = null, Action <string> logger = null) { if (string.IsNullOrEmpty(dacpacPath)) { throw new ArgumentNullException(nameof(dacpacPath)); } if (!File.Exists(dacpacPath)) { throw new FileNotFoundException("Specified DacPac file does not exist", dacpacPath); } if (string.IsNullOrEmpty(serverName)) { serverName = "localhost"; } if (string.IsNullOrEmpty(databaseName)) { databaseName = "SoftwarePlatform"; } if (string.IsNullOrEmpty(filePrefix)) { filePrefix = "SoftwarePlatform"; } bool databaseCreationLocationModifierActive = !string.IsNullOrEmpty(mdfDirectory) && !string.IsNullOrEmpty(ldfDirectory); var contributors = new List <string>( ); if (databaseCreationLocationModifierActive) { ///// //Contributor to set the MDF and LDF file locations. ///// contributors.Add("ReadiNowDeploymentPlanContributors.DatabaseCreationLocationModifier"); } var contributorArguments = new Dictionary <string, string>( ); if (databaseCreationLocationModifierActive) { ///// // Set the file paths. ///// string mdfFileName = string.Format("{0}_Dat.mdf", filePrefix); string ldfFileName = string.Format("{0}_Log.ldf", filePrefix); string mdfFilePath = Path.Combine(mdfDirectory, mdfFileName); string ldfFilePath = Path.Combine(ldfDirectory, ldfFileName); contributorArguments.Add("DatabaseCreationLocationModifier.MdfFilePath", mdfFilePath); contributorArguments.Add("DatabaseCreationLocationModifier.LdfFilePath", ldfFilePath); } var options = new DacDeployOptions { BlockOnPossibleDataLoss = false }; if (contributors.Count > 0) { ///// // Add any contributors. ///// options.AdditionalDeploymentContributors = string.Join(";", contributors); if (contributorArguments.Count > 0) { ///// // Add any contributor arguments. ///// options.AdditionalDeploymentContributorArguments = string.Join(";", contributorArguments.Select(arg => string.Format("{0}={1}", arg.Key, arg.Value))); } } bool impersonate = false; var credential = new NetworkCredential( ); if (!string.IsNullOrEmpty(dbUser)) { credential = CredentialHelper.ConvertToNetworkCredential(dbUser, dbPassword); ///// // Check if the context identity matches the current windows identity ///// WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent( ); if (windowsIdentity != null) { var principal = new WindowsPrincipal(windowsIdentity); string account = (( WindowsIdentity )principal.Identity).Name; if (String.Compare(CredentialHelper.GetFullyQualifiedName(credential), account, StringComparison.OrdinalIgnoreCase) != 0) { impersonate = true; } } } ImpersonationContext impersonationContext = null; try { using (DacPackage dacpac = DacPackage.Load(dacpacPath, DacSchemaModelStorageType.Memory)) { if (impersonate) { impersonationContext = ImpersonationContext.GetContext(credential); } string connectionString = "Data Source=" + serverName + ";Integrated Security=True"; var dacServices = new DacServices(connectionString); dacServices.Message += (sender, e) => LogDacpacMessage(e, logger); dacServices.Deploy(dacpac, databaseName, true, options); } } catch (DacServicesException exc) { DacMessage directoryNotFoundMessage = exc.Messages.FirstOrDefault(message => message.MessageType == DacMessageType.Error && message.Number == 72014); if (directoryNotFoundMessage != null) { var pathRegex = new Regex("Directory lookup for the file \"(.*)?\" failed"); Match match = pathRegex.Match(directoryNotFoundMessage.Message); if (match.Success) { string directory = Path.GetDirectoryName(match.Groups[1].Value); throw new DirectoryNotFoundException(string.Format("Directory '{0}' was not found. Please create it prior to deploying the database.", directory), exc); } } throw; } finally { if (impersonationContext != null) { impersonationContext.Dispose( ); } } }
public static void RestoreImpersonationContext(ImpersonationContext ic) { using (logX.loggerX.VerboseCall()) { // Reset old if different than new // ------------------------------- if (m_ImpersonationContext == ImpersonationContext.TargetComputer && ic != ImpersonationContext.TargetComputer) { if (m_targetImpersionationContext != null) { logX.loggerX.Verbose( string.Format("Leaving Target Computer Impersonation Context: {0}", WindowsIdentity.GetCurrent().Name)); m_targetImpersionationContext.Undo(); m_targetImpersionationContext.Dispose(); m_targetImpersionationContext = null; } else { if (TargetServer != null) { logX.loggerX.Verbose(string.Format("Leaving Target Computer Bind Context: {0}", m_targetUserName)); TargetServer.Unbind(); } } } else if (m_ImpersonationContext == ImpersonationContext.TargetSQLServer && ic != ImpersonationContext.TargetSQLServer) { if (m_targetSQLServerImpersionationContext != null) { logX.loggerX.Verbose( string.Format("Leaving Target SQL Server Impersonation Context: {0}", WindowsIdentity.GetCurrent().Name)); m_targetSQLServerImpersionationContext.Undo(); m_targetSQLServerImpersionationContext.Dispose(); m_targetSQLServerImpersionationContext = null; } } else if (m_ImpersonationContext == ImpersonationContext.Local && ic != ImpersonationContext.Local) { logX.loggerX.Verbose( string.Format("Leaving Local Impersonation Context: {0}", WindowsIdentity.GetCurrent().Name)); //if (m_LocalImpersionationContext != null) //{ // m_LocalImpersionationContext.Undo(); // m_LocalImpersionationContext.Dispose(); // m_LocalImpersionationContext = null; //} } // Set new if different than old // ----------------------------- if (ic == ImpersonationContext.TargetComputer && m_ImpersonationContext != ImpersonationContext.TargetComputer) { if (m_targetIdentity != null) { m_targetImpersionationContext = m_targetIdentity.Impersonate(); logX.loggerX.Verbose( string.Format("Entering Target Computer Impersonation Context: {0}", WindowsIdentity.GetCurrent().Name)); } else { if (TargetServer != null) { TargetServer.Bind(); logX.loggerX.Verbose(string.Format("Entering Target Computer Bind Context: {0}", m_targetUserName)); } } } else if (ic == ImpersonationContext.TargetSQLServer && m_ImpersonationContext != ImpersonationContext.TargetSQLServer) { if (m_targetSQLServerIdentity != null) { m_targetSQLServerImpersionationContext = m_targetSQLServerIdentity.Impersonate(); logX.loggerX.Verbose( string.Format("Entering Target SQL Server Impersonation Context: {0}", WindowsIdentity.GetCurrent().Name)); } else { if (m_UserSQLAuthentication) { logX.loggerX.Verbose("Using SQL Server Credentials"); } else { logX.loggerX.Verbose("Failed to Enter Target SQL Server Impersonation Context"); logX.loggerX.Verbose(string.Format("Using Local User Context for Target SQL Server: {0}", WindowsIdentity.GetCurrent().Name)); } } } else if (ic == ImpersonationContext.Local && m_ImpersonationContext != ImpersonationContext.Local) { logX.loggerX.Verbose( string.Format("Entering Local Impersonation Context: {0}", WindowsIdentity.GetCurrent().Name)); //if (m_LocalIdentity != null) //{ // m_LocalImpersionationContext = m_LocalIdentity.Impersonate(); // logX.loggerX.Verbose( // string.Format("Entering Local Impersonation Context: {0}", WindowsIdentity.GetCurrent().Name)); //} } m_ImpersonationContext = ic; } }
/// <summary> /// Adds the database user. /// </summary> /// <param name="username">The username.</param> /// <param name="role">The role.</param> /// <param name="server">The server.</param> /// <param name="catalog">The catalog.</param> /// <param name="dbUser">The database user.</param> /// <param name="dbPassword">The database password.</param> /// <exception cref="ArgumentNullException"></exception> public static void AddDatabaseUser(string username, string role, string server, string catalog, string dbUser, string dbPassword) { if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(server) || string.IsNullOrEmpty(catalog)) { throw new ArgumentNullException( ); } bool impersonate = false; var credential = new NetworkCredential( ); if (!string.IsNullOrEmpty(dbUser)) { credential = CredentialHelper.ConvertToNetworkCredential(dbUser, dbPassword); ///// // Check if the context identity matches the current windows identity ///// WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent( ); var principal = new WindowsPrincipal(windowsIdentity); string account = (( WindowsIdentity )principal.Identity).Name; if (String.Compare(CredentialHelper.GetFullyQualifiedName(credential), account, StringComparison.OrdinalIgnoreCase) != 0) { impersonate = true; } } ImpersonationContext impersonationContext = null; ///// // Format up the connection string ///// string connectionString = GetDatabaseConnectionString(server); try { if (impersonate) { impersonationContext = ImpersonationContext.GetContext(credential); } using (var platformDbConnection = new SqlConnection(connectionString)) { platformDbConnection.Open( ); using (SqlCommand sqlCommand = platformDbConnection.CreateCommand( )) { ///// // If specific user exists then delete it ///// sqlCommand.CommandText = string.Format(@"DECLARE @login NVARCHAR(MAX) = NULL; SELECT @login = name FROM sys.server_principals WHERE LOWER(name) = LOWER(N'{0}'); IF (@login IS NULL) CREATE LOGIN [{0}] FROM WINDOWS; GRANT VIEW SERVER STATE TO [{0}]", username); sqlCommand.ExecuteNonQuery( ); } platformDbConnection.Close( ); } ///// // Connect to the platform database and add in the new user to the database role. ///// connectionString = $@"Server=tcp:{server};Integrated security=SSPI;database={catalog}"; using (var platformDbConnection = new SqlConnection(connectionString)) { platformDbConnection.Open( ); using (SqlCommand sqlCommand = platformDbConnection.CreateCommand( )) { // If specific user exists then delete it sqlCommand.CommandText = string.Format(@"DECLARE @user NVARCHAR(MAX) = NULL; SELECT @user = name FROM sys.database_principals WHERE LOWER(name) = LOWER(N'{0}'); IF (@user IS NOT NULL) EXEC ('ALTER USER [' + @user + '] WITH LOGIN = [{0}]') ELSE CREATE USER [{0}] FOR LOGIN [{0}]", username); sqlCommand.ExecuteNonQuery( ); ///// // Assign the role for the user ///// sqlCommand.CommandText = string.Format(@"exec sp_addrolemember N'{1}', N'{0}'", username, role); sqlCommand.ExecuteNonQuery( ); } platformDbConnection.Close( ); } } finally { impersonationContext?.Dispose( ); } }