private SocketProtectionLevel GetSocketProtectionLevel(SocketEncryption encryption) { _encryptionLevel = SocketProtectionLevel.PlainSocket; switch (encryption) { case SocketEncryption.None: _encryptionLevel = SocketProtectionLevel.PlainSocket; break; case SocketEncryption.Tls10: _encryptionLevel = SocketProtectionLevel.Tls10; break; case SocketEncryption.Tls11: _encryptionLevel = SocketProtectionLevel.Tls11; break; case SocketEncryption.Tls12: _encryptionLevel = SocketProtectionLevel.Tls12; break; } return(_encryptionLevel); }
private SocketProtectionLevel GetSocketProtectionLevel(SocketEncryption encryption) { _encryptionLevel = SocketProtectionLevel.PlainSocket; switch (encryption) { case SocketEncryption.None: _encryptionLevel = SocketProtectionLevel.PlainSocket; break; case SocketEncryption.Ssl: _encryptionLevel = SocketProtectionLevel.Ssl; break; //case SocketEncryption.Tls10: // IsEncrypted = true; // _encryptionLevel = SocketProtectionLevel.Tls10; // break; //case SocketEncryption.Tls11: // IsEncrypted = true; // _encryptionLevel = SocketProtectionLevel.Tls11; // break; //case SocketEncryption.Tls12: // IsEncrypted = true; // _encryptionLevel = SocketProtectionLevel.Tls12; // break; } return(_encryptionLevel); }
public async Task ConnectAsync(Uri url, CancellationToken cancellationToken) { string host = url.Host; string serviceName = url.Port.ToString((IFormatProvider)CultureInfo.InvariantCulture); HostName hostName = new HostName(host); bool useTls = string.Equals("HTTPS", url.Scheme, StringComparison.OrdinalIgnoreCase); if (!useTls && !string.Equals("HTTP", url.Scheme, StringComparison.OrdinalIgnoreCase)) { throw new NotSupportedException("Scheme not supported: " + url.Scheme); } StreamSocket socket = new StreamSocket(); if (null != Interlocked.CompareExchange <StreamSocket>(ref this._socket, socket, (StreamSocket)null)) { socket.Dispose(); throw new InvalidOperationException("The socket is in use"); } try { socket.Control.NoDelay = true; SocketProtectionLevel protectionLevel = useTls ? SocketProtectionLevel.Ssl : SocketProtectionLevel.PlainSocket; await WindowsRuntimeSystemExtensions.AsTask(socket.ConnectAsync(hostName, serviceName, protectionLevel), cancellationToken).ConfigureAwait(false); } catch (Exception ex) { this.Close(); throw; } }
public void Connect(string hostName, int port) { //How to secure socket connections with TLS/SSL: //http://msdn.microsoft.com/en-us/library/windows/apps/jj150597.aspx //Networking in Windows 8 Apps - Using StreamSocket for TCP Communication //http://blogs.msdn.com/b/metulev/archive/2012/10/22/networking-in-windows-8-apps-using-streamsocket-for-tcp-communication.aspx Socket = new StreamSocket(); Socket.Control.KeepAlive = true; var host = new HostName(hostName); SocketProtectionLevel spl = SocketProtectionLevel.PlainSocket; if (UseHTTPSProtocol) { spl = SocketProtectionLevel. #if UNITY_WSA_8_0 || BUILD_FOR_WP8 Ssl; } #else Tls12; #endif // https://msdn.microsoft.com/en-us/library/windows/apps/xaml/jj710176.aspx#content try { var result = Socket.ConnectAsync(host, UseHTTPSProtocol ? "https" : port.ToString(), spl); if (ConnectTimeout > TimeSpan.Zero) { Connected = result.AsTask().Wait(ConnectTimeout); } else { Connected = result.AsTask().Wait(TimeSpan.FromMilliseconds(-1)); } } catch (AggregateException ex) { if (ex.InnerException != null) { throw ex.InnerException; } else { throw ex; } } if (!Connected) { throw new TimeoutException("Connection timed out!"); } }
public async Task ConnectAsync(Address address, ConnectionFactory factory) { SocketProtectionLevel spl = !address.UseSsl ? SocketProtectionLevel.PlainSocket : #if NETFX_CORE SocketProtectionLevel.Tls12; #else SocketProtectionLevel.Ssl; #endif StreamSocket ss = new StreamSocket(); await ss.ConnectAsync(new HostName(address.Host), address.Port.ToString(), spl); this.socket = ss; }
/// <summary> /// Attempt to upgrade stream to SSL. /// </summary> /// <param name="validationHost">Host subject to SSL upgrade.</param> internal void UpgradeToSsl(string validationHost) { #if SSL const SocketProtectionLevel protectionLevel = SocketProtectionLevel.Ssl; #else const SocketProtectionLevel protectionLevel = SocketProtectionLevel.Tls10; #endif if ( !Task.Run( async() => await _socket.UpgradeToSslAsync(protectionLevel, new HostName(validationHost))) .Wait(10000)) { throw new InvalidOperationException( String.Format("Could not authenticate '{0}' as SSL server", validationHost)); } }
/// <summary> /// Establishes a connection between the server and the client. /// </summary> /// <returns>The SMTP response from the server.</returns> public async Task <SmtpResponse> EstablishConnection() { try { _reader = new DataReader(_socket.InputStream); _reader.InputStreamOptions = InputStreamOptions.Partial; _writer = new DataWriter(_socket.OutputStream); SocketProtectionLevel protection = _ssl ? SocketProtectionLevel.Tls10 : SocketProtectionLevel.PlainSocket; await _socket.ConnectAsync(_host, _port.ToString(), protection); return(await GetResponse("Connect")); } catch { return(null); } }
private void SocketConnect() { if (IsConnected) { #if DEBUG _manager.Events.LogMessage(this, LogType.Warn, "Already connected"); #endif return; } if (_socketConnector != null && _socketConnector.Status == AsyncStatus.Started) { #if DEBUG _manager.Events.LogMessage(this, LogType.Warn, "Already connecting"); #endif return; } //CleanupState(); try { _hostname = new HostName(_manager.Settings.Hostname); } catch { ConnectionError(ErrorType.InvalidHostName, ErrorPolicyType.Deactivate); return; } _socket.Control.KeepAlive = false; SocketProtectionLevel protection = _manager.Settings.OldSSL ? SocketProtectionLevel.SslAllowNullEncryption : SocketProtectionLevel.PlainSocket; _socketConnector = _socket.ConnectAsync(_hostname, _manager.Settings.Port.ToString(), protection); _socketConnector.Completed = OnSocketConnectorCompleted; }
public async Task ConnectAsync(Address address, ConnectionFactory factory) { SocketProtectionLevel spl = !address.UseSsl ? SocketProtectionLevel.PlainSocket : #if NETFX_CORE SocketProtectionLevel.Tls12; #else SocketProtectionLevel.Ssl; #endif StreamSocket streamSocket = new StreamSocket(); streamSocket.Control.NoDelay = true; #if UWP if (factory.sslSettings != null) { spl = factory.sslSettings.ProtectionLevel; streamSocket.Control.ClientCertificate = factory.sslSettings.ClientCertificate; } #endif await streamSocket.ConnectAsync(new HostName(address.Host), address.Port.ToString(), spl); this.socket = streamSocket; }
protected override async Task <Stream> OnInitiateUpgradeAsync(Stream stream, OutWrapper <SecurityMessageProperty> remoteSecurityWrapper) { if (WcfEventSource.Instance.SslOnInitiateUpgradeIsEnabled()) { WcfEventSource.Instance.SslOnInitiateUpgrade(); } // There is currently no way to convert a .Net X509Certificate2 to a UWP Certificate. The client certificate // needs to be provided by looking it up in the certificate store. E.g. // // factory.Credentials.ClientCertificate.SetCertificate( // StoreLocation.CurrentUser, // StoreName.My, // X509FindType.FindByThumbprint, // clientCertThumb); // // The certificate is retrieved using .Net api's and UWP api's. An artifical X509Extension is used to attach the // UWP certificate to the .Net X509Certificate2. This is then retrieved at the point of usage to use with UWP // networking api's. Certificate clientCertificate = null; if (_clientToken != null) { foreach (var extension in _clientToken.Certificate.Extensions) { var attachmentExtension = extension as X509CertificateInitiatorClientCredential.X509UwpCertificateAttachmentExtension; if (attachmentExtension != null && attachmentExtension.AttachedCertificate != null) { clientCertificate = attachmentExtension.AttachedCertificate; break; } } Contract.Assert(clientCertificate != null, "Missing UWP Certificate as an attachment to X509Certificate2"); } try { // Fetch the underlying raw transport object. For UWP, this will be a StreamSocket var connectionStream = stream as ConnectionStream; Contract.Assert(connectionStream != null, "stream is either null or not a ConnectionStream"); var rtStreamSocket = connectionStream.Connection.GetCoreTransport() as StreamSocket; Contract.Assert(rtStreamSocket != null, "Core transport is either null or not a StreamSocket"); rtStreamSocket.Control.ClientCertificate = clientCertificate; // On CoreClr, we use SslStream which calls a callback with any problems with the server certificate, which // returns whether to accept the certificate or not. With SocketStream in UWP, any custom validation needs to // happen after the connection has successfully negotiated. Some certificate errors need to be set to be ignored // to allow the connection to be established so we can retrieve the server certificate and choose whether to // accept the server certificate or not. rtStreamSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted); rtStreamSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Expired); rtStreamSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName); rtStreamSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.IncompleteChain); rtStreamSocket.Control.IgnorableServerCertificateErrors.Add( ChainValidationResult.RevocationInformationMissing); rtStreamSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.RevocationFailure); // SocketStream doesn't take a bitwise field of accepted protocols, but instead accepts a value specifying the highest // protocol that can be negotiated. A check is made for each of the protocols in order to see if they've been requested // by the binding and set the protection level to the UWP equivalent. This will have the effect of protectionLevel being // set to the most secure protocol that was specified by client code. After the connection is established, if a protocol // was negotiated which the binding didn't request, the connection needs to be aborted. This could happen for example if // the requested SslProtocols was SslProtocols.Tls11 | SslProtocols.Tls12 and the server only supported SSL3 | Tls10. In // this case, SocketProtectionLevel would be set to SocketProtectionLevel.Tls12, which would mean Tls10, Tls11 and Tls12 // are all acceptable protocols to negotiate. As the server is offering SSL3 | Tls10, the connection would be successfully // negotiated using Tls10 which isn't allowed according to the binding configuration. SocketProtectionLevel protectionLevel = SocketProtectionLevel.PlainSocket; if ((_parent.SslProtocols & SslProtocols.Tls) != SslProtocols.None) { protectionLevel = SocketProtectionLevel.Tls10; } if ((_parent.SslProtocols & SslProtocols.Tls11) != SslProtocols.None) { protectionLevel = SocketProtectionLevel.Tls11; } if ((_parent.SslProtocols & SslProtocols.Tls12) != SslProtocols.None) { protectionLevel = SocketProtectionLevel.Tls12; } // With SslStream, the hostname provided in the server certificate is provided to the client and verified in the callback. // With UWP StreamSocket, the hostname needs to be provided to the call to UpgradeToSslAsync. The code to fetch the identity // lives in the callback for CoreClr but needs to be pulled into this method for UWP. EndpointAddress remoteAddress = RemoteAddress; if (remoteAddress.Identity == null && remoteAddress.Uri != Via) { remoteAddress = new EndpointAddress(Via); } EndpointIdentity identity; if (!_parent.IdentityVerifier.TryGetIdentity(remoteAddress, out identity)) { SecurityTraceRecordHelper.TraceIdentityVerificationFailure(identity: identity, authContext: null, identityVerifier: GetType()); throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning( new MessageSecurityException(SR.Format(SR.IdentityCheckFailedForOutgoingMessage, identity, remoteAddress))); } Contract.Assert(identity.IdentityClaim.ClaimType == ClaimTypes.Dns); string dnsHostName = identity.IdentityClaim.Resource as string; // This is the actual call to negotiate an SSL connection await rtStreamSocket.UpgradeToSslAsync(protectionLevel, new HostName(dnsHostName)).AsTask(); // Verify that we didn't negotiate a protocol lower than the binding configuration specified. No need to check Tls12 // as it will only be negotiated if Tls12 was actually specified. var negotiatedProtectionLevel = rtStreamSocket.Information.ProtectionLevel; if ((negotiatedProtectionLevel == SocketProtectionLevel.Tls11 && (_parent.SslProtocols & SslProtocols.Tls11) == SslProtocols.None) || (negotiatedProtectionLevel == SocketProtectionLevel.Tls10 && (_parent.SslProtocols & SslProtocols.Tls) == SslProtocols.None)) { // Need to dispose StreamSocket as normally SslStream wouldn't end up in a usable state in this situation. As // post-upgrade validation is required in UWP, the connection needs to be Dispose'd to ensure it isn't used. rtStreamSocket.Dispose(); throw new SecurityNegotiationException(SR.Format(SR.SSLProtocolNegotiationFailed, _parent.SslProtocols, negotiatedProtectionLevel)); } X509Certificate2 serverCertificate = null; X509Certificate2[] chainCertificates = null; X509Chain chain = null; try { // Convert the UWP Certificate object to a .Net X509Certificate2. byte[] serverCertificateBlob = rtStreamSocket.Information.ServerCertificate.GetCertificateBlob().ToArray(); serverCertificate = new X509Certificate2(serverCertificateBlob); // The chain building and validation logic is done by SslStream in CoreClr. This section of code is based // on the SslStream implementation to try to maintain behavior parity. chain = new X509Chain(); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot; var serverIntermediateCertificates = rtStreamSocket.Information.ServerIntermediateCertificates; chainCertificates = new X509Certificate2[serverIntermediateCertificates.Count]; for (int i = 0; i < chainCertificates.Length; i++) { chainCertificates[i] = new X509Certificate2(serverIntermediateCertificates[i].GetCertificateBlob().ToArray()); } chain.ChainPolicy.ExtraStore.AddRange(chainCertificates); chain.Build(serverCertificate); SslPolicyErrors policyErrors = SslPolicyErrors.None; foreach (var serverCertificateError in rtStreamSocket.Information.ServerCertificateErrors) { if (serverCertificateError == ChainValidationResult.InvalidName) { policyErrors |= SslPolicyErrors.RemoteCertificateNameMismatch; continue; } if (serverCertificateError == ChainValidationResult.IncompleteChain) { policyErrors |= SslPolicyErrors.RemoteCertificateChainErrors; } } X509ChainStatus[] chainStatusArray = chain.ChainStatus; if (chainStatusArray != null && chainStatusArray.Length != 0) { policyErrors |= SslPolicyErrors.RemoteCertificateChainErrors; } if (!ValidateRemoteCertificate(this, serverCertificate, chain, policyErrors)) { // Need to dispose StreamSocket as normally SslStream wouldn't end up in a usable state in this situation. As // post-upgrade validation is required in UWP, the connection needs to be Dispose'd to ensure it isn't used. rtStreamSocket.Dispose(); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityNegotiationException(SR.ssl_io_cert_validation)); } } finally { serverCertificate?.Dispose(); chain?.Dispose(); if (chainCertificates != null) { foreach (var chainCert in chainCertificates) { chainCert?.Dispose(); } } } } catch (SecurityTokenValidationException tokenValidationException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityNegotiationException(tokenValidationException.Message, tokenValidationException)); } catch (IOException ioException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException( SR.Format(SR.NegotiationFailedIO, ioException.Message), ioException)); } catch (Exception exception) { // In NET Native the WinRT API's can throw the base Exception // class with an HRESULT indicating the issue. However, custom // validation code can also throw Exception, and to be compatible // with the CoreCLR version, we must allow those exceptions to // propagate without wrapping them. We use the simple heuristic // that if an HRESULT has been set to other than the default, // the exception should be wrapped in SecurityNegotiationException. if (exception.HResult == __HResults.COR_E_EXCEPTION) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException( exception.Message, exception)); } remoteSecurityWrapper.Value = _serverSecurity; return(stream); }
public IAsyncAction ConnectAsync(HostName remoteHostName, string remoteServiceName, SocketProtectionLevel protectionLevel, NetworkAdapter adapter) { return _streamSocket.ConnectAsync(remoteHostName, remoteServiceName, protectionLevel, adapter); }
public IAsyncAction ConnectAsync(HostName remoteHostName, string remoteServiceName, SocketProtectionLevel protectionLevel) { return _streamSocket.ConnectAsync(remoteHostName, remoteServiceName, protectionLevel); }
public IAsyncAction ConnectAsync(EndpointPair endpointPair, SocketProtectionLevel protectionLevel) { return _streamSocket.ConnectAsync(endpointPair, protectionLevel); }
public IAsyncAction UpgradeToSslAsync(SocketProtectionLevel protectionLevel, HostName validationHostName) { return _streamSocket.UpgradeToSslAsync(protectionLevel, validationHostName); }
private SocketProtectionLevel GetSocketProtectionLevel(SocketEncryption encryption) { _encryptionLevel = SocketProtectionLevel.PlainSocket; switch (encryption) { case SocketEncryption.None: _encryptionLevel = SocketProtectionLevel.PlainSocket; break; case SocketEncryption.Tls10: _encryptionLevel = SocketProtectionLevel.Tls10; break; case SocketEncryption.Tls11: _encryptionLevel = SocketProtectionLevel.Tls11; break; case SocketEncryption.Tls12: _encryptionLevel = SocketProtectionLevel.Tls12; break; } return _encryptionLevel; }
public StreamSocketConnectOperation ConnectAsync (HostName hostName, string remoteServiceName, SocketProtectionLevel protectionLevel) { throw new NotImplementedException(); }
public void Connect(string hostName, int port) { //How to secure socket connections with TLS/SSL: //http://msdn.microsoft.com/en-us/library/windows/apps/jj150597.aspx //Networking in Windows 8 Apps - Using StreamSocket for TCP Communication //http://blogs.msdn.com/b/metulev/archive/2012/10/22/networking-in-windows-8-apps-using-streamsocket-for-tcp-communication.aspx Socket = new StreamSocket(); Socket.Control.KeepAlive = true; Socket.Control.NoDelay = true; var host = new HostName(hostName); SocketProtectionLevel spl = SocketProtectionLevel.PlainSocket; if (UseHTTPSProtocol) { spl = SocketProtectionLevel. #if UNITY_WSA_8_0 || BUILD_FOR_WP8 Ssl; } #else Tls12; #endif System.Threading.CancellationTokenSource tokenSource = new System.Threading.CancellationTokenSource(); // https://msdn.microsoft.com/en-us/library/windows/apps/xaml/jj710176.aspx#content try { if (ConnectTimeout > TimeSpan.Zero) { tokenSource.CancelAfter(ConnectTimeout); } var task = Socket.ConnectAsync(host, UseHTTPSProtocol ? "https" : port.ToString(), spl).AsTask(tokenSource.Token); task.ConfigureAwait(false); task.Wait(); Connected = task.IsCompleted; } catch (AggregateException ex) { //https://msdn.microsoft.com/en-us/library/dd537614(v=vs.110).aspx?f=255&MSPPError=-2147217396 Connected = false; if (ex.InnerException != null) //throw ex.InnerException; { if (ex.Message.Contains("No such host is known") || ex.Message.Contains("unreachable host")) { throw new Exception("Socket Exception"); } else { throw ex.InnerException; } } else { throw ex; } } finally { // https://docs.microsoft.com/en-us/dotnet/api/system.threading.cancellationtokensource tokenSource.Dispose(); } if (!Connected) { throw new TimeoutException("Connection timed out!"); } }
private SocketProtectionLevel GetSocketProtectionLevel(SocketEncryption encryption) { _encryptionLevel = SocketProtectionLevel.PlainSocket; switch (encryption) { case SocketEncryption.None: _encryptionLevel = SocketProtectionLevel.PlainSocket; break; case SocketEncryption.Ssl: _encryptionLevel = SocketProtectionLevel.Ssl; break; //case SocketEncryption.Tls10: // IsEncrypted = true; // _encryptionLevel = SocketProtectionLevel.Tls10; // break; //case SocketEncryption.Tls11: // IsEncrypted = true; // _encryptionLevel = SocketProtectionLevel.Tls11; // break; //case SocketEncryption.Tls12: // IsEncrypted = true; // _encryptionLevel = SocketProtectionLevel.Tls12; // break; } return _encryptionLevel; }
public UpgradeToSslOperation UpgradeToSslAsync (SocketProtectionLevel protectionlevel, HostName validationHostName) { throw new NotImplementedException(); }
public IAsyncAction BindServiceNameAsync(string localServiceName, SocketProtectionLevel protectionLevel) => new AsyncAction();
private async Task ConnectAsync() { // TODO maybe don't allow NULL cipher SocketProtectionLevel protectionLevel = secure ? SocketProtectionLevel.Ssl : SocketProtectionLevel.PlainSocket; await socket.ConnectAsync(new HostName(this.remoteHostName), this.remotePort.ToString(), protectionLevel); }