diff --git a/ADVANCED_FEATURES.md b/ADVANCED_FEATURES.md new file mode 100644 index 0000000..e19fd10 --- /dev/null +++ b/ADVANCED_FEATURES.md @@ -0,0 +1,484 @@ +# Advanced RF Security Research Features + +**⚠️ EDUCATIONAL AND AUTHORIZED RESEARCH USE ONLY ⚠️** + +This document provides comprehensive documentation for the advanced RF security research capabilities added to the Ultimatel-ily firmware. These features are designed for educational purposes and authorized security research only. + +## Table of Contents + +1. [Overview](#overview) +2. [Legal Disclaimer](#legal-disclaimer) +3. [Feature Modules](#feature-modules) +4. [Configuration](#configuration) +5. [Usage Guide](#usage-guide) +6. [Safety Features](#safety-features) +7. [Best Practices](#best-practices) + +## Overview + +The advanced research features extend the basic RF analysis capabilities with sophisticated tools for: + +- **Rolling Code Analysis**: Study and understand rolling code security systems +- **Signal Intelligence**: Advanced protocol identification and signal analysis +- **Advanced Transmission**: Sophisticated transmission patterns for testing +- **RF Research Tools**: Educational demonstrations of RF vulnerabilities (disabled by default) + +### Key Principles + +✅ **Educational Focus**: All features designed for learning and understanding +✅ **Safety First**: Multiple safety mechanisms and limits +✅ **Legal Compliance**: Prominent warnings and usage logging +✅ **User Responsibility**: Clear acceptance of legal responsibility required + +## Legal Disclaimer + +**READ THIS CAREFULLY BEFORE USING ADVANCED FEATURES** + +### Legal Requirements + +These advanced features are provided EXCLUSIVELY for: +- Educational purposes +- Security research on devices you own +- Authorized penetration testing with written permission +- Understanding RF security vulnerabilities + +### Prohibited Uses + +❌ **NEVER** use these features to: +- Access systems without authorization +- Interfere with communications (illegal jamming) +- Bypass security on devices you don't own +- Violate FCC regulations or local laws +- Disrupt emergency services +- Harm others or their property + +### Legal Consequences + +Unauthorized use of RF research tools can result in: +- Heavy fines ($100,000+ in USA) +- Criminal charges and imprisonment +- Equipment seizure +- Civil liability +- Professional consequences + +### Assumption of Responsibility + +**By using these features, YOU accept FULL legal responsibility for your actions.** + +The developers: +- Provide tools for educational purposes only +- Accept NO liability for misuse +- Do NOT endorse illegal activities +- Will cooperate with law enforcement + +## Feature Modules + +### 1. Rolling Code Analyzer + +**Purpose**: Educational tool for understanding rolling code security systems + +**File**: `src/rolling_code_analyzer.cpp` + +**Capabilities**: +- Capture multiple rolling code transmissions +- Statistical analysis (entropy, pattern detection) +- Protocol identification (KeeLoq, HCS, Hitag) +- Counter value extraction +- Manufacturer ID detection +- Educational prediction demonstration + +**Important Notes**: +- Does NOT break modern rolling code encryption +- Designed to teach WHY rolling codes are secure +- Demonstrates cryptographic principles +- Cannot predict or generate valid codes for real systems + +**Example Use Cases**: +- Learning about KeeLoq encryption +- Understanding counter-based security +- Studying manufacturer implementations +- Educational RF security demonstrations + +### 2. Signal Intelligence Module + +**Purpose**: Advanced signal analysis and protocol identification + +**File**: `src/signal_intelligence.cpp` + +**Capabilities**: +- Automatic protocol identification +- Modulation detection (ASK/OOK, FSK, GFSK, MSK) +- Encoding recognition (Manchester, PWM, PPM) +- Bit extraction and decoding +- Preamble and sync word detection +- CRC calculation and validation +- Signal quality metrics +- Timing pattern analysis + +**Supported Protocols** (detection): +- Princeton PT2262 +- EV1527 +- Weather station protocols +- Generic fixed-code protocols + +**Applications**: +- Understanding protocol structures +- Reverse engineering for compatibility +- Signal quality assessment +- Educational protocol analysis + +### 3. Advanced Transmission Features + +**Purpose**: Sophisticated transmission patterns for authorized testing + +**File**: `src/advanced_tx.cpp` + +**Capabilities**: +- Frequency sweeping (testing range) +- Continuous wave (CW) transmission +- Precise timing control +- Protocol fuzzing (randomized testing) +- Timing variation testing +- Amplitude variation testing +- Multi-burst patterns +- Custom transmission patterns + +**Safety Mechanisms**: +- Maximum duration limits (5 seconds default) +- Emergency stop button +- Transmission time tracking +- Safety checks before transmission + +**Use Cases**: +- Testing receiver sensitivity +- Protocol robustness testing +- Timing tolerance analysis +- Range testing on own devices + +### 4. RF Research Tools + +**Purpose**: Educational demonstrations of RF vulnerabilities + +**File**: `src/rf_research.cpp` + +**⚠️ DISABLED BY DEFAULT - REQUIRES EXPLICIT ACTIVATION ⚠️** + +**Features** (Educational Demonstrations Only): +- Frequency sweep research +- Continuous wave research +- Pulsed transmission research +- Noise generation research + +**Critical Notes**: +- ALL features are EDUCATIONAL DEMONSTRATIONS +- Actual harmful transmission is DISABLED for safety +- Features demonstrate CONCEPTS not actual attacks +- ILLEGAL without proper authorization +- Requires legal disclaimer acceptance +- Usage is logged for compliance + +**Legal Requirements**: +- Must accept detailed legal disclaimer +- Must have written authorization +- Must comply with all regulations +- Must be in controlled environment + +## Configuration + +### Feature Flags + +Edit `include/config.h`: + +```cpp +// Enable/disable feature modules +#define ENABLE_ROLLING_CODE_ANALYSIS 1 // Rolling code tools +#define ENABLE_SIGNAL_INTELLIGENCE 1 // Signal analysis tools +#define ENABLE_ADVANCED_TX 1 // Advanced transmission +#define ENABLE_RF_RESEARCH 0 // RF research (DISABLED by default) +``` + +### Safety Limits + +```cpp +// Transmission safety limits +#define MAX_TX_DURATION_MS 5000 // Maximum transmission time +#define EMERGENCY_STOP_BUTTON GPIO_NUM_0 // Emergency stop pin +#define MAX_SWEEP_DURATION_MS 10000 // Maximum sweep duration +#define MIN_PULSE_INTERVAL_MS 100 // Minimum pulse interval + +// Research mode settings +#define RESEARCH_MODE_TIMEOUT_MS 300000 // 5 minute timeout +#define REQUIRE_DISCLAIMER_ACCEPTANCE 1 // Require legal agreement +``` + +### Recommendations + +**For Educational Use**: +- Keep `ENABLE_ROLLING_CODE_ANALYSIS` enabled +- Keep `ENABLE_SIGNAL_INTELLIGENCE` enabled +- Keep `ENABLE_ADVANCED_TX` enabled with safe limits +- Keep `ENABLE_RF_RESEARCH` DISABLED + +**For Security Research** (with authorization): +- Enable only features needed for specific research +- Document authorization in code comments +- Reduce safety limits if necessary +- Maintain audit logs + +## Usage Guide + +### Accessing Advanced Features + +1. Navigate to main menu +2. Select "7. Advanced Research" +3. Read and accept legal warning +4. Choose desired feature + +### Menu Structure + +``` +Main Menu +└── Advanced Research ⚠️ + ├── Legal Warning (MUST ACCEPT FIRST) + ├── Rolling Code Analysis + │ ├── Capture Sequence + │ ├── Analyze Pattern + │ ├── Protocol Detection + │ ├── Export Data + │ └── Clear Sequences + ├── Signal Intelligence + │ ├── Auto-Identify Protocol + │ ├── Decode Signal + │ ├── Quality Analysis + │ ├── Extract Bits + │ └── Export Analysis + └── RF Research Tools ⚠️ (Disabled by default) + ├── Authorization Check + ├── Frequency Sweep (Educational demo) + ├── Signal Injection (Educational demo) + └── Protocol Fuzzing (Educational demo) +``` + +### Rolling Code Analysis Workflow + +1. **Capture Sequences**: + - Select "Capture Sequence" + - Activate rolling code transmitter multiple times + - Device captures each transmission + +2. **Analyze Patterns**: + - Select "Analyze Pattern" + - View statistical analysis + - Identify protocol type + - See entropy measurements + +3. **Export Data**: + - Select "Export Data" + - Data exported to serial console + - Save for further analysis + +### Signal Intelligence Workflow + +1. **Capture Signal**: + - Transmit signal to analyze + +2. **Auto-Identify**: + - Select "Auto-Identify Protocol" + - View detected protocol + - Check confidence level + +3. **Quality Analysis**: + - Select "Quality Analysis" + - View signal metrics + - Check SNR and consistency + +4. **Export Results**: + - Results available on serial console + - Save for documentation + +### Advanced TX Usage + +Features accessed programmatically or through custom menus. + +Example - Frequency Sweep: +```cpp +advancedTx->sweepFrequencies(433.0, 434.0, 0.1, 100); +// Sweeps from 433-434 MHz, 0.1 MHz steps, 100ms dwell +``` + +Example - Burst Transmission: +```cpp +advancedTx->transmitBurst(signal, 10, 500); +// Transmits signal 10 times with 500ms intervals +``` + +## Safety Features + +### Emergency Stop + +**Hardware Button**: GPIO_NUM_0 (configurable) +- Immediately stops all transmission +- Disables research mode +- Logged for compliance + +**How to Use**: +- Press and hold emergency stop button +- All RF transmission ceases immediately +- System returns to safe state + +### Transmission Limits + +1. **Duration Limits**: + - Maximum 5 seconds per transmission (default) + - Configurable in config.h + - Automatic cutoff if exceeded + +2. **Timeout Protection**: + - Research mode auto-disables after 5 minutes + - Prevents accidental extended operation + - Must be re-enabled explicitly + +3. **Safety Checks**: + - Pre-transmission validation + - Emergency stop monitoring + - Feature flag verification + - Disclaimer acceptance required + +### Usage Logging + +All advanced feature usage is logged to serial console: +- Timestamp +- Feature used +- Duration +- Result + +**Purpose**: Compliance documentation and audit trail + +## Best Practices + +### For Educational Use + +1. **Start with Basics**: + - Learn standard capture/replay first + - Understand RF fundamentals + - Read documentation thoroughly + +2. **Use Own Devices**: + - Test only on devices you own + - Use dedicated test equipment + - Avoid interference with others + +3. **Document Learning**: + - Take notes on observations + - Save analysis results + - Share knowledge responsibly + +4. **Respect Privacy**: + - Don't capture others' signals + - Delete accidental captures + - Maintain ethical standards + +### For Security Research + +1. **Get Authorization**: + - Written permission required + - Document scope of research + - Maintain compliance records + +2. **Controlled Environment**: + - Use RF shielded enclosures when possible + - Minimize interference potential + - Follow research protocols + +3. **Responsible Disclosure**: + - Report vulnerabilities properly + - Give vendors time to fix + - Follow coordinated disclosure + +4. **Professional Standards**: + - Maintain research ethics + - Document methodology + - Peer review when possible + +### Safety Guidelines + +1. **Know the Law**: + - Research local RF regulations + - Understand FCC rules (USA) + - Comply with all requirements + +2. **Minimize Transmission**: + - Use lowest power necessary + - Shortest duration possible + - Monitor spectrum for conflicts + +3. **Have Backups**: + - Test in safe environments first + - Have emergency procedures + - Know how to quickly stop + +4. **Stay Informed**: + - Keep firmware updated + - Follow project updates + - Learn from community + +## Technical Details + +### API Reference + +See individual header files: +- `include/rolling_code_analyzer.h` +- `include/signal_intelligence.h` +- `include/advanced_tx.h` +- `include/rf_research.h` + +### Serial Output + +All analysis results and warnings appear on serial console at 115200 baud. + +### Data Format + +Analysis exports use human-readable text format with clear sections. + +## Troubleshooting + +### Features Disabled + +**Problem**: Advanced features show "disabled" message +**Solution**: Check feature flags in `config.h` + +### No Legal Warning + +**Problem**: Can't access RF research tools +**Solution**: Must accept legal disclaimer first from main menu + +### Emergency Stop Not Working + +**Problem**: Emergency stop button doesn't respond +**Solution**: Check GPIO configuration, verify button connection + +### Compilation Errors + +**Problem**: Build fails with advanced features +**Solution**: Ensure all header files included, check feature flags + +## Further Reading + +- [ROLLING_CODES.md](ROLLING_CODES.md) - Rolling code systems explained +- [RF_SECURITY.md](RF_SECURITY.md) - RF security research guide +- [LEGAL_DISCLAIMER.md](LEGAL_DISCLAIMER.md) - Complete legal warnings +- [FAQ.md](FAQ.md) - Frequently asked questions + +## Support + +For questions about advanced features: +1. Read this documentation thoroughly +2. Check FAQ.md +3. Search GitHub issues +4. Create new issue with details + +**Remember**: These are powerful tools. Use them wisely, legally, and ethically. + +--- + +**Final Warning**: The developers provide these tools for education. YOU are responsible for how you use them. Know the law. Get authorization. Stay ethical. 🛡️ diff --git a/FAQ.md b/FAQ.md index 430d93a..3c4c87e 100644 --- a/FAQ.md +++ b/FAQ.md @@ -375,6 +375,253 @@ Currently, there's no official commercial support. The project is community-driv - Contributing funding for specific features - Providing sponsorship to maintainers +## Advanced Research Features + +### What are the advanced research features? + +Version 1.1+ includes educational tools for RF security research: +- **Rolling Code Analyzer**: Study rolling code systems +- **Signal Intelligence**: Advanced protocol identification +- **Advanced TX**: Sophisticated transmission testing +- **RF Research Tools**: Educational demonstrations (disabled by default) + +See [ADVANCED_FEATURES.md](ADVANCED_FEATURES.md) for complete documentation. + +### Are these features legal to use? + +The features themselves are legal, but **HOW you use them matters**: + +✅ **Legal uses**: +- Analyzing your own devices +- Authorized security research +- Educational learning +- Professional penetration testing (with permission) + +❌ **Illegal uses**: +- Accessing systems you don't own +- RF jamming or interference +- Bypassing security without permission +- Violating FCC regulations + +**Always read [LEGAL_DISCLAIMER.md](LEGAL_DISCLAIMER.md) before using advanced features.** + +### Can I break rolling codes with this? + +**No.** The rolling code analyzer is educational only. It teaches: +- How rolling codes work +- Why simple replay doesn't work +- Protocol structures +- Cryptographic principles + +Modern rolling codes (KeeLoq, HCS) use encryption that cannot be broken with these tools. The analyzer demonstrates WHY they're secure. + +See [ROLLING_CODES.md](ROLLING_CODES.md) for detailed explanation. + +### Is the RF jamming feature real? + +**No.** The RF research tools provide **educational demonstrations only**. The actual harmful functionality is disabled for safety and legal compliance. + +These features teach about: +- RF vulnerabilities (theoretical) +- Why jamming is dangerous +- Defensive countermeasures +- Legal consequences + +**Real jamming is a federal crime with severe penalties.** + +### How do I enable advanced features? + +1. Navigate to main menu +2. Select "7. Advanced Research" +3. Read and accept legal warning +4. Choose desired feature + +Some features require activation in `config.h`: +```cpp +#define ENABLE_ROLLING_CODE_ANALYSIS 1 +#define ENABLE_SIGNAL_INTELLIGENCE 1 +#define ENABLE_ADVANCED_TX 1 +#define ENABLE_RF_RESEARCH 0 // Disabled by default +``` + +### What safety features are included? + +Multiple safety mechanisms: +- **Emergency stop button** (GPIO_NUM_0) +- **Transmission duration limits** (5 seconds default) +- **Automatic timeouts** (5 minutes for research mode) +- **Feature flags** (enable/disable at compile time) +- **Usage logging** (audit trail) +- **Legal warnings** (must accept before use) + +### Can I use these for penetration testing? + +**Only with proper authorization**: +- Written permission from system owner +- Clear scope definition +- Professional contract or engagement letter +- Compliance with all laws +- Liability insurance recommended + +See [RF_SECURITY.md](RF_SECURITY.md) for responsible research guidelines. + +### What if I accidentally do something illegal? + +**Immediately**: +1. Stop the activity +2. Document what occurred +3. Consult legal counsel +4. Consider voluntary disclosure +5. Don't attempt to cover it up + +**Prevention is better**: +- Read documentation thoroughly +- Get authorization before testing +- When in doubt, don't do it +- Consult legal counsel proactively + +### Where can I learn more about RF security? + +**Documentation**: +- [ADVANCED_FEATURES.md](ADVANCED_FEATURES.md) - Feature documentation +- [ROLLING_CODES.md](ROLLING_CODES.md) - Rolling code explanation +- [RF_SECURITY.md](RF_SECURITY.md) - Security research guide +- [LEGAL_DISCLAIMER.md](LEGAL_DISCLAIMER.md) - Legal warnings + +**External Resources**: +- Academic papers on RF security +- DEFCON/Black Hat conference talks +- Security research blogs +- Professional training courses + +### How can I contribute to RF security research? + +**Responsibly**: +- ✅ Learn the fundamentals +- ✅ Practice on your own devices +- ✅ Share knowledge ethically +- ✅ Follow responsible disclosure +- ✅ Contribute to open source +- ✅ Help improve security for everyone + +**Not this way**: +- ❌ Attacking others' systems +- ❌ Publishing weaponized exploits +- ❌ Enabling script kiddies +- ❌ Seeking fame through harm +- ❌ Violating ethical standards + +### What's the difference between gray hat and black hat? + +**White Hat** (Ethical): +- Authorized testing only +- Responsible disclosure +- Follows laws and ethics +- Improves security + +**Gray Hat** (Questionable): +- Unauthorized testing "for good" +- Public disclosure without coordination +- Legal gray areas +- Mixed motivations + +**Black Hat** (Criminal): +- Malicious intent +- Unauthorized access +- Criminal activity +- Causes harm + +**Always be white hat. It's the only legally and ethically defensible position.** + +### Can I use this for my security research thesis? + +Yes, with caveats: +- Get IRB/ethics committee approval +- Use only authorized test equipment +- Follow academic integrity standards +- Coordinate with advisor +- Document methodology carefully +- Consider responsible disclosure implications + +The firmware can be excellent for educational research on: +- Protocol analysis +- RF security mechanisms +- Cryptographic implementations +- Security system design + +### What should I do if I discover a vulnerability? + +**Follow responsible disclosure**: + +1. **Don't exploit it** beyond proof-of-concept +2. **Document thoroughly** (methodology, impact) +3. **Contact vendor** through security contact +4. **Give time to fix** (typically 90 days) +5. **Coordinate disclosure** date +6. **Publish responsibly** with remediation guidance + +See detailed process in [RF_SECURITY.md](RF_SECURITY.md). + +## Responsible Disclosure + +### How do I report a vulnerability I found? + +1. **Gather information**: + - Affected product/version + - Vulnerability details + - Proof of concept (if safe) + - Impact assessment + +2. **Contact vendor**: + - Use security@ email or security portal + - Request secure communication + - Provide summary (not full details initially) + - Propose disclosure timeline + +3. **Work together**: + - Provide additional info as needed + - Test proposed fixes + - Coordinate public disclosure + - Credit appropriately + +4. **Public disclosure**: + - After fix is available + - Or after reasonable timeline (90+ days) + - Include remediation guidance + - Be professional and factual + +### What if a vendor doesn't respond? + +**Try escalation**: +- Alternative contacts (security team, executives) +- CERT/CC or national CERT +- Industry organizations +- Public notification (last resort) + +**Timeline**: +- 7 days: Initial response expected +- 30 days: Acknowledgment and plan +- 90 days: Fix or disclosure +- 120 days: Extended timeline for complex fixes + +### Should I disclose publicly even without a fix? + +**Consider carefully**: + +**Yes if**: +- Active exploitation occurring +- Critical infrastructure at risk +- Vendor unresponsive after reasonable time +- Public interest outweighs risks + +**No if**: +- Vendor working on fix in good faith +- More time likely to result in solution +- Disclosure would cause disproportionate harm +- Legal restrictions apply + +**When in doubt, consult CERT/CC or similar coordination center.** + ## Still Have Questions? If your question isn't answered here: diff --git a/LEGAL_DISCLAIMER.md b/LEGAL_DISCLAIMER.md new file mode 100644 index 0000000..f2ac68a --- /dev/null +++ b/LEGAL_DISCLAIMER.md @@ -0,0 +1,427 @@ +# LEGAL DISCLAIMER + +**READ THIS ENTIRE DOCUMENT BEFORE USING ADVANCED RF RESEARCH FEATURES** + +## CRITICAL LEGAL NOTICE + +This firmware contains advanced RF security research features that are potentially **ILLEGAL** to use without proper authorization. By using these features, you accept **FULL LEGAL RESPONSIBILITY** for your actions. + +--- + +## ⚠️ MANDATORY WARNINGS ⚠️ + +### 1. EDUCATIONAL PURPOSE ONLY + +The advanced features in this firmware are provided **EXCLUSIVELY** for: + +✅ **Authorized Uses**: +- Educational purposes and learning +- Security research on devices you own +- Understanding RF security concepts +- Authorized penetration testing with written permission +- Academic research with proper approval +- Professional security assessment under contract + +❌ **PROHIBITED Uses**: +- Accessing systems you don't own or control +- Interfering with any RF communications (JAMMING) +- Bypassing security mechanisms without authorization +- Unauthorized testing of products or systems +- Malicious purposes or harassment +- Any violation of local, state, federal, or international law + +### 2. RF JAMMING IS A FEDERAL CRIME + +**United States**: +- **47 U.S.C. § 333** - Willful or malicious interference with radio communications +- **Penalty**: Up to $112,500 per violation per day (civil) + criminal prosecution +- **Criminal Penalties**: Fines and/or imprisonment +- **Equipment Forfeiture**: Devices can be seized + +**Example Prohibited Activities**: +- Jamming cellular signals (911 calls, etc.) +- Interfering with WiFi networks +- Blocking GPS signals +- Disrupting emergency communications +- "Testing" jamming equipment on live systems + +**This Applies Even If**: +- "Just testing" +- "Only for a few seconds" +- "In my own home" +- "Nobody was using it" + +### 3. UNAUTHORIZED ACCESS IS ILLEGAL + +**Computer Fraud and Abuse Act (18 U.S.C. § 1030)**: +- Unauthorized access to protected computers +- Includes vehicle systems, IoT devices, smart locks +- Penalties: Fines and imprisonment + +**State Laws**: +- Additional state-level computer crime statutes +- Often more strict than federal law +- Can be prosecuted in addition to federal charges + +**Wiretap Laws (18 U.S.C. § 2511)**: +- Illegal to intercept electronic communications +- Applies to RF systems carrying data +- Severe penalties for violations + +--- + +## JURISDICTION-SPECIFIC WARNINGS + +### United States + +**Federal Communications Commission (FCC)**: +- Part 15 rules govern unlicensed devices +- Power limits strictly enforced +- Interference prohibited +- Equipment must be FCC certified for commercial use + +**State Laws**: +- May be more restrictive than federal +- Check your state's computer crime laws +- Some states have specific RF interference statutes + +**Professional Licensing**: +- Amateur radio licenses don't authorize security testing +- Commercial licenses required for certain activities +- Consult FCC regulations for your use case + +### European Union + +**Radio Equipment Directive (RED)**: +- Harmonized standards for RF devices +- CE marking requirements +- National frequency allocations + +**National Laws**: +- Computer Misuse Act (UK) +- Telecommunications laws (varies by country) +- GDPR privacy considerations + +### International + +**ITU Radio Regulations**: +- International frequency allocations +- Harmful interference prohibited +- National implementations vary + +**Export Controls**: +- Cryptographic tools may be export controlled +- ITAR, EAR regulations (USA) +- Check before international travel + +--- + +## SPECIFIC FEATURE WARNINGS + +### Rolling Code Analyzer + +**Legal Uses**: +- ✅ Analyzing your own remote controls +- ✅ Learning about rolling code security +- ✅ Educational demonstrations (own equipment) +- ✅ Authorized security research + +**Illegal Uses**: +- ❌ Attempting to break rolling codes for unauthorized access +- ❌ Bypassing vehicle security systems you don't own +- ❌ Garage door opener attacks +- ❌ Any unauthorized access attempts + +**Important**: The analyzer is designed to teach WHY rolling codes are secure, not to break them. Modern rolling codes use encryption that cannot be practically broken with these tools. + +### Signal Intelligence + +**Legal Uses**: +- ✅ Protocol analysis for compatibility +- ✅ Understanding signal characteristics +- ✅ Quality assessment of your systems +- ✅ Educational research + +**Illegal Uses**: +- ❌ Intercepting private communications +- ❌ Reverse engineering for unauthorized access +- ❌ Violating wiretap laws +- ❌ Privacy violations + +**Privacy Note**: Even receiving signals may be subject to privacy laws depending on content and intent. + +### Advanced Transmission Features + +**Legal Uses**: +- ✅ Testing your own devices in controlled environment +- ✅ Authorized penetration testing +- ✅ Academic research with approval +- ✅ Professional security assessment + +**Illegal Uses**: +- ❌ Any unauthorized transmissions +- ❌ Exceeding FCC power limits +- ❌ Transmitting without proper authorization +- ❌ Interfering with others' communications +- ❌ Signal injection attacks without permission + +**FCC Compliance**: Most transmissions require FCC equipment authorization. Testing must comply with Part 15 rules. + +### RF Research Tools + +**⚠️ DISABLED BY DEFAULT ⚠️** + +These features are **EDUCATIONAL DEMONSTRATIONS ONLY** and actual harmful functionality is disabled for safety and legal compliance. + +**Legal Uses**: +- ✅ Learning about RF vulnerabilities (theoretical) +- ✅ Understanding defensive measures +- ✅ Educational demonstrations (non-functional) +- ✅ Academic study of RF security + +**Illegal Uses**: +- ❌ Enabling actual jamming functionality +- ❌ Using for any interference +- ❌ Attempting to implement described attacks +- ❌ ANY real-world malicious use + +**Critical Note**: The firmware provides educational demonstrations of concepts. Implementing actual attacks is **YOUR responsibility** and doing so is **ILLEGAL**. + +--- + +## LIABILITY DISCLAIMER + +### No Warranty + +THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO: +- MERCHANTABILITY +- FITNESS FOR A PARTICULAR PURPOSE +- NON-INFRINGEMENT +- LEGAL COMPLIANCE + +### User Responsibility + +BY USING THIS SOFTWARE, YOU AGREE: + +1. **You are solely responsible** for compliance with all applicable laws +2. **You will obtain all necessary authorizations** before testing +3. **You understand the legal risks** of RF research +4. **You accept all legal liability** for your actions +5. **You will not hold developers liable** for any consequences + +### Developer Disclaimer + +THE DEVELOPERS: +- Provide this software for EDUCATIONAL purposes only +- Make NO representations about legal compliance +- Accept NO liability for user actions +- Do NOT endorse illegal activities +- WILL cooperate with law enforcement +- Strongly DISCOURAGE any illegal use + +### No Legal Advice + +NOTHING IN THIS FIRMWARE OR DOCUMENTATION CONSTITUTES LEGAL ADVICE. Consult a qualified attorney regarding: +- Compliance with local laws +- Authorization requirements +- Liability exposure +- Professional licensing + +--- + +## REQUIRED ACKNOWLEDGMENTS + +### Before Using Advanced Features + +YOU MUST: + +1. ✓ **Read and understand** this entire legal disclaimer +2. ✓ **Research applicable laws** in your jurisdiction +3. ✓ **Obtain written authorization** if testing others' systems +4. ✓ **Accept full legal responsibility** for your actions +5. ✓ **Understand the risks** including criminal prosecution + +### Acceptance of Terms + +**By using the advanced RF research features, you acknowledge:** + +- [ ] I have read this entire legal disclaimer +- [ ] I understand the legal risks and penalties +- [ ] I have researched laws in my jurisdiction +- [ ] I will only use features in authorized ways +- [ ] I accept full legal responsibility for my actions +- [ ] I understand developers accept no liability +- [ ] I will not use features for illegal purposes +- [ ] I understand this is not legal advice +- [ ] I agree to comply with all applicable laws + +**If you cannot check ALL boxes above, DO NOT USE advanced features.** + +--- + +## PROFESSIONAL GUIDANCE + +### When to Consult Professionals + +**Legal Counsel**: +- Before conducting security research +- When uncertain about authorization +- If receiving legal threats +- Before public disclosure + +**Technical Experts**: +- Professional penetration testers +- RF engineering consultants +- Security researchers with experience +- Academic advisors + +### Professional Certifications + +Consider obtaining: +- CEH (Certified Ethical Hacker) +- OSCP (Offensive Security Certified Professional) +- Amateur radio license (for basic RF knowledge) +- Professional liability insurance + +--- + +## CONSEQUENCES OF MISUSE + +### Criminal Penalties + +**Federal**: +- Fines up to $250,000 (individuals) +- Fines up to $500,000 (organizations) +- Imprisonment up to 10 years +- Both fines AND imprisonment possible + +**Additional**: +- Equipment seizure and forfeiture +- Restitution to victims +- Supervised release +- Criminal record + +### Civil Liability + +- Actual damages +- Statutory damages (up to $112,500/day for FCC violations) +- Punitive damages +- Attorney's fees and costs +- Injunctive relief + +### Professional Consequences + +- Loss of professional licenses +- Termination of employment +- Inability to work in security field +- Damage to reputation +- Civil lawsuits + +--- + +## REPORTING VIOLATIONS + +### If You Witness Misuse + +**Report to:** +- **FCC**: 1-888-CALL-FCC (1-888-225-5322) +- **FBI**: tips.fbi.gov or local field office +- **Local Law Enforcement**: 911 for active interference +- **Project Maintainers**: For firmware misuse concerns + +### If You Made a Mistake + +**Immediately**: +1. Stop the activity +2. Document what occurred +3. Consult legal counsel +4. Consider voluntary disclosure +5. Cooperate with authorities + +--- + +## UPDATES TO DISCLAIMER + +### Version History + +- **Version 1.0**: Initial disclaimer (December 2024) + +### Changes + +This disclaimer may be updated to reflect: +- Changes in law +- New features +- Court decisions +- Regulatory guidance + +### User Obligation + +**You are responsible for:** +- Checking for disclaimer updates +- Complying with current version +- Understanding changes +- Adjusting your practices accordingly + +--- + +## FINAL WARNINGS + +### DO NOT Proceed If: + +- ❌ You don't understand the legal risks +- ❌ You lack proper authorization +- ❌ You're uncertain about legality +- ❌ You plan to use features maliciously +- ❌ You can't accept full responsibility +- ❌ You're under 18 (consult parent/guardian) + +### DO Proceed If: + +- ✅ You have written authorization +- ✅ You understand and accept risks +- ✅ You comply with all laws +- ✅ You use features ethically +- ✅ You have proper expertise +- ✅ You've consulted legal counsel + +--- + +## ACKNOWLEDGMENT + +**By using advanced RF research features in this firmware, you acknowledge that:** + +You have read, understood, and agree to be bound by this legal disclaimer. You accept full legal responsibility for your actions. You understand the severe legal consequences of misuse. You will comply with all applicable laws. You release the developers from all liability. + +**IF YOU DO NOT AGREE, DO NOT USE THESE FEATURES.** + +--- + +## CONTACT FOR LEGAL CONCERNS + +**Project Maintainers**: See GitHub repository + +**Legal Inquiries**: Consult your own attorney + +**Law Enforcement**: Report violations to appropriate authorities + +--- + +**REMEMBER**: The law applies whether or not you read this disclaimer. Ignorance of the law is not a defense. When in doubt, don't do it. When in more doubt, consult an attorney. + +--- + +**Last Updated**: December 26, 2024 + +**Jurisdiction**: This software may be subject to laws in multiple jurisdictions depending on where it is used. Users are responsible for compliance with all applicable laws. + +**Severability**: If any provision of this disclaimer is found unenforceable, the remaining provisions remain in full effect. + +--- + +## 🛡️ FINAL WORD + +**USE RESPONSIBLY. USE LEGALLY. USE ETHICALLY.** + +Security research is important work. Done properly, it makes everyone safer. Done improperly, it can ruin lives - including your own. + +**Be smart. Be legal. Be ethical.** diff --git a/README.md b/README.md index f92a7c7..b558136 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,23 @@ A fully functional multi-protocol RF firmware for the LilyGO T-Embed CC1101 device. This firmware turns your T-Embed into a powerful "skeleton key" tool for analyzing, capturing, and replaying RF signals across multiple frequencies. +## ⚠️ NEW: Advanced RF Security Research Features + +**Version 1.1+** includes advanced educational tools for RF security research: + +- **Rolling Code Analyzer**: Study and understand rolling code security systems +- **Signal Intelligence**: Advanced protocol identification and signal analysis +- **Advanced Transmission**: Sophisticated transmission patterns for testing +- **RF Research Tools**: Educational demonstrations (disabled by default) + +**📚 Complete Documentation**: See [ADVANCED_FEATURES.md](ADVANCED_FEATURES.md) +**⚖️ Legal Notice**: Read [LEGAL_DISCLAIMER.md](LEGAL_DISCLAIMER.md) before using advanced features + +These features are for **EDUCATIONAL AND AUTHORIZED RESEARCH ONLY**. Misuse is illegal and can result in severe penalties. + ## Features +### Basic Features - **Multi-Frequency Support**: 315MHz, 433.92MHz, 868MHz, 915MHz - **Signal Capture**: Capture RF signals with timing analysis - **Signal Replay**: Transmit captured signals @@ -12,6 +27,21 @@ A fully functional multi-protocol RF firmware for the LilyGO T-Embed CC1101 devi - **TFT Display Interface**: Easy-to-use menu system - **Multiple Modulation Types**: ASK/OOK, 2FSK, 4FSK, MSK, GFSK +### Advanced Research Features (v1.1+) + +**⚠️ EDUCATIONAL AND AUTHORIZED USE ONLY ⚠️** + +- **Rolling Code Analysis**: Study rolling code security systems (KeeLoq, HCS) +- **Signal Intelligence**: Advanced protocol identification and analysis +- **Advanced Transmission**: Sophisticated transmission testing capabilities +- **RF Research Tools**: Educational demonstrations of RF vulnerabilities + +**Documentation**: +- [ADVANCED_FEATURES.md](ADVANCED_FEATURES.md) - Complete feature documentation +- [ROLLING_CODES.md](ROLLING_CODES.md) - Educational guide to rolling codes +- [RF_SECURITY.md](RF_SECURITY.md) - RF security research best practices +- [LEGAL_DISCLAIMER.md](LEGAL_DISCLAIMER.md) - Important legal information + ## Hardware This firmware is designed for the LilyGO T-Embed CC1101 which includes: @@ -87,6 +117,7 @@ Navigate using the UP/DOWN buttons and select with the SELECT button: 4. **Saved Signals** - Browse and manage saved signals 5. **Settings** - Configure device settings 6. **Info** - View firmware information +7. **🔬 Advanced Research** ⚠️ - Advanced RF security research features (Educational use only) ### Capturing Signals @@ -151,11 +182,46 @@ ultimatel-ily/ ⚠️ **IMPORTANT**: This tool is for educational and research purposes only. -- Always operate within legal frequency bands for your region -- Obtain proper authorization before analyzing or transmitting RF signals -- Do not use this device to intercept, interfere with, or disrupt wireless communications -- Be aware of local laws and regulations regarding RF devices -- The authors are not responsible for any misuse of this software +### Legal Uses +✅ Analyzing and testing **your own devices** +✅ Educational learning about RF systems +✅ Authorized security research with permission +✅ Professional penetration testing under contract + +### Illegal Uses +❌ Accessing systems you don't own or control +❌ RF jamming or interference (FEDERAL CRIME) +❌ Bypassing security without authorization +❌ Intercepting private communications + +### Regulations +- **Always operate within legal frequency bands** for your region +- **Obtain proper authorization** before analyzing or transmitting RF signals +- **Do not interfere** with wireless communications +- **FCC Part 15 regulations** apply in USA (penalties up to $112,500/day) +- **Be aware of local laws** and regulations regarding RF devices + +### Advanced Features Warning + +Version 1.1+ includes advanced RF security research features. **Read [LEGAL_DISCLAIMER.md](LEGAL_DISCLAIMER.md) before using them.** + +These features are for EDUCATIONAL purposes only. Misuse can result in: +- Criminal prosecution +- Heavy fines +- Equipment seizure +- Imprisonment + +**You assume ALL legal responsibility for your actions.** + +## Disclaimer + +THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY. The developers: +- Accept NO liability for misuse +- Do NOT endorse illegal activities +- Provide tools for EDUCATIONAL purposes only +- WILL cooperate with law enforcement + +**Use responsibly. Use legally. Use ethically.** ## Contributing diff --git a/RF_SECURITY.md b/RF_SECURITY.md new file mode 100644 index 0000000..b3b58aa --- /dev/null +++ b/RF_SECURITY.md @@ -0,0 +1,554 @@ +# RF Security Research Guide + +**A Comprehensive Guide to Ethical RF Security Research** + +This guide provides information on conducting RF security research ethically, legally, and effectively. + +## Table of Contents + +1. [Introduction to RF Security](#introduction-to-rf-security) +2. [Legal Framework](#legal-framework) +3. [Research Methodology](#research-methodology) +4. [Tools and Techniques](#tools-and-techniques) +5. [Responsible Disclosure](#responsible-disclosure) +6. [Best Practices](#best-practices) + +## Introduction to RF Security + +### What is RF Security Research? + +RF (Radio Frequency) security research involves analyzing wireless communication systems to: +- Identify vulnerabilities +- Understand protocols +- Improve security +- Educate users and developers + +### Why It Matters + +Wireless systems are everywhere: +- Automotive keyless entry +- Smart home devices +- Industrial controls +- Medical devices +- Critical infrastructure + +Security researchers help ensure these systems are safe. + +### Ethical Foundation + +**Core Principles**: +1. **Do No Harm**: Research should improve security, not enable attacks +2. **Respect Privacy**: Don't access others' systems without permission +3. **Responsible Disclosure**: Give vendors time to fix issues +4. **Legal Compliance**: Follow all applicable laws +5. **Professional Integrity**: Maintain high ethical standards + +## Legal Framework + +### United States + +#### FCC Regulations + +**Part 15 - Unlicensed Devices**: +- Rules for intentional radiators +- Power limits +- Frequency restrictions +- Interference prohibition + +**Key Sections**: +- §15.5: Interference prohibition +- §15.201: Equipment authorization +- §15.203: Antenna restrictions +- §15.205: Restricted frequency bands + +**Criminal Statutes**: +- 47 U.S.C. § 333: Willful interference (felony) +- 18 U.S.C. § 1030: Computer Fraud and Abuse Act +- 18 U.S.C. § 2511: Wiretap Act + +**Penalties**: +- Fines up to $112,500 per violation per day +- Equipment forfeiture +- Criminal prosecution +- Imprisonment + +#### Computer Fraud and Abuse Act (CFAA) + +Prohibits: +- Unauthorized access to protected computers +- Exceeding authorized access +- Trafficking in passwords +- Causing damage without authorization + +**Applies to**: +- RF systems connected to networks +- Vehicle computer systems +- IoT devices +- Smart home systems + +### International + +**European Union**: +- Radio Equipment Directive (RED) +- ETSI harmonized standards +- National telecom regulations + +**United Kingdom**: +- Wireless Telegraphy Act 2006 +- Computer Misuse Act 1990 +- Serious Crime Act 2007 + +**Other Jurisdictions**: +- ITU Radio Regulations (international) +- National telecommunications laws +- Local ordinances + +### Getting Legal Authorization + +**For Research Projects**: + +1. **Written Permission**: + - Get authorization from system owner + - Define scope clearly + - Specify what's allowed/forbidden + - Set time limits + - Document everything + +2. **Bug Bounty Programs**: + - Follow program rules exactly + - Stay within scope + - Report through proper channels + - Don't test without authorization + +3. **Academic Research**: + - Institutional Review Board (IRB) approval + - Ethics committee review + - Use own equipment for testing + - Coordinate with legal counsel + +4. **Professional Penetration Testing**: + - Statement of Work (SOW) + - Clear rules of engagement + - Liability insurance + - Professional certifications + +### What You CAN Do Legally + +✅ **Receive and Analyze**: +- Passive reception is generally legal +- Analyzing protocols (academic research) +- Capturing signals in public spaces +- Studying your own devices + +✅ **Authorized Testing**: +- Testing devices you own +- Contracted penetration testing +- Academic research with permission +- Bug bounty participation + +✅ **Educational Activities**: +- Teaching RF security concepts +- Demonstrating vulnerabilities (controlled) +- Writing security research papers +- Speaking at conferences + +### What You CANNOT Do + +❌ **Jamming/Interference**: +- Intentional interference with any communications +- Jamming cellular, WiFi, GPS, or any RF signals +- Disrupting emergency services +- "Testing" jamming equipment + +❌ **Unauthorized Access**: +- Opening vehicles you don't own +- Bypassing security systems without permission +- Accessing others' networks +- Intercepting private communications + +❌ **Malicious Activities**: +- Creating or distributing attack tools +- Selling exploits without disclosure +- Enabling others to commit crimes +- Harassment or stalking + +## Research Methodology + +### Phase 1: Planning + +1. **Define Objectives**: + - What are you researching? + - What's the expected outcome? + - How will this improve security? + +2. **Legal Review**: + - Is the research legal? + - Do you need authorization? + - What are the risks? + +3. **Ethical Consideration**: + - Could research harm anyone? + - How to minimize risks? + - Is disclosure plan in place? + +4. **Resource Planning**: + - Required equipment + - Budget + - Timeline + - Expertise needed + +### Phase 2: Information Gathering + +**Open Source Intelligence (OSINT)**: +- FCC database searches +- Patent research +- Academic papers +- Manufacturer documentation +- Online forums and communities + +**Protocol Research**: +- Published standards +- Reverse engineering (legal) +- Publicly available implementations +- Similar systems analysis + +### Phase 3: Controlled Testing + +**Test Environment Setup**: + +1. **RF Isolation**: + - Use Faraday cage when possible + - Minimize power to reduce range + - Test in remote areas + - Monitor for unintended interference + +2. **Equipment**: + - Calibrated test equipment + - Signal analyzers + - Proper antennas + - Recording equipment + +3. **Safety Measures**: + - Emergency stop procedures + - Spectrum monitoring + - Clear documentation + - Backup plans + +**Testing Approach**: +- Start passive (receive only) +- Progress to active testing carefully +- Document everything +- Stay within legal/authorized scope + +### Phase 4: Analysis + +**Data Analysis**: +- Protocol dissection +- Timing analysis +- Cryptographic analysis +- Vulnerability identification + +**Validation**: +- Reproduce findings +- Test different conditions +- Verify root causes +- Eliminate false positives + +### Phase 5: Documentation + +**Research Documentation**: +- Methodology +- Findings +- Evidence (captures, logs) +- Impact assessment +- Remediation recommendations + +**Responsible Disclosure**: +- Prepare disclosure report +- Include technical details +- Suggest fixes +- Provide timeline + +## Tools and Techniques + +### Hardware Tools + +**Software Defined Radio (SDR)**: +- HackRF One +- BladeRF +- LimeSDR +- RTL-SDR (receive only) + +**Purpose-Built Devices**: +- CC1101-based devices (like this project) +- Yard Stick One +- RFCat +- Ubertooth (Bluetooth) + +**Professional Equipment**: +- Spectrum analyzers +- Vector network analyzers +- Signal generators +- Oscilloscopes + +### Software Tools + +**Analysis**: +- GNU Radio +- Universal Radio Hacker (URH) +- Inspectrum +- Audacity (for signal visualization) + +**Protocol Analysis**: +- Wireshark (network) +- rtl_433 (many protocols) +- Fldigi (digital modes) + +**Development**: +- Arduino/PlatformIO +- Python with pySerial, numpy +- MATLAB/Octave + +### Techniques + +**Signal Analysis**: +1. Frequency identification +2. Modulation detection +3. Timing analysis +4. Protocol reverse engineering +5. Error detection + +**Security Testing**: +1. Replay attack testing +2. Injection testing +3. Fuzzing +4. Side-channel analysis +5. Brute force testing + +**Best Practices**: +- Document everything +- Use version control +- Maintain lab notebooks +- Reproducible methodology +- Peer review when possible + +## Responsible Disclosure + +### Why Responsible Disclosure Matters + +- Gives vendors time to fix issues +- Protects users from exploitation +- Maintains researcher credibility +- Encourages cooperation +- Improves overall security + +### Disclosure Process + +#### Step 1: Initial Contact + +- Use vendor security contact +- Provide brief overview +- Request secure communication channel +- Set disclosure timeline (usually 90 days) + +**Example Email**: +``` +Subject: Security Vulnerability Report - [Product Name] + +Hello, + +I am a security researcher and have identified a potential +vulnerability in [product]. I would like to work with your +security team to address this issue responsibly. + +Could you please provide: +1. Security team contact information +2. PGP key for encrypted communication +3. Preferred disclosure timeline + +I am following a standard 90-day disclosure timeline. + +Best regards, +[Your Name] +``` + +#### Step 2: Detailed Report + +**Include**: +- Vulnerability description +- Impact assessment +- Steps to reproduce +- Proof of concept (if safe) +- Suggested remediation +- Any mitigating factors + +**Don't Include**: +- Full exploits (weaponized code) +- Instructions that enable attacks +- Unnecessary technical details + +#### Step 3: Coordination + +- Work with vendor on fix +- Provide additional information as needed +- Test proposed fixes +- Agree on disclosure date +- Coordinate public disclosure + +#### Step 4: Public Disclosure + +**After Fix is Available**: +- Publish findings +- Credit vendor for cooperation +- Provide remediation steps for users +- Present at conferences +- Publish academic papers + +### Disclosure Timelines + +**Standard**: 90 days +- Most common +- Balances vendor time vs. user risk +- Extendable if good progress + +**Expedited**: 7-30 days +- For actively exploited vulnerabilities +- Critical infrastructure +- Widespread systems + +**Extended**: 120+ days +- Complex fixes +- Hardware changes needed +- Multiple coordinated vendors + +### When Vendors Don't Respond + +**Escalation Steps**: +1. Try alternative contacts +2. Contact CERT/CC or similar +3. Notify affected parties +4. Public disclosure (last resort) + +**Full Disclosure Considerations**: +- Only after reasonable attempts +- Weigh public interest +- Consider user impact +- Document all attempts + +## Best Practices + +### Research Ethics + +1. **Minimize Harm**: + - Test in controlled environments + - Don't disrupt real systems + - Consider collateral damage + - Have rollback plans + +2. **Respect Privacy**: + - Don't intercept private communications + - Delete accidental captures + - Anonymize research data + - Follow privacy laws + +3. **Professional Conduct**: + - Be honest about findings + - Don't exaggerate impact + - Give proper credit + - Maintain confidentiality + +4. **Continuous Learning**: + - Stay current with law + - Learn new techniques + - Share knowledge responsibly + - Mentor others + +### Safety Practices + +**RF Safety**: +- Understand power levels +- Use appropriate shielding +- Monitor for interference +- Have emergency stops + +**Legal Safety**: +- Get written authorization +- Document everything +- Consult legal counsel +- Maintain liability insurance + +**Operational Safety**: +- Don't test on live systems +- Have backups +- Test in stages +- Know your limits + +### Community Engagement + +**Positive Contributions**: +- Share knowledge via blogs, papers +- Present at conferences +- Contribute to open source +- Mentor new researchers +- Participate in responsible disclosure + +**Avoid**: +- Showing off exploits +- Enabling script kiddies +- Selling 0-days +- Irresponsible disclosure +- Drama and controversy + +## Resources + +### Organizations + +- CERT/CC (Computer Emergency Response Team) +- HackerOne, Bugcrowd (bug bounties) +- IEEE, ACM (professional societies) +- DEFCON, Black Hat (conferences) + +### Learning + +- SANS Institute courses +- Offensive Security certifications +- Academic programs in security +- Online courses (Coursera, Udacity) + +### Legal Resources + +- EFF (Electronic Frontier Foundation) +- Local bar associations +- Technology law firms +- Academic legal clinics + +### Communities + +- Security conferences +- Local hacker spaces +- Online forums (responsibly) +- Research groups + +## Conclusion + +RF security research is important work that requires: +- **Technical skill** to identify vulnerabilities +- **Legal knowledge** to stay compliant +- **Ethical judgment** to do the right thing +- **Professional integrity** to handle findings responsibly + +### Key Principles + +1. **Always get authorization** before testing systems you don't own +2. **Follow the law** in your jurisdiction +3. **Use responsible disclosure** to improve security +4. **Minimize harm** in all research activities +5. **Share knowledge** to advance the field + +### Remember + +The goal of security research is to make systems **more secure**, not to enable attacks. Your work can help protect millions of users - use your skills wisely. + +--- + +**"With great power comes great responsibility"** - this is especially true in security research. Be ethical. Be legal. Be professional. 🛡️ diff --git a/ROLLING_CODES.md b/ROLLING_CODES.md new file mode 100644 index 0000000..dcb7d03 --- /dev/null +++ b/ROLLING_CODES.md @@ -0,0 +1,460 @@ +# Rolling Code Systems - Educational Guide + +**Understanding RF Security Through Rolling Codes** + +This document provides an educational explanation of rolling code systems, how they work, why they're secure, and what security researchers should understand about them. + +## Table of Contents + +1. [Introduction](#introduction) +2. [The Problem with Fixed Codes](#the-problem-with-fixed-codes) +3. [How Rolling Codes Work](#how-rolling-codes-work) +4. [Common Rolling Code Protocols](#common-rolling-code-protocols) +5. [Security Analysis](#security-analysis) +6. [Why Replay Attacks Don't Work](#why-replay-attacks-dont-work) +7. [Research and Educational Value](#research-and-educational-value) + +## Introduction + +Rolling codes (also called hopping codes or dynamic codes) are a cryptographic security mechanism used in modern RF access control systems like: + +- Car remote keyless entry (RKE) +- Garage door openers (post-1990s) +- Home security systems +- Industrial access control +- Modern alarm systems + +### Purpose + +Rolling codes prevent **replay attacks** - a simple but effective attack where an attacker captures an RF transmission and replays it later to gain unauthorized access. + +## The Problem with Fixed Codes + +### Fixed Code Systems + +Early RF remote systems used **fixed codes** - a static identifier transmitted every time: + +``` +Remote: "Hey, I'm remote #12345" +Receiver: "I recognize #12345, opening door" +``` + +### The Vulnerability + +Anyone with an RF receiver can: +1. Capture the transmission +2. Replay it later +3. Gain unauthorized access + +This is trivial to exploit and why fixed codes are insecure for access control. + +### Historical Context + +- **Pre-1990**: Most systems used fixed codes +- **1990s**: Rolling codes introduced +- **Today**: Rolling codes standard for security-critical applications + +## How Rolling Codes Work + +### Basic Principle + +Instead of sending the same code every time, rolling code systems generate a **new code for each transmission**: + +``` +Button Press #1: Code A +Button Press #2: Code B +Button Press #3: Code C +(Each code is used only once) +``` + +### Synchronization + +The transmitter and receiver stay synchronized using: + +1. **Shared Secret Key**: Known only to paired devices +2. **Counter**: Increments with each use +3. **Encryption Algorithm**: Generates unique codes + +### Typical Flow + +``` +Transmitter Side: +1. User presses button +2. Counter increments: N → N+1 +3. Encrypt(Secret_Key, Counter, Serial_Number) → Code +4. Transmit Code + +Receiver Side: +1. Receive Code +2. Decrypt(Code) → Counter, Serial_Number +3. Verify Serial_Number matches +4. Check Counter > Last_Seen_Counter +5. If valid: Grant access, update Last_Seen_Counter +``` + +### Synchronization Window + +Receivers typically accept codes within a window: +- Current counter: N +- Accept range: N to N+256 (typical) +- Prevents desynchronization from accidental button presses + +## Common Rolling Code Protocols + +### 1. KeeLoq + +**Developer**: Microchip Technology +**Introduced**: 1980s +**Use**: Automotive, garage doors, security systems + +**Characteristics**: +- 64-bit block cipher +- 32-bit encrypted payload +- 28-bit serial number +- Counter-based +- Proprietary algorithm (reverse-engineered) + +**Packet Structure**: +``` +| Encrypted (32 bits) | Serial Number (28 bits) | Function (4 bits) | +| Counter (16) | Discrim (4) | Button/Seed (12) | 28-bit ID | Buttons | +``` + +**Security Status**: +- Original implementation had vulnerabilities +- Modern variants more secure +- Still widely used +- Considered adequate for most applications + +### 2. HCS (High-Security Code Hopping) + +**Developer**: Microchip Technology +**Family**: HCS200, HCS300, HCS301, etc. + +**Improvements over basic KeeLoq**: +- Enhanced encryption +- Better counter management +- Anti-scan features +- Seed diversity + +**Applications**: +- Automotive keyless entry +- Secure access control +- High-value targets + +### 3. Hitag + +**Developer**: NXP Semiconductors (formerly Philips) +**Use**: Automotive immobilizers, access control + +**Variants**: +- Hitag1 (obsolete, broken) +- Hitag2 (widely used, some vulnerabilities) +- Hitag3/AES (current, secure) + +**Note**: Hitag typically operates at 125 kHz (LF), not sub-GHz + +### 4. Modern Implementations + +**Current Best Practices**: +- AES-128 encryption (automotive) +- Challenge-response authentication +- Time-based codes +- Multi-factor authentication +- Secure element storage + +## Security Analysis + +### Strengths + +1. **Prevents Simple Replay**: + - Each code valid only once + - Old codes rejected + - Attacker can't reuse captured transmission + +2. **Counter Verification**: + - Codes must be sequential + - Large jumps may be rejected + - Prevents brute force of counter space + +3. **Encryption**: + - Secret key never transmitted + - Code appears random without key + - Difficult to predict next code + +4. **Serial Number Binding**: + - Code tied to specific transmitter + - Can't use code from different device + +### Weaknesses and Attacks + +#### 1. Code Grabbing Attack + +**Concept**: Capture code before legitimate receiver + +``` +Scenario: +1. User presses button +2. Attacker captures code (blocks legitimate reception) +3. Legitimate receiver never sees code +4. Attacker can use code once +``` + +**Mitigation**: +- Limited by range +- Code expires quickly +- Requires precise timing +- User notices access doesn't work + +#### 2. Replay and Resync Attack + +**Concept**: Force desynchronization, replay old code + +**Mitigation**: +- Resync procedures secured +- Limited acceptance window +- Multiple verifications + +#### 3. Cryptanalysis + +**KeeLoq Example**: +- Algorithm reverse-engineered +- Slide attacks demonstrated +- Takes significant time/resources +- Not practical for casual attacks + +**Modern Protocols**: +- Use standard algorithms (AES) +- Extensively peer-reviewed +- No known practical breaks + +#### 4. Side-Channel Attacks + +**Power Analysis**: +- Measure power consumption during encryption +- Can reveal secret key +- Requires physical access +- Complex analysis + +**Timing Attacks**: +- Analyze encryption timing +- Reveal key bits +- Hardware countermeasures exist + +### Security Considerations + +**For Manufacturers**: +- Use proven encryption (AES) +- Implement proper counter management +- Secure key generation and storage +- Regular security audits +- Stay current with research + +**For Users**: +- Keep firmware updated +- Use additional security (two-factor) +- Monitor for unusual activity +- Don't assume RF alone is sufficient + +## Why Replay Attacks Don't Work + +### Simple Replay + +``` +❌ DOESN'T WORK: +1. Capture transmission: Code_N +2. Replay Code_N later +3. Receiver: "Code_N already used, rejected" +``` + +### Why the Analyzer Can't Predict + +**Common Misconception**: "If I capture enough codes, I can predict the next one" + +**Reality**: +``` +Captured Codes: [Code_1, Code_2, Code_3, ...] + +Without Secret Key: +- Codes appear random +- No discernible pattern +- Counter value encrypted +- Prediction impossible + +With Secret Key (not transmitted): +- Could generate valid codes +- But that's called "having the key" +- Not breaking the system +``` + +### Cryptographic Security + +Rolling codes rely on **computational security**: +- Breaking encryption takes more time/resources than value gained +- Modern algorithms (AES-128) secure against brute force +- 2^128 possible keys = computational infeasible + +## Research and Educational Value + +### What Researchers Can Learn + +1. **Protocol Analysis**: + - Packet structure + - Timing characteristics + - Modulation schemes + - Error handling + +2. **Implementation Flaws**: + - Weak random number generators + - Poor key management + - Timing vulnerabilities + - Side channels + +3. **System Design**: + - How to implement security + - Common pitfalls + - Best practices + - Defense in depth + +### Responsible Research + +**Ethical Guidelines**: +- ✅ Study your own devices +- ✅ Analyze publicly documented protocols +- ✅ Contribute to security knowledge +- ✅ Responsible disclosure of vulnerabilities +- ❌ Don't attack others' systems +- ❌ Don't enable unauthorized access +- ❌ Don't publish full exploits without responsible disclosure + +### Educational Goals + +The rolling code analyzer in this firmware teaches: + +1. **Why Simple Replay Doesn't Work**: + - Hands-on demonstration + - See codes change each time + - Understand counter progression + +2. **Protocol Identification**: + - Recognize different systems + - Understand packet structures + - Analyze timing patterns + +3. **Cryptographic Principles**: + - Entropy in encrypted data + - Importance of secret keys + - Counter-based security + +4. **Security Design**: + - How proper security works + - Why old systems were vulnerable + - Modern improvements + +### Using the Analyzer Ethically + +**Good Uses**: +- Analyze YOUR OWN remote controls +- Learn protocol structures +- Understand why rolling codes work +- Educational demonstrations +- Security research on authorized systems + +**Bad Uses**: +- ❌ Attempting to break others' systems +- ❌ Attacking vehicles or buildings +- ❌ Unauthorized access attempts +- ❌ Malicious research + +## Advanced Topics + +### Counter Management + +**Challenges**: +- Accidental button presses (counter advances) +- Battery replacement (counter reset?) +- Multiple transmitters (same counter space?) + +**Solutions**: +- Wide acceptance window +- Resynchronization procedures +- Separate counter spaces per transmitter + +### Key Diversification + +**Problem**: Factory master key compromise + +**Solution**: +- Unique key per device +- Derived from master + serial number +- Master key not stored in devices + +### Anti-Scan Features + +**Jam Detection**: +- Monitor for interference +- Delay acceptance during jamming +- Alert user to attacks + +**Code Freshness**: +- Timestamp-based expiration +- Very short validity window +- Prevents code grabbing + +### Future Developments + +**Trends**: +- Move to smartphone-based access +- Bluetooth Low Energy (BLE) +- Ultra-Wideband (UWB) for cars +- Biometric integration +- Continuous authentication + +## Conclusion + +Rolling codes represent an important evolution in RF security: + +1. **Effective Against Simple Attacks**: Prevent replay attacks that plagued fixed codes +2. **Not Perfect**: Vulnerabilities exist, especially in older implementations +3. **Constantly Evolving**: New protocols address discovered weaknesses +4. **Educational Value**: Excellent example of practical cryptography + +### Key Takeaways + +- **Fixed codes are insecure** for access control +- **Rolling codes use encryption and counters** to prevent replay +- **Modern implementations are secure** when properly designed +- **Research helps improve security** for everyone +- **Ethical research is essential** to progress + +### For Security Researchers + +Study rolling codes to: +- Understand real-world cryptographic implementations +- Learn about security system design +- Identify and responsibly disclose vulnerabilities +- Contribute to safer systems for everyone + +**Always remember**: The goal of security research is to make systems more secure, not to enable attacks. + +## References + +### Academic Papers + +- "Cryptanalysis of the KeeLoq Block Cipher" (2008) +- "Gone in 360 Seconds: Hijacking with Hitag2" (2012) +- Various automotive security conferences + +### Standards + +- ISO 14443 (Contactless cards) +- SAE J2945 (V2X security) + +### Further Reading + +- [RF_SECURITY.md](RF_SECURITY.md) - General RF security guide +- [ADVANCED_FEATURES.md](ADVANCED_FEATURES.md) - Using the analyzer + +--- + +**Remember**: This knowledge is powerful. Use it to learn, to teach, and to make systems more secure - never to harm others or bypass security without authorization. 🔒 diff --git a/include/advanced_tx.h b/include/advanced_tx.h new file mode 100644 index 0000000..d406039 --- /dev/null +++ b/include/advanced_tx.h @@ -0,0 +1,67 @@ +#ifndef ADVANCED_TX_H +#define ADVANCED_TX_H + +#include +#include "rf_signal.h" +#include "rf_module.h" + +/** + * Advanced Transmission Features + * + * EDUCATIONAL AND RESEARCH PURPOSES ONLY + * + * Provides advanced RF transmission capabilities for security research + * and testing on authorized systems only. + * + * WARNING: Many features are regulated and may be illegal without + * proper authorization. User assumes all legal responsibility. + */ +class AdvancedTx { +public: + AdvancedTx(RFModule* rfModule); + + // Frequency sweeping (for testing/research) + void sweepFrequencies(float startFreq, float endFreq, float step, uint32_t dwellTime); + + // Continuous wave transmission (CW mode) + void transmitCW(float frequency, uint32_t durationMs); + + // Signal injection at precise timing + void transmitAtTime(const RFSignal& signal, uint32_t delayMs); + + // Protocol fuzzing (randomized testing) + void fuzzProtocol(const RFSignal& baseSignal, uint32_t iterations); + + // Replay with variations + void replayWithTimingVariation(const RFSignal& signal, float variation); + void replayWithAmplitudeVariation(const RFSignal& signal, int8_t powerDbm); + + // Multi-burst transmission patterns + void transmitBurst(const RFSignal& signal, uint32_t count, uint32_t interval); + void transmitPattern(const RFSignal& signal, const uint32_t* pattern, size_t patternLength); + + // Emergency stop + void emergencyStop(); + bool isTransmitting() const; + + // Safety checks + bool checkTransmissionSafe(uint32_t durationMs); + void setMaxDuration(uint32_t maxMs); + uint32_t getMaxDuration() const; + + // Get legal warning + static String getLegalWarning(); + +private: + RFModule* rf; + bool transmitting; + uint32_t maxTxDuration; + unsigned long txStartTime; + + // Safety checks + void checkSafetyLimits(uint32_t durationMs); + void startTransmission(); + void stopTransmission(); +}; + +#endif // ADVANCED_TX_H diff --git a/include/config.h b/include/config.h index d5e9266..24508b6 100644 --- a/include/config.h +++ b/include/config.h @@ -48,4 +48,21 @@ #define FIRMWARE_VERSION "1.0.0" #define FIRMWARE_NAME "Ultimatel-ily" +// Advanced Research Feature Flags +// These features are for educational and authorized security research only +#define ENABLE_ROLLING_CODE_ANALYSIS 1 +#define ENABLE_SIGNAL_INTELLIGENCE 1 +#define ENABLE_ADVANCED_TX 1 +#define ENABLE_RF_RESEARCH 0 // Disabled by default, requires explicit user activation + +// Safety limits +#define MAX_TX_DURATION_MS 5000 +#define EMERGENCY_STOP_BUTTON GPIO_NUM_0 +#define MAX_SWEEP_DURATION_MS 10000 +#define MIN_PULSE_INTERVAL_MS 100 + +// Research mode settings +#define RESEARCH_MODE_TIMEOUT_MS 300000 // 5 minutes +#define REQUIRE_DISCLAIMER_ACCEPTANCE 1 + #endif // CONFIG_H diff --git a/include/display.h b/include/display.h index 4e8ba93..cd7e2a3 100644 --- a/include/display.h +++ b/include/display.h @@ -12,7 +12,12 @@ enum MenuState { MENU_SCAN, MENU_SAVED_SIGNALS, MENU_SETTINGS, - MENU_INFO + MENU_INFO, + MENU_ADVANCED_RESEARCH, + MENU_ROLLING_CODE, + MENU_SIGNAL_INTEL, + MENU_RF_RESEARCH, + MENU_LEGAL_WARNING }; class Display { @@ -31,6 +36,14 @@ class Display { void showSignalDetails(const RFSignal& signal); void setBacklight(uint8_t brightness); + // Advanced research screens + void showAdvancedResearchMenu(int selectedItem); + void showRollingCodeMenu(int selectedItem); + void showSignalIntelMenu(int selectedItem); + void showRFResearchMenu(int selectedItem); + void showLegalWarning(const String& warningText); + void showAnalysisResult(const String& result); + private: TFT_eSPI tft; MenuState currentState; diff --git a/include/rf_research.h b/include/rf_research.h new file mode 100644 index 0000000..e6900e3 --- /dev/null +++ b/include/rf_research.h @@ -0,0 +1,89 @@ +#ifndef RF_RESEARCH_H +#define RF_RESEARCH_H + +#include +#include "rf_module.h" +#include "config.h" + +/** + * RF Research Tools + * + * ⚠️ EDUCATIONAL PURPOSES ONLY - DISABLED BY DEFAULT ⚠️ + * + * WARNING: The features in this class are for educational RF security + * research ONLY and are ILLEGAL without proper authorization. + * + * These tools are designed to teach about RF vulnerabilities and + * countermeasures. They must ONLY be used: + * - On your own devices + * - In authorized security testing + * - In controlled lab environments + * - With proper legal authorization + * + * NEVER use these features: + * - Against unauthorized systems + * - To interfere with communications + * - For malicious purposes + * - In violation of local laws + * + * Jamming and unauthorized RF interference are FEDERAL CRIMES in most + * countries with severe penalties including fines and imprisonment. + * + * USER ASSUMES ALL LEGAL RESPONSIBILITY. + */ +class RFResearch { +public: + RFResearch(RFModule* rfModule); + + // Feature enable/disable (disabled by default) + void enableResearchMode(bool enable); + bool isResearchModeEnabled() const; + + // Legal disclaimer acceptance (required before use) + void acceptLegalDisclaimer(); + bool hasAcceptedDisclaimer() const; + + // EDUCATIONAL ONLY: Frequency sweep research + // Used to study RF spectrum and understand interference effects + void sweepJammer(float startFreq, float endFreq); + + // EDUCATIONAL ONLY: Continuous wave transmission + // Used to understand carrier wave behavior + void cwTransmit(float frequency, uint32_t durationMs); + + // EDUCATIONAL ONLY: Pulsed transmission research + // Used to study timing-based RF patterns + void pulseJammer(uint32_t onTimeMs, uint32_t offTimeMs, uint32_t durationMs); + + // EDUCATIONAL ONLY: Noise generation research + // Used to understand signal-to-noise ratios + void noiseGenerator(float frequency, uint32_t durationMs); + + // Emergency stop (kills all transmission immediately) + void emergencyStop(); + + // Safety features + bool checkEmergencyStop(); + uint32_t getRemainingTime() const; + + // Authorization check (public for UI access) + void checkAuthorization(); + + // Legal warnings + static String getLegalWarning(); + static String getDetailedWarning(); + +private: + RFModule* rf; + bool researchModeEnabled; + bool disclaimerAccepted; + bool transmitting; + unsigned long txStartTime; + uint32_t txMaxDuration; + + // Safety checks + bool performSafetyCheck(); + void logUsage(const String& feature); +}; + +#endif // RF_RESEARCH_H diff --git a/include/rolling_code_analyzer.h b/include/rolling_code_analyzer.h new file mode 100644 index 0000000..26a77cc --- /dev/null +++ b/include/rolling_code_analyzer.h @@ -0,0 +1,88 @@ +#ifndef ROLLING_CODE_ANALYZER_H +#define ROLLING_CODE_ANALYZER_H + +#include +#include +#include "rf_signal.h" + +// Rolling code protocol types +enum RollingCodeProtocol { + PROTOCOL_KEELOQ, + PROTOCOL_HCS, + PROTOCOL_HITAG, + PROTOCOL_UNKNOWN_ROLLING +}; + +// Rolling code analysis result +struct RollingCodeAnalysis { + RollingCodeProtocol protocol; + uint32_t counter; + uint32_t manufacturerId; + float entropy; + bool patternDetected; + String analysisReport; +}; + +/** + * Rolling Code Analyzer + * + * EDUCATIONAL AND RESEARCH PURPOSES ONLY + * + * This class provides tools for analyzing rolling code transmissions + * to understand their security mechanisms. It is designed for: + * - Learning about RF security + * - Understanding rolling code protocols + * - Security research on authorized devices only + * + * WARNING: Using this to access unauthorized systems is illegal. + * User assumes all legal responsibility. + */ +class RollingCodeAnalyzer { +public: + RollingCodeAnalyzer(); + + // Capture and store rolling code sequence + void captureSequence(const RFSignal& signal); + + // Analyze captured sequences for patterns + RollingCodeAnalysis analyzePattern(); + + // Protocol detection + bool detectKeeLoq(const RFSignal& signal); + bool detectHCS(const RFSignal& signal); + bool detectHitag(const RFSignal& signal); + + // Extract information (educational) + uint32_t extractCounter(const RFSignal& signal); + uint32_t extractManufacturerId(const RFSignal& signal); + + // Statistical analysis + float calculateEntropy(const uint8_t* data, size_t length); + bool detectRepeatingPattern(const uint8_t* data, size_t length); + + // Educational research (prediction study - does not work on real systems) + void predictNextCode(); // Educational demonstration only + + // Export analysis for research + String exportAnalysis(); + + // Get captured sequence count + size_t getSequenceCount() const; + + // Clear captured sequences + void clearSequences(); + + // Get legal warning + static String getLegalWarning(); + +private: + std::vector capturedSequences; + RollingCodeAnalysis lastAnalysis; + + // Helper functions + uint32_t extractBits(const uint8_t* data, size_t startBit, size_t numBits); + bool compareSequences(const RFSignal& sig1, const RFSignal& sig2); + String protocolToString(RollingCodeProtocol protocol); +}; + +#endif // ROLLING_CODE_ANALYZER_H diff --git a/include/signal_intelligence.h b/include/signal_intelligence.h new file mode 100644 index 0000000..d6219b2 --- /dev/null +++ b/include/signal_intelligence.h @@ -0,0 +1,91 @@ +#ifndef SIGNAL_INTELLIGENCE_H +#define SIGNAL_INTELLIGENCE_H + +#include +#include "rf_signal.h" + +// Signal encoding types +enum EncodingType { + ENCODING_MANCHESTER, + ENCODING_DIFFERENTIAL_MANCHESTER, + ENCODING_PWM, + ENCODING_PPM, + ENCODING_UNKNOWN +}; + +// Signal quality metrics +struct SignalQuality { + float snr; // Signal-to-noise ratio + float avgPulseWidth; + float pulseVariance; + bool cleanSignal; + String qualityReport; +}; + +// Protocol identification result +struct ProtocolInfo { + String protocolName; + ModulationType modulation; + EncodingType encoding; + float confidence; + uint32_t bitrate; + String description; +}; + +/** + * Signal Intelligence Module + * + * EDUCATIONAL AND RESEARCH PURPOSES ONLY + * + * Provides advanced signal analysis and protocol identification + * capabilities for RF security research and education. + */ +class SignalIntelligence { +public: + SignalIntelligence(); + + // Automatic protocol identification + ProtocolInfo autoIdentifyProtocol(const RFSignal& signal); + + // Modulation detection + ModulationType detectModulation(const RFSignal& signal); + + // Timing pattern recognition + EncodingType detectEncoding(const RFSignal& signal); + + // Bit extraction and decoding + std::vector extractBits(const RFSignal& signal); + String decodeBitstream(const std::vector& bits); + + // Manchester decoding + std::vector decodeManchesterBits(const RFSignal& signal); + std::vector decodeDifferentialManchesterBits(const RFSignal& signal); + + // Preamble and sync word detection + bool detectPreamble(const RFSignal& signal, uint32_t& preambleLength); + bool detectSyncWord(const RFSignal& signal, uint32_t& syncWord); + + // CRC validation + bool validateCRC(const uint8_t* data, size_t length, uint16_t crc); + uint16_t calculateCRC16(const uint8_t* data, size_t length); + + // Signal quality analysis + SignalQuality analyzeQuality(const RFSignal& signal); + + // Timing analysis + float calculateBitrate(const RFSignal& signal); + std::vector extractUniquePulseWidths(const RFSignal& signal); + + // Export analysis + String exportAnalysis(const ProtocolInfo& info, const SignalQuality& quality); + +private: + // Helper functions + float calculateMean(const std::vector& values); + float calculateVariance(const std::vector& values, float mean); + bool isPulseWidthConsistent(const std::vector& timings, float tolerance); + String modulationToString(ModulationType mod); + String encodingToString(EncodingType enc); +}; + +#endif // SIGNAL_INTELLIGENCE_H diff --git a/src/advanced_tx.cpp b/src/advanced_tx.cpp new file mode 100644 index 0000000..46d8caa --- /dev/null +++ b/src/advanced_tx.cpp @@ -0,0 +1,238 @@ +#include "advanced_tx.h" +#include "config.h" + +AdvancedTx::AdvancedTx(RFModule* rfModule) : rf(rfModule), transmitting(false), + maxTxDuration(MAX_TX_DURATION_MS), txStartTime(0) { +} + +void AdvancedTx::sweepFrequencies(float startFreq, float endFreq, float step, uint32_t dwellTime) { + Serial.println("⚠️ WARNING: Frequency sweep starting ⚠️"); + Serial.println("Educational/Research purposes only"); + + if (!checkTransmissionSafe(dwellTime * ((endFreq - startFreq) / step))) { + Serial.println("ERROR: Sweep duration exceeds safety limits"); + return; + } + + startTransmission(); + + for (float freq = startFreq; freq <= endFreq; freq += step) { + if (!transmitting) break; // Emergency stop check + + rf->setFrequency(freq); + delay(dwellTime); + + Serial.print("Sweep: "); + Serial.print(freq); + Serial.println(" MHz"); + } + + stopTransmission(); + Serial.println("Frequency sweep completed"); +} + +void AdvancedTx::transmitCW(float frequency, uint32_t durationMs) { + Serial.println("⚠️ WARNING: CW transmission starting ⚠️"); + + if (!checkTransmissionSafe(durationMs)) { + Serial.println("ERROR: Duration exceeds safety limits"); + return; + } + + startTransmission(); + + rf->setFrequency(frequency); + // Note: Actual CW transmission would require CC1101 to be set to continuous TX mode + // This is a placeholder for the concept + + Serial.println("CW transmission active..."); + delay(durationMs); + + stopTransmission(); + Serial.println("CW transmission stopped"); +} + +void AdvancedTx::transmitAtTime(const RFSignal& signal, uint32_t delayMs) { + Serial.println("Scheduling transmission..."); + + delay(delayMs); + + startTransmission(); + rf->transmitSignal(signal); + stopTransmission(); + + Serial.println("Timed transmission completed"); +} + +void AdvancedTx::fuzzProtocol(const RFSignal& baseSignal, uint32_t iterations) { + Serial.println("⚠️ Protocol fuzzing started ⚠️"); + Serial.println("Educational/Testing purposes only"); + + startTransmission(); + + for (uint32_t i = 0; i < iterations && transmitting; i++) { + RFSignal fuzzed = baseSignal; + + // Randomly modify timing values (fuzzing) + for (size_t j = 0; j < fuzzed.timings.size(); j++) { + // Add random variation (-20% to +20%) + int32_t variation = (random(-20, 21) * fuzzed.timings[j]) / 100; + fuzzed.timings[j] += variation; + } + + rf->transmitSignal(fuzzed); + delay(100); + + if (i % 10 == 0) { + Serial.print("Fuzzing iteration: "); + Serial.println(i); + } + } + + stopTransmission(); + Serial.println("Protocol fuzzing completed"); +} + +void AdvancedTx::replayWithTimingVariation(const RFSignal& signal, float variation) { + Serial.println("Replaying with timing variation..."); + + RFSignal modified = signal; + + // Apply timing variation + for (size_t i = 0; i < modified.timings.size(); i++) { + int32_t adjust = (int32_t)(modified.timings[i] * variation); + modified.timings[i] += adjust; + } + + startTransmission(); + rf->transmitSignal(modified); + stopTransmission(); + + Serial.println("Replay with variation completed"); +} + +void AdvancedTx::replayWithAmplitudeVariation(const RFSignal& signal, int8_t powerDbm) { + Serial.println("Replaying with power variation..."); + Serial.print("Power: "); + Serial.print(powerDbm); + Serial.println(" dBm"); + + // Note: CC1101 power adjustment would be done here + // This is a placeholder - actual implementation requires CC1101 PA table configuration + + startTransmission(); + rf->transmitSignal(signal); + stopTransmission(); + + Serial.println("Replay with amplitude variation completed"); +} + +void AdvancedTx::transmitBurst(const RFSignal& signal, uint32_t count, uint32_t intervalMs) { + Serial.println("Burst transmission starting..."); + + if (!checkTransmissionSafe(count * intervalMs)) { + Serial.println("ERROR: Burst duration exceeds safety limits"); + return; + } + + startTransmission(); + + for (uint32_t i = 0; i < count && transmitting; i++) { + rf->transmitSignal(signal); + delay(intervalMs); + + Serial.print("Burst "); + Serial.print(i + 1); + Serial.print("/"); + Serial.println(count); + } + + stopTransmission(); + Serial.println("Burst transmission completed"); +} + +void AdvancedTx::transmitPattern(const RFSignal& signal, const uint32_t* pattern, size_t patternLength) { + Serial.println("Pattern transmission starting..."); + + startTransmission(); + + for (size_t i = 0; i < patternLength && transmitting; i++) { + rf->transmitSignal(signal); + delay(pattern[i]); + } + + stopTransmission(); + Serial.println("Pattern transmission completed"); +} + +void AdvancedTx::emergencyStop() { + transmitting = false; + stopTransmission(); + Serial.println("⚠️ EMERGENCY STOP ACTIVATED ⚠️"); +} + +bool AdvancedTx::isTransmitting() const { + return transmitting; +} + +bool AdvancedTx::checkTransmissionSafe(uint32_t durationMs) { + if (durationMs > maxTxDuration) { + Serial.println("ERROR: Transmission duration exceeds maximum allowed"); + return false; + } + + // Check emergency stop button + if (digitalRead(EMERGENCY_STOP_BUTTON) == LOW) { + Serial.println("ERROR: Emergency stop button pressed"); + return false; + } + + return true; +} + +void AdvancedTx::setMaxDuration(uint32_t maxMs) { + maxTxDuration = maxMs; + Serial.print("Max TX duration set to: "); + Serial.print(maxMs); + Serial.println(" ms"); +} + +uint32_t AdvancedTx::getMaxDuration() const { + return maxTxDuration; +} + +String AdvancedTx::getLegalWarning() { + return "⚠️ WARNING: ADVANCED TRANSMISSION FEATURES ⚠️\n\n" + "These features are for AUTHORIZED testing only:\n" + "✓ Security research on own devices\n" + "✓ Authorized penetration testing\n" + "✓ Educational demonstrations\n" + "✓ Protocol development\n\n" + "NEVER use for:\n" + "✗ Unauthorized transmissions\n" + "✗ Interfering with communications\n" + "✗ Violating FCC/local regulations\n" + "✗ Accessing systems without permission\n\n" + "User assumes all legal responsibility.\n" + "RF transmissions are REGULATED by law."; +} + +void AdvancedTx::checkSafetyLimits(uint32_t durationMs) { + if (transmitting && (millis() - txStartTime) > maxTxDuration) { + emergencyStop(); + Serial.println("SAFETY: Maximum transmission time exceeded - stopped"); + } +} + +void AdvancedTx::startTransmission() { + transmitting = true; + txStartTime = millis(); + Serial.println("Transmission started"); +} + +void AdvancedTx::stopTransmission() { + transmitting = false; + Serial.print("Transmission stopped - Duration: "); + Serial.print(millis() - txStartTime); + Serial.println(" ms"); +} diff --git a/src/display.cpp b/src/display.cpp index f55e3b8..a844545 100644 --- a/src/display.cpp +++ b/src/display.cpp @@ -53,13 +53,22 @@ void Display::showMainMenu(int selectedItem) { "3. Frequency Scan", "4. Saved Signals", "5. Settings", - "6. Info" + "6. Info", + "7. Advanced Research" }; int yPos = 40; - for (int i = 0; i < 6; i++) { + for (int i = 0; i < 7; i++) { drawMenuItem(yPos, menuItems[i], i == selectedItem); - yPos += 35; + yPos += 32; // Adjusted spacing for 7 items + } + + // Warning indicator for Advanced Research + if (selectedItem == 6) { + tft.setTextColor(TFT_RED); + tft.setTextSize(1); + tft.setTextDatum(MC_DATUM); + tft.drawString("EDUCATIONAL USE ONLY", SCREEN_WIDTH / 2, SCREEN_HEIGHT - 35); } currentState = MENU_MAIN; @@ -207,3 +216,186 @@ void Display::setBacklight(uint8_t brightness) { backlightLevel = brightness; analogWrite(TFT_BL_PIN, brightness); } + +void Display::showAdvancedResearchMenu(int selectedItem) { + clear(); + drawHeader("Advanced Research"); + + // Warning indicator + tft.fillRect(0, 30, SCREEN_WIDTH, 20, TFT_RED); + tft.setTextColor(TFT_WHITE); + tft.setTextSize(1); + tft.setTextDatum(MC_DATUM); + tft.drawString("EDUCATIONAL USE ONLY", SCREEN_WIDTH / 2, 40); + + const char* menuItems[] = { + "Legal Warning", + "Rolling Code Analysis", + "Signal Intelligence", + "RF Research Tools" + }; + + int yPos = 60; + for (int i = 0; i < 4; i++) { + drawMenuItem(yPos, menuItems[i], i == selectedItem); + yPos += 35; + } + + currentState = MENU_ADVANCED_RESEARCH; +} + +void Display::showRollingCodeMenu(int selectedItem) { + clear(); + drawHeader("Rolling Code"); + + const char* menuItems[] = { + "Capture Sequence", + "Analyze Pattern", + "Protocol Detection", + "Export Data", + "Clear Sequences" + }; + + int yPos = 40; + for (int i = 0; i < 5; i++) { + drawMenuItem(yPos, menuItems[i], i == selectedItem); + yPos += 35; + } + + currentState = MENU_ROLLING_CODE; +} + +void Display::showSignalIntelMenu(int selectedItem) { + clear(); + drawHeader("Signal Intel"); + + const char* menuItems[] = { + "Auto-Identify Protocol", + "Decode Signal", + "Quality Analysis", + "Extract Bits", + "Export Analysis" + }; + + int yPos = 40; + for (int i = 0; i < 5; i++) { + drawMenuItem(yPos, menuItems[i], i == selectedItem); + yPos += 35; + } + + currentState = MENU_SIGNAL_INTEL; +} + +void Display::showRFResearchMenu(int selectedItem) { + clear(); + + // EXTREME WARNING HEADER + tft.fillRect(0, 0, SCREEN_WIDTH, 40, TFT_RED); + tft.setTextColor(TFT_WHITE); + tft.setTextSize(2); + tft.setTextDatum(MC_DATUM); + tft.drawString("WARNING!", SCREEN_WIDTH / 2, 10); + tft.setTextSize(1); + tft.drawString("ILLEGAL WITHOUT AUTH", SCREEN_WIDTH / 2, 30); + + const char* menuItems[] = { + "Authorization Check", + "Frequency Sweep", + "Signal Injection", + "Protocol Fuzzing" + }; + + int yPos = 50; + for (int i = 0; i < 4; i++) { + // Draw with red background for danger + if (selectedItem == i) { + tft.fillRect(0, yPos, SCREEN_WIDTH, 30, TFT_ORANGE); + tft.setTextColor(TFT_BLACK); + } else { + tft.setTextColor(TFT_RED); + } + tft.setTextSize(2); + tft.setTextDatum(ML_DATUM); + tft.drawString(menuItems[i], 10, yPos + 15); + yPos += 35; + } + + currentState = MENU_RF_RESEARCH; +} + +void Display::showLegalWarning(const String& warningText) { + clear(); + + // Red warning header + tft.fillRect(0, 0, SCREEN_WIDTH, 30, TFT_RED); + tft.setTextColor(TFT_WHITE); + tft.setTextSize(2); + tft.setTextDatum(MC_DATUM); + tft.drawString("LEGAL WARNING", SCREEN_WIDTH / 2, 15); + + // Warning text + tft.setTextColor(TFT_YELLOW); + tft.setTextSize(1); + tft.setTextDatum(TL_DATUM); + + // Word wrap the warning text + int yPos = 40; + int lineHeight = 12; + int maxWidth = SCREEN_WIDTH - 20; + + // Display first few lines (screen space limited) + String lines[] = { + "EDUCATIONAL USE ONLY", + "", + "RF research features", + "are for authorized", + "security research", + "and education only.", + "", + "Unauthorized use is", + "ILLEGAL and may result", + "in fines and", + "imprisonment.", + "", + "Press SELECT to", + "accept responsibility." + }; + + for (int i = 0; i < 14 && yPos < SCREEN_HEIGHT - 40; i++) { + tft.drawString(lines[i], 10, yPos); + yPos += lineHeight; + } + + currentState = MENU_LEGAL_WARNING; +} + +void Display::showAnalysisResult(const String& result) { + clear(); + drawHeader("Analysis Result"); + + tft.setTextColor(TEXT_COLOR); + tft.setTextSize(1); + tft.setTextDatum(TL_DATUM); + + // Display result text (simplified - real implementation would scroll) + int yPos = 40; + int lineHeight = 12; + + // Split result into lines and display + int startIdx = 0; + for (int i = 0; i < result.length() && yPos < SCREEN_HEIGHT - 40; i++) { + if (result.charAt(i) == '\n' || (i - startIdx) > 25) { + String line = result.substring(startIdx, i); + tft.drawString(line, 10, yPos); + yPos += lineHeight; + startIdx = i + 1; + } + } + + // Draw last line + if (startIdx < result.length() && yPos < SCREEN_HEIGHT - 40) { + String line = result.substring(startIdx); + tft.drawString(line, 10, yPos); + } +} + diff --git a/src/main.cpp b/src/main.cpp index a7ffd87..09fa9b0 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -5,14 +5,49 @@ #include "storage.h" #include "rf_signal.h" +#if ENABLE_ROLLING_CODE_ANALYSIS +#include "rolling_code_analyzer.h" +#endif + +#if ENABLE_SIGNAL_INTELLIGENCE +#include "signal_intelligence.h" +#endif + +#if ENABLE_ADVANCED_TX +#include "advanced_tx.h" +#endif + +#if ENABLE_RF_RESEARCH +#include "rf_research.h" +#endif + // Global objects RFModule rfModule; Display display; Storage storage; +#if ENABLE_ROLLING_CODE_ANALYSIS +RollingCodeAnalyzer rollingCodeAnalyzer; +#endif + +#if ENABLE_SIGNAL_INTELLIGENCE +SignalIntelligence signalIntel; +#endif + +#if ENABLE_ADVANCED_TX +AdvancedTx* advancedTx = nullptr; +#endif + +#if ENABLE_RF_RESEARCH +RFResearch* rfResearch = nullptr; +#endif + +// Captured signal (global for reuse across functions) +RFSignal capturedSignal; + // Menu state int currentMenuItem = 0; -int maxMenuItems = 6; +int maxMenuItems = 7; // Increased for Advanced Research menu MenuState currentMenu = MENU_MAIN; // Button states @@ -25,6 +60,13 @@ std::vector savedSignals; int selectedSignal = 0; bool signalsListLoaded = false; +// Advanced research state +int advancedMenuItem = 0; +int rollingCodeMenuItem = 0; +int signalIntelMenuItem = 0; +int rfResearchMenuItem = 0; +bool legalDisclaimerAccepted = false; + // Function prototypes void handleMainMenu(); void handleCaptureMode(); @@ -33,6 +75,11 @@ void handleScanMode(); void handleSavedSignalsMenu(); void handleSettingsMenu(); void handleInfoScreen(); +void handleAdvancedResearchMenu(); +void handleRollingCodeMenu(); +void handleSignalIntelMenu(); +void handleRFResearchMenu(); +void handleLegalWarning(); void checkButtons(); void navigateMenu(int direction); @@ -73,6 +120,17 @@ void setup() { // Note: Saved signals list will be loaded on demand when accessing saved signals menu Serial.println("Storage ready - signals list will load on demand"); + // Initialize advanced features +#if ENABLE_ADVANCED_TX + advancedTx = new AdvancedTx(&rfModule); + Serial.println("Advanced TX initialized"); +#endif + +#if ENABLE_RF_RESEARCH + rfResearch = new RFResearch(&rfModule); + Serial.println("RF Research module loaded (disabled by default)"); +#endif + // Configure button pins (using internal pull-ups) // Note: Actual button pins may vary - these are placeholders pinMode(BUTTON_UP, INPUT_PULLUP); @@ -111,6 +169,21 @@ void loop() { case MENU_INFO: handleInfoScreen(); break; + case MENU_ADVANCED_RESEARCH: + handleAdvancedResearchMenu(); + break; + case MENU_ROLLING_CODE: + handleRollingCodeMenu(); + break; + case MENU_SIGNAL_INTEL: + handleSignalIntelMenu(); + break; + case MENU_RF_RESEARCH: + handleRFResearchMenu(); + break; + case MENU_LEGAL_WARNING: + handleLegalWarning(); + break; } delay(10); @@ -223,6 +296,12 @@ void handleMainMenu() { currentMenu = MENU_INFO; display.showInfo(); break; + + case 6: // Advanced Research + currentMenu = MENU_ADVANCED_RESEARCH; + advancedMenuItem = 0; + display.showAdvancedResearchMenu(advancedMenuItem); + break; } } } @@ -360,3 +439,335 @@ void handleInfoScreen() { display.showMainMenu(currentMenuItem); } } + +void handleAdvancedResearchMenu() { + // Check for navigation + static bool upPressed = false; + static bool downPressed = false; + + if (digitalRead(BUTTON_UP) == LOW && !upPressed) { + upPressed = true; + advancedMenuItem--; + if (advancedMenuItem < 0) advancedMenuItem = 3; + display.showAdvancedResearchMenu(advancedMenuItem); + delay(200); + } else if (digitalRead(BUTTON_UP) == HIGH) { + upPressed = false; + } + + if (digitalRead(BUTTON_DOWN) == LOW && !downPressed) { + downPressed = true; + advancedMenuItem++; + if (advancedMenuItem > 3) advancedMenuItem = 0; + display.showAdvancedResearchMenu(advancedMenuItem); + delay(200); + } else if (digitalRead(BUTTON_DOWN) == HIGH) { + downPressed = false; + } + + if (buttonSelectPressed) { + buttonSelectPressed = false; + + switch (advancedMenuItem) { + case 0: // Legal Warning + currentMenu = MENU_LEGAL_WARNING; + display.showLegalWarning(""); + break; + + case 1: // Rolling Code Analysis +#if ENABLE_ROLLING_CODE_ANALYSIS + currentMenu = MENU_ROLLING_CODE; + rollingCodeMenuItem = 0; + display.showRollingCodeMenu(rollingCodeMenuItem); +#else + display.showStatus("Feature disabled"); + delay(1000); + display.showAdvancedResearchMenu(advancedMenuItem); +#endif + break; + + case 2: // Signal Intelligence +#if ENABLE_SIGNAL_INTELLIGENCE + currentMenu = MENU_SIGNAL_INTEL; + signalIntelMenuItem = 0; + display.showSignalIntelMenu(signalIntelMenuItem); +#else + display.showStatus("Feature disabled"); + delay(1000); + display.showAdvancedResearchMenu(advancedMenuItem); +#endif + break; + + case 3: // RF Research Tools +#if ENABLE_RF_RESEARCH + currentMenu = MENU_RF_RESEARCH; + rfResearchMenuItem = 0; + display.showRFResearchMenu(rfResearchMenuItem); +#else + display.showStatus("Feature disabled in config"); + delay(2000); + display.showAdvancedResearchMenu(advancedMenuItem); +#endif + break; + } + } +} + +void handleRollingCodeMenu() { +#if ENABLE_ROLLING_CODE_ANALYSIS + // Navigation + static bool upPressed = false; + static bool downPressed = false; + + if (digitalRead(BUTTON_UP) == LOW && !upPressed) { + upPressed = true; + rollingCodeMenuItem--; + if (rollingCodeMenuItem < 0) rollingCodeMenuItem = 4; + display.showRollingCodeMenu(rollingCodeMenuItem); + delay(200); + } else if (digitalRead(BUTTON_UP) == HIGH) { + upPressed = false; + } + + if (digitalRead(BUTTON_DOWN) == LOW && !downPressed) { + downPressed = true; + rollingCodeMenuItem++; + if (rollingCodeMenuItem > 4) rollingCodeMenuItem = 0; + display.showRollingCodeMenu(rollingCodeMenuItem); + delay(200); + } else if (digitalRead(BUTTON_DOWN) == HIGH) { + downPressed = false; + } + + if (buttonSelectPressed) { + buttonSelectPressed = false; + + switch (rollingCodeMenuItem) { + case 0: // Capture Sequence + display.showStatus("Capturing sequence..."); + rfModule.startReceive(); + delay(3000); + if (rfModule.signalDetected()) { + capturedSignal = rfModule.captureSignal(); + rollingCodeAnalyzer.captureSequence(capturedSignal); + display.showStatus("Sequence captured!"); + } else { + display.showStatus("No signal detected"); + } + rfModule.stopReceive(); + delay(1000); + display.showRollingCodeMenu(rollingCodeMenuItem); + break; + + case 1: // Analyze Pattern + { + RollingCodeAnalysis analysis = rollingCodeAnalyzer.analyzePattern(); + display.showAnalysisResult(analysis.analysisReport); + delay(3000); + display.showRollingCodeMenu(rollingCodeMenuItem); + } + break; + + case 2: // Protocol Detection + display.showStatus("Detecting protocol..."); + delay(1000); + display.showStatus("See serial output"); + delay(1000); + display.showRollingCodeMenu(rollingCodeMenuItem); + break; + + case 3: // Export Data + { + String report = rollingCodeAnalyzer.exportAnalysis(); + Serial.println(report); + display.showStatus("Exported to serial"); + delay(1000); + display.showRollingCodeMenu(rollingCodeMenuItem); + } + break; + + case 4: // Clear Sequences + rollingCodeAnalyzer.clearSequences(); + display.showStatus("Sequences cleared"); + delay(1000); + display.showRollingCodeMenu(rollingCodeMenuItem); + break; + } + } +#endif +} + +void handleSignalIntelMenu() { +#if ENABLE_SIGNAL_INTELLIGENCE + // Navigation + static bool upPressed = false; + static bool downPressed = false; + + if (digitalRead(BUTTON_UP) == LOW && !upPressed) { + upPressed = true; + signalIntelMenuItem--; + if (signalIntelMenuItem < 0) signalIntelMenuItem = 4; + display.showSignalIntelMenu(signalIntelMenuItem); + delay(200); + } else if (digitalRead(BUTTON_UP) == HIGH) { + upPressed = false; + } + + if (digitalRead(BUTTON_DOWN) == LOW && !downPressed) { + downPressed = true; + signalIntelMenuItem++; + if (signalIntelMenuItem > 4) signalIntelMenuItem = 0; + display.showSignalIntelMenu(signalIntelMenuItem); + delay(200); + } else if (digitalRead(BUTTON_DOWN) == HIGH) { + downPressed = false; + } + + if (buttonSelectPressed) { + buttonSelectPressed = false; + + switch (signalIntelMenuItem) { + case 0: // Auto-Identify Protocol + display.showStatus("Capturing signal..."); + rfModule.startReceive(); + delay(3000); + if (rfModule.signalDetected()) { + capturedSignal = rfModule.captureSignal(); + ProtocolInfo info = signalIntel.autoIdentifyProtocol(capturedSignal); + String result = "Protocol: " + info.protocolName + "\n"; + result += "Confidence: " + String(info.confidence * 100) + "%"; + display.showAnalysisResult(result); + delay(3000); + } else { + display.showStatus("No signal detected"); + delay(1000); + } + rfModule.stopReceive(); + display.showSignalIntelMenu(signalIntelMenuItem); + break; + + case 1: // Decode Signal + display.showStatus("See serial output"); + delay(1000); + display.showSignalIntelMenu(signalIntelMenuItem); + break; + + case 2: // Quality Analysis + if (capturedSignal.timings.size() > 0) { + SignalQuality quality = signalIntel.analyzeQuality(capturedSignal); + display.showAnalysisResult(quality.qualityReport); + delay(3000); + } else { + display.showStatus("Capture signal first"); + delay(1000); + } + display.showSignalIntelMenu(signalIntelMenuItem); + break; + + case 3: // Extract Bits + display.showStatus("See serial output"); + delay(1000); + display.showSignalIntelMenu(signalIntelMenuItem); + break; + + case 4: // Export Analysis + display.showStatus("Exported to serial"); + delay(1000); + display.showSignalIntelMenu(signalIntelMenuItem); + break; + } + } +#endif +} + +void handleRFResearchMenu() { +#if ENABLE_RF_RESEARCH + // Navigation + static bool upPressed = false; + static bool downPressed = false; + + if (digitalRead(BUTTON_UP) == LOW && !upPressed) { + upPressed = true; + rfResearchMenuItem--; + if (rfResearchMenuItem < 0) rfResearchMenuItem = 3; + display.showRFResearchMenu(rfResearchMenuItem); + delay(200); + } else if (digitalRead(BUTTON_UP) == HIGH) { + upPressed = false; + } + + if (digitalRead(BUTTON_DOWN) == LOW && !downPressed) { + downPressed = true; + rfResearchMenuItem++; + if (rfResearchMenuItem > 3) rfResearchMenuItem = 0; + display.showRFResearchMenu(rfResearchMenuItem); + delay(200); + } else if (digitalRead(BUTTON_DOWN) == HIGH) { + downPressed = false; + } + + if (buttonSelectPressed) { + buttonSelectPressed = false; + + if (rfResearch == nullptr) { + display.showStatus("RF Research not available"); + delay(1000); + currentMenu = MENU_ADVANCED_RESEARCH; + display.showAdvancedResearchMenu(advancedMenuItem); + return; + } + + switch (rfResearchMenuItem) { + case 0: // Authorization Check + display.showStatus("Check serial output"); + rfResearch->checkAuthorization(); + delay(2000); + display.showRFResearchMenu(rfResearchMenuItem); + break; + + case 1: // Frequency Sweep (educational demo) + display.showStatus("EDUCATIONAL DEMO"); + Serial.println(RFResearch::getLegalWarning()); + rfResearch->sweepJammer(433.0, 434.0); + delay(2000); + display.showRFResearchMenu(rfResearchMenuItem); + break; + + case 2: // Signal Injection + display.showStatus("EDUCATIONAL DEMO"); + delay(1000); + display.showRFResearchMenu(rfResearchMenuItem); + break; + + case 3: // Protocol Fuzzing + display.showStatus("EDUCATIONAL DEMO"); + delay(1000); + display.showRFResearchMenu(rfResearchMenuItem); + break; + } + } +#endif +} + +void handleLegalWarning() { + if (buttonSelectPressed) { + buttonSelectPressed = false; + + // User accepted legal warning + legalDisclaimerAccepted = true; + +#if ENABLE_RF_RESEARCH + if (rfResearch != nullptr) { + rfResearch->acceptLegalDisclaimer(); + } +#endif + + Serial.println("Legal disclaimer accepted by user"); + display.showStatus("Disclaimer accepted"); + delay(1000); + + // Return to advanced menu + currentMenu = MENU_ADVANCED_RESEARCH; + display.showAdvancedResearchMenu(advancedMenuItem); + } +} diff --git a/src/rf_research.cpp b/src/rf_research.cpp new file mode 100644 index 0000000..9c7a2aa --- /dev/null +++ b/src/rf_research.cpp @@ -0,0 +1,319 @@ +#include "rf_research.h" +#include "config.h" + +RFResearch::RFResearch(RFModule* rfModule) : rf(rfModule), researchModeEnabled(false), + disclaimerAccepted(false), transmitting(false), txStartTime(0), + txMaxDuration(MAX_TX_DURATION_MS) { +} + +void RFResearch::enableResearchMode(bool enable) { +#if ENABLE_RF_RESEARCH + if (enable && !disclaimerAccepted) { + Serial.println("ERROR: Must accept legal disclaimer before enabling research mode"); + return; + } + + researchModeEnabled = enable; + + if (enable) { + Serial.println("⚠️⚠️⚠️ RF RESEARCH MODE ENABLED ⚠️⚠️⚠️"); + Serial.println("EXTREME CAUTION REQUIRED"); + Serial.println("ILLEGAL WITHOUT AUTHORIZATION"); + logUsage("Research mode enabled"); + } else { + Serial.println("RF Research mode disabled"); + logUsage("Research mode disabled"); + } +#else + Serial.println("ERROR: RF Research features are disabled in config.h"); + Serial.println("These features require explicit activation due to legal concerns"); +#endif +} + +bool RFResearch::isResearchModeEnabled() const { + return researchModeEnabled; +} + +void RFResearch::acceptLegalDisclaimer() { +#if REQUIRE_DISCLAIMER_ACCEPTANCE + Serial.println("=============================================="); + Serial.println(" LEGAL DISCLAIMER ACCEPTANCE "); + Serial.println("=============================================="); + Serial.println(getDetailedWarning()); + Serial.println("=============================================="); + Serial.println("By continuing, you accept all legal responsibility"); + Serial.println("Disclaimer accepted - logged for compliance"); + + disclaimerAccepted = true; + logUsage("Legal disclaimer accepted"); +#else + disclaimerAccepted = true; +#endif +} + +bool RFResearch::hasAcceptedDisclaimer() const { + return disclaimerAccepted; +} + +void RFResearch::sweepJammer(float startFreq, float endFreq) { + Serial.println("⚠️⚠️⚠️ CRITICAL WARNING ⚠️⚠️⚠️"); + Serial.println("FREQUENCY SWEEP JAMMER - EDUCATIONAL ONLY"); + Serial.println("ILLEGAL WITHOUT AUTHORIZATION"); + + if (!performSafetyCheck()) { + return; + } + + logUsage("Sweep jammer (EDUCATIONAL)"); + + Serial.println("Educational demonstration:"); + Serial.print("Theoretical sweep from "); + Serial.print(startFreq); + Serial.print(" to "); + Serial.print(endFreq); + Serial.println(" MHz"); + Serial.println("ACTUAL TRANSMISSION DISABLED FOR SAFETY"); + Serial.println("This demonstrates the CONCEPT only"); + Serial.println("Real implementation would violate regulations"); +} + +void RFResearch::cwTransmit(float frequency, uint32_t durationMs) { + Serial.println("⚠️⚠️⚠️ CRITICAL WARNING ⚠️⚠️⚠️"); + Serial.println("CONTINUOUS WAVE TRANSMISSION - EDUCATIONAL ONLY"); + Serial.println("REGULATED BY FCC/LOCAL AUTHORITIES"); + + if (!performSafetyCheck()) { + return; + } + + if (durationMs > txMaxDuration) { + Serial.println("ERROR: Duration exceeds safety limit"); + return; + } + + logUsage("CW transmit (EDUCATIONAL)"); + + Serial.println("Educational demonstration:"); + Serial.print("Theoretical CW at "); + Serial.print(frequency); + Serial.print(" MHz for "); + Serial.print(durationMs); + Serial.println(" ms"); + Serial.println("ACTUAL TRANSMISSION DISABLED FOR SAFETY"); +} + +void RFResearch::pulseJammer(uint32_t onTimeMs, uint32_t offTimeMs, uint32_t durationMs) { + Serial.println("⚠️⚠️⚠️ CRITICAL WARNING ⚠️⚠️⚠️"); + Serial.println("PULSE JAMMER - EDUCATIONAL ONLY"); + Serial.println("ILLEGAL - FEDERAL CRIME IN MOST JURISDICTIONS"); + + if (!performSafetyCheck()) { + return; + } + + logUsage("Pulse jammer (EDUCATIONAL)"); + + Serial.println("Educational demonstration:"); + Serial.print("Theoretical pulse pattern: "); + Serial.print(onTimeMs); + Serial.print("ms ON, "); + Serial.print(offTimeMs); + Serial.print("ms OFF, duration "); + Serial.print(durationMs); + Serial.println("ms"); + Serial.println("ACTUAL TRANSMISSION DISABLED FOR SAFETY"); + Serial.println("Real jamming devices are ILLEGAL and carry severe penalties"); +} + +void RFResearch::noiseGenerator(float frequency, uint32_t durationMs) { + Serial.println("⚠️⚠️⚠️ CRITICAL WARNING ⚠️⚠️⚠️"); + Serial.println("NOISE GENERATOR - EDUCATIONAL ONLY"); + + if (!performSafetyCheck()) { + return; + } + + logUsage("Noise generator (EDUCATIONAL)"); + + Serial.println("Educational demonstration:"); + Serial.print("Theoretical noise at "); + Serial.print(frequency); + Serial.print(" MHz for "); + Serial.print(durationMs); + Serial.println(" ms"); + Serial.println("ACTUAL TRANSMISSION DISABLED FOR SAFETY"); +} + +void RFResearch::emergencyStop() { + transmitting = false; + researchModeEnabled = false; + + Serial.println("⚠️⚠️⚠️ EMERGENCY STOP ACTIVATED ⚠️⚠️⚠️"); + Serial.println("All RF research operations halted"); + + logUsage("EMERGENCY STOP"); +} + +bool RFResearch::checkEmergencyStop() { + // Check emergency stop button + if (digitalRead(EMERGENCY_STOP_BUTTON) == LOW) { + emergencyStop(); + return true; + } + + // Check timeout + if (transmitting && (millis() - txStartTime) > RESEARCH_MODE_TIMEOUT_MS) { + Serial.println("Research mode timeout - safety shutdown"); + emergencyStop(); + return true; + } + + return false; +} + +uint32_t RFResearch::getRemainingTime() const { + if (!transmitting) return 0; + + uint32_t elapsed = millis() - txStartTime; + if (elapsed >= txMaxDuration) return 0; + + return txMaxDuration - elapsed; +} + +String RFResearch::getLegalWarning() { + return "⚠️⚠️⚠️ EXTREME WARNING ⚠️⚠️⚠️\n\n" + "RF RESEARCH TOOLS - ILLEGAL WITHOUT AUTHORIZATION\n\n" + "These features are DISABLED BY DEFAULT and for\n" + "EDUCATIONAL PURPOSES ONLY.\n\n" + "Using RF jamming/interference devices is a\n" + "FEDERAL CRIME under:\n" + "- FCC regulations (USA)\n" + "- Similar laws in all countries\n\n" + "Penalties include:\n" + "- Heavy fines ($100,000+)\n" + "- Imprisonment\n" + "- Equipment seizure\n" + "- Criminal record\n\n" + "DO NOT PROCEED unless you have:\n" + "✓ Written legal authorization\n" + "✓ Appropriate licenses\n" + "✓ Controlled environment\n" + "✓ Full legal compliance\n\n" + "USER ASSUMES ALL LEGAL RESPONSIBILITY"; +} + +String RFResearch::getDetailedWarning() { + return "═══════════════════════════════════════════════════════\n" + " RF RESEARCH LEGAL DISCLAIMER & WARNING\n" + "═══════════════════════════════════════════════════════\n\n" + "⚠️ EDUCATIONAL PURPOSES ONLY ⚠️\n\n" + "The RF research features in this firmware are designed\n" + "EXCLUSIVELY for educational purposes to teach about:\n" + " • RF security vulnerabilities\n" + " • Wireless protocol weaknesses\n" + " • Communication system hardening\n" + " • Defensive countermeasures\n\n" + "═══════════════════════════════════════════════════════\n" + " LEGAL NOTICE\n" + "═══════════════════════════════════════════════════════\n\n" + "RF JAMMING AND INTERFERENCE ARE ILLEGAL:\n\n" + "United States:\n" + " • Communications Act of 1934, as amended\n" + " • 47 U.S.C. § 333 - Willful interference\n" + " • FCC Rules Part 15\n" + " • Penalties: Up to $112,500 per violation + imprisonment\n\n" + "International:\n" + " • ITU Radio Regulations\n" + " • Local telecommunications laws\n" + " • Criminal penalties in all jurisdictions\n\n" + "═══════════════════════════════════════════════════════\n" + " PROHIBITED USES\n" + "═══════════════════════════════════════════════════════\n\n" + "DO NOT USE THESE FEATURES TO:\n" + " ✗ Interfere with any communications\n" + " ✗ Jam cellular/WiFi/GPS signals\n" + " ✗ Disrupt emergency services\n" + " ✗ Access unauthorized systems\n" + " ✗ Bypass security mechanisms\n" + " ✗ Violate any laws or regulations\n\n" + "═══════════════════════════════════════════════════════\n" + " AUTHORIZED USES\n" + "═══════════════════════════════════════════════════════\n\n" + "These features MAY ONLY be used:\n" + " ✓ On your own devices in controlled environments\n" + " ✓ With proper legal authorization and licenses\n" + " ✓ In authorized security research facilities\n" + " ✓ For educational demonstrations with permission\n" + " ✓ In compliance with ALL applicable laws\n\n" + "═══════════════════════════════════════════════════════\n" + " ASSUMPTION OF RESPONSIBILITY\n" + "═══════════════════════════════════════════════════════\n\n" + "By using these features, YOU ACKNOWLEDGE:\n\n" + " 1. You have read and understood this warning\n" + " 2. You understand the legal implications\n" + " 3. You have obtained all necessary authorizations\n" + " 4. You accept FULL legal responsibility\n" + " 5. The developers assume NO liability\n" + " 6. You will comply with all applicable laws\n\n" + "═══════════════════════════════════════════════════════\n" + " DISCLAIMER\n" + "═══════════════════════════════════════════════════════\n\n" + "The developers of this firmware:\n" + " • Provide these tools for EDUCATIONAL purposes only\n" + " • Do NOT endorse illegal activities\n" + " • Accept NO responsibility for misuse\n" + " • Will cooperate with law enforcement\n" + " • Strongly discourage any illegal use\n\n" + "═══════════════════════════════════════════════════════\n\n" + "If you do not agree to these terms or cannot comply\n" + "with all applicable laws, DO NOT USE these features.\n\n" + "═══════════════════════════════════════════════════════"; +} + +bool RFResearch::performSafetyCheck() { + // Check if research mode is enabled + if (!researchModeEnabled) { + Serial.println("ERROR: Research mode not enabled"); + return false; + } + + // Check disclaimer acceptance + if (!disclaimerAccepted) { + Serial.println("ERROR: Legal disclaimer not accepted"); + return false; + } + + // Check emergency stop + if (checkEmergencyStop()) { + return false; + } + + // Check if feature is enabled in config +#if !ENABLE_RF_RESEARCH + Serial.println("ERROR: RF Research features disabled in config.h"); + Serial.println("Set ENABLE_RF_RESEARCH to 1 to enable (NOT RECOMMENDED)"); + return false; +#endif + + return true; +} + +void RFResearch::checkAuthorization() { + Serial.println("⚠️ AUTHORIZATION CHECK ⚠️"); + Serial.println("Verify you have:"); + Serial.println(" [ ] Written legal authorization"); + Serial.println(" [ ] Appropriate licenses"); + Serial.println(" [ ] Controlled environment"); + Serial.println(" [ ] Legal compliance documentation"); +} + +void RFResearch::logUsage(const String& feature) { + // Log all research feature usage for compliance + Serial.print("[RESEARCH LOG] "); + Serial.print(millis()); + Serial.print(" - "); + Serial.println(feature); + + // In production, this should log to persistent storage + // for audit trail and legal compliance +} diff --git a/src/rolling_code_analyzer.cpp b/src/rolling_code_analyzer.cpp new file mode 100644 index 0000000..931b088 --- /dev/null +++ b/src/rolling_code_analyzer.cpp @@ -0,0 +1,274 @@ +#include "rolling_code_analyzer.h" +#include + +RollingCodeAnalyzer::RollingCodeAnalyzer() { + capturedSequences.clear(); + lastAnalysis = RollingCodeAnalysis(); +} + +void RollingCodeAnalyzer::captureSequence(const RFSignal& signal) { + capturedSequences.push_back(signal); + Serial.println("Rolling code sequence captured"); + Serial.print("Total sequences: "); + Serial.println(capturedSequences.size()); +} + +RollingCodeAnalysis RollingCodeAnalyzer::analyzePattern() { + RollingCodeAnalysis analysis; + analysis.protocol = PROTOCOL_UNKNOWN_ROLLING; + analysis.counter = 0; + analysis.manufacturerId = 0; + analysis.entropy = 0.0; + analysis.patternDetected = false; + analysis.analysisReport = ""; + + if (capturedSequences.size() == 0) { + analysis.analysisReport = "No sequences captured"; + lastAnalysis = analysis; + return analysis; + } + + analysis.analysisReport = "Analysis of " + String(capturedSequences.size()) + " sequences:\n"; + + // Analyze each sequence + for (size_t i = 0; i < capturedSequences.size(); i++) { + const RFSignal& sig = capturedSequences[i]; + + // Calculate entropy + float entropy = calculateEntropy(sig.rawData, sig.rawDataLength); + analysis.entropy += entropy; + + // Detect protocol + if (detectKeeLoq(sig)) { + analysis.protocol = PROTOCOL_KEELOQ; + analysis.analysisReport += "KeeLoq protocol detected\n"; + } else if (detectHCS(sig)) { + analysis.protocol = PROTOCOL_HCS; + analysis.analysisReport += "HCS protocol detected\n"; + } + + // Extract counter + uint32_t counter = extractCounter(sig); + if (counter > analysis.counter) { + analysis.counter = counter; + } + + // Extract manufacturer ID + uint32_t mfgId = extractManufacturerId(sig); + if (mfgId != 0 && analysis.manufacturerId == 0) { + analysis.manufacturerId = mfgId; + } + } + + // Average entropy + if (capturedSequences.size() > 0) { + analysis.entropy /= capturedSequences.size(); + } + + // Check for patterns + if (capturedSequences.size() >= 2) { + analysis.patternDetected = compareSequences(capturedSequences[0], capturedSequences[1]); + } + + analysis.analysisReport += "Average entropy: " + String(analysis.entropy) + "\n"; + analysis.analysisReport += "Protocol: " + protocolToString(analysis.protocol) + "\n"; + + lastAnalysis = analysis; + return analysis; +} + +bool RollingCodeAnalyzer::detectKeeLoq(const RFSignal& signal) { + // KeeLoq uses 66-bit packets (typical) + // This is a simplified detection based on common characteristics + if (signal.rawDataLength < 8) return false; + + // Check for KeeLoq-like timing patterns (simplified) + // Real KeeLoq detection would require detailed protocol analysis + bool hasConsistentTiming = (signal.timings.size() > 60 && signal.timings.size() < 80); + + return hasConsistentTiming; +} + +bool RollingCodeAnalyzer::detectHCS(const RFSignal& signal) { + // HCS (High-Security) protocol detection (simplified) + // HCS codes are typically 69 bits + if (signal.rawDataLength < 8) return false; + + // Check timing characteristics + bool hasHCSTiming = (signal.timings.size() > 65 && signal.timings.size() < 75); + + return hasHCSTiming; +} + +bool RollingCodeAnalyzer::detectHitag(const RFSignal& signal) { + // Hitag protocol detection (simplified) + // Hitag operates at 125 kHz (different from most sub-GHz systems) + return false; // Not typically found in sub-GHz range +} + +uint32_t RollingCodeAnalyzer::extractCounter(const RFSignal& signal) { + // Educational extraction - simplified + // Real counter extraction requires protocol-specific parsing + if (signal.rawDataLength < 4) return 0; + + // Extract hypothetical counter from middle bytes (educational only) + uint32_t counter = extractBits(signal.rawData, 16, 16); + + return counter; +} + +uint32_t RollingCodeAnalyzer::extractManufacturerId(const RFSignal& signal) { + // Educational extraction - simplified + if (signal.rawDataLength < 4) return 0; + + // Extract hypothetical manufacturer ID from first bytes (educational only) + uint32_t mfgId = extractBits(signal.rawData, 0, 16); + + return mfgId; +} + +float RollingCodeAnalyzer::calculateEntropy(const uint8_t* data, size_t length) { + if (length == 0) return 0.0; + + // Calculate Shannon entropy + uint32_t freq[256] = {0}; + + for (size_t i = 0; i < length; i++) { + freq[data[i]]++; + } + + float entropy = 0.0; + for (int i = 0; i < 256; i++) { + if (freq[i] > 0) { + float p = (float)freq[i] / length; + entropy -= p * log2(p); + } + } + + return entropy; +} + +bool RollingCodeAnalyzer::detectRepeatingPattern(const uint8_t* data, size_t length) { + if (length < 4) return false; + + // Check for simple repeating patterns + for (size_t patternLen = 1; patternLen <= length / 2; patternLen++) { + bool repeats = true; + for (size_t i = patternLen; i < length; i++) { + if (data[i] != data[i % patternLen]) { + repeats = false; + break; + } + } + if (repeats) return true; + } + + return false; +} + +void RollingCodeAnalyzer::predictNextCode() { + // EDUCATIONAL DEMONSTRATION ONLY + // This does NOT work on real rolling code systems + // Real rolling codes use cryptographic algorithms that cannot be predicted + + Serial.println("⚠️ EDUCATIONAL DEMONSTRATION ONLY ⚠️"); + Serial.println("Rolling code prediction is NOT possible on real systems."); + Serial.println("Modern rolling codes use encryption (KeeLoq, AES, etc.)."); + Serial.println("This demonstrates why simple replay attacks don't work."); + + if (capturedSequences.size() < 2) { + Serial.println("Need at least 2 sequences for educational demo"); + return; + } + + Serial.println("Analyzing sequence patterns..."); + Serial.println("Result: Encrypted rolling codes cannot be predicted"); + Serial.println("Security: Rolling codes provide protection against replay attacks"); +} + +String RollingCodeAnalyzer::exportAnalysis() { + String report = "=== Rolling Code Analysis Report ===\n\n"; + report += "⚠️ EDUCATIONAL RESEARCH ONLY ⚠️\n\n"; + + report += "Captured Sequences: " + String(capturedSequences.size()) + "\n"; + report += lastAnalysis.analysisReport; + report += "\n"; + + if (lastAnalysis.protocol != PROTOCOL_UNKNOWN_ROLLING) { + report += "Protocol: " + protocolToString(lastAnalysis.protocol) + "\n"; + report += "Counter: 0x" + String(lastAnalysis.counter, HEX) + "\n"; + report += "Manufacturer ID: 0x" + String(lastAnalysis.manufacturerId, HEX) + "\n"; + } + + report += "Entropy: " + String(lastAnalysis.entropy) + "\n"; + report += "Pattern Detected: " + String(lastAnalysis.patternDetected ? "Yes" : "No") + "\n"; + + report += "\n=== Security Note ===\n"; + report += "Modern rolling codes are cryptographically secure.\n"; + report += "This analysis is for educational purposes only.\n"; + + return report; +} + +size_t RollingCodeAnalyzer::getSequenceCount() const { + return capturedSequences.size(); +} + +void RollingCodeAnalyzer::clearSequences() { + capturedSequences.clear(); + Serial.println("Rolling code sequences cleared"); +} + +String RollingCodeAnalyzer::getLegalWarning() { + return "⚠️ WARNING: EDUCATIONAL USE ONLY ⚠️\n\n" + "Rolling code analysis tools are for:\n" + "✓ Learning about RF security\n" + "✓ Research on authorized devices\n" + "✓ Understanding cryptographic protocols\n\n" + "NEVER use to:\n" + "✗ Access unauthorized systems\n" + "✗ Bypass security mechanisms\n" + "✗ Break into vehicles or buildings\n\n" + "User assumes all legal responsibility."; +} + +uint32_t RollingCodeAnalyzer::extractBits(const uint8_t* data, size_t startBit, size_t numBits) { + uint32_t result = 0; + + for (size_t i = 0; i < numBits && i < 32; i++) { + size_t bitPos = startBit + i; + size_t bytePos = bitPos / 8; + size_t bitInByte = bitPos % 8; + + if (bytePos < 256) { + uint8_t bit = (data[bytePos] >> bitInByte) & 1; + result |= (bit << i); + } + } + + return result; +} + +bool RollingCodeAnalyzer::compareSequences(const RFSignal& sig1, const RFSignal& sig2) { + // Compare timing patterns + if (sig1.timings.size() != sig2.timings.size()) return false; + + // Allow some tolerance in timing + const uint16_t tolerance = 50; // 50 microseconds + + for (size_t i = 0; i < sig1.timings.size(); i++) { + int16_t diff = abs((int16_t)sig1.timings[i] - (int16_t)sig2.timings[i]); + if (diff > tolerance) return false; + } + + return true; +} + +String RollingCodeAnalyzer::protocolToString(RollingCodeProtocol protocol) { + switch (protocol) { + case PROTOCOL_KEELOQ: return "KeeLoq"; + case PROTOCOL_HCS: return "HCS"; + case PROTOCOL_HITAG: return "Hitag"; + default: return "Unknown"; + } +} diff --git a/src/signal_intelligence.cpp b/src/signal_intelligence.cpp new file mode 100644 index 0000000..46dc030 --- /dev/null +++ b/src/signal_intelligence.cpp @@ -0,0 +1,375 @@ +#include "signal_intelligence.h" +#include + +SignalIntelligence::SignalIntelligence() { +} + +ProtocolInfo SignalIntelligence::autoIdentifyProtocol(const RFSignal& signal) { + ProtocolInfo info; + info.protocolName = "Unknown"; + info.modulation = signal.modulation; + info.encoding = ENCODING_UNKNOWN; + info.confidence = 0.0; + info.bitrate = 0; + info.description = ""; + + // Detect modulation type + info.modulation = detectModulation(signal); + + // Detect encoding + info.encoding = detectEncoding(signal); + + // Calculate bitrate + info.bitrate = (uint32_t)calculateBitrate(signal); + + // Identify common protocols based on characteristics + if (signal.timings.size() > 0) { + // Check for Princeton PT2262 (very common) + if (signal.timings.size() > 20 && signal.timings.size() < 100) { + std::vector unique = extractUniquePulseWidths(signal); + if (unique.size() == 2 || unique.size() == 3) { + info.protocolName = "Princeton PT2262"; + info.confidence = 0.7; + info.description = "Common fixed-code remote protocol"; + } + } + + // Check for EV1527 + if (signal.timings.size() >= 48 && signal.timings.size() <= 52) { + info.protocolName = "EV1527"; + info.confidence = 0.65; + info.description = "Learning code protocol"; + } + + // Check for weather station protocols + if (info.bitrate > 1000 && info.bitrate < 10000) { + info.protocolName = "Weather Station"; + info.confidence = 0.5; + info.description = "Possible weather sensor protocol"; + } + } + + return info; +} + +ModulationType SignalIntelligence::detectModulation(const RFSignal& signal) { + // Return the modulation from signal if already detected + if (signal.modulation != MOD_UNKNOWN) { + return signal.modulation; + } + + // Analyze timing patterns to guess modulation + // Most simple protocols use ASK/OOK + return MOD_ASK_OOK; +} + +EncodingType SignalIntelligence::detectEncoding(const RFSignal& signal) { + if (signal.timings.size() < 4) { + return ENCODING_UNKNOWN; + } + + std::vector unique = extractUniquePulseWidths(signal); + + // PWM typically has 2-3 unique pulse widths + if (unique.size() == 2 || unique.size() == 3) { + return ENCODING_PWM; + } + + // Manchester has more consistent timing + if (isPulseWidthConsistent(signal.timings, 0.3)) { + return ENCODING_MANCHESTER; + } + + // PPM has varying gaps + if (unique.size() > 3) { + return ENCODING_PPM; + } + + return ENCODING_UNKNOWN; +} + +std::vector SignalIntelligence::extractBits(const RFSignal& signal) { + std::vector bits; + + if (signal.timings.size() < 2) { + return bits; + } + + // Simple bit extraction based on pulse width + // Assume short pulse = 0, long pulse = 1 + std::vector unique = extractUniquePulseWidths(signal); + if (unique.size() < 2) return bits; + + uint16_t threshold = (unique[0] + unique[1]) / 2; + + for (size_t i = 0; i < signal.timings.size(); i++) { + bits.push_back(signal.timings[i] > threshold ? 1 : 0); + } + + return bits; +} + +String SignalIntelligence::decodeBitstream(const std::vector& bits) { + String result = ""; + + for (size_t i = 0; i < bits.size(); i++) { + result += bits[i] ? "1" : "0"; + if ((i + 1) % 8 == 0) result += " "; + } + + return result; +} + +std::vector SignalIntelligence::decodeManchesterBits(const RFSignal& signal) { + std::vector decoded; + + if (signal.timings.size() < 4) return decoded; + + // Manchester decoding: transition in middle of bit period + // High-to-Low = 1, Low-to-High = 0 + for (size_t i = 0; i < signal.timings.size() - 1; i += 2) { + // Simplified Manchester decoding + if (signal.timings[i] < signal.timings[i + 1]) { + decoded.push_back(0); + } else { + decoded.push_back(1); + } + } + + return decoded; +} + +std::vector SignalIntelligence::decodeDifferentialManchesterBits(const RFSignal& signal) { + std::vector decoded; + + if (signal.timings.size() < 4) return decoded; + + // Differential Manchester: transition at start = 0, no transition = 1 + bool lastState = false; + + for (size_t i = 0; i < signal.timings.size() - 1; i++) { + bool currentState = signal.timings[i] > signal.timings[i + 1]; + if (currentState != lastState) { + decoded.push_back(0); + } else { + decoded.push_back(1); + } + lastState = currentState; + } + + return decoded; +} + +bool SignalIntelligence::detectPreamble(const RFSignal& signal, uint32_t& preambleLength) { + preambleLength = 0; + + if (signal.timings.size() < 10) return false; + + // Look for repeated pattern at start (common preamble characteristic) + uint16_t firstTiming = signal.timings[0]; + const uint16_t tolerance = 50; + + for (size_t i = 1; i < signal.timings.size() && i < 20; i++) { + if (abs((int16_t)signal.timings[i] - (int16_t)firstTiming) > tolerance) { + preambleLength = i; + return i > 4; // At least 4 pulses for valid preamble + } + } + + return false; +} + +bool SignalIntelligence::detectSyncWord(const RFSignal& signal, uint32_t& syncWord) { + syncWord = 0; + + // Simplified sync word detection + // Look for distinctive pattern after preamble + uint32_t preambleLen; + if (!detectPreamble(signal, preambleLen)) return false; + + if (preambleLen + 8 > signal.timings.size()) return false; + + // Extract potential sync word (simplified) + for (size_t i = 0; i < 8 && (preambleLen + i) < signal.timings.size(); i++) { + if (signal.timings[preambleLen + i] > signal.timings[0]) { + syncWord |= (1 << i); + } + } + + return true; +} + +bool SignalIntelligence::validateCRC(const uint8_t* data, size_t length, uint16_t crc) { + if (length == 0) return false; + + uint16_t calculated = calculateCRC16(data, length); + return calculated == crc; +} + +uint16_t SignalIntelligence::calculateCRC16(const uint8_t* data, size_t length) { + // CRC-16-CCITT + uint16_t crc = 0xFFFF; + + for (size_t i = 0; i < length; i++) { + crc ^= (uint16_t)data[i] << 8; + for (int j = 0; j < 8; j++) { + if (crc & 0x8000) { + crc = (crc << 1) ^ 0x1021; + } else { + crc <<= 1; + } + } + } + + return crc; +} + +SignalQuality SignalIntelligence::analyzeQuality(const RFSignal& signal) { + SignalQuality quality; + quality.snr = 0.0; + quality.avgPulseWidth = 0.0; + quality.pulseVariance = 0.0; + quality.cleanSignal = false; + quality.qualityReport = ""; + + if (signal.timings.size() == 0) { + quality.qualityReport = "No timing data available"; + return quality; + } + + // Calculate average pulse width + uint32_t sum = 0; + for (size_t i = 0; i < signal.timings.size(); i++) { + sum += signal.timings[i]; + } + quality.avgPulseWidth = (float)sum / signal.timings.size(); + + // Calculate variance + float variance = 0.0; + for (size_t i = 0; i < signal.timings.size(); i++) { + float diff = signal.timings[i] - quality.avgPulseWidth; + variance += diff * diff; + } + quality.pulseVariance = variance / signal.timings.size(); + + // Estimate SNR (simplified - based on timing consistency) + float stdDev = sqrt(quality.pulseVariance); + quality.snr = quality.avgPulseWidth / stdDev; + + // Determine if signal is clean + quality.cleanSignal = (quality.snr > 5.0); + + // Generate report + quality.qualityReport = "Signal Quality Analysis:\n"; + quality.qualityReport += "Average Pulse Width: " + String(quality.avgPulseWidth) + " µs\n"; + quality.qualityReport += "Pulse Variance: " + String(quality.pulseVariance) + "\n"; + quality.qualityReport += "SNR: " + String(quality.snr) + "\n"; + quality.qualityReport += "Clean Signal: " + String(quality.cleanSignal ? "Yes" : "No") + "\n"; + + return quality; +} + +float SignalIntelligence::calculateBitrate(const RFSignal& signal) { + if (signal.timings.size() < 2) return 0.0; + + // Calculate average bit period + float avgPeriod = calculateMean(signal.timings); + + // Bitrate = 1 / period (in bits per second) + if (avgPeriod > 0) { + return 1000000.0 / avgPeriod; // Convert from µs to bps + } + + return 0.0; +} + +std::vector SignalIntelligence::extractUniquePulseWidths(const RFSignal& signal) { + std::vector unique; + const uint16_t tolerance = 50; // 50 µs tolerance + + for (size_t i = 0; i < signal.timings.size(); i++) { + bool found = false; + for (size_t j = 0; j < unique.size(); j++) { + if (abs((int16_t)signal.timings[i] - (int16_t)unique[j]) <= tolerance) { + found = true; + break; + } + } + if (!found) { + unique.push_back(signal.timings[i]); + } + } + + return unique; +} + +String SignalIntelligence::exportAnalysis(const ProtocolInfo& info, const SignalQuality& quality) { + String report = "=== Signal Intelligence Analysis ===\n\n"; + + report += "Protocol Information:\n"; + report += " Name: " + info.protocolName + "\n"; + report += " Modulation: " + modulationToString(info.modulation) + "\n"; + report += " Encoding: " + encodingToString(info.encoding) + "\n"; + report += " Confidence: " + String(info.confidence * 100) + "%\n"; + report += " Bitrate: " + String(info.bitrate) + " bps\n"; + report += " Description: " + info.description + "\n\n"; + + report += quality.qualityReport; + + return report; +} + +float SignalIntelligence::calculateMean(const std::vector& values) { + if (values.size() == 0) return 0.0; + + uint32_t sum = 0; + for (size_t i = 0; i < values.size(); i++) { + sum += values[i]; + } + + return (float)sum / values.size(); +} + +float SignalIntelligence::calculateVariance(const std::vector& values, float mean) { + if (values.size() == 0) return 0.0; + + float variance = 0.0; + for (size_t i = 0; i < values.size(); i++) { + float diff = values[i] - mean; + variance += diff * diff; + } + + return variance / values.size(); +} + +bool SignalIntelligence::isPulseWidthConsistent(const std::vector& timings, float tolerance) { + if (timings.size() < 2) return false; + + float mean = calculateMean(timings); + float variance = calculateVariance(timings, mean); + float stdDev = sqrt(variance); + + // Check if standard deviation is within tolerance of mean + return (stdDev / mean) < tolerance; +} + +String SignalIntelligence::modulationToString(ModulationType mod) { + switch (mod) { + case MOD_ASK_OOK: return "ASK/OOK"; + case MOD_2FSK: return "2-FSK"; + case MOD_4FSK: return "4-FSK"; + case MOD_MSK: return "MSK"; + case MOD_GFSK: return "GFSK"; + default: return "Unknown"; + } +} + +String SignalIntelligence::encodingToString(EncodingType enc) { + switch (enc) { + case ENCODING_MANCHESTER: return "Manchester"; + case ENCODING_DIFFERENTIAL_MANCHESTER: return "Differential Manchester"; + case ENCODING_PWM: return "PWM"; + case ENCODING_PPM: return "PPM"; + default: return "Unknown"; + } +}