Sfoglia il codice sorgente

Fix Obfuscated connection and add websocket support

painor 5 anni fa
parent
commit
4505ad10ae

+ 1 - 1
gramjs/Password.js

@@ -35,7 +35,7 @@ function checkPrimeAndGoodCheck(prime, g) {
             throw new Error(`bad g ${g}, mod8 ${prime % 5}`)
             throw new Error(`bad g ${g}, mod8 ${prime % 5}`)
         }
         }
     } else if (g === BigInt(6)) {
     } else if (g === BigInt(6)) {
-        if (!([BigInt(9), BigInt(3)].includes(prime % BigInt(4)))) {
+        if (!([BigInt(19), BigInt(23)].includes(prime % BigInt(24)))) {
             throw new Error(`bad g ${g}, mod8 ${prime % 24}`)
             throw new Error(`bad g ${g}, mod8 ${prime % 24}`)
         }
         }
     } else if (g === BigInt(7)) {
     } else if (g === BigInt(7)) {

+ 2 - 7
gramjs/client/TelegramClient.js

@@ -14,6 +14,8 @@ const { functions, types } = require('../tl')
 const { computeCheck } = require('../Password')
 const { computeCheck } = require('../Password')
 const MTProtoSender = require('../network/MTProtoSender')
 const MTProtoSender = require('../network/MTProtoSender')
 const { ConnectionTCPObfuscated } = require('../network/connection/TCPObfuscated')
 const { ConnectionTCPObfuscated } = require('../network/connection/TCPObfuscated')
+const { ConnectionTCPFull } = require('../network/connection/TCPFull')
+
 const DEFAULT_DC_ID = 4
 const DEFAULT_DC_ID = 4
 const DEFAULT_IPV4_IP = '149.154.167.51'
 const DEFAULT_IPV4_IP = '149.154.167.51'
 const DEFAULT_IPV6_IP = '[2001:67c:4e8:f002::a]'
 const DEFAULT_IPV6_IP = '[2001:67c:4e8:f002::a]'
@@ -305,11 +307,9 @@ class TelegramClient {
         let twoStepDetected = false
         let twoStepDetected = false
 
 
         await this.sendCodeRequest(phone, args.forceSMS)
         await this.sendCodeRequest(phone, args.forceSMS)
-        console.log('you  got sent the code')
 
 
         let signUp = false
         let signUp = false
         while (attempts < args.maxAttempts) {
         while (attempts < args.maxAttempts) {
-            console.log('try nummber', attempts)
             try {
             try {
                 const value = args.code
                 const value = args.code
                 if (!value) {
                 if (!value) {
@@ -475,9 +475,7 @@ class TelegramClient {
             if (result.type instanceof types.auth.SentCodeTypeSms) {
             if (result.type instanceof types.auth.SentCodeTypeSms) {
                 forceSMS = false
                 forceSMS = false
             }
             }
-            console.log('got result', result)
             if (result.phoneCodeHash) {
             if (result.phoneCodeHash) {
-                console.log('appending hash')
                 this._phoneCodeHash[phone] = phoneHash = result.phoneCodeHash
                 this._phoneCodeHash[phone] = phoneHash = result.phoneCodeHash
             }
             }
         } else {
         } else {
@@ -716,9 +714,7 @@ class TelegramClient {
         // will work with access_hash = 0. Similar for channels.getChannels.
         // will work with access_hash = 0. Similar for channels.getChannels.
         // If we're not a bot but the user is in our contacts, it seems to work
         // If we're not a bot but the user is in our contacts, it seems to work
         // regardless. These are the only two special-cased requests.
         // regardless. These are the only two special-cased requests.
-        console.log('the peer i will get is ', peer)
         peer = utils.getPeer(peer)
         peer = utils.getPeer(peer)
-        console.log('the peer i got was ', peer)
         if (peer instanceof types.PeerUser) {
         if (peer instanceof types.PeerUser) {
             const users = await this.invoke(new functions.users.GetUsersRequest({
             const users = await this.invoke(new functions.users.GetUsersRequest({
                 id: [new types.InputUser({
                 id: [new types.InputUser({
@@ -771,7 +767,6 @@ class TelegramClient {
         channelId: null,
         channelId: null,
         ptsDate: null,
         ptsDate: null,
     }) {
     }) {
-        console.log('event args are ', args)
         for (const [builder, callback] of this._eventBuilders) {
         for (const [builder, callback] of this._eventBuilders) {
             const event = builder.build(args.update)
             const event = builder.build(args.update)
             if (event) {
             if (event) {

+ 0 - 1
gramjs/crypto/AESCTR.js

@@ -10,7 +10,6 @@ class AESModeCTR {
     }
     }
 
 
     encrypt(data) {
     encrypt(data) {
-        console.log('first data to encrypt is ', data.toString('hex'))
         const res = this.cipher.encrypt(data)
         const res = this.cipher.encrypt(data)
         return Buffer.from(res)
         return Buffer.from(res)
     }
     }

+ 3 - 3
gramjs/crypto/Factorizator.js

@@ -9,11 +9,11 @@ class Factorizator {
     static findSmallMultiplierLopatin(what) {
     static findSmallMultiplierLopatin(what) {
         let g = BigInt(0)
         let g = BigInt(0)
         for (let i = BigInt(0); i < BigInt(3); i++) {
         for (let i = BigInt(0); i < BigInt(3); i++) {
-            const q = BigInt(0) || (getRandomInt(0, 127) & 15) + 17
-            let x = BigInt(0) || getRandomInt(0, 1000000000) + 1
+            const q = BigInt(30) || BigInt((getRandomInt(0, 127) & 15) + 17)
+            let x = BigInt(40) || BigInt(getRandomInt(0, 1000000000) + 1)
 
 
             let y = x
             let y = x
-            const lim = BigInt(1) << (i + BigInt(8))
+            const lim = BigInt(1) << (i + BigInt(18))
             for (let j = BigInt(1); j < lim; j++) {
             for (let j = BigInt(1); j < lim; j++) {
                 let a = x
                 let a = x
                 let b = x
                 let b = x

+ 0 - 1
gramjs/errors/Common.js

@@ -45,7 +45,6 @@ class InvalidChecksumError extends Error {
  */
  */
 class InvalidBufferError extends Error {
 class InvalidBufferError extends Error {
     constructor(payload) {
     constructor(payload) {
-        console.log("paerlkaelm rkae",payload)
         const code = -(struct.unpack('<i', payload)[0])
         const code = -(struct.unpack('<i', payload)[0])
         if (payload.length === 4) {
         if (payload.length === 4) {
             super(`Invalid response buffer (HTTP code ${code})`)
             super(`Invalid response buffer (HTTP code ${code})`)

+ 1 - 1
gramjs/extensions/BinaryReader.js

@@ -47,7 +47,7 @@ class BinaryReader {
      * @returns {bigint}
      * @returns {bigint}
      */
      */
     readLong(signed = true) {
     readLong(signed = true) {
-        return this.readLargeInt(8, signed)
+        return this.readLargeInt(64, signed)
     }
     }
 
 
     /**
     /**

+ 3 - 4
gramjs/extensions/PromisedWebSockets.js

@@ -22,7 +22,7 @@ class PromisedWebSockets {
 
 
     async read(number) {
     async read(number) {
         if (this.closed || !await this.canRead) {
         if (this.closed || !await this.canRead) {
-            console.log('wops ccouln\'t read')
+            console.log('couldn\'t read')
             throw closeError
             throw closeError
         }
         }
 
 
@@ -57,7 +57,7 @@ class PromisedWebSockets {
         }
         }
     }
     }
 
 
-    async connect(ip, port) {
+    async connect(port, ip) {
         const tunnelingAgent = tunnel.httpOverHttp({
         const tunnelingAgent = tunnel.httpOverHttp({
             proxy: {
             proxy: {
                 host: '127.0.0.1',
                 host: '127.0.0.1',
@@ -92,7 +92,7 @@ class PromisedWebSockets {
     }
     }
 
 
     async close() {
     async close() {
-        console.log('something happened. clsong')
+        console.log('something happened. closing')
         await this.connection.close()
         await this.connection.close()
         this.resolveRead(false)
         this.resolveRead(false)
         this.closed = true
         this.closed = true
@@ -100,7 +100,6 @@ class PromisedWebSockets {
 
 
     async receive() {
     async receive() {
         this.connection.on('message', function(message) {
         this.connection.on('message', function(message) {
-            console.log(message)
             let data
             let data
             if (message.binaryData) {
             if (message.binaryData) {
                 data = Buffer.from(message.binaryData)
                 data = Buffer.from(message.binaryData)

+ 0 - 1
gramjs/network/Authenticator.js

@@ -25,7 +25,6 @@ const { ReqPqMultiRequest } = require('../tl/functions')
  * @returns {Promise<{authKey: *, timeOffset: *}>}
  * @returns {Promise<{authKey: *, timeOffset: *}>}
  */
  */
 async function doAuthentication(sender, log) {
 async function doAuthentication(sender, log) {
-    console.log('starting auth')
     // Step 1 sending: PQ Request, endianness doesn't matter since it's random
     // Step 1 sending: PQ Request, endianness doesn't matter since it's random
     let bytes = Helpers.generateRandomBytes(16)
     let bytes = Helpers.generateRandomBytes(16)
 
 

+ 1 - 0
gramjs/network/MTProtoPlainSender.js

@@ -28,6 +28,7 @@ class MTProtoPlainSender {
      * @param request
      * @param request
      */
      */
     async send(request) {
     async send(request) {
+
         let body = request.bytes
         let body = request.bytes
         let msgId = this._state._getNewMsgId()
         let msgId = this._state._getNewMsgId()
         const res = Buffer.concat([struct.pack('<qqi', [0, msgId.toString(), body.length]), body])
         const res = Buffer.concat([struct.pack('<qqi', [0, msgId.toString(), body.length]), body])

+ 0 - 2
gramjs/network/MTProtoSender.js

@@ -326,7 +326,6 @@ class MTProtoSender {
                 return
                 return
             }
             }
             try {
             try {
-                console.log('body len ', body.length)
                 message = await this._state.decryptMessageData(body)
                 message = await this._state.decryptMessageData(body)
             } catch (e) {
             } catch (e) {
                 console.log(e)
                 console.log(e)
@@ -522,7 +521,6 @@ class MTProtoSender {
      * @private
      * @private
      */
      */
     async _handlePong(message) {
     async _handlePong(message) {
-        console.log(message)
         const pong = message.obj
         const pong = message.obj
         this._log.debug(`Handling pong for message ${pong.msgId}`)
         this._log.debug(`Handling pong for message ${pong.msgId}`)
         const state = this._pending_state[pong.msgId]
         const state = this._pending_state[pong.msgId]

+ 2 - 3
gramjs/network/MTProtoState.js

@@ -177,12 +177,11 @@ class MTProtoState {
     _getNewMsgId() {
     _getNewMsgId() {
         const now = new Date().getTime() / 1000 + this.timeOffset
         const now = new Date().getTime() / 1000 + this.timeOffset
         const nanoseconds = Math.floor((now - Math.floor(now)) * 1e9)
         const nanoseconds = Math.floor((now - Math.floor(now)) * 1e9)
-        let newMsgId = (BigInt(Math.floor(now)) << BigInt(2)) | (BigInt(nanoseconds) << BigInt(2))
+        let newMsgId = (BigInt(Math.floor(now)) << BigInt(32)) | (BigInt(nanoseconds) << BigInt(2))
         if (this._lastMsgId >= newMsgId) {
         if (this._lastMsgId >= newMsgId) {
             newMsgId = this._lastMsgId + BigInt(4)
             newMsgId = this._lastMsgId + BigInt(4)
         }
         }
         this._lastMsgId = newMsgId
         this._lastMsgId = newMsgId
-
         return newMsgId
         return newMsgId
     }
     }
 
 
@@ -195,7 +194,7 @@ class MTProtoState {
         const bad = this._getNewMsgId()
         const bad = this._getNewMsgId()
         const old = this.timeOffset
         const old = this.timeOffset
         const now = Math.floor(new Date().getTime() / 1000)
         const now = Math.floor(new Date().getTime() / 1000)
-        const correct = correctMsgId >> BigInt(2)
+        const correct = correctMsgId >> BigInt(32)
         this.timeOffset = correct - now
         this.timeOffset = correct - now
 
 
         if (this.timeOffset !== old) {
         if (this.timeOffset !== old) {

+ 2 - 4
gramjs/network/connection/Connection.js

@@ -29,9 +29,9 @@ class Connection {
         this._obfuscation = null // TcpObfuscated and MTProxy
         this._obfuscation = null // TcpObfuscated and MTProxy
         this._sendArray = new AsyncQueue()
         this._sendArray = new AsyncQueue()
         this._recvArray = new AsyncQueue()
         this._recvArray = new AsyncQueue()
-        this.socket = new PromiseSocket(new Socket())
+        //this.socket = new PromiseSocket(new Socket())
 
 
-        //this.socket = new PromisedWebSockets()
+        this.socket = new PromisedWebSockets()
     }
     }
 
 
     async _connect() {
     async _connect() {
@@ -80,7 +80,6 @@ class Connection {
         try {
         try {
             while (this._connected) {
             while (this._connected) {
                 const data = await this._sendArray.pop()
                 const data = await this._sendArray.pop()
-                console.log("data to send",data)
                 await this._send(data)
                 await this._send(data)
             }
             }
         } catch (e) {
         } catch (e) {
@@ -135,7 +134,6 @@ class ObfuscatedConnection extends Connection {
     }
     }
 
 
     _send(data) {
     _send(data) {
-        console.log('i am here first', data.toString('hex'))
         this._obfuscation.write(this._codec.encodePacket(data))
         this._obfuscation.write(this._codec.encodePacket(data))
     }
     }
 
 

+ 2 - 7
gramjs/network/connection/TCPAbridged.js

@@ -24,17 +24,12 @@ class AbridgedPacketCodec extends PacketCodec {
 
 
     async readPacket(reader) {
     async readPacket(reader) {
         const readData = await reader.read(1)
         const readData = await reader.read(1)
-        console.log('aeraer', readData)
-
         let length = struct.unpack('<B', readData)[0]
         let length = struct.unpack('<B', readData)[0]
-        console.log('len is ', length)
-
-        if (length > 127) {
+        if (length >= 127) {
             length = struct.unpack(
             length = struct.unpack(
                 '<i', Buffer.concat([await reader.read(3), Buffer.alloc(1)]))[0]
                 '<i', Buffer.concat([await reader.read(3), Buffer.alloc(1)]))[0]
         }
         }
-        console.log(length)
-        console.log('gonna read ', length << 2)
+
         return await reader.read(length << 2)
         return await reader.read(length << 2)
     }
     }
 }
 }

+ 0 - 10
gramjs/network/connection/TCPObfuscated.js

@@ -10,8 +10,6 @@ class ObfuscatedIO {
         this.connection = connection.socket
         this.connection = connection.socket
         const res = this.initHeader(connection.PacketCodecClass)
         const res = this.initHeader(connection.PacketCodecClass)
         this.header = res.random
         this.header = res.random
-        console.log(this.header.toString('hex'))
-        console.log(this.header.toString('hex').length)
 
 
         this._encrypt = res.encryptor
         this._encrypt = res.encryptor
         this._decrypt = res.decryptor
         this._decrypt = res.decryptor
@@ -42,7 +40,6 @@ class ObfuscatedIO {
         random = random.toJSON().data
         random = random.toJSON().data
 
 
         const randomReversed = Buffer.from(random.slice(8, 56)).reverse()
         const randomReversed = Buffer.from(random.slice(8, 56)).reverse()
-        console.log(randomReversed.toString('hex'))
         // Encryption has "continuous buffer" enabled
         // Encryption has "continuous buffer" enabled
         const encryptKey = Buffer.from(random.slice(8, 40))
         const encryptKey = Buffer.from(random.slice(8, 40))
         const encryptIv = Buffer.from(random.slice(40, 56))
         const encryptIv = Buffer.from(random.slice(40, 56))
@@ -50,10 +47,6 @@ class ObfuscatedIO {
         const decryptIv = Buffer.from(randomReversed.slice(32, 48))
         const decryptIv = Buffer.from(randomReversed.slice(32, 48))
         const encryptor = new AESModeCTR(encryptKey, encryptIv)
         const encryptor = new AESModeCTR(encryptKey, encryptIv)
         const decryptor = new AESModeCTR(decryptKey, decryptIv)
         const decryptor = new AESModeCTR(decryptKey, decryptIv)
-        console.log('decryptor data ', decryptKey.toString('hex'), decryptIv.toString('hex'))
-        console.log('encryptor data ', encryptKey.toString('hex'), encryptIv.toString('hex'))
-
-        process.exit(0)
 
 
         random = Buffer.concat([
         random = Buffer.concat([
             Buffer.from(random.slice(0, 56)), packetCodec.obfuscateTag, Buffer.from(random.slice(60)),
             Buffer.from(random.slice(0, 56)), packetCodec.obfuscateTag, Buffer.from(random.slice(60)),
@@ -66,9 +59,6 @@ class ObfuscatedIO {
 
 
     async read(n) {
     async read(n) {
         const data = await this.connection.read(n)
         const data = await this.connection.read(n)
-        console.log('read raw data is ', data.toString('hex'))
-        console.log('obfuscated adata is ', this._decrypt.encrypt(data))
-        process.exit(0)
         return this._decrypt.encrypt(data)
         return this._decrypt.encrypt(data)
     }
     }