Пример #1
0
        public void Open()
        {
            SN.RequestInfo rei = new SN.RequestInfo();

            byte[] data = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(rei));


            this.resp_inf = Newtonsoft.Json.JsonConvert.DeserializeObject <ResponseInfo>(System.Text.Encoding.UTF8.GetString(this.AuthSend(data)));

            while (true)
            {
                string key, iv;

                key = CreateRandomString(16);
                iv  = CreateRandomString(16);

                aes_key = Encoding.ASCII.GetBytes(key);
                aes_iv  = Encoding.ASCII.GetBytes(iv);

                RSA rsa = new RSA(0, false, true);
                rsa.SetPublicKey(resp_inf.rsa_p_key);
                string[] cipher   = rsa.Encrypt(Encoding.UTF8.GetBytes(key + " " + iv), sha256(CreateRandomString(32)));
                string   rsa_text = "";
                for (int i = 0; i < cipher.Length; i++)
                {
                    rsa_text += cipher[i] + " ";
                }
                rsa_text = Convert.ToBase64String(Encoding.ASCII.GetBytes(rsa_text));
                rei      = new RequestInfo();
                rei.sid  = this.resp_inf.sid;
                rei.tkn  = rsa_text;
                data     = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(rei));


                if (System.Text.Encoding.UTF8.GetString(AuthSend(data)) == "ok.")
                {
                    //       System.Windows.Forms.MessageBox.Show("Connected");
                    break;
                }
            }
            con = true;
        }
Пример #2
0
        public void Start()
        {
            keyloader = new RSAKeyLoader("keys1024.txt");
            TcpListener listener = new TcpListener(IPAddress.Parse(_ip), _port);

            listener.Start();
            Console.WriteLine("Listener initialized and listening to " + _ip + ":" + _port);
            // System.Windows.Forms.MessageBox.Show("Listener initialized and listening to " + _ip + ":" + _port);
            new Thread(() =>
            {
                RemoveExpiredSessions();
            }).Start();
            while (true)
            {
                TcpClient client = listener.AcceptTcpClient();

                new Thread((cl) =>
                {
                    try
                    {
                        NetworkStream networkStream = ((TcpClient)cl).GetStream();
                        byte[] bytesFrom            = new byte[(int)((TcpClient)cl).ReceiveBufferSize];
                        MemoryStream requestStrm    = new MemoryStream();
                        int bytesread     = 0;
                        byte[] last_bytes = new byte[6];
                        do
                        {
                            bytesread = networkStream.Read(bytesFrom, 0, (int)((TcpClient)cl).ReceiveBufferSize);
                            requestStrm.Write(bytesFrom, 0, bytesread);
                            bytesFrom = new byte[(int)((TcpClient)cl).ReceiveBufferSize];

                            requestStrm.Seek((int)requestStrm.Length - 6, SeekOrigin.Begin);
                            requestStrm.Read(last_bytes, 0, 6);
                            requestStrm.Seek(0, SeekOrigin.End);
                        } while (
                            last_bytes[0] != 5 ||
                            last_bytes[1] != 6 ||
                            last_bytes[2] != 1 ||
                            last_bytes[3] != 100 ||
                            last_bytes[4] != 1 ||
                            last_bytes[5] != 123
                            );

                        string request = Encoding.UTF8.GetString(requestStrm.ToArray(), 0, (int)requestStrm.Length - 6);

                        byte[] sendBytes = new byte[0];

                        try
                        {
                            SN.RequestInfo info = Newtonsoft.Json.JsonConvert.DeserializeObject <SN.RequestInfo>(request);
                            bool isNewClient    = true;
                            bool clientAuth     = false;
                            bool badtoken       = false;
                            if (info.sid != null)
                            {
                                if (SN.Sessions.Current.ContainsKey(info.sid))
                                {
                                    if (SN.Sessions.Current[info.sid]["session.clientip"] == ((IPEndPoint)((TcpClient)cl).Client.RemoteEndPoint).Address.ToString())
                                    {
                                        if (SN.Sessions.Current[info.sid]["session.authflag"] == true)
                                        {
                                            string base64message = info.tkn;

                                            string[] rsa_numbers = Encoding.ASCII.GetString(Convert.FromBase64String(base64message)).Split(' ');
                                            rsa_numbers          = rsa_numbers.Take(rsa_numbers.Count() - 1).ToArray();
                                            string[] aes_token   = Encoding.ASCII.GetString(((RSA)SN.Sessions.Current[info.sid]["RSA"]).Decrypt((rsa_numbers))).Split(' ');

                                            if (aes_token[0].Length != 16 || aes_token[1].Length != 16)
                                            {
                                                isNewClient = false;
                                                badtoken    = true;
                                            }
                                            else
                                            {
                                                SN.Sessions.Current[info.sid]["AES_KEY"]          = aes_token[0];
                                                SN.Sessions.Current[info.sid]["AES_IV"]           = aes_token[1];
                                                SN.Sessions.Current[info.sid]["session.authflag"] = false;
                                                sendBytes = System.Text.Encoding.UTF8.GetBytes("ok.");

                                                isNewClient = false;
                                                clientAuth  = true;
                                            }
                                        }
                                        else
                                        {
                                            isNewClient = false;
                                            try
                                            {
                                                SN.Sessions.Current[info.sid]["session.activationdate"] = DateTime.Now;

                                                info.msg  = Newtonsoft.Json.JsonConvert.DeserializeObject(AES.Decrypt(info.msg, Encoding.ASCII.GetBytes((string)SN.Sessions.Current[info.sid]["AES_KEY"]), Encoding.ASCII.GetBytes((string)SN.Sessions.Current[info.sid]["AES_IV"])));
                                                sendBytes = System.Text.Encoding.UTF8.GetBytes(AES.Encrypt(Newtonsoft.Json.JsonConvert.SerializeObject(SN.InvokeByAttribute.Invoke(info.attr, info)), Encoding.ASCII.GetBytes((string)SN.Sessions.Current[info.sid]["AES_KEY"]), Encoding.ASCII.GetBytes((string)SN.Sessions.Current[info.sid]["AES_IV"])));



                                                clientAuth = true;
                                            }
                                            catch (Exception ex) { Console.WriteLine(ex.Message); }
                                        }
                                    }
                                }
                            }

                            if (isNewClient)
                            {
                                string session_id  = CreateSession(((IPEndPoint)((TcpClient)cl).Client.RemoteEndPoint).Address.ToString());
                                ResponseInfo rinfo = new ResponseInfo();
                                rinfo.rsa_p_key    = ((RSA)SN.Sessions.Current[session_id]["RSA"]).GetPublicKey();
                                rinfo.sid          = session_id;

                                sendBytes = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(rinfo));
                            }
                            else
                            {
                                if (!clientAuth)
                                {
                                    if (badtoken)
                                    {
                                        sendBytes = System.Text.Encoding.UTF8.GetBytes("Bad Token.");
                                    }
                                    else
                                    {
                                        sendBytes = System.Text.Encoding.UTF8.GetBytes("Authentication error.");
                                    }
                                }
                            }
                        }
                        catch
                        {
                            sendBytes = System.Text.Encoding.UTF8.GetBytes("Protocol error.");
                        }
                        MemoryStream resstrm = new MemoryStream();
                        resstrm.Write(sendBytes, 0, sendBytes.Length);
                        resstrm.Write(eos, 0, 6);

                        networkStream.Write(resstrm.ToArray(), 0, (int)resstrm.Length);

                        networkStream.Flush();

                        ((TcpClient)cl).Close();
                    }
                    catch (Exception ex) { Console.WriteLine(ex.Message); }
                    GC.Collect();
                }).Start(client);
            }
        }