netplaySniff – Blame information for rev 2

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  
70 const mqttClient = mqtt.connect(config.mqtt.connect)
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) => {
2 office 94 logger.error(`Error found while connecting to MQTT server ${error}`)
1 office 95 })
96  
97 cap.on('packet', function(bytes, truncated) {
98 let netplay = {}
99  
100 if(linkType !== 'ETHERNET') {
101 return
102 }
103  
104 var ret = decoders.Ethernet(buffer)
105  
106 if (ret.info.type !== PROTOCOL.ETHERNET.IPV4) {
107 return
108 }
109  
110 ret = decoders.IPV4(buffer, ret.offset)
111 netplay.ip = ret.info.srcaddr
112  
113 if (ret.info.protocol !== PROTOCOL.IP.TCP) {
114 return
115 }
116  
117 var dataLength = ret.info.totallen - ret.hdrlen
118  
119 ret = decoders.TCP(buffer, ret.offset)
120 dataLength -= ret.hdrlen
121  
122 var payload = buffer.subarray(ret.offset, ret.offset + dataLength)
123  
124 // look for the NETPLAY_CMD_NICK in "netplay_private.h" data marker.
125 if(payload.indexOf('0020', 0, "hex") !== 2) {
126 return
127 }
128  
129 // remove NULL and NETPLAY_CMD_NICK
130 netplay.nick = payload.toString().replace(/[\u0000\u0020]+/gi, '')
131 netplay.hash = shortHash(`${netplay.nick}${netplay.ip}`)
132 netplay.time = new Date().toISOString()
133  
2 office 134 logger.info(`Player ${netplay.nick} joined via IP ${netplay.ip}`);
135  
136 const db = new sqlite.Database({ filename: config.db.file }, sqlite.OPEN_CREATE | sqlite.OPEN_READWRITE | sqlite.OPEN_FULLMUTEX, (error) => {
137 if(error) {
138 logger.error(`failed to open database ${config.db.file}`)
139 return
140 }
141  
142 db.run(`CREATE TABLE IF NOT EXISTS "players" ("nick" TEXT(15) NOT NULL, "ip" TEXT NOT NULL)`, (error, result) => {
143 if(error) {
144 logger.error(`could not create database table`);
145 return
146 }
147 db.run(`INSERT INTO "players" ("nick", "ip") VALUES (:nick, :ip)`, { nick: netplay.nick, $ip: netplay.ip }, (error) => {
148 if(error) {
149 logger.error(`could not insert player and IP into database`)
150 return
151 }
152  
153 logger.info(`player added to database`)
154 })
155 })
156 })
157  
158 // send data to MQTT server
159 const data = JSON.stringify(netplay, null, 4)
160 mqttClient.publish(`${config.mqtt.topic}`, data)
161  
1 office 162 // ban by nick.
163 if(nickBanSet.has(netplay.nick)) {
164 logger.info(`nick found to be banned: ${netplay.nick}`)
2 office 165 exec(`iptables -t mangle -A PREROUTING -p tcp --src ${netplay.ip} --dport ${config.netplay.port} -j DROP`, (error, stdout, stderr) => {
1 office 166 if (error) {
167 logger.error(`Error returned while banning connecting client ${error.message}`)
168 return
169 }
170 if (stderr) {
171 logger.error(`Standard error returned ${stderr}`)
172 return
173 }
2 office 174 if (stdout) {
1 office 175 logger.info(`Standard error reported while banning ${typeof stdout}`)
176 return
177 }
178 })
179 }
180  
181 })