Exemple #1
0
        /// <summary>
        /// Handler for pre-login request
        /// </summary>
        public override TDSMessageCollection OnPreLoginRequest(ITDSServerSession session, TDSMessage request)
        {
            // Delegate to the base class
            TDSMessageCollection response = base.OnPreLoginRequest(session, request);

            // Check if arguments are of the routing server
            if (Arguments is RoutingTDSServerArguments)
            {
                // Cast to routing server arguments
                RoutingTDSServerArguments serverArguments = Arguments as RoutingTDSServerArguments;

                // Check if routing is configured during login
                if (serverArguments.RouteOnPacket == TDSMessageType.TDS7Login)
                {
                    // Check if pre-login response is contained inside the first message
                    if (response.Count > 0 && response[0].Any(t => t is TDSPreLoginToken))
                    {
                        // Find the first prelogin token
                        TDSPreLoginToken preLoginResponse = (TDSPreLoginToken)response[0].Where(t => t is TDSPreLoginToken).First();

                        // Inflate pre-login request from the message
                        TDSPreLoginToken preLoginRequest = request[0] as TDSPreLoginToken;

                        // Update MARS with the requested value
                        preLoginResponse.IsMARS = preLoginRequest.IsMARS;
                    }
                }
            }

            return response;
        }
Exemple #2
0
        /// <summary>
        /// Handler for login request
        /// </summary>
        public override TDSMessageCollection OnLogin7Request(ITDSServerSession session, TDSMessage request)
        {
            // Inflate login7 request from the message
            TDSLogin7Token loginRequest = request[0] as TDSLogin7Token;

            // Check if arguments are of the routing server
            if (Arguments is RoutingTDSServerArguments)
            {
                // Cast to routing server arguments
                RoutingTDSServerArguments ServerArguments = Arguments as RoutingTDSServerArguments;

                // Check filter
                if (ServerArguments.RequireReadOnly && (loginRequest.TypeFlags.ReadOnlyIntent != TDSLogin7TypeFlagsReadOnlyIntent.ReadOnly))
                {
                    // Log request
                    TDSUtilities.Log(Arguments.Log, "Request", loginRequest);

                    // Prepare ERROR token with the denial details
                    TDSErrorToken errorToken = new TDSErrorToken(18456, 1, 14, "Received application intent: " + loginRequest.TypeFlags.ReadOnlyIntent.ToString(), Arguments.ServerName);

                    // Log response
                    TDSUtilities.Log(Arguments.Log, "Response", errorToken);

                    // Serialize the error token into the response packet
                    TDSMessage responseMessage = new TDSMessage(TDSMessageType.Response, errorToken);

                    // Prepare ERROR token for the final decision
                    errorToken = new TDSErrorToken(18456, 1, 14, "Read-Only application intent is required for routing", Arguments.ServerName);

                    // Log response
                    TDSUtilities.Log(Arguments.Log, "Response", errorToken);

                    // Serialize the error token into the response packet
                    responseMessage.Add(errorToken);

                    // Create DONE token
                    TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Error);

                    // Log response
                    TDSUtilities.Log(Arguments.Log, "Response", doneToken);

                    // Serialize DONE token into the response packet
                    responseMessage.Add(doneToken);

                    // Return a single message in the collection
                    return new TDSMessageCollection(responseMessage);
                }
            }

            // Delegate to the base class
            return base.OnLogin7Request(session, request);
        }
        /// <summary>
        /// Handler for login request
        /// </summary>
        public override TDSMessageCollection OnLogin7Request(ITDSServerSession session, TDSMessage request)
        {
            // Get the collection from the normal behavior On Login7 Request
            TDSMessageCollection login7Collection = base.OnLogin7Request(session, request);

            // Check if arguments are of the Federated Authentication server
            if (Arguments is FederatedAuthenticationNegativeTDSServerArguments)
            {
                // Cast to federated authentication server arguments
                FederatedAuthenticationNegativeTDSServerArguments ServerArguments = Arguments as FederatedAuthenticationNegativeTDSServerArguments;

                // Get the Federated Authentication ExtAck from Login 7
                TDSFeatureExtAckFederatedAuthenticationOption fedAutExtAct = GetFeatureExtAckFederatedAuthenticationOptionFromLogin7(login7Collection);

                // If not found, return the base collection intact
                if (fedAutExtAct != null)
                {
                    switch (ServerArguments.Scenario)
                    {
                        case FederatedAuthenticationNegativeTDSScenarioType.NonceMissingInFedAuthFEATUREXTACK:
                            {
                                // Delete the nonce from the Token
                                fedAutExtAct.ClientNonce = null;

                                break;
                            }
                        case FederatedAuthenticationNegativeTDSScenarioType.FedAuthMissingInFEATUREEXTACK:
                            {
                                // Remove the Fed Auth Ext Ack from the options list in the FeatureExtAckToken
                                GetFeatureExtAckTokenFromLogin7(login7Collection).Options.Remove(fedAutExtAct);

                                break;
                            }
                        case FederatedAuthenticationNegativeTDSScenarioType.SignatureMissingInFedAuthFEATUREXTACK:
                            {
                                // Delete the signature from the Token
                                fedAutExtAct.Signature = null;

                                break;
                            }
                    }
                }
            }

            // Return the collection
            return login7Collection;
        }
        /// <summary>
        /// Handler for login request
        /// </summary>
        public override TDSMessageCollection OnPreLoginRequest(ITDSServerSession session, TDSMessage request)
        {
            // Get the collection from a valid On PreLogin Request
            TDSMessageCollection preLoginCollection = base.OnPreLoginRequest(session, request);

            // Check if arguments are of the Federated Authentication server
            if (Arguments is FederatedAuthenticationNegativeTDSServerArguments)
            {
                // Cast to federated authentication server arguments
                FederatedAuthenticationNegativeTDSServerArguments ServerArguments = Arguments as FederatedAuthenticationNegativeTDSServerArguments;

                // Find the is token carrying on TDSPreLoginToken
                TDSPreLoginToken preLoginToken = preLoginCollection.Find(message => message.Exists(packetToken => packetToken is TDSPreLoginToken)).
                    Find(packetToken => packetToken is TDSPreLoginToken) as TDSPreLoginToken;

                switch (ServerArguments.Scenario)
                {
                    case FederatedAuthenticationNegativeTDSScenarioType.NonceMissingInFedAuthPreLogin:
                        {
                            // If we have the prelogin token
                            if (preLoginToken != null && preLoginToken.Nonce != null)
                            {
                                // Nullify the nonce from the Token
                                preLoginToken.Nonce = null;
                            }

                            break;
                        }

                    case FederatedAuthenticationNegativeTDSScenarioType.InvalidB_FEDAUTHREQUIREDResponse:
                        {
                            // If we have the prelogin token
                            if (preLoginToken != null)
                            {
                                // Set an illegal value for B_FEDAUTHREQURED
                                preLoginToken.FedAuthRequired = TdsPreLoginFedAuthRequiredOption.Illegal;
                            }

                            break;
                        }
                }
            }

            // Return the collection
            return preLoginCollection;
        }
Exemple #5
0
        public virtual TDSMessageCollection OnFederatedAuthenticationTokenMessage(ITDSServerSession session, TDSMessage message)
        {
            // Get the FedAuthToken
            TDSFedAuthToken fedauthToken = message[0] as TDSFedAuthToken;

            // Log
            TDSUtilities.Log(Arguments.Log, "Request", fedauthToken);

            return OnFederatedAuthenticationCompleted(session, fedauthToken.Token);
        }
Exemple #6
0
        /// <summary>
        /// Handler for login request
        /// </summary>
        public override TDSMessageCollection OnLogin7Request(ITDSServerSession session, TDSMessage request)
        {
            // Get the collection from the normal behavior On Login7 Request
            TDSMessageCollection login7Collection = base.OnLogin7Request(session, request);

            // Check if arguments are of the Federated Authentication server
            if (Arguments is FederatedAuthenticationNegativeTDSServerArguments)
            {
                // Cast to federated authentication server arguments
                FederatedAuthenticationNegativeTDSServerArguments ServerArguments = Arguments as FederatedAuthenticationNegativeTDSServerArguments;

                // Get the Federated Authentication ExtAck from Login 7
                TDSFeatureExtAckFederatedAuthenticationOption fedAutExtAct = GetFeatureExtAckFederatedAuthenticationOptionFromLogin7(login7Collection);

                // If not found, return the base collection intact
                if (fedAutExtAct != null)
                {
                    switch (ServerArguments.Scenario)
                    {
                    case FederatedAuthenticationNegativeTDSScenarioType.NonceMissingInFedAuthFEATUREXTACK:
                    {
                        // Delete the nonce from the Token
                        fedAutExtAct.ClientNonce = null;

                        break;
                    }

                    case FederatedAuthenticationNegativeTDSScenarioType.FedAuthMissingInFEATUREEXTACK:
                    {
                        // Remove the Fed Auth Ext Ack from the options list in the FeatureExtAckToken
                        GetFeatureExtAckTokenFromLogin7(login7Collection).Options.Remove(fedAutExtAct);

                        break;
                    }

                    case FederatedAuthenticationNegativeTDSScenarioType.SignatureMissingInFedAuthFEATUREXTACK:
                    {
                        // Delete the signature from the Token
                        fedAutExtAct.Signature = null;

                        break;
                    }
                    }
                }
            }

            // Return the collection
            return(login7Collection);
        }
Exemple #7
0
        /// <summary>
        /// Read data from TDS server
        /// </summary>
        /// <returns></returns>
        private TDSMessage _ReadResponse()
        {
            // Prepare response container
            TDSMessage responseMessage = new TDSMessage();

            // Loop as long as it takes to receive the entire message
            while (!responseMessage.InflateServerResponse(Client.State, Transport))
            {
                // Switch context to avoid CPU overloading
                System.Threading.Thread.Sleep(1);
            }

            // Log event
            Log("Recieved a response to \"{0}\"", Client.State);

            // Return what we inflated
            return responseMessage;
        }
        /// <summary>
        /// Handler for login request
        /// </summary>
        public override TDSMessageCollection OnLogin7Request(ITDSServerSession session, TDSMessage request)
        {
            // Inflate login7 request from the message
            TDSLogin7Token loginRequest = request[0] as TDSLogin7Token;

            // Check if arguments are of the authenticating TDS server
            if (Arguments is AuthenticatingTDSServerArguments)
            {
                // Cast to authenticating TDS server arguments
                AuthenticatingTDSServerArguments ServerArguments = Arguments as AuthenticatingTDSServerArguments;

                // Check if we're still processing normal login
                if (ServerArguments.ApplicationIntentFilter != ApplicationIntentFilterType.All)
                {
                    // Check filter
                    if ((ServerArguments.ApplicationIntentFilter == ApplicationIntentFilterType.ReadOnly && loginRequest.TypeFlags.ReadOnlyIntent != TDSLogin7TypeFlagsReadOnlyIntent.ReadOnly)
                        || (ServerArguments.ApplicationIntentFilter == ApplicationIntentFilterType.None))
                    {
                        // Log request to which we're about to send a failure
                        TDSUtilities.Log(Arguments.Log, "Request", loginRequest);

                        // Prepare ERROR token with the denial details
                        TDSErrorToken errorToken = new TDSErrorToken(18456, 1, 14, "Received application intent: " + loginRequest.TypeFlags.ReadOnlyIntent.ToString(), Arguments.ServerName);

                        // Log response
                        TDSUtilities.Log(Arguments.Log, "Response", errorToken);

                        // Serialize the error token into the response packet
                        TDSMessage responseMessage = new TDSMessage(TDSMessageType.Response, errorToken);

                        // Prepare ERROR token for the final decision
                        errorToken = new TDSErrorToken(18456, 1, 14, "Connection is denied by application intent filter", Arguments.ServerName);

                        // Log response
                        TDSUtilities.Log(Arguments.Log, "Response", errorToken);

                        // Serialize the error token into the response packet
                        responseMessage.Add(errorToken);

                        // Create DONE token
                        TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Error);

                        // Log response
                        TDSUtilities.Log(Arguments.Log, "Response", doneToken);

                        // Serialize DONE token into the response packet
                        responseMessage.Add(doneToken);

                        // Put a single message into the collection and return it
                        return new TDSMessageCollection(responseMessage);
                    }
                }

                // Check if we're still processing normal login and there's a filter to check
                if (ServerArguments.ServerNameFilterType != ServerNameFilterType.None)
                {
                    // Check each algorithm
                    if ((ServerArguments.ServerNameFilterType == ServerNameFilterType.Equals && string.Compare(ServerArguments.ServerNameFilter, loginRequest.ServerName, true) != 0)
                        || (ServerArguments.ServerNameFilterType == ServerNameFilterType.StartsWith && !loginRequest.ServerName.StartsWith(ServerArguments.ServerNameFilter))
                        || (ServerArguments.ServerNameFilterType == ServerNameFilterType.EndsWith && !loginRequest.ServerName.EndsWith(ServerArguments.ServerNameFilter))
                        || (ServerArguments.ServerNameFilterType == ServerNameFilterType.Contains && !loginRequest.ServerName.Contains(ServerArguments.ServerNameFilter)))
                    {
                        // Log request to which we're about to send a failure
                        TDSUtilities.Log(Arguments.Log, "Request", loginRequest);

                        // Prepare ERROR token with the reason
                        TDSErrorToken errorToken = new TDSErrorToken(18456, 1, 14, string.Format("Received server name \"{0}\", expected \"{1}\" using \"{2}\" algorithm", loginRequest.ServerName, ServerArguments.ServerNameFilter, ServerArguments.ServerNameFilterType), Arguments.ServerName);

                        // Log response
                        TDSUtilities.Log(Arguments.Log, "Response", errorToken);

                        // Serialize the errorToken token into the response packet
                        TDSMessage responseMessage = new TDSMessage(TDSMessageType.Response, errorToken);

                        // Prepare ERROR token with the final errorToken
                        errorToken = new TDSErrorToken(18456, 1, 14, "Connection is denied by server name filter", Arguments.ServerName);

                        // Log response
                        TDSUtilities.Log(Arguments.Log, "Response", errorToken);

                        // Serialize the errorToken token into the response packet
                        responseMessage.Add(errorToken);

                        // Create DONE token
                        TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Error);

                        // Log response
                        TDSUtilities.Log(Arguments.Log, "Response", doneToken);

                        // Serialize DONE token into the response packet
                        responseMessage.Add(doneToken);

                        // Return only a single message with the collection
                        return new TDSMessageCollection(responseMessage);
                    }
                }

                // Check if packet size filter is applied
                if (ServerArguments.PacketSizeFilter != null)
                {
                    // Check if requested packet size is the same as the filter specified
                    if (loginRequest.PacketSize != ServerArguments.PacketSizeFilter.Value)
                    {
                        // Log request to which we're about to send a failure
                        TDSUtilities.Log(Arguments.Log, "Request", loginRequest);

                        // Prepare ERROR token with the reason
                        TDSErrorToken errorToken = new TDSErrorToken(1919, 1, 14, string.Format("Received packet size \"{0}\", expected \"{1}\"", loginRequest.PacketSize, ServerArguments.PacketSizeFilter.Value), Arguments.ServerName);

                        // Log response
                        TDSUtilities.Log(Arguments.Log, "Response", errorToken);

                        // Serialize the errorToken token into the response packet
                        TDSMessage responseMessage = new TDSMessage(TDSMessageType.Response, errorToken);

                        // Prepare ERROR token with the final errorToken
                        errorToken = new TDSErrorToken(1919, 1, 14, "Connection is denied by packet size filter", Arguments.ServerName);

                        // Log response
                        TDSUtilities.Log(Arguments.Log, "Response", errorToken);

                        // Serialize the errorToken token into the response packet
                        responseMessage.Add(errorToken);

                        // Create DONE token
                        TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Error);

                        // Log response
                        TDSUtilities.Log(Arguments.Log, "Response", doneToken);

                        // Serialize DONE token into the response packet
                        responseMessage.Add(doneToken);

                        // Return only a single message with the collection
                        return new TDSMessageCollection(responseMessage);
                    }
                }

                // If we have an application name filter
                if (ServerArguments.ApplicationNameFilter != null)
                {
                    // If we are supposed to block this connection attempt
                    if (loginRequest.ApplicationName.Equals(ServerArguments.ApplicationNameFilter, System.StringComparison.OrdinalIgnoreCase))
                    {
                        // Log request to which we're about to send a failure
                        TDSUtilities.Log(Arguments.Log, "Request", loginRequest);

                        // Prepare ERROR token with the denial details
                        TDSErrorToken errorToken = new TDSErrorToken(18456, 1, 14, "Received application name: " + loginRequest.ApplicationName, Arguments.ServerName);

                        // Log response
                        TDSUtilities.Log(Arguments.Log, "Response", errorToken);

                        // Serialize the error token into the response packet
                        TDSMessage responseMessage = new TDSMessage(TDSMessageType.Response, errorToken);

                        // Prepare ERROR token for the final decision
                        errorToken = new TDSErrorToken(18456, 1, 14, "Connection is denied by application name filter", Arguments.ServerName);

                        // Log response
                        TDSUtilities.Log(Arguments.Log, "Response", errorToken);

                        // Serialize the error token into the response packet
                        responseMessage.Add(errorToken);

                        // Create DONE token
                        TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Error);

                        // Log response
                        TDSUtilities.Log(Arguments.Log, "Response", doneToken);

                        // Serialize DONE token into the response packet
                        responseMessage.Add(doneToken);

                        // Put a single message into the collection and return it
                        return new TDSMessageCollection(responseMessage);
                    }
                }
            }

            // Return login response from the base class
            return base.OnLogin7Request(session, request);
        }
Exemple #9
0
        protected virtual TDSMessageCollection OnFederatedAuthenticationInfoRequest(ITDSServerSession session)
        {
            TDSFedAuthInfoToken infoToken = new TDSFedAuthInfoToken();

            // Make fake info options
            TDSFedAuthInfoOptionSPN spn = new TDSFedAuthInfoOptionSPN(Arguments.ServerPrincipalName);
            TDSFedAuthInfoOptionSTSURL stsurl = new TDSFedAuthInfoOptionSTSURL(Arguments.StsUrl);
            infoToken.Options.Add(0, spn);
            infoToken.Options.Add(1, stsurl);

            // Log response
            TDSUtilities.Log(Arguments.Log, "Response", spn);
            TDSUtilities.Log(Arguments.Log, "Response", stsurl);

            TDSMessage infoMessage = new TDSMessage(TDSMessageType.FederatedAuthenticationInfo, infoToken);
            return new TDSMessageCollection(infoMessage);
        }
Exemple #10
0
 /// <summary>
 /// It is called when attention arrives
 /// </summary>
 public virtual TDSMessageCollection OnAttention(ITDSServerSession session, TDSMessage message)
 {
     // Delegate into the query engine
     return Engine.ExecuteAttention(session, message);
 }
        public virtual TDSMessageCollection OnFederatedAuthenticationTokenMessage(ITDSServerSession session, TDSMessage message)
        {
            // Get the FedAuthToken
            TDSFedAuthToken fedauthToken = message[0] as TDSFedAuthToken;

            // Log
            TDSUtilities.Log(Arguments.Log, "Request", fedauthToken);

            return(OnFederatedAuthenticationCompleted(session, fedauthToken.Token));
        }
        /// <summary>
        /// Handler for login request
        /// </summary>
        public virtual TDSMessageCollection OnLogin7Request(ITDSServerSession session, TDSMessage request)
        {
            // Inflate login7 request from the message
            TDSLogin7Token loginRequest = request[0] as TDSLogin7Token;

            // Log request
            TDSUtilities.Log(Arguments.Log, "Request", loginRequest);

            // Update server context
            session.Database = string.IsNullOrEmpty(loginRequest.Database) ? "master" : loginRequest.Database;

            // Resolve TDS version
            session.TDSVersion = TDSVersion.Resolve(TDSVersion.GetTDSVersion(Arguments.ServerVersion), loginRequest.TDSVersion);

            // Check for the TDS version
            TDSMessageCollection collection = CheckTDSVersion(session);

            // Check if any errors are posted
            if (collection != null)
            {
                // Version check needs to send own message hence we can't proceed
                return(collection);
            }

            // Indicates federated authentication
            bool bIsFedAuthConnection = false;

            // Federated authentication option to be used later
            TDSLogin7FedAuthOptionToken federatedAuthenticationOption = null;

            // Check if feature extension block is available
            if (loginRequest.FeatureExt != null)
            {
                // Go over the feature extension data
                foreach (TDSLogin7FeatureOptionToken option in loginRequest.FeatureExt)
                {
                    // Check option type
                    switch (option.FeatureID)
                    {
                    case TDSFeatureID.SessionRecovery:
                    {
                        // Enable session recovery
                        session.IsSessionRecoveryEnabled = true;

                        // Cast to session state options
                        TDSLogin7SessionRecoveryOptionToken sessionStateOption = option as TDSLogin7SessionRecoveryOptionToken;

                        // Inflate session state
                        (session as GenericTDSServerSession).Inflate(sessionStateOption.Initial, sessionStateOption.Current);

                        break;
                    }

                    case TDSFeatureID.FederatedAuthentication:
                    {
                        // Cast to federated authentication option
                        federatedAuthenticationOption = option as TDSLogin7FedAuthOptionToken;

                        // Mark authentication as federated
                        bIsFedAuthConnection = true;

                        // Validate federated authentication option
                        collection = CheckFederatedAuthenticationOption(session, option as TDSLogin7FedAuthOptionToken);

                        if (collection != null)
                        {
                            // Version error happened.
                            return(collection);
                        }

                        // Save the fed auth library to be used
                        (session as GenericTDSServerSession).FederatedAuthenticationLibrary = federatedAuthenticationOption.Library;

                        break;
                    }

                    default:
                    {
                        // Do nothing
                        break;
                    }
                    }
                }
            }

            // Check if SSPI authentication is requested
            if (loginRequest.OptionalFlags2.IntegratedSecurity == TDSLogin7OptionalFlags2IntSecurity.On)
            {
                // Delegate to SSPI authentication
                return(ContinueSSPIAuthentication(session, loginRequest.SSPI));
            }

            // If it is not a FedAuth connection or the server has been started up as not supporting FedAuth, just ignore the FeatureExtension
            // Yes unfortunately for the fake server, supporting FedAuth = Requiring FedAuth
            if (!bIsFedAuthConnection ||
                Arguments.FedAuthRequiredPreLoginOption == TdsPreLoginFedAuthRequiredOption.FedAuthNotRequired)
            {
                // We use SQL authentication
                session.SQLUserID = loginRequest.UserID;

                // Process with the SQL login.
                return(OnSqlAuthenticationCompleted(session));
            }
            else
            {
                // Fedauth feature extension is present and server has been started up as Requiring (or Supporting) FedAuth
                if (federatedAuthenticationOption.IsRequestingAuthenticationInfo)
                {
                    // Must provide client with more info before completing authentication
                    return(OnFederatedAuthenticationInfoRequest(session));
                }
                else
                {
                    return(OnFederatedAuthenticationCompleted(session, federatedAuthenticationOption.Token));
                }
            }
        }
        /// <summary>
        /// Handler for pre-login request
        /// </summary>
        public virtual TDSMessageCollection OnPreLoginRequest(ITDSServerSession session, TDSMessage request)
        {
            // Inflate pre-login request from the message
            TDSPreLoginToken preLoginRequest = request[0] as TDSPreLoginToken;

            // Log request
            TDSUtilities.Log(Arguments.Log, "Request", preLoginRequest);

            // Generate server response for encryption
            TDSPreLoginTokenEncryptionType serverResponse = TDSUtilities.GetEncryptionResponse(preLoginRequest.Encryption, Arguments.Encryption);

            // Update client state with encryption resolution
            session.Encryption = TDSUtilities.ResolveEncryption(preLoginRequest.Encryption, serverResponse);

            // Create TDS prelogin packet
            TDSPreLoginToken preLoginToken = new TDSPreLoginToken(Arguments.ServerVersion, serverResponse, false); // TDS server doesn't support MARS

            // Cache the recieved Nonce into the session
            (session as GenericTDSServerSession).ClientNonce = preLoginRequest.Nonce;

            // Check if the server has been started up as requiring FedAuth when choosing between SSPI and FedAuth
            if (Arguments.FedAuthRequiredPreLoginOption == TdsPreLoginFedAuthRequiredOption.FedAuthRequired)
            {
                if (preLoginRequest.FedAuthRequired == TdsPreLoginFedAuthRequiredOption.FedAuthRequired)
                {
                    // Set the FedAuthRequired option
                    preLoginToken.FedAuthRequired = TdsPreLoginFedAuthRequiredOption.FedAuthRequired;
                }

                // Keep the federated authentication required flag in the server session
                (session as GenericTDSServerSession).FedAuthRequiredPreLoginServerResponse = preLoginToken.FedAuthRequired;

                if (preLoginRequest.Nonce != null)
                {
                    // Generate Server Nonce
                    preLoginToken.Nonce = _GenerateRandomBytes(32);
                }
            }

            // Cache the server Nonce in a session
            (session as GenericTDSServerSession).ServerNonce = preLoginToken.Nonce;

            // Log response
            TDSUtilities.Log(Arguments.Log, "Response", preLoginToken);

            // Reset authentication information
            session.SQLUserID = null;
            session.NTUserAuthenticationContext = null;

            // Respond with a single message that contains only one token
            return(new TDSMessageCollection(new TDSMessage(TDSMessageType.Response, preLoginToken)));
        }
        /// <summary>
        /// Handler for login request
        /// </summary>
        public override TDSMessageCollection OnLogin7Request(ITDSServerSession session, TDSMessage request)
        {
            // Inflate login7 request from the message
            TDSLogin7Token loginRequest = request[0] as TDSLogin7Token;

            // Check if arguments are of the authenticating TDS server
            if (Arguments is AuthenticatingTDSServerArguments)
            {
                // Cast to authenticating TDS server arguments
                AuthenticatingTDSServerArguments ServerArguments = Arguments as AuthenticatingTDSServerArguments;

                // Check if we're still processing normal login
                if (ServerArguments.ApplicationIntentFilter != ApplicationIntentFilterType.All)
                {
                    // Check filter
                    if ((ServerArguments.ApplicationIntentFilter == ApplicationIntentFilterType.ReadOnly && loginRequest.TypeFlags.ReadOnlyIntent != TDSLogin7TypeFlagsReadOnlyIntent.ReadOnly) ||
                        (ServerArguments.ApplicationIntentFilter == ApplicationIntentFilterType.None))
                    {
                        // Log request to which we're about to send a failure
                        TDSUtilities.Log(Arguments.Log, "Request", loginRequest);

                        // Prepare ERROR token with the denial details
                        TDSErrorToken errorToken = new TDSErrorToken(18456, 1, 14, "Received application intent: " + loginRequest.TypeFlags.ReadOnlyIntent.ToString(), Arguments.ServerName);

                        // Log response
                        TDSUtilities.Log(Arguments.Log, "Response", errorToken);

                        // Serialize the error token into the response packet
                        TDSMessage responseMessage = new TDSMessage(TDSMessageType.Response, errorToken);

                        // Prepare ERROR token for the final decision
                        errorToken = new TDSErrorToken(18456, 1, 14, "Connection is denied by application intent filter", Arguments.ServerName);

                        // Log response
                        TDSUtilities.Log(Arguments.Log, "Response", errorToken);

                        // Serialize the error token into the response packet
                        responseMessage.Add(errorToken);

                        // Create DONE token
                        TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Error);

                        // Log response
                        TDSUtilities.Log(Arguments.Log, "Response", doneToken);

                        // Serialize DONE token into the response packet
                        responseMessage.Add(doneToken);

                        // Put a single message into the collection and return it
                        return(new TDSMessageCollection(responseMessage));
                    }
                }

                // Check if we're still processing normal login and there's a filter to check
                if (ServerArguments.ServerNameFilterType != ServerNameFilterType.None)
                {
                    // Check each algorithm
                    if ((ServerArguments.ServerNameFilterType == ServerNameFilterType.Equals && string.Compare(ServerArguments.ServerNameFilter, loginRequest.ServerName, true) != 0) ||
                        (ServerArguments.ServerNameFilterType == ServerNameFilterType.StartsWith && !loginRequest.ServerName.StartsWith(ServerArguments.ServerNameFilter)) ||
                        (ServerArguments.ServerNameFilterType == ServerNameFilterType.EndsWith && !loginRequest.ServerName.EndsWith(ServerArguments.ServerNameFilter)) ||
                        (ServerArguments.ServerNameFilterType == ServerNameFilterType.Contains && !loginRequest.ServerName.Contains(ServerArguments.ServerNameFilter)))
                    {
                        // Log request to which we're about to send a failure
                        TDSUtilities.Log(Arguments.Log, "Request", loginRequest);

                        // Prepare ERROR token with the reason
                        TDSErrorToken errorToken = new TDSErrorToken(18456, 1, 14, string.Format("Received server name \"{0}\", expected \"{1}\" using \"{2}\" algorithm", loginRequest.ServerName, ServerArguments.ServerNameFilter, ServerArguments.ServerNameFilterType), Arguments.ServerName);

                        // Log response
                        TDSUtilities.Log(Arguments.Log, "Response", errorToken);

                        // Serialize the errorToken token into the response packet
                        TDSMessage responseMessage = new TDSMessage(TDSMessageType.Response, errorToken);

                        // Prepare ERROR token with the final errorToken
                        errorToken = new TDSErrorToken(18456, 1, 14, "Connection is denied by server name filter", Arguments.ServerName);

                        // Log response
                        TDSUtilities.Log(Arguments.Log, "Response", errorToken);

                        // Serialize the errorToken token into the response packet
                        responseMessage.Add(errorToken);

                        // Create DONE token
                        TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Error);

                        // Log response
                        TDSUtilities.Log(Arguments.Log, "Response", doneToken);

                        // Serialize DONE token into the response packet
                        responseMessage.Add(doneToken);

                        // Return only a single message with the collection
                        return(new TDSMessageCollection(responseMessage));
                    }
                }

                // Check if packet size filter is applied
                if (ServerArguments.PacketSizeFilter != null)
                {
                    // Check if requested packet size is the same as the filter specified
                    if (loginRequest.PacketSize != ServerArguments.PacketSizeFilter.Value)
                    {
                        // Log request to which we're about to send a failure
                        TDSUtilities.Log(Arguments.Log, "Request", loginRequest);

                        // Prepare ERROR token with the reason
                        TDSErrorToken errorToken = new TDSErrorToken(1919, 1, 14, string.Format("Received packet size \"{0}\", expected \"{1}\"", loginRequest.PacketSize, ServerArguments.PacketSizeFilter.Value), Arguments.ServerName);

                        // Log response
                        TDSUtilities.Log(Arguments.Log, "Response", errorToken);

                        // Serialize the errorToken token into the response packet
                        TDSMessage responseMessage = new TDSMessage(TDSMessageType.Response, errorToken);

                        // Prepare ERROR token with the final errorToken
                        errorToken = new TDSErrorToken(1919, 1, 14, "Connection is denied by packet size filter", Arguments.ServerName);

                        // Log response
                        TDSUtilities.Log(Arguments.Log, "Response", errorToken);

                        // Serialize the errorToken token into the response packet
                        responseMessage.Add(errorToken);

                        // Create DONE token
                        TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Error);

                        // Log response
                        TDSUtilities.Log(Arguments.Log, "Response", doneToken);

                        // Serialize DONE token into the response packet
                        responseMessage.Add(doneToken);

                        // Return only a single message with the collection
                        return(new TDSMessageCollection(responseMessage));
                    }
                }

                // If we have an application name filter
                if (ServerArguments.ApplicationNameFilter != null)
                {
                    // If we are supposed to block this connection attempt
                    if (loginRequest.ApplicationName.Equals(ServerArguments.ApplicationNameFilter, System.StringComparison.OrdinalIgnoreCase))
                    {
                        // Log request to which we're about to send a failure
                        TDSUtilities.Log(Arguments.Log, "Request", loginRequest);

                        // Prepare ERROR token with the denial details
                        TDSErrorToken errorToken = new TDSErrorToken(18456, 1, 14, "Received application name: " + loginRequest.ApplicationName, Arguments.ServerName);

                        // Log response
                        TDSUtilities.Log(Arguments.Log, "Response", errorToken);

                        // Serialize the error token into the response packet
                        TDSMessage responseMessage = new TDSMessage(TDSMessageType.Response, errorToken);

                        // Prepare ERROR token for the final decision
                        errorToken = new TDSErrorToken(18456, 1, 14, "Connection is denied by application name filter", Arguments.ServerName);

                        // Log response
                        TDSUtilities.Log(Arguments.Log, "Response", errorToken);

                        // Serialize the error token into the response packet
                        responseMessage.Add(errorToken);

                        // Create DONE token
                        TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Error);

                        // Log response
                        TDSUtilities.Log(Arguments.Log, "Response", doneToken);

                        // Serialize DONE token into the response packet
                        responseMessage.Add(doneToken);

                        // Put a single message into the collection and return it
                        return(new TDSMessageCollection(responseMessage));
                    }
                }
            }

            // Return login response from the base class
            return(base.OnLogin7Request(session, request));
        }
Exemple #15
0
        /// <summary>
        /// Handler for SSPI request
        /// </summary>
        public virtual TDSMessageCollection OnSSPIRequest(ITDSServerSession session, TDSMessage request)
        {
            // Get the SSPI token
            TDSSSPIClientToken sspiRequest = request[0] as TDSSSPIClientToken;

            // Log request
            TDSUtilities.Log(Arguments.Log, "Request", sspiRequest.Payload);

            // Delegate to SSPI routine
            return ContinueSSPIAuthentication(session, sspiRequest.Payload);
        }
Exemple #16
0
        /// <summary>
        /// It is called when SQL batch request arrives
        /// </summary>
        public virtual TDSMessageCollection OnSQLBatchRequest(ITDSServerSession session, TDSMessage message)
        {
            // Delegate to the query engine
            TDSMessageCollection responseMessage = Engine.ExecuteBatch(session, message);

            // Check if session packet size is different than the engine packet size
            if (session.PacketSize != Arguments.PacketSize)
            {
                // Get the first message
                TDSMessage firstMessage = responseMessage[0];

                // Find DONE token in it
                int indexOfDone = firstMessage.IndexOf(firstMessage.Where(t => t is TDSDoneToken).First());

                // Create new packet size environment change token
                TDSEnvChangeToken envChange = new TDSEnvChangeToken(TDSEnvChangeTokenType.PacketSize, Arguments.PacketSize.ToString(), session.PacketSize.ToString());

                // Log response
                TDSUtilities.Log(Arguments.Log, "Response", envChange);

                // Insert env change before done token
                firstMessage.Insert(indexOfDone, envChange);

                // Update session with the new packet size
                session.PacketSize = (uint)Arguments.PacketSize;
            }

            return responseMessage;
        }
        /// <summary>
        /// It is called when SQL batch request arrives
        /// </summary>
        public virtual TDSMessageCollection OnSQLBatchRequest(ITDSServerSession session, TDSMessage message)
        {
            // Delegate to the query engine
            TDSMessageCollection responseMessage = Engine.ExecuteBatch(session, message);

            // Check if session packet size is different than the engine packet size
            if (session.PacketSize != Arguments.PacketSize)
            {
                // Get the first message
                TDSMessage firstMessage = responseMessage[0];

                // Find DONE token in it
                int indexOfDone = firstMessage.IndexOf(firstMessage.Where(t => t is TDSDoneToken).First());

                // Create new packet size environment change token
                TDSEnvChangeToken envChange = new TDSEnvChangeToken(TDSEnvChangeTokenType.PacketSize, Arguments.PacketSize.ToString(), session.PacketSize.ToString());

                // Log response
                TDSUtilities.Log(Arguments.Log, "Response", envChange);

                // Insert env change before done token
                firstMessage.Insert(indexOfDone, envChange);

                // Update session with the new packet size
                session.PacketSize = (uint)Arguments.PacketSize;
            }

            return(responseMessage);
        }
Exemple #18
0
        /// <summary>
        /// Advances one step in SSPI authentication sequence
        /// </summary>
        protected virtual TDSMessageCollection ContinueSSPIAuthentication(ITDSServerSession session, byte[] payload)
        {
            // Response to send to the client
            SSPIResponse response;

            try
            {
                // Check if we have an SSPI context
                if (session.NTUserAuthenticationContext == null)
                {
                    // This is the first step so we need to create a server context and initialize it
                    session.NTUserAuthenticationContext = SSPIContext.CreateServer();

                    // Run the first step of authentication
                    response = session.NTUserAuthenticationContext.StartServerAuthentication(payload);
                }
                else
                {
                    // Process SSPI request from the client
                    response = session.NTUserAuthenticationContext.ContinueServerAuthentication(payload);
                }
            }
            catch (Exception e)
            {
                // Prepare ERROR token with the reason
                TDSErrorToken errorToken = new TDSErrorToken(12345, 1, 15, "Failed to accept security SSPI context", Arguments.ServerName);

                // Log response
                TDSUtilities.Log(Arguments.Log, "Response", errorToken);

                // Serialize the error token into the response packet
                TDSMessage responseErrorMessage = new TDSMessage(TDSMessageType.Response, errorToken);

                // Prepare ERROR token with the final errorToken
                errorToken = new TDSErrorToken(12345, 1, 15, e.Message, Arguments.ServerName);

                // Log response
                TDSUtilities.Log(Arguments.Log, "Response", errorToken);

                // Serialize the error token into the response packet
                responseErrorMessage.Add(errorToken);

                // Create DONE token
                TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Error);

                // Log response
                TDSUtilities.Log(Arguments.Log, "Response", doneToken);

                // Serialize DONE token into the response packet
                responseErrorMessage.Add(doneToken);

                // Respond with a single message
                return new TDSMessageCollection(responseErrorMessage);
            }

            // Message collection to respond with
            TDSMessageCollection responseMessages = new TDSMessageCollection();

            // Check if there's a response
            if (response != null)
            {
                // Check if there's a payload
                if (response.Payload != null)
                {
                    // Create SSPI token
                    TDSSSPIToken sspiToken = new TDSSSPIToken(response.Payload);

                    // Log response
                    TDSUtilities.Log(Arguments.Log, "Response", sspiToken);

                    // Prepare response message with a single response token
                    responseMessages.Add(new TDSMessage(TDSMessageType.Response, sspiToken));

                    // Check if we can complete login
                    if (!response.IsFinal)
                    {
                        // Send the message to the client
                        return responseMessages;
                    }
                }
            }

            // Reset SQL user identifier since we're using NT authentication
            session.SQLUserID = null;

            // Append successfully authentication response
            responseMessages.AddRange(OnAuthenticationCompleted(session));

            // Return the message with SSPI token
            return responseMessages;
        }
Exemple #19
0
        /// <summary>
        /// Run one cycle of the parser to process incoming stream of data or dispatch outgoing data
        /// </summary>
        public void Run()
        {
            // Check if there's a message being inflated
            if (MessageBeingReceived == null)
            {
                // Create a new message
                MessageBeingReceived = new TDSMessage();
            }

            // Inflate the message using incoming stream
            // This call will use only as much data is it needs and leave everything else on the stream
            if (MessageBeingReceived.InflateClientRequest(Transport))
            {
                // Call into the server logics to process the message and generate the response
                TDSMessageCollection responseMessages = null;

                // Check the type of the packet
                switch (MessageBeingReceived.MessageType)
                {
                    case TDSMessageType.PreLogin:
                        {
                            // Call into the subscriber to process the packet
                            responseMessages = Server.OnPreLoginRequest(Session, MessageBeingReceived);
                            break;
                        }
                    case TDSMessageType.TDS7Login:
                        {
                            // Call into the subscriber to process the packet
                            responseMessages = Server.OnLogin7Request(Session, MessageBeingReceived);

                            // Check if encryption needs to be turned off
                            if (Session.Encryption == TDSEncryptionType.LoginOnly)
                            {
                                // Disable transport encryption
                                DisableTransportEncryption();
                            }

                            break;
                        }
                    case TDSMessageType.SSPI:
                        {
                            // Call into the subscriber to process the packet
                            responseMessages = Server.OnSSPIRequest(Session, MessageBeingReceived);
                            break;
                        }
                    case TDSMessageType.SQLBatch:
                        {
                            // Call into the subscriber to process the packet
                            responseMessages = Server.OnSQLBatchRequest(Session, MessageBeingReceived);
                            break;
                        }
                    case TDSMessageType.Attention:
                        {
                            // Call into the subscriber to process the packet
                            responseMessages = Server.OnAttention(Session, MessageBeingReceived);
                            break;
                        }
                    case TDSMessageType.FederatedAuthenticationToken:
                        {
                            // Call into the subscriber to process the packet
                            responseMessages = Server.OnFederatedAuthenticationTokenMessage(Session, MessageBeingReceived);
                            break;
                        }
                    default:
                        {
                            // New code is needed to process this message
                            throw new NotImplementedException(string.Format("Handler of TDS message \"{0}\" is not implemented", MessageBeingReceived.MessageType));
                        }
                }

                // Check if TDS packet size changed
                if (Session.PacketSize != Transport.PacketSize)
                {
                    // Update packet size
                    Transport.PacketSize = Session.PacketSize;
                }

                // Send all messages to the client
                responseMessages.Deflate(Transport);

                // Check the type of message just sent
                if (MessageBeingReceived.MessageType == TDSMessageType.PreLogin)
                {
                    // Check encryption settings on the session
                    if (Session.Encryption == TDSEncryptionType.LoginOnly || Session.Encryption == TDSEncryptionType.Full)
                    {
                        // Enable server side encryption
                        EnableServerTransportEncryption(Session.EncryptionCertificate);
                    }
                }

                // Reset the current message because it's complete
                // It would also trigger creation of the next message during the next cycle
                MessageBeingReceived = null;
            }
        }
Exemple #20
0
        protected virtual TDSMessageCollection OnAuthenticationCompleted(ITDSServerSession session)
        {
            // Create new database environment change token
            TDSEnvChangeToken envChange = new TDSEnvChangeToken(TDSEnvChangeTokenType.Database, session.Database, "master");

            // Log response
            TDSUtilities.Log(Arguments.Log, "Response", envChange);

            // Serialize the login token into the response packet
            TDSMessage responseMessage = new TDSMessage(TDSMessageType.Response, envChange);

            // Create information token on the change
            TDSInfoToken infoToken = new TDSInfoToken(5701, 2, 0, string.Format("Changed database context to '{0}'", envChange.NewValue), Arguments.ServerName);

            // Log response
            TDSUtilities.Log(Arguments.Log, "Response", infoToken);

            // Serialize the login token into the response packet
            responseMessage.Add(infoToken);

            // Create new collation change token
            envChange = new TDSEnvChangeToken(TDSEnvChangeTokenType.SQLCollation, (session as GenericTDSServerSession).Collation);

            // Log response
            TDSUtilities.Log(Arguments.Log, "Response", envChange);

            // Serialize the login token into the response packet
            responseMessage.Add(envChange);

            // Create new language change token
            envChange = new TDSEnvChangeToken(TDSEnvChangeTokenType.Language, LanguageString.ToString((session as GenericTDSServerSession).Language));

            // Log response
            TDSUtilities.Log(Arguments.Log, "Response", envChange);

            // Serialize the login token into the response packet
            responseMessage.Add(envChange);

            // Create information token on the change
            infoToken = new TDSInfoToken(5703, 1, 0, string.Format("Changed language setting to {0}", envChange.NewValue), Arguments.ServerName);

            // Log response
            TDSUtilities.Log(Arguments.Log, "Response", infoToken);

            // Serialize the login token into the response packet
            responseMessage.Add(infoToken);

            // Create new packet size environment change token
            envChange = new TDSEnvChangeToken(TDSEnvChangeTokenType.PacketSize, Arguments.PacketSize.ToString(), Arguments.PacketSize.ToString());

            // Log response
            TDSUtilities.Log(Arguments.Log, "Response", envChange);

            // Serialize the login token into the response packet
            responseMessage.Add(envChange);

            // Update session packet size
            session.PacketSize = (uint)Arguments.PacketSize;

            // Create login acknowledgnment packet
            TDSLoginAckToken loginResponseToken = new TDSLoginAckToken(Arguments.ServerVersion, session.TDSVersion, TDSLogin7TypeFlagsSQL.SQL, "Microsoft SQL Server");  // Otherwise SNAC yields E_FAIL

            // Log response
            TDSUtilities.Log(Arguments.Log, "Response", loginResponseToken);

            // Serialize the login token into the response packet
            responseMessage.Add(loginResponseToken);

            // Check if session recovery is enabled
            if (session.IsSessionRecoveryEnabled)
            {
                // Create Feature extension Ack token
                TDSFeatureExtAckToken featureExtActToken = new TDSFeatureExtAckToken(new TDSFeatureExtAckSessionStateOption((session as GenericTDSServerSession).Deflate()));

                // Log response
                TDSUtilities.Log(Arguments.Log, "Response", featureExtActToken);

                // Serialize feature extnesion token into the response
                responseMessage.Add(featureExtActToken);
            }

            // Create DONE token
            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final);

            // Log response
            TDSUtilities.Log(Arguments.Log, "Response", doneToken);

            // Serialize DONE token into the response packet
            responseMessage.Add(doneToken);

            // Wrap a single message in a collection
            return new TDSMessageCollection(responseMessage);
        }
Exemple #21
0
        /// <summary>
        /// Handle attention from the client
        /// </summary>
        public TDSMessageCollection ExecuteAttention(ITDSServerSession session, TDSMessage request)
        {
            // Create attention DONE token
            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Attention);

            // Log response
            TDSUtilities.Log(Log, "Response", doneToken);

            // Return a single message with DONE token only
            return new TDSMessageCollection(new TDSMessage(TDSMessageType.Response, doneToken));
        }
Exemple #22
0
        /// <summary>
        /// It is called when SQL batch request arrives
        /// </summary>
        /// <param name="message">TDS message recieved</param>
        /// <returns>TDS message to respond with</returns>
        public override TDSMessageCollection OnSQLBatchRequest(ITDSServerSession session, TDSMessage request)
        {
            // Delegate to the base class to produce the response first
            TDSMessageCollection batchResponse = base.OnSQLBatchRequest(session, request);

            // Check if arguments are of routing server
            if (Arguments is RoutingTDSServerArguments)
            {
                // Cast to routing server arguments
                RoutingTDSServerArguments ServerArguments = Arguments as RoutingTDSServerArguments;

                // Check routing condition
                if (ServerArguments.RouteOnPacket == TDSMessageType.SQLBatch)
                {
                    // Construct routing token
                    TDSPacketToken routingToken = CreateRoutingToken();

                    // Log response
                    TDSUtilities.Log(Arguments.Log, "Response", routingToken);

                    // Insert the routing token at the beginning of the response
                    batchResponse[0].Insert(0, routingToken);
                }
                else
                {
                    // Get the first response message
                    TDSMessage responseMessage = batchResponse[0];

                    // Reset the content of the first message
                    responseMessage.Clear();

                    // Prepare ERROR token with the denial details
                    responseMessage.Add(new TDSErrorToken(11111, 1, 14, "Client should have been routed by now", Arguments.ServerName));

                    // Log response
                    TDSUtilities.Log(Arguments.Log, "Response", responseMessage[0]);

                    // Prepare DONE token
                    responseMessage.Add(new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Error));

                    // Log response
                    TDSUtilities.Log(Arguments.Log, "Response", responseMessage[1]);
                }
            }

            // Register only one message with the collection
            return batchResponse;
        }
Exemple #23
0
        /// <summary>
        /// Execute the query and produce a response
        /// </summary>
        public TDSMessageCollection ExecuteBatch(ITDSServerSession session, TDSMessage request)
        {
            // Get the batch from the tokens
            TDSSQLBatchToken batchRequest = request[0] as TDSSQLBatchToken;

            // Log request
            TDSUtilities.Log(Log, "Request", batchRequest);

            // Increase the counter of connection reset requests if the message contains the proper flags
            if (request.IsResetConnectionRequestSet || request.IsResetConnectionSkipTransactionRequestSet)
            {
                session.ConnectionResetRequestCount++;
            }

            // Prepare response message
            TDSMessage responseMessage = new TDSMessage(TDSMessageType.Response);

            // Prepare query text
            string lowerBatchText = batchRequest.Text.ToLowerInvariant();

            // Check query
            if (lowerBatchText.Contains("serverproperty('servername')"))  // SELECT convert(nvarchar(256), ServerProperty('ServerName'))
            {
                // Delegate to server name query
                responseMessage = _PrepareServerNameResponse(session);
            }
            if (lowerBatchText.Contains("serverproperty('machinename')"))  // SELECT convert(nvarchar(256), ServerProperty('MachineName'))
            {
                // Delegate to server name query
                responseMessage = _PrepareMachineNameResponse(session);
            }
            else if (lowerBatchText.Contains("serverproperty('instancename')"))  // SELECT convert(nvarchar(256), ServerProperty('InstanceName'))
            {
                // Delegate to instance name query
                responseMessage = _PrepareInstanceNameResponse(session);
            }
            else if (lowerBatchText.Contains("serverproperty('ishadrenabled')"))  // SELECT convert(bit, ServerProperty('IsHADREnabled')) 
            {
                // Delegate to HADRon query
                responseMessage = _PrepareIsHADRResponse(session);
            }
            else if (lowerBatchText.Contains("serverproperty('engineedition')"))  // SELECT convert(int, ServerProperty('EngineEdition'))
            {
                // Delegate to Azure query
                responseMessage = _PrepareIsAzure(session);
            }
            else if (lowerBatchText.Contains("serverproperty('islocaldb')"))  // SELECT convert(bit, ServerProperty('IsLocalDB')) 
            {
                // Delegate to Local DB query
                responseMessage = _PrepareIsLocalDB(session);
            }
            else if (lowerBatchText.Contains("serverproperty('istestsqlserver')"))  // SELECT convert(bit, ServerProperty('IsTestSQLServer')) 
            {
                // Delegate to test SQL Server query response
                responseMessage = _PrepareIsTestSQLServerResponse(session);
            }
            else if (lowerBatchText.Contains("serverproperty('testsqlserverclass')"))  // SELECT convert(nvarchar(256), ServerProperty('TestSQLServerClass')) 
            {
                // Delegate to test SQL Server class response
                responseMessage = _PrepareTestSQLServerClassResponse(session);
            }
            else if (lowerBatchText.Contains("dm_exec_sessions")
                && lowerBatchText.Contains("login_name")
                && lowerBatchText.Contains("nt_domain")
                && lowerBatchText.Contains("nt_user_name")
                && lowerBatchText.Contains("session_id"))  // SELECT login_name, nt_domain, nt_user_name FROM sys.dm_exec_sessions WHERE session_id = @@spid
            {
                // Delegate to session user query
                responseMessage = _PrepareSessionUserResponse(session);
            }
            else if (lowerBatchText.Contains("sp_oledb_ro_usrname"))  // exec [sys].sp_oledb_ro_usrname
            {
                // Delegate to OLE DB query
                responseMessage = _PrepareOleDbReadOnlyUserName(session);
            }
            else if (lowerBatchText.Contains("physical_net_transport")
                && lowerBatchText.Contains("local_net_address")
                && lowerBatchText.Contains("local_tcp_port"))  // SELECT convert(nvarchar(40), ConnectionProperty('physical_net_transport')), convert(varchar(48), ConnectionProperty('local_net_address')), convert(int, ConnectionProperty('local_tcp_port'))
            {
                // Delegate to connection information query
                responseMessage = _PrepareConnectionInfoResponse(session);
            }
            else if (lowerBatchText.Contains("dm_exec_connections")
                && lowerBatchText.Contains("encrypt_option")
                && lowerBatchText.Contains("session_id"))  // SELECT TOP (1) [encrypt_option] FROM [sys].[dm_exec_connections] WHERE [session_id] = @@SPID
            {
                // Delegate to encryption information query
                responseMessage = _PrepareEncryptionInfoResponse(session);
            }
            else if (lowerBatchText.Contains("select 1"))  // SELECT 1
            {
                // Delegate to server ping response
                responseMessage = _PreparePingResponse(session);
            }
            else if (lowerBatchText.Contains("name")
                && lowerBatchText.Contains("state")
                && lowerBatchText.Contains("databases")
                && lowerBatchText.Contains("db_name"))  // SELECT [name], [state] FROM [sys].[databases] WHERE [name] = db_name()
            {
                // Delegate to current database response
                responseMessage = _PrepareDatabaseResponse(session);
            }
            else if (lowerBatchText.Contains("dbcc")
                && lowerBatchText.Contains("tracestatus"))   // dbcc tracestatus()
            {
                // Delegate to current configuration response
                responseMessage = _PrepareConfigurationResponse(session);
            }
            else if (lowerBatchText.Contains("connectionproperty('sp_reset_connection_count')"))  // select CONNECTIONPROPERTY('sp_reset_connection_count')
            {
                // Delegate to reset connection request response
                responseMessage = _PrepareConnectionResetRequestCountResponse(session);
            }
            else if (lowerBatchText.Contains("select")
                && lowerBatchText.Contains("convert")
                && lowerBatchText.Contains("nvarchar(128)")
                && lowerBatchText.Contains("@@spid"))  // SELECT convert(nvarchar(128), @@SPID)
            {
                // Delegate to reset connection request response
                responseMessage = _PrepareSPIDResponse(session);
            }
            else if (lowerBatchText.Contains("select")
                && lowerBatchText.Contains("auth_scheme")
                && lowerBatchText.Contains("dm_exec_connections")) //select top (1) [auth_scheme] from [sys].[dm_exec_connections] where [session_id] = @@spid
            {
                // Delegate to reset connection request response
                responseMessage = _PrepareAuthSchemeResponse(session);
            }
            else if (lowerBatchText.Contains("select")
                && lowerBatchText.Contains("ansi_defaults")
                && lowerBatchText.Contains("dm_exec_sessions")
                && lowerBatchText.Contains("session_id")
                && lowerBatchText.Contains("@@spid"))  // SELECT TOP (1) [ansi_defaults] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID
            {
                // Delegate session property query
                responseMessage = _PrepareAnsiDefaultsResponse(session);
            }
            else if (lowerBatchText.Contains("select")
                && lowerBatchText.Contains("ansi_null_dflt_on")
                && lowerBatchText.Contains("dm_exec_sessions")
                && lowerBatchText.Contains("session_id")
                && lowerBatchText.Contains("@@spid"))  // SELECT TOP (1) [ansi_null_dflt_on] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID
            {
                // Delegate session property query
                responseMessage = _PrepareAnsiNullDefaultOnResponse(session);
            }
            else if (lowerBatchText.Contains("select")
                && lowerBatchText.Contains("ansi_nulls")
                && lowerBatchText.Contains("dm_exec_sessions")
                && lowerBatchText.Contains("session_id")
                && lowerBatchText.Contains("@@spid"))  // SELECT TOP (1) [ansi_nulls] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID
            {
                // Delegate session property query
                responseMessage = _PrepareAnsiNullsResponse(session);
            }
            else if (lowerBatchText.Contains("select")
                && lowerBatchText.Contains("ansi_padding")
                && lowerBatchText.Contains("dm_exec_sessions")
                && lowerBatchText.Contains("session_id")
                && lowerBatchText.Contains("@@spid"))  // SELECT TOP (1) [ansi_padding] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID
            {
                // Delegate session property query
                responseMessage = _PrepareAnsiPaddingResponse(session);
            }
            else if (lowerBatchText.Contains("select")
                && lowerBatchText.Contains("ansi_warnings")
                && lowerBatchText.Contains("dm_exec_sessions")
                && lowerBatchText.Contains("session_id")
                && lowerBatchText.Contains("@@spid"))  // SELECT TOP (1) [ansi_warnings] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID
            {
                // Delegate session property query
                responseMessage = _PrepareAnsiWarningsResponse(session);
            }
            else if (lowerBatchText.Contains("select")
                && lowerBatchText.Contains("arithabort")
                && lowerBatchText.Contains("dm_exec_sessions")
                && lowerBatchText.Contains("session_id")
                && lowerBatchText.Contains("@@spid"))  // SELECT TOP (1) [arithabort] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID
            {
                // Delegate session property query
                responseMessage = _PrepareArithAbortResponse(session);
            }
            else if (lowerBatchText.Contains("select")
                && lowerBatchText.Contains("concat_null_yields_null")
                && lowerBatchText.Contains("dm_exec_sessions")
                && lowerBatchText.Contains("session_id")
                && lowerBatchText.Contains("@@spid"))  // SELECT TOP (1) [concat_null_yields_null] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID
            {
                // Delegate session property query
                responseMessage = _PrepareConcatNullYieldsNullResponse(session);
            }
            else if (lowerBatchText.Contains("select")
                && lowerBatchText.Contains("date_first")
                && lowerBatchText.Contains("dm_exec_sessions")
                && lowerBatchText.Contains("session_id")
                && lowerBatchText.Contains("@@spid"))  // SELECT TOP (1) [date_first] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID
            {
                // Delegate session property query
                responseMessage = _PrepareDateFirstResponse(session);
            }
            else if (lowerBatchText.Contains("select")
                && lowerBatchText.Contains("date_format")
                && lowerBatchText.Contains("dm_exec_sessions")
                && lowerBatchText.Contains("session_id")
                && lowerBatchText.Contains("@@spid"))  // SELECT TOP (1) [date_format] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID
            {
                // Delegate session property query
                responseMessage = _PrepareDateFormatResponse(session);
            }
            else if (lowerBatchText.Contains("select")
                && lowerBatchText.Contains("deadlock_priority")
                && lowerBatchText.Contains("dm_exec_sessions")
                && lowerBatchText.Contains("session_id")
                && lowerBatchText.Contains("@@spid"))  // SELECT TOP (1) [deadlock_priority] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID
            {
                // Delegate session property query
                responseMessage = _PrepareDeadlockPriorityResponse(session);
            }
            else if (lowerBatchText.Contains("select")
                && lowerBatchText.Contains("language")
                && lowerBatchText.Contains("dm_exec_sessions")
                && lowerBatchText.Contains("session_id")
                && lowerBatchText.Contains("@@spid"))  // SELECT TOP (1) [language] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID
            {
                // Delegate session property query
                responseMessage = _PrepareLanguageResponse(session);
            }
            else if (lowerBatchText.Contains("select")
                && lowerBatchText.Contains("lock_timeout")
                && lowerBatchText.Contains("dm_exec_sessions")
                && lowerBatchText.Contains("session_id")
                && lowerBatchText.Contains("@@spid"))  // SELECT TOP (1) [lock_timeout] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID
            {
                // Delegate session property query
                responseMessage = _PrepareLockTimeoutResponse(session);
            }
            else if (lowerBatchText.Contains("select")
                && lowerBatchText.Contains("quoted_identifier")
                && lowerBatchText.Contains("dm_exec_sessions")
                && lowerBatchText.Contains("session_id")
                && lowerBatchText.Contains("@@spid"))  // SELECT TOP (1) [quoted_identifier] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID
            {
                // Delegate session property query
                responseMessage = _PrepareQuotedIdentifierResponse(session);
            }
            else if (lowerBatchText.Contains("select")
                && lowerBatchText.Contains("text_size")
                && lowerBatchText.Contains("dm_exec_sessions")
                && lowerBatchText.Contains("session_id")
                && lowerBatchText.Contains("@@spid"))  // SELECT TOP (1) [text_size] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID
            {
                // Delegate session property query
                responseMessage = _PrepareTextSizeResponse(session);
            }
            else if (lowerBatchText.Contains("select")
                && lowerBatchText.Contains("transaction_isolation_level")
                && lowerBatchText.Contains("dm_exec_sessions")
                && lowerBatchText.Contains("session_id")
                && lowerBatchText.Contains("@@spid"))  // SELECT TOP (1) [transaction_isolation_level] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID
            {
                // Delegate session property query
                responseMessage = _PrepareTransactionIsolationLevelResponse(session);
            }
            else if (lowerBatchText.Contains("select")
                && lowerBatchText.Contains("@@options"))  // SELECT @@OPTIONS
            {
                // Delegate session property query
                responseMessage = _PrepareOptionsResponse(session);
            }
            else if (lowerBatchText.Contains("select")
                && lowerBatchText.Contains("context_info()"))  // SELECT CONTEXT_INFO() 
            {
                // Delegate session property query
                responseMessage = _PrepareContextInfoResponse(session);
            }
            else
            {
                // Create an info token that contains the query received
                TDSInfoToken infoToken = new TDSInfoToken(2012, 2, 0, lowerBatchText);

                // Log response
                TDSUtilities.Log(Log, "Response", infoToken);

                // Serialize DONE token into the response packet
                responseMessage.Add(infoToken);

                // Create an info token to let client know that we don't recognize this query
                infoToken = new TDSInfoToken(2012, 2, 0, "Received query is not recognized by the query engine. Please ask a very specific question.");

                // Log response
                TDSUtilities.Log(Log, "Response", infoToken);

                // Serialize DONE token into the response packet
                responseMessage.Add(infoToken);

                // Create generic DONE token
                TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final);

                // Log response
                TDSUtilities.Log(Log, "Response", doneToken);

                // Serialize DONE token into the response packet
                responseMessage.Add(doneToken);
            }

            // Response collection will contain only one message
            return new TDSMessageCollection(responseMessage);
        }
Exemple #24
0
        /// <summary>
        /// Handler for pre-login request
        /// </summary>
        public virtual TDSMessageCollection OnPreLoginRequest(ITDSServerSession session, TDSMessage request)
        {
            // Inflate pre-login request from the message
            TDSPreLoginToken preLoginRequest = request[0] as TDSPreLoginToken;

            // Log request
            TDSUtilities.Log(Arguments.Log, "Request", preLoginRequest);

            // Generate server response for encryption
            TDSPreLoginTokenEncryptionType serverResponse = TDSUtilities.GetEncryptionResponse(preLoginRequest.Encryption, Arguments.Encryption);

            // Update client state with encryption resolution
            session.Encryption = TDSUtilities.ResolveEncryption(preLoginRequest.Encryption, serverResponse);

            // Create TDS prelogin packet
            TDSPreLoginToken preLoginToken = new TDSPreLoginToken(Arguments.ServerVersion, serverResponse, false); // TDS server doesn't support MARS

            // Cache the recieved Nonce into the session
            (session as GenericTDSServerSession).ClientNonce = preLoginRequest.Nonce;

            // Check if the server has been started up as requiring FedAuth when choosing between SSPI and FedAuth
            if (Arguments.FedAuthRequiredPreLoginOption == TdsPreLoginFedAuthRequiredOption.FedAuthRequired)
            {
                if (preLoginRequest.FedAuthRequired == TdsPreLoginFedAuthRequiredOption.FedAuthRequired)
                {
                    // Set the FedAuthRequired option
                    preLoginToken.FedAuthRequired = TdsPreLoginFedAuthRequiredOption.FedAuthRequired;
                }

                // Keep the federated authentication required flag in the server session
                (session as GenericTDSServerSession).FedAuthRequiredPreLoginServerResponse = preLoginToken.FedAuthRequired;

                if (preLoginRequest.Nonce != null)
                {
                    // Generate Server Nonce
                    preLoginToken.Nonce = _GenerateRandomBytes(32);
                }
            }

            // Cache the server Nonce in a session
            (session as GenericTDSServerSession).ServerNonce = preLoginToken.Nonce;

            // Log response
            TDSUtilities.Log(Arguments.Log, "Response", preLoginToken);

            // Reset authentication information
            session.SQLUserID = null;
            session.NTUserAuthenticationContext = null;

            // Respond with a single message that contains only one token
            return new TDSMessageCollection(new TDSMessage(TDSMessageType.Response, preLoginToken));
        }
Exemple #25
0
        /// <summary>
        /// Handler for login request
        /// </summary>
        public virtual TDSMessageCollection OnLogin7Request(ITDSServerSession session, TDSMessage request)
        {
            // Inflate login7 request from the message
            TDSLogin7Token loginRequest = request[0] as TDSLogin7Token;

            // Log request
            TDSUtilities.Log(Arguments.Log, "Request", loginRequest);

            // Update server context
            session.Database = string.IsNullOrEmpty(loginRequest.Database) ? "master" : loginRequest.Database;

            // Resolve TDS version
            session.TDSVersion = TDSVersion.Resolve(TDSVersion.GetTDSVersion(Arguments.ServerVersion), loginRequest.TDSVersion);

            // Check for the TDS version
            TDSMessageCollection collection = CheckTDSVersion(session);

            // Check if any errors are posted
            if (collection != null)
            {
                // Version check needs to send own message hence we can't proceed
                return collection;
            }

            // Indicates federated authentication
            bool bIsFedAuthConnection = false;

            // Federated authentication option to be used later
            TDSLogin7FedAuthOptionToken federatedAuthenticationOption = null;

            // Check if feature extension block is available
            if (loginRequest.FeatureExt != null)
            {
                // Go over the feature extension data
                foreach (TDSLogin7FeatureOptionToken option in loginRequest.FeatureExt)
                {
                    // Check option type
                    switch (option.FeatureID)
                    {
                        case TDSFeatureID.SessionRecovery:
                            {
                                // Enable session recovery
                                session.IsSessionRecoveryEnabled = true;

                                // Cast to session state options
                                TDSLogin7SessionRecoveryOptionToken sessionStateOption = option as TDSLogin7SessionRecoveryOptionToken;

                                // Inflate session state
                                (session as GenericTDSServerSession).Inflate(sessionStateOption.Initial, sessionStateOption.Current);

                                break;
                            }
                        case TDSFeatureID.FederatedAuthentication:
                            {
                                // Cast to federated authentication option
                                federatedAuthenticationOption = option as TDSLogin7FedAuthOptionToken;

                                // Mark authentication as federated
                                bIsFedAuthConnection = true;

                                // Validate federated authentication option
                                collection = CheckFederatedAuthenticationOption(session, option as TDSLogin7FedAuthOptionToken);

                                if (collection != null)
                                {
                                    // Version error happened.
                                    return collection;
                                }

                                // Save the fed auth library to be used
                                (session as GenericTDSServerSession).FederatedAuthenticationLibrary = federatedAuthenticationOption.Library;

                                break;
                            }
                        default:
                            {
                                // Do nothing
                                break;
                            }
                    }
                }
            }

            // Check if SSPI authentication is requested
            if (loginRequest.OptionalFlags2.IntegratedSecurity == TDSLogin7OptionalFlags2IntSecurity.On)
            {
                // Delegate to SSPI authentication
                return ContinueSSPIAuthentication(session, loginRequest.SSPI);
            }

            // If it is not a FedAuth connection or the server has been started up as not supporting FedAuth, just ignore the FeatureExtension
            // Yes unfortunately for the fake server, supporting FedAuth = Requiring FedAuth
            if (!bIsFedAuthConnection
                || Arguments.FedAuthRequiredPreLoginOption == TdsPreLoginFedAuthRequiredOption.FedAuthNotRequired)
            {
                // We use SQL authentication
                session.SQLUserID = loginRequest.UserID;

                // Process with the SQL login.
                return OnSqlAuthenticationCompleted(session);
            }
            else
            {
                // Fedauth feature extension is present and server has been started up as Requiring (or Supporting) FedAuth
                if (federatedAuthenticationOption.IsRequestingAuthenticationInfo)
                {
                    // Must provide client with more info before completing authentication
                    return OnFederatedAuthenticationInfoRequest(session);
                }
                else
                {
                    return OnFederatedAuthenticationCompleted(session, federatedAuthenticationOption.Token);
                }
            }
        }
Exemple #26
0
        /// <summary>
        /// Send a request to the TDS server
        /// </summary>
        private void _WriteRequest(TDSMessage requestMessage)
        {
            // Check if TDS packet size changed
            if (Client.Context.PacketSize != Transport.PacketSize)
            {
                // Update packet size
                Transport.PacketSize = Client.Context.PacketSize;
            }

            // Check if there is  request to send
            if (requestMessage != null)
            {
                // Dispatch the request to the server
                requestMessage.Deflate(Transport);

                // Log event
                Log("Sent a request and entered \"{0}\"", Client.State);
            }
            else
            {
                // Log event
                Log("Client entered \"{0}\"", Client.State);
            }
        }
Exemple #27
0
        /// <summary>
        /// Handler for login request
        /// </summary>
        public override TDSMessageCollection OnPreLoginRequest(ITDSServerSession session, TDSMessage request)
        {
            // Get the collection from a valid On PreLogin Request
            TDSMessageCollection preLoginCollection = base.OnPreLoginRequest(session, request);

            // Check if arguments are of the Federated Authentication server
            if (Arguments is FederatedAuthenticationNegativeTDSServerArguments)
            {
                // Cast to federated authentication server arguments
                FederatedAuthenticationNegativeTDSServerArguments ServerArguments = Arguments as FederatedAuthenticationNegativeTDSServerArguments;

                // Find the is token carrying on TDSPreLoginToken
                TDSPreLoginToken preLoginToken = preLoginCollection.Find(message => message.Exists(packetToken => packetToken is TDSPreLoginToken)).
                                                 Find(packetToken => packetToken is TDSPreLoginToken) as TDSPreLoginToken;

                switch (ServerArguments.Scenario)
                {
                case FederatedAuthenticationNegativeTDSScenarioType.NonceMissingInFedAuthPreLogin:
                {
                    // If we have the prelogin token
                    if (preLoginToken != null && preLoginToken.Nonce != null)
                    {
                        // Nullify the nonce from the Token
                        preLoginToken.Nonce = null;
                    }

                    break;
                }

                case FederatedAuthenticationNegativeTDSScenarioType.InvalidB_FEDAUTHREQUIREDResponse:
                {
                    // If we have the prelogin token
                    if (preLoginToken != null)
                    {
                        // Set an illegal value for B_FEDAUTHREQURED
                        preLoginToken.FedAuthRequired = TdsPreLoginFedAuthRequiredOption.Illegal;
                    }

                    break;
                }
                }
            }

            // Return the collection
            return(preLoginCollection);
        }