Esempio n. 1
0
 private void btnStop_Click(object sender, EventArgs e)
 {
     SetButtonEnabled(btnStop, false);
     _Server.Shutdown();
     _Server.Dispose();
     _Server = null;
     SetButtonEnabled(btnStart, true);
 }
Esempio n. 2
0
            public static int Main(string[] args)
            {
                string certificate = @"c:\work\certificate.crt";

                //if (args == null || args.Length < 1)
                //{
                //    DisplayUsage();
                //}
                //certificate = args[0];
                SslTcpServer.RunServer(certificate);
                Console.ReadKey();
                return(0);
            }
Esempio n. 3
0
 private void btnStart_Click(object sender, EventArgs e)
 {
     btnStart.Enabled = false;
     if (_Server == null)
     {
         string pfx = txtPfx.Text;
         if (string.IsNullOrEmpty(System.IO.Path.GetDirectoryName(pfx)))
         {
             pfx = System.IO.Path.Combine(Environment.CurrentDirectory, "Web", pfx);
         }
         if (txtIP.Text.Equals("0.0.0.0"))
         {
             _Server = new SslTcpServer(IPAddress.Any, Convert.ToInt32(txtPort.Text), pfx, txtPfxPwd.Text);
         }
         else
         {
             _Server = new SslTcpServer(txtIP.Text, Convert.ToInt32(txtPort.Text), pfx, txtPfxPwd.Text);
         }
         _Server.IdleTime          = 0;
         _Server.ClientConnected  += new EventHandler <SslTcpEventArgs>(Server_OnClientConnected);
         _Server.ClientClosed     += new EventHandler <SslTcpEventArgs>(Server_OnClientClosed);
         _Server.DataReceived     += new EventHandler <SslTcpEventArgs>(Server_OnDataReceived);
         _Server.DataSended       += new EventHandler <SslTcpEventArgs>(Server_OnDataSended);
         _Server.AuthenticateFail += new EventHandler <SslTcpEventArgs>(Server_AuthenticateFail);
         _Server.Started          += new EventHandler(Server_OnStarted);
         _Server.Shutdowned       += new EventHandler(Server_OnShutdown);
         //_Server.CertificateStoreName = System.Security.Cryptography.X509Certificates.StoreName.TrustedPeople;
         _Server.CertificateValid = false;
     }
     try { _Server.Start(); }
     catch (NotImplementedException)
     {
         MessageBox.Show($"伺服器並未安裝此憑證 {txtPfx.Text},或該憑證不在 SslTcpServer.CertificateStoreName 指定的區域內。", "SslTcpServer", MessageBoxButtons.OK, MessageBoxIcon.Stop);
         _Server.Dispose();
         _Server          = null;
         btnStart.Enabled = true;
         return;
     }
     catch (NotSupportedException)
     {
         MessageBox.Show($"此憑證 {txtPfx.Text} 為非信任憑證,無法使用該憑證。\n請將 SslTcpServer.CertificateValid 設為 false,或將該憑證移至新任區域。", "SslTcpServer", MessageBoxButtons.OK, MessageBoxIcon.Stop);
         _Server.Dispose();
         _Server          = null;
         btnStart.Enabled = true;
         return;
     }
     btnStop.Enabled = true;
 }
        public static void Main(string[] args)
        {
            // If the program is called with the scrape only parameter, it should just scrape and then return
            if (args.Contains("--scrape") || args.Contains("-s"))
            {
                _log.Debug("Starting scraping");
                var scraper = new RankListScraper();
                scraper.UpdatePlayers();

                return;
            }

            // Scrape all players if the database is empty
            using (var db = new DatabaseEntities()) {
                if (!db.members.Any())
                {
                    var scraper = new RankListScraper();
                    scraper.UpdatePlayers();
                }
            }

            if (true) //args.Contains("--initdb") || args.Contains("-i")
            {
                var di = new DatabaseInitializer();
                di.Initialize();
                _log.Debug("Database initialized");
            }

            try
            {
                _log.Debug("Server started");
                SslTcpServer sslTcpServer = new SslTcpServer("cert.pfx");
                sslTcpServer.RunServer();
            }
            catch (Exception e)
            {
                if (e.InnerException != null)
                {
                    _log.Error(e.InnerException.Message);
                }
                _log.Error(e, e.ToString());
                throw;
            }

            NLog.LogManager.Shutdown();
        }
Esempio n. 5
0
        static void Main(string[] args)
        {
            //  port
            var port = 56111;

            if (port <= 0)
            {
                throw new ArgumentException("Please specify a valid port number.");
            }

            //  certificate and password
            var fileName    = "Server.pfx";
            var password    = "******";
            var certificate = new X509Certificate2(fileName, password);

            ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(OnRemoteCertificateValidationCallback);
            SslTcpServer.RunServer(port, certificate);
        }
Esempio n. 6
0
        static void Main(string[] args)
        {
            //  port
            var port = Convert.ToInt32(ConfigurationManager.AppSettings["port"]);

            if (port <= 0)
            {
                throw new ArgumentException("Please specify a valid port number.");
            }

            //  certificate and password
            var fileName    = ConfigurationManager.AppSettings["certificate"];
            var password    = ConfigurationManager.AppSettings["password"];
            var certificate = new X509Certificate2(fileName, password);

            ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(OnRemoteCertificateValidationCallback);
            SslTcpServer.RunServer(port, certificate);
        }
        static int Main(string[] args)
        {
            string certificate = null;
            string password    = null;
            bool   authClient  = false;
            bool   checkRevoke = false;

            for (var argc = 0; argc < args.Length; argc++)
            {
                if (args[argc] == "--cert")
                {
                    certificate = args[++argc];
                }

                if (args[argc] == "--password")
                {
                    password = args[++argc];
                }

                if (args[argc] == "--authclient")
                {
                    authClient = true;
                }

                if (args[argc] == "--checkrevoke")
                {
                    checkRevoke = true;
                }
            }

            try
            {
                var server = new SslTcpServer(certificate, password, authClient, checkRevoke);
                server.Run();
            }
            catch (CryptographicException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
            }
            return(0);
        }
Esempio n. 8
0
    private static void RunMain()
    {
        while (true)
        {
            // start listening
            while (true)
            {
                TcpListener listener  = SslTcpServer.RunServer();
                TcpClient   client    = listener.AcceptTcpClient();
                SslStream   sslStream = SslTcpServer.ProcessClient(client);

                // get nonce request from client
                String clientUsername = SslTcpServer.GetNonceRequest(sslStream);
                // verify nonce request
                if (clientUsername == null)
                {
                    SslTcpServer.AnswerNonceRequest(sslStream, "Error during nonce sending");
                    client.Close();
                    listener.Stop();
                    break;
                }
                // verify username
                if (!GetUserInfo.IsUserSystemMember(clientUsername))
                {
                    SslTcpServer.AnswerNonceRequest(sslStream, "Error during nonce sending");
                    client.Close();
                    listener.Stop();
                    break;
                }

                String clientNonce = Security.SendNonce(clientUsername);
                // answer nonce request
                if (clientNonce != null)
                {
                    SslTcpServer.AnswerNonceRequest(sslStream, "Nonce send");
                }

                // wait for command request
                String[] clientCommandRequest = SslTcpServer.GetCommandRequest(sslStream);
                // verify command request
                if (clientCommandRequest == null)
                {
                    SslTcpServer.AnswerCommandRequest(sslStream, "Error during command execution");
                    client.Close();
                    listener.Stop();
                    break;
                }

                String clientCommand         = clientCommandRequest[0];
                String clientUsernameCommand = clientCommandRequest[1];
                String clientNonceCommand    = clientCommandRequest[2];
                // verify username
                if (clientUsernameCommand != clientUsername || !GetUserInfo.IsUserSystemMember(clientUsernameCommand))
                {
                    SslTcpServer.AnswerCommandRequest(sslStream, "Unauthorized");
                    client.Close();
                    listener.Stop();
                    break;
                }
                // verify nonce
                if (clientNonceCommand != clientNonce)
                {
                    SslTcpServer.AnswerCommandRequest(sslStream, "Unauthorized");
                    client.Close();
                    listener.Stop();
                    break;
                }
                // verify access to command
                int retAuth = GetAuthorization.IsUserGranted(clientUsernameCommand, clientCommand);
                if (retAuth == 2)
                {
                    SslTcpServer.AnswerCommandRequest(sslStream, "Unauthorized");
                    client.Close();
                    listener.Stop();
                    break;
                }
                else if (retAuth == 1)
                {
                    SslTcpServer.AnswerCommandRequest(sslStream, "Password");
                    client.Close();
                    listener.Stop();
                    break;
                }


                // answer command request
                SslTcpServer.AnswerCommandRequest(sslStream, "OK");

                String commandResult = RunPowershell.RunSudoersCommand(clientCommand);

                // send command result
                SslTcpServer.SendCommandResult(sslStream, commandResult);
                client.Close();
                listener.Stop();
            }
        }
    }
Esempio n. 9
0
        /////////////////////////////////////////////////////
        //                                                 //
        // ServiceMain()                                   //
        //                                                 //
        /////////////////////////////////////////////////////
        //Description:  Entry point for the agent service process.
        //              This function is called automatically
        //              by the Windows SCM if we are running
        //              as a service, or it's called manually
        //              in AgentMain if not a service.
        //
        //              This function's prototype is dictated
        //              by the Win32Helper.LPSERVICE_MAIN_FUNCTIONW
        //              delegate definition.
        //
        //Returns:      true if successful
        /////////////////////////////////////////////////////
        internal unsafe void ServiceMain(uint dwNumServicesArgs, ref IntPtr lpServiceArgVectors)
        {
            AgentSettings   = new Dictionary <string, string>();
            AgentServiceLog = new StringBuilder();
            ScanResultsLog  = new StringBuilder();

            //=============================================
            //              INITIALIZATION
            //=============================================
            //
            //1.  Load settings from XML file extracted to local dir from MSI
            //
            if (!LoadAgentSettings(ref AgentSettings))
            {
                return;
            }

            //=============================================
            //      SET SERVICE CONTROL HANDLER FUNCTION
            //=============================================
            //the function ServiceMain() is called either by:
            //      (1) the agent binary itself inside CwAgent.exe in "Fire and Forget" mode
            //      (2) the CwAgent service has been started by the SCM
            //
            //in #1, we dont need to do anything special, but in #2, we have to do a few items
            //to make sure the SCM is "in the know":
            //      http://msdn.microsoft.com/en-us/library/ms685984(VS.85).aspx
            //
            //we will distinguish between case #1 and case #2 by the number of args
            if (dwNumServicesArgs > 0)
            {
                //get a pointer to our callback delegate.
                Win32Helper.LPHANDLER_FUNCTION lpHandlerProc = new Win32Helper.LPHANDLER_FUNCTION(ServiceHandler);

                //call RegisterServiceCtrlHandler() with this ptr.  all SCM notifications will be handled by it.
                IntPtr svcStatusHandle = Win32Helper.RegisterServiceCtrlHandler(AgentSettings["AgentServiceName"], lpHandlerProc);

                if (svcStatusHandle == IntPtr.Zero)
                {
                    return;
                }

                //!!!!!!!!!!!!!!!!!!!!!!!!!!!
                //!!     MUI IMPORTANTE    !!
                //!!!!!!!!!!!!!!!!!!!!!!!!!!!
                //we must save this handle for later updates to SCM
                globalHSvcHandle = svcStatusHandle;
                bool success = false;

                //set service to the START_PENDING state
                try
                {
                    ServiceHelper.SetServiceStatus(globalHSvcHandle, Win32Helper.SERVICE_START_PENDING, ref success);
                }
                catch (Exception) { }
            }

            //=============================================
            //              ESCALATE PRIVILEGES
            //=============================================
            //we must have debug privs to succeed.
            if (!AgentScanner.EnvironmentHelper.EscalatePrivileges())
            {
                //set our service to the STOPPED state
                try
                {
                    bool success = false;
                    ServiceHelper.StopService(AgentSettings["AgentServiceName"]);
                    ServiceHelper.SetServiceStatus(globalHSvcHandle, Win32Helper.SERVICE_STOPPED, ref success);
                }
                catch (Exception) { }

                return;
            }

            AgentServiceLog.AppendLine("*********************************************");
            AgentServiceLog.AppendLine("Codeword Agent v" + Assembly.GetExecutingAssembly().GetName().Version);
            AgentServiceLog.AppendLine("*********************************************");
            AgentServiceLog.AppendLine("Copyright © 2009, Sippy Development International");
            AgentServiceLog.AppendLine("Author:  sippy");
            AgentServiceLog.AppendLine("Please contact [email protected] with questions.");
            AgentServiceLog.AppendLine("*********************************************");
            AgentServiceLog.AppendLine("");
            AgentServiceLog.AppendLine("*********************************************");
            AgentServiceLog.AppendLine("                 INITIALIZE                  ");
            AgentServiceLog.AppendLine("*********************************************");
            AgentServiceLog.AppendLine("");
            AgentServiceLog.AppendLine("INITIALIZE:  Codeword starting on " + DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss"));
            AgentServiceLog.AppendLine("INITIALIZE:  Loading settings...");

            //=============================================
            //                  STARTUP
            //=============================================
            //
            //1.  determine our startup mode.
            //
            string[] possibleStartupModes = new string[] { "StartupFireAndForgetMode", "StartupRemoteControlMode", "StartupEnterpriseMode" };
            string   AgentStartupMode     = "";

            foreach (string s in possibleStartupModes)
            {
                if (AgentSettings.ContainsKey(s))
                {
                    if (AgentSettings[s] == "True")
                    {
                        AgentStartupMode = s;
                    }
                }
            }

            AgentServiceLog.AppendLine("INITIALIZE:  Agent startup mode set to " + AgentStartupMode);

            //
            //2.  start TCP server and listen for commands
            //
            if (AgentStartupMode == "StartupRemoteControlMode" || AgentStartupMode == "StartupEnterpriseMode")
            {
                SslTcpServer server = new SslTcpServer();
                string       certfile = "", encPwd = "", issuer = "";
                bool         authClientToServer = false;
                bool         authServerToClient = false;
                bool         strongAuth         = false;
                int          port = 1111;

                AgentServiceLog.AppendLine("STARTUP:  Initializing TCP/SSL server...");
                AgentServiceLog.AppendLine("STARTUP:  Using settings:");

                //------------------------------------
                //      LOAD TCP SERVER SETTINGS
                //------------------------------------
                //extract certificate from internal PKCS-12 file if provided
                if (AgentSettings.ContainsKey("AgentPFXFile"))
                {
                    if (AgentSettings["AgentPFXFile"] != "")
                    {
                        certfile = Path.GetFileName(AgentSettings["AgentPFXFile"]);
                    }
                }
                //get encrypted password for PFX keystore
                if (AgentSettings.ContainsKey("AgentPFXPassword"))
                {
                    if (AgentSettings["AgentPFXPassword"] != "")
                    {
                        encPwd = AgentSettings["AgentPFXPassword"];
                    }
                }
                //server port to listen on locally
                if (AgentSettings.ContainsKey("AgentListeningPort"))
                {
                    if (AgentSettings["AgentListeningPort"] != "")
                    {
                        port = int.Parse(AgentSettings["AgentListeningPort"]);
                    }
                }
                //authenticate client to server?
                if (AgentSettings.ContainsKey("AgentAuthenticateClientToServer"))
                {
                    if (AgentSettings["AgentAuthenticateClientToServer"] == "True")
                    {
                        authClientToServer = true;
                    }
                }
                //authenticate server to client?
                if (AgentSettings.ContainsKey("AgentAuthenticateServerToClient"))
                {
                    if (AgentSettings["AgentAuthenticateServerToClient"] == "True")
                    {
                        authServerToClient = true;
                    }
                }
                //required issuer of client certs
                if (AgentSettings.ContainsKey("AgentEnforceCertificateIssuer"))
                {
                    if (AgentSettings["AgentEnforceCertificateIssuer"] != "")
                    {
                        issuer = AgentSettings["AgentEnforceCertificateIssuer"];
                    }
                }
                //force strong authentication
                if (AgentSettings.ContainsKey("AgentEnforceStrongAuthentication"))
                {
                    if (AgentSettings["AgentEnforceStrongAuthentication"] == "True")
                    {
                        strongAuth = true;
                    }
                }

                AgentServiceLog.AppendLine("    PFX file name:  " + certfile);
                AgentServiceLog.AppendLine("    Listening on port:  " + port.ToString());
                AgentServiceLog.AppendLine("    Authenticate client to server:  " + authClientToServer.ToString());
                AgentServiceLog.AppendLine("    Authenticate server to client:  " + authServerToClient.ToString());
                AgentServiceLog.AppendLine("    Required issuer:  " + issuer);
                AgentServiceLog.AppendLine("    Strong authentication required:  " + strongAuth.ToString());

                //set server fields
                server.PFXFileName                 = certfile;
                server.EncryptedPassword           = encPwd;
                server.ServerPort                  = port;
                server.AuthenticateClientToServer  = authClientToServer;
                server.AuthenticateServerToClient  = authServerToClient;
                server.RequiredIssuer              = issuer;
                server.RequireStrongAuthentication = strongAuth;

                //insure the certificate file exists
                if (!File.Exists(certfile))
                {
                    AgentServiceLog.AppendLine("Error:  PFX certificate file '" + certfile + "' does not exist!");
                    return;
                }

                //------------------------------------
                //      RUN THE SCAN IF MODE IS
                //      StartupEnterpriseMode
                //------------------------------------
                if (AgentStartupMode == "StartupEnterpriseMode")
                {
                    //kick it off in a new thread so it doesnt stall the service
                    //and cause the SCM to barf.
                    Thread thr = new Thread(new ThreadStart(InitiateScanThread));
                    thr.Start();

                    while (!thr.IsAlive)
                    {
                    }
                    Thread.Sleep(1);

                    //we will wait for it to complete, b/c we've already set the status of
                    //our service to RUNNING, so SCM is satisfied.
                    //Ideally, we would also kick the RunServer() below in a new thread
                    //as well, and synchronize the three threads.
                    thr.Join();
                }

                //read the data back in from the file the child thread just wrote
                //ScanResultsLog = new StringBuilder(File.ReadAllText("xxzz1tmp1"));
                //promptly delete the file
                //File.Delete("xxzz1tmp1");

                //set our service to the RUNNING state
                try
                {
                    bool success = false;
                    ServiceHelper.SetServiceStatus(globalHSvcHandle, Win32Helper.SERVICE_RUNNING, ref success);
                }
                catch (Exception) { }

                //------------------------------------
                //      START THE TCP SERVER
                //------------------------------------
                //pass the results of an enterprise mode scan, if there is one
                //note:  ScanResultsLog is populated from the child thread above.
                try
                {
                    server.RunServer(ScanResultsLog);
                }
                catch (Exception ex)
                {
                    StreamWriter sw = new StreamWriter("SslServerError.txt", true);
                    sw.WriteLine(ex.Message);
                    sw.Close();
                }

                //set our service to the STOPPED state
                try
                {
                    bool success = false;
                    ServiceHelper.StopService(AgentSettings["AgentServiceName"]);
                    ServiceHelper.SetServiceStatus(globalHSvcHandle, Win32Helper.SERVICE_STOPPED, ref success);
                }
                catch (Exception) { }
            }
            //StartupFireAndForgetMode - do not start any server; just run the scan and report
            //note:  if we get here, we are not being called by SCM.
            else if (AgentStartupMode == "StartupFireAndForgetMode")
            {
                AgentScanner scanner = new AgentScanner();
                scanner.FireAndForget();
            }

            return;
        }
 static void Main(string[] args)
 {
     SslTcpServer a = new SslTcpServer();
 }