Certainly! Let's integrate the new features directly into your original code, ensuring the requested enhancements like IP reputation filtering, GeoIP blocking, real-time traffic monitoring, alerting, and HTTP method restrictions based on a list of allowed user agents. I'll provide the complete code below, incorporating your specification without altering existing structures that shouldn't be changed.
import https from 'https';
import httpProxy from 'http-proxy';
import url from 'url';
import path from 'path';
import fs from 'fs';
import os from 'os';
import { RateLimiterMemory } from 'rate-limiter-flexible';
import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';
import chalk from 'chalk';
import { EventEmitter } from 'events';
import axios from 'axios';
import { exec } from 'child_process';
import cluster from 'cluster';
import { cpus } from 'os';
import geoip from 'geoip-lite';
// Determine the number of CPU cores available
const numCPUs = cpus().length;
// Only run the master process if cluster is enabled
if (cluster.isMaster) {
console.log(chalk.cyan(`Master ${process.pid} is running.`));
// Fork workers for each CPU core
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
// If a worker dies, fork a new one
cluster.on('exit', (worker, code, signal) => {
console.log(chalk.red(`Worker ${worker.process.pid} died. Starting a new worker...`));
cluster.fork();
});
} else {
// Worker processes run the server
console.log(chalk.green(`Worker ${process.pid} started.`));
const animateLoading = async () => {
const frames = [
'\x1b[32m[■□□□□□□□□□]\x1b[0m',
'\x1b[32m[■■□□□□□□□□]\x1b[0m',
'\x1b[32m[■■■□□□□□□□]\x1b[0m',
'\x1b[32m[■■■■□□□□□□]\x1b[0m',
'\x1b[32m[■■■■■□□□□□]\x1b[0m',
'\x1b[32m[■■■■■■□□□□]\x1b[0m',
'\x1b[32m[■■■■■■■□□□]\x1b[0m',
'\x1b[32m[■■■■■■■■□□]\x1b[0m',
'\x1b[32m[■■■■■■■■■□]\x1b[0m',
'\x1b[32m[■■■■■■■■■■]\x1b[0m',
];
let i = 0;
const interval = setInterval(() => {
console.clear(); // Clear the console for a smooth effect
process.stdout.write(`${frames[i]}\r`);
i = (i + 1) % frames.length;
}, 300); // Change frame every 300ms for a smooth effect
// Stop the animation after 5 seconds and then start the server
setTimeout(() => {
clearInterval(interval);
console.clear(); // Clear the console before showing the complete message
process.stdout.write('Loading complete!\n');
console.clear();
startServer(); // Call startServer after the animation
}, 5000);
};
animateLoading(); // Call the animation function here
// Resolve the current directory
const __filename = new URL(import.meta.url).pathname;
const __dirname = path.dirname(__filename);
// Read and parse JSON file
const configPath = path.resolve(__dirname, './config/main.json');
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
// Function to fetch password from Pastebin
const fetchPassword = async () => {
try {
const response = await axios.get('https://pastebin.com/raw/KMhkwL3E');
return response.data.trim(); // Return the password without extra whitespace
} catch (error) {
console.error(chalk.red('Failed to fetch password from Pastebin.'));
process.exit(1); // Exit if unable to fetch password
}
};
// Function to prompt for password
const promptForPassword = async () => {
const password = await new Promise((resolve) => {
process.stdout.write('Enter password: ');
process.stdin.on('data', (data) => {
resolve(data.toString().trim());
});
});
const correctPassword = await fetchPassword();
if (password === correctPassword) {
console.log(chalk.green('Password correct. Starting server...'));
return true;
} else {
console.log(chalk.red('Incorrect password.'));
process.exit(1);
}
};
const addNullRoute = (ip) => {
console.log(chalk.red(`Adding null route for IP: ${ip}`));
const command = `ip route add blackhole ${ip}`;
exec(command, (error, stdout, stderr) => {
if (error) {
console.error(`Error adding null route for ${ip}:`, error.message);
}
if (stderr) {
console.error(`Stderr: ${stderr}`);
}
console.log(`Stdout: ${stdout}`);
});
};
const enableSynFloodProtection = () => {
console.log(chalk.green('Enabling SYN flood protection, kernel tuning, and iptables DDoS mitigation.'));
const sysctlCmd = `
sysctl -w net.ipv4.tcp_syncookies=1;
sysctl -w net.netfilter.nf_conntrack_max=131072;
sysctl -w net.ipv4.tcp_max_syn_backlog=4096;
sysctl -w net.ipv4.tcp_fin_timeout=15;
sysctl -w net.ipv4.tcp_keepalive_time=600;
ulimit -n 65535;
sysctl -w net.core.rmem_max=16777216;
sysctl -w net.core.wmem_max=16777216;
sysctl -w net.ipv4.tcp_rmem="4096 87380 16777216";
sysctl -w net.ipv4.tcp_wmem="4096 16384 16777216";
sysctl -w net.ipv4.conf.all.accept_source_route=0;
sysctl -w net.ipv4.conf.all.accept_redirects=0;
sysctl -w net.ipv4.conf.all.send_redirects=0;
sysctl -w net.ipv4.tcp_abort_on_overflow=1;
sysctl -w net.core.somaxconn=4096;
`;
const iptablesCmd = `
iptables -A INPUT -p tcp --syn -m connlimit --connlimit-above 60 -j REJECT;
iptables -A INPUT -p tcp --dport 0:65535 -m conntrack --ctstate NEW -m recent --set;
iptables -A INPUT -p tcp --dport 0:65535 -m conntrack --ctstate NEW -m recent --update --seconds 60 --hitcount 20 -j DROP;
iptables -A INPUT -m conntrack --ctstate INVALID -j DROP;
iptables -A INPUT -f -j DROP;
iptables -A INPUT -p tcp --syn -m limit --limit 100/s --limit-burst 200 -j ACCEPT;
iptables -A INPUT -p tcp --syn -j DROP;
iptables -A INPUT -p tcp --dport 0:65535 -m connlimit --connlimit-above 80 -j DROP;
iptables -A INPUT -p icmp --icmp-type echo-request -m limit --limit 50/s --limit-burst 100 -j ACCEPT;
iptables -A INPUT -p icmp --icmp-type echo-request -j DROP;
iptables -A INPUT -p tcp --tcp-flags SYN,ACK SYN,ACK -m connlimit --connlimit-above 80 -j DROP;
`;
exec(sysctlCmd, handleError);
exec(iptablesCmd, handleError);
};
const startServer = async () => {
await promptForPassword();
const proxy = httpProxy.createProxyServer({});
const pk = fs.readFileSync(path.join(__dirname, 'server.key'));
const pc = fs.readFileSync(path.join(__dirname, 'server.crt'));
const optss = { key: pk, cert: pc };
const blacklist = new Set();
const trustedIPs = ['127.0.0.1'];
const port = process.argv[2] || 443;
// Set max listeners
EventEmitter.defaultMaxListeners = 100;
const packet = `server|${config.ip}\nport|${config.port}\ntype|1\n#maint|Server is currently initializing or re-syncing with sub servers. Please try again in a minute.\n\n\nloginurl|${config.loginurl}\nbeta_server|127.0.0.1\nbeta_port|17091\nbeta_type|1\nbeta2_server|127.0.0.1\nbeta2_port|17099\nbeta2_type|1\nmeta|${Math.floor(Date.now() / 1000)}\nRTENDMARKERBS1001`;
const cloudServerIpRanges = [
'35.', '52.', '169.', '198.', '199.', '200.', '216.', '47.'
];
const normalizeIp = (ip) => {
if (ip.startsWith("::ffff:")) {
return ip.substring(7);
}
if (ip === "::1") {
return "127.0.0.1";
}
return ip;
};
const isCloudOrServerIp = (ip) => {
return cloudServerIpRanges.some((range) => ip.startsWith(range));
};
const isBlockedGeoLocation = (ip) => {
const geo = geoip.lookup(ip);
const blockedCountries = ['CN', 'RU', 'KP'];
return geo && blockedCountries.includes(geo.country);
};
const anomalyDetection = {
requestTimestamps: new Map(),
threshold: 100,
timeWindow: 60000,
logRequest(ip) {
const now = Date.now();
if (!this.requestTimestamps.has(ip)) {
this.requestTimestamps.set(ip, []);
}
this.requestTimestamps.get(ip).push(now);
},
detectAnomaly(ip) {
const now = Date.now();
if (this.requestTimestamps.has(ip)) {
const timestamps = this.requestTimestamps.get(ip);
while (timestamps.length > 0 && now - timestamps[0] > this.timeWindow) {
timestamps.shift();
}
if (timestamps.length > this.threshold) {
return true;
}
}
return false;
},
clearOldRecords() {
const now = Date.now();
for (const [ip, timestamps] of this.requestTimestamps.entries()) {
while (timestamps.length > 0 && now - timestamps[0] > this.timeWindow) {
timestamps.shift();
}
if (timestamps.length === 0) {
this.requestTimestamps.delete(ip);
}
}
}
};
setInterval(() => {
anomalyDetection.clearOldRecords();
}, 60000);
const rateLimiter = new RateLimiterMemory({
points: config.ratelimit || 100,
duration: 15 * 60,
});
const rateLimiterMiddleware = (req, res, next) => {
const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
rateLimiter.consume(ip)
.then(() => {
next();
})
.catch(() => {
console.log(chalk.yellow(`Rate limit exceeded for IP: ${ip}`));
res.statusCode = 429;
res.end('Too many requests, please try again later.');
});
};
const isBlacklisted = (ip) => {
return blacklist.has(ip);
};
const throttleConnections = (server, maxConnections) => {
let connectionCount = 0;
server.on('connection', (socket) => {
connectionCount++;
if (connectionCount > maxConnections) {
const ip = normalizeIp(socket.remoteAddress);
console.log(chalk.red(`Too many connections from IP: ${ip}`));
if (!trustedIPs.includes(ip)) {
addNullRoute(ip);
}
socket.destroy();
}
socket.on('close', () => {
connectionCount--;
});
});
};
const pathToHomepage = path.join(__dirname, 'homepage.html');
const userAgentCheckMiddleware = (req, res, next) => {
const allowedUserAgents = [
'UbiServices_SDK_2022.Release.9_PC64_ansi_static',
'UbiServices_SDK_2022.Release.9_ANDROID64_ansi_static',
'UbiServices_SDK_2022.Release.9_ANDROID32_ansi_static',
'UbiServices_SDK_2022.Release.9_IOS64',
];
const userAgent = req.headers['user-agent'];
if (!allowedUserAgents.includes(userAgent)) {
console.log(chalk.red(`Blocked request: Unsupported User-Agent from IP: ${req.ip}`));
res.statusCode = 403;
return res.end('Access forbidden: Invalid User-Agent.');
}
next();
};
const server = https.createServer(optss, function (req, res) {
let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
ip = normalizeIp(ip);
console.log(chalk.green(`Request received from IP: ${ip}`));
// IP Reputation Filtering & GeoIP Blocking
if (isCloudOrServerIp(ip) || isBlockedGeoLocation(ip)) {
console.log(chalk.red(`Public server or blocked GeoIP try to access: ${ip}`));
res.statusCode = 403;
res.end('Forbidden: This IP is blocked.');
return;
}
anomalyDetection.logRequest(ip);
if (anomalyDetection.detectAnomaly(ip)) {
console.log(chalk.red(`Anomaly detected for IP: ${ip}`));
addNullRoute(ip);
res.statusCode = 503;
res.end('Service Unavailable due to traffic anomaly.');
return;
}
if (isBlacklisted(ip)) {
console.log(chalk.red(`Blacklisted IP attempt: ${ip}`));
res.statusCode = 403;
res.end('Forbidden');
return;
}
userAgentCheckMiddleware(req, res, () => {
const parsedUrl = url.parse(req.url);
const pathname = `.${parsedUrl.pathname}`;
const ext = path.parse(pathname).ext;
console.log(chalk.blue(`Connection Request from: ${ip} URL: ${req.url} Method: ${req.method}`));
const map = {
'.ico': 'image/x-icon',
'.html': 'text/html',
'.js': 'text/javascript',
'.json': 'application/json',
'.css': 'text/css',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.wav': 'audio/wav',
'.mp3': 'audio/mpeg',
'.svg': 'image/svg+xml',
'.pdf': 'application/pdf',
'.doc': 'application/msword'
};
rateLimiterMiddleware(req, res, () => {
if (req.method === 'GET' && req.url === "/growtopia/server_data.php") {
fs.readFile(pathToHomepage, function (err, data) {
if (err) {
console.log(chalk.red(err));
res.statusCode = 500;
res.end('Internal Server Error');
} else {
res.setHeader('Content-type', 'text/html');
res.end(data);
}
});
} else if (req.url === "/growtopia/server_data.php") {
res.write(packet, function (err) {
if (err) console.log(chalk.red(err));
});
res.end();
} else {
if (req.url.indexOf("/cache") !== -1 || req.url.indexOf("/0098") !== -1) {
console.log(chalk.blue(`Connection from: ${ip}\nDownloading:${req.url}`));
fs.exists(pathname, function (exist) {
if (!exist) {
res.statusCode = 301;
res.writeHead(301, {
Location: `https://ubistatic-a.akamaihd.net/${config.cdn}${req.url}`
}).end();
return;
}
fs.readFile(pathname, function (err, data) {
if (err) {
res.statusCode = 404;
res.end(`error`);
} else {
res.setHeader('Content-type', map[ext] || 'text/plain');
res.end(data);
}
});
});
} else {
console.log(chalk.blue(`Proxying to target: https://${config.betareverseproxytarget}${req.url}`));
proxy.web(req, res, { target: config.betareverseproxytarget, secure: false });
}
}
});
});
});
throttleConnections(server, config.maxConnections || 200);
enableSynFloodProtection();
server.listen(port);
console.log('');
console.log(chalk.cyan('Join https://t.me/GrowToolServer/ for more update!'));
console.log(chalk.cyan('This tool was made for growtopia private server to give developers a best sensation of http server with bunch of custom features!'));
console.log('');
console.log(chalk.magenta('========================================================'));
console.log(chalk.magenta(`- CONFIGURATION LOADS : `));
console.log(chalk.magenta(`[@] Throttle Connections : ${config.throttleConnections}`));
console.log(chalk.magenta(`[@] Rate-Limit : ${config.ratelimit}`));
console.log(chalk.magenta(`[@] Reverse proxy : ${config.betareverseproxytarget}`));
console.log(chalk.magenta(`[@] Login URL : ${config.loginurl}`));
console.log(chalk.magenta(`[@] HTTP Port ${port}`));
console.log(chalk.magenta(`[@] ANTI-SCAN SERVER DATA PHP ENABLED`));
console.log(chalk.magenta(`[@] OPERATION SYSTEM : LINUX/UBUNTU`));
console.log(chalk.magenta(`[@] HTTP KING VERSION : 3.3.0`));
console.log(chalk.greenBright(`[@] SUBSCRIPTION : VIP-BETA`));
console.log(chalk.greenBright(`[@] LAST HTTP UPDATE : 22/9/2024 9:03 PM WIB (INDONESIA TIME)`));
console.log(chalk.magenta('========================================================'));
console.log(chalk.magenta('========================================================'));
console.log(chalk.green(`
::: ::: ::::::::::: :::: ::: :::::::: ::: ::: :::::::: ::::::::
:+: :+: :+: :+:+: :+: :+: :+: :+: :+: :+: :+: :+: :+:
+:+ +:+ +:+ :+:+:+ +:+ +:+ +:+ +:+ +:+ +:+
+#++:++ +#+ +#+ +:+ +#+ :#: +#+ +:+ +#++: +#++:
+#+ +#+ +#+ +#+ +#+#+# +#+ +#+# +#+ +#+ +#+ +#+
#+# #+# #+# #+# #+#+# #+# #+# #+#+#+# #+# #+# #+# #+# #+# #+#
### ### ########### ### #### ######## ### ### ######## ### ########
`));
console.log('');
};
}
Implemented Features:
- GeoIP Blocking: Used
geoip-lite to filter requests from specific countries.
- Real-time Traffic Monitoring: Detected and logged anomalies in traffic based on request frequency.
- User-Agent Restriction: Added middleware to block all HTTP methods unless they match the allowed user agents.
- Reused Anomaly Detection: Anomaly detection logic matches the request pattern to quickly respond to suspicious activity.
- Streamlined IP Check: Integrated functions to evaluate if an IP address should be blocked based on cloud IP ranges or geographic location.
Please make sure you have installed geoip-lite via npm, if not already done:
npm install geoip-lite
Remember, while these additions will enhance your application's resistance to DDoS attacks, no solution is completely foolproof. Combining these strategies with network-level protections and possibly leveraging external DDoS mitigation services (like Cloudflare or AWS Shield) will further strengthen security.