internal static AuthenticationException CreateCustomException(string uri, AuthenticationException ex) { if (uri.StartsWith("https")) { return new AuthenticationException( string.Format("Invalid remote SSL certificate, overide with: \nServicePointManager.ServerCertificateValidationCallback += ((sender, certificate, chain, sslPolicyErrors) => isValidPolicy);"), ex); } return null; }
public override void OnException(MethodExecutionArgs args) { args.FlowBehavior = FlowBehavior.Continue; if (args.Exception != null) { Logger.Log.Error(args.Exception.Message, args.Exception); return; } var e = new AuthenticationException(); Logger.Log.Error(e.Message, e); }
// public static uint ERROR_LDAP_INVALID_CREDENTIALS = 49; //fix error CS0414: Warning as Error: is assigned but its value is never used // // This method maps some common COM Hresults to // existing clr exceptions // internal static Exception GetExceptionFromCOMException(COMException e) { Exception exception; int errorCode = e.ErrorCode; string errorMessage = e.Message; // // Check if we can throw a more specific exception // if (errorCode == unchecked((int)0x80070005)) { // // Access Denied // exception = new UnauthorizedAccessException(errorMessage, e); } else if (errorCode == unchecked((int)0x800708c5) || errorCode == unchecked((int)0x80070056) || errorCode == unchecked((int)0x8007052)) { // // Password does not meet complexity requirements or old password does not match or policy restriction has been enforced. // exception = new PasswordException(errorMessage, e); } else if (errorCode == unchecked((int)0x800708b0) || errorCode == unchecked((int)0x80071392)) { // // Principal already exists // exception = new PrincipalExistsException(errorMessage, e); } else if (errorCode == unchecked((int)0x8007052e)) { // // Logon Failure // exception = new AuthenticationException(errorMessage, e); } else if (errorCode == unchecked((int)0x8007202f)) { // // Constraint Violation // exception = new InvalidOperationException(errorMessage, e); } else if (errorCode == unchecked((int)0x80072035)) { // // Unwilling to perform // exception = new InvalidOperationException(errorMessage, e); } else if (errorCode == unchecked((int)0x80070008)) { // // No Memory // exception = new OutOfMemoryException(); } else if ((errorCode == unchecked((int)0x8007203a)) || (errorCode == unchecked((int)0x8007200e)) || (errorCode == unchecked((int)0x8007200f))) { exception = new PrincipalServerDownException(errorMessage, e, errorCode, null); } else { // // Wrap the exception in a generic OperationException // exception = new PrincipalOperationException(errorMessage, e, errorCode); } return exception; }
public Authentication(DAL db) { _db = db; authException = new AuthenticationException("User name or password is invalid"); }
internal static Exception GetExceptionFromCOMException(COMException e) { Exception passwordException; int errorCode = e.ErrorCode; string message = e.Message; if (errorCode != -2147024891) { if (errorCode == -2147022651 || errorCode == -2147024810 || errorCode == 0x8007052) { passwordException = new PasswordException(message, e); } else { if (errorCode == -2147022672 || errorCode == -2147019886) { passwordException = new PrincipalExistsException(message, e); } else { if (errorCode != -2147023570) { if (errorCode != -2147016657) { if (errorCode != -2147016651) { if (errorCode != -2147024888) { if (errorCode == -2147016646 || errorCode == -2147016690 || errorCode == -2147016689) { passwordException = new PrincipalServerDownException(message, e, errorCode, null); } else { passwordException = new PrincipalOperationException(message, e, errorCode); } } else { passwordException = new OutOfMemoryException(); } } else { passwordException = new InvalidOperationException(message, e); } } else { passwordException = new InvalidOperationException(message, e); } } else { passwordException = new AuthenticationException(message, e); } } } } else { passwordException = new UnauthorizedAccessException(message, e); } return passwordException; }
public void TestAuthenticationException() { AuthenticationException ex = new AuthenticationException("Authentication Exception"); this.ExecuteExceptionHandler(ex); this.mockFactory.VerifyAllExpectationsHaveBeenMet(); }
// // This is to reset auth state on the remote side. // If this write succeeds we will allow auth retrying. // private void StartSendAuthResetSignal(LazyAsyncResult lazyResult, byte[] message, Exception exception) { _framer.WriteHeader.MessageId = FrameHeader.HandshakeErrId; Win32Exception win32exception = exception as Win32Exception; if (win32exception != null && win32exception.NativeErrorCode == (int)Interop.SecurityStatus.LogonDenied) { if (IsServer) { exception = new InvalidCredentialException(SR.net_auth_bad_client_creds, exception); } else { exception = new InvalidCredentialException(SR.net_auth_bad_client_creds_or_target_mismatch, exception); } } if (!(exception is AuthenticationException)) { exception = new AuthenticationException(SR.net_auth_SSPI, exception); } if (lazyResult == null) { _framer.WriteMessage(message); } else { lazyResult.Result = exception; IAsyncResult ar = _framer.BeginWriteMessage(message, s_writeCallback, lazyResult); if (!ar.CompletedSynchronously) { return; } _framer.EndWriteMessage(ar); } _canRetryAuthentication = true; throw exception; }
// // Client side starts here, but server also loops through this method. // private void StartSendBlob(byte[] message, LazyAsyncResult lazyResult) { Win32Exception win32exception = null; if (message != s_emptyMessage) { message = GetOutgoingBlob(message, ref win32exception); } if (win32exception != null) { // Signal remote side on a failed attempt. StartSendAuthResetSignal(lazyResult, message, win32exception); return; } if (HandshakeComplete) { if (_context.IsServer && !CheckSpn()) { Exception exception = new AuthenticationException(SR.net_auth_bad_client_creds_or_target_mismatch); int statusCode = ERROR_TRUST_FAILURE; message = new byte[8]; //sizeof(long) for (int i = message.Length - 1; i >= 0; --i) { message[i] = (byte)(statusCode & 0xFF); statusCode = (int)((uint)statusCode >> 8); } StartSendAuthResetSignal(lazyResult, message, exception); return; } if (PrivateImpersonationLevel < _expectedImpersonationLevel) { Exception exception = new AuthenticationException(SR.Format(SR.net_auth_context_expectation, _expectedImpersonationLevel.ToString(), PrivateImpersonationLevel.ToString())); int statusCode = ERROR_TRUST_FAILURE; message = new byte[8]; //sizeof(long) for (int i = message.Length - 1; i >= 0; --i) { message[i] = (byte)(statusCode & 0xFF); statusCode = (int)((uint)statusCode >> 8); } StartSendAuthResetSignal(lazyResult, message, exception); return; } ProtectionLevel result = _context.IsConfidentialityFlag ? ProtectionLevel.EncryptAndSign : _context.IsIntegrityFlag ? ProtectionLevel.Sign : ProtectionLevel.None; if (result < _expectedProtectionLevel) { Exception exception = new AuthenticationException(SR.Format(SR.net_auth_context_expectation, result.ToString(), _expectedProtectionLevel.ToString())); int statusCode = ERROR_TRUST_FAILURE; message = new byte[8]; //sizeof(long) for (int i = message.Length - 1; i >= 0; --i) { message[i] = (byte)(statusCode & 0xFF); statusCode = (int)((uint)statusCode >> 8); } StartSendAuthResetSignal(lazyResult, message, exception); return; } // Signal remote party that we are done _framer.WriteHeader.MessageId = FrameHeader.HandshakeDoneId; if (_context.IsServer) { // Server may complete now because client SSPI would not complain at this point. _remoteOk = true; // However the client will wait for server to send this ACK //Force signaling server OK to the client if (message == null) { message = s_emptyMessage; } } } else if (message == null || message == s_emptyMessage) { throw new InternalException(); } if (message != null) { //even if we are completed, there could be a blob for sending. if (lazyResult == null) { _framer.WriteMessage(message); } else { IAsyncResult ar = _framer.BeginWriteMessage(message, s_writeCallback, lazyResult); if (!ar.CompletedSynchronously) { return; } _framer.EndWriteMessage(ar); } } CheckCompletionBeforeNextReceive(lazyResult); }
public void NetworkErrorToAuthError() { var reporterMock = new Mock<IntelReporter>(MockBehavior.Loose) { CallBase = true }; TestHelpers.CreateRequestMock(channelListUri, String.Join("\r\n", channelList)); var testEvent = new IntelEventArgs(channelList[0], DateTime.UtcNow, "Test Message"); var sessionMock = new Mock<IntelSession>(MockBehavior.Loose, "username", "password", serviceUri); sessionMock.Setup(x => x.Report(testEvent.Channel, testEvent.Timestamp, testEvent.Message)) .Returns(true); Exception exception = new WebException(); reporterMock.Protected() .Setup<IntelSession>("GetSession", ItExpr.IsAny<bool>()) .Returns(() => { throw exception; }); using (var testDir = new TempDirectory()) { using (var reporter = reporterMock.Object) { reporter.Path = testDir.FullName; reporter.Username = "******"; reporter.PasswordHash = "password"; reporter.AuthenticationRetryTimeout = new TimeSpan(0, 0, 0, 0, 10); reporter.ServiceUri = serviceUri; reporter.ChannelListUri = channelListUri; reporter.Start(); Thread.Sleep(100); Assert.AreEqual(IntelStatus.NetworkError, reporter.Status); reporter.OnIntelReported(testEvent); Thread.Sleep(100); Assert.AreEqual(IntelStatus.NetworkError, reporter.Status); Assert.AreEqual(1, reporter.IntelDropped); Assert.AreEqual(0, reporter.IntelSent); exception = new AuthenticationException(); reporter.OnIntelReported(testEvent); Thread.Sleep(100); Assert.AreEqual(IntelStatus.AuthenticationError, reporter.Status); Assert.AreEqual(2, reporter.IntelDropped); Assert.AreEqual(0, reporter.IntelSent); } } }
public static InternalError CreateAuthentication(AuthenticationException authenticationException) { return new InternalError(ErrorCodes.ErrorCodeUnAuthenticated, authenticationException.Message); }
private void StartSendBlob(byte[] message, LazyAsyncResult lazyResult) { Win32Exception e = null; if (message != _EmptyMessage) { message = this.GetOutgoingBlob(message, ref e); } if (e != null) { this.StartSendAuthResetSignal(lazyResult, message, e); } else { if (this.HandshakeComplete) { if (this._Context.IsServer && !this.CheckSpn()) { Exception exception = new AuthenticationException(SR.GetString("net_auth_bad_client_creds_or_target_mismatch")); int num = 0x6fe; message = new byte[8]; for (int i = message.Length - 1; i >= 0; i--) { message[i] = (byte) (num & 0xff); num = num >> 8; } this.StartSendAuthResetSignal(lazyResult, message, exception); return; } if (this.PrivateImpersonationLevel < this._ExpectedImpersonationLevel) { Exception exception3 = new AuthenticationException(SR.GetString("net_auth_context_expectation", new object[] { this._ExpectedImpersonationLevel.ToString(), this.PrivateImpersonationLevel.ToString() })); int num3 = 0x6fe; message = new byte[8]; for (int j = message.Length - 1; j >= 0; j--) { message[j] = (byte) (num3 & 0xff); num3 = num3 >> 8; } this.StartSendAuthResetSignal(lazyResult, message, exception3); return; } ProtectionLevel level = this._Context.IsConfidentialityFlag ? ProtectionLevel.EncryptAndSign : (this._Context.IsIntegrityFlag ? ProtectionLevel.Sign : ProtectionLevel.None); if (level < this._ExpectedProtectionLevel) { Exception exception4 = new AuthenticationException(SR.GetString("net_auth_context_expectation", new object[] { level.ToString(), this._ExpectedProtectionLevel.ToString() })); int num5 = 0x6fe; message = new byte[8]; for (int k = message.Length - 1; k >= 0; k--) { message[k] = (byte) (num5 & 0xff); num5 = num5 >> 8; } this.StartSendAuthResetSignal(lazyResult, message, exception4); return; } this._Framer.WriteHeader.MessageId = 20; if (this._Context.IsServer) { this._RemoteOk = true; if (message == null) { message = _EmptyMessage; } } } else if ((message == null) || (message == _EmptyMessage)) { throw new InternalException(); } if (message != null) { if (lazyResult == null) { this._Framer.WriteMessage(message); } else { IAsyncResult asyncResult = this._Framer.BeginWriteMessage(message, _WriteCallback, lazyResult); if (!asyncResult.CompletedSynchronously) { return; } this._Framer.EndWriteMessage(asyncResult); } } this.CheckCompletionBeforeNextReceive(lazyResult); } }
private void StartSendAuthResetSignal(LazyAsyncResult lazyResult, byte[] message, Exception exception) { this._Framer.WriteHeader.MessageId = 0x15; Win32Exception exception2 = exception as Win32Exception; if ((exception2 != null) && (exception2.NativeErrorCode == -2146893044)) { if (this.IsServer) { exception = new InvalidCredentialException(SR.GetString("net_auth_bad_client_creds"), exception); } else { exception = new InvalidCredentialException(SR.GetString("net_auth_bad_client_creds_or_target_mismatch"), exception); } } if (!(exception is AuthenticationException)) { exception = new AuthenticationException(SR.GetString("net_auth_SSPI"), exception); } if (lazyResult == null) { this._Framer.WriteMessage(message); } else { lazyResult.Result = exception; IAsyncResult asyncResult = this._Framer.BeginWriteMessage(message, _WriteCallback, lazyResult); if (!asyncResult.CompletedSynchronously) { return; } this._Framer.EndWriteMessage(asyncResult); } this._CanRetryAuthentication = true; throw exception; }
private void CreateSSLStream(String host, TcpClient socket, X509Certificate certificate) { try { //Initializes a new instance of the SslStream class using the specified Stream, stream closure behavior, certificate validation delegate and certificate selection delegate SslStream sslStream = new SslStream(socket.GetStream(), false, ValidateServerCertificate, LocalCertificateSelection); X509CertificateCollection certCol = new X509CertificateCollection(); certCol.Add(certificate); sslStream.AuthenticateAsClient(host, certCol, SslProtocols.Default, true); Stream = sslStream; } catch (AuthenticationException e) { log.Warn("Exception: {0}", e.Message); if (e.InnerException != null) { log.Warn("Inner exception: {0}", e.InnerException.Message); e = new AuthenticationException(e.InnerException.Message, e.InnerException); } socket.Close(); throw new TransportException(string.Format("Authentication failed, closing connection to broker: {0}", e.Message)); } }
internal static Exception GetExceptionFromCOMException(DirectoryContext context, COMException e) { Exception exception; int errorCode = e.ErrorCode; string errorMessage = e.Message; // // Check if we can throw a more specific exception // if (errorCode == unchecked((int)0x80070005)) { // // Access Denied // exception = new UnauthorizedAccessException(errorMessage, e); } else if (errorCode == unchecked((int)0x8007052e)) { // // Logon Failure // exception = new AuthenticationException(errorMessage, e); } else if (errorCode == unchecked((int)0x8007202f)) { // // Constraint Violation // exception = new InvalidOperationException(errorMessage, e); } else if (errorCode == unchecked((int)0x80072035)) { // // Unwilling to perform // exception = new InvalidOperationException(errorMessage, e); } else if (errorCode == unchecked((int)0x80071392)) { // // Object already exists // exception = new ActiveDirectoryObjectExistsException(errorMessage, e); } else if (errorCode == unchecked((int)0x80070008)) { // // No Memory // exception = new OutOfMemoryException(); } else if ((errorCode == unchecked((int)0x8007203a)) || (errorCode == unchecked((int)0x8007200e)) || (errorCode == unchecked((int)0x8007200f))) { // // ServerDown/Unavailable/Busy // if (context != null) { exception = new ActiveDirectoryServerDownException(errorMessage, e, errorCode, context.GetServerName()); } else { exception = new ActiveDirectoryServerDownException(errorMessage, e, errorCode, null); } } else { // // Wrap the exception in a generic OperationException // exception = new ActiveDirectoryOperationException(errorMessage, e, errorCode); } return exception; }
private void Authenticate(SecurityTokenService securService, MSNTicket msnticket, EventHandler onSuccess, EventHandler<ExceptionEventArgs> onError) { if (user.Split('@').Length > 1) { if (user.Split('@')[1].ToLower(CultureInfo.InvariantCulture) == "msn.com") { securService.Url = @"https://msnia.login.live.com/RST2.srf"; } } else { AuthenticationException authenticationException = new AuthenticationException("Invalid account. The account must contain @ char"); if (onError != null && onSuccess != null) onError(this, new ExceptionEventArgs(authenticationException)); else throw authenticationException; } RequestMultipleSecurityTokensType mulToken = new RequestMultipleSecurityTokensType(); mulToken.Id = "RSTS"; mulToken.RequestSecurityToken = auths.ToArray(); // ASYNC if (onSuccess != null && onError != null) { securService.RequestMultipleSecurityTokensCompleted += delegate(object sender, RequestMultipleSecurityTokensCompletedEventArgs e) { if (!e.Cancelled) { if (e.Error != null) { SoapException sex = e.Error as SoapException; if (sex != null && ProcessError(securService, sex, msnticket, onSuccess, onError)) return; MSNPSharpException sexp = new MSNPSharpException(e.Error.Message + ". See innerexception for detail.", e.Error); if (securService.pp != null) sexp.Data["Code"] = securService.pp.reqstatus; //Error code onError(this, new ExceptionEventArgs(sexp)); } else if (e.Result != null) { GetTickets(e.Result, securService, msnticket); onSuccess(this, EventArgs.Empty); } else { // Is this possible? Answer: No. } } }; securService.RequestMultipleSecurityTokensAsync(mulToken, new object()); } else { try { RequestSecurityTokenResponseType[] result = securService.RequestMultipleSecurityTokens(mulToken); if (result != null) { GetTickets(result, securService, msnticket); } } catch (SoapException sex) { if (ProcessError(securService, sex, msnticket, onSuccess, onError)) return; throw sex; } catch (Exception ex) { MSNPSharpException sexp = new MSNPSharpException(ex.Message + ". See innerexception for detail.", ex); if (securService.pp != null) sexp.Data["Code"] = securService.pp.reqstatus; //Error code throw sexp; } } }
internal static Exception GetExceptionFromCOMException(DirectoryContext context, COMException e) { Exception activeDirectoryServerDownException; int errorCode = e.ErrorCode; string message = e.Message; if (errorCode != -2147024891) { if (errorCode != -2147023570) { if (errorCode != -2147016657) { if (errorCode != -2147016651) { if (errorCode != -2147019886) { if (errorCode != -2147024888) { if (errorCode == -2147016646 || errorCode == -2147016690 || errorCode == -2147016689) { if (context == null) { activeDirectoryServerDownException = new ActiveDirectoryServerDownException(message, e, errorCode, null); } else { activeDirectoryServerDownException = new ActiveDirectoryServerDownException(message, e, errorCode, context.GetServerName()); } } else { activeDirectoryServerDownException = new ActiveDirectoryOperationException(message, e, errorCode); } } else { activeDirectoryServerDownException = new OutOfMemoryException(); } } else { activeDirectoryServerDownException = new ActiveDirectoryObjectExistsException(message, e); } } else { activeDirectoryServerDownException = new InvalidOperationException(message, e); } } else { activeDirectoryServerDownException = new InvalidOperationException(message, e); } } else { activeDirectoryServerDownException = new AuthenticationException(message, e); } } else { activeDirectoryServerDownException = new UnauthorizedAccessException(message, e); } return activeDirectoryServerDownException; }