@cto.af/pcap-ng-parser 2.1.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1109 +0,0 @@
1
- import * as BlockConfig from './BlockConfig.js';
2
- import {
3
- CUSTOM_COPY,
4
- CUSTOM_NOCOPY,
5
- DECRYPTION_SECRETS,
6
- ENHANCED_PACKET,
7
- INTERFACE_DESCRIPTION,
8
- INTERFACE_STATISTICS,
9
- NAME_RESOLUTION,
10
- OPTION_NAMES,
11
- SECTION_HEADER,
12
- SIMPLE_PACKET,
13
- } from './options.js';
14
- import {NoFilter, TruncationError} from 'nofilter';
15
- import {Buffer} from 'node:buffer';
16
- import {LINK_TYPE_NAMES} from './linkTypes.js';
17
- import {Transform} from 'node:stream';
18
- import {decode as ipDecode} from '@leichtgewicht/ip-codec';
19
-
20
- const PCAP_MAGIC_MICRO = 0xA1B2C3D4;
21
- const PCAP_MAGIC_NANO = 0xA1B23C4D;
22
- const PCAP_MAGIC_MICRO_LE = 0xD4C3B2A1;
23
- const PCAP_MAGIC_NANO_LE = 0x4D3CB2A1;
24
-
25
- /** @import {Readable, TransformCallback} from 'node:stream' */
26
- /** @import {OptionType} from './options.js' */
27
-
28
- const EPB_FLAGS_DIRECTIONS = /** @type {const} */([
29
- 'notAvailable',
30
- 'inbound',
31
- 'outbound',
32
- 'invalid',
33
- ]);
34
-
35
- const EPB_FLAGS_RECEPTION = /** @type {const} */([
36
- 'notSpecified',
37
- 'unicast',
38
- 'multicast',
39
- 'broadcast',
40
- 'promiscuous',
41
- 'invalid',
42
- 'invalid',
43
- 'invalid',
44
- ]);
45
-
46
- const EPB_FLAGS_LINK_LAYER_ERRORS = /** @type {const} */([
47
- 'symbol',
48
- 'preamble',
49
- 'startFrameDelimiter',
50
- 'unalignedFrame',
51
- 'wrongInterFrameGap',
52
- 'packetTooShort',
53
- 'packetTooLong',
54
- 'CRC',
55
- 'invalid',
56
- 'invalid',
57
- 'invalid',
58
- 'invalid',
59
- 'invalid',
60
- 'invalid',
61
- 'invalid',
62
- 'invalid',
63
- ]);
64
-
65
- // #region Utility methods
66
-
67
- /**
68
- * @param {number} n
69
- * @returns {number}
70
- */
71
- function pad4(n) {
72
- return (Math.ceil(n / 4) * 4) - n;
73
- }
74
-
75
- /**
76
- * @param {number} byteOrderMagic
77
- * @returns {Endianess}
78
- * @throws {Error} On invalid endianess.
79
- */
80
- function processByteOrderMagic(byteOrderMagic) {
81
- if (byteOrderMagic === 0x1A2B3C4D) {
82
- return 'BE';
83
- } else if (byteOrderMagic === 0x4D3C2B1A) {
84
- return 'LE';
85
- }
86
- throw new Error(`Unable to determine endian from ${byteOrderMagic.toString(16)}`);
87
- }
88
-
89
- /**
90
- * Convert buffer to hex string with colon separators (e.g. Ethernet address).
91
- *
92
- * @param {Buffer} buf
93
- * @returns {string}
94
- */
95
- function colons(buf) {
96
- return Array.from(buf)
97
- .map(x => x.toString(16).padStart(2, '0'))
98
- .join(':');
99
- }
100
-
101
- // #endregion Utility methods
102
- // #region Types
103
-
104
- /**
105
- * @typedef {object} Interface
106
- * @property {number} linkType See https://datatracker.ietf.org/doc/html/draft-ietf-opsawg-pcaplinktype for info.
107
- * @property {string} [linkTypeName]
108
- * @property {number} snapLen Capture length.
109
- * @property {string} [name] Interface name.
110
- * @property {bigint} tsoffset Offset, in MS, applied to each timestamp.
111
- * @property {bigint} tsresol Timestamp resolution in MS.
112
- * @property {Option[]} options All interface options.
113
- */
114
-
115
- /**
116
- * @typedef {object} IPv4ResolutionRecord
117
- * @property {'nrb_record_ipv4'} name
118
- * @property {string} ipv4
119
- * @property {string[]} entries
120
- */
121
-
122
- /**
123
- * @typedef {object} IPv6ResolutionRecord
124
- * @property {'nrb_record_ipv6'} name
125
- * @property {string} ipv6
126
- * @property {string[]} entries
127
- */
128
-
129
- /**
130
- * @typedef {object} EUI48ResolutionRecord
131
- * @property {'nrb_record_eui48'} name
132
- * @property {string} eui48
133
- * @property {string[]} entries
134
- */
135
-
136
- /**
137
- * @typedef {object} EUI64ResolutionRecord
138
- * @property {'nrb_record_eui64'} name
139
- * @property {string} eui64
140
- * @property {string[]} entries
141
- */
142
-
143
- /**
144
- * @typedef {IPv4ResolutionRecord | IPv6ResolutionRecord |
145
- * EUI48ResolutionRecord | EUI64ResolutionRecord} NameResolutionRecord
146
- */
147
-
148
- /**
149
- * @typedef {object} NameResolution
150
- * @property {NameResolutionRecord[]} records
151
- * @property {Option[]} options NameResolution options.
152
- */
153
-
154
- /**
155
- * @typedef {object} PacketFlags
156
- * @property {typeof EPB_FLAGS_DIRECTIONS[number]} [direction]
157
- * @property {typeof EPB_FLAGS_RECEPTION[number]} [reception]
158
- * @property {number} FCSlen
159
- * @property {boolean} [noChecksum]
160
- * @property {boolean} [checksumValid]
161
- * @property {boolean} [TCPsegmentationOfflad]
162
- * @property {typeof EPB_FLAGS_LINK_LAYER_ERRORS[number][]} [linkLayerErrors]
163
- */
164
-
165
- /**
166
- * @typedef {object} Packet
167
- * @property {number} interfaceId
168
- * @property {Date} [timestamp]
169
- * @property {PacketFlags} [flags]
170
- * @property {number} originalPacketLength
171
- * @property {Buffer} data
172
- * @property {Option[]} options
173
- */
174
-
175
- /**
176
- * @typedef {object} InterfaceStatistics
177
- * @property {number} interfaceId
178
- * @property {Date} timestamp
179
- * @property {Option[]} options
180
- */
181
-
182
- /**
183
- * @typedef {object} DecryptionSecrets
184
- * @property {number} secretsType
185
- * @property {Buffer} data
186
- * @property {Option[]} options
187
- */
188
-
189
- /**
190
- * @typedef {object} CustomBlock
191
- * @property {number} pen
192
- * @property {Buffer} data
193
- * @property {boolean} copy
194
- */
195
-
196
- /**
197
- * @typedef {object} BlockConfig
198
- * @property {number} blockType
199
- * @property {number} blockTotalLength
200
- */
201
-
202
- /**
203
- * @typedef {object} Data
204
- * @property {NoFilter} data
205
- */
206
-
207
- /**
208
- * @typedef {BlockConfig & Data} Block
209
- */
210
-
211
- /**
212
- * @typedef {object} GenericOption
213
- * @property {number} optionType
214
- * @property {number} [dataLength]
215
- * @property {Buffer} [data]
216
- * @property {string} [str]
217
- * @property {bigint} [bigint]
218
- * @property {Date} [date]
219
- * @property {string} [name]
220
- * @property {boolean} [private]
221
- */
222
-
223
- /**
224
- * @typedef {object} PrivateEnterpriseNumber
225
- * @property {number} [pen]
226
- */
227
-
228
- /** @typedef {GenericOption & PrivateEnterpriseNumber} Option */
229
-
230
- /** @typedef {"BE" | "LE"} Endianess */
231
-
232
- /**
233
- * @typedef {object} SectionHeader
234
- * @property {Endianess} endianess
235
- * @property {number} majorVersion
236
- * @property {number} minorVersion
237
- * @property {number} sectionLength
238
- * @property {Option[]} [options]
239
- */
240
-
241
- /**
242
- * @typedef {object} ParseEvents
243
- * @property {[number]} blockType Unknown block type received.
244
- * @property {[]} close Both ends of the stream have closed.
245
- * @property {[CustomBlock]} custom A Custom block was read.
246
- * @property {[Packet]} data A Simple or Extended Packet was read.
247
- * @property {[]} drain If a call to stream.write(chunk) returns false, the
248
- * 'drain' event will be emitted when it is appropriate to resume writing
249
- * data to the stream.
250
- * @property {[]} end There is no more data to be consumed from the stream.
251
- * @property {[unknown]} error Error in parsing.
252
- * @property {[]} finish The input to the parse stream has ended.
253
- * @property {[Interface]} interface An Interface record was read.
254
- * @property {[NameResolution]} names A NameResolution record was read.
255
- * @property {[]} pause `stream.pause()` was called.
256
- * @property {[Readable]} pipe Output of stream was redirect.
257
- * @property {[SectionHeader]} section A new Section has started. Always emitted
258
- * before other parse events in a valid file.
259
- * @property {[]} readable Data is available to be read from the stream.
260
- * @property {[]} resume `stream.resume()` was called.
261
- * @property {[DecryptionSecrets]} secrets A Decryption Secrets block was read.
262
- * @property {[InterfaceStatistics]} stats Interface Statistics block was read.
263
- * @property {[Readable]} unpipe `stream.unpipe()` was called.
264
- */
265
-
266
- /**
267
- * @typedef {object} ParserOptions
268
- * @property {AbortSignal} [signal]
269
- */
270
- // # endregion Types
271
-
272
- export class PCAPNGParser extends Transform {
273
- /** @type {Interface[]} */
274
- interfaces = [];
275
-
276
- /** @import {BlockDescriptor} from './BlockConfig.js' */
277
-
278
- /**
279
- * @typedef {Record<string, number>} Numbers
280
- */
281
-
282
- /** @type {Endianess} */
283
- #endianess = 'LE';
284
-
285
- /** @type {SectionHeader | undefined} */
286
- #sectionHeader = undefined;
287
-
288
- /** @type {NoFilter | undefined} */
289
- #nof = undefined;
290
-
291
- /** @type {Promise<void> | undefined} */
292
- #reading = undefined;
293
-
294
- /** @type {AbortSignal | undefined} */
295
- #signal = undefined;
296
-
297
- /** Is this the -ng format, or the older format? */
298
- #ng = true;
299
-
300
- // #region Transform
301
-
302
- /**
303
- * @param {ParserOptions} opts
304
- */
305
- constructor(opts = {}) {
306
- const {signal} = opts;
307
-
308
- // The magic bit to allow objects
309
- super({
310
- readableObjectMode: true,
311
- signal,
312
- });
313
- this.#signal = signal;
314
- }
315
-
316
- /**
317
- * Is this file in the pcap-ng format?
318
- *
319
- * @returns If false, in the old pcap format.
320
- */
321
- get ng() {
322
- return this.#ng;
323
- }
324
-
325
- /**
326
- * Transform chunks of data into packets and interface events.
327
- * DO NOT call directly.
328
- *
329
- * @param {Buffer} chunk Data to process.
330
- * @param {string} _encoding Ignored.
331
- * @param {TransformCallback} callback Called when finished with chunk.
332
- */
333
- _transform(chunk, _encoding, callback) {
334
- if (!this.#nof) {
335
- this.#nof = new NoFilter({
336
- signal: this.#signal,
337
- objectMode: false,
338
- watchPipe: false,
339
- });
340
- this.#reading = this.#readFile(this.#nof);
341
- }
342
- this.#nof.write(chunk, callback);
343
- }
344
-
345
- /**
346
- * Finished writing.
347
- * DO NOT call directly.
348
- *
349
- * @param {TransformCallback} cb
350
- */
351
- _flush(cb) {
352
- this.#nof?.end();
353
- if (this.#reading) {
354
- this.#reading.then(() => cb(), cb);
355
- } else {
356
- // Never started writing data.
357
- cb(new Error('At least one Section Header required'));
358
- }
359
- }
360
- // #endregion Transform
361
-
362
- // #region Read
363
-
364
- /**
365
- * Read the whole file, once data has started to flow.
366
- *
367
- * @param {NoFilter} nof
368
- */
369
- async #readFile(nof) {
370
- try {
371
- await nof.waitFor(4);
372
- const magic = /** @type {Buffer} */(nof.slice(0, 4)).readUint32BE(0);
373
- if (magic === SECTION_HEADER) {
374
- while (true) {
375
- const block = await this.#readBlock(nof);
376
- if (!block) {
377
- break;
378
- }
379
- switch (block.blockType) {
380
- case SECTION_HEADER:
381
- await this.#processSectionHeader(block);
382
- break;
383
- case INTERFACE_DESCRIPTION:
384
- await this.#processInterface(block);
385
- break;
386
- case SIMPLE_PACKET:
387
- await this.#processSimplePacket(block);
388
- break;
389
- case NAME_RESOLUTION:
390
- await this.#processNameResolution(block);
391
- break;
392
- case INTERFACE_STATISTICS:
393
- await this.#processInterfaceStatistics(block);
394
- break;
395
- case ENHANCED_PACKET:
396
- await this.#processEnhancedPacket(block);
397
- break;
398
- case DECRYPTION_SECRETS:
399
- await this.#processDecryptionSecrets(block);
400
- break;
401
- case CUSTOM_COPY:
402
- case CUSTOM_NOCOPY:
403
- await this.#processCustom(block);
404
- break;
405
- default:
406
- if (block.blockType >= 0) {
407
- this.emit('blockType', block.blockType);
408
- }
409
- break;
410
- }
411
- }
412
- } else if (magic === PCAP_MAGIC_MICRO) {
413
- await this.#readPCAP(nof, 'BE', false);
414
- } else if (magic === PCAP_MAGIC_MICRO_LE) {
415
- await this.#readPCAP(nof, 'LE', false);
416
- } else if (magic === PCAP_MAGIC_NANO) {
417
- await this.#readPCAP(nof, 'BE', true);
418
- } else if (magic === PCAP_MAGIC_NANO_LE) {
419
- await this.#readPCAP(nof, 'LE', true);
420
- } else {
421
- throw new Error(`Invalid file format: magic = ${magic}`);
422
- }
423
- } catch (er) {
424
- this.emit('error', er);
425
- }
426
- }
427
-
428
- /**
429
- * Read an old-style PCAP file.
430
- *
431
- * @param {NoFilter} nof
432
- * @param {Endianess} endian
433
- * @param {boolean} nano
434
- * @see https://www.ietf.org/archive/id/draft-ietf-opsawg-pcap-06.html
435
- */
436
- async #readPCAP(nof, endian, nano) {
437
- this.#endianess = endian;
438
- this.#ng = false;
439
- const {linkType, snapLen} = await this.#readNumbers(
440
- nof, BlockConfig.pcapHeaderFormat
441
- );
442
- const tsresol = nano ? 1000000n : 1000n;
443
-
444
- /** @type {Interface} */
445
- const int = {
446
- linkType: linkType & 0xffff,
447
- snapLen,
448
- tsresol,
449
- tsoffset: 0n,
450
- options: [],
451
- };
452
- const ltName = LINK_TYPE_NAMES.get(int.linkType);
453
- if (ltName) {
454
- int.linkTypeName = ltName;
455
- }
456
- const fcsPresent = Boolean(linkType & 0x04000000);
457
- if (fcsPresent) {
458
- const FCSlen = linkType >> 28; // 16 bit words
459
- int.options.push({
460
- optionType: 13,
461
- name: 'if_fcslen',
462
- data: Buffer.from([FCSlen * 16]), // Bits
463
- });
464
- }
465
- this.interfaces.push(int);
466
- this.emit('interface', int);
467
-
468
- while (true) {
469
- try {
470
- await nof.waitFor(4);
471
- } catch (er) {
472
- if (er instanceof TruncationError && er.size === 4) {
473
- return;
474
- }
475
- throw er;
476
- }
477
- const {
478
- timestampHigh, timestampLow, capturedPacketLength, originalPacketLength,
479
- } = await this.#readNumbers(nof, BlockConfig.pcapPacketFormat);
480
-
481
- const data = capturedPacketLength ?
482
- /** @type {Buffer} */(await nof.readFull(capturedPacketLength)) :
483
- Buffer.alloc(0);
484
-
485
- /** @type {Packet} */
486
- const pkt = {
487
- interfaceId: 0,
488
- timestamp: new Date(
489
- (timestampHigh * 1000) + (timestampLow / Number(tsresol))
490
- ),
491
- originalPacketLength,
492
- data,
493
- options: [],
494
- };
495
- this.push(pkt);
496
- }
497
- }
498
-
499
- /**
500
- * Read a block.
501
- *
502
- * @param {NoFilter} nof
503
- * @returns {Promise<Block | undefined>}
504
- */
505
- async #readBlock(nof) {
506
- let bt = undefined;
507
- try {
508
- const {blockType} = await this.#readNumbers(
509
- nof, BlockConfig.blockType
510
- );
511
- bt = blockType;
512
- } catch (er) {
513
- if ((er instanceof TruncationError) && (er.size === 4)) {
514
- // Done. OK to be done at the start of a block.
515
- return undefined;
516
- }
517
- throw er;
518
- }
519
-
520
- if (bt === SECTION_HEADER) {
521
- // Peek at the byte order first.
522
- await nof.waitFor(8);
523
- const bom = /** @type {Buffer} */(nof.slice(4, 8)).readUint32BE(0);
524
- this.#endianess = processByteOrderMagic(bom);
525
- }
526
-
527
- const {blockTotalLength} = await this.#readNumbers(
528
- nof, BlockConfig.blockTotalLength
529
- );
530
-
531
- const dataLen = blockTotalLength - 12;
532
- const block = {
533
- blockType: bt,
534
- blockTotalLength,
535
- data: new NoFilter(await nof.readFull(dataLen)),
536
- };
537
- // Padding
538
- await nof.readFull(pad4(dataLen));
539
-
540
- const {endTotalLength} = await this.#readNumbers(
541
- nof, BlockConfig.endLength
542
- );
543
- if (endTotalLength !== blockTotalLength) {
544
- throw new Error(`Length mismatch, ${endTotalLength} != ${blockTotalLength}`);
545
- }
546
- return block;
547
- }
548
-
549
- /**
550
- * @param {Block} block
551
- * @param {number} [interfaceId]
552
- * @returns {Promise<Option[]>}
553
- */
554
- async #readOptions(block, interfaceId) {
555
- let foundEndOption = false;
556
-
557
- /** @type {Option[]} */
558
- const options = [];
559
- while (block.data.length && !foundEndOption) {
560
- const rb = await this.#readNumbers(
561
- block.data, BlockConfig.optionBlock
562
- );
563
- if (rb.optionType === 0) {
564
- foundEndOption = true;
565
- } else {
566
- /** @type {PrivateEnterpriseNumber | undefined} */
567
- let pen = undefined;
568
- let name = undefined;
569
-
570
- /** @type {OptionType} */
571
- let typ = undefined;
572
-
573
- const desc = OPTION_NAMES.get(block.blockType)?.get(rb.optionType);
574
- if (desc) {
575
- name = {name: desc[0]};
576
- // eslint-disable-next-line prefer-destructuring
577
- typ = desc[1];
578
- if (desc[2]) {
579
- pen = await this.#readNumbers(
580
- block.data, BlockConfig.privateEnterpriseNumber
581
- );
582
- }
583
- }
584
-
585
- /** @type {Option} */
586
- const opt = {
587
- ...rb,
588
- ...name,
589
- ...pen,
590
- data: /** @type {Buffer} */ (block.data.read(rb.dataLength)),
591
- };
592
-
593
- if (rb.optionType & 0x8000) {
594
- opt.private = true;
595
- }
596
- switch (typ) {
597
- case 'string':
598
- opt.str = /** @type {Buffer} */(opt.data).toString('utf-8')
599
- .replaceAll('\0', '')
600
- .trim();
601
- delete opt.data;
602
- break;
603
- case 'ipv4':
604
- case 'ipv6':
605
- opt.str = ipDecode(/** @type {Buffer}*/(opt.data));
606
- delete opt.data;
607
- break;
608
- case 'ipv4mask':
609
- if (!opt.data || (opt.data.length !== 8)) {
610
- throw new Error('Invalid ipv4mask option');
611
- }
612
- opt.str = `${ipDecode(opt.data.subarray(0, 4))}/${ipDecode(opt.data.subarray(4, 8))}`;
613
- delete opt.data;
614
- break;
615
- case 'ipv6prefix':
616
- if (!opt.data || (opt.data.length !== 17)) {
617
- throw new Error('Invalid ipv6prefix option');
618
- }
619
- opt.str = `${ipDecode(opt.data.subarray(0, 16))}/${opt.data[16]}`;
620
- delete opt.data;
621
- break;
622
- case 'eui':
623
- opt.str = colons(/** @type {Buffer} */ (opt.data));
624
- delete opt.data;
625
- break;
626
- case 'u32': {
627
- const {u32} = await this.#readNumbers(
628
- new NoFilter(opt.data), BlockConfig.u32Format
629
- );
630
- opt.bigint = BigInt(u32);
631
- delete opt.data;
632
- break;
633
- }
634
- case 'u64': {
635
- const {u64} = await this.#readNumbers(
636
- new NoFilter(opt.data), BlockConfig.u64Format
637
- );
638
- opt.bigint = BigInt(u64);
639
- delete opt.data;
640
- break;
641
- }
642
- case 'timestamp': {
643
- const {timestampHigh, timestampLow} = await this.#readNumbers(
644
- new NoFilter(opt.data),
645
- BlockConfig.timestampFormat
646
- );
647
- opt.date = this.#timestamp(
648
- timestampHigh, timestampLow, /** @type {number} */(interfaceId)
649
- );
650
- delete opt.data;
651
- }
652
- }
653
- delete opt.dataLength;
654
-
655
- // Skip padding
656
- block.data.read(pad4(rb.dataLength));
657
- options.push(opt);
658
- }
659
- }
660
- return options;
661
- }
662
-
663
- /**
664
- * Read a set of numbers from the given input.
665
- *
666
- * @template {BlockDescriptor} T Describe the name/length pairs.
667
- * @param {NoFilter} nof
668
- * @param {T} blockDescriptor
669
- * @returns {Promise<Record<keyof T, number>>}
670
- */
671
- async #readNumbers(nof, blockDescriptor) {
672
- /** @type {Partial<Record<keyof T, number>>} */
673
- const props = {};
674
- for (const [prop, {size, signed}] of Object.entries(blockDescriptor)) {
675
- const buf = await nof.readFull(size);
676
- const readMethod = `read${(size === 8) ? 'Big' : ''}${signed ? '' : 'U'}Int${size * 8}${this.#endianess}`;
677
- // @ts-expect-error readMethod hides type
678
- props[prop] = buf[readMethod](0);
679
- }
680
- return /** @type {Record<keyof T, number>} */(props);
681
- }
682
-
683
- // #endregion Read
684
- // #region utilities
685
-
686
- /**
687
- * Convert the given timestamp to real clock time.
688
- *
689
- * @param {number} stampHigh
690
- * @param {number} stampLow
691
- * @param {number} interfaceId Known valid.
692
- * @returns {Date}
693
- * @throws {Error} On invalid interface ID.
694
- */
695
- #timestamp(stampHigh, stampLow, interfaceId) {
696
- // Don't read as bigint, since each half could be LE.
697
- const stamp = (BigInt(stampHigh) << 32n) | BigInt(stampLow);
698
- const int = this.interfaces[interfaceId];
699
-
700
- const off = int.tsoffset + (stamp / int.tsresol);
701
- return new Date(Number(off));
702
- }
703
-
704
- // #endregion
705
- // #region Process Blocks
706
-
707
- /**
708
- * @param {Block} block
709
- */
710
- async #processSectionHeader(block) {
711
- // Byte order magic handled in #readBlock proactively
712
- const hdr = await this.#readNumbers(
713
- block.data,
714
- BlockConfig.sectionHeaderBlock
715
- );
716
-
717
- this.#sectionHeader = {
718
- ...hdr,
719
- endianess: this.#endianess,
720
- options: await this.#readOptions(block),
721
- };
722
-
723
- this.interfaces = []; // Reset interfaces in each section.
724
- this.emit('section', this.#sectionHeader);
725
- }
726
-
727
- /**
728
- * Interface Description Block.
729
- *
730
- * @param {Block} block
731
- * @returns {Promise<void>}
732
- * @see https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-04.html#name-interface-description-block
733
- */
734
- async #processInterface(block) {
735
- // Interface definition
736
- const idRes = await this.#readNumbers(
737
- block.data,
738
- BlockConfig.interfaceDescriptionBlockFormat
739
- );
740
-
741
- /** @type {Interface} */
742
- const iData = {
743
- linkType: idRes.linkType,
744
- snapLen: idRes.snapLen,
745
- tsoffset: 0n,
746
- tsresol: 1000n,
747
- options: await this.#readOptions(block),
748
- };
749
- for (const opt of iData.options) {
750
- switch (opt.optionType) {
751
- case 2:
752
- iData.name = /** @type {string} */ (opt.str);
753
- break;
754
- case 14: {
755
- iData.tsoffset = /** @type {bigint} */(opt.bigint) * 1000n;
756
- break;
757
- }
758
- case 9: {
759
- const [tsresol] = /** @type {Buffer} */(opt.data);
760
- if (tsresol & 0x80) {
761
- // This is going to lose precision. Hope nobody does this in
762
- // practice.
763
- iData.tsresol = (1n << BigInt(tsresol & 0x7F)) / 1000n;
764
- } else {
765
- iData.tsresol = 10n ** (BigInt(tsresol) - 3n);
766
- }
767
- break;
768
- }
769
- }
770
- }
771
-
772
- this.interfaces.push(iData);
773
-
774
- // Notify listeners we got a new interface
775
- this.emit('interface', iData);
776
- }
777
-
778
- /**
779
- * Simple Packet Block.
780
- *
781
- * @param {Block} block
782
- * @returns {Promise<void>}
783
- * @see https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-04.html#name-simple-packet-block
784
- */
785
- async #processSimplePacket(block) {
786
- if (!this.interfaces.length) {
787
- throw new Error('No interface for simple packet');
788
- }
789
- const [int] = this.interfaces;
790
- const {originalPacketLength} = await this.#readNumbers(
791
- block.data, BlockConfig.simplePacketFormat
792
- );
793
- const len = Math.min(originalPacketLength, int.snapLen);
794
-
795
- const data = len ?
796
- /** @type {Buffer} */(await block.data.read(len)) :
797
- Buffer.alloc(0);
798
-
799
- /** @type {Packet} */
800
- const pkt = {
801
- interfaceId: 0,
802
- originalPacketLength,
803
- data,
804
- options: [],
805
- };
806
- // Skip dealing with padding
807
- this.push(pkt);
808
- }
809
-
810
- /**
811
- * Name Resolution Block.
812
- *
813
- * @param {Block} block
814
- * @returns {Promise<void>}
815
- * @see https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-04.html#name-name-resolution-block
816
- */
817
- async #processNameResolution(block) {
818
- /** @type {NameResolution} */
819
- const res = {
820
- records: [],
821
- options: [],
822
- };
823
- while (true) {
824
- const {recordType, recordValueLength} = await this.#readNumbers(
825
- block.data, BlockConfig.nameResolutionFormat
826
- );
827
- if (recordType === 0) {
828
- break;
829
- }
830
- const val = /** @type {Buffer} */ (block.data.read(recordValueLength));
831
- block.data.read(pad4(recordValueLength));
832
- switch (recordType) {
833
- case 0x0001:
834
- if (recordValueLength < 6) {
835
- throw new Error('Invalid nrb_record_ipv4 record');
836
- }
837
- res.records.push({
838
- name: 'nrb_record_ipv4',
839
- ipv4: ipDecode(val.subarray(0, 4)),
840
- entries: val.subarray(4)
841
- .toString()
842
- .split('\x00')
843
- .slice(0, -1),
844
- });
845
- break;
846
- case 0x0002:
847
- if (recordValueLength < 18) {
848
- throw new Error('Invalid nrb_record_ipv6 record');
849
- }
850
- res.records.push({
851
- name: 'nrb_record_ipv6',
852
- ipv6: ipDecode(val.subarray(0, 16)),
853
- entries: val.subarray(16)
854
- .toString()
855
- .split('\x00')
856
- .slice(0, -1),
857
- });
858
- break;
859
- case 0x0003:
860
- if (recordValueLength < 8) {
861
- throw new Error('Invalid nrb_record_eui48 record');
862
- }
863
- res.records.push({
864
- name: 'nrb_record_eui48',
865
- eui48: colons(val.subarray(0, 6)),
866
- entries: val.subarray(6)
867
- .toString()
868
- .split('\x00')
869
- .slice(0, -1),
870
- });
871
- break;
872
- case 0x0004:
873
- if (recordValueLength < 10) {
874
- throw new Error('Invalid nrb_record_eui64 record');
875
- }
876
- res.records.push({
877
- name: 'nrb_record_eui64',
878
- eui64: colons(val.subarray(0, 8)),
879
- entries: val.subarray(8)
880
- .toString()
881
- .split('\x00')
882
- .slice(0, -1),
883
- });
884
- break;
885
- }
886
- }
887
- res.options = await this.#readOptions(block);
888
- this.emit('names', res);
889
- }
890
-
891
- /**
892
- * Interface Statistics block.
893
- *
894
- * @param {Block} block
895
- * @returns {Promise<void>}
896
- * @see https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-04.html#name-interface-statistics-block
897
- */
898
- async #processInterfaceStatistics(block) {
899
- const {interfaceId, timestampHigh, timestampLow} = await this.#readNumbers(
900
- block.data,
901
- BlockConfig.interfaceStatisticsFormat
902
- );
903
- if (interfaceId >= this.interfaces.length) {
904
- throw new Error(`Invalid interface id: ${interfaceId}`);
905
- }
906
-
907
- /** @type {InterfaceStatistics} */
908
- const stats = {
909
- interfaceId,
910
- timestamp: this.#timestamp(timestampHigh, timestampLow, interfaceId),
911
- options: await this.#readOptions(block, interfaceId),
912
- };
913
- this.emit('stats', stats);
914
- }
915
-
916
- /**
917
- * Enhanced Packet Block.
918
- *
919
- * @param {Block} block
920
- * @returns {Promise<void>}
921
- * @see https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-04.html#name-enhanced-packet-block
922
- */
923
- async #processEnhancedPacket(block) {
924
- const {
925
- interfaceId,
926
- timestampHigh,
927
- timestampLow,
928
- capturedPacketLength,
929
- originalPacketLength,
930
- } = await this.#readNumbers(
931
- block.data, BlockConfig.enhancedPacketBlockFormat
932
- );
933
-
934
- if (interfaceId >= this.interfaces.length) {
935
- throw new Error(`Invalid interface ID: ${interfaceId} >= ${this.interfaces.length}`);
936
- }
937
-
938
- const data = capturedPacketLength ?
939
- /** @type {Buffer} */(block.data.read(capturedPacketLength)) :
940
- Buffer.alloc(0);
941
-
942
- /** @type {Packet} */
943
- const pkt = {
944
- interfaceId,
945
- timestamp: this.#timestamp(timestampHigh, timestampLow, interfaceId),
946
- originalPacketLength,
947
- data,
948
- options: [],
949
- };
950
-
951
- block.data.read(pad4(capturedPacketLength));
952
- pkt.options = await this.#readOptions(block, interfaceId);
953
- for (const o of pkt.options) {
954
- if (o.optionType === 2) { // Type epb_flags
955
- let {flags} = await this.#readNumbers(
956
- new NoFilter(o.data), BlockConfig.epbFlagsFormat
957
- );
958
- pkt.flags = {
959
- direction: EPB_FLAGS_DIRECTIONS[flags & 0x3],
960
- reception: EPB_FLAGS_RECEPTION[(flags >> 2) & 0x7],
961
- FCSlen: (flags >> 5) & 0xF,
962
- noChecksum: Boolean((flags >> 9) & 0x1),
963
- checksumValid: Boolean((flags >> 10) & 0x1),
964
- TCPsegmentationOfflad: Boolean((flags >> 11) & 0x1),
965
- linkLayerErrors: [],
966
- };
967
- flags >>= 16;
968
- for (let i = 0; i < 8; i++) {
969
- if (flags & 0x1) {
970
- pkt.flags.linkLayerErrors?.push(EPB_FLAGS_LINK_LAYER_ERRORS[i]);
971
- }
972
- flags >>= 1;
973
- }
974
- }
975
- }
976
- this.push(pkt);
977
- }
978
-
979
- /**
980
- * Decryption Secrets block.
981
- *
982
- * @param {Block} block
983
- * @returns {Promise<void>}
984
- * @see https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-04.html#name-decryption-secrets-block
985
- */
986
- async #processDecryptionSecrets(block) {
987
- // TODO(@hildjj): parse the keying information for each of the spec'd
988
- // secret types.
989
- const {secretsType, secretsLength} =
990
- await this.#readNumbers(
991
- block.data,
992
- BlockConfig.decryptionSecretsFormat
993
- );
994
-
995
- /** @type {DecryptionSecrets} */
996
- const secrets = {
997
- secretsType,
998
- data: /** @type {Buffer} */(await block.data.read(secretsLength)),
999
- options: [],
1000
- };
1001
- block.data.read(pad4(secretsLength));
1002
- secrets.options = await this.#readOptions(block);
1003
- this.emit('secrets', secrets);
1004
- }
1005
-
1006
- /**
1007
- * Custom block.
1008
- * @param {Block} block
1009
- * @returns {Promise<void>}
1010
- */
1011
- async #processCustom(block) {
1012
- const {pen} = await this.#readNumbers(
1013
- block.data, BlockConfig.privateEnterpriseNumber
1014
- );
1015
-
1016
- // For options, see:
1017
- // https://github.com/IETF-OPSAWG-WG/draft-ietf-opsawg-pcap/issues/125
1018
- const custom = {
1019
- pen,
1020
- data: /** @type {Buffer} */(block.data.read()),
1021
- copy: (block.blockType === CUSTOM_COPY),
1022
- };
1023
- this.emit('custom', custom);
1024
- }
1025
- // #endregion Process Blocks
1026
-
1027
- // #region EventEmitter
1028
- // The following overrides of EventEmitter are here to make event code type
1029
- // safe, including the new events added by this class.
1030
-
1031
- /**
1032
- * @template {keyof ParseEvents} K Event name.
1033
- * @param {K} eventName
1034
- * @param {ParseEvents[K]} args
1035
- * @returns {boolean}
1036
- */
1037
- emit(eventName, ...args) {
1038
- return super.emit(eventName, ...args);
1039
- }
1040
-
1041
- /**
1042
- * @template {keyof ParseEvents} K Event name.
1043
- * @param {K} eventName
1044
- * @param {(...args: ParseEvents[K]) => void} listener
1045
- * @returns {this}
1046
- */
1047
- addListener(eventName, listener) {
1048
- super.addListener(eventName, listener);
1049
- return this;
1050
- }
1051
-
1052
- /**
1053
- * @template {keyof ParseEvents} K Event name.
1054
- * @param {K} eventName
1055
- * @param {(...args: ParseEvents[K]) => void} listener
1056
- * @returns {this}
1057
- */
1058
- prependListener(eventName, listener) {
1059
- super.prependListener(eventName, listener);
1060
- return this;
1061
- }
1062
-
1063
- /**
1064
- * @template {keyof ParseEvents} K Event name.
1065
- * @param {K} eventName
1066
- * @param {(...args: ParseEvents[K]) => void} listener
1067
- * @returns {this}
1068
- */
1069
- prependOnceListener(eventName, listener) {
1070
- super.prependOnceListener(eventName, listener);
1071
- return this;
1072
- }
1073
-
1074
- /**
1075
- * @template {keyof ParseEvents} K Event name.
1076
- * @param {K} eventName
1077
- * @param {(...args: ParseEvents[K]) => void} listener
1078
- * @returns {this}
1079
- */
1080
- removeListener(eventName, listener) {
1081
- super.removeListener(eventName, listener);
1082
- return this;
1083
- }
1084
-
1085
- /**
1086
- * @template {keyof ParseEvents} K Event name.
1087
- * @param {K} eventName
1088
- * @param {(...args: ParseEvents[K]) => void} listener
1089
- * @returns {this}
1090
- */
1091
- on(eventName, listener) {
1092
- super.on(eventName, listener);
1093
- return this;
1094
- }
1095
-
1096
- /**
1097
- * @template {keyof ParseEvents} K Event name.
1098
- * @param {K} eventName
1099
- * @param {(...args: ParseEvents[K]) => void} listener
1100
- * @returns {this}
1101
- */
1102
- once(eventName, listener) {
1103
- super.once(eventName, listener);
1104
- return this;
1105
- }
1106
- // #endregion EventEmitter
1107
- }
1108
-
1109
- export default PCAPNGParser;