/// <summary> /// Set an authentication provider by method. /// </summary> /// <param name="authenticationMethod">Authentication method.</param> /// <param name="provider">Authentication provider.</param> /// <returns>True if succeeded, false otherwise, e.g., the existing provider disallows overriding.</returns> public bool SetProvider(SqlAuthenticationMethod authenticationMethod, SqlAuthenticationProvider provider) { if (!provider.IsSupported(authenticationMethod)) { throw SQL.UnsupportedAuthenticationByProvider(authenticationMethod.ToString(), provider.GetType().Name); } var methodName = "SetProvider"; if (_authenticationsWithAppSpecifiedProvider.Contains(authenticationMethod)) { _sqlAuthLogger.LogError(_typeName, methodName, $"Failed to add provider {GetProviderType(provider)} because a user-defined provider with type {GetProviderType(_providers[authenticationMethod])} already existed for authentication {authenticationMethod}."); return(false); } _providers.AddOrUpdate(authenticationMethod, provider, (key, oldProvider) => { if (oldProvider != null) { oldProvider.BeforeUnload(authenticationMethod); } if (provider != null) { provider.BeforeLoad(authenticationMethod); } _sqlAuthLogger.LogInfo(_typeName, methodName, $"Added auth provider {GetProviderType(provider)}, overriding existed provider {GetProviderType(oldProvider)} for authentication {authenticationMethod}."); return(provider); }); return(true); }
internal static string AuthenticationTypeToString(SqlAuthenticationMethod value) { Debug.Assert(IsValidAuthenticationTypeValue(value)); switch (value) { case SqlAuthenticationMethod.SqlPassword: return(SqlPasswordString); case SqlAuthenticationMethod.ActiveDirectoryPassword: return(ActiveDirectoryPasswordString); case SqlAuthenticationMethod.ActiveDirectoryIntegrated: return(ActiveDirectoryIntegratedString); case SqlAuthenticationMethod.ActiveDirectoryInteractive: return(ActiveDirectoryInteractiveString); case SqlAuthenticationMethod.ActiveDirectoryServicePrincipal: return(ActiveDirectoryServicePrincipalString); case SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow: return(ActiveDirectoryDeviceCodeFlowString); default: return(null); } }
internal static string AuthenticationTypeToString(SqlAuthenticationMethod value) { Debug.Assert(IsValidAuthenticationTypeValue(value)); switch (value) { case SqlAuthenticationMethod.SqlPassword: return(SqlPasswordString); case SqlAuthenticationMethod.ActiveDirectoryPassword: return(ActiveDirectoryPasswordString); case SqlAuthenticationMethod.ActiveDirectoryIntegrated: return(ActiveDirectoryIntegratedString); case SqlAuthenticationMethod.ActiveDirectoryInteractive: return(ActiveDirectoryInteractiveString); #if ADONET_CERT_AUTH case SqlAuthenticationMethod.SqlCertificate: return(SqlCertificateString); #endif default: return(null); } }
internal static bool TryConvertToAuthenticationType(string value, out SqlAuthenticationMethod result) { Debug.Assert(Enum.GetNames(typeof(SqlAuthenticationMethod)).Length == 9, "SqlAuthenticationMethod enum has changed, update needed"); bool isSuccess = false; if (StringComparer.InvariantCultureIgnoreCase.Equals(value, SqlPasswordString) || StringComparer.InvariantCultureIgnoreCase.Equals(value, Convert.ToString(SqlAuthenticationMethod.SqlPassword, CultureInfo.InvariantCulture))) { result = SqlAuthenticationMethod.SqlPassword; isSuccess = true; } else if (StringComparer.InvariantCultureIgnoreCase.Equals(value, ActiveDirectoryPasswordString) || StringComparer.InvariantCultureIgnoreCase.Equals(value, Convert.ToString(SqlAuthenticationMethod.ActiveDirectoryPassword, CultureInfo.InvariantCulture))) { result = SqlAuthenticationMethod.ActiveDirectoryPassword; isSuccess = true; } else if (StringComparer.InvariantCultureIgnoreCase.Equals(value, ActiveDirectoryIntegratedString) || StringComparer.InvariantCultureIgnoreCase.Equals(value, Convert.ToString(SqlAuthenticationMethod.ActiveDirectoryIntegrated, CultureInfo.InvariantCulture))) { result = SqlAuthenticationMethod.ActiveDirectoryIntegrated; isSuccess = true; } else if (StringComparer.InvariantCultureIgnoreCase.Equals(value, ActiveDirectoryInteractiveString) || StringComparer.InvariantCultureIgnoreCase.Equals(value, Convert.ToString(SqlAuthenticationMethod.ActiveDirectoryInteractive, CultureInfo.InvariantCulture))) { result = SqlAuthenticationMethod.ActiveDirectoryInteractive; isSuccess = true; } else if (StringComparer.InvariantCultureIgnoreCase.Equals(value, ActiveDirectoryServicePrincipalString) || StringComparer.InvariantCultureIgnoreCase.Equals(value, Convert.ToString(SqlAuthenticationMethod.ActiveDirectoryServicePrincipal, CultureInfo.InvariantCulture))) { result = SqlAuthenticationMethod.ActiveDirectoryServicePrincipal; isSuccess = true; } else if (StringComparer.InvariantCultureIgnoreCase.Equals(value, ActiveDirectoryDeviceCodeFlowString) || StringComparer.InvariantCultureIgnoreCase.Equals(value, Convert.ToString(SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow, CultureInfo.InvariantCulture))) { result = SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow; isSuccess = true; } else if (StringComparer.InvariantCultureIgnoreCase.Equals(value, ActiveDirectoryManagedIdentityString) || StringComparer.InvariantCultureIgnoreCase.Equals(value, Convert.ToString(SqlAuthenticationMethod.ActiveDirectoryManagedIdentity, CultureInfo.InvariantCulture))) { result = SqlAuthenticationMethod.ActiveDirectoryManagedIdentity; isSuccess = true; } else if (StringComparer.InvariantCultureIgnoreCase.Equals(value, ActiveDirectoryMSIString) || StringComparer.InvariantCultureIgnoreCase.Equals(value, Convert.ToString(SqlAuthenticationMethod.ActiveDirectoryMSI, CultureInfo.InvariantCulture))) { result = SqlAuthenticationMethod.ActiveDirectoryMSI; isSuccess = true; } else { result = DbConnectionStringDefaults.Authentication; } return(isSuccess); }
/// <summary> /// Checks support for authentication type in lower case. /// Interactive authentication added. /// </summary> public override bool IsSupported(SqlAuthenticationMethod authentication) { return(authentication == SqlAuthenticationMethod.ActiveDirectoryIntegrated || authentication == SqlAuthenticationMethod.ActiveDirectoryPassword || authentication == SqlAuthenticationMethod.ActiveDirectoryInteractive || authentication == SqlAuthenticationMethod.ActiveDirectoryServicePrincipal); }
internal static bool TryConvertToAuthenticationType(string value, out SqlAuthenticationMethod result) { Debug.Assert(Enum.GetNames(typeof(SqlAuthenticationMethod)).Length == 4, "SqlAuthenticationMethod enum has changed, update needed"); bool isSuccess = false; if (StringComparer.InvariantCultureIgnoreCase.Equals(value, SqlPasswordString)) { result = SqlAuthenticationMethod.SqlPassword; isSuccess = true; } else if (StringComparer.InvariantCultureIgnoreCase.Equals(value, ActiveDirectoryPasswordString)) { result = SqlAuthenticationMethod.ActiveDirectoryPassword; isSuccess = true; } else if (StringComparer.InvariantCultureIgnoreCase.Equals(value, ActiveDirectoryIntegratedString)) { result = SqlAuthenticationMethod.ActiveDirectoryIntegrated; isSuccess = true; } else { result = DbConnectionStringDefaults.Authentication; } return(isSuccess); }
internal static void CreateConnectionString(string dataSource, SqlAuthenticationMethod method, string login, string password) { _connectionStr = new SqlConnectionStringBuilder(); _connectionStr.Authentication = method; _connectionStr.UserID = login; _connectionStr.Password = password; _connectionStr.DataSource = dataSource; }
internal Builder(SqlAuthenticationMethod authenticationMethod, string resource, string authority, string serverName, string databaseName) { _authenticationMethod = authenticationMethod; _serverName = serverName; _databaseName = databaseName; _scopes = new string[] { resource + "/.default" }; _authority = authority; }
internal Builder(SqlAuthenticationMethod authenticationMethod, string resource, string authority, string serverName, string databaseName) { _authenticationMethod = authenticationMethod; _serverName = serverName; _databaseName = databaseName; _resource = resource; _authority = authority; }
internal static bool IsValidAuthenticationTypeValue(SqlAuthenticationMethod value) { Debug.Assert(Enum.GetNames(typeof(SqlAuthenticationMethod)).Length == 4, "SqlAuthenticationMethod enum has changed, update needed"); return(value == SqlAuthenticationMethod.SqlPassword || value == SqlAuthenticationMethod.ActiveDirectoryPassword || value == SqlAuthenticationMethod.ActiveDirectoryIntegrated || value == SqlAuthenticationMethod.NotSpecified); }
public void SetInvalidAuthentication_Throws() { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(); SqlAuthenticationMethod invalid = (SqlAuthenticationMethod)Enum.GetValues(typeof(SqlAuthenticationMethod)).Length + 1; ArgumentOutOfRangeException ex = Assert.Throws <ArgumentOutOfRangeException>(() => builder.Authentication = invalid); Assert.Contains("SqlAuthenticationMethod", ex.Message, StringComparison.OrdinalIgnoreCase); }
/// <summary> /// Constructor. /// </summary> public SqlAuthenticationProviderManager(SqlAuthenticationProviderConfigurationSection configSection) { _typeName = GetType().Name; _providers = new ConcurrentDictionary <SqlAuthenticationMethod, SqlAuthenticationProvider>(); var authenticationsWithAppSpecifiedProvider = new HashSet <SqlAuthenticationMethod>(); _authenticationsWithAppSpecifiedProvider = authenticationsWithAppSpecifiedProvider; if (configSection == null) { return; } // Create user-defined auth initializer, if any. // if (!string.IsNullOrEmpty(configSection.InitializerType)) { try { var initializerType = Type.GetType(configSection.InitializerType, true); _initializer = (SqlAuthenticationInitializer)Activator.CreateInstance(initializerType); _initializer.Initialize(); } catch (Exception e) { throw SQL.CannotCreateSqlAuthInitializer(configSection.InitializerType, e); } } // add user-defined providers, if any. // if (configSection.Providers != null && configSection.Providers.Count > 0) { foreach (ProviderSettings providerSettings in configSection.Providers) { SqlAuthenticationMethod authentication = AuthenticationEnumFromString(providerSettings.Name); SqlAuthenticationProvider provider; try { var providerType = Type.GetType(providerSettings.Type, true); provider = (SqlAuthenticationProvider)Activator.CreateInstance(providerType); } catch (Exception e) { throw SQL.CannotCreateAuthProvider(authentication.ToString(), providerSettings.Type, e); } if (!provider.IsSupported(authentication)) { throw SQL.UnsupportedAuthenticationByProvider(authentication.ToString(), providerSettings.Type); } _providers[authentication] = provider; authenticationsWithAppSpecifiedProvider.Add(authentication); } } }
// This c-tor is used to create SSE and user instance connection strings when user instance is set to true // BUG (VSTFDevDiv) 479687: Using TransactionScope with Linq2SQL against user instances fails with "connection has been broken" message internal SqlConnectionString(SqlConnectionString connectionOptions, string dataSource, bool userInstance, bool?setEnlistValue) : base(connectionOptions) { _integratedSecurity = connectionOptions._integratedSecurity; _connectionReset = connectionOptions._connectionReset; _contextConnection = connectionOptions._contextConnection; _encrypt = connectionOptions._encrypt; if (setEnlistValue.HasValue) { _enlist = setEnlistValue.Value; } else { _enlist = connectionOptions._enlist; } _mars = connectionOptions._mars; _persistSecurityInfo = connectionOptions._persistSecurityInfo; _pooling = connectionOptions._pooling; _replication = connectionOptions._replication; _userInstance = userInstance; _connectTimeout = connectionOptions._connectTimeout; _loadBalanceTimeout = connectionOptions._loadBalanceTimeout; _poolBlockingPeriod = connectionOptions._poolBlockingPeriod; _maxPoolSize = connectionOptions._maxPoolSize; _minPoolSize = connectionOptions._minPoolSize; _multiSubnetFailover = connectionOptions._multiSubnetFailover; _transparentNetworkIPResolution = connectionOptions._transparentNetworkIPResolution; _packetSize = connectionOptions._packetSize; _applicationName = connectionOptions._applicationName; _attachDBFileName = connectionOptions._attachDBFileName; _currentLanguage = connectionOptions._currentLanguage; _dataSource = dataSource; _localDBInstance = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource); _failoverPartner = connectionOptions._failoverPartner; _initialCatalog = connectionOptions._initialCatalog; _password = connectionOptions._password; _userID = connectionOptions._userID; _networkLibrary = connectionOptions._networkLibrary; _workstationId = connectionOptions._workstationId; _expandedAttachDBFilename = connectionOptions._expandedAttachDBFilename; _typeSystemVersion = connectionOptions._typeSystemVersion; _typeSystemAssemblyVersion = connectionOptions._typeSystemAssemblyVersion; _transactionBinding = connectionOptions._transactionBinding; _applicationIntent = connectionOptions._applicationIntent; _connectRetryCount = connectionOptions._connectRetryCount; _connectRetryInterval = connectionOptions._connectRetryInterval; _authType = connectionOptions._authType; _columnEncryptionSetting = connectionOptions._columnEncryptionSetting; _enclaveAttestationUrl = connectionOptions._enclaveAttestationUrl; #if ADONET_CERT_AUTH _certificate = connectionOptions._certificate; #endif ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source); }
/// <include file='../../../../../../doc/snippets/Microsoft.Data.SqlClient/ActiveDirectoryAuthenticationProvider.xml' path='docs/members[@name="ActiveDirectoryAuthenticationProvider"]/IsSupported/*'/> public override bool IsSupported(SqlAuthenticationMethod authentication) { return(authentication == SqlAuthenticationMethod.ActiveDirectoryIntegrated || authentication == SqlAuthenticationMethod.ActiveDirectoryPassword || authentication == SqlAuthenticationMethod.ActiveDirectoryInteractive || authentication == SqlAuthenticationMethod.ActiveDirectoryServicePrincipal || authentication == SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow || authentication == SqlAuthenticationMethod.ActiveDirectoryManagedIdentity || authentication == SqlAuthenticationMethod.ActiveDirectoryMSI || authentication == SqlAuthenticationMethod.ActiveDirectoryDefault); }
internal static bool IsValidAuthenticationTypeValue(SqlAuthenticationMethod value) { Debug.Assert(Enum.GetNames(typeof(SqlAuthenticationMethod)).Length == 9, "SqlAuthenticationMethod enum has changed, update needed"); return(value == SqlAuthenticationMethod.SqlPassword || value == SqlAuthenticationMethod.ActiveDirectoryPassword || value == SqlAuthenticationMethod.ActiveDirectoryIntegrated || value == SqlAuthenticationMethod.ActiveDirectoryInteractive || value == SqlAuthenticationMethod.ActiveDirectoryServicePrincipal || value == SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow || value == SqlAuthenticationMethod.ActiveDirectoryManagedIdentity || value == SqlAuthenticationMethod.ActiveDirectoryMSI || value == SqlAuthenticationMethod.NotSpecified); }
internal static string AuthenticationTypeToString(SqlAuthenticationMethod value) { Debug.Assert(IsValidAuthenticationTypeValue(value)); switch (value) { case SqlAuthenticationMethod.SqlPassword: return(SqlPasswordString); case SqlAuthenticationMethod.ActiveDirectoryPassword: return(ActiveDirectoryPasswordString); default: return(null); } }
protected SqlAuthenticationParameters( SqlAuthenticationMethod authenticationMethod, string serverName, string databaseName, string[] scopes, string authority, string userId, string password, Guid connectionId) { AuthenticationMethod = authenticationMethod; ServerName = serverName; DatabaseName = databaseName; Scopes = scopes; Authority = authority; UserId = userId; Password = password; ConnectionId = connectionId; }
/// <include file='../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlAuthenticationParameters.xml' path='docs/members[@name="SqlAuthenticationParameters"]/ctor/*'/> protected SqlAuthenticationParameters( SqlAuthenticationMethod authenticationMethod, string serverName, string databaseName, string resource, string authority, string userId, string password, Guid connectionId, int connectionTimeout) { AuthenticationMethod = authenticationMethod; ServerName = serverName; DatabaseName = databaseName; Resource = resource; Authority = authority; UserId = userId; Password = password; ConnectionId = connectionId; ConnectionTimeout = connectionTimeout; }
/// <summary> /// Set an authentication provider by method. /// </summary> /// <param name="authenticationMethod">Authentication method.</param> /// <param name="provider">Authentication provider.</param> /// <returns>True if succeeded, false otherwise, e.g., the existing provider disallows overriding.</returns> public bool SetProvider(SqlAuthenticationMethod authenticationMethod, SqlAuthenticationProvider provider) { if (!provider.IsSupported(authenticationMethod)) { throw SQL.UnsupportedAuthenticationByProvider(authenticationMethod.ToString(), provider.GetType().Name); } if (_authenticationsWithAppSpecifiedProvider.Contains(authenticationMethod)) { } _providers.AddOrUpdate(authenticationMethod, provider, (key, oldProvider) => { if (oldProvider != null) { oldProvider.BeforeUnload(authenticationMethod); } if (provider != null) { provider.BeforeLoad(authenticationMethod); } return(provider); }); return(true); }
/// <summary> /// Constructor. /// </summary> public SqlAuthenticationProviderManager(SqlAuthenticationProviderConfigurationSection configSection = null) { var methodName = "Ctor"; _typeName = GetType().Name; _providers = new ConcurrentDictionary <SqlAuthenticationMethod, SqlAuthenticationProvider>(); var authenticationsWithAppSpecifiedProvider = new HashSet <SqlAuthenticationMethod>(); _authenticationsWithAppSpecifiedProvider = authenticationsWithAppSpecifiedProvider; if (configSection == null) { _sqlAuthLogger.LogInfo(_typeName, methodName, "Neither SqlClientAuthenticationProviders nor SqlAuthenticationProviders configuration section found."); return; } if (!string.IsNullOrEmpty(configSection.ApplicationClientId)) { _applicationClientId = configSection.ApplicationClientId; _sqlAuthLogger.LogInfo(_typeName, methodName, "Received user-defined Application Client Id"); } else { _sqlAuthLogger.LogInfo(_typeName, methodName, "No user-defined Application Client Id found."); } // Create user-defined auth initializer, if any. if (!string.IsNullOrEmpty(configSection.InitializerType)) { try { var initializerType = Type.GetType(configSection.InitializerType, true); _initializer = (SqlAuthenticationInitializer)Activator.CreateInstance(initializerType); _initializer.Initialize(); } catch (Exception e) { throw SQL.CannotCreateSqlAuthInitializer(configSection.InitializerType, e); } _sqlAuthLogger.LogInfo(_typeName, methodName, "Created user-defined SqlAuthenticationInitializer."); } else { _sqlAuthLogger.LogInfo(_typeName, methodName, "No user-defined SqlAuthenticationInitializer found."); } // add user-defined providers, if any. if (configSection.Providers != null && configSection.Providers.Count > 0) { foreach (ProviderSettings providerSettings in configSection.Providers) { SqlAuthenticationMethod authentication = AuthenticationEnumFromString(providerSettings.Name); SqlAuthenticationProvider provider; try { var providerType = Type.GetType(providerSettings.Type, true); provider = (SqlAuthenticationProvider)Activator.CreateInstance(providerType); } catch (Exception e) { throw SQL.CannotCreateAuthProvider(authentication.ToString(), providerSettings.Type, e); } if (!provider.IsSupported(authentication)) { throw SQL.UnsupportedAuthenticationByProvider(authentication.ToString(), providerSettings.Type); } _providers[authentication] = provider; authenticationsWithAppSpecifiedProvider.Add(authentication); _sqlAuthLogger.LogInfo(_typeName, methodName, string.Format("Added user-defined auth provider: {0} for authentication {1}.", providerSettings?.Type, authentication)); } } else { _sqlAuthLogger.LogInfo(_typeName, methodName, "No user-defined auth providers."); } }
public override bool IsSupported(SqlAuthenticationMethod authenticationMethod) { return(authenticationMethod == SqlAuthenticationMethod.ActiveDirectoryInteractive); }
private readonly string _expandedAttachDBFilename; // expanded during construction so that CreatePermissionSet & Expand are consistent internal SqlConnectionString(string connectionString) : base(connectionString, GetParseSynonyms()) { ThrowUnsupportedIfKeywordSet(KEY.AsynchronousProcessing); ThrowUnsupportedIfKeywordSet(KEY.Connection_Reset); ThrowUnsupportedIfKeywordSet(KEY.Context_Connection); // Network Library has its own special error message if (ContainsKey(KEY.Network_Library)) { throw SQL.NetworkLibraryKeywordNotSupported(); } _integratedSecurity = ConvertValueToIntegratedSecurity(); #if netcoreapp _poolBlockingPeriod = ConvertValueToPoolBlockingPeriod(); #endif _encrypt = ConvertValueToBoolean(KEY.Encrypt, DEFAULT.Encrypt); _enlist = ConvertValueToBoolean(KEY.Enlist, DEFAULT.Enlist); _mars = ConvertValueToBoolean(KEY.MARS, DEFAULT.MARS); _persistSecurityInfo = ConvertValueToBoolean(KEY.Persist_Security_Info, DEFAULT.Persist_Security_Info); _pooling = ConvertValueToBoolean(KEY.Pooling, DEFAULT.Pooling); _replication = ConvertValueToBoolean(KEY.Replication, DEFAULT.Replication); _userInstance = ConvertValueToBoolean(KEY.User_Instance, DEFAULT.User_Instance); _multiSubnetFailover = ConvertValueToBoolean(KEY.MultiSubnetFailover, DEFAULT.MultiSubnetFailover); _connectTimeout = ConvertValueToInt32(KEY.Connect_Timeout, DEFAULT.Connect_Timeout); _loadBalanceTimeout = ConvertValueToInt32(KEY.Load_Balance_Timeout, DEFAULT.Load_Balance_Timeout); _maxPoolSize = ConvertValueToInt32(KEY.Max_Pool_Size, DEFAULT.Max_Pool_Size); _minPoolSize = ConvertValueToInt32(KEY.Min_Pool_Size, DEFAULT.Min_Pool_Size); _packetSize = ConvertValueToInt32(KEY.Packet_Size, DEFAULT.Packet_Size); _connectRetryCount = ConvertValueToInt32(KEY.Connect_Retry_Count, DEFAULT.Connect_Retry_Count); _connectRetryInterval = ConvertValueToInt32(KEY.Connect_Retry_Interval, DEFAULT.Connect_Retry_Interval); _applicationIntent = ConvertValueToApplicationIntent(); _applicationName = ConvertValueToString(KEY.Application_Name, DEFAULT.Application_Name); _attachDBFileName = ConvertValueToString(KEY.AttachDBFilename, DEFAULT.AttachDBFilename); _currentLanguage = ConvertValueToString(KEY.Current_Language, DEFAULT.Current_Language); _dataSource = ConvertValueToString(KEY.Data_Source, DEFAULT.Data_Source); _localDBInstance = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource); _failoverPartner = ConvertValueToString(KEY.FailoverPartner, DEFAULT.FailoverPartner); _initialCatalog = ConvertValueToString(KEY.Initial_Catalog, DEFAULT.Initial_Catalog); _password = ConvertValueToString(KEY.Password, DEFAULT.Password); _trustServerCertificate = ConvertValueToBoolean(KEY.TrustServerCertificate, DEFAULT.TrustServerCertificate); _authType = ConvertValueToAuthenticationType(); _columnEncryptionSetting = ConvertValueToColumnEncryptionSetting(); _enclaveAttestationUrl = ConvertValueToString(KEY.EnclaveAttestationUrl, DEFAULT.EnclaveAttestationUrl); _attestationProtocol = ConvertValueToAttestationProtocol(); // Temporary string - this value is stored internally as an enum. string typeSystemVersionString = ConvertValueToString(KEY.Type_System_Version, null); string transactionBindingString = ConvertValueToString(KEY.TransactionBinding, null); _userID = ConvertValueToString(KEY.User_ID, DEFAULT.User_ID); _workstationId = ConvertValueToString(KEY.Workstation_Id, null); if (_loadBalanceTimeout < 0) { throw ADP.InvalidConnectionOptionValue(KEY.Load_Balance_Timeout); } if (_connectTimeout < 0) { throw ADP.InvalidConnectionOptionValue(KEY.Connect_Timeout); } if (_maxPoolSize < 1) { throw ADP.InvalidConnectionOptionValue(KEY.Max_Pool_Size); } if (_minPoolSize < 0) { throw ADP.InvalidConnectionOptionValue(KEY.Min_Pool_Size); } if (_maxPoolSize < _minPoolSize) { throw ADP.InvalidMinMaxPoolSizeValues(); } if ((_packetSize < TdsEnums.MIN_PACKET_SIZE) || (TdsEnums.MAX_PACKET_SIZE < _packetSize)) { throw SQL.InvalidPacketSizeValue(); } ValidateValueLength(_applicationName, TdsEnums.MAXLEN_APPNAME, KEY.Application_Name); ValidateValueLength(_currentLanguage, TdsEnums.MAXLEN_LANGUAGE, KEY.Current_Language); ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source); ValidateValueLength(_failoverPartner, TdsEnums.MAXLEN_SERVERNAME, KEY.FailoverPartner); ValidateValueLength(_initialCatalog, TdsEnums.MAXLEN_DATABASE, KEY.Initial_Catalog); ValidateValueLength(_password, TdsEnums.MAXLEN_CLIENTSECRET, KEY.Password); ValidateValueLength(_userID, TdsEnums.MAXLEN_CLIENTID, KEY.User_ID); if (null != _workstationId) { ValidateValueLength(_workstationId, TdsEnums.MAXLEN_HOSTNAME, KEY.Workstation_Id); } if (!string.Equals(DEFAULT.FailoverPartner, _failoverPartner, StringComparison.OrdinalIgnoreCase)) { // fail-over partner is set if (_multiSubnetFailover) { throw SQL.MultiSubnetFailoverWithFailoverPartner(serverProvidedFailoverPartner: false, internalConnection: null); } if (string.Equals(DEFAULT.Initial_Catalog, _initialCatalog, StringComparison.OrdinalIgnoreCase)) { throw ADP.MissingConnectionOptionValue(KEY.FailoverPartner, KEY.Initial_Catalog); } } // expand during construction so that CreatePermissionSet and Expand are consistent _expandedAttachDBFilename = ExpandDataDirectory(KEY.AttachDBFilename, _attachDBFileName); if (null != _expandedAttachDBFilename) { if (0 <= _expandedAttachDBFilename.IndexOf('|')) { throw ADP.InvalidConnectionOptionValue(KEY.AttachDBFilename); } ValidateValueLength(_expandedAttachDBFilename, TdsEnums.MAXLEN_ATTACHDBFILE, KEY.AttachDBFilename); if (_localDBInstance == null) { // fail fast to verify LocalHost when using |DataDirectory| // still must check again at connect time string host = _dataSource; VerifyLocalHostAndFixup(ref host, true, false /*don't fix-up*/); } } else if (0 <= _attachDBFileName.IndexOf('|')) { throw ADP.InvalidConnectionOptionValue(KEY.AttachDBFilename); } else { ValidateValueLength(_attachDBFileName, TdsEnums.MAXLEN_ATTACHDBFILE, KEY.AttachDBFilename); } _typeSystemAssemblyVersion = constTypeSystemAsmVersion10; if (true == _userInstance && !string.IsNullOrEmpty(_failoverPartner)) { throw SQL.UserInstanceFailoverNotCompatible(); } if (string.IsNullOrEmpty(typeSystemVersionString)) { typeSystemVersionString = DbConnectionStringDefaults.TypeSystemVersion; } if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.Latest, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.Latest; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2000, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.SQLServer2000; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2005, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.SQLServer2005; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2008, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.SQLServer2008; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2012, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.SQLServer2012; _typeSystemAssemblyVersion = constTypeSystemAsmVersion11; } else { throw ADP.InvalidConnectionOptionValue(KEY.Type_System_Version); } if (string.IsNullOrEmpty(transactionBindingString)) { transactionBindingString = DbConnectionStringDefaults.TransactionBinding; } if (transactionBindingString.Equals(TRANSACTIONBINDING.ImplicitUnbind, StringComparison.OrdinalIgnoreCase)) { _transactionBinding = TransactionBindingEnum.ImplicitUnbind; } else if (transactionBindingString.Equals(TRANSACTIONBINDING.ExplicitUnbind, StringComparison.OrdinalIgnoreCase)) { _transactionBinding = TransactionBindingEnum.ExplicitUnbind; } else { throw ADP.InvalidConnectionOptionValue(KEY.TransactionBinding); } if (_applicationIntent == ApplicationIntent.ReadOnly && !string.IsNullOrEmpty(_failoverPartner)) { throw SQL.ROR_FailoverNotSupportedConnString(); } if ((_connectRetryCount < 0) || (_connectRetryCount > 255)) { throw ADP.InvalidConnectRetryCountValue(); } if ((_connectRetryInterval < 1) || (_connectRetryInterval > 60)) { throw ADP.InvalidConnectRetryIntervalValue(); } if (Authentication != SqlAuthenticationMethod.NotSpecified && _integratedSecurity == true) { throw SQL.AuthenticationAndIntegratedSecurity(); } if (Authentication == SqlClient.SqlAuthenticationMethod.ActiveDirectoryIntegrated && HasPasswordKeyword) { throw SQL.IntegratedWithPassword(); } if (Authentication == SqlAuthenticationMethod.ActiveDirectoryInteractive && HasPasswordKeyword) { throw SQL.InteractiveWithPassword(); } if (Authentication == SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow && (HasUserIdKeyword || HasPasswordKeyword)) { throw SQL.DeviceFlowWithUsernamePassword(); } }
public override bool IsSupported(SqlAuthenticationMethod authenticationMethod) { return(authenticationMethod.Equals(SqlAuthenticationMethod.ActiveDirectoryPassword)); }
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlAuthenticationProvider.xml' path='docs/members[@name="SqlAuthenticationProvider"]/IsSupported/*'/> public abstract bool IsSupported(SqlAuthenticationMethod authenticationMethod);
/// <include file='../../../../../../doc/snippets/Microsoft.Data.SqlClient/ActiveDirectoryAuthenticationProvider.xml' path='docs/members[@name="ActiveDirectoryAuthenticationProvider"]/BeforeUnload/*'/> public override void BeforeUnload(SqlAuthenticationMethod authentication) { _logger.LogInfo(_type, "BeforeUnload", $"being unloaded from SqlAuthProviders for {authentication}."); }
private PreLoginHandshakeStatus ConsumePreLoginHandshake(SqlAuthenticationMethod authType, bool encrypt, bool trustServerCert, bool integratedSecurity, out bool marsCapable, out bool fedAuthRequired) { // Assign default values marsCapable = _fMARS; fedAuthRequired = false; bool isYukonOrLater = false; // Debug.Assert(_physicalStateObj._syncOverAsync, "Should not attempt pends in a synchronous call"); bool result = _physicalStateObj.TryReadNetworkPacket(); if (!result) { throw SQL.SynchronousCallMayNotPend(); } if (_physicalStateObj._inBytesRead == 0) { // If the server did not respond then something has gone wrong and we need to close the connection _physicalStateObj.AddError(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, _server, SQLMessage.PreloginError(), "", 0)); _physicalStateObj.Dispose(); ThrowExceptionAndWarning(_physicalStateObj); } // SEC byte[] payload = new byte[_physicalStateObj._inBytesRead - _physicalStateObj._inBytesUsed - _physicalStateObj._inputHeaderLen]; Debug.Assert(_physicalStateObj._syncOverAsync, "Should not attempt pends in a synchronous call"); result = _physicalStateObj.TryReadByteArray(payload, 0, payload.Length); if (!result) { throw SQL.SynchronousCallMayNotPend(); } if (payload[0] == 0xaa) { // If the first byte is 0xAA, we are connecting to a 6.5 or earlier server, which // is not supported. SQL BU DT 296425 throw SQL.InvalidSQLServerVersionUnknown(); } int offset = 0; int payloadOffset = 0; int payloadLength = 0; int option = payload[offset++]; while (option != (byte)PreLoginOptions.LASTOPT) { switch (option) { case (int)PreLoginOptions.VERSION: payloadOffset = payload[offset++] << 8 | payload[offset++]; payloadLength = payload[offset++] << 8 | payload[offset++]; byte majorVersion = payload[payloadOffset]; byte minorVersion = payload[payloadOffset + 1]; int level = (payload[payloadOffset + 2] << 8) | payload[payloadOffset + 3]; isYukonOrLater = majorVersion >= 9; if (!isYukonOrLater) { marsCapable = false; // If pre-Yukon, MARS not supported. } break; case (int)PreLoginOptions.ENCRYPT: payloadOffset = payload[offset++] << 8 | payload[offset++]; payloadLength = payload[offset++] << 8 | payload[offset++]; EncryptionOptions serverOption = (EncryptionOptions)payload[payloadOffset]; /* internal enum EncryptionOptions { OFF, ON, NOT_SUP, REQ, LOGIN } */ switch (_encryptionOption) { case (EncryptionOptions.ON): if (serverOption == EncryptionOptions.NOT_SUP) { _physicalStateObj.AddError(new SqlError(TdsEnums.ENCRYPTION_NOT_SUPPORTED, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, _server, SQLMessage.EncryptionNotSupportedByServer(), "", 0)); _physicalStateObj.Dispose(); ThrowExceptionAndWarning(_physicalStateObj); } break; case (EncryptionOptions.OFF): if (serverOption == EncryptionOptions.OFF) { // Only encrypt login. _encryptionOption = EncryptionOptions.LOGIN; } else if (serverOption == EncryptionOptions.REQ) { // Encrypt all. _encryptionOption = EncryptionOptions.ON; } break; case (EncryptionOptions.NOT_SUP): if (serverOption == EncryptionOptions.REQ) { _physicalStateObj.AddError(new SqlError(TdsEnums.ENCRYPTION_NOT_SUPPORTED, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, _server, SQLMessage.EncryptionNotSupportedByClient(), "", 0)); _physicalStateObj.Dispose(); ThrowExceptionAndWarning(_physicalStateObj); } break; default: Debug.Assert(false, "Invalid client encryption option detected"); break; } if (_encryptionOption == EncryptionOptions.ON || _encryptionOption == EncryptionOptions.LOGIN) { UInt32 error = 0; // If we're using legacy server certificate validation behavior (Authentication keyword not provided and not using access token), then validate if // Encrypt=true and Trust Sever Certificate = false. // If using Authentication keyword or access token, validate if Trust Server Certificate=false. bool shouldValidateServerCert = (encrypt && !trustServerCert) || ((authType != SqlAuthenticationMethod.NotSpecified || _connHandler._accessTokenInBytes != null) && !trustServerCert); UInt32 info = (shouldValidateServerCert ? TdsEnums.SNI_SSL_VALIDATE_CERTIFICATE : 0) | (isYukonOrLater ? TdsEnums.SNI_SSL_USE_SCHANNEL_CACHE : 0); if (encrypt && !integratedSecurity) { // optimization: in case of SQL Authentication and encryption, set SNI_SSL_IGNORE_CHANNEL_BINDINGS to let SNI // know that it does not need to allocate/retrieve the Channel Bindings from the SSL context. info |= TdsEnums.SNI_SSL_IGNORE_CHANNEL_BINDINGS; } // Add SSL (Encryption) SNI provider. error = SNINativeMethodWrapper.SNIAddProvider(_physicalStateObj.Handle, SNINativeMethodWrapper.ProviderEnum.SSL_PROV, ref info); if (error != TdsEnums.SNI_SUCCESS) { _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj)); ThrowExceptionAndWarning(_physicalStateObj); } // in the case where an async connection is made, encryption is used and Windows Authentication is used, // wait for SSL handshake to complete, so that the SSL context is fully negotiated before we try to use its // Channel Bindings as part of the Windows Authentication context build (SSL handshake must complete // before calling SNISecGenClientContext). error = SNINativeMethodWrapper.SNIWaitForSSLHandshakeToComplete(_physicalStateObj.Handle, _physicalStateObj.GetTimeoutRemaining()); if (error != TdsEnums.SNI_SUCCESS) { _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj)); ThrowExceptionAndWarning(_physicalStateObj); } // create a new packet encryption changes the internal packet size Bug# 228403 try {} // EmptyTry/Finally to avoid FXCop violation finally { _physicalStateObj.ClearAllWritePackets(); } } break; case (int)PreLoginOptions.INSTANCE: payloadOffset = payload[offset++] << 8 | payload[offset++]; payloadLength = payload[offset++] << 8 | payload[offset++]; byte ERROR_INST = 0x1; byte instanceResult = payload[payloadOffset]; if (instanceResult == ERROR_INST) { // Check if server says ERROR_INST. That either means the cached info // we used to connect is not valid or we connected to a named instance // listening on default params. return PreLoginHandshakeStatus.InstanceFailure; } break; case (int)PreLoginOptions.THREADID: // DO NOTHING FOR THREADID offset += 4; break; case (int)PreLoginOptions.MARS: payloadOffset = payload[offset++] << 8 | payload[offset++]; payloadLength = payload[offset++] << 8 | payload[offset++]; marsCapable = (payload[payloadOffset] == 0 ? false : true); Debug.Assert(payload[payloadOffset] == 0 || payload[payloadOffset] == 1, "Value for Mars PreLoginHandshake option not equal to 1 or 0!"); break; case (int)PreLoginOptions.TRACEID: // DO NOTHING FOR TRACEID offset += 4; break; case (int)PreLoginOptions.FEDAUTHREQUIRED: payloadOffset = payload[offset++] << 8 | payload[offset++]; payloadLength = payload[offset++] << 8 | payload[offset++]; // Only 0x00 and 0x01 are accepted values from the server. if (payload[payloadOffset] != 0x00 && payload[payloadOffset] != 0x01) { Bid.Trace("<sc.TdsParser.ConsumePreLoginHandshake|ERR> %d#, Server sent an unexpected value for FedAuthRequired PreLogin Option. Value was %d.\n", ObjectID, (int)payload[payloadOffset]); throw SQL.ParsingErrorValue(ParsingErrorState.FedAuthRequiredPreLoginResponseInvalidValue, (int)payload[payloadOffset]); } // We must NOT use the response for the FEDAUTHREQUIRED PreLogin option, if the connection string option // was not using the new Authentication keyword or in other words, if Authentication=NotSpecified // Or AccessToken is not null, mean token based authentication is used. if ((_connHandler.ConnectionOptions != null && _connHandler.ConnectionOptions.Authentication != SqlAuthenticationMethod.NotSpecified) || _connHandler._accessTokenInBytes != null) { fedAuthRequired = payload[payloadOffset] == 0x01 ? true : false; } break; default: Debug.Assert(false, "UNKNOWN option in ConsumePreLoginHandshake, option:" + option); // DO NOTHING FOR THESE UNKNOWN OPTIONS offset += 4; break; } if (offset < payload.Length) { option = payload[offset++]; } else { break; } } return PreLoginHandshakeStatus.Successful; }
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlAuthenticationProvider.xml' path='docs/members[@name="SqlAuthenticationProvider"]/GetProvider/*'/> public static SqlAuthenticationProvider GetProvider(SqlAuthenticationMethod authenticationMethod) { return(SqlAuthenticationProviderManager.Instance.GetProvider(authenticationMethod)); }
internal void Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, bool ignoreSniOpenTimeout, long timerExpire, bool encrypt, bool trustServerCert, bool integratedSecurity, bool withFailover, bool isFirstTransparentAttempt, SqlAuthenticationMethod authType) { if (_state != TdsParserState.Closed) { Debug.Assert(false, "TdsParser.Connect called on non-closed connection!"); return; } _connHandler = connHandler; _loginWithFailover = withFailover; UInt32 sniStatus = SNILoadHandle.SingletonInstance.SNIStatus; if (sniStatus != TdsEnums.SNI_SUCCESS) { _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj)); _physicalStateObj.Dispose(); ThrowExceptionAndWarning(_physicalStateObj); Debug.Assert(false, "SNI returned status != success, but no error thrown?"); } //Create LocalDB instance if necessary if (connHandler.ConnectionOptions.LocalDBInstance != null) LocalDBAPI.CreateLocalDBInstance(connHandler.ConnectionOptions.LocalDBInstance); if (integratedSecurity || authType == SqlAuthenticationMethod.ActiveDirectoryIntegrated) { LoadSSPILibrary(); // now allocate proper length of buffer _sniSpnBuffer = new byte[SNINativeMethodWrapper.SniMaxComposedSpnLength]; Bid.Trace("<sc.TdsParser.Connect|SEC> SSPI or Active Directory Authentication Library for SQL Server based integrated authentication\n"); } else { _sniSpnBuffer = null; if (authType == SqlAuthenticationMethod.ActiveDirectoryPassword) { Bid.Trace("<sc.TdsParser.Connect|SEC> Active Directory Password authentication\n"); } else if (authType == SqlAuthenticationMethod.SqlPassword) { Bid.Trace("<sc.TdsParser.Connect|SEC> SQL Password authentication\n"); } else{ Bid.Trace("<sc.TdsParser.Connect|SEC> SQL authentication\n"); } } byte[] instanceName = null; Debug.Assert(_connHandler != null, "SqlConnectionInternalTds handler can not be null at this point."); _connHandler.TimeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.PreLoginBegin); _connHandler.TimeoutErrorInternal.SetAndBeginPhase(SqlConnectionTimeoutErrorPhase.InitializeConnection); bool fParallel = _connHandler.ConnectionOptions.MultiSubnetFailover; TransparentNetworkResolutionState transparentNetworkResolutionState; if(_connHandler.ConnectionOptions.TransparentNetworkIPResolution) { if(isFirstTransparentAttempt) transparentNetworkResolutionState = TransparentNetworkResolutionState.SequentialMode; else transparentNetworkResolutionState = TransparentNetworkResolutionState.ParallelMode; } else transparentNetworkResolutionState = TransparentNetworkResolutionState.DisabledMode; int totalTimeout = _connHandler.ConnectionOptions.ConnectTimeout; _physicalStateObj.CreatePhysicalSNIHandle(serverInfo.ExtendedServerName, ignoreSniOpenTimeout, timerExpire, out instanceName, _sniSpnBuffer, false, true, fParallel, transparentNetworkResolutionState, totalTimeout); if (TdsEnums.SNI_SUCCESS != _physicalStateObj.Status) { _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj)); // Since connect failed, free the unmanaged connection memory. // HOWEVER - only free this after the netlib error was processed - if you // don't, the memory for the connection object might not be accurate and thus // a bad error could be returned (as it was when it was freed to early for me). _physicalStateObj.Dispose(); Bid.Trace("<sc.TdsParser.Connect|ERR|SEC> Login failure\n"); ThrowExceptionAndWarning(_physicalStateObj); Debug.Assert(false, "SNI returned status != success, but no error thrown?"); } _server = serverInfo.ResolvedServerName; if (null != connHandler.PoolGroupProviderInfo) { // If we are pooling, check to see if we were processing an // alias which has changed, which means we need to clean out // the pool. See Webdata 104293. // This should not apply to routing, as it is not an alias change, routed connection // should still use VNN of AlwaysOn cluster as server for pooling purposes. connHandler.PoolGroupProviderInfo.AliasCheck(serverInfo.PreRoutingServerName==null ? serverInfo.ResolvedServerName: serverInfo.PreRoutingServerName); } _state = TdsParserState.OpenNotLoggedIn; _physicalStateObj.SniContext = SniContext.Snix_PreLoginBeforeSuccessfullWrite; // SQL BU DT 376766 _physicalStateObj.TimeoutTime = timerExpire; bool marsCapable = false; _connHandler.TimeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.InitializeConnection); _connHandler.TimeoutErrorInternal.SetAndBeginPhase(SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake); UInt32 result = SNINativeMethodWrapper.SniGetConnectionId(_physicalStateObj.Handle, ref _connHandler._clientConnectionId); Debug.Assert(result == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SniGetConnectionId"); // Bid.Trace("<sc.TdsParser.Connect|SEC> Sending prelogin handshake\n"); SendPreLoginHandshake(instanceName, encrypt); _connHandler.TimeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake); _connHandler.TimeoutErrorInternal.SetAndBeginPhase(SqlConnectionTimeoutErrorPhase.ConsumePreLoginHandshake); _physicalStateObj.SniContext = SniContext.Snix_PreLogin; Bid.Trace("<sc.TdsParser.Connect|SEC> Consuming prelogin handshake\n"); PreLoginHandshakeStatus status = ConsumePreLoginHandshake(authType, encrypt, trustServerCert, integratedSecurity, out marsCapable, out _connHandler._fedAuthRequired); if (status == PreLoginHandshakeStatus.InstanceFailure) { Bid.Trace("<sc.TdsParser.Connect|SEC> Prelogin handshake unsuccessful. Reattempting prelogin handshake\n"); _physicalStateObj.Dispose(); // Close previous connection // On Instance failure re-connect and flush SNI named instance cache. _physicalStateObj.SniContext=SniContext.Snix_Connect; _physicalStateObj.CreatePhysicalSNIHandle(serverInfo.ExtendedServerName, ignoreSniOpenTimeout, timerExpire, out instanceName, _sniSpnBuffer, true, true, fParallel, transparentNetworkResolutionState, totalTimeout); if (TdsEnums.SNI_SUCCESS != _physicalStateObj.Status) { _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj)); Bid.Trace("<sc.TdsParser.Connect|ERR|SEC> Login failure\n"); ThrowExceptionAndWarning(_physicalStateObj); } UInt32 retCode = SNINativeMethodWrapper.SniGetConnectionId(_physicalStateObj.Handle, ref _connHandler._clientConnectionId); Debug.Assert(retCode == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SniGetConnectionId"); Bid.Trace("<sc.TdsParser.Connect|SEC> Sending prelogin handshake\n"); SendPreLoginHandshake(instanceName, encrypt); status = ConsumePreLoginHandshake(authType, encrypt, trustServerCert, integratedSecurity, out marsCapable, out _connHandler._fedAuthRequired); // Don't need to check for Sphinx failure, since we've already consumed // one pre-login packet and know we are connecting to Shiloh. if (status == PreLoginHandshakeStatus.InstanceFailure) { Bid.Trace("<sc.TdsParser.Connect|ERR|SEC> Prelogin handshake unsuccessful. Login failure\n"); throw SQL.InstanceFailure(); } } Bid.Trace("<sc.TdsParser.Connect|SEC> Prelogin handshake successful\n"); if (_fMARS && marsCapable) { // if user explictly disables mars or mars not supported, don't create the session pool _sessionPool = new TdsParserSessionPool(this); } else { _fMARS = false; } if (authType == SqlAuthenticationMethod.ActiveDirectoryPassword || (authType == SqlAuthenticationMethod.ActiveDirectoryIntegrated && _connHandler._fedAuthRequired)) { Debug.Assert(!integratedSecurity, "The legacy Integrated Security connection string option cannot be true when using Active Directory Authentication Library for SQL Server Based workflows."); LoadADALLibrary(); if (Bid.AdvancedOn) { Bid.Trace("<sc.TdsParser.Connect|SEC> Active directory authentication.Loaded Active Directory Authentication Library for SQL Server\n"); } } return; }
/// <summary> /// Get an authentication provider by method. /// </summary> /// <param name="authenticationMethod">Authentication method.</param> /// <returns>Authentication provider or null if not found.</returns> public SqlAuthenticationProvider GetProvider(SqlAuthenticationMethod authenticationMethod) { SqlAuthenticationProvider value; return(_providers.TryGetValue(authenticationMethod, out value) ? value : null); }
// This c-tor is used to create SSE and user instance connection strings when user instance is set to true // internal SqlConnectionString(SqlConnectionString connectionOptions, string dataSource, bool userInstance, bool? setEnlistValue) : base(connectionOptions) { _integratedSecurity = connectionOptions._integratedSecurity; _connectionReset = connectionOptions._connectionReset; _contextConnection = connectionOptions._contextConnection; _encrypt = connectionOptions._encrypt; if (setEnlistValue.HasValue) { _enlist = setEnlistValue.Value; } else { _enlist = connectionOptions._enlist; } _mars = connectionOptions._mars; _persistSecurityInfo = connectionOptions._persistSecurityInfo; _pooling = connectionOptions._pooling; _replication = connectionOptions._replication; _userInstance = userInstance; _connectTimeout = connectionOptions._connectTimeout; _loadBalanceTimeout = connectionOptions._loadBalanceTimeout; _maxPoolSize = connectionOptions._maxPoolSize; _minPoolSize = connectionOptions._minPoolSize; _multiSubnetFailover = connectionOptions._multiSubnetFailover; _packetSize = connectionOptions._packetSize; _applicationName = connectionOptions._applicationName; _attachDBFileName = connectionOptions._attachDBFileName; _currentLanguage = connectionOptions._currentLanguage; _dataSource = dataSource; _localDBInstance = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource); _failoverPartner = connectionOptions._failoverPartner; _initialCatalog = connectionOptions._initialCatalog; _password = connectionOptions._password; _userID = connectionOptions._userID; _networkLibrary = connectionOptions._networkLibrary; _workstationId = connectionOptions._workstationId; _expandedAttachDBFilename = connectionOptions._expandedAttachDBFilename; _typeSystemVersion = connectionOptions._typeSystemVersion; _typeSystemAssemblyVersion =connectionOptions._typeSystemAssemblyVersion; _transactionBinding = connectionOptions._transactionBinding; _applicationIntent = connectionOptions._applicationIntent; _connectRetryCount = connectionOptions._connectRetryCount; _connectRetryInterval = connectionOptions._connectRetryInterval; _authType = connectionOptions._authType; _columnEncryptionSetting = connectionOptions._columnEncryptionSetting; ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source); }
internal SqlConnectionString(string connectionString) : base(connectionString, GetParseSynonyms(), false) { bool runningInProc = InOutOfProcHelper.InProc; _integratedSecurity = ConvertValueToIntegratedSecurity(); ConvertValueToBoolean(KEY.AsynchronousProcessing, DEFAULT.Asynchronous); // while we don't use it anymore, we still need to verify it is true/false // SQLPT 41700: Ignore ResetConnection=False (still validate the keyword/value) _connectionReset = ConvertValueToBoolean(KEY.Connection_Reset, DEFAULT.Connection_Reset); _contextConnection = ConvertValueToBoolean(KEY.Context_Connection, DEFAULT.Context_Connection); _encrypt = ConvertValueToEncrypt(); _enlist = ConvertValueToBoolean(KEY.Enlist, ADP.IsWindowsNT); _mars = ConvertValueToBoolean(KEY.MARS, DEFAULT.MARS); _persistSecurityInfo = ConvertValueToBoolean(KEY.Persist_Security_Info, DEFAULT.Persist_Security_Info); _pooling = ConvertValueToBoolean(KEY.Pooling, DEFAULT.Pooling); _replication = ConvertValueToBoolean(KEY.Replication, DEFAULT.Replication); _userInstance = ConvertValueToBoolean(KEY.User_Instance, DEFAULT.User_Instance); _multiSubnetFailover = ConvertValueToBoolean(KEY.MultiSubnetFailover, DEFAULT.MultiSubnetFailover); _connectTimeout = ConvertValueToInt32(KEY.Connect_Timeout, DEFAULT.Connect_Timeout); _loadBalanceTimeout = ConvertValueToInt32(KEY.Load_Balance_Timeout, DEFAULT.Load_Balance_Timeout); _maxPoolSize = ConvertValueToInt32(KEY.Max_Pool_Size, DEFAULT.Max_Pool_Size); _minPoolSize = ConvertValueToInt32(KEY.Min_Pool_Size, DEFAULT.Min_Pool_Size); _packetSize = ConvertValueToInt32(KEY.Packet_Size, DEFAULT.Packet_Size); _connectRetryCount = ConvertValueToInt32(KEY.Connect_Retry_Count, DEFAULT.Connect_Retry_Count); _connectRetryInterval = ConvertValueToInt32(KEY.Connect_Retry_Interval, DEFAULT.Connect_Retry_Interval); _applicationIntent = ConvertValueToApplicationIntent(); _applicationName = ConvertValueToString(KEY.Application_Name, DEFAULT.Application_Name); _attachDBFileName = ConvertValueToString(KEY.AttachDBFilename, DEFAULT.AttachDBFilename); _currentLanguage = ConvertValueToString(KEY.Current_Language, DEFAULT.Current_Language); _dataSource = ConvertValueToString(KEY.Data_Source, DEFAULT.Data_Source); _localDBInstance = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource); _failoverPartner = ConvertValueToString(KEY.FailoverPartner, DEFAULT.FailoverPartner); _initialCatalog = ConvertValueToString(KEY.Initial_Catalog, DEFAULT.Initial_Catalog); _networkLibrary = ConvertValueToString(KEY.Network_Library, null); _password = ConvertValueToString(KEY.Password, DEFAULT.Password); _trustServerCertificate = ConvertValueToBoolean(KEY.TrustServerCertificate, DEFAULT.TrustServerCertificate); _authType = ConvertValueToAuthenticationType(); _columnEncryptionSetting = ConvertValueToColumnEncryptionSetting(); // Temporary string - this value is stored internally as an enum. string typeSystemVersionString = ConvertValueToString(KEY.Type_System_Version, null); string transactionBindingString = ConvertValueToString(KEY.TransactionBinding, null); _userID = ConvertValueToString(KEY.User_ID, DEFAULT.User_ID); _workstationId = ConvertValueToString(KEY.Workstation_Id, null); if (_contextConnection) { // We have to be running in the engine for you to request a // context connection. if (!runningInProc) { throw SQL.ContextUnavailableOutOfProc(); } // When using a context connection, we need to ensure that no // other connection string keywords are specified. foreach (DictionaryEntry entry in Parsetable) { if ((string) entry.Key != KEY.Context_Connection && (string) entry.Key != KEY.Type_System_Version) { throw SQL.ContextAllowsLimitedKeywords(); } } } if (!_encrypt) { // Support legacy registry encryption settings const string folder = "Software\\Microsoft\\MSSQLServer\\Client\\SuperSocketNetLib"; const string value = "Encrypt"; Object obj = ADP.LocalMachineRegistryValue(folder, value); if ((obj is Int32) && (1 == (int)obj)) { // If the registry key exists _encrypt = true; } } if (_loadBalanceTimeout < 0) { throw ADP.InvalidConnectionOptionValue(KEY.Load_Balance_Timeout); } if (_connectTimeout < 0) { throw ADP.InvalidConnectionOptionValue(KEY.Connect_Timeout); } if (_maxPoolSize < 1) { throw ADP.InvalidConnectionOptionValue(KEY.Max_Pool_Size); } if (_minPoolSize < 0) { throw ADP.InvalidConnectionOptionValue(KEY.Min_Pool_Size); } if (_maxPoolSize < _minPoolSize) { throw ADP.InvalidMinMaxPoolSizeValues(); } if ((_packetSize < TdsEnums.MIN_PACKET_SIZE) || (TdsEnums.MAX_PACKET_SIZE < _packetSize)) { throw SQL.InvalidPacketSizeValue(); } if (null != _networkLibrary) { // MDAC 83525 string networkLibrary = _networkLibrary.Trim().ToLower(CultureInfo.InvariantCulture); Hashtable netlib = NetlibMapping(); if (!netlib.ContainsKey(networkLibrary)) { throw ADP.InvalidConnectionOptionValue(KEY.Network_Library); } _networkLibrary = (string) netlib[networkLibrary]; } else { _networkLibrary = DEFAULT.Network_Library; } ValidateValueLength(_applicationName, TdsEnums.MAXLEN_APPNAME, KEY.Application_Name); ValidateValueLength(_currentLanguage , TdsEnums.MAXLEN_LANGUAGE, KEY.Current_Language); ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source); ValidateValueLength(_failoverPartner, TdsEnums.MAXLEN_SERVERNAME, KEY.FailoverPartner); ValidateValueLength(_initialCatalog, TdsEnums.MAXLEN_DATABASE, KEY.Initial_Catalog); ValidateValueLength(_password, TdsEnums.MAXLEN_PASSWORD, KEY.Password); ValidateValueLength(_userID, TdsEnums.MAXLEN_USERNAME, KEY.User_ID); if (null != _workstationId) { ValidateValueLength(_workstationId, TdsEnums.MAXLEN_HOSTNAME, KEY.Workstation_Id); } if (!String.Equals(DEFAULT.FailoverPartner, _failoverPartner, StringComparison.OrdinalIgnoreCase)) { // fail-over partner is set if (_multiSubnetFailover) { throw SQL.MultiSubnetFailoverWithFailoverPartner(serverProvidedFailoverPartner: false, internalConnection: null); } if (String.Equals(DEFAULT.Initial_Catalog, _initialCatalog, StringComparison.OrdinalIgnoreCase)) { throw ADP.MissingConnectionOptionValue(KEY.FailoverPartner, KEY.Initial_Catalog); } } // expand during construction so that CreatePermissionSet and Expand are consistent string datadir = null; _expandedAttachDBFilename = ExpandDataDirectory(KEY.AttachDBFilename, _attachDBFileName, ref datadir); if (null != _expandedAttachDBFilename) { if (0 <= _expandedAttachDBFilename.IndexOf('|')) { throw ADP.InvalidConnectionOptionValue(KEY.AttachDBFilename); } ValidateValueLength(_expandedAttachDBFilename, TdsEnums.MAXLEN_ATTACHDBFILE, KEY.AttachDBFilename); if (_localDBInstance == null) { // fail fast to verify LocalHost when using |DataDirectory| // still must check again at connect time string host = _dataSource; string protocol = _networkLibrary; TdsParserStaticMethods.AliasRegistryLookup(ref host, ref protocol); VerifyLocalHostAndFixup(ref host, true, false /*don't fix-up*/); } } else if (0 <= _attachDBFileName.IndexOf('|')) { throw ADP.InvalidConnectionOptionValue(KEY.AttachDBFilename); } else { ValidateValueLength(_attachDBFileName, TdsEnums.MAXLEN_ATTACHDBFILE, KEY.AttachDBFilename); } _typeSystemAssemblyVersion = constTypeSystemAsmVersion10; if (true == _userInstance && !ADP.IsEmpty(_failoverPartner)) { throw SQL.UserInstanceFailoverNotCompatible(); } if (ADP.IsEmpty(typeSystemVersionString)) { typeSystemVersionString = DbConnectionStringDefaults.TypeSystemVersion; } if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.Latest, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.Latest; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2000, StringComparison.OrdinalIgnoreCase)) { if (_contextConnection) { throw SQL.ContextAllowsOnlyTypeSystem2005(); } _typeSystemVersion = TypeSystem.SQLServer2000; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2005, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.SQLServer2005; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2008, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.SQLServer2008; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2012, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.SQLServer2012; _typeSystemAssemblyVersion = constTypeSystemAsmVersion11; } else { throw ADP.InvalidConnectionOptionValue(KEY.Type_System_Version); } if (ADP.IsEmpty(transactionBindingString)) { transactionBindingString = DbConnectionStringDefaults.TransactionBinding; } if (transactionBindingString.Equals(TRANSACIONBINDING.ImplicitUnbind, StringComparison.OrdinalIgnoreCase)) { _transactionBinding = TransactionBindingEnum.ImplicitUnbind; } else if (transactionBindingString.Equals(TRANSACIONBINDING.ExplicitUnbind, StringComparison.OrdinalIgnoreCase)) { _transactionBinding = TransactionBindingEnum.ExplicitUnbind; } else { throw ADP.InvalidConnectionOptionValue(KEY.TransactionBinding); } if (_applicationIntent == ApplicationIntent.ReadOnly && !String.IsNullOrEmpty(_failoverPartner)) throw SQL.ROR_FailoverNotSupportedConnString(); if ((_connectRetryCount<0) || (_connectRetryCount>255)) { throw ADP.InvalidConnectRetryCountValue(); } if ((_connectRetryInterval < 1) || (_connectRetryInterval > 60)) { throw ADP.InvalidConnectRetryIntervalValue(); } if (Authentication != SqlAuthenticationMethod.NotSpecified && _integratedSecurity == true) { throw SQL.AuthenticationAndIntegratedSecurity(); } if (Authentication == SqlClient.SqlAuthenticationMethod.ActiveDirectoryIntegrated && (HasUserIdKeyword || HasPasswordKeyword)) { throw SQL.IntegratedWithUserIDAndPassword(); } }
private void SetAuthenticationValue(SqlAuthenticationMethod value) { Debug.Assert(DbConnectionStringBuilderUtil.IsValidAuthenticationTypeValue(value), "Invalid value for AuthenticationType"); base[DbConnectionStringKeywords.Authentication] = DbConnectionStringBuilderUtil.AuthenticationTypeToString(value); }
private void Reset(Keywords index) { switch(index) { case Keywords.ApplicationIntent: _applicationIntent = DbConnectionStringDefaults.ApplicationIntent; break; case Keywords.ApplicationName: _applicationName = DbConnectionStringDefaults.ApplicationName; break; case Keywords.AsynchronousProcessing: _asynchronousProcessing = DbConnectionStringDefaults.AsynchronousProcessing; break; case Keywords.AttachDBFilename: _attachDBFilename = DbConnectionStringDefaults.AttachDBFilename; break; case Keywords.Authentication: _authentication = DbConnectionStringDefaults.Authentication; break; case Keywords.ConnectTimeout: _connectTimeout = DbConnectionStringDefaults.ConnectTimeout; break; case Keywords.ConnectionReset: _connectionReset = DbConnectionStringDefaults.ConnectionReset; break; case Keywords.ContextConnection: _contextConnection = DbConnectionStringDefaults.ContextConnection; break; case Keywords.CurrentLanguage: _currentLanguage = DbConnectionStringDefaults.CurrentLanguage; break; case Keywords.DataSource: _dataSource = DbConnectionStringDefaults.DataSource; break; case Keywords.Encrypt: _encrypt = DbConnectionStringDefaults.Encrypt; break; case Keywords.Enlist: _enlist = DbConnectionStringDefaults.Enlist; break; case Keywords.FailoverPartner: _failoverPartner = DbConnectionStringDefaults.FailoverPartner; break; case Keywords.InitialCatalog: _initialCatalog = DbConnectionStringDefaults.InitialCatalog; break; case Keywords.IntegratedSecurity: _integratedSecurity = DbConnectionStringDefaults.IntegratedSecurity; break; case Keywords.LoadBalanceTimeout: _loadBalanceTimeout = DbConnectionStringDefaults.LoadBalanceTimeout; break; case Keywords.MultipleActiveResultSets: _multipleActiveResultSets = DbConnectionStringDefaults.MultipleActiveResultSets; break; case Keywords.MaxPoolSize: _maxPoolSize = DbConnectionStringDefaults.MaxPoolSize; break; case Keywords.MinPoolSize: _minPoolSize = DbConnectionStringDefaults.MinPoolSize; break; case Keywords.MultiSubnetFailover: _multiSubnetFailover = DbConnectionStringDefaults.MultiSubnetFailover; break; // case Keywords.NamedConnection: // _namedConnection = DbConnectionStringDefaults.NamedConnection; // break; case Keywords.NetworkLibrary: _networkLibrary = DbConnectionStringDefaults.NetworkLibrary; break; case Keywords.PacketSize: _packetSize = DbConnectionStringDefaults.PacketSize; break; case Keywords.Password: _password = DbConnectionStringDefaults.Password; break; case Keywords.PersistSecurityInfo: _persistSecurityInfo = DbConnectionStringDefaults.PersistSecurityInfo; break; case Keywords.Pooling: _pooling = DbConnectionStringDefaults.Pooling; break; case Keywords.ConnectRetryCount: _connectRetryCount = DbConnectionStringDefaults.ConnectRetryCount; break; case Keywords.ConnectRetryInterval: _connectRetryInterval = DbConnectionStringDefaults.ConnectRetryInterval; break; case Keywords.Replication: _replication = DbConnectionStringDefaults.Replication; break; case Keywords.TransactionBinding: _transactionBinding = DbConnectionStringDefaults.TransactionBinding; break; case Keywords.TrustServerCertificate: _trustServerCertificate = DbConnectionStringDefaults.TrustServerCertificate; break; case Keywords.TypeSystemVersion: _typeSystemVersion = DbConnectionStringDefaults.TypeSystemVersion; break; case Keywords.UserID: _userID = DbConnectionStringDefaults.UserID; break; case Keywords.UserInstance: _userInstance = DbConnectionStringDefaults.UserInstance; break; case Keywords.WorkstationID: _workstationID = DbConnectionStringDefaults.WorkstationID; break; case Keywords.ColumnEncryptionSetting: _columnEncryptionSetting = DbConnectionStringDefaults.ColumnEncryptionSetting; break; default: Debug.Assert(false, "unexpected keyword"); throw ADP.KeywordNotSupported(_validKeywords[(int)index]); } }
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlAuthenticationProvider.xml' path='docs/members[@name="SqlAuthenticationProvider"]/SetProvider/*'/> public static bool SetProvider(SqlAuthenticationMethod authenticationMethod, SqlAuthenticationProvider provider) { return(SqlAuthenticationProviderManager.Instance.SetProvider(authenticationMethod, provider)); }
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlAuthenticationProvider.xml' path='docs/members[@name="SqlAuthenticationProvider"]/BeforeUnload/*'/> public virtual void BeforeUnload(SqlAuthenticationMethod authenticationMethod) { }
public override bool IsSupported(SqlAuthenticationMethod authenticationMethod) => authenticationMethod.Equals(SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow);