-
-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathhandshake.go
More file actions
executable file
·408 lines (352 loc) · 11.7 KB
/
handshake.go
File metadata and controls
executable file
·408 lines (352 loc) · 11.7 KB
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
// Copyright (c) 2025 @AmarnathCJD
package gogram
import (
"bytes"
"context"
"encoding/binary"
"encoding/hex"
"fmt"
"math/big"
"time"
"errors"
ige "github.com/amarnathcjd/gogram/internal/aes_ige"
"github.com/amarnathcjd/gogram/internal/encoding/tl"
"github.com/amarnathcjd/gogram/internal/keys"
"github.com/amarnathcjd/gogram/internal/math"
"github.com/amarnathcjd/gogram/internal/mtproto/objects"
"github.com/amarnathcjd/gogram/internal/session"
"github.com/amarnathcjd/gogram/internal/utils"
)
// https://core.telegram.org/mtproto/auth_key
func (m *MTProto) makeAuthKey() error {
return m.makeAuthKeyInternal(0)
}
func (m *MTProto) makeTempAuthKey(expiresIn int32) error {
if expiresIn <= 0 {
expiresIn = 24 * 60 * 60
}
return m.makeAuthKeyInternal(expiresIn)
}
const maxAuthKeyDecryptRetries = 5
func (m *MTProto) makeAuthKeyInternal(expiresIn int32) error {
for attempt := 0; ; attempt++ {
err := m.makeAuthKeyOnce(expiresIn)
if err == nil {
return nil
}
if !errors.Is(err, errAuthKeyDecryptRetry) {
return err
}
if attempt+1 >= maxAuthKeyDecryptRetries {
return fmt.Errorf("auth key generation: decrypt failed after %d attempts: %w", maxAuthKeyDecryptRetries, err)
}
m.Logger.WithError(err).Debugf("decrypt failed - retrying auth key generation (attempt %d/%d)", attempt+2, maxAuthKeyDecryptRetries)
}
}
var errAuthKeyDecryptRetry = errors.New("auth key decrypt failed")
func (m *MTProto) makeAuthKeyOnce(expiresIn int32) error {
isTemp := expiresIn > 0
m.serviceModeActivated = true
defer func() { m.serviceModeActivated = false }()
// telegram sometimes gvs wrong nonce, idk
const maxNonceRetries = 5
nonceRetries := 0
var nonceFirst *tl.Int128
var res *objects.ResPQ
var err error
for {
nonceFirst = tl.RandomInt128()
if m.cdn {
res, err = m.reqPQMulti(nonceFirst)
} else {
res, err = m.reqPQ(nonceFirst)
}
if err != nil {
return fmt.Errorf("reqPQ: %w", err)
}
if nonceFirst.Cmp(res.Nonce.Int) == 0 {
break
}
nonceRetries++
if nonceRetries >= maxNonceRetries {
return fmt.Errorf("reqPQ: nonce mismatch after %d retries (%v, %v)", maxNonceRetries, nonceFirst, res.Nonce)
}
time.Sleep(200 * time.Millisecond)
}
found := false
for _, b := range res.Fingerprints {
if m.cdn {
for _, key := range m.cdnKeys {
if uint64(b) == binary.LittleEndian.Uint64(keys.RSAFingerprint(key)) {
found = true
m.publicKey = key
break
}
}
}
if uint64(b) == binary.LittleEndian.Uint64(keys.RSAFingerprint(m.publicKey)) {
found = true
break
}
}
if !found {
return fmt.Errorf("reqPQ: no matching fingerprint")
}
pq := big.NewInt(0).SetBytes(res.Pq)
p, q := math.Factorize(pq)
if p == nil || q == nil {
p, q = math.SplitPQ(pq)
}
nonceSecond := tl.RandomInt256()
nonceServer := res.ServerNonce
var message []byte
if isTemp {
message, err = tl.Marshal(&objects.PQInnerDataTempDc{
Pq: res.Pq,
P: p.Bytes(),
Q: q.Bytes(),
Nonce: nonceFirst,
ServerNonce: nonceServer,
NewNonce: nonceSecond,
Dc: int32(m.GetDC()),
ExpiresIn: expiresIn,
})
} else {
message, err = tl.Marshal(&objects.PQInnerData{
Pq: res.Pq,
P: p.Bytes(),
Q: q.Bytes(),
Nonce: nonceFirst,
ServerNonce: nonceServer,
NewNonce: nonceSecond,
})
}
if err != nil {
m.Logger.WithField("error", err).Debug("makeAuthKey: failed to marshal pq inner data")
return err
}
hashAndMsg := make([]byte, 255)
copy(hashAndMsg, append(utils.Sha1(string(message)), message...))
encryptedMessage, err := math.DoRSAencrypt(hashAndMsg, m.publicKey)
if err != nil {
return fmt.Errorf("rsa encrypt: %w", err)
}
keyFingerprint := int64(binary.LittleEndian.Uint64(keys.RSAFingerprint(m.publicKey)))
dhResponse, err := m.reqDHParams(nonceFirst, nonceServer, p.Bytes(), q.Bytes(), keyFingerprint, encryptedMessage)
if err != nil {
return fmt.Errorf("reqDHParams: %w", err)
}
dhParams, ok := dhResponse.(*objects.ServerDHParamsOk)
if !ok {
return fmt.Errorf("reqDHParams: invalid response")
}
if nonceFirst.Cmp(dhParams.Nonce.Int) != 0 {
return fmt.Errorf("reqDHParams: nonce mismatch")
}
if nonceServer.Cmp(dhParams.ServerNonce.Int) != 0 {
return fmt.Errorf("reqDHParams: server nonce mismatch")
}
decodedMessage, err := ige.DecryptMessageWithTempKeys(dhParams.EncryptedAnswer, nonceSecond.Int, nonceServer.Int)
if err != nil {
return fmt.Errorf("%w: %w", errAuthKeyDecryptRetry, err)
}
data, err := tl.DecodeUnknownObject(decodedMessage)
if err != nil {
return fmt.Errorf("decode: %w", err)
}
dhi, ok := data.(*objects.ServerDHInnerData)
if !ok {
return fmt.Errorf("decode: invalid response")
}
if nonceFirst.Cmp(dhi.Nonce.Int) != 0 {
return fmt.Errorf("decode: nonce mismatch")
}
if nonceServer.Cmp(dhi.ServerNonce.Int) != 0 {
return fmt.Errorf("decode: server nonce mismatch")
}
_, gB, gAB := math.MakeGAB(dhi.G, big.NewInt(0).SetBytes(dhi.GA), big.NewInt(0).SetBytes(dhi.DhPrime))
authKey := gAB.Bytes()
if authKey[0] == 0 {
authKey = authKey[1:]
}
t4 := make([]byte, 32+1+8)
copy(t4[0:], nonceSecond.Bytes())
t4[32] = 1
copy(t4[33:], utils.Sha1Byte(authKey)[0:8])
nonceHash1 := utils.Sha1Byte(t4)[4:20]
salt := make([]byte, tl.LongLen)
copy(salt, nonceSecond.Bytes()[:8])
math.XOR(salt, nonceServer.Bytes()[:8])
newSalt := int64(binary.LittleEndian.Uint64(salt))
clientDHData, err := tl.Marshal(&objects.ClientDHInnerData{
Nonce: nonceFirst,
ServerNonce: nonceServer,
Retry: 0,
GB: gB.Bytes(),
})
if err != nil {
m.Logger.WithField("error", err).Debug("makeAuthKey: failed to marshal client dh inner data")
return err
}
encryptedMessage, err = ige.EncryptMessageWithTempKeys(clientDHData, nonceSecond.Int, nonceServer.Int)
if err != nil {
return errors.New("dh: " + err.Error())
}
dhGenStatus, err := m.setClientDHParams(nonceFirst, nonceServer, encryptedMessage)
if err != nil {
return errors.New("dh: " + err.Error())
}
dhg, ok := dhGenStatus.(*objects.DHGenOk)
if !ok {
return fmt.Errorf("invalid response")
}
if nonceFirst.Cmp(dhg.Nonce.Int) != 0 {
return fmt.Errorf("handshake: Wrong nonce: %v, %v", nonceFirst, dhg.Nonce)
}
if nonceServer.Cmp(dhg.ServerNonce.Int) != 0 {
return fmt.Errorf("handshake: Wrong server_nonce: %v, %v", nonceServer, dhg.ServerNonce)
}
if !bytes.Equal(nonceHash1, dhg.NewNonceHash1.Bytes()) {
return fmt.Errorf(
"handshake: Wrong new_nonce_hash1: %v, %v",
hex.EncodeToString(nonceHash1),
hex.EncodeToString(dhg.NewNonceHash1.Bytes()),
)
}
if isTemp {
m.tempAuthKey = authKey
m.tempAuthKeyHash = utils.AuthKeyHash(authKey)
m.tempAuthExpiresAt = time.Now().Unix() + int64(expiresIn)
m.serverSalt.Store(newSalt)
} else {
m.SetAuthKey(authKey)
m.serverSalt.Store(newSalt)
m.encrypted.Store(true)
if err := m.SaveSession(m.memorySession); err != nil {
m.Logger.WithError(err).Error("failed to save session")
}
}
return nil
}
// createTempAuthKey performs the temporary auth key handshake
func (m *MTProto) createTempAuthKey(expiresIn int32) error {
cfg := Config{
AuthKeyFile: "__pfs__temp",
AuthAESKey: "",
SessionStorage: session.NewInMemory(),
MemorySession: true,
AppID: m.appID,
EnablePFS: false,
ServerHost: m.GetAddr(),
PublicKey: m.publicKey,
DataCenter: m.GetDC(),
Logger: m.Logger.Clone().WithPrefix("gogram [mtp-pfs]"),
Proxy: m.proxy,
Mode: "Abridged",
Ipv6: m.IpV6,
CustomHost: true,
LocalAddr: m.localAddr,
Timeout: int(m.connConfig.Timeout.Seconds()),
ReqTimeout: int(m.reqTimeout.Seconds()),
UseWebSocket: m.useWebSocket,
UseWebSocketTLS: m.useWebSocketTLS,
}
tmp, err := NewMTProto(cfg)
if err != nil {
return fmt.Errorf("createTempAuthKey: creating temp MTProto: %w", err)
}
defer tmp.Terminate() // Ensure cleanup in all cases
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if err := tmp.connect(ctx); err != nil {
return fmt.Errorf("createTempAuthKey: connecting temp MTProto: %w", err)
}
tmp.tcpState.SetActive(true)
tmp.startReadingResponses(ctx)
if err := tmp.makeTempAuthKey(expiresIn); err != nil {
return fmt.Errorf("createTempAuthKey: makeTempAuthKey on temp connection: %w", err)
}
// Copy the generated temporary auth key and its metadata back to the main
// MTProto instance. The server salt associated with the temporary key is
// also propagated so that subsequent messages encrypted with the temp key
// use the correct salt.
m.tempAuthKey = tmp.tempAuthKey
m.tempAuthKeyHash = tmp.tempAuthKeyHash
m.tempAuthExpiresAt = tmp.tempAuthExpiresAt
m.serverSalt.Store(tmp.serverSalt.Load())
m.Logger.Debug("temporary auth key created successfully")
return nil
}
// bindTempAuthKey binds the temporary auth key to the permanent auth key using auth.bindTempAuthKey.
func (m *MTProto) bindTempAuthKey() error {
if m.tempAuthKey == nil {
return errors.New("bindTempAuthKey: tempAuthKey is nil")
}
if len(m.authKey) == 0 {
return errors.New("bindTempAuthKey: permanent authKey is nil")
}
permKeyHash := utils.AuthKeyHash(m.authKey)
permAuthKeyID := int64(binary.LittleEndian.Uint64(permKeyHash))
tempKeyHash := utils.AuthKeyHash(m.tempAuthKey)
tempAuthKeyID := int64(binary.LittleEndian.Uint64(tempKeyHash))
// Use current session ID as temp_session_id for the binding.
tempSessionID := m.sessionId.Load()
expiresAt := int32(m.tempAuthExpiresAt)
if expiresAt == 0 {
expiresAt = int32(time.Now().Unix() + 24*60*60)
}
nonce := utils.GenerateSessionID()
msgID := m.genMsgID(m.timeOffset.Load())
inner := &objects.BindAuthKeyInner{
Nonce: nonce,
TempAuthKeyID: tempAuthKeyID,
PermAuthKeyID: permAuthKeyID,
TempSessionID: tempSessionID,
ExpiresAt: expiresAt,
}
innerBytes, err := tl.Marshal(inner)
if err != nil {
return fmt.Errorf("marshal BindAuthKeyInner: %w", err)
}
// Build MTProto v1 plaintext: random:int128 + msg_id + seqno(0) + msg_len + inner.
random128 := utils.RandomBytes(16)
plaintext := make([]byte, 0, 16+8+4+4+len(innerBytes))
plaintext = append(plaintext, random128...)
buf8 := make([]byte, 8)
binary.LittleEndian.PutUint64(buf8, uint64(msgID))
plaintext = append(plaintext, buf8...)
buf4 := make([]byte, 4)
binary.LittleEndian.PutUint32(buf4, 0) // seqno = 0
plaintext = append(plaintext, buf4...)
binary.LittleEndian.PutUint32(buf4, uint32(len(innerBytes)))
plaintext = append(plaintext, buf4...)
plaintext = append(plaintext, innerBytes...)
// Encrypt binding message with permanent auth key using MTProto 1.0 helpers.
cipher, msgKey, err := ige.EncryptV1(plaintext, m.authKey)
if err != nil {
return fmt.Errorf("encrypt BindAuthKeyInner: %w", err)
}
encryptedMessage := make([]byte, 0, len(permKeyHash)+len(msgKey)+len(cipher))
encryptedMessage = append(encryptedMessage, permKeyHash...)
encryptedMessage = append(encryptedMessage, msgKey...)
encryptedMessage = append(encryptedMessage, cipher...)
params := &objects.AuthBindTempAuthKeyParams{
PermAuthKeyID: permAuthKeyID,
Nonce: nonce,
ExpiresAt: expiresAt,
EncryptedMessage: encryptedMessage,
}
// Send auth.bindTempAuthKey with the same msg_id used inside the MTProto
// v1 binding message, as required by the PFS specification.
respCh, _, err := m.sendPacketWithMsgID(params, msgID)
if err != nil {
return fmt.Errorf("auth.bindTempAuthKey: %w", err)
}
response := <-respCh
if rpcErr, ok := response.(*objects.RpcError); ok {
return fmt.Errorf("auth.bindTempAuthKey: %w", RpcErrorToNative(rpcErr))
}
// Any non-error response is treated as success; the exact Bool value is not
// critical here, as the server typically returns true on success.
return nil
}