-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
308 lines (287 loc) · 8.57 KB
/
index.ts
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
import express, {Response} from "express";
import exphbs from "express-handlebars";
import cookieParser from "cookie-parser";
import {hash, formatDuration, sendAndReceive} from "./util.js";
import {User, Site} from "./types.js";
import {v4 as uuid} from "uuid";
import fetch from "node-fetch";
const app = express();
app.engine(
"hbs",
exphbs({
extname: "hbs",
})
);
app.set("view engine", "hbs");
if (!process.env.PORT) {
throw new Error("Must put port or unix socket in PORT env var.");
}
let FLAG: string;
if (!process.env.FLAG) {
console.error("WARNING: No FLAG env var. Using placeholder flag instead.");
FLAG = "flag{placeholder_flag}";
} else {
FLAG = process.env.FLAG;
}
const PORT = process.env.PORT;
const EXPIRATION_TIME =
Number(process.env.EXPIRATION_TIME) || 24 * 60 * 60 * 1000;
let RECAPTCHA_KEYS: {
site: string;
secret: string;
} | null = null;
if (process.env.RECAPTCHA_KEYS) {
const [site, secret] = process.env.RECAPTCHA_KEYS.split(":");
if (!site || !secret) {
console.error(
"WARNING: RECAPTCHA_KEYS needs to be in the format site_key:secret_key. Ignoring."
);
} else {
RECAPTCHA_KEYS = {
site,
secret,
};
}
}
const LB_HOST = process.env.LB_HOST;
if (!LB_HOST) {
throw new Error("Must include LB_HOST environment variable.");
}
const LB_PORT = Number(process.env.LB_PORT);
if (!LB_PORT) {
throw new Error("Must include LB_PORT environment variable.");
}
let SELF_LOC = process.env.SELF_LOC;
if (!SELF_LOC) {
throw new Error("Must include SELF_LOC environment variable.");
}
if (!SELF_LOC.endsWith("/")) {
SELF_LOC += "/";
}
const SELF_DOMAIN = SELF_LOC.split("://")[1].split("/")[0];
const users: Record<string, User> = {};
const sites: Record<string, Site> = {};
const ADMIN_ID = uuid();
users[ADMIN_ID] = {
sites: {},
created: new Date(),
id: ADMIN_ID
};
app.use(cookieParser());
app.use(express.urlencoded({extended: false}));
app.use(function (req, res, next) {
// stay protected
res.set("X-Frame-Options", "DENY");
res.set("Content-Security-Policy", "default-src 'self'; frame-src 'none'; script-src 'self' https://www.google.com/recaptcha/api.js");
const token: string | undefined = req.cookies.sessid;
let user: User;
if (!token || !(token in users)) {
const newToken = uuid();
user = {
sites: {},
created: new Date(),
id: newToken,
};
users[newToken] = user;
res.cookie("sessid", newToken, {
httpOnly: true,
sameSite: "strict",
expires: new Date(Date.now() + EXPIRATION_TIME),
});
} else {
user = users[token];
}
res.locals.user = user;
next();
});
function renderHome(res: Response, error?: string, text: string = "") {
res.render("home", {
sites: Object.entries((res.locals.user as User).sites)
.sort((a, b) => b[1].created.getTime() - a[1].created.getTime())
.map((x) => ({
id: x[1].id,
time: formatDuration(x[1].created, new Date()),
})),
error,
text,
});
}
function getSiteContent(site: Site): string {
return site.content;
}
app.get("/", function (req, res) {
renderHome(res);
});
app.get("/flag", function (req, res) {
if (req.cookies.sessid === ADMIN_ID) {
res.type("text/plain").send(FLAG);
} else {
res.type("text/plain").status(401).send("no flag for you :)");
}
});
app.post("/site", function (req, res) {
if (!req.body.content || typeof req.body.content !== "string") {
res.status(400);
renderHome(res, "Must include a non-empty site content.");
return;
}
if (req.body.content.length > 1500) {
res.status(400);
renderHome(res, "Content must be at most 1500 chars.");
return;
}
const user: User = res.locals.user;
let content = req.body.content.trim();
const siteHash = hash(content);
if (siteHash in user.sites) {
res.status(400);
renderHome(res, "Site with identical content already exists.");
return;
}
const id = uuid();
const site: Site = {
type: req.body.type,
content: content,
created: new Date(),
id,
hash: siteHash,
};
sites[site.id] = site;
user.sites[site.hash] = site;
res.redirect("/");
});
app.get("/api/sites/raw/:siteid", function (req, res) {
if (!(req.params.siteid in sites)) {
res.status(400).send("Could not find note.");
return;
}
const site = sites[req.params.siteid];
res.send(site.content);
});
app.get("/sites/:siteid", function (req, res) {
if (!(req.params.siteid in sites)) {
res.status(400).render("error_page", {
error: "Could not find note.",
});
return;
}
const site = sites[req.params.siteid];
res.type("text/html").send(getSiteContent(site));
});
app.get("/report/:siteid", function (req, res) {
if (!(req.params.siteid in sites)) {
res.status(400).render("error_page", {
error: "Could not find site.",
});
return;
}
// disable csp on report site to run recaptcha scripts
res.set("Content-Security-Policy", "");
res.render("report", {
recaptcha: RECAPTCHA_KEYS,
id: req.params.siteid,
});
});
app.post("/report/:siteid", async function (req, res) {
if (!(req.params.siteid in sites)) {
res.status(400).render("error_page", {
error: "Could not find site.",
});
return;
}
const site = sites[req.params.siteid];
const captcha = req.body["g-recaptcha-response"];
if (RECAPTCHA_KEYS && (!captcha || typeof captcha !== "string")) {
res.status(400).render("report", {
recaptcha: RECAPTCHA_KEYS,
id: req.params.siteid,
error: "Missing RECAPTCHA. Is Javascript enabled?",
});
return;
}
if (RECAPTCHA_KEYS) {
const validation = (await fetch(
"https://www.google.com/recaptcha/api/siteverify",
{
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
secret: RECAPTCHA_KEYS.secret,
response: captcha,
}).toString(),
}
).then((res) => res.json())) as {success: boolean};
if (!validation.success) {
res.status(400).render("report", {
recaptcha: RECAPTCHA_KEYS,
id: req.params.siteid,
error: "Invalid RECAPTCHA. Try submitting again?",
});
return;
}
}
const visitRes = await sendAndReceive(
LB_PORT,
LB_HOST,
"c" +
JSON.stringify({
type: "VISIT",
value: {
url: SELF_LOC + "sites/" + req.params.siteid,
cookies: [
{
name: "sessid",
value: ADMIN_ID,
sameSite: "Strict",
httpOnly: true,
domain: SELF_DOMAIN,
},
],
},
}) +
"\n",
true
);
const parsedVisit = JSON.parse(visitRes.trim());
if (parsedVisit.type === "VISIT_RESULT" && parsedVisit.value) {
res.redirect("/");
} else {
res.status(400).render("report", {
recaptcha: RECAPTCHA_KEYS,
id: req.params.siteid,
error: "The report failed. Try reporting again?",
});
}
});
app.use(express.static("./static"));
// cleanup
setInterval(function () {
const threshold = Date.now() - EXPIRATION_TIME;
for (const key in users) {
// don't remove admin
if (key === ADMIN_ID) {
continue;
}
if (users[key].created.getTime() < threshold) {
delete users[key];
}
}
for (const key in sites) {
if (sites[key].created.getTime() < threshold) {
delete sites[key];
}
}
}, 15000);
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}.`);
console.log(`Using flag ${FLAG}.`);
if (RECAPTCHA_KEYS) {
console.log(
`Using RECAPTCHA site key "${RECAPTCHA_KEYS.site}" and secret key "${RECAPTCHA_KEYS.secret}".`
);
} else {
console.log("RECAPTCHA disabled.");
}
});