/// <summary> /// Creates security stream and authenticates as client. /// </summary> /// <param name="source">The stream wrapped by the security stream.</param> /// <returns>Security stream of type NegotiateStream.</returns> public Stream CreateSecurityStreamAndAuthenticate(Stream source) { using (EneterTrace.Entering()) { NegotiateStream aNegotiateStream = new NegotiateStream(source, false); try { if (myNetworkCredential != null && !string.IsNullOrEmpty(myServicePrincipalName)) { aNegotiateStream.AuthenticateAsClient(myNetworkCredential, myServicePrincipalName); } else { aNegotiateStream.AuthenticateAsClient(); } } catch (Exception err) { EneterTrace.Error(TracedObject + "failed to authenticate the client.", err); throw; } return(aNegotiateStream); } }
public static async Task <PayloadData> AuthenticateAsync(ConnectionSettings cs, byte[] switchRequestPayloadData, ServerSession session, IOBehavior ioBehavior, CancellationToken cancellationToken) { using var innerStream = new NegotiateToMySqlConverterStream(session, ioBehavior, cancellationToken); using var negotiateStream = new NegotiateStream(innerStream); var targetName = cs.ServerSPN.Length == 0 ? GetServicePrincipalName(switchRequestPayloadData) : cs.ServerSPN; #if NETSTANDARD1_3 await negotiateStream.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, targetName).ConfigureAwait(false); #else if (ioBehavior == IOBehavior.Synchronous) { negotiateStream.AuthenticateAsClient(CredentialCache.DefaultNetworkCredentials, targetName); } else { await negotiateStream.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, targetName).ConfigureAwait(false); } #endif if (cs.ServerSPN.Length != 0 && !negotiateStream.IsMutuallyAuthenticated) { // Negotiate used NTLM fallback, server name cannot be verified. throw new AuthenticationException(String.Format( "GSSAPI : Unable to verify server principal name using authentication type {0}", negotiateStream.RemoteIdentity?.AuthenticationType)); } if (innerStream.MySQLProtocolPayload is PayloadData payload) { // return already pre-read OK packet. return(payload); } // Read final OK packet from server return(await session.ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false)); }
public bool Authenticate(NetworkCredential creds) { TcpClient client = new TcpClient( "localhost", this.port ); ThreadPool.QueueUserWorkItem( new WaitCallback(CreateServer) ); NegotiateStream nsClient = new NegotiateStream( client.GetStream(), true ); using (nsClient) { try { nsClient.AuthenticateAsClient( creds, creds.Domain + @"\" + creds.UserName, ProtectionLevel.None, TokenImpersonationLevel.Impersonation ); return(nsClient.IsAuthenticated); } catch (AuthenticationException) { return(false); } } }
public bool Authenticate(NetworkCredential creds) { listener = new TcpListener(IPAddress.Loopback, _port); listener.Start(); var client = new TcpClient("localhost", _port); ThreadPool.QueueUserWorkItem(new WaitCallback(CreateServer)); var nsClient = new NegotiateStream(client.GetStream(), true); using (nsClient) { try { nsClient.AuthenticateAsClient(creds, creds.Domain + "\\" + creds.UserName, ProtectionLevel.None, TokenImpersonationLevel.Impersonation); listener.Stop(); return(nsClient.IsAuthenticated); } catch (Exception ex) { //LogEvent.LogError(ex);//LogEvent does not exist listener.Stop(); return(false); } } }
/// <summary> /// Logs in to domain /// </summary> /// <param name="userName"></param> /// <param name="password"></param> /// <param name="domain"></param> /// <returns></returns> /// <example> /// WindowsIdentity wi = SSPIHelper.LogonUser(token.Username, token.Password, "fintrax"); /// if (wi == null) /// throw new SecurityException(); /// </example> public static WindowsIdentity LogonUser(string userName, string password, string domain) { TcpListener tcpListener = new TcpListener(IPAddress.Loopback, 0); tcpListener.Start(); WindowsIdentity id = null; tcpListener.BeginAcceptTcpClient(delegate(IAsyncResult asyncResult) { using (NegotiateStream serverSide = new NegotiateStream(tcpListener.EndAcceptTcpClient(asyncResult).GetStream())) { serverSide.AuthenticateAsServer( CredentialCache.DefaultNetworkCredentials, ProtectionLevel.None, TokenImpersonationLevel.Impersonation); id = (WindowsIdentity)serverSide.RemoteIdentity; } }, null); using (NegotiateStream clientSide = new NegotiateStream(new TcpClient(IPAddress.Loopback.ToString(), ((IPEndPoint)tcpListener.LocalEndpoint).Port).GetStream())) { clientSide.AuthenticateAsClient(new NetworkCredential(userName, password, domain), "", ProtectionLevel.None, TokenImpersonationLevel.Impersonation); } return(id); }
} // CreateSocketHandler #if !FEATURE_PAL private Stream CreateAuthenticatedStream(Stream netStream, String machinePortAndSid) { //Check for explicitly set userName, and authenticate using it NetworkCredential credentials = null; NegotiateStream negoClient = null; if (_securityUserName != null) { credentials = new NetworkCredential(_securityUserName, _securityPassword, _securityDomain); } //else use default Credentials else { credentials = (NetworkCredential)CredentialCache.DefaultCredentials; } try { negoClient = new NegotiateStream(netStream); negoClient.AuthenticateAsClient(credentials, _spn, _protectionLevel, _tokenImpersonationLevel); } catch (IOException e) { throw new RemotingException( String.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Tcp_AuthenticationFailed")), e); } return(negoClient); }
public void NegotiateStream_DisposedState_Throws() { (Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional(); using (var client = new NegotiateStream(stream1)) using (var server = new NegotiateStream(stream2)) { client.Dispose(); Assert.Throws <ObjectDisposedException>(() => client.AuthenticateAsClient()); } }
public void NegotiateStream_DisposedState_Throws() { var network = new VirtualNetwork(); using (var clientStream = new VirtualNetworkStream(network, isServer: false)) using (var serverStream = new VirtualNetworkStream(network, isServer: true)) using (var client = new NegotiateStream(clientStream)) using (var server = new NegotiateStream(serverStream)) { client.Dispose(); Assert.Throws <ObjectDisposedException>(() => client.AuthenticateAsClient()); } }
public void NegotiateStream_NullServicePrincipalName_Throws() { string servicePrincipalName = null; var network = new VirtualNetwork(); using (var clientStream = new VirtualNetworkStream(network, isServer: false)) using (var serverStream = new VirtualNetworkStream(network, isServer: true)) using (var client = new NegotiateStream(clientStream)) using (var server = new NegotiateStream(serverStream)) { AssertExtensions.Throws <ArgumentNullException>(nameof(servicePrincipalName), () => client.AuthenticateAsClient(CredentialCache.DefaultNetworkCredentials, servicePrincipalName)); } }
public bool AuthenticateAsClient(Stream stream) { using (var negotiateStream = new NegotiateStream(stream, true)) { try { negotiateStream.AuthenticateAsClient(m_credentials, string.Empty); } catch (Exception) { return(false); } return(true); } }
public static Client Create(IPEndPoint endpoint, IByteEncoder byteEncoder) { var tcpClient = new TcpClient(); tcpClient.Connect(endpoint.Address, endpoint.Port); var stream = new NegotiateStream(tcpClient.GetStream(), false); stream.AuthenticateAsClient(); var client = new Client(stream, byteEncoder); client.Start(); return(client); }
private void EndConnect(IAsyncResult result) { SocketAsyncState state = (SocketAsyncState)result.AsyncState; try { Socket.EndConnect(result); } catch { //出现异常,连接失败。 state.Completed = true; //判断是否为异步,异步则引发事件 if (state.IsAsync) { if (ConnectCompleted != null) { ConnectCompleted(this, new SocketEventArgs(this, SocketAsyncOperation.Connect)); } } return; } //连接成功。 //创建Socket网络流 Stream = new NetworkStream(Socket); if (IsUseAuthenticate) { NegotiateStream negotiate = new NegotiateStream(Stream); negotiate.AuthenticateAsClient(); while (!negotiate.IsMutuallyAuthenticated) { Thread.Sleep(10); } } //连接完成 state.Completed = true; if (state.IsAsync) { if (ConnectCompleted != null) { ConnectCompleted(this, new SocketEventArgs(this, SocketAsyncOperation.Connect)); } } //开始接收数据 Handler.BeginReceive(Stream, EndReceive, state); }
//<snippet4> public static void Main(String[] args) { //<snippet3> // Establish the remote endpoint for the socket. // For this example, use the local machine. IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); IPAddress ipAddress = ipHostInfo.AddressList[0]; // Client and server use port 11000. IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000); // Create a TCP/IP socket. TcpClient 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)); // Request authentication. NetworkStream clientStream = client.GetStream(); NegotiateStream authStream = new NegotiateStream(clientStream); // Request authentication for the client only (no mutual authentication). // Authenicate using the client's default credetials. // Permit the server to impersonate the client to access resources on the server only. // Request that data be transmitted using encryption and data signing. authStream.AuthenticateAsClient( (NetworkCredential)CredentialCache.DefaultCredentials, "", ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Impersonation); //</snippet3> DisplayAuthenticationProperties(authStream); DisplayStreamProperties(authStream); if (authStream.CanWrite) { // Encode the test data into a byte array. byte[] message = System.Text.Encoding.UTF8.GetBytes("Hello from the client."); authStream.Write(message, 0, message.Length); authStream.Flush(); Console.WriteLine("Sent {0} bytes.", message.Length); } // Close the client connection. authStream.Close(); Console.WriteLine("Client closed."); }
private static WindowsIdentity LogonUserTCPListen(string userName, string domain, string password) { // need a full duplex stream - loopback is easiest way to get that TcpListener tcpListener = new TcpListener(IPAddress.Loopback, 0); tcpListener.Start(); ManualResetEvent done = new ManualResetEvent(false); WindowsIdentity id = null; tcpListener.BeginAcceptTcpClient(delegate(IAsyncResult asyncResult) { try { using (NegotiateStream serverSide = new NegotiateStream( tcpListener.EndAcceptTcpClient(asyncResult).GetStream())) { serverSide.AuthenticateAsServer(CredentialCache.DefaultNetworkCredentials, ProtectionLevel.None, TokenImpersonationLevel.Impersonation); id = (WindowsIdentity)serverSide.RemoteIdentity; } } catch { id = null; } finally { done.Set(); } }, null); using (NegotiateStream clientSide = new NegotiateStream(new TcpClient("localhost", ((IPEndPoint)tcpListener.LocalEndpoint).Port).GetStream())) { try { clientSide.AuthenticateAsClient(new NetworkCredential(userName, password, domain), "", ProtectionLevel.None, TokenImpersonationLevel.Impersonation); } catch { id = null; }//When the authentication fails it throws an exception } tcpListener.Stop(); done.WaitOne();//Wait until we really have the id populated to continue return(id); }
private static Stream BindTcpStream() { TcpClient client = new TcpClient(); client.Connect(_uri.Host, _uri.Port); Stream ret = client.GetStream(); if (_secure) { NegotiateStream stm = new NegotiateStream(ret); NetworkCredential cred = _username == null ? CredentialCache.DefaultNetworkCredentials : new NetworkCredential(_username, _password, _domain); stm.AuthenticateAsClient(cred, String.Empty, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Impersonation); ret = stm; } return(ret); }
private static Stream BindStream() { Stream ret = null; if (_uri.Scheme == "tcp") { TcpClient client = new TcpClient(); client.Connect(_uri.Host, _uri.Port); ret = client.GetStream(); if (_secure) { NegotiateStream stm = new NegotiateStream(ret); NetworkCredential cred = _username == null ? CredentialCache.DefaultNetworkCredentials : new NetworkCredential(_username, _password, _domain); stm.AuthenticateAsClient(cred, String.Empty, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Impersonation); ret = stm; } } else if (_uri.Scheme == "ipc") { NamedPipeClientStream stm = new NamedPipeClientStream(".", _uri.Host, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation, HandleInheritability.None); stm.Connect(); ret = stm; } if (ret == null) { throw new InvalidOperationException("Could not bind stream"); } return(ret); }
#pragma warning disable 1998 async Task AuthenticateGSS(bool async, CancellationToken cancellationToken) #pragma warning restore 1998 { if (!IntegratedSecurity) { throw new NpgsqlException("SSPI authentication but IntegratedSecurity not enabled"); } using (var negotiateStream = new NegotiateStream(new GSSPasswordMessageStream(this), true)) { try { var targetName = $"{KerberosServiceName}/{Host}"; // AuthenticateAsClientAsync doesn't exist in .NET 4.5/4.5.1 (only introduced in 4.6) // Conversely, no sync in .NET Standard 1.3 :/ #if NET45 || NET451 negotiateStream.AuthenticateAsClient(CredentialCache.DefaultNetworkCredentials, targetName); #elif NETSTANDARD1_3 await negotiateStream.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, targetName); #else #error Missing platform #endif } catch (AuthenticationCompleteException) { return; } catch (IOException e) when(e.InnerException is AuthenticationCompleteException) { return; } catch (IOException e) when(e.InnerException is PostgresException) { throw e.InnerException; } } throw new NpgsqlException("NegotiateStream.AuthenticateAsClient completed unexpectedly without signaling success"); }
/// <summary> /// 异步连接完成 /// </summary> /// <param name="iar">异步结果</param> private void EndConnect(IAsyncResult iar) { SocketAsyncState state = (SocketAsyncState)iar.AsyncState; try { Socket.EndConnect(iar); } catch //出现异常 { state.Completed = true; //连接失败 if (state.IsAsync && ConnectCompleted != null) //判断是否异步,如果异步则触发异步完成事件 { ConnectCompleted(this, new SocketEventArgs(this, SocketAsyncOperation.Connect)); } return; } Stream = new NetworkStream(Socket); //连接成功,创建Socket网络流 if (IsUseAuthenticate) // { NegotiateStream negotiate = new NegotiateStream(Stream); negotiate.AuthenticateAsClient(); while (!negotiate.IsMutuallyAuthenticated) { System.Threading.Thread.Sleep(10); } } state.Completed = true; //连接完成 if (state.IsAsync && ConnectCompleted != null) { ConnectCompleted(this, new SocketEventArgs(this, SocketAsyncOperation.Connect)); } Hander.BeginReceive(Stream, EndReceive, state); //开始接收数据 }
#pragma warning disable CA1801 // Review unused parameters async Task AuthenticateGSS(bool async) { if (!IntegratedSecurity) { throw new NpgsqlException("SSPI authentication but IntegratedSecurity not enabled"); } using (var negotiateStream = new NegotiateStream(new GSSPasswordMessageStream(this), true)) { try { var targetName = $"{KerberosServiceName}/{Host}"; if (async) { negotiateStream.AuthenticateAsClient(CredentialCache.DefaultNetworkCredentials, targetName); } else { await negotiateStream.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, targetName); } } catch (AuthenticationCompleteException) { return; } catch (IOException e) when(e.InnerException is AuthenticationCompleteException) { return; } catch (IOException e) when(e.InnerException is PostgresException) { throw e.InnerException; } } throw new NpgsqlException("NegotiateStream.AuthenticateAsClient completed unexpectedly without signaling success"); }
private Stream CreateAuthenticatedStream(Stream netStream, string machinePortAndSid) { NetworkCredential defaultCredentials = null; NegotiateStream stream = null; if (this._securityUserName != null) { defaultCredentials = new NetworkCredential(this._securityUserName, this._securityPassword, this._securityDomain); } else { defaultCredentials = (NetworkCredential)CredentialCache.DefaultCredentials; } try { stream = new NegotiateStream(netStream); stream.AuthenticateAsClient(defaultCredentials, this._spn, this._protectionLevel, this._tokenImpersonationLevel); } catch (IOException exception) { throw new RemotingException(string.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Tcp_AuthenticationFailed"), new object[0]), exception); } return(stream); }
protected override Task AuthenticateAsClientAsync(NegotiateStream client, NetworkCredential credential, string targetName) => Task.Run(() => client.AuthenticateAsClient(credential, targetName));
static string ProcessMessage(string[] args) { // If no arguments supplied, default to show help. if (args.Count() == 0) { args = new string[] { "help" } } ; // Look to see what local / library commands there are. var command = ArgsCommand.Create(args); // Generally, the only commands processed locally by the // cli are 'api' and 'script'. The API command sets the // service end point, and the SCRIPT command runs a // script of commands. All other commands are processed // on the server if (args[0].Equals("api", StringComparison.OrdinalIgnoreCase)) { return(command.Execute()); } else if (args[0].Equals("script", StringComparison.OrdinalIgnoreCase)) { var script = command.Execute(); var lines = Regex.Split(script, "\r\n|\r|\n"); string output = ""; foreach (var line in lines) { var l = line.Trim(); if (l.Length > 0 && l.Substring(0, 1) != "#") { output += ProcessMessage(line.ParseArgs()) + Environment.NewLine; } } return(output); } else { string result = string.Empty; string host = (string)Properties.Settings.Default["host"]; int port = (int)Properties.Settings.Default["port"]; // must be processed on server. TcpClient client = new TcpClient(); //client.Client.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false); // Parse the host value. Can be host name or IPv4 address. IPAddress addr = null; if (!IPAddress.TryParse(host, out addr)) { // if failed, try dns lookup var hostEntry = Dns.GetHostEntry(host); foreach (var item in hostEntry.AddressList) { // Get the first IPv4 address. if (item.AddressFamily == AddressFamily.InterNetwork) { addr = item; break; } } if (addr == null) { throw new Exception("Invalid host."); } } IPEndPoint serverEndPoint = new IPEndPoint(addr, port); client.Connect(serverEndPoint); // Ensure the client does not close when there is // still data to be sent to the server. client.LingerState = (new LingerOption(true, 0)); // Request authentication NetworkStream clientStream = client.GetStream(); NegotiateStream authStream = new NegotiateStream(clientStream, false); // Pass the NegotiateStream as the AsyncState object // so that it is available to the callback delegate. authStream.AuthenticateAsClient(); // Convert client arguments to a byte array BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, args); byte[] buffer = new byte[ms.Length]; buffer = ms.ToArray(); // Send a message to the server. // Encode the test data into a byte array. authStream.Write(buffer, 0, buffer.Length); // get the response byte[] message = new byte[4096]; int bytesRead; while (true) { bytesRead = 0; try { //blocks until a client sends a message bytesRead = authStream.Read(message, 0, 4096); } catch { //a socket error has occured break; } if (bytesRead == 0) { //the client has disconnected from the server break; } ASCIIEncoding encoder = new ASCIIEncoding(); result += encoder.GetString(message, 0, bytesRead); if (bytesRead < 4096) { break; } } // Close the client connection. authStream.Close(); return(result); } } }
protected override Task AuthenticateAsClientAsync(NegotiateStream client, NetworkCredential credential, string targetName) => Task.Run(() => client.AuthenticateAsClient(credential, targetName, ProtectionLevel.None, TokenImpersonationLevel.Identification));
static void Connect( String server, String message, string servicePrincipalName) { NegotiateStream negotiateStream = null; try { // Create a TcpClient. // Note, for this client to work you need to have a TcpServer // connected to the same address as specified by the server, // port combination. Int32 port = 13000; TcpClient client = new TcpClient(server, port); // Translate the message into a byte array. // The encoding used is application specific. Byte[] data = System.Text.Encoding.ASCII.GetBytes(message); // Get a client stream for reading and writing. // Wrap it in a NegotiateStream. negotiateStream = new NegotiateStream(client.GetStream()); // This example uses the SPN which is required for Kerberos. // If you don't know your service principal name, you can do // NTLM authentication by commenting out the line below negotiateStream.AuthenticateAsClient( CredentialCache.DefaultNetworkCredentials, servicePrincipalName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Impersonation); // And then uncomment this line // authenticatedStream.AuthenticateAsClient(); if (negotiateStream.IsAuthenticated) { Console.WriteLine( "IsAuthenticated: {0}", negotiateStream.IsAuthenticated); Console.WriteLine( "IsMutuallyAuthenticated: {0}", negotiateStream.IsMutuallyAuthenticated); Console.WriteLine( "IsEncrypted: {0}", negotiateStream.IsEncrypted); Console.WriteLine( "IsSigned: {0}", negotiateStream.IsSigned); Console.WriteLine( "IsServer: {0}", negotiateStream.IsServer); } // Send the message to the connected TcpServer. negotiateStream.Write(data, 0, data.Length); Console.WriteLine("Sent: {0}", message); // Receive the TcpServer.response: // Buffer to store the response bytes. data = new Byte[256]; // String to store the response ASCII representation. String responseData = String.Empty; // Read the first batch of the TcpServer response bytes. Int32 bytes = negotiateStream.Read(data, 0, data.Length); responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes); Console.WriteLine("Received: {0}", responseData); } catch (AuthenticationException ex) { Console.WriteLine(ex.Message); } catch (SocketException ex) { Console.WriteLine(ex.Message); } catch (IOException ex) { Console.WriteLine(ex.Message); } finally { if (negotiateStream != null) { negotiateStream.Close(); } } Console.WriteLine("\n Press Enter to continue..."); Console.Read(); }
public void NegotiateStream_NullCredential_Throws() { NetworkCredential credential = null; var network = new VirtualNetwork(); using (var clientStream = new VirtualNetworkStream(network, isServer: false)) using (var serverStream = new VirtualNetworkStream(network, isServer: true)) using (var client = new NegotiateStream(clientStream)) using (var server = new NegotiateStream(serverStream)) { AssertExtensions.Throws <ArgumentNullException>(nameof(credential), () => client.AuthenticateAsClient(null, TargetName)); } }
/// <summary> /// Handles the connection process of clients /// </summary> private void HandleClientComm(object sender) { //This conntects the client //first we need an rescue timer _BootUpTimer = new Timer(new TimerCallback(_BootUpTimer_Elapsed), null, 100, 100); bool leaveInnerStreamOpen = false; try { // encryption if (_Mode == VaserOptions.ModeKerberos) { QueueSend = QueueSendKerberos; _AuthStream = new NegotiateStream(new NetworkStream(_SocketTCPClient), leaveInnerStreamOpen); } if (_Mode == VaserOptions.ModeSSL) { QueueSend = QueueSendSSL; _sslStream = new SslStream(new NetworkStream(_SocketTCPClient), leaveInnerStreamOpen); } if (_Mode == VaserOptions.ModeNotEncrypted) { QueueSend = QueueSendNotEncrypted; } if (_Mode == VaserOptions.ModeNamedPipeServerStream) { //QueueSend = QueueSendNotEncrypted; } if (_Mode == VaserOptions.ModeNamedPipeClientStream) { //QueueSend = QueueSendNotEncrypted; } if (IsServer) { //server if (_Mode == VaserOptions.ModeKerberos) { if (_vKerberosS._policy == null) { if (_vKerberosS._credential == null) { _AuthStream.AuthenticateAsServer(); } else { _AuthStream.AuthenticateAsServer(_vKerberosS._credential, _vKerberosS._requiredProtectionLevel, _vKerberosS._requiredImpersonationLevel); } } else { if (_vKerberosS._credential == null) { _AuthStream.AuthenticateAsServer(_vKerberosS._policy); } else { _AuthStream.AuthenticateAsServer(_vKerberosS._credential, _vKerberosS._policy, _vKerberosS._requiredProtectionLevel, _vKerberosS._requiredImpersonationLevel); } } link.IsAuthenticated = _AuthStream.IsAuthenticated; link.IsEncrypted = _AuthStream.IsEncrypted; link.IsMutuallyAuthenticated = _AuthStream.IsMutuallyAuthenticated; link.IsSigned = _AuthStream.IsSigned; link.IsServer = _AuthStream.IsServer; IIdentity id = _AuthStream.RemoteIdentity; link.UserName = id.Name; } if (_Mode == VaserOptions.ModeSSL) { if (_vSSLS._enabledSslProtocols == SslProtocols.None) { _sslStream.AuthenticateAsServer(_vSSLS._serverCertificate); } else { _sslStream.AuthenticateAsServer(_vSSLS._serverCertificate, _vSSLS._clientCertificateRequired, _vSSLS._enabledSslProtocols, _vSSLS._checkCertificateRevocation); } link.IsEncrypted = true; link.IsServer = true; } if (_Mode == VaserOptions.ModeNotEncrypted) { link.IsServer = true; } if (_Mode == VaserOptions.ModeNamedPipeServerStream) { link.IsServer = true; } link.vServer = server; BootupDone = true; server.AddNewLink(link); } else { //client if (_Mode == VaserOptions.ModeKerberos) { if (_vKerberosC._binding == null) { if (_vKerberosC._credential == null) { _AuthStream.AuthenticateAsClient(); } else { if (_vKerberosC._requiredProtectionLevel == ProtectionLevel.None && _vKerberosC._requiredImpersonationLevel == TokenImpersonationLevel.None) { _AuthStream.AuthenticateAsClient(_vKerberosC._credential, _vKerberosC._targetName); } else { _AuthStream.AuthenticateAsClient(_vKerberosC._credential, _vKerberosC._targetName, _vKerberosC._requiredProtectionLevel, _vKerberosC._requiredImpersonationLevel); } } } else { if (_vKerberosC._requiredProtectionLevel == ProtectionLevel.None && _vKerberosC._requiredImpersonationLevel == TokenImpersonationLevel.None) { _AuthStream.AuthenticateAsClient(_vKerberosC._credential, _vKerberosC._binding, _vKerberosC._targetName); } else { _AuthStream.AuthenticateAsClient(_vKerberosC._credential, _vKerberosC._binding, _vKerberosC._targetName, _vKerberosC._requiredProtectionLevel, _vKerberosC._requiredImpersonationLevel); } } link.IsAuthenticated = _AuthStream.IsAuthenticated; link.IsEncrypted = _AuthStream.IsEncrypted; link.IsMutuallyAuthenticated = _AuthStream.IsMutuallyAuthenticated; link.IsSigned = _AuthStream.IsSigned; link.IsServer = _AuthStream.IsServer; IIdentity id = _AuthStream.RemoteIdentity; } if (_Mode == VaserOptions.ModeSSL) { if (_vSSLC._clientCertificates == null) { _sslStream.AuthenticateAsClient(_vSSLC._targetHost); } else { _sslStream.AuthenticateAsClient(_vSSLC._targetHost, _vSSLC._clientCertificates, _vSSLC._enabledSslProtocols, _vSSLC._checkCertificateRevocation); } link.IsEncrypted = true; } if (_Mode == VaserOptions.ModeNamedPipeClientStream) { } //Thread.Sleep(50); BootupDone = true; _IsAccepted = true; if (_Mode == VaserOptions.ModeNotEncrypted) { ThreadPool.QueueUserWorkItem(ReceiveNotEncrypted); } if (_Mode == VaserOptions.ModeKerberos) { ThreadPool.QueueUserWorkItem(ReceiveKerberos); } if (_Mode == VaserOptions.ModeSSL) { ThreadPool.QueueUserWorkItem(ReceiveSSL); } } if (EnableHeartbeat) { HeartbeatTimer = new Timer(new TimerCallback(OnHeartbeatEvent), null, HeartbeatMilliseconds, HeartbeatMilliseconds); } } catch (AuthenticationException e) { Debug.WriteLine("Authentication failed. " + e.ToString()); _BootUpTimer.Dispose(); Stop(); return; } catch (Exception e) { Debug.WriteLine("Authentication failed. " + e.ToString()); _BootUpTimer.Dispose(); Stop(); return; } // encryption END _BootUpTimer.Dispose(); _BootUpTimer = null; }
/// <summary> /// Authenticates the client using the supplied stream. /// </summary> /// <param name="stream">the stream to use to authenticate the connection.</param> /// <param name="additionalChallenge">Additional data that much match between the client and server /// for the connection to succeed.</param> /// <returns> /// True if authentication succeded, false otherwise. /// </returns> public bool TryAuthenticateAsClient(Stream stream, byte[] additionalChallenge = null) { if (additionalChallenge is null) { additionalChallenge = new byte[] { } } ; if (additionalChallenge.Length > short.MaxValue) { throw new ArgumentOutOfRangeException("additionalChallenge", "Must be less than 32767 bytes"); } using (NegotiateStream negotiateStream = new NegotiateStream(stream, true)) { try { negotiateStream.AuthenticateAsClient(m_credentials, string.Empty, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification); } catch (Exception ex) { Log.Publish(MessageLevel.Info, "Security Login Failed", "Attempting an integrated security login failed", null, ex); return(false); } //Exchange the challenge data. //Since NegotiateStream is already a trusted stream //Simply writing the raw is as secure as creating a challenge response negotiateStream.Write((short)additionalChallenge.Length); if (additionalChallenge.Length > 0) { negotiateStream.Write(additionalChallenge); } negotiateStream.Flush(); int len = negotiateStream.ReadInt16(); if (len < 0) { Log.Publish(MessageLevel.Info, "Security Login Failed", "Attempting an integrated security login failed", "Challenge Length is invalid: " + len.ToString()); return(false); } byte[] remoteChallenge; if (len == 0) { remoteChallenge = new byte[0]; } else { remoteChallenge = negotiateStream.ReadBytes(len); } if (remoteChallenge.SecureEquals(additionalChallenge)) { return(true); } else { Log.Publish(MessageLevel.Info, "Security Login Failed", "Attempting an integrated security login failed", "Challenge did not match. Potential man in the middle attack."); return(false); } } } }
protected override Task AuthenticateAsClientAsync(NegotiateStream client, NetworkCredential credential, string targetName) => Task.Run(() => client.AuthenticateAsClient(credential, null, targetName));
public void NegotiateStream_NullServicePrincipalName_Throws() { (Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional(); using (var client = new NegotiateStream(stream1)) using (var server = new NegotiateStream(stream2)) { AssertExtensions.Throws <ArgumentNullException>("servicePrincipalName", () => client.AuthenticateAsClient(CredentialCache.DefaultNetworkCredentials, null)); } }
public void NegotiateStream_NullCredential_Throws() { (Stream stream1, Stream stream2) = ConnectedStreams.CreateBidirectional(); using (var client = new NegotiateStream(stream1)) using (var server = new NegotiateStream(stream2)) { AssertExtensions.Throws <ArgumentNullException>("credential", () => client.AuthenticateAsClient(null, TargetName)); } }
public static int Main(string[] args) { if (args.Length < 6) { Help(); return(-1); } int port; if (!Int32.TryParse(args[0], out port)) { Console.WriteLine("Got bad port number for arg 1"); return(-2); } Guid authGuid; if (!Guid.TryParse(args[1], out authGuid)) { Console.WriteLine("Got bad auth guid for arg 2"); return(-3); } var addrs = Dns.GetHostAddresses(args[2]); if (addrs.Length == 0) { Console.WriteLine("Cannot connect back to VisualStudio machine"); return(-4); } string curDir = args[3]; string projectDir = args[4]; string exe = args[5]; if (!File.Exists(exe)) { Console.WriteLine("{0} does not exist, please install the Python interpreter or update the project debug settings to point at the correct interpreter.", exe); } Guid launchId = Guid.NewGuid(); ManualResetEvent launchEvent = new ManualResetEvent(false); #pragma warning disable 618 // Handle is obsolete but we need it. string msVsMonArgs = "/__dbgautolaunch 0x" + launchEvent.Handle.ToString("X") + " 0x" + Process.GetCurrentProcess().Id.ToString("X") + " /name " + launchId.ToString() + " /timeout:600"; #pragma warning restore 618 Process msvsmonProc; try { var procStartInfo = new ProcessStartInfo( Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "msvsmon.exe"), msVsMonArgs); procStartInfo.UseShellExecute = false; msvsmonProc = Process.Start(procStartInfo); } catch (Exception e) { Console.WriteLine("Failed to start " + Path.Combine(Assembly.GetExecutingAssembly().Location, "msvsmon.exe")); Console.WriteLine(e); return(-7); } var processEvent = new ManualResetEvent(true); processEvent.SafeWaitHandle = new SafeWaitHandle(msvsmonProc.Handle, false); if (WaitHandle.WaitAny(new[] { launchEvent, processEvent }) != 0) { Console.WriteLine("Failed to initialize msvsmon"); return(-5); } try { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP)) { socket.Blocking = true; socket.Connect(new IPEndPoint(addrs[0], port)); var secureStream = new NegotiateStream(new NetworkStream(socket, false), true); secureStream.AuthenticateAsClient(); var writer = new StreamWriter(secureStream); writer.WriteLine(authGuid.ToString()); writer.WriteLine(exe); writer.WriteLine(curDir); writer.WriteLine(projectDir); writer.WriteLine(String.Join(" ", args, 6, args.Length - 6)); writer.WriteLine(launchId + "@" + Environment.MachineName); writer.Flush(); var reader = new StreamReader(secureStream); var procId = reader.ReadLine(); var processId = Int32.Parse(procId); if (processId != 0) { var debuggee = Process.GetProcessById(processId); debuggee.WaitForExit(); msvsmonProc.WaitForExit(); } else { int errorLen = Int32.Parse(reader.ReadLine()); char[] buffer = new char[errorLen]; int bytesRead = reader.Read(buffer, 0, buffer.Length); Console.WriteLine("failed to get process to debug: {0}", new string(buffer, 0, bytesRead)); return(-6); } } } catch (SocketException) { Console.WriteLine("Failed to connect back to Visual Studio process."); msvsmonProc.Kill(); return(-8); } GC.KeepAlive(launchEvent); GC.KeepAlive(msvsmonProc); return(0); }