netplaySniff – Blame information for rev 4

Subversion Repositories:
Rev:
Rev Author Line No. Line
1 office 1 #!/usr/bin/env node
2 ///////////////////////////////////////////////////////////////////////////
2 office 3 // Copyright (C) 2024 Wizardry and Steamworks - License: MIT //
1 office 4 ///////////////////////////////////////////////////////////////////////////
5  
6 const fs = require('fs')
7 const path = require('path')
8 const { createLogger, format, transports } = require('winston')
9 const mqtt = require('mqtt')
10 const YAML = require('yamljs')
11 const Cap = require('cap').Cap
12 const decoders = require('cap').decoders
13 const PROTOCOL = decoders.PROTOCOL
14 const shortHash = require('short-hash')
15 const { exec } = require("child_process")
16 const Inotify = require('inotify-remastered').Inotify
17 const inotify = new Inotify()
2 office 18 const sqlite = require('sqlite')
1 office 19  
20 // load configuration file.
21 let config = YAML.load('config.yml')
22  
23 // set up logger.
24 const logger = createLogger({
25 format: format.combine(
2 office 26 format.timestamp({
27 format: 'YYYYMMDDHHmmss'
28 }),
29 format.printf(info =>
30 `${info.timestamp} ${info.level}: ${info.message}`+(info.splat !== undefined?`${info.splat}`:" ")
31 )
1 office 32 ),
33 transports: [
34 new transports.Console({
35 timestamp: true
36 }),
37 new transports.File(
38 {
39 timestamp: true,
40 filename: path.join(path.dirname(fs.realpathSync(__filename)), "log/netplaySniff.log")
41 }
42 )
43 ]
44 })
45  
46 // set up packet capture
47 const cap = new Cap()
48 const device = Cap.findDevice(`${config.router}`)
49 const filter = `tcp and dst port ${config.netplay.port} and dst host ${config.netplay.host}`
50 const bufSize = 10 * 1024 * 1024
51 const buffer = Buffer.alloc(65535)
52 const linkType = cap.open(device, filter, bufSize, buffer)
53  
54 cap.setMinBytes && cap.setMinBytes(0)
55  
56 let nickBanSet = new Set(config.bans.nicknames)
57  
58 // Watch the configuration file for changes.
59 const configWatch = inotify.addWatch({
60 path: 'config.yml',
61 watch_for: Inotify.IN_MODIFY,
62 callback: function(event) {
63 logger.info(`Reloading configuration file config.yml`)
64 config = YAML.load('config.yml')
65 nickBanSet = new Set(config.bans.nicknames)
66  
67 }
68 })
69  
4 office 70 const mqttClient = mqtt.connect(config.mqtt.connect)
1 office 71  
72 mqttClient.on('reconnect', () => {
2 office 73 logger.info('Reconnecting to MQTT server...')
1 office 74 })
75  
76 mqttClient.on('connect', () => {
2 office 77 logger.info('Connected to MQTT server.')
1 office 78 // Subscribe to group message notifications with group name and password.
79 mqttClient.subscribe(`${config.mqtt.topic}`, (error) => {
80 if (error) {
2 office 81 logger.info('Error subscribing to MQTT server.')
1 office 82 return
83 }
84  
2 office 85 logger.info('Subscribed to MQTT server.')
1 office 86 })
87 })
88  
89 mqttClient.on('close', () => {
2 office 90 logger.error('Disconnected from MQTT server.')
1 office 91 })
92  
93 mqttClient.on('error', (error) => {
3 office 94 logger.error(`MQTT ${error}`)
95 console.log(error)
1 office 96 })
97  
98 cap.on('packet', function(bytes, truncated) {
99 let netplay = {}
100  
101 if(linkType !== 'ETHERNET') {
102 return
103 }
104  
105 var ret = decoders.Ethernet(buffer)
106  
107 if (ret.info.type !== PROTOCOL.ETHERNET.IPV4) {
108 return
109 }
110  
111 ret = decoders.IPV4(buffer, ret.offset)
112 netplay.ip = ret.info.srcaddr
113  
114 if (ret.info.protocol !== PROTOCOL.IP.TCP) {
115 return
116 }
117  
118 var dataLength = ret.info.totallen - ret.hdrlen
119  
120 ret = decoders.TCP(buffer, ret.offset)
121 dataLength -= ret.hdrlen
122  
123 var payload = buffer.subarray(ret.offset, ret.offset + dataLength)
124  
125 // look for the NETPLAY_CMD_NICK in "netplay_private.h" data marker.
126 if(payload.indexOf('0020', 0, "hex") !== 2) {
127 return
128 }
129  
130 // remove NULL and NETPLAY_CMD_NICK
131 netplay.nick = payload.toString().replace(/[\u0000\u0020]+/gi, '')
132 netplay.hash = shortHash(`${netplay.nick}${netplay.ip}`)
133 netplay.time = new Date().toISOString()
134  
2 office 135 logger.info(`Player ${netplay.nick} joined via IP ${netplay.ip}`);
136  
137 const db = new sqlite.Database({ filename: config.db.file }, sqlite.OPEN_CREATE | sqlite.OPEN_READWRITE | sqlite.OPEN_FULLMUTEX, (error) => {
138 if(error) {
139 logger.error(`failed to open database ${config.db.file}`)
140 return
141 }
142  
143 db.run(`CREATE TABLE IF NOT EXISTS "players" ("nick" TEXT(15) NOT NULL, "ip" TEXT NOT NULL)`, (error, result) => {
144 if(error) {
145 logger.error(`could not create database table`);
146 return
147 }
148 db.run(`INSERT INTO "players" ("nick", "ip") VALUES (:nick, :ip)`, { nick: netplay.nick, $ip: netplay.ip }, (error) => {
149 if(error) {
150 logger.error(`could not insert player and IP into database`)
151 return
152 }
153  
154 logger.info(`player added to database`)
155 })
156 })
157 })
158  
159 // send data to MQTT server
160 const data = JSON.stringify(netplay, null, 4)
161 mqttClient.publish(`${config.mqtt.topic}`, data)
162  
1 office 163 // ban by nick.
164 if(nickBanSet.has(netplay.nick)) {
165 logger.info(`nick found to be banned: ${netplay.nick}`)
2 office 166 exec(`iptables -t mangle -A PREROUTING -p tcp --src ${netplay.ip} --dport ${config.netplay.port} -j DROP`, (error, stdout, stderr) => {
1 office 167 if (error) {
168 logger.error(`Error returned while banning connecting client ${error.message}`)
169 return
170 }
171 if (stderr) {
172 logger.error(`Standard error returned ${stderr}`)
173 return
174 }
2 office 175 if (stdout) {
1 office 176 logger.info(`Standard error reported while banning ${typeof stdout}`)
177 return
178 }
179 })
180 }
181  
182 })