-
Notifications
You must be signed in to change notification settings - Fork 0
/
browser.js
75 lines (64 loc) · 1.69 KB
/
browser.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
/*
log2pcap exporter
(c) qxip bv 2023
*/
const ip = require("ip-packet");
const tcp = require("tcp-packet");
const udp = require("udp-packet");
const { configure } = require("pcap-generator");
const generator = configure({ Buffer: Buffer });
function checkPacketData(packet) {
return typeof packet.data === "string"
? Buffer.from(packet.data)
: Buffer.from("");
}
function protoEncode(proto, packet, bufferData) {
return proto.encode({
sourcePort: packet.srcPort,
destinationPort: packet.dstPort,
data: Buffer.from(bufferData),
});
}
function ipEncode(packet, packet_data) {
return ip.encode({
version: packet.version || 4,
protocol: packet.proto,
sourceIp: packet.srcIp,
destinationIp: packet.dstIp,
data: packet_data,
});
}
function processPacketData(packet) {
const bufferData = checkPacketData(packet);
if (packet.proto === 6) {
// TCP
return protoEncode(tcp, packet, bufferData);
} else if (packet.proto === 17) {
// UDP
return protoEncode(udp, packet, bufferData);
}
}
function encodePcap(packetArray) {
const pcapData = [];
packetArray.forEach((packet) => {
const packet_data = processPacketData(packet);
const ipv4_packet = ipEncode(packet, packet_data);
pcapData.push({
timestamp: packet.ts || Date.now(),
buffer: ipv4_packet,
});
});
return pcapData;
}
function writePcap(file) {
try {
const pcapFile = encodePcap(file);
return pcapFile;
} catch (e) {
console.log("Error on writing PCAP file");
}
}
module.exports = {
writePcap,
generator,
};