Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            server = new TcpListener(IPAddress.Any, 9999);
            server.Start();
            while (true)
            {
                client = server.AcceptTcpClient();
                object my_lock = new object();

                ns = client.GetStream();

                Task.Factory.StartNew(() =>
                {
                    // change this to change session life time
                    Thread.Sleep(920000);
                    Console.Write(DateTime.Now);

                    lock (my_lock)
                    {
                        Console.Write(DateTime.Now);

                        client.Client.Close();
                    }
                });

                Task.Factory.StartNew(() =>
                {
                    AES aes = null;
                    RSACryptoServiceProvider rsa = null;
                    byte[] key = null;
                    while (true)
                    {
                        int messageType;
                        try
                        {
                            messageType = BitConverter.ToInt32(Receive(client, 4), 0);
                        }
                        catch (IOException e)
                        {
                            break;
                        }

                        lock (my_lock)
                        {
                            if (messageType == TCPConnection.GET_SESSION_KEY)
                            {
                                var lenBytes = BitConverter.ToInt32(Receive(client, 4), 0);
                                aes          = GenerateSessionKey();
                                SendEcryptedSessionKey(aes, rsa);
                            }

                            if (messageType == TCPConnection.PUBLIC_KEY)
                            {
                                var lenBytes = BitConverter.ToInt32(Receive(client, 4), 0);
                                rsa          = GetPublicKeyFromClient(client, lenBytes);
                            }

                            if (messageType == TCPConnection.LOGIN)
                            {
                                var lenBytes = BitConverter.ToInt32(Receive(client, 4), 0);
                                var msg      = Receive(client, lenBytes);

                                byte[] loginLenArray = new byte[4];
                                Array.Copy(msg, 0, loginLenArray, 0, 4);

                                var loginLen = BitConverter.ToInt32(loginLenArray, 0);

                                byte[] loginArray = new byte[loginLen];
                                Array.Copy(msg, 4, loginArray, 0, loginLen);
                                loginArray = AES.Decrypt(loginArray, aes.rijndaelManaged.Key, aes.rijndaelManaged.IV);
                                var login  = Encoding.Default.GetString(loginArray);

                                var passwordLen      = msg.Length - 4 - loginLen;
                                byte[] passwordArray = new byte[passwordLen];
                                Array.Copy(msg, 4 + loginLen, passwordArray, 0, passwordLen);
                                passwordArray = AES.Decrypt(passwordArray, aes.rijndaelManaged.Key, aes.rijndaelManaged.IV);
                                var password  = Encoding.Default.GetString(passwordArray);

                                if (checkUser(login, password))
                                {
                                    if (key == null)
                                    {
                                        key = KeyGeneration.GenerateRandomKey(20);
                                        Send(client, TCPConnection.QR_CODE_GENERATED, AES.Encrypt(key, aes.rijndaelManaged.Key, aes.rijndaelManaged.IV));
                                    }
                                    else
                                    {
                                        Send(client, TCPConnection.USE_OLD_KEY, null);
                                    }
                                }
                                else
                                {
                                    Send(client, TCPConnection.LOGIN_REJECTED, null);
                                }
                            }
                            else if (messageType == TCPConnection.FILENAME)
                            {
                                var lenBytes = BitConverter.ToInt32(Receive(client, 4), 0);
                                var msg      = Receive(client, lenBytes);
                                var filename = Encoding.UTF8.GetString(AES.Decrypt(msg, aes.rijndaelManaged.Key, aes.rijndaelManaged.IV));
                                if (File.Exists(filename))
                                {
                                    var text = File.ReadAllBytes(filename);
                                    text     = AES.Encrypt(text, aes.rijndaelManaged.Key, aes.rijndaelManaged.IV);
                                    Send(client, TCPConnection.TEXT, text);
                                }
                                else
                                {
                                    Send(client, TCPConnection.FILE_DO_NOT_EXISTS, null);
                                }
                            }
                            else if (messageType == TCPConnection.TEXT)
                            {
                                var lenBytes = BitConverter.ToInt32(Receive(client, 4), 0);
                                var msg      = Receive(client, lenBytes);

                                byte[] filenameLenArray = new byte[4];
                                Array.Copy(msg, 0, filenameLenArray, 0, 4);

                                var filenameLen = BitConverter.ToInt32(filenameLenArray, 0);

                                byte[] filenameArray = new byte[filenameLen];
                                Array.Copy(msg, 4, filenameArray, 0, filenameLen);
                                filenameArray = AES.Decrypt(filenameArray, aes.rijndaelManaged.Key, aes.rijndaelManaged.IV);
                                var filename  = Encoding.Default.GetString(filenameArray);

                                var textLen      = msg.Length - 4 - filenameLen;
                                byte[] textArray = new byte[textLen];
                                Array.Copy(msg, 4 + filenameLen, textArray, 0, textLen);

                                textArray = AES.Decrypt(textArray, aes.rijndaelManaged.Key, aes.rijndaelManaged.IV);

                                File.WriteAllBytes(filename, textArray);
                                Send(client, TCPConnection.FILE_SAVED, null);
                            }
                            else if (messageType == TCPConnection.QR_PASS_FROM_USER)
                            {
                                var lenBytes = BitConverter.ToInt32(Receive(client, 4), 0);
                                var msg      = Receive(client, lenBytes);

                                byte[] qrPassArray = new byte[lenBytes];
                                Array.Copy(msg, 0, qrPassArray, 0, lenBytes);
                                var decrypred = AES.Decrypt(qrPassArray, aes.rijndaelManaged.Key, aes.rijndaelManaged.IV);
                                var pass      = Encoding.Default.GetString(decrypred);

                                var totp = new Totp(key);

                                var isValidTotpCode = totp.VerifyTotp(DateTime.UtcNow, pass, out long timeStepMatched, new VerificationWindow(previous: 1, future: 1));
                                Send(client, TCPConnection.LOGIN_APPROVED, null);
                            }
                        }
                    }
                });
            }
        }
Ejemplo n.º 2
0
        private void btnMainAct_Click(object sender, EventArgs e)
        {
            if (_connectionState == false)
            {
                string ip      = ipTextBox.Text;
                string portStr = portTextBox.Text;

                ip = ipCheck(ip);
                int port = portCheck(portStr);

                if (ip == "" || port == -1)
                {
                    return;
                }

                _server = new AsyncServer(ip, port, AddLog, new Command[] {
                    new Command("hello", (state, parts) =>
                    {
                        return($"hello variant {parts[1]}");
                    }),
                    new Command("bye", true, (state, parts) =>
                    {
                        if (parts.Length == 1)
                        {
                            return("bye");
                        }
                        return($"bye variant {parts[1]}");
                    }),
                    new Command("encrypt", (state, parts) =>
                    {
                        string pass = "";
                        string text = "";
                        bool isFile = false;
                        for (int i = 1; i < parts.Length; ++i)
                        {
                            if (parts[i] == "-f")
                            {
                                isFile = true;
                            }
                            else if (parts[i] == "-p")
                            {
                                if (i + 1 == parts.Length)
                                {
                                    return("Wrong cmd: use encrypt [-p] <pass> <message>");
                                }
                                else
                                {
                                    pass = parts[i + 1];
                                    ++i;
                                }
                            }
                            else if (pass != "")
                            {
                                StringBuilder sb = new StringBuilder();
                                for (int j = i; j < parts.Length; ++j)
                                {
                                    sb.Append(parts[j]);
                                }
                                text = sb.ToString();
                                break;
                            }
                        }
                        if (pass != "" && text != "")
                        {
                            MD5Hash hasher = new MD5Hash();
                            pass           = hasher.GetHash(pass, true);
                            AES aes        = new AES();
                            text           = aes.Encrypt(text, pass, !isFile);
                            return(text);
                        }
                        else
                        {
                            return("Wrong cmd: use encrypt [-p] <pass> <message>");
                        }
                    }),
                    new Command("decrypt", (state, parts) =>
                    {
                        string pass = "";
                        string text = "";
                        bool isFile = false;
                        for (int i = 1; i < parts.Length; ++i)
                        {
                            if (parts[i] == "-f")
                            {
                                isFile = true;
                            }
                            else if (parts[i] == "-p")
                            {
                                if (i + 1 == parts.Length)
                                {
                                    return("Wrong cmd: use encrypt [-p] <pass> <message>");
                                }
                                else
                                {
                                    pass = parts[i + 1];
                                    ++i;
                                }
                            }
                            else if (pass != "")
                            {
                                StringBuilder sb = new StringBuilder();
                                for (int j = i; j < parts.Length; ++j)
                                {
                                    sb.Append(parts[j]);
                                }
                                text = sb.ToString();
                                break;
                            }
                        }
                        if (pass != "" && text != "")
                        {
                            MD5Hash hasher = new MD5Hash();
                            pass           = hasher.GetHash(pass, true);
                            AES aes        = new AES();
                            text           = aes.Decrypt(text, pass);
                            return(text);
                        }
                        else
                        {
                            return("Wrong cmd: use encrypt [-p] <pass> <message>");
                        }
                    }),
                    new Command("help", (state, parts) =>
                    {
                        string help = "hello <n>, bye <n>, [encrypt | decrypt] -p <pass> <text>";
                        return(help);
                    }),
                });

                _token = new CancellationTokenSource();
                CancellationToken ct = _token.Token;

                _task = new Task(() =>
                {
                    _server.Start(ct);
                }, ct);
                _task.Start();

                btnMainAct.Text  = "Деактивировать";
                _connectionState = true;
            }
            else
            {
                AsyncServer.AllDone.Set();
                _token.Cancel();
                Task.Factory.StartNew(() =>
                {
                    _server.Stop();
                });
                btnMainAct.Text  = "Активировать";
                _connectionState = false;
            }
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            server = new TcpListener(IPAddress.Any, 9999);
            server.Start();
            while (true)
            {
                client = server.AcceptTcpClient();
                object my_lock = new object();

                ns = client.GetStream();

                Task.Factory.StartNew(() =>
                {
                    Thread.Sleep(10000);
                    Console.Write(DateTime.Now);

                    lock (my_lock)
                    {
                        Console.Write(DateTime.Now);

                        client.Client.Close();
                    }
                });

                Task.Factory.StartNew(() =>
                {
                    AES aes = null;
                    RSACryptoServiceProvider rsa = null;
                    while (true)
                    {
                        int messageType;
                        try
                        {
                            messageType = BitConverter.ToInt32(Receive(client, 4), 0);
                        }
                        catch (IOException e)
                        {
                            break;
                        }

                        lock (my_lock)
                        {
                            if (messageType == TCPConnection.GET_SESSION_KEY)
                            {
                                var lenBytes = BitConverter.ToInt32(Receive(client, 4), 0);
                                aes          = GenerateSessionKey();
                                SendEcryptedSessionKey(aes, rsa);
                            }

                            if (messageType == TCPConnection.PUBLIC_KEY)
                            {
                                var lenBytes = BitConverter.ToInt32(Receive(client, 4), 0);
                                rsa          = GetPublicKeyFromClient(client, lenBytes);
                            }

                            if (messageType == TCPConnection.LOGIN)
                            {
                                var lenBytes = BitConverter.ToInt32(Receive(client, 4), 0);
                                var msg      = Receive(client, lenBytes);

                                byte[] loginLenArray = new byte[4];
                                Array.Copy(msg, 0, loginLenArray, 0, 4);

                                var loginLen = BitConverter.ToInt32(loginLenArray, 0);

                                byte[] loginArray = new byte[loginLen];
                                Array.Copy(msg, 4, loginArray, 0, loginLen);
                                loginArray = AES.Decrypt(loginArray, aes.rijndaelManaged.Key, aes.rijndaelManaged.IV);
                                var login  = Encoding.Default.GetString(loginArray);

                                var passwordLen      = msg.Length - 4 - loginLen;
                                byte[] passwordArray = new byte[passwordLen];
                                Array.Copy(msg, 4 + loginLen, passwordArray, 0, passwordLen);
                                passwordArray = AES.Decrypt(passwordArray, aes.rijndaelManaged.Key, aes.rijndaelManaged.IV);
                                var password  = Encoding.Default.GetString(passwordArray);

                                if (checkUser(login, password))
                                {
                                    Send(client, TCPConnection.LOGIN_APPROVED, null);
                                }
                                else
                                {
                                    Send(client, TCPConnection.LOGIN_REJECTED, null);
                                }
                            }
                            else if (messageType == TCPConnection.FILENAME)
                            {
                                var lenBytes = BitConverter.ToInt32(Receive(client, 4), 0);
                                var msg      = Receive(client, lenBytes);
                                var filename = Encoding.UTF8.GetString(AES.Decrypt(msg, aes.rijndaelManaged.Key, aes.rijndaelManaged.IV));
                                if (File.Exists(filename))
                                {
                                    var text = File.ReadAllBytes(filename);
                                    text     = AES.Encrypt(text, aes.rijndaelManaged.Key, aes.rijndaelManaged.IV);
                                    Send(client, TCPConnection.TEXT, text);
                                }
                                else
                                {
                                    Send(client, TCPConnection.FILE_DO_NOT_EXISTS, null);
                                }
                            }
                            else if (messageType == TCPConnection.TEXT)
                            {
                                var lenBytes = BitConverter.ToInt32(Receive(client, 4), 0);
                                var msg      = Receive(client, lenBytes);

                                byte[] filenameLenArray = new byte[4];
                                Array.Copy(msg, 0, filenameLenArray, 0, 4);

                                var filenameLen = BitConverter.ToInt32(filenameLenArray, 0);

                                byte[] filenameArray = new byte[filenameLen];
                                Array.Copy(msg, 4, filenameArray, 0, filenameLen);
                                filenameArray = AES.Decrypt(filenameArray, aes.rijndaelManaged.Key, aes.rijndaelManaged.IV);
                                var filename  = Encoding.Default.GetString(filenameArray);

                                var textLen      = msg.Length - 4 - filenameLen;
                                byte[] textArray = new byte[textLen];
                                Array.Copy(msg, 4 + filenameLen, textArray, 0, textLen);

                                textArray = AES.Decrypt(textArray, aes.rijndaelManaged.Key, aes.rijndaelManaged.IV);

                                File.WriteAllBytes(filename, textArray);
                                Send(client, TCPConnection.FILE_SAVED, null);
                            }
                        }
                    }
                });
            }
        }