forked from Akka0/Iridium-NG
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sniffer.go
397 lines (345 loc) · 9.94 KB
/
sniffer.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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
package main
import (
"encoding/base64"
"encoding/binary"
"encoding/json"
"log"
"os"
"strconv"
"strings"
"time"
"github.com/fatih/color"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/google/gopacket/pcap"
"github.com/google/gopacket/pcapgo"
"github.com/jhump/protoreflect/dynamic"
"github.com/xtaci/kcp-go"
)
type Packet struct {
Time int64 `json:"time"`
FromServer bool `json:"fromServer"`
PacketId uint16 `json:"packetId"`
PacketName string `json:"packetName"`
Object interface{} `json:"object"`
Raw []byte `json:"raw"`
}
type UniCmdItem struct {
PacketId uint16 `json:"packetId"`
PacketName string `json:"packetName"`
Object interface{} `json:"object"`
Raw []byte `json:"raw"`
}
var getPlayerTokenRspPacketId uint16
var getPlayerTokenReqPacketId uint16
var unionCmdNotifyPacketId uint16
var initialKey = make(map[uint16][]byte)
var sessionSeed uint64
var serverSeed uint64
var sentMs uint64
var captureHandler *pcap.Handle
var kcpMap map[string]*kcp.KCP
var packetFilter = make(map[string]bool)
var pcapFile *os.File
func openPcap(fileName string) {
readKeys()
var err error
captureHandler, err = pcap.OpenOffline(fileName)
if err != nil {
log.Println("Could not open pacp file", err)
return
}
startSniffer()
}
func openCapture() {
readKeys()
var err error
captureHandler, err = pcap.OpenLive(config.DeviceName, 1500, true, -1)
if err != nil {
log.Println("Could not open capture", err)
return
}
if config.AutoSavePcapFiles {
pcapFile, err = os.Create(time.Now().Format("06-01-02 15.04.05") + ".pcapng")
if err != nil {
log.Println("Could not create pcapng file", err)
}
defer pcapFile.Close()
}
startSniffer()
}
func closeHandle() {
if captureHandler != nil {
captureHandler.Close()
captureHandler = nil
}
if pcapFile != nil {
pcapFile.Close()
pcapFile = nil
}
}
func readKeys() {
var initialKeyJson map[uint16]string
file, err := os.ReadFile("./data/Keys.json")
if err != nil {
log.Fatal("Could not load initial key @ ./data/Keys.json #1", err)
}
err = json.Unmarshal(file, &initialKeyJson)
if err != nil {
log.Fatal("Could not load initial key @ ./data/Keys.json #2", err)
}
for k, v := range initialKeyJson {
decode, _ := base64.RawStdEncoding.DecodeString(v)
initialKey[k] = decode
}
getPlayerTokenReqPacketId = packetNameMap["GetPlayerTokenReq"]
getPlayerTokenRspPacketId = packetNameMap["GetPlayerTokenRsp"]
unionCmdNotifyPacketId = packetNameMap["UnionCmdNotify"]
}
func startSniffer() {
defer captureHandler.Close()
err := captureHandler.SetBPFFilter("udp portrange 22101-22102")
if err != nil {
log.Println("Could not set the filter of capture")
return
}
packetSource := gopacket.NewPacketSource(captureHandler, captureHandler.LinkType())
packetSource.NoCopy = true
kcpMap = make(map[string]*kcp.KCP)
var pcapWriter *pcapgo.NgWriter
if pcapFile != nil {
pcapWriter, err = pcapgo.NewNgWriter(pcapFile, captureHandler.LinkType())
if err != nil {
log.Println("Could not create pcapng writer", err)
}
}
for packet := range packetSource.Packets() {
if pcapWriter != nil {
err := pcapWriter.WritePacket(packet.Metadata().CaptureInfo, packet.Data())
if err != nil {
log.Println("Could not write packet to pcap file", err)
}
}
capTime := packet.Metadata().Timestamp
data := packet.ApplicationLayer().Payload()
udp := packet.TransportLayer().(*layers.UDP)
fromServer := udp.SrcPort == 22101 || udp.SrcPort == 22102
if len(data) <= 20 {
handleSpecialPacket(data, fromServer, capTime)
continue
}
handleKcp(data, fromServer, capTime)
}
}
func handleKcp(data []byte, fromServer bool, capTime time.Time) {
data = reformData(data)
conv := binary.LittleEndian.Uint32(data[:4])
key := strconv.Itoa(int(conv))
if fromServer {
key += "svr"
} else {
key += "cli"
}
if _, ok := kcpMap[key]; !ok {
kcpInstance := kcp.NewKCP(conv, func(buf []byte, size int) {})
kcpInstance.WndSize(1024, 1024)
kcpMap[key] = kcpInstance
}
kcpInstance := kcpMap[key]
_ = kcpInstance.Input(data, true, true)
size := kcpInstance.PeekSize()
for size > 0 {
kcpBytes := make([]byte, size)
kcpInstance.Recv(kcpBytes)
handleProtoPacket(kcpBytes, fromServer, capTime)
size = kcpInstance.PeekSize()
}
kcpInstance.Update()
}
func handleSpecialPacket(data []byte, fromServer bool, timestamp time.Time) {
sessionSeed = 0
serverSeed = 0
sentMs = 0
switch binary.BigEndian.Uint32(data[:4]) {
case 0xFF:
buildPacketToSend(data, fromServer, timestamp, 0, "Hamdshanke pls.")
case 404:
buildPacketToSend(data, fromServer, timestamp, 0, "Disconnected.")
default:
buildPacketToSend(data, fromServer, timestamp, 0, "Hamdshanke estamblished.")
}
}
func handleProtoPacket(data []byte, fromServer bool, timestamp time.Time) {
key := binary.BigEndian.Uint16(data[:4])
key = key ^ 0x4567
var xorPad []byte
xorPad = initialKey[key]
if initialKey[key] == nil {
seed := sessionSeed
if seed == 0 {
seed = sentMs
}
seed, xorPad = bruteforce(seed, serverSeed, data)
if xorPad == nil {
log.Println("Could not found key to decrypt", key)
closeHandle()
}
if sessionSeed == 0 {
sessionSeed = seed
}
initialKey[key] = xorPad
}
xorDecrypt(data, xorPad)
packetId := binary.BigEndian.Uint16(data[2:4])
var objectJson interface{}
if packetId == getPlayerTokenReqPacketId {
data, objectJson = handleGetPlayerTokenReqPacket(data, packetId, timestamp, objectJson)
} else if packetId == getPlayerTokenRspPacketId {
data, objectJson = handleGetPlayerTokenRspPacket(data, packetId, objectJson)
} else if packetId == unionCmdNotifyPacketId {
data, objectJson = handleUnionCmdNotifyPacket(data, packetId, objectJson)
} else {
data = removeHeaderForParse(data)
objectJson = parseProtoToInterface(packetId, data)
}
buildPacketToSend(data, fromServer, timestamp, packetId, objectJson)
}
func handleGetPlayerTokenReqPacket(data []byte, packetId uint16, timestamp time.Time, objectJson interface{}) ([]byte, interface{}) {
data = removeMagic(data)
dMsg, err := parseProto(packetId, data)
if err != nil {
log.Println("Could not parse GetPlayerTokenReqPacket proto", err)
closeHandle()
}
oj, err := dMsg.MarshalJSON()
if err != nil {
log.Println("Could not parse GetPlayerTokenReqPacket proto", err)
closeHandle()
}
err = json.Unmarshal(oj, &objectJson)
if err != nil {
log.Println("Could not parse GetPlayerTokenReqPacket proto", err)
closeHandle()
}
sentMs = uint64(timestamp.UnixMilli())
return data, objectJson
}
func handleGetPlayerTokenRspPacket(data []byte, packetId uint16, objectJson interface{}) ([]byte, interface{}) {
data = removeMagic(data)
dMsg, err := parseProto(packetId, data)
if err != nil {
log.Println("Could not parse GetPlayerTokenRspPacket proto", err)
closeHandle()
}
oj, err := dMsg.MarshalJSON()
if err != nil {
log.Println("Could not parse GetPlayerTokenRspPacket proto", err)
closeHandle()
}
err = json.Unmarshal(oj, &objectJson)
if err != nil {
log.Println("Could not parse GetPlayerTokenRspPacket proto", err)
closeHandle()
}
serverRandKey := dMsg.GetFieldByName("server_rand_key").(string)
seed, err := base64.StdEncoding.DecodeString(serverRandKey)
if err != nil {
log.Println("Failed to decode server rand key")
closeHandle()
}
seed, err = decrypt("data/private_key_4.pem", seed)
if err != nil {
log.Println("Failed to decrypt server rand key")
closeHandle()
}
serverSeed = binary.BigEndian.Uint64(seed)
log.Println("Server seed", serverSeed)
return data, objectJson
}
func handleUnionCmdNotifyPacket(data []byte, packetId uint16, objectJson interface{}) ([]byte, interface{}) {
data = removeHeaderForParse(data)
dMsg, err := parseProto(packetId, data)
if err != nil {
log.Println("Could not parse UnionCmdNotify proto", err)
}
cmdList := dMsg.GetFieldByName("cmd_list").([]interface{})
cmdListJson := make([]*UniCmdItem, len(cmdList))
for i, item := range cmdList {
msgItem := item.(*dynamic.Message)
itemPacketId := uint16(msgItem.GetFieldByName("message_id").(uint32))
itemData := msgItem.GetFieldByName("body").([]byte)
childJson := parseProtoToInterface(itemPacketId, itemData)
cmdListJson[i] = &UniCmdItem{
PacketId: itemPacketId,
PacketName: GetProtoNameById(itemPacketId),
Object: childJson,
Raw: itemData,
}
}
return data, cmdListJson
}
func buildPacketToSend(data []byte, fromSever bool, timestamp time.Time, packetId uint16, objectJson interface{}) {
packet := &Packet{
Time: timestamp.UnixMilli(),
FromServer: fromSever,
PacketId: packetId,
PacketName: GetProtoNameById(packetId),
Object: objectJson,
Raw: data,
}
jsonResult, err := json.Marshal(packet)
if err != nil {
log.Println("Json marshal error", err)
}
logPacket(packet)
if packetFilter[GetProtoNameById(packetId)] {
return
}
sendStreamMsg(string(jsonResult))
}
func logPacket(packet *Packet) {
from := "[Client]"
if packet.FromServer {
from = "[Server]"
}
forward := ""
if strings.Contains(packet.PacketName, "Rsp") {
forward = "<--"
} else if strings.Contains(packet.PacketName, "Req") {
forward = "-->"
} else if strings.Contains(packet.PacketName, "Notify") && packet.FromServer {
forward = "<-i"
} else if strings.Contains(packet.PacketName, "Notify") {
forward = "i->"
}
log.Println(color.GreenString(from),
"\t",
color.CyanString(forward),
"\t",
color.RedString(packet.PacketName),
color.YellowString("#"+strconv.Itoa(int(packet.PacketId))),
"\t",
len(packet.Raw),
)
if packet.PacketId == unionCmdNotifyPacketId {
logUnionCmdNotifyPacket(packet)
}
}
func logUnionCmdNotifyPacket(packet *Packet) {
uniCmdItem := packet.Object.([]*UniCmdItem)
for i, item := range uniCmdItem {
group := "├─"
if i == len(uniCmdItem) {
group = "└─"
}
log.Println("\t",
"\t",
color.CyanString(group),
"\t",
color.RedString(item.PacketName),
color.YellowString("#"+strconv.Itoa(int(item.PacketId))),
"\t",
len(item.Raw),
)
}
}