2021-10-02 02:02:49 +00:00
|
|
|
"use strict";
|
|
|
|
|
|
|
|
import { once } from 'events';
|
|
|
|
|
2022-01-09 16:30:42 +00:00
|
|
|
import log from '../io/NamespacedLog.mjs'; const l = log("rekey");
|
2021-10-02 23:34:55 +00:00
|
|
|
import jpake from 'jpake';
|
2021-10-02 02:02:49 +00:00
|
|
|
|
|
|
|
export default async function rekey(connection, secret_join) {
|
|
|
|
// 0: Setup jpake
|
2021-10-02 23:34:55 +00:00
|
|
|
let jpake_inst = new jpake.JPake(secret_join);
|
2021-10-02 02:02:49 +00:00
|
|
|
|
|
|
|
// 1: Round 1
|
2021-10-02 23:34:55 +00:00
|
|
|
connection.send("rekey", { round: 1, content: jpake_inst.GetRound1Message() });
|
2021-10-02 02:02:49 +00:00
|
|
|
|
|
|
|
// 2: Round 2
|
|
|
|
|
2021-10-03 01:33:54 +00:00
|
|
|
const their_round1 = (await once(connection, "message-rekey"))[0];
|
|
|
|
l.debug(`THEIR_ROUND1`, their_round1);
|
2021-10-02 02:02:49 +00:00
|
|
|
|
2021-10-02 16:34:15 +00:00
|
|
|
if(typeof their_round1 !== "object"
|
|
|
|
|| their_round1.round !== 1
|
|
|
|
|| typeof their_round1.content !== "string")
|
|
|
|
throw new Error(`Error: Received invalid round 1 from peer`);
|
2021-10-02 02:02:49 +00:00
|
|
|
|
2021-10-02 23:34:55 +00:00
|
|
|
l.debug(`REKEY GOT ROUND 1`);
|
|
|
|
|
|
|
|
const our_round2 = jpake_inst.GetRound2Message(their_round1.content);
|
2021-10-02 16:34:15 +00:00
|
|
|
if(typeof our_round2 !== "string") throw new Error(`Error: Failed to compute rekey round 2`);
|
|
|
|
|
2021-10-02 23:34:55 +00:00
|
|
|
|
2021-10-02 16:34:15 +00:00
|
|
|
connection.send("rekey", { round: 2, content: our_round2 });
|
2021-10-02 02:02:49 +00:00
|
|
|
|
|
|
|
// 3: Compute new shared key
|
2021-10-03 01:33:54 +00:00
|
|
|
const their_round2 = (await once(connection, "message-rekey"))[0];
|
2021-10-03 11:14:57 +00:00
|
|
|
|
2021-10-02 16:38:24 +00:00
|
|
|
if(typeof their_round2 !== "object"
|
2021-10-03 01:33:54 +00:00
|
|
|
|| their_round2.round !== 2
|
2021-10-02 16:38:24 +00:00
|
|
|
|| typeof their_round2.content !== "string")
|
|
|
|
throw new Error(`Error: Received invalid round 2 from peer`);
|
2021-10-02 23:34:55 +00:00
|
|
|
|
|
|
|
l.debug(`REKEY GOT ROUND 2`);
|
2021-10-02 16:38:24 +00:00
|
|
|
|
2021-10-02 23:34:55 +00:00
|
|
|
const new_shared_key = jpake_inst.ComputeSharedKey(their_round2.content);
|
2021-10-02 16:38:24 +00:00
|
|
|
if(typeof new_shared_key !== "string")
|
|
|
|
throw new Error(`Error: Failed to compute shared key`);
|
2021-10-02 02:02:49 +00:00
|
|
|
|
2021-10-02 23:34:55 +00:00
|
|
|
l.debug(`REKEY COMPLETE`);
|
|
|
|
|
2021-10-02 02:02:49 +00:00
|
|
|
return Buffer.from(new_shared_key, "hex");
|
|
|
|
|
|
|
|
// let data_bytes = response[0].toString("base64");
|
|
|
|
//
|
|
|
|
// const cert_theirs = decrypt(secret_join, data_bytes.toString("base64"));
|
|
|
|
// if(cert_theirs === null) {
|
|
|
|
// socket.destroy();
|
|
|
|
// return null;
|
|
|
|
// }
|
|
|
|
// console.log(`STARTTLS cert_theirs`, cert_theirs);
|
|
|
|
}
|