From 97c20742362b0fdd9a924460a9cccaf257212a70 Mon Sep 17 00:00:00 2001 From: Alexander Zinchuk Date: Sat, 8 May 2021 22:41:34 +0300 Subject: [PATCH] GramJs: Add missing security checks (#1065) --- src/lib/gramjs/network/MTProtoState.js | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/src/lib/gramjs/network/MTProtoState.js b/src/lib/gramjs/network/MTProtoState.js index 9f66f007c..83ef93812 100644 --- a/src/lib/gramjs/network/MTProtoState.js +++ b/src/lib/gramjs/network/MTProtoState.js @@ -153,7 +153,12 @@ class MTProtoState { if (body.length < 8) { throw new InvalidBufferError(body); } - + if (body.length < 0) { // length needs to be positive + throw new SecurityError('Server replied with negative length'); + } + if (body.length % 4 !== 0) { + throw new SecurityError('Server replied with length not divisible by 4'); + } // TODO Check salt,sessionId, and sequenceNumber const keyId = Helpers.readBigIntFromBuffer(body.slice(0, 8)); if (keyId.neq(this.authKey.keyId)) { @@ -180,13 +185,19 @@ class MTProtoState { const reader = new BinaryReader(body); reader.readLong(); // removeSalt const serverId = reader.readLong(); - if (serverId !== this.id) { - // throw new SecurityError('Server replied with a wrong session ID'); + if (!serverId.eq(this.id)) { + throw new SecurityError('Server replied with a wrong session ID'); } const remoteMsgId = reader.readLong(); const remoteSequence = reader.readInt(); - reader.readInt(); // msgLen for the inner object, padding ignored + const containerLen = reader.readInt(); // msgLen for the inner object, padding ignored + const diff = body.length - containerLen; + // We want to check if it's between 12 and 1024 + // https://core.telegram.org/mtproto/security_guidelines#checking-message-length + if (diff < 12 || diff > 1024) { + throw new SecurityError('Server replied with the wrong message padding'); + } // We could read msg_len bytes and use those in a new reader to read // the next TLObject without including the padding, but since the