forked from teamgram/teamgram-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
message.go
382 lines (318 loc) · 9.57 KB
/
message.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
// Copyright (c) 2018-present, NebulaChat Studio (https://nebula.chat).
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Author: Benqi ([email protected])
package mtproto
import (
"bytes"
"encoding/binary"
"encoding/hex"
"fmt"
"github.com/golang/glog"
"github.com/nebula-chat/chatengine/pkg/crypto"
"reflect"
)
const (
QUICK_ACKID = iota
UNENCRYPTED_MESSAGE
ENCRYPTED_MESSAGE
)
type MTProtoMessage interface {
// encode([]byte) ([]byte, error)
// decode([]byte) error
// MessageType() int
}
type QuickAckMessage struct {
ackId int32
}
func (m *QuickAckMessage) MessageType() int {
return QUICK_ACKID
}
func (m *QuickAckMessage) encode() ([]byte, error) {
return nil, nil
}
func (m *QuickAckMessage) decode(b []byte) error {
if len(b) != 4 {
return fmt.Errorf("Message len: %d (need 4)", len(b))
}
m.ackId = int32(binary.LittleEndian.Uint32(b))
return nil
}
type UnencryptedMessage struct {
NeedAck bool
// authKeyId int64
MessageId int64
// messageDataLength int32
// messageData []byte
// classID int32
Object TLObject
}
func (m *UnencryptedMessage) MessageType() int {
return UNENCRYPTED_MESSAGE
}
func (m *UnencryptedMessage) Encode() []byte {
buf, _ := m.encode()
return buf
}
func (m *UnencryptedMessage) EncodeToLayer(int) []byte {
buf, _ := m.encode()
return buf
}
func (m *UnencryptedMessage) encode() ([]byte, error) {
x := NewEncodeBuf(512)
x.Long(0)
m.MessageId = GenerateMessageId()
x.Long(m.MessageId)
if m.Object == nil {
x.Int(0)
} else {
b := m.Object.Encode()
x.Int(int32(len(b)))
x.Bytes(b)
}
return x.buf, nil
}
func (m *UnencryptedMessage) Decode(b []byte) error {
return m.decode(b)
}
func (m *UnencryptedMessage) decode(b []byte) error {
dbuf := NewDecodeBuf(b)
// m.authKeyId = dbuf.Long()
m.MessageId = dbuf.Long()
// glog.Info("messageId:", m.messageId)
// mod := m.messageId & 3
// if mod != 1 && mod != 3 {
// return fmt.Errorf("Wrong bits of message_id: %d", mod)
// }
messageLen := dbuf.Int()
if messageLen < 4 {
return fmt.Errorf("message len(%d) < 4", messageLen)
}
// glog.Info("messageLen:", m.messageId)
if int(messageLen) != dbuf.size-12 {
return fmt.Errorf("message len: %d (need %d)", messageLen, dbuf.size-12)
}
m.Object = dbuf.Object()
if m.Object == nil {
return fmt.Errorf("decode object is nil")
}
// proto.Message()
// glog.Info("Recved object: ", m.Object.(proto.Message).String())
return dbuf.err
}
////////////////////////////////////////////////////////////////////////////////////////////
// MsgDetailedInfo
type MsgDetailedInfoContainer struct {
Message *EncryptedMessage2
}
////////////////////////////////////////////////////////////////////////////////////////////
// TODO(@benqi): 将Encrypt和Descrypt移到底层
type EncryptedMessage2 struct {
authKeyId int64
NeedAck bool
msgKey []byte
Salt int64
SessionId int64
MessageId int64
SeqNo int32
Object TLObject
}
func NewEncryptedMessage2(authKeyId int64) *EncryptedMessage2 {
return &EncryptedMessage2{
authKeyId: authKeyId,
}
}
func (m *EncryptedMessage2) String() string {
return fmt.Sprintf("{auth_key_id: %d. salt: %d, session_id: %d, message_id: %d, seq_no: %d, object: %v}",
m.authKeyId, m.Salt, m.SessionId, m.MessageId, m.SeqNo, reflect.TypeOf(m.Object))
}
func (m *EncryptedMessage2) MessageType() int {
return ENCRYPTED_MESSAGE
}
func (m *EncryptedMessage2) Encode(authKeyId int64, authKey []byte) ([]byte, error) {
buf, err := m.encode(authKeyId, authKey)
return buf, err
}
func (m *EncryptedMessage2) EncodeToLayer(authKeyId int64, authKey []byte, layer int) ([]byte, error) {
buf, err := m.encodeToLayer(authKeyId, authKey, layer)
return buf, err
}
func (m *EncryptedMessage2) encodeToLayer(authKeyId int64, authKey []byte, layer int) ([]byte, error) {
objData := m.Object.EncodeToLayer(layer)
var additionalSize = (32 + len(objData)) % 16
if additionalSize != 0 {
additionalSize = 16 - additionalSize
}
if MTPROTO_VERSION == 2 && additionalSize < 12 {
additionalSize += 16
}
x := NewEncodeBuf(32 + len(objData) + additionalSize)
// x.Long(authKeyId)
// msgKey := make([]byte, 16)
// x.Bytes(msgKey)
x.Long(m.Salt)
x.Long(m.SessionId)
if m.MessageId == 0 {
m.MessageId = GenerateMessageId()
}
x.Long(m.MessageId)
x.Int(m.SeqNo)
x.Int(int32(len(objData)))
x.Bytes(objData)
x.Bytes(crypto.GenerateNonce(additionalSize))
// glog.Info("Encode object: ", m.Object)
encryptedData, _ := m.encrypt(authKey, x.buf, len(objData))
x2 := NewEncodeBuf(56 + len(objData) + additionalSize)
x2.Long(authKeyId)
x2.Bytes(m.msgKey)
x2.Bytes(encryptedData)
// glog.Info(x2.buf)
return x2.buf, nil
}
func (m *EncryptedMessage2) encode(authKeyId int64, authKey []byte) ([]byte, error) {
objData := m.Object.Encode()
var additionalSize = (32 + len(objData)) % 16
if additionalSize != 0 {
additionalSize = 16 - additionalSize
}
if MTPROTO_VERSION == 2 && additionalSize < 12 {
additionalSize += 16
}
x := NewEncodeBuf(32 + len(objData) + additionalSize)
// x.Long(authKeyId)
// msgKey := make([]byte, 16)
// x.Bytes(msgKey)
x.Long(m.Salt)
x.Long(m.SessionId)
if m.MessageId == 0 {
m.MessageId = GenerateMessageId()
}
x.Long(m.MessageId)
x.Int(m.SeqNo)
x.Int(int32(len(objData)))
x.Bytes(objData)
x.Bytes(crypto.GenerateNonce(additionalSize))
// glog.Info("Encode object: ", m.Object)
encryptedData, _ := m.encrypt(authKey, x.buf, len(objData))
x2 := NewEncodeBuf(56 + len(objData) + additionalSize)
x2.Long(authKeyId)
x2.Bytes(m.msgKey)
x2.Bytes(encryptedData)
// glog.Info(x2.buf)
return x2.buf, nil
}
func (m *EncryptedMessage2) Decode(authKeyId int64, authKey, b []byte) error {
_ = authKeyId
return m.decode(authKey, b)
}
func (m *EncryptedMessage2) decode(authKey []byte, b []byte) error {
msgKey := b[:16]
// aesKey, aesIV := generateMessageKey(msgKey, authKey, false)
// x, err := doAES256IGEdecrypt(b[16:], aesKey, aesIV)
x, err := m.decrypt(msgKey, authKey, b[16:])
if err != nil {
return err
}
dbuf := NewDecodeBuf(x)
m.Salt = dbuf.Long() // salt
m.SessionId = dbuf.Long() // session_id
m.MessageId = dbuf.Long()
// mod := m.messageId & 3
// if mod != 1 && mod != 3 {
// return fmt.Errorf("Wrong bits of message_id: %d", mod)
// }
m.SeqNo = dbuf.Int()
messageLen := dbuf.Int()
if int(messageLen) > dbuf.size-32 {
// return fmt.Errorf("Message len: %d (need less than %d)", messagxeLen, dbuf.size-32)
}
m.Object = dbuf.Object()
if m.Object == nil {
glog.Errorf("salt: %d, sessionId: %d, messageId: %d, seqNo: %d, messageLen: %d", m.Salt, m.SessionId, m.MessageId, m.SeqNo, messageLen)
return fmt.Errorf("decode object is nil")
}
// glog.Info("Recved object: ", m.Object.String())
return nil
}
func (m *EncryptedMessage2) decrypt(msgKey, authKey, data []byte) ([]byte, error) {
// dbuf := NewDecodeBuf(data)
// m.authKeyId = dbuf.Long()
// msgKey := dbuf.Bytes(16)
var dataLen = uint32(len(data))
// 创建aesKey, aesIV
aesKey, aesIV := generateMessageKey(msgKey, authKey, false)
d := crypto.NewAES256IGECryptor(aesKey, aesIV)
x, err := d.Decrypt(data)
if err != nil {
glog.Error("descrypted data error: ", err)
return nil, err
}
//// 校验解密后的数据合法性
messageLen := binary.LittleEndian.Uint32(x[28:])
// glog.Info("descrypt - messageLen = ", messageLen)
if messageLen+32 > dataLen {
// return fmt.Errorf("Message len: %d (need less than %d)", messageLen, dbuf.size-32)
err = fmt.Errorf("descrypted data error: Wrong message length %d", messageLen)
glog.Error(err)
return nil, err
}
messageKey := make([]byte, 96)
switch MTPROTO_VERSION {
case 2:
tmpData := make([]byte, 0, 32+dataLen)
tmpData = append(tmpData, authKey[88:88+32]...)
tmpData = append(tmpData, x[:dataLen]...)
copy(messageKey, crypto.Sha256Digest(tmpData))
default:
copy(messageKey[4:], crypto.Sha1Digest(x[:32+messageLen]))
}
if !bytes.Equal(messageKey[8:8+16], msgKey[:16]) {
err = fmt.Errorf("descrypted data error: (data: %s, aesKey: %s, aseIV: %s, authKeyId: %d, authKey: %s), msgKey verify error, sign: %s, msgKey: %s",
hex.EncodeToString(data[:64]),
hex.EncodeToString(aesKey),
hex.EncodeToString(aesIV),
m.authKeyId,
hex.EncodeToString(authKey[88:88+32]),
hex.EncodeToString(messageKey[8:8+16]),
hex.EncodeToString(msgKey[:16]))
glog.Error(err)
return nil, err
}
return x, nil
}
func (m *EncryptedMessage2) encrypt(authKey []byte, data []byte, messageSize int) ([]byte, error) {
messageKey := make([]byte, 32)
switch MTPROTO_VERSION {
case 2:
tmpData := make([]byte, 0, 32+len(data))
tmpData = append(tmpData, authKey[88+8:88+8+32]...)
tmpData = append(tmpData, data...)
copy(messageKey, crypto.Sha256Digest(tmpData))
default:
copy(messageKey[4:], crypto.Sha1Digest(data[:32+messageSize]))
}
// glog.Info(data[:messageSize])
// glog.Info(messageKey)
// copy(message_key[8:], )
// memcpy(p_data + 8, message_key + 8, 16);
aesKey, aesIV := generateMessageKey(messageKey[8:8+16], authKey, true)
e := crypto.NewAES256IGECryptor(aesKey, aesIV)
x, err := e.Encrypt(data)
if err != nil {
glog.Error("Encrypt data error: ", err)
return nil, err
}
m.msgKey = messageKey[8 : 8+16]
return x, nil
}