Ejemplo n.º 1
0
        /// <summary>
        /// Extends BeginAuthenticateAsClient so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// negotiatestream.BeginAuthenticateAsClient(credential, binding, targetName, requiredProtectionLevel, allowedImpersonationLevel, asyncCallback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginAuthenticateAsClient(this NegotiateStream negotiatestream, System.Net.NetworkCredential credential, System.Security.Authentication.ExtendedProtection.ChannelBinding binding, String targetName, ProtectionLevel requiredProtectionLevel, System.Security.Principal.TokenImpersonationLevel allowedImpersonationLevel, AsyncCallback asyncCallback)
        {
            if (negotiatestream == null)
            {
                throw new ArgumentNullException("negotiatestream");
            }

            return(negotiatestream.BeginAuthenticateAsClient(credential, binding, targetName, requiredProtectionLevel, allowedImpersonationLevel, asyncCallback, null));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Extends BeginAuthenticateAsClient so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// negotiatestream.BeginAuthenticateAsClient(credential, targetName, asyncCallback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginAuthenticateAsClient(this NegotiateStream negotiatestream, System.Net.NetworkCredential credential, String targetName, AsyncCallback asyncCallback)
        {
            if (negotiatestream == null)
            {
                throw new ArgumentNullException("negotiatestream");
            }

            return(negotiatestream.BeginAuthenticateAsClient(credential, targetName, asyncCallback, null));
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Extends BeginAuthenticateAsClient so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// negotiatestream.BeginAuthenticateAsClient(asyncCallback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginAuthenticateAsClient(this NegotiateStream negotiatestream, AsyncCallback asyncCallback)
        {
            if (negotiatestream == null)
            {
                throw new ArgumentNullException("negotiatestream");
            }

            return(negotiatestream.BeginAuthenticateAsClient(asyncCallback, null));
        }
Ejemplo n.º 4
0
        public static void Main(String[] args)
        {
            //<snippet2>
            //<snippet1>
            // Establish the remote endpoint for the socket.
            // For this example, use the local machine.
            IPHostEntry ipHostInfo = Dns.GetHostEntry("localhost");
            IPAddress   ipAddress  = ipHostInfo.AddressList[0];
            // Client and server use port 11000.
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);

            // Create a TCP/IP socket.
            client = new TcpClient();
            // Connect the socket to the remote endpoint.
            client.Connect(remoteEP);
            Console.WriteLine("Client connected to {0}.", remoteEP.ToString());
            // Ensure the client does not close when there is
            // still data to be sent to the server.
            client.LingerState = (new LingerOption(true, 0));
            //<snippet3>
            // Request authentication.
            NetworkStream   clientStream = client.GetStream();
            NegotiateStream authStream   = new NegotiateStream(clientStream, false);
            //</snippet1>
            // Pass the NegotiateStream as the AsyncState object
            // so that it is available to the callback delegate.
            IAsyncResult ar = authStream.BeginAuthenticateAsClient(
                new AsyncCallback(EndAuthenticateCallback),
                authStream
                );

            //</snippet2>
            Console.WriteLine("Client waiting for authentication...");
            // Wait until the result is available.
            ar.AsyncWaitHandle.WaitOne();
            // Display the properties of the authenticated stream.
            AuthenticatedStreamReporter.DisplayProperties(authStream);
            // Send a message to the server.
            // Encode the test data into a byte array.
            byte[] message = Encoding.UTF8.GetBytes("Hello from the client.");
            ar = authStream.BeginWrite(message, 0, message.Length,
                                       new AsyncCallback(EndWriteCallback),
                                       authStream);
            //</snippet3>
            ar.AsyncWaitHandle.WaitOne();
            Console.WriteLine("Sent {0} bytes.", message.Length);
            // Close the client connection.
            authStream.Close();
            Console.WriteLine("Client closed.");
        }
Ejemplo n.º 5
0
 protected override Task AuthenticateAsClientAsync(NegotiateStream client, NetworkCredential credential, string targetName) =>
 Task.Factory.FromAsync(
     (callback, state) => client.BeginAuthenticateAsClient(credential, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, callback, state),
     client.EndAuthenticateAsClient, null);
Ejemplo n.º 6
0
        internal static bool TryOpenChannel(NetworkPath netPath, int timeoutInMs, out TcpClientChannel channel, out NetworkTransportException networkEx)
        {
            channel   = null;
            networkEx = null;
            Exception       ex              = null;
            Socket          socket          = null;
            Stream          stream          = null;
            NegotiateStream negotiateStream = null;
            ReplayStopwatch replayStopwatch = new ReplayStopwatch();

            replayStopwatch.Start();
            try
            {
                socket = new Socket(netPath.TargetEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                if (netPath.Purpose == NetworkPath.ConnectionPurpose.Seeding)
                {
                    socket.ReceiveBufferSize = RegistryParameters.SeedingNetworkTransferSize;
                    socket.SendBufferSize    = RegistryParameters.SeedingNetworkTransferSize;
                }
                else
                {
                    socket.ReceiveBufferSize = RegistryParameters.LogCopyNetworkTransferSize;
                    socket.SendBufferSize    = RegistryParameters.LogCopyNetworkTransferSize;
                }
                if (netPath.HasSourceEndpoint())
                {
                    socket.Bind(netPath.SourceEndPoint);
                }
                TcpClientChannel.ConnectAbandon connectAbandon = new TcpClientChannel.ConnectAbandon(socket);
                IAsyncResult asyncResult = socket.BeginConnect(netPath.TargetEndPoint.Address, netPath.TargetEndPoint.Port, null, connectAbandon);
                if (!asyncResult.AsyncWaitHandle.WaitOne(timeoutInMs, false))
                {
                    socket = null;
                    connectAbandon.Cancel(asyncResult);
                    TcpChannel.ThrowTimeoutException(netPath.TargetNodeName, ReplayStrings.NetworkConnectionTimeout(timeoutInMs / 1000));
                }
                socket.EndConnect(asyncResult);
                long elapsedMilliseconds = replayStopwatch.ElapsedMilliseconds;
                ExTraceGlobals.TcpClientTracer.TraceDebug <long>(0L, "Connection took {0}ms", elapsedMilliseconds);
                socket.LingerState = new LingerOption(true, 0);
                if (!netPath.UseSocketStream || RegistryParameters.DisableSocketStream)
                {
                    stream = new NetworkStream(socket, false);
                }
                else
                {
                    stream = new SocketStream(socket, netPath.SocketStreamBufferPool, netPath.SocketStreamAsyncArgPool, netPath.SocketStreamPerfCounters);
                }
                negotiateStream     = new NegotiateStream(stream, false);
                stream              = null;
                elapsedMilliseconds = replayStopwatch.ElapsedMilliseconds;
                if (elapsedMilliseconds >= (long)timeoutInMs)
                {
                    TcpChannel.ThrowTimeoutException(netPath.TargetNodeName, ReplayStrings.NetworkConnectionTimeout(timeoutInMs / 1000));
                }
                int num = timeoutInMs - (int)elapsedMilliseconds;
                negotiateStream.WriteTimeout = num;
                negotiateStream.ReadTimeout  = num;
                TcpClientChannel.AuthAbandon authAbandon = new TcpClientChannel.AuthAbandon(socket, negotiateStream);
                string targetName;
                if (netPath.UseNullSpn)
                {
                    targetName = "";
                }
                else
                {
                    targetName = "HOST/" + netPath.TargetNodeName;
                }
                bool            encrypt = netPath.Encrypt;
                ProtectionLevel protectionLevel;
                if (encrypt)
                {
                    protectionLevel = ProtectionLevel.EncryptAndSign;
                }
                else if (RegistryParameters.DisableNetworkSigning)
                {
                    protectionLevel = ProtectionLevel.None;
                }
                else
                {
                    protectionLevel = ProtectionLevel.Sign;
                }
                asyncResult = negotiateStream.BeginAuthenticateAsClient(CredentialCache.DefaultNetworkCredentials, targetName, protectionLevel, TokenImpersonationLevel.Identification, null, authAbandon);
                if (!asyncResult.AsyncWaitHandle.WaitOne(num, false))
                {
                    negotiateStream = null;
                    socket          = null;
                    authAbandon.Abandon(asyncResult);
                    TcpChannel.ThrowTimeoutException(netPath.TargetNodeName, ReplayStrings.NetworkConnectionTimeout(timeoutInMs / 1000));
                }
                negotiateStream.EndAuthenticateAsClient(asyncResult);
                bool flag = false;
                if (!negotiateStream.IsAuthenticated)
                {
                    flag = true;
                }
                else if (protectionLevel != ProtectionLevel.None && !negotiateStream.IsMutuallyAuthenticated)
                {
                    if (netPath.IgnoreMutualAuth || MachineName.Comparer.Equals(netPath.TargetNodeName, Environment.MachineName))
                    {
                        ExTraceGlobals.TcpClientTracer.TraceDebug(0L, "Ignoring mutual auth since we are local");
                    }
                    else
                    {
                        flag = true;
                    }
                }
                if (!flag && encrypt && !negotiateStream.IsEncrypted)
                {
                    ExTraceGlobals.TcpClientTracer.TraceError(0L, "Encryption requested, but could not be negotiated");
                    flag = true;
                }
                if (flag)
                {
                    ExTraceGlobals.TcpClientTracer.TraceError <bool, bool, bool>(0L, "Security Negotiation failed. Auth={0},MAuth={1},Encrypt={2}", negotiateStream.IsAuthenticated, negotiateStream.IsMutuallyAuthenticated, negotiateStream.IsEncrypted);
                    NetworkManager.ThrowException(new NetworkCommunicationException(netPath.TargetNodeName, ReplayStrings.NetworkSecurityFailed));
                }
                ExTraceGlobals.TcpClientTracer.TraceDebug <long, bool, ProtectionLevel>(0L, "Authenticated Connection took {0}ms. Encrypt={1} ProtRequested={2}", replayStopwatch.ElapsedMilliseconds, negotiateStream.IsEncrypted, protectionLevel);
                channel = new TcpClientChannel(netPath.TargetNodeName, socket, negotiateStream, timeoutInMs);
                return(true);
            }
            catch (SocketException ex2)
            {
                ex = ex2;
            }
            catch (IOException ex3)
            {
                ex = ex3;
            }
            catch (AuthenticationException ex4)
            {
                ex = ex4;
            }
            catch (NetworkTransportException ex5)
            {
                ex = ex5;
            }
            finally
            {
                if (channel == null)
                {
                    if (negotiateStream != null)
                    {
                        negotiateStream.Dispose();
                    }
                    else if (stream != null)
                    {
                        stream.Dispose();
                    }
                    if (socket != null)
                    {
                        socket.Close();
                    }
                }
                else
                {
                    ReplayCrimsonEvents.NetworkConnectionSuccess.Log <string, IPEndPoint, IPEndPoint>(netPath.TargetNodeName, netPath.TargetEndPoint, channel.LocalEndpoint);
                }
            }
            ExTraceGlobals.TcpClientTracer.TraceError <Exception>(0L, "TryOpenChannel failed. Ex={0}", ex);
            ReplayCrimsonEvents.NetworkConnectionFailure.Log <string, IPEndPoint, IPEndPoint, string>(netPath.TargetNodeName, netPath.TargetEndPoint, netPath.SourceEndPoint, ex.ToString());
            if (ex is NetworkTransportException)
            {
                networkEx = (NetworkTransportException)ex;
            }
            else
            {
                networkEx = new NetworkCommunicationException(netPath.TargetNodeName, ex.Message, ex);
            }
            return(false);
        }
Ejemplo n.º 7
0
        private static void Connect(string username = null, string password = null, string host = "localhost", int addressIndex = 1, int port = 11000)
        {
            // Get IP address.
            var ipAddress = Dns.GetHostEntry(host).AddressList[addressIndex];
            // Get remote end point.
            var endPoint = new IPEndPoint(ipAddress, port);

            // Create a TCP/IP socket.
            _client = new TcpClient();
            // Connect the socket to the remote endpoint.
            _client.Connect(endPoint);
            Logging.Log($"Client successfully connected to {endPoint}.");
            // Keep connection alive if transfer isn't complete.
            _client.LingerState = new LingerOption(true, 0);
            // Get negotiation stream from client.
            var negotiateStream = new NegotiateStream(_client.GetStream(), false);
            // Pass the NegotiateStream as the AsyncState object
            // so that it is available to the callback delegate.


            IAsyncResult asyncResult;

            // If username/password provided, use as credentials.
            if (username != null && password != null)
            {
                asyncResult = negotiateStream.BeginAuthenticateAsClient(
                    new NetworkCredential("username", "password"),
                    host,
                    EndAuthenticateCallback,
                    negotiateStream);
            }
            else
            {
                // Use Identification ImpersonationLevel
                asyncResult = negotiateStream.BeginAuthenticateAsClient(
                    EndAuthenticateCallback,
                    negotiateStream
                    );
            }

            Logging.Log("Client attempting to authenticate.");
            // Await result.
            asyncResult.AsyncWaitHandle.WaitOne();

            // Send encoded test message to server.
            var message = Encoding.UTF8.GetBytes("Hello, it's me, the client!");

            asyncResult = negotiateStream.BeginWrite(
                message,
                0,
                message.Length,
                EndWriteCallback,
                negotiateStream);

            // Await result.
            asyncResult.AsyncWaitHandle.WaitOne();
            Logging.Log($"Successfully sent message containing {message.Length} bytes.");

            // Close the client connection.
            negotiateStream.Close();
            Logging.Log("Client closed.");
        }