상속: TeleSharp.TL.TLObject
예제 #1
0
 public override void DeserializeResponse(BinaryReader br)
 {
     Response = (TLAuthorization)ObjectUtils.DeserializeObject(br);
 }
예제 #2
0
        private async Task ReconnectToDcAsync(int dcId, CancellationToken token = default)
        {
            token.ThrowIfCancellationRequested();

            if (this.dcOptions == null || !this.dcOptions.Any())
            {
                throw new InvalidOperationException($"Can't reconnect. Establish initial connection first.");
            }

            TLExportedAuthorization exported = null;

            if (this._session.TLUser != null)
            {
                TLRequestExportAuthorization exportAuthorization = new TLRequestExportAuthorization()
                {
                    DcId = dcId
                };
                exported = await this.SendRequestAsync <TLExportedAuthorization>(exportAuthorization, token).ConfigureAwait(false);
            }

            IEnumerable <TLDcOption> dcs;

            if (this.dcIpVersion == DataCenterIPVersion.OnlyIPv6)
            {
                dcs = this.dcOptions.Where(d => d.Id == dcId && d.Ipv6); // selects only ipv6 addresses
            }
            else if (this.dcIpVersion == DataCenterIPVersion.OnlyIPv4)
            {
                dcs = this.dcOptions.Where(d => d.Id == dcId && !d.Ipv6); // selects only ipv4 addresses
            }
            else
            {
                dcs = this.dcOptions.Where(d => d.Id == dcId); // any
            }

            dcs = dcs.Where(d => !d.MediaOnly);

            TLDcOption dc;

            if (this.dcIpVersion != DataCenterIPVersion.Default)
            {
                if (!dcs.Any())
                {
                    throw new Exception($"Telegram server didn't provide us with any IPAddress that matches your preferences. If you chose OnlyIPvX, try switch to PreferIPvX instead.");
                }

                dcs = dcs.OrderBy(d => d.Ipv6);
                dc  = this.dcIpVersion == DataCenterIPVersion.PreferIPv4 ? dcs.First() : dcs.Last(); // ipv4 addresses are at the beginning of the list because it was ordered
            }
            else
            {
                dc = dcs.First();
            }

            DataCenter dataCenter = new DataCenter(dcId, dc.IpAddress, dc.Port);

            this.transport           = new TcpTransport(dc.IpAddress, dc.Port, this.handler);
            this._session.DataCenter = dataCenter;

            //await this.AuthenticateAsync(true, token).ConfigureAwait(false);

            if (this._session.TLUser != null)
            {
                TLRequestImportAuthorization importAuthorization = new TLRequestImportAuthorization()
                {
                    Id = exported.Id, Bytes = exported.Bytes
                };
                TLAuthorization imported = await this.SendRequestAsync <TLAuthorization>(importAuthorization, token).ConfigureAwait(false);

                this.OnUserAuthenticated((TLUser)imported.User);
            }
        }
 public override void deserializeResponse(BinaryReader br)
 {
     Response = (Auth.TLAuthorization)ObjectUtils.DeserializeObject(br);
 }
예제 #4
0
        private static void ProcessRequest(TcpListener tcpListener)
        {
            Console.WriteLine("Processing...");
            var        tcpClient = tcpListener.AcceptTcpClient();
            var        netStream = tcpClient.GetStream();
            BigInteger ga        = null;

            byte[]     newNonce       = new byte[32];
            BigInteger a              = new BigInteger(2048, new Random());
            var        dhPrime        = new BigInteger("00C150023E2F70DB7985DED064759CFECF0AF328E69A41DAF4D6F01B538135A6F91F8F8B2A0EC9BA9720CE352EFCF6C5680FFC424BD634864902DE0B4BD6D49F4E580230E3AE97D95C8B19442B3C0A10D8F5633FECEDD6926A7F6DAB0DDB7D457F9EA81B8465FCD6FFFEED114011DF91C059CAEDAF97625F6C96ECC74725556934EF781D866B34F011FCE4D835A090196E9A5F0E4449AF7EB697DDB9076494CA5F81104A305B6DD27665722C46B60E5DF680FB16B210607EF217652E60236C255F6A28315F4083A96791D7214BF64C1DF4FD0DB1944FB26A2A57031B32EEE64AD15A8BA68885CDE74A5BFC920F6ABF59BA5C75506373E7130F9042DA922179251F", 16);
            BigInteger gb             = null;
            var        sequenceNumber = 1;
            ulong?     messageId      = null;
            var        privateKey     = new BigInteger("582A4D5EE3A45C1AEEBDECD549D1FD4E12337B05C4C0A03FA8FF4A0A7B2861BAB86E8B58A70AAB9CF173FA313348239E28B17D34C7CEC8B68544BAD8623A306D747B7DC1D3D064FA73CE96893E8AFC36F7CDF58A383F48BDEC284D30BFFBC3F1A413DC869B3692EDD26004EE661C021BDA32F124D6631C67891E3E35EEDEAA08BFED8DBB7A6CC1D550CF16C67703BBDFFF0500FD81A55F98D92ECD67CE3CC31B766EA0DFBA284E18677E46036D9ED04105AAD11E97FD675F49A3B54D5AD395AA3C5B8343CDFF70C2E2A9243A47FBC5F541BBAE910B5DD1BF574B1E732A105C2B8F5239A4DFA0BCE0559F18BA0C44D31A279FA7CDCA612BD8F9796EBD114F7FA9", 16);
            AuthKey    authKey        = null;

            //var getingCounter = 0;
            //while (true)
            //{
            //    if (!netStream.DataAvailable)
            //        continue;
            //    Console.WriteLine("Get data " + ++getingCounter);
            //}

            while (tcpClient.Connected)
            {
                System.Threading.Thread.Sleep(100);
                if (!netStream.DataAvailable)
                {
                    continue;
                }

                byte[] nonceFromClient = new byte[16];
                byte[] servernonce     = new byte[16];

                uint responseCode  = 0;
                int  innerCode     = 0;
                long authkeysample = 123456789;

                const long step1Constructor = 0x60469778;
                const long step2Constructor = 0xd712e4be;
                const long step3Constructor = 0xf5045f1f;

                if (netStream.CanRead)
                {
                    var bytes = new byte[tcpClient.ReceiveBufferSize];
                    netStream.Read(bytes, 0, (int)tcpClient.ReceiveBufferSize);
                    var tcpMessage   = TcpMessage.Decode(bytes);
                    var binaryReader = new BinaryReader(new MemoryStream(tcpMessage.Body, false));


                    var authKeyId = binaryReader.ReadInt64();
                    if (authKeyId == 0)
                    {
                        var msgId      = binaryReader.ReadInt64();
                        var datalength = binaryReader.ReadInt32();
                        var data       = binaryReader.ReadBytes(datalength);

                        var binaryReader2 = new BinaryReader(new MemoryStream(data, false));

                        responseCode = binaryReader2.ReadUInt32();
                        Console.WriteLine("Request code: " + responseCode);
                        if (responseCode == step1Constructor) //---Step1_PQRequest
                        {
                            nonceFromClient = binaryReader2.ReadBytes(16);
                        }
                        else if (responseCode == step2Constructor) //---Step1_PQRequest
                        {
                            nonceFromClient = binaryReader2.ReadBytes(16);
                            servernonce     = binaryReader2.ReadBytes(16);
                            var p = binaryReader2.ReadBytes(4);
                            var q = binaryReader2.ReadBytes(8);
                            var targetFingerprint = BitConverter.ToString(binaryReader2.ReadBytes(8)).Replace("-", string.Empty);

                            //TODO: need to decryption
                            var ciphertext = Bytes.read(binaryReader2);
                            ciphertext = RSA.Decrypt(targetFingerprint, ciphertext, privateKey, 0, ciphertext.Length);
                            var cipherReader    = new BinaryReader(new MemoryStream(ciphertext, false));
                            var hashsum         = cipherReader.ReadBytes(20);
                            var innercode       = cipherReader.ReadUInt32();//0x83c95aec
                            var pq              = cipherReader.ReadBytes(20);
                            var noncetemp       = cipherReader.ReadBytes(16);
                            var servernoncetemp = cipherReader.ReadBytes(16);
                            newNonce = cipherReader.ReadBytes(32);
                            //Array.Copy(ciphertext, ciphertext.Length - 32, newNonce, 0, 32);
                            //ciphertext.CopyTo(newnoncetemp, ciphertext.Length - 32);
                        }
                        else if (responseCode == step3Constructor) //---Step1_PQRequest
                        {
                            nonceFromClient = binaryReader2.ReadBytes(16);
                            servernonce     = binaryReader2.ReadBytes(16);

                            //TODO: need to decryption
                            var        ciphertext                = Bytes.read(binaryReader2);
                            AESKeyData key                       = AES.GenerateKeyDataFromNonces(servernonce, newNonce);
                            var        cleartext                 = AES.DecryptAES(key, ciphertext);
                            var        binaryReadernner          = new BinaryReader(new MemoryStream(cleartext, false));
                            var        hasheddata                = binaryReadernner.ReadBytes(20);
                            var        client_dh_inner_data_code = binaryReadernner.ReadUInt32();
                            if (client_dh_inner_data_code != 0x6643b654)
                            {
                                throw new Exception("We have a complex story");
                            }
                            var nonceFromClient_temp = binaryReadernner.ReadBytes(16);
                            var servernonce_temp     = binaryReadernner.ReadBytes(16);
                            var zero = binaryReadernner.ReadUInt64();
                            gb = new BigInteger(Bytes.read(binaryReadernner));
                        }
                    }
                    else
                    {
                        var _gba = gb.ModPow(a, dhPrime);
                        authKey = new AuthKey(_gba);
                        var decodeMessage = DecodeMessage(tcpMessage.Body, authKey);
                        var objrawReader  = new BinaryReader(new MemoryStream(decodeMessage.Item1, false));
                        messageId = decodeMessage.Item2;
                        innerCode = objrawReader.ReadInt32();


                        if (innerCode == 0x62d6b459)//acknowledged
                        {
                            var vector   = objrawReader.ReadInt32();
                            var msgCount = objrawReader.ReadInt32();
                            continue;
                        }
                        else //if (responseCode == -627372787)
                        {
                            objrawReader.BaseStream.Position += -4;
                            var obj = ObjectUtils.DeserializeObject(objrawReader);
                            if (obj is TLRequestInvokeWithLayer)
                            {
                                var invokewithlayer = (TLRequestInvokeWithLayer)obj;
                                if (invokewithlayer.Query is TLRequestInitConnection)
                                {
                                    var requestInitConnection = (TLRequestInitConnection)invokewithlayer.Query;
                                }
                                else if (invokewithlayer.Query is TLRequestSendCode)
                                {
                                    var requestSendCode = (TLRequestSendCode)invokewithlayer.Query;
                                }
                            }
                            else if (obj is TLRequestSendCode)
                            {
                                var requestSendCode = (TLRequestSendCode)obj;
                            }
                            else if (obj is TLRequestSignIn)
                            {
                                var requestSignIn = (TLRequestSignIn)obj;
                            }
                            else if (obj is TLRequestGetContacts)
                            {
                                var requestGetContacts = (TLRequestGetContacts)obj;
                            }
                        }

                        //var keyData = Helpers.CalcKey(buffer, messageKey, false);
                        //var data = AES.DecryptAES(keyData, buffer);
                    }
                }

                if (netStream.CanWrite)
                {
                    var fingerprint = StringToByteArray("216be86c022bb4c3");

                    byte[] outputdata = null;
                    if (responseCode == step1Constructor)
                    {
                        var nonce = new byte[16];
                        new Random().NextBytes(nonce);
                        outputdata = new Step1_Response()
                        {
                            Pq           = new BigInteger(1, BitConverter.GetBytes(880)),
                            ServerNonce  = nonceFromClient,
                            Nonce        = nonce,
                            Fingerprints = new List <byte[]>()
                            {
                                fingerprint
                            }
                        }.ToBytes();
                    }
                    else if (responseCode == step2Constructor)
                    {
                        //var nonce = new byte[16];
                        //new Random().NextBytes(nonce);

                        byte[]     answer;
                        var        hashsum       = Encoding.UTF8.GetBytes("asdfghjklmnbvcxzasdf");
                        const uint innerCodetemp = 0xb5890dba;
                        AESKeyData key           = AES.GenerateKeyDataFromNonces(servernonce, newNonce);

                        var g = 47;
                        ga = BigInteger.ValueOf(g).ModPow(a, dhPrime);

                        using (var memoryStream = new MemoryStream())
                        {
                            using (var binaryWriter = new BinaryWriter(memoryStream))
                            {
                                binaryWriter.Write(hashsum);
                                binaryWriter.Write(innerCodetemp);
                                binaryWriter.Write(nonceFromClient);
                                binaryWriter.Write(servernonce);
                                binaryWriter.Write(g);
                                Bytes.write(binaryWriter, dhPrime.ToByteArrayUnsigned());
                                Bytes.write(binaryWriter, ga.ToByteArrayUnsigned());
                                Bytes.write(binaryWriter, BitConverter.GetBytes((int)(Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds) / 1000)));//server datetime
                                answer = memoryStream.ToArray();
                            }
                        }

                        outputdata = new Step2_Response()
                        {
                            ServerNonce     = nonceFromClient,
                            Nonce           = servernonce,
                            NewNonce        = newNonce,
                            EncryptedAnswer = AES.EncryptAES(key, answer)
                        }.ToBytes();
                    }
                    else if (responseCode == step3Constructor)
                    {
                        var _gba = gb.ModPow(a, dhPrime);
                        authKey = new AuthKey(_gba);
                        var        newNonceHash  = authKey.CalcNewNonceHash(newNonce, 1);
                        const uint innerCodeTemp = 0x3bcbf734;
                        using (var memoryStream = new MemoryStream())
                        {
                            using (var binaryWriter = new BinaryWriter(memoryStream))
                            {
                                binaryWriter.Write(innerCodeTemp);
                                binaryWriter.Write(servernonce);
                                binaryWriter.Write(nonceFromClient);
                                binaryWriter.Write(newNonceHash);//hashnewnonce
                                outputdata = memoryStream.ToArray();
                            }
                        }
                    }
                    else if (innerCode == -2035355412)//TLRequestSendCode
                    {
                        #region Generate TLSentCode

                        var sentCode = new TLSentCode();
                        sentCode.PhoneRegistered = false;
                        sentCode.Timeout         = 7777;
                        sentCode.PhoneCodeHash   = "asdfghjklmnbvcxzasdf";
                        sentCode.Flags           = 3;
                        sentCode.NextType        = new TLCodeTypeSms();
                        sentCode.Type            = new TLSentCodeTypeApp()
                        {
                            Length = 20
                        };

                        #endregion

                        using (var memoryStream = new MemoryStream())
                        {
                            using (var binaryWriter = new BinaryWriter(memoryStream))
                            {
                                binaryWriter.Write(0xf35c6d01);      //main code
                                binaryWriter.Write(messageId.Value); //requestId -- ulong -- from mesage id
                                sentCode.SerializeBody(binaryWriter);
                                outputdata = memoryStream.ToArray();
                            }
                        }
                    }
                    else if (innerCode == -627372787)
                    {
                        #region Generate TLConfig
                        //---Genrate mock tlconfig
                        var config = new TLConfig();
                        config.CallConnectTimeoutMs = 7777;
                        config.CallPacketTimeoutMs  = 7777;
                        config.CallReceiveTimeoutMs = 7777;
                        config.CallRingTimeoutMs    = 7777;
                        config.ChatBigSize          = 7777;
                        config.ChatSizeMax          = 777;
                        config.Date      = Convert.ToInt32((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds);
                        config.DcOptions = new TLVector <TLDcOption>()
                        {
                            new TLDcOption()
                            {
                                Flags = 0, Id = 1, IpAddress = "127.0.0.1", Port = 5000
                            }
                        };
                        config.DisabledFeatures      = new TLVector <TLDisabledFeature>();
                        config.ForwardedCountMax     = 777;
                        config.MegagroupSizeMax      = 777;
                        config.NotifyCloudDelayMs    = 7777;
                        config.NotifyDefaultDelayMs  = 7777;
                        config.OfflineBlurTimeoutMs  = 7777;
                        config.OfflineIdleTimeoutMs  = 7777;
                        config.OnlineCloudTimeoutMs  = 7777;
                        config.OnlineUpdatePeriodMs  = 7777;
                        config.PhonecallsEnabled     = false;
                        config.PinnedDialogsCountMax = 7;
                        config.PushChatLimit         = 7;
                        config.PushChatPeriodMs      = 777;
                        config.RatingEDecay          = 777;
                        config.SavedGifsLimit        = 777;
                        config.StickersRecentLimit   = 777;
                        config.ThisDc      = 1;//TODO: ---what's this?!---
                        config.MeUrlPrefix = "https://t.me/";
                        config.TestMode    = false;
                        #endregion

                        using (var memoryStream = new MemoryStream())
                        {
                            using (var binaryWriter = new BinaryWriter(memoryStream))
                            {
                                binaryWriter.Write(0xf35c6d01);      //main code
                                                                     //binaryWriter.Write(0xf35c6d02);//code
                                binaryWriter.Write(messageId.Value); //requestId -- ulong -- from mesage id
                                                                     //binaryWriter.Write(0x2144ca17);//innercode -- int
                                                                     //binaryWriter.Write(1123456789);//sample code
                                                                     //Serializers.Bytes.write(binaryWriter, config.Serialize());
                                config.SerializeBody(binaryWriter);
                                outputdata = memoryStream.ToArray();
                            }
                        }
                    }
                    else if (innerCode == -1126886015)
                    {
                        #region Generate TLAuthorization

                        var auth = new TeleSharp.TL.Auth.TLAuthorization();
                        auth.Flags = 3;
                        auth.User  = new TLUser()
                        {
                            FirstName = "Meysami"
                        };

                        #endregion

                        using (var memoryStream = new MemoryStream())
                        {
                            using (var binaryWriter = new BinaryWriter(memoryStream))
                            {
                                binaryWriter.Write(0xf35c6d01);      //main code
                                binaryWriter.Write(messageId.Value); //requestId -- ulong -- from mesage id
                                auth.SerializeBody(binaryWriter);
                                outputdata = memoryStream.ToArray();
                            }
                        }
                    }
                    else if (innerCode == 583445000)//GetContacts
                    {
                        #region Generate TLAbsContacts

                        var contacts = new TLContacts();
                        contacts.Contacts = new TLVector <TLContact>()
                        {
                            new TLContact()
                            {
                                UserId = 11
                            },
                            new TLContact()
                            {
                                UserId = 12
                            }
                        };
                        contacts.Users = new TLVector <TLAbsUser>()
                        {
                            new TLUser()
                            {
                                Bot = false, FirstName = "Mary", Id = 11
                            },
                            new TLUser()
                            {
                                Bot = false, FirstName = "Mary 2", Id = 12
                            }
                        };

                        #endregion

                        using (var memoryStream = new MemoryStream())
                        {
                            using (var binaryWriter = new BinaryWriter(memoryStream))
                            {
                                binaryWriter.Write(0xf35c6d01);      //main code
                                binaryWriter.Write(messageId.Value); //requestId -- ulong -- from mesage id
                                contacts.SerializeBody(binaryWriter);
                                outputdata = memoryStream.ToArray();
                            }
                        }
                    }
                    else
                    {
                        continue;
                    }

                    if (innerCode != 0)
                    {
                        outputdata = PrepareToSend2(outputdata, authKey.Id, 0, 0, 0, servernonce, sequenceNumber, authKey);
                    }
                    else
                    {
                        outputdata = PrepareToSend(outputdata);
                    }

                    outputdata = Encode(outputdata, sequenceNumber++);
                    netStream.Write(outputdata, 0, outputdata.Length);
                }
                else
                {
                    Console.WriteLine("You cannot write data to this stream.");
                    tcpClient.Close();
                    netStream.Close();
                }
            }
        }