meshcoredecoder 0.1.0__py3-none-any.whl
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.
- cli.py +249 -0
- index.py +66 -0
- meshcoredecoder/__init__.py +8 -0
- meshcoredecoder/crypto/__init__.py +6 -0
- meshcoredecoder/crypto/channel_crypto.py +113 -0
- meshcoredecoder/crypto/ed25519_verifier.py +136 -0
- meshcoredecoder/crypto/key_manager.py +71 -0
- meshcoredecoder/decoder/__init__.py +26 -0
- meshcoredecoder/decoder/packet_decoder.py +500 -0
- meshcoredecoder/decoder/payload_decoders/__init__.py +22 -0
- meshcoredecoder/decoder/payload_decoders/ack.py +91 -0
- meshcoredecoder/decoder/payload_decoders/advert.py +281 -0
- meshcoredecoder/decoder/payload_decoders/anon_request.py +137 -0
- meshcoredecoder/decoder/payload_decoders/group_text.py +130 -0
- meshcoredecoder/decoder/payload_decoders/path.py +89 -0
- meshcoredecoder/decoder/payload_decoders/request.py +143 -0
- meshcoredecoder/decoder/payload_decoders/response.py +133 -0
- meshcoredecoder/decoder/payload_decoders/text_message.py +70 -0
- meshcoredecoder/decoder/payload_decoders/trace.py +156 -0
- meshcoredecoder/types/__init__.py +15 -0
- meshcoredecoder/types/crypto.py +67 -0
- meshcoredecoder/types/enums.py +60 -0
- meshcoredecoder/types/packet.py +139 -0
- meshcoredecoder/types/payloads.py +244 -0
- meshcoredecoder/utils/__init__.py +18 -0
- meshcoredecoder/utils/auth_token.py +234 -0
- meshcoredecoder/utils/enum_names.py +58 -0
- meshcoredecoder/utils/hex.py +38 -0
- meshcoredecoder-0.1.0.dist-info/METADATA +332 -0
- meshcoredecoder-0.1.0.dist-info/RECORD +34 -0
- meshcoredecoder-0.1.0.dist-info/WHEEL +5 -0
- meshcoredecoder-0.1.0.dist-info/entry_points.txt +2 -0
- meshcoredecoder-0.1.0.dist-info/licenses/LICENSE +21 -0
- meshcoredecoder-0.1.0.dist-info/top_level.txt +3 -0
cli.py
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
MeshCore Decoder CLI
|
|
4
|
+
Copyright (c) 2025 Michael Hart: https://github.com/michaelhart/meshcore-decoder
|
|
5
|
+
MIT License
|
|
6
|
+
|
|
7
|
+
Complete CLI implementation for decoding MeshCore packets
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import sys
|
|
11
|
+
import json
|
|
12
|
+
import asyncio
|
|
13
|
+
from typing import List, Optional
|
|
14
|
+
from meshcoredecoder import MeshCoreDecoder
|
|
15
|
+
from meshcoredecoder.crypto import MeshCoreKeyStore
|
|
16
|
+
from meshcoredecoder.types.crypto import DecryptionOptions
|
|
17
|
+
from meshcoredecoder.utils.enum_names import get_route_type_name, get_payload_type_name, get_device_role_name
|
|
18
|
+
from meshcoredecoder.types.enums import PayloadType
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def print_formatted_packet(packet, keys: Optional[List[str]] = None):
|
|
22
|
+
"""Print formatted packet information"""
|
|
23
|
+
print('\n=== MeshCore Packet Analysis ===\n')
|
|
24
|
+
|
|
25
|
+
if not packet.is_valid:
|
|
26
|
+
print('❌ Invalid Packet')
|
|
27
|
+
if packet.errors:
|
|
28
|
+
for error in packet.errors:
|
|
29
|
+
print(f' {error}')
|
|
30
|
+
else:
|
|
31
|
+
print('✅ Valid Packet')
|
|
32
|
+
|
|
33
|
+
print(f'{bold("Message Hash:")} {packet.message_hash}')
|
|
34
|
+
print(f'{bold("Route Type:")} {get_route_type_name(packet.route_type)}')
|
|
35
|
+
print(f'{bold("Payload Type:")} {get_payload_type_name(packet.payload_type)}')
|
|
36
|
+
print(f'{bold("Total Bytes:")} {packet.total_bytes}')
|
|
37
|
+
|
|
38
|
+
if packet.path and len(packet.path) > 0:
|
|
39
|
+
print(f'{bold("Path:")} {" → ".join(packet.path)}')
|
|
40
|
+
|
|
41
|
+
# Show payload details
|
|
42
|
+
if packet.payload['decoded']:
|
|
43
|
+
print(f'\n{bold("=== Payload Details ===")}')
|
|
44
|
+
show_payload_details(packet.payload['decoded'])
|
|
45
|
+
|
|
46
|
+
if not packet.is_valid:
|
|
47
|
+
sys.exit(1)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def show_payload_details(payload):
|
|
51
|
+
"""Show details for specific payload types"""
|
|
52
|
+
from datetime import datetime
|
|
53
|
+
|
|
54
|
+
payload_type = payload.type
|
|
55
|
+
|
|
56
|
+
if payload_type == PayloadType.Advert:
|
|
57
|
+
advert = payload
|
|
58
|
+
print(f'{bold("Device Role:")} {get_device_role_name(advert.app_data["device_role"])}')
|
|
59
|
+
|
|
60
|
+
if advert.app_data.get('name'):
|
|
61
|
+
print(f'{bold("Device Name:")} {advert.app_data["name"]}')
|
|
62
|
+
|
|
63
|
+
if advert.app_data.get('location'):
|
|
64
|
+
loc = advert.app_data['location']
|
|
65
|
+
print(f'{bold("Location:")} {loc["latitude"]}, {loc["longitude"]}')
|
|
66
|
+
|
|
67
|
+
print(f'{bold("Timestamp:")} {datetime.fromtimestamp(advert.timestamp).isoformat()}')
|
|
68
|
+
|
|
69
|
+
# Show signature verification status
|
|
70
|
+
if advert.signature_valid is not None:
|
|
71
|
+
if advert.signature_valid:
|
|
72
|
+
print(f'{bold("Signature:")} ✅ Valid Ed25519 signature')
|
|
73
|
+
else:
|
|
74
|
+
print(f'{bold("Signature:")} ❌ Invalid Ed25519 signature')
|
|
75
|
+
if advert.signature_error:
|
|
76
|
+
print(f'{bold("Error:")} {advert.signature_error}')
|
|
77
|
+
else:
|
|
78
|
+
print(f'{bold("Signature:")} ⚠️ Not verified (use --verify flag)')
|
|
79
|
+
|
|
80
|
+
elif payload_type == PayloadType.GroupText:
|
|
81
|
+
group_text = payload
|
|
82
|
+
print(f'{bold("Channel Hash:")} {group_text.channel_hash}')
|
|
83
|
+
|
|
84
|
+
if group_text.decrypted:
|
|
85
|
+
print(f'{bold("🔓 Decrypted Message:")}')
|
|
86
|
+
if group_text.decrypted.get('sender'):
|
|
87
|
+
print(f'{bold("Sender:")} {group_text.decrypted["sender"]}')
|
|
88
|
+
print(f'{bold("Message:")} {group_text.decrypted["message"]}')
|
|
89
|
+
print(f'{bold("Timestamp:")} {datetime.fromtimestamp(group_text.decrypted["timestamp"]).isoformat()}')
|
|
90
|
+
else:
|
|
91
|
+
print('🔒 Encrypted (no key available)')
|
|
92
|
+
print(f'{bold("Ciphertext:")} {group_text.ciphertext[:32]}...')
|
|
93
|
+
|
|
94
|
+
elif payload_type == PayloadType.Trace:
|
|
95
|
+
trace = payload
|
|
96
|
+
print(f'{bold("Trace Tag:")} {trace.trace_tag}')
|
|
97
|
+
print(f'{bold("Auth Code:")} {trace.auth_code}')
|
|
98
|
+
if trace.snr_values and len(trace.snr_values) > 0:
|
|
99
|
+
snr_str = ', '.join([f'{snr:.1f}dB' for snr in trace.snr_values])
|
|
100
|
+
print(f'{bold("SNR Values:")} {snr_str}')
|
|
101
|
+
|
|
102
|
+
else:
|
|
103
|
+
print(f'{bold("Type:")} {get_payload_type_name(payload_type)}')
|
|
104
|
+
print(f'{bold("Valid:")} {"✅" if payload.is_valid else "❌"}')
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def bold(text: str) -> str:
|
|
108
|
+
"""Make text bold (simple version without colorama)"""
|
|
109
|
+
return f'\033[1m{text}\033[0m'
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def main():
|
|
113
|
+
"""Main CLI entry point"""
|
|
114
|
+
import argparse
|
|
115
|
+
|
|
116
|
+
parser = argparse.ArgumentParser(
|
|
117
|
+
description='CLI tool for decoding MeshCore packets',
|
|
118
|
+
formatter_class=argparse.RawDescriptionHelpFormatter
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
parser.add_argument('--version', action='version', version='0.1.0')
|
|
122
|
+
|
|
123
|
+
subparsers = parser.add_subparsers(dest='command', help='Commands')
|
|
124
|
+
|
|
125
|
+
# Decode command
|
|
126
|
+
decode_parser = subparsers.add_parser('decode', help='Decode a MeshCore packet')
|
|
127
|
+
decode_parser.add_argument('hex', help='Hex string of the packet to decode')
|
|
128
|
+
decode_parser.add_argument('-k', '--key', action='append', dest='keys', help='Channel secret keys for decryption (hex)')
|
|
129
|
+
decode_parser.add_argument('-j', '--json', action='store_true', help='Output as JSON instead of formatted text')
|
|
130
|
+
decode_parser.add_argument('-s', '--structure', action='store_true', help='Show detailed packet structure analysis')
|
|
131
|
+
decode_parser.add_argument('--verify', action='store_true', help='Verify Ed25519 signatures (async)')
|
|
132
|
+
|
|
133
|
+
# Validate command
|
|
134
|
+
validate_parser = subparsers.add_parser('validate', help='Validate packet format')
|
|
135
|
+
validate_parser.add_argument('hex', help='Hex string to validate')
|
|
136
|
+
|
|
137
|
+
args = parser.parse_args()
|
|
138
|
+
|
|
139
|
+
if not args.command:
|
|
140
|
+
parser.print_help()
|
|
141
|
+
sys.exit(1)
|
|
142
|
+
|
|
143
|
+
if args.command == 'decode':
|
|
144
|
+
decode_command(args)
|
|
145
|
+
elif args.command == 'validate':
|
|
146
|
+
validate_command(args)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def decode_command(args):
|
|
150
|
+
"""Handle decode command"""
|
|
151
|
+
try:
|
|
152
|
+
# Clean up hex input
|
|
153
|
+
clean_hex = args.hex.replace(' ', '').replace('0x', '').replace('0X', '')
|
|
154
|
+
|
|
155
|
+
# Create key store if keys provided
|
|
156
|
+
key_store = None
|
|
157
|
+
if args.keys and len(args.keys) > 0:
|
|
158
|
+
key_store = MeshCoreKeyStore({
|
|
159
|
+
'channel_secrets': args.keys
|
|
160
|
+
})
|
|
161
|
+
|
|
162
|
+
# Create decryption options
|
|
163
|
+
options = DecryptionOptions(key_store=key_store) if key_store else None
|
|
164
|
+
|
|
165
|
+
# Decode packet
|
|
166
|
+
if args.verify:
|
|
167
|
+
# Use async verification
|
|
168
|
+
import asyncio
|
|
169
|
+
loop = asyncio.get_event_loop()
|
|
170
|
+
packet = loop.run_until_complete(
|
|
171
|
+
MeshCoreDecoder.decode_with_verification(clean_hex, options)
|
|
172
|
+
)
|
|
173
|
+
else:
|
|
174
|
+
packet = MeshCoreDecoder.decode(clean_hex, options)
|
|
175
|
+
|
|
176
|
+
if args.json:
|
|
177
|
+
# JSON output
|
|
178
|
+
if args.structure:
|
|
179
|
+
# Get structure as well
|
|
180
|
+
if args.verify:
|
|
181
|
+
import asyncio
|
|
182
|
+
loop = asyncio.get_event_loop()
|
|
183
|
+
structure = loop.run_until_complete(
|
|
184
|
+
MeshCoreDecoder.analyze_structure_with_verification(clean_hex, options)
|
|
185
|
+
)
|
|
186
|
+
else:
|
|
187
|
+
structure = MeshCoreDecoder.analyze_structure(clean_hex, options)
|
|
188
|
+
print(json.dumps({'packet': packet.__dict__, 'structure': structure.__dict__}, indent=2, default=str))
|
|
189
|
+
else:
|
|
190
|
+
print(json.dumps(packet.__dict__, indent=2, default=str))
|
|
191
|
+
else:
|
|
192
|
+
# Formatted output
|
|
193
|
+
print_formatted_packet(packet, args.keys)
|
|
194
|
+
|
|
195
|
+
# Show structure if requested
|
|
196
|
+
if args.structure:
|
|
197
|
+
print(f'\n{bold("=== Packet Structure ===")}')
|
|
198
|
+
|
|
199
|
+
if args.verify:
|
|
200
|
+
import asyncio
|
|
201
|
+
loop = asyncio.get_event_loop()
|
|
202
|
+
structure = loop.run_until_complete(
|
|
203
|
+
MeshCoreDecoder.analyze_structure_with_verification(clean_hex, options)
|
|
204
|
+
)
|
|
205
|
+
else:
|
|
206
|
+
structure = MeshCoreDecoder.analyze_structure(clean_hex, options)
|
|
207
|
+
|
|
208
|
+
print(f'\n{bold("Main Segments:")}')
|
|
209
|
+
for i, seg in enumerate(structure.segments):
|
|
210
|
+
print(f'{i + 1}. {bold(seg.name)} (bytes {seg.start_byte}-{seg.end_byte}): {seg.value}')
|
|
211
|
+
if seg.description:
|
|
212
|
+
print(f' {seg.description}')
|
|
213
|
+
|
|
214
|
+
if structure.payload and structure.payload.get('segments'):
|
|
215
|
+
print(f'\n{bold("Payload Segments:")}')
|
|
216
|
+
for i, seg in enumerate(structure.payload['segments']):
|
|
217
|
+
print(f'{i + 1}. {bold(seg.name)} (bytes {seg.start_byte}-{seg.end_byte}): {seg.value}')
|
|
218
|
+
print(f' {seg.description}')
|
|
219
|
+
|
|
220
|
+
except Exception as error:
|
|
221
|
+
print(f'Error: {error}', file=sys.stderr)
|
|
222
|
+
sys.exit(1)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def validate_command(args):
|
|
226
|
+
"""Handle validate command"""
|
|
227
|
+
try:
|
|
228
|
+
# Clean up hex input
|
|
229
|
+
clean_hex = args.hex.replace(' ', '').replace('0x', '').replace('0X', '')
|
|
230
|
+
|
|
231
|
+
result = MeshCoreDecoder.validate(clean_hex)
|
|
232
|
+
|
|
233
|
+
if result.is_valid:
|
|
234
|
+
print('✅ Valid packet format')
|
|
235
|
+
sys.exit(0)
|
|
236
|
+
else:
|
|
237
|
+
print('❌ Invalid packet format')
|
|
238
|
+
if result.errors:
|
|
239
|
+
for error in result.errors:
|
|
240
|
+
print(f' {error}')
|
|
241
|
+
sys.exit(1)
|
|
242
|
+
|
|
243
|
+
except Exception as error:
|
|
244
|
+
print(f'Error: {error}', file=sys.stderr)
|
|
245
|
+
sys.exit(1)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
if __name__ == '__main__':
|
|
249
|
+
main()
|
index.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""
|
|
2
|
+
MeshCore Packet Decoder - Python Implementation
|
|
3
|
+
Copyright (c) 2025 Michael Hart: https://github.com/michaelhart/meshcore-decoder
|
|
4
|
+
MIT License
|
|
5
|
+
|
|
6
|
+
Main entry point for the MeshCore decoder Python port
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
__version__ = "0.1.0"
|
|
10
|
+
|
|
11
|
+
# Main decoder
|
|
12
|
+
from src.decoder.packet_decoder import MeshCorePacketDecoder
|
|
13
|
+
|
|
14
|
+
# Crypto
|
|
15
|
+
from src.crypto.key_manager import MeshCoreKeyStore
|
|
16
|
+
from src.crypto.ed25519_verifier import Ed25519SignatureVerifier
|
|
17
|
+
|
|
18
|
+
# Type exports
|
|
19
|
+
from src.types.enums import (
|
|
20
|
+
RouteType, PayloadType, PayloadVersion, DeviceRole, AdvertFlags, RequestType
|
|
21
|
+
)
|
|
22
|
+
from src.types.crypto import CryptoKeyStore, DecryptionOptions, DecryptionResult, ValidationResult
|
|
23
|
+
from src.types.packet import DecodedPacket, PacketStructure, PacketSegment, PayloadSegment, HeaderBreakdown
|
|
24
|
+
from src.types.payloads import (
|
|
25
|
+
BasePayload, AdvertPayload, TracePayload, GroupTextPayload,
|
|
26
|
+
RequestPayload, TextMessagePayload, AnonRequestPayload,
|
|
27
|
+
AckPayload, PathPayload, ResponsePayload
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
# Utility exports
|
|
31
|
+
from src.utils.hex import hex_to_bytes, bytes_to_hex, number_to_hex, byte_to_hex
|
|
32
|
+
from src.utils.enum_names import (
|
|
33
|
+
get_route_type_name, get_payload_type_name, get_payload_version_name,
|
|
34
|
+
get_device_role_name, get_request_type_name
|
|
35
|
+
)
|
|
36
|
+
from src.utils.auth_token import (
|
|
37
|
+
create_auth_token, verify_auth_token, parse_auth_token, decode_auth_token_payload,
|
|
38
|
+
AuthTokenPayload, AuthToken
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
# Enum exports
|
|
42
|
+
__all__ = [
|
|
43
|
+
# Main decoder
|
|
44
|
+
'MeshCorePacketDecoder',
|
|
45
|
+
'MeshCoreKeyStore',
|
|
46
|
+
'Ed25519SignatureVerifier',
|
|
47
|
+
# Enums
|
|
48
|
+
'RouteType', 'PayloadType', 'PayloadVersion', 'DeviceRole', 'AdvertFlags', 'RequestType',
|
|
49
|
+
# Crypto types
|
|
50
|
+
'CryptoKeyStore', 'DecryptionOptions', 'DecryptionResult', 'ValidationResult',
|
|
51
|
+
# Packet types
|
|
52
|
+
'DecodedPacket', 'PacketStructure', 'PacketSegment', 'PayloadSegment', 'HeaderBreakdown',
|
|
53
|
+
# Payload types
|
|
54
|
+
'AdvertPayload', 'TracePayload', 'GroupTextPayload',
|
|
55
|
+
'RequestPayload', 'TextMessagePayload', 'AnonRequestPayload',
|
|
56
|
+
'AckPayload', 'PathPayload', 'ResponsePayload',
|
|
57
|
+
# Utilities
|
|
58
|
+
'hex_to_bytes', 'bytes_to_hex', 'number_to_hex', 'byte_to_hex',
|
|
59
|
+
'get_route_type_name', 'get_payload_type_name', 'get_payload_version_name',
|
|
60
|
+
'get_device_role_name', 'get_request_type_name',
|
|
61
|
+
'create_auth_token', 'verify_auth_token', 'parse_auth_token', 'decode_auth_token_payload',
|
|
62
|
+
'AuthTokenPayload', 'AuthToken',
|
|
63
|
+
]
|
|
64
|
+
|
|
65
|
+
# Convenience aliases
|
|
66
|
+
MeshCoreDecoder = MeshCorePacketDecoder
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""MeshCore Decoder - Python implementation"""
|
|
2
|
+
from .decoder.packet_decoder import MeshCorePacketDecoder
|
|
3
|
+
|
|
4
|
+
# Main class export (shorter name for convenience)
|
|
5
|
+
MeshCoreDecoder = MeshCorePacketDecoder
|
|
6
|
+
|
|
7
|
+
__all__ = ['MeshCoreDecoder', 'MeshCorePacketDecoder']
|
|
8
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Copyright (c) 2025 Michael Hart: https://github.com/michaelhart/meshcore-decoder
|
|
3
|
+
MIT License
|
|
4
|
+
|
|
5
|
+
Channel encryption/decryption using MeshCore algorithm
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import hmac
|
|
9
|
+
import hashlib
|
|
10
|
+
import re
|
|
11
|
+
from Crypto.Cipher import AES
|
|
12
|
+
from Crypto.Util.Padding import unpad
|
|
13
|
+
from ..types.crypto import DecryptionResult
|
|
14
|
+
from ..utils.hex import hex_to_bytes, bytes_to_hex
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ChannelCrypto:
|
|
18
|
+
@staticmethod
|
|
19
|
+
def decrypt_group_text_message(
|
|
20
|
+
ciphertext: str,
|
|
21
|
+
cipher_mac: str,
|
|
22
|
+
channel_key: str
|
|
23
|
+
) -> DecryptionResult:
|
|
24
|
+
"""
|
|
25
|
+
Decrypt GroupText message using MeshCore algorithm:
|
|
26
|
+
- HMAC-SHA256 verification with 2-byte MAC
|
|
27
|
+
- AES-128 ECB decryption
|
|
28
|
+
"""
|
|
29
|
+
try:
|
|
30
|
+
# Convert hex strings to byte arrays
|
|
31
|
+
channel_key_16 = hex_to_bytes(channel_key)
|
|
32
|
+
mac_bytes = hex_to_bytes(cipher_mac)
|
|
33
|
+
|
|
34
|
+
# MeshCore uses 32-byte channel secret: 16-byte key + 16 zero bytes
|
|
35
|
+
channel_secret = bytearray(32)
|
|
36
|
+
channel_secret[:16] = channel_key_16
|
|
37
|
+
# Rest are already zero
|
|
38
|
+
|
|
39
|
+
# Step 1: Verify HMAC-SHA256 using full 32-byte channel secret
|
|
40
|
+
ciphertext_bytes = hex_to_bytes(ciphertext)
|
|
41
|
+
|
|
42
|
+
h = hmac.new(channel_secret, ciphertext_bytes, hashlib.sha256)
|
|
43
|
+
calculated_mac_bytes = h.digest()
|
|
44
|
+
calculated_mac_first2 = calculated_mac_bytes[:2]
|
|
45
|
+
|
|
46
|
+
if calculated_mac_first2[0] != mac_bytes[0] or calculated_mac_first2[1] != mac_bytes[1]:
|
|
47
|
+
return DecryptionResult(success=False, error='MAC verification failed')
|
|
48
|
+
|
|
49
|
+
# Step 2: Decrypt using AES-128 ECB with first 16 bytes of channel secret
|
|
50
|
+
key_bytes = hex_to_bytes(channel_key)
|
|
51
|
+
|
|
52
|
+
cipher = AES.new(key_bytes, AES.MODE_ECB)
|
|
53
|
+
decrypted_bytes = cipher.decrypt(ciphertext_bytes)
|
|
54
|
+
|
|
55
|
+
if not decrypted_bytes or len(decrypted_bytes) < 5:
|
|
56
|
+
return DecryptionResult(success=False, error='Decrypted content too short')
|
|
57
|
+
|
|
58
|
+
# Parse MeshCore format: timestamp(4) + flags(1) + message_text
|
|
59
|
+
timestamp = (
|
|
60
|
+
decrypted_bytes[0] |
|
|
61
|
+
(decrypted_bytes[1] << 8) |
|
|
62
|
+
(decrypted_bytes[2] << 16) |
|
|
63
|
+
(decrypted_bytes[3] << 24)
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
flags_and_attempt = decrypted_bytes[4]
|
|
67
|
+
|
|
68
|
+
# Extract message text with UTF-8 decoding
|
|
69
|
+
message_bytes = decrypted_bytes[5:]
|
|
70
|
+
try:
|
|
71
|
+
message_text = message_bytes.decode('utf-8')
|
|
72
|
+
except UnicodeDecodeError:
|
|
73
|
+
# Try to decode as much as possible
|
|
74
|
+
message_text = message_bytes.decode('utf-8', errors='replace')
|
|
75
|
+
|
|
76
|
+
# Remove null terminator if present
|
|
77
|
+
null_index = message_text.find('\0')
|
|
78
|
+
if null_index >= 0:
|
|
79
|
+
message_text = message_text[:null_index]
|
|
80
|
+
|
|
81
|
+
# Parse sender and message (format: "sender: message")
|
|
82
|
+
colon_index = message_text.find(': ')
|
|
83
|
+
sender = None
|
|
84
|
+
content = message_text
|
|
85
|
+
|
|
86
|
+
if 0 < colon_index < 50:
|
|
87
|
+
potential_sender = message_text[:colon_index]
|
|
88
|
+
if not re.search(r'[:\[\]]', potential_sender):
|
|
89
|
+
sender = potential_sender
|
|
90
|
+
content = message_text[colon_index + 2:]
|
|
91
|
+
|
|
92
|
+
return DecryptionResult(
|
|
93
|
+
success=True,
|
|
94
|
+
data={
|
|
95
|
+
'timestamp': timestamp,
|
|
96
|
+
'flags': flags_and_attempt,
|
|
97
|
+
'sender': sender,
|
|
98
|
+
'message': content
|
|
99
|
+
}
|
|
100
|
+
)
|
|
101
|
+
except Exception as error:
|
|
102
|
+
error_msg = str(error) if isinstance(error, Exception) else 'Decryption failed'
|
|
103
|
+
return DecryptionResult(success=False, error=error_msg)
|
|
104
|
+
|
|
105
|
+
@staticmethod
|
|
106
|
+
def calculate_channel_hash(secret_key_hex: str) -> str:
|
|
107
|
+
"""
|
|
108
|
+
Calculate MeshCore channel hash from secret key
|
|
109
|
+
Returns the first byte of SHA256(secret) as hex string
|
|
110
|
+
"""
|
|
111
|
+
hash_obj = hashlib.sha256(hex_to_bytes(secret_key_hex))
|
|
112
|
+
hash_bytes = hash_obj.digest()
|
|
113
|
+
return f"{hash_bytes[0]:02x}"
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Copyright (c) 2025 Michael Hart: https://github.com/michaelhart/meshcore-decoder
|
|
3
|
+
MIT License
|
|
4
|
+
|
|
5
|
+
Ed25519 signature verification for MeshCore packets
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from typing import Optional
|
|
9
|
+
from ..utils.hex import hex_to_bytes, bytes_to_hex
|
|
10
|
+
|
|
11
|
+
try:
|
|
12
|
+
from cryptography.hazmat.primitives.asymmetric import ed25519
|
|
13
|
+
from cryptography.hazmat.backends import default_backend
|
|
14
|
+
CRYPTOGRAPHY_AVAILABLE = True
|
|
15
|
+
except ImportError:
|
|
16
|
+
try:
|
|
17
|
+
import ed25519 as ed25519_module
|
|
18
|
+
CRYPTOGRAPHY_AVAILABLE = False
|
|
19
|
+
ED25519_MODULE_AVAILABLE = True
|
|
20
|
+
except ImportError:
|
|
21
|
+
CRYPTOGRAPHY_AVAILABLE = False
|
|
22
|
+
ED25519_MODULE_AVAILABLE = False
|
|
23
|
+
print("Warning: No Ed25519 library available. Signature verification disabled.")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class Ed25519SignatureVerifier:
|
|
27
|
+
"""Ed25519 signature verification for MeshCore advertisement packets"""
|
|
28
|
+
|
|
29
|
+
@staticmethod
|
|
30
|
+
async def verify_advertisement_signature(
|
|
31
|
+
public_key_hex: str,
|
|
32
|
+
signature_hex: str,
|
|
33
|
+
timestamp: int,
|
|
34
|
+
app_data_hex: str
|
|
35
|
+
) -> bool:
|
|
36
|
+
"""
|
|
37
|
+
Verify an Ed25519 signature for MeshCore advertisement packets
|
|
38
|
+
|
|
39
|
+
According to MeshCore protocol, the signed message for advertisements is:
|
|
40
|
+
public_key (32 bytes) + timestamp (4 bytes LE) + app_data (variable)
|
|
41
|
+
"""
|
|
42
|
+
try:
|
|
43
|
+
# Convert hex strings to bytes
|
|
44
|
+
public_key = hex_to_bytes(public_key_hex)
|
|
45
|
+
signature = hex_to_bytes(signature_hex)
|
|
46
|
+
app_data = hex_to_bytes(app_data_hex)
|
|
47
|
+
|
|
48
|
+
# Construct the signed message according to MeshCore format
|
|
49
|
+
message = Ed25519SignatureVerifier._construct_advert_signed_message(
|
|
50
|
+
public_key_hex, timestamp, app_data
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
# Verify the signature
|
|
54
|
+
return Ed25519SignatureVerifier._verify_signature(signature, message, public_key)
|
|
55
|
+
except Exception as error:
|
|
56
|
+
print(f'Ed25519 signature verification failed: {error}')
|
|
57
|
+
return False
|
|
58
|
+
|
|
59
|
+
@staticmethod
|
|
60
|
+
def _construct_advert_signed_message(
|
|
61
|
+
public_key_hex: str,
|
|
62
|
+
timestamp: int,
|
|
63
|
+
app_data: bytes
|
|
64
|
+
) -> bytes:
|
|
65
|
+
"""
|
|
66
|
+
Construct the signed message for MeshCore advertisements
|
|
67
|
+
According to MeshCore source (Mesh.cpp lines 242-248):
|
|
68
|
+
Format: public_key (32 bytes) + timestamp (4 bytes LE) + app_data (variable length)
|
|
69
|
+
"""
|
|
70
|
+
public_key = hex_to_bytes(public_key_hex)
|
|
71
|
+
|
|
72
|
+
# Timestamp (4 bytes, little-endian)
|
|
73
|
+
timestamp_bytes = timestamp.to_bytes(4, byteorder='little')
|
|
74
|
+
|
|
75
|
+
# Concatenate: public_key + timestamp + app_data
|
|
76
|
+
message = public_key + timestamp_bytes + app_data
|
|
77
|
+
|
|
78
|
+
return message
|
|
79
|
+
|
|
80
|
+
@staticmethod
|
|
81
|
+
def _verify_signature(signature: bytes, message: bytes, public_key: bytes) -> bool:
|
|
82
|
+
"""Verify Ed25519 signature using available library"""
|
|
83
|
+
if CRYPTOGRAPHY_AVAILABLE:
|
|
84
|
+
return Ed25519SignatureVerifier._verify_with_cryptography(signature, message, public_key)
|
|
85
|
+
elif ED25519_MODULE_AVAILABLE:
|
|
86
|
+
return Ed25519SignatureVerifier._verify_with_ed25519_module(signature, message, public_key)
|
|
87
|
+
else:
|
|
88
|
+
print("No Ed25519 library available for verification")
|
|
89
|
+
return False
|
|
90
|
+
|
|
91
|
+
@staticmethod
|
|
92
|
+
def _verify_with_cryptography(signature: bytes, message: bytes, public_key: bytes) -> bool:
|
|
93
|
+
"""Verify using cryptography library"""
|
|
94
|
+
try:
|
|
95
|
+
public_key_obj = ed25519.Ed25519PublicKey.from_public_bytes(public_key)
|
|
96
|
+
public_key_obj.verify(signature, message)
|
|
97
|
+
return True
|
|
98
|
+
except Exception as e:
|
|
99
|
+
print(f'Cryptography library verification error: {e}')
|
|
100
|
+
return False
|
|
101
|
+
|
|
102
|
+
@staticmethod
|
|
103
|
+
def _verify_with_ed25519_module(signature: bytes, message: bytes, public_key: bytes) -> bool:
|
|
104
|
+
"""Verify using ed25519 module"""
|
|
105
|
+
try:
|
|
106
|
+
# Create public key object
|
|
107
|
+
public_key_obj = ed25519_mod.VerifyingKey(public_key)
|
|
108
|
+
public_key_obj.verify(signature, message)
|
|
109
|
+
return True
|
|
110
|
+
except Exception as e:
|
|
111
|
+
print(f'Ed25519 module verification error: {e}')
|
|
112
|
+
return False
|
|
113
|
+
|
|
114
|
+
@staticmethod
|
|
115
|
+
def get_signed_message_description(
|
|
116
|
+
public_key_hex: str,
|
|
117
|
+
timestamp: int,
|
|
118
|
+
app_data_hex: str
|
|
119
|
+
) -> str:
|
|
120
|
+
"""Get a human-readable description of what was signed"""
|
|
121
|
+
from datetime import datetime
|
|
122
|
+
ts_str = datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
|
|
123
|
+
return f"Public Key: {public_key_hex} + Timestamp: {timestamp} ({ts_str}) + App Data: {app_data_hex}"
|
|
124
|
+
|
|
125
|
+
@staticmethod
|
|
126
|
+
def get_signed_message_hex(
|
|
127
|
+
public_key_hex: str,
|
|
128
|
+
timestamp: int,
|
|
129
|
+
app_data_hex: str
|
|
130
|
+
) -> str:
|
|
131
|
+
"""Get the hex representation of the signed message for debugging"""
|
|
132
|
+
app_data = hex_to_bytes(app_data_hex)
|
|
133
|
+
message = Ed25519SignatureVerifier._construct_advert_signed_message(
|
|
134
|
+
public_key_hex, timestamp, app_data
|
|
135
|
+
)
|
|
136
|
+
return bytes_to_hex(message)
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Copyright (c) 2025 Michael Hart: https://github.com/michaelhart/meshcore-decoder
|
|
3
|
+
MIT License
|
|
4
|
+
|
|
5
|
+
Key management for MeshCore crypto operations
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from typing import Dict, List, Optional
|
|
9
|
+
from ..types.crypto import CryptoKeyStore
|
|
10
|
+
from .channel_crypto import ChannelCrypto
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class MeshCoreKeyStore:
|
|
14
|
+
"""
|
|
15
|
+
Key store for MeshCore packet decryption
|
|
16
|
+
|
|
17
|
+
Manages:
|
|
18
|
+
- Node keys for TextMessage/Request decryption
|
|
19
|
+
- Channel secrets for GroupText decryption
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
def __init__(self, initial_keys: Optional[Dict[str, any]] = None):
|
|
23
|
+
"""Initialize key store with optional initial keys"""
|
|
24
|
+
self.node_keys: Dict[str, str] = {} # nodePublicKey -> privateKey (hex)
|
|
25
|
+
self._channel_hash_to_keys: Dict[str, List[str]] = {} # channelHash -> [secret_keys...]
|
|
26
|
+
|
|
27
|
+
if initial_keys:
|
|
28
|
+
if 'channel_secrets' in initial_keys:
|
|
29
|
+
self.add_channel_secrets(initial_keys['channel_secrets'])
|
|
30
|
+
|
|
31
|
+
if 'node_keys' in initial_keys:
|
|
32
|
+
for pub_key, priv_key in initial_keys['node_keys'].items():
|
|
33
|
+
self.add_node_key(pub_key, priv_key)
|
|
34
|
+
|
|
35
|
+
def add_node_key(self, public_key: str, private_key: str) -> None:
|
|
36
|
+
"""Add or update a node key"""
|
|
37
|
+
normalized_pub_key = public_key.upper()
|
|
38
|
+
self.node_keys[normalized_pub_key] = private_key
|
|
39
|
+
|
|
40
|
+
def has_channel_key(self, channel_hash: str) -> bool:
|
|
41
|
+
"""Check if a channel key exists for the given hash"""
|
|
42
|
+
normalized_hash = channel_hash.lower()
|
|
43
|
+
return normalized_hash in self._channel_hash_to_keys
|
|
44
|
+
|
|
45
|
+
def has_node_key(self, public_key: str) -> bool:
|
|
46
|
+
"""Check if a node key exists for the given public key"""
|
|
47
|
+
normalized_pub_key = public_key.upper()
|
|
48
|
+
return normalized_pub_key in self.node_keys
|
|
49
|
+
|
|
50
|
+
def get_channel_keys(self, channel_hash: str) -> List[str]:
|
|
51
|
+
"""Get all channel keys that match the given channel hash (handles collisions)"""
|
|
52
|
+
normalized_hash = channel_hash.lower()
|
|
53
|
+
return self._channel_hash_to_keys.get(normalized_hash, [])
|
|
54
|
+
|
|
55
|
+
def get_node_key(self, public_key: str) -> Optional[str]:
|
|
56
|
+
"""Get a node key by public key"""
|
|
57
|
+
normalized_pub_key = public_key.upper()
|
|
58
|
+
return self.node_keys.get(normalized_pub_key)
|
|
59
|
+
|
|
60
|
+
def add_channel_secrets(self, secret_keys: List[str]) -> None:
|
|
61
|
+
"""
|
|
62
|
+
Add channel keys by secret keys (new simplified API)
|
|
63
|
+
Automatically calculates channel hashes
|
|
64
|
+
"""
|
|
65
|
+
for secret_key in secret_keys:
|
|
66
|
+
channel_hash = ChannelCrypto.calculate_channel_hash(secret_key).lower()
|
|
67
|
+
|
|
68
|
+
# Handle potential hash collisions
|
|
69
|
+
if channel_hash not in self._channel_hash_to_keys:
|
|
70
|
+
self._channel_hash_to_keys[channel_hash] = []
|
|
71
|
+
self._channel_hash_to_keys[channel_hash].append(secret_key)
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Decoder module"""
|
|
2
|
+
from .packet_decoder import MeshCorePacketDecoder
|
|
3
|
+
from .payload_decoders import (
|
|
4
|
+
AckPayloadDecoder,
|
|
5
|
+
TracePayloadDecoder,
|
|
6
|
+
PathPayloadDecoder,
|
|
7
|
+
AdvertPayloadDecoder,
|
|
8
|
+
GroupTextPayloadDecoder,
|
|
9
|
+
RequestPayloadDecoder,
|
|
10
|
+
ResponsePayloadDecoder,
|
|
11
|
+
AnonRequestPayloadDecoder,
|
|
12
|
+
TextMessagePayloadDecoder
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
'MeshCorePacketDecoder',
|
|
17
|
+
'AckPayloadDecoder',
|
|
18
|
+
'TracePayloadDecoder',
|
|
19
|
+
'PathPayloadDecoder',
|
|
20
|
+
'AdvertPayloadDecoder',
|
|
21
|
+
'GroupTextPayloadDecoder',
|
|
22
|
+
'RequestPayloadDecoder',
|
|
23
|
+
'ResponsePayloadDecoder',
|
|
24
|
+
'AnonRequestPayloadDecoder',
|
|
25
|
+
'TextMessagePayloadDecoder',
|
|
26
|
+
]
|