Skip to content

Instantly share code, notes, and snippets.

@HamdaanAliQuatil
Created January 2, 2024 23:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HamdaanAliQuatil/c7db6f3dd0666bd9396a7f4e6ebe6665 to your computer and use it in GitHub Desktop.
Save HamdaanAliQuatil/c7db6f3dd0666bd9396a7f4e6ebe6665 to your computer and use it in GitHub Desktop.
Defending against SSRF attacks
const express = require("express");
const axios = require("axios");
const fs = require("fs").promises;
const path = require("path");
const app = express();
const port = 3000;
// Function to fetch private resource
const fetchPrivateResource = async () => {
try {
const content = await fs.readFile("data.json", "utf-8");
return content;
} catch (error) {
console.error("Error reading private resource:", error.message);
throw error;
}
};
app.get("/fetch", async (req, res) => {
const url = req.query.url;
try {
const response = await axios.get(url);
const responseData = JSON.stringify(response.data);
const filename = path.basename(url);
const textFilePath = path.join(__dirname, "uploads", "upload-data.txt");
await fs.writeFile(textFilePath, responseData, "utf-8");
res.send("Upload Successful");
} catch (error) {
console.error("Error:", error.message);
res.status(500).send("Internal Server Error");
}
});
// Serve uploaded files over the internet
app.get("/uploads/:filename", async (req, res) => {
const filename = req.params.filename;
const filePath = path.join(__dirname, "uploads", filename);
console.log(filePath);
try {
// Check if file exists
await fs.access(filePath);
// If file exists, send it to the client
res.sendFile(filePath);
} catch (error) {
res.status(404).send("File not found: " + error);
}
});
// middleware to protect admin API
app.use("/admin", async (req, res, next) => {
const isLocalhost =
req.hostname === "localhost" || req.hostname === "127.0.0.1";
if (isLocalhost) {
next();
} else {
res.status(403).send("Forbidden");
}
});
// Route to access the admin API
app.get("/admin", async (req, res) => {
try {
const content = await fetchPrivateResource();
res.send(content);
} catch (error) {
res.status(500).send("Internal Server Error");
}
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
{
"name": "Hamdaan Ali Quatil",
"password": "violinblackeye"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment