public static bool IsDeviceAlive(string strIP, int strPort) { try { // Uri uri = new Uri(strUrl); System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient(); var result = clientSocket.BeginConnect(strIP, strPort, null, null); var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(3)); if (!success) { return(false); } // we have connected clientSocket.EndConnect(result); return(true); } catch (Exception ex) { _logger.Info("CameraStatusService IsDeviceAlive() Exception" + ex.Message); string Message = "CameraStatusService IsDeviceAlive() Exception" + ex.Message; InsertBrokerOperationLog.AddProcessLog(Message); } return(false); }
public static bool CheckPort(string ip, int port, int timeout) { using (System.Net.Sockets.TcpClient tcp = new System.Net.Sockets.TcpClient()) { IAsyncResult ar = tcp.BeginConnect(ip, port, null, null); System.Threading.WaitHandle wh = ar.AsyncWaitHandle; try { if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(timeout), false)) { tcp.Close(); throw new TimeoutException(); } tcp.EndConnect(ar); return true; } catch (Exception) { return false; } finally { wh.Close(); } } }
private bool CheckConnection() { bool success = false; string ip = ConfigurationManager.AppSettings["bankServerIP"]; int port = Convert.ToInt32(ConfigurationManager.AppSettings["bankServerPort"]); int timeout = Convert.ToInt32(ConfigurationManager.AppSettings["connectionTimeout"]); try { using (System.Net.Sockets.TcpClient tcp = new System.Net.Sockets.TcpClient()) { IAsyncResult ar = tcp.BeginConnect(ip, port, null, null); System.Threading.WaitHandle wh = ar.AsyncWaitHandle; try { if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(timeout), false)) { tcp.Close(); throw new TimeoutException(); } success = tcp.Connected; tcp.EndConnect(ar); } finally { wh.Close(); } } } catch (Exception e) { log.Error(e); } return(success); }
bool TryConnect(string hostname, System.Net.IPAddress ip, int port, int connectTimeout) { //EB.Debug.Log("Try connect {0}:{1}", ip, port); if (_client.Client.AddressFamily != ip.AddressFamily) { _client.Close(); _client = new System.Net.Sockets.TcpClient(ip.AddressFamily); _client.NoDelay = true; } var async = _client.BeginConnect(ip, port, null, null); if (!async.AsyncWaitHandle.WaitOne(System.TimeSpan.FromMilliseconds(connectTimeout))) { _error = NetworkFailure.TimedOut; return(false); } if (!async.IsCompleted) { _error = NetworkFailure.TimedOut; return(false); } _client.EndConnect(async); if (_client.Connected == false) { EB.Debug.LogError("Failed to connect to {0}:{1}", ip, port); _error = NetworkFailure.CannotConnectToHost; return(false); } OnConnected(); _net = _client.GetStream(); _stream = _net; if (_secure) { //EB.Debug.Log("Doing ssl connect {0}:{1}", ip, port); _ssl = new System.Net.Security.SslStream(_stream, true, RemoteCertificateValidationCallback, null); try { _ssl.AuthenticateAsClient(hostname); } catch (System.Exception e) { EB.Debug.LogError("Failed to authenticate: " + e); return(false); } _stream = _ssl; } //EB.Debug.Log("Connected to {0}:{1}", ip, port); LastTime = System.DateTime.Now; return(true); }
public void ProcessDevTimeSync() { try { System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient(); var result = clientSocket.BeginConnect(strIp, 554, null, null); var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5)); clientSocket.EndConnect(result); if (success) { try { CPPlusDahuaSDK.NET_DEVICEINFO deviceInfo; int error = 0; CPPlusDahuaSDK.CLIENT_SetConnectTime(10000, 1); ushort DVRPortNumber = (ushort)nPort;//37777 m_lUserID = CPPlusDahuaSDK.CLIENT_Login(strIp, DVRPortNumber, strUserName, strPassword, out deviceInfo, out error); if (m_lUserID == -1) { //Login failed //Log message... strIp Camera login failed StopInterface(); return; } CPPlusDahuaSDK.LPNET_TIME CurTime; CurTime.dwYear = uint.Parse(DateTime.Now.Year.ToString()); CurTime.dwMonth = uint.Parse(DateTime.Now.Month.ToString()); CurTime.dwDay = uint.Parse(DateTime.Now.Day.ToString()); CurTime.dwHour = uint.Parse(DateTime.Now.Hour.ToString()); CurTime.dwMinute = uint.Parse(DateTime.Now.Minute.ToString()); CurTime.dwSecond = uint.Parse(DateTime.Now.Second.ToString()); var IsTimeSet = CPPlusDahuaSDK.CLIENT_SetupDeviceTime(m_lUserID, CurTime); if (IsTimeSet == true) { //Log message......Successfuly Time Sync strIp Camera } else { //Log message......Failed Time Sync strIp Camera } StopInterface(); } catch (Exception ex) { } } else { //Log message... strIp Camera is offline } } catch (Exception ex) { } }
static bool IsPortOpen(string host, int port, TimeSpan timeout) { try { using (var client = new System.Net.Sockets.TcpClient()) { var result = client.BeginConnect(host, port, null, null); var success = result.AsyncWaitHandle.WaitOne(timeout); client.EndConnect(result); return(success); } } catch { return(false); } }
/// <summary> /// Connect with timeout /// </summary> /// <param name="connectTimeout">connect timeout. In millisecond</param> public void Connect(int connectTimeout) { if (connectTimeout > 30000) { Connect(); return; } if (_Client == null) { _Client = new System.Net.Sockets.TcpClient(); } IPEndPoint serverEndPoint = new IPEndPoint(RemoteAddress, Port); IAsyncResult ar = _Client.BeginConnect(serverEndPoint.Address, serverEndPoint.Port, null, null); System.Threading.WaitHandle wh = ar.AsyncWaitHandle; try { if (!ar.AsyncWaitHandle.WaitOne(connectTimeout, false)) { _Client.Close(); throw new TimeoutException(string.Format("Try to connect {0} timeout", serverEndPoint)); } _Client.EndConnect(ar); } finally { wh.Close(); } _ClientStream = _Client.GetStream(); if (_Async) { _Thread = new Thread(AsyncMessageRecv); _Thread.IsBackground = true; _Thread.Start(); } }
/// <summary> /// Callback for client's connection /// </summary> private void ClientConnected(IAsyncResult ar) { try { System.Net.Sockets.TcpClient client = (System.Net.Sockets.TcpClient)ar.AsyncState; client.EndConnect(ar); // Request Acknowledgement this.StartWriteSync(new NetPacket(0, this._id, NetPacket.PacketType.Command, new TcpCommand(TcpCommand.Command.Acknowledge, UnicodeEncoding.UTF8.GetBytes(this._name)).Serialize())); this.BeginReadFromClient(); } catch (Exception e) { if (this.OnError != null) { this.OnError(this._tcpClient, new NetEventArgs(e)); } } }
public static bool PingSync(string ip, ushort port) { try { using (var a = new System.Net.Sockets.TcpClient()) { var b = a.BeginConnect(ip, port, null, null); for (var n = 0; n < 10; n++) { if (b.AsyncWaitHandle.WaitOne(75)) { a.EndConnect(b); return(true); } } return(false); } } catch { return(false); } }
private bool HostIsAvailableViaTcp(double timeout) { bool returnValue = false; using (System.Net.Sockets.TcpClient tcp = new System.Net.Sockets.TcpClient()) { System.IAsyncResult asyncResult = tcp.BeginConnect(SyslogServerHostname, SyslogServerPort, null, null); System.Threading.WaitHandle waitHandle = asyncResult.AsyncWaitHandle; try { if (!asyncResult.AsyncWaitHandle.WaitOne(System.TimeSpan.FromSeconds(timeout), false)) { tcp.Close(); returnValue = false; //throw new TimeoutException(); } if (tcp.Client != null) { if (tcp.Client.Connected) { tcp.EndConnect(asyncResult); returnValue = true; } else { returnValue = false; } } } finally { waitHandle.Close(); } } return(returnValue); }
public static async Task <bool> Ping(string ip, short port) { try { //Console.WriteLine("Pinging Port"); using (var a = new System.Net.Sockets.TcpClient()) { var b = a.BeginConnect(ip, port, null, null); await Task.Delay(1000); //Console.WriteLine("Timeout Over"); if (b.AsyncWaitHandle.WaitOne(10)) { a.EndConnect(b); //Console.WriteLine("Ended connect"); return(true); } //Console.WriteLine("Connected Fine"); return(false); } } catch { return(false); } }
private static void ConnectCallback(IAsyncResult asyncresult) { try { IsConnectionSuccessful = false; System.Net.Sockets.TcpClient tcpclient = asyncresult.AsyncState as System.Net.Sockets.TcpClient; if (tcpclient.Client != null) { tcpclient.EndConnect(asyncresult); IsConnectionSuccessful = true; } } catch (Exception ex) { IsConnectionSuccessful = false; socketexception = ex; } finally { TimeoutObject.Set(); } }
bool TryConnect(string hostname, System.Net.IPAddress ip, int port, int connectTimeout) { //EB.Debug.Log("Try connect {0}:{1}", ip, port); if (_client.Client.AddressFamily != ip.AddressFamily) { _client.Close(); _client = new System.Net.Sockets.TcpClient(ip.AddressFamily); _client.NoDelay = true; } var async = _client.BeginConnect(ip, port, null, null); if (!async.AsyncWaitHandle.WaitOne(System.TimeSpan.FromMilliseconds(connectTimeout))) { _error = NetworkFailure.TimedOut; return(false); } if (!async.IsCompleted) { _error = NetworkFailure.TimedOut; return(false); } _client.EndConnect(async); if (_client.Connected == false) { EB.Debug.LogError("Failed to connect to {0}:{1}", ip, port); _error = NetworkFailure.CannotConnectToHost; return(false); } _net = _client.GetStream(); _stream = _net; OnConnected(); if (_secure) { //EB.Debug.Log("Doing ssl connect {0}:{1}", ip, port); try { var random = new System.Random(); var bytes = new byte[20]; random.NextBytes(bytes); #if BCWP71 var secureRandom = new SecureRandom(bytes); #else var secureRandom = SecureRandom.GetInstance("SHA1PRNG", false); #endif secureRandom.SetSeed(bytes); _auth = new MyTlsAuthentication(); _tlsClient = new MyTlsClient(_auth); #if BCWP71 _handler = new TlsProtocolHandler(_net, secureRandom); #else _handler = new TlsClientProtocol(_net, secureRandom); #endif _handler.Connect(_tlsClient); _stream = _handler.Stream; if (_stream == null) { EB.Debug.LogError("stream is null"); _error = NetworkFailure.SecureConnectionFailed; return(false); } } catch (System.Exception ex) { EB.Debug.LogError("ssl connect failed {0}\n{1}", ex.Message, ex.StackTrace); _error = NetworkFailure.SecureConnectionFailed; return(false); } } //EB.Debug.Log("Connected to {0}:{1}", ip, port); LastTime = System.DateTime.Now; return(true); }
static void Main(string[] args) { string info = @" .d8888b. 888 888b 888 d8b d8b d88P Y88b 888 8888b 888 Y8P Y8P 888 888 888 88888b 888 888 888d888 .d88b. .d88888 888Y88b 888 888 88888b. 8888 8888b. 888 888P"" d8P Y8b d88"" 888 888 Y88b888 888 888 ""88b ""888 ""88b 888 888 888 88888888 888 888 888 Y88888 888 888 888 888.d888888 Y88b d88P 888 Y8b.Y88b 888 888 Y8888 888 888 888 888 888 888 ""Y8888P"" 888 ""Y8888 ""Y88888 888 Y888 888 888 888 888 ""Y888888 888 d88P 888P"" Chris King(@raikiasec) For help: CredNinja.exe -h This script is designed to identify if credentials are valid, invalid, or local admin valid credentials within a domain network and will also check for local admin. It works by attempting to mount C$ on each server using different credentials. Author: Chris King (@raikiasec) Massive Contributor: Alyssa Rahman (@ramen0x3f) Example: > CredNinja.exe --creds test\raikia:hunter2,test\user:password --hosts 10.10.10.10,10.20.20.20,10.30.30.30 --users --os Links: https://github.com/Raikia/CredNinja https://twitter.com/raikiasec https://twitter.com/ramen0x3f"; //Print help if (args.Length == 0) { Console.WriteLine(info); return; } Options opt; //Parse out args try { opt = CliParser.Parse <Options>(args); } catch (clipr.Core.ParserExit e) { return; } catch (ParseException e) { Console.WriteLine(info); Console.WriteLine(e.Message); return; } //Convert hosts and creds to arrays string[] hosts = opt.hosts.Split(','); string[] creds = opt.creds.Split(','); //Reduce Hosts list to only live hosts if told to scan if (opt.scan) { List <string> alive_hosts = new List <string>(); //Because it's bad practice modifying an array midloop System.Net.Sockets.TcpClient tcp = new System.Net.Sockets.TcpClient(); tcp.SendTimeout = opt.scan_timeout * 1000; tcp.ReceiveTimeout = opt.scan_timeout * 1000; foreach (var h in hosts) { var result = tcp.BeginConnect(h, 445, null, null); //Wait for a connection var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(opt.scan_timeout)); //Add if successful if (success) { alive_hosts.Add(h); } tcp.EndConnect(result); } hosts = alive_hosts.ToArray(); } //Do the thing try { Exec(hosts, creds, opt.delim, opt.users, opt.users_time, opt.valid, opt.invalid, opt.os, opt.output, opt.threads, opt.delay); } catch (Exception e) { Console.WriteLine("An error occurred: '{0}'", e); } }
public void ProcessDevTimeSync() { try { //Log time // System.Windows.Application.Current.Dispatcher.BeginInvoke((Action)(() => //{ // _MainWindow.LogText.AppendText("\n\n" + DateTime.Now.ToString() + " Process Hik Cam for Ip " + strIp + " Started ..." + _nCount.ToString()); //})); // OperationLogs.AddLog("Process Hik Cam for Ip " + strIp + " Started ... " + _nCo.ToString() + " " + _nCount.ToString()); try { _ConnectionTimeOut = Int32.Parse(ConnectTimeOut);// *1000; } catch (Exception ex) { InsertBrokerOperationLog.AddProcessLog("Error _ConnectionTimeOut ..." + ex.Message); } System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient(); var result = clientSocket.BeginConnect(strIp, 554, null, null); var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(_ConnectionTimeOut));//TimeSpan.FromSeconds(50)); if (success) { try { _hikContime = uint.Parse(HikConnectTime) * 1000; } catch (Exception ex) { } CHCNetSDK.NET_DVR_SetConnectTime(_hikContime, 1);//10000, 1); Int32 DVRPortNumber = nPort; m_lUserID = CHCNetSDK.NET_DVR_Login_V30(strIp, DVRPortNumber, strUserName, strPassword, ref m_struDeviceInfo); if (m_lUserID == -1) { //Login failed //Log message... strIp Camera login failed InsertBrokerOperationLog.AddProcessLog(strIp + " :Login failed ..."); StopInterface(); return; } else { InsertBrokerOperationLog.AddProcessLog(strIp + " :Login Success ..."); } CHCNetSDK.NET_DVR_TIME CurTime; CurTime.dwYear = uint.Parse(DateTime.Now.Year.ToString()); CurTime.dwMonth = uint.Parse(DateTime.Now.Month.ToString()); CurTime.dwDay = uint.Parse(DateTime.Now.Day.ToString()); CurTime.dwHour = uint.Parse(DateTime.Now.Hour.ToString()); CurTime.dwMinute = uint.Parse(DateTime.Now.Minute.ToString()); CurTime.dwSecond = uint.Parse(DateTime.Now.Second.ToString()); IntPtr pnt = Marshal.AllocHGlobal(Marshal.SizeOf(CurTime)); try { // Copy the struct to unmanaged memory. Marshal.StructureToPtr(CurTime, pnt, false); uint _size = (uint)Marshal.SizeOf(CurTime); var IsTimeSet = CHCNetSDK.NET_DVR_SetDVRConfig(m_lUserID, CHCNetSDK.NET_DVR_SET_TIMECFG, 0, pnt, _size); if (IsTimeSet == true) { //Log message......Successfuly Time Sync strIp Camera try { using (var ctx = new CentralDBEntities()) { var tblDeviceSync = ctx.tblTimeSyncinfo.FirstOrDefault(x => x.DeviceID == _deviceID); tblDeviceSync.DateTimeSyncStatus = 1; ctx.Entry(tblDeviceSync).State = System.Data.EntityState.Modified; ctx.SaveChanges(); } } catch (Exception ex) { } InsertBrokerOperationLog.AddProcessLog("Successfuly Time Sync: " + strIp + " Camera ..."); } else { //Log message......Failed Time Sync strIp Camera . try { using (var ctx = new CentralDBEntities()) { var tblDeviceSync = ctx.tblTimeSyncinfo.FirstOrDefault(x => x.DeviceID == _deviceID); tblDeviceSync.DateTimeSyncStatus = 0; ctx.Entry(tblDeviceSync).State = System.Data.EntityState.Modified; ctx.SaveChanges(); } } catch (Exception ex) { } InsertBrokerOperationLog.AddProcessLog("Failed Time Sync: " + strIp + " Camera ..."); } StopInterface(); clientSocket.EndConnect(result); } catch (Exception ex) { InsertBrokerOperationLog.AddProcessLog("Error ProcessDevTimeSync NET_DVR_SetDVRConfig ..." + ex.Message); } finally { // Free the unmanaged memory. Marshal.FreeHGlobal(pnt); } } else { InsertBrokerOperationLog.AddProcessLog(strIp + " :Camera is offline"); //Log message... strIp Camera is offline } } catch (Exception ex) { InsertBrokerOperationLog.AddProcessLog("Error ProcessDevTimeSync ..." + ex.Message); MessageBox.Show("Error ProcessDevTimeSync ..." + ex.Message); } //System.Windows.Application.Current.Dispatcher.BeginInvoke((Action)(() => //{ // _MainWindow.LogText.AppendText("\n\n" + DateTime.Now.ToString() + " Process Hik Cam for Ip " + strIp + " End ..." + _nCount.ToString()); //})); // OperationLogs.AddLog("Process Hik Cam for Ip " + strIp + " End ... " + _nCo.ToString() + " " + _nCount.ToString()); }
/// <summary> /// The main entry point for the application. /// </summary> internal static void Main() { /* * * System.Security.Principal.WindowsIdentity currentIdentity = System.Security.Principal.WindowsIdentity.GetCurrent(TokenAccessLevels.Read); * //Console.WriteLine(currentIdentity.User.Value); * System.Security.Principal.SecurityIdentifier userSid = new SecurityIdentifier("S-1-5-21-149779583-363096731-646672791-379352"); * Console.WriteLine((userSid == currentIdentity.User)); * * System.Collections.Specialized.StringCollection existingRights = GetRights(currentIdentity); * Console.WriteLine("Rights for {0}", currentIdentity.Name); * Console.WriteLine(new string('=', 30)); * foreach (string rightName in existingRights) * { * Console.WriteLine(rightName); * } * * SetRight(currentIdentity, "SeDebugPrivilege"); * SetRight(currentIdentity, "SeBackupPrivilege"); * * System.Collections.Specialized.StringCollection newRights = GetRights(currentIdentity); * Console.WriteLine(); * Console.WriteLine("Rights for {0}", currentIdentity.Name); * Console.WriteLine(new string('=', 30)); * foreach (string rightName in newRights) * { * Console.WriteLine(rightName); * } * * RemoveRight(currentIdentity, "SeBackupPrivilege"); * * newRights = GetRights(currentIdentity); * Console.WriteLine(); * Console.WriteLine("Rights for {0}", currentIdentity.Name); * Console.WriteLine(new string('=', 30)); * foreach (string rightName in newRights) * { * Console.WriteLine(rightName); * } */ string SyslogServerHostname = "patrick-syslog"; //int SyslogServerPort = 514; int SyslogServerPort = 1468; Console.WriteLine(DateTime.Now); /* * System.Net.Sockets.TcpClient tcpClient = new System.Net.Sockets.TcpClient(); * tcpClient.SendTimeout = 5; * try * { * tcpClient.Connect(SyslogServerHostname, SyslogServerPort); * } * catch (Exception) { }; */ Console.WriteLine(DateTime.Now); /* * System.Net.Sockets.UdpClient udpClient = new System.Net.Sockets.UdpClient(); * udpClient.Connect(SyslogServerHostname, SyslogServerPort); * * byte[] testBytes = System.Text.UnicodeEncoding.Unicode.GetBytes("TEST"); * * int returnValue = udpClient.Send(testBytes, testBytes.Length); */ using (System.Net.Sockets.TcpClient tcp = new System.Net.Sockets.TcpClient()) { IAsyncResult asyncResult = tcp.BeginConnect(SyslogServerHostname, SyslogServerPort, null, null); System.Threading.WaitHandle waitHandle = asyncResult.AsyncWaitHandle; try { if (!asyncResult.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2), false)) { tcp.Close(); Console.WriteLine("Failed to connect."); //throw new TimeoutException(); } if (tcp.Client != null) { if (tcp.Client.Connected) { tcp.EndConnect(asyncResult); } else { Console.WriteLine("TCP client is not connected."); } } } finally { waitHandle.Close(); } } int q = 0; /* * for (int x = 0; x < 2; x++) * { * syslog.WriteInformationEvent(string.Format("This is informational event {0:N0}.", x), System.Diagnostics.Process.GetCurrentProcess().Id, string.Empty); * } */ /* * Console.WriteLine(new string('=', 30)); * Console.WriteLine(new string('=', 30)); * Console.WriteLine(LocalAdministratorGroup.LocalAdminGroupName); * Console.WriteLine(new string('=', 30)); * Console.WriteLine(new string('=', 30)); * * Console.WriteLine(System.Globalization.CultureInfo.CurrentCulture.Name); * Console.WriteLine(System.Globalization.CultureInfo.CurrentUICulture.Name); * * Console.WriteLine(new string('=', 30)); * * Console.WriteLine(System.Threading.Thread.CurrentThread.CurrentCulture.Name); * Console.WriteLine(System.Threading.Thread.CurrentThread.CurrentUICulture.Name); * * System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture; * * Console.WriteLine(new string('=', 30)); * * Console.WriteLine(System.Threading.Thread.CurrentThread.CurrentCulture.Name); * Console.WriteLine(System.Threading.Thread.CurrentThread.CurrentUICulture.Name); */ /* * } * * FreeSid(sid); */ /* * //Now that we have the SID an the policy, * //we can add rights to the account. * * //initialize an unicode-string for the privilege name * LSA_UNICODE_STRING[] userRights = new LSA_UNICODE_STRING[1]; * userRights[0] = new LSA_UNICODE_STRING(); * userRights[0].Buffer = Marshal.StringToHGlobalUni(privilegeName); * userRights[0].Length = (UInt16)(privilegeName.Length * UnicodeEncoding.CharSize); * userRights[0].MaximumLength = (UInt16)((privilegeName.Length + 1) * UnicodeEncoding.CharSize); * * //add the right to the account * long res = LsaAddAccountRights(policyHandle, sid, userRights, 1); * winErrorCode = LsaNtStatusToWinError(res); * if (winErrorCode != 0) * { * Console.WriteLine("LsaAddAccountRights failed: " + winErrorCode); * } */ /* * * int WinWorldSid = 1; * int POLICY_ALL_ACCESS = 0xF0FFF; * int SECURITY_MAX_SID_SIZE = 68; * string SE_DENY_REMOTE_INTERACTIVE_LOGON_NAME = "SeDenyRemoteInteractiveLogonRight"; * uint NT_STATUS_OBJECT_NAME_NOT_FOUND = 0xC0000034; * uint STATUS_NO_MORE_ENTRIES = 0x8000001A; * * // add the Deny permission * Public Sub DenyTS(ByVal PC As String) * Dim ret, Access, sidsize As Integer * Dim SystemName, DenyTSRights As LSA_UNICODE_STRING * Dim objectAttributes As LSA_OBJECT_ATTRIBUTES * Dim policyHandle, EveryoneSID As IntPtr * * // build a well-known SID for "Everyone" * sidsize = SECURITY_MAX_SID_SIZE * EveryoneSID = Marshal.AllocHGlobal(sidsize) * If CreateWellKnownSid(WinWorldSid, IntPtr.Zero, EveryoneSID, sidsize) = False Then * ret = Marshal.GetLastWin32Error() * Throw New Win32Exception(ret) * End If * * // setup the parameters for the LsaOpenPolicy API * objectAttributes.Length = Marshal.SizeOf(objectAttributes) * SystemName.Length = PC.Length * UnicodeEncoding.CharSize * SystemName.MaximumLength = (PC.Length + 1) * UnicodeEncoding.CharSize * SystemName.Buffer = Marshal.StringToHGlobalUni(PC) * Access = POLICY_ALL_ACCESS * * // open a policy handle on the remote PC * ret = LsaOpenPolicy(SystemName, objectAttributes, Access, policyHandle) * If ret<> 0 Then * Throw New Win32Exception(LsaNtStatusToWinError(ret)) * End If * * // clean up * Marshal.FreeHGlobal(SystemName.Buffer) * * // Setup the input parameters for the LsaRemoveAccountRights API * DenyTSRights.Length = SE_DENY_REMOTE_INTERACTIVE_LOGON_NAME.Length * UnicodeEncoding.CharSize * DenyTSRights.MaximumLength = (SE_DENY_REMOTE_INTERACTIVE_LOGON_NAME.Length + 1) * UnicodeEncoding.CharSize * DenyTSRights.Buffer = Marshal.StringToHGlobalUni(SE_DENY_REMOTE_INTERACTIVE_LOGON_NAME) * * // Do it! * ret = LsaAddAccountRights(policyHandle, EveryoneSID, DenyTSRights, 1) * If ret<> 0 Then * Marshal.FreeHGlobal(DenyTSRights.Buffer) * LsaClose(policyHandle) * Throw New Win32Exception(LsaNtStatusToWinError(ret)) * End If * * // clean up * Marshal.FreeHGlobal(DenyTSRights.Buffer) * LsaClose(policyHandle) * End Sub * */ /* * for (int i = 0; i < 10; i++) * { */ /* * Console.WriteLine(DateTime.Now.ToLongTimeString()); * Console.WriteLine("Desktops Detected"); * Console.WriteLine("================="); * * System.Text.StringBuilder desktopNameString = new System.Text.StringBuilder("Desktops: "); * string[] desktopNames = Desktop.GetDesktops(); * for (int j = 0; j < desktopNames.Length; j++) * { * desktopNameString.Append(desktopNames[j]); * if (j < (desktopNames.Length - 1)) * { * desktopNameString.Append(", "); * } * } * Console.WriteLine(desktopNameString.ToString()); */ /* * foreach (string desktop in Desktop.GetDesktops()) * { * Console.WriteLine(desktop); * } */ /* * Console.WriteLine(); */ /* * Console.WriteLine("Window Stations Detected"); * Console.WriteLine("========================"); * System.Text.StringBuilder winStaNameString = new System.Text.StringBuilder("Window Stations: "); * string[] winStaNames = Desktop.GetWindowStations(); * for (int j = 0; j < winStaNames.Length; j++) * { * winStaNameString.Append(winStaNames[j]); * if (j < (winStaNames.Length - 1)) * { * winStaNameString.Append(", "); * } * } * Console.WriteLine(winStaNameString.ToString()); */ /* * foreach (string winsta in Desktop.GetWindowStations()) * { * Console.WriteLine(winsta); * } */ /* * long DESKTOP_ENUMERATE = 0x0040L; * long DESKTOP_READOBJECTS = 0x0001L; * long DESKTOP_WRITEOBJECTS = 0x0080L; * long READ_CONTROL = 0x00020000L; * * long MAXIMUM_ALLOWED = 0x02000000L; */ /* * //Console.WriteLine(LsaLogonSessions.LogonSessions.WTSGetActiveConsoleSessionId()); * //Console.WriteLine(LsaLogonSessions.LogonSessions.GetDesktopWindow()); * IntPtr inputDesktopPtr = LsaLogonSessions.LogonSessions.OpenInputDesktop(0, false, 256); * * if (inputDesktopPtr == IntPtr.Zero) * { * Console.ForegroundColor = ConsoleColor.Red; * Console.WriteLine("input desktop pointer was zero!"); * Console.ResetColor(); * * inputDesktopPtr = LsaLogonSessions.LogonSessions.OpenDesktop("Winlogon", 0, false, (uint)MAXIMUM_ALLOWED); * if (inputDesktopPtr == IntPtr.Zero) * { * Console.ForegroundColor = ConsoleColor.Red; * Console.WriteLine("input desktop pointer is still zero!"); * Console.ResetColor(); * } * LsaLogonSessions.LogonSessions.SetThreadDesktop(inputDesktopPtr); * int lastError = Marshal.GetLastWin32Error(); * Console.WriteLine("SetThreadDesktop Error: {0:N0}", lastError); * LsaLogonSessions.LogonSessions.CloseDesktop(inputDesktopPtr); * lastError = Marshal.GetLastWin32Error(); * Console.WriteLine("CloseDesktop Error: {0:N0}", lastError); */ /* * inputDesktopPtr = LsaLogonSessions.LogonSessions.OpenDesktop("Default", 0, false, 256); * if (inputDesktopPtr == IntPtr.Zero) * { * Console.ForegroundColor = ConsoleColor.Red; * Console.WriteLine("input desktop pointer is still zero!"); * Console.ResetColor(); * } * else * { * Console.ForegroundColor = ConsoleColor.Green; * Console.WriteLine("i was able to open the default desktop!"); * Console.ResetColor(); * bool switchResult = LsaLogonSessions.LogonSessions.SwitchDesktop(inputDesktopPtr); * Console.WriteLine("able to switch desktops: {0}", switchResult); * } */ /* * } * * //int lastError = Marshal.GetLastWin32Error(); * Console.WriteLine(inputDesktopPtr); * //Console.WriteLine("Last Error: {0:N0}", lastError); * LsaLogonSessions.LogonSessions.CloseDesktop(inputDesktopPtr); */ /* * System.Threading.Thread.Sleep(2000); * Console.WriteLine(); * } */ /*currentIdentity.Dispose();*/ #if DEBUG Console.Write("\n\nPress <ENTER> to close this program."); Console.ReadLine(); #endif }