wa1kpcap 0.1.0__tar.gz

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 (125) hide show
  1. wa1kpcap-0.1.0/.github/workflows/publish.yml +90 -0
  2. wa1kpcap-0.1.0/.github/workflows/tests.yml +49 -0
  3. wa1kpcap-0.1.0/.gitignore +82 -0
  4. wa1kpcap-0.1.0/CHANGELOG.md +31 -0
  5. wa1kpcap-0.1.0/CLAUDE.md +175 -0
  6. wa1kpcap-0.1.0/CMakeLists.txt +12 -0
  7. wa1kpcap-0.1.0/LICENSE +21 -0
  8. wa1kpcap-0.1.0/MANIFEST.in +12 -0
  9. wa1kpcap-0.1.0/PKG-INFO +105 -0
  10. wa1kpcap-0.1.0/README.md +69 -0
  11. wa1kpcap-0.1.0/README_CN.md +69 -0
  12. wa1kpcap-0.1.0/context.md +93 -0
  13. wa1kpcap-0.1.0/docs/README.md +475 -0
  14. wa1kpcap-0.1.0/docs/README_CN.md +475 -0
  15. wa1kpcap-0.1.0/examples/README.md +67 -0
  16. wa1kpcap-0.1.0/examples/basic_usage.py +65 -0
  17. wa1kpcap-0.1.0/examples/custom_feature.py +282 -0
  18. wa1kpcap-0.1.0/examples/export_data.py +85 -0
  19. wa1kpcap-0.1.0/examples/feature_extraction.py +147 -0
  20. wa1kpcap-0.1.0/plan_context.md +288 -0
  21. wa1kpcap-0.1.0/pyproject.toml +62 -0
  22. wa1kpcap-0.1.0/pytest.ini +34 -0
  23. wa1kpcap-0.1.0/skills/add-custom-protocol/SKILL.md +38 -0
  24. wa1kpcap-0.1.0/skills/add-custom-protocol/examples/complete-example.md +154 -0
  25. wa1kpcap-0.1.0/skills/add-yaml-protocol/SKILL.md +66 -0
  26. wa1kpcap-0.1.0/skills/add-yaml-protocol/examples/syslog.yaml +62 -0
  27. wa1kpcap-0.1.0/src/cpp/CMakeLists.txt +36 -0
  28. wa1kpcap-0.1.0/src/cpp/bindings.cpp +1045 -0
  29. wa1kpcap-0.1.0/src/cpp/bpf_filter.cpp +780 -0
  30. wa1kpcap-0.1.0/src/cpp/bpf_filter.h +146 -0
  31. wa1kpcap-0.1.0/src/cpp/expression_eval.cpp +274 -0
  32. wa1kpcap-0.1.0/src/cpp/expression_eval.h +59 -0
  33. wa1kpcap-0.1.0/src/cpp/field_value.h +49 -0
  34. wa1kpcap-0.1.0/src/cpp/flow_buffer.cpp +77 -0
  35. wa1kpcap-0.1.0/src/cpp/flow_buffer.h +35 -0
  36. wa1kpcap-0.1.0/src/cpp/hardcoded_parsers.cpp +122 -0
  37. wa1kpcap-0.1.0/src/cpp/hardcoded_parsers.h +34 -0
  38. wa1kpcap-0.1.0/src/cpp/parsed_packet.h +229 -0
  39. wa1kpcap-0.1.0/src/cpp/pcap_reader.cpp +475 -0
  40. wa1kpcap-0.1.0/src/cpp/pcap_reader.h +87 -0
  41. wa1kpcap-0.1.0/src/cpp/protocol_engine.cpp +2241 -0
  42. wa1kpcap-0.1.0/src/cpp/protocol_engine.h +258 -0
  43. wa1kpcap-0.1.0/src/cpp/protocol_registry.h +31 -0
  44. wa1kpcap-0.1.0/src/cpp/util.h +84 -0
  45. wa1kpcap-0.1.0/src/cpp/yaml_loader.cpp +307 -0
  46. wa1kpcap-0.1.0/src/cpp/yaml_loader.h +138 -0
  47. wa1kpcap-0.1.0/test/dup.pcap +0 -0
  48. wa1kpcap-0.1.0/test/fin-rst.pcap +0 -0
  49. wa1kpcap-0.1.0/test/ip_seg.pcap +0 -0
  50. wa1kpcap-0.1.0/test/multi.pcap +0 -0
  51. wa1kpcap-0.1.0/test/single.pcap +0 -0
  52. wa1kpcap-0.1.0/test.csv +1 -0
  53. wa1kpcap-0.1.0/tests/conftest.py +78 -0
  54. wa1kpcap-0.1.0/tests/test_analyzer.py +298 -0
  55. wa1kpcap-0.1.0/tests/test_arp_icmp.py +457 -0
  56. wa1kpcap-0.1.0/tests/test_coverage_additional.py +226 -0
  57. wa1kpcap-0.1.0/tests/test_custom_protocol.py +393 -0
  58. wa1kpcap-0.1.0/tests/test_exporters.py +175 -0
  59. wa1kpcap-0.1.0/tests/test_exporters_coverage.py +328 -0
  60. wa1kpcap-0.1.0/tests/test_ext_protocol.py +182 -0
  61. wa1kpcap-0.1.0/tests/test_features.py +460 -0
  62. wa1kpcap-0.1.0/tests/test_filter.py +510 -0
  63. wa1kpcap-0.1.0/tests/test_flow.py +523 -0
  64. wa1kpcap-0.1.0/tests/test_flow_key.py +162 -0
  65. wa1kpcap-0.1.0/tests/test_link_layer_protocols.py +1037 -0
  66. wa1kpcap-0.1.0/tests/test_native_engine.py +934 -0
  67. wa1kpcap-0.1.0/tests/test_packet.py +381 -0
  68. wa1kpcap-0.1.0/tests/test_phase0_gaps.py +411 -0
  69. wa1kpcap-0.1.0/tests/test_protocol_parsing.py +631 -0
  70. wa1kpcap-0.1.0/tests/test_protocols.py +383 -0
  71. wa1kpcap-0.1.0/tests/test_reader.py +372 -0
  72. wa1kpcap-0.1.0/tests/test_tls_integration.py +245 -0
  73. wa1kpcap-0.1.0/wa1kpcap/__init__.py +83 -0
  74. wa1kpcap-0.1.0/wa1kpcap/core/__init__.py +60 -0
  75. wa1kpcap-0.1.0/wa1kpcap/core/analyzer.py +1460 -0
  76. wa1kpcap-0.1.0/wa1kpcap/core/filter.py +1040 -0
  77. wa1kpcap-0.1.0/wa1kpcap/core/flow.py +1266 -0
  78. wa1kpcap-0.1.0/wa1kpcap/core/packet.py +1196 -0
  79. wa1kpcap-0.1.0/wa1kpcap/core/reader.py +386 -0
  80. wa1kpcap-0.1.0/wa1kpcap/exporters.py +365 -0
  81. wa1kpcap-0.1.0/wa1kpcap/features/__init__.py +22 -0
  82. wa1kpcap-0.1.0/wa1kpcap/features/extractor.py +524 -0
  83. wa1kpcap-0.1.0/wa1kpcap/features/registry.py +719 -0
  84. wa1kpcap-0.1.0/wa1kpcap/native/__init__.py +16 -0
  85. wa1kpcap-0.1.0/wa1kpcap/native/converter.py +307 -0
  86. wa1kpcap-0.1.0/wa1kpcap/native/engine.py +100 -0
  87. wa1kpcap-0.1.0/wa1kpcap/native/protocols/bsd_loopback.yaml +11 -0
  88. wa1kpcap-0.1.0/wa1kpcap/native/protocols/dhcp.yaml +68 -0
  89. wa1kpcap-0.1.0/wa1kpcap/native/protocols/dhcpv6.yaml +12 -0
  90. wa1kpcap-0.1.0/wa1kpcap/native/protocols/dns.yaml +29 -0
  91. wa1kpcap-0.1.0/wa1kpcap/native/protocols/ethernet.yaml +24 -0
  92. wa1kpcap-0.1.0/wa1kpcap/native/protocols/gre.yaml +33 -0
  93. wa1kpcap-0.1.0/wa1kpcap/native/protocols/ipv4.yaml +72 -0
  94. wa1kpcap-0.1.0/wa1kpcap/native/protocols/ipv6.yaml +45 -0
  95. wa1kpcap-0.1.0/wa1kpcap/native/protocols/link_types.yaml +9 -0
  96. wa1kpcap-0.1.0/wa1kpcap/native/protocols/linux_sll.yaml +29 -0
  97. wa1kpcap-0.1.0/wa1kpcap/native/protocols/linux_sll2.yaml +37 -0
  98. wa1kpcap-0.1.0/wa1kpcap/native/protocols/mpls.yaml +14 -0
  99. wa1kpcap-0.1.0/wa1kpcap/native/protocols/nflog.yaml +5 -0
  100. wa1kpcap-0.1.0/wa1kpcap/native/protocols/raw_ip.yaml +16 -0
  101. wa1kpcap-0.1.0/wa1kpcap/native/protocols/tcp.yaml +75 -0
  102. wa1kpcap-0.1.0/wa1kpcap/native/protocols/tls_certificate.yaml +7 -0
  103. wa1kpcap-0.1.0/wa1kpcap/native/protocols/tls_client_hello.yaml +44 -0
  104. wa1kpcap-0.1.0/wa1kpcap/native/protocols/tls_ext_alpn.yaml +7 -0
  105. wa1kpcap-0.1.0/wa1kpcap/native/protocols/tls_ext_signature_algorithms.yaml +14 -0
  106. wa1kpcap-0.1.0/wa1kpcap/native/protocols/tls_ext_sni.yaml +14 -0
  107. wa1kpcap-0.1.0/wa1kpcap/native/protocols/tls_ext_supported_groups.yaml +14 -0
  108. wa1kpcap-0.1.0/wa1kpcap/native/protocols/tls_handshake.yaml +17 -0
  109. wa1kpcap-0.1.0/wa1kpcap/native/protocols/tls_record.yaml +23 -0
  110. wa1kpcap-0.1.0/wa1kpcap/native/protocols/tls_server_hello.yaml +36 -0
  111. wa1kpcap-0.1.0/wa1kpcap/native/protocols/tls_stream.yaml +6 -0
  112. wa1kpcap-0.1.0/wa1kpcap/native/protocols/udp.yaml +28 -0
  113. wa1kpcap-0.1.0/wa1kpcap/native/protocols/vlan.yaml +24 -0
  114. wa1kpcap-0.1.0/wa1kpcap/native/protocols/vxlan.yaml +21 -0
  115. wa1kpcap-0.1.0/wa1kpcap/protocols/__init__.py +73 -0
  116. wa1kpcap-0.1.0/wa1kpcap/protocols/application.py +530 -0
  117. wa1kpcap-0.1.0/wa1kpcap/protocols/base.py +129 -0
  118. wa1kpcap-0.1.0/wa1kpcap/protocols/link.py +219 -0
  119. wa1kpcap-0.1.0/wa1kpcap/protocols/network.py +181 -0
  120. wa1kpcap-0.1.0/wa1kpcap/protocols/registry.py +226 -0
  121. wa1kpcap-0.1.0/wa1kpcap/protocols/transport.py +175 -0
  122. wa1kpcap-0.1.0/wa1kpcap/reassembly/__init__.py +31 -0
  123. wa1kpcap-0.1.0/wa1kpcap/reassembly/ip_fragment.py +269 -0
  124. wa1kpcap-0.1.0/wa1kpcap/reassembly/tcp_stream.py +345 -0
  125. wa1kpcap-0.1.0/wa1kpcap/reassembly/tls_record.py +320 -0
@@ -0,0 +1,90 @@
1
+ name: Build & Publish
2
+
3
+ on:
4
+ push:
5
+ tags: ["v*"]
6
+ workflow_dispatch:
7
+
8
+ jobs:
9
+ build-sdist:
10
+ name: Build sdist
11
+ runs-on: ubuntu-latest
12
+ steps:
13
+ - uses: actions/checkout@v4
14
+
15
+ - name: Build sdist
16
+ run: pipx run build --sdist
17
+
18
+ - uses: actions/upload-artifact@v4
19
+ with:
20
+ name: sdist
21
+ path: dist/*.tar.gz
22
+
23
+ build-wheels:
24
+ name: Build wheels (${{ matrix.os }})
25
+ runs-on: ${{ matrix.os }}
26
+ strategy:
27
+ fail-fast: false
28
+ matrix:
29
+ os: [ubuntu-latest, windows-latest, macos-latest]
30
+
31
+ steps:
32
+ - uses: actions/checkout@v4
33
+
34
+ - name: Build wheels
35
+ uses: pypa/cibuildwheel@v2.21
36
+ env:
37
+ CIBW_BUILD: "cp310-* cp311-* cp312-* cp313-*"
38
+ CIBW_SKIP: "*-musllinux_i686 *-manylinux_i686 *-win32"
39
+ CIBW_ARCHS_LINUX: "x86_64"
40
+ CIBW_ARCHS_MACOS: "x86_64 arm64"
41
+ CIBW_ARCHS_WINDOWS: "AMD64"
42
+ CIBW_BUILD_VERBOSITY: 1
43
+
44
+ - uses: actions/upload-artifact@v4
45
+ with:
46
+ name: wheels-${{ matrix.os }}
47
+ path: wheelhouse/*.whl
48
+
49
+ publish:
50
+ name: Publish to PyPI
51
+ needs: [build-sdist, build-wheels]
52
+ runs-on: ubuntu-latest
53
+ if: startsWith(github.ref, 'refs/tags/v')
54
+ permissions:
55
+ id-token: write
56
+
57
+ steps:
58
+ - uses: actions/download-artifact@v4
59
+ with:
60
+ path: dist
61
+ merge-multiple: true
62
+
63
+ - name: Publish to PyPI
64
+ uses: pypa/gh-action-pypi-publish@release/v1
65
+
66
+ github-release:
67
+ name: Create GitHub Release
68
+ needs: [publish]
69
+ runs-on: ubuntu-latest
70
+ if: startsWith(github.ref, 'refs/tags/v')
71
+ permissions:
72
+ contents: write
73
+
74
+ steps:
75
+ - uses: actions/checkout@v4
76
+
77
+ - uses: actions/download-artifact@v4
78
+ with:
79
+ path: dist
80
+ merge-multiple: true
81
+
82
+ - name: Extract latest release notes
83
+ run: |
84
+ awk '/^## v/{if(found) exit; found=1} found' CHANGELOG.md > RELEASE_NOTES.tmp
85
+
86
+ - name: Create Release
87
+ uses: softprops/action-gh-release@v2
88
+ with:
89
+ files: dist/*
90
+ body_path: RELEASE_NOTES.tmp
@@ -0,0 +1,49 @@
1
+ name: Tests
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ paths-ignore:
7
+ - '.github/workflows/**'
8
+ - '*.md'
9
+ - 'LICENSE'
10
+ - 'MANIFEST.in'
11
+ - 'examples/**'
12
+ - 'skills/**'
13
+ - 'docs/**'
14
+ pull_request:
15
+ branches: [main]
16
+ paths-ignore:
17
+ - '.github/workflows/**'
18
+ - '*.md'
19
+ - 'LICENSE'
20
+ - 'MANIFEST.in'
21
+ - 'examples/**'
22
+ - 'skills/**'
23
+ - 'docs/**'
24
+
25
+ jobs:
26
+ test:
27
+ runs-on: ${{ matrix.os }}
28
+ strategy:
29
+ fail-fast: false
30
+ matrix:
31
+ os: [ubuntu-latest, windows-latest, macos-latest]
32
+ python-version: ["3.10", "3.11", "3.12", "3.13"]
33
+
34
+ steps:
35
+ - uses: actions/checkout@v4
36
+
37
+ - name: Set up Python ${{ matrix.python-version }}
38
+ uses: actions/setup-python@v5
39
+ with:
40
+ python-version: ${{ matrix.python-version }}
41
+
42
+ - name: Install build dependencies
43
+ run: pip install scikit-build-core pybind11 cmake ninja
44
+
45
+ - name: Install package with dev dependencies
46
+ run: pip install -e ".[dev,dpkt]"
47
+
48
+ - name: Run tests
49
+ run: python -m pytest tests/ -x -q
@@ -0,0 +1,82 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ build/
8
+ develop-eggs/
9
+ dist/
10
+ downloads/
11
+ eggs/
12
+ .eggs/
13
+ lib/
14
+ lib64/
15
+ parts/
16
+ sdist/
17
+ var/
18
+ wheels/
19
+ *.egg-info/
20
+ .installed.cfg
21
+ *.egg
22
+
23
+ # Virtual environments
24
+ .env
25
+ .venv
26
+ env/
27
+ venv/
28
+ ENV/
29
+
30
+ # IDE
31
+ .idea/
32
+ .vscode/
33
+ *.swp
34
+ *.swo
35
+
36
+ # Pytest
37
+ .pytest_cache/
38
+ .coverage
39
+ htmlcov/
40
+
41
+ # Native build artifacts
42
+ *.pyd
43
+ *.dll
44
+ *.exe
45
+ *.obj
46
+ *.o
47
+ *.a
48
+ *.lib
49
+
50
+ # CMake
51
+ CMakeCache.txt
52
+ CMakeFiles/
53
+ cmake_install.cmake
54
+ Makefile
55
+
56
+ # Misc
57
+ *.log
58
+ *.tmp
59
+ .DS_Store
60
+ Thumbs.db
61
+ nul
62
+
63
+ # Data files
64
+ *.pcap
65
+ *.pcapng
66
+ *.npz
67
+ !test/*.pcap
68
+
69
+ # Scratch scripts & docs
70
+ extract_*.py
71
+ benchmark*
72
+ docs/*
73
+ !docs/README.md
74
+ !docs/README_CN.md
75
+
76
+ # Planning files
77
+ task_plan.md
78
+ findings.md
79
+ progress.md
80
+
81
+ # Internal-only skills (keep locally, don't commit)
82
+ .claude/
@@ -0,0 +1,31 @@
1
+ # Changelog
2
+
3
+ ## v0.1.0 (2026-02-20)
4
+
5
+ Initial release.
6
+
7
+ ### Features
8
+
9
+ - Dual-engine architecture: native C++ engine (default) and dpkt fallback
10
+ - Flow-level feature extraction with signed directional lengths
11
+ - 8 sequence features per flow: packet_lengths, ip_lengths, trans_lengths, app_lengths, timestamps, iats, tcp_flags, tcp_window_sizes
12
+ - Statistical aggregation: mean, std, var, min, max, range, median, skew, kurt, cv, plus up/down directional breakdowns
13
+ - BPF filter with protocol-aware keywords (dhcp, dhcpv6, vlan, gre, vxlan, mpls)
14
+ - Application layer parsing control: full / port_only / none
15
+ - IP fragment, TCP stream, and TLS record reassembly
16
+ - Export to pandas DataFrame, CSV, JSON
17
+ - Custom incremental feature registration via BaseIncrementalFeature
18
+ - YAML-based protocol extension for the native engine
19
+
20
+ ### Supported Protocols
21
+
22
+ - Link: Ethernet, VLAN (802.1Q), Linux SLL/SLL2, Raw IP, BSD Loopback, NFLOG
23
+ - Network: IPv4, IPv6, ARP, ICMP, ICMPv6
24
+ - Tunnel: GRE, VXLAN, MPLS
25
+ - Transport: TCP, UDP
26
+ - Application: TLS (SNI/ALPN/certs), DNS, HTTP, DHCP, DHCPv6
27
+
28
+ ### Supported Platforms
29
+
30
+ - Python 3.10 - 3.13
31
+ - Linux (x86_64, aarch64), macOS (x86_64, arm64), Windows (AMD64)
@@ -0,0 +1,175 @@
1
+ # CLAUDE.md
2
+
3
+ This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4
+
5
+ ## Environment
6
+
7
+ - Conda environment: `web` (Python 3.10).
8
+ - Python executable: `D:/miniconda3/envs/web/python.exe`
9
+ - Platform: Windows 11. Claude Code uses Git Bash (Unix syntax). All shell commands in this file use bash syntax.
10
+ - In Git Bash, `conda activate` is typically unavailable. Use `python`/`pip` directly (they should already point to the conda env). If `python` is not in PATH or points to the wrong env, fall back to the full path: `"D:/miniconda3/envs/web/python.exe"` and `"D:/miniconda3/envs/web/python.exe" -m pip`.
11
+
12
+ ## Language
13
+
14
+ - Respond in Chinese (中文) for explanatory, discussion, or conversational replies.
15
+ - Internal thinking, code, comments, and commit messages can remain in English.
16
+
17
+ ## Build & Install
18
+
19
+ The project uses scikit-build-core with CMake for the optional C++ native engine.
20
+
21
+ ```bash
22
+ # Install Python package (dpkt engine only)
23
+ pip install -e .
24
+
25
+ # Install with native C++ engine
26
+ rm -rf build/cp310-cp310-win_amd64/*
27
+ pip install ".[native]" --force-reinstall --no-deps --no-cache-dir
28
+
29
+ # After native build, copy .pyd into source tree (editable install loads from source tree, not site-packages)
30
+ cp "/d/miniconda3/envs/web/Lib/site-packages/wa1kpcap/_wa1kpcap_native.cp310-win_amd64.pyd" "/d/MyProgram/wa1kpcap1/wa1kpcap/"
31
+ ```
32
+
33
+ The C++ build requires CMake 3.15+, C++17, and fetches yaml-cpp 0.8.0 via FetchContent. pybind11 provides the Python bindings.
34
+
35
+ ### MSVC Build Quirks
36
+
37
+ - `NOMINMAX` must be defined before any Windows headers to prevent `min`/`max` macro conflicts with STL and pybind11. `bindings.cpp` also `#undef`s leaked macros and provides `dabs()`/`dmax()` replacements.
38
+ - Use `Py_ssize_t` instead of `ssize_t` (not available on MSVC).
39
+ - `src/cpp/CMakeLists.txt` sets `CMAKE_POLICY_VERSION_MINIMUM 3.5` to allow yaml-cpp 0.8.0's old `cmake_minimum_required` to work under CMake 4.0+.
40
+
41
+ ## Tests
42
+
43
+ ```bash
44
+ # Run all tests
45
+ python -m pytest tests/ -x -q
46
+
47
+ # Run a single test file
48
+ python -m pytest tests/test_flow.py -x -q
49
+
50
+ # Run a specific test
51
+ python -m pytest tests/test_flow.py::TestFlowManager::test_add_packet -x -q
52
+
53
+ # Benchmark dpkt vs native vs flowcontainer
54
+ python benchmark.py # full: consistency check + speed benchmark + report
55
+ python benchmark.py consistency # consistency check only (dpkt vs native vs flowcontainer on test/multi.pcap)
56
+ python benchmark.py speed # speed benchmark only (per-file dpkt vs native vs flowcontainer on datasets)
57
+ python benchmark.py lite-speed # quick dpkt vs native speed comparison on a few specific pcap files
58
+ ```
59
+
60
+ Coverage is 68% (4958 statements, 1575 missed). There are 331 tests across 18 test files (329 passed, 2 skipped).
61
+
62
+ `benchmark.py` compares wa1kpcap's dpkt engine, native C++ engine, and flowcontainer. It has four modes:
63
+ - `all` (default): runs both consistency check and speed benchmark, writes a markdown report to `benchmark_report.md`.
64
+ - `consistency`: compares flow extraction results (5-tuple matching, IAT comparison) between dpkt, native, and flowcontainer on `test/multi.pcap`.
65
+ - `speed`: benchmarks per-file throughput (time, flows, MB/s, speedup) across datasets configured in `DATASETS`.
66
+ - `lite-speed`: quick dpkt vs native comparison on a few hardcoded pcap files (no report file).
67
+
68
+ ## Architecture
69
+
70
+ ### Dual Engine Design
71
+
72
+ The library has two independent parsing engines selected via `Wa1kPcap(engine="dpkt"|"native")`:
73
+
74
+ - **dpkt engine** (default): Uses the dpkt library for protocol parsing. Code path: `analyzer.py:_process_reader()` → `_parse_protocols()` using handlers in `wa1kpcap/protocols/`.
75
+ - **native engine**: C++ pybind11 module (`_wa1kpcap_native`) driven by YAML protocol configs. Code path: `analyzer.py:_process_native()` → `NativeEngine.read_and_parse()` → C++ `NativeParser.parse_to_dataclass()` which constructs Python dataclasses directly in C++ (bypasses dict + `converter.py`).
76
+
77
+ Both engines feed into the same Python flow management pipeline: `FlowManager` groups packets into bidirectional `Flow` objects, `FeatureExtractor` computes sequence/statistical features, and exporters produce DataFrame/CSV/JSON output.
78
+
79
+ ### C++ Native Engine (`src/cpp/`)
80
+
81
+ The C++ engine is YAML-configuration-driven with 10 parsing primitives: `fixed`, `bitfield`, `length_prefixed`, `computed`, `tlv`, `counted_list`, `rest`, `hardcoded`, `prefixed_list`, `repeat`. Protocol definitions live in `wa1kpcap/native/protocols/*.yaml`.
82
+
83
+ Key mechanisms in `protocol_engine.cpp`:
84
+ - `header_size_field`: After parsing fixed fields, adjusts `bytes_consumed` to the computed header size (handles IP/TCP options).
85
+ - `total_length_field`: Bounds `remaining` bytes to IP total_length, excluding Ethernet padding.
86
+ - Computed fields (type `COMPUTED`) must evaluate even when `offset >= len` — they consume 0 bytes but produce values like `flags` and `header_length` that downstream logic depends on.
87
+ - `parse_packet()` chains layers via `next_protocol` mappings until no more protocols match or data runs out.
88
+ - `prefixed_list` primitive: length-prefixed item list with optional TLV dispatch. Two modes: Mode A (typed items) reads `[total_len][type][len][data]...` and dispatches sub-protocols via `type_mapping`; Mode B (simple) reads `[total_len][item_len][data]...` with `item_format`. Sub-protocol fields are merged into the parent FieldMap with a prefix (e.g., `tls_ext_sni.server_name`). Used by `tls_client_hello.yaml` and `tls_server_hello.yaml` to parse TLS extensions via YAML instead of hardcoded C++.
89
+ - TLS is NOT chained from TCP via `next_protocol` — TCP's YAML has no next_protocol to TLS. Instead, TLS is parsed via a separate reassembly path: Python buffers TCP payloads, extracts complete TLS records, then calls C++ `NativeParser.parse_tls_record()` which uses `parse_from_protocol_struct("tls_record", ...)` to parse starting from the TLS layer.
90
+
91
+ #### Dispatch Tables
92
+
93
+ The engine uses `unordered_map` dispatch tables (populated in the `ProtocolEngine` constructor) instead of if-else chains:
94
+
95
+ - `fast_dispatch_` (`std::unordered_map<std::string, FastParseFn>`): maps protocol name → fast-path parser. Unified signature: `FastResult(const uint8_t* buf, size_t len, size_t remaining, NativeParsedPacket& pkt)`. Only Type A protocols register here.
96
+ - `fill_dispatch_` (`std::unordered_map<std::string, std::function<void(SlowFillContext&)>>`): maps protocol name → fill function. Both Type A and Type B protocols register here. `SlowFillContext` carries `pkt`, `fields`, `cur`, `bytes_consumed`, `remaining`, `has_tls`, `tls_layers`, `proto_name`.
97
+
98
+ New built-in protocols register by adding lambdas in the constructor. Some protocols have special fill logic (TCP/UDP compute `app_len`, TLS sub-layers store into `tls_layers` for deferred processing).
99
+
100
+ #### Two Built-in Protocol Subtypes
101
+
102
+ - **Type A: Fast-Path** — has both `fast_parse_xxx()` (raw byte parsing, registered in `fast_dispatch_`) and `fill_xxx()` (registered in `fill_dispatch_`). For simple fixed-layout wire formats. Current: Ethernet, IPv4, IPv6, TCP, UDP, ARP, ICMP, ICMPv6.
103
+ - **Type B: Fill-Only** — has only `fill_xxx()` (registered in `fill_dispatch_`). YAML engine handles all parsing; fill copies fields into the C++ struct. For complex variable formats. Current: DNS, TLS series (tls_stream, tls_record, tls_handshake, tls_client_hello, tls_server_hello, tls_certificate).
104
+
105
+ Rule of thumb: if you can parse with pointer arithmetic in < 50 lines of C++, use Type A. If parsing needs TLV, compression, counted lists — use Type B.
106
+
107
+ #### Profiling Infrastructure
108
+
109
+ Built-in timing instrumentation controlled by a global flag:
110
+
111
+ - `g_profiling_enabled` (bool): global toggle, default `false`.
112
+ - `g_prof` (`ProfilingStats`): atomic counters for `total_ns`, `parse_layer_ns`, `fill_struct_ns`, `next_proto_ns`, `fieldmap_insert_ns`, `total_packets`, `total_layers`, plus per-primitive counters (`fixed_ns`/`fixed_count`, `bitfield_ns`/`bitfield_count`, etc.).
113
+ - `ScopedTimer`: RAII timer that accumulates nanoseconds into a target `std::atomic<uint64_t>` when `g_profiling_enabled` is true.
114
+ - Python API (exposed in `bindings.cpp`): `profiling_enable()`, `profiling_disable()`, `profiling_reset()`, `profiling_get_stats()` → returns dict with all counters.
115
+
116
+ The fast path (`parse_to_dataclass` in `bindings.cpp`) parses to a C++ `NativeParsedPacket` struct, then constructs Python dataclasses directly with positional args (cached class references, pre-cached constants like `py::none()` and `py::bytes("")`). The legacy path (`parse_packet` → `py::dict` → `converter.py`) is only used for fallback BPF app-layer filtering.
117
+
118
+ `NativeParsedPacket` (`parsed_packet.h`) embeds all sub-structs (NativeIPInfo, NativeTCPInfo, etc.) directly — no heap allocation. Presence flags (`has_eth`, `has_ip`, etc.) replace nullptr checks. pybind11 bindings return `py::none()` when the flag is false. Unknown protocols parsed by YAML are stored in `extra_layers` (a `std::map<std::string, FieldMap>`), converted to Python dicts in `build_dataclass_from_struct`, and passed to `ParsedPacket.__init__` which wraps them in `ProtocolInfo` instances via `ProtocolRegistry`.
119
+
120
+ ### ProtocolInfo & Extensibility (`wa1kpcap/core/packet.py`)
121
+
122
+ Protocol layer data uses a two-tier class hierarchy under a common `_ProtocolInfoBase`:
123
+
124
+ - **Built-in protocols** (`EthernetInfo`, `IPInfo`, `TCPInfo`, `UDPInfo`, `TLSInfo`, `DNSInfo`, `HTTPInfo`, etc.) inherit from `_SlottedInfoBase(_ProtocolInfoBase)` and store fields as direct `__slots__` attributes for performance (~40% faster construction than dict-based). Each class defines `__slots__`, `_SLOT_NAMES`, and `_SLOT_DEFAULTS`. The `_fields` property returns a dict view of all slots for compatibility.
125
+ - **Custom/user protocols** inherit from `ProtocolInfo(_ProtocolInfoBase)` and use a `_fields` dict as source of truth, with typed property accessors.
126
+
127
+ `ParsedPacket.layers` is a `dict[str, _ProtocolInfoBase]` keyed by protocol name; legacy properties like `pkt.ip`, `pkt.tls` are aliases into this dict. The `isinstance` check in `_aggregate_flow_info()` uses `_ProtocolInfoBase` (the common ancestor).
128
+
129
+ To add a new protocol without modifying C++:
130
+ 1. Create `<name>.yaml` in `wa1kpcap/native/protocols/` (or a custom directory).
131
+ 2. Write a `ProtocolInfo` subclass with typed properties and a `merge()` method.
132
+ 3. Register it: `ProtocolRegistry.get_instance().register('<name>', MyProtoInfo, yaml_path="/path/to/myproto.yaml", routing={"udp": {5000: "myproto"}})`.
133
+ 4. `NativeEngine` auto-loads `yaml_path` files and injects `routing` mappings at init time — no need to modify built-in YAML files.
134
+
135
+ All fast-path parsers (ethernet, ipv4, ipv6, tcp, udp, vlan, sll, sll2) have YAML fallback: when the hardcoded switch doesn't match, they query `yaml_next_protocol_lookup()` against the YAML `next_protocol.mapping`. This means injected routing works for both fast-path and slow-path protocols. C++ also exposes `NativeParser.load_extra_file()` and `NativeParser.add_protocol_routing()` for direct use.
136
+
137
+ To add a new built-in protocol (with C++ fast path):
138
+ 1. Follow the steps in `docs/add-builtin-protocol-guide.md` or use `/add-builtin-protocol`.
139
+ 2. The Python Info class must inherit `_SlottedInfoBase` with `__slots__` direct attributes (not `ProtocolInfo` with `_fields` dict).
140
+
141
+ Known protocols use dispatch table lookups (`fast_dispatch_` / `fill_dispatch_`) for optimized C++ struct fill. Unknown protocols go through `extra_layers` → `ProtocolRegistry` lookup → `ProtocolInfo` construction. If no class is registered, a generic `ProtocolInfo(fields=dict)` is used as fallback.
142
+
143
+ Flow-level aggregation in `analyzer.py:_aggregate_flow_info()` iterates `pkt.layers` generically: first packet's layer is `copy()`'d, subsequent packets' layers are `merge()`'d. The `copy()` is a selective shallow copy (one-level `list()`/`dict()` for mutables, direct reference for scalars) — not `deepcopy`.
144
+
145
+ ### Flow Management (`wa1kpcap/core/flow.py`)
146
+
147
+ - `FlowKey`: 5-tuple (src_ip, dst_ip, src_port, dst_port, protocol), normalized so the same pair always maps to the same flow regardless of direction.
148
+ - `Flow`: Bidirectional flow with TCP state machine (SYN_SENT → ESTABLISHED → FIN_WAIT → CLOSED etc.). First packet determines "up" direction.
149
+ - Signed packet lengths: positive = client-to-server (up), negative = server-to-client (down).
150
+ - TCP retransmission detection (`_check_retransmission` in analyzer.py) uses per-direction sequence number tracking.
151
+
152
+ ### Reassembly Pipeline
153
+
154
+ `IPFragmentReassembler` → `TCPStreamReassembler` → `TLSRecordReassembler`. For the native engine, `FlowBuffer` bridges Python TCP reassembly with C++ application-layer parsing.
155
+
156
+ ### Feature Extraction (`wa1kpcap/features/`)
157
+
158
+ Sequence features: `packet_lengths`, `ip_lengths`, `trans_lengths`, `app_lengths`, `timestamps`, `iats`, `tcp_flags`, `tcp_window_sizes`. Statistical features computed from sequences: mean, std, var, min, max, range, median, skew, kurtosis, cv — with directional (up/down) variants.
159
+
160
+ `compute_array_stats` in `bindings.cpp` provides a C++ single-pass implementation (O(n) median via `nth_element`) that `_compute_array_stats()` in `extractor.py` calls when the native module is available, with a pure-Python fallback.
161
+
162
+ ## YAML Protocol Configs
163
+
164
+ Located in `wa1kpcap/native/protocols/`. When adding a new protocol:
165
+ 1. Create `<name>.yaml` with `name`, `fields` (using the 10 primitives), and optionally `next_protocol`, `header_size_field`, `total_length_field`.
166
+ 2. Add the DLT or next_protocol mapping that routes to it.
167
+ 3. If the protocol has variable-length headers, declare `header_size_field` pointing to a computed field.
168
+ 4. If the protocol carries a total length (like IPv4/IPv6), declare `total_length_field` to prevent Ethernet padding from inflating payload sizes.
169
+
170
+ ## Conventions
171
+
172
+ - All protocol parsing in the dpkt path goes through handler classes in `wa1kpcap/protocols/` registered via `ProtocolHandlerRegistry`.
173
+ - `ParsedPacket` is the universal packet representation shared by both engines.
174
+ - The `wa1kpcap/__init__.py` re-exports all public API symbols — new public classes should be added to `__all__` there.
175
+ - Test pcap fixtures are referenced from `tests/conftest.py`.
@@ -0,0 +1,12 @@
1
+ cmake_minimum_required(VERSION 3.15)
2
+ project(wa1kpcap_native LANGUAGES CXX)
3
+
4
+ set(CMAKE_CXX_STANDARD 17)
5
+ set(CMAKE_CXX_STANDARD_REQUIRED ON)
6
+ set(CMAKE_POSITION_INDEPENDENT_CODE ON)
7
+
8
+ option(BUILD_NATIVE "Build native C++ engine" ON)
9
+
10
+ if(BUILD_NATIVE)
11
+ add_subdirectory(src/cpp)
12
+ endif()
wa1kpcap-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ljs_2002
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,12 @@
1
+ include LICENSE
2
+ include README.md
3
+ include CMakeLists.txt
4
+
5
+ # C++ source
6
+ recursive-include src/cpp *.h *.hpp *.cpp *.c
7
+
8
+ # YAML protocol definitions
9
+ recursive-include wa1kpcap *.yaml
10
+
11
+ # pybind11 build support
12
+ include pyproject.toml
@@ -0,0 +1,105 @@
1
+ Metadata-Version: 2.4
2
+ Name: wa1kpcap
3
+ Version: 0.1.0
4
+ Summary: Dual-engine PCAP analysis library for flow-level feature extraction and protocol parsing
5
+ Keywords: pcap,network,traffic,flow,packet,protocol,tls,dns,feature-extraction,nids
6
+ Author-Email: 1in_js <ljs_2002@163.com>
7
+ License-Expression: MIT
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Topic :: System :: Networking :: Monitoring
17
+ Classifier: Topic :: Scientific/Engineering
18
+ Project-URL: Homepage, https://github.com/ljs-2002/wa1kpcap
19
+ Project-URL: Repository, https://github.com/ljs-2002/wa1kpcap
20
+ Project-URL: Issues, https://github.com/ljs-2002/wa1kpcap/issues
21
+ Requires-Python: >=3.10
22
+ Requires-Dist: PyYAML>=6.0
23
+ Requires-Dist: numpy>=1.23
24
+ Provides-Extra: dpkt
25
+ Requires-Dist: dpkt>=1.9; extra == "dpkt"
26
+ Provides-Extra: export
27
+ Requires-Dist: pandas>=1.5; extra == "export"
28
+ Provides-Extra: crypto
29
+ Requires-Dist: cryptography>=41.0; extra == "crypto"
30
+ Provides-Extra: dev
31
+ Requires-Dist: pytest>=7.0; extra == "dev"
32
+ Requires-Dist: scapy>=2.5; extra == "dev"
33
+ Requires-Dist: pandas>=1.5; extra == "dev"
34
+ Requires-Dist: cryptography>=41.0; extra == "dev"
35
+ Description-Content-Type: text/markdown
36
+
37
+ # wa1kpcap
38
+
39
+ [中文文档](README_CN.md)
40
+
41
+ Dual-engine PCAP analysis library for Python. Extracts flow-level features and protocol fields from network traffic captures using a native C++ engine (default) or dpkt as fallback.
42
+
43
+ ## Installation
44
+
45
+ ```bash
46
+ pip install wa1kpcap
47
+ ```
48
+
49
+ Optional dependencies:
50
+
51
+ ```bash
52
+ pip install wa1kpcap[dpkt] # dpkt engine support
53
+ pip install wa1kpcap[export] # pandas DataFrame export
54
+ pip install wa1kpcap[crypto] # TLS certificate parsing
55
+ pip install wa1kpcap[dev] # development (pytest, scapy, etc.)
56
+ ```
57
+
58
+ ## Quick Start
59
+
60
+ ```python
61
+ from wa1kpcap import Wa1kPcap
62
+
63
+ analyzer = Wa1kPcap()
64
+ flows = analyzer.analyze_file('traffic.pcap')
65
+
66
+ for flow in flows:
67
+ print(f"{flow.key} packets={flow.packet_count} duration={flow.duration:.3f}s")
68
+ ```
69
+
70
+ ## Supported Protocols
71
+
72
+ | Layer | Protocols |
73
+ |-------|-----------|
74
+ | Link | Ethernet, VLAN (802.1Q), Linux SLL/SLL2, Raw IP, BSD Loopback, NFLOG |
75
+ | Network | IPv4, IPv6, ARP, ICMP, ICMPv6 |
76
+ | Tunnel | GRE, VXLAN, MPLS |
77
+ | Transport | TCP, UDP |
78
+ | Application | TLS (SNI/ALPN/certs), DNS, HTTP, DHCP, DHCPv6 |
79
+
80
+ All protocols have C++ fast-path implementations. Tunnel protocols (GRE, VXLAN, MPLS) support recursive inner-packet dispatch.
81
+
82
+ ## Features
83
+
84
+ - Dual engine: native C++ (default) or dpkt fallback
85
+ - Flow-level feature extraction with signed directional lengths
86
+ - 8 sequence features per flow: packet_lengths, ip_lengths, trans_lengths, app_lengths, timestamps, iats, tcp_flags, tcp_window_sizes
87
+ - Statistical aggregation: mean, std, var, min, max, range, median, skew, kurt, cv, plus directional breakdowns
88
+ - BPF filter with protocol-aware keywords (dhcp, dhcpv6, vlan, gre, vxlan, mpls)
89
+ - Application layer parsing control: full / port_only / none
90
+ - IP/TCP/TLS reassembly
91
+ - Export to DataFrame, CSV, JSON
92
+ - Custom incremental feature registration
93
+ - YAML-based protocol extension
94
+
95
+ ## Documentation
96
+
97
+ For detailed usage, API reference, and examples, see [docs/README.md](docs/README.md).
98
+
99
+ ## License
100
+
101
+ MIT License
102
+
103
+ ## Author
104
+
105
+ 1in_js
@@ -0,0 +1,69 @@
1
+ # wa1kpcap
2
+
3
+ [中文文档](README_CN.md)
4
+
5
+ Dual-engine PCAP analysis library for Python. Extracts flow-level features and protocol fields from network traffic captures using a native C++ engine (default) or dpkt as fallback.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ pip install wa1kpcap
11
+ ```
12
+
13
+ Optional dependencies:
14
+
15
+ ```bash
16
+ pip install wa1kpcap[dpkt] # dpkt engine support
17
+ pip install wa1kpcap[export] # pandas DataFrame export
18
+ pip install wa1kpcap[crypto] # TLS certificate parsing
19
+ pip install wa1kpcap[dev] # development (pytest, scapy, etc.)
20
+ ```
21
+
22
+ ## Quick Start
23
+
24
+ ```python
25
+ from wa1kpcap import Wa1kPcap
26
+
27
+ analyzer = Wa1kPcap()
28
+ flows = analyzer.analyze_file('traffic.pcap')
29
+
30
+ for flow in flows:
31
+ print(f"{flow.key} packets={flow.packet_count} duration={flow.duration:.3f}s")
32
+ ```
33
+
34
+ ## Supported Protocols
35
+
36
+ | Layer | Protocols |
37
+ |-------|-----------|
38
+ | Link | Ethernet, VLAN (802.1Q), Linux SLL/SLL2, Raw IP, BSD Loopback, NFLOG |
39
+ | Network | IPv4, IPv6, ARP, ICMP, ICMPv6 |
40
+ | Tunnel | GRE, VXLAN, MPLS |
41
+ | Transport | TCP, UDP |
42
+ | Application | TLS (SNI/ALPN/certs), DNS, HTTP, DHCP, DHCPv6 |
43
+
44
+ All protocols have C++ fast-path implementations. Tunnel protocols (GRE, VXLAN, MPLS) support recursive inner-packet dispatch.
45
+
46
+ ## Features
47
+
48
+ - Dual engine: native C++ (default) or dpkt fallback
49
+ - Flow-level feature extraction with signed directional lengths
50
+ - 8 sequence features per flow: packet_lengths, ip_lengths, trans_lengths, app_lengths, timestamps, iats, tcp_flags, tcp_window_sizes
51
+ - Statistical aggregation: mean, std, var, min, max, range, median, skew, kurt, cv, plus directional breakdowns
52
+ - BPF filter with protocol-aware keywords (dhcp, dhcpv6, vlan, gre, vxlan, mpls)
53
+ - Application layer parsing control: full / port_only / none
54
+ - IP/TCP/TLS reassembly
55
+ - Export to DataFrame, CSV, JSON
56
+ - Custom incremental feature registration
57
+ - YAML-based protocol extension
58
+
59
+ ## Documentation
60
+
61
+ For detailed usage, API reference, and examples, see [docs/README.md](docs/README.md).
62
+
63
+ ## License
64
+
65
+ MIT License
66
+
67
+ ## Author
68
+
69
+ 1in_js