const synFloodTracker = {};
const MAX_SYN_REQUESTS = 10; // Max allowed per minute
const SYN_BLOCK_TIME_MS = 60000; // Block time if SYN flood detected
// Rate Limiting Configurations
const rateLimit = {};
const MAX_REQUESTS_PER_MINUTE = 100; // Set your limit here (100)
const BLOCK_TIME_MS = 60000; // Time to block the IP (1 minute) (60000)
// DNS attack prevention configurations
const dnsWhitelist = ['8.8.8.8', '1.1.1.1']; // Trusted DNS resolvers (Google DNS and Cloudflare DNS)
const MAX_DNS_REQUESTS_PER_MINUTE = 50; // Limit DNS-related requests
const dnsRateLimit = {};
// Function to check and update DNS rate limits
const isSuspiciousDNSRequest = (ip, requestUrl) => {
if (!requestUrl.toLowerCase().includes('dns')) return false; // Only check DNS-related requests
if (!dnsWhitelist.includes(ip)) {
const now = Date.now();
if (!dnsRateLimit[ip]) {
dnsRateLimit[ip] = { count: 1, timestamp: now };
} else {
const timePassed = now - dnsRateLimit[ip].timestamp;
if (timePassed > BLOCK_TIME_MS) {
dnsRateLimit[ip] = { count: 1, timestamp: now };
} else {
dnsRateLimit[ip].count++;
}
code
if (dnsRateLimit[ip].count > MAX_DNS_REQUESTS_PER_MINUTE) {
return true; // DNS request limit exceeded
}
}
}
return false;
};
// Function to check and update UDP rate limits
const isUdpRateLimited = (ip) => {
const now = Date.now();
if (!udpRateLimit[ip]) {
udpRateLimit[ip] = { count: 1, timestamp: now };
return false;
} else {
const timePassed = now - udpRateLimit[ip].timestamp;
if (timePassed > UDP_BLOCK_TIME_MS) {
udpRateLimit[ip] = { count: 1, timestamp: now };
return false;
} else {
udpRateLimit[ip].count++;
if (udpRateLimit[ip].count > MAX_UDP_REQUESTS_PER_MINUTE) {
return true;
}
}
}
return false;
};
Assistant
To add a condition where only a specific PID number like "4120" is allowed when handling the POST /growtopia/server_data.php request, you can modify the logic handling this route to check for the presence and value of a PID parameter. This parameter can be passed either in the headers, the body, or the URL, depending on how your application expects to receive it.
Let's assume we're checking for this value in the request headers. Here's how you could modify the existing logic:
User
Don't assume, please find out how to get the pID and implement it.
Assistant
// Function to check and update network usage
const isNetworkUsageLimited = (ip, bytes) => {
const now = Date.now();
if (!networkUsage[ip]) {
networkUsage[ip] = { sent: bytes, received: bytes, timestamp: now };
return false;
} else {
const timePassed = now - networkUsage[ip].timestamp;
if (timePassed > NETWORK_BLOCK_TIME_MS) {
networkUsage[ip] = { sent: bytes, received: bytes, timestamp: now };
return false;
} else {
networkUsage[ip].sent += bytes;
networkUsage[ip].received += bytes;
if (networkUsage[ip].sent > MAX_BYTES_PER_MINUTE || networkUsage[ip].received > MAX_BYTES_PER_MINUTE) {
return true;
}
}
}
return false;
};
// Function to normalize IP addresses
const normalizeIp = (ip) => {
if (ip.startsWith("::ffff:")) {
return ip.substring(7);
}
if (ip === "::1") {
return "127.0.0.1";
}
return ip;
};
// Function to check if IP is from cloud/server ranges
const isCloudOrServerIp = (ip) => {
return cloudServerIpRanges.some((range) => ip.startsWith(range));
};
// Helper function to check GeoIP blocking
const isBlockedGeoIp = (ip) => {
const geo = geoip.lookup(ip);
if (geo && !allowedCountries.includes(geo.country)) {
return true;
}
return false;
};
const isSynFlood = (ip) => {
const now = Date.now();
if (!synFloodTracker[ip]) {
synFloodTracker[ip] = { count: 1, timestamp: now };
return false;
}
const timePassed = now - synFloodTracker[ip].timestamp;
if (timePassed > SYN_BLOCK_TIME_MS) {
synFloodTracker[ip] = { count: 1, timestamp: now };
return false;
} else {
synFloodTracker[ip].count++;
if (synFloodTracker[ip].count > MAX_SYN_REQUESTS) {
console.log(chalk.red(SYN flood detected from IP: ${ip}));
logBlockedIP(ip, 'SYN Flood');
return true;
}
}
return false;
};
// Start UI Server
configApp.listen(CONFIG_PORT, () => {
console.log(chalk.blue(Admin dashboard is running on http://localhost:${CONFIG_PORT}/config));
});
// Start Server Function
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 trustedIPs = ['127.0.0.1'];
const port = process.argv[2] || 443;
import('open').then(module => {
module.default(https://localhost:${CONFIG_PORT}/config);
}).catch(err => {
console.error(chalk.red('Failed to open admin dashboard automatically', err));
});
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 server = https.createServer(optss, function (req, res) {
let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
const normalizedIp = normalizeIp(ip);
const hostHeader = req.headers.host;
console.log(chalk.green([DEVELOPER MODE], req.headers['user-agent']));
console.log(chalk.green(Request received from IP: ${normalizedIp}));
code
if (isSynFlood(ip)) {
console.log(chalk.red(`SYN flood detected from IP: ${normalizedIp}`));
logBlockedIP(normalizedIp, 'SYN Flood');
// Use the underlying socket to destroy the connection
req.socket.end(); // Gracefully end the connection
req.socket.destroy(); // Forcefully close the connection, ignoring any pending data or errors
return;
}
// Rate Limiting Logic
if (!rateLimit[normalizedIp]) {
rateLimit[normalizedIp] = { count: 1, timestamp: Date.now() };
} else {
const currentTime = Date.now();
const timePassed = currentTime - rateLimit[normalizedIp].timestamp;
// Reset count if more than 1 minute has passed
if (timePassed > BLOCK_TIME_MS) {
rateLimit[normalizedIp] = { count: 1, timestamp: currentTime };
} else {
rateLimit[normalizedIp].count++;
}
// Check if the limit is reached
if (rateLimit[normalizedIp].count > MAX_REQUESTS_PER_MINUTE) {
console.log(chalk.red(`Rate limit exceeded for IP: ${normalizedIp}`));
logBlockedIP(normalizedIp, 'TCP');
res.statusCode = 429; // Too Many Requests
res.end('Too many requests. Your connection is being throttled.');
return;
}
}
// DNS attack protection
if (isSuspiciousDNSRequest(normalizedIp, req.url)) {
console.log(chalk.red(`DNS DDoS detected from IP: ${normalizedIp}`));
logBlockedIP(normalizedIp, 'TCP-DNS');
res.statusCode = 403; // Forbidden
res.end('Forbidden: DNS DDoS attack detected.');
return;
}
// Network Usage Limiting for TCP
const requestBytes = Buffer.byteLength(req.url); // Approximate
if (isNetworkUsageLimited(normalizedIp, requestBytes)) {
console.log(chalk.red(`Network usage limit exceeded for IP: ${normalizedIp} (TCP)`));
logBlockedIP(normalizedIp, 'TCP-NETWORK');
res.statusCode = 429; // Too Many Requests
res.end('Too many requests. Your connection is being throttled.');
return;
}
// Check for cloud or server IP range
if (!trustedIPs.includes(normalizedIp) && isCloudOrServerIp(normalizedIp)) {
console.log(chalk.red(`Blocking cloud/server IP: ${normalizedIp}`));
logBlockedIP(normalizedIp, 'TCP-Cloud');
res.statusCode = 403;
res.end('Forbidden: Access from cloud/server IP is blocked.');
return;
}
// Check for GeoIP block
if (isBlockedGeoIp(normalizedIp)) {
console.log(chalk.red(`Blocking access from IP: ${normalizedIp} (GeoIP Block)`));
logBlockedIP(normalizedIp, 'TCP-GeoIP');
res.statusCode = 403;
res.end('Forbidden: Access from your location is blocked.');
return;
}
const parsedUrl = url.parse(req.url);
const pathname = `.${parsedUrl.pathname}`;
const ext = path.parse(pathname).ext;
console.log(chalk.blue(`Connection Request from: ${normalizedIp} 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'
};
const allowedUserAgents = [
'UbiServices_SDK_2022.Release.9_PC64_ansi_static',
'UbiServices_SDK_2022.Release.9_ANDROID64_static',
'UbiServices_SDK_2022.Release.9_ANDROID32_static',
'UbiServices_SDK_2022.Release.9_IOS64',
];
const userAgent = req.headers['user-agent'];
// Handle /growtopia/server_data.php - Only POST and allowed User-Agents
// Handle /growtopia/server_data.php - Only POST and allowed User-Agents
if (req.url === "/growtopia/server_data.php") {
if (req.method !== 'POST' || hostHeader !== 'www.growtopia2.com') {
console.log(chalk.red(Mata mata : ${req.url}));
res.statusCode = 403;
res.end(`
server|normalizedIpport∣{Math.floor(Date.now() / 69)}
type|1
#maint|Server is currently initializing or re-syncing with sub servers. Please try again in a minute.
server.listen(port, () => {
console.log(chalk.green(Server is running on port ${port}));
});
// -------------------- UDP Server Setup --------------------
const udpServer = dgram.createSocket('udp4');
const UDP_PORT = 53; // DNS typically uses port 53
udpServer.on('error', (err) => {
console.error(UDP server error:\n${err.stack});
udpServer.close();
});
udpServer.on('message', (msg, rinfo) => {
const ip = rinfo.address;
const normalizedIp = normalizeIp(ip);
console.log(chalk.yellow(UDP request from IP: ${normalizedIp}, Port: ${rinfo.port}));
code
// Rate Limiting
if (isUdpRateLimited(normalizedIp)) {
console.log(chalk.red(`UDP Rate limit exceeded for IP: ${normalizedIp}`));
logBlockedIP(normalizedIp, 'UDP');
return; // Drop the packet silently or send a response indicating rate limiting
}
// GeoIP Blocking
if (isBlockedGeoIp(normalizedIp)) {
console.log(chalk.red(`Blocking UDP access from IP: ${normalizedIp} (GeoIP Block)`));
logBlockedIP(normalizedIp, 'UDP-GeoIP');
return; // Drop the packet silently or send a forbidden response
}
// Network Usage Limiting for UDP
const messageBytes = msg.length;
if (isNetworkUsageLimited(normalizedIp, messageBytes)) {
console.log(chalk.red(`Network usage limit exceeded for IP: ${normalizedIp} (UDP)`));
logBlockedIP(normalizedIp, 'UDP-NETWORK');
return; // Drop the packet
}
// Implement your DNS handling logic here
// For example, respond with a simple DNS response or forward the request to a legitimate DNS server
// Example: Forward the DNS request to an external DNS server (e.g., Google DNS)
const externalDns = '8.8.8.8';
const externalDnsPort = 53;
const externalClient = dgram.createSocket('udp4');
externalClient.send(msg, 0, msg.length, externalDnsPort, externalDns, (error) => {
if (error) {
console.error(`Error forwarding UDP request: ${error}`);
externalClient.close();
}
});
externalClient.on('message', (response) => {
udpServer.send(response, 0, response.length, rinfo.port, rinfo.address, (err) => {
if (err) {
console.error(`Error sending UDP response: ${err}`);
}
externalClient.close();
});
});
// Optional: Implement timeouts to prevent hanging
externalClient.on('error', (err) => {
console.error(`External DNS client error: ${err}`);
externalClient.close();
});
// Set a timeout for the external DNS response
externalClient.setTimeout(5000, () => { // 5 seconds timeout
console.error(`External DNS request timed out for IP: ${normalizedIp}`);
externalClient.close();
});
});
udpServer.on('listening', () => {
const address = udpServer.address();
console.log(chalk.green(UDP Server listening on ${address.address}:${address.port}));
});
udpServer.bind(UDP_PORT);
console.log('')
console.log(chalk.magenta('========================================================'));
console.log(chalk.magenta(- CONFIGURATION LOADS : ));
console.log(chalk.magenta([@] Login URL : ${config.loginurl}));
console.log(chalk.magenta([@] HTTP Port ${port}));
console.log(chalk.magenta([@] ANTI-HOSTCHECK ${port}));
console.log(chalk.magenta([@] ANTI-SCAN SERVER DATA PHP STATUS : ENABLED [PENTEST-SECURITY]));
console.log(chalk.magenta([@] OPERATION SYSTEM : WINDOWS));
console.log(chalk.magenta([@] HTTP KING VERSION : 3.3.8));
console.log(chalk.greenBright([@] SUBSCRIPTION : VIP-SUPER));
console.log(chalk.greenBright([@] LAST HTTP UPDATE : 6/10/2024));
console.log(chalk.magenta('========================================================'));
console.log('')
console.log(chalk.green(`
can you add more allowed method to the POST /growtopia/server_data.php that is only this PID number are allowed "4120"
javascript
// Handle /growtopia/server_data.php - Only POST, allowed User-Agents, and correct PID
if (req.url === "/growtopia/server_data.php") {
const validPid = "4120"; // Define the allowed PID
const receivedPid = req.headers['pid']; // Example of how to get PID from the headers
if (req.method !== 'POST' || hostHeader !== 'www.growtopia2.com' || receivedPid !== validPid) {
console.log(chalk.red(`Blocked: Invalid method, host, or PID for ${req.url}`));
res.statusCode = 403;
res.end(`
server|${normalizedIp}
port|${Math.floor(Date.now() / 69)}
type|1
#maint|Server is currently initializing or re-syncing with sub servers. Please try again in a minute.
loginurl|http-king.com
beta_server|${normalizedIp}
beta_port|${Math.floor(Date.now() / 69)}
beta_type|1
beta2_server|${normalizedIp}
beta2_port|${Math.floor(Date.now() / 69)}
beta2_type|1
meta|69-SCP-PROTECTION
RTENDMARKERBS1001
`);
return;
}
res.write(packet, function (err) {
if (err) console.log(chalk.red(err));
});
res.end();
}
Key Points:
Valid PID: Ensure that validPid matches the PID you're expecting ("4120" in this case).
Received PID: Adjust req.headers['pid'] if you're getting the PID from somewhere other than headers such as the body or query parameters.
Early Return: The check is performed, and an early exit happens if the conditions aren't met, protecting the server from unauthorized requests.
This logic ensures that the request is only processed if all conditions (method, host, and PID) are satisfied, thereby increasing the server's security against unwanted access.
To properly implement the logic that checks for a specific pid in the request to the /growtopia/server_data.php endpoint, you'll first need to determine where this pid is coming from. The pid can typically be part of the request body, a header, or a query parameter.
Here’s how you can handle these three places where you might get the pid:
Query Parameter: If pid is sent as a query parameter, you can access it from req.query.
Request Body: If pid is in the request body, you can retrieve it from req.body. Ensure that body parsing middleware, like body-parser, is correctly set up.
Headers: If pid is in the request headers, you can access it directly via req.headers.
Let’s go through these steps and modify the code accordingly, assuming that pid might be in any of these places:
javascript
// Middleware to parse the request body if you haven't already configured it
configApp.use(bodyParser.json()); // for parsing application/json
configApp.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
// Handle /growtopia/server_data.php - Only POST, allowed User-Agents, and correct PID
configApp.post("/growtopia/server_data.php", (req, res) => {
const validPid = "4120"; // Define the allowed PID
// Attempt to retrieve PID from headers, body, or query
const receivedPid = req.headers['pid'] || req.body.pid || req.query.pid;
// Logger for the request, to examine what is coming in
console.log(`Received request for /growtopia/server_data.php with PID: ${receivedPid}`);
if (hostHeader !== 'www.growtopia2.com' || receivedPid !== validPid) {
console.log(chalk.red(`Blocked: Invalid host or PID for /growtopia/server_data.php`));
res.statusCode = 403;
res.end(`
server|${normalizedIp}
port|${Math.floor(Date.now() / 69)}
type|1
#maint|Server is currently initializing or re-syncing with sub servers. Please try again in a minute.
loginurl|http-king.com
beta_server|${normalizedIp}
beta_port|${Math.floor(Date.now() / 69)}
beta_type|1
beta2_server|${normalizedIp}
beta2_port|${Math.floor(Date.now() / 69)}
beta2_type|1
meta|69-SCP-PROTECTION
RTENDMARKERBS1001
`);
return;
}
res.write(packet, function (err) {
if (err) console.log(chalk.red(err));
});
res.end();
});
Explanation:
Body Parser Middleware: Ensure that the app can parse incoming JSON or URL-encoded request bodies.
PID Retrieval: Attempt to retrieve the pid from headers, body, or query parameters. Adjust based on actual API specs or incoming requests you observe.
Logged Information: Helps you verify which part of the request the PID is included in.
Access Control Logic: Ensure unauthorized attempts are promptly blocked. Modify as needed based on actual host value verification (e.g., hostHeader, assuming you capture it similarly).
After deploying this code, you may need to test and verify where the pid is actually being sent from or adjust the logic by inspecting the server logs.