-
-
Notifications
You must be signed in to change notification settings - Fork 139
/
client_flow.go
253 lines (223 loc) · 8.25 KB
/
client_flow.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
package exchange
import (
"context"
"crypto/rand"
"crypto/rsa"
"math/big"
"go.uber.org/zap"
"github.com/gotd/td/internal/proto"
"golang.org/x/xerrors"
"github.com/gotd/td/bin"
"github.com/gotd/td/internal/crypto"
"github.com/gotd/td/internal/mt"
)
// Run runs client-side flow.
func (c ClientExchange) Run(ctx context.Context) (ClientExchangeResult, error) {
// 1. DH exchange initiation.
nonce, err := crypto.RandInt128(c.rand)
if err != nil {
return ClientExchangeResult{}, xerrors.Errorf("client nonce generation: %w", err)
}
b := new(bin.Buffer)
c.log.Debug("Sending ReqPqMultiRequest")
if err := c.writeUnencrypted(ctx, b, &mt.ReqPqMultiRequest{Nonce: nonce}); err != nil {
return ClientExchangeResult{}, xerrors.Errorf("write ReqPqMultiRequest: %w", err)
}
// 2. Server sends response of the form
// resPQ#05162463 nonce:int128 server_nonce:int128 pq:string server_public_key_fingerprints:Vector long = ResPQ;
var res mt.ResPQ
if err := c.readUnencrypted(ctx, b, &res); err != nil {
return ClientExchangeResult{}, xerrors.Errorf("read ResPQ response: %w", err)
}
c.log.Debug("Received server ResPQ")
if res.Nonce != nonce {
return ClientExchangeResult{}, xerrors.New("ResPQ nonce mismatch")
}
// Selecting first public key that match fingerprint.
var selectedPubKey *rsa.PublicKey
Loop:
for _, fingerprint := range res.ServerPublicKeyFingerprints {
for _, key := range c.keys {
if fingerprint == crypto.RSAFingerprint(key) {
selectedPubKey = key
break Loop
}
}
}
if selectedPubKey == nil {
return ClientExchangeResult{}, xerrors.New("unable to select public key")
}
// The pq is a representation of a natural number (in binary big endian format).
// SetBytes is also big endian.
pq := big.NewInt(0).SetBytes(res.Pq)
// Normally pq is less than or equal to 2^63-1.
pqMax := big.NewInt(0).Exp(big.NewInt(2), big.NewInt(63), nil)
if pq.Cmp(pqMax) > 0 {
return ClientExchangeResult{}, xerrors.New("server provided bad pq")
}
start := c.clock.Now()
// 3. Client decomposes pq into prime factors such that p < q.
// Performing proof of work.
p, q, err := crypto.DecomposePQ(pq, c.rand)
if err != nil {
return ClientExchangeResult{}, xerrors.Errorf("decompose pq: %w", err)
}
c.log.Debug("PQ decomposing complete", zap.Duration("took", c.clock.Now().Sub(start)))
// Make a copy of p and q values to reduce allocations.
pBytes := p.Bytes()
qBytes := q.Bytes()
// 4. Client sends query to server.
// req_DH_params#d712e4be nonce:int128 server_nonce:int128 p:string q:string
// public_key_fingerprint:long encrypted_data:string = Server_DH_Params
newNonce, err := crypto.RandInt256(c.rand)
if err != nil {
return ClientExchangeResult{}, xerrors.Errorf("generate new nonce: %w", err)
}
pqInnerData := &mt.PQInnerData{
Pq: res.Pq,
Nonce: nonce,
NewNonce: newNonce,
ServerNonce: res.ServerNonce,
P: pBytes,
Q: qBytes,
}
b.Reset()
if err := pqInnerData.Encode(b); err != nil {
return ClientExchangeResult{}, err
}
// `encrypted_data := RSA (data_with_hash, server_public_key);`
encryptedData, err := crypto.RSAEncryptHashed(b.Buf, selectedPubKey, c.rand)
if err != nil {
return ClientExchangeResult{}, xerrors.Errorf("encrypted_data generation: %w", err)
}
reqDHParams := &mt.ReqDHParamsRequest{
Nonce: nonce,
ServerNonce: res.ServerNonce,
P: pBytes,
Q: qBytes,
PublicKeyFingerprint: crypto.RSAFingerprint(selectedPubKey),
EncryptedData: encryptedData,
}
c.log.Debug("Sending ReqDHParamsRequest")
if err := c.writeUnencrypted(ctx, b, reqDHParams); err != nil {
return ClientExchangeResult{}, xerrors.Errorf("write ReqDHParamsRequest: %w", err)
}
// 5. Server responds with Server_DH_Params.
if err := c.conn.Recv(ctx, b); err != nil {
return ClientExchangeResult{}, xerrors.Errorf("read ServerDHParams message: %w", err)
}
c.log.Debug("Received server ServerDHParams")
var plaintextMsg proto.UnencryptedMessage
if err := plaintextMsg.Decode(b); err != nil {
return ClientExchangeResult{}, xerrors.Errorf("decode ServerDHParams message: %w", err)
}
b.ResetTo(plaintextMsg.MessageData)
dhParams, err := mt.DecodeServerDHParams(b)
if err != nil {
return ClientExchangeResult{}, err
}
switch p := dhParams.(type) {
case *mt.ServerDHParamsOk:
// Success.
if p.Nonce != nonce {
return ClientExchangeResult{}, xerrors.New("ServerDHParamsOk nonce mismatch")
}
key, iv := crypto.TempAESKeys(newNonce.BigInt(), res.ServerNonce.BigInt())
// Decrypting inner data.
data, err := crypto.DecryptExchangeAnswer(p.EncryptedAnswer, key, iv)
if err != nil {
return ClientExchangeResult{}, xerrors.Errorf("exchange answer decrypt: %w", err)
}
b.ResetTo(data)
innerData := mt.ServerDHInnerData{}
if err := innerData.Decode(b); err != nil {
return ClientExchangeResult{}, err
}
dhPrime := big.NewInt(0).SetBytes(innerData.DhPrime)
g := big.NewInt(int64(innerData.G))
gA := big.NewInt(0).SetBytes(innerData.GA)
// 6. Random number b is computed:
randMax := big.NewInt(0).SetBit(big.NewInt(0), 2048, 1)
bParam, err := rand.Int(c.rand, randMax)
if err != nil {
return ClientExchangeResult{}, xerrors.Errorf("number b generation: %w", err)
}
// g_b = g^b mod dh_prime
gB := big.NewInt(0).Exp(g, bParam, dhPrime)
// Checking key exchange parameters.
if err := crypto.CheckDHParams(dhPrime, g, gA, gB); err != nil {
return ClientExchangeResult{}, xerrors.Errorf("key exchange failed: invalid params: %w", err)
}
clientInnerData := mt.ClientDHInnerData{
ServerNonce: innerData.ServerNonce,
Nonce: innerData.Nonce,
GB: gB.Bytes(),
// first attempt
RetryID: 0,
}
b.Reset()
if err := clientInnerData.Encode(b); err != nil {
return ClientExchangeResult{}, err
}
clientEncrypted, err := crypto.EncryptExchangeAnswer(c.rand, b.Buf, key, iv)
if err != nil {
return ClientExchangeResult{}, xerrors.Errorf("exchange answer encrypt: %w", err)
}
setParamsReq := &mt.SetClientDHParamsRequest{
Nonce: nonce,
ServerNonce: reqDHParams.ServerNonce,
EncryptedData: clientEncrypted,
}
c.log.Debug("Sending SetClientDHParamsRequest")
if err := c.writeUnencrypted(ctx, b, setParamsReq); err != nil {
return ClientExchangeResult{}, xerrors.Errorf("write SetClientDHParamsRequest: %w", err)
}
// 7. Computing auth_key using formula (g_a)^b mod dh_prime
authKey := big.NewInt(0).Exp(gA, bParam, dhPrime)
b.Reset()
if err := c.conn.Recv(ctx, b); err != nil {
return ClientExchangeResult{}, xerrors.Errorf("read DhGen message: %w", err)
}
c.log.Debug("Received server DhGen")
if err := plaintextMsg.Decode(b); err != nil {
return ClientExchangeResult{}, xerrors.Errorf("decode DhGen message: %w", err)
}
b.ResetTo(plaintextMsg.MessageData)
dhSetRes, err := mt.DecodeSetClientDHParamsAnswer(b)
if err != nil {
return ClientExchangeResult{}, xerrors.Errorf("decode DhGen answer: %w", err)
}
switch v := dhSetRes.(type) {
case *mt.DhGenOk: // dh_gen_ok#3bcbf734
var key crypto.Key
authKey.FillBytes(key[:])
authKeyID := key.ID()
// Checking received hash.
nonceHash1 := crypto.NonceHash1(newNonce, key)
serverSalt := crypto.ServerSalt(newNonce, v.ServerNonce)
if nonceHash1 != v.NewNonceHash1 {
return ClientExchangeResult{}, xerrors.New("key exchange verification failed: hash mismatch")
}
// Generating new session id and salt.
sessionID, err := crypto.NewSessionID(c.rand)
if err != nil {
return ClientExchangeResult{}, err
}
return ClientExchangeResult{
AuthKey: crypto.AuthKey{Value: key, ID: authKeyID},
SessionID: sessionID,
ServerSalt: serverSalt,
}, nil
case *mt.DhGenRetry: // dh_gen_retry#46dc1fb9
return ClientExchangeResult{}, xerrors.Errorf("retry required: %x", v.NewNonceHash2)
case *mt.DhGenFail: // dh_gen_fail#a69dae02
return ClientExchangeResult{}, xerrors.Errorf("dh_hen_fail: %x", v.NewNonceHash3)
default:
return ClientExchangeResult{}, xerrors.Errorf("unexpected SetClientDHParamsRequest result %T", v)
}
case *mt.ServerDHParamsFail:
return ClientExchangeResult{}, xerrors.New("server respond with server_DH_params_fail")
default:
return ClientExchangeResult{}, xerrors.Errorf("unexpected ReqDHParamsRequest result %T", p)
}
}