diff options
Diffstat (limited to 'research/executables/claude-ai-slop')
4 files changed, 1146 insertions, 0 deletions
diff --git a/research/executables/claude-ai-slop/checksum_bruteforce.py b/research/executables/claude-ai-slop/checksum_bruteforce.py new file mode 100644 index 0000000..3cfa7cf --- /dev/null +++ b/research/executables/claude-ai-slop/checksum_bruteforce.py @@ -0,0 +1,367 @@ +#!/usr/bin/env python3 +""" +Comprehensive checksum bruteforce tool for the MEL protocol +Usage: python checksum_bruteforce.py <hex_file> +""" + +import sys +import struct +from typing import List, Tuple, Dict + +def parse_hex_line(hex_string: str) -> List[int]: + """Parse a hex string into list of bytes""" + hex_clean = hex_string.strip().replace(' ', '') + return [int(hex_clean[i:i+2], 16) for i in range(0, len(hex_clean), 2)] + +def bytes_to_hex(bytes_list: List[int]) -> str: + """Convert bytes to hex string""" + return ''.join(f'{b:02x}' for b in bytes_list) + +class ChecksumTester: + def __init__(self): + self.algorithms = [ + self.simple_sum, + self.sum_with_carry, + self.twos_complement, + self.ones_complement, + self.xor_checksum, + self.crc16_ccitt, + self.crc16_ibm, + self.fletcher16, + self.modsum_256, + self.internet_checksum, + ] + + def simple_sum(self, data: List[int]) -> int: + """Simple sum of all bytes""" + return sum(data) & 0xFFFF + + def sum_with_carry(self, data: List[int]) -> int: + """Sum with end-around carry""" + s = sum(data) + while s > 0xFFFF: + s = (s & 0xFFFF) + (s >> 16) + return s + + def twos_complement(self, data: List[int]) -> int: + """Two's complement of sum""" + s = sum(data) + return (~s + 1) & 0xFFFF + + def ones_complement(self, data: List[int]) -> int: + """One's complement of sum""" + s = sum(data) + return (~s) & 0xFFFF + + def xor_checksum(self, data: List[int]) -> int: + """XOR of all bytes, extended to 16-bit""" + result = 0 + for b in data: + result ^= b + return result + + def crc16_ccitt(self, data: List[int], poly: int = 0x1021) -> int: + """CRC-16 CCITT""" + crc = 0xFFFF + for byte in data: + crc ^= (byte << 8) + for _ in range(8): + if crc & 0x8000: + crc = (crc << 1) ^ poly + else: + crc <<= 1 + crc &= 0xFFFF + return crc + + def crc16_ibm(self, data: List[int]) -> int: + """CRC-16 IBM/ANSI""" + return self.crc16_ccitt(data, 0x8005) + + def fletcher16(self, data: List[int]) -> int: + """Fletcher-16 checksum""" + sum1 = sum2 = 0 + for byte in data: + sum1 = (sum1 + byte) % 255 + sum2 = (sum2 + sum1) % 255 + return (sum2 << 8) | sum1 + + def modsum_256(self, data: List[int]) -> int: + """Sum modulo 256, extended to 16-bit""" + return sum(data) % 256 + + def internet_checksum(self, data: List[int]) -> int: + """Internet/TCP checksum""" + # Pad to even length + if len(data) % 2: + data = data + [0] + + s = 0 + for i in range(0, len(data), 2): + s += (data[i] << 8) + data[i+1] + + while s >> 16: + s = (s & 0xFFFF) + (s >> 16) + + return (~s) & 0xFFFF + +def test_parametric_algorithms(data: List[int], expected: int) -> List[str]: + """Test algorithms with various parameters""" + matches = [] + + # Test sum with different initial values + for init_val in range(0, 0x10000, 0x1000): + result = (init_val + sum(data)) & 0xFFFF + if result == expected: + matches.append(f"Sum + 0x{init_val:04x}") + + # Test sum with different modulo values + for mod_val in [0xFF, 0x100, 0x101, 0x1FF, 0x200, 0xFFFF, 0x10000]: + if mod_val > 0: + result = sum(data) % mod_val + if result == expected: + matches.append(f"Sum mod 0x{mod_val:x}") + + # Test XOR with different patterns + for pattern in [0x00, 0xFF, 0xAA, 0x55, 0x5A, 0xA5]: + result = 0 + for byte in data: + result ^= (byte ^ pattern) + if (result & 0xFFFF) == expected: + matches.append(f"XOR with pattern 0x{pattern:02x}") + + # Test rotation-based checksums + for shift in range(1, 16): + result = 0 + for byte in data: + result = ((result << shift) | (result >> (16 - shift))) & 0xFFFF + result ^= byte + if result == expected: + matches.append(f"Rotate-XOR shift {shift}") + + return matches + +def analyze_file(filename: str): + """Analyze a file of hex data to find checksum patterns""" + with open(filename, 'r') as f: + lines = [line.strip() for line in f if line.strip()] + + print(f"Analyzing {filename} with {len(lines)} entries") + + tester = ChecksumTester() + algorithm_matches = {} + + # Test first 10 entries to find patterns + for i, line in enumerate(lines[:10]): + bytes_data = parse_hex_line(line) + if len(bytes_data) < 3: + continue + + # Assume last 2 bytes are checksum + payload = bytes_data[:-2] + checksum_be = (bytes_data[-2] << 8) | bytes_data[-1] + checksum_le = bytes_data[-2] | (bytes_data[-1] << 8) + + print(f"\nEntry {i}:") + print(f" Payload: {bytes_to_hex(payload)}") + print(f" Checksum BE: 0x{checksum_be:04x}") + print(f" Checksum LE: 0x{checksum_le:04x}") + + # Test standard algorithms for both byte orders + for checksum, order in [(checksum_be, "BE"), (checksum_le, "LE")]: + print(f" Testing {order} interpretation:") + for algo in tester.algorithms: + result = algo(payload) + if result == checksum: + algo_name = f"{algo.__name__}_{order}" + algorithm_matches[algo_name] = algorithm_matches.get(algo_name, 0) + 1 + print(f" ✓ {algo.__name__}: 0x{result:04x}") + else: + print(f" ✗ {algo.__name__}: 0x{result:04x}") + + # Test parametric algorithms + param_matches = test_parametric_algorithms(payload, checksum) + for match in param_matches: + print(f" ✓ {match}") + key = f"{match}_{order}" + algorithm_matches[key] = algorithm_matches.get(key, 0) + 1 + + # Summary of algorithms that work consistently + print(f"\n{'='*50}") + print("SUMMARY - Algorithms with multiple matches:") + for algo, count in sorted(algorithm_matches.items(), key=lambda x: x[1], reverse=True): + if count > 1: + print(f" {algo}: {count} matches") + + return algorithm_matches + +def brute_force_unknown_algorithm(filename: str, max_entries: int = 5): + """Brute force approach for completely unknown algorithms""" + with open(filename, 'r') as f: + lines = [line.strip() for line in f if line.strip()][:max_entries] + + print(f"Brute forcing {len(lines)} entries...") + + # Collect all data points + data_points = [] + for line in lines: + bytes_data = parse_hex_line(line) + payload = bytes_data[:-2] + checksum_le = bytes_data[-2] | (bytes_data[-1] << 8) + data_points.append((payload, checksum_le)) + + # Try to find a mathematical relationship + # This is a simplified approach - in practice you'd want more sophisticated analysis + + # Check if it's a linear relationship: checksum = a * sum(payload) + b + if len(data_points) >= 2: + payload_sums = [sum(payload) for payload, _ in data_points] + checksums = [checksum for _, checksum in data_points] + + print(f"Payload sums: {[f'0x{s:x}' for s in payload_sums[:5]]}") + print(f"Checksums: {[f'0x{c:04x}' for c in checksums[:5]]}") + + # Try to solve for linear relationship + if len(set(payload_sums)) > 1: # Need different sums to solve + sum1, sum2 = payload_sums[0], payload_sums[1] + check1, check2 = checksums[0], checksums[1] + + if sum1 != sum2: + # Solve: check1 = a * sum1 + b, check2 = a * sum2 + b + a = (check2 - check1) / (sum2 - sum1) + b = check1 - a * sum1 + + print(f"Testing linear relationship: checksum = {a:.3f} * sum + {b:.3f}") + + # Verify with all data points + matches = 0 + for payload, expected in data_points: + predicted = int(a * sum(payload) + b) & 0xFFFF + if predicted == expected: + matches += 1 + print(f" ✓ Linear match: sum={sum(payload)}, expected=0x{expected:04x}, predicted=0x{predicted:04x}") + else: + print(f" ✗ Linear miss: sum={sum(payload)}, expected=0x{expected:04x}, predicted=0x{predicted:04x}") + + if matches == len(data_points): + print(f"🎉 FOUND LINEAR RELATIONSHIP! checksum = {a:.3f} * sum(payload) + {b:.3f}") + +def generate_test_vectors(base_hex: str, variations: int = 10): + """Generate test vectors by modifying a base message""" + base_bytes = parse_hex_line(base_hex) + payload = base_bytes[:-2] + + print(f"Generating {variations} test vectors from base:") + print(f"Base: {base_hex}") + + # Generate variations by changing single bytes + for i in range(min(variations, len(payload))): + modified = payload.copy() + modified[i] = (modified[i] + 1) % 256 # Increment one byte + + # You would calculate the correct checksum here and append it + # For now, we'll just show the modified payload + print(f"Variation {i}: {bytes_to_hex(modified)} + [CHECKSUM_TO_CALCULATE]") + +def test_specific_algorithms(data: List[int], expected: int) -> Dict[str, int]: + """Test specific algorithms that might be used in embedded systems""" + results = {} + + # Test sum with various bit operations + s = sum(data) + + # Basic variations + results["sum_low16"] = s & 0xFFFF + results["sum_high16"] = (s >> 16) & 0xFFFF + results["sum_rotated"] = ((s << 8) | (s >> 8)) & 0xFFFF + results["sum_inverted"] = (~s) & 0xFFFF + results["sum_twos_comp"] = (-s) & 0xFFFF + + # With different initial values (common in embedded systems) + for init in [0x0000, 0x5555, 0xAAAA, 0xFFFF, 0x1234, 0x4321]: + results[f"sum_init_{init:04x}"] = (s + init) & 0xFFFF + results[f"xor_init_{init:04x}"] = (s ^ init) & 0xFFFF + + # Byte-wise operations + byte_xor = 0 + byte_sum = 0 + for b in data: + byte_xor ^= b + byte_sum += b + + results["byte_xor"] = byte_xor + results["byte_xor_16bit"] = (byte_xor << 8) | byte_xor + results["byte_sum_mod256"] = byte_sum % 256 + results["byte_sum_mod255"] = byte_sum % 255 + + # Position-weighted sums + pos_sum = sum(i * b for i, b in enumerate(data)) + results["position_weighted"] = pos_sum & 0xFFFF + + # Polynomial checksums (simplified) + poly_result = 0 + for b in data: + poly_result = ((poly_result << 1) ^ b) & 0xFFFF + results["poly_shift_xor"] = poly_result + + # Return only matches + return {name: value for name, value in results.items() if value == expected} + +def main(): + if len(sys.argv) != 2: + print("Usage: python checksum_bruteforce.py <hex_file>") + print("\nThis tool will:") + print("1. Test standard checksum algorithms") + print("2. Try parametric variations") + print("3. Attempt to find mathematical relationships") + print("4. Generate test vectors for validation") + sys.exit(1) + + filename = sys.argv[1] + + try: + # Main analysis + print("=" * 60) + print("COMPREHENSIVE CHECKSUM ANALYSIS") + print("=" * 60) + + matches = analyze_file(filename) + + print("\n" + "=" * 60) + print("BRUTE FORCE UNKNOWN ALGORITHMS") + print("=" * 60) + + brute_force_unknown_algorithm(filename, max_entries=10) + + print("\n" + "=" * 60) + print("SPECIFIC EMBEDDED ALGORITHMS") + print("=" * 60) + + # Test first entry with specific algorithms + with open(filename, 'r') as f: + first_line = f.readline().strip() + + bytes_data = parse_hex_line(first_line) + payload = bytes_data[:-2] + checksum_le = bytes_data[-2] | (bytes_data[-1] << 8) + + specific_matches = test_specific_algorithms(payload, checksum_le) + if specific_matches: + print("Specific algorithm matches found:") + for name, value in specific_matches.items(): + print(f" ✓ {name}: 0x{value:04x}") + else: + print("No specific algorithm matches found") + + print("\n" + "=" * 60) + print("TEST VECTOR GENERATION") + print("=" * 60) + + generate_test_vectors(first_line, 5) + + except FileNotFoundError: + print(f"Error: File '{filename}' not found") + except Exception as e: + print(f"Error: {e}") + +if __name__ == "__main__": + main()
\ No newline at end of file diff --git a/research/executables/claude-ai-slop/mel_checksum_cracker.py b/research/executables/claude-ai-slop/mel_checksum_cracker.py new file mode 100644 index 0000000..c851742 --- /dev/null +++ b/research/executables/claude-ai-slop/mel_checksum_cracker.py @@ -0,0 +1,319 @@ +#!/usr/bin/env python3 +""" +MEL Checksum Cracker - Final comprehensive tool +Based on analysis showing sum-sequence is constant but checksum follows different pattern +""" + +import sys +import struct + +def parse_hex(hex_str): + """Parse hex string to bytes""" + return [int(hex_str[i:i+2], 16) for i in range(0, len(hex_str), 2)] + +def calculate_mel_checksum(payload_bytes, sequence=None): + """ + Calculate MEL checksum based on discovered patterns + This function will be updated as we discover the actual algorithm + """ + if sequence is None: + # Try to extract sequence from payload if it's a full packet + if len(payload_bytes) >= 8: + sequence = payload_bytes[7] + else: + sequence = 0 + + # Calculate payload sum (excluding checksum bytes) + if len(payload_bytes) > 31: # Full packet + payload_sum = sum(payload_bytes[:-2]) + else: # Just payload + payload_sum = sum(payload_bytes) + + # Test various algorithms based on our analysis + algorithms = { + 'simple_sum': payload_sum & 0xFFFF, + 'sum_minus_seq': (payload_sum - sequence) & 0xFFFF, + 'sum_plus_seq': (payload_sum + sequence) & 0xFFFF, + 'twos_complement': (~payload_sum + 1) & 0xFFFF, + 'ones_complement': (~payload_sum) & 0xFFFF, + 'constant_minus_sum': (0x10000 - payload_sum) & 0xFFFF, + 'sum_with_carry': payload_sum + (payload_sum >> 16), + } + + return algorithms + +def analyze_pattern_discovery(filename): + """Discover the actual checksum pattern""" + print(f"Pattern Discovery Analysis for {filename}") + print("=" * 60) + + with open(filename, 'r') as f: + lines = [line.strip() for line in f if line.strip()] + + # Analyze first 20 entries to find the pattern + entries = [] + for i, line in enumerate(lines[:20]): + bytes_data = parse_hex(line) + payload = bytes_data[:-2] + checksum = bytes_data[-2] | (bytes_data[-1] << 8) # Little endian + sequence = bytes_data[7] if len(bytes_data) > 7 else 0 + payload_sum = sum(payload) + + entries.append({ + 'index': i, + 'sequence': sequence, + 'checksum': checksum, + 'payload_sum': payload_sum, + 'payload': payload, + 'hex': line + }) + + # Print analysis table + print("Entry | Seq | Checksum | PayloadSum | Sum-Seq | Patterns") + print("------|-----|----------|------------|---------|----------") + + base_constant = None + for entry in entries: + seq = entry['sequence'] + check = entry['checksum'] + psum = entry['payload_sum'] + sum_minus_seq = psum - seq + + if base_constant is None: + base_constant = sum_minus_seq + + # Test various patterns + pattern_tests = [] + if sum_minus_seq == base_constant: + pattern_tests.append("SUM-SEQ=CONST") + + # Test if checksum relates to a base value + if entry['index'] == 0: + base_checksum = check + checksum_base = check + else: + checksum_diff = check - base_checksum + pattern_tests.append(f"ΔCHK={checksum_diff:+d}") + + patterns = " ".join(pattern_tests) if pattern_tests else "-" + + print(f"{entry['index']:5d} | {seq:3d} | 0x{check:04x} | {psum:10d} | {sum_minus_seq:7d} | {patterns}") + + # Test for mathematical relationships + print(f"\nMathematical Relationship Analysis:") + print(f"Base constant (sum - sequence): {base_constant}") + + # Look for checksum calculation pattern + print(f"\nChecksum Pattern Analysis:") + + # Test if there's a consistent transformation from payload_sum to checksum + transformations = {} + for entry in entries: + psum = entry['payload_sum'] + check = entry['checksum'] + seq = entry['sequence'] + + # Test various transformations + transforms = { + 'sum_low8': psum & 0xFF, + 'sum_high8': (psum >> 8) & 0xFF, + 'sum_mod256': psum % 256, + 'sum_mod255': psum % 255, + 'sum_rotated': ((psum << 8) | (psum >> 8)) & 0xFFFF, + 'sum_xor_seq': (psum ^ seq) & 0xFFFF, + 'sum_add_magic': (psum + 0x5555) & 0xFFFF, + 'sum_sub_magic': (psum - 0x5555) & 0xFFFF, + } + + for name, value in transforms.items(): + if value == check: + if name not in transformations: + transformations[name] = [] + transformations[name].append(entry['index']) + + if transformations: + print("Found consistent transformations:") + for transform, indices in transformations.items(): + if len(indices) > 1: + print(f" {transform}: matches at entries {indices}") + else: + print("No simple mathematical transformation found") + + # Advanced pattern detection + print(f"\nAdvanced Pattern Detection:") + + # Check if it's a lookup table or formula with sequence + checksum_by_seq = {} + for entry in entries: + seq = entry['sequence'] + check = entry['checksum'] + if seq not in checksum_by_seq: + checksum_by_seq[seq] = [] + checksum_by_seq[seq].append(check) + + # Look for sequence-based pattern + if len(checksum_by_seq) > 1: + print("Checksum vs Sequence relationship:") + for seq in sorted(checksum_by_seq.keys())[:10]: + checksums = checksum_by_seq[seq] + print(f" Sequence {seq:3d}: checksums {[f'0x{c:04x}' for c in checksums]}") + + return entries + +def brute_force_checksum_algorithm(entries): + """Brute force the checksum algorithm using known good data""" + print("\nBrute Force Algorithm Discovery:") + print("=" * 40) + + # Get the first entry as reference + ref_entry = entries[0] + ref_sum = ref_entry['payload_sum'] + ref_checksum = ref_entry['checksum'] + + print(f"Reference: sum={ref_sum}, checksum=0x{ref_checksum:04x}") + + # Try to find the magic constant or operation + # Test if checksum = (payload_sum + magic) & 0xFFFF + for magic in range(-1000, 1000): + predicted = (ref_sum + magic) & 0xFFFF + if predicted == ref_checksum: + print(f"Possible algorithm: checksum = (payload_sum + {magic}) & 0xFFFF") + + # Verify with other entries + matches = 0 + for entry in entries[1:6]: # Test next 5 entries + test_predicted = (entry['payload_sum'] + magic) & 0xFFFF + if test_predicted == entry['checksum']: + matches += 1 + + print(f" Verification: {matches}/5 additional entries match") + if matches >= 4: + print(f" 🎉 LIKELY ALGORITHM FOUND!") + return f"(payload_sum + {magic}) & 0xFFFF" + + # Test multiplicative factors + for factor in [1, 2, 3, 4, 5, 7, 8, 15, 16, 31, 32, 63, 64, 127, 128, 255, 256]: + for offset in range(-100, 101, 10): + predicted = (ref_sum * factor + offset) & 0xFFFF + if predicted == ref_checksum: + # Verify with next entry + next_entry = entries[1] + next_predicted = (next_entry['payload_sum'] * factor + offset) & 0xFFFF + if next_predicted == next_entry['checksum']: + print(f"Possible algorithm: checksum = (payload_sum * {factor} + {offset}) & 0xFFFF") + + print("No simple algorithm found in brute force range") + return None + +def generate_implementation(algorithm_desc): + """Generate C/Python implementation of discovered algorithm""" + if not algorithm_desc: + return + + print(f"\nGenerated Implementation:") + print("=" * 30) + + print("Python:") + print(f"def calculate_mel_checksum(payload_bytes):") + print(f" payload_sum = sum(payload_bytes)") + print(f" return {algorithm_desc}") + + print("\nC:") + print(f"uint16_t calculate_mel_checksum(uint8_t* payload, size_t length) {{") + print(f" uint32_t payload_sum = 0;") + print(f" for (size_t i = 0; i < length; i++) {{") + print(f" payload_sum += payload[i];") + print(f" }}") + print(f" return {algorithm_desc.replace('payload_sum', 'payload_sum')};") + print(f"}}") + +def validate_algorithm(filename, algorithm_func): + """Validate the discovered algorithm against all entries in file""" + print(f"\nValidating algorithm against all entries in {filename}") + print("=" * 50) + + with open(filename, 'r') as f: + lines = [line.strip() for line in f if line.strip()] + + matches = 0 + total = 0 + mismatches = [] + + for i, line in enumerate(lines): + bytes_data = parse_hex(line) + payload = bytes_data[:-2] + expected_checksum = bytes_data[-2] | (bytes_data[-1] << 8) + + calculated_checksum = algorithm_func(payload) + + if calculated_checksum == expected_checksum: + matches += 1 + else: + mismatches.append((i, expected_checksum, calculated_checksum)) + + total += 1 + + # Show first few results + if i < 10: + status = "✓" if calculated_checksum == expected_checksum else "✗" + print(f" Entry {i:3d}: expected=0x{expected_checksum:04x}, calculated=0x{calculated_checksum:04x} {status}") + + success_rate = (matches / total) * 100 + print(f"\nValidation Results:") + print(f" Matches: {matches}/{total} ({success_rate:.1f}%)") + + if success_rate == 100: + print(" 🎉 PERFECT MATCH! Algorithm verified!") + elif success_rate > 95: + print(" ⚠️ Very high success rate - likely correct with minor issues") + else: + print(" ❌ Low success rate - algorithm needs refinement") + if mismatches[:3]: + print(" First few mismatches:") + for entry_idx, expected, calculated in mismatches[:3]: + print(f" Entry {entry_idx}: expected=0x{expected:04x}, got=0x{calculated:04x}") + +def main(): + if len(sys.argv) < 2: + print("MEL Checksum Cracker - Comprehensive Analysis Tool") + print("=" * 50) + print("Usage: python mel_checksum_cracker.py <hex_file>") + print("\nThis tool will:") + print(" 1. Discover checksum patterns") + print(" 2. Brute force the algorithm") + print(" 3. Generate implementations") + print(" 4. Validate against all data") + sys.exit(1) + + filename = sys.argv[1] + + try: + # Step 1: Pattern discovery + entries = analyze_pattern_discovery(filename) + + # Step 2: Brute force algorithm + algorithm = brute_force_checksum_algorithm(entries) + + # Step 3: Generate implementation + generate_implementation(algorithm) + + # Step 4: Validation (if algorithm found) + if algorithm: + # Create a lambda function for validation + def test_algorithm(payload): + payload_sum = sum(payload) + # This would be replaced with the actual discovered algorithm + # For now, using a placeholder + return payload_sum & 0xFFFF + + validate_algorithm(filename, test_algorithm) + + except FileNotFoundError: + print(f"Error: File '{filename}' not found") + except Exception as e: + print(f"Error: {e}") + import traceback + traceback.print_exc() + +if __name__ == "__main__": + main()
\ No newline at end of file diff --git a/research/executables/claude-ai-slop/mel_protocol_checksum_analyzer.py b/research/executables/claude-ai-slop/mel_protocol_checksum_analyzer.py new file mode 100644 index 0000000..701e8f2 --- /dev/null +++ b/research/executables/claude-ai-slop/mel_protocol_checksum_analyzer.py @@ -0,0 +1,231 @@ +#!/usr/bin/env python3 +""" +MEL Protocol Checksum Analyzer +Specifically designed for the MEL protocol hex data + +Based on analysis of the provided data patterns. +""" + +import sys +from typing import List, Tuple + +def parse_hex(hex_str: str) -> List[int]: + """Parse hex string to bytes""" + return [int(hex_str[i:i+2], 16) for i in range(0, len(hex_str), 2)] + +def analyze_mel_structure(hex_line: str) -> dict: + """Analyze MEL protocol structure""" + bytes_data = parse_hex(hex_line.strip()) + + return { + 'header': bytes_data[0:4], # 4D454C00 + 'length': bytes_data[4], # Packet length + 'flags': bytes_data[5:8], # Type/flags + 'sequence': bytes_data[6], # Sequence number (based on your data) + 'command': bytes_data[8:12], # Command and zone info + 'zone_mask': bytes_data[12:16], # Zone targeting + 'reserved': bytes_data[16:28], # Reserved/padding + 'payload': bytes_data[28:-2], # Actual payload + 'checksum_bytes': bytes_data[-2:], # Last 2 bytes + 'checksum_le': bytes_data[-2] | (bytes_data[-1] << 8), # Little endian + 'checksum_be': (bytes_data[-2] << 8) | bytes_data[-1], # Big endian + 'full_payload': bytes_data[:-2], # Everything except checksum + } + +def test_mel_checksums(data: List[int], expected: int) -> List[Tuple[str, int, bool]]: + """Test checksum algorithms specific to MEL protocol""" + results = [] + + # Test 1: Simple sum of all payload bytes + simple_sum = sum(data) & 0xFFFF + results.append(("Simple Sum", simple_sum, simple_sum == expected)) + + # Test 2: Sum with initial value (common in embedded protocols) + for init_val in [0x0000, 0x5555, 0xAAAA, 0xFFFF, 0x1234, 0x4321, 0x0001]: + checksum = (sum(data) + init_val) & 0xFFFF + results.append((f"Sum + 0x{init_val:04x}", checksum, checksum == expected)) + + # Test 3: Two's complement variations + sum_val = sum(data) + twos_comp = (~sum_val + 1) & 0xFFFF + results.append(("Two's Complement", twos_comp, twos_comp == expected)) + + # Test 4: One's complement + ones_comp = (~sum_val) & 0xFFFF + results.append(("One's Complement", ones_comp, ones_comp == expected)) + + # Test 5: Subtract from constant + for const in [0xFFFF, 0x10000, 0x8000, 0x7FFF]: + checksum = (const - sum_val) & 0xFFFF + results.append((f"0x{const:04x} - Sum", checksum, checksum == expected)) + + # Test 6: XOR-based checksums + xor_result = 0 + for byte in data: + xor_result ^= byte + results.append(("XOR all bytes", xor_result, xor_result == expected)) + + # Test 7: Position-weighted sum + pos_sum = sum(i * byte for i, byte in enumerate(data)) & 0xFFFF + results.append(("Position-weighted sum", pos_sum, pos_sum == expected)) + + # Test 8: Rolling checksum + rolling = 0 + for byte in data: + rolling = ((rolling << 1) | (rolling >> 15)) & 0xFFFF + rolling ^= byte + results.append(("Rolling XOR", rolling, rolling == expected)) + + # Test 9: Modular arithmetic variations + for mod_val in [0x100, 0x101, 0x1FF, 0x200, 0x255, 0x256]: + if mod_val > 0: + checksum = sum(data) % mod_val + results.append((f"Sum mod 0x{mod_val:x}", checksum, checksum == expected)) + + return results + +def analyze_sequence_relationship(filename: str): + """Analyze relationship between sequence numbers and checksums""" + with open(filename, 'r') as f: + lines = [line.strip() for line in f if line.strip()] + + print(f"Analyzing sequence-checksum relationship in {filename}") + print("=" * 60) + + sequence_data = [] + + for i, line in enumerate(lines[:20]): # First 20 entries + mel_data = analyze_mel_structure(line) + + # Look for the actual sequence field + # Based on your data, it seems to increment in byte 6 + actual_sequence = mel_data['sequence'] + checksum = mel_data['checksum_le'] + + sequence_data.append((i, actual_sequence, checksum)) + + print(f"Entry {i:2d}: seq=0x{actual_sequence:02x} ({actual_sequence:3d}), " + f"checksum=0x{checksum:04x} ({checksum:5d})") + + # Look for patterns + print("\nSequence vs Checksum Analysis:") + print("=" * 40) + + # Check if checksum changes predictably with sequence + if len(sequence_data) > 1: + for i in range(1, min(10, len(sequence_data))): + seq_diff = sequence_data[i][1] - sequence_data[i-1][1] + check_diff = sequence_data[i][2] - sequence_data[i-1][2] + print(f"Entry {i-1}→{i}: seq_diff={seq_diff:2d}, check_diff={check_diff:4d} (0x{check_diff & 0xFFFF:04x})") + +def find_checksum_algorithm(filename: str): + """Main function to find the checksum algorithm""" + with open(filename, 'r') as f: + lines = [line.strip() for line in f if line.strip()] + + print(f"MEL Protocol Checksum Analysis") + print(f"File: {filename}") + print(f"Entries: {len(lines)}") + print("=" * 60) + + # Analyze first few entries + algorithm_scores = {} + + for i, line in enumerate(lines[:10]): + mel_data = analyze_mel_structure(line) + + print(f"\nEntry {i}:") + print(f" Hex: {line}") + print(f" Sequence: 0x{mel_data['sequence']:02x}") + print(f" Expected checksum: 0x{mel_data['checksum_le']:04x} (LE)") + print(f" Payload length: {len(mel_data['full_payload'])} bytes") + + # Test algorithms + results = test_mel_checksums(mel_data['full_payload'], mel_data['checksum_le']) + + for algo_name, result, is_match in results: + if is_match: + print(f" ✓ {algo_name}: 0x{result:04x}") + algorithm_scores[algo_name] = algorithm_scores.get(algo_name, 0) + 1 + # Uncomment below to see all results + # else: + # print(f" ✗ {algo_name}: 0x{result:04x}") + + # Summary + print(f"\n{'='*60}") + print("ALGORITHM MATCH SUMMARY") + print(f"{'='*60}") + + if algorithm_scores: + for algo, score in sorted(algorithm_scores.items(), key=lambda x: x[1], reverse=True): + print(f"{algo}: {score}/10 matches") + + best_algo = max(algorithm_scores.items(), key=lambda x: x[1]) + if best_algo[1] >= 8: # At least 8/10 matches + print(f"\n🎉 LIKELY ALGORITHM FOUND: {best_algo[0]}") + print(f" Confidence: {best_algo[1]}/10 matches") + else: + print("No consistent algorithm found with standard methods.") + print("This may require custom algorithm development.") + + # Analyze sequence relationship + print(f"\n{'='*60}") + analyze_sequence_relationship(filename) + +def verify_algorithm(filename: str, algorithm_name: str): + """Verify a specific algorithm against all entries""" + with open(filename, 'r') as f: + lines = [line.strip() for line in f if line.strip()] + + print(f"Verifying algorithm '{algorithm_name}' against {len(lines)} entries...") + + matches = 0 + mismatches = [] + + for i, line in enumerate(lines): + mel_data = analyze_mel_structure(line) + expected = mel_data['checksum_le'] + + # Apply the algorithm (you'd implement the specific one here) + if algorithm_name == "Simple Sum": + calculated = sum(mel_data['full_payload']) & 0xFFFF + elif algorithm_name.startswith("Sum + "): + init_val = int(algorithm_name.split("0x")[1], 16) + calculated = (sum(mel_data['full_payload']) + init_val) & 0xFFFF + else: + print(f"Algorithm '{algorithm_name}' not implemented in verify function") + return + + if calculated == expected: + matches += 1 + else: + mismatches.append((i, expected, calculated)) + if len(mismatches) <= 5: # Show first 5 mismatches + print(f" Mismatch at entry {i}: expected 0x{expected:04x}, got 0x{calculated:04x}") + + print(f"Results: {matches}/{len(lines)} matches ({100*matches/len(lines):.1f}%)") + + if matches == len(lines): + print("🎉 PERFECT MATCH! Algorithm verified.") + elif matches > len(lines) * 0.9: + print("⚠️ Very close match. May need minor adjustment.") + else: + print("❌ Algorithm doesn't work consistently.") + +def main(): + if len(sys.argv) < 2: + print("Usage:") + print(" python mel_checksum_analyzer.py <hex_file> # Find algorithm") + print(" python mel_checksum_analyzer.py <hex_file> verify <algorithm> # Verify algorithm") + sys.exit(1) + + filename = sys.argv[1] + + if len(sys.argv) >= 4 and sys.argv[2] == "verify": + algorithm = sys.argv[3] + verify_algorithm(filename, algorithm) + else: + find_checksum_algorithm(filename) + +if __name__ == "__main__": + main()
\ No newline at end of file diff --git a/research/executables/claude-ai-slop/pattern_finder.py b/research/executables/claude-ai-slop/pattern_finder.py new file mode 100644 index 0000000..c53fb9d --- /dev/null +++ b/research/executables/claude-ai-slop/pattern_finder.py @@ -0,0 +1,229 @@ +#!/usr/bin/env python3 +""" +Pattern Analysis Tool for MEL Protocol Checksums +Looks for mathematical relationships and patterns in the checksum data +""" + +import sys +import struct +from collections import defaultdict + +def parse_hex(hex_str: str): + """Parse hex string to bytes""" + return [int(hex_str[i:i+2], 16) for i in range(0, len(hex_str), 2)] + +def find_changing_bytes(filename: str): + """Find which bytes change between consecutive entries""" + with open(filename, 'r') as f: + lines = [line.strip() for line in f if line.strip()] + + if len(lines) < 2: + return + + print(f"Analyzing byte changes in {filename}") + print("=" * 50) + + # Parse first two entries + bytes1 = parse_hex(lines[0]) + bytes2 = parse_hex(lines[1]) + + print("Changes between first two entries:") + for i, (b1, b2) in enumerate(zip(bytes1, bytes2)): + if b1 != b2: + print(f" Byte {i:2d}: 0x{b1:02x} → 0x{b2:02x} (diff: {b2-b1:+d})") + + # Look at sequence field specifically (byte 6 based on your data) + print(f"\nSequence progression (byte 6):") + for i in range(min(20, len(lines))): + bytes_data = parse_hex(lines[i]) + seq = bytes_data[6] if len(bytes_data) > 6 else 0 + checksum = bytes_data[-2] | (bytes_data[-1] << 8) if len(bytes_data) >= 2 else 0 + print(f" Entry {i:2d}: seq=0x{seq:02x}, checksum=0x{checksum:04x}") + +def analyze_checksum_patterns(filename: str): + """Analyze patterns in checksum values""" + with open(filename, 'r') as f: + lines = [line.strip() for line in f if line.strip()] + + print(f"Checksum Pattern Analysis for {filename}") + print("=" * 50) + + checksums = [] + sequences = [] + payload_sums = [] + + for line in lines: + bytes_data = parse_hex(line) + payload = bytes_data[:-2] + checksum = bytes_data[-2] | (bytes_data[-1] << 8) + sequence = bytes_data[6] if len(bytes_data) > 6 else 0 + + checksums.append(checksum) + sequences.append(sequence) + payload_sums.append(sum(payload)) + + # Look for arithmetic progression in checksums + print("Checksum differences (first 20):") + for i in range(1, min(20, len(checksums))): + diff = checksums[i] - checksums[i-1] + print(f" {i-1:2d}→{i:2d}: {diff:+5d} (0x{diff & 0xFFFF:04x})") + + # Check for correlation with payload sum + print(f"\nPayload sum vs Checksum correlation:") + for i in range(min(10, len(checksums))): + print(f" Entry {i}: sum={payload_sums[i]:5d}, checksum={checksums[i]:5d}, " + f"ratio={checksums[i]/payload_sums[i] if payload_sums[i] != 0 else 'N/A':.3f}") + +def test_bitwise_operations(filename: str): + """Test various bitwise operations that might be used""" + with open(filename, 'r') as f: + first_line = f.readline().strip() + + bytes_data = parse_hex(first_line) + payload = bytes_data[:-2] + expected = bytes_data[-2] | (bytes_data[-1] << 8) + + print(f"Testing bitwise operations on first entry:") + print(f"Expected checksum: 0x{expected:04x}") + print("=" * 40) + + # Sum with bit operations + s = sum(payload) + + tests = [ + ("Sum", s & 0xFFFF), + ("Sum >> 1", (s >> 1) & 0xFFFF), + ("Sum << 1", (s << 1) & 0xFFFF), + ("Sum rotated right", ((s >> 8) | (s << 8)) & 0xFFFF), + ("Sum rotated left", ((s << 8) | (s >> 8)) & 0xFFFF), + ("Sum XOR 0xFFFF", (s ^ 0xFFFF) & 0xFFFF), + ("Sum XOR 0x5555", (s ^ 0x5555) & 0xFFFF), + ("Sum XOR 0xAAAA", (s ^ 0xAAAA) & 0xFFFF), + ("~Sum", (~s) & 0xFFFF), + ("~Sum + 1", (~s + 1) & 0xFFFF), + ("0x10000 - Sum", (0x10000 - s) & 0xFFFF), + ("0xFFFF - Sum", (0xFFFF - s) & 0xFFFF), + ] + + for name, result in tests: + match = "✓" if result == expected else "✗" + print(f" {match} {name:20s}: 0x{result:04x}") + +def analyze_multiple_files(filenames): + """Compare patterns across multiple files""" + print("Multi-file Pattern Analysis") + print("=" * 50) + + all_data = {} + + for filename in filenames: + try: + with open(filename, 'r') as f: + lines = [line.strip() for line in f if line.strip()] + + # Get first entry from each file + if lines: + bytes_data = parse_hex(lines[0]) + payload = bytes_data[:-2] + checksum = bytes_data[-2] | (bytes_data[-1] << 8) + + all_data[filename] = { + 'payload': payload, + 'checksum': checksum, + 'payload_sum': sum(payload), + 'first_hex': lines[0] + } + + except FileNotFoundError: + print(f"Warning: File {filename} not found") + continue + + print("Comparison of first entries:") + for filename, data in all_data.items(): + print(f"\n{filename}:") + print(f" Checksum: 0x{data['checksum']:04x}") + print(f" Payload sum: {data['payload_sum']}") + print(f" First hex: {data['first_hex'][:40]}...") + + # Look for common differences + checksums = [data['checksum'] for data in all_data.values()] + sums = [data['payload_sum'] for data in all_data.values()] + + if len(checksums) > 1: + print(f"\nDifferences between files:") + filenames_list = list(all_data.keys()) + for i in range(len(filenames_list)): + for j in range(i+1, len(filenames_list)): + f1, f2 = filenames_list[i], filenames_list[j] + check_diff = all_data[f2]['checksum'] - all_data[f1]['checksum'] + sum_diff = all_data[f2]['payload_sum'] - all_data[f1]['payload_sum'] + print(f" {f1} vs {f2}:") + print(f" Checksum diff: {check_diff:+d}") + print(f" Sum diff: {sum_diff:+d}") + +def find_magic_constants(filename: str): + """Try to find magic constants used in the checksum calculation""" + with open(filename, 'r') as f: + lines = [line.strip() for line in f if line.strip()] + + print("Searching for magic constants...") + print("=" * 40) + + # Test first few entries + for i, line in enumerate(lines[:5]): + bytes_data = parse_hex(line) + payload = bytes_data[:-2] + expected = bytes_data[-2] | (bytes_data[-1] << 8) + payload_sum = sum(payload) + + print(f"\nEntry {i}:") + print(f" Expected: 0x{expected:04x} ({expected})") + print(f" Sum: 0x{payload_sum:04x} ({payload_sum})") + + # Try to find what constant when added/subtracted/XORed gives the expected result + magic_add = (expected - payload_sum) & 0xFFFF + magic_sub = (payload_sum - expected) & 0xFFFF + magic_xor = expected ^ payload_sum + + print(f" Magic add: 0x{magic_add:04x} (sum + this = expected)") + print(f" Magic sub: 0x{magic_sub:04x} (sum - this = expected)") + print(f" Magic XOR: 0x{magic_xor:04x} (sum ^ this = expected)") + +def main(): + if len(sys.argv) < 2: + print("Usage:") + print(" python pattern_finder.py <file1> [file2] [file3] ...") + print("\nThis tool will:") + print(" - Find changing bytes between entries") + print(" - Analyze checksum patterns") + print(" - Test bitwise operations") + print(" - Compare multiple files") + print(" - Search for magic constants") + sys.exit(1) + + filenames = sys.argv[1:] + + # Single file analysis + main_file = filenames[0] + + print("PATTERN ANALYSIS REPORT") + print("=" * 60) + + find_changing_bytes(main_file) + print() + + analyze_checksum_patterns(main_file) + print() + + test_bitwise_operations(main_file) + print() + + find_magic_constants(main_file) + print() + + # Multi-file analysis if multiple files provided + if len(filenames) > 1: + analyze_multiple_files(filenames) + +if __name__ == "__main__": + main()
\ No newline at end of file |