Esempio n. 1
0
        public void Restart()
        {
            try
            {
                switch (v_SQLType)
                {
                case DB_Type.MySQL:
                {
                    MySQLConn.Close();
                    MySQLConn.Dispose();
                    MySQLConn = new MySqlConnection(string.Format("Server={0};Port={4};User ID={1};Password={2};Database={3};Compress=false;Connection Timeout=1;", SQLHost, SQLUser, SQLPass, SQLDBName, SQLPort));
                    MySQLConn.Open();
                    if (MySQLConn.State == ConnectionState.Open)
                    {
                        SQLMessage?.Invoke(EMessages.ID_Message, "MySQL Connection restarted!");
                    }
                    else
                    {
                        SQLMessage?.Invoke(EMessages.ID_Error, "Unable to restart MySQL connection.");
                    }

                    break;
                }
                }
            }
            catch (MySqlException e)
            {
                SQLMessage?.Invoke(EMessages.ID_Error, "MySQL Connection Error [" + e.Message + "]");
            }
        }
Esempio n. 2
0
        public static IBaseMessage CreateInstance(ChatMessageSaveType type)
        {
            IBaseMessage msg;

            switch (type)
            {
            case ChatMessageSaveType.SearchEngine:
                msg = ElasticMessage.Instance;
                break;

            case ChatMessageSaveType.SQL:
                msg = new SQLMessage();
                break;

            case ChatMessageSaveType.Queue:
                msg = new QueueMessage();
                break;

            case ChatMessageSaveType.Main:
                msg = new QueueMessage();
                break;

            default:
                msg = new SQLMessage();
                break;
            }
            return(msg);
        }
Esempio n. 3
0
        private void LoadSSPILibrary()
        {
            if (TdsParserStateObjectFactory.UseManagedSNI)
            {
                return;
            }
            // Outer check so we don't acquire lock once it's loaded.
            if (!s_fSSPILoaded)
            {
                lock (s_tdsParserLock)
                {
                    // re-check inside lock
                    if (!s_fSSPILoaded)
                    {
                        // use local for ref param to defer setting s_maxSSPILength until we know the call succeeded.
                        uint maxLength = 0;

                        if (0 != SNINativeMethodWrapper.SNISecInitPackage(ref maxLength))
                        {
                            SSPIError(SQLMessage.SSPIInitializeError(), TdsEnums.INIT_SSPI_PACKAGE);
                        }

                        s_maxSSPILength = maxLength;
                        s_fSSPILoaded   = true;
                    }
                }
            }

            if (s_maxSSPILength > int.MaxValue)
            {
                throw SQL.InvalidSSPIPacketSize();   // SqlBu 332503
            }
        }
Esempio n. 4
0
        /// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlException.xml' path='docs/members[@name="SqlException"]/ToString/*' />
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder(base.ToString());

            sb.AppendLine();
            sb.AppendFormat(SQLMessage.ExClientConnectionId(), _clientConnectionId);

            // Append the error number, state and class if the server provided it
            if (Number != 0)
            {
                sb.AppendLine();
                sb.AppendFormat(SQLMessage.ExErrorNumberStateClass(), Number, State, Class);
            }

            // If routed, include the original client connection id
            if (Data.Contains(OriginalClientConnectionIdKey))
            {
                sb.AppendLine();
                sb.AppendFormat(SQLMessage.ExOriginalClientConnectionId(), Data[OriginalClientConnectionIdKey]);
            }

            // If routed, provide the routing destination
            if (Data.Contains(RoutingDestinationKey))
            {
                sb.AppendLine();
                sb.AppendFormat(SQLMessage.ExRoutingDestination(), Data[RoutingDestinationKey]);
            }

            return(sb.ToString());
        }
Esempio n. 5
0
        /// <summary>
        /// Generate SSPI context
        /// </summary>
        /// <param name="handle">SNI connection handle</param>
        /// <param name="receivedBuff">Receive buffer</param>
        /// <param name="receivedLength">Received length</param>
        /// <param name="sendBuff">Send buffer</param>
        /// <param name="sendLength">Send length</param>
        /// <param name="serverName">Service Principal Name buffer</param>
        /// <param name="serverNameLength">Length of Service Principal Name</param>
        /// <returns>SNI error code</returns>
        public void GenSspiClientContext(SspiClientContextStatus sspiClientContextStatus, byte[] receivedBuff, ref byte[] sendBuff, byte[] serverName)
        {
            SafeDeleteContext   securityContext   = sspiClientContextStatus.SecurityContext;
            ContextFlagsPal     contextFlags      = sspiClientContextStatus.ContextFlags;
            SafeFreeCredentials credentialsHandle = sspiClientContextStatus.CredentialsHandle;

            SecurityBuffer[] inSecurityBufferArray = null;
            if (securityContext == null) //first iteration
            {
                credentialsHandle = NegotiateStreamPal.AcquireDefaultCredential(Kerberos, false);
            }
            else
            {
                inSecurityBufferArray = new SecurityBuffer[] { new SecurityBuffer(receivedBuff, SecurityBufferType.SECBUFFER_TOKEN) };
            }

            int            tokenSize         = NegotiateStreamPal.QueryMaxTokenSize(Kerberos);
            SecurityBuffer outSecurityBuffer = new SecurityBuffer(tokenSize, SecurityBufferType.SECBUFFER_TOKEN);

            ContextFlagsPal requestedContextFlags = ContextFlagsPal.Connection
                                                    | ContextFlagsPal.Confidentiality
                                                    | ContextFlagsPal.MutualAuth;

            string serverSPN = System.Text.Encoding.UTF8.GetString(serverName);

            SecurityStatusPal statusCode = NegotiateStreamPal.InitializeSecurityContext(
                credentialsHandle,
                ref securityContext,
                serverSPN,
                requestedContextFlags,
                inSecurityBufferArray,
                outSecurityBuffer,
                ref contextFlags);

            if (statusCode.ErrorCode == SecurityStatusPalErrorCode.CompleteNeeded ||
                statusCode.ErrorCode == SecurityStatusPalErrorCode.CompAndContinue)
            {
                inSecurityBufferArray = new SecurityBuffer[] { outSecurityBuffer };
                statusCode            = NegotiateStreamPal.CompleteAuthToken(ref securityContext, inSecurityBufferArray);
            }

            sendBuff = outSecurityBuffer.token;

            sspiClientContextStatus.SecurityContext   = securityContext;
            sspiClientContextStatus.ContextFlags      = contextFlags;
            sspiClientContextStatus.CredentialsHandle = credentialsHandle;

            if (IsErrorStatus(statusCode.ErrorCode))
            {
                if (statusCode.ErrorCode == SecurityStatusPalErrorCode.InternalError &&
                    statusCode.Exception is Interop.NetSecurityNative.GssApiException) // when unable to access Kerberos Ticket
                {
                    throw new Exception(SQLMessage.KerberosTicketMissingError() + "\n" + statusCode);
                }
                else
                {
                    throw new Exception(SQLMessage.SSPIGenerateError() + "\n" + statusCode);
                }
            }
        }
Esempio n. 6
0
        /* TODO ERROR: Skipped EndRegionDirectiveTrivia *//* TODO ERROR: Skipped RegionDirectiveTrivia */
        public void Insert(string sqlquery)
        {
            switch (v_SQLType)
            {
            case DB_Type.MySQL:
            {
                if (MySQLConn.State != ConnectionState.Open)
                {
                    Restart();
                    if (MySQLConn.State != ConnectionState.Open)
                    {
                        SQLMessage?.Invoke(EMessages.ID_Error, "MySQL Database Request Failed!");
                        return;
                    }
                }

                break;
            }
            }

            try
            {
                switch (v_SQLType)
                {
                case DB_Type.MySQL:
                {
                    Monitor.Enter(MySQLConn);
                    var MySQLTransaction = MySQLConn.BeginTransaction();
                    var MySQLCommand     = new MySqlCommand(sqlquery, MySQLConn, MySQLTransaction);
                    MySQLCommand.ExecuteNonQuery();
                    MySQLTransaction.Commit();
                    Console.WriteLine("transaction completed");
                    break;
                }
                }
            }
            catch (MySqlException e)
            {
                SQLMessage?.Invoke(EMessages.ID_Error, "Error Reading From MySQL Database " + e.Message);
                SQLMessage?.Invoke(EMessages.ID_Error, "Insert string was: " + sqlquery);
            }
            finally
            {
                switch (v_SQLType)
                {
                case DB_Type.MySQL:
                {
                    Monitor.Exit(MySQLConn);
                    break;
                }
                }
            }
        }
Esempio n. 7
0
        public int Connect()
        {
            try
            {
                if (SQLHost.Length < 1)
                {
                    SQLMessage?.Invoke(EMessages.ID_Error, "You have to set the SQLHost cannot be empty");
                    return((int)ReturnState.FatalError);
                }

                if (SQLPort.Length < 1)
                {
                    SQLMessage?.Invoke(EMessages.ID_Error, "You have to set the SQLPort cannot be empty");
                    return((int)ReturnState.FatalError);
                }

                if (SQLUser.Length < 1)
                {
                    SQLMessage?.Invoke(EMessages.ID_Error, "You have to set the SQLUser cannot be empty");
                    return((int)ReturnState.FatalError);
                }

                if (SQLPass.Length < 1)
                {
                    SQLMessage?.Invoke(EMessages.ID_Error, "You have to set the SQLPassword cannot be empty");
                    return((int)ReturnState.FatalError);
                }

                if (SQLDBName.Length < 1)
                {
                    SQLMessage?.Invoke(EMessages.ID_Error, "You have to set the SQLDatabaseName cannot be empty");
                    return((int)ReturnState.FatalError);
                }

                switch (v_SQLType)
                {
                case DB_Type.MySQL:
                {
                    MySQLConn = new MySqlConnection(string.Format("Server={0};Port={4};User ID={1};Password={2};Database={3};Compress=false;Connection Timeout=1;", SQLHost, SQLUser, SQLPass, SQLDBName, SQLPort));
                    MySQLConn.Open();
                    SQLMessage?.Invoke(EMessages.ID_Message, "MySQL Connection Opened Successfully [" + SQLUser + "@" + SQLHost + "]");
                    break;
                }
                }
            }
            catch (MySqlException e)
            {
                SQLMessage?.Invoke(EMessages.ID_Error, "MySQL Connection Error [" + e.Message + "]");
                return((int)ReturnState.FatalError);
            }

            return((int)ReturnState.Success);
        }
Esempio n. 8
0
        /* TODO ERROR: Skipped EndRegionDirectiveTrivia *//* TODO ERROR: Skipped RegionDirectiveTrivia */
        public void Update(string sqlquery)
        {
            switch (v_SQLType)
            {
            case DB_Type.MySQL:
            {
                if (MySQLConn.State != ConnectionState.Open)
                {
                    Restart();
                    if (MySQLConn.State != ConnectionState.Open)
                    {
                        SQLMessage?.Invoke(EMessages.ID_Error, "MySQL Database Request Failed!");
                        return;
                    }
                }

                break;
            }
            }

            try
            {
                switch (v_SQLType)
                {
                case DB_Type.MySQL:
                {
                    Monitor.Enter(MySQLConn);
                    var MySQLCommand = new MySqlCommand(sqlquery, MySQLConn);
                    var MySQLAdapter = new MySqlDataAdapter(MySQLCommand);
                    var result       = new DataTable();
                    MySQLAdapter.Fill(result);
                    break;
                }
                }
            }
            catch (MySqlException e)
            {
                SQLMessage?.Invoke(EMessages.ID_Error, "Error Reading From MySQL Database " + e.Message);
                SQLMessage?.Invoke(EMessages.ID_Error, "Update string was: " + sqlquery);
            }
            finally
            {
                switch (v_SQLType)
                {
                case DB_Type.MySQL:
                {
                    Monitor.Exit(MySQLConn);
                    break;
                }
                }
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Finds instance port number for given instance name.
        /// </summary>
        /// <param name="browserHostName">SQL Sever Browser hostname</param>
        /// <param name="instanceName">instance name to find port number</param>
        /// <returns>port number for given instance name</returns>
        internal static int GetPortByInstanceName(string browserHostName, string instanceName)
        {
            Debug.Assert(!string.IsNullOrWhiteSpace(browserHostName), "browserHostName should not be null, empty, or whitespace");
            Debug.Assert(!string.IsNullOrWhiteSpace(instanceName), "instanceName should not be null, empty, or whitespace");
            long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(s_className);

            try
            {
                byte[] instanceInfoRequest = CreateInstanceInfoRequest(instanceName);
                byte[] responsePacket      = null;
                try
                {
                    responsePacket = SendUDPRequest(browserHostName, SqlServerBrowserPort, instanceInfoRequest);
                }
                catch (SocketException se)
                {
                    SqlClientEventSource.Log.TrySNITraceEvent(s_className, EventType.ERR, "SocketException Message = {0}", args0: se?.Message);
                    throw new Exception(SQLMessage.SqlServerBrowserNotAccessible(), se);
                }

                const byte SvrResp = 0x05;
                if (responsePacket == null || responsePacket.Length <= 3 || responsePacket[0] != SvrResp ||
                    BitConverter.ToUInt16(responsePacket, 1) != responsePacket.Length - 3)
                {
                    throw new SocketException();
                }

                string serverMessage = Encoding.ASCII.GetString(responsePacket, 3, responsePacket.Length - 3);

                string[] elements = serverMessage.Split(SemicolonSeparator);
                int      tcpIndex = Array.IndexOf(elements, "tcp");
                if (tcpIndex < 0 || tcpIndex == elements.Length - 1)
                {
                    throw new SocketException();
                }

                return(ushort.Parse(elements[tcpIndex + 1]));
            }
            finally
            {
                SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID);
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Generate SSPI context
        /// </summary>
        /// <param name="sspiClientContextStatus">SSPI client context status</param>
        /// <param name="receivedBuff">Receive buffer</param>
        /// <param name="sendBuff">Send buffer</param>
        /// <param name="serverName">Service Principal Name buffer</param>
        public void GenSspiClientContext(SspiClientContextStatus sspiClientContextStatus, byte[] receivedBuff, ref byte[] sendBuff, byte[] serverName)
        {
            SafeDeleteContext   securityContext   = sspiClientContextStatus.SecurityContext;
            ContextFlagsPal     contextFlags      = sspiClientContextStatus.ContextFlags;
            SafeFreeCredentials credentialsHandle = sspiClientContextStatus.CredentialsHandle;

            string securityPackage = NegotiationInfoClass.Negotiate;

            if (securityContext == null)
            {
                credentialsHandle = NegotiateStreamPal.AcquireDefaultCredential(securityPackage, false);
            }

            int tokenSize = NegotiateStreamPal.QueryMaxTokenSize(securityPackage);

            byte[] resultToken = new byte[tokenSize];

            ContextFlagsPal requestedContextFlags = ContextFlagsPal.Connection
                                                    | ContextFlagsPal.Confidentiality
                                                    | ContextFlagsPal.Delegate
                                                    | ContextFlagsPal.MutualAuth;

            string serverSPN = System.Text.Encoding.UTF8.GetString(serverName);

            SecurityStatusPal statusCode = NegotiateStreamPal.InitializeSecurityContext(
                ref credentialsHandle,
                ref securityContext,
                serverSPN,
                requestedContextFlags,
                receivedBuff,
                null,
                ref resultToken,
                ref contextFlags);

            if (statusCode.ErrorCode == SecurityStatusPalErrorCode.CompleteNeeded ||
                statusCode.ErrorCode == SecurityStatusPalErrorCode.CompAndContinue)
            {
                statusCode  = NegotiateStreamPal.CompleteAuthToken(ref securityContext, resultToken);
                resultToken = null;
            }

            sendBuff = resultToken;
            if (sendBuff == null)
            {
                sendBuff = Array.Empty <byte>();
            }

            sspiClientContextStatus.SecurityContext   = securityContext;
            sspiClientContextStatus.ContextFlags      = contextFlags;
            sspiClientContextStatus.CredentialsHandle = credentialsHandle;

            if (IsErrorStatus(statusCode.ErrorCode))
            {
                // Could not access Kerberos Ticket.
                //
                // SecurityStatusPalErrorCode.InternalError only occurs in Unix and always comes with a GssApiException,
                // so we don't need to check for a GssApiException here.
                if (statusCode.ErrorCode == SecurityStatusPalErrorCode.InternalError)
                {
                    throw new InvalidOperationException(SQLMessage.KerberosTicketMissingError() + "\n" + statusCode);
                }
                else
                {
                    throw new InvalidOperationException(SQLMessage.SSPIGenerateError() + "\n" + statusCode);
                }
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="serverName">Server name</param>
        /// <param name="port">TCP port number</param>
        /// <param name="timerExpire">Connection timer expiration</param>
        /// <param name="callbackObject">Callback object</param>
        public SNITCPHandle(string serverName, int port, long timerExpire, bool parallel, out SNIError sniError)
            : base(serverName)
        {
            try
            {
                TimeSpan ts;

                // In case the Timeout is Infinite, we will receive the max value of Int64 as the tick count
                // The infinite Timeout is a function of ConnectionString Timeout=0
                bool isInfiniteTimeOut = long.MaxValue == timerExpire;
                if (!isInfiniteTimeOut)
                {
                    ts = DateTime.FromFileTime(timerExpire) - DateTime.Now;
                    ts = ts.Ticks < 0 ? TimeSpan.FromTicks(0) : ts;
                }

                Task <Socket> connectTask;
                if (parallel)
                {
                    Task <IPAddress[]> serverAddrTask = Dns.GetHostAddressesAsync(serverName);
                    serverAddrTask.Wait(ts);
                    IPAddress[] serverAddresses = serverAddrTask.Result;

                    if (serverAddresses.Length > MaxParallelIpAddresses)
                    {
                        // Fail if above 64 to match legacy behavior
                        sniError = new SNIError(SNIProviders.TCP_PROV, 0, SNIErrorCode.MultiSubnetFailoverWithMoreThan64IPs, string.Empty);
                        return;
                    }

                    connectTask = ConnectAsync(serverAddresses, port);
                }
                else
                {
                    connectTask = ConnectAsync(serverName, port);
                }

                if (!(isInfiniteTimeOut ? connectTask.Wait(-1) : connectTask.Wait(ts)))
                {
                    sniError = new SNIError(SNIProviders.TCP_PROV, 0, SNIErrorCode.ConnOpenFailedError, SQLMessage.Timeout());
                    return;
                }

                _socket         = connectTask.Result;
                _socket.NoDelay = true;
                _tcpStream      = new NetworkStream(_socket, true);

                _sslOverTdsStream = new SslOverTdsStream(_tcpStream);
                _sslStream        = new SslStream(_sslOverTdsStream, true, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
            }
            catch (SocketException se)
            {
                sniError = new SNIError(SNIProviders.TCP_PROV, 0, se);
                return;
            }
            catch (Exception e)
            {
                sniError = new SNIError(SNIProviders.TCP_PROV, 0, e);
                return;
            }

            _stream  = _tcpStream;
            sniError = null;
        }
Esempio n. 12
0
        public static EncryptionOptions ParsePreLoginHandshake(byte[] payload, int payloadOffset, EncryptionOptions encryptionRequested)
        {
            if (payload[payloadOffset] == 0xaa)
            {
                throw SQL.InvalidSqlServerVersionUnknown();
            }
            var result = new TdsConnectionResult();
            var offset = payloadOffset;
            int option = payload[offset++];

            while (option != (byte)PreLoginOptions.LASTOPT)
            {
                var dataOffset = ((payload[offset] << 8) | payload[offset + 1]) + payloadOffset;
                switch (option)
                {
                case (int)PreLoginOptions.VERSION:
                    result.Version = payload[dataOffset];
                    break;

                case (int)PreLoginOptions.ENCRYPT:
                    var serverOption = (EncryptionOptions)payload[dataOffset];

                    /* internal enum encryptionOptions {
                     *  OFF,
                     *  ON,
                     *  NOT_SUP,
                     *  REQ,
                     *  LOGIN
                     * } */
                    result.EncryptionOption = encryptionRequested;
                    switch (encryptionRequested)
                    {
                    case EncryptionOptions.ON:
                        if (serverOption == EncryptionOptions.NOT_SUP)
                        {
                            throw new Exception(SQLMessage.EncryptionNotSupportedByServer());
                        }
                        break;

                    case EncryptionOptions.OFF:
                        switch (serverOption)
                        {
                        case EncryptionOptions.OFF:
                            // Only encrypt login.
                            result.EncryptionOption = EncryptionOptions.LOGIN;
                            break;

                        case EncryptionOptions.REQ:
                            // Encrypt all.
                            result.EncryptionOption = EncryptionOptions.ON;
                            break;
                        }

                        break;

                    case EncryptionOptions.NOT_SUP:
                        if (serverOption == EncryptionOptions.REQ)
                        {
                            throw new Exception(SQLMessage.EncryptionNotSupportedByClient());
                        }
                        break;
                    }

                    break;

                case (int)PreLoginOptions.INSTANCE:

                    if (payload[dataOffset] == 0x1)
                    {
                        throw new Exception("Instancename not correct");
                    }

                    break;

                case (int)PreLoginOptions.THREADID:
                    // DO NOTHING FOR THREADID
                    break;

                case (int)PreLoginOptions.MARS:
                    result.IsMarsCapable = payload[dataOffset] != 0;
                    break;

                case (int)PreLoginOptions.TRACEID:
                    // DO NOTHING FOR TRACEID
                    break;
                }

                offset += 4;
                if (offset >= payload.Length)
                {
                    break;
                }
                option = payload[offset++];
            }

            return(result.EncryptionOption);
        }
Esempio n. 13
0
        internal string GetErrorMessage()
        {
            StringBuilder errorBuilder;
            string        durationString;

            switch (_currentPhase)
            {
            case SqlConnectionTimeoutErrorPhase.PreLoginBegin:
                errorBuilder   = new StringBuilder(SQLMessage.Timeout_PreLogin_Begin());
                durationString = SQLMessage.Duration_PreLogin_Begin(
                    _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.PreLoginBegin].GetMilliSecondDuration());
                break;

            case SqlConnectionTimeoutErrorPhase.InitializeConnection:
                errorBuilder   = new StringBuilder(SQLMessage.Timeout_PreLogin_InitializeConnection());
                durationString = SQLMessage.Duration_PreLogin_Begin(
                    _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.PreLoginBegin].GetMilliSecondDuration() +
                    _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.InitializeConnection].GetMilliSecondDuration());
                break;

            case SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake:
                errorBuilder   = new StringBuilder(SQLMessage.Timeout_PreLogin_SendHandshake());
                durationString = SQLMessage.Duration_PreLoginHandshake(
                    _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.PreLoginBegin].GetMilliSecondDuration() +
                    _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.InitializeConnection].GetMilliSecondDuration(),
                    _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake].GetMilliSecondDuration());
                break;

            case SqlConnectionTimeoutErrorPhase.ConsumePreLoginHandshake:
                errorBuilder   = new StringBuilder(SQLMessage.Timeout_PreLogin_ConsumeHandshake());
                durationString = SQLMessage.Duration_PreLoginHandshake(
                    _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.PreLoginBegin].GetMilliSecondDuration() +
                    _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.InitializeConnection].GetMilliSecondDuration(),
                    _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake].GetMilliSecondDuration() +
                    _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.ConsumePreLoginHandshake].GetMilliSecondDuration());
                break;

            case SqlConnectionTimeoutErrorPhase.LoginBegin:
                errorBuilder   = new StringBuilder(SQLMessage.Timeout_Login_Begin());
                durationString = SQLMessage.Duration_Login_Begin(
                    _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.PreLoginBegin].GetMilliSecondDuration() +
                    _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.InitializeConnection].GetMilliSecondDuration(),
                    _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake].GetMilliSecondDuration() +
                    _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.ConsumePreLoginHandshake].GetMilliSecondDuration(),
                    _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.LoginBegin].GetMilliSecondDuration());
                break;

            case SqlConnectionTimeoutErrorPhase.ProcessConnectionAuth:
                errorBuilder   = new StringBuilder(SQLMessage.Timeout_Login_ProcessConnectionAuth());
                durationString = SQLMessage.Duration_Login_ProcessConnectionAuth(
                    _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.PreLoginBegin].GetMilliSecondDuration() +
                    _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.InitializeConnection].GetMilliSecondDuration(),
                    _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake].GetMilliSecondDuration() +
                    _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.ConsumePreLoginHandshake].GetMilliSecondDuration(),
                    _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.LoginBegin].GetMilliSecondDuration(),
                    _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.ProcessConnectionAuth].GetMilliSecondDuration());
                break;

            case SqlConnectionTimeoutErrorPhase.PostLogin:
                errorBuilder   = new StringBuilder(SQLMessage.Timeout_PostLogin());
                durationString = SQLMessage.Duration_PostLogin(
                    _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.PreLoginBegin].GetMilliSecondDuration() +
                    _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.InitializeConnection].GetMilliSecondDuration(),
                    _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake].GetMilliSecondDuration() +
                    _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.ConsumePreLoginHandshake].GetMilliSecondDuration(),
                    _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.LoginBegin].GetMilliSecondDuration(),
                    _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.ProcessConnectionAuth].GetMilliSecondDuration(),
                    _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.PostLogin].GetMilliSecondDuration());
                break;

            default:
                errorBuilder   = new StringBuilder(SQLMessage.Timeout());
                durationString = null;
                break;
            }

            // This message is to be added only when within the various stages of a connection.
            // In all other cases, it will default to the original error message.
            if ((_currentPhase != SqlConnectionTimeoutErrorPhase.Undefined) && (_currentPhase != SqlConnectionTimeoutErrorPhase.Complete))
            {
                // NOTE: In case of a failover scenario, add a string that this failure occurred as part of the primary or secondary server
                if (_isFailoverScenario)
                {
                    errorBuilder.Append("  ");
                    errorBuilder.AppendFormat((IFormatProvider)null, SQLMessage.Timeout_FailoverInfo(), _currentSourceType);
                }
                else if (_currentSourceType == SqlConnectionInternalSourceType.RoutingDestination)
                {
                    errorBuilder.Append("  ");
                    errorBuilder.AppendFormat((IFormatProvider)null, SQLMessage.Timeout_RoutingDestination(),
                                              _originalPhaseDurations[(int)SqlConnectionTimeoutErrorPhase.PreLoginBegin].GetMilliSecondDuration() +
                                              _originalPhaseDurations[(int)SqlConnectionTimeoutErrorPhase.InitializeConnection].GetMilliSecondDuration(),
                                              _originalPhaseDurations[(int)SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake].GetMilliSecondDuration() +
                                              _originalPhaseDurations[(int)SqlConnectionTimeoutErrorPhase.ConsumePreLoginHandshake].GetMilliSecondDuration(),
                                              _originalPhaseDurations[(int)SqlConnectionTimeoutErrorPhase.LoginBegin].GetMilliSecondDuration(),
                                              _originalPhaseDurations[(int)SqlConnectionTimeoutErrorPhase.ProcessConnectionAuth].GetMilliSecondDuration(),
                                              _originalPhaseDurations[(int)SqlConnectionTimeoutErrorPhase.PostLogin].GetMilliSecondDuration());
                }
            }

            // NOTE: To display duration in each phase.
            if (durationString != null)
            {
                errorBuilder.Append("  ");
                errorBuilder.Append(durationString);
            }

            return(errorBuilder.ToString());
        }
Esempio n. 14
0
        /// <summary>
        /// Generate SSPI context
        /// </summary>
        /// <param name="sspiClientContextStatus">SSPI client context status</param>
        /// <param name="receivedBuff">Receive buffer</param>
        /// <param name="sendBuff">Send buffer</param>
        /// <param name="serverName">Service Principal Name buffer</param>
        /// <returns>SNI error code</returns>
        internal static void GenSspiClientContext(SspiClientContextStatus sspiClientContextStatus, byte[] receivedBuff, ref byte[] sendBuff, byte[][] serverName)
        {
            SafeDeleteContext   securityContext   = sspiClientContextStatus.SecurityContext;
            ContextFlagsPal     contextFlags      = sspiClientContextStatus.ContextFlags;
            SafeFreeCredentials credentialsHandle = sspiClientContextStatus.CredentialsHandle;

            string securityPackage = NegotiationInfoClass.Negotiate;

            if (securityContext == null)
            {
                credentialsHandle = NegotiateStreamPal.AcquireDefaultCredential(securityPackage, false);
            }

            SecurityBuffer[] inSecurityBufferArray;
            if (receivedBuff != null)
            {
                inSecurityBufferArray = new SecurityBuffer[] { new SecurityBuffer(receivedBuff, SecurityBufferType.SECBUFFER_TOKEN) };
            }
            else
            {
                inSecurityBufferArray = Array.Empty <SecurityBuffer>();
            }

            int tokenSize = NegotiateStreamPal.QueryMaxTokenSize(securityPackage);

            SecurityBuffer outSecurityBuffer = new SecurityBuffer(tokenSize, SecurityBufferType.SECBUFFER_TOKEN);

            ContextFlagsPal requestedContextFlags = ContextFlagsPal.Connection
                                                    | ContextFlagsPal.Confidentiality
                                                    | ContextFlagsPal.Delegate
                                                    | ContextFlagsPal.MutualAuth;

            string[] serverSPNs = new string[serverName.Length];
            for (int i = 0; i < serverName.Length; i++)
            {
                serverSPNs[i] = Encoding.UTF8.GetString(serverName[i]);
            }
            SecurityStatusPal statusCode = NegotiateStreamPal.InitializeSecurityContext(
                credentialsHandle,
                ref securityContext,
                serverSPNs,
                requestedContextFlags,
                inSecurityBufferArray,
                outSecurityBuffer,
                ref contextFlags);

            if (statusCode.ErrorCode == SecurityStatusPalErrorCode.CompleteNeeded ||
                statusCode.ErrorCode == SecurityStatusPalErrorCode.CompAndContinue)
            {
                inSecurityBufferArray   = new SecurityBuffer[] { outSecurityBuffer };
                statusCode              = NegotiateStreamPal.CompleteAuthToken(ref securityContext, inSecurityBufferArray);
                outSecurityBuffer.token = null;
            }

            sendBuff = outSecurityBuffer.token;
            if (sendBuff == null)
            {
                sendBuff = Array.Empty <byte>();
            }

            sspiClientContextStatus.SecurityContext   = securityContext;
            sspiClientContextStatus.ContextFlags      = contextFlags;
            sspiClientContextStatus.CredentialsHandle = credentialsHandle;

            if (IsErrorStatus(statusCode.ErrorCode))
            {
                // Could not access Kerberos Ticket.
                //
                // SecurityStatusPalErrorCode.InternalError only occurs in Unix and always comes with a GssApiException,
                // so we don't need to check for a GssApiException here.
                if (statusCode.ErrorCode == SecurityStatusPalErrorCode.InternalError)
                {
                    throw new InvalidOperationException(SQLMessage.KerberosTicketMissingError() + "\n" + statusCode);
                }
                else
                {
                    throw new InvalidOperationException(SQLMessage.SSPIGenerateError() + "\n" + statusCode);
                }
            }
        }
Esempio n. 15
0
        /* TODO ERROR: Skipped EndRegionDirectiveTrivia *//* TODO ERROR: Skipped EndRegionDirectiveTrivia */
        /* TODO ERROR: Skipped RegionDirectiveTrivia *//* TODO ERROR: Skipped RegionDirectiveTrivia */
        public int Query(string sqlquery, ref DataTable Result)
        {
            switch (v_SQLType)
            {
            case DB_Type.MySQL:
            {
                if (MySQLConn.State != ConnectionState.Open)
                {
                    Restart();
                    if (MySQLConn.State != ConnectionState.Open)
                    {
                        SQLMessage?.Invoke(EMessages.ID_Error, "MySQL Database Request Failed!");
                        return((int)ReturnState.MinorError);
                    }
                }

                break;
            }
            }

            int ExitCode = (int)ReturnState.Success;

            try
            {
                switch (v_SQLType)
                {
                case DB_Type.MySQL:
                {
                    Monitor.Enter(MySQLConn);
                    var MySQLCommand = new MySqlCommand(sqlquery, MySQLConn);
                    var MySQLAdapter = new MySqlDataAdapter(MySQLCommand);
                    if (Result is null)
                    {
                        Result = new DataTable();
                    }
                    else
                    {
                        Result.Clear();
                    }

                    MySQLAdapter.Fill(Result);
                    break;
                }
                }
            }
            catch (MySqlException e)
            {
                SQLMessage?.Invoke(EMessages.ID_Error, "Error Reading From MySQL Database " + e.Message);
                SQLMessage?.Invoke(EMessages.ID_Error, "Query string was: " + sqlquery);
                ExitCode = (int)ReturnState.FatalError;
            }
            finally
            {
                switch (v_SQLType)
                {
                case DB_Type.MySQL:
                {
                    Monitor.Exit(MySQLConn);
                    break;
                }
                }
            }

            return(ExitCode);
        }