/// <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 == null) additionalChallenge = new byte[] { }; if (additionalChallenge.Length > short.MaxValue) throw new ArgumentOutOfRangeException("additionalChallenge","Must be less than 32767 bytes"); using (var 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; } } }
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; } }
/// <summary> /// Callback method for asynchronous connect operation. /// </summary> private void ProcessConnect() { try { // Perform post-connect operations. m_connectionAttempts++; if (m_connectArgs.SocketError != SocketError.Success) throw new SocketException((int)m_connectArgs.SocketError); #if !MONO // Send current Windows credentials for authentication. if (m_integratedSecurity) { NetworkStream socketStream = null; NegotiateStream authenticationStream = null; try { socketStream = new NetworkStream(m_tcpClient.Provider); authenticationStream = new NegotiateStream(socketStream); authenticationStream.AuthenticateAsClient(); } finally { if (socketStream != null) socketStream.Dispose(); if (authenticationStream != null) authenticationStream.Dispose(); } } #endif // Set up send and receive args. using (SocketAsyncEventArgs sendArgs = m_sendArgs, receiveArgs = m_receiveArgs) { m_sendArgs = FastObjectFactory<SocketAsyncEventArgs>.CreateObjectFunction(); m_receiveArgs = FastObjectFactory<SocketAsyncEventArgs>.CreateObjectFunction(); } m_tcpClient.SetSendBuffer(SendBufferSize); m_sendArgs.SetBuffer(m_tcpClient.SendBuffer, 0, m_tcpClient.SendBufferSize); m_sendArgs.Completed += m_sendHandler; m_receiveArgs.Completed += ReceiveHandler; // Notify user of established connection. m_connectWaitHandle.Set(); OnConnectionEstablished(); // Set up send buffer and begin receiving. ReceivePayloadAsync(); } catch (SocketException ex) { OnConnectionException(ex); if (ex.SocketErrorCode == SocketError.ConnectionRefused && (MaxConnectionAttempts == -1 || m_connectionAttempts < MaxConnectionAttempts)) { // Server is unavailable, so keep retrying connection to the server. try { ConnectAsync(); } catch { TerminateConnection(); } } else { // For any other reason, clean-up as if the client was disconnected. TerminateConnection(); } } catch (Exception ex) { // This is highly unlikely, but we must handle this situation just-in-case. OnConnectionException(ex); TerminateConnection(); } }
/// <summary> /// Performs NTLM and Kerberos authentication via the Security Support /// Provider Interface (SSPI). /// </summary> /// <param name="tag">The tag identifier to use for performing the /// authentication commands.</param> /// <param name="username">The username with which to login in to the /// IMAP server.</param> /// <param name="password">The password with which to log in to the /// IMAP server.</param> /// <param name="useNtlm">True to authenticate using NTLM, otherwise /// GSSAPI (Kerberos) is used.</param> /// <returns>The response sent by the server.</returns> private string SspiAuthenticate(string tag, string username, string password, bool useNtlm) { string response = SendCommandGetResponse(tag + "AUTHENTICATE " + (useNtlm ? "NTLM" : "GSSAPI")); // If we get a BAD or NO response, the mechanism is not supported. if (response.StartsWith(tag + "BAD") || response.StartsWith(tag + "NO")) { throw new NotSupportedException("The requested authentication " + "mechanism is not supported by the server."); } using (FilterStream fs = new FilterStream(stream, true)) { using (NegotiateStream ns = new NegotiateStream(fs, true)) { try { ns.AuthenticateAsClient( new NetworkCredential(username, password), null, String.Empty, useNtlm ? ProtectionLevel.None : ProtectionLevel.EncryptAndSign, System.Security.Principal.TokenImpersonationLevel.Delegation); } catch { return String.Empty; } } } response = GetResponse(); // Swallow any continuation data we unexpectedly receive from the server. while (response.StartsWith("+ ")) response = SendCommandGetResponse(String.Empty); return response; }
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; }
public static int Main(string[] args) { if (args.Length < 7) { 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 options = args[5]; string exe = args[6]; 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.Skip(7).Select(MaybeQuote))); writer.WriteLine(launchId + "@" + Environment.MachineName); writer.WriteLine(options); 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; }
} // 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; }
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; }