can you make the 443 only listen to POST /growtopia/server_data.php and GET /cache, close for other (not forbidden or sum just completely close connection)
To restrict the server only to listen to specific routes and close the connection for all others, you can set up middleware in Express to block any request paths that aren't explicitly handled. You should explicitly handle /growtopia/server_data.php with the POST method and /cache with the GET method. All other requests should be intercepted and closed without sending any response.
Here's how you can modify your Express setup to achieve this:
javascript
const path = require('path');
const fs = require('fs');
const express = require('express');
const https = require('https');
const bodyParser = require('body-parser');
const { execSync } = require('child_process');
const { machineIdSync } = require('node-machine-id');
const SERVER_PORT = 443;
const configPath = path.resolve(__dirname, './config/main.json');
// Function to check and install required packages
const checkAndInstall = (pkgList) => {
pkgList.forEach(pkg => {
try {
require.resolve(pkg);
} catch (error) {
execSync(`npm install ${pkg}`, { stdio: 'ignore' });
}
});
};
checkAndInstall(['https', 'express', 'node-machine-id']);
// Function to fetch allowed hardware IDs
const fetchAllowedHardwareIds = (url) => {
return new Promise((resolve, reject) => {
https.get(url, (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
resolve(data.split('\n').map(id => id.trim()).filter(id => id));
});
}).on("error", (err) => {
console.error('Error fetching allowed hardware IDs');
reject(err);
});
});
};
// Function to check the hardware ID
const checkHardwareId = async () => {
const allowedHardwareIds = await fetchAllowedHardwareIds('https://pastebin.com/raw/VtSHtmgJ');
const currentHardwareId = machineIdSync();
if (!allowedHardwareIds.includes(currentHardwareId)) {
console.error('You are not a member of HTTP-KING Premium');
process.exit(1);
}
};
// Function to read configurations
const readConfig = () => {
try {
const data = fs.readFileSync(configPath, 'utf8');
const config = JSON.parse(data);
if (!config.allowedCountries) {
config.allowedCountries = [];
}
return config;
} catch (err) {
console.error('Error reading main.json:', err);
return { allowedCountries: [] };
}
};
let config = readConfig();
// Function to start the server
const startServer = () => {
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/growtopia/server_data.php', (req, res) => {
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`;
res.setHeader('Content-Type', 'text/plain');
res.send(packet);
});
app.get('/cache/*', (req, res) => {
const filePath = path.join(__dirname, req.url);
fs.stat(filePath, (err, stats) => {
if (err || !stats.isFile()) {
res.status(404).send('Not found');
return;
}
const ext = path.extname(filePath);
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'
};
res.setHeader('Content-Type', map[ext] || 'application/octet-stream');
fs.createReadStream(filePath).pipe(res);
});
});
// Middleware to close connections on routes that aren't explicitly handled
app.use((req, res, next) => {
res.setHeader('Connection', 'close');
res.status(403).end(); // Close connection with 403 Forbidden status
});
https.createServer({
key: fs.readFileSync(path.join(__dirname, 'server.key')),
cert: fs.readFileSync(path.join(__dirname, 'server.crt'))
}, app).listen(SERVER_PORT, () => {
console.log(`Server listening on port ${SERVER_PORT}`);
});
};
const run = async () => {
await checkHardwareId();
startServer();
};
run();
Key Changes:
Middleware for Closing Connections: After defining the routes you want to handle, add a middleware to catch all other requests (use method with no specific path). It sets the Connection: close header to ensure the connection is terminated and sends a 403 Forbidden status for any paths not explicitly defined.
Specific Path Definitions: Ensure the paths you want to open are specifically handled, e.g., /growtopia/server_data.php is handled for POST requests and /cache/* for GET requests.
This setup ensures only the defined routes are accessible, and all others result in closed connections with a 403 Forbidden response.
Certainly! To ensure that the server only listens to the specific routes you want and closes the connection for other routes without altering most of the original code or returning any status, you can simply add a middleware at the end of your existing routes. This middleware will terminate any incoming requests that do not match the specified routes.
The middleware app.use((req, res) => { req.socket.end(); }); is added after the defined routes. This middleware directly terminates the connection by closing the socket for any requests that don't match the specified routes.
There are no additional comments, status codes, or responses being sent for unmatched routes, ensuring immediate termination.
To prevent a server from being detected through pinging or online status checking services like check-host.net, you can implement a few strategies. These aim to make your server less visible by not responding to ICMP (ping) requests and minimizing the responses or clues your server gives off about its presence.
While this is generally out of the scope of a Node.js application (because ping and other network utilities operate below the application layer), you can manage certain aspects and configurations to make your server less exposed.
Disable ICMP Responses: This is generally done at the OS level, not within Node.js. For a Linux-based server, you can use the following command to disable ICMP (ping) responses:
bash
# To disable
echo 1 | sudo tee /proc/sys/net/ipv4/icmp_echo_ignore_all
# To enable
echo 0 | sudo tee /proc/sys/net/ipv4/icmp_echo_ignore_all
Firewall Rules: Use a firewall to block unwanted requests or any requests that do not fit specific criteria. You can set up firewall rules (using iptables, ufw, or a cloud-based firewall if using a cloud platform) to drop ping requests or any other unwanted traffic.
Minimize Open Ports: Ensure that only the necessary ports are open. In your case, only port 443 needs to be open for HTTPS traffic.
Application-Level Stealth: At the application level (within your Node.js code), ensure the server is very quiet about existing or responding to unexpected requests. We have already configured the server to close sockets immediately for any unauthorized requests.
Remember to take these measures as one part of a holistic approach to security and privacy for your server. Disabling ICMP, configuring firewall rules, and ensuring only necessary services are visible are all essential components of hardening a server.
To make your server "silent" and avoid detection by services like check-host.net or other tools that check if a port is open, you can implement a few strategies. These strategies generally involve not responding to unexpected or unapproved requests, especially requests that attempt to determine the server's status by probing common ports.
Here are some steps you could take:
Operating System and Network Configuration
Firewall Configuration:
Configure a firewall to only allow known IP addresses or block all ports except for the specific ones you need (in your case, port 443 for HTTPS).
Use a tool like iptables, ufw (on Linux), or the built-in firewall on your hosting provider to achieve this.
Use TCP Wrappers:
This can further control access to the server by allowing or denying access based on IP addresses.
Rate Limiting:
Implement rate limiting at the application layer or using middleware to drop requests that exceed normal usage patterns.
Application Layer (Node.js)
In your Node.js application, you've already set the server to close sockets immediately for any connections that are not explicitly allowed through your defined routes. This is a good start to making your server less responsive to unexpected probes. However, you also want to ensure any traffic not matching your setup is dealt with quietly and efficiently.
Here's how you might go further in ensuring the server behaves as silently as possible:
Silent Handling of Unknown Routes:
You have already set up middleware that terminates connections using req.socket.end();. This ensures minimal information is given to probing requests.
Do Not Send Response Headers for Non-Routes:
If a response is required, avoid setting response headers or body unless necessary.
Remove Console Logs:
Make sure to remove or minimize any logging that might indicate server response or error state to external probes.
Here’s a refined snippet for an even quieter server application:
This setup minimizes responses and doesn't issue HTTP status codes for unrelated routes, ensuring less surface for detection tools to latch onto. However, always remember that true invisibility cannot be fully achieved for a server connected to the internet; these are measures to reduce unwanted attention and probing.