This repository has been archived by the owner on Nov 8, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
util.ts
510 lines (493 loc) · 17.8 KB
/
util.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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
/* eslint-disable @typescript-eslint/no-explicit-any */
import axios from "axios";
import * as Config from "./config";
import log, { LogLevel } from "./logging";
import { getConfigs, getDemoStaticFiles } from "./setup";
import crypto from "crypto";
import path from 'path';
import { i2pJanitor } from "./prokurilo";
export const jail: Config.JailedToken[] = [];
const ACCEPTING_TUNNELS = 'Accepting tunnels'
const REJECTING_TUNNELS = 'Rejecting tunnels: Starting up'
const NODE_ENV = process.env.NODE_ENV || "";
/* himitsu specific */
let himitsuName = '';
let walletIsSet = false;
let addressIsSet = false;
let signatureIsSet = false;
let himitsuConfigured = false;
let himitsuExpiration = 0;
let data = crypto.randomBytes(32).toString('hex');
/* himitsu specific */
let i2pKillSwitchCheck = 0;
let i2pStatus = '';
let i2pReconnect = false;
let utilI2pJanitor = setInterval(() => {/* initialize reconnect janitor for event loop */}, 0);
const verifyHimitsuSignature = async (address: string, signature: string): Promise<boolean> => {
const body = {
jsonrpc: Config.RPC.VERSION,
id: Config.RPC.ID,
method: Config.RPC.VERIFY,
params: { address, data, signature },
};
try {
const sResponse = await (await axios.post(`http://${Config.XMR_RPC_HOST}/json_rpc`, body)).data;
return sResponse.result.good;
} catch {
return false;
}
}
/**
* Use one time challenge to configure himitsu.
* 1. Start monero-wallet-rpc
* 2. Start prokurilo with --himitsu-rpc-restrict flag
* 3. On wallet initialization Himitsu will request the challenge
* from prokurilo. It will then take the challenge and use
* it as data for signing.
* 4. On the initial request himitsu fails with 403 and
* challenge response. Next it sends primary address and
* signature for validation.
* 5. Set himitsu configured and challenge address
* 6. New challenge generated after cookie expiration with 401
* 7. Continue to send signature to match challenge for each additional auth
* NOTE: An attacker would somehow need to get the challenge which is
* not possible because a new 32-byte challenge is generated on each session.
* Himitsu does not store this challenge, and the signature is place in a
* cryptographically signed cookie with the address to maintain the user session.
* Himitsu has a password lock screen which with a secure enough
* password makes the wallet inaccessible.
* basic <address:signature> on the first request "handshake"
* verify the custom himitsu cookie on each request
* @param auth - basic auth for himitsu
*/
const configureHimitsu = async (auth: string, req: any, res: any) => {
const parseIt = auth && auth.length > 0 && auth.indexOf(":") > 0 ? auth.split("basic ")[1] : '';
const address = parseIt !== '' ? parseIt.split(":")[0] : '';
const signature = parseIt !== '' ? parseIt.split(":")[1] : '';
if (addressIsSet && walletIsSet && signatureIsSet && address.length > 0 && signature.length > 0) {
log(`checking signature for configuration`, LogLevel.DEBUG, true);
if (await verifyHimitsuSignature(address, signature)){
log(`configuring himitsu instance`, LogLevel.INFO, true);
himitsuConfigured = true;
himitsuExpiration = Date.now() + Config.HIMITSU_TTL;
res.status(Config.Http.OK).send({ expire: himitsuExpiration});
} else {
log(`himitsu configuration failure`, LogLevel.ERROR, true);
res
.status(Config.Http.FORBIDDEN)
.header("www-authenticate", `challenge=${data}`)
.send();
}
} else if ((!addressIsSet || !walletIsSet || !signatureIsSet) && req.body.method) {
log(`bypass for signing only`, LogLevel.WARN, true);
if (req.body.method === 'create_wallet' || req.body.method === 'open_wallet'
|| req.body.method === 'restore_deterministic_wallet') {
himitsuName = req.body.params.filename;
walletIsSet = true;
log(`wallet is set`, LogLevel.DEBUG, true);
}
if (req.body.method === 'get_address') {
log(`address is set`, LogLevel.DEBUG, true);
addressIsSet = true;
}
if (req.body.method === 'sign') {
log(`signature is set`, LogLevel.DEBUG, true);
signatureIsSet = true;
}
passThrough(req, res, null); // one time deal for the handshake
} else {
log(`himitsu configuration failure`, LogLevel.ERROR, true);
res
.status(Config.Http.FORBIDDEN)
.header("www-authenticate", `challenge=${data}`)
.send();
}
};
/**
* Entry point post-cofiguration. After the himitsu custom cookie
* expires the client will return for the wallet name, re-open
* the wallet and sign a new challenge.
* @param req request
* @param res response
*/
const verifyHimitsu = async (req: any, res: any) => {
const himitsu = req.headers.himitsu;
const address = himitsu ? himitsu.split(':')[0] : '';
const signature = himitsu ? himitsu.split(':')[1] : '';
if (await verifyHimitsuSignature(address, signature) && himitsuExpiration > Date.now()) {
log(`welcome back himitsu!`, LogLevel.INFO, true);
passThrough(req, res, null);
} else if (await !verifyHimitsuSignature(address, signature)) {
res.status(Config.Http.FORBIDDEN).send();
} else {
// a new challenge has arrived!
log(`invalid himitsu session detected`, LogLevel.DEBUG, true);
addressIsSet = false;
walletIsSet = false;
signatureIsSet = false;
himitsuConfigured = false;
data = crypto.randomBytes(32).toString('hex');
const body = { jsonrpc: Config.RPC.VERSION, id: Config.RPC.ID, method: Config.RPC.CLOSE };
await axios.post(`http://${Config.XMR_RPC_HOST}/json_rpc`, body);
res.status(Config.Http.UNAUTHORIZED).json({ himitsuName }).send();
}
};
/**
* Hash the signature and store hash temporarily
* for anti-spam measures.
* TODO: this won't scale. Implement MongoDB
* @param proof - signature from reserve proof
*/
const jailToken = (proof: string): void => {
const timestamp = Date.now();
const hash = crypto.createHash("sha256");
hash.update(proof);
const signature = hash.copy().digest("hex");
jail.push({ timestamp, signature });
};
/**
* Check jail (cache) for a signature hash
* @param proof - reserve proof signature
* @returns - boolean
*/
const isJailed = (proof: string): boolean => {
let match = false;
const hash = crypto.createHash("sha256");
hash.update(proof);
const h_signature = hash.copy().digest("hex");
if (jail.length === 0) return false;
jail.forEach((j) => {
if (j.signature === h_signature) {
log(`token in jail since ${j.timestamp}`, LogLevel.DEBUG, true);
match = true;
}
});
return match;
};
/**
* Validate uri requested against documented assets
* @param uri - uri of asset
* @returns Asset
*/
const validateAsset = (uri: string): Config.Asset => {
log(`validate asset for uri: ${uri}`, LogLevel.DEBUG, true);
const sConfig: string = getConfigs().toString();
const assets: Config.Asset[] = JSON.parse(sConfig).assets;
let vAsset = null;
assets.forEach((a) => {
if (a.uri === uri) {
vAsset = a;
}
});
return vAsset;
};
/**
* Bypass uri requested against documented assets
* @param uri - uri of asset
* @returns Asset
*/
const bypassAsset = (req: any): boolean => {
log(`checking bypass asset for uri: ${req.url}`, LogLevel.DEBUG, true);
const sConfig: string = getConfigs().toString();
const uris: string[] = JSON.parse(sConfig).bypass;
/* In the demo static content is getting injected from the examples
This should be ok in order to serve but normally things like images
won't be on this server.
*/
const d = getDemoStaticFiles();
const isDemoContent = Config.LOCAL_HOSTS.indexOf(req.ip) > -1
&& d.indexOf(req.url.replace("/", "")) > -1 && NODE_ENV === 'test';
return uris.indexOf(req.url) > -1 || isDemoContent;
};
/**
* Helper function for parsing the hash, signature etc. from header
* @param {String} tpat - transaction proof authentication token
* @returns {Object} data with hash and signature
*/
const parseHeader = (tpat: string): Config.TPAT | null => {
log(`tpat: ${tpat}`, LogLevel.DEBUG, true);
try {
let hash;
let signature;
let sao;
if (tpat && tpat.indexOf("tpat ") > -1) {
hash = tpat.split("tpat ")[1].split(":")[0];
signature = tpat.split("tpat ")[1].split(":")[1];
sao = tpat.split("tpat ")[1].split(":")[2];
}
if (tpat && tpat.indexOf("TPAT ") > -1) {
hash = tpat.split("TPAT ")[1].split(":")[0];
signature = tpat.split("TPAT ")[1].split(":")[1];
sao = tpat.split("TPAT ")[1].split(":")[2];
}
const subaddress_override = sao;
const isSubAddressOverride =
subaddress_override !== null &&
subaddress_override !== undefined &&
subaddress_override !== "";
const isValid =
tpat !== undefined &&
tpat !== null &&
hash !== undefined &&
hash !== null &&
hash !== "" &&
signature !== undefined &&
signature !== null &&
signature !== "" &&
tpat.indexOf("TPAT") > -1 || tpat.indexOf("tpat ") > -1;
if (isValid) {
return {
hash,
min_amt: 0,
signature,
ttl: 0,
subaddress: isSubAddressOverride ? subaddress_override : "",
};
}
return null;
} catch {
return null;
}
};
/**
* Helper function for return header in the response
* @param parsedHeader
* @param req
* @param res
*/
const returnHeader = (parsedHeader: Config.TPAT, req: any, res: any): void => {
const h = validateAsset(req.url);
if (parsedHeader === null && h !== null) {
res
.status(Config.Http.PAYMENT_REQUIRED)
.header(
"www-authenticate",
`TPAT address="${h.subaddress}", ` +
`min_amt="${h.amt}", ttl="${h.ttl}", hash="", signature="", ast="${Config.ANTI_SPAM_THRESHOLD}"`
)
.send();
} else if (h === null) {
res.status(Config.Http.FORBIDDEN).send();
} else {
res
.status(Config.Http.PAYMENT_REQUIRED)
.header(
"www-authenticate",
`TPAT address="${h.subaddress}", ` +
`min_amt="${h.amt}", ttl="${h.ttl}", hash="${parsedHeader.hash}",` +
`signature="${parsedHeader.signature}", ast="${Config.ANTI_SPAM_THRESHOLD}"`
)
.send();
}
};
/**
* Final pass-through to the asset
* @param req
* @param res
*/
const passThrough = (req: any, res: any, h: Config.Asset) => {
if (h && h.static && NODE_ENV === "test") { // demo examples
res.sendFile(path.join(__dirname, "../examples/static", h.file));
} else if (NODE_ENV === "test" && req.url === "/") {
res.sendFile(path.join(__dirname, "../examples/static", "login.html"));
} else if (NODE_ENV === "test" && req.url !== "/" && !h && !Config.HIMITSU_RESTRICTED) {
res.sendFile(path.join(__dirname, "../examples/static", req.url.replace("/", "")));
} else if ((h && h.static)) { // static or redirects
if (req.method === "GET") {
axios
.get(`http://${Config.ASSET_HOST}${req.url}`, req.body)
.then((v) => {
const html = v.data.replace("\n", "");
res.send(html);
})
.catch((v) => res.json(v));
} else if (req.method === "POST") {
axios
.post(`http://${Config.ASSET_HOST}${req.url}`, req.body)
.then((v) => {
const html = v.data.replace("\n", "");
res.send(html);
})
.catch((v) => res.json(v));
} else if (req.method === "PATCH") {
axios
.patch(`http://${Config.ASSET_HOST}${req.url}`, req.body)
.then((v) => {
const html = v.data.replace("\n", "");
res.send(html);
})
.catch((v) => res.json(v));
} else if (req.method === "DELETE") {
axios
.delete(`http://${Config.ASSET_HOST}${req.url}`, req.body)
.then((v) => {
const html = v.data.replace("\n", "");
res.send(html);
})
.catch((v) => res.json(v));
}
}
else { // return json from protected API handlers
if (req.method === "GET") {
axios
.get(`http://${Config.ASSET_HOST}${req.url}`, req.body)
.then((v) => res.json(v.data))
.catch((v) => res.json(v));
} else if (req.method === "POST") {
axios
.post(`http://${Config.ASSET_HOST}${req.url}`, req.body)
.then((v) => res.json(v.data))
.catch((v) => res.json(v));
} else if (req.method === "PATCH") {
axios
.patch(`http://${Config.ASSET_HOST}${req.url}`, req.body)
.then((v) => res.json(v.data))
.catch((v) => res.json(v));
} else if (req.method === "DELETE") {
axios
.delete(`http://${Config.ASSET_HOST}${req.url}`, req.body)
.then((v) => res.json(v.data))
.catch((v) => res.json(v));
}
}
};
/**
* @param {Object} tpat - transaction proof authentication token
* Object parsed from the www-authenticate header.
* Format is 'www-authenticate: TPAT address="<recipient_address>"",
* min_amount="<minimum_amount_piconero>", ttl="<confirmations>",
* hash="<transaction_hash>", signature="<transaction_proof>", ast="<60>"'
* @returns
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export const isValidProof = async (req: any, res: any): Promise<void> => {
const authHeader = req.headers[Config.Header.AUTHORIZATION];
// check for bypass, always bypass home (login?) page
if (bypassAsset(req) || req.url === "/") {
passThrough(req, res, null);
} else if (Config.HIMITSU_RESTRICTED && !himitsuConfigured) {
await configureHimitsu(authHeader, req, res);
} else if (Config.HIMITSU_RESTRICTED && himitsuConfigured) {
verifyHimitsu(req, res);
} else {
// check the proof
const h = validateAsset(req.url);
const values = parseHeader(authHeader);
if (values === null && !h) {
returnHeader(values, req, res);
} else {
let oa;
try {
oa = req.body.tpat_subaddress_override;
} catch {
oa = null;
}
const ioa = oa !== null && oa !== undefined && oa !== "" && h.override;
const sig = h.static ? req.body.tpat_tx_proof : values.signature;
const body = {
jsonrpc: Config.RPC.VERSION,
id: Config.RPC.ID,
method: Config.RPC.CHECK_TX_PROOF,
params: {
address: ioa ? oa : h.subaddress,
txid: h.static ? req.body.tpat_tx_hash : values.hash,
signature: sig,
},
};
axios
.post(`http://${Config.XMR_RPC_HOST}/json_rpc`, body)
.then((rp) => {
const p = rp.data.result;
log(`rpc response: ${JSON.stringify(p)}`, LogLevel.DEBUG, false);
/*
Validations:
1. signature is valid or "good"
2. the transaction is broadcasted - not in pool
3. confirmations are not past the threshold the default is 30 blocks or about an hour
the transaction proof can be used like a ticket until that threshold. The MIN_AMOUNT
get one hour, doubling get two hours time-to-live etc.
*/
const isValidTTL =
Math.floor(p.received / h.amt) * h.ttl > p.confirmations;
const isNotFree = isJailed(sig);
log(
`ttl value: ${Math.floor(p.received / h.amt) * h.ttl}, ` +
`isValid: ${isValidTTL}, isJailed: ${isNotFree}`,
LogLevel.DEBUG,
true
);
if (
p.good === false ||
p.in_pool === true ||
!isValidTTL ||
isNotFree
) {
returnHeader(values, req, res);
} else {
// jail token
jailToken(sig);
// pass response
passThrough(req, res, h);
}
})
.catch(() =>
res
.status(Config.Http.SERVER_FAILURE)
.json({ message: "Proof validation failure" })
);
}
}
};
/**
* This is some really hacky logic for killing prokurilo
* if it is not running over i2p.
*/
export const i2pCheck = (): void => {
getI2pStatus()
.catch(() => {
// kill the currently running janitor
clearInterval(i2pJanitor);
if (i2pReconnect) {
clearInterval(utilI2pJanitor);
}
log(`i2p is connection lost`, LogLevel.ERROR, true );
log(
`prokurilo will disconnect in ${(Config.I2P_KILL_SWITCH_LIMIT - 1) - i2pKillSwitchCheck} minutes`,
LogLevel.WARN, true
);
log(`please restart i2p`, LogLevel.INFO, true );
// this is some kind of quasi-task executor that kill the server
// if i2p is down for more than twenty minutes
if (i2pKillSwitchCheck === 0) {
const i2pKillSwitch = setInterval(() => {
getI2pStatus(); // the kill switch logic needs to get its own status
i2pKillSwitchCheck += 1;
log(`executing i2p check ${i2pKillSwitchCheck}/${Config.I2P_KILL_SWITCH_LIMIT - 1}`, LogLevel.INFO, true);
if (i2pKillSwitchCheck === Config.I2P_KILL_SWITCH_LIMIT) {
process.exit(Config.I2P_OFFLINE_ERROR);
}
if (i2pStatus === ACCEPTING_TUNNELS) {
log(`i2p connection re-established`, LogLevel.INFO, true);
i2pKillSwitchCheck = 0; // back on-line reset the check
i2pReconnect = true;
log(`initialized new i2p janitor`, LogLevel.INFO, true);
// start a new janitor
utilI2pJanitor = setInterval(() => { i2pCheck(); }, Config.I2P_CHECK_INTERVAL);
clearInterval(i2pKillSwitch);
}
}, Config.I2P_CHECK_INTERVAL)
}
})
};
const getI2pStatus = () => axios.get('http://localhost:7657/tunnels')
.then(v => {
i2pStatus = v.data.split('<h4><span class="tunnelBuildStatus">')[1].split('</span></h4>')[0]
if (i2pStatus === ACCEPTING_TUNNELS) {
log('i2p is active', LogLevel.INFO, true);
} else if (i2pStatus === REJECTING_TUNNELS) {
log('i2p is starting up', LogLevel.INFO, true);
} else {
log('no i2p connection', LogLevel.INFO, true);
}
})
export default isValidProof;