Ejemplo n.º 1
0
        public async Task NegotiateSessionAsync_InvalidStateValidOptions_ThrowsInvalidOperationException()
        {
            var target = GetTarget(SessionState.Negotiating);

            var compressionOptions = new SessionCompression[] { SessionCompression.None };
            var encryptionOptions  = new SessionEncryption[] { SessionEncryption.None, SessionEncryption.TLS };

            var cancellationToken = DataUtil.CreateCancellationToken();

            var actual = await target.NegotiateSessionAsync(compressionOptions, encryptionOptions, cancellationToken);
        }
Ejemplo n.º 2
0
        public async Task NegotiateSessionAsync_EmptyEncryptionOptions_ThrowsArgumentException()
        {
            var target             = GetTarget();
            var compressionOptions = new SessionCompression[] { SessionCompression.None };
            var encryptionOptions  = new SessionEncryption[0];
            var cancellationToken  = Dummy.CreateCancellationToken();

            var actual =
                await
                target.NegotiateSessionAsync(compressionOptions, encryptionOptions, cancellationToken)
                .ShouldThrowAsync <ArgumentException>();
        }
Ejemplo n.º 3
0
        public async Task NegotiateSessionAsync_InvalidStateValidOptions_ThrowsInvalidOperationException()
        {
            // Arrange
            var target             = GetTarget(SessionState.Negotiating);
            var compressionOptions = new SessionCompression[] { SessionCompression.None };
            var encryptionOptions  = new SessionEncryption[] { SessionEncryption.None, SessionEncryption.TLS };
            var cancellationToken  = Dummy.CreateCancellationToken();

            // Act
            var actual =
                await
                target.NegotiateSessionAsync(compressionOptions, encryptionOptions, cancellationToken)
                .ShouldThrowAsync <InvalidOperationException>();
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TransportInformation"/> class.
 /// </summary>
 /// <param name="compression">The compression.</param>
 /// <param name="encryption">The encryption.</param>
 /// <param name="isConnected">if set to <c>true</c> [is connected].</param>
 /// <param name="localEndPoint">The local end point.</param>
 /// <param name="remoteEndPoint">The remote end point.</param>
 /// <param name="options">The options.</param>
 public TransportInformation(
     SessionCompression compression,
     SessionEncryption encryption,
     bool isConnected,
     string localEndPoint,
     string remoteEndPoint,
     IReadOnlyDictionary <string, object> options)
 {
     Compression    = compression;
     Encryption     = encryption;
     IsConnected    = isConnected;
     LocalEndPoint  = localEndPoint;
     RemoteEndPoint = remoteEndPoint;
     Options        = options;
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Sends a negotiate session envelope
        /// to accepts the session negotiation options
        /// and awaits for the server confirmation.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <param name="sessionCompression">The session compression option</param>
        /// <param name="sessionEncryption">The session encryption option</param>
        /// <returns></returns>
        /// <exception cref="System.InvalidOperationException">
        /// Cannot await for a session response since there's already a listener.
        /// </exception>
        public async Task<Session> NegotiateSessionAsync(SessionCompression sessionCompression, SessionEncryption sessionEncryption, CancellationToken cancellationToken)
        {
            if (this.State != SessionState.Negotiating)
            {
                throw new InvalidOperationException(string.Format("Cannot negotiate a session in the '{0}' state", this.State));
            }

            var session = new Session()
            {
                Id = this.SessionId,
                State = SessionState.Negotiating,
                Compression = sessionCompression,
                Encryption = sessionEncryption
            };

            await base.SendSessionAsync(session).ConfigureAwait(false);
            return await this.ReceiveSessionAsync(cancellationToken).ConfigureAwait(false);
        }
Ejemplo n.º 6
0
        public ActionResult LogOff()
        {
            //Log out from sub user redirect to sub user log in
            //long subUserId = Utility.GetLong(SessionEncryption.GetValueFromSession(SessionItemKey.SubUserId));

            if (Session != null)
            {
                string queryString = string.Empty;
                SessionEncryption.SetSessionValue(SessionItemKey.EmailAddress, null);
                SessionEncryption.SetSessionValue(SessionItemKey.UserId, null);
                SessionEncryption.SetSessionValue(SessionItemKey.UserName, null);
            }
            FormsAuthentication.SignOut();
            if (Session != null)
            {
                Session.Abandon();
                Session.Clear();
            }
            return(Redirect(Url.RouteUrl(new { Controller = "Datamantra", Action = "Index" })));
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Changes the session state and 
        /// sends a negotiate session envelope
        /// to the node with the available 
        /// options and awaits for the client
        /// selected option.
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <param name="compressionOptions">The session compression options.</param>
        /// <param name="encryptionOptions"></param>
        /// <returns>
        /// A negotiating session envelope with the client node selected options.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">
        /// compressionOptions
        /// or
        /// encryptionOptions
        /// </exception>
        /// <exception cref="System.ArgumentException">
        /// No available options for compression negotiation
        /// or
        /// No available options for encryption negotiation
        /// </exception>
        /// <exception cref="System.InvalidOperationException">Cannot await for a session response since there's already a listener.</exception>
        public async Task<Session> NegotiateSessionAsync(SessionCompression[] compressionOptions, SessionEncryption[] encryptionOptions, CancellationToken cancellationToken)
        {
            if (base.State != SessionState.New)
            {
                throw new InvalidOperationException(string.Format("Cannot start a session negotiating in the '{0}' state", this.State));
            }

            if (compressionOptions == null)
            {
                throw new ArgumentNullException("compressionOptions");
            }

            if (compressionOptions.Length == 0)
            {
                throw new ArgumentException("No available options for compression negotiation");
            }

            if (encryptionOptions == null)
            {
                throw new ArgumentNullException("encryptionOptions");
            }

            if (encryptionOptions.Length == 0)
            {
                throw new ArgumentException("No available options for encryption negotiation");
            }

            base.State = SessionState.Negotiating;

            var session = new Session()
            {
                Id = base.SessionId,
                From = base.LocalNode,
                State = base.State,
                CompressionOptions = compressionOptions,
                EncryptionOptions = encryptionOptions
            };

            await base.SendSessionAsync(session).ConfigureAwait(false);
            return await this.ReceiveSessionAsync(cancellationToken).ConfigureAwait(false);
        }
Ejemplo n.º 8
0
        public async Task NegotiateSessionAsync_NewStateValidOptions_CallsTransportAndReadsFromBuffer()
        {
            var session = DataUtil.CreateSession(SessionState.Negotiating);


            var target = GetTarget(sessionId: session.Id);

            var compressionOptions = new SessionCompression[] { SessionCompression.None };
            var encryptionOptions  = new SessionEncryption[] { SessionEncryption.None, SessionEncryption.TLS };

            var cancellationToken = DataUtil.CreateCancellationToken();

            _transport
            .Setup(t => t.ReceiveAsync(It.IsAny <CancellationToken>()))
            .Returns(() => Task.FromResult <Envelope>(session))
            .Verifiable();

            var actual = await target.NegotiateSessionAsync(compressionOptions, encryptionOptions, cancellationToken);

            _transport.Verify();

            _transport.Verify(
                t => t.SendAsync(
                    It.Is <Session>(e => e.State == SessionState.Negotiating &&
                                    e.CompressionOptions == compressionOptions &&
                                    e.EncryptionOptions == encryptionOptions &&
                                    e.From.Equals(target.LocalNode) &&
                                    e.To == null &&
                                    e.SchemeOptions == null &&
                                    e.Compression == null &&
                                    e.Encryption == null &&
                                    e.Authentication == null &&
                                    e.Id == target.SessionId),
                    It.IsAny <CancellationToken>()),
                Times.Once());

            Assert.AreEqual(SessionState.Negotiating, target.State);
            Assert.AreEqual(session, actual);
        }
Ejemplo n.º 9
0
        public ActionResult SignUp(User user)
        {
            User userRes = new User();

            using (var client = new DatamantraAPIClient())
            {
                string requestUri    = "User/SaveUser";
                var    _UserResponse = client.PostAsJsonAsync(requestUri, user).Result;
                if (_UserResponse != null && _UserResponse.IsSuccessStatusCode)
                {
                    userRes = _UserResponse.Content.ReadAsAsync <User>().Result;
                    if (userRes != null && userRes.Status == StatusType.Success)
                    {
                        SessionEncryption.SetSessionValue(SessionItemKey.RoleID, userRes.RoleId);
                        SessionEncryption.SetSessionValue(SessionItemKey.UserId, userRes.UserId);
                        SessionEncryption.SetSessionValue(SessionItemKey.UserName, userRes.UserName);
                        SessionEncryption.SetSessionValue(SessionItemKey.EmailAddress, userRes.EmailAddress);
                    }
                }
            }
            return(Json(userRes, JsonRequestBehavior.AllowGet));
        }
Ejemplo n.º 10
0
        /// <summary>
        /// 获取远程配置内容
        /// </summary>
        /// <param name="url">远程配置服务地址</param>
        /// <param name="solutionID">app配置方案ID</param>
        /// <param name="token">app的安全令牌</param>
        /// <returns></returns>
        private AppConfig GetRemote(string url, Guid solutionID, string token, int version, int appId)
        {
            SessionEncryption se = new SessionEncryption();
            var dic = new Dictionary <string, string>();

            dic.Add("sid", solutionID.ToString());
            dic.Add("v", version.ToString());
            dic.Add("apt", se.Encrypt(token));
            dic.Add("appid", appId.ToString());
            string    str    = "";
            AppConfig result = null;

            Console.WriteLine("请求地址:" + url + ";sid:" + solutionID.ToString());
            str = _httpRequestHelper.Transaction(url, dic);
            //str = HttpUtility.UrlDecode(str);
            //str = str;//解密TODO,等待安全算法实现后替换
            Console.WriteLine("发送配置内容:" + str);
            try
            {
                var response = Newtonsoft.Json.JsonConvert.DeserializeObject <TransactionResult <AppConfig> >(str);
                if (response.Code == 0)
                {
                    result = response.Data;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("远程结果:" + str + "--异常:" + ex.Message);
            }
            if (result == null)
            {
                throw new Exception("获取远程配置错误,远程结果:" + str);
            }

            return(result);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Send a negotiate session envelope
        /// to the remote node to confirm the
        /// session negotiation options.
        /// </summary>
        /// <param name="sessionCompression">The session compression option</param>
        /// <param name="sessionEncryption">The session encryption option</param>
        /// <returns></returns>
        /// <exception cref="System.InvalidOperationException"></exception>
        public Task SendNegotiatingSessionAsync(SessionCompression sessionCompression, SessionEncryption sessionEncryption)
        {
            if (this.State != SessionState.Negotiating)
            {
                throw new InvalidOperationException(string.Format("Cannot negotiate a session in the '{0}' state", this.State));
            }

            var session = new Session()
            {
                Id          = this.SessionId,
                From        = this.LocalNode,
                State       = base.State,
                Compression = sessionCompression,
                Encryption  = sessionEncryption
            };

            return(this.SendSessionAsync(session));
        }
 public Task SetEncryptionAsync(SessionEncryption encryption, CancellationToken cancellationToken)
 {
     return(_transport.SetEncryptionAsync(encryption, cancellationToken).WithCancellation(cancellationToken));
 }
 public TConfigurator UsingEncryption(SessionEncryption sessionEncryption)
 {
     Encryption = sessionEncryption;
     return((TConfigurator)this);
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Defines the encryption mode
        /// for the transport
        /// </summary>
        /// <param name="encryption"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="System.NotSupportedException"></exception>
        public override async Task SetEncryptionAsync(SessionEncryption encryption, CancellationToken cancellationToken)
        {
            if (_sendSemaphore.CurrentCount == 0)
            {
                System.Console.WriteLine("Send semaphore being used");
            }

            if (_receiveSemaphore.CurrentCount == 0)
            {
                System.Console.WriteLine("Receive semaphore being used");
            }

            await _sendSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);

            try
            {
                await _receiveSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);

                try
                {
                    switch (encryption)
                    {
                    case SessionEncryption.None:
                        _stream = _tcpClient.GetStream();
                        break;

                    case SessionEncryption.TLS:
                        SslStream sslStream;

                        if (_serverCertificate != null)
                        {
                                                        #if MONO
                            // Server
                            sslStream = new SslStream(
                                _stream,
                                false,
                                new RemoteCertificateValidationCallback(ValidateClientCertificate),
                                null);
                                                        #else
                            // Server
                            sslStream = new SslStream(
                                _stream,
                                false,
                                new RemoteCertificateValidationCallback(ValidateClientCertificate),
                                null,
                                EncryptionPolicy.RequireEncryption);
                                                        #endif

                            await sslStream
                            .AuthenticateAsServerAsync(
                                _serverCertificate,
                                true,
                                SslProtocols.Tls,
                                false)
                            .WithCancellation(cancellationToken)
                            .ConfigureAwait(false);
                        }
                        else
                        {
                            // Client
                            if (string.IsNullOrWhiteSpace(_hostName))
                            {
                                throw new InvalidOperationException("The hostname is mandatory for TLS client encryption support");
                            }

                            sslStream = new SslStream(
                                _stream,
                                false,
                                new RemoteCertificateValidationCallback(ValidateServerCertificate));

                            X509CertificateCollection clientCertificates = null;

                            if (_clientCertificate != null)
                            {
                                clientCertificates = new X509CertificateCollection(new[] { _clientCertificate });
                            }

                            await sslStream
                            .AuthenticateAsClientAsync(
                                _hostName,
                                clientCertificates,
                                SslProtocols.Tls,
                                false)
                            .WithCancellation(cancellationToken)
                            .ConfigureAwait(false);
                        }

                        _stream = sslStream;
                        break;

                    default:
                        throw new NotSupportedException();
                    }

                    this.Encryption = encryption;
                }
                finally
                {
                    _receiveSemaphore.Release();
                }
            }
            finally
            {
                _sendSemaphore.Release();
            }
        }
Ejemplo n.º 15
0
		/// <summary>
		/// Defines the encryption mode
		/// for the transport
		/// </summary>
		/// <param name="encryption"></param>
		/// <param name="cancellationToken"></param>
		/// <returns></returns>
		/// <exception cref="System.NotSupportedException"></exception>        
		public override async Task SetEncryptionAsync(SessionEncryption encryption, CancellationToken cancellationToken)
		{
			if (_sendSemaphore.CurrentCount == 0)
			{
				System.Console.WriteLine("Send semaphore being used");
			}

			if (_receiveSemaphore.CurrentCount == 0)
			{
				System.Console.WriteLine("Receive semaphore being used");
			}

			await _sendSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
			try
			{
				await _receiveSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
				try
				{
					switch (encryption)
					{
						case SessionEncryption.None:
							_stream = _tcpClient.GetStream();
							break;
						case SessionEncryption.TLS:
							SslStream sslStream;

							if (_serverCertificate != null)
							{
							#if MONO
								// Server
								sslStream = new SslStream(
									_stream,
									false,
									new RemoteCertificateValidationCallback(ValidateClientCertificate),
									null);
							#else

								// Server
								sslStream = new SslStream(
									_stream,
									false,
									new RemoteCertificateValidationCallback(ValidateClientCertificate),
									null,
									EncryptionPolicy.RequireEncryption);
							#endif

								await sslStream
									.AuthenticateAsServerAsync(
										_serverCertificate,
										true,
										SslProtocols.Tls,
										false)
									.WithCancellation(cancellationToken)
									.ConfigureAwait(false);                                    
							}
							else
							{
								// Client
								if (string.IsNullOrWhiteSpace(_hostName))
								{
									throw new InvalidOperationException("The hostname is mandatory for TLS client encryption support");
								}

								sslStream = new SslStream(
									_stream,
									false,
									 new RemoteCertificateValidationCallback(ValidateServerCertificate));

								X509CertificateCollection clientCertificates = null;

								if (_clientCertificate != null)
								{
									clientCertificates = new X509CertificateCollection(new[] { _clientCertificate });
								}

								await sslStream
									.AuthenticateAsClientAsync(
										_hostName,
										clientCertificates,
										SslProtocols.Tls,
										false)
									.WithCancellation(cancellationToken)
									.ConfigureAwait(false);
							}

							_stream = sslStream;
							break;

						default:
							throw new NotSupportedException();
					}

					this.Encryption = encryption;
				}
				finally
				{
					_receiveSemaphore.Release();                    
				}

			}
			finally
			{
				_sendSemaphore.Release();
			}
		}
Ejemplo n.º 16
0
        /// <summary>
        /// Sends a negotiate session envelope
        /// to accepts the session negotiation options
        /// and awaits for the server confirmation.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <param name="sessionCompression">The session compression option</param>
        /// <param name="sessionEncryption">The session encryption option</param>
        /// <returns></returns>
        /// <exception cref="System.InvalidOperationException">
        /// Cannot await for a session response since there's already a listener.
        /// </exception>
        public async Task <Session> NegotiateSessionAsync(SessionCompression sessionCompression, SessionEncryption sessionEncryption, CancellationToken cancellationToken)
        {
            if (this.State != SessionState.Negotiating)
            {
                throw new InvalidOperationException(string.Format("Cannot negotiate a session in the '{0}' state", this.State));
            }

            var session = new Session()
            {
                Id          = this.SessionId,
                State       = SessionState.Negotiating,
                Compression = sessionCompression,
                Encryption  = sessionEncryption
            };

            await base.SendSessionAsync(session).ConfigureAwait(false);

            return(await this.ReceiveSessionAsync(cancellationToken).ConfigureAwait(false));
        }
Ejemplo n.º 17
0
        public async Task NegotiateSessionAsync_InvalidStateValidOptions_ThrowsInvalidOperationException()
        {
            var target = GetTarget(SessionState.Negotiating);

            var compressionOptions = new SessionCompression[] { SessionCompression.None };
            var encryptionOptions = new SessionEncryption[] { SessionEncryption.None, SessionEncryption.TLS };

            var cancellationToken = DataUtil.CreateCancellationToken();

            var actual = await target.NegotiateSessionAsync(compressionOptions, encryptionOptions, cancellationToken);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Sends a negotiate session envelope
        /// to accepts the session negotiation options
        /// and awaits for the server confirmation.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <param name="sessionCompression">The session compression option</param>
        /// <param name="sessionEncryption">The session encryption option</param>
        /// <returns></returns>
        /// <exception cref="System.InvalidOperationException">
        /// Cannot await for a session response since there's already a listener.
        /// </exception>
        public async Task <Session> NegotiateSessionAsync(SessionCompression sessionCompression, SessionEncryption sessionEncryption, CancellationToken cancellationToken)
        {
            if (State != SessionState.Negotiating)
            {
                throw new InvalidOperationException($"Cannot negotiate a session in the '{State}' state");
            }

            var session = new Session
            {
                Id          = SessionId,
                State       = SessionState.Negotiating,
                Compression = sessionCompression,
                Encryption  = sessionEncryption
            };

            await SendSessionAsync(session, cancellationToken).ConfigureAwait(false);

            return(await ReceiveSessionAsync(cancellationToken).ConfigureAwait(false));
        }
Ejemplo n.º 19
0
        public async Task NegotiateSessionAsync_NewStateValidOptions_CallsTransportAndReadsFromBuffer()
        {
            var session = DataUtil.CreateSession(SessionState.Negotiating);


            var target = GetTarget(sessionId: session.Id);           

            var compressionOptions = new SessionCompression[] { SessionCompression.None };
            var encryptionOptions = new SessionEncryption[] { SessionEncryption.None, SessionEncryption.TLS };

            var cancellationToken = DataUtil.CreateCancellationToken();

            _transport
                .Setup(t => t.ReceiveAsync(It.IsAny<CancellationToken>()))
                .Returns(() => Task.FromResult<Envelope>(session))
                .Verifiable();

            var actual = await target.NegotiateSessionAsync(compressionOptions, encryptionOptions, cancellationToken);

            _transport.Verify();

            _transport.Verify(
                t => t.SendAsync(
                    It.Is<Session>(e => e.State == SessionState.Negotiating &&
                                        e.CompressionOptions == compressionOptions &&
                                        e.EncryptionOptions == encryptionOptions &&
                                        e.From.Equals(target.LocalNode) &&
                                        e.To == null &&
                                        e.SchemeOptions == null &&
                                        e.Compression == null &&
                                        e.Encryption == null &&
                                        e.Authentication == null &&
                                        e.Id == target.SessionId),
                    It.IsAny<CancellationToken>()),
                    Times.Once());

            Assert.AreEqual(SessionState.Negotiating, target.State);
            Assert.AreEqual(session, actual);
        }
Ejemplo n.º 20
0
        public async Task NegotiateSessionAsync_EmptyEncryptionOptions_ThrowsArgumentException()
        {
            var target = GetTarget();

            var compressionOptions = new SessionCompression[] { SessionCompression.None };
            var encryptionOptions = new SessionEncryption[0];

            var cancellationToken = DataUtil.CreateCancellationToken();

            var actual = await target.NegotiateSessionAsync(compressionOptions, encryptionOptions, cancellationToken);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Send a negotiate session envelope
        /// to the remote node to confirm the 
        /// session negotiation options.
        /// </summary>
        /// <param name="sessionCompression">The session compression option</param>
        /// <param name="sessionEncryption">The session encryption option</param>
        /// <returns></returns>
        /// <exception cref="System.InvalidOperationException"></exception>
        public Task SendNegotiatingSessionAsync(SessionCompression sessionCompression, SessionEncryption sessionEncryption)
        {
            if (this.State != SessionState.Negotiating)
            {
                throw new InvalidOperationException(string.Format("Cannot negotiate a session in the '{0}' state", this.State));
            }

            var session = new Session()
            {
                Id = this.SessionId,
                From = this.LocalNode,
                State = base.State,
                Compression = sessionCompression,
                Encryption = sessionEncryption
            };

            return this.SendSessionAsync(session);
        }
Ejemplo n.º 22
0
 public BlipClientBuilder UsingEncryption(SessionEncryption sessionEncryption)
 {
     Encryption = sessionEncryption;
     return(this);
 }
 /// <summary>
 /// Sets the encryption option to be used in the session establishment.
 /// </summary>
 /// <param name="encryption">The encryption.</param>
 /// <returns></returns>
 public EstablishedClientChannelBuilder WithEncryption(SessionEncryption encryption)
 {
     return(WithEncryption(options => encryption));
 }
Ejemplo n.º 24
0
        /// <summary>
        /// Send a negotiate session envelope to the remote node to confirm the session negotiation options.
        /// </summary>
        /// <param name="sessionCompression">The session compression option</param>
        /// <param name="sessionEncryption">The session encryption option</param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="System.InvalidOperationException"></exception>
        public Task SendNegotiatingSessionAsync(SessionCompression sessionCompression, SessionEncryption sessionEncryption, CancellationToken cancellationToken)
        {
            if (State != SessionState.Negotiating)
            {
                throw new InvalidOperationException($"Cannot negotiate a session in the '{State}' state");
            }

            var session = new Session
            {
                Id          = SessionId,
                From        = LocalNode,
                State       = State,
                Compression = sessionCompression,
                Encryption  = sessionEncryption
            };

            return(SendSessionAsync(session, cancellationToken));
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Defines the encryption mode for the transport.
        /// </summary>
        /// <param name="encryption"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="System.NotSupportedException"></exception>
        public override async Task SetEncryptionAsync(SessionEncryption encryption, CancellationToken cancellationToken)
        {
            await _sendSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);

            try
            {
                await _receiveSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);

                try
                {
                    switch (encryption)
                    {
                    case SessionEncryption.None:
                        _stream = _tcpClient.GetStream();
                        break;

                    case SessionEncryption.TLS:
                        SslStream sslStream;

                        if (_serverCertificate != null)
                        {
                            if (_stream == null)
                            {
                                throw new InvalidOperationException("The stream was not initialized. Call OpenAsync first.");
                            }

                            // Server
                            sslStream = new SslStream(
                                _stream,
                                false,
                                _clientCertificateValidationCallback,
                                null,
                                EncryptionPolicy.RequireEncryption);

                            await sslStream
                            .AuthenticateAsServerAsync(
                                _serverCertificate,
                                true,
                                SslProtocols.Tls,
                                false)
                            .WithCancellation(cancellationToken)
                            .ConfigureAwait(false);
                        }
                        else
                        {
                            // Client
                            if (string.IsNullOrWhiteSpace(_hostName))
                            {
                                throw new InvalidOperationException("The hostname is mandatory for TLS client encryption support");
                            }

                            sslStream = new SslStream(
                                _stream,
                                false,
                                _serverCertificateValidationCallback);

                            X509CertificateCollection clientCertificates = null;

                            if (_clientCertificate != null)
                            {
                                clientCertificates = new X509CertificateCollection(new X509Certificate[] { _clientCertificate });
                            }

                            await sslStream
                            .AuthenticateAsClientAsync(
                                _hostName,
                                clientCertificates,
                                SslProtocols.Tls,
                                false)
                            .WithCancellation(cancellationToken)
                            .ConfigureAwait(false);
                        }
                        _stream = sslStream;
                        break;

                    default:
                        throw new NotSupportedException();
                    }

                    Encryption = encryption;
                }
                finally
                {
                    _receiveSemaphore.Release();
                }
            }
            finally
            {
                _sendSemaphore.Release();
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Defines the encryption mode
        /// for the transport
        /// </summary>
        /// <param name="encryption"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="System.NotSupportedException"></exception>
        public virtual Task SetEncryptionAsync(SessionEncryption encryption, CancellationToken cancellationToken)
        {
            if (encryption != SessionEncryption.None)
            {
                throw new NotSupportedException();
            }

            return Task.FromResult<object>(null);
        }