@netkitty/codec 2.0.0 → 2.2.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.
Files changed (136) hide show
  1. package/CHANGELOG.md +324 -0
  2. package/README.md +31 -7
  3. package/README.zh-CN.md +28 -7
  4. package/dist/Codec.d.ts +4 -3
  5. package/dist/Codec.js +48 -6
  6. package/dist/PacketHeaders.d.ts +2 -0
  7. package/dist/PacketHeaders.js +8 -4
  8. package/dist/abstracts/BaseHeader.d.ts +43 -0
  9. package/dist/abstracts/BaseHeader.js +75 -0
  10. package/dist/headers/AH.js +3 -2
  11. package/dist/headers/ARP.d.ts +3 -1
  12. package/dist/headers/ARP.js +8 -1
  13. package/dist/headers/BACnetIP.js +2 -1
  14. package/dist/headers/BFD.d.ts +2 -1
  15. package/dist/headers/BFD.js +30 -4
  16. package/dist/headers/BGP.js +8 -3
  17. package/dist/headers/Babel.js +1 -1
  18. package/dist/headers/C37118.d.ts +3 -2
  19. package/dist/headers/C37118.js +34 -15
  20. package/dist/headers/CDP.d.ts +3 -3
  21. package/dist/headers/CDP.js +46 -10
  22. package/dist/headers/CMS.js +25 -10
  23. package/dist/headers/COTP.js +2 -3
  24. package/dist/headers/CoAP.js +20 -2
  25. package/dist/headers/Codesys.js +3 -2
  26. package/dist/headers/DCCP.d.ts +3 -2
  27. package/dist/headers/DCCP.js +60 -8
  28. package/dist/headers/DHCP.js +2 -1
  29. package/dist/headers/DNP3.d.ts +12 -5
  30. package/dist/headers/DNP3.js +153 -18
  31. package/dist/headers/DTLS.js +5 -3
  32. package/dist/headers/Diameter.js +2 -1
  33. package/dist/headers/EIGRP.d.ts +3 -2
  34. package/dist/headers/EIGRP.js +31 -5
  35. package/dist/headers/Elasticsearch.js +3 -2
  36. package/dist/headers/EthernetII.d.ts +1 -0
  37. package/dist/headers/EthernetII.js +4 -0
  38. package/dist/headers/GELF.js +1 -0
  39. package/dist/headers/GENEVE.js +1 -0
  40. package/dist/headers/GRE.js +1 -0
  41. package/dist/headers/GTPv2C.js +1 -0
  42. package/dist/headers/Goose.d.ts +31 -7
  43. package/dist/headers/Goose.js +413 -172
  44. package/dist/headers/HARTIP.js +2 -2
  45. package/dist/headers/HSR.js +1 -0
  46. package/dist/headers/HTTP2.js +1 -0
  47. package/dist/headers/ICMP.js +2 -1
  48. package/dist/headers/ICMPv6.js +10 -16
  49. package/dist/headers/IEC104_I_Frame.d.ts +28 -0
  50. package/dist/headers/IEC104_I_Frame.js +434 -319
  51. package/dist/headers/IEC104_S_Frame.js +22 -4
  52. package/dist/headers/IEC104_U_Frame.js +24 -4
  53. package/dist/headers/IEC61850SampledValues.d.ts +1 -0
  54. package/dist/headers/IEC61850SampledValues.js +20 -5
  55. package/dist/headers/IGMP.d.ts +8 -7
  56. package/dist/headers/IGMP.js +57 -19
  57. package/dist/headers/IPFIX.js +3 -2
  58. package/dist/headers/IPv4.d.ts +1 -0
  59. package/dist/headers/IPv4.js +32 -23
  60. package/dist/headers/IPv6.d.ts +1 -0
  61. package/dist/headers/IPv6.js +10 -1
  62. package/dist/headers/IPv6HopByHopOptions.js +11 -1
  63. package/dist/headers/ISAKMP.js +1 -0
  64. package/dist/headers/KNXnetIP.js +3 -2
  65. package/dist/headers/Kerberos.js +1 -0
  66. package/dist/headers/L2TP.js +1 -0
  67. package/dist/headers/LACP.js +2 -1
  68. package/dist/headers/LDAP.js +1 -1
  69. package/dist/headers/LDP.js +2 -2
  70. package/dist/headers/LLC.js +1 -0
  71. package/dist/headers/MQTT.js +3 -1
  72. package/dist/headers/MarkerProtocol.js +2 -1
  73. package/dist/headers/NHRP.d.ts +1 -1
  74. package/dist/headers/NHRP.js +29 -4
  75. package/dist/headers/NetFlowV5.js +2 -1
  76. package/dist/headers/OPCUA.js +4 -0
  77. package/dist/headers/OSPF.d.ts +5 -5
  78. package/dist/headers/OSPF.js +98 -12
  79. package/dist/headers/OSPFv3.d.ts +37 -0
  80. package/dist/headers/OSPFv3.js +314 -0
  81. package/dist/headers/PIM.d.ts +3 -3
  82. package/dist/headers/PIM.js +55 -6
  83. package/dist/headers/PPPoEDiscovery.js +2 -0
  84. package/dist/headers/PPTP.js +2 -2
  85. package/dist/headers/PTP.js +5 -1
  86. package/dist/headers/QUIC.js +8 -3
  87. package/dist/headers/RDP.js +2 -0
  88. package/dist/headers/RGoose.js +4 -1
  89. package/dist/headers/RIP.js +3 -2
  90. package/dist/headers/RIPng.js +3 -2
  91. package/dist/headers/RSVP.d.ts +3 -3
  92. package/dist/headers/RSVP.js +56 -42
  93. package/dist/headers/RTCP.js +4 -2
  94. package/dist/headers/RTP.js +3 -2
  95. package/dist/headers/SCTP.d.ts +2 -2
  96. package/dist/headers/SCTP.js +29 -5
  97. package/dist/headers/SFlow.js +4 -2
  98. package/dist/headers/SLMP.js +2 -1
  99. package/dist/headers/SLP.js +2 -1
  100. package/dist/headers/SLPv1.js +2 -1
  101. package/dist/headers/SMB1.js +3 -2
  102. package/dist/headers/SMB2.js +3 -2
  103. package/dist/headers/SNAP.js +2 -2
  104. package/dist/headers/SNMP.js +2 -2
  105. package/dist/headers/STUN.js +3 -2
  106. package/dist/headers/SercosIII.d.ts +3 -2
  107. package/dist/headers/SercosIII.js +41 -5
  108. package/dist/headers/TCP.js +13 -58
  109. package/dist/headers/TLS_Alert.js +20 -2
  110. package/dist/headers/TLS_ApplicationData.d.ts +3 -3
  111. package/dist/headers/TLS_ApplicationData.js +25 -6
  112. package/dist/headers/TLS_ChangeCipherSpec.d.ts +2 -2
  113. package/dist/headers/TLS_ChangeCipherSpec.js +24 -4
  114. package/dist/headers/TLS_Handshake.d.ts +6 -0
  115. package/dist/headers/TLS_Handshake.js +67 -9
  116. package/dist/headers/TLS_Heartbeat.d.ts +4 -3
  117. package/dist/headers/TLS_Heartbeat.js +40 -7
  118. package/dist/headers/TPKT.js +1 -1
  119. package/dist/headers/TacacsPlus.js +3 -1
  120. package/dist/headers/Trailer.d.ts +30 -0
  121. package/dist/headers/Trailer.js +63 -0
  122. package/dist/headers/UDP.js +17 -61
  123. package/dist/headers/VLAN_802dot1Q.d.ts +1 -0
  124. package/dist/headers/VLAN_802dot1Q.js +4 -0
  125. package/dist/headers/VRRP.d.ts +2 -1
  126. package/dist/headers/VRRP.js +45 -9
  127. package/dist/headers/WakeOnLAN.js +2 -1
  128. package/dist/headers/WireGuard.js +3 -2
  129. package/dist/headers/Zabbix.js +2 -2
  130. package/dist/helper/Checksum.d.ts +15 -0
  131. package/dist/helper/Checksum.js +56 -0
  132. package/dist/helper/Crc.d.ts +18 -0
  133. package/dist/helper/Crc.js +58 -0
  134. package/dist/lib/BERElement.d.ts +51 -0
  135. package/dist/lib/BERElement.js +125 -0
  136. package/package.json +2 -2
package/dist/Codec.js CHANGED
@@ -38,6 +38,8 @@ exports.Codec = void 0;
38
38
  const FlexibleObject_1 = require("./lib/FlexibleObject");
39
39
  const ProcessPacketPostHandlers_1 = require("./lib/ProcessPacketPostHandlers");
40
40
  const RawData_1 = require("./headers/RawData");
41
+ const Trailer_1 = require("./headers/Trailer");
42
+ const BaseHeader_1 = require("./abstracts/BaseHeader");
41
43
  const CodecSchemaValidateError_1 = require("./errors/CodecSchemaValidateError");
42
44
  const packetHeaders = __importStar(require("./PacketHeaders"));
43
45
  /**
@@ -95,6 +97,11 @@ class Codec {
95
97
  * used explicitly as the final fallback so decode never fails.
96
98
  */
97
99
  #rawDataCodec = RawData_1.RawData;
100
+ /**
101
+ * The Trailer layer: bytes past the end a layer's own length field gives (Ethernet padding). Not
102
+ * part of the dispatch table or heuristic list; decode places it (see #decode), never selects it.
103
+ */
104
+ #trailerCodec = Trailer_1.Trailer;
98
105
  get HEADER_CODECS() {
99
106
  return this.#codecModuleConstructors;
100
107
  }
@@ -168,6 +175,10 @@ class Codec {
168
175
  this.#rawDataCodec = codecModuleConstructor;
169
176
  continue;
170
177
  }
178
+ if (protocolId === Trailer_1.Trailer.PROTOCOL_ID) {
179
+ this.#trailerCodec = codecModuleConstructor;
180
+ continue;
181
+ }
171
182
  for (const heuristicParent of codecModuleConstructor.HEURISTIC_PARENTS || []) {
172
183
  const parentId = typeof heuristicParent === 'string' ? heuristicParent : heuristicParent.parent;
173
184
  const entry = {
@@ -362,7 +373,10 @@ class Codec {
362
373
  const codecModule = codecModuleConstructor.CREATE_INSTANCE(codecData, codecModules);
363
374
  let validated;
364
375
  try {
365
- validated = codecModule.validate(input.data);
376
+ //Ajv fills schema defaults into, and coerces types in, the object it validates. Work on
377
+ //a deep copy so the caller's input is never changed (re-encoding it later must not
378
+ //replay those defaults as explicit values).
379
+ validated = codecModule.validate(structuredClone(input.data));
366
380
  }
367
381
  catch (e) {
368
382
  //Name the input layer by position too, so a caller can bind the error to its form.
@@ -437,6 +451,25 @@ class Codec {
437
451
  codecModules.push(codecModule);
438
452
  if (codecData.startPos >= codecData.packet.length)
439
453
  return;
454
+ const payloadEnd = codecModule.payloadEnd();
455
+ if (payloadEnd !== undefined && payloadEnd >= codecData.startPos && payloadEnd < codecData.packet.length) {
456
+ //The layer's own length ends its payload before the bytes do (Ethernet padding, a trailer).
457
+ //Decode the layers above on a view cut at that end, so neither they nor their post-decode
458
+ //handlers see the extra bytes, then keep those bytes as a trailer layer. Nested bounds (IP in
459
+ //IP) cut the view again, each level adding its own trailer.
460
+ if (payloadEnd > codecData.startPos) {
461
+ const payloadData = { packet: codecData.packet.subarray(0, payloadEnd), startPos: codecData.startPos, postHandlers: codecData.postHandlers };
462
+ await this.#decode(payloadData, codecModules, collectRanges);
463
+ }
464
+ codecData.startPos = payloadEnd;
465
+ const trailer = this.#trailerCodec.CREATE_INSTANCE(codecData, codecModules);
466
+ if (collectRanges)
467
+ trailer.enableByteRangeTracking();
468
+ await trailer.decode();
469
+ codecData.startPos = trailer.endPos;
470
+ codecModules.push(trailer);
471
+ return;
472
+ }
440
473
  return this.#decode(codecData, codecModules, collectRanges, rootLinktype);
441
474
  }
442
475
  /**
@@ -481,6 +514,13 @@ class Codec {
481
514
  await postEncodeHandler.handler();
482
515
  postEncodeHandler = postEncodeHandlers.shift();
483
516
  }
517
+ //Trailer layers are written only now, once every packet-level post handler has run, so no
518
+ //computed length or checksum counted their bytes (see Trailer).
519
+ reports.forEach((report, index) => {
520
+ if (!(report instanceof Trailer_1.Trailer))
521
+ return;
522
+ report.appendToPacket(reports.slice(index + 1).some((later) => later instanceof BaseHeader_1.BaseHeader && !(later instanceof Trailer_1.Trailer)));
523
+ });
484
524
  //Collect each layer's errors only now, so those recorded by packet-level post handlers (which
485
525
  //run after every layer is encoded) are reported too; layer order is preserved.
486
526
  const errors = [];
@@ -510,7 +550,8 @@ class Codec {
510
550
  * may follow `parentLayerId`, each tagged with the {field,value} to set on the parent so decode
511
551
  * would route to it. Derived by reversing the dispatch table over the parent's producer fields,
512
552
  * plus the content-heuristic children that declare this parent in `heuristicParents` (listed with a
513
- * null discriminator). RawData is always appended as the custom/fallback layer that may follow anything.
553
+ * null discriminator). RawData (the custom/fallback layer) and Trailer (padding written after every
554
+ * other layer) are always appended: either may follow anything.
514
555
  * @param parentLayerId
515
556
  */
516
557
  allowedNextLayers(parentLayerId) {
@@ -554,6 +595,7 @@ class Codec {
554
595
  result.push({ id: codecModuleConstructor.PROTOCOL_ID, name: codecModuleConstructor.PROTOCOL_NAME, discriminator: discriminator });
555
596
  }
556
597
  result.push({ id: this.#rawDataCodec.PROTOCOL_ID, name: this.#rawDataCodec.PROTOCOL_NAME, discriminator: null });
598
+ result.push({ id: this.#trailerCodec.PROTOCOL_ID, name: this.#trailerCodec.PROTOCOL_NAME, discriminator: null });
557
599
  return result;
558
600
  }
559
601
  /**
@@ -576,7 +618,7 @@ class Codec {
576
618
  * actually follows (e.g. eth.etherType says IPv6 but the next layer is IPv4). This is advisory
577
619
  * only — encode never blocks on it, since a deliberately-inconsistent packet is a valid crafted
578
620
  * packet. Only demux-based relationships are checked; content-heuristic children (TLS/IEC104) are
579
- * not flagged. RawData may follow anything and is never flagged.
621
+ * not flagged. RawData and Trailer may follow anything and are never flagged.
580
622
  * @param decoded
581
623
  */
582
624
  checkConsistency(decoded) {
@@ -584,7 +626,7 @@ class Codec {
584
626
  for (let i = 0; i < decoded.length - 1; i++) {
585
627
  const parent = decoded[i];
586
628
  const child = decoded[i + 1];
587
- if (child.id === this.#rawDataCodec.PROTOCOL_ID)
629
+ if (child.id === this.#rawDataCodec.PROTOCOL_ID || child.id === this.#trailerCodec.PROTOCOL_ID)
588
630
  continue;
589
631
  //A content-heuristic child (no matchKeys, or heuristicFallback dual) is legitimately
590
632
  //reachable off its well-known demux value (e.g. TLS on a non-443 port). Never flag it as
@@ -702,7 +744,7 @@ class Codec {
702
744
  * One-line human summary of a decoded packet (Wireshark's Info column). The innermost layer that
703
745
  * declares a `summary` template in its schema wins (the most specific layer describes the packet);
704
746
  * the template's ${dotted.field} placeholders are filled from that layer's decoded data. Falls back
705
- * to the innermost non-raw layer's name when no template is declared. Read-only projection.
747
+ * to the innermost layer that is neither raw nor a trailer when no template is declared. Read-only projection.
706
748
  * @param decoded
707
749
  */
708
750
  summary(decoded) {
@@ -712,7 +754,7 @@ class Codec {
712
754
  return this.#renderSummary(schema.summary, decoded[i].data);
713
755
  }
714
756
  for (let i = decoded.length - 1; i >= 0; i--) {
715
- if (decoded[i].id !== this.#rawDataCodec.PROTOCOL_ID)
757
+ if (decoded[i].id !== this.#rawDataCodec.PROTOCOL_ID && decoded[i].id !== this.#trailerCodec.PROTOCOL_ID)
716
758
  return decoded[i].name;
717
759
  }
718
760
  return decoded.length ? decoded[decoded.length - 1].name : '';
@@ -8,6 +8,7 @@ export { IPv6 } from './headers/IPv6';
8
8
  export { IPv6HopByHopOptions } from './headers/IPv6HopByHopOptions';
9
9
  export { ICMPv6 } from './headers/ICMPv6';
10
10
  export { RawData } from './headers/RawData';
11
+ export { Trailer } from './headers/Trailer';
11
12
  export { TCP } from './headers/TCP';
12
13
  export { UDP } from './headers/UDP';
13
14
  export { NTP } from './headers/NTP';
@@ -48,6 +49,7 @@ export { GRE } from './headers/GRE';
48
49
  export { BFD } from './headers/BFD';
49
50
  export { VRRP } from './headers/VRRP';
50
51
  export { OSPF } from './headers/OSPF';
52
+ export { OSPFv3 } from './headers/OSPFv3';
51
53
  export { ModbusTCP } from './headers/ModbusTCP';
52
54
  export { DNP3 } from './headers/DNP3';
53
55
  export { C37118 } from './headers/C37118';
@@ -1,9 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.OSPF = exports.VRRP = exports.BFD = exports.GRE = exports.GENEVE = exports.SOCKS5 = exports.Memcached = exports.Telnet = exports.Kerberos = exports.LDAP = exports.SSH = exports.RFB = exports.Kafka = exports.AMQP = exports.SFlow = exports.WireGuard = exports.ISAKMP = exports.Diameter = exports.PostgreSQL = exports.MySQL = exports.NetFlowV5 = exports.RGoose = exports.L2TP = exports.RMCP = exports.GTPU = exports.VXLAN = exports.RADIUS = exports.Syslog = exports.NBNS = exports.LLMNR = exports.TFTP = exports.DHCPv6 = exports.MDNS = exports.SNMP = exports.DNS = exports.DHCP = exports.STUN = exports.NTP = exports.UDP = exports.TCP = exports.RawData = exports.ICMPv6 = exports.IPv6HopByHopOptions = exports.IPv6 = exports.IPv4 = exports.ICMP = exports.IEC61850SampledValues = exports.Goose = exports.EthernetII = exports.ARP = void 0;
4
- exports.SunRPC = exports.SSDP = exports.RSVP = exports.RIPng = exports.PTP = exports.PPPoESession = exports.PPPoEDiscovery = exports.PIM = exports.MPLS = exports.LACP = exports.Ident = exports.IGMP = exports.HSRP = exports.GTPv2C = exports.EIGRP = exports.DCCP = exports.WHOIS = exports.SOCKS4 = exports.Rlogin = exports.RIP = exports.Finger = exports.ESP = exports.EAPOL = exports.BGP = exports.AH = exports.HSR = exports.IRC = exports.NNTP = exports.IMAP = exports.POP3 = exports.SMTP = exports.COTP = exports.TPKT = exports.RTSP = exports.FTP = exports.HTTP = exports.EtherCAT = exports.PROFINETRT = exports.SIP = exports.LLDP = exports.TacacsPlus = exports.Redis = exports.MQTT = exports.CoAP = exports.OPCUA = exports.ENIP = exports.BACnetIP = exports.C37118 = exports.DNP3 = exports.ModbusTCP = void 0;
5
- exports.BitTorrent = exports.BSAPIP = exports.ADSAMS = exports.Zabbix = exports.TimeProtocol = exports.StatsD = exports.Skinny = exports.OPCUAPubSub = exports.OLSR = exports.NHRP = exports.NATS = exports.MGCP = exports.MACsec = exports.IPFIX = exports.IAX2 = exports.GLBP = exports.FCoE = exports.Elasticsearch = exports.Collectd = exports.SMPP = exports.SMB2 = exports.SLMP = exports.Rsync = exports.RTPS = exports.OpenFlow = exports.OmronFINS = exports.NBDS = exports.MongoDB = exports.MQTTSN = exports.LISP = exports.KNXnetIP = exports.GitProtocol = exports.CassandraCQL = exports.CAPWAP = exports.XMPP = exports.WCCP = exports.SercosIII = exports.STOMP = exports.PPTP = exports.POWERLINK = exports.OpenVPN = exports.NBSS = exports.LPD = exports.LDP = exports.ISCSI = exports.HARTIP = exports.Gopher = exports.FoundationFieldbusHSE = exports.DTLS = exports.Babel = void 0;
6
- exports.IEC104_U_Frame = exports.IEC104_S_Frame = exports.IEC104_I_Frame = exports.TLS_Heartbeat = exports.TLS_Handshake = exports.TLS_ChangeCipherSpec = exports.TLS_ApplicationData = exports.TLS_Alert = exports.VLAN_802dot1Q = exports.MMS = exports.CMS = exports.ISOSession = exports.RDP = exports.SNAP = exports.ISIS = exports.CDP = exports.S7comm = exports.STP = exports.LLC = exports.SMB1 = exports.SCTP = exports.RTP = exports.RTCP = exports.QUIC = exports.NFS = exports.WakeOnLAN = exports.WSDiscovery = exports.Teredo = exports.SLPv1 = exports.SLP = exports.PCWorx = exports.ModbusUDP = exports.Megaco = exports.MarkerProtocol = exports.HTTP2 = exports.GESRTP = exports.GELF = exports.DHCPFailover = exports.Codesys = void 0;
3
+ exports.VRRP = exports.BFD = exports.GRE = exports.GENEVE = exports.SOCKS5 = exports.Memcached = exports.Telnet = exports.Kerberos = exports.LDAP = exports.SSH = exports.RFB = exports.Kafka = exports.AMQP = exports.SFlow = exports.WireGuard = exports.ISAKMP = exports.Diameter = exports.PostgreSQL = exports.MySQL = exports.NetFlowV5 = exports.RGoose = exports.L2TP = exports.RMCP = exports.GTPU = exports.VXLAN = exports.RADIUS = exports.Syslog = exports.NBNS = exports.LLMNR = exports.TFTP = exports.DHCPv6 = exports.MDNS = exports.SNMP = exports.DNS = exports.DHCP = exports.STUN = exports.NTP = exports.UDP = exports.TCP = exports.Trailer = exports.RawData = exports.ICMPv6 = exports.IPv6HopByHopOptions = exports.IPv6 = exports.IPv4 = exports.ICMP = exports.IEC61850SampledValues = exports.Goose = exports.EthernetII = exports.ARP = void 0;
4
+ exports.RSVP = exports.RIPng = exports.PTP = exports.PPPoESession = exports.PPPoEDiscovery = exports.PIM = exports.MPLS = exports.LACP = exports.Ident = exports.IGMP = exports.HSRP = exports.GTPv2C = exports.EIGRP = exports.DCCP = exports.WHOIS = exports.SOCKS4 = exports.Rlogin = exports.RIP = exports.Finger = exports.ESP = exports.EAPOL = exports.BGP = exports.AH = exports.HSR = exports.IRC = exports.NNTP = exports.IMAP = exports.POP3 = exports.SMTP = exports.COTP = exports.TPKT = exports.RTSP = exports.FTP = exports.HTTP = exports.EtherCAT = exports.PROFINETRT = exports.SIP = exports.LLDP = exports.TacacsPlus = exports.Redis = exports.MQTT = exports.CoAP = exports.OPCUA = exports.ENIP = exports.BACnetIP = exports.C37118 = exports.DNP3 = exports.ModbusTCP = exports.OSPFv3 = exports.OSPF = void 0;
5
+ exports.ADSAMS = exports.Zabbix = exports.TimeProtocol = exports.StatsD = exports.Skinny = exports.OPCUAPubSub = exports.OLSR = exports.NHRP = exports.NATS = exports.MGCP = exports.MACsec = exports.IPFIX = exports.IAX2 = exports.GLBP = exports.FCoE = exports.Elasticsearch = exports.Collectd = exports.SMPP = exports.SMB2 = exports.SLMP = exports.Rsync = exports.RTPS = exports.OpenFlow = exports.OmronFINS = exports.NBDS = exports.MongoDB = exports.MQTTSN = exports.LISP = exports.KNXnetIP = exports.GitProtocol = exports.CassandraCQL = exports.CAPWAP = exports.XMPP = exports.WCCP = exports.SercosIII = exports.STOMP = exports.PPTP = exports.POWERLINK = exports.OpenVPN = exports.NBSS = exports.LPD = exports.LDP = exports.ISCSI = exports.HARTIP = exports.Gopher = exports.FoundationFieldbusHSE = exports.DTLS = exports.Babel = exports.SunRPC = exports.SSDP = void 0;
6
+ exports.IEC104_U_Frame = exports.IEC104_S_Frame = exports.IEC104_I_Frame = exports.TLS_Heartbeat = exports.TLS_Handshake = exports.TLS_ChangeCipherSpec = exports.TLS_ApplicationData = exports.TLS_Alert = exports.VLAN_802dot1Q = exports.MMS = exports.CMS = exports.ISOSession = exports.RDP = exports.SNAP = exports.ISIS = exports.CDP = exports.S7comm = exports.STP = exports.LLC = exports.SMB1 = exports.SCTP = exports.RTP = exports.RTCP = exports.QUIC = exports.NFS = exports.WakeOnLAN = exports.WSDiscovery = exports.Teredo = exports.SLPv1 = exports.SLP = exports.PCWorx = exports.ModbusUDP = exports.Megaco = exports.MarkerProtocol = exports.HTTP2 = exports.GESRTP = exports.GELF = exports.DHCPFailover = exports.Codesys = exports.BitTorrent = exports.BSAPIP = void 0;
7
7
  var ARP_1 = require("./headers/ARP");
8
8
  Object.defineProperty(exports, "ARP", { enumerable: true, get: function () { return ARP_1.ARP; } });
9
9
  var EthernetII_1 = require("./headers/EthernetII");
@@ -24,6 +24,8 @@ var ICMPv6_1 = require("./headers/ICMPv6");
24
24
  Object.defineProperty(exports, "ICMPv6", { enumerable: true, get: function () { return ICMPv6_1.ICMPv6; } });
25
25
  var RawData_1 = require("./headers/RawData");
26
26
  Object.defineProperty(exports, "RawData", { enumerable: true, get: function () { return RawData_1.RawData; } });
27
+ var Trailer_1 = require("./headers/Trailer");
28
+ Object.defineProperty(exports, "Trailer", { enumerable: true, get: function () { return Trailer_1.Trailer; } });
27
29
  var TCP_1 = require("./headers/TCP");
28
30
  Object.defineProperty(exports, "TCP", { enumerable: true, get: function () { return TCP_1.TCP; } });
29
31
  var UDP_1 = require("./headers/UDP");
@@ -104,6 +106,8 @@ var VRRP_1 = require("./headers/VRRP");
104
106
  Object.defineProperty(exports, "VRRP", { enumerable: true, get: function () { return VRRP_1.VRRP; } });
105
107
  var OSPF_1 = require("./headers/OSPF");
106
108
  Object.defineProperty(exports, "OSPF", { enumerable: true, get: function () { return OSPF_1.OSPF; } });
109
+ var OSPFv3_1 = require("./headers/OSPFv3");
110
+ Object.defineProperty(exports, "OSPFv3", { enumerable: true, get: function () { return OSPFv3_1.OSPFv3; } });
107
111
  var ModbusTCP_1 = require("./headers/ModbusTCP");
108
112
  Object.defineProperty(exports, "ModbusTCP", { enumerable: true, get: function () { return ModbusTCP_1.ModbusTCP; } });
109
113
  var DNP3_1 = require("./headers/DNP3");
@@ -149,6 +149,15 @@ export declare abstract class BaseHeader {
149
149
  * Readonly Header length
150
150
  */
151
151
  get length(): number;
152
+ /**
153
+ * Decode only: the packet offset where this layer's payload ends by its own length field (IPv4
154
+ * Total Length, IPv6 Payload Length, an 802.3 length), read after decode(). The codec decodes the
155
+ * layers above inside that bound and keeps any bytes past it as a `trailer` layer (Ethernet padding
156
+ * and the like). Undefined, the default, means the payload runs to the end of the bytes available.
157
+ * The codec ignores a bound outside [endPos, the bytes available), so a zero, overstated or
158
+ * truncated length decodes as it would without one.
159
+ */
160
+ payloadEnd(): number | undefined;
152
161
  /**
153
162
  * Header length
154
163
  * @protected
@@ -295,6 +304,40 @@ export declare abstract class BaseHeader {
295
304
  * @protected
296
305
  */
297
306
  protected encodeOmittedEtherType(field: FlexibleObject, offset: number): void;
307
+ /**
308
+ * payloadEnd() for a header whose `etherType` field doubles as an IEEE 802.3 length (Ethernet,
309
+ * 802.1Q): a value of 3–1500 gives the octets of LLC data that follow this header. Anything else
310
+ * (an EtherType, or a length too short for an LLC header) sets no bound.
311
+ * @param field the etherType field
312
+ * @protected
313
+ */
314
+ protected ieee802dot3PayloadEnd(field: FlexibleObject): number | undefined;
315
+ /**
316
+ * True when `field` was left out of the encode input, which is what asks encode to calculate an
317
+ * autoCalculated length, count or checksum. Any value given, 0 included, is written as given, so a
318
+ * deliberately wrong value can still be crafted. An empty string counts as left out (a hex field
319
+ * has no bytes to write then). Read it at the top of the field's encode closure, before the closure
320
+ * writes a placeholder into the same node.
321
+ * @param field
322
+ * @protected
323
+ */
324
+ protected isLeftOut(field: FlexibleObject): boolean;
325
+ /**
326
+ * The nearest IPv4 or IPv6 layer beneath this one, skipping whatever sits in between (AH, IPv6
327
+ * extension headers, …); undefined when there is none.
328
+ * @protected
329
+ */
330
+ protected nearestIPModule(): CodecModule | undefined;
331
+ /**
332
+ * The pseudo-header an upper-layer checksum covers, built from the nearest IP layer beneath: for
333
+ * IPv4 source, destination, zero, protocol and the 16-bit upper-layer length (RFC 768 / 793); for
334
+ * IPv6 source, destination, the 32-bit length, three zero octets and the next header (RFC 8200
335
+ * section 8.1). undefined when no IP layer is beneath or its addresses are unusable.
336
+ * @param protocol the upper-layer protocol number (6 TCP, 17 UDP, …)
337
+ * @param upperLayerLength byte count the checksum covers above the pseudo-header
338
+ * @protected
339
+ */
340
+ protected ipPseudoHeader(protocol: number, upperLayerLength: number): Buffer | undefined;
298
341
  /**
299
342
  * Record encode/decode error
300
343
  * @param path
@@ -157,6 +157,17 @@ class BaseHeader {
157
157
  get length() {
158
158
  return this.headerLength;
159
159
  }
160
+ /**
161
+ * Decode only: the packet offset where this layer's payload ends by its own length field (IPv4
162
+ * Total Length, IPv6 Payload Length, an 802.3 length), read after decode(). The codec decodes the
163
+ * layers above inside that bound and keeps any bytes past it as a `trailer` layer (Ethernet padding
164
+ * and the like). Undefined, the default, means the payload runs to the end of the bytes available.
165
+ * The codec ignores a bound outside [endPos, the bytes available), so a zero, overstated or
166
+ * truncated length decodes as it would without one.
167
+ */
168
+ payloadEnd() {
169
+ return undefined;
170
+ }
160
171
  /**
161
172
  * Post packet handlers
162
173
  * @protected
@@ -606,6 +617,70 @@ class BaseHeader {
606
617
  this.writeBytes(offset, (0, NumberToBuffer_1.UInt16ToBuffer)(Math.min(length, 0xffff)));
607
618
  });
608
619
  }
620
+ /**
621
+ * payloadEnd() for a header whose `etherType` field doubles as an IEEE 802.3 length (Ethernet,
622
+ * 802.1Q): a value of 3–1500 gives the octets of LLC data that follow this header. Anything else
623
+ * (an EtherType, or a length too short for an LLC header) sets no bound.
624
+ * @param field the etherType field
625
+ * @protected
626
+ */
627
+ ieee802dot3PayloadEnd(field) {
628
+ const length = parseInt(field.getValue('').toString(), 16);
629
+ return length >= 3 && length <= 0x05dc ? this.endPos + length : undefined;
630
+ }
631
+ /**
632
+ * True when `field` was left out of the encode input, which is what asks encode to calculate an
633
+ * autoCalculated length, count or checksum. Any value given, 0 included, is written as given, so a
634
+ * deliberately wrong value can still be crafted. An empty string counts as left out (a hex field
635
+ * has no bytes to write then). Read it at the top of the field's encode closure, before the closure
636
+ * writes a placeholder into the same node.
637
+ * @param field
638
+ * @protected
639
+ */
640
+ isLeftOut(field) {
641
+ const value = field.getValue();
642
+ return value === undefined || value === null || value === '';
643
+ }
644
+ /**
645
+ * The nearest IPv4 or IPv6 layer beneath this one, skipping whatever sits in between (AH, IPv6
646
+ * extension headers, …); undefined when there is none.
647
+ * @protected
648
+ */
649
+ nearestIPModule() {
650
+ for (let i = this.prevCodecModules.length - 1; i >= 0; i--) {
651
+ const id = this.prevCodecModules[i].id;
652
+ if (id === 'ipv4' || id === 'ipv6')
653
+ return this.prevCodecModules[i];
654
+ }
655
+ return undefined;
656
+ }
657
+ /**
658
+ * The pseudo-header an upper-layer checksum covers, built from the nearest IP layer beneath: for
659
+ * IPv4 source, destination, zero, protocol and the 16-bit upper-layer length (RFC 768 / 793); for
660
+ * IPv6 source, destination, the 32-bit length, three zero octets and the next header (RFC 8200
661
+ * section 8.1). undefined when no IP layer is beneath or its addresses are unusable.
662
+ * @param protocol the upper-layer protocol number (6 TCP, 17 UDP, …)
663
+ * @param upperLayerLength byte count the checksum covers above the pseudo-header
664
+ * @protected
665
+ */
666
+ ipPseudoHeader(protocol, upperLayerLength) {
667
+ const ip = this.nearestIPModule();
668
+ if (!ip)
669
+ return undefined;
670
+ const sourceIp = ip.instance.sip.getValue();
671
+ const destinationIp = ip.instance.dip.getValue();
672
+ if (typeof sourceIp !== 'string' || typeof destinationIp !== 'string')
673
+ return undefined;
674
+ try {
675
+ if (ip.id === 'ipv4') {
676
+ return Buffer.concat([(0, IPToBuffer_1.IPv4ToBuffer)(sourceIp), (0, IPToBuffer_1.IPv4ToBuffer)(destinationIp), (0, NumberToBuffer_1.UInt8ToBuffer)(0), (0, NumberToBuffer_1.UInt8ToBuffer)(protocol), (0, NumberToBuffer_1.UInt16ToBuffer)(upperLayerLength)]);
677
+ }
678
+ return Buffer.concat([(0, IPToBuffer_1.IPv6ToBuffer)(sourceIp), (0, IPToBuffer_1.IPv6ToBuffer)(destinationIp), (0, NumberToBuffer_1.UInt32ToBuffer)(upperLayerLength), Buffer.alloc(3, 0), (0, NumberToBuffer_1.UInt8ToBuffer)(protocol)]);
679
+ }
680
+ catch (e) {
681
+ return undefined;
682
+ }
683
+ }
609
684
  /**
610
685
  * Dotted path of the index-th field codec in the same walk order getFieldCodecs uses. Cold path only
611
686
  * (a field closure threw): rebuilds the path list on demand so the hot loop carries no per-field
@@ -69,7 +69,7 @@ class AH extends BaseHeader_1.BaseHeader {
69
69
  //Next Header is an IP-protocol number (the type of the protected payload); stored as
70
70
  //`nxt` — the field name IPv6 extension headers use — so the `ipproto` demux routes the
71
71
  //inner layer and TCP/UDP's `nxt`-aware match() accepts AH as a parent.
72
- nxt: this.fieldUInt('nxt', 0, 1, 'Next Header'),
72
+ nxt: { ...this.fieldUInt('nxt', 0, 1, 'Next Header'), autoCalculated: true },
73
73
  //AH total length in 4-octet words minus 2. Honored-else-derived: a supplied value is
74
74
  //kept verbatim, an absent (0) one is recomputed from the encoded ICV length.
75
75
  payloadLen: {
@@ -82,10 +82,11 @@ class AH extends BaseHeader_1.BaseHeader {
82
82
  this.instance.payloadLen.setValue((0, BufferToNumber_1.BufferToUInt8)(this.readBytes(1, 1)));
83
83
  },
84
84
  encode: function () {
85
+ const leftOut = this.isLeftOut(this.instance.payloadLen);
85
86
  const payloadLen = this.instance.payloadLen.getValue(0);
86
87
  this.instance.payloadLen.setValue(payloadLen);
87
88
  this.writeBytes(1, (0, NumberToBuffer_1.UInt8ToBuffer)(payloadLen));
88
- if (!payloadLen) {
89
+ if (leftOut) {
89
90
  this.addPostSelfEncodeHandler(() => {
90
91
  //Fixed prefix is 12 octets (3 words); total = 12 + ICV octets, and
91
92
  //Payload Len = totalWords - 2 = (12 + icvBytes)/4 - 2 = icvBytes/4 + 1.
@@ -14,7 +14,8 @@ import { BaseHeader } from '../abstracts/BaseHeader';
14
14
  *
15
15
  * The 6-octet MAC and 4-octet IPv4 widths are fixed here (Ethernet + IPv4 ARP), independent of the
16
16
  * declared hardware/protocol sizes. Values are range-clamped rather than rejected. match() keys purely
17
- * on the parent's EtherType being 0x0806.
17
+ * on the parent's EtherType being 0x0806. When the declared sizes are 6 and 4, the bytes after the 28
18
+ * octets (Ethernet padding) decode as a `trailer` layer (see payloadEnd).
18
19
  */
19
20
  export declare class ARP extends BaseHeader {
20
21
  SCHEMA: ProtocolJSONSchema;
@@ -22,5 +23,6 @@ export declare class ARP extends BaseHeader {
22
23
  readonly matchKeys: string[];
23
24
  readonly name: string;
24
25
  readonly nickname: string;
26
+ payloadEnd(): number | undefined;
25
27
  match(): boolean;
26
28
  }
@@ -24,7 +24,8 @@ const IPToBuffer_1 = require("../helper/IPToBuffer");
24
24
  *
25
25
  * The 6-octet MAC and 4-octet IPv4 widths are fixed here (Ethernet + IPv4 ARP), independent of the
26
26
  * declared hardware/protocol sizes. Values are range-clamped rather than rejected. match() keys purely
27
- * on the parent's EtherType being 0x0806.
27
+ * on the parent's EtherType being 0x0806. When the declared sizes are 6 and 4, the bytes after the 28
28
+ * octets (Ethernet padding) decode as a `trailer` layer (see payloadEnd).
28
29
  */
29
30
  class ARP extends BaseHeader_1.BaseHeader {
30
31
  constructor() {
@@ -237,6 +238,12 @@ class ARP extends BaseHeader_1.BaseHeader {
237
238
  this.name = 'Address Resolution Protocol';
238
239
  this.nickname = 'ARP';
239
240
  }
241
+ payloadEnd() {
242
+ //An Ethernet/IPv4 ARP packet ends after its 28 octets, so what follows is Ethernet padding. Other
243
+ //declared address sizes set no bound: the fixed-width fields do not cover such a packet.
244
+ const ethernetIPv4 = this.instance.hardware.size.getValue() === 6 && this.instance.protocol.size.getValue() === 4;
245
+ return ethernetIPv4 ? this.endPos : undefined;
246
+ }
240
247
  match() {
241
248
  if (!this.prevCodecModule)
242
249
  return false;
@@ -40,7 +40,8 @@ class BACnetIP extends BaseHeader_1.BaseHeader {
40
40
  type: 'object',
41
41
  summary: 'BACnet/IP func=${function}',
42
42
  properties: {
43
- type: this.fieldHex('type', 0, 1, 'Type'),
43
+ //Default 0x81: the BVLC type of BACnet/IP, and what match() requires.
44
+ type: { ...this.fieldHex('type', 0, 1, 'Type'), default: '81' },
44
45
  'function': this.fieldUInt('function', 1, 1, 'Function'),
45
46
  length: {
46
47
  type: 'integer',
@@ -13,7 +13,8 @@ import { DemuxProducer } from '../types/DemuxProducer';
13
13
  * If the A (Authentication Present) flag is set an optional Authentication Section follows the
14
14
  * mandatory 24 bytes (Auth Type, Auth Len, then type-specific auth data). It is kept verbatim as
15
15
  * `authSection` hex so any auth variant round-trips byte-for-byte; when A is clear it is empty. The
16
- * Length field is honoured verbatim (not recomputed) so a captured packet re-encodes byte-for-byte.
16
+ * Length field is written as given (so a captured packet re-encodes byte-for-byte); left out, it is the
17
+ * 24 mandatory bytes plus the authentication section.
17
18
  * BFD Control is a leaf — nothing rides on top of it.
18
19
  */
19
20
  export declare class BFD extends BaseHeader {
@@ -5,6 +5,8 @@ const BaseHeader_1 = require("../abstracts/BaseHeader");
5
5
  const BufferToHex_1 = require("../helper/BufferToHex");
6
6
  const HexToBuffer_1 = require("../helper/HexToBuffer");
7
7
  const StringContentEncodingEnum_1 = require("../lib/StringContentEncodingEnum");
8
+ const BufferToNumber_1 = require("../helper/BufferToNumber");
9
+ const NumberToBuffer_1 = require("../helper/NumberToBuffer");
8
10
  /**
9
11
  * BFD — Bidirectional Forwarding Detection Control (RFC 5880), UDP port 3784 (single-hop) and 4784
10
12
  * (multi-hop). The mandatory section is 24 bytes: a first byte carrying Version[3] (= 1) and a 5-bit
@@ -17,7 +19,8 @@ const StringContentEncodingEnum_1 = require("../lib/StringContentEncodingEnum");
17
19
  * If the A (Authentication Present) flag is set an optional Authentication Section follows the
18
20
  * mandatory 24 bytes (Auth Type, Auth Len, then type-specific auth data). It is kept verbatim as
19
21
  * `authSection` hex so any auth variant round-trips byte-for-byte; when A is clear it is empty. The
20
- * Length field is honoured verbatim (not recomputed) so a captured packet re-encodes byte-for-byte.
22
+ * Length field is written as given (so a captured packet re-encodes byte-for-byte); left out, it is the
23
+ * 24 mandatory bytes plus the authentication section.
21
24
  * BFD Control is a leaf — nothing rides on top of it.
22
25
  */
23
26
  class BFD extends BaseHeader_1.BaseHeader {
@@ -70,11 +73,13 @@ class BFD extends BaseHeader_1.BaseHeader {
70
73
  properties: {
71
74
  //Byte 0: Version (top 3 bits, = 1 for RFC 5880) + Diagnostic (low 5 bits). MSB-first,
72
75
  //so version is bitOffset 0..2 and diagnostic bitOffset 3..7 of a 1-octet window.
76
+ //Default 1: the RFC 5880 version, which encode writes when it is left out.
73
77
  version: {
74
78
  type: 'integer',
75
79
  label: 'Version',
76
80
  minimum: 0,
77
81
  maximum: 7,
82
+ default: 1,
78
83
  decode: function () { this.instance.version.setValue(this.readBits(0, 1, 0, 3)); },
79
84
  encode: function () { this.writeBits(0, 1, 0, 3, this.instance.version.getValue(1)); }
80
85
  },
@@ -108,9 +113,30 @@ class BFD extends BaseHeader_1.BaseHeader {
108
113
  }
109
114
  },
110
115
  detectMult: this.fieldUInt('detectMult', 2, 1, 'Detect Mult'),
111
- //Length of the entire BFD Control packet in bytes. Honoured verbatim (a real no-auth
112
- //packet carries 24) — not recomputed, so a captured packet re-encodes byte-for-byte.
113
- length: this.fieldUInt('length', 3, 1, 'Length'),
116
+ //Length of the entire BFD Control packet in bytes (a real no-auth packet carries 24).
117
+ length: {
118
+ type: 'integer',
119
+ autoCalculated: true,
120
+ label: 'Length',
121
+ minimum: 0,
122
+ maximum: 255,
123
+ decode: function () {
124
+ this.instance.length.setValue((0, BufferToNumber_1.BufferToUInt8)(this.readBytes(3, 1)));
125
+ },
126
+ encode: function () {
127
+ if (!this.isLeftOut(this.instance.length)) {
128
+ this.writeBytes(3, (0, NumberToBuffer_1.UInt8ToBuffer)(this.instance.length.getValue(0)));
129
+ return;
130
+ }
131
+ let length = 24 + (0, HexToBuffer_1.HexToBuffer)(this.instance.authSection.getValue('')).length;
132
+ if (length > 255) {
133
+ this.recordError(this.instance.length.getPath(), 'Maximum value is 255');
134
+ length = 255;
135
+ }
136
+ this.instance.length.setValue(length);
137
+ this.writeBytes(3, (0, NumberToBuffer_1.UInt8ToBuffer)(length));
138
+ }
139
+ },
114
140
  myDiscriminator: this.fieldUInt('myDiscriminator', 4, 4, 'My Discriminator'),
115
141
  yourDiscriminator: this.fieldUInt('yourDiscriminator', 8, 4, 'Your Discriminator'),
116
142
  desiredMinTxInterval: this.fieldUInt('desiredMinTxInterval', 12, 4, 'Desired Min TX Interval'),
@@ -41,13 +41,16 @@ class BGP extends BaseHeader_1.BaseHeader {
41
41
  summary: 'BGP type=${type} len=${length}',
42
42
  properties: {
43
43
  //The 16-byte Marker. In RFC 4271 (no authentication) it is all ones (0xFF); kept
44
- //verbatim so any legacy/authenticated marker still round-trips.
45
- marker: this.fieldHex('marker', 0, 16, 'Marker'),
44
+ //verbatim so any legacy/authenticated marker still round-trips. Default all ones: what
45
+ //match() requires.
46
+ marker: { ...this.fieldHex('marker', 0, 16, 'Marker'), default: 'ff'.repeat(16) },
46
47
  length: {
47
48
  type: 'integer',
48
49
  autoCalculated: true,
49
50
  label: 'Length',
50
- minimum: 19,
51
+ //The field floor, not the 19-byte minimum message: a given value is written as
52
+ //given (flagged when too short) so a malformed message can be crafted.
53
+ minimum: 0,
51
54
  maximum: 65535,
52
55
  decode: function () {
53
56
  this.instance.length.setValue((0, BufferToNumber_1.BufferToUInt16)(this.readBytes(16, 2)));
@@ -63,6 +66,8 @@ class BGP extends BaseHeader_1.BaseHeader {
63
66
  this.recordError(this.instance.length.getPath(), 'Maximum value is 65535');
64
67
  value = 65535;
65
68
  }
69
+ if (value < 19)
70
+ this.recordError(this.instance.length.getPath(), 'Length should be at least 19');
66
71
  this.instance.length.setValue(value);
67
72
  this.writeBytes(16, (0, NumberToBuffer_1.UInt16ToBuffer)(value));
68
73
  }
@@ -61,7 +61,7 @@ class Babel extends BaseHeader_1.BaseHeader {
61
61
  summary: 'Babel v${version} ${tlvs.length} TLVs',
62
62
  properties: {
63
63
  //The Magic byte, always 42 (0x2a) for Babel — also the match signature on UDP 6696.
64
- magic: this.fieldUInt('magic', 0, 1, 'Magic'),
64
+ magic: { ...this.fieldUInt('magic', 0, 1, 'Magic'), default: 42 },
65
65
  //The protocol version, always 2 (RFC 8966).
66
66
  version: this.fieldUInt('version', 1, 1, 'Version'),
67
67
  //The octet count of the packet body (the TLV sequence) following this 4-byte header, NOT
@@ -11,8 +11,9 @@ import { DemuxProducer } from '../types/DemuxProducer';
11
11
  *
12
12
  * The frame body between the header and the CHK is frame-type-specific (a configuration frame defines
13
13
  * the data layout for the data frames that follow — cross-frame state, not a single-packet concern), so
14
- * this codec keeps the body verbatim as `body` hex, bounded by FRAMESIZE, and keeps the CHK verbatim
15
- * (never recomputed). A well-formed frame round-trips byte-for-byte.
14
+ * this codec keeps the body verbatim as `body` hex, bounded by FRAMESIZE. FRAMESIZE and CHK are written
15
+ * as given; left out, FRAMESIZE is the actual frame length and CHK the CRC-CCITT (CRC-16/CCITT-FALSE:
16
+ * polynomial 0x1021, initial 0xFFFF) of every octet before it. A well-formed frame round-trips byte-for-byte.
16
17
  */
17
18
  export declare class C37118 extends BaseHeader {
18
19
  #private;