-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.go
369 lines (318 loc) · 8.75 KB
/
game.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
package vikebot
import (
"bufio"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/tls"
"encoding/base64"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"strconv"
)
type roundInformation struct {
Ticket string `json:"ticket"`
AesKey string `json:"aes_key"`
IPV4 string `json:"ipv4"`
IPV6 string `json:"ipv6"`
Port int `json:"port"`
Error *string `json:"error"`
}
// Game manages all connections and authorizations for the client. Also holds
// the state of the active player
type Game struct {
conn *net.Conn
buf *bufio.Reader
gcm cipher.AEAD
pc uint32
Encrypted bool
Player *Player
}
// Close frees all local infos about the game and closes all remote connections
// to any servers or APIs.
func (g *Game) Close() error {
g.buf = nil
g.gcm = nil
g.Encrypted = false
g.Player = nil
conn := g.conn
g.conn = nil
return (*conn).Close()
}
func (g Game) encrypt(plain []byte) (cipher []byte, err error) {
// Generate random nonce value for this encryption round
nonce := make([]byte, g.gcm.NonceSize())
_, err = io.ReadFull(rand.Reader, nonce)
if err != nil {
return nil, fmt.Errorf("vikebot: unable to create nonce value for encryption, err = %v", err)
}
// Seal our plaintext
cipherBuf := g.gcm.Seal(nil, nonce, plain, nil)
// Append nonce at the front
cipherBuf = append(nonce, cipherBuf...)
return cipherBuf, nil
}
func (g Game) encrypt64(plain []byte) (cipher64 []byte, err error) {
// encrypt plain content
cipher, err := g.encrypt(plain)
if err != nil {
return nil, err
}
// convert the cipher to it's base64 equivalent using raw base64 encoding
base64Cipher := make([]byte, base64.RawStdEncoding.EncodedLen(len(cipher)))
base64.RawStdEncoding.Encode(base64Cipher, cipher)
return base64Cipher, nil
}
func (g Game) encryptStr(plain string) (cipher string, err error) {
cipherBuf, err := g.encrypt([]byte(plain))
if err != nil {
return "", err
}
return base64.RawStdEncoding.EncodeToString(cipherBuf), err
}
func (g Game) decrypt(cipher []byte) (plain []byte, err error) {
nonce := cipher[0:g.gcm.NonceSize()]
ciphertext := cipher[g.gcm.NonceSize():]
plain, err = g.gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, err
}
return
}
func (g Game) decrypt64(cipher64 []byte) (plain []byte, err error) {
cipher := make([]byte, base64.RawStdEncoding.DecodedLen(len(cipher64)))
_, err = base64.RawStdEncoding.Decode(cipher, cipher64)
if err != nil {
return nil, err
}
return g.decrypt(cipher)
}
func (g Game) decryptStr(cipher string) (plain string, err error) {
cipherBuf, err := base64.RawStdEncoding.DecodeString(cipher)
if err != nil {
return "", err
}
plainBuf, err := g.decrypt(cipherBuf)
if err != nil {
return "", err
}
return string(plainBuf), nil
}
func (g *Game) write(buf []byte) error {
if g.Encrypted {
cipher, err := g.encrypt64(buf)
if err != nil {
return fmt.Errorf("vikebot: encryption failed - %s", err.Error())
}
buf = cipher
}
buf = append(buf, '\n')
_, err := (*g.conn).Write(buf)
if err != nil {
return fmt.Errorf("vikebot: %s", err.Error())
}
return nil
}
func (g *Game) read(extractPt bool) (pt string, buf []byte, err error) {
buf, err = g.buf.ReadBytes('\n')
if err != nil {
return "", nil, err
}
if g.Encrypted {
buf = buf[:len(buf)-1]
plain, err := g.decrypt64(buf)
if err != nil {
return "", nil, fmt.Errorf("vikebot: unsecure connection - %s", err.Error())
}
buf = plain
}
if !extractPt {
return "", buf, nil
}
var t typePacket
err = json.Unmarshal(buf, &t)
if err != nil {
return "", nil, fmt.Errorf("vikebot: %s", err.Error())
}
return t.Type, buf, nil
}
func (g *Game) trivialAction(pt string, packet []byte) error {
_, err := g.trivialActionResp(pt, packet)
return err
}
func (g *Game) trivialActionResp(pt string, packet []byte) (buf []byte, err error) {
// Send packet
err = g.write(packet)
if err != nil {
return nil, err
}
// Read response, unmarshal it and extract error message
_, buf, err = g.read(false)
if err != nil {
return nil, err
}
var resp response
err = json.Unmarshal(buf, &resp)
if err != nil {
return nil, fmt.Errorf("vikebot: %s", err.Error())
}
// Check for server errors or forbidden messages
if resp.Type != pt {
if resp.Error != nil && (resp.Type == "unknown" || resp.Type == "forbidden") {
return nil, fmt.Errorf("vikebot: %s", *resp.Error)
}
return nil, errors.New("vikebot: invalid server response. unexpected packet")
}
// Check for pc increase if connection is encrypted
if g.Encrypted {
g.pc++
if resp.Pc == nil {
return nil, errors.New("vikebot: invalid server response. missing pc")
} else if *resp.Pc != g.pc {
return nil, errors.New("vikebot: invalid server response. pc mismatch")
}
}
return buf, nil
}
// Join exchanges the `authtoken` for server credentials and establishes a
// secure connection (`AES256-GCM`) to the game-server. Afterwards it returns
// a game object containing basic infos and the player's state.
func Join(authtoken string) (g *Game, err error) {
production := true
// Exchange authtoken for round information
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: !production},
}
httpclient := &http.Client{Transport: tr}
get, err := httpclient.Get("https://api.vikebot.com/v1/roundentry/connectinfo/" + authtoken)
if err != nil {
return nil, fmt.Errorf("vikebot: %s", err.Error())
}
defer get.Body.Close()
var ri roundInformation
err = json.NewDecoder(get.Body).Decode(&ri)
if err != nil {
return nil, fmt.Errorf("vikebot: %s", err.Error())
}
if ri.Error != nil {
return nil, fmt.Errorf("vikebot: %v", *ri.Error)
}
// Get aes key and iv byte slices
keyBuf, err := base64.StdEncoding.DecodeString(ri.AesKey)
if err != nil {
return nil, fmt.Errorf("vikebot: %s", err.Error())
}
// Create aesblock
block, err := aes.NewCipher(keyBuf)
if err != nil {
return nil, fmt.Errorf("vikebot: %s", err.Error())
}
// Create gcm cipher
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, fmt.Errorf("vikebot: %s", err.Error())
}
// Open connection to game server
client, err := net.Dial("tcp", fmt.Sprintf("%s:%d", ri.IPV4, ri.Port))
if err != nil {
return nil, fmt.Errorf("vikebot: %s", err.Error())
}
// Create game object
g = &Game{
conn: &client,
buf: bufio.NewReader(client),
gcm: gcm,
}
//
// Start login process
//
// Login packet
err = g.trivialAction("login", loginPacket(ri.Ticket))
if err != nil {
return nil, err
}
// Client hello
challengeBuf := make([]byte, 8)
_, err = io.ReadFull(rand.Reader, challengeBuf)
if err != nil {
return nil, fmt.Errorf("vikebot: %s", err.Error())
}
challenge := binary.BigEndian.Uint64(challengeBuf)
challengeStr := strconv.FormatUint(challenge, 10)
clienthelloCipher, err := g.encryptStr("clienthello:" + challengeStr)
if err != nil {
return nil, fmt.Errorf("vikebot: %s", err.Error())
}
err = g.write(clienthelloPacket(clienthelloCipher))
if err != nil {
return nil, err
}
// Server hello
pt, buf, err := g.read(true)
if err != nil {
return nil, err
} else if pt != "serverhello" {
var resp response
err = json.Unmarshal(buf, &resp)
if err != nil {
return nil, fmt.Errorf("vikebot: %s", err.Error())
}
if resp.Error != nil {
return nil, fmt.Errorf("vikebot: %s", *resp.Error)
}
}
var serverhello serverhelloPacket
err = json.Unmarshal(buf, &serverhello)
if err != nil {
return nil, fmt.Errorf("vikebot: %s", err.Error())
}
if serverhello.Obj.Cipher == nil {
return nil, errors.New("vikebot: invalid server response serverhello.Obj.Cipher == nil")
}
plainServerhello, err := g.decryptStr(*serverhello.Obj.Cipher)
if err != nil {
return nil, err
} else if plainServerhello != "serverhello:"+challengeStr {
return nil, fmt.Errorf("vikebot: invalid plain text - expecting 'serverhello:%s'", challengeStr)
}
// Connection verified -> enable complete encryption
g.Encrypted = true
// Initial pc
pt, buf, err = g.read(true)
if err != nil {
return nil, err
} else if pt != "initialpc" {
return nil, errors.New("vikebot: invalid server response. expected initialpc packet")
}
var resp response
err = json.Unmarshal(buf, &resp)
if err != nil {
return nil, fmt.Errorf("vikebot: %s", err.Error())
}
if resp.Pc == nil {
return nil, errors.New("vikebot: invalid server response. expected pc in initialpc packet")
}
g.pc = *resp.Pc
// Finished login process itself -> agree on connection
err = g.trivialAction("agreeconn", agreeconnPacket(g))
if err != nil {
return nil, err
}
// Allocate player struct
g.Player = &Player{g: g}
return g, nil
}
// MustJoin is like Join but panics if any errors occur. It simplifies safe
// initialization of the game object.
func MustJoin(authtoken string) *Game {
g, err := Join(authtoken)
if err != nil {
panic(err)
}
return g
}