-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
292 lines (252 loc) · 8.5 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
const express = require("express");
const config = require("./config.json");
const fs = require("fs");
const asyncfs = require("fs").promises;
const upload = require("express-fileupload");
const bodyParser = require("body-parser");
const rand = require("random-id");
const mime = require("mime-types");
const { Readable } = require("stream");
const path = require("path");
const crypto = require("crypto");
require("path");
const zlib = require("zlib");
const AppendInitVect = require("./appendInitVect");
let cooldown = new Set();
let bandwidth = 0;
fs.readFile("./bandwidth.json", "utf8", (err, data) => {
if (err) {
console.log(err);
} else {
bandwidth = JSON.parse(data).bandwidth;
}
});
const app = express();
app.use(express.static("public"));
app.use(
upload({
preserveExtension: true,
safeFileNames: true,
limits: { fileSize: 10000000000000000000 * 1024 * 1024 },
})
);
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
setInterval(() => {
// write bandwidth
fs.writeFileSync(
"./bandwidth.json",
JSON.stringify({ bandwidth: bandwidth }),
"utf8"
);
}, 10 * 60 * 1000);
app.post("/upload", function (req, res) {
if (!req.files) {
res.status(404).send("no file sent");
}
const file = req.files.file;
let password;
if (req.query["randomKey"]) {
password = rand(10, "aA0");
} else {
password = req.body.key;
}
const id = rand(6, "aA0");
const ext = mime.extension(file.mimetype);
let e = ext.toLowerCase();
const fileName = id + "." + ext;
if (e.includes("htm") || e.includes("php") || e.includes("xml")) {
return res.status(403).send("File extension not allowed");
}
if (config.Cloudflare) {
if (
cooldown.has(req.headers["x-forwarded-for"]) &&
req.header("auth") !== config.BypassCooldownToken
) {
return res
.status(429)
.send("You can only upload a file every 15 seconds.");
} else {
cooldown.add(req.headers["x-forwarded-for"]);
setTimeout(() => {
cooldown.delete(req.headers["x-forwarded-for"]);
}, 15 * 1000);
}
} else {
if (
cooldown.has(req.connection.remoteAddress) &&
req.header("auth") !== config.BypassCooldownToken
) {
return res
.status(429)
.send("You can only upload a file every 15 seconds.");
} else {
cooldown.add(req.connection.remoteAddress);
setTimeout(() => {
cooldown.delete(req.connection.remoteAddress);
}, 15 * 1000);
}
}
encrypt(file, password, fileName);
if (req.query["randomKey"]) {
res.send(`https://${req.headers.host}/${fileName}?key=${password}`);
} else {
res.send(
`<a href="https://${req.headers.host}/${fileName}?key=${password}">https://${req.headers.host}/${fileName}?key=${password}</a>`
);
}
});
// legacy
app.get("/decrypt", function (req, res) {
const fileName = req.query.id;
const password = req.query.key;
if (!password) {
return res.status(403).end("No key specified");
}
if (fs.existsSync(__dirname + "/files/" + fileName + ".enc")) {
decrypt(fileName, password, res);
} else {
res.status(404).send("File does not exist");
}
});
app.get("/totalsize", function (req, res) {
res.set("Cache-control", "public, max-age=0").send({
usage: convertBytes(getTotalSize("./files")),
bandwidth: convertBytes(bandwidth),
});
});
app.get("/:filename", function (req, res) {
const fileName = req.params.filename;
const password = req.query.key;
if (!password) {
return res.status(403).end("No key specified");
}
if (fs.existsSync(__dirname + "/files/" + fileName + ".enc")) {
decrypt(fileName, password, res);
} else {
res.status(404).send("File does not exist");
}
});
app.listen(config.port, config.bindIP);
const getAllFiles = function (dirPath, arrayOfFiles) {
let files = fs.readdirSync(dirPath);
arrayOfFiles = arrayOfFiles || [];
files.forEach(function (file) {
if (fs.statSync(dirPath + "/" + file).isDirectory()) {
arrayOfFiles = getAllFiles(dirPath + "/" + file, arrayOfFiles);
} else {
arrayOfFiles.push(path.join(__dirname, dirPath, file));
}
});
return arrayOfFiles;
};
const getTotalSize = function (directoryPath) {
const arrayOfFiles = getAllFiles(directoryPath);
let totalSize = 0;
arrayOfFiles.forEach(function (filePath) {
totalSize += fs.statSync(filePath).size;
});
return totalSize;
};
const convertBytes = function (bytes) {
const sizes = ["Bytes", "KB", "MB", "GB", "TB"];
if (bytes === 0) {
return "n/a";
}
const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
if (i === 0) {
return bytes + " " + sizes[i];
}
return (bytes / Math.pow(1024, i)).toFixed(1) + " " + sizes[i];
};
async function encrypt(file, password, name) {
const initVect = crypto.randomBytes(16);
const CIPHER_KEY = getCipherKey(password);
const readStream = Readable.from(file.data);
const gzip = zlib.createGzip();
const cipher = crypto.createCipheriv("aes256", CIPHER_KEY, initVect);
const appendInitVect = new AppendInitVect(initVect);
const writeStream = fs.createWriteStream(
__dirname + "/files/" + name + ".enc"
);
// write to file
readStream.pipe(gzip).pipe(cipher).pipe(appendInitVect).pipe(writeStream);
// create an hmac for integrity verification
const hmac = crypto
.createHmac("sha256", password)
.update(file.data)
.digest("hex");
// write hmac to a file
await asyncfs.writeFile(
__dirname + "/files/" + name + ".hmac",
hmac,
"utf8"
);
}
async function decrypt(file, password, res) {
const readInitVect = fs.createReadStream(
__dirname + "/files/" + file + ".enc",
{ end: 15 }
);
let initVect;
readInitVect.on("data", (chunk) => {
initVect = chunk;
});
readInitVect.on("close", () => {
const cipherKey = getCipherKey(password);
const readStream = fs.createReadStream(
__dirname + "/files/" + file + ".enc",
{ start: 16 }
);
const decipher = crypto.createDecipheriv("aes256", cipherKey, initVect);
const unzip = zlib.createUnzip();
const writeStream = fs.createWriteStream(__dirname + "/files/" + file);
let pipeshit = readStream.pipe(decipher).pipe(unzip).pipe(writeStream);
unzip.on("error", function (err) {
res.status(500).send("Failed to decompress, probably wrong key?");
res.end(err);
fs.unlinkSync(__dirname + "/files/" + file);
});
pipeshit.on("finish", () => {
fs.stat(__dirname + "/files/" + file, (err, stats) => {
if (err) {
console.log(`File doesn't exist.`);
} else {
bandwidth = bandwidth + stats.size;
}
});
// verify hmac
const hmac = crypto
.createHmac("sha256", password)
.update(fs.readFileSync(__dirname + "/files/" + file))
.digest("hex");
const fsHmac = fs.readFileSync(
__dirname + "/files/" + file + ".hmac",
"utf8"
);
// check to see if the computed hmac is the same as the one on fs
if (hmac !== fsHmac) {
// tell the user that the file is corrupted or tampered
res.status(500).send(
"HMAC Mismatch: File is corrupted or tampered"
);
return;
}
// send decrypted file back to client
res.header("abuse", config.abuseHeaderMessage).sendFile(
__dirname + "/files/" + file,
function (error) {
if (error) {
console.log(error);
res.status(500).end("Error!");
}
fs.unlinkSync(__dirname + "/files/" + file);
}
);
});
});
}
function getCipherKey(password) {
return crypto.createHash("sha256").update(password).digest();
}
process.on("uncaughtException", function (err) {});