Exemple #1
0
        private static AlertLevel inferAlertLevel(AlertDescription description)
        {
            switch (description)
            {
            case AlertDescription.CloseNotify:
            case AlertDescription.NoRenegotiation:
            case AlertDescription.UserCancelled:
                return(AlertLevel.Warning);

            case AlertDescription.AccessDenied:
            case AlertDescription.BadCertificate:
            case AlertDescription.BadRecordMAC:
            case AlertDescription.CertificateExpired:
            case AlertDescription.CertificateRevoked:
            case AlertDescription.CertificateUnknown:
            case AlertDescription.DecodeError:
            case AlertDescription.DecompressionFailiure:
            case AlertDescription.DecryptError:
            case AlertDescription.DecryptionFailed:
            case AlertDescription.ExportRestriction:
            case AlertDescription.HandshakeFailiure:
            case AlertDescription.IlegalParameter:
            case AlertDescription.InsuficientSecurity:
            case AlertDescription.InternalError:
            case AlertDescription.ProtocolVersion:
            case AlertDescription.RecordOverflow:
            case AlertDescription.UnexpectedMessage:
            case AlertDescription.UnknownCA:
            case AlertDescription.UnsupportedCertificate:
            default:
                return(AlertLevel.Fatal);
            }
        }
Exemple #2
0
 public Alert(
     AlertLevel level,
     AlertDescription description)
 {
     Level       = level;
     Description = description;
 }
 public Alert(
     AlertLevel level,
     AlertDescription description)
 {
     this.level       = level;
     this.description = description;
 }
 public void ProcessAlertMessage(AlertLevel level, AlertDescription desc)
 {
     if (level == AlertLevel.Fatal)
     {
         throw new SslFatalAlertReceived();
     }
 }
Exemple #5
0
        public override void NotifyAlertReceived(byte alertLevel, byte alertDescription)
        {
            string description = AlertDescription.GetText(alertDescription);

            AlertLevelsEnum level     = AlertLevelsEnum.Warning;
            AlertTypesEnum  alertType = AlertTypesEnum.unknown;

            if (Enum.IsDefined(typeof(AlertLevelsEnum), alertLevel))
            {
                level = (AlertLevelsEnum)alertLevel;
            }

            if (Enum.IsDefined(typeof(AlertTypesEnum), alertDescription))
            {
                alertType = (AlertTypesEnum)alertDescription;
            }

            if (alertType == AlertTypesEnum.close_notify)
            {
                logger.LogDebug(
                    $"DTLS client received close notification: {AlertLevel.GetText(alertLevel)}, {description}.");
            }
            else
            {
                logger.LogWarning(
                    $"DTLS client received unexpected alert: {AlertLevel.GetText(alertLevel)}, {description}.");
            }

            OnAlert?.Invoke(level, alertType, description);
        }
Exemple #6
0
 internal TlsException(
     AlertLevel level,
     AlertDescription description,
     string message) : base(message)
 {
     this.alert = new Alert(level, description);
 }
Exemple #7
0
 public static void WriteAlert(ref WritableBuffer output, AlertLevel level, AlertDescription description, State.IConnectionState connectionState)
 {
     connectionState.FrameWriter.StartFrame(RecordType.Alert, ref output);
     output.WriteBigEndian(level);
     output.WriteBigEndian(description);
     connectionState.FrameWriter.FinishFrame(ref output);
 }
Exemple #8
0
        public AlertMessage(AlertLevel level, AlertDescription description)
        {
            SecurityAssert.SAssert((AllowedDescLevels[(int)description] & level) != 0);

            Level = level;
            Description = description;
        }
Exemple #9
0
        public override void NotifyAlertRaised(byte alertLevel, byte alertDescription, string message, Exception cause)
        {
            string description = null;

            if (message != null)
            {
                description += message;
            }
            if (cause != null)
            {
                description += cause;
            }

            string alertMessage = $"{AlertLevel.GetText(alertLevel)}, {AlertDescription.GetText(alertDescription)}";

            alertMessage += !string.IsNullOrEmpty(description) ? $", {description}." : ".";

            if (alertDescription == AlertTypesEnum.close_notify.GetHashCode())
            {
                logger.LogDebug($"DTLS client raised close notification: {alertMessage}");
            }
            else
            {
                logger.LogWarning($"DTLS client raised unexpected alert: {alertMessage}");
            }
        }
Exemple #10
0
        public AlertMessage(AlertLevel level, AlertDescription description)
        {
            SecurityAssert.Assert(level.IsAllowed(description));

            Level       = level;
            Description = description;
        }
Exemple #11
0
		internal TlsException(
			AlertLevel			level,
			AlertDescription	description,
			string				message) : base (message)
		{
			this.alert = new Alert(level, description);
		}
Exemple #12
0
        public override void NotifyAlertReceived(byte alertLevel, byte alertDescription)
        {
            string description = AlertDescription.GetText(alertDescription);

            AlertLevelsEnum level     = AlertLevelsEnum.Warning;
            AlertTypesEnum  alertType = AlertTypesEnum.unknown;

            if (Enum.IsDefined(typeof(AlertLevelsEnum), alertLevel))
            {
                level = (AlertLevelsEnum)alertLevel;
            }

            if (Enum.IsDefined(typeof(AlertTypesEnum), alertDescription))
            {
                alertType = (AlertTypesEnum)alertDescription;
            }

            string alertMsg = $"{AlertLevel.GetText(alertLevel)}";

            alertMsg += (!string.IsNullOrEmpty(description)) ? $", {description}." : ".";

            if (alertType == AlertTypesEnum.close_notify)
            {
                logger.LogDebug($"DTLS server received close notification: {alertMsg}");
            }
            else
            {
                logger.LogWarning($"DTLS server received unexpected alert: {alertMsg}");
            }

            OnAlert?.Invoke(level, alertType, description);
        }
Exemple #13
0
        public override void NotifyAlertReceived(byte alertLevel, byte alertDescription)
        {
            TextWriter output = (alertLevel == AlertLevel.fatal) ? Console.Error : Console.Out;

            output.WriteLine("TLS-PSK client received alert: " + AlertLevel.GetText(alertLevel)
                             + ", " + AlertDescription.GetText(alertDescription));
        }
        /**
         * Terminate this connection with an alert.
         * <p/>
         * Can be used for normal closure too.
         *
         * @param alertLevel       The level of the alert, an be AlertLevel.fatal or AL_warning.
         * @param alertDescription The exact alert message.
         * @throws IOException If alert was fatal.
         */
        private void FailWithError(AlertLevel alertLevel, AlertDescription alertDescription)
        {
            /*
             * Check if the connection is still open.
             */
            if (!closed)
            {
                /*
                 * Prepare the message
                 */
                this.closed = true;

                if (alertLevel == AlertLevel.fatal)
                {
                    /*
                     * This is a fatal message.
                     */
                    this.failedWithError = true;
                }
                SendAlert(alertLevel, alertDescription);
                rs.Close();
                if (alertLevel == AlertLevel.fatal)
                {
                    throw new IOException(TLS_ERROR_MESSAGE);
                }
            }
            else
            {
                throw new IOException(TLS_ERROR_MESSAGE);
            }
        }
Exemple #15
0
        void RemoteValidation(ClientContext context, AlertDescription description)
        {
            ValidationResult res = context.SslStream.RaiseServerCertificateValidation2(certificates);

            if (res.Trusted)
            {
                return;
            }

            long error = res.ErrorCode;

            switch (error)
            {
            case 0x800B0101:
                description = AlertDescription.CertificateExpired;
                break;

            case 0x800B010A:
                description = AlertDescription.UnknownCA;
                break;

            case 0x800B0109:
                description = AlertDescription.UnknownCA;
                break;

            default:
                description = AlertDescription.CertificateUnknown;
                break;
            }
            string err = String.Format("Invalid certificate received from server. Error code: 0x{0:x}", error);

            throw new TlsException(description, err);
        }
        internal void SendAlert(AlertLevel alertLevel, AlertDescription alertDescription)
        {
            byte[] error = new byte[2];
            error[0] = (byte)alertLevel;
            error[1] = (byte)alertDescription;

            rs.WriteMessage(ContentType.alert, error, 0, 2);
        }
Exemple #17
0
        public override uint Deserialize(Span <byte> buffer)
        {
            uint byteCount = base.Deserialize(buffer);

            Level       = (AlertLevel)buffer[(int)byteCount++];
            Description = (AlertDescription)buffer[(int)byteCount++];
            return(byteCount);
        }
Exemple #18
0
        public Alert(byte[] data)
        {
            Level = AlertLevel.Fatal;
            Description = AlertDescription.IllegalParameter;

            if (data.Length == 2) {
                Level = (AlertLevel) data[0];
                Description = (AlertDescription) data[1];
            }
        }
        public async Task ExpectAlert(TestContext ctx, AlertDescription alert, CancellationToken cancellationToken)
        {
            var serverTask = Server.WaitForConnection(ctx, cancellationToken);
            var clientTask = Client.WaitForConnection(ctx, cancellationToken);

            var t1 = clientTask.ContinueWith(t => MonoConnectionHelper.ExpectAlert(ctx, t, alert, "client"));
            var t2 = serverTask.ContinueWith(t => MonoConnectionHelper.ExpectAlert(ctx, t, alert, "server"));

            await Task.WhenAll(t1, t2);
        }
Exemple #20
0
        public static void WriteAlert(ref WritableBuffer output, AlertLevel level, AlertDescription description, State.IConnectionState connectionState)
        {
            var buffer = new byte[sizeof(AlertLevel) + sizeof(AlertDescription)];
            var span   = new Span <byte>(buffer);

            span.Write(level);
            span = span.Slice(sizeof(AlertLevel));
            span.Write(description);
            RecordProcessor.WriteRecord(ref output, RecordType.Alert, buffer, connectionState);
        }
Exemple #21
0
        public Alert(byte[] data)
        {
            Level       = AlertLevel.Fatal;
            Description = AlertDescription.IllegalParameter;

            if (data.Length == 2)
            {
                Level       = (AlertLevel)data[0];
                Description = (AlertDescription)data[1];
            }
        }
Exemple #22
0
        public static void CheckAndThrow(UnityTls.unitytls_errorstate errorState, string context,
                                         AlertDescription defaultAlert = AlertDescription.InternalError)
        {
            if (errorState.code == UnityTls.unitytls_error_code.UNITYTLS_SUCCESS)
            {
                return;
            }

            var message = string.Format("{0} - error code: {1}", context, errorState.code);

            throw new TlsException(defaultAlert, message);
        }
Exemple #23
0
        private void ProcessAlert(AlertLevel alertLevel, AlertDescription alertDesc)
        {
            AlertLevel alertLevel2 = alertLevel;

            if (alertLevel2 != AlertLevel.Warning && alertLevel2 == AlertLevel.Fatal)
            {
                throw new TlsException(alertLevel, alertDesc);
            }
            if (alertDesc == AlertDescription.CloseNotify)
            {
                context.ReceivedConnectionEnd = true;
            }
        }
Exemple #24
0
        private void inferAlertLevel()
        {
            AlertDescription alertDescription = this.description;

            switch (alertDescription)
            {
            case AlertDescription.HandshakeFailiure:
            case AlertDescription.BadCertificate:
            case AlertDescription.UnsupportedCertificate:
            case AlertDescription.CertificateRevoked:
            case AlertDescription.CertificateExpired:
            case AlertDescription.CertificateUnknown:
            case AlertDescription.IlegalParameter:
            case AlertDescription.UnknownCA:
            case AlertDescription.AccessDenied:
            case AlertDescription.DecodeError:
            case AlertDescription.DecryptError:
            case AlertDescription.ExportRestriction:
                break;

            default:
                switch (alertDescription)
                {
                case AlertDescription.BadRecordMAC:
                case AlertDescription.DecryptionFailed:
                case AlertDescription.RecordOverflow:
                    break;

                default:
                    if (alertDescription != AlertDescription.ProtocolVersion && alertDescription != AlertDescription.InsuficientSecurity)
                    {
                        if (alertDescription != AlertDescription.CloseNotify)
                        {
                            if (alertDescription == AlertDescription.UnexpectedMessage || alertDescription == AlertDescription.DecompressionFailiure || alertDescription == AlertDescription.InternalError)
                            {
                                break;
                            }
                            if (alertDescription != AlertDescription.UserCancelled && alertDescription != AlertDescription.NoRenegotiation)
                            {
                                break;
                            }
                        }
                        this.level = AlertLevel.Warning;
                        return;
                    }
                    break;
                }
                break;
            }
            this.level = AlertLevel.Fatal;
        }
Exemple #25
0
        //ConnectionState readstate = new ConnectionState();
        //ConnectionState writestate = new ConnectionState();
        //ConnectionState pendingreadstate = new ConnectionState();
        //ConnectionState pendingwritestate = new ConnectionState();

        internal void SendAlert(AlertLevel level, AlertDescription desc)
        {
            TLSRecord       record = new TLSRecord();
            TLSAlertMessage msg    = new TLSAlertMessage();

            msg.AlertLevel       = level;
            msg.AlertDescription = desc;

            record.ContentType  = TLSContentType.Alert;
            record.MajorVersion = 0x03;
            record.MinorVersion = 0x01;
            record.Messages.Add(msg);
            Client.Send(record.Bytes, record.Bytes.Length, false);
        }
Exemple #26
0
        public override void NotifyAlertRaised(byte alertLevel, byte alertDescription, string message, Exception cause)
        {
            TextWriter output = (alertLevel == AlertLevel.fatal) ? Console.Error : Console.Out;

            output.WriteLine("TLS-PSK client raised alert: " + AlertLevel.GetText(alertLevel)
                             + ", " + AlertDescription.GetText(alertDescription));
            if (message != null)
            {
                output.WriteLine("> " + message);
            }
            if (cause != null)
            {
                output.WriteLine(cause);
            }
        }
        public override void NotifyAlertReceived(byte alertLevel, byte alertDescription)
        {
            if (alertLevel == AlertLevel.fatal && firstFatalAlertConnectionEnd == -1)
            {
                firstFatalAlertConnectionEnd = ConnectionEnd.server;
                firstFatalAlertDescription   = alertDescription;
            }

            if (TlsTestConfig.DEBUG)
            {
                TextWriter output = (alertLevel == AlertLevel.fatal) ? Console.Error : Console.Out;
                output.WriteLine("TLS client received alert: " + AlertLevel.GetText(alertLevel)
                                 + ", " + AlertDescription.GetText(alertDescription));
            }
        }
        private void ProcessAlert(AlertLevel alertLevel, AlertDescription alertDesc)
        {
            switch (alertLevel)
            {
            case AlertLevel.Fatal:
                throw new TlsException(alertLevel, alertDesc);

            default:
                if (alertDesc != AlertDescription.CloseNotify)
                {
                    break;
                }
                this.context.ReceivedConnectionEnd = true;
                break;
            }
        }
Exemple #29
0
        public static void CheckAndThrow(UnityTls.unitytls_errorstate errorState,
                                         UnityTls.unitytls_x509verify_result verifyResult, string context,
                                         AlertDescription defaultAlert = AlertDescription.InternalError)
        {
            // Ignore verify result if verification is not the issue.
            if (verifyResult == UnityTls.unitytls_x509verify_result.UNITYTLS_X509VERIFY_SUCCESS)
            {
                CheckAndThrow(errorState, context, defaultAlert);
                return;
            }

            var alert   = UnityTlsConversions.VerifyResultToAlertDescription(verifyResult, defaultAlert);
            var message = string.Format("{0} - error code: {1}, verify result: {2}", context, errorState.code,
                                        verifyResult);

            throw new TlsException(alert, message);
        }
Exemple #30
0
        void ExpectAlert(Task t, AlertDescription expectedAlert, string message)
        {
            Assert.That(t.IsFaulted, Is.True, "#1:" + message);
            var baseException = t.Exception.GetBaseException();

            if (baseException is AggregateException)
            {
                var aggregate = baseException as AggregateException;
                Assert.That(aggregate.InnerExceptions.Count, Is.EqualTo(2), "#2a:" + message);
                Assert.That(aggregate.InnerExceptions [0], Is.InstanceOf <AuthenticationException> (), "#2b:" + message);
                baseException = aggregate.InnerExceptions [1];
            }
            Assert.That(baseException, Is.InstanceOf <TlsException> (), "#2:" + message);
            var alert = ((TlsException)baseException).Alert;

            Assert.That(alert.Level, Is.EqualTo(AlertLevel.Fatal), "#3:" + message);
            Assert.That(alert.Description, Is.EqualTo(expectedAlert), "#4:" + message);
        }
Exemple #31
0
        private void ProcessAlert(AlertLevel alertLevel, AlertDescription alertDesc)
        {
            switch (alertLevel)
            {
            case AlertLevel.Fatal:
                throw new TlsException(alertLevel, alertDesc);

            case AlertLevel.Warning:
            default:
                switch (alertDesc)
                {
                case AlertDescription.CloseNotify:
                    this.context.ConnectionEnd = true;
                    break;
                }
                break;
            }
        }
Exemple #32
0
        protected SslHandshakeStatus ProcessAlert(RecordMessage message)
        {
            if (message.length != 2 || message.fragment.Length != 2)
            {
                throw new SslException(AlertDescription.RecordOverflow, "The alert message is invalid.");
            }
            try {
                AlertLevel       level       = (AlertLevel)message.fragment[0];
                AlertDescription description = (AlertDescription)message.fragment[1];

                if (level == AlertLevel.Fatal && description == AlertDescription.NoApplicationProtocol)
                {
                    throw new ALPNCantSelectProtocolException();
                }

                if (level == AlertLevel.Fatal)
                {
                    throw new SslException(description, "The other side has sent a failure alert with code: " + description.ToString());
                }
                SslHandshakeStatus ret;
                if (description == AlertDescription.CloseNotify)
                {
                    if (m_State == HandshakeType.ShuttingDown)                       // true if we've already sent a shutdown notification
                    // close connection
                    {
                        ret = new SslHandshakeStatus(SslStatus.Close, null);
                    }
                    else
                    {
                        // send a shutdown notifications, and then close the connection
                        ret = new SslHandshakeStatus(SslStatus.Close, GetControlBytes(ControlType.Shutdown));
                    }
                }
                else
                {
                    ret = new SslHandshakeStatus(SslStatus.OK, null);
                }
                return(ret);
            } catch (SslException) {
                throw;
            } catch (Exception e) {
                throw new SslException(e, AlertDescription.InternalError, "There was an internal error.");
            }
        }
		public static void ExpectAlert (TestContext ctx, Task t, AlertDescription expectedAlert, string message)
		{
			ctx.Assert (t.IsFaulted, Is.True, "#1:" + message);
			var baseException = t.Exception.GetBaseException ();
			if (baseException is AggregateException) {
				var aggregate = baseException as AggregateException;
				ctx.Assert (aggregate.InnerExceptions.Count, Is.EqualTo (2), "#2a:" + message);
				var authExcType = aggregate.InnerExceptions [0].GetType ();
				ctx.Assert (authExcType.FullName, Is.EqualTo ("System.Security.Authentication.AuthenticationException"), "#2b:" + message);
				baseException = aggregate.InnerExceptions [1];
			}
			// OpenSsl can't report TlsException's like Mono.
			if (baseException.GetType ().FullName.Equals ("Mono.Security.NewTls.TestProvider.NativeOpenSslException"))
				return;
			ctx.Assert (baseException, Is.InstanceOf<TlsException> (), "#2:" + message);
			var alert = ((TlsException)baseException).Alert;
			ctx.Assert (alert.Level, Is.EqualTo (AlertLevel.Fatal), "#3:" + message);
			ctx.Assert (alert.Description, Is.EqualTo (expectedAlert), "#4:" + message);
		}
        public async Task ConnectAsync(CoapTransportLayerConnectOptions connectOptions, CancellationToken cancellationToken)
        {
            if (connectOptions == null)
            {
                throw new ArgumentNullException(nameof(connectOptions));
            }

            cancellationToken.ThrowIfCancellationRequested();

            try
            {
                _udpTransport = new UdpTransport(connectOptions);
                var clientProtocol = new DtlsClientProtocol(_secureRandom);
                _dtlsClient = new DtlsClient(ConvertProtocolVersion(DtlsVersion), (PreSharedKey)Credentials);

                using (cancellationToken.Register(() =>
                {
                    _udpTransport.Close();
                }))
                {
                    _dtlsTransport = await Task.Run(() => clientProtocol.Connect(_dtlsClient, _udpTransport), cancellationToken).ConfigureAwait(false);
                }
            }
            catch
            {
                _udpTransport?.Dispose();

                if (cancellationToken.IsCancellationRequested)
                {
                    throw new OperationCanceledException();
                }

                if (_dtlsClient.ReceivedAlert != 0)
                {
                    throw new DtlsException($"Received alert {AlertDescription.GetText(_dtlsClient.ReceivedAlert)}.", null)
                          {
                              ReceivedAlert = _dtlsClient.ReceivedAlert
                          };
                }

                throw;
            }
        }
Exemple #35
0
 public void SendAlert(AlertLevel level, AlertDescription description)
 {
     state.RecordWriter.WriteRecord(new Record(RecordType.Alert, state.Version, new[]
     {
         (byte)level,
         (byte)description
     }));
     state.Flush();
 }
Exemple #36
0
		public SslException(AlertDescription description, string message) : this(null, description, message) {}
Exemple #37
0
 internal Alert(AlertDescription description, AlertLevel level)
 {
     this.Level = level;
     this.Description = description;
 }
		public AlertException(AlertDescription description) : base()
		{
			_description = AlertDescription;
		}
		void RemoteValidation (ClientContext context, AlertDescription description)
		{
			ValidationResult res = context.SslStream.RaiseServerCertificateValidation2 (certificates);
			if (res.Trusted)
				return;

			long error = res.ErrorCode;
			switch (error) {
			case 0x800B0101:
				description = AlertDescription.CertificateExpired;
				break;
			case 0x800B010A:
				description = AlertDescription.UnknownCA;
				break;
			case 0x800B0109:
				description = AlertDescription.UnknownCA;
				break;
			default:
				description = AlertDescription.CertificateUnknown;
				break;
			}
			string err = String.Format ("Invalid certificate received from server. Error code: 0x{0:x}", error);
			throw new TlsException (description, err);
		}
		internal void SendAlert(AlertLevel alertLevel, AlertDescription alertDescription)
		{
			byte[] error = new byte[2];
			error[0] = (byte)alertLevel;
			error[1] = (byte)alertDescription;

			rs.WriteMessage(ContentType.alert, error, 0, 2);
		}
 public ServerAlertException(AlertDescription description) : base(description.ToString())
 {
     Description = description;
 }
Exemple #42
0
		public Alert(
			AlertLevel			level,
			AlertDescription	description)
		{
			this.level			= level;
			this.description	= description;
		}
Exemple #43
0
		public static string GetAlertMessage(AlertDescription description)
		{
			#if (DEBUG)
			switch (description)
			{
				case AlertDescription.AccessDenied:
					return "An inappropriate message was received.";

				case AlertDescription.BadCertificate:
					return "TLSCiphertext decrypted in an invalid way.";

				case AlertDescription.BadRecordMAC:
					return "Record with an incorrect MAC.";

				case AlertDescription.CertificateExpired:
					return "Certificate has expired or is not currently valid";

				case AlertDescription.CertificateRevoked:
					return "Certificate was revoked by its signer.";
					
				case AlertDescription.CertificateUnknown:
					return "Certificate Unknown.";

				case AlertDescription.CloseNotify:
					return "Connection closed";

				case AlertDescription.DecodeError:
					return "A message could not be decoded because some field was out of the specified range or the length of the message was incorrect.";

				case AlertDescription.DecompressionFailure:
					return "The decompression function received improper input (e.g. data that would expand to excessive length).";

				case AlertDescription.DecryptError:
					return "TLSCiphertext decrypted in an invalid way: either it wasn`t an even multiple of the block length or its padding values, when checked, weren`t correct.";

				case AlertDescription.DecryptionFailed_RESERVED:
					return "Handshake cryptographic operation failed, including being unable to correctly verify a signature, decrypt a key exchange, or validate finished message.";

				case AlertDescription.ExportRestriction:
					return "Negotiation not in compliance with export restrictions was detected.";

				case AlertDescription.HandshakeFailure:
					return "Unable to negotiate an acceptable set of security parameters given the options available.";

				case AlertDescription.IlegalParameter:
					return "A field in the handshake was out of range or inconsistent with other fields.";
					
				case AlertDescription.InsuficientSecurity:
					return "Negotiation has failed specifically because the server requires ciphers more secure than those supported by the client.";
					
				case AlertDescription.InternalError:
					return "Internal error unrelated to the peer or the correctness of the protocol makes it impossible to continue.";

				case AlertDescription.NoRenegotiation:
					return "Invalid renegotiation.";

				case AlertDescription.ProtocolVersion:
					return "Unsupported protocol version.";

				case AlertDescription.RecordOverflow:
					return "Invalid length on TLSCiphertext record or TLSCompressed record.";

				case AlertDescription.UnexpectedMessage:
					return "Invalid message received.";

				case AlertDescription.UnknownCA:
					return "CA can't be identified as a trusted CA.";

				case AlertDescription.UnsupportedCertificate:
					return "Certificate was of an unsupported type.";

				case AlertDescription.UserCancelled:
					return "Handshake cancelled by user.";

				case AlertDescription.UnsupportedExtension:
					return "Unsupported extension.";

				default:
					return "";
			}
			#else
			return "The authentication or decryption has failed.";
			#endif
		}
Exemple #44
0
		public Alert(AlertDescription description)
		{
			this.description = description;
			this.inferAlertLevel();
		}
Exemple #45
0
 public Alert(AlertLevel level, AlertDescription description, ProtocolVersion version)
 {
     Level = level;
     Description = description;
     ValidateForProtocolVersion(version);
 }
Exemple #46
0
        private void ValidateForProtocolVersion(ProtocolVersion version)
        {
            switch (Description) {
            // Warning alerts that are SSLv3 only
            case AlertDescription.NoCertificate:
                Level = AlertLevel.Warning;
                if (version != ProtocolVersion.SSL3_0)
                    Level = AlertLevel.None;
                break;

            // Warning alerts supported in all versions
            case AlertDescription.CloseNotify:
                Level = AlertLevel.Warning;
                break;

            // Fatal alerts supported in all versions
            case AlertDescription.UnexpectedMessage:
            case AlertDescription.BadRecordMAC:
            case AlertDescription.DecompressionFailure:
            case AlertDescription.HandshakeFailure:
            case AlertDescription.IllegalParameter:
                Level = AlertLevel.Fatal;
                break;

            // Other alerts supported in all versions
            case AlertDescription.BadCertificate:
            case AlertDescription.UnsupportedCertificate:
            case AlertDescription.CertificateRevoked:
            case AlertDescription.CertificateExpired:
            case AlertDescription.CertificateUnknown:
                break;

            // Fatal alerts that are TLS only
            case AlertDescription.UnknownCA:
            case AlertDescription.AccessDenied:
                Level = AlertLevel.Fatal;
                if (version == ProtocolVersion.SSL3_0)
                    Description = AlertDescription.CertificateUnknown;
                break;
            case AlertDescription.RecordOverflow:
            case AlertDescription.DecodeError:
            case AlertDescription.DecryptError:
            case AlertDescription.InternalError:
                Level = AlertLevel.Fatal;
                if (version == ProtocolVersion.SSL3_0)
                    Description = AlertDescription.IllegalParameter;
                break;
            case AlertDescription.ProtocolVersion:
            case AlertDescription.InsufficientSecurity:
                Level = AlertLevel.Fatal;
                if (version == ProtocolVersion.SSL3_0)
                    Description = AlertDescription.HandshakeFailure;
                break;

            // Warning alerts that are TLS only
            case AlertDescription.UserCanceled:
            case AlertDescription.NoRenegotiation:
                Level = AlertLevel.Warning;
                if (version == ProtocolVersion.SSL3_0)
                    Level = AlertLevel.None;
                break;

            // Fatal alerts that are TLSv1.2 only
            case AlertDescription.UnsupportedExtension:
                Level = AlertLevel.Fatal;
                if (version != ProtocolVersion.TLS1_2)
                    Description = AlertDescription.IllegalParameter;
                break;
            }
        }
		public async Task ExpectAlert (TestContext ctx, AlertDescription alert, CancellationToken cancellationToken)
		{
			var serverTask = Server.WaitForConnection (ctx, cancellationToken);
			var clientTask = Client.WaitForConnection (ctx, cancellationToken);

			var t1 = clientTask.ContinueWith (t => MonoConnectionHelper.ExpectAlert (ctx, t, alert, "client"));
			var t2 = serverTask.ContinueWith (t => MonoConnectionHelper.ExpectAlert (ctx, t, alert, "server"));

			await Task.WhenAll (t1, t2);
		}
 void WriteAlertFatal(AlertDescription description)
 {
     _buf[0] = (byte)ContentType.Alert;
     Utils.WriteUInt16(_buf, 1, (ushort)_connState.TlsVersion);
     _buf[5 + _connState.IvLen] = (byte)AlertLevel.Fatal;
     _buf[5 + _connState.IvLen + 1] = (byte)description;
     int endPos = Encrypt(0, 2);
     _baseStream.Write(_buf, 0, endPos);
     _baseStream.Flush();
     _baseStream.Dispose();
     _eof = true;
     _closed = true;
     _connState.Dispose();
     _pendingConnState?.Dispose();
     if (_temp512 != null)
         Utils.ClearArray(_temp512);
 }
		private void ProcessAlert(AlertLevel alertLevel, AlertDescription alertDesc)
		{
			switch (alertLevel)
			{
				case AlertLevel.Fatal:
					throw new TlsException(alertLevel, alertDesc);

				case AlertLevel.Warning:
				default:
				switch (alertDesc)
				{
					case AlertDescription.CloseNotify:
						this.context.ConnectionEnd = true;
						break;
				}
				break;
			}
		}
		void LocalValidation (ClientContext context, AlertDescription description)
		{
			// the leaf is the web server certificate
			X509Certificate leaf = certificates [0];
			X509Cert.X509Certificate cert = new X509Cert.X509Certificate (leaf.RawData);

			ArrayList errors = new ArrayList();

			// SSL specific check - not all certificates can be 
			// used to server-side SSL some rules applies after 
			// all ;-)
			if (!checkCertificateUsage (leaf)) 
			{
				// WinError.h CERT_E_PURPOSE 0x800B0106
				errors.Add ((int)-2146762490);
			}

			// SSL specific check - does the certificate match 
			// the host ?
			if (!checkServerIdentity (leaf))
			{
				// WinError.h CERT_E_CN_NO_MATCH 0x800B010F
				errors.Add ((int)-2146762481);
			}

			// Note: building and verifying a chain can take much time
			// so we do it last (letting simple things fails first)

			// Note: In TLS the certificates MUST be in order (and
			// optionally include the root certificate) so we're not
			// building the chain using LoadCertificate (it's faster)

			// Note: IIS doesn't seem to send the whole certificate chain
			// but only the server certificate :-( it's assuming that you
			// already have this chain installed on your computer. duh!
			// http://groups.google.ca/groups?q=IIS+server+certificate+chain&hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=85058s%24avd%241%40nnrp1.deja.com&rnum=3

			// we must remove the leaf certificate from the chain
			X509CertificateCollection chain = new X509CertificateCollection (certificates);
			chain.Remove (leaf);
			X509Chain verify = new X509Chain (chain);

			bool result = false;

			try
			{
				result = verify.Build (leaf);
			}
			catch (Exception)
			{
				result = false;
			}

			if (!result) 
			{
				switch (verify.Status) 
				{
					case X509ChainStatusFlags.InvalidBasicConstraints:
						// WinError.h TRUST_E_BASIC_CONSTRAINTS 0x80096019
						errors.Add ((int)-2146869223);
						break;
					
					case X509ChainStatusFlags.NotSignatureValid:
						// WinError.h TRUST_E_BAD_DIGEST 0x80096010
						errors.Add ((int)-2146869232);
						break;
					
					case X509ChainStatusFlags.NotTimeNested:
						// WinError.h CERT_E_VALIDITYPERIODNESTING 0x800B0102
						errors.Add ((int)-2146762494);
						break;
					
					case X509ChainStatusFlags.NotTimeValid:
						// WinError.h CERT_E_EXPIRED 0x800B0101
						description = AlertDescription.CertificateExpired;
						errors.Add ((int)-2146762495);
						break;
					
					case X509ChainStatusFlags.PartialChain:
						// WinError.h CERT_E_CHAINING 0x800B010A
						description = AlertDescription.UnknownCA;
						errors.Add ((int)-2146762486);
						break;
					
					case X509ChainStatusFlags.UntrustedRoot:
						// WinError.h CERT_E_UNTRUSTEDROOT 0x800B0109
						description = AlertDescription.UnknownCA;
						errors.Add ((int)-2146762487);
						break;
					
					default:
						// unknown error
						description = AlertDescription.CertificateUnknown;
						errors.Add ((int)verify.Status);
						break;
				}
			}

			int[] certificateErrors = (int[])errors.ToArray(typeof(int));

			if (!context.SslStream.RaiseServerCertificateValidation(
				cert, 
				certificateErrors))
			{
				throw new TlsException(
					description,
					"Invalid certificate received from server.");
			}
		}
		public void SendAlert(
			AlertLevel			level, 
			AlertDescription	description)
		{
			this.SendAlert(new Alert(level, description));
		}
 void SendAlertFatal(AlertDescription description, string message = null)
 {
     throw new ClientAlertException(description, message);
 }
		/**
		* Terminate this connection with an alert.
		* <p/>
		* Can be used for normal closure too.
		*
		* @param alertLevel       The level of the alert, an be AlertLevel.fatal or AL_warning.
		* @param alertDescription The exact alert message.
		* @throws IOException If alert was fatal.
		*/
		private void FailWithError(AlertLevel alertLevel, AlertDescription	alertDescription)
		{
			/*
			* Check if the connection is still open.
			*/
			if (!closed)
			{
				/*
				* Prepare the message
				*/
				this.closed = true;

				if (alertLevel == AlertLevel.fatal)
				{
					/*
					* This is a fatal message.
					*/
					this.failedWithError = true;
				}
				SendAlert(alertLevel, alertDescription);
				rs.Close();
				if (alertLevel == AlertLevel.fatal)
				{
					throw new IOException(TLS_ERROR_MESSAGE);
				}
			}
			else
			{
				throw new IOException(TLS_ERROR_MESSAGE);
			}
		}
Exemple #54
0
		internal TlsException(
			AlertDescription description) 
			: this (description, Alert.GetAlertMessage(description))
		{
		}
Exemple #55
0
 public Alert(AlertDescription description, ProtocolVersion version)
     : this(AlertLevel.Fatal, description, version)
 {
 }
Exemple #56
0
 public Alert(AlertLevel level, AlertDescription desc)
     : base(ContentType.Alert)
 {
     _level = level;
     _desc = desc;
 }
		public void SendAlert(AlertDescription description)
		{
			this.SendAlert(new Alert(description));
		}
Exemple #58
0
		private static AlertLevel inferAlertLevel(AlertDescription description)
		{
			switch (description)
			{
				case AlertDescription.CloseNotify:
				case AlertDescription.NoRenegotiation:
				case AlertDescription.UserCancelled:
					return AlertLevel.Warning;

				case AlertDescription.AccessDenied:
				case AlertDescription.BadCertificate:
				case AlertDescription.BadRecordMAC:
				case AlertDescription.CertificateExpired:
				case AlertDescription.CertificateRevoked:
				case AlertDescription.CertificateUnknown:
				case AlertDescription.DecodeError:
				case AlertDescription.DecompressionFailiure:
				case AlertDescription.DecryptError:
				case AlertDescription.DecryptionFailed:
				case AlertDescription.ExportRestriction:
				case AlertDescription.HandshakeFailiure:
				case AlertDescription.IlegalParameter:
				case AlertDescription.InsuficientSecurity:
				case AlertDescription.InternalError:
				case AlertDescription.ProtocolVersion:
				case AlertDescription.RecordOverflow:
				case AlertDescription.UnexpectedMessage:
				case AlertDescription.UnknownCA:
				case AlertDescription.UnsupportedCertificate:
				default:
					return AlertLevel.Fatal;
			}
		}
		public AlertException(AlertDescription description, string message, Exception e) : base(message, e)
		{
			_description = description;
		}
Exemple #60
0
		public SslException(Exception e, AlertDescription description, string message) : base(message, e) {
			m_AlertDescription = description;
		}