Explorar el Código

fix decryption error

painor hace 5 años
padre
commit
e5e70ea901

+ 4 - 4
gramjs/crypto/AESCTR.js

@@ -6,13 +6,13 @@ class AESModeCTR {
         if (!(key instanceof Buffer) || !(iv instanceof Buffer) || iv.length !== 16) {
             throw new Error('Key and iv need to be a buffer')
         }
-        this.key = key
-        this.iv = iv
-        this.cipher = new aesjs.ModeOfOperation.ctr(key, iv)
+        this.cipher = new aesjs.ModeOfOperation.ctr(Buffer.from(key), Buffer.from(iv))
     }
 
     encrypt(data) {
-        return Buffer.from(this.cipher.encrypt(data))
+        console.log('first data to encrypt is ', data.toString('hex'))
+        const res = this.cipher.encrypt(data)
+        return Buffer.from(res)
     }
 
     decrypt(data) {

+ 1 - 0
gramjs/errors/Common.js

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

+ 1 - 1
gramjs/extensions/PromisedWebSockets.js

@@ -84,7 +84,7 @@ class PromisedWebSockets {
         }.bind(this))
     }
 
-    send(data) {
+    write(data) {
         if (this.closed) {
             throw closeError
         }

+ 3 - 2
gramjs/network/Authenticator.js

@@ -25,6 +25,7 @@ const { ReqPqMultiRequest } = require('../tl/functions')
  * @returns {Promise<{authKey: *, timeOffset: *}>}
  */
 async function doAuthentication(sender, log) {
+    console.log('starting auth')
     // Step 1 sending: PQ Request, endianness doesn't matter since it's random
     let bytes = Helpers.generateRandomBytes(16)
 
@@ -82,7 +83,7 @@ async function doAuthentication(sender, log) {
             q: q,
             publicKeyFingerprint: targetFingerprint,
             encryptedData: cipherText,
-        })
+        }),
     )
     if (!(serverDhParams instanceof ServerDHParamsOk || serverDhParams instanceof ServerDHParamsFail)) {
         throw new Error(`Step 2.1 answer was ${serverDhParams}`)
@@ -152,7 +153,7 @@ async function doAuthentication(sender, log) {
             nonce: resPQ.nonce,
             serverNonce: resPQ.serverNonce,
             encryptedData: clientDhEncrypted,
-        })
+        }),
     )
     const nonceTypes = [DhGenOk, DhGenRetry, DhGenFail]
     if (!(dhGen instanceof nonceTypes[0] || dhGen instanceof nonceTypes[1] || dhGen instanceof nonceTypes[2])) {

+ 1 - 0
gramjs/network/MTProtoSender.js

@@ -326,6 +326,7 @@ class MTProtoSender {
                 return
             }
             try {
+                console.log('body len ', body.length)
                 message = await this._state.decryptMessageData(body)
             } catch (e) {
                 console.log(e)

+ 0 - 1
gramjs/network/MTProtoState.js

@@ -126,7 +126,6 @@ class MTProtoState {
      * @param body
      */
     async decryptMessageData(body) {
-        console.log(body)
         if (body.length < 8) {
             throw new InvalidBufferError(body)
         }

+ 13 - 8
gramjs/network/connection/Connection.js

@@ -1,5 +1,7 @@
 const PromisedWebSockets = require('../../extensions/PromisedWebSockets')
 const AsyncQueue = require('../../extensions/AsyncQueue')
+const Socket = require('net').Socket
+const { PromiseSocket } = require('promise-socket')
 
 /**
  * The `Connection` class is a wrapper around ``asyncio.open_connection``.
@@ -20,8 +22,6 @@ class Connection {
         this._port = port
         this._dcId = dcId
         this._log = loggers
-        this._reader = null
-        this._writer = null
         this._connected = false
         this._sendTask = null
         this._recvTask = null
@@ -29,12 +29,14 @@ class Connection {
         this._obfuscation = null // TcpObfuscated and MTProxy
         this._sendArray = new AsyncQueue()
         this._recvArray = new AsyncQueue()
-        this.socket = new PromisedWebSockets()
+        this.socket = new PromiseSocket(new Socket())
+
+        //this.socket = new PromisedWebSockets()
     }
 
     async _connect() {
         this._log.debug('Connecting')
-        await this.socket.connect(this._ip, this._port)
+        await this.socket.connect(this._port, this._ip)
         this._log.debug('Finished connecting')
         // await this.socket.connect({host: this._ip, port: this._port});
         this._codec = new this.PacketCodecClass(this)
@@ -77,7 +79,9 @@ class Connection {
         // TODO handle errors
         try {
             while (this._connected) {
-                await this._send(await this._sendArray.pop())
+                const data = await this._sendArray.pop()
+                console.log("data to send",data)
+                await this._send(data)
             }
         } catch (e) {
             console.log(e)
@@ -104,13 +108,13 @@ class Connection {
 
     async _initConn() {
         if (this._codec.tag) {
-            await this.socket.send(this._codec.tag)
+            await this.socket.write(this._codec.tag)
         }
     }
 
     async _send(data) {
         const encodedPacket = this._codec.encodePacket(data)
-        await this.socket.send(encodedPacket)
+        this.socket.write(encodedPacket)
     }
 
     async _recv() {
@@ -127,10 +131,11 @@ class ObfuscatedConnection extends Connection {
 
     async _initConn() {
         this._obfuscation = new this.ObfuscatedIO(this)
-        this.socket.send(this._obfuscation.header)
+        this.socket.write(this._obfuscation.header)
     }
 
     _send(data) {
+        console.log('i am here first', data.toString('hex'))
         this._obfuscation.write(this._codec.encodePacket(data))
     }
 

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

@@ -24,12 +24,17 @@ class AbridgedPacketCodec extends PacketCodec {
 
     async readPacket(reader) {
         const readData = await reader.read(1)
+        console.log('aeraer', readData)
+
         let length = struct.unpack('<B', readData)[0]
-        console.log(length)
+        console.log('len is ', length)
+
         if (length > 127) {
             length = struct.unpack(
                 '<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)
     }
 }
@@ -46,4 +51,4 @@ class ConnectionTCPAbridged extends Connection {
 module.exports = {
     ConnectionTCPAbridged,
     AbridgedPacketCodec,
-}
+}

+ 16 - 4
gramjs/network/connection/TCPObfuscated.js

@@ -10,6 +10,9 @@ class ObfuscatedIO {
         this.connection = connection.socket
         const res = this.initHeader(connection.PacketCodecClass)
         this.header = res.random
+        console.log(this.header.toString('hex'))
+        console.log(this.header.toString('hex').length)
+
         this._encrypt = res.encryptor
         this._decrypt = res.decryptor
     }
@@ -22,7 +25,7 @@ class ObfuscatedIO {
 
         // eslint-disable-next-line no-constant-condition
         while (true) {
-            random = generateRandomBytes(64)
+            random = Buffer.from('dbf538959e7eed8a5b432e6b6c446424a126f29fcfea79ccefd803923b7d70c2118f86ecfc922e5e7e1938df06c956dab0b51ded5110ec598dc7fefcacd0b514', 'hex')// generateRandomBytes(64)
             if (random[0] !== 0xef && !(random.slice(4, 8).equals(Buffer.alloc(4)))) {
                 let ok = true
                 for (const key of keywords) {
@@ -37,8 +40,9 @@ class ObfuscatedIO {
             }
         }
         random = random.toJSON().data
-        const randomReversed = Buffer.from(random.slice(7, 55)).reverse()
 
+        const randomReversed = Buffer.from(random.slice(8, 56)).reverse()
+        console.log(randomReversed.toString('hex'))
         // Encryption has "continuous buffer" enabled
         const encryptKey = Buffer.from(random.slice(8, 40))
         const encryptIv = Buffer.from(random.slice(40, 56))
@@ -46,6 +50,11 @@ class ObfuscatedIO {
         const decryptIv = Buffer.from(randomReversed.slice(32, 48))
         const encryptor = new AESModeCTR(encryptKey, encryptIv)
         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([
             Buffer.from(random.slice(0, 56)), packetCodec.obfuscateTag, Buffer.from(random.slice(60)),
         ])
@@ -57,11 +66,14 @@ class ObfuscatedIO {
 
     async 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)
     }
 
     write(data) {
-        this.connection.send(this._encrypt.encrypt(data))
+        this.connection.write(this._encrypt.encrypt(data))
     }
 }
 
@@ -72,4 +84,4 @@ class ConnectionTCPObfuscated extends ObfuscatedConnection {
 
 module.exports = {
     ConnectionTCPObfuscated,
-}
+}