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