Exemple #1
0
 /// <summary>
 /// Creates a new instance of the <see cref="EpoxyTlsConfig"/> class.
 /// </summary>
 /// <param name="remoteCertificateValidationCallback">
 /// Normal use is to omit this parameter/pass <c>null</c> so that the
 /// system's default behavior is used. Passing something other than
 /// null here is almost always a bug. This delegate is passed to
 /// <see cref="SslStream"/>; consult the SslStream documentation for
 /// more details about its use.
 /// </param>
 /// <param name="checkCertificateRevocation">
 /// Whether certificate revocation is checked. Defaults to <c>true</c>.
 /// </param>
 protected EpoxyTlsConfig(
     RemoteCertificateValidationCallback remoteCertificateValidationCallback = null,
     bool checkCertificateRevocation = true)
 {
     RemoteCertificateValidationCallback = remoteCertificateValidationCallback;
     CheckCertificateRevocation = checkCertificateRevocation;
 }
        internal static SslStream ManageClientRequest(TcpClient client)
        {
            SslStream sslStream = null;

            try
            {
                bool leaveInnerStreamOpen = true;

                RemoteCertificateValidationCallback validationCallback =
                    new RemoteCertificateValidationCallback(ClientValidationCallback);
                LocalCertificateSelectionCallback selectionCallback =
                    new LocalCertificateSelectionCallback(ServerCertificateSelectionCallback);
                EncryptionPolicy encryptionPolicy = EncryptionPolicy.AllowNoEncryption;

                sslStream = new SslStream(client.GetStream(), leaveInnerStreamOpen, validationCallback, selectionCallback, encryptionPolicy);
                Console.WriteLine("Server starting handshake");
                ServerSideHandshake(sslStream);
                Console.WriteLine("Server finished handshake");
            }
            catch(Exception ex)
            {
                sslStream = null;
                Console.WriteLine("\nError detected in sslStream: " + ex.Message);
            }
            return sslStream;
        }
Exemple #3
0
 public MailClient(string hostname, int port, bool isSecure = false, RemoteCertificateValidationCallback validate = null)
 {
     this.hostName = hostname;
     this.port = port;
     this.isSecure = isSecure;
     this.validate = validate;
 }
        internal static SslStream ManageServerRequest(TcpClient client, String connectToIP)
        {
            SslStream sslStream = null;
            try
            {
                bool leaveInnerStreamOpen = true;

                RemoteCertificateValidationCallback validationCallback =
                    new RemoteCertificateValidationCallback(ServerValidationCallback);

                LocalCertificateSelectionCallback selectionCallback =
                    new LocalCertificateSelectionCallback(ClientCertificateSelectionCallback);

                EncryptionPolicy encryptionPolicy = EncryptionPolicy.NoEncryption;

                sslStream = new SslStream(client.GetStream(), leaveInnerStreamOpen, validationCallback, selectionCallback, encryptionPolicy);
                Console.WriteLine("Client starting handshake");
                ClientSideHandshake(sslStream, connectToIP);
                Console.WriteLine("client finished handshake");
            }
            catch(AuthenticationException ex)
            {
                Console.WriteLine("\nAuthentication Exception: " + ex.Message);
            }
            catch(Exception ex)
            {
                Console.WriteLine("\nError detected: " + ex.Message);
            }

            return sslStream;
        }
        public TTlsServerSocketTransport(
            int port,
            bool useBufferedSockets,
            X509Certificate2 certificate,
            RemoteCertificateValidationCallback clientCertValidator = null,
            LocalCertificateSelectionCallback localCertificateSelectionCallback = null,
            SslProtocols sslProtocols = SslProtocols.Tls12)
        {
            if (!certificate.HasPrivateKey)
            {
                throw new TTransportException(TTransportException.ExceptionType.Unknown,
                    "Your server-certificate needs to have a private key");
            }

            _port = port;
            _serverCertificate = certificate;
            _useBufferedSockets = useBufferedSockets;
            _clientCertValidator = clientCertValidator;
            _localCertificateSelectionCallback = localCertificateSelectionCallback;
            _sslProtocols = sslProtocols;

            try
            {
                // Create server socket
                _server = new TcpListener(IPAddress.Any, _port);
                _server.Server.NoDelay = true;
            }
            catch (Exception)
            {
                _server = null;
                throw new TTransportException($"Could not create ServerSocket on port {port}.");
            }
        }
Exemple #6
0
 protected MailClient(string host, int port, bool isSsl, RemoteCertificateValidationCallback validate)
 {
     HostName = host;
     PortNo = port;
     IsSsl = isSsl;
     Validate = validate;
 }
        public SecureTcpServer(int listenPort, X509Certificate serverCertificate,
            SecureConnectionResultsCallback callback,
            RemoteCertificateValidationCallback certValidationCallback)
        {
            if (listenPort < 0 || listenPort > UInt16.MaxValue)
                throw new ArgumentOutOfRangeException("listenPort");

            if (serverCertificate == null)
                throw new ArgumentNullException("serverCertificate");

            if (callback == null)
                throw new ArgumentNullException("callback");

            onAcceptConnection = new AsyncCallback(OnAcceptConnection);
            onAuthenticateAsServer = new AsyncCallback(OnAuthenticateAsServer);

            this.serverCert = serverCertificate;
            this.certValidationCallback = certValidationCallback;
            this.connectionCallback = callback;
            this.listenPort = listenPort;
            this.disposed = 0;
            this.checkCertifcateRevocation = false;
            this.clientCertificateRequired = false;
            this.sslProtocols = SslProtocols.Default;
        }
Exemple #8
0
		internal static MSI.MonoRemoteCertificateValidationCallback PublicToMono (RemoteCertificateValidationCallback callback)
		{
			if (callback == null)
				return null;

			return (h, c, ch, e) => callback (h, c, (X509Chain)(object)ch, (SslPolicyErrors)e);
		}
Exemple #9
0
 public SslStream(
   NetworkStream innerStream,
   bool leaveInnerStreamOpen,
   RemoteCertificateValidationCallback userCertificateValidationCallback
 ) : base(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback)
 {
 }
Exemple #10
0
		public LRClient()
		{
			_serializer = LRUtils.GetSerializer();
            _encoder = LRUtils.GetEncoder();
			_harvester = new Harvester();
            SslValidationCallback = AcceptAllCertificates;
		}
Exemple #11
0
        internal TcpClientAdapter()
        {
            _sendQueue = new Queue<SendState>();

            _sendCallback = new AsyncCallback(sendHandler);
            _receiveCallback = new AsyncCallback(receiveHandler);
            _certCallback = new RemoteCertificateValidationCallback(ValidateCert);
        }
Exemple #12
0
        /// <summary>
        /// Initialises ssl client as a client side endpoint.
        /// </summary>
        public SslClient(IRawByteClient client,
                         string targetHost,
                         RemoteCertificateValidationCallback remoteCertificateValidationCallback)
        {
            Ensure.IsNotNull(client, "client");
            Ensure.IsNotNullOrWhiteSpace(targetHost, "targetHost");

            InitializeAsClient(client, targetHost, remoteCertificateValidationCallback);
        }
        public SslCertificateValidator(bool acceptAll, string[] validHashes)
        {
            m_acceptAll = acceptAll;
            m_validHashes = validHashes;
            m_oldCallback = System.Net.ServicePointManager.ServerCertificateValidationCallback;

            System.Net.ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertficate);
            m_isAttached = true;
        }
        /// <summary>
        /// Initializes a new instance of a <see cref="BaseHttpQrCodeProvider"/>.
        /// </summary>
        /// <param name="baseUri">The base Uri for the QR code provider.</param>
        /// <param name="remoteCertificateValidationCallback">
        /// The <see cref="RemoteCertificateValidationCallback"/> to be used by the QR code provider.
        /// </param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="baseUri"/> is null.</exception>
        protected BaseHttpQrCodeProvider(Uri baseUri, RemoteCertificateValidationCallback remoteCertificateValidationCallback)
        {
            if (baseUri == null)
                throw new ArgumentNullException("baseUri");
            this.BaseUri = baseUri;

            this.RemoteCertificateValidationCallback = remoteCertificateValidationCallback;
            this.TimeOut = DEFAULTTIMEOUT;
        }
 /// <summary>
 /// 表示SSL客户端会话对象
 /// </summary>  
 /// <param name="targetHost">目标主机</param>
 /// <param name="certificateValidationCallback">远程证书验证回调</param>
 /// <exception cref="ArgumentNullException"></exception>
 public SslTcpSession(string targetHost, RemoteCertificateValidationCallback certificateValidationCallback)
 {
     if (string.IsNullOrEmpty(targetHost) == true)
     {
         throw new ArgumentNullException("targetHost");
     }
     this.targetHost = targetHost;
     this.certificateValidationCallback = certificateValidationCallback;
 }
 /// <summary>
 /// 表示SSL服务器会话对象
 /// </summary>  
 /// <param name="certificate">服务器证书</param>
 ///  <exception cref="ArgumentNullException"></exception>
 public SslTcpSession(X509Certificate certificate)
 {
     if (certificate == null)
     {
         throw new ArgumentNullException();
     }
     this.certificate = certificate;
     this.certificateValidationCallback = (a, b, c, d) => true;
 }
Exemple #17
0
        //private string hostname, username, password;
        public static void UploadFiles(ConfigurationProfile profile, string temppath, string remotedir)
        {
            // Setup session options
            // add support for: scp/sftp protocols, ssh host/private keys, active/passive mode, port, FtpSecure, timeout, ssl cert,

            using (FTPSClient session = new FTPSClient())
            {

                ESSLSupportMode sslSupportMode = ESSLSupportMode.ClearText;
                RemoteCertificateValidationCallback userValidateServerCertificate;
                userValidateServerCertificate = new RemoteCertificateValidationCallback(ValidateServerCertificate);

                // enable encryption if desired
                if (profile.Encryption.IsTrue())
                {
                    sslSupportMode |= ESSLSupportMode.ControlAndDataChannelsRequired | ESSLSupportMode.CredentialsRequired;
                    if (profile.EncryptionImplicit.IsTrue())
                    {
                        // implicit if desired
                        sslSupportMode |= ESSLSupportMode.Implicit;
                    }
                    if (profile.ForceEncryption.IsTrue())
                    {
                        // force encryption if desired
                        userValidateServerCertificate = new RemoteCertificateValidationCallback(delegate { return true; });
                    }
                }

                session.Connect(profile.Hostname, new System.Net.NetworkCredential(profile.Username, profile.Password), sslSupportMode, userValidateServerCertificate);

                // Upload files
                //TransferOptions transferOptions = new TransferOptions();
                //transferOptions.TransferMode = TransferMode.Binary;

                //TransferOperationResult transferResult;
                //transferResult = session.PutFiles(Path.Combine(temppath, "*"), Common.Parse(remotedir), false, transferOptions);

                try
                {
                    session.SetCurrentDirectory(Common.ParseTemplate(remotedir));
                }
                catch
                {
                    session.MakeDir(Common.ParseTemplate(remotedir));
                }
                session.PutFiles(temppath, Common.ParseTemplate(remotedir), "*", EPatternStyle.Wildcard, false, new FileTransferCallback(TransferCallback));

                // Throw on any error
                //transferResult.Check();

                // Print results
                //foreach (TransferEventArgs transfer in transferResult.Transfers)
                //{
                //    Console.WriteLine("Upload of {0} succeeded", transfer.FileName);
                //}
            }
        }
		public DotNetSslStreamImpl (
			Stream innerStream, bool leaveInnerStreamOpen,
			RemoteCertificateValidationCallback userCertificateValidationCallback,
			LocalCertificateSelectionCallback userCertificateSelectionCallback)
		{
			impl = new SslStream (
				innerStream, leaveInnerStreamOpen,
				userCertificateValidationCallback,
				userCertificateSelectionCallback);
		}
Exemple #19
0
 /// <summary>
 /// Create a new HTTPClient using the given optional parameters.
 /// </summary>
 /// <param name="RemoteSocket">The remote IP socket to connect to.</param>
 /// <param name="RemoteCertificateValidator">A delegate to verify the remote TLS certificate.</param>
 /// <param name="ClientCert">The TLS client certificate to use.</param>
 /// <param name="DNSClient">An optional DNS client.</param>
 public HTTPSClient(IPSocket                             RemoteSocket,
                    RemoteCertificateValidationCallback  RemoteCertificateValidator,
                    X509Certificate                      ClientCert  = null,
                    DNSClient                            DNSClient   = null)
     : base(RemoteSocket,
            RemoteCertificateValidator,
            ClientCert,
            DNSClient)
 {
 }
Exemple #20
0
        /// <summary>
        ///     Creates new instance of <see cref="HttpProxy" /> using provided default port and internal buffer size.
        /// </summary>
        /// <param name="defaultPort">
        ///     Port number on destination server which will be used if not specified in request
        /// </param>
        /// <param name="certificate">
        ///     Certificate used for server authentication
        /// </param>
        /// <param name="rcValidationCallback">
        ///     Used to validate destination server certificate. By default it accepts anything provided by server
        /// </param>
        public SslProxy(X509Certificate certificate, Int32 defaultPort,
            RemoteCertificateValidationCallback rcValidationCallback = null)
            : base(defaultPort)
        {
            Contract.Requires<ArgumentNullException>(certificate != null, "certificate");

            _certificateValidationCallback = rcValidationCallback ?? DefaultCertificateValidationCallback;

            _certificate = certificate;
        }
Exemple #21
0
		public LRClient(string baseUri)
		{
			_baseUri = new Uri(baseUri);
            _serializer = LRUtils.GetSerializer();
            _encoder = LRUtils.GetEncoder();
			_harvester = new Harvester(_baseUri);
            Username = "";
            Password = "";
            SslValidationCallback = AcceptAllCertificates;
		}
Exemple #22
0
        /// <include file='../../../_Doc/System.xml' path='doc/members/member[@name="M:System.Net.Security.SslStream.#ctor(System.IO.Stream,System.Boolean,System.Net.Security.RemoteCertificateValidationCallback)"]/*' />
        public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback)
        {
            var tcpClientStream = innerStream as NetworkStream;
            if (tcpClientStream == null)
                throw new ArgumentException("Stream type not associated with TCP client", "innerStream");

            _innerStream = tcpClientStream;
            _leaveInnerStreamOpen = leaveInnerStreamOpen;
            this.userCertificateValidationCallback = userCertificateValidationCallback;
        }
 public TTlsSocketClientTransport(IPAddress host, int port, string certificatePath,
     RemoteCertificateValidationCallback certValidator = null,
     LocalCertificateSelectionCallback localCertificateSelectionCallback = null,
     SslProtocols sslProtocols = SslProtocols.Tls12)
     : this(host, port, 0,
         new X509Certificate2(certificatePath),
         certValidator,
         localCertificateSelectionCallback,
         sslProtocols)
 {
 }
		public DotNetSslStreamImpl (
			Stream innerStream, bool leaveInnerStreamOpen, DotNetTlsProvider provider,
			RemoteCertificateValidationCallback userCertificateValidationCallback,
			LocalCertificateSelectionCallback userCertificateSelectionCallback)
		{
			this.provider = provider;
			impl = new SslStream (
				innerStream, leaveInnerStreamOpen,
				userCertificateValidationCallback,
				userCertificateSelectionCallback);
		}
Exemple #25
0
        TlsHandler(bool isServer, X509Certificate2 certificate, string targetHost, RemoteCertificateValidationCallback certificateValidationCallback)
        {
            Contract.Requires(!isServer || certificate != null);
            Contract.Requires(isServer || !string.IsNullOrEmpty(targetHost));

            this.sslStreamWriteQueue = new Queue<TaskCompletionSource<int>>();
            this.isServer = isServer;
            this.certificate = certificate;
            this.targetHost = targetHost;
            this.mediationStream = new MediationStream(this);
            this.sslStream = new SslStream(this.mediationStream, true, certificateValidationCallback);
        }
Exemple #26
0
		public WebRequestHandler ()
		{
			allowPipelining = true;
			authenticationLevel = AuthenticationLevel.MutualAuthRequested;
			cachePolicy = System.Net.WebRequest.DefaultCachePolicy;
			continueTimeout = TimeSpan.FromMilliseconds (350);
			impersonationLevel = TokenImpersonationLevel.Delegation;
			maxResponseHeadersLength = HttpWebRequest.DefaultMaximumResponseHeadersLength;
			readWriteTimeout = 300000;
			serverCertificateValidationCallback = null;
			unsafeAuthenticatedConnectionSharing = false;
		}
Exemple #27
0
 /// <summary>
 /// Create a new HTTPClient using the given optional parameters.
 /// </summary>
 /// <param name="RemoteHost">The remote hostname to connect to.</param>
 /// <param name="RemoteCertificateValidator">A delegate to verify the remote TLS certificate.</param>
 /// <param name="ClientCert">The TLS client certificate to use.</param>
 /// <param name="RemotePort">An optional remote IP port to connect to [default: 443].</param>
 /// <param name="DNSClient">An optional DNS client.</param>
 public HTTPSClient(String                               RemoteHost,
                    RemoteCertificateValidationCallback  RemoteCertificateValidator,
                    X509Certificate                      ClientCert  = null,
                    IPPort                               RemotePort  = null,
                    DNSClient                            DNSClient   = null)
     : base(RemoteHost,
            RemotePort != null ? RemotePort : IPPort.Parse(443),
            RemoteCertificateValidator,
            ClientCert,
            DNSClient)
 {
 }
 public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback, LocalCertificateSelectionCallback userCertificateSelectionCallback, EncryptionPolicy encryptionPolicy) : base(innerStream, leaveInnerStreamOpen)
 {
     if (((encryptionPolicy != EncryptionPolicy.RequireEncryption) && (encryptionPolicy != EncryptionPolicy.AllowNoEncryption)) && (encryptionPolicy != EncryptionPolicy.NoEncryption))
     {
         throw new ArgumentException(SR.GetString("net_invalid_enum", new object[] { "EncryptionPolicy" }), "encryptionPolicy");
     }
     this._userCertificateValidationCallback = userCertificateValidationCallback;
     this._userCertificateSelectionCallback = userCertificateSelectionCallback;
     RemoteCertValidationCallback certValidationCallback = new RemoteCertValidationCallback(this.userCertValidationCallbackWrapper);
     LocalCertSelectionCallback certSelectionCallback = (userCertificateSelectionCallback == null) ? null : new LocalCertSelectionCallback(this.userCertSelectionCallbackWrapper);
     this._SslState = new SslState(innerStream, certValidationCallback, certSelectionCallback, encryptionPolicy);
 }
 private static void AddServerCertMapping(HttpWebRequest request, string thumbprint)
 {
     lock (serverCertMap)
     {
         if (!serverCertValidationCallbackInstalled)
         {
             chainedServerCertValidationCallback = ServicePointManager.ServerCertificateValidationCallback;
             ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(HttpTransportSecurityHelpers.OnValidateServerCertificate);
             serverCertValidationCallbackInstalled = true;
         }
         serverCertMap.Add(request, thumbprint);
     }
 }
 public MailboxSearchEwsBinding(string componentId, RemoteCertificateValidationCallback remoteCertificateValidationCallback) : base(componentId, remoteCertificateValidationCallback)
 {
 }
Exemple #31
0
        // the thread function
        // STATIC to avoid sharing state!
        // => pass ClientState object. a new one is created for each new thread!
        // => avoids data races where an old dieing thread might still modify
        //    the current thread's state :/
        static void ReceiveThreadFunction(ClientState state, string ip, int port, int MaxMessageSize, bool NoDelay, int SendTimeout, int QueueLimit)
        {
            Thread sendThread = null;

            // absolutely must wrap with try/catch, otherwise thread
            // exceptions are silent
            try
            {
                // connect (blocking)
                client.Connect(ip, port);

                Stream stream = client.GetStream();

                if (_Encrypted)
                {
                    RemoteCertificateValidationCallback trustCert = (object sender, X509Certificate x509Certificate,
                                                                     X509Chain x509Chain, SslPolicyErrors policyErrors) =>
                    {
                        if (_AcceptSelfSignedCert)
                        {
                            // All certificates are accepted
                            return(true);
                        }
                        else
                        {
                            if (policyErrors == SslPolicyErrors.None)
                            {
                                return(true);
                            }
                            else
                            {
                                return(false);
                            }
                        }
                    };

                    SslStream encryptedStream = new SslStream(client.GetStream(), false, trustCert, null);
                    stream = encryptedStream;

                    encryptedStream.AuthenticateAsClient(ip);
                }

                _Connecting = false;
                state.client.Connect(ip, port);
                state.Connecting = false; // volatile!

                // set socket options after the socket was created in Connect()
                // (not after the constructor because we clear the socket there)
                state.client.NoDelay     = NoDelay;
                state.client.SendTimeout = SendTimeout;

                // start send thread only after connected
                // IMPORTANT: DO NOT SHARE STATE ACROSS MULTIPLE THREADS!
                sendThread = new Thread(() => { ThreadFunctions.SendLoop(0, state.client, state.sendPipe, state.sendPending); });
                sendThread.IsBackground = true;
                sendThread.Start();

                // run the receive loop
                // IMPORTANT: DO NOT SHARE STATE ACROSS MULTIPLE THREADS!
                ThreadFunctions.ReceiveLoop(0, state.client, MaxMessageSize, state.receivePipe, QueueLimit);
            }
            catch (SocketException exception)
            {
                // this happens if (for example) the ip address is correct
                // but there is no server running on that ip/port
                Log.Info("Client Recv: failed to connect to ip=" + ip + " port=" + port + " reason=" + exception);

                // set 'Disconnected' event to receive pipe so that the caller
                // knows that the Connect failed. otherwise they will never know
                state.receivePipe.SetDisconnected();
            }
            catch (ThreadInterruptedException)
            {
                // expected if Disconnect() aborts it
            }
            catch (ThreadAbortException)
            {
                // expected if Disconnect() aborts it
            }
            catch (ObjectDisposedException)
            {
                // expected if Disconnect() aborts it and disposed the client
                // while ReceiveThread is in a blocking Connect() call
            }
            catch (Exception exception)
            {
                // something went wrong. probably important.
                Log.Error("Client Recv Exception: " + exception);
            }

            // sendthread might be waiting on ManualResetEvent,
            // so let's make sure to end it if the connection
            // closed.
            // otherwise the send thread would only end if it's
            // actually sending data while the connection is
            // closed.
            sendThread?.Interrupt();

            // Connect might have failed. thread might have been closed.
            // let's reset connecting state no matter what.
            state.Connecting = false;

            // if we got here then we are done. ReceiveLoop cleans up already,
            // but we may never get there if connect fails. so let's clean up
            // here too.
            state.client?.Close();
        }
Exemple #32
0
        private Stream NegotiateStream(Stream stream)
        {
            if (!_configuration.SslEnabled)
            {
                return(stream);
            }

            var validateRemoteCertificate = new RemoteCertificateValidationCallback(
                (object sender,
                 X509Certificate certificate,
                 X509Chain chain,
                 SslPolicyErrors sslPolicyErrors)
                =>
            {
                if (sslPolicyErrors == SslPolicyErrors.None)
                {
                    return(true);
                }

                if (_configuration.SslPolicyErrorsBypassed)
                {
                    return(true);
                }
                else
                {
                    _log.ErrorFormat("Error occurred when validating remote certificate: [{0}], [{1}].",
                                     this.RemoteEndPoint, sslPolicyErrors);
                }

                return(false);
            });

            var sslStream = new SslStream(
                stream,
                false,
                validateRemoteCertificate,
                null,
                _configuration.SslEncryptionPolicy);

            IAsyncResult ar = null;

            if (_configuration.SslClientCertificates == null || _configuration.SslClientCertificates.Count == 0)
            {
                ar = sslStream.BeginAuthenticateAsClient( // No client certificates are used in the authentication. The certificate revocation list is not checked during authentication.
                    _configuration.SslTargetHost,         // The name of the server that will share this SslStream. The value specified for targetHost must match the name on the server's certificate.
                    null, _tcpClient);
            }
            else
            {
                ar = sslStream.BeginAuthenticateAsClient(
                    _configuration.SslTargetHost,                 // The name of the server that will share this SslStream. The value specified for targetHost must match the name on the server's certificate.
                    _configuration.SslClientCertificates,         // The X509CertificateCollection that contains client certificates.
                    _configuration.SslEnabledProtocols,           // The SslProtocols value that represents the protocol used for authentication.
                    _configuration.SslCheckCertificateRevocation, // A Boolean value that specifies whether the certificate revocation list is checked during authentication.
                    null, _tcpClient);
            }
            if (!ar.AsyncWaitHandle.WaitOne(ConnectTimeout))
            {
                Close(false);
                throw new TimeoutException(string.Format(
                                               "Negotiate SSL/TSL with remote [{0}] timeout [{1}].", this.RemoteEndPoint, ConnectTimeout));
            }
            sslStream.EndAuthenticateAsClient(ar);

            // When authentication succeeds, you must check the IsEncrypted and IsSigned properties
            // to determine what security services are used by the SslStream.
            // Check the IsMutuallyAuthenticated property to determine whether mutual authentication occurred.
            _log.DebugFormat(
                "Ssl Stream: SslProtocol[{0}], IsServer[{1}], IsAuthenticated[{2}], IsEncrypted[{3}], IsSigned[{4}], IsMutuallyAuthenticated[{5}], "
                + "HashAlgorithm[{6}], HashStrength[{7}], KeyExchangeAlgorithm[{8}], KeyExchangeStrength[{9}], CipherAlgorithm[{10}], CipherStrength[{11}].",
                sslStream.SslProtocol,
                sslStream.IsServer,
                sslStream.IsAuthenticated,
                sslStream.IsEncrypted,
                sslStream.IsSigned,
                sslStream.IsMutuallyAuthenticated,
                sslStream.HashAlgorithm,
                sslStream.HashStrength,
                sslStream.KeyExchangeAlgorithm,
                sslStream.KeyExchangeStrength,
                sslStream.CipherAlgorithm,
                sslStream.CipherStrength);

            return(sslStream);
        }
Exemple #33
0
        private async Task <Stream> NegotiateStream(Stream stream)
        {
            if (!_configuration.SslEnabled)
            {
                return(stream);
            }

            var validateRemoteCertificate = new RemoteCertificateValidationCallback(
                (object sender,
                 X509Certificate certificate,
                 X509Chain chain,
                 SslPolicyErrors sslPolicyErrors)
                =>
            {
                if (sslPolicyErrors == SslPolicyErrors.None)
                {
                    return(true);
                }

                if (_configuration.SslPolicyErrorsBypassed)
                {
                    return(true);
                }
                else
                {
                    _log.Error("Session [{0}] error occurred when validating remote certificate: [{1}], [{2}].", this, this.RemoteEndPoint, sslPolicyErrors);
                }

                return(false);
            });

            var sslStream = new SslStream(
                stream,
                false,
                validateRemoteCertificate,
                null,
                _configuration.SslEncryptionPolicy);

            if (!_configuration.SslClientCertificateRequired)
            {
                await sslStream.AuthenticateAsServerAsync(_configuration.SslServerCertificate); // The X509Certificate used to authenticate the server.
            }
            else
            {
                await sslStream.AuthenticateAsServerAsync(
                    _configuration.SslServerCertificate,           // The X509Certificate used to authenticate the server.
                    _configuration.SslClientCertificateRequired,   // A Boolean value that specifies whether the client must supply a certificate for authentication.
                    _configuration.SslEnabledProtocols,            // The SslProtocols value that represents the protocol used for authentication.
                    _configuration.SslCheckCertificateRevocation); // A Boolean value that specifies whether the certificate revocation list is checked during authentication.
            }

            // When authentication succeeds, you must check the IsEncrypted and IsSigned properties
            // to determine what security services are used by the SslStream.
            // Check the IsMutuallyAuthenticated property to determine whether mutual authentication occurred.
            _log.Debug(
                "Ssl Stream: SslProtocol[{0}], IsServer[{1}], IsAuthenticated[{2}], IsEncrypted[{3}], IsSigned[{4}], IsMutuallyAuthenticated[{5}], "
                + "HashAlgorithm[{6}], HashStrength[{7}], KeyExchangeAlgorithm[{8}], KeyExchangeStrength[{9}], CipherAlgorithm[{10}], CipherStrength[{11}].",
                sslStream.SslProtocol,
                sslStream.IsServer,
                sslStream.IsAuthenticated,
                sslStream.IsEncrypted,
                sslStream.IsSigned,
                sslStream.IsMutuallyAuthenticated,
                sslStream.HashAlgorithm,
                sslStream.HashStrength,
                sslStream.KeyExchangeAlgorithm,
                sslStream.KeyExchangeStrength,
                sslStream.CipherAlgorithm,
                sslStream.CipherStrength);

            return(sslStream);
        }
Exemple #34
0
 /// <summary>
 /// Attempts to bind to the configured IPEndpoint and performs a TLS handshake for incoming clients.
 /// </summary>
 public Promise <ISockNetChannel> BindWithTLS(X509Certificate serverCertificate, RemoteCertificateValidationCallback certificateValidationCallback)
 {
     return(BindInternal(true, serverCertificate, certificateValidationCallback));
 }
Exemple #35
0
 public CertificateCallbackMapper(Func <HttpRequestMessage, X509Certificate2?, X509Chain?, SslPolicyErrors, bool> fromHttpClientHandler)
 {
     FromHttpClientHandler = fromHttpClientHandler;
     ForSocketsHttpHandler = (object sender, X509Certificate? certificate, X509Chain? chain, SslPolicyErrors sslPolicyErrors) =>
                             FromHttpClientHandler((HttpRequestMessage)sender, certificate as X509Certificate2, chain, sslPolicyErrors);
 }
Exemple #36
0
 public WebSocketSecureConnectionExtension(X509Certificate2 certificate, RemoteCertificateValidationCallback validation)
 {
     _certificate = certificate;
     _validation  = validation;
 }
Exemple #37
0
 private void OverrideSSL()
 {
     SSLCallback = ServicePointManager.ServerCertificateValidationCallback;
     ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateSSL);
 }
Exemple #38
0
 public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback)
     : this(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback, null, EncryptionPolicy.RequireEncryption)
 {
 }
Exemple #39
0
 static void SetCertValidation()
 {
     // Set up cert validator
     originalValidationCallback = ServicePointManager.ServerCertificateValidationCallback;
     ServicePointManager.ServerCertificateValidationCallback = GDEOAuthValidator;
 }
        protected override async Task <AuthenticationTicket> CreateTicketAsync(ClaimsIdentity identity, AuthenticationProperties properties, OAuthTokenResponse tokens)
        {
            HttpRequestMessage request = GetTokenInfoRequestMessage(tokens);
            HttpClient         client  = GetHttpClient();

#if NET452
            RemoteCertificateValidationCallback prevValidator = null;
            if (!Options.ValidateCertificates)
            {
                prevValidator = ServicePointManager.ServerCertificateValidationCallback;
                ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
            }
#endif

            HttpResponseMessage response = null;
            try
            {
                response = await client.SendAsync(request, Context.RequestAborted);
            }
            finally
            {
#if NET452
                ServicePointManager.ServerCertificateValidationCallback = prevValidator;
#endif
            }

            response.EnsureSuccessStatusCode();

            var resp = await response.Content.ReadAsStringAsync();

            var payload = JObject.Parse(resp);

            var identifier = CloudFoundryHelper.GetId(payload);
            if (!string.IsNullOrEmpty(identifier))
            {
                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, identifier, ClaimValueTypes.String, Options.ClaimsIssuer));
            }

            var givenName = CloudFoundryHelper.GetGivenName(payload);
            if (!string.IsNullOrEmpty(givenName))
            {
                identity.AddClaim(new Claim(ClaimTypes.GivenName, givenName, ClaimValueTypes.String, Options.ClaimsIssuer));
            }

            var familyName = CloudFoundryHelper.GetFamilyName(payload);
            if (!string.IsNullOrEmpty(familyName))
            {
                identity.AddClaim(new Claim(ClaimTypes.Surname, familyName, ClaimValueTypes.String, Options.ClaimsIssuer));
            }

            var name = CloudFoundryHelper.GetName(payload);
            if (!string.IsNullOrEmpty(name))
            {
                identity.AddClaim(new Claim(ClaimTypes.Name, name, ClaimValueTypes.String, Options.ClaimsIssuer));
            }

            var email = CloudFoundryHelper.GetEmail(payload);
            if (!string.IsNullOrEmpty(email))
            {
                identity.AddClaim(new Claim(ClaimTypes.Email, email, ClaimValueTypes.String, Options.ClaimsIssuer));
            }

            var scopes = CloudFoundryHelper.GetScopes(payload);
            if (scopes != null)
            {
                foreach (var s in scopes)
                {
                    identity.AddClaim(new Claim("scope", s, ClaimValueTypes.String, Options.ClaimsIssuer));
                }
            }

            var ticket  = new AuthenticationTicket(new ClaimsPrincipal(identity), properties, Options.AuthenticationScheme);
            var context = new OAuthCreatingTicketContext(ticket, Context, Options, Backchannel, tokens, payload);

            await Options.Events.CreatingTicket(context);

            return(context.Ticket);
        }
Exemple #41
0
        public override void Import(PwDatabase pwStorage, Stream sInput,
                                    IStatusLogger slLogger)
        {
            slLogger.SetText("> Spamex.com...", LogStatusType.Info);

            SingleLineEditForm dlgUser = new SingleLineEditForm();

            dlgUser.InitEx("Spamex.com", KPRes.WebSiteLogin + " - " + KPRes.UserName,
                           KPRes.UserNamePrompt, KeePass.Properties.Resources.B48x48_WWW,
                           string.Empty, null);
            if (dlgUser.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            SingleLineEditForm dlgPassword = new SingleLineEditForm();

            dlgPassword.InitEx("Spamex.com", KPRes.WebSiteLogin + " - " + KPRes.Password,
                               KPRes.PasswordPrompt, KeePass.Properties.Resources.B48x48_WWW,
                               string.Empty, null);
            if (dlgPassword.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            RemoteCertificateValidationCallback pPrevCertCb =
                ServicePointManager.ServerCertificateValidationCallback;

            ServicePointManager.ServerCertificateValidationCallback =
                delegate(object sender, X509Certificate certificate, X509Chain chain,
                         SslPolicyErrors sslPolicyErrors)
            {
                return(true);
            };

            try
            {
                slLogger.SetText(KPRes.ImportingStatusMsg, LogStatusType.Info);

                string strUser     = dlgUser.ResultString;;
                string strPassword = dlgPassword.ResultString;

                string strPostData = @"toollogin=&MetaDomain=&LoginEmail=" +
                                     strUser + @"&LoginPassword="******"&Remember=1";

                List <KeyValuePair <string, string> > vCookies;
                string strMain = NetUtil.WebPageLogin(new Uri(UrlLoginPage),
                                                      strPostData, out vCookies);

                if (strMain.IndexOf("Welcome <b>" + strUser + "</b>") < 0)
                {
                    MessageService.ShowWarning(KPRes.InvalidUserPassword);
                    return;
                }

                string strIndexPage = NetUtil.WebPageGetWithCookies(new Uri(UrlIndexPage),
                                                                    vCookies, UrlDomain);

                ImportIndex(pwStorage, strIndexPage, vCookies, slLogger);

                int           nOffset   = 0;
                List <string> vSubPages = new List <string>();
                while (true)
                {
                    string strLink = StrUtil.GetStringBetween(strIndexPage, nOffset,
                                                              StrTabLinksStart, StrTabLinksEnd, out nOffset);
                    ++nOffset;

                    if (strLink.Length == 0)
                    {
                        break;
                    }

                    if (!strLink.StartsWith(StrTabLinkUrl))
                    {
                        continue;
                    }
                    if (vSubPages.IndexOf(strLink) >= 0)
                    {
                        continue;
                    }

                    vSubPages.Add(strLink);

                    string strSubPage = NetUtil.WebPageGetWithCookies(new Uri(
                                                                          UrlBase + strLink), vCookies, UrlDomain);

                    ImportIndex(pwStorage, strSubPage, vCookies, slLogger);
                }
            }
            catch
            {
                ServicePointManager.ServerCertificateValidationCallback = pPrevCertCb;
                throw;
            }

            ServicePointManager.ServerCertificateValidationCallback = pPrevCertCb;
        }
Exemple #42
0
 private async Task WithVirtualConnection(Func <SslStream, SslStream, Task> serverClientConnection, RemoteCertificateValidationCallback clientCertValidate)
 {
     (Stream clientStream, Stream serverStream) = TestHelper.GetConnectedStreams();
     using (SslStream server = new SslStream(serverStream, leaveInnerStreamOpen: false),
            client = new SslStream(clientStream, leaveInnerStreamOpen: false, clientCertValidate))
     {
         await serverClientConnection(server, client);
     }
 }
Exemple #43
0
        public RtmpClient(Uri uri, ObjectEncoding objectEncoding, SerializationContext serializationContext, RemoteCertificateValidationCallback validator)
            : this(uri, serializationContext, objectEncoding)
        {
            if (validator == null)
            {
                throw new ArgumentNullException(nameof(validator));
            }

            this.validator = validator;
        }
Exemple #44
0
 /// <summary>
 /// Configures the <see cref="DbContext"/> to use the specified <see cref="RemoteCertificateValidationCallback"/>.
 /// </summary>
 /// <param name="callback">The callback to use.</param>
 public virtual void RemoteCertificateValidationCallback([CanBeNull] RemoteCertificateValidationCallback callback)
 => WithOption(e => e.WithRemoteCertificateValidationCallback(callback));
        /// <summary>
        /// Create a new OICP roaming client for CPOs.
        /// </summary>
        /// <param name="ClientId">A unqiue identification of this client.</param>
        /// <param name="RemoteHostname">The hostname of the remote OICP service.</param>
        /// <param name="RemoteTCPPort">An optional TCP port of the remote OICP service.</param>
        /// <param name="RemoteCertificateValidator">A delegate to verify the remote TLS certificate.</param>
        /// <param name="ClientCertificateSelector">A delegate to select a TLS client certificate.</param>
        /// <param name="RemoteHTTPVirtualHost">An optional HTTP virtual hostname of the remote OICP service.</param>
        /// <param name="HTTPUserAgent">An optional HTTP user agent identification string for this HTTP client.</param>
        /// <param name="RequestTimeout">An optional timeout for upstream queries.</param>
        /// <param name="MaxNumberOfRetries">The default number of maximum transmission retries.</param>
        ///
        /// <param name="ServerName">An optional identification string for the HTTP server.</param>
        /// <param name="ServiceName">An optional identification for this SOAP service.</param>
        /// <param name="ServerTCPPort">An optional TCP port for the HTTP server.</param>
        /// <param name="ServerURLPrefix">An optional prefix for the HTTP URLs.</param>
        /// <param name="ServerContentType">An optional HTTP content type to use.</param>
        /// <param name="ServerRegisterHTTPRootService">Register HTTP root services for sending a notice to clients connecting via HTML or plain text.</param>
        /// <param name="ServerAutoStart">Whether to start the server immediately or not.</param>
        ///
        /// <param name="ClientLoggingContext">An optional context for logging client methods.</param>
        /// <param name="ServerLoggingContext">An optional context for logging server methods.</param>
        /// <param name="LogfileCreator">A delegate to create a log file from the given context and log file name.</param>
        ///
        /// <param name="DNSClient">An optional DNS client to use.</param>
        public CPORoaming(String ClientId,
                          HTTPHostname RemoteHostname,
                          IPPort?RemoteTCPPort = null,
                          RemoteCertificateValidationCallback RemoteCertificateValidator = null,
                          LocalCertificateSelectionCallback ClientCertificateSelector    = null,
                          HTTPHostname?RemoteHTTPVirtualHost = null,
                          HTTPPath?URLPrefix           = null,
                          String EVSEDataURL           = CPOClient.DefaultEVSEDataURL,
                          String EVSEStatusURL         = CPOClient.DefaultEVSEStatusURL,
                          String AuthorizationURL      = CPOClient.DefaultAuthorizationURL,
                          String AuthenticationDataURL = CPOClient.DefaultAuthenticationDataURL,
                          String HTTPUserAgent         = CPOClient.DefaultHTTPUserAgent,
                          TimeSpan?RequestTimeout      = null,
                          Byte?MaxNumberOfRetries      = CPOClient.DefaultMaxNumberOfRetries,

                          String ServerName                     = CPOSOAPServer.DefaultHTTPServerName,
                          IPPort?ServerTCPPort                  = null,
                          String ServiceName                    = null,
                          HTTPPath?ServerURLPrefix              = null,
                          String ServerAuthorizationURL         = CPOSOAPServer.DefaultAuthorizationURL,
                          String ServerReservationURL           = CPOSOAPServer.DefaultReservationURL,
                          HTTPContentType ServerContentType     = null,
                          Boolean ServerRegisterHTTPRootService = true,
                          Boolean ServerAutoStart               = false,

                          String ClientLoggingContext           = CPOClient.CPOClientLogger.DefaultContext,
                          String ServerLoggingContext           = CPOServerLogger.DefaultContext,
                          LogfileCreatorDelegate LogfileCreator = null,

                          DNSClient DNSClient = null)

            : this(new CPOClient(ClientId,
                                 RemoteHostname,
                                 RemoteTCPPort,
                                 RemoteCertificateValidator,
                                 ClientCertificateSelector,
                                 RemoteHTTPVirtualHost,
                                 URLPrefix ?? CPOClient.DefaultURLPrefix,
                                 EVSEDataURL,
                                 EVSEStatusURL,
                                 AuthorizationURL,
                                 AuthenticationDataURL,
                                 HTTPUserAgent,
                                 RequestTimeout,
                                 MaxNumberOfRetries,
                                 DNSClient,
                                 ClientLoggingContext,
                                 LogfileCreator),

                   new CPOSOAPServer(ServerName,
                                     ServerTCPPort,
                                     ServiceName,
                                     ServerURLPrefix ?? CPOSOAPServer.DefaultURLPathPrefix,
                                     ServerAuthorizationURL,
                                     ServerReservationURL,
                                     ServerContentType,
                                     ServerRegisterHTTPRootService,
                                     DNSClient,
                                     false),

                   ServerLoggingContext,
                   LogfileCreator)

        {
            if (ServerAutoStart)
            {
                Start();
            }
        }
Exemple #46
0
        public string Test()
        {
            StringBuilder results = new StringBuilder();

            results.Append("\n\n");
            DateTime StartTime = DateTime.MinValue;

            byte[] Data = StringToUtf8Bytes(requestXml);

            //ServicePointManager.CertificatePolicy =
            //  new TrustAllCertificatePolicy();

            RemoteCertificateValidationCallback callback = new RemoteCertificateValidationCallback(ValidateAnyServerCertificate);

            ServicePointManager.ServerCertificateValidationCallback = callback;

            HttpWebRequest webRequest =
                (HttpWebRequest)WebRequest.Create(requestUrl);

            webRequest.Method        = "POST";
            webRequest.ContentLength = Data.Length;

            webRequest.Headers.Add("Authorization",
                                   string.Format("Basic {0}",
                                                 GetAuthorization(merchantID, merchantKey)));

            webRequest.ContentType = "application/xml";
            webRequest.Accept      = "application/xml";
            webRequest.Timeout     = timeoutMilliseconds;

            try
            {
                Stream requestStream = webRequest.GetRequestStream();
                requestStream.Write(Data, 0, Data.Length);
                requestStream.Close();


                try
                {
                    StartTime = DateTime.Now;
                    HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

                    results.Append(string.Format("Status code: {0}\n", webResponse.StatusCode));

                    Stream       responseStream = webResponse.GetResponseStream();
                    StreamReader responseReader = new StreamReader(responseStream);

                    results.Append(responseReader.ReadToEnd());
                    responseReader.Close();

                    results.Append(string.Format("\nResponse time: {0} ms",
                                                 DateTime.Now.Subtract(StartTime).TotalMilliseconds));
                }
                catch (WebException ex)
                {
                    if (ex.Response != null)
                    {
                        HttpWebResponse errorResponse = (HttpWebResponse)ex.Response;
                        results.Append(string.Format("Status code: {0}\n", errorResponse.StatusCode));

                        StreamReader sr = new
                                          StreamReader(errorResponse.GetResponseStream());

                        results.Append(sr.ReadToEnd());
                        sr.Close();

                        results.Append(string.Format("\nResponse time: {0} ms",
                                                     DateTime.Now.Subtract(StartTime).TotalMilliseconds));
                    }
                }
            }
            catch (WebException ex)
            {
                results.Append(ex.Message);
            }

            return(results.ToString());
        }
Exemple #47
0
 static Http()
 {
     AcceptAllCertificationsCallback = new RemoteCertificateValidationCallback(AcceptAllCertifications);
 }
Exemple #48
0
        /// <summary>
        /// Create an instance of the Open Charging Cloud EMP API.
        /// </summary>
        /// <param name="ServiceName">The name of the service.</param>
        /// <param name="HTTPServerName">The default HTTP servername, used whenever no HTTP Host-header had been given.</param>
        /// <param name="LocalHostname">The HTTP hostname for all URIs within this API.</param>
        /// <param name="LocalPort">A TCP port to listen on.</param>
        /// <param name="ExternalDNSName">The offical URL/DNS name of this service, e.g. for sending e-mails.</param>
        /// <param name="URLPathPrefix">A common prefix for all URLs.</param>
        ///
        /// <param name="ServerCertificateSelector">An optional delegate to select a SSL/TLS server certificate.</param>
        /// <param name="ClientCertificateValidator">An optional delegate to verify the SSL/TLS client certificate used for authentication.</param>
        /// <param name="ClientCertificateSelector">An optional delegate to select the SSL/TLS client certificate used for authentication.</param>
        /// <param name="AllowedTLSProtocols">The SSL/TLS protocol(s) allowed for this connection.</param>
        ///
        /// <param name="APIEMailAddress">An e-mail address for this API.</param>
        /// <param name="APIPassphrase">A GPG passphrase for this API.</param>
        /// <param name="APIAdminEMails">A list of admin e-mail addresses.</param>
        /// <param name="APISMTPClient">A SMTP client for sending e-mails.</param>
        ///
        /// <param name="SMSAPICredentials">The credentials for the SMS API.</param>
        /// <param name="APIAdminSMS">A list of admin SMS phonenumbers.</param>
        ///
        /// <param name="CookieName">The name of the HTTP Cookie for authentication.</param>
        /// <param name="UseSecureCookies">Force the web browser to send cookies only via HTTPS.</param>
        /// <param name="Language">The main language of the API.</param>
        /// <param name="NewUserSignUpEMailCreator">A delegate for sending a sign-up e-mail to a new user.</param>
        /// <param name="NewUserWelcomeEMailCreator">A delegate for sending a welcome e-mail to a new user.</param>
        /// <param name="ResetPasswordEMailCreator">A delegate for sending a reset password e-mail to a user.</param>
        /// <param name="PasswordChangedEMailCreator">A delegate for sending a password changed e-mail to a user.</param>
        /// <param name="MinUserNameLength">The minimal user name length.</param>
        /// <param name="MinRealmLength">The minimal realm length.</param>
        /// <param name="PasswordQualityCheck">A delegate to ensure a minimal password quality.</param>
        /// <param name="SignInSessionLifetime">The sign-in session lifetime.</param>
        ///
        /// <param name="ServerThreadName">The optional name of the TCP server thread.</param>
        /// <param name="ServerThreadPriority">The optional priority of the TCP server thread.</param>
        /// <param name="ServerThreadIsBackground">Whether the TCP server thread is a background thread or not.</param>
        /// <param name="ConnectionIdBuilder">An optional delegate to build a connection identification based on IP socket information.</param>
        /// <param name="ConnectionThreadsNameBuilder">An optional delegate to set the name of the TCP connection threads.</param>
        /// <param name="ConnectionThreadsPriorityBuilder">An optional delegate to set the priority of the TCP connection threads.</param>
        /// <param name="ConnectionThreadsAreBackground">Whether the TCP connection threads are background threads or not (default: yes).</param>
        /// <param name="ConnectionTimeout">The TCP client timeout for all incoming client connections in seconds (default: 30 sec).</param>
        /// <param name="MaxClientConnections">The maximum number of concurrent TCP client connections (default: 4096).</param>
        ///
        /// <param name="SkipURLTemplates">Skip URI templates.</param>
        /// <param name="DisableNotifications">Disable external notifications.</param>
        /// <param name="DisableLogfile">Disable the log file.</param>
        /// <param name="LoggingPath">The path for all logfiles.</param>
        /// <param name="LogfileName">The name of the logfile for this API.</param>
        /// <param name="DNSClient">The DNS client of the API.</param>
        /// <param name="Autostart">Whether to start the API automatically.</param>
        public OpenChargingCloudEMPAPI(String ServiceName         = "GraphDefined Open Charging Cloud EMP API",
                                       String HTTPServerName      = "GraphDefined Open Charging Cloud EMP API",
                                       HTTPHostname?LocalHostname = null,
                                       IPPort?LocalPort           = null,
                                       String ExternalDNSName     = null,
                                       HTTPPath?URLPathPrefix     = null,

                                       ServerCertificateSelectorDelegate ServerCertificateSelector    = null,
                                       RemoteCertificateValidationCallback ClientCertificateValidator = null,
                                       LocalCertificateSelectionCallback ClientCertificateSelector    = null,
                                       SslProtocols AllowedTLSProtocols = SslProtocols.Tls12,

                                       EMailAddress APIEMailAddress    = null,
                                       String APIPassphrase            = null,
                                       EMailAddressList APIAdminEMails = null,
                                       SMTPClient APISMTPClient        = null,

                                       Credentials SMSAPICredentials         = null,
                                       IEnumerable <PhoneNumber> APIAdminSMS = null,

                                       HTTPCookieName?CookieName = null,
                                       Boolean UseSecureCookies  = true,
                                       Languages?Language        = null,
                                       NewUserSignUpEMailCreatorDelegate NewUserSignUpEMailCreator     = null,
                                       NewUserWelcomeEMailCreatorDelegate NewUserWelcomeEMailCreator   = null,
                                       ResetPasswordEMailCreatorDelegate ResetPasswordEMailCreator     = null,
                                       PasswordChangedEMailCreatorDelegate PasswordChangedEMailCreator = null,
                                       Byte?MinUserNameLength = null,
                                       Byte?MinRealmLength    = null,
                                       PasswordQualityCheckDelegate PasswordQualityCheck = null,
                                       TimeSpan?SignInSessionLifetime = null,

                                       String ServerThreadName                 = null,
                                       ThreadPriority ServerThreadPriority     = ThreadPriority.AboveNormal,
                                       Boolean ServerThreadIsBackground        = true,
                                       ConnectionIdBuilder ConnectionIdBuilder = null,
                                       ConnectionThreadsNameBuilder ConnectionThreadsNameBuilder         = null,
                                       ConnectionThreadsPriorityBuilder ConnectionThreadsPriorityBuilder = null,
                                       Boolean ConnectionThreadsAreBackground = true,
                                       TimeSpan?ConnectionTimeout             = null,
                                       UInt32 MaxClientConnections            = TCPServer.__DefaultMaxClientConnections,

                                       Boolean SkipURLTemplates     = false,
                                       Boolean DisableNotifications = false,
                                       Boolean DisableLogfile       = false,
                                       String DatabaseFile          = DefaultOpenChargingCloudEMPAPIDatabaseFile,
                                       String LoggingPath           = null,
                                       String LogfileName           = DefaultOpenChargingCloudEMPAPILogFile,
                                       DNSClient DNSClient          = null,
                                       Boolean Autostart            = false)

            : base(ServiceName:                       ServiceName ?? "GraphDefined Open Charging Cloud EMP API",
                   HTTPServerName:                    HTTPServerName ?? "GraphDefined Open Charging Cloud EMP API",
                   LocalHostname:                     LocalHostname,
                   LocalPort:                         LocalPort,
                   ExternalDNSName:                           ExternalDNSName,
                   URLPathPrefix:                     URLPathPrefix,
                   UseSecureCookies:                  UseSecureCookies,

                   ServerCertificateSelector:         ServerCertificateSelector,
                   ClientCertificateValidator:        ClientCertificateValidator,
                   ClientCertificateSelector:         ClientCertificateSelector,
                   AllowedTLSProtocols:               AllowedTLSProtocols,

                   APIEMailAddress:                   APIEMailAddress,
                   APIPassphrase:                     APIPassphrase,
                   APIAdminEMails:                    APIAdminEMails,
                   APISMTPClient:                     APISMTPClient,

                   SMSAPICredentials:                 SMSAPICredentials,
                   APIAdminSMS:                       APIAdminSMS,

                   CookieName:                        CookieName ?? HTTPCookieName.Parse("OpenChargingCloudEMPAPI"),
                   Language:                          Language,
                   NewUserSignUpEMailCreator:         NewUserSignUpEMailCreator,
                   NewUserWelcomeEMailCreator:        NewUserWelcomeEMailCreator,
                   ResetPasswordEMailCreator:         ResetPasswordEMailCreator,
                   PasswordChangedEMailCreator:       PasswordChangedEMailCreator,
                   MinUserNameLength:                 MinUserNameLength,
                   MinRealmLength:                    MinRealmLength,
                   PasswordQualityCheck:              PasswordQualityCheck,
                   SignInSessionLifetime:             SignInSessionLifetime,

                   ServerThreadName:                  ServerThreadName,
                   ServerThreadPriority:              ServerThreadPriority,
                   ServerThreadIsBackground:          ServerThreadIsBackground,
                   ConnectionIdBuilder:               ConnectionIdBuilder,
                   ConnectionThreadsNameBuilder:      ConnectionThreadsNameBuilder,
                   ConnectionThreadsPriorityBuilder:  ConnectionThreadsPriorityBuilder,
                   ConnectionThreadsAreBackground:    ConnectionThreadsAreBackground,
                   ConnectionTimeout:                 ConnectionTimeout,
                   MaxClientConnections:              MaxClientConnections,

                   SkipURLTemplates:                  SkipURLTemplates,
                   DisableNotifications:              DisableNotifications,
                   DisableLogfile:                    DisableLogfile,
                   DatabaseFile:                      DatabaseFile ?? DefaultOpenChargingCloudEMPAPIDatabaseFile,
                   LoggingPath:                       LoggingPath ?? "default",
                   LogfileName:                       LogfileName ?? DefaultOpenChargingCloudEMPAPILogFile,
                   DNSClient:                         DNSClient,
                   Autostart:                         false)

        {
            //RegisterURLTemplates();

            if (Autostart)
            {
                Start();
            }
        }
Exemple #49
0
 public MqttServerOptionsBuilder WithRemoteCertificateValidationCallback(RemoteCertificateValidationCallback value)
 {
     _options.TlsEndpointOptions.RemoteCertificateValidationCallback = value;
     return(this);
 }
 internal SslStream CreateSslStream(Stream innerStream, bool ownsStream, RemoteCertificateValidationCallback callback)
 {
     return(new SslStream(innerStream, ownsStream, callback));
 }
        public SecureTcpServer(int listenPort, X509Certificate serverCertificate, SecureConnectionResultsCallback callback, RemoteCertificateValidationCallback certValidationCallback)
        {
            if (listenPort < 0 || listenPort > UInt16.MaxValue)
            {
                throw new ArgumentOutOfRangeException("listenPort");
            }
            if (serverCertificate == null)
            {
                throw new ArgumentNullException("serverCertificate");
            }
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

            onAcceptConnection          = new AsyncCallback(OnAcceptConnection);
            onAuthenticateAsServer      = new AsyncCallback(OnAuthenticateAsServer);
            this.serverCert             = serverCertificate;
            this.certValidationCallback = certValidationCallback;
            this.connectionCallback     = callback;
            this.listenPort             = listenPort;
            this.disposed = 0;
            this.checkCertifcateRevocation = false;
            this.clientCertificateRequired = false;
            this.sslProtocols = SslProtocols.Default;
        }
Exemple #52
0
        /// <summary>
        /// Binds to the configured endpoint and sets security variables.
        /// </summary>
        /// <param name="isSsl"></param>
        /// <param name="certificateValidationCallback"></param>
        /// <returns></returns>
        private Promise <ISockNetChannel> BindInternal(bool isSsl, X509Certificate serverCertificate, RemoteCertificateValidationCallback certificateValidationCallback)
        {
            Promise <ISockNetChannel> promise = new Promise <ISockNetChannel>();

            if (TryFlaggingAs(ServerSockNetChannelState.Binding, ServerSockNetChannelState.Closed))
            {
                SockNetLogger.Log(SockNetLogger.LogLevel.INFO, this, "Binding to [{0}]...", bindEndpoint);

                this.IsSsl = isSsl;
                this.CertificateValidationCallback = certificateValidationCallback;
                this.ServerCertificate             = serverCertificate;

                Socket.Bind(bindEndpoint);
                Socket.Listen(backlog);

                this.State = ServerSockNetChannelState.Bound;

                SockNetLogger.Log(SockNetLogger.LogLevel.INFO, this, "Bound to [{0}].", LocalEndpoint);

                Socket.BeginAccept(new AsyncCallback(AcceptCallback), Socket);

                promise.CreateFulfiller().Fulfill(this);
            }
            else
            {
                throw new Exception("The server is already bound.");
            }

            return(promise);
        }
Exemple #53
0
        public async Task OpenAsync(
            bool useWebSocket,
            X509Certificate2 clientCert,
            IWebProxy proxy,
            RemoteCertificateValidationCallback remoteCerificateValidationCallback,
            CancellationToken cancellationToken)
        {
            if (Logging.IsEnabled)
            {
                Logging.Enter(this, $"{nameof(AmqpClientConnection)}.{nameof(OpenAsync)}");
            }

            string hostName = _uri.Host;

            var tcpSettings = new TcpTransportSettings {
                Host = hostName, Port = _uri.Port != -1 ? _uri.Port : AmqpConstants.DefaultSecurePort
            };

            TransportSettings = new TlsTransportSettings(tcpSettings)
            {
                TargetHost  = hostName,
                Certificate = clientCert,
                CertificateValidationCallback = remoteCerificateValidationCallback,
            };

            if (useWebSocket)
            {
                _transport = await CreateClientWebSocketTransportAsync(proxy, cancellationToken).ConfigureAwait(false);

                SaslTransportProvider provider = _amqpSettings.GetTransportProvider <SaslTransportProvider>();
                if (provider != null)
                {
                    if (Logging.IsEnabled)
                    {
                        Logging.Info(this, $"{nameof(AmqpClientConnection)}.{nameof(OpenAsync)}: Using SaslTransport");
                    }

                    _sentHeader      = new ProtocolHeader(provider.ProtocolId, provider.DefaultVersion);
                    using var buffer = new ByteBuffer(new byte[AmqpConstants.ProtocolHeaderSize]);
                    _sentHeader.Encode(buffer);

                    _tcs = new TaskCompletionSource <TransportBase>();

                    var args = new TransportAsyncCallbackArgs();
                    args.SetBuffer(buffer.Buffer, buffer.Offset, buffer.Length);
                    args.CompletedCallback = OnWriteHeaderComplete;
                    args.Transport         = _transport;
                    bool operationPending = _transport.WriteAsync(args);

                    if (Logging.IsEnabled)
                    {
                        Logging.Info(
                            this,
                            $"{nameof(AmqpClientConnection)}.{nameof(OpenAsync)}: " +
                            $"Sent Protocol Header: {_sentHeader} operationPending: {operationPending} completedSynchronously: {args.CompletedSynchronously}");
                    }

                    if (!operationPending)
                    {
                        args.CompletedCallback(args);
                    }

                    _transport = await _tcs.Task.ConfigureAwait(false);

                    await _transport.OpenAsync(cancellationToken).ConfigureAwait(false);
                }
            }
            else
            {
                var tcpInitiator = new AmqpTransportInitiator(_amqpSettings, TransportSettings);
                _transport = await tcpInitiator.ConnectAsync(cancellationToken).ConfigureAwait(false);
            }

            AmqpConnection         = new AmqpConnection(_transport, _amqpSettings, AmqpConnectionSettings);
            AmqpConnection.Closed += OnConnectionClosed;
            await AmqpConnection.OpenAsync(cancellationToken).ConfigureAwait(false);

            IsConnectionClosed = false;
        }
Exemple #54
0
 private void connect()
 {
     if (this.client != null)
     {
         this.disconnect();
     }
     this.client = new TcpClient();
     ApplePushChannel.ConnectingDelegate onConnecting = this.OnConnecting;
     if (onConnecting != null)
     {
         onConnecting(this.appleSettings.Host, this.appleSettings.Port);
     }
     try
     {
         AutoResetEvent connectDone = new AutoResetEvent(false);
         this.connectAsyncResult = this.client.BeginConnect(this.appleSettings.Host, this.appleSettings.Port, (AsyncCallback)(ar =>
         {
             if (this.connectAsyncResult != ar)
             {
                 return;
             }
             try
             {
                 this.client.EndConnect(ar);
                 try
                 {
                     this.client.SetSocketKeepAliveValues(1200000, 30000);
                 }
                 catch
                 {
                 }
                 Interlocked.Increment(ref this.reconnects);
                 connectDone.Set();
             }
             catch (Exception ex)
             {
                 Log.Error("APNS Connect Callback Failed: " + (object)ex);
             }
         }), (object)this.client);
         if (!connectDone.WaitOne(this.appleSettings.ConnectionTimeout))
         {
             throw new TimeoutException("Connection to Host Timed Out!");
         }
     }
     catch (Exception ex)
     {
         throw new ConnectionFailureException("Connection to Host Failed", ex);
     }
     if (this.appleSettings.SkipSsl)
     {
         this.networkStream = (Stream)this.client.GetStream();
     }
     else
     {
         RemoteCertificateValidationCallback userCertificateValidationCallback;
         if (this.appleSettings != null && this.appleSettings.ValidateServerCertificate)
         {
             userCertificateValidationCallback = new RemoteCertificateValidationCallback(ApplePushChannel.ValidateRemoteCertificate);
         }
         else
         {
             userCertificateValidationCallback = (RemoteCertificateValidationCallback)((sender, cert, chain, sslPolicyErrors) => true);
         }
         this.stream = new SslStream((Stream)this.client.GetStream(), false, userCertificateValidationCallback, (LocalCertificateSelectionCallback)((sender, targetHost, localCerts, remoteCert, acceptableIssuers) => this.certificate));
         try
         {
             this.stream.AuthenticateAsClient(this.appleSettings.Host, this.certificates, SslProtocols.Tls, false);
         }
         catch (AuthenticationException ex)
         {
             throw new ConnectionFailureException("SSL Stream Failed to Authenticate as Client", (Exception)ex);
         }
         if (!this.stream.IsMutuallyAuthenticated)
         {
             throw new ConnectionFailureException("SSL Stream Failed to Authenticate", (Exception)null);
         }
         if (!this.stream.CanWrite)
         {
             throw new ConnectionFailureException("SSL Stream is not Writable", (Exception)null);
         }
         this.networkStream = (Stream)this.stream;
     }
     this.Reader();
 }
Exemple #55
0
 public ImapClient(string hostName, int port, bool isSecure = false, RemoteCertificateValidationCallback validate = null)
     : base(hostName, port, isSecure, validate)
 {
 }
Exemple #56
0
 /// <summary>
 /// Constructor (TCP/IP communication layer on port 8883 with SSL/TLS and default settings)
 /// </summary>
 /// <param name="serverCert">X509 Server certificate</param>
 /// <param name="sslProtocol">SSL/TLS protocol version</param>
 /// <param name="userCertificateSelectionCallback">A RemoteCertificateValidationCallback delegate responsible for validating the certificate supplied by the remote party</param>
 /// <param name="userCertificateValidationCallback">A LocalCertificateSelectionCallback delegate responsible for selecting the certificate used for authentication</param>
 public MqttBroker(X509Certificate serverCert, MqttSslProtocols sslProtocol,
                   RemoteCertificateValidationCallback userCertificateValidationCallback,
                   LocalCertificateSelectionCallback userCertificateSelectionCallback)
     : this(new MqttTcpCommunicationLayer(MqttSettings.MQTT_BROKER_DEFAULT_SSL_PORT, true, serverCert, sslProtocol, userCertificateValidationCallback, userCertificateSelectionCallback), MqttSettings.Instance)
 {
 }
Exemple #57
0
        // Constructor with all parameters possible from class 'JetbusConnection' - Without ssh certification.
        //public TestJetbusConnection(Behavior behavior, string ipAddr, string user, string passwd, RemoteCertificateValidationCallback certificationCallback, int timeoutMs = 5000) : base(ipAddr, user, passwd, certificationCallback, timeoutMs = 5000)

        public TestJetbusConnection(Behavior behavior, string ipAddr, string user, string passwd, RemoteCertificateValidationCallback certificationCallback, int timeoutMs = 5000)
        {
            //IJetConnection jetConnection = new WebSocketJetConnection(_uri, RemoteCertificationCheck);

            _peer = new TestJetPeer(behavior, this);

            this.connected = false;
            this.behavior  = behavior;
            this.messages  = new List <string>();

            _dataBuffer = new Dictionary <string, JToken>();

            this._mTimeoutMs = 5000; // values of 5000 according to the initialization in class JetBusConnection.

            //ConnectOnPeer(user, passwd, timeoutMs);
            FetchAll();
        }
Exemple #58
0
 public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback)
     : this(innerStream, leaveInnerStreamOpen)
 {
 }
Exemple #59
0
 public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback, LocalCertificateSelectionCallback userCertificateSelectionCallback, EncryptionPolicy encryptionPolicy)
     : this(innerStream, leaveInnerStreamOpen)
 {
 }
Exemple #60
-1
        private void connect(string host, int port, bool isSsl, RemoteCertificateValidationCallback validate)
        {
            if (_client == null)
            {
                _client = new TcpClient { ReceiveTimeout = 20000 };
            }

            if (!_client.Connected)
            {
                try
                {
                    _client.Connect(host, port);
                }
                catch (SocketException ex)
                {
                    var retVal = string.Empty;
                    switch (ex.ErrorCode)
                    {
                        case 11001: // Host not found.
                            retVal = ex.Message;
                            break;
                        case 10060: //Connection timed out.  (invalid portNo) (yahoo,hotmail and indiatimes)
                        case 10061: //Connection refused.
                        case 10013: // Permission denied. from hotmail
                            retVal = "Invalid host or port number";
                            break;
                        default:
                            retVal = "Invalid host or port number";
                            break;
                    }

                    throw new Exception(retVal);
                }
            }

            if (_client.Connected)
            {
                _stream = _client.GetStream();
                if (isSsl)
                {
                    try
                    {
                        var sslStream = new SslStream(_stream, false, validate ?? ((sender, cert, chain, err) => true));
                        sslStream.AuthenticateAsClient(host);
                        _stream = sslStream;
                    }
                    catch(Exception)
                    {
                        throw;
                    }
                }

                var response = ReadResponse();

                ValidateResponse(response);
            }
        }