netplaySniff – Blame information for rev 7

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