예제 #1
0
        private void ProcessServerMessages(AsynchronousSocket socket)
        {
            // Get the encrypted byte array from the client
            byte[] encryptedMessage = SRP6.SubArray(
                socket.ReceiveBuffer, 0,
                socket.ReceiveBufferLength);

            // Start file receive
            if (isReceivingUpdate && !socket.IsReceivingFile)
            {
                receiveStream = new MemoryStream();
                socket.BeginFileReceive(receiveStream);
            }

            // FileReceive In-Progress
            if (socket.IsReceivingFile)
            {
                ProcessFileReceive(socket, encryptedMessage);
                return;
            }

            // Get the decrypted message
            byte[] message = srpClient.Decrypt(encryptedMessage);
            ProcessDecryptedServerMessages(socket, message);
        }
    static void Main(string[] args)
    {
        Console.WriteLine("This example explains how to use the SecureSocket in asynchronous mode. This class will fetch the index page of www.microsoft.com.");
        AsynchronousSocket asc = new AsynchronousSocket();

        asc.Start();
    }
예제 #3
0
 private void ProcessFileReceive(AsynchronousSocket socket, byte[] encryptedMessage)
 {
     socket.WriteFileReceive(encryptedMessage);
     BytesReceived += Socket.ReceiveBufferSize;
     if (ReceivedFileBlock != null)
     {
         ReceivedFileBlock.Invoke(this, new EventArgs());
     }
     if (socket.FileBytesReceived >= encryptedFileSize)
     {
         isReceivingUpdate = false;
         byte[]     encryptedData = receiveStream.ToArray();
         byte[]     decryptedData = srpClient.Decrypt(encryptedData);
         FileStream fileStream;
         if (!File.Exists(UpdateFileLocation))
         {
             fileStream = new FileStream(UpdateFileLocation, FileMode.CreateNew, FileAccess.Write);
         }
         else
         {
             fileStream = new FileStream(UpdateFileLocation, FileMode.Truncate, FileAccess.Write);
         }
         fileStream.Write(decryptedData, 0, decryptedData.Length);
         fileStream.Flush();
         fileStream.Close();
         socket.EndFileReceive();
         FileInfo fileInfo = new FileInfo(UpdateFileLocation);
         if (fileInfo.Length == UpdateFileSize)
         {
             wasUpdateCompleted = true;
         }
         socket.Disconnect();
     }
 }
예제 #4
0
        private void ServerGreetingReceived(AsynchronousSocket socket)
        {
            if (socket.ReceiveBufferLength != 80)
            {
                OnDebug("Server did not send a proper greeting");
                socket.Disconnect();
                return;
            }
            string salt      = SRP6.BytesToHex(SRP6.SubArray(socket.ReceiveBuffer, 0, 32));
            string pubKey    = SRP6.BytesToHex(SRP6.SubArray(socket.ReceiveBuffer, 32, 32));
            string scrambler = SRP6.BytesToHex(SRP6.SubArray(socket.ReceiveBuffer, 64, 16));

            // Setup the SessionKey
            srpClient = new SRP6(IdentityHash, Modulus, 0x07, salt);
            srpClient.SetSessionKey(pubKey, scrambler);
            OnDebug("Salt = " + salt);
            OnDebug("Server's PublicKey = " + pubKey);
            OnDebug("Scrambler = " + scrambler);

            step++;

            // Send my public key to the server
            OnDebug("Client->PublicKey");
            OnDebug("PublicKey = " + srpClient.GetPublicKey());
            byte[] reply = srpClient.PublicKey.ToUnsignedByteArray();
            socket.Send(reply, 0, reply.Length);
            OnDebug("SessionKey = " + srpClient.GetSessionKey());
        }
예제 #5
0
        private void ProcessClientMessage(AsynchronousSocket socket)
        {
            // Get the encrypted byte array from the client
            byte[] encryptedMessage = SRP6.SubArray(
                socket.ReceiveBuffer, 0,
                socket.ReceiveBufferLength);
            OnDebug("Received encrypted client message, length = " +
                    socket.ReceiveBufferLength);

            // Start file receive
            if (isReceivingCrashReport && !socket.IsReceivingFile)
            {
                OnDebug("Starting receive of crash report");
                receiveStream = new MemoryStream();
                socket.BeginFileReceive(receiveStream);
            }

            // FileReceive In-Progress
            if (socket.IsReceivingFile)
            {
                ProcessFileReceive(socket, encryptedMessage);
                return;
            }

            // Get the decrypted message
            byte[] message = srpServer.Decrypt(encryptedMessage);
            ProcessDecryptedClientMessages(socket, message);
        }
예제 #6
0
        private void InitializeSrpServer(AsynchronousSocket socket)
        {
            byte[] identityHash = SRP6.SubArray(socket.ReceiveBuffer, 0, socket.ReceiveBufferLength);
            OnDebug("IdentityHash = " + SRP6.BytesToHex(identityHash));

            // Verify that the server knows this identity before proceeding
            if (!OnAuthenticationRequest(socket, identityHash))
            {
                return;
            }

            // Server generates (and sends to client) public-key, scrambler, and salt
            srpServer = new SRP6(identityHash, Modulus, 0x07, 256, 128);
            socket.Step++;

            byte[] salt        = srpServer.Salt.ToUnsignedByteArray();
            byte[] pubKey      = srpServer.PublicKey.ToUnsignedByteArray();
            byte[] scrambler   = srpServer.Scrambler.ToUnsignedByteArray();
            byte[] replyPacket = SRP6.ConcatArray(salt, pubKey, scrambler);

            OnDebug("Server->Salt, PublicKey, and Scrambler");
            OnDebug("Salt = " + srpServer.GetSalt());
            OnDebug("PublicKey = " + srpServer.GetPublicKey());
            OnDebug("Scrambler = " + srpServer.GetScrambler());
            socket.Send(replyPacket, 0, replyPacket.Length);
        }
예제 #7
0
        protected bool OnAuthenticationRequest(AsynchronousSocket socket, byte[] identityHash)
        {
            bool allow = false;
            AuthenticationRequestEventHandler handler = AuthenticationRequest;

            if (handler != null)
            {
                AuthenticationRequestEventArgs args =
                    new AuthenticationRequestEventArgs(identityHash);
                foreach (AuthenticationRequestEventHandler tmp in
                         handler.GetInvocationList())
                {
                    tmp(this, args);
                    if (args.Allow)
                    {
                        allow = true;
                        break;
                    }
                }
            }

            if (!allow)
            {
                socket.Disconnect();
                return(false);
            }

            return(true);
        }
예제 #8
0
 public void Start()
 {
     if (!File.Exists(UpdateFileLocation))
     {
         OnDebug("Update file \"" + UpdateFileLocation + "\" doesn't exist!");
     }
     else if (!IsListening)
     {
         IsListening = true;
         if (listenerSocket == null)
         {
             listenerSocket                     = new AsynchronousSocket();
             listenerSocket.Debug              += new TextEventHandler(listenerSocket_Debug);
             listenerSocket.ClientConnected    += new EventHandler(listenerSocket_ClientConnected);
             listenerSocket.IsListeningChanged += new EventHandler(listenerSocket_IsListeningChanged);
         }
         listenerSocket.Bind(IPAddress.Any, ListeningPort);
         listenerSocket.StartListening(); // Blocks until StopListening
     }
     IsListening = false;
     if (ServerStopped != null) // Thread is about to exit
     {
         ServerStopped.Invoke(this, new EventArgs());
     }
 }
예제 #9
0
        public void Start()
        {
            InitializeDefaultProperties();
            isSendingCrashReport = false;
            isCheckingVersion    = false;
            Socket                   = new AsynchronousSocket();
            Socket.Connected        += new EventHandler(socket_Connected);
            Socket.ConnectFailed    += new EventHandler(socket_ConnectFailed);
            Socket.Disconnected     += new EventHandler(socket_Disconnected);
            Socket.SendCompleted    += new EventHandler(socket_SendCompleted);
            Socket.SendFailed       += new EventHandler(socket_SendFailed);
            Socket.ReceiveCompleted += new EventHandler(socket_ReceiveCompleted);
            int port = -1;

            try
            {
                port = Convert.ToInt32(LocalSetting.Values.String["UpdateServerPort"]);
            }
            catch
            {
                return;
            }
            Socket.Connect(
                LocalSetting.Values.String["UpdateServer"], port, 10000); // Blocks until disconnected
        }
예제 #10
0
        private static void clientSocket_Disconnected(object sender, EventArgs e)
        {
            AsynchronousSocket socket = sender as AsynchronousSocket;

            clients.Remove(socket);
            Console.WriteLine("Server: Client Disconnected (" + socket.TcpSocket.RemoteEndPoint.ToString() + ")");
        }
예제 #11
0
        private void ProcessCrashReport(AsynchronousSocket socket, byte[] message)
        {
            Exception ex = (Exception)message.DeserializeObject();

            OnDebug(ex.GetType().ToString() + Environment.NewLine +
                    ex.Message + Environment.NewLine + ex.StackTrace);
        }
예제 #12
0
        private void StartAuthenicationTimeOut(AsynchronousSocket socket)
        {
            ParameterizedThreadStart threadStart =
                new ParameterizedThreadStart(DisconnectTimeoutStart);
            Thread thread = new Thread(threadStart);

            thread.Start(socket);
        }
예제 #13
0
        private static void listenerSocket_ClientConnected(object sender, EventArgs e)
        {
            AsynchronousSocket socket = sender as AsynchronousSocket;

            clients.Add(socket);
            socket.Disconnected     += new EventHandler(clientSocket_Disconnected);
            socket.ReceiveCompleted += new EventHandler(clientSocket_ReceiveCompleted);
        }
예제 #14
0
        private void ProcessDecryptedClientMessages(AsynchronousSocket socket, byte[] message)
        {
            string command = ASCIIEncoding.ASCII.GetString(message, 0, (message.Length > 128 ? 128 : message.Length));

            OnDebug("Client Message \"" + SRP6.ArrayToString(message, 0, message.Length) + "\"");

            if (command.StartsWith("SUBMIT_CRASH")) // Client wants to send us a crash report
            {
                OnDebug("Beginning submitting Crash Report");
                string   strMessage = SRP6.ArrayToString(message, 13, message.Length - 13);
                string[] strTokens  = strMessage.Split(' ');
                try
                {
                    crashReportSize = Convert.ToInt32(strTokens[0]);
                }
                catch { }
                try
                {
                    crashReportEncryptedSize = Convert.ToInt32(strTokens[1]);
                }
                catch { }

                if ((crashReportSize > 0) && (crashReportEncryptedSize >= crashReportSize))
                {
                    isReceivingCrashReport = true;
                    // We know what to expect now, send "PROCEED" message.
                    srpServer.EncryptAndSend(socket, "PROCEED");
                }
                else
                {
                    OnDebug(
                        "Failed to get valid transfer information from the client");
                }
            }
            else if (command.StartsWith("VERSION"))
            {
                srpServer.EncryptAndSend(socket, TemposVersionString);
            }
            else if (command.StartsWith("SEND"))
            {
                socket.SendStream          = new FileStream(UpdateFileLocation, FileMode.Open, FileAccess.Read);
                socket.EncryptedSendStream = srpServer.Encrypt(socket.SendStream);
                srpServer.EncryptAndSend(socket, socket.SendStream.Length.ToString() + " " +
                                         socket.EncryptedSendStream.Length.ToString());
            }
            else if (command.StartsWith("CONTINUE"))
            {
                if (socket.EncryptedSendStream != null)
                {
                    socket.SendFile(socket.EncryptedSendStream);
                }
            }
            else
            {
                socket.Disconnect();
                OnDebug("Unhandled: " + command);
            }
        }
예제 #15
0
        void listenerSocket_IsListeningChanged(object sender, EventArgs e)
        {
            AsynchronousSocket socket = sender as AsynchronousSocket;

            if ((socket.IsListening) && (ServerStarted != null))
            {
                ServerStarted.Invoke(this, new EventArgs());
            }
        }
예제 #16
0
        void socket_ConnectFailed(object sender, EventArgs e)
        {
            AsynchronousSocket socket = sender as AsynchronousSocket;

            if (ConnectFailed != null)
            {
                ConnectFailed.Invoke(this, new EventArgs());
            }
        }
예제 #17
0
        private static void listenerSocket_IsListeningChanged(object sender, EventArgs e)
        {
            AsynchronousSocket socket = (sender as AsynchronousSocket);

            if (socket.IsListening && (StartedListening != null))
            {
                StartedListening.Invoke(socket, new EventArgs());
            }
        }
예제 #18
0
        static void Socket_Connected(object sender, EventArgs e)
        {
            AsynchronousSocket socket = sender as AsynchronousSocket;

            IsConnected = true;
            if (Connected != null)
            {
                Connected.Invoke(socket, new EventArgs());
            }
        }
예제 #19
0
        void clientSocket_Disconnected(object sender, EventArgs e)
        {
            AsynchronousSocket socket = sender as AsynchronousSocket;

            if (clients.Contains(socket))
            {
                clients.Remove(socket);
            }
            OnDebug("Client Disconnected (" + socket.TcpSocket.RemoteEndPoint.ToString() + ")");
        }
예제 #20
0
        private static void StartThread(object objectPort)
        {
            int port = (int)objectPort;

            //Console.WriteLine("Listening on port 41111");
            listenerSocket = new AsynchronousSocket();
            listenerSocket.IsListeningChanged +=
                new EventHandler(listenerSocket_IsListeningChanged);
            listenerSocket.ClientConnected +=
                new EventHandler(listenerSocket_ClientConnected);
            listenerSocket.Bind(IPAddress.Any, port);
            listenerSocket.StartListening(); // Blocks until StopListening
        }
예제 #21
0
        private static void StartThread(object objectPort)
        {
            int port = (int)objectPort;

            Socket                   = new AsynchronousSocket();
            Socket.Connected        += Socket_Connected;
            Socket.ConnectFailed    += Socket_ConnectFailed;
            Socket.Disconnected     += Socket_Disconnected;
            Socket.SendCompleted    += Socket_SendCompleted;
            Socket.SendFailed       += Socket_SendFailed;
            Socket.ReceiveCompleted += Socket_ReceiveCompleted;
            Socket.Connect(IPAddress.Loopback, port, 10000); // Blocks until disconnected
        }
예제 #22
0
        void socket_Connected(object sender, EventArgs e)
        {
            AsynchronousSocket socket = sender as AsynchronousSocket;

            if (Connected != null)
            {
                Connected.Invoke(this, new EventArgs());
            }

            // Send the server my identity hash
            socket.Send(IdentityHash, 0, IdentityHash.Length);
            OnDebug("Client->IdentityHash");
            OnDebug("IndetityHash = " + SRP6.BytesToHex(IdentityHash));
        }
예제 #23
0
        private void ServerReadyReceived(AsynchronousSocket socket)
        {
            byte[] message = SRP6.SubArray(
                socket.ReceiveBuffer, 0,
                socket.ReceiveBufferLength);
            string strMessage = SRP6.ArrayToString(message, 0, message.Length);

            // Server and client are now both ready for encrypted communications
            if (strMessage.Equals("READY"))
            {
                OnDebug("Received \"READY\" from server");
                step++;
                if (Authenticated != null)
                {
                    Authenticated.Invoke(this, new EventArgs());
                }

                if (crashReportOnly)
                {
                    // Request to send a crash report to the server
                    OnDebug("Telling server we want to upload a crash report");
                    try
                    {
                        byte[] serializedObject = CrashException.SerializeObject();
                        socket.SendStream          = new MemoryStream(serializedObject);
                        socket.EncryptedSendStream = srpClient.Encrypt(socket.SendStream);
                        srpClient.EncryptAndSend(socket, "SUBMIT_CRASH " +
                                                 socket.SendStream.Length + " " +
                                                 socket.EncryptedSendStream.Length);
                    }
                    catch (Exception ex)
                    {
                        OnDebug("Exception: " + ex.Message);
                    }
                }
                else
                {
                    // Request the current version
                    OnDebug("Sending version-check request to server");
                    isCheckingVersion = true;
                    srpClient.EncryptAndSend(socket, "VERSION");
                }
            }
            else
            {
                OnDebug("Authentication Failed");
                socket.Disconnect();
            }
        }
예제 #24
0
        /// <summary>
        /// 엘리베이터 통신 서버의 IP, PORT로 접속 클래스 생성하는 함수
        /// </summary>
        /// <param name="remoteIPAddress"></param>
        /// <param name="port"></param>
        public void StartAsyncSocket(string remoteIPAddress, int port)
        {
            try
            {
                this.targetIPAddress = remoteIPAddress;
                this.targetPort      = port;

                ClientSocket           = new AsynchronousSocket(remoteIPAddress, port);
                ClientSocket.Received += new ReceiveDelegate(OnReceived);
            }
            catch (Exception E)
            {
                Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} [Controller Controller Error] {E.Message}");
            }
        }
예제 #25
0
        private void DisconnectTimeoutStart(object obj)
        {
            AsynchronousSocket socket    = obj as AsynchronousSocket;
            DateTime           startTime = DateTime.Now;
            DateTime           endTime   = startTime + new TimeSpan(0, 0, 15);

            while (DateTime.Now < endTime)
            {
                Thread.Sleep(1000);
            }
            if (socket.Step < 2) // Not authenticated
            {
                socket.Disconnect();
                socket.Close();
            }
        }
예제 #26
0
        private void ProcessClientsPublicKey(AsynchronousSocket socket)
        {
            byte[] pubKey = SRP6.SubArray(socket.ReceiveBuffer, 0, socket.ReceiveBufferLength);

            string pubKeyString = SRP6.BytesToHex(pubKey);

            srpServer.SetSessionKey(pubKeyString);

            socket.SessionKey = srpServer.SessionKey.ToUnsignedByteArray();
            OnDebug("Client's PublicKey = " + pubKeyString);
            OnDebug("SessionKey = " + srpServer.GetSessionKey());
            socket.Step++;

            // From this point on, both client and server use encrypted communications
            OnDebug("Sending READY to client");
            socket.Send("READY");
        }
예제 #27
0
        void listenerSocket_ClientConnected(object sender, EventArgs e)
        {
            AsynchronousSocket socket   = sender as AsynchronousSocket;
            IPEndPoint         endPoint = socket.TcpSocket.RemoteEndPoint as IPEndPoint;

            OnDebug("Client Connected: (" + endPoint.Address + ")");
            if (!IsClientPermitted(socket))
            {
                socket.Disconnect();
                socket.Close();
                return;
            }
            StartAuthenicationTimeOut(socket);
            clients.Add(socket);
            socket.Disconnected     += new EventHandler(clientSocket_Disconnected);
            socket.ReceiveCompleted += new EventHandler(clientSocket_ReceiveCompleted);
        }
예제 #28
0
        void socket_Disconnected(object sender, EventArgs e)
        {
            AsynchronousSocket socket = sender as AsynchronousSocket;

            if (socket.IsReceivingFile)
            {
                socket.EndFileReceive();
            }
            if (Disconnected != null)
            {
                Disconnected.Invoke(this, new EventArgs());
            }
            if (wasUpdateCompleted && (UpdateReceived != null))
            {
                UpdateReceived.Invoke(this, new EventArgs());
            }
        }
예제 #29
0
        void clientSocket_ReceiveCompleted(object sender, EventArgs e)
        {
            AsynchronousSocket socket = sender as AsynchronousSocket;

            if (socket.Step == 0)
            {
                InitializeSrpServer(socket);
            }
            else if (socket.Step == 1)
            {
                ProcessClientsPublicKey(socket);
            }
            else if (socket.Step == 2)
            {
                ProcessClientMessage(socket);
            }
        }
예제 #30
0
        void socket_ReceiveCompleted(object sender, EventArgs e)
        {
            AsynchronousSocket socket = sender as AsynchronousSocket;

            if (step == 0)
            {
                ServerGreetingReceived(socket);
            }
            else if (step == 1)
            {
                ServerReadyReceived(socket);
            }
            else if (step == 2)
            {
                ProcessServerMessages(socket);
            }
        }
 static void Main(string[] args)
 {
     Console.WriteLine("This example explains how to use the SecureSocket in asynchronous mode. This class will fetch the index page of www.microsoft.com.");
     AsynchronousSocket asc = new AsynchronousSocket();
     asc.Start();
 }