diff --git a/ARCHITECTURE.adoc b/ARCHITECTURE.adoc new file mode 100644 index 0000000..1c0a7a6 --- /dev/null +++ b/ARCHITECTURE.adoc @@ -0,0 +1,48 @@ +== Architecture + +=== Overview + +This repository follows a modular, maintainable architecture designed +for clarity, scalability, and long-term sustainability. + +=== Directory Structure + +.... +. +├── src/ # Source code +├── tests/ # Test suites +├── docs/ # Documentation +├── scripts/ # Utility scripts +├── config/ # Configuration files +├── LICENSE # License file +├── LICENSES/ # Full license texts +└── README.adoc # Project documentation +.... + +=== Design Principles + +* *Separation of Concerns*: Each module has a single responsibility +* *Testability*: Code is written to be easily testable +* *Documentation*: All public APIs are documented +* *Configuration*: Environment-specific settings are externalized + +=== Dependencies + +* External dependencies are minimized and clearly declared +* Version pinning is used for reproducibility + +=== Security Considerations + +* Sensitive data is never committed to the repository +* Secrets are managed through environment variables or secure vaults +* Regular dependency audits are performed + +=== Maintainability + +* Code follows consistent style guidelines +* Pull requests require review and CI checks +* Issues and discussions are tracked transparently + +''''' + +_Last updated: 2026-07-18_ diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md deleted file mode 100644 index 607e3d8..0000000 --- a/ARCHITECTURE.md +++ /dev/null @@ -1,47 +0,0 @@ -# Architecture - -## Overview - -This repository follows a modular, maintainable architecture designed for clarity, scalability, and long-term sustainability. - -## Directory Structure - -``` -. -├── src/ # Source code -├── tests/ # Test suites -├── docs/ # Documentation -├── scripts/ # Utility scripts -├── config/ # Configuration files -├── LICENSE # License file -├── LICENSES/ # Full license texts -└── README.adoc # Project documentation -``` - -## Design Principles - -- **Separation of Concerns**: Each module has a single responsibility -- **Testability**: Code is written to be easily testable -- **Documentation**: All public APIs are documented -- **Configuration**: Environment-specific settings are externalized - -## Dependencies - -- External dependencies are minimized and clearly declared -- Version pinning is used for reproducibility - -## Security Considerations - -- Sensitive data is never committed to the repository -- Secrets are managed through environment variables or secure vaults -- Regular dependency audits are performed - -## Maintainability - -- Code follows consistent style guidelines -- Pull requests require review and CI checks -- Issues and discussions are tracked transparently - ---- - -*Last updated: 2026-07-18* diff --git a/CHANGELOG.adoc b/CHANGELOG.adoc index cd64ba1..8779ac1 100644 --- a/CHANGELOG.adoc +++ b/CHANGELOG.adoc @@ -1,155 +1,175 @@ -// SPDX-License-Identifier: CC-BY-SA-4.0 -// Copyright (c) Jonathan D.A. Jewell -= Changelog +== Changelog All notable changes to SafeBruteForce will be documented in this file. -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -== [0.1.0] - 2025-01-15 - -=== Added - -==== Core Features -- **State Management**: gen_statem-based state machine for pause/resume functionality -- **Pattern Generation**: Multiple strategies (wordlist, charset, sequential, custom) -- **Execution Engine**: Concurrent worker pool with gen_server -- **Result Aggregation**: Filtered output and statistics tracking -- **Checkpoint System**: Save/restore capability for long-running operations -- **Safety Mechanisms**: Automatic pause every 25 attempts with user confirmation - -==== Modules -- `sbf.lfe` - Main API and entry point -- `sbf_app.lfe` - OTP application behavior -- `sbf_sup.lfe` - Supervision tree -- `sbf_state.lfe` - State machine (gen_statem) -- `sbf_executor.lfe` - Execution engine (gen_server) -- `sbf_patterns.lfe` - Pattern generation strategies -- `sbf_output.lfe` - Result formatting and filtering -- `sbf_checkpoint.lfe` - Checkpoint save/restore -- `sbf_logger.lfe` - Structured logging -- `sbf_progress.lfe` - Progress tracking with ETA -- `sbf_rate_limiter.lfe` - Token bucket rate limiting - -==== Pattern Strategies -- Wordlist loading from files -- Wordlist mutations (leet speak, capitalization, suffixes) -- Charset combinations with configurable length -- Sequential number generation -- Common password lists -- Date pattern generation -- Custom pattern functions -- Keyboard pattern generator - -==== Target Support -- HTTP/HTTPS endpoints (POST/GET) -- Custom validation functions -- Mock targets for testing -- JSON and URL-encoded body formats -- Custom headers support -- Success/failure pattern matching - -==== Safety Features -- Automatic pause every N attempts (configurable, default 25) -- Manual pause/resume controls -- Rate limiting (token bucket algorithm) -- Authorization verification in CLI -- Audit logging -- User agent identification - -==== CLI and Interface -- Interactive REPL support -- Command-line interface (sbf_cli) -- Authorization prompts -- Progress bars -- Colorized output -- Comprehensive help system - -==== Documentation -- Comprehensive README with examples -- Usage guide (docs/USAGE.md) -- Security best practices (docs/SECURITY.md) -- Contributing guidelines (docs/CONTRIBUTING.md) -- CLAUDE.md for AI assistant guidance -- Inline code documentation -- Example code in examples/ directory - -==== Testing -- Unit tests for all core modules -- State machine lifecycle tests -- Pattern generation tests -- Executor tests with mock targets -- Checkpoint save/restore tests -- Safety mechanism tests -- Integration tests - -==== Examples -- HTTP login testing (examples/http_login_test.lfe) -- PIN code brute-forcing (examples/pin_code_test.lfe) -- Custom pattern generation (examples/custom_pattern_test.lfe) - -==== Utilities -- Progress tracking with ETA calculation -- Structured logging with multiple levels -- Result export to files -- Checkpoint management -- Statistics dashboard -- Duration formatting -- Timestamp formatting - -==== Wordlists -- Common passwords (60+ entries) -- Test wordlist for development -- Located in priv/wordlists/ - -==== Configuration -- Rebar3 project configuration -- OTP application configuration -- VM arguments for production -- Configurable pause interval -- Configurable rate limits -- Configurable worker pool size -- Configurable timeouts - -=== Security -- Safety mechanisms cannot be fully disabled -- Authorization checks in CLI -- Audit logging for accountability -- Responsible disclosure guidelines -- Clear ethical use documentation -- Rate limiting by default - -=== Developer Experience -- Full LFE/Erlang source code -- Comprehensive test suite -- Example applications -- Documentation for contributors -- Coding standards guide -- Interactive REPL development - -== [Unreleased] - -=== Planned for v0.2.0 -- SSH brute-force module -- FTP support -- Database connection testing -- Distributed worker support -- Web UI dashboard -- Enhanced reporting (PDF, HTML) -- Performance optimizations -- Additional pattern strategies -- More target protocol support - -=== Future Considerations -- Machine learning pattern generation -- Cloud integration (AWS, GCP, Azure) -- SIEM integration -- Custom plugin system -- Advanced analytics -- Real-time collaboration features -- Mobile app support - ---- - -**Note**: This project follows ethical security testing principles. All features are designed for authorized testing only. +The format is based on https://keepachangelog.com/en/1.0.0/[Keep a +Changelog], and this project adheres to +https://semver.org/spec/v2.0.0.html[Semantic Versioning]. + +=== [0.1.0] - 2025-01-15 + +==== Added + +===== Core Features + +* *State Management*: gen_statem-based state machine for pause/resume +functionality +* *Pattern Generation*: Multiple strategies (wordlist, charset, +sequential, custom) +* *Execution Engine*: Concurrent worker pool with gen_server +* *Result Aggregation*: Filtered output and statistics tracking +* *Checkpoint System*: Save/restore capability for long-running +operations +* *Safety Mechanisms*: Automatic pause every 25 attempts with user +confirmation + +===== Modules + +* `+sbf.lfe+` - Main API and entry point +* `+sbf_app.lfe+` - OTP application behavior +* `+sbf_sup.lfe+` - Supervision tree +* `+sbf_state.lfe+` - State machine (gen_statem) +* `+sbf_executor.lfe+` - Execution engine (gen_server) +* `+sbf_patterns.lfe+` - Pattern generation strategies +* `+sbf_output.lfe+` - Result formatting and filtering +* `+sbf_checkpoint.lfe+` - Checkpoint save/restore +* `+sbf_logger.lfe+` - Structured logging +* `+sbf_progress.lfe+` - Progress tracking with ETA +* `+sbf_rate_limiter.lfe+` - Token bucket rate limiting + +===== Pattern Strategies + +* Wordlist loading from files +* Wordlist mutations (leet speak, capitalization, suffixes) +* Charset combinations with configurable length +* Sequential number generation +* Common password lists +* Date pattern generation +* Custom pattern functions +* Keyboard pattern generator + +===== Target Support + +* HTTP/HTTPS endpoints (POST/GET) +* Custom validation functions +* Mock targets for testing +* JSON and URL-encoded body formats +* Custom headers support +* Success/failure pattern matching + +===== Safety Features + +* Automatic pause every N attempts (configurable, default 25) +* Manual pause/resume controls +* Rate limiting (token bucket algorithm) +* Authorization verification in CLI +* Audit logging +* User agent identification + +===== CLI and Interface + +* Interactive REPL support +* Command-line interface (sbf_cli) +* Authorization prompts +* Progress bars +* Colorized output +* Comprehensive help system + +===== Documentation + +* Comprehensive README with examples +* Usage guide (docs/USAGE.md) +* Security best practices (docs/SECURITY.md) +* Contributing guidelines (docs/CONTRIBUTING.md) +* CLAUDE.md for AI assistant guidance +* Inline code documentation +* Example code in examples/ directory + +===== Testing + +* Unit tests for all core modules +* State machine lifecycle tests +* Pattern generation tests +* Executor tests with mock targets +* Checkpoint save/restore tests +* Safety mechanism tests +* Integration tests + +===== Examples + +* HTTP login testing (examples/http_login_test.lfe) +* PIN code brute-forcing (examples/pin_code_test.lfe) +* Custom pattern generation (examples/custom_pattern_test.lfe) + +===== Utilities + +* Progress tracking with ETA calculation +* Structured logging with multiple levels +* Result export to files +* Checkpoint management +* Statistics dashboard +* Duration formatting +* Timestamp formatting + +===== Wordlists + +* Common passwords (60+ entries) +* Test wordlist for development +* Located in priv/wordlists/ + +===== Configuration + +* Rebar3 project configuration +* OTP application configuration +* VM arguments for production +* Configurable pause interval +* Configurable rate limits +* Configurable worker pool size +* Configurable timeouts + +==== Security + +* Safety mechanisms cannot be fully disabled +* Authorization checks in CLI +* Audit logging for accountability +* Responsible disclosure guidelines +* Clear ethical use documentation +* Rate limiting by default + +==== Developer Experience + +* Full LFE/Erlang source code +* Comprehensive test suite +* Example applications +* Documentation for contributors +* Coding standards guide +* Interactive REPL development + +=== [Unreleased] + +==== Planned for v0.2.0 + +* SSH brute-force module +* FTP support +* Database connection testing +* Distributed worker support +* Web UI dashboard +* Enhanced reporting (PDF, HTML) +* Performance optimizations +* Additional pattern strategies +* More target protocol support + +==== Future Considerations + +* Machine learning pattern generation +* Cloud integration (AWS, GCP, Azure) +* SIEM integration +* Custom plugin system +* Advanced analytics +* Real-time collaboration features +* Mobile app support + +''''' + +*Note*: This project follows ethical security testing principles. All +features are designed for authorized testing only. diff --git a/CHANGELOG.md b/CHANGELOG.md deleted file mode 100644 index 4d2ddee..0000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,157 +0,0 @@ - -# Changelog - -All notable changes to SafeBruteForce will be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -## [0.1.0] - 2025-01-15 - -### Added - -#### Core Features -- **State Management**: gen_statem-based state machine for pause/resume functionality -- **Pattern Generation**: Multiple strategies (wordlist, charset, sequential, custom) -- **Execution Engine**: Concurrent worker pool with gen_server -- **Result Aggregation**: Filtered output and statistics tracking -- **Checkpoint System**: Save/restore capability for long-running operations -- **Safety Mechanisms**: Automatic pause every 25 attempts with user confirmation - -#### Modules -- `sbf.lfe` - Main API and entry point -- `sbf_app.lfe` - OTP application behavior -- `sbf_sup.lfe` - Supervision tree -- `sbf_state.lfe` - State machine (gen_statem) -- `sbf_executor.lfe` - Execution engine (gen_server) -- `sbf_patterns.lfe` - Pattern generation strategies -- `sbf_output.lfe` - Result formatting and filtering -- `sbf_checkpoint.lfe` - Checkpoint save/restore -- `sbf_logger.lfe` - Structured logging -- `sbf_progress.lfe` - Progress tracking with ETA -- `sbf_rate_limiter.lfe` - Token bucket rate limiting - -#### Pattern Strategies -- Wordlist loading from files -- Wordlist mutations (leet speak, capitalization, suffixes) -- Charset combinations with configurable length -- Sequential number generation -- Common password lists -- Date pattern generation -- Custom pattern functions -- Keyboard pattern generator - -#### Target Support -- HTTP/HTTPS endpoints (POST/GET) -- Custom validation functions -- Mock targets for testing -- JSON and URL-encoded body formats -- Custom headers support -- Success/failure pattern matching - -#### Safety Features -- Automatic pause every N attempts (configurable, default 25) -- Manual pause/resume controls -- Rate limiting (token bucket algorithm) -- Authorization verification in CLI -- Audit logging -- User agent identification - -#### CLI and Interface -- Interactive REPL support -- Command-line interface (sbf_cli) -- Authorization prompts -- Progress bars -- Colorized output -- Comprehensive help system - -#### Documentation -- Comprehensive README with examples -- Usage guide (docs/USAGE.md) -- Security best practices (docs/SECURITY.md) -- Contributing guidelines (docs/CONTRIBUTING.md) -- CLAUDE.md for AI assistant guidance -- Inline code documentation -- Example code in examples/ directory - -#### Testing -- Unit tests for all core modules -- State machine lifecycle tests -- Pattern generation tests -- Executor tests with mock targets -- Checkpoint save/restore tests -- Safety mechanism tests -- Integration tests - -#### Examples -- HTTP login testing (examples/http_login_test.lfe) -- PIN code brute-forcing (examples/pin_code_test.lfe) -- Custom pattern generation (examples/custom_pattern_test.lfe) - -#### Utilities -- Progress tracking with ETA calculation -- Structured logging with multiple levels -- Result export to files -- Checkpoint management -- Statistics dashboard -- Duration formatting -- Timestamp formatting - -#### Wordlists -- Common passwords (60+ entries) -- Test wordlist for development -- Located in priv/wordlists/ - -#### Configuration -- Rebar3 project configuration -- OTP application configuration -- VM arguments for production -- Configurable pause interval -- Configurable rate limits -- Configurable worker pool size -- Configurable timeouts - -### Security -- Safety mechanisms cannot be fully disabled -- Authorization checks in CLI -- Audit logging for accountability -- Responsible disclosure guidelines -- Clear ethical use documentation -- Rate limiting by default - -### Developer Experience -- Full LFE/Erlang source code -- Comprehensive test suite -- Example applications -- Documentation for contributors -- Coding standards guide -- Interactive REPL development - -## [Unreleased] - -### Planned for v0.2.0 -- SSH brute-force module -- FTP support -- Database connection testing -- Distributed worker support -- Web UI dashboard -- Enhanced reporting (PDF, HTML) -- Performance optimizations -- Additional pattern strategies -- More target protocol support - -### Future Considerations -- Machine learning pattern generation -- Cloud integration (AWS, GCP, Azure) -- SIEM integration -- Custom plugin system -- Advanced analytics -- Real-time collaboration features -- Mobile app support - ---- - -**Note**: This project follows ethical security testing principles. All features are designed for authorized testing only. diff --git a/CODE_OF_CONDUCT.adoc b/CODE_OF_CONDUCT.adoc new file mode 100644 index 0000000..376f232 --- /dev/null +++ b/CODE_OF_CONDUCT.adoc @@ -0,0 +1,192 @@ +== Contributor Covenant Code of Conduct + +=== Our Pledge + +We as members, contributors, and leaders pledge to make participation in +our community a harassment-free experience for everyone, regardless of +age, body size, visible or invisible disability, ethnicity, sex +characteristics, gender identity and expression, level of experience, +education, socio-economic status, nationality, personal appearance, +race, caste, color, religion, or sexual identity and orientation. + +We pledge to act and interact in ways that contribute to an open, +welcoming, diverse, inclusive, and healthy community. + +=== Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our +mistakes, and learning from the experience +* Focusing on what is best not just for us as individuals, but for the +overall community +* *Prioritizing emotional safety alongside technical excellence* +* *Assuming good faith in all interactions* +* *Recognizing that mistakes are opportunities for learning, not +punishment* + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or +advances of any kind +* Trolling, insulting or derogatory comments, and personal or political +attacks +* Public or private harassment +* Publishing others’ private information, such as a physical or email +address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a +professional setting +* *Using this tool for unauthorized or illegal activities* +* *Sharing exploits or vulnerabilities publicly before responsible +disclosure* +* *Encouraging or assisting in malicious use of security tools* + +=== Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our +standards of acceptable behavior and will take appropriate and fair +corrective action in response to any behavior that they deem +inappropriate, threatening, offensive, or harmful. + +Community leaders have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other +contributions that are not aligned to this Code of Conduct, and will +communicate reasons for moderation decisions when appropriate. + +=== Scope + +This Code of Conduct applies within all community spaces, and also +applies when an individual is officially representing the community in +public spaces. Examples of representing our community include using an +official e-mail address, posting via an official social media account, +or acting as an appointed representative at an online or offline event. + +*This Code of Conduct specifically extends to the use of +SafeBruteForce:* - Only use this tool on systems you own or have +explicit written authorization to test - Follow all applicable laws and +regulations - Practice responsible disclosure for any vulnerabilities +discovered - Respect rate limits and system resources - Document and +report misuse + +=== Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may +be reported to the community leaders responsible for enforcement at +[security@safeBruteForce.example] (please update with actual contact). + +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security +of the reporter of any incident. + +=== Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in +determining the consequences for any action they deem in violation of +this Code of Conduct: + +==== 1. Correction + +*Community Impact*: Use of inappropriate language or other behavior +deemed unprofessional or unwelcome in the community. + +*Consequence*: A private, written warning from community leaders, +providing clarity around the nature of the violation and an explanation +of why the behavior was inappropriate. A public apology may be +requested. + +==== 2. Warning + +*Community Impact*: A violation through a single incident or series of +actions. + +*Consequence*: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, for a specified period of +time. This includes avoiding interactions in community spaces as well as +external channels like social media. Violating these terms may lead to a +temporary or permanent ban. + +==== 3. Temporary Ban + +*Community Impact*: A serious violation of community standards, +including sustained inappropriate behavior. + +*Consequence*: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No +public or private interaction with the people involved, including +unsolicited interaction with those enforcing the Code of Conduct, is +allowed during this period. Violating these terms may lead to a +permanent ban. + +==== 4. Permanent Ban + +*Community Impact*: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of +individuals. + +*Consequence*: A permanent ban from any sort of public interaction +within the community. + +=== Attribution + +This Code of Conduct is adapted from the +https://www.contributor-covenant.org[Contributor Covenant], version 2.1, +available at +https://www.contributor-covenant.org/version/2/1/code_of_conduct.html. + +Community Impact Guidelines were inspired by +https://github.com/mozilla/diversity[Mozilla’s code of conduct +enforcement ladder]. + +For answers to common questions about this code of conduct, see the FAQ +at https://www.contributor-covenant.org/faq. Translations are available +at https://www.contributor-covenant.org/translations. + +=== SafeBruteForce Specific Guidelines + +==== Ethical Use Commitment + +All contributors and users of SafeBruteForce commit to: + +[arabic] +. *Authorization First*: Never test systems without explicit written +permission +. *Legal Compliance*: Follow all applicable laws (CFAA, GDPR, etc.) +. *Responsible Disclosure*: Report vulnerabilities privately with +reasonable time to fix +. *Minimize Harm*: Use rate limiting, respect system resources, avoid +disruption +. *Educational Focus*: Prioritize learning and defense over offensive +capabilities +. *Transparency*: Clearly identify testing activities, maintain audit +logs +. *Privacy Respect*: Handle discovered credentials and data with utmost +care + +==== Reporting Misuse + +If you become aware of SafeBruteForce being used for: - Unauthorized +access attempts - Illegal activities - Harassment or stalking - Mass +credential stuffing - Any violation of this Code of Conduct + +Please report immediately to: security@[domain] (use PGP key if +available) + +==== Emotional Safety + +We recognize that security work can be stressful. Our community: - +Assumes good faith in all interactions - Provides constructive, kind +feedback - Celebrates learning from mistakes - Offers support for +anxiety and imposter syndrome - Maintains a judgment-free environment +for questions - Values emotional well-being alongside technical +excellence + +''''' + +*Version*: 1.0.0 *Last Updated*: 2025-01-15 *Review Cycle*: Annual diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md deleted file mode 100644 index bd66c49..0000000 --- a/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,191 +0,0 @@ - -# Contributor Covenant Code of Conduct - -## Our Pledge - -We as members, contributors, and leaders pledge to make participation in our -community a harassment-free experience for everyone, regardless of age, body -size, visible or invisible disability, ethnicity, sex characteristics, gender -identity and expression, level of experience, education, socio-economic status, -nationality, personal appearance, race, caste, color, religion, or sexual -identity and orientation. - -We pledge to act and interact in ways that contribute to an open, welcoming, -diverse, inclusive, and healthy community. - -## Our Standards - -Examples of behavior that contributes to a positive environment for our -community include: - -* Demonstrating empathy and kindness toward other people -* Being respectful of differing opinions, viewpoints, and experiences -* Giving and gracefully accepting constructive feedback -* Accepting responsibility and apologizing to those affected by our mistakes, - and learning from the experience -* Focusing on what is best not just for us as individuals, but for the overall - community -* **Prioritizing emotional safety alongside technical excellence** -* **Assuming good faith in all interactions** -* **Recognizing that mistakes are opportunities for learning, not punishment** - -Examples of unacceptable behavior include: - -* The use of sexualized language or imagery, and sexual attention or advances of - any kind -* Trolling, insulting or derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or email address, - without their explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting -* **Using this tool for unauthorized or illegal activities** -* **Sharing exploits or vulnerabilities publicly before responsible disclosure** -* **Encouraging or assisting in malicious use of security tools** - -## Enforcement Responsibilities - -Community leaders are responsible for clarifying and enforcing our standards of -acceptable behavior and will take appropriate and fair corrective action in -response to any behavior that they deem inappropriate, threatening, offensive, -or harmful. - -Community leaders have the right and responsibility to remove, edit, or reject -comments, commits, code, wiki edits, issues, and other contributions that are -not aligned to this Code of Conduct, and will communicate reasons for moderation -decisions when appropriate. - -## Scope - -This Code of Conduct applies within all community spaces, and also applies when -an individual is officially representing the community in public spaces. -Examples of representing our community include using an official e-mail address, -posting via an official social media account, or acting as an appointed -representative at an online or offline event. - -**This Code of Conduct specifically extends to the use of SafeBruteForce:** -- Only use this tool on systems you own or have explicit written authorization to test -- Follow all applicable laws and regulations -- Practice responsible disclosure for any vulnerabilities discovered -- Respect rate limits and system resources -- Document and report misuse - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported to the community leaders responsible for enforcement at -[security@safeBruteForce.example] (please update with actual contact). - -All complaints will be reviewed and investigated promptly and fairly. - -All community leaders are obligated to respect the privacy and security of the -reporter of any incident. - -## Enforcement Guidelines - -Community leaders will follow these Community Impact Guidelines in determining -the consequences for any action they deem in violation of this Code of Conduct: - -### 1. Correction - -**Community Impact**: Use of inappropriate language or other behavior deemed -unprofessional or unwelcome in the community. - -**Consequence**: A private, written warning from community leaders, providing -clarity around the nature of the violation and an explanation of why the -behavior was inappropriate. A public apology may be requested. - -### 2. Warning - -**Community Impact**: A violation through a single incident or series of -actions. - -**Consequence**: A warning with consequences for continued behavior. No -interaction with the people involved, including unsolicited interaction with -those enforcing the Code of Conduct, for a specified period of time. This -includes avoiding interactions in community spaces as well as external channels -like social media. Violating these terms may lead to a temporary or permanent -ban. - -### 3. Temporary Ban - -**Community Impact**: A serious violation of community standards, including -sustained inappropriate behavior. - -**Consequence**: A temporary ban from any sort of interaction or public -communication with the community for a specified period of time. No public or -private interaction with the people involved, including unsolicited interaction -with those enforcing the Code of Conduct, is allowed during this period. -Violating these terms may lead to a permanent ban. - -### 4. Permanent Ban - -**Community Impact**: Demonstrating a pattern of violation of community -standards, including sustained inappropriate behavior, harassment of an -individual, or aggression toward or disparagement of classes of individuals. - -**Consequence**: A permanent ban from any sort of public interaction within the -community. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], -version 2.1, available at -[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. - -Community Impact Guidelines were inspired by -[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. - -For answers to common questions about this code of conduct, see the FAQ at -[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at -[https://www.contributor-covenant.org/translations][translations]. - -[homepage]: https://www.contributor-covenant.org -[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html -[Mozilla CoC]: https://github.com/mozilla/diversity -[FAQ]: https://www.contributor-covenant.org/faq -[translations]: https://www.contributor-covenant.org/translations - -## SafeBruteForce Specific Guidelines - -### Ethical Use Commitment - -All contributors and users of SafeBruteForce commit to: - -1. **Authorization First**: Never test systems without explicit written permission -2. **Legal Compliance**: Follow all applicable laws (CFAA, GDPR, etc.) -3. **Responsible Disclosure**: Report vulnerabilities privately with reasonable time to fix -4. **Minimize Harm**: Use rate limiting, respect system resources, avoid disruption -5. **Educational Focus**: Prioritize learning and defense over offensive capabilities -6. **Transparency**: Clearly identify testing activities, maintain audit logs -7. **Privacy Respect**: Handle discovered credentials and data with utmost care - -### Reporting Misuse - -If you become aware of SafeBruteForce being used for: -- Unauthorized access attempts -- Illegal activities -- Harassment or stalking -- Mass credential stuffing -- Any violation of this Code of Conduct - -Please report immediately to: security@[domain] (use PGP key if available) - -### Emotional Safety - -We recognize that security work can be stressful. Our community: -- Assumes good faith in all interactions -- Provides constructive, kind feedback -- Celebrates learning from mistakes -- Offers support for anxiety and imposter syndrome -- Maintains a judgment-free environment for questions -- Values emotional well-being alongside technical excellence - ---- - -**Version**: 1.0.0 -**Last Updated**: 2025-01-15 -**Review Cycle**: Annual diff --git a/CONTRIBUTING.adoc b/CONTRIBUTING.adoc index e9b1993..da6aee6 100644 --- a/CONTRIBUTING.adoc +++ b/CONTRIBUTING.adoc @@ -1,21 +1,109 @@ -// SPDX-License-Identifier: CC-BY-SA-4.0 -// Copyright (c) Jonathan D.A. Jewell -= Contributing Guide +== Clone the repository -== Getting Started +git clone https://github.com/hyperpolymath/safe-brute-force.git cd +safe-brute-force -1. Fork the repository -2. Create a feature branch from `main` -3. Sign off commits (`git commit -s`) -4. Submit a pull request +== Using Nix (recommended for reproducibility) -== Commit Guidelines +nix develop -* Conventional commits: `type(scope): description` -* Sign all commits (DCO required) -* Atomic, focused commits +== Or using toolbox/distrobox -== License +toolbox create safe-brute-force-dev toolbox enter safe-brute-force-dev # +Install dependencies manually -Contributions licensed under project license. +== Verify setup +just check # or: cargo check / mix compile / etc. just test # Run test +suite + +.... + +### Repository Structure +.... + +safe-brute-force/ ├── src/ # Source code (Perimeter 1-2) ├── lib/ # +Library code (Perimeter 1-2) ├── extensions/ # Extensions (Perimeter 2) +├── plugins/ # Plugins (Perimeter 2) ├── tools/ # Tooling (Perimeter 2) +├── docs/ # Documentation (Perimeter 3) │ ├── architecture/ # ADRs, +specs (Perimeter 2) │ └── proposals/ # RFCs (Perimeter 3) ├── examples/ +# Examples (Perimeter 3) ├── spec/ # Spec tests (Perimeter 3) ├── tests/ +# Test suite (Perimeter 2-3) ├── .well-known/ # Protocol files +(Perimeter 1-3) ├── .github/ # GitHub config (Perimeter 1) │ ├── +ISSUE_TEMPLATE/ │ └── workflows/ ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md +├── CONTRIBUTING.md # This file ├── GOVERNANCE.md ├── LICENSE ├── +MAINTAINERS.md ├── README.adoc ├── SECURITY.md ├── flake.nix # Nix flake +(Perimeter 1) └── Justfile # Task runner (Perimeter 1) + +.... + +--- + +## How to Contribute + +### Reporting Bugs + +**Before reporting**: +1. Search existing issues +2. Check if it's already fixed in `main` +3. Determine which perimeter the bug affects + +**When reporting**: + +Use the [bug report template](.github/ISSUE_TEMPLATE/bug_report.md) and include: + +- Clear, descriptive title +- Environment details (OS, versions, toolchain) +- Steps to reproduce +- Expected vs actual behaviour +- Logs, screenshots, or minimal reproduction + +### Suggesting Features + +**Before suggesting**: +1. Check the [roadmap](ROADMAP.md) if available +2. Search existing issues and discussions +3. Consider which perimeter the feature belongs to + +**When suggesting**: + +Use the [feature request template](.github/ISSUE_TEMPLATE/feature_request.md) and include: + +- Problem statement (what pain point does this solve?) +- Proposed solution +- Alternatives considered +- Which perimeter this affects + +### Your First Contribution + +Look for issues labelled: + +- [`good first issue`](https://github.com/hyperpolymath/safe-brute-force/labels/good%20first%20issue) — Simple Perimeter 3 tasks +- [`help wanted`](https://github.com/hyperpolymath/safe-brute-force/labels/help%20wanted) — Community help needed +- [`documentation`](https://github.com/hyperpolymath/safe-brute-force/labels/documentation) — Docs improvements +- [`perimeter-3`](https://github.com/hyperpolymath/safe-brute-force/labels/perimeter-3) — Community sandbox scope + +--- + +## Development Workflow + +### Branch Naming +.... + +docs/short-description # Documentation (P3) test/what-added # Test +additions (P3) feat/short-description # New features (P2) +fix/issue-number-description # Bug fixes (P2) refactor/what-changed # +Code improvements (P2) security/what-fixed # Security fixes (P1-2) + +.... + +### Commit Messages + +We follow [Conventional Commits](https://www.conventionalcommits.org/): +.... + +(): + +{empty}[optional body] + +{empty}[optional footer] diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 1885198..0000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,120 +0,0 @@ - -# Clone the repository -git clone https://github.com/hyperpolymath/safe-brute-force.git -cd safe-brute-force - -# Using Nix (recommended for reproducibility) -nix develop - -# Or using toolbox/distrobox -toolbox create safe-brute-force-dev -toolbox enter safe-brute-force-dev -# Install dependencies manually - -# Verify setup -just check # or: cargo check / mix compile / etc. -just test # Run test suite -``` - -### Repository Structure -``` -safe-brute-force/ -├── src/ # Source code (Perimeter 1-2) -├── lib/ # Library code (Perimeter 1-2) -├── extensions/ # Extensions (Perimeter 2) -├── plugins/ # Plugins (Perimeter 2) -├── tools/ # Tooling (Perimeter 2) -├── docs/ # Documentation (Perimeter 3) -│ ├── architecture/ # ADRs, specs (Perimeter 2) -│ └── proposals/ # RFCs (Perimeter 3) -├── examples/ # Examples (Perimeter 3) -├── spec/ # Spec tests (Perimeter 3) -├── tests/ # Test suite (Perimeter 2-3) -├── .well-known/ # Protocol files (Perimeter 1-3) -├── .github/ # GitHub config (Perimeter 1) -│ ├── ISSUE_TEMPLATE/ -│ └── workflows/ -├── CHANGELOG.md -├── CODE_OF_CONDUCT.md -├── CONTRIBUTING.md # This file -├── GOVERNANCE.md -├── LICENSE -├── MAINTAINERS.md -├── README.adoc -├── SECURITY.md -├── flake.nix # Nix flake (Perimeter 1) -└── Justfile # Task runner (Perimeter 1) -``` - ---- - -## How to Contribute - -### Reporting Bugs - -**Before reporting**: -1. Search existing issues -2. Check if it's already fixed in `main` -3. Determine which perimeter the bug affects - -**When reporting**: - -Use the [bug report template](.github/ISSUE_TEMPLATE/bug_report.md) and include: - -- Clear, descriptive title -- Environment details (OS, versions, toolchain) -- Steps to reproduce -- Expected vs actual behaviour -- Logs, screenshots, or minimal reproduction - -### Suggesting Features - -**Before suggesting**: -1. Check the [roadmap](ROADMAP.md) if available -2. Search existing issues and discussions -3. Consider which perimeter the feature belongs to - -**When suggesting**: - -Use the [feature request template](.github/ISSUE_TEMPLATE/feature_request.md) and include: - -- Problem statement (what pain point does this solve?) -- Proposed solution -- Alternatives considered -- Which perimeter this affects - -### Your First Contribution - -Look for issues labelled: - -- [`good first issue`](https://github.com/hyperpolymath/safe-brute-force/labels/good%20first%20issue) — Simple Perimeter 3 tasks -- [`help wanted`](https://github.com/hyperpolymath/safe-brute-force/labels/help%20wanted) — Community help needed -- [`documentation`](https://github.com/hyperpolymath/safe-brute-force/labels/documentation) — Docs improvements -- [`perimeter-3`](https://github.com/hyperpolymath/safe-brute-force/labels/perimeter-3) — Community sandbox scope - ---- - -## Development Workflow - -### Branch Naming -``` -docs/short-description # Documentation (P3) -test/what-added # Test additions (P3) -feat/short-description # New features (P2) -fix/issue-number-description # Bug fixes (P2) -refactor/what-changed # Code improvements (P2) -security/what-fixed # Security fixes (P1-2) -``` - -### Commit Messages - -We follow [Conventional Commits](https://www.conventionalcommits.org/): -``` -(): - -[optional body] - -[optional footer] diff --git a/GOVERNANCE.adoc b/GOVERNANCE.adoc new file mode 100644 index 0000000..9b836fb --- /dev/null +++ b/GOVERNANCE.adoc @@ -0,0 +1,60 @@ +== Governance + +=== Overview + +This project is governed by the following principles and structures to +ensure transparent, inclusive, and effective decision-making. + +=== Roles and Responsibilities + +==== Maintainers + +Maintainers are responsible for: - Reviewing and merging pull requests - +Managing releases and versioning - Ensuring code quality and standards - +Triaging issues and bug reports - Community engagement and support + +==== Contributors + +Contributors are expected to: - Follow the code of conduct - Submit +well-documented pull requests - Write tests for new functionality - +Maintain existing tests - Update documentation as needed + +=== Decision Making + +==== Minor Changes + +* Can be made by any maintainer +* Include bug fixes, documentation updates, dependency updates + +==== Major Changes + +* Require discussion in issues or pull requests +* Include new features, architectural changes, API changes +* Need approval from at least 2 maintainers + +==== Breaking Changes + +* Require RFC (Request for Comments) process +* Need approval from majority of maintainers +* Must include migration guide + +=== Code of Conduct + +All participants are expected to follow our Code of Conduct. Violations +can be reported to the maintainers. + +=== Communication + +* *Issues*: For bug reports and feature requests +* *Discussions*: For questions and general discussion +* *Pull Requests*: For code contributions + +=== Licensing + +All contributions are made under the terms of the repository’s LICENSE +file. By submitting a pull request, you agree to license your +contributions accordingly. + +''''' + +_Last updated: 2026-07-18_ diff --git a/GOVERNANCE.md b/GOVERNANCE.md deleted file mode 100644 index e27364c..0000000 --- a/GOVERNANCE.md +++ /dev/null @@ -1,60 +0,0 @@ -# Governance - -## Overview - -This project is governed by the following principles and structures to ensure transparent, inclusive, and effective decision-making. - -## Roles and Responsibilities - -### Maintainers - -Maintainers are responsible for: -- Reviewing and merging pull requests -- Managing releases and versioning -- Ensuring code quality and standards -- Triaging issues and bug reports -- Community engagement and support - -### Contributors - -Contributors are expected to: -- Follow the code of conduct -- Submit well-documented pull requests -- Write tests for new functionality -- Maintain existing tests -- Update documentation as needed - -## Decision Making - -### Minor Changes -- Can be made by any maintainer -- Include bug fixes, documentation updates, dependency updates - -### Major Changes -- Require discussion in issues or pull requests -- Include new features, architectural changes, API changes -- Need approval from at least 2 maintainers - -### Breaking Changes -- Require RFC (Request for Comments) process -- Need approval from majority of maintainers -- Must include migration guide - -## Code of Conduct - -All participants are expected to follow our Code of Conduct. Violations can be reported to the maintainers. - -## Communication - -- **Issues**: For bug reports and feature requests -- **Discussions**: For questions and general discussion -- **Pull Requests**: For code contributions - -## Licensing - -All contributions are made under the terms of the repository's LICENSE file. -By submitting a pull request, you agree to license your contributions accordingly. - ---- - -*Last updated: 2026-07-18* diff --git a/MAINTAINERS.adoc b/MAINTAINERS.adoc index aa23a55..eeb2340 100644 --- a/MAINTAINERS.adoc +++ b/MAINTAINERS.adoc @@ -1,48 +1,187 @@ -// SPDX-License-Identifier: CC-BY-SA-4.0 -// Copyright (c) Jonathan D.A. Jewell -= Maintainers -:toc: preamble +== Maintainers -This document lists the maintainers of this project and their responsibilities. +This document lists the maintainers of the SafeBruteForce project. -== Current Maintainers +=== Current Maintainers -[cols="2,3,2",options="header"] -|=== -| Name | Role | Contact +==== Lead Maintainer -| Jonathan D.A. Jewell -| Lead Maintainer -| https://github.com/hyperpolymath[@hyperpolymath] -|=== +*Hyperpolymath* - GitHub: +https://github.com/Hyperpolymath[@Hyperpolymath] - Role: Project +Creator, Lead Developer, Security Architect - Responsibilities: - +Overall project direction and vision - Security architecture and ethical +guidelines - Final approval on major changes - Release management - +Legal and compliance oversight - Focus Areas: LFE/Erlang core, state +management, safety mechanisms - Availability: Best effort, check GitHub +for response times - PGP Key: [To be added] -== Responsibilities +=== Maintainer Responsibilities -Maintainers are responsible for: +Maintainers of SafeBruteForce are responsible for: -* Reviewing and merging pull requests -* Triaging issues and feature requests -* Ensuring code quality and security standards -* Managing releases and versioning -* Upholding the project's code of conduct +==== Code Review -== Becoming a Maintainer +* Review and merge pull requests +* Ensure code quality and consistency +* Verify safety mechanisms remain intact +* Check for security vulnerabilities +* Validate test coverage -Contributors who demonstrate: +==== Security -* Consistent, high-quality contributions -* Understanding of the project's goals and standards -* Constructive participation in discussions -* Commitment to the project's long-term health +* Review security implications of changes +* Ensure ethical use guidelines are maintained +* Verify authorization checks remain in place +* Monitor for potential misuse +* Coordinate responsible disclosure -May be invited to become maintainers at the discretion of existing maintainers. +==== Documentation -== Decision Making +* Keep documentation up-to-date +* Review documentation PRs +* Ensure examples are accurate +* Maintain API reference +* Update security guidelines -* Routine decisions (bug fixes, minor improvements) can be made by any maintainer -* Significant changes require discussion and consensus among maintainers -* Breaking changes or major features should be discussed in issues before implementation +==== Community -== Contact +* Respond to issues and discussions +* Help contributors get started +* Enforce Code of Conduct +* Foster welcoming environment +* Recognize contributors -For questions about project governance, open an issue or contact the maintainers listed above. +==== Releases + +* Manage version numbers (SemVer) +* Create release notes +* Tag releases +* Update CHANGELOG.md +* Announce releases + +=== Becoming a Maintainer + +SafeBruteForce follows a *graduated trust model* aligned with the TPCF +(Tri-Perimeter Contribution Framework): + +==== Path to Maintainership + +*Perimeter 3: Community Sandbox (Current)* - Open contribution without +pre-approval - All contributions welcome - Community review process - +Focus on building trust + +*Perimeter 2: Trusted Contributor* (Future) - Consistent high-quality +contributions (10+ accepted PRs) - Demonstrated understanding of +security implications - Active participation in reviews - Commitment to +ethical guidelines - Direct commit access to non-critical paths + +*Perimeter 1: Core Maintainer* (Future) - Deep understanding of project +architecture - Proven commitment over 6+ months - Security expertise - +Community respect and trust - Full commit access + +==== Nomination Process + +[arabic] +. *Self-nomination or nomination by existing maintainer* +* Open an issue titled "`Maintainer Nomination: [Your Name]`" +* Include contribution history +* Describe areas of expertise +* Explain motivation and time commitment +. *Community Discussion* +* Open discussion period (2 weeks minimum) +* Existing maintainers provide feedback +* Community input welcome +. *Decision* +* Consensus among existing maintainers +* Focus on: contribution quality, security awareness, ethical alignment, +communication skills +. *Onboarding* +* Grant appropriate access levels +* Add to MAINTAINERS.md +* Announce to community +* Provide mentorship period + +=== Maintainer Expectations + +==== Time Commitment + +* No strict requirements (this is volunteer work) +* Best effort response to issues/PRs +* Communicate availability changes +* Step down gracefully if unable to continue + +==== Technical Requirements + +* Understanding of Erlang/OTP and LFE +* Security testing knowledge +* Git/GitHub workflow proficiency +* Familiarity with ethical hacking principles + +==== Ethical Requirements + +* Commitment to authorized testing only +* Understanding of legal frameworks (CFAA, GDPR, etc.) +* Responsible disclosure practices +* Alignment with safety-first philosophy + +==== Communication + +* Professional and respectful +* Transparent decision-making +* Responsive to community +* Clear, constructive feedback + +=== Emeritus Maintainers + +Maintainers who step down in good standing are listed here with +gratitude: + +_None yet - project is new!_ + +=== Governance + +==== Decision Making + +*Consensus Model*: - Aim for consensus on all decisions - Open +discussion period for major changes - Lead maintainer has final say if +consensus cannot be reached - All decisions documented in issues/PRs + +*Major Decisions* (require consensus): - Architecture changes - Safety +mechanism modifications - License changes - New maintainer additions - +Security policy updates + +*Minor Decisions* (single maintainer): - Bug fixes - Documentation +updates - Dependency updates - Code formatting + +==== Conflict Resolution + +[arabic] +. *Discussion*: Open, respectful dialogue +. *Mediation*: Neutral third party if needed +. *Vote*: Maintainers vote if discussion fails +. *Lead Decision*: Lead maintainer decides if vote is tied +. *Code of Conduct*: Severe conflicts escalate to CoC enforcement + +=== Contact + +* *General Inquiries*: Open an issue on GitHub +* *Security Issues*: security@[domain] (private, encrypted) +* *Code of Conduct*: conduct@[domain] (private) +* *Maintainer Discussion*: maintainers@[domain] (private list) + +=== Updates + +This document is reviewed and updated: - Annually (minimum) - When +maintainers change - When governance evolves - As project grows + +*Last Updated*: 2025-01-15 *Next Review*: 2026-01-15 + +''''' + +=== Acknowledgments + +We are grateful for all contributions, whether code, documentation, bug +reports, or community support. Every contribution helps make +SafeBruteForce better and more secure. + +*Thank you to all contributors!* 🛡️ diff --git a/MAINTAINERS.md b/MAINTAINERS.md deleted file mode 100644 index e3a3c6c..0000000 --- a/MAINTAINERS.md +++ /dev/null @@ -1,201 +0,0 @@ - -# Maintainers - -This document lists the maintainers of the SafeBruteForce project. - -## Current Maintainers - -### Lead Maintainer - -**Hyperpolymath** -- GitHub: [@Hyperpolymath](https://github.com/Hyperpolymath) -- Role: Project Creator, Lead Developer, Security Architect -- Responsibilities: - - Overall project direction and vision - - Security architecture and ethical guidelines - - Final approval on major changes - - Release management - - Legal and compliance oversight -- Focus Areas: LFE/Erlang core, state management, safety mechanisms -- Availability: Best effort, check GitHub for response times -- PGP Key: [To be added] - -## Maintainer Responsibilities - -Maintainers of SafeBruteForce are responsible for: - -### Code Review -- Review and merge pull requests -- Ensure code quality and consistency -- Verify safety mechanisms remain intact -- Check for security vulnerabilities -- Validate test coverage - -### Security -- Review security implications of changes -- Ensure ethical use guidelines are maintained -- Verify authorization checks remain in place -- Monitor for potential misuse -- Coordinate responsible disclosure - -### Documentation -- Keep documentation up-to-date -- Review documentation PRs -- Ensure examples are accurate -- Maintain API reference -- Update security guidelines - -### Community -- Respond to issues and discussions -- Help contributors get started -- Enforce Code of Conduct -- Foster welcoming environment -- Recognize contributors - -### Releases -- Manage version numbers (SemVer) -- Create release notes -- Tag releases -- Update CHANGELOG.md -- Announce releases - -## Becoming a Maintainer - -SafeBruteForce follows a **graduated trust model** aligned with the TPCF (Tri-Perimeter Contribution Framework): - -### Path to Maintainership - -**Perimeter 3: Community Sandbox (Current)** -- Open contribution without pre-approval -- All contributions welcome -- Community review process -- Focus on building trust - -**Perimeter 2: Trusted Contributor** (Future) -- Consistent high-quality contributions (10+ accepted PRs) -- Demonstrated understanding of security implications -- Active participation in reviews -- Commitment to ethical guidelines -- Direct commit access to non-critical paths - -**Perimeter 1: Core Maintainer** (Future) -- Deep understanding of project architecture -- Proven commitment over 6+ months -- Security expertise -- Community respect and trust -- Full commit access - -### Nomination Process - -1. **Self-nomination or nomination by existing maintainer** - - Open an issue titled "Maintainer Nomination: [Your Name]" - - Include contribution history - - Describe areas of expertise - - Explain motivation and time commitment - -2. **Community Discussion** - - Open discussion period (2 weeks minimum) - - Existing maintainers provide feedback - - Community input welcome - -3. **Decision** - - Consensus among existing maintainers - - Focus on: contribution quality, security awareness, ethical alignment, communication skills - -4. **Onboarding** - - Grant appropriate access levels - - Add to MAINTAINERS.md - - Announce to community - - Provide mentorship period - -## Maintainer Expectations - -### Time Commitment -- No strict requirements (this is volunteer work) -- Best effort response to issues/PRs -- Communicate availability changes -- Step down gracefully if unable to continue - -### Technical Requirements -- Understanding of Erlang/OTP and LFE -- Security testing knowledge -- Git/GitHub workflow proficiency -- Familiarity with ethical hacking principles - -### Ethical Requirements -- Commitment to authorized testing only -- Understanding of legal frameworks (CFAA, GDPR, etc.) -- Responsible disclosure practices -- Alignment with safety-first philosophy - -### Communication -- Professional and respectful -- Transparent decision-making -- Responsive to community -- Clear, constructive feedback - -## Emeritus Maintainers - -Maintainers who step down in good standing are listed here with gratitude: - -*None yet - project is new!* - -## Governance - -### Decision Making - -**Consensus Model**: -- Aim for consensus on all decisions -- Open discussion period for major changes -- Lead maintainer has final say if consensus cannot be reached -- All decisions documented in issues/PRs - -**Major Decisions** (require consensus): -- Architecture changes -- Safety mechanism modifications -- License changes -- New maintainer additions -- Security policy updates - -**Minor Decisions** (single maintainer): -- Bug fixes -- Documentation updates -- Dependency updates -- Code formatting - -### Conflict Resolution - -1. **Discussion**: Open, respectful dialogue -2. **Mediation**: Neutral third party if needed -3. **Vote**: Maintainers vote if discussion fails -4. **Lead Decision**: Lead maintainer decides if vote is tied -5. **Code of Conduct**: Severe conflicts escalate to CoC enforcement - -## Contact - -- **General Inquiries**: Open an issue on GitHub -- **Security Issues**: security@[domain] (private, encrypted) -- **Code of Conduct**: conduct@[domain] (private) -- **Maintainer Discussion**: maintainers@[domain] (private list) - -## Updates - -This document is reviewed and updated: -- Annually (minimum) -- When maintainers change -- When governance evolves -- As project grows - -**Last Updated**: 2025-01-15 -**Next Review**: 2026-01-15 - ---- - -## Acknowledgments - -We are grateful for all contributions, whether code, documentation, bug reports, or community support. Every contribution helps make SafeBruteForce better and more secure. - -**Thank you to all contributors!** 🛡️ diff --git a/PROJECT_SUMMARY.adoc b/PROJECT_SUMMARY.adoc new file mode 100644 index 0000000..3075c84 --- /dev/null +++ b/PROJECT_SUMMARY.adoc @@ -0,0 +1,663 @@ +== SafeBruteForce v0.1.0 - Complete Implementation Summary + +This document summarizes the comprehensive implementation completed in +this session. + +=== Overview + +SafeBruteForce is now a *production-ready, ethical brute-force utility* +built with Erlang/OTP and LFE (Lisp Flavored Erlang). The implementation +includes 30+ files, 5000+ lines of code, comprehensive documentation, +and extensive safety mechanisms. + +=== What Was Built + +==== Core Architecture (11 LFE Modules) + +===== 1. *sbf_state.lfe* (State Management) + +* gen_statem-based state machine +* 4 states: running, paused, waiting_confirmation, stopped +* Automatic safety pause every 25 attempts +* Manual pause/resume controls +* Success/failure tracking +* Comprehensive statistics +* *Lines:* ~250 + +===== 2. *sbf_executor.lfe* (Execution Engine) + +* gen_server-based worker pool +* HTTP/HTTPS request execution +* Custom function validators +* Mock target support +* Rate-limited execution +* Result aggregation +* *Lines:* ~280 + +===== 3. *sbf_patterns.lfe* (Pattern Generation) + +* Wordlist loading and mutations +* Charset combinations +* Sequential number generation +* Date pattern generation +* Common password lists +* Custom pattern functions +* Leet speak transformations +* *Lines:* ~330 + +===== 4. *sbf_output.lfe* (Result Management) + +* Filtered output (successes/failures/all) +* Colorized console output +* ASCII art banners +* Progress bars +* Statistics dashboards +* File export +* Clean formatting +* *Lines:* ~240 + +===== 5. *sbf_checkpoint.lfe* (Checkpoint System) + +* Auto-save functionality +* Manual checkpoint creation +* Restore from checkpoints +* Checkpoint metadata +* List/delete operations +* Binary serialization +* *Lines:* ~200 + +===== 6. *sbf.lfe* (Main API) + +* High-level convenience functions +* Synchronous/asynchronous execution +* Checkpoint operations +* Status and control +* Pattern/target configuration +* Batch processing +* *Lines:* ~300 + +===== 7. *sbf_app.lfe* (Application Behavior) + +* OTP application callbacks +* Configuration loading +* Application lifecycle +* *Lines:* ~50 + +===== 8. *sbf_sup.lfe* (Supervisor) + +* Supervision tree +* Child specifications +* Fault tolerance +* one_for_one strategy +* *Lines:* ~50 + +===== 9. *sbf_logger.lfe* (Logging System) + +* Structured logging +* Multiple log levels +* File logging +* Specialized loggers +* Timestamp formatting +* *Lines:* ~180 + +===== 10. *sbf_progress.lfe* (Progress Tracking) + +* ETA calculation +* Progress bars +* Rate calculation +* Duration formatting +* Statistics +* *Lines:* ~150 + +===== 11. *sbf_rate_limiter.lfe* (Rate Limiting) + +* Token bucket algorithm +* gen_server-based +* Configurable rates +* Automatic token refill +* *Lines:* ~130 + +*Total Core Code: ~2,160 lines* + +==== Testing (1 Module) + +===== sbf_tests.lfe + +* Pattern generation tests +* State machine lifecycle tests +* Executor tests with mocks +* Checkpoint save/restore tests +* Output formatting tests +* Safety mechanism tests +* Integration tests +* *Lines:* ~350 + +==== Examples (3 Modules) + +===== 1. http_login_test.lfe + +* HTTP form authentication +* JSON API testing +* Custom headers +* Success/failure patterns +* *Lines:* ~80 + +===== 2. pin_code_test.lfe + +* 4-digit PIN testing +* 6-digit PIN testing +* Date-based PINs +* Custom validators +* *Lines:* ~70 + +===== 3. custom_pattern_test.lfe + +* Company-based patterns +* Season/year combinations +* Keyboard patterns +* Custom generators +* *Lines:* ~90 + +*Total Example Code: ~240 lines* + +==== Documentation (6 Files) + +===== 1. README.md + +* Complete project overview +* Feature highlights +* Installation instructions +* Quick start guide +* Usage examples +* Architecture diagrams +* Legal/ethical guidelines +* *Lines:* ~410 + +===== 2. docs/USAGE.md + +* Comprehensive usage guide +* Pattern strategies +* Target configuration +* Safety features +* Checkpoint system +* Advanced usage +* Configuration reference +* *Lines:* ~450 + +===== 3. docs/SECURITY.md + +* Legal considerations +* Ethical guidelines +* Authorization requirements +* Responsible testing practices +* Data protection +* Incident response +* Compliance guidance +* *Lines:* ~480 + +===== 4. docs/CONTRIBUTING.md + +* Code of conduct +* Development setup +* Contribution workflow +* Coding standards +* Testing requirements +* Documentation standards +* Security review +* *Lines:* ~460 + +===== 5. docs/API_REFERENCE.md + +* Complete API documentation +* All module references +* Function signatures +* Parameters and returns +* Code examples +* Configuration reference +* *Lines:* ~670 + +===== 6. docs/QUICKSTART.md + +* 5-minute getting started +* Installation steps +* First examples +* Common commands +* Troubleshooting +* Best practices +* *Lines:* ~350 + +*Total Documentation: ~2,820 lines* + +==== Configuration & Build Files + +===== 1. rebar.config + +* Project dependencies +* LFE plugin configuration +* Profile settings +* Release configuration + +===== 2. config/sys.config + +* Application environment +* Pause interval +* Worker limits +* Rate limiting +* Checkpoint settings + +===== 3. config/vm.args + +* VM configuration +* Node naming +* Resource limits +* Crash dump location + +===== 4. Makefile + +* Build commands +* Test runners +* Development helpers +* Release builders +* Utility functions + +===== 5. src/safe_brute_force.app.src + +* OTP application resource +* Application metadata +* Dependencies +* Environment defaults + +===== 6. sbf_cli (Escript) + +* Command-line interface +* Authorization prompts +* Help system +* *Lines:* ~180 + +===== 7. CHANGELOG.md + +* Version history +* Feature list +* Roadmap +* *Lines:* ~150 + +===== 8. .gitignore + +* Erlang build artifacts +* Checkpoints +* Logs +* Sensitive data patterns + +==== Wordlists (2 Files) + +===== 1. priv/wordlists/common-passwords.txt + +* 60+ common passwords +* Real-world examples +* Testing data + +===== 2. priv/wordlists/test-wordlist.txt + +* Development test data +* Simple patterns +* Quick testing + +==== Supporting Files + +===== 1. CLAUDE.md + +* AI assistant guidance +* Project overview +* Ethical boundaries +* Development patterns +* *Lines:* ~200 + +=== Key Features Implemented + +==== Safety Mechanisms ✅ + +[arabic] +. *Automatic Pause System* +* Triggers every 25 attempts (configurable) +* Requires explicit user confirmation +* Cannot be fully disabled in production +* Clear visual indicators +. *Rate Limiting* +* Token bucket algorithm +* Configurable requests per second +* Prevents system overload +* Respectful testing +. *Authorization Checks* +* CLI prompts for permission +* Legal warnings +* Explicit confirmation required +* Audit logging +. *State Management* +* Robust state machine +* Safe transitions +* Error handling +* Recovery mechanisms + +==== Pattern Strategies ✅ + +[arabic] +. *Wordlist Support* +* File loading +* Mutation engine (leet speak, capitalization) +* Three mutation levels (minimal, standard, aggressive) +* Custom wordlists +. *Charset Combinations* +* Configurable character sets +* Variable length ranges +* Efficient generation +* Large combination support +. *Built-in Patterns* +* Common passwords +* PIN codes +* Date patterns +* Sequential numbers +* Hex colors +. *Custom Generators* +* Lambda function support +* Full flexibility +* Integration with other modules + +==== Target Support ✅ + +[arabic] +. *HTTP/HTTPS* +* POST and GET methods +* JSON and form-encoded bodies +* Custom headers +* Success/failure pattern matching +* Status code analysis +. *Custom Functions* +* Any validation logic +* Integration with existing systems +* Full Erlang/LFE power +. *Mock Targets* +* Testing without external dependencies +* Development support +* CI/CD friendly + +==== Operational Features ✅ + +[arabic] +. *Checkpoint System* +* Auto-save every N attempts +* Manual save/restore +* Binary serialization +* Metadata tracking +* List/delete operations +. *Progress Tracking* +* Real-time progress bars +* ETA calculations +* Rate metrics +* Time elapsed +* Percent complete +. *Result Management* +* Success/failure filtering +* Pattern tracking +* Statistics aggregation +* File export +* Clean console output +. *Logging* +* Multiple log levels +* File logging +* Structured data +* Timestamps +* Specialized loggers + +==== Development Tools ✅ + +[arabic] +. *Comprehensive Tests* +* Unit tests +* Integration tests +* State machine tests +* Safety verification +* Edge case coverage +. *Build System* +* Rebar3 integration +* Make targets +* Clean/compile/test +* Release building +. *CLI Interface* +* Escript-based +* User-friendly +* Authorization prompts +* Multiple modes +. *Documentation* +* API reference +* Usage guide +* Security practices +* Contributing guide +* Quick start +* README + +=== Statistics + +==== Code Metrics + +* *Total Files:* 30+ +* *Total Lines of Code:* ~5,000+ +* *Core Modules:* 11 +* *Test Modules:* 1 +* *Example Modules:* 3 +* *Documentation Files:* 6 +* *Configuration Files:* 8 + +==== Module Breakdown + +[cols=",,,",options="header",] +|=== +|Module |Purpose |Lines |Complexity +|sbf_state |State machine |250 |High +|sbf_executor |Worker pool |280 |High +|sbf_patterns |Pattern gen |330 |Medium +|sbf_output |Formatting |240 |Medium +|sbf_checkpoint |Save/restore |200 |Medium +|sbf |Main API |300 |Medium +|sbf_logger |Logging |180 |Low +|sbf_progress |Progress |150 |Low +|sbf_rate_limiter |Rate limit |130 |Medium +|sbf_app |Application |50 |Low +|sbf_sup |Supervisor |50 |Low +|=== + +==== Documentation Metrics + +* *README:* 410 lines +* *Usage Guide:* 450 lines +* *Security Guide:* 480 lines +* *Contributing:* 460 lines +* *API Reference:* 670 lines +* *Quick Start:* 350 lines +* *Total Docs:* 2,820 lines + +=== Architecture Highlights + +==== OTP Design Patterns + +[arabic] +. *Supervision Tree* +* one_for_one strategy +* Automatic restart +* Fault isolation +* Process monitoring +. *gen_statem (State Machine)* +* Explicit states +* Safe transitions +* Event handling +* Timeout support +. *gen_server (Worker Pool)* +* Concurrent execution +* Message passing +* State encapsulation +* Call/cast patterns + +==== Concurrency Model + +* Erlang lightweight processes +* Message-based communication +* No shared state +* Fault tolerance +* Hot code reloading + +==== Safety by Design + +* Immutable data structures +* Pattern matching +* Tagged return values +* Explicit error handling +* No silent failures + +=== Ethical Considerations + +==== Built-in Safeguards + +[arabic] +. *Cannot be easily weaponized* +* Mandatory pause system +* Authorization prompts +* Clear identification +* Audit logging +. *Educational focus* +* Comprehensive documentation +* Legal warnings +* Ethical guidelines +* Responsible disclosure +. *Defensive security* +* Helps organizations +* Password policy testing +* Vulnerability assessment +* Controlled environment + +==== Legal Compliance + +* CFAA awareness +* GDPR considerations +* Authorization requirements +* Responsible disclosure +* Penetration testing standards + +=== Use Cases + +==== Approved Applications + +[arabic] +. *Penetration Testing* +* Authorized engagements +* Written permission +* Controlled scope +* Professional use +. *CTF Competitions* +* Challenge solving +* Skill development +* Educational context +* Legal framework +. *Security Research* +* Own systems +* Academic study +* Tool development +* Methodology research +. *Password Policy Testing* +* Organizational use +* Policy validation +* Compliance checking +* Risk assessment + +=== Future Enhancements (Roadmap) + +==== v0.2.0 (Planned) + +* SSH brute-force module +* FTP support +* Database testing +* Distributed workers +* Web UI dashboard +* PDF/HTML reports + +==== v0.3.0 (Future) + +* ML pattern generation +* Cloud integration +* SIEM integration +* Plugin system +* Advanced analytics + +=== Quality Assurance + +==== Testing Coverage + +* ✅ Unit tests for all modules +* ✅ Integration tests +* ✅ State machine verification +* ✅ Safety mechanism tests +* ✅ Error handling tests +* ✅ Edge case coverage + +==== Code Quality + +* ✅ Consistent style +* ✅ Comprehensive documentation +* ✅ Clear naming +* ✅ Error handling +* ✅ Type safety (Erlang patterns) + +==== Documentation Quality + +* ✅ Complete API reference +* ✅ Usage examples +* ✅ Security guidelines +* ✅ Contributing guide +* ✅ Quick start +* ✅ Troubleshooting + +=== Deployment + +==== Build Process + +[source,bash] +---- +rebar3 compile # Compile code +rebar3 lfe test # Run tests +rebar3 release # Build release +---- + +==== Configuration + +* Environment variables +* Config files +* Runtime configuration +* VM tuning + +==== Distribution + +* Standalone escript +* OTP release +* Docker support (future) +* Package managers (future) + +=== Conclusion + +This implementation represents a *complete, production-ready, ethical +brute-force utility* with: + +✅ Robust architecture (Erlang/OTP) ✅ Comprehensive safety mechanisms +✅ Extensive documentation ✅ Full test coverage ✅ Multiple use cases +✅ Legal/ethical framework ✅ Professional quality ✅ Maintainable +codebase ✅ Clear roadmap ✅ Community-ready + +The project is ready for: - Professional penetration testing - +Educational use - CTF competitions - Security research - Open source +contribution - Production deployment + +*Total development effort:* Comprehensive autonomous implementation +maximizing the value of available Claude credits while maintaining the +highest standards of safety, ethics, and code quality. + +''''' + +*For any questions or clarifications, refer to the comprehensive +documentation in the `+docs/+` directory.* diff --git a/PROJECT_SUMMARY.md b/PROJECT_SUMMARY.md deleted file mode 100644 index f9193a8..0000000 --- a/PROJECT_SUMMARY.md +++ /dev/null @@ -1,645 +0,0 @@ - -# SafeBruteForce v0.1.0 - Complete Implementation Summary - -This document summarizes the comprehensive implementation completed in this session. - -## Overview - -SafeBruteForce is now a **production-ready, ethical brute-force utility** built with Erlang/OTP and LFE (Lisp Flavored Erlang). The implementation includes 30+ files, 5000+ lines of code, comprehensive documentation, and extensive safety mechanisms. - -## What Was Built - -### Core Architecture (11 LFE Modules) - -#### 1. **sbf_state.lfe** (State Management) -- gen_statem-based state machine -- 4 states: running, paused, waiting_confirmation, stopped -- Automatic safety pause every 25 attempts -- Manual pause/resume controls -- Success/failure tracking -- Comprehensive statistics -- **Lines:** ~250 - -#### 2. **sbf_executor.lfe** (Execution Engine) -- gen_server-based worker pool -- HTTP/HTTPS request execution -- Custom function validators -- Mock target support -- Rate-limited execution -- Result aggregation -- **Lines:** ~280 - -#### 3. **sbf_patterns.lfe** (Pattern Generation) -- Wordlist loading and mutations -- Charset combinations -- Sequential number generation -- Date pattern generation -- Common password lists -- Custom pattern functions -- Leet speak transformations -- **Lines:** ~330 - -#### 4. **sbf_output.lfe** (Result Management) -- Filtered output (successes/failures/all) -- Colorized console output -- ASCII art banners -- Progress bars -- Statistics dashboards -- File export -- Clean formatting -- **Lines:** ~240 - -#### 5. **sbf_checkpoint.lfe** (Checkpoint System) -- Auto-save functionality -- Manual checkpoint creation -- Restore from checkpoints -- Checkpoint metadata -- List/delete operations -- Binary serialization -- **Lines:** ~200 - -#### 6. **sbf.lfe** (Main API) -- High-level convenience functions -- Synchronous/asynchronous execution -- Checkpoint operations -- Status and control -- Pattern/target configuration -- Batch processing -- **Lines:** ~300 - -#### 7. **sbf_app.lfe** (Application Behavior) -- OTP application callbacks -- Configuration loading -- Application lifecycle -- **Lines:** ~50 - -#### 8. **sbf_sup.lfe** (Supervisor) -- Supervision tree -- Child specifications -- Fault tolerance -- one_for_one strategy -- **Lines:** ~50 - -#### 9. **sbf_logger.lfe** (Logging System) -- Structured logging -- Multiple log levels -- File logging -- Specialized loggers -- Timestamp formatting -- **Lines:** ~180 - -#### 10. **sbf_progress.lfe** (Progress Tracking) -- ETA calculation -- Progress bars -- Rate calculation -- Duration formatting -- Statistics -- **Lines:** ~150 - -#### 11. **sbf_rate_limiter.lfe** (Rate Limiting) -- Token bucket algorithm -- gen_server-based -- Configurable rates -- Automatic token refill -- **Lines:** ~130 - -**Total Core Code: ~2,160 lines** - -### Testing (1 Module) - -#### sbf_tests.lfe -- Pattern generation tests -- State machine lifecycle tests -- Executor tests with mocks -- Checkpoint save/restore tests -- Output formatting tests -- Safety mechanism tests -- Integration tests -- **Lines:** ~350 - -### Examples (3 Modules) - -#### 1. http_login_test.lfe -- HTTP form authentication -- JSON API testing -- Custom headers -- Success/failure patterns -- **Lines:** ~80 - -#### 2. pin_code_test.lfe -- 4-digit PIN testing -- 6-digit PIN testing -- Date-based PINs -- Custom validators -- **Lines:** ~70 - -#### 3. custom_pattern_test.lfe -- Company-based patterns -- Season/year combinations -- Keyboard patterns -- Custom generators -- **Lines:** ~90 - -**Total Example Code: ~240 lines** - -### Documentation (6 Files) - -#### 1. README.md -- Complete project overview -- Feature highlights -- Installation instructions -- Quick start guide -- Usage examples -- Architecture diagrams -- Legal/ethical guidelines -- **Lines:** ~410 - -#### 2. docs/USAGE.md -- Comprehensive usage guide -- Pattern strategies -- Target configuration -- Safety features -- Checkpoint system -- Advanced usage -- Configuration reference -- **Lines:** ~450 - -#### 3. docs/SECURITY.md -- Legal considerations -- Ethical guidelines -- Authorization requirements -- Responsible testing practices -- Data protection -- Incident response -- Compliance guidance -- **Lines:** ~480 - -#### 4. docs/CONTRIBUTING.md -- Code of conduct -- Development setup -- Contribution workflow -- Coding standards -- Testing requirements -- Documentation standards -- Security review -- **Lines:** ~460 - -#### 5. docs/API_REFERENCE.md -- Complete API documentation -- All module references -- Function signatures -- Parameters and returns -- Code examples -- Configuration reference -- **Lines:** ~670 - -#### 6. docs/QUICKSTART.md -- 5-minute getting started -- Installation steps -- First examples -- Common commands -- Troubleshooting -- Best practices -- **Lines:** ~350 - -**Total Documentation: ~2,820 lines** - -### Configuration & Build Files - -#### 1. rebar.config -- Project dependencies -- LFE plugin configuration -- Profile settings -- Release configuration - -#### 2. config/sys.config -- Application environment -- Pause interval -- Worker limits -- Rate limiting -- Checkpoint settings - -#### 3. config/vm.args -- VM configuration -- Node naming -- Resource limits -- Crash dump location - -#### 4. Makefile -- Build commands -- Test runners -- Development helpers -- Release builders -- Utility functions - -#### 5. src/safe_brute_force.app.src -- OTP application resource -- Application metadata -- Dependencies -- Environment defaults - -#### 6. sbf_cli (Escript) -- Command-line interface -- Authorization prompts -- Help system -- **Lines:** ~180 - -#### 7. CHANGELOG.md -- Version history -- Feature list -- Roadmap -- **Lines:** ~150 - -#### 8. .gitignore -- Erlang build artifacts -- Checkpoints -- Logs -- Sensitive data patterns - -### Wordlists (2 Files) - -#### 1. priv/wordlists/common-passwords.txt -- 60+ common passwords -- Real-world examples -- Testing data - -#### 2. priv/wordlists/test-wordlist.txt -- Development test data -- Simple patterns -- Quick testing - -### Supporting Files - -#### 1. CLAUDE.md -- AI assistant guidance -- Project overview -- Ethical boundaries -- Development patterns -- **Lines:** ~200 - -## Key Features Implemented - -### Safety Mechanisms ✅ - -1. **Automatic Pause System** - - Triggers every 25 attempts (configurable) - - Requires explicit user confirmation - - Cannot be fully disabled in production - - Clear visual indicators - -2. **Rate Limiting** - - Token bucket algorithm - - Configurable requests per second - - Prevents system overload - - Respectful testing - -3. **Authorization Checks** - - CLI prompts for permission - - Legal warnings - - Explicit confirmation required - - Audit logging - -4. **State Management** - - Robust state machine - - Safe transitions - - Error handling - - Recovery mechanisms - -### Pattern Strategies ✅ - -1. **Wordlist Support** - - File loading - - Mutation engine (leet speak, capitalization) - - Three mutation levels (minimal, standard, aggressive) - - Custom wordlists - -2. **Charset Combinations** - - Configurable character sets - - Variable length ranges - - Efficient generation - - Large combination support - -3. **Built-in Patterns** - - Common passwords - - PIN codes - - Date patterns - - Sequential numbers - - Hex colors - -4. **Custom Generators** - - Lambda function support - - Full flexibility - - Integration with other modules - -### Target Support ✅ - -1. **HTTP/HTTPS** - - POST and GET methods - - JSON and form-encoded bodies - - Custom headers - - Success/failure pattern matching - - Status code analysis - -2. **Custom Functions** - - Any validation logic - - Integration with existing systems - - Full Erlang/LFE power - -3. **Mock Targets** - - Testing without external dependencies - - Development support - - CI/CD friendly - -### Operational Features ✅ - -1. **Checkpoint System** - - Auto-save every N attempts - - Manual save/restore - - Binary serialization - - Metadata tracking - - List/delete operations - -2. **Progress Tracking** - - Real-time progress bars - - ETA calculations - - Rate metrics - - Time elapsed - - Percent complete - -3. **Result Management** - - Success/failure filtering - - Pattern tracking - - Statistics aggregation - - File export - - Clean console output - -4. **Logging** - - Multiple log levels - - File logging - - Structured data - - Timestamps - - Specialized loggers - -### Development Tools ✅ - -1. **Comprehensive Tests** - - Unit tests - - Integration tests - - State machine tests - - Safety verification - - Edge case coverage - -2. **Build System** - - Rebar3 integration - - Make targets - - Clean/compile/test - - Release building - -3. **CLI Interface** - - Escript-based - - User-friendly - - Authorization prompts - - Multiple modes - -4. **Documentation** - - API reference - - Usage guide - - Security practices - - Contributing guide - - Quick start - - README - -## Statistics - -### Code Metrics - -- **Total Files:** 30+ -- **Total Lines of Code:** ~5,000+ -- **Core Modules:** 11 -- **Test Modules:** 1 -- **Example Modules:** 3 -- **Documentation Files:** 6 -- **Configuration Files:** 8 - -### Module Breakdown - -| Module | Purpose | Lines | Complexity | -|--------|---------|-------|------------| -| sbf_state | State machine | 250 | High | -| sbf_executor | Worker pool | 280 | High | -| sbf_patterns | Pattern gen | 330 | Medium | -| sbf_output | Formatting | 240 | Medium | -| sbf_checkpoint | Save/restore | 200 | Medium | -| sbf | Main API | 300 | Medium | -| sbf_logger | Logging | 180 | Low | -| sbf_progress | Progress | 150 | Low | -| sbf_rate_limiter | Rate limit | 130 | Medium | -| sbf_app | Application | 50 | Low | -| sbf_sup | Supervisor | 50 | Low | - -### Documentation Metrics - -- **README:** 410 lines -- **Usage Guide:** 450 lines -- **Security Guide:** 480 lines -- **Contributing:** 460 lines -- **API Reference:** 670 lines -- **Quick Start:** 350 lines -- **Total Docs:** 2,820 lines - -## Architecture Highlights - -### OTP Design Patterns - -1. **Supervision Tree** - - one_for_one strategy - - Automatic restart - - Fault isolation - - Process monitoring - -2. **gen_statem (State Machine)** - - Explicit states - - Safe transitions - - Event handling - - Timeout support - -3. **gen_server (Worker Pool)** - - Concurrent execution - - Message passing - - State encapsulation - - Call/cast patterns - -### Concurrency Model - -- Erlang lightweight processes -- Message-based communication -- No shared state -- Fault tolerance -- Hot code reloading - -### Safety by Design - -- Immutable data structures -- Pattern matching -- Tagged return values -- Explicit error handling -- No silent failures - -## Ethical Considerations - -### Built-in Safeguards - -1. **Cannot be easily weaponized** - - Mandatory pause system - - Authorization prompts - - Clear identification - - Audit logging - -2. **Educational focus** - - Comprehensive documentation - - Legal warnings - - Ethical guidelines - - Responsible disclosure - -3. **Defensive security** - - Helps organizations - - Password policy testing - - Vulnerability assessment - - Controlled environment - -### Legal Compliance - -- CFAA awareness -- GDPR considerations -- Authorization requirements -- Responsible disclosure -- Penetration testing standards - -## Use Cases - -### Approved Applications - -1. **Penetration Testing** - - Authorized engagements - - Written permission - - Controlled scope - - Professional use - -2. **CTF Competitions** - - Challenge solving - - Skill development - - Educational context - - Legal framework - -3. **Security Research** - - Own systems - - Academic study - - Tool development - - Methodology research - -4. **Password Policy Testing** - - Organizational use - - Policy validation - - Compliance checking - - Risk assessment - -## Future Enhancements (Roadmap) - -### v0.2.0 (Planned) -- SSH brute-force module -- FTP support -- Database testing -- Distributed workers -- Web UI dashboard -- PDF/HTML reports - -### v0.3.0 (Future) -- ML pattern generation -- Cloud integration -- SIEM integration -- Plugin system -- Advanced analytics - -## Quality Assurance - -### Testing Coverage - -- ✅ Unit tests for all modules -- ✅ Integration tests -- ✅ State machine verification -- ✅ Safety mechanism tests -- ✅ Error handling tests -- ✅ Edge case coverage - -### Code Quality - -- ✅ Consistent style -- ✅ Comprehensive documentation -- ✅ Clear naming -- ✅ Error handling -- ✅ Type safety (Erlang patterns) - -### Documentation Quality - -- ✅ Complete API reference -- ✅ Usage examples -- ✅ Security guidelines -- ✅ Contributing guide -- ✅ Quick start -- ✅ Troubleshooting - -## Deployment - -### Build Process - -```bash -rebar3 compile # Compile code -rebar3 lfe test # Run tests -rebar3 release # Build release -``` - -### Configuration - -- Environment variables -- Config files -- Runtime configuration -- VM tuning - -### Distribution - -- Standalone escript -- OTP release -- Docker support (future) -- Package managers (future) - -## Conclusion - -This implementation represents a **complete, production-ready, ethical brute-force utility** with: - -✅ Robust architecture (Erlang/OTP) -✅ Comprehensive safety mechanisms -✅ Extensive documentation -✅ Full test coverage -✅ Multiple use cases -✅ Legal/ethical framework -✅ Professional quality -✅ Maintainable codebase -✅ Clear roadmap -✅ Community-ready - -The project is ready for: -- Professional penetration testing -- Educational use -- CTF competitions -- Security research -- Open source contribution -- Production deployment - -**Total development effort:** Comprehensive autonomous implementation maximizing the value of available Claude credits while maintaining the highest standards of safety, ethics, and code quality. - ---- - -**For any questions or clarifications, refer to the comprehensive documentation in the `docs/` directory.** diff --git a/RSR_COMPLIANCE.adoc b/RSR_COMPLIANCE.adoc new file mode 100644 index 0000000..6e8bd82 --- /dev/null +++ b/RSR_COMPLIANCE.adoc @@ -0,0 +1,315 @@ +== RSR Framework Compliance Report + +*Project*: SafeBruteForce *Version*: 0.1.0 *Date*: 2025-01-15 +*Compliance Level*: *Bronze* (Working toward Silver) *TPCF Perimeter*: +*3 (Community Sandbox)* + +=== Executive Summary + +SafeBruteForce has achieved *Bronze-level compliance* with the Rhodium +Standard Repository (RSR) Framework. This document details our +compliance status across all 11 RSR categories and our roadmap for +achieving higher levels. + +=== RSR Framework Categories + +==== 1. Documentation ✅ COMPLIANT + +*Required Files:* - ✅ README.md - Comprehensive project overview (410 +lines) - ✅ LICENSE - MIT License (OSI-approved) - ✅ CHANGELOG.md - +Version history and roadmap - ✅ CODE_OF_CONDUCT.md - Contributor +Covenant 2.1 - ✅ CONTRIBUTING.md - Contribution guidelines - ✅ +SECURITY.md - Security policy and responsible disclosure - ✅ +MAINTAINERS.md - Project governance and maintainer list + +*Additional Documentation:* - ✅ docs/USAGE.md - Comprehensive usage +guide (450 lines) - ✅ docs/API_REFERENCE.md - Complete API +documentation (670 lines) - ✅ docs/QUICKSTART.md - 5-minute getting +started guide - ✅ CLAUDE.md - AI assistant-specific guidance - ✅ +PROJECT_SUMMARY.md - Implementation overview + +*Status*: *EXCELLENT* - Exceeds Bronze requirements + +==== 2. .well-known/ Directory ✅ COMPLIANT + +*Required Files:* - ✅ .well-known/security.txt - RFC 9116 compliant - +Contact information - Expires field - Canonical URI - Preferred +languages - Security policy link + +* ✅ .well-known/ai.txt - AI training and usage policy +** Training permissions +** Attribution requirements +** Ethical constraints +** Commercial usage terms +* ✅ .well-known/humans.txt - Attribution and team info +** Team members +** Technology stack +** Project values +** Citation formats + +*Status*: *EXCELLENT* - Full compliance with metadata standards + +==== 3. Build System ✅ COMPLIANT + +*Build Tools:* - ✅ rebar.config - Rebar3 configuration - ✅ Makefile - +Convenient build commands (20+ recipes) - ✅ +src/safe_brute_force.app.src - OTP application resource - ✅ +config/sys.config - Application configuration - ✅ config/vm.args - VM +settings + +*Build Capabilities:* - ✅ Dependency management - ✅ Compilation - ✅ +Testing - ✅ Release building - ✅ Documentation generation - ✅ Cleanup + +*Status*: *EXCELLENT* - Comprehensive build infrastructure + +==== 4. Testing ✅ COMPLIANT + +*Test Infrastructure:* - ✅ test/sbf_tests.lfe - Comprehensive test +suite (~350 lines) - ✅ Unit tests for all core modules - ✅ Integration +tests - ✅ State machine lifecycle tests - ✅ Safety mechanism +verification - ✅ Edge case coverage + +*Test Coverage:* - Pattern generation: ✅ - State management: ✅ - +Execution engine: ✅ - Output formatting: ✅ - Checkpoint system: ✅ - +Safety mechanisms: ✅ + +*Commands:* + +[source,bash] +---- +rebar3 lfe test # Run all tests +rebar3 lfe test --cover # With coverage +make test # Via Makefile +---- + +*Status*: *GOOD* - Comprehensive tests, working toward 100% coverage + +==== 5. CI/CD ✅ COMPLIANT + +*Continuous Integration:* - ✅ .gitlab-ci.yml - GitLab CI/CD pipeline - +Build stage - Test stage (unit, coverage, integration) - Lint stage +(Dialyzer, formatting) - Security stage (dependencies, RSR compliance, +ethical checks) - Documentation stage - Deploy stage + +* ✅ .github/workflows/ci.yml - GitHub Actions +** Multi-version testing (OTP 26, 27) +** Code coverage (Codecov integration) +** Static analysis (Dialyzer) +** Security checks +** RSR compliance verification +** Documentation building +** Release automation + +*Automated Checks:* - ✅ Compilation - ✅ Unit tests - ✅ Coverage +reporting - ✅ Static analysis - ✅ Security scanning - ✅ RSR +compliance - ✅ Safety mechanism verification + +*Status*: *EXCELLENT* - Comprehensive CI/CD on both platforms + +==== 6. Type Safety ⚠️ PARTIAL + +*Language*: LFE (Lisp Flavored Erlang) + +*Type Safety Mechanisms:* - ✅ Erlang compile-time checks - ✅ Pattern +matching enforcement - ✅ Guards and specifications - ✅ Tagged tuples +for return values - ⚠️ No static type system (unlike Rust/Ada) + +*Safety Patterns:* - ✅ Explicit return type patterns: `+{ok, result}+`, +`+{error, reason}+` - ✅ Pattern matching for exhaustive case handling - +✅ Guards for runtime type checking - ✅ Dialyzer for type inference and +checking + +*Roadmap:* - ○ Add Dialyzer type specifications to all functions - ○ +Document type contracts for FFI boundaries - ○ Consider Gradualizer for +gradual typing + +*Status*: *PARTIAL* - Language limitations, but follows best practices + +==== 7. Memory Safety ✅ COMPLIANT + +*Language*: Erlang/OTP (Memory-safe by design) + +*Memory Safety Features:* - ✅ Garbage collection - ✅ No manual memory +management - ✅ Immutable data structures - ✅ Process isolation - ✅ No +buffer overflows possible - ✅ No use-after-free - ✅ No null pointer +dereferences - ✅ Zero unsafe blocks (N/A in Erlang) + +*Concurrency Safety:* - ✅ Actor model (isolated processes) - ✅ No +shared mutable state - ✅ Message passing only - ✅ Fault tolerance (let +it crash) + +*Status*: *EXCELLENT* - Inherent language guarantee + +==== 8. Offline-First ✅ COMPLIANT + +*Offline Capabilities:* - ✅ No required network calls for core +functionality - ✅ Works air-gapped - ✅ Local pattern generation - ✅ +Local validation functions - ✅ Checkpoint system (local file storage) - +✅ Self-contained examples + +*Network Features (Optional):* - HTTP/HTTPS testing (opt-in) - Users +choose when to make network requests - Clear offline vs online modes + +*Status*: *EXCELLENT* - Fully functional without network + +==== 9. Reproducible Builds ⚠️ PARTIAL + +*Current State:* - ✅ Rebar3 lock file (rebar.lock) - ✅ Specific +dependency versions - ✅ Makefile for consistent commands - ⚠️ No Nix +flake yet (planned) + +*Determinism:* - ✅ Locked dependencies - ✅ Versioned build tools - ⚠️ +Not yet bit-for-bit reproducible + +*Roadmap:* - ○ Add flake.nix for Nix reproducible builds - ○ Document +build environment - ○ Add checksums for releases + +*Status*: *PARTIAL* - Dependency locking present, Nix planned + +==== 10. TPCF (Tri-Perimeter Contribution Framework) ✅ COMPLIANT + +*Current Perimeter*: *3 (Community Sandbox)* + +*Perimeter 3 Characteristics:* - ✅ Fully open contribution - ✅ No +pre-approval required - ✅ Community review process - ✅ Welcoming to +newcomers - ✅ Public issue tracker - ✅ Clear contribution guidelines + +*Governance Model:* - ✅ Documented in MAINTAINERS.md - ✅ Graduated +trust path defined - ✅ Consensus-based decision making - ✅ Code of +Conduct enforced + +*Future Perimeters:* - ○ Perimeter 2: Trusted contributors (direct +commit) - ○ Perimeter 1: Core maintainers (full access) + +*Status*: *EXCELLENT* - Clear TPCF implementation + +==== 11. License Clarity ✅ COMPLIANT + +*License*: MIT (OSI-approved) + +*License Files:* - ✅ LICENSE - Full MIT license text - ✅ Clear +copyright notice - ✅ Attribution requirements documented + +*License Compliance:* - ✅ Compatible with open source - ✅ Permissive +(commercial use allowed) - ✅ Attribution preserved - ✅ No copyleft +restrictions + +*Optional Enhancement:* - ○ Consider dual-licensing with Palimpsest v0.8 +- ○ Add SPDX identifiers to source files + +*Status*: *EXCELLENT* - Clear, permissive, OSI-approved + +=== Overall Compliance Summary + +[cols=",,,,",options="header",] +|=== +|Category |Status |Bronze |Silver |Gold +|Documentation |✅ |✅ |✅ |⚠️ +|.well-known/ |✅ |✅ |✅ |✅ +|Build System |✅ |✅ |✅ |⚠️ +|Testing |✅ |✅ |⚠️ |❌ +|CI/CD |✅ |✅ |✅ |⚠️ +|Type Safety |⚠️ |✅ |⚠️ |❌ +|Memory Safety |✅ |✅ |✅ |✅ +|Offline-First |✅ |✅ |✅ |✅ +|Reproducible Builds |⚠️ |⚠️ |❌ |❌ +|TPCF |✅ |✅ |✅ |✅ +|License |✅ |✅ |✅ |✅ +|=== + +*Current Level*: *Bronze* ✅ *Next Target*: *Silver* (80%+ complete) + +=== Roadmap to Silver Level + +==== High Priority + +[arabic] +. ✅ Add Nix flake for reproducible builds +. ⚠️ Increase test coverage to 80%+ +. ⚠️ Add Dialyzer type specs to all public functions +. ⚠️ Document build environment precisely + +==== Medium Priority + +[arabic, start=5] +. ○ Add property-based tests (PropEr) +. ○ Implement integration test suite +. ○ Add performance benchmarks +. ○ Multi-platform build verification + +==== Future Enhancements + +[arabic, start=9] +. ○ Consider Gradualizer for gradual typing +. ○ WASM compilation target +. ○ FFI contracts for multi-language support +. ○ Formal verification of safety properties + +=== Compliance Verification + +To verify RSR compliance yourself: + +[source,bash] +---- +# Clone repository +git clone https://github.com/Hyperpolymath/safe-brute-force.git +cd safe-brute-force + +# Check documentation +test -f README.md && echo "✓ README" +test -f LICENSE && echo "✓ LICENSE" +test -f CHANGELOG.md && echo "✓ CHANGELOG" +test -f CODE_OF_CONDUCT.md && echo "✓ CODE_OF_CONDUCT" +test -f MAINTAINERS.md && echo "✓ MAINTAINERS" + +# Check .well-known/ +test -f .well-known/security.txt && echo "✓ security.txt" +test -f .well-known/ai.txt && echo "✓ ai.txt" +test -f .well-known/humans.txt && echo "✓ humans.txt" + +# Check build system +test -f rebar.config && echo "✓ rebar.config" +test -f Makefile && echo "✓ Makefile" + +# Run tests +rebar3 compile && echo "✓ Compilation" +rebar3 lfe test && echo "✓ Tests pass" + +# Check CI/CD +test -f .gitlab-ci.yml && echo "✓ GitLab CI" +test -f .github/workflows/ci.yml && echo "✓ GitHub Actions" + +echo "" +echo "🎉 RSR Bronze Level Verified!" +---- + +=== Badges + +[source,markdown] +---- +[![RSR Compliance](https://img.shields.io/badge/RSR-Bronze-cd7f32)]() +[![TPCF Perimeter](https://img.shields.io/badge/TPCF-P3%20Community-green)]() +[![License](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE) +[![CI](https://github.com/Hyperpolymath/safe-brute-force/workflows/CI/badge.svg)]() +---- + +=== References + +* *RSR Framework*: https://github.com/Hyperpolymath/rhodium[Rhodium +Standard Repository] +* *TPCF*: Tri-Perimeter Contribution Framework +* *RFC 9116*: security.txt Standard +* *Contributor Covenant*: Code of Conduct + +=== Changelog + +[cols=",,",options="header",] +|=== +|Date |Version |Change +|2025-01-15 |0.1.0 |Initial RSR Bronze compliance achieved +|=== + +''''' + +*Maintained by*: Hyperpolymath *Last Updated*: 2025-01-15 *Next Review*: +2025-04-15 diff --git a/RSR_COMPLIANCE.md b/RSR_COMPLIANCE.md deleted file mode 100644 index 248b3f2..0000000 --- a/RSR_COMPLIANCE.md +++ /dev/null @@ -1,370 +0,0 @@ - -# RSR Framework Compliance Report - -**Project**: SafeBruteForce -**Version**: 0.1.0 -**Date**: 2025-01-15 -**Compliance Level**: **Bronze** (Working toward Silver) -**TPCF Perimeter**: **3 (Community Sandbox)** - -## Executive Summary - -SafeBruteForce has achieved **Bronze-level compliance** with the Rhodium Standard Repository (RSR) Framework. This document details our compliance status across all 11 RSR categories and our roadmap for achieving higher levels. - -## RSR Framework Categories - -### 1. Documentation ✅ COMPLIANT - -**Required Files:** -- ✅ README.md - Comprehensive project overview (410 lines) -- ✅ LICENSE - MIT License (OSI-approved) -- ✅ CHANGELOG.md - Version history and roadmap -- ✅ CODE_OF_CONDUCT.md - Contributor Covenant 2.1 -- ✅ CONTRIBUTING.md - Contribution guidelines -- ✅ SECURITY.md - Security policy and responsible disclosure -- ✅ MAINTAINERS.md - Project governance and maintainer list - -**Additional Documentation:** -- ✅ docs/USAGE.md - Comprehensive usage guide (450 lines) -- ✅ docs/API_REFERENCE.md - Complete API documentation (670 lines) -- ✅ docs/QUICKSTART.md - 5-minute getting started guide -- ✅ CLAUDE.md - AI assistant-specific guidance -- ✅ PROJECT_SUMMARY.md - Implementation overview - -**Status**: **EXCELLENT** - Exceeds Bronze requirements - -### 2. .well-known/ Directory ✅ COMPLIANT - -**Required Files:** -- ✅ .well-known/security.txt - RFC 9116 compliant - - Contact information - - Expires field - - Canonical URI - - Preferred languages - - Security policy link - -- ✅ .well-known/ai.txt - AI training and usage policy - - Training permissions - - Attribution requirements - - Ethical constraints - - Commercial usage terms - -- ✅ .well-known/humans.txt - Attribution and team info - - Team members - - Technology stack - - Project values - - Citation formats - -**Status**: **EXCELLENT** - Full compliance with metadata standards - -### 3. Build System ✅ COMPLIANT - -**Build Tools:** -- ✅ rebar.config - Rebar3 configuration -- ✅ Makefile - Convenient build commands (20+ recipes) -- ✅ src/safe_brute_force.app.src - OTP application resource -- ✅ config/sys.config - Application configuration -- ✅ config/vm.args - VM settings - -**Build Capabilities:** -- ✅ Dependency management -- ✅ Compilation -- ✅ Testing -- ✅ Release building -- ✅ Documentation generation -- ✅ Cleanup - -**Status**: **EXCELLENT** - Comprehensive build infrastructure - -### 4. Testing ✅ COMPLIANT - -**Test Infrastructure:** -- ✅ test/sbf_tests.lfe - Comprehensive test suite (~350 lines) -- ✅ Unit tests for all core modules -- ✅ Integration tests -- ✅ State machine lifecycle tests -- ✅ Safety mechanism verification -- ✅ Edge case coverage - -**Test Coverage:** -- Pattern generation: ✅ -- State management: ✅ -- Execution engine: ✅ -- Output formatting: ✅ -- Checkpoint system: ✅ -- Safety mechanisms: ✅ - -**Commands:** -```bash -rebar3 lfe test # Run all tests -rebar3 lfe test --cover # With coverage -make test # Via Makefile -``` - -**Status**: **GOOD** - Comprehensive tests, working toward 100% coverage - -### 5. CI/CD ✅ COMPLIANT - -**Continuous Integration:** -- ✅ .gitlab-ci.yml - GitLab CI/CD pipeline - - Build stage - - Test stage (unit, coverage, integration) - - Lint stage (Dialyzer, formatting) - - Security stage (dependencies, RSR compliance, ethical checks) - - Documentation stage - - Deploy stage - -- ✅ .github/workflows/ci.yml - GitHub Actions - - Multi-version testing (OTP 26, 27) - - Code coverage (Codecov integration) - - Static analysis (Dialyzer) - - Security checks - - RSR compliance verification - - Documentation building - - Release automation - -**Automated Checks:** -- ✅ Compilation -- ✅ Unit tests -- ✅ Coverage reporting -- ✅ Static analysis -- ✅ Security scanning -- ✅ RSR compliance -- ✅ Safety mechanism verification - -**Status**: **EXCELLENT** - Comprehensive CI/CD on both platforms - -### 6. Type Safety ⚠️ PARTIAL - -**Language**: LFE (Lisp Flavored Erlang) - -**Type Safety Mechanisms:** -- ✅ Erlang compile-time checks -- ✅ Pattern matching enforcement -- ✅ Guards and specifications -- ✅ Tagged tuples for return values -- ⚠️ No static type system (unlike Rust/Ada) - -**Safety Patterns:** -- ✅ Explicit return type patterns: `{ok, result}`, `{error, reason}` -- ✅ Pattern matching for exhaustive case handling -- ✅ Guards for runtime type checking -- ✅ Dialyzer for type inference and checking - -**Roadmap:** -- ○ Add Dialyzer type specifications to all functions -- ○ Document type contracts for FFI boundaries -- ○ Consider Gradualizer for gradual typing - -**Status**: **PARTIAL** - Language limitations, but follows best practices - -### 7. Memory Safety ✅ COMPLIANT - -**Language**: Erlang/OTP (Memory-safe by design) - -**Memory Safety Features:** -- ✅ Garbage collection -- ✅ No manual memory management -- ✅ Immutable data structures -- ✅ Process isolation -- ✅ No buffer overflows possible -- ✅ No use-after-free -- ✅ No null pointer dereferences -- ✅ Zero unsafe blocks (N/A in Erlang) - -**Concurrency Safety:** -- ✅ Actor model (isolated processes) -- ✅ No shared mutable state -- ✅ Message passing only -- ✅ Fault tolerance (let it crash) - -**Status**: **EXCELLENT** - Inherent language guarantee - -### 8. Offline-First ✅ COMPLIANT - -**Offline Capabilities:** -- ✅ No required network calls for core functionality -- ✅ Works air-gapped -- ✅ Local pattern generation -- ✅ Local validation functions -- ✅ Checkpoint system (local file storage) -- ✅ Self-contained examples - -**Network Features (Optional):** -- HTTP/HTTPS testing (opt-in) -- Users choose when to make network requests -- Clear offline vs online modes - -**Status**: **EXCELLENT** - Fully functional without network - -### 9. Reproducible Builds ⚠️ PARTIAL - -**Current State:** -- ✅ Rebar3 lock file (rebar.lock) -- ✅ Specific dependency versions -- ✅ Makefile for consistent commands -- ⚠️ No Nix flake yet (planned) - -**Determinism:** -- ✅ Locked dependencies -- ✅ Versioned build tools -- ⚠️ Not yet bit-for-bit reproducible - -**Roadmap:** -- ○ Add flake.nix for Nix reproducible builds -- ○ Document build environment -- ○ Add checksums for releases - -**Status**: **PARTIAL** - Dependency locking present, Nix planned - -### 10. TPCF (Tri-Perimeter Contribution Framework) ✅ COMPLIANT - -**Current Perimeter**: **3 (Community Sandbox)** - -**Perimeter 3 Characteristics:** -- ✅ Fully open contribution -- ✅ No pre-approval required -- ✅ Community review process -- ✅ Welcoming to newcomers -- ✅ Public issue tracker -- ✅ Clear contribution guidelines - -**Governance Model:** -- ✅ Documented in MAINTAINERS.md -- ✅ Graduated trust path defined -- ✅ Consensus-based decision making -- ✅ Code of Conduct enforced - -**Future Perimeters:** -- ○ Perimeter 2: Trusted contributors (direct commit) -- ○ Perimeter 1: Core maintainers (full access) - -**Status**: **EXCELLENT** - Clear TPCF implementation - -### 11. License Clarity ✅ COMPLIANT - -**License**: MIT (OSI-approved) - -**License Files:** -- ✅ LICENSE - Full MIT license text -- ✅ Clear copyright notice -- ✅ Attribution requirements documented - -**License Compliance:** -- ✅ Compatible with open source -- ✅ Permissive (commercial use allowed) -- ✅ Attribution preserved -- ✅ No copyleft restrictions - -**Optional Enhancement:** -- ○ Consider dual-licensing with Palimpsest v0.8 -- ○ Add SPDX identifiers to source files - -**Status**: **EXCELLENT** - Clear, permissive, OSI-approved - -## Overall Compliance Summary - -| Category | Status | Bronze | Silver | Gold | -|----------|--------|--------|--------|------| -| Documentation | ✅ | ✅ | ✅ | ⚠️ | -| .well-known/ | ✅ | ✅ | ✅ | ✅ | -| Build System | ✅ | ✅ | ✅ | ⚠️ | -| Testing | ✅ | ✅ | ⚠️ | ❌ | -| CI/CD | ✅ | ✅ | ✅ | ⚠️ | -| Type Safety | ⚠️ | ✅ | ⚠️ | ❌ | -| Memory Safety | ✅ | ✅ | ✅ | ✅ | -| Offline-First | ✅ | ✅ | ✅ | ✅ | -| Reproducible Builds | ⚠️ | ⚠️ | ❌ | ❌ | -| TPCF | ✅ | ✅ | ✅ | ✅ | -| License | ✅ | ✅ | ✅ | ✅ | - -**Current Level**: **Bronze** ✅ -**Next Target**: **Silver** (80%+ complete) - -## Roadmap to Silver Level - -### High Priority -1. ✅ Add Nix flake for reproducible builds -2. ⚠️ Increase test coverage to 80%+ -3. ⚠️ Add Dialyzer type specs to all public functions -4. ⚠️ Document build environment precisely - -### Medium Priority -5. ○ Add property-based tests (PropEr) -6. ○ Implement integration test suite -7. ○ Add performance benchmarks -8. ○ Multi-platform build verification - -### Future Enhancements -9. ○ Consider Gradualizer for gradual typing -10. ○ WASM compilation target -11. ○ FFI contracts for multi-language support -12. ○ Formal verification of safety properties - -## Compliance Verification - -To verify RSR compliance yourself: - -```bash -# Clone repository -git clone https://github.com/Hyperpolymath/safe-brute-force.git -cd safe-brute-force - -# Check documentation -test -f README.md && echo "✓ README" -test -f LICENSE && echo "✓ LICENSE" -test -f CHANGELOG.md && echo "✓ CHANGELOG" -test -f CODE_OF_CONDUCT.md && echo "✓ CODE_OF_CONDUCT" -test -f MAINTAINERS.md && echo "✓ MAINTAINERS" - -# Check .well-known/ -test -f .well-known/security.txt && echo "✓ security.txt" -test -f .well-known/ai.txt && echo "✓ ai.txt" -test -f .well-known/humans.txt && echo "✓ humans.txt" - -# Check build system -test -f rebar.config && echo "✓ rebar.config" -test -f Makefile && echo "✓ Makefile" - -# Run tests -rebar3 compile && echo "✓ Compilation" -rebar3 lfe test && echo "✓ Tests pass" - -# Check CI/CD -test -f .gitlab-ci.yml && echo "✓ GitLab CI" -test -f .github/workflows/ci.yml && echo "✓ GitHub Actions" - -echo "" -echo "🎉 RSR Bronze Level Verified!" -``` - -## Badges - -```markdown -[![RSR Compliance](https://img.shields.io/badge/RSR-Bronze-cd7f32)]() -[![TPCF Perimeter](https://img.shields.io/badge/TPCF-P3%20Community-green)]() -[![License](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE) -[![CI](https://github.com/Hyperpolymath/safe-brute-force/workflows/CI/badge.svg)]() -``` - -## References - -- **RSR Framework**: [Rhodium Standard Repository](https://github.com/Hyperpolymath/rhodium) -- **TPCF**: Tri-Perimeter Contribution Framework -- **RFC 9116**: security.txt Standard -- **Contributor Covenant**: Code of Conduct - -## Changelog - -| Date | Version | Change | -|------|---------|--------| -| 2025-01-15 | 0.1.0 | Initial RSR Bronze compliance achieved | - ---- - -**Maintained by**: Hyperpolymath -**Last Updated**: 2025-01-15 -**Next Review**: 2025-04-15 diff --git a/SECURITY.adoc b/SECURITY.adoc new file mode 100644 index 0000000..b0574df --- /dev/null +++ b/SECURITY.adoc @@ -0,0 +1,24 @@ +== Security Policy + +=== Supported Versions + +[cols=",",options="header",] +|=== +|Version |Supported +|main |:white_check_mark: +|< main |:x: +|=== + +=== Reporting a Vulnerability + +Please report security vulnerabilities through GitHub private +vulnerability reporting: 1. Go to the *Security* tab 2. Click *Report a +vulnerability* 3. Fill out the form + +We respond within 48 hours. + +=== Security Measures + +* Dependabot for dependency updates +* CodeQL for code scanning +* Secret scanning and push protection diff --git a/SECURITY.md b/SECURITY.md deleted file mode 100644 index ab42fae..0000000 --- a/SECURITY.md +++ /dev/null @@ -1,28 +0,0 @@ - -# Security Policy - -## Supported Versions - -| Version | Supported | -| ------- | ------------------ | -| main | :white_check_mark: | -| < main | :x: | - -## Reporting a Vulnerability - -Please report security vulnerabilities through GitHub private vulnerability reporting: -1. Go to the **Security** tab -2. Click **Report a vulnerability** -3. Fill out the form - -We respond within 48 hours. - -## Security Measures - -- Dependabot for dependency updates -- CodeQL for code scanning -- Secret scanning and push protection - diff --git a/TEST-NEEDS.adoc b/TEST-NEEDS.adoc new file mode 100644 index 0000000..c018d6f --- /dev/null +++ b/TEST-NEEDS.adoc @@ -0,0 +1,59 @@ +== TEST-NEEDS.md — CRG Grade B Test Documentation + +=== Grade B Status: 6 Test Targets + +This file documents the six independently runnable test targets required +for CRG Grade B compliance. + +[width="100%",cols="16%,31%,24%,29%",options="header",] +|=== +|Target |Justfile Recipe |Description |Pass Criterion +|T1 |`+just test-lfe+` |LFE unit tests via `+rebar3 lfe test+` |All LFE +test assertions pass + +|T2 |`+just test-structure+` |Structural validation +(`+tests/validate_structure.sh+`) |All required files/dirs present; ≥3 +workflows + +|T3 |`+just test-compile+` |Compilation check via `+rebar3 compile+` +|Exits 0 (no compile errors) + +|T4 |`+just test-static+` |Static analysis via `+rebar3 xref+` |Exits 0 +or degrades gracefully + +|T5 |`+just test-nickel+` |Nickel k9 contractile typecheck +|`+nickel typecheck+` exits 0 (skipped if nickel absent) + +|T6 |`+just test-examples+` |Example LFE syntax validation +(`+tests/validate_examples.sh+`) |0 syntax errors in `+examples/*.lfe+` +(skipped if erlc absent) +|=== + +=== Running All Targets + +[source,bash] +---- +just test +---- + +=== Individual Targets + +[source,bash] +---- +just test-lfe +just test-structure +just test-compile +just test-static +just test-nickel +just test-examples +---- + +=== Notes + +* T4 degrades gracefully: `+rebar3 xref+` exit code is not surfaced as a +failure to avoid blocking on environments without complete PLT. +* T5 and T6 degrade gracefully when the required tools (`+nickel+`, +`+erlc+`) are not installed — they emit `+SKIP:+` and exit 0. +* T5 strips the `+K9!+` header from the k9 template file before passing +to `+nickel typecheck+` (the header is a k9 DSL marker, not valid +Nickel). diff --git a/TEST-NEEDS.md b/TEST-NEEDS.md deleted file mode 100644 index c0bedf2..0000000 --- a/TEST-NEEDS.md +++ /dev/null @@ -1,41 +0,0 @@ - -# TEST-NEEDS.md — CRG Grade B Test Documentation - -## Grade B Status: 6 Test Targets - -This file documents the six independently runnable test targets required for CRG Grade B compliance. - -| Target | Justfile Recipe | Description | Pass Criterion | -|--------|-----------------|-------------|----------------| -| T1 | `just test-lfe` | LFE unit tests via `rebar3 lfe test` | All LFE test assertions pass | -| T2 | `just test-structure` | Structural validation (`tests/validate_structure.sh`) | All required files/dirs present; ≥3 workflows | -| T3 | `just test-compile` | Compilation check via `rebar3 compile` | Exits 0 (no compile errors) | -| T4 | `just test-static` | Static analysis via `rebar3 xref` | Exits 0 or degrades gracefully | -| T5 | `just test-nickel` | Nickel k9 contractile typecheck | `nickel typecheck` exits 0 (skipped if nickel absent) | -| T6 | `just test-examples` | Example LFE syntax validation (`tests/validate_examples.sh`) | 0 syntax errors in `examples/*.lfe` (skipped if erlc absent) | - -## Running All Targets - -```bash -just test -``` - -## Individual Targets - -```bash -just test-lfe -just test-structure -just test-compile -just test-static -just test-nickel -just test-examples -``` - -## Notes - -- T4 degrades gracefully: `rebar3 xref` exit code is not surfaced as a failure to avoid blocking on environments without complete PLT. -- T5 and T6 degrade gracefully when the required tools (`nickel`, `erlc`) are not installed — they emit `SKIP:` and exit 0. -- T5 strips the `K9!` header from the k9 template file before passing to `nickel typecheck` (the header is a k9 DSL marker, not valid Nickel). diff --git a/docs/API_REFERENCE.adoc b/docs/API_REFERENCE.adoc new file mode 100644 index 0000000..0f97d00 --- /dev/null +++ b/docs/API_REFERENCE.adoc @@ -0,0 +1,684 @@ +== SafeBruteForce API Reference + +Complete API documentation for SafeBruteForce modules. + +=== Table of Contents + +[arabic] +. link:#main-api-sbf[Main API (sbf)] +. link:#state-management-sbf_state[State Management (sbf_state)] +. link:#pattern-generation-sbf_patterns[Pattern Generation +(sbf_patterns)] +. link:#output-sbf_output[Output (sbf_output)] +. link:#checkpoints-sbf_checkpoint[Checkpoints (sbf_checkpoint)] +. link:#progress-tracking-sbf_progress[Progress Tracking (sbf_progress)] +. link:#logging-sbf_logger[Logging (sbf_logger)] + +''''' + +=== Main API (sbf) + +High-level interface for SafeBruteForce operations. + +==== Application Control + +===== `+(sbf:start)+` + +Start the SafeBruteForce application. + +*Returns:* `+{ok, [started_apps]} | {error, reason}+` + +*Example:* + +[source,lisp] +---- +> (sbf:start) +{ok,[safe_brute_force,lfe,lhttpc,uuid]} +---- + +===== `+(sbf:stop)+` + +Stop the SafeBruteForce application. + +*Returns:* `+ok | {error, reason}+` + +==== Brute-Force Operations + +===== `+(sbf:run pattern-config target-config)+` + +Run brute-force operation synchronously. + +*Parameters:* - `+pattern-config+` - Property list for pattern +generation - `+target-config+` - Property list for target configuration + +*Returns:* Final statistics map + +*Example:* + +[source,lisp] +---- +(sbf:run + (list (tuple 'type 'wordlist) + (tuple 'filename "passwords.txt")) + (list (tuple 'type 'http) + (tuple 'url "http://localhost/login"))) +---- + +===== `+(sbf:run_async pattern-config target-config)+` + +Run brute-force operation asynchronously. + +*Returns:* `+#Pid<...>+` (process ID) + +==== Convenience Functions + +===== `+(sbf:test_http url username wordlist-file)+` + +Test HTTP endpoint with username and wordlist. + +*Parameters:* - `+url+` - Target URL string - `+username+` - Username +string - `+wordlist-file+` - Path to wordlist file + +*Example:* + +[source,lisp] +---- +(sbf:test_http "http://localhost/login" "admin" "passwords.txt") +---- + +===== `+(sbf:test_wordlist wordlist-file test-fn)+` + +Test patterns from wordlist using custom function. + +*Parameters:* - `+wordlist-file+` - Path to wordlist - `+test-fn+` - +Function that takes pattern and returns boolean + +===== `+(sbf:test_pins test-fn)+` + +Test all 4-digit PIN codes. + +*Parameters:* - `+test-fn+` - Function that validates PIN codes + +===== `+(sbf:test_custom pattern-list test-fn)+` + +Test custom pattern list. + +*Parameters:* - `+pattern-list+` - List of patterns to test - +`+test-fn+` - Validation function + +==== Control Functions + +===== `+(sbf:pause)+` + +Manually pause the operation. + +*Returns:* `+ok+` + +===== `+(sbf:resume)+` + +Resume paused operation. + +*Returns:* `+ok+` + +===== `+(sbf:status)+` + +Get current status. + +*Returns:* Status map with keys: - `+state+` - Current state +(running/paused/etc.) - `+attempts+` - Total attempts - `+successes+` - +Successful attempts + +===== `+(sbf:stats)+` + +Get detailed statistics. + +*Returns:* Comprehensive statistics map + +==== Checkpoint Operations + +===== `+(sbf:save_checkpoint)+` + +Save checkpoint with default name. + +*Returns:* `+{ok, info} | {error, reason}+` + +===== `+(sbf:save_checkpoint session-name)+` + +Save checkpoint with specific name. + +*Returns:* `+{ok, info} | {error, reason}+` + +===== `+(sbf:load_checkpoint checkpoint-id)+` + +Load checkpoint by ID. + +*Returns:* `+{ok, checkpoint-data} | {error, reason}+` + +===== `+(sbf:list_checkpoints)+` + +List all checkpoints. + +*Returns:* List of checkpoint metadata maps + +''''' + +=== State Management (sbf_state) + +State machine for pause/resume functionality. + +==== API Functions + +===== `+(sbf_state:start_link config)+` + +Start state manager with configuration. + +*Parameters:* - `+config+` - Property list with: - `+pause_interval+` - +Attempts before pause (default: 25) - `+safety_enabled+` - Enable safety +pause (default: true) + +===== `+(sbf_state:attempt pattern result)+` + +Record an attempt. + +*Parameters:* - `+pattern+` - The pattern tested - `+result+` - +`+'success+` or `+'failure+` + +*Returns:* `+{ok, state, count} | {ok, paused, count}+` + +===== `+(sbf_state:get_status)+` + +Get current status. + +*Returns:* Status map + +===== `+(sbf_state:get_stats)+` + +Get detailed statistics. + +*Returns:* Statistics map with: - `+state+` - Current state - +`+attempt_count+` - Total attempts - `+success_count+` - Successful +attempts - `+failure_count+` - Failed attempts - `+successful_patterns+` +- List of successful patterns - `+elapsed_seconds+` - Time elapsed - +`+attempts_per_second+` - Rate - `+success_rate_percent+` - Success +percentage + +===== `+(sbf_state:reset)+` + +Reset counters. + +*Returns:* `+ok+` + +''''' + +=== Pattern Generation (sbf_patterns) + +Generate patterns for brute-forcing. + +==== Generation Functions + +===== `+(sbf_patterns:charset_combinations charset max-length)+` + +Generate all combinations from charset up to max-length. + +*Parameters:* - `+charset+` - String of characters to use - +`+max-length+` - Maximum pattern length + +*Returns:* List of pattern strings + +*Example:* + +[source,lisp] +---- +> (sbf_patterns:charset_combinations "abc" 2) +["a","b","c","aa","ab","ac","ba","bb","bc","ca","cb","cc"] +---- + +===== `+(sbf_patterns:charset_combinations charset min-length max-length)+` + +Generate combinations between min and max length. + +===== `+(sbf_patterns:sequential_numbers start end)+` + +Generate sequential numbers as strings. + +*Example:* + +[source,lisp] +---- +> (sbf_patterns:sequential_numbers 1000 1005) +["1000","1001","1002","1003","1004","1005"] +---- + +===== `+(sbf_patterns:wordlist filename)+` + +Load patterns from file. + +*Parameters:* - `+filename+` - Path to wordlist file (one pattern per +line) + +*Returns:* List of patterns + +===== `+(sbf_patterns:wordlist_with_mutations filename)+` + +Load wordlist and apply standard mutations. + +*Returns:* Expanded list with mutations + +===== `+(sbf_patterns:common_passwords)+` + +Get list of common passwords. + +*Returns:* List of common password strings + +===== `+(sbf_patterns:date_patterns year)+` + +Generate date patterns for a given year. + +*Parameters:* - `+year+` - Year as integer + +*Returns:* List of date pattern strings in various formats + +==== Utility Functions + +===== `+(sbf_patterns:estimate_total type config)+` + +Estimate total patterns for a strategy. + +*Parameters:* - `+type+` - Pattern type (’charset, ’wordlist, etc.) - +`+config+` - Configuration for that type + +*Returns:* Integer count or ’unknown + +===== `+(sbf_patterns:permutations list)+` + +Generate all permutations of a list. + +===== `+(sbf_patterns:combinations n list)+` + +Generate all combinations of n elements from list. + +==== Built-in Recipes + +===== `+(sbf_patterns:pin-codes)+` + +All 4-digit PIN codes (10,000 patterns). + +===== `+(sbf_patterns:simple-passwords)+` + +Simple alphanumeric passwords 4-6 characters. + +===== `+(sbf_patterns:hex-colors)+` + +All possible hex color codes. + +''''' + +=== Output (sbf_output) + +Result formatting and output management. + +==== Formatting Functions + +===== `+(sbf_output:format_results results)+` + +Format results (successes only by default). + +===== `+(sbf_output:format_results results mode)+` + +Format results with specific mode. + +*Parameters:* - `+results+` - List of result tuples - `+mode+` - +`+'successes_only | 'failures_only | 'all | 'summary+` + +*Returns:* Formatted results + +===== `+(sbf_output:filter_results results type)+` + +Filter results by type. + +*Parameters:* - `+results+` - List of results - `+type+` - +`+'success | 'failure | 'error+` + +==== File Output + +===== `+(sbf_output:save_results results filename)+` + +Save results to file. + +*Returns:* `+{ok, info} | {error, reason}+` + +==== Console Output + +===== `+(sbf_output:print_summary stats)+` + +Print comprehensive summary to console. + +*Parameters:* - `+stats+` - Statistics map from `+(sbf:stats)+` + +===== `+(sbf_output:print_progress current total)+` + +Print progress bar. + +*Parameters:* - `+current+` - Current count - `+total+` - Total count + +===== `+(sbf_output:print_banner)+` + +Print SafeBruteForce banner. + +==== Colorized Output + +===== `+(sbf_output:print_success message)+` + +Print success message in green. + +===== `+(sbf_output:print_error message)+` + +Print error message in red. + +===== `+(sbf_output:print_warning message)+` + +Print warning message in yellow. + +===== `+(sbf_output:print_info message)+` + +Print info message in cyan. + +''''' + +=== Checkpoints (sbf_checkpoint) + +Save and restore session state. + +==== Save Functions + +===== `+(sbf_checkpoint:save session-name state)+` + +Save checkpoint with auto-generated ID. + +*Returns:* `+{ok, info} | {error, reason}+` + +===== `+(sbf_checkpoint:save session-name checkpoint-id state)+` + +Save checkpoint with specific ID. + +==== Restore Functions + +===== `+(sbf_checkpoint:restore checkpoint-id)+` + +Restore session from checkpoint. + +*Returns:* `+{ok, checkpoint-data} | {error, reason}+` + +==== Management Functions + +===== `+(sbf_checkpoint:list_checkpoints)+` + +List all checkpoints. + +===== `+(sbf_checkpoint:list_checkpoints session-name)+` + +List checkpoints for specific session. + +===== `+(sbf_checkpoint:delete checkpoint-id)+` + +Delete a checkpoint. + +*Returns:* `+{ok, info} | {error, reason}+` + +===== `+(sbf_checkpoint:auto_save state)+` + +Auto-save with timestamp-based ID. + +===== `+(sbf_checkpoint:get_checkpoint_info checkpoint-id)+` + +Get metadata without loading full checkpoint. + +''''' + +=== Progress Tracking (sbf_progress) + +Track progress and calculate ETA. + +==== Core Functions + +===== `+(sbf_progress:new total)+` + +Create new progress tracker. + +*Parameters:* - `+total+` - Total number of items + +*Returns:* Progress map + +===== `+(sbf_progress:update progress current)+` + +Update progress with current count. + +*Returns:* Updated progress map + +===== `+(sbf_progress:get_eta progress)+` + +Get estimated time remaining in seconds. + +*Returns:* Integer seconds or `+'unknown+` + +===== `+(sbf_progress:get_percent progress)+` + +Get completion percentage. + +*Returns:* Float percentage (0.0-100.0) + +===== `+(sbf_progress:get_rate progress)+` + +Get current rate (items per second). + +*Returns:* Float rate + +===== `+(sbf_progress:print progress)+` + +Print progress bar to console. + +==== Utility Functions + +===== `+(sbf_progress:format_duration seconds)+` + +Format duration in human-readable form. + +*Returns:* String like "`2m 30s`" or "`1h 15m`" + +===== `+(sbf_progress:get_stats progress)+` + +Get comprehensive progress statistics. + +''''' + +=== Logging (sbf_logger) + +Structured logging system. + +==== Logging Functions + +===== `+(sbf_logger:log level message)+` + +Log message at specified level. + +*Parameters:* - `+level+` - +`+'debug | 'info | 'warning | 'error | 'success | 'failure+` - +`+message+` - Message string + +===== `+(sbf_logger:log level message metadata)+` + +Log with metadata. + +*Parameters:* - `+metadata+` - Map of additional data + +===== `+(sbf_logger:debug message)+` + +Log debug message. + +===== `+(sbf_logger:info message)+` + +Log info message. + +===== `+(sbf_logger:warning message)+` + +Log warning message. + +===== `+(sbf_logger:error message)+` + +Log error message. + +===== `+(sbf_logger:success message)+` + +Log success message. + +===== `+(sbf_logger:failure message)+` + +Log failure message. + +==== Configuration + +===== `+(sbf_logger:set_level level)+` + +Set minimum logging level. + +*Parameters:* - `+level+` - `+'debug | 'info | 'warning | 'error+` + +===== `+(sbf_logger:get_level)+` + +Get current logging level. + +==== File Logging + +===== `+(sbf_logger:log_to_file filename message)+` + +Append log message to file. + +*Returns:* `+ok | {error, reason}+` + +==== Specialized Logging + +===== `+(sbf_logger:log_attempt pattern result metadata)+` + +Log a brute-force attempt. + +===== `+(sbf_logger:log_session_start config)+` + +Log session start. + +===== `+(sbf_logger:log_session_end stats)+` + +Log session end with statistics. + +===== `+(sbf_logger:log_pause)+` + +Log pause event. + +===== `+(sbf_logger:log_resume)+` + +Log resume event. + +===== `+(sbf_logger:log_checkpoint checkpoint-id)+` + +Log checkpoint save. + +''''' + +=== Configuration Reference + +==== Pattern Config + +[source,lisp] +---- +;; Wordlist +(list (tuple 'type 'wordlist) + (tuple 'filename "path/to/wordlist.txt") + (tuple 'mutations 'standard)) ; optional: minimal | standard | aggressive + +;; Charset +(list (tuple 'type 'charset) + (tuple 'charset "abcdefgh123456") + (tuple 'min_length 4) + (tuple 'max_length 8)) + +;; Sequential +(list (tuple 'type 'sequential) + (tuple 'start 1000) + (tuple 'end 9999)) + +;; Custom +(list (tuple 'type 'custom) + (tuple 'function (lambda () (list "pattern1" "pattern2")))) +---- + +==== Target Config + +[source,lisp] +---- +;; HTTP +(list (tuple 'type 'http) + (tuple 'url "http://example.com/login") + (tuple 'method 'post) ; or 'get + (tuple 'username "admin") + (tuple 'username_field "user") + (tuple 'password_field "pass") + (tuple 'success_pattern "Welcome") + (tuple 'failure_pattern "Invalid") + (tuple 'body_format 'urlencoded) ; or 'json + (tuple 'headers (list (tuple "X-Custom" "value")))) + +;; Function +(list (tuple 'type 'function) + (tuple 'function (lambda (p) (validate p)))) + +;; Mock +(list (tuple 'type 'mock) + (tuple 'expected "correct_password")) +---- + +''''' + +=== Error Handling + +All functions return tagged tuples: + +[source,lisp] +---- +{ok, result} ; Success +{error, reason} ; Error with reason +{ok, state, data} ; Success with state and data +---- + +Common error reasons: - `+checkpoint_not_found+` - +`+invalid_checkpoint+` - `+stopped+` - `+waiting_confirmation+` - +`+unknown_target_type+` - `+unknown_request+` + +''''' + +=== Type Specifications + +==== Pattern Types + +* `+'wordlist+` - Load from file +* `+'charset+` - Generate combinations +* `+'sequential+` - Number sequences +* `+'common+` - Common passwords +* `+'custom+` - Custom function + +==== Target Types + +* `+'http+` - HTTP/HTTPS endpoints +* `+'function+` - Custom validators +* `+'mock+` - Testing targets +* `+'ssh+` - SSH (planned) + +==== State Machine States + +* `+'running+` - Actively processing +* `+'paused+` - Manually paused +* `+'waiting_confirmation+` - Auto-paused, waiting for user +* `+'stopped+` - Stopped/completed + +''''' + +For complete examples, see the `+examples/+` directory and +`+docs/USAGE.md+`. diff --git a/docs/API_REFERENCE.md b/docs/API_REFERENCE.md deleted file mode 100644 index a240162..0000000 --- a/docs/API_REFERENCE.md +++ /dev/null @@ -1,618 +0,0 @@ - -# SafeBruteForce API Reference - -Complete API documentation for SafeBruteForce modules. - -## Table of Contents - -1. [Main API (sbf)](#main-api-sbf) -2. [State Management (sbf_state)](#state-management-sbf_state) -3. [Pattern Generation (sbf_patterns)](#pattern-generation-sbf_patterns) -4. [Output (sbf_output)](#output-sbf_output) -5. [Checkpoints (sbf_checkpoint)](#checkpoints-sbf_checkpoint) -6. [Progress Tracking (sbf_progress)](#progress-tracking-sbf_progress) -7. [Logging (sbf_logger)](#logging-sbf_logger) - ---- - -## Main API (sbf) - -High-level interface for SafeBruteForce operations. - -### Application Control - -#### `(sbf:start)` -Start the SafeBruteForce application. - -**Returns:** `{ok, [started_apps]} | {error, reason}` - -**Example:** -```lisp -> (sbf:start) -{ok,[safe_brute_force,lfe,lhttpc,uuid]} -``` - -#### `(sbf:stop)` -Stop the SafeBruteForce application. - -**Returns:** `ok | {error, reason}` - -### Brute-Force Operations - -#### `(sbf:run pattern-config target-config)` -Run brute-force operation synchronously. - -**Parameters:** -- `pattern-config` - Property list for pattern generation -- `target-config` - Property list for target configuration - -**Returns:** Final statistics map - -**Example:** -```lisp -(sbf:run - (list (tuple 'type 'wordlist) - (tuple 'filename "passwords.txt")) - (list (tuple 'type 'http) - (tuple 'url "http://localhost/login"))) -``` - -#### `(sbf:run_async pattern-config target-config)` -Run brute-force operation asynchronously. - -**Returns:** `#Pid<...>` (process ID) - -### Convenience Functions - -#### `(sbf:test_http url username wordlist-file)` -Test HTTP endpoint with username and wordlist. - -**Parameters:** -- `url` - Target URL string -- `username` - Username string -- `wordlist-file` - Path to wordlist file - -**Example:** -```lisp -(sbf:test_http "http://localhost/login" "admin" "passwords.txt") -``` - -#### `(sbf:test_wordlist wordlist-file test-fn)` -Test patterns from wordlist using custom function. - -**Parameters:** -- `wordlist-file` - Path to wordlist -- `test-fn` - Function that takes pattern and returns boolean - -#### `(sbf:test_pins test-fn)` -Test all 4-digit PIN codes. - -**Parameters:** -- `test-fn` - Function that validates PIN codes - -#### `(sbf:test_custom pattern-list test-fn)` -Test custom pattern list. - -**Parameters:** -- `pattern-list` - List of patterns to test -- `test-fn` - Validation function - -### Control Functions - -#### `(sbf:pause)` -Manually pause the operation. - -**Returns:** `ok` - -#### `(sbf:resume)` -Resume paused operation. - -**Returns:** `ok` - -#### `(sbf:status)` -Get current status. - -**Returns:** Status map with keys: -- `state` - Current state (running/paused/etc.) -- `attempts` - Total attempts -- `successes` - Successful attempts - -#### `(sbf:stats)` -Get detailed statistics. - -**Returns:** Comprehensive statistics map - -### Checkpoint Operations - -#### `(sbf:save_checkpoint)` -Save checkpoint with default name. - -**Returns:** `{ok, info} | {error, reason}` - -#### `(sbf:save_checkpoint session-name)` -Save checkpoint with specific name. - -**Returns:** `{ok, info} | {error, reason}` - -#### `(sbf:load_checkpoint checkpoint-id)` -Load checkpoint by ID. - -**Returns:** `{ok, checkpoint-data} | {error, reason}` - -#### `(sbf:list_checkpoints)` -List all checkpoints. - -**Returns:** List of checkpoint metadata maps - ---- - -## State Management (sbf_state) - -State machine for pause/resume functionality. - -### API Functions - -#### `(sbf_state:start_link config)` -Start state manager with configuration. - -**Parameters:** -- `config` - Property list with: - - `pause_interval` - Attempts before pause (default: 25) - - `safety_enabled` - Enable safety pause (default: true) - -#### `(sbf_state:attempt pattern result)` -Record an attempt. - -**Parameters:** -- `pattern` - The pattern tested -- `result` - `'success` or `'failure` - -**Returns:** `{ok, state, count} | {ok, paused, count}` - -#### `(sbf_state:get_status)` -Get current status. - -**Returns:** Status map - -#### `(sbf_state:get_stats)` -Get detailed statistics. - -**Returns:** Statistics map with: -- `state` - Current state -- `attempt_count` - Total attempts -- `success_count` - Successful attempts -- `failure_count` - Failed attempts -- `successful_patterns` - List of successful patterns -- `elapsed_seconds` - Time elapsed -- `attempts_per_second` - Rate -- `success_rate_percent` - Success percentage - -#### `(sbf_state:reset)` -Reset counters. - -**Returns:** `ok` - ---- - -## Pattern Generation (sbf_patterns) - -Generate patterns for brute-forcing. - -### Generation Functions - -#### `(sbf_patterns:charset_combinations charset max-length)` -Generate all combinations from charset up to max-length. - -**Parameters:** -- `charset` - String of characters to use -- `max-length` - Maximum pattern length - -**Returns:** List of pattern strings - -**Example:** -```lisp -> (sbf_patterns:charset_combinations "abc" 2) -["a","b","c","aa","ab","ac","ba","bb","bc","ca","cb","cc"] -``` - -#### `(sbf_patterns:charset_combinations charset min-length max-length)` -Generate combinations between min and max length. - -#### `(sbf_patterns:sequential_numbers start end)` -Generate sequential numbers as strings. - -**Example:** -```lisp -> (sbf_patterns:sequential_numbers 1000 1005) -["1000","1001","1002","1003","1004","1005"] -``` - -#### `(sbf_patterns:wordlist filename)` -Load patterns from file. - -**Parameters:** -- `filename` - Path to wordlist file (one pattern per line) - -**Returns:** List of patterns - -#### `(sbf_patterns:wordlist_with_mutations filename)` -Load wordlist and apply standard mutations. - -**Returns:** Expanded list with mutations - -#### `(sbf_patterns:common_passwords)` -Get list of common passwords. - -**Returns:** List of common password strings - -#### `(sbf_patterns:date_patterns year)` -Generate date patterns for a given year. - -**Parameters:** -- `year` - Year as integer - -**Returns:** List of date pattern strings in various formats - -### Utility Functions - -#### `(sbf_patterns:estimate_total type config)` -Estimate total patterns for a strategy. - -**Parameters:** -- `type` - Pattern type ('charset, 'wordlist, etc.) -- `config` - Configuration for that type - -**Returns:** Integer count or 'unknown - -#### `(sbf_patterns:permutations list)` -Generate all permutations of a list. - -#### `(sbf_patterns:combinations n list)` -Generate all combinations of n elements from list. - -### Built-in Recipes - -#### `(sbf_patterns:pin-codes)` -All 4-digit PIN codes (10,000 patterns). - -#### `(sbf_patterns:simple-passwords)` -Simple alphanumeric passwords 4-6 characters. - -#### `(sbf_patterns:hex-colors)` -All possible hex color codes. - ---- - -## Output (sbf_output) - -Result formatting and output management. - -### Formatting Functions - -#### `(sbf_output:format_results results)` -Format results (successes only by default). - -#### `(sbf_output:format_results results mode)` -Format results with specific mode. - -**Parameters:** -- `results` - List of result tuples -- `mode` - `'successes_only | 'failures_only | 'all | 'summary` - -**Returns:** Formatted results - -#### `(sbf_output:filter_results results type)` -Filter results by type. - -**Parameters:** -- `results` - List of results -- `type` - `'success | 'failure | 'error` - -### File Output - -#### `(sbf_output:save_results results filename)` -Save results to file. - -**Returns:** `{ok, info} | {error, reason}` - -### Console Output - -#### `(sbf_output:print_summary stats)` -Print comprehensive summary to console. - -**Parameters:** -- `stats` - Statistics map from `(sbf:stats)` - -#### `(sbf_output:print_progress current total)` -Print progress bar. - -**Parameters:** -- `current` - Current count -- `total` - Total count - -#### `(sbf_output:print_banner)` -Print SafeBruteForce banner. - -### Colorized Output - -#### `(sbf_output:print_success message)` -Print success message in green. - -#### `(sbf_output:print_error message)` -Print error message in red. - -#### `(sbf_output:print_warning message)` -Print warning message in yellow. - -#### `(sbf_output:print_info message)` -Print info message in cyan. - ---- - -## Checkpoints (sbf_checkpoint) - -Save and restore session state. - -### Save Functions - -#### `(sbf_checkpoint:save session-name state)` -Save checkpoint with auto-generated ID. - -**Returns:** `{ok, info} | {error, reason}` - -#### `(sbf_checkpoint:save session-name checkpoint-id state)` -Save checkpoint with specific ID. - -### Restore Functions - -#### `(sbf_checkpoint:restore checkpoint-id)` -Restore session from checkpoint. - -**Returns:** `{ok, checkpoint-data} | {error, reason}` - -### Management Functions - -#### `(sbf_checkpoint:list_checkpoints)` -List all checkpoints. - -#### `(sbf_checkpoint:list_checkpoints session-name)` -List checkpoints for specific session. - -#### `(sbf_checkpoint:delete checkpoint-id)` -Delete a checkpoint. - -**Returns:** `{ok, info} | {error, reason}` - -#### `(sbf_checkpoint:auto_save state)` -Auto-save with timestamp-based ID. - -#### `(sbf_checkpoint:get_checkpoint_info checkpoint-id)` -Get metadata without loading full checkpoint. - ---- - -## Progress Tracking (sbf_progress) - -Track progress and calculate ETA. - -### Core Functions - -#### `(sbf_progress:new total)` -Create new progress tracker. - -**Parameters:** -- `total` - Total number of items - -**Returns:** Progress map - -#### `(sbf_progress:update progress current)` -Update progress with current count. - -**Returns:** Updated progress map - -#### `(sbf_progress:get_eta progress)` -Get estimated time remaining in seconds. - -**Returns:** Integer seconds or `'unknown` - -#### `(sbf_progress:get_percent progress)` -Get completion percentage. - -**Returns:** Float percentage (0.0-100.0) - -#### `(sbf_progress:get_rate progress)` -Get current rate (items per second). - -**Returns:** Float rate - -#### `(sbf_progress:print progress)` -Print progress bar to console. - -### Utility Functions - -#### `(sbf_progress:format_duration seconds)` -Format duration in human-readable form. - -**Returns:** String like "2m 30s" or "1h 15m" - -#### `(sbf_progress:get_stats progress)` -Get comprehensive progress statistics. - ---- - -## Logging (sbf_logger) - -Structured logging system. - -### Logging Functions - -#### `(sbf_logger:log level message)` -Log message at specified level. - -**Parameters:** -- `level` - `'debug | 'info | 'warning | 'error | 'success | 'failure` -- `message` - Message string - -#### `(sbf_logger:log level message metadata)` -Log with metadata. - -**Parameters:** -- `metadata` - Map of additional data - -#### `(sbf_logger:debug message)` -Log debug message. - -#### `(sbf_logger:info message)` -Log info message. - -#### `(sbf_logger:warning message)` -Log warning message. - -#### `(sbf_logger:error message)` -Log error message. - -#### `(sbf_logger:success message)` -Log success message. - -#### `(sbf_logger:failure message)` -Log failure message. - -### Configuration - -#### `(sbf_logger:set_level level)` -Set minimum logging level. - -**Parameters:** -- `level` - `'debug | 'info | 'warning | 'error` - -#### `(sbf_logger:get_level)` -Get current logging level. - -### File Logging - -#### `(sbf_logger:log_to_file filename message)` -Append log message to file. - -**Returns:** `ok | {error, reason}` - -### Specialized Logging - -#### `(sbf_logger:log_attempt pattern result metadata)` -Log a brute-force attempt. - -#### `(sbf_logger:log_session_start config)` -Log session start. - -#### `(sbf_logger:log_session_end stats)` -Log session end with statistics. - -#### `(sbf_logger:log_pause)` -Log pause event. - -#### `(sbf_logger:log_resume)` -Log resume event. - -#### `(sbf_logger:log_checkpoint checkpoint-id)` -Log checkpoint save. - ---- - -## Configuration Reference - -### Pattern Config - -```lisp -;; Wordlist -(list (tuple 'type 'wordlist) - (tuple 'filename "path/to/wordlist.txt") - (tuple 'mutations 'standard)) ; optional: minimal | standard | aggressive - -;; Charset -(list (tuple 'type 'charset) - (tuple 'charset "abcdefgh123456") - (tuple 'min_length 4) - (tuple 'max_length 8)) - -;; Sequential -(list (tuple 'type 'sequential) - (tuple 'start 1000) - (tuple 'end 9999)) - -;; Custom -(list (tuple 'type 'custom) - (tuple 'function (lambda () (list "pattern1" "pattern2")))) -``` - -### Target Config - -```lisp -;; HTTP -(list (tuple 'type 'http) - (tuple 'url "http://example.com/login") - (tuple 'method 'post) ; or 'get - (tuple 'username "admin") - (tuple 'username_field "user") - (tuple 'password_field "pass") - (tuple 'success_pattern "Welcome") - (tuple 'failure_pattern "Invalid") - (tuple 'body_format 'urlencoded) ; or 'json - (tuple 'headers (list (tuple "X-Custom" "value")))) - -;; Function -(list (tuple 'type 'function) - (tuple 'function (lambda (p) (validate p)))) - -;; Mock -(list (tuple 'type 'mock) - (tuple 'expected "correct_password")) -``` - ---- - -## Error Handling - -All functions return tagged tuples: - -```lisp -{ok, result} ; Success -{error, reason} ; Error with reason -{ok, state, data} ; Success with state and data -``` - -Common error reasons: -- `checkpoint_not_found` -- `invalid_checkpoint` -- `stopped` -- `waiting_confirmation` -- `unknown_target_type` -- `unknown_request` - ---- - -## Type Specifications - -### Pattern Types -- `'wordlist` - Load from file -- `'charset` - Generate combinations -- `'sequential` - Number sequences -- `'common` - Common passwords -- `'custom` - Custom function - -### Target Types -- `'http` - HTTP/HTTPS endpoints -- `'function` - Custom validators -- `'mock` - Testing targets -- `'ssh` - SSH (planned) - -### State Machine States -- `'running` - Actively processing -- `'paused` - Manually paused -- `'waiting_confirmation` - Auto-paused, waiting for user -- `'stopped` - Stopped/completed - ---- - -For complete examples, see the `examples/` directory and `docs/USAGE.md`. diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.adoc similarity index 51% rename from docs/CONTRIBUTING.md rename to docs/CONTRIBUTING.adoc index 5a91bb5..9bba223 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.adoc @@ -1,87 +1,84 @@ - -# Contributing to SafeBruteForce +== Contributing to SafeBruteForce -Thank you for your interest in contributing to SafeBruteForce! This document provides guidelines for contributing to the project. +Thank you for your interest in contributing to SafeBruteForce! This +document provides guidelines for contributing to the project. -## Table of Contents +=== Table of Contents -1. [Code of Conduct](#code-of-conduct) -2. [Getting Started](#getting-started) -3. [Development Setup](#development-setup) -4. [How to Contribute](#how-to-contribute) -5. [Coding Standards](#coding-standards) -6. [Testing](#testing) -7. [Documentation](#documentation) -8. [Security Considerations](#security-considerations) +[arabic] +. link:#code-of-conduct[Code of Conduct] +. link:#getting-started[Getting Started] +. link:#development-setup[Development Setup] +. link:#how-to-contribute[How to Contribute] +. link:#coding-standards[Coding Standards] +. link:#testing[Testing] +. link:#documentation[Documentation] +. link:#security-considerations[Security Considerations] -## Code of Conduct +=== Code of Conduct -### Ethical Requirements +==== Ethical Requirements All contributors must: -- ✅ Understand this is a **defensive security tool** -- ✅ Commit to **ethical use only** -- ✅ Follow **responsible disclosure** practices -- ✅ Respect **authorization requirements** -- ✅ Maintain the **"Safety First"** principle +* ✅ Understand this is a *defensive security tool* +* ✅ Commit to *ethical use only* +* ✅ Follow *responsible disclosure* practices +* ✅ Respect *authorization requirements* +* ✅ Maintain the *"`Safety First`"* principle -### What We Won't Accept +==== What We Won’t Accept We will reject contributions that: -- ❌ Remove or bypass safety mechanisms -- ❌ Encourage unauthorized access -- ❌ Implement DoS/DDoS capabilities -- ❌ Enable mass credential stuffing -- ❌ Violate ethical hacking principles +* ❌ Remove or bypass safety mechanisms +* ❌ Encourage unauthorized access +* ❌ Implement DoS/DDoS capabilities +* ❌ Enable mass credential stuffing +* ❌ Violate ethical hacking principles -## Getting Started +=== Getting Started -### Prerequisites +==== Prerequisites -- Erlang/OTP 26+ -- Rebar3 -- LFE (Lisp Flavored Erlang) -- Git -- Basic understanding of: - - Functional programming - - Erlang/OTP design principles - - Brute-force techniques - - Security testing ethics +* Erlang/OTP 26+ +* Rebar3 +* LFE (Lisp Flavored Erlang) +* Git +* Basic understanding of: +** Functional programming +** Erlang/OTP design principles +** Brute-force techniques +** Security testing ethics -### First Contribution +==== First Contribution Good first issues for newcomers: -1. **Documentation improvements** - - Fix typos - - Add examples - - Improve clarity - -2. **Pattern generators** - - Add new wordlist mutation strategies - - Implement date/time patterns - - Create industry-specific patterns - -3. **Output formatting** - - Improve console output - - Add export formats (JSON, CSV) - - Enhanced progress bars - -4. **Test coverage** - - Add unit tests - - Write integration tests - - Test edge cases - -## Development Setup - -### Clone and Build - -```bash +[arabic] +. *Documentation improvements* +* Fix typos +* Add examples +* Improve clarity +. *Pattern generators* +* Add new wordlist mutation strategies +* Implement date/time patterns +* Create industry-specific patterns +. *Output formatting* +* Improve console output +* Add export formats (JSON, CSV) +* Enhanced progress bars +. *Test coverage* +* Add unit tests +* Write integration tests +* Test edge cases + +=== Development Setup + +==== Clone and Build + +[source,bash] +---- # Fork the repository first on GitHub git clone https://github.com/YOUR_USERNAME/safe-brute-force.git cd safe-brute-force @@ -94,11 +91,12 @@ rebar3 compile # Run tests rebar3 lfe test -``` +---- -### Development Workflow +==== Development Workflow -```bash +[source,bash] +---- # Create a feature branch git checkout -b feature/your-feature-name @@ -115,11 +113,12 @@ git commit -m "Add: description of your changes" git push origin feature/your-feature-name # Open Pull Request on GitHub -``` +---- -### Interactive Development +==== Interactive Development -```bash +[source,bash] +---- # Start REPL for interactive testing rebar3 lfe repl @@ -128,15 +127,16 @@ rebar3 lfe repl # Test functions > (your_module:your_function args) -``` +---- -## How to Contribute +=== How to Contribute -### Reporting Bugs +==== Reporting Bugs Use GitHub Issues with the following template: -```markdown +[source,markdown] +---- **Bug Description** Clear description of the bug @@ -157,11 +157,12 @@ What you expected to happen **Additional Context** Logs, screenshots, etc. -``` +---- -### Suggesting Enhancements +==== Suggesting Enhancements -```markdown +[source,markdown] +---- **Feature Description** Clear description of the feature @@ -176,24 +177,25 @@ How does this maintain safety/ethical use? **Alternatives Considered** Other approaches you've thought about -``` +---- -### Pull Requests +==== Pull Requests -#### PR Checklist +===== PR Checklist -- [ ] Code follows LFE style guide -- [ ] All tests pass (`rebar3 lfe test`) -- [ ] New code has tests -- [ ] Documentation updated -- [ ] CHANGELOG.md updated -- [ ] Commit messages are clear -- [ ] Safety mechanisms preserved -- [ ] No sensitive data in commits +* [ ] Code follows LFE style guide +* [ ] All tests pass (`+rebar3 lfe test+`) +* [ ] New code has tests +* [ ] Documentation updated +* [ ] CHANGELOG.md updated +* [ ] Commit messages are clear +* [ ] Safety mechanisms preserved +* [ ] No sensitive data in commits -#### PR Template +===== PR Template -```markdown +[source,markdown] +---- ## Description What does this PR do? @@ -214,15 +216,16 @@ How was this tested? ## Related Issues Closes #123 -``` +---- -## Coding Standards +=== Coding Standards -### LFE Style Guide +==== LFE Style Guide -#### Module Structure +===== Module Structure -```lisp +[source,lisp] +---- ;;;; Module Title ;;;; Brief description @@ -251,11 +254,12 @@ Closes #123 "Internal helper function" ;; Implementation ) -``` +---- -#### Naming Conventions +===== Naming Conventions -```lisp +[source,lisp] +---- ;; Functions: lowercase with hyphens (defun calculate-checksum (data) ...) @@ -273,11 +277,12 @@ Closes #123 (('success data) ...) (('failure reason) ...) (('error error) ...)) -``` +---- -#### Comments and Documentation +===== Comments and Documentation -```lisp +[source,lisp] +---- ;; Single line comments for code explanation ;;; Section dividers for major sections @@ -295,11 +300,12 @@ Closes #123 Description of return value" ;; Implementation ) -``` +---- -### Error Handling +==== Error Handling -```lisp +[source,lisp] +---- ;; Always return tagged tuples (defun safe-operation (input) (try @@ -317,11 +323,12 @@ Closes #123 (handle-success result)) ((tuple 'error reason) (handle-error reason))) -``` +---- -### Testing Standards +==== Testing Standards -```lisp +[source,lisp] +---- ;;;; Module Tests (defmodule module_tests @@ -343,13 +350,14 @@ Closes #123 (case (module:risky-function bad-input) ((tuple 'error _) 'ok) (_ (eunit:assert_failed "Should have returned error")))) -``` +---- -## Testing +=== Testing -### Running Tests +==== Running Tests -```bash +[source,bash] +---- # All tests rebar3 lfe test @@ -358,26 +366,26 @@ rebar3 lfe test --module=sbf_patterns_tests # With coverage rebar3 lfe test --cover -``` +---- -### Test Requirements +==== Test Requirements Every new feature must include: -1. **Unit tests** - Test individual functions -2. **Integration tests** - Test component interactions -3. **Edge case tests** - Test boundary conditions -4. **Error tests** - Test error handling +[arabic] +. *Unit tests* - Test individual functions +. *Integration tests* - Test component interactions +. *Edge case tests* - Test boundary conditions +. *Error tests* - Test error handling -### Test Safety +==== Test Safety -Tests must: -- Use mock/local targets only -- Not make external network calls (unless mocked) -- Not test against real systems -- Include safety pause verification +Tests must: - Use mock/local targets only - Not make external network +calls (unless mocked) - Not test against real systems - Include safety +pause verification -```lisp +[source,lisp] +---- (defun safety_pause_test () "Verify safety pause triggers correctly" (let ((config (list (tuple 'pause_interval 5) @@ -385,24 +393,26 @@ Tests must: ;; Test pause triggers at correct interval ;; ... )) -``` +---- -## Documentation +=== Documentation -### Required Documentation +==== Required Documentation When adding features, update: -1. **Code comments** - Inline documentation -2. **Docstrings** - Function documentation -3. **README.md** - If feature is user-facing -4. **docs/USAGE.md** - Usage examples -5. **CHANGELOG.md** - Version history -6. **CLAUDE.md** - AI assistant guidance (if architecture changes) +[arabic] +. *Code comments* - Inline documentation +. *Docstrings* - Function documentation +. *README.md* - If feature is user-facing +. *docs/USAGE.md* - Usage examples +. *CHANGELOG.md* - Version history +. *CLAUDE.md* - AI assistant guidance (if architecture changes) -### Documentation Style +==== Documentation Style -```markdown +[source,markdown] +---- # Feature Name ## Overview @@ -411,87 +421,87 @@ Brief description of feature ## Usage ```lisp (example:code "here") -``` +---- + +=== Parameters -## Parameters -- `param1` - Description -- `param2` - Description +* `+param1+` - Description +* `+param2+` - Description + +=== Returns -## Returns Description of return value -## Examples -```lisp +=== Examples + +[source,lisp] +---- ;; Example 1: Basic usage (example:basic) ;; Example 2: Advanced usage (example:advanced options) -``` +---- + +=== Notes -## Notes -Any important notes or warnings -``` +Any important notes or warnings ``` -## Security Considerations +=== Security Considerations -### Security Review Checklist +==== Security Review Checklist All PRs must pass security review: -- [ ] No hardcoded credentials -- [ ] Input validation implemented -- [ ] Rate limiting respected -- [ ] Safety pause mechanism intact -- [ ] No sensitive data in logs -- [ ] Authorization checks present -- [ ] Error messages don't leak info -- [ ] Dependencies are trusted +* [ ] No hardcoded credentials +* [ ] Input validation implemented +* [ ] Rate limiting respected +* [ ] Safety pause mechanism intact +* [ ] No sensitive data in logs +* [ ] Authorization checks present +* [ ] Error messages don’t leak info +* [ ] Dependencies are trusted -### Responsible Disclosure +==== Responsible Disclosure If you discover a security vulnerability: -1. **DO NOT** create a public issue -2. Email security@[domain] with details -3. Allow reasonable time for fix -4. Follow coordinated disclosure +[arabic] +. *DO NOT* create a public issue +. Email security@[domain] with details +. Allow reasonable time for fix +. Follow coordinated disclosure -### Safety Mechanism Policy +==== Safety Mechanism Policy -**Never submit PRs that:** -- Disable safety pause by default -- Remove authorization checks -- Bypass rate limiting -- Enable mass/distributed attacks -- Implement evasion techniques +*Never submit PRs that:* - Disable safety pause by default - Remove +authorization checks - Bypass rate limiting - Enable mass/distributed +attacks - Implement evasion techniques -## Getting Help +=== Getting Help -### Resources +==== Resources -- **Documentation**: Read `docs/` directory -- **Examples**: Check `examples/` directory -- **Tests**: Look at existing tests for patterns -- **CLAUDE.md**: Guidance for understanding architecture +* *Documentation*: Read `+docs/+` directory +* *Examples*: Check `+examples/+` directory +* *Tests*: Look at existing tests for patterns +* *CLAUDE.md*: Guidance for understanding architecture -### Communication +==== Communication -- **GitHub Issues**: Bug reports and feature requests -- **Pull Requests**: Code discussions -- **Discussions**: General questions and ideas +* *GitHub Issues*: Bug reports and feature requests +* *Pull Requests*: Code discussions +* *Discussions*: General questions and ideas -### Maintainer Contact +==== Maintainer Contact -- Create an issue for project-related questions -- Email for security concerns -- Tag `@maintainer` in discussions +* Create an issue for project-related questions +* Email for security concerns +* Tag `+@maintainer+` in discussions -## Recognition +=== Recognition -Contributors will be: -- Listed in CONTRIBUTORS.md -- Credited in release notes -- Acknowledged in README.md +Contributors will be: - Listed in CONTRIBUTORS.md - Credited in release +notes - Acknowledged in README.md Thank you for helping make SafeBruteForce better! 🛡️ diff --git a/docs/MULTI_LANGUAGE_ARCHITECTURE.adoc b/docs/MULTI_LANGUAGE_ARCHITECTURE.adoc new file mode 100644 index 0000000..673df4b --- /dev/null +++ b/docs/MULTI_LANGUAGE_ARCHITECTURE.adoc @@ -0,0 +1,355 @@ +== Multi-Language Architecture (iSOS Model) + +SafeBruteForce now implements the *iSOS (Integrated Sound Operating +System)* multi-language architecture from the RSR Framework, combining +the strengths of multiple type-safe languages. + +=== Architecture Overview + +.... +┌────────────────────────────────────────────────────────────────┐ +│ SafeBruteForce iSOS Stack │ +└────────────────────────────────────────────────────────────────┘ + +┌──────────────────────┐ +│ LFE/Erlang/OTP │ Concurrency & Distribution Layer +│ (Dynamic) │ - Supervision trees +│ Memory Safe ✅ │ - Actor model concurrency +│ Type Safe: 40% │ - Fault tolerance +└──────────┬───────────┘ - State management + │ + ├─────────────────────────────────────────────┐ + │ │ + ▼ ▼ +┌──────────────────────┐ ┌───────────────────────┐ +│ ReScript (v11) │ │ Rust (1.75+) │ +│ (Static) │ │ (Static) │ +│ Type Safe: 100% ✅ │ │ Type Safe: 100% ✅ │ +│ Memory Safe: 100% │ │ Memory Safe: 100% ✅│ +└──────────────────────┘ └───────────────────────┘ +│ Pattern Generation │ │ Performance NIFs │ +│ - Charset combos │ │ - Parallel processing │ +│ - Mutations │ │ - Zero-copy operations│ +│ - Validation │ │ - Multi-core support │ +└──────────────────────┘ └───────────────────────┘ + │ │ + │ Port/FFI │ + └─────────────────┬───────────────────────────┘ + │ + ▼ + ┌─────────────────┐ + │ Unified API │ + │ (LFE Interface)│ + └─────────────────┘ +.... + +=== Why Multi-Language? + +==== Each Language for Its Strength + +*LFE/Erlang/OTP*: Concurrency & Fault Tolerance - ✅ Best-in-class actor +model - ✅ Hot code reloading - ✅ Supervisor trees - ✅ Distributed +systems - ⚠️ Dynamic typing (40% type safety with Dialyzer) - ✅ Memory +safe (garbage collected) + +*ReScript*: Pure Type Safety - ✅ 100% compile-time type checking - ✅ +Sound type system (no any/unknown) - ✅ Exhaustive pattern matching - ✅ +No null/undefined - ✅ Fast compilation - ✅ Compiles to readable +JavaScript - Port integration via Node.js + +*Rust*: Performance & Systems Programming - ✅ 100% type safety (strong +static types) - ✅ 100% memory safety (ownership + borrow checker) - ✅ +Zero-cost abstractions - ✅ Parallel processing (Rayon) - ✅ No garbage +collection overhead - ✅ C ABI compatibility (NIFs) + +=== Type Safety Breakdown + +[cols=",,,",options="header",] +|=== +|Component |Language |Type Safety |Memory Safety +|OTP Supervision |Erlang |40% |✅ 100% +|State Machine |LFE |40% (+Dialyzer) |✅ 100% +|Output/Logging |LFE |40% |✅ 100% +|*Pattern Generation* |*ReScript* |*✅ 100%* |*✅ 100%* +|*Performance NIFs* |*Rust* |*✅ 100%* |*✅ 100%* +|Checkpoints |LFE |40% |✅ 100% +|HTTP Client |Erlang |40% |✅ 100% +|=== + +*Overall*: 60%+ type safety (weighted by criticality) + +=== Component Responsibilities + +==== LFE/Erlang Layer (Orchestration) + +[source,lisp] +---- +;; High-level orchestration +(defun run (pattern-config target-config) + ;; Use ReScript for pattern generation + (let ((patterns (generate-patterns-rescript pattern-config))) + ;; Use Rust for fast mutations + (let ((mutated (mutate-patterns-rust patterns 'standard))) + ;; Use Erlang for concurrent execution + (process-patterns-concurrent mutated target-config)))) +---- + +*Handles*: - Application lifecycle - Supervision trees - State +management (gen_statem) - Worker orchestration (gen_server) - Network +I/O - File I/O - Checkpoint serialization + +==== ReScript Layer (Pure Logic) + +[source,rescript] +---- +// Type-safe pattern generation +let generatePatterns = (config: patternConfig): result, error> => { + switch config { + | Charset(chars, min, max) => generateCharsetCombinations(chars, min, max) + | Sequential(start, end) => generateSequential(start, end) + | Wordlist(words) => Ok(words) + | Custom(fn) => Ok(fn()) + } +} +---- + +*Handles*: - Pattern generation logic - Mutation algorithms - Validation +rules - Pure computations - Type-safe transformations + +==== Rust Layer (Performance) + +[source,rust] +---- +/// Parallel pattern generation with zero-copy optimization +pub fn generate_parallel( + charset: &Charset, + range: RangeInclusive, +) -> Result, GeneratorError> { + range + .into_par_iter() // Rayon parallel iterator + .map(|len| generate_for_length(charset, len)) + .collect() +} +---- + +*Handles*: - CPU-intensive operations - Parallel processing - Zero-copy +optimizations - Performance-critical paths - Low-level bit manipulation + +=== FFI Contracts & Safety + +==== Erlang ↔ ReScript (Port) + +[source,lisp] +---- +;; LFE side +(defun call-rescript (module function args) + (let* ((port (erlang:open_port + (tuple 'spawn (++ "node rescript_modules/" module ".bs.js")) + '(binary))) + (cmd (jsx:encode (map 'function function 'args args)))) + (erlang:port_command port cmd) + (receive + ((tuple port (tuple 'data result)) + (jsx:decode result))))) +---- + +*Safety*: - ✅ JSON serialization (type-safe boundaries) - ✅ Explicit +error handling - ✅ Timeout protection - ✅ Port isolation (crashes +don’t affect VM) + +==== Erlang ↔ Rust (NIF) + +[source,erlang] +---- +%% Erlang side +-module(sbf_rust_nif). +-export([generate_patterns/3]). +-on_load(init/0). + +init() -> + SoName = filename:join([code:priv_dir(safe_brute_force), "sbf_nif"]), + erlang:load_nif(SoName, 0). + +generate_patterns(Charset, MinLen, MaxLen) -> + %% Direct call to Rust NIF + generate_charset_combinations_nif(Charset, MinLen, MaxLen). +---- + +*Safety*: - ✅ Type conversion at boundary - ✅ Error atoms for failures +- ✅ No unsafe code in Rust module - ✅ Panic handling (returns error to +Erlang) - ⚠️ NIFs can crash VM if Rust panics (use panic catching) + +=== Build Integration + +==== Unified Build System + +[source,makefile] +---- +# Makefile targets for all languages + +all: compile-erlang compile-rescript compile-rust + +compile-erlang: + rebar3 compile + +compile-rescript: + cd rescript_modules && npm install && npm run build + +compile-rust: + cd rust_nif && cargo build --release + mkdir -p priv + cp rust_nif/target/release/libsbf_nif.so priv/sbf_nif.so + +clean: + rebar3 clean + cd rescript_modules && npm run clean + cd rust_nif && cargo clean + +test: test-erlang test-rescript test-rust + +test-erlang: + rebar3 lfe test + +test-rescript: + cd rescript_modules && npm test + +test-rust: + cd rust_nif && cargo test + +.PHONY: all compile-erlang compile-rescript compile-rust clean test +---- + +==== CI/CD Integration + +[source,yaml] +---- +# .gitlab-ci.yml additions +build:rescript: + stage: build + image: node:20 + script: + - cd rescript_modules + - npm install + - npm run build + artifacts: + paths: + - rescript_modules/src/*.bs.js + +build:rust: + stage: build + image: rust:latest + script: + - cd rust_nif + - cargo build --release + - cargo test + artifacts: + paths: + - rust_nif/target/release/libsbf_nif.so +---- + +=== Performance Characteristics + +==== Benchmarks (Estimated) + +[cols=",,,",options="header",] +|=== +|Operation |Pure LFE |+ ReScript |+ Rust NIF +|Generate 1k patterns |50ms |30ms |5ms +|Generate 10k patterns |500ms |300ms |50ms +|Mutations (1k words) |200ms |100ms |20ms +|Parallel (4-core) |N/A |N/A |5ms +|=== + +==== Memory Usage + +* LFE: ~50MB baseline (BEAM VM) +* +ReScript: ~20MB (Node.js port) +* +Rust NIF: ~5MB (shared library) +* *Total*: ~75MB for full stack + +=== Migration Path + +==== Phase 1: Current (LFE Only) ✅ + +* 100% LFE/Erlang +* 40% type safety (Dialyzer) +* Full functionality + +==== Phase 2: Add ReScript (Optional) 🔄 + +* Critical logic in ReScript +* 100% type safety for patterns +* Port-based integration +* Fallback to LFE if port fails + +==== Phase 3: Add Rust NIFs (Optional) 🔄 + +* Performance-critical paths +* 100% type + memory safety +* Direct NIF integration +* Graceful degradation if NIF unavailable + +==== Phase 4: Full iSOS Stack ⭐ + +* All three languages integrated +* 60%+ overall type safety +* Maximum performance +* Fault-tolerant boundaries + +=== When to Use Which Language? + +==== Use LFE/Erlang for: + +* ✅ Concurrent operations +* ✅ State machines +* ✅ Supervision +* ✅ Network I/O +* ✅ Long-running processes +* ✅ Hot code reloading + +==== Use ReScript for: + +* ✅ Pure computation +* ✅ Complex validation logic +* ✅ Type-critical algorithms +* ✅ Data transformations +* ✅ Pattern generation + +==== Use Rust for: + +* ✅ CPU-intensive operations +* ✅ Parallel processing +* ✅ Low-level optimization +* ✅ Memory-constrained operations +* ✅ Performance bottlenecks + +=== RSR Compliance Impact + +With multi-language architecture: + +*Type Safety*: 40% → 60-80% - LFE: 40% (with Dialyzer) - ReScript: 100% +(critical paths) - Rust: 100% (performance paths) - Weighted average: +~60-80% + +*Memory Safety*: 100% - All three languages are memory-safe - No manual +memory management - Garbage collection (LFE, ReScript) or ownership +(Rust) + +*Reproducible Builds*: 90% - rebar.lock (Erlang) - package-lock.json +(ReScript) - Cargo.lock (Rust) - Deterministic compilation flags + +*Overall RSR Level*: Silver → Gold trajectory + +=== Conclusion + +The multi-language iSOS architecture allows SafeBruteForce to: + +[arabic] +. *Leverage strengths* of each language +. *Achieve higher type safety* without rewriting everything +. *Maintain OTP benefits* (concurrency, fault tolerance) +. *Maximize performance* where it matters +. *Progress toward Gold level* RSR compliance + +This is the power of the iSOS model: *composable correctness* across +language boundaries. diff --git a/docs/MULTI_LANGUAGE_ARCHITECTURE.md b/docs/MULTI_LANGUAGE_ARCHITECTURE.md deleted file mode 100644 index ddb3287..0000000 --- a/docs/MULTI_LANGUAGE_ARCHITECTURE.md +++ /dev/null @@ -1,371 +0,0 @@ - -# Multi-Language Architecture (iSOS Model) - -SafeBruteForce now implements the **iSOS (Integrated Sound Operating System)** multi-language architecture from the RSR Framework, combining the strengths of multiple type-safe languages. - -## Architecture Overview - -``` -┌────────────────────────────────────────────────────────────────┐ -│ SafeBruteForce iSOS Stack │ -└────────────────────────────────────────────────────────────────┘ - -┌──────────────────────┐ -│ LFE/Erlang/OTP │ Concurrency & Distribution Layer -│ (Dynamic) │ - Supervision trees -│ Memory Safe ✅ │ - Actor model concurrency -│ Type Safe: 40% │ - Fault tolerance -└──────────┬───────────┘ - State management - │ - ├─────────────────────────────────────────────┐ - │ │ - ▼ ▼ -┌──────────────────────┐ ┌───────────────────────┐ -│ ReScript (v11) │ │ Rust (1.75+) │ -│ (Static) │ │ (Static) │ -│ Type Safe: 100% ✅ │ │ Type Safe: 100% ✅ │ -│ Memory Safe: 100% │ │ Memory Safe: 100% ✅│ -└──────────────────────┘ └───────────────────────┘ -│ Pattern Generation │ │ Performance NIFs │ -│ - Charset combos │ │ - Parallel processing │ -│ - Mutations │ │ - Zero-copy operations│ -│ - Validation │ │ - Multi-core support │ -└──────────────────────┘ └───────────────────────┘ - │ │ - │ Port/FFI │ - └─────────────────┬───────────────────────────┘ - │ - ▼ - ┌─────────────────┐ - │ Unified API │ - │ (LFE Interface)│ - └─────────────────┘ -``` - -## Why Multi-Language? - -### Each Language for Its Strength - -**LFE/Erlang/OTP**: Concurrency & Fault Tolerance -- ✅ Best-in-class actor model -- ✅ Hot code reloading -- ✅ Supervisor trees -- ✅ Distributed systems -- ⚠️ Dynamic typing (40% type safety with Dialyzer) -- ✅ Memory safe (garbage collected) - -**ReScript**: Pure Type Safety -- ✅ 100% compile-time type checking -- ✅ Sound type system (no any/unknown) -- ✅ Exhaustive pattern matching -- ✅ No null/undefined -- ✅ Fast compilation -- ✅ Compiles to readable JavaScript -- Port integration via Node.js - -**Rust**: Performance & Systems Programming -- ✅ 100% type safety (strong static types) -- ✅ 100% memory safety (ownership + borrow checker) -- ✅ Zero-cost abstractions -- ✅ Parallel processing (Rayon) -- ✅ No garbage collection overhead -- ✅ C ABI compatibility (NIFs) - -## Type Safety Breakdown - -| Component | Language | Type Safety | Memory Safety | -|-----------|----------|-------------|---------------| -| OTP Supervision | Erlang | 40% | ✅ 100% | -| State Machine | LFE | 40% (+Dialyzer) | ✅ 100% | -| Output/Logging | LFE | 40% | ✅ 100% | -| **Pattern Generation** | **ReScript** | **✅ 100%** | **✅ 100%** | -| **Performance NIFs** | **Rust** | **✅ 100%** | **✅ 100%** | -| Checkpoints | LFE | 40% | ✅ 100% | -| HTTP Client | Erlang | 40% | ✅ 100% | - -**Overall**: 60%+ type safety (weighted by criticality) - -## Component Responsibilities - -### LFE/Erlang Layer (Orchestration) - -```lisp -;; High-level orchestration -(defun run (pattern-config target-config) - ;; Use ReScript for pattern generation - (let ((patterns (generate-patterns-rescript pattern-config))) - ;; Use Rust for fast mutations - (let ((mutated (mutate-patterns-rust patterns 'standard))) - ;; Use Erlang for concurrent execution - (process-patterns-concurrent mutated target-config)))) -``` - -**Handles**: -- Application lifecycle -- Supervision trees -- State management (gen_statem) -- Worker orchestration (gen_server) -- Network I/O -- File I/O -- Checkpoint serialization - -### ReScript Layer (Pure Logic) - -```rescript -// Type-safe pattern generation -let generatePatterns = (config: patternConfig): result, error> => { - switch config { - | Charset(chars, min, max) => generateCharsetCombinations(chars, min, max) - | Sequential(start, end) => generateSequential(start, end) - | Wordlist(words) => Ok(words) - | Custom(fn) => Ok(fn()) - } -} -``` - -**Handles**: -- Pattern generation logic -- Mutation algorithms -- Validation rules -- Pure computations -- Type-safe transformations - -### Rust Layer (Performance) - -```rust -/// Parallel pattern generation with zero-copy optimization -pub fn generate_parallel( - charset: &Charset, - range: RangeInclusive, -) -> Result, GeneratorError> { - range - .into_par_iter() // Rayon parallel iterator - .map(|len| generate_for_length(charset, len)) - .collect() -} -``` - -**Handles**: -- CPU-intensive operations -- Parallel processing -- Zero-copy optimizations -- Performance-critical paths -- Low-level bit manipulation - -## FFI Contracts & Safety - -### Erlang ↔ ReScript (Port) - -```lisp -;; LFE side -(defun call-rescript (module function args) - (let* ((port (erlang:open_port - (tuple 'spawn (++ "node rescript_modules/" module ".bs.js")) - '(binary))) - (cmd (jsx:encode (map 'function function 'args args)))) - (erlang:port_command port cmd) - (receive - ((tuple port (tuple 'data result)) - (jsx:decode result))))) -``` - -**Safety**: -- ✅ JSON serialization (type-safe boundaries) -- ✅ Explicit error handling -- ✅ Timeout protection -- ✅ Port isolation (crashes don't affect VM) - -### Erlang ↔ Rust (NIF) - -```erlang -%% Erlang side --module(sbf_rust_nif). --export([generate_patterns/3]). --on_load(init/0). - -init() -> - SoName = filename:join([code:priv_dir(safe_brute_force), "sbf_nif"]), - erlang:load_nif(SoName, 0). - -generate_patterns(Charset, MinLen, MaxLen) -> - %% Direct call to Rust NIF - generate_charset_combinations_nif(Charset, MinLen, MaxLen). -``` - -**Safety**: -- ✅ Type conversion at boundary -- ✅ Error atoms for failures -- ✅ No unsafe code in Rust module -- ✅ Panic handling (returns error to Erlang) -- ⚠️ NIFs can crash VM if Rust panics (use panic catching) - -## Build Integration - -### Unified Build System - -```makefile -# Makefile targets for all languages - -all: compile-erlang compile-rescript compile-rust - -compile-erlang: - rebar3 compile - -compile-rescript: - cd rescript_modules && npm install && npm run build - -compile-rust: - cd rust_nif && cargo build --release - mkdir -p priv - cp rust_nif/target/release/libsbf_nif.so priv/sbf_nif.so - -clean: - rebar3 clean - cd rescript_modules && npm run clean - cd rust_nif && cargo clean - -test: test-erlang test-rescript test-rust - -test-erlang: - rebar3 lfe test - -test-rescript: - cd rescript_modules && npm test - -test-rust: - cd rust_nif && cargo test - -.PHONY: all compile-erlang compile-rescript compile-rust clean test -``` - -### CI/CD Integration - -```yaml -# .gitlab-ci.yml additions -build:rescript: - stage: build - image: node:20 - script: - - cd rescript_modules - - npm install - - npm run build - artifacts: - paths: - - rescript_modules/src/*.bs.js - -build:rust: - stage: build - image: rust:latest - script: - - cd rust_nif - - cargo build --release - - cargo test - artifacts: - paths: - - rust_nif/target/release/libsbf_nif.so -``` - -## Performance Characteristics - -### Benchmarks (Estimated) - -| Operation | Pure LFE | + ReScript | + Rust NIF | -|-----------|----------|------------|------------| -| Generate 1k patterns | 50ms | 30ms | 5ms | -| Generate 10k patterns | 500ms | 300ms | 50ms | -| Mutations (1k words) | 200ms | 100ms | 20ms | -| Parallel (4-core) | N/A | N/A | 5ms | - -### Memory Usage - -- LFE: ~50MB baseline (BEAM VM) -- +ReScript: ~20MB (Node.js port) -- +Rust NIF: ~5MB (shared library) -- **Total**: ~75MB for full stack - -## Migration Path - -### Phase 1: Current (LFE Only) ✅ -- 100% LFE/Erlang -- 40% type safety (Dialyzer) -- Full functionality - -### Phase 2: Add ReScript (Optional) 🔄 -- Critical logic in ReScript -- 100% type safety for patterns -- Port-based integration -- Fallback to LFE if port fails - -### Phase 3: Add Rust NIFs (Optional) 🔄 -- Performance-critical paths -- 100% type + memory safety -- Direct NIF integration -- Graceful degradation if NIF unavailable - -### Phase 4: Full iSOS Stack ⭐ -- All three languages integrated -- 60%+ overall type safety -- Maximum performance -- Fault-tolerant boundaries - -## When to Use Which Language? - -### Use LFE/Erlang for: -- ✅ Concurrent operations -- ✅ State machines -- ✅ Supervision -- ✅ Network I/O -- ✅ Long-running processes -- ✅ Hot code reloading - -### Use ReScript for: -- ✅ Pure computation -- ✅ Complex validation logic -- ✅ Type-critical algorithms -- ✅ Data transformations -- ✅ Pattern generation - -### Use Rust for: -- ✅ CPU-intensive operations -- ✅ Parallel processing -- ✅ Low-level optimization -- ✅ Memory-constrained operations -- ✅ Performance bottlenecks - -## RSR Compliance Impact - -With multi-language architecture: - -**Type Safety**: 40% → 60-80% -- LFE: 40% (with Dialyzer) -- ReScript: 100% (critical paths) -- Rust: 100% (performance paths) -- Weighted average: ~60-80% - -**Memory Safety**: 100% -- All three languages are memory-safe -- No manual memory management -- Garbage collection (LFE, ReScript) or ownership (Rust) - -**Reproducible Builds**: 90% -- rebar.lock (Erlang) -- package-lock.json (ReScript) -- Cargo.lock (Rust) -- Deterministic compilation flags - -**Overall RSR Level**: Silver → Gold trajectory - -## Conclusion - -The multi-language iSOS architecture allows SafeBruteForce to: - -1. **Leverage strengths** of each language -2. **Achieve higher type safety** without rewriting everything -3. **Maintain OTP benefits** (concurrency, fault tolerance) -4. **Maximize performance** where it matters -5. **Progress toward Gold level** RSR compliance - -This is the power of the iSOS model: **composable correctness** across language boundaries. diff --git a/docs/QUICKSTART.md b/docs/QUICKSTART.adoc similarity index 72% rename from docs/QUICKSTART.md rename to docs/QUICKSTART.adoc index a51242a..d8af77d 100644 --- a/docs/QUICKSTART.md +++ b/docs/QUICKSTART.adoc @@ -1,16 +1,13 @@ - -# SafeBruteForce Quick Start Guide +== SafeBruteForce Quick Start Guide Get up and running with SafeBruteForce in 5 minutes. -## Prerequisites +=== Prerequisites Install Erlang/OTP 26+ and Rebar3: -```bash +[source,bash] +---- # Ubuntu/Debian sudo apt-get update sudo apt-get install erlang rebar3 @@ -21,11 +18,12 @@ brew install erlang rebar3 # Verify installation erl -version rebar3 version -``` +---- -## Installation +=== Installation -```bash +[source,bash] +---- # Clone the repository git clone https://github.com/Hyperpolymath/safe-brute-force.git cd safe-brute-force @@ -35,19 +33,21 @@ rebar3 compile # Run tests to verify installation rebar3 lfe test -``` +---- -## Your First Brute-Force Test +=== Your First Brute-Force Test -### Example 1: Simple Function Test +==== Example 1: Simple Function Test Start the interactive REPL: -```bash +[source,bash] +---- rebar3 lfe repl -``` +---- -```lisp +[source,lisp] +---- ;; Start the application > (sbf:start) @@ -74,13 +74,14 @@ rebar3 lfe repl ;; Check results at any time: > (sbf:stats) -``` +---- -### Example 2: PIN Code Test +==== Example 2: PIN Code Test Test all 4-digit PIN codes (with a mock validator): -```lisp +[source,lisp] +---- > (sbf:start) ;; Create a PIN validator (this is just an example - replace with real logic) @@ -89,11 +90,12 @@ Test all 4-digit PIN codes (with a mock validator): (sbf:test_pins validator)) ;; This will test all 10,000 PINs, pausing every 25 attempts -``` +---- -### Example 3: HTTP Login Test (Requires Running Server) +==== Example 3: HTTP Login Test (Requires Running Server) -```lisp +[source,lisp] +---- > (sbf:start) ;; Test against a local web application @@ -108,46 +110,47 @@ Test all 4-digit PIN codes (with a mock validator): ;; 2. Try each password against the HTTP endpoint ;; 3. Pause every 25 attempts for your confirmation ;; 4. Report successful credentials -``` +---- -## Using the CLI +=== Using the CLI Make the CLI executable: -```bash +[source,bash] +---- chmod +x sbf_cli -``` +---- -### Test with Wordlist +==== Test with Wordlist -```bash +[source,bash] +---- ./sbf_cli wordlist priv/wordlists/common-passwords.txt \ http://localhost:8080/login admin -``` +---- -The CLI will: -1. Prompt for authorization confirmation -2. Load the wordlist -3. Begin testing -4. Pause every 25 attempts +The CLI will: 1. Prompt for authorization confirmation 2. Load the +wordlist 3. Begin testing 4. Pause every 25 attempts -### Test PIN Codes +==== Test PIN Codes -```bash +[source,bash] +---- ./sbf_cli pins http://localhost:8080/verify -``` +---- -### Generate Charset Combinations +==== Generate Charset Combinations -```bash +[source,bash] +---- ./sbf_cli charset "abc123" 4 6 http://localhost:8080/api -``` +---- -## Understanding the Output +=== Understanding the Output -### During Execution +==== During Execution -``` +.... [SafeBruteForce] Generated 60 patterns [SafeBruteForce] Batch size: 25 [SafeBruteForce] ⚠️ Pause every 25 attempts (safety enabled) @@ -155,22 +158,22 @@ The CLI will: [=========>---------] 45.0% (27/60) | 12.5/s | ETA: 3s [SUCCESS] Pattern: secret123 -> SUCCESS -``` +.... -### At Pause +==== At Pause -``` +.... ╔════════════════════════════════════════════════╗ ║ 🛑 PAUSED - Safety Checkpoint ║ ║ Completed 25 attempts ║ ║ Call (sbf:resume) to continue ║ ║ Call (sbf:stats) to see results ║ ╚════════════════════════════════════════════════╝ -``` +.... -### Final Summary +==== Final Summary -``` +.... ╔════════════════════════════════════════════════════╗ ║ SafeBruteForce - Session Summary ║ ╠════════════════════════════════════════════════════╣ @@ -185,13 +188,14 @@ The CLI will: Successful Patterns: ✓ secret123 -``` +.... -## Common Commands +=== Common Commands -### REPL Commands +==== REPL Commands -```lisp +[source,lisp] +---- ;; Start application (sbf:start) @@ -218,13 +222,14 @@ Successful Patterns: ;; Stop application (sbf:stop) -``` +---- -## Creating Custom Tests +=== Creating Custom Tests -### Custom Pattern Generator +==== Custom Pattern Generator -```lisp +[source,lisp] +---- ;; Generate year-based passwords (let ((pattern-generator (lambda () @@ -240,11 +245,12 @@ Successful Patterns: (list (tuple 'type 'function) (tuple 'function test-fn)))) (sbf:run pattern-config target-config)) -``` +---- -### Custom HTTP Test +==== Custom HTTP Test -```lisp +[source,lisp] +---- (let ((pattern-config (list (tuple 'type 'wordlist) (tuple 'filename "passwords.txt") @@ -260,13 +266,14 @@ Successful Patterns: (tuple 'success_pattern "\"authenticated\":true") (tuple 'headers (list (tuple "Content-Type" "application/json")))))) (sbf:run pattern-config target-config)) -``` +---- -## Configuration +=== Configuration -Customize behavior by editing `config/sys.config`: +Customize behavior by editing `+config/sys.config+`: -```erlang +[source,erlang] +---- {safe_brute_force, [ {pause_interval, 25}, % Change pause frequency {max_workers, 10}, % Concurrent workers @@ -275,80 +282,87 @@ Customize behavior by editing `config/sys.config`: {checkpoint_interval, 100}, % Auto-checkpoint frequency {safety_enabled, true} % NEVER disable in production! ]} -``` +---- -## Safety Features +=== Safety Features SafeBruteForce includes mandatory safety features: -1. **Automatic Pause**: Stops every 25 attempts by default -2. **User Confirmation**: You must explicitly resume -3. **Rate Limiting**: Prevents overwhelming target systems -4. **Authorization Checks**: CLI prompts for confirmation -5. **Audit Logging**: All actions are logged +[arabic] +. *Automatic Pause*: Stops every 25 attempts by default +. *User Confirmation*: You must explicitly resume +. *Rate Limiting*: Prevents overwhelming target systems +. *Authorization Checks*: CLI prompts for confirmation +. *Audit Logging*: All actions are logged -## Best Practices +=== Best Practices -1. **Always get authorization** before testing any system -2. **Start with small wordlists** to verify configuration -3. **Use rate limiting** to be respectful to systems -4. **Save checkpoints** for long operations -5. **Test locally first** before testing remote systems +[arabic] +. *Always get authorization* before testing any system +. *Start with small wordlists* to verify configuration +. *Use rate limiting* to be respectful to systems +. *Save checkpoints* for long operations +. *Test locally first* before testing remote systems -## Troubleshooting +=== Troubleshooting -### Application won't start +==== Application won’t start -```bash +[source,bash] +---- # Check Erlang version erl -version # Should be 26+ # Clean and rebuild rebar3 clean rebar3 compile -``` +---- -### Tests failing +==== Tests failing -```bash +[source,bash] +---- # Run verbose tests rebar3 lfe test --verbose # Check for missing dependencies rebar3 get-deps rebar3 compile -``` +---- -### Permission denied on sbf_cli +==== Permission denied on sbf_cli -```bash +[source,bash] +---- # Make executable chmod +x sbf_cli -``` +---- -### Checkpoints not saving +==== Checkpoints not saving -```bash +[source,bash] +---- # Ensure directory exists mkdir -p priv/checkpoints chmod 755 priv/checkpoints -``` +---- -## Next Steps +=== Next Steps -- Read the [Full Usage Guide](USAGE.md) -- Review [Security Best Practices](SECURITY.md) -- Check [API Reference](API_REFERENCE.md) -- Explore example code in `examples/` -- Review [Contributing Guidelines](CONTRIBUTING.md) +* Read the link:USAGE.md[Full Usage Guide] +* Review link:SECURITY.md[Security Best Practices] +* Check link:API_REFERENCE.md[API Reference] +* Explore example code in `+examples/+` +* Review link:CONTRIBUTING.md[Contributing Guidelines] -## Getting Help +=== Getting Help -- **Documentation**: Check the `docs/` directory -- **Examples**: See `examples/` for complete code -- **Issues**: Report bugs on GitHub -- **Security**: See SECURITY.md for responsible disclosure +* *Documentation*: Check the `+docs/+` directory +* *Examples*: See `+examples/+` for complete code +* *Issues*: Report bugs on GitHub +* *Security*: See SECURITY.md for responsible disclosure ---- +''''' -**Remember**: SafeBruteForce is for authorized testing only. Always ensure you have explicit permission before testing any system. +*Remember*: SafeBruteForce is for authorized testing only. Always ensure +you have explicit permission before testing any system. diff --git a/docs/REPRODUCIBLE_BUILDS.adoc b/docs/REPRODUCIBLE_BUILDS.adoc new file mode 100644 index 0000000..b03c1f8 --- /dev/null +++ b/docs/REPRODUCIBLE_BUILDS.adoc @@ -0,0 +1,219 @@ +== Reproducible Builds Status and Roadmap + +=== Current Status: PARTIAL ⚠️ + +SafeBruteForce has basic reproducible build infrastructure but not yet +*bit-for-bit* reproducibility. + +==== What We Have ✅ + +[arabic] +. *Dependency Locking* +* `+rebar.lock+` - pins exact dependency versions +* All dependencies fetched from known sources +* Version pinning in `+rebar.config+` +. *Nix Flake* +* `+flake.nix+` - declares build environment +* Nix provides hermetic builds +* Locked nixpkgs version +* Development shell with fixed tool versions +. *Build Tools Versioned* +* Erlang/OTP 26.2 (specified) +* Rebar3 3.22.1 (specified) +* LFE 2.1.5 (target) + +==== What’s Missing ❌ + +[arabic] +. *BEAM File Non-Determinism* ++ +.... +Issue: Erlang BEAM compiler embeds: +- Compilation timestamps +- Build machine info +- Non-deterministic ordering + +Solution: Use ERL_COMPILER_OPTIONS with deterministic flag +Status: NOT YET IMPLEMENTED +.... +. *LFE Dependency Not Fully Locked* ++ +.... +Issue: flake.nix has placeholder SHA256 +Solution: Calculate actual hash or use nixpkgs LFE +Status: TODO +.... +. *No Reproducibility Verification* ++ +.... +Issue: No CI job that rebuilds and compares artifacts +Solution: Add "reproducible-check" CI job +Status: NOT YET IMPLEMENTED +.... +. *No Published Checksums* ++ +.... +Issue: Releases don't include SHA256SUMS file +Solution: Generate and sign checksums on release +Status: NOT YET IMPLEMENTED +.... + +=== Achieving 100% Reproducibility + +==== Phase 1: Fix Erlang Compilation (Quick Win) + +*Add to rebar.config:* + +[source,erlang] +---- +{erl_opts, [ + debug_info, + deterministic, % Remove timestamps and paths + {source, "."} % Relative paths only +]}. + +{erlc_compiler, [ + {source_ext, ".erl"}, + {out_dir, "ebin"} +]}. +---- + +*Add to build process:* + +[source,bash] +---- +export SOURCE_DATE_EPOCH=1705334400 # Fixed timestamp +export ERL_COMPILER_OPTIONS="[deterministic]" +export LANG=C.UTF-8 +export LC_ALL=C.UTF-8 +---- + +*Estimated Effort*: 2-4 hours *Achievement*: 80% reproducibility + +==== Phase 2: Nix Hardening (Medium Effort) + +*Fix flake.nix:* 1. Calculate real SHA256 for LFE: +`+bash nix-prefetch-git https://github.com/lfe/lfe --rev v2.1.5+` + +[arabic, start=2] +. Add to build phase: ++ +[source,nix] +---- +# Make builds deterministic +export SOURCE_DATE_EPOCH=1 +export LANG=C.UTF-8 +export BUILD_ID="" +---- +. Remove non-deterministic elements: +* Strip build paths from artifacts +* Use `+strip-nondeterminism+` tool +* Ensure consistent file ordering + +*Estimated Effort*: 4-8 hours *Achievement*: 90% reproducibility + +==== Phase 3: Verification Infrastructure (High Effort) + +*Add CI job (.gitlab-ci.yml):* + +[source,yaml] +---- +reproducible-verify: + stage: test + script: + - echo "Build 1..." + - nix build .#default --rebuild + - sha256sum result > build1.sum + + - echo "Build 2 (clean)..." + - nix build .#default --rebuild + - sha256sum result > build2.sum + + - echo "Comparing..." + - diff build1.sum build2.sum || (echo "NOT REPRODUCIBLE!" && exit 1) + - echo "✓ Builds are reproducible!" +---- + +*Add release checksums:* + +[source,yaml] +---- +release:checksums: + stage: deploy + script: + - sha256sum _build/prod/rel/*.tar.gz > SHA256SUMS + - gpg --detach-sign --armor SHA256SUMS + artifacts: + paths: + - SHA256SUMS + - SHA256SUMS.asc +---- + +*Estimated Effort*: 8-12 hours *Achievement*: 95% reproducibility + +==== Phase 4: Multi-Builder Verification (Gold Standard) + +*Independent builders verify:* + +[source,bash] +---- +# Builder A +nix build github:Hyperpolymath/safe-brute-force +sha256sum result + +# Builder B (different machine) +nix build github:Hyperpolymath/safe-brute-force +sha256sum result + +# Compare hashes - should match! +---- + +*Publish attestations:* - reproducible-builds.org integration - Public +verification by third parties - Transparency log of build hashes + +*Estimated Effort*: 16-24 hours *Achievement*: 100% reproducibility +(Gold Level) + +=== Why This Matters for RSR + +Reproducible builds ensure: 1. ✅ *Security*: Verify no malicious code +injection 2. ✅ *Trust*: Anyone can verify artifacts 3. ✅ +*Auditability*: Trace source → binary 4. ✅ *Long-term*: Rebuild exact +same artifact years later + +=== Comparison with rhodium-minimal + +The rhodium-minimal example achieves 100% because: - *Rust* has +deterministic compilation by default - Cargo.lock provides perfect +dependency pinning - Fewer runtime dependencies than Erlang/BEAM - +Simpler build process + +For LFE/Erlang to match: - Need `+deterministic+` compiler flag - Need +SOURCE_DATE_EPOCH - Need to strip non-deterministic metadata - Need +verification infrastructure + +=== Current RSR Level Impact + +*Bronze Level*: ✅ Dependency locking sufficient *Silver Level*: ⚠️ Need +basic reproducibility (80%+) *Gold Level*: ❌ Need verified +reproducibility (100%) + +=== Recommendation + +*Short-term* (for Silver Level): 1. Add `+deterministic+` to erl_opts (2 +hours) 2. Fix flake.nix SHA256 (1 hour) 3. Add SOURCE_DATE_EPOCH (1 +hour) → *Achieves 80-90% reproducibility* + +*Long-term* (for Gold Level): 1. Add verification CI job (8 hours) 2. +Publish checksums on release (4 hours) 3. Multi-builder verification (12 +hours) → *Achieves 100% reproducibility* + +=== Current Priority + +Focus on *Dialyzer type specs* FIRST (bigger impact on code quality), +then tackle reproducible builds for Silver/Gold levels. + +''''' + +*Status*: Partial (60%) *Path to Silver*: 80% (achievable in 4-6 hours) +*Path to Gold*: 100% (achievable in 24-32 hours) diff --git a/docs/REPRODUCIBLE_BUILDS.md b/docs/REPRODUCIBLE_BUILDS.md deleted file mode 100644 index 3122966..0000000 --- a/docs/REPRODUCIBLE_BUILDS.md +++ /dev/null @@ -1,226 +0,0 @@ - -# Reproducible Builds Status and Roadmap - -## Current Status: PARTIAL ⚠️ - -SafeBruteForce has basic reproducible build infrastructure but not yet **bit-for-bit** reproducibility. - -### What We Have ✅ - -1. **Dependency Locking** - - `rebar.lock` - pins exact dependency versions - - All dependencies fetched from known sources - - Version pinning in `rebar.config` - -2. **Nix Flake** - - `flake.nix` - declares build environment - - Nix provides hermetic builds - - Locked nixpkgs version - - Development shell with fixed tool versions - -3. **Build Tools Versioned** - - Erlang/OTP 26.2 (specified) - - Rebar3 3.22.1 (specified) - - LFE 2.1.5 (target) - -### What's Missing ❌ - -1. **BEAM File Non-Determinism** - ``` - Issue: Erlang BEAM compiler embeds: - - Compilation timestamps - - Build machine info - - Non-deterministic ordering - - Solution: Use ERL_COMPILER_OPTIONS with deterministic flag - Status: NOT YET IMPLEMENTED - ``` - -2. **LFE Dependency Not Fully Locked** - ``` - Issue: flake.nix has placeholder SHA256 - Solution: Calculate actual hash or use nixpkgs LFE - Status: TODO - ``` - -3. **No Reproducibility Verification** - ``` - Issue: No CI job that rebuilds and compares artifacts - Solution: Add "reproducible-check" CI job - Status: NOT YET IMPLEMENTED - ``` - -4. **No Published Checksums** - ``` - Issue: Releases don't include SHA256SUMS file - Solution: Generate and sign checksums on release - Status: NOT YET IMPLEMENTED - ``` - -## Achieving 100% Reproducibility - -### Phase 1: Fix Erlang Compilation (Quick Win) - -**Add to rebar.config:** -```erlang -{erl_opts, [ - debug_info, - deterministic, % Remove timestamps and paths - {source, "."} % Relative paths only -]}. - -{erlc_compiler, [ - {source_ext, ".erl"}, - {out_dir, "ebin"} -]}. -``` - -**Add to build process:** -```bash -export SOURCE_DATE_EPOCH=1705334400 # Fixed timestamp -export ERL_COMPILER_OPTIONS="[deterministic]" -export LANG=C.UTF-8 -export LC_ALL=C.UTF-8 -``` - -**Estimated Effort**: 2-4 hours -**Achievement**: 80% reproducibility - -### Phase 2: Nix Hardening (Medium Effort) - -**Fix flake.nix:** -1. Calculate real SHA256 for LFE: - ```bash - nix-prefetch-git https://github.com/lfe/lfe --rev v2.1.5 - ``` - -2. Add to build phase: - ```nix - # Make builds deterministic - export SOURCE_DATE_EPOCH=1 - export LANG=C.UTF-8 - export BUILD_ID="" - ``` - -3. Remove non-deterministic elements: - - Strip build paths from artifacts - - Use `strip-nondeterminism` tool - - Ensure consistent file ordering - -**Estimated Effort**: 4-8 hours -**Achievement**: 90% reproducibility - -### Phase 3: Verification Infrastructure (High Effort) - -**Add CI job (.gitlab-ci.yml):** -```yaml -reproducible-verify: - stage: test - script: - - echo "Build 1..." - - nix build .#default --rebuild - - sha256sum result > build1.sum - - - echo "Build 2 (clean)..." - - nix build .#default --rebuild - - sha256sum result > build2.sum - - - echo "Comparing..." - - diff build1.sum build2.sum || (echo "NOT REPRODUCIBLE!" && exit 1) - - echo "✓ Builds are reproducible!" -``` - -**Add release checksums:** -```yaml -release:checksums: - stage: deploy - script: - - sha256sum _build/prod/rel/*.tar.gz > SHA256SUMS - - gpg --detach-sign --armor SHA256SUMS - artifacts: - paths: - - SHA256SUMS - - SHA256SUMS.asc -``` - -**Estimated Effort**: 8-12 hours -**Achievement**: 95% reproducibility - -### Phase 4: Multi-Builder Verification (Gold Standard) - -**Independent builders verify:** -```bash -# Builder A -nix build github:Hyperpolymath/safe-brute-force -sha256sum result - -# Builder B (different machine) -nix build github:Hyperpolymath/safe-brute-force -sha256sum result - -# Compare hashes - should match! -``` - -**Publish attestations:** -- reproducible-builds.org integration -- Public verification by third parties -- Transparency log of build hashes - -**Estimated Effort**: 16-24 hours -**Achievement**: 100% reproducibility (Gold Level) - -## Why This Matters for RSR - -Reproducible builds ensure: -1. ✅ **Security**: Verify no malicious code injection -2. ✅ **Trust**: Anyone can verify artifacts -3. ✅ **Auditability**: Trace source → binary -4. ✅ **Long-term**: Rebuild exact same artifact years later - -## Comparison with rhodium-minimal - -The rhodium-minimal example achieves 100% because: -- **Rust** has deterministic compilation by default -- Cargo.lock provides perfect dependency pinning -- Fewer runtime dependencies than Erlang/BEAM -- Simpler build process - -For LFE/Erlang to match: -- Need `deterministic` compiler flag -- Need SOURCE_DATE_EPOCH -- Need to strip non-deterministic metadata -- Need verification infrastructure - -## Current RSR Level Impact - -**Bronze Level**: ✅ Dependency locking sufficient -**Silver Level**: ⚠️ Need basic reproducibility (80%+) -**Gold Level**: ❌ Need verified reproducibility (100%) - -## Recommendation - -**Short-term** (for Silver Level): -1. Add `deterministic` to erl_opts (2 hours) -2. Fix flake.nix SHA256 (1 hour) -3. Add SOURCE_DATE_EPOCH (1 hour) -→ **Achieves 80-90% reproducibility** - -**Long-term** (for Gold Level): -1. Add verification CI job (8 hours) -2. Publish checksums on release (4 hours) -3. Multi-builder verification (12 hours) -→ **Achieves 100% reproducibility** - -## Current Priority - -Focus on **Dialyzer type specs** FIRST (bigger impact on code quality), -then tackle reproducible builds for Silver/Gold levels. - ---- - -**Status**: Partial (60%) -**Path to Silver**: 80% (achievable in 4-6 hours) -**Path to Gold**: 100% (achievable in 24-32 hours) diff --git a/docs/SECURITY.adoc b/docs/SECURITY.adoc new file mode 100644 index 0000000..db074c4 --- /dev/null +++ b/docs/SECURITY.adoc @@ -0,0 +1,365 @@ +== Security Best Practices + +=== Legal and Ethical Considerations + +==== Authorization is Mandatory + +*⚠️ CRITICAL: You must have explicit written authorization before +testing any system.* + +SafeBruteForce is designed for: - ✅ Authorized penetration testing +engagements - ✅ CTF (Capture The Flag) competitions - ✅ Security +research on systems you own - ✅ Educational demonstrations in +controlled environments - ✅ Password policy validation for your own +organization + +SafeBruteForce must NEVER be used for: - ❌ Unauthorized access to +third-party systems - ❌ Credential stuffing or account takeover attacks +- ❌ Testing systems without written permission - ❌ Circumventing +security controls maliciously - ❌ Any activity that violates laws or +regulations + +==== Legal Frameworks + +Be aware of applicable laws: - *CFAA (USA)*: Computer Fraud and Abuse +Act - *GDPR (EU)*: Data protection regulations - *DMCA (USA)*: +Anti-circumvention provisions - *Local laws*: Vary by jurisdiction + +*Violation of these laws can result in criminal prosecution and civil +liability.* + +=== Responsible Testing Practices + +==== 1. Documentation and Authorization + +Before starting any test: + +[source,markdown] +---- +[ ] Obtain written authorization from system owner +[ ] Document scope of testing (URLs, accounts, timeframes) +[ ] Establish emergency contact procedures +[ ] Define acceptable impact levels +[ ] Get sign-off from legal/compliance team +[ ] Review and accept terms of service +---- + +==== 2. Scope Limitation + +[source,lisp] +---- +;; Example: Limit testing to specific endpoint +(let ((target-config + (list (tuple 'type 'http) + (tuple 'url "http://test.example.com/authorized-test-endpoint") + ;; NOT: http://example.com/* (too broad) + ))) + (sbf:run pattern-config target-config)) +---- + +==== 3. Rate Limiting + +Always configure appropriate rate limits: + +[source,erlang] +---- +%% Conservative rate limiting +{safe_brute_force, [ + {rate_limit, 10}, % Max 10 requests per second + {request_timeout, 5000}, % 5 second timeout + {max_workers, 3} % Limited concurrency +]} +---- + +==== 4. Time Windows + +Conduct testing during agreed-upon windows: + +[source,bash] +---- +# Example: Only test between 2-4 AM +# Use cron or manual scheduling +0 2 * * * /path/to/sbf_cli wordlist passwords.txt http://test.example.com +---- + +==== 5. Monitoring and Logging + +Maintain comprehensive logs: + +[source,lisp] +---- +;; Enable detailed logging +(sbf_logger:set_level 'info) + +;; Log to file +(sbf_logger:log_to_file "logs/test-session-2025-01-15.log" + "Starting authorized test") +---- + +=== Technical Security Measures + +==== Defense Against Misuse + +===== 1. Mandatory Safety Pause + +The built-in safety pause cannot be disabled in production: + +[source,erlang] +---- +%% This setting should ALWAYS be true in production +{safety_enabled, true} +---- + +===== 2. Authorization Verification + +The CLI includes authorization checks: + +[source,bash] +---- +$ ./sbf_cli wordlist passwords.txt http://example.com +⚠️ AUTHORIZATION CHECK ⚠️ +You must have written authorization to test this system. +Do you have authorization to test this system? (yes/no): +---- + +===== 3. User Agent Identification + +HTTP requests identify themselves: + +[source,erlang] +---- +%% Default User-Agent header +{"User-Agent", "SafeBruteForce/0.1.0 (Authorized Testing)"} +---- + +This allows system administrators to: - Identify brute-force attempts - +Distinguish authorized tests from attacks - Apply appropriate rate +limiting + +==== Protecting Your Own Systems + +If you’re a system administrator, protect against brute-force attacks: + +===== 1. Rate Limiting + +[source,nginx] +---- +# Nginx example +limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m; + +location /login { + limit_req zone=login burst=3 nodelay; +} +---- + +===== 2. Account Lockout + +[source,python] +---- +# Example: Lock account after 5 failed attempts +failed_attempts = get_failed_attempts(username) +if failed_attempts >= 5: + lock_account(username, duration=timedelta(minutes=15)) +---- + +===== 3. CAPTCHA + +Implement CAPTCHA after multiple failures: + +[source,javascript] +---- +if (failedAttempts >= 3) { + requireCaptcha = true; +} +---- + +===== 4. Multi-Factor Authentication + +Require MFA for sensitive accounts: - Time-based OTP (TOTP) - SMS +verification - Hardware tokens (YubiKey, etc.) + +===== 5. Monitoring and Alerting + +[source,python] +---- +# Alert on suspicious patterns +if (failed_attempts > 10 and time_window < 60): + send_alert("Possible brute-force attack detected") +---- + +=== Data Protection + +==== 1. Credential Storage + +*NEVER store discovered credentials in plain text:* + +[source,lisp] +---- +;; BAD: Don't do this +(defun save_found_password (password) + (file:write_file "found_passwords.txt" password)) + +;; GOOD: Use secure reporting +(defun report_vulnerability (pattern metadata) + (let ((report (map 'timestamp (erlang:system_time 'second) + 'pattern_type "redacted" + 'metadata metadata))) + (sbf_logger:log 'success "Vulnerability confirmed" report))) +---- + +==== 2. Result Handling + +[source,lisp] +---- +;; Filter sensitive data from logs +(defun sanitize_results (results) + (lists:map + (lambda ((tuple pattern result data)) + (tuple "***REDACTED***" result (map 'success 'true))) + results)) +---- + +==== 3. Checkpoint Security + +Checkpoints may contain sensitive data: + +[source,bash] +---- +# Protect checkpoint directory +chmod 700 priv/checkpoints + +# Encrypt sensitive checkpoints +gpg -c priv/checkpoints/session_*.checkpoint + +# Delete after use +rm -P priv/checkpoints/*.checkpoint +---- + +=== Incident Response + +==== If You Discover a Vulnerability + +[arabic] +. *Stop testing immediately* upon finding an actual vulnerability +. *Document the finding* without exploiting further +. *Follow responsible disclosure*: +* Contact the system owner privately +* Provide reasonable time to patch (typically 90 days) +* Do not publicly disclose until patched +. *Report through proper channels*: +* security@organization.com +* Bug bounty programs (HackerOne, Bugcrowd) +* CERT/CC for critical infrastructure + +==== If Unauthorized Testing is Detected + +If you accidentally test an unauthorized system: + +[arabic] +. *Stop immediately* +. *Contact the system owner* and explain the mistake +. *Provide logs* if requested +. *Delete all collected data* +. *Document the incident* for your records + +=== Compliance and Governance + +==== Penetration Testing Agreement Template + +[source,markdown] +---- +# Penetration Testing Agreement + +**Client**: [Organization Name] +**Tester**: [Your Name/Company] +**Date**: [YYYY-MM-DD] + +## Scope +- Target Systems: [Specific URLs, IP ranges, applications] +- Testing Methods: Brute-force authentication testing +- Timeframe: [Start Date] to [End Date] +- Authorized Hours: [e.g., 2:00 AM - 4:00 AM UTC] + +## Limitations +- Maximum request rate: [e.g., 10 requests/second] +- Excluded systems: [List any off-limits systems] +- Data restrictions: [e.g., no data exfiltration] + +## Responsibilities +- Tester will: [List obligations] +- Client will: [List obligations] + +## Emergency Contact +- Name: [Contact] +- Phone: [Number] +- Email: [Address] + +**Signatures** +Client: _________________ Date: _______ +Tester: _________________ Date: _______ +---- + +==== Audit Trail + +Maintain comprehensive records: + +[source,lisp] +---- +;; Log all activities +(defun audit_log (action details) + (let ((entry (map 'timestamp (erlang:system_time 'second) + 'action action + 'details details + 'user (whoami)))) + (sbf_logger:log_to_file "audit.log" + (format_audit_entry entry)))) +---- + +=== Ethical Guidelines + +==== The SafeBruteForce Code of Ethics + +[arabic] +. *Authorization First*: Never test without permission +. *Minimize Impact*: Use rate limiting and timeboxing +. *Responsible Disclosure*: Report vulnerabilities privately +. *Data Protection*: Handle discovered credentials securely +. *Continuous Compliance*: Stay updated on laws and regulations +. *Professional Standards*: Follow industry best practices (OWASP, NIST) +. *Transparency*: Clearly identify your testing activity +. *Accountability*: Maintain audit trails and documentation + +=== Resources + +==== Legal and Compliance + +* https://owasp.org/www-project-web-security-testing-guide/[OWASP +Testing Guide] +* https://www.nist.gov/cyberframework[NIST Cybersecurity Framework] +* https://www.iso.org/isoiec-27001-information-security.html[ISO 27001 +Information Security] + +==== Responsible Disclosure + +* https://www.bugcrowd.com/resources/glossary/responsible-disclosure/[Bugcrowd +Disclosure Guidelines] +* https://www.hackerone.com/disclosure-guidelines[HackerOne Disclosure +Guidelines] + +==== Penetration Testing Standards + +* http://www.pentest-standard.org/[PTES (Penetration Testing Execution +Standard)] +* https://www.isecom.org/OSSTMM.3.pdf[OSSTMM (Open Source Security +Testing Methodology Manual)] + +=== Contact + +For security concerns about SafeBruteForce itself: - Email: +security@[your-domain] - PGP Key: [Key ID] - Responsible Disclosure +Policy: [URL] + +''''' + +*Remember: With great power comes great responsibility. Use +SafeBruteForce ethically and legally.* diff --git a/docs/SECURITY.md b/docs/SECURITY.md deleted file mode 100644 index 1d15ba3..0000000 --- a/docs/SECURITY.md +++ /dev/null @@ -1,345 +0,0 @@ - -# Security Best Practices - -## Legal and Ethical Considerations - -### Authorization is Mandatory - -**⚠️ CRITICAL: You must have explicit written authorization before testing any system.** - -SafeBruteForce is designed for: -- ✅ Authorized penetration testing engagements -- ✅ CTF (Capture The Flag) competitions -- ✅ Security research on systems you own -- ✅ Educational demonstrations in controlled environments -- ✅ Password policy validation for your own organization - -SafeBruteForce must NEVER be used for: -- ❌ Unauthorized access to third-party systems -- ❌ Credential stuffing or account takeover attacks -- ❌ Testing systems without written permission -- ❌ Circumventing security controls maliciously -- ❌ Any activity that violates laws or regulations - -### Legal Frameworks - -Be aware of applicable laws: -- **CFAA (USA)**: Computer Fraud and Abuse Act -- **GDPR (EU)**: Data protection regulations -- **DMCA (USA)**: Anti-circumvention provisions -- **Local laws**: Vary by jurisdiction - -**Violation of these laws can result in criminal prosecution and civil liability.** - -## Responsible Testing Practices - -### 1. Documentation and Authorization - -Before starting any test: - -```markdown -[ ] Obtain written authorization from system owner -[ ] Document scope of testing (URLs, accounts, timeframes) -[ ] Establish emergency contact procedures -[ ] Define acceptable impact levels -[ ] Get sign-off from legal/compliance team -[ ] Review and accept terms of service -``` - -### 2. Scope Limitation - -```lisp -;; Example: Limit testing to specific endpoint -(let ((target-config - (list (tuple 'type 'http) - (tuple 'url "http://test.example.com/authorized-test-endpoint") - ;; NOT: http://example.com/* (too broad) - ))) - (sbf:run pattern-config target-config)) -``` - -### 3. Rate Limiting - -Always configure appropriate rate limits: - -```erlang -%% Conservative rate limiting -{safe_brute_force, [ - {rate_limit, 10}, % Max 10 requests per second - {request_timeout, 5000}, % 5 second timeout - {max_workers, 3} % Limited concurrency -]} -``` - -### 4. Time Windows - -Conduct testing during agreed-upon windows: - -```bash -# Example: Only test between 2-4 AM -# Use cron or manual scheduling -0 2 * * * /path/to/sbf_cli wordlist passwords.txt http://test.example.com -``` - -### 5. Monitoring and Logging - -Maintain comprehensive logs: - -```lisp -;; Enable detailed logging -(sbf_logger:set_level 'info) - -;; Log to file -(sbf_logger:log_to_file "logs/test-session-2025-01-15.log" - "Starting authorized test") -``` - -## Technical Security Measures - -### Defense Against Misuse - -#### 1. Mandatory Safety Pause - -The built-in safety pause cannot be disabled in production: - -```erlang -%% This setting should ALWAYS be true in production -{safety_enabled, true} -``` - -#### 2. Authorization Verification - -The CLI includes authorization checks: - -```bash -$ ./sbf_cli wordlist passwords.txt http://example.com -⚠️ AUTHORIZATION CHECK ⚠️ -You must have written authorization to test this system. -Do you have authorization to test this system? (yes/no): -``` - -#### 3. User Agent Identification - -HTTP requests identify themselves: - -```erlang -%% Default User-Agent header -{"User-Agent", "SafeBruteForce/0.1.0 (Authorized Testing)"} -``` - -This allows system administrators to: -- Identify brute-force attempts -- Distinguish authorized tests from attacks -- Apply appropriate rate limiting - -### Protecting Your Own Systems - -If you're a system administrator, protect against brute-force attacks: - -#### 1. Rate Limiting - -```nginx -# Nginx example -limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m; - -location /login { - limit_req zone=login burst=3 nodelay; -} -``` - -#### 2. Account Lockout - -```python -# Example: Lock account after 5 failed attempts -failed_attempts = get_failed_attempts(username) -if failed_attempts >= 5: - lock_account(username, duration=timedelta(minutes=15)) -``` - -#### 3. CAPTCHA - -Implement CAPTCHA after multiple failures: - -```javascript -if (failedAttempts >= 3) { - requireCaptcha = true; -} -``` - -#### 4. Multi-Factor Authentication - -Require MFA for sensitive accounts: -- Time-based OTP (TOTP) -- SMS verification -- Hardware tokens (YubiKey, etc.) - -#### 5. Monitoring and Alerting - -```python -# Alert on suspicious patterns -if (failed_attempts > 10 and time_window < 60): - send_alert("Possible brute-force attack detected") -``` - -## Data Protection - -### 1. Credential Storage - -**NEVER store discovered credentials in plain text:** - -```lisp -;; BAD: Don't do this -(defun save_found_password (password) - (file:write_file "found_passwords.txt" password)) - -;; GOOD: Use secure reporting -(defun report_vulnerability (pattern metadata) - (let ((report (map 'timestamp (erlang:system_time 'second) - 'pattern_type "redacted" - 'metadata metadata))) - (sbf_logger:log 'success "Vulnerability confirmed" report))) -``` - -### 2. Result Handling - -```lisp -;; Filter sensitive data from logs -(defun sanitize_results (results) - (lists:map - (lambda ((tuple pattern result data)) - (tuple "***REDACTED***" result (map 'success 'true))) - results)) -``` - -### 3. Checkpoint Security - -Checkpoints may contain sensitive data: - -```bash -# Protect checkpoint directory -chmod 700 priv/checkpoints - -# Encrypt sensitive checkpoints -gpg -c priv/checkpoints/session_*.checkpoint - -# Delete after use -rm -P priv/checkpoints/*.checkpoint -``` - -## Incident Response - -### If You Discover a Vulnerability - -1. **Stop testing immediately** upon finding an actual vulnerability -2. **Document the finding** without exploiting further -3. **Follow responsible disclosure**: - - Contact the system owner privately - - Provide reasonable time to patch (typically 90 days) - - Do not publicly disclose until patched -4. **Report through proper channels**: - - security@organization.com - - Bug bounty programs (HackerOne, Bugcrowd) - - CERT/CC for critical infrastructure - -### If Unauthorized Testing is Detected - -If you accidentally test an unauthorized system: - -1. **Stop immediately** -2. **Contact the system owner** and explain the mistake -3. **Provide logs** if requested -4. **Delete all collected data** -5. **Document the incident** for your records - -## Compliance and Governance - -### Penetration Testing Agreement Template - -```markdown -# Penetration Testing Agreement - -**Client**: [Organization Name] -**Tester**: [Your Name/Company] -**Date**: [YYYY-MM-DD] - -## Scope -- Target Systems: [Specific URLs, IP ranges, applications] -- Testing Methods: Brute-force authentication testing -- Timeframe: [Start Date] to [End Date] -- Authorized Hours: [e.g., 2:00 AM - 4:00 AM UTC] - -## Limitations -- Maximum request rate: [e.g., 10 requests/second] -- Excluded systems: [List any off-limits systems] -- Data restrictions: [e.g., no data exfiltration] - -## Responsibilities -- Tester will: [List obligations] -- Client will: [List obligations] - -## Emergency Contact -- Name: [Contact] -- Phone: [Number] -- Email: [Address] - -**Signatures** -Client: _________________ Date: _______ -Tester: _________________ Date: _______ -``` - -### Audit Trail - -Maintain comprehensive records: - -```lisp -;; Log all activities -(defun audit_log (action details) - (let ((entry (map 'timestamp (erlang:system_time 'second) - 'action action - 'details details - 'user (whoami)))) - (sbf_logger:log_to_file "audit.log" - (format_audit_entry entry)))) -``` - -## Ethical Guidelines - -### The SafeBruteForce Code of Ethics - -1. **Authorization First**: Never test without permission -2. **Minimize Impact**: Use rate limiting and timeboxing -3. **Responsible Disclosure**: Report vulnerabilities privately -4. **Data Protection**: Handle discovered credentials securely -5. **Continuous Compliance**: Stay updated on laws and regulations -6. **Professional Standards**: Follow industry best practices (OWASP, NIST) -7. **Transparency**: Clearly identify your testing activity -8. **Accountability**: Maintain audit trails and documentation - -## Resources - -### Legal and Compliance -- [OWASP Testing Guide](https://owasp.org/www-project-web-security-testing-guide/) -- [NIST Cybersecurity Framework](https://www.nist.gov/cyberframework) -- [ISO 27001 Information Security](https://www.iso.org/isoiec-27001-information-security.html) - -### Responsible Disclosure -- [Bugcrowd Disclosure Guidelines](https://www.bugcrowd.com/resources/glossary/responsible-disclosure/) -- [HackerOne Disclosure Guidelines](https://www.hackerone.com/disclosure-guidelines) - -### Penetration Testing Standards -- [PTES (Penetration Testing Execution Standard)](http://www.pentest-standard.org/) -- [OSSTMM (Open Source Security Testing Methodology Manual)](https://www.isecom.org/OSSTMM.3.pdf) - -## Contact - -For security concerns about SafeBruteForce itself: -- Email: security@[your-domain] -- PGP Key: [Key ID] -- Responsible Disclosure Policy: [URL] - ---- - -**Remember: With great power comes great responsibility. Use SafeBruteForce ethically and legally.** diff --git a/docs/TYPE_SAFETY_ROADMAP.adoc b/docs/TYPE_SAFETY_ROADMAP.adoc new file mode 100644 index 0000000..0b614c6 --- /dev/null +++ b/docs/TYPE_SAFETY_ROADMAP.adoc @@ -0,0 +1,68 @@ +== Type Safety Improvement Plan for SafeBruteForce + +=== Current Limitation + +SafeBruteForce is written in LFE (Lisp Flavored Erlang), which is +*dynamically typed*. This means we CANNOT achieve 100% compile-time type +safety like Rust, Ada, or ReScript. + +=== Options to Improve Type Safety + +==== Option 1: Add Dialyzer Specs (Best for LFE) + +Add type specifications to all functions: + +[source,erlang] +---- +%% In .erl files or as comments in .lfe +-spec attempt(pattern :: string(), result :: atom()) -> + {ok, atom(), integer()} | {error, term()}. +---- + +*Achievable*: 80% type coverage *Effort*: Medium (2-3 days) *Benefit*: +Catch type errors during CI/CD + +==== Option 2: Add Gradualizer (Experimental) + +Use Gradualizer for gradual typing: - More sophisticated than Dialyzer - +Still not compile-time guarantees - Experimental for LFE + +*Achievable*: 85% type coverage *Effort*: High (1 week) *Benefit*: +Better type inference + +==== Option 3: Rewrite Critical Modules in Type-Safe Languages + +*ReScript Option:* - Rewrite pattern generation in ReScript - Compile to +JavaScript - Call from Erlang via ports - *Achievable*: 100% type safety +for those modules - *Effort*: Very High (2-3 weeks) + +*Rust Option:* - Rewrite core logic in Rust - Use NIFs (Native +Implemented Functions) - *Achievable*: 100% type safety + memory safety +- *Effort*: Very High (2-3 weeks) + +==== Option 4: Complete Rewrite in Type-Safe Stack + +*iSOS Multi-Language Approach* (from RSR docs): - ReScript for web UI - +Haskell for business logic - Ada/SPARK for safety-critical parts - +Elixir for distributed coordination - WASM for portability + +*Achievable*: 100% type safety *Effort*: Massive (6-8 weeks) *Benefit*: +Perfect RSR compliance + +=== Recommendation + +For LFE project: *Add Dialyzer specs* (Option 1) - Practical and +achievable - Improves from 40% → 80% type coverage - Maintains LFE +codebase - CI/CD catches type errors + +For RSR Gold Level: *Hybrid approach* (Option 3) - Keep LFE for OTP +infrastructure - Add ReScript for pattern generation - Add Rust NIFs for +performance-critical paths - Achieves multi-language verification (iSOS +model) + +''''' + +*Current Status*: 40% (Erlang runtime + pattern matching + guards) *With +Dialyzer*: 80% (static analysis catches most type errors) *With Hybrid*: +95% (type-safe modules + FFI contracts) *Complete Rewrite*: 100% (but +loses existing codebase) diff --git a/docs/TYPE_SAFETY_ROADMAP.md b/docs/TYPE_SAFETY_ROADMAP.md deleted file mode 100644 index f9a9a9d..0000000 --- a/docs/TYPE_SAFETY_ROADMAP.md +++ /dev/null @@ -1,86 +0,0 @@ - -# Type Safety Improvement Plan for SafeBruteForce - -## Current Limitation - -SafeBruteForce is written in LFE (Lisp Flavored Erlang), which is **dynamically typed**. -This means we CANNOT achieve 100% compile-time type safety like Rust, Ada, or ReScript. - -## Options to Improve Type Safety - -### Option 1: Add Dialyzer Specs (Best for LFE) - -Add type specifications to all functions: - -```erlang -%% In .erl files or as comments in .lfe --spec attempt(pattern :: string(), result :: atom()) -> - {ok, atom(), integer()} | {error, term()}. -``` - -**Achievable**: 80% type coverage -**Effort**: Medium (2-3 days) -**Benefit**: Catch type errors during CI/CD - -### Option 2: Add Gradualizer (Experimental) - -Use Gradualizer for gradual typing: -- More sophisticated than Dialyzer -- Still not compile-time guarantees -- Experimental for LFE - -**Achievable**: 85% type coverage -**Effort**: High (1 week) -**Benefit**: Better type inference - -### Option 3: Rewrite Critical Modules in Type-Safe Languages - -**ReScript Option:** -- Rewrite pattern generation in ReScript -- Compile to JavaScript -- Call from Erlang via ports -- **Achievable**: 100% type safety for those modules -- **Effort**: Very High (2-3 weeks) - -**Rust Option:** -- Rewrite core logic in Rust -- Use NIFs (Native Implemented Functions) -- **Achievable**: 100% type safety + memory safety -- **Effort**: Very High (2-3 weeks) - -### Option 4: Complete Rewrite in Type-Safe Stack - -**iSOS Multi-Language Approach** (from RSR docs): -- ReScript for web UI -- Haskell for business logic -- Ada/SPARK for safety-critical parts -- Elixir for distributed coordination -- WASM for portability - -**Achievable**: 100% type safety -**Effort**: Massive (6-8 weeks) -**Benefit**: Perfect RSR compliance - -## Recommendation - -For LFE project: **Add Dialyzer specs** (Option 1) -- Practical and achievable -- Improves from 40% → 80% type coverage -- Maintains LFE codebase -- CI/CD catches type errors - -For RSR Gold Level: **Hybrid approach** (Option 3) -- Keep LFE for OTP infrastructure -- Add ReScript for pattern generation -- Add Rust NIFs for performance-critical paths -- Achieves multi-language verification (iSOS model) - ---- - -**Current Status**: 40% (Erlang runtime + pattern matching + guards) -**With Dialyzer**: 80% (static analysis catches most type errors) -**With Hybrid**: 95% (type-safe modules + FFI contracts) -**Complete Rewrite**: 100% (but loses existing codebase) diff --git a/docs/USAGE.md b/docs/USAGE.adoc similarity index 68% rename from docs/USAGE.md rename to docs/USAGE.adoc index 7811392..c47c239 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.adoc @@ -1,24 +1,22 @@ - -# SafeBruteForce Usage Guide +== SafeBruteForce Usage Guide -## Table of Contents +=== Table of Contents -1. [Installation](#installation) -2. [Quick Start](#quick-start) -3. [Pattern Generation Strategies](#pattern-generation-strategies) -4. [Target Configuration](#target-configuration) -5. [Safety Features](#safety-features) -6. [Checkpoint System](#checkpoint-system) -7. [Advanced Usage](#advanced-usage) +[arabic] +. link:#installation[Installation] +. link:#quick-start[Quick Start] +. link:#pattern-generation-strategies[Pattern Generation Strategies] +. link:#target-configuration[Target Configuration] +. link:#safety-features[Safety Features] +. link:#checkpoint-system[Checkpoint System] +. link:#advanced-usage[Advanced Usage] -## Installation +=== Installation -### Prerequisites +==== Prerequisites -```bash +[source,bash] +---- # Install Erlang/OTP (version 26 or higher) # On Ubuntu/Debian: sudo apt-get install erlang @@ -33,25 +31,28 @@ sudo mv rebar3 /usr/local/bin/ # Install LFE rebar3 new lfe-app myapp -``` +---- -### Build SafeBruteForce +==== Build SafeBruteForce -```bash +[source,bash] +---- git clone https://github.com/Hyperpolymath/safe-brute-force.git cd safe-brute-force rebar3 compile -``` +---- -## Quick Start +=== Quick Start -### Interactive REPL (Recommended) +==== Interactive REPL (Recommended) -```bash +[source,bash] +---- rebar3 lfe repl -``` +---- -```lisp +[source,lisp] +---- ;; Start the application > (sbf:start) @@ -63,11 +64,12 @@ rebar3 lfe repl > (sbf:test_http "http://localhost/login" "admin" "priv/wordlists/common-passwords.txt") -``` +---- -### Command Line Interface +==== Command Line Interface -```bash +[source,bash] +---- # Basic wordlist test ./sbf_cli wordlist priv/wordlists/test-wordlist.txt http://localhost/login admin @@ -76,15 +78,16 @@ rebar3 lfe repl # Charset combinations ./sbf_cli charset "abc" 2 4 http://localhost -``` +---- -## Pattern Generation Strategies +=== Pattern Generation Strategies -### 1. Wordlist Mode +==== 1. Wordlist Mode Load patterns from a text file: -```lisp +[source,lisp] +---- (let ((pattern-config (list (tuple 'type 'wordlist) (tuple 'filename "priv/wordlists/common-passwords.txt"))) @@ -92,59 +95,63 @@ Load patterns from a text file: (list (tuple 'type 'function) (tuple 'function (lambda (p) (== p "target")))))) (sbf:run pattern-config target-config)) -``` +---- -### 2. Wordlist with Mutations +==== 2. Wordlist with Mutations Apply common mutations (leet speak, capitalization, suffixes): -```lisp +[source,lisp] +---- (let ((pattern-config (list (tuple 'type 'wordlist) (tuple 'filename "passwords.txt") (tuple 'mutations 'standard)))) ; or 'minimal or 'aggressive (sbf:run pattern-config target-config)) -``` +---- -Mutation levels: -- **minimal**: Original + Capitalized -- **standard**: + numbers (123, 2024) + leet speak -- **aggressive**: All mutations + reverse + combinations +Mutation levels: - *minimal*: Original + Capitalized - *standard*: + +numbers (123, 2024) + leet speak - *aggressive*: All mutations + reverse ++ combinations -### 3. Charset Combinations +==== 3. Charset Combinations Generate all combinations from a character set: -```lisp +[source,lisp] +---- (let ((pattern-config (list (tuple 'type 'charset) (tuple 'charset "abcdefghijklmnopqrstuvwxyz0123456789") (tuple 'min_length 4) (tuple 'max_length 6)))) (sbf:run pattern-config target-config)) -``` +---- -### 4. Sequential Numbers +==== 4. Sequential Numbers -```lisp +[source,lisp] +---- (let ((pattern-config (list (tuple 'type 'sequential) (tuple 'start 1000) (tuple 'end 9999)))) (sbf:run pattern-config target-config)) -``` +---- -### 5. Common Passwords +==== 5. Common Passwords -```lisp +[source,lisp] +---- (let ((pattern-config (list (tuple 'type 'common)))) (sbf:run pattern-config target-config)) -``` +---- -### 6. Custom Function +==== 6. Custom Function -```lisp +[source,lisp] +---- (let ((pattern-config (list (tuple 'type 'custom) (tuple 'function @@ -152,13 +159,14 @@ Generate all combinations from a character set: ;; Generate custom patterns (list "pattern1" "pattern2" "pattern3")))))) (sbf:run pattern-config target-config)) -``` +---- -## Target Configuration +=== Target Configuration -### HTTP/HTTPS Targets +==== HTTP/HTTPS Targets -```lisp +[source,lisp] +---- (let ((target-config (list (tuple 'type 'http) (tuple 'url "http://example.com/login") @@ -175,11 +183,12 @@ Generate all combinations from a character set: ;; Optional: body format (tuple 'body_format 'json)))) ; or 'urlencoded (default) (sbf:run pattern-config target-config)) -``` +---- -### Custom Function Targets +==== Custom Function Targets -```lisp +[source,lisp] +---- (let ((target-config (list (tuple 'type 'function) (tuple 'function @@ -187,24 +196,26 @@ Generate all combinations from a character set: ;; Your validation logic (== pattern "correct")))))) (sbf:run pattern-config target-config)) -``` +---- -### Mock Targets (Testing) +==== Mock Targets (Testing) -```lisp +[source,lisp] +---- (let ((target-config (list (tuple 'type 'mock) (tuple 'expected "secret123")))) (sbf:run pattern-config target-config)) -``` +---- -## Safety Features +=== Safety Features -### Automatic Pause +==== Automatic Pause SafeBruteForce automatically pauses every 25 attempts (configurable): -```lisp +[source,lisp] +---- ;; The system will pause and display: ╔════════════════════════════════════════════════╗ ║ 🛑 PAUSED - Safety Checkpoint ║ @@ -215,11 +226,12 @@ SafeBruteForce automatically pauses every 25 attempts (configurable): ;; To continue: > (sbf:resume) -``` +---- -### Manual Control +==== Manual Control -```lisp +[source,lisp] +---- ;; Pause at any time > (sbf:pause) @@ -231,99 +243,108 @@ SafeBruteForce automatically pauses every 25 attempts (configurable): ;; Get detailed statistics > (sbf:stats) -``` +---- -### Rate Limiting +==== Rate Limiting Configure requests per second: -```erlang +[source,erlang] +---- %% In config/sys.config {safe_brute_force, [ {rate_limit, 50} % Max 50 requests per second ]} -``` +---- -## Checkpoint System +=== Checkpoint System -### Save Checkpoint +==== Save Checkpoint -```lisp +[source,lisp] +---- ;; Auto-save with default name > (sbf:save_checkpoint) ;; Save with custom name > (sbf:save_checkpoint 'my_session) -``` +---- -### Restore Checkpoint +==== Restore Checkpoint -```lisp +[source,lisp] +---- ;; List available checkpoints > (sbf:list_checkpoints) ;; Restore from checkpoint > (sbf:load_checkpoint "my_session_1234567890_5678") -``` +---- -### Auto-Checkpoint +==== Auto-Checkpoint Checkpoints are automatically saved every 100 attempts (configurable): -```erlang +[source,erlang] +---- %% In config/sys.config {safe_brute_force, [ {checkpoint_interval, 100} ]} -``` +---- -## Advanced Usage +=== Advanced Usage -### Async Execution +==== Async Execution -```lisp +[source,lisp] +---- ;; Run asynchronously > (sbf:run_async pattern-config target-config) #Pid<0.123.0> ;; Check status while running > (sbf:status) -``` +---- -### Progress Tracking +==== Progress Tracking -```lisp +[source,lisp] +---- ;; Get progress with ETA (let ((progress (sbf_progress:new 10000))) ;; ... process items ... (sbf_progress:print progress)) ;; Output: [=========>----------] 45.2% (4520/10000) | 120.5/s | ETA: 45s -``` +---- -### Custom Logging +==== Custom Logging -```lisp +[source,lisp] +---- ;; Set log level (sbf_logger:set_level 'debug) ; 'debug | 'info | 'warning | 'error ;; Log custom messages (sbf_logger:info "Starting custom test") (sbf_logger:success "Pattern found!") -``` +---- -### Result Filtering +==== Result Filtering -```lisp +[source,lisp] +---- ;; After running (let ((stats (sbf:stats))) (let ((successful-patterns (maps:get 'successful_patterns stats))) (io:format "Found: ~p~n" (list successful-patterns)))) -``` +---- -### Custom Pattern Recipes +==== Custom Pattern Recipes -```lisp +[source,lisp] +---- ;; PIN codes (sbf_patterns:pin-codes) ; All 4-digit PINs @@ -332,13 +353,14 @@ Checkpoints are automatically saved every 100 attempts (configurable): ;; Hex colors (sbf_patterns:hex-colors) ; All #RRGGBB colors -``` +---- -## Configuration Reference +=== Configuration Reference -### Environment Variables +==== Environment Variables -```erlang +[source,erlang] +---- {safe_brute_force, [ {pause_interval, 25}, % Pause every N attempts {max_workers, 10}, % Concurrent workers @@ -348,66 +370,71 @@ Checkpoints are automatically saved every 100 attempts (configurable): {checkpoint_dir, "priv/checkpoints"}, {safety_enabled, true} % Enable safety pause ]} -``` +---- -### Disabling Safety (Not Recommended) +==== Disabling Safety (Not Recommended) -```erlang +[source,erlang] +---- %% Only for testing! {safe_brute_force, [ {safety_enabled, false} ]} -``` +---- -## Examples +=== Examples -See the `examples/` directory for complete examples: +See the `+examples/+` directory for complete examples: -- `http_login_test.lfe` - HTTP form authentication -- `pin_code_test.lfe` - PIN code brute-forcing -- `custom_pattern_test.lfe` - Custom pattern generation +* `+http_login_test.lfe+` - HTTP form authentication +* `+pin_code_test.lfe+` - PIN code brute-forcing +* `+custom_pattern_test.lfe+` - Custom pattern generation -## Troubleshooting +=== Troubleshooting -### Application Won't Start +==== Application Won’t Start -```bash +[source,bash] +---- # Check Erlang version erl -version # Rebuild rebar3 clean rebar3 compile -``` +---- -### Rate Limiting Too Aggressive +==== Rate Limiting Too Aggressive -```erlang +[source,erlang] +---- % Adjust in config/sys.config {rate_limit, 0} % Disable rate limiting (use with caution!) -``` +---- -### Checkpoints Not Saving +==== Checkpoints Not Saving -```bash +[source,bash] +---- # Ensure directory exists mkdir -p priv/checkpoints chmod 755 priv/checkpoints -``` +---- -## Best Practices +=== Best Practices -1. **Always get authorization** before testing any system -2. **Start with small wordlists** to verify configuration -3. **Use rate limiting** to avoid overwhelming targets -4. **Save checkpoints** for long-running operations -5. **Monitor system resources** during large operations -6. **Review results carefully** using filtering functions -7. **Test on local/mock systems first** +[arabic] +. *Always get authorization* before testing any system +. *Start with small wordlists* to verify configuration +. *Use rate limiting* to avoid overwhelming targets +. *Save checkpoints* for long-running operations +. *Monitor system resources* during large operations +. *Review results carefully* using filtering functions +. *Test on local/mock systems first* -## Getting Help +=== Getting Help -- Read the [README](../README.md) -- Check [CLAUDE.md](../CLAUDE.md) for AI assistant guidance -- Review [Security Best Practices](SECURITY.md) -- Open an issue on GitHub +* Read the link:../README.md[README] +* Check link:../CLAUDE.md[CLAUDE.md] for AI assistant guidance +* Review link:SECURITY.md[Security Best Practices] +* Open an issue on GitHub diff --git a/docs/tech-debt-2026-05-26.adoc b/docs/tech-debt-2026-05-26.adoc new file mode 100644 index 0000000..a96b0ec --- /dev/null +++ b/docs/tech-debt-2026-05-26.adoc @@ -0,0 +1,67 @@ +== Tech-Debt Audit — safe-brute-force — 2026-05-26 + +*Source:* estate-wide automated scan 2026-05-26. *Companion:* +https://github.com/hyperpolymath/standards/tree/main/docs/audits[`+hyperpolymath/standards+` +2026-05-26-estate-*-debt audits]. *Combined severity:* `+LOW+`. + +This file records the _raw findings_ — it does not by itself fix the +debt. Each section ends with a '`Recommended next move`' line; closing +the debt is follow-up work. + +=== 1. Proof debt + +No proof-bearing files (`+*.v+`, `+*.lean+`, `+*.agda+`, `+*.idr+`, +`+*.idr2+`, `+*.fst+`, `+*.dfy+`, `+*.tla+`, `+*.ads+`, `+*.adb+`) found +in this repo. + +*Recommended next move:* none. + +=== 2. Licence debt + +[cols=",",options="header",] +|=== +|Field |Value +|LICENSE file |`+LICENSE+` +|SPDX header |`+MPL-2.0+` +|Manifest licence |`+NONE+` +|Body classifier |`+Palimp-MPL-2.0+` +|Severity |`+ok+` +|=== + +*Recommended next move:* none for licence. + +=== 3. Documentation debt + +[cols=",",options="header",] +|=== +|Field |Value +|README lines |429 +|`+docs/+` files |9 +|`+docs/+` LoC |2914 +|CHANGELOG.md |Y +|CONTRIBUTING.md |Y +|CODE_OF_CONDUCT.md |Y +|SECURITY.md |Y +|Severity |`+LOW+` +|=== + +*Recommended next move:* `+docs/+` has only 9 file(s). Aim for ≥10 +organised docs (architecture, usage, contributing-guide, +troubleshooting, design-decisions). The user’s bar for a +"`heavily-developed and well-organised wiki`" is ≥10 files with topical +organisation. + +=== Cross-references + +* Estate proof-debt audit: +`+hyperpolymath/standards/docs/audits/2026-05-26-estate-proof-debt.md+` +* Estate licence-debt audit: +`+hyperpolymath/standards/docs/audits/2026-05-26-estate-licence-debt.md+` +* Estate documentation-debt audit: +`+hyperpolymath/standards/docs/audits/2026-05-26-estate-documentation-debt.md+` + +''''' + +🤖 Generated by Claude Code estate-wide tech-debt scan (2026-05-26). +This file is informational — closing the debt is follow-up work owned by +the maintainer. diff --git a/docs/tech-debt-2026-05-26.md b/docs/tech-debt-2026-05-26.md deleted file mode 100644 index a6ac8df..0000000 --- a/docs/tech-debt-2026-05-26.md +++ /dev/null @@ -1,54 +0,0 @@ - -# Tech-Debt Audit — safe-brute-force — 2026-05-26 - -**Source:** estate-wide automated scan 2026-05-26. -**Companion:** [`hyperpolymath/standards` 2026-05-26-estate-*-debt audits](https://github.com/hyperpolymath/standards/tree/main/docs/audits). -**Combined severity:** `LOW`. - -This file records the *raw findings* — it does not by itself fix the debt. Each section ends with a 'Recommended next move' line; closing the debt is follow-up work. - -## 1. Proof debt - -No proof-bearing files (`*.v`, `*.lean`, `*.agda`, `*.idr`, `*.idr2`, `*.fst`, `*.dfy`, `*.tla`, `*.ads`, `*.adb`) found in this repo. - -**Recommended next move:** none. - -## 2. Licence debt - -| Field | Value | -|---|---| -| LICENSE file | `LICENSE` | -| SPDX header | `MPL-2.0` | -| Manifest licence | `NONE` | -| Body classifier | `Palimp-MPL-2.0` | -| Severity | `ok` | - -**Recommended next move:** none for licence. - -## 3. Documentation debt - -| Field | Value | -|---|---| -| README lines | 429 | -| `docs/` files | 9 | -| `docs/` LoC | 2914 | -| CHANGELOG.md | Y | -| CONTRIBUTING.md | Y | -| CODE_OF_CONDUCT.md | Y | -| SECURITY.md | Y | -| Severity | `LOW` | - -**Recommended next move:** `docs/` has only 9 file(s). Aim for ≥10 organised docs (architecture, usage, contributing-guide, troubleshooting, design-decisions). The user's bar for a "heavily-developed and well-organised wiki" is ≥10 files with topical organisation. - -## Cross-references - -- Estate proof-debt audit: `hyperpolymath/standards/docs/audits/2026-05-26-estate-proof-debt.md` -- Estate licence-debt audit: `hyperpolymath/standards/docs/audits/2026-05-26-estate-licence-debt.md` -- Estate documentation-debt audit: `hyperpolymath/standards/docs/audits/2026-05-26-estate-documentation-debt.md` - ---- - -🤖 Generated by Claude Code estate-wide tech-debt scan (2026-05-26). This file is informational — closing the debt is follow-up work owned by the maintainer. diff --git a/rescript_modules/README.md b/rescript_modules/README.adoc similarity index 63% rename from rescript_modules/README.md rename to rescript_modules/README.adoc index 9b88929..046b6c8 100644 --- a/rescript_modules/README.md +++ b/rescript_modules/README.adoc @@ -1,42 +1,44 @@ - -# ReScript Pattern Generation Module +== ReScript Pattern Generation Module -This module provides **100% type-safe pattern generation** for SafeBruteForce. +This module provides *100% type-safe pattern generation* for +SafeBruteForce. -## Why ReScript? +=== Why ReScript? -- ✅ **100% compile-time type safety** (no runtime type errors) -- ✅ **Sound type system** (no null, no undefined, exhaustive pattern matching) -- ✅ **Compiles to JavaScript** (easy Erlang/Node.js interop via ports) -- ✅ **Excellent performance** (optimized JS output) -- ✅ **No runtime overhead** (types erased at compile time) +* ✅ *100% compile-time type safety* (no runtime type errors) +* ✅ *Sound type system* (no null, no undefined, exhaustive pattern +matching) +* ✅ *Compiles to JavaScript* (easy Erlang/Node.js interop via ports) +* ✅ *Excellent performance* (optimized JS output) +* ✅ *No runtime overhead* (types erased at compile time) -## Type Safety Guarantees +=== Type Safety Guarantees -```rescript +[source,rescript] +---- // This will NOT compile - type error caught at build time: let bad = generateCharsetCombinations(123, "a", "b") // ❌ Type error! // This WILL compile - types are correct: let good = generateCharsetCombinations("abc", 1, 3) // ✅ Type safe! -``` +---- -## Building +=== Building -```bash +[source,bash] +---- cd rescript_modules npm install npm run build -``` +---- -## Usage from Erlang +=== Usage from Erlang -The ReScript module compiles to JavaScript and can be called from Erlang via ports: +The ReScript module compiles to JavaScript and can be called from Erlang +via ports: -```erlang +[source,erlang] +---- %% In Erlang Port = open_port({spawn, "node pattern_generator.js"}, [binary]), port_command(Port, term_to_binary({generate, charset, #{ @@ -49,11 +51,12 @@ receive Patterns = binary_to_term(Binary), io:format("Generated: ~p~n", [Patterns]) end. -``` +---- -## From LFE +=== From LFE -```lisp +[source,lisp] +---- (defun generate-patterns-rescript (type config) "Call ReScript pattern generator via Node.js port" (let* ((port (erlang:open_port @@ -64,31 +67,33 @@ end. (receive ((tuple port (tuple 'data result)) (jsx:decode result))))) -``` +---- -## Type-Safe API +=== Type-Safe API All functions have explicit type signatures: -```rescript +[source,rescript] +---- let generateCharsetCombinations: ( charset, // string int, // min length int, // max length ) => result, generatorError> // Result type -``` +---- -## Benefits for SafeBruteForce +=== Benefits for SafeBruteForce -1. **Pattern Generation**: 100% type-safe implementation -2. **FFI Contracts**: Type-safe boundary with Erlang -3. **Mutation Engine**: Compile-time verified transformations -4. **Validation**: Type-checked pattern validation -5. **iSOS Model**: Demonstrates multi-language verification +[arabic] +. *Pattern Generation*: 100% type-safe implementation +. *FFI Contracts*: Type-safe boundary with Erlang +. *Mutation Engine*: Compile-time verified transformations +. *Validation*: Type-checked pattern validation +. *iSOS Model*: Demonstrates multi-language verification -## Architecture +=== Architecture -``` +.... ┌─────────────────────────────────────┐ │ Erlang/LFE (Dynamic) │ │ - OTP Supervision │ @@ -103,26 +108,26 @@ let generateCharsetCombinations: ( │ - Mutation Engine │ │ - Validation Logic │ └─────────────────────────────────────┘ -``` +.... -## Testing +=== Testing -```bash +[source,bash] +---- # Type check (compile) npm run build # If it compiles, types are correct! # ReScript: "If it compiles, it works" -``` +---- -## RSR Compliance +=== RSR Compliance -This module achieves: -- ✅ **100% Type Safety** (compile-time guarantees) -- ✅ **100% Memory Safety** (JS GC + no unsafe operations) -- ✅ **Offline-First** (no network dependencies) -- ✅ **Reproducible Builds** (deterministic compilation) +This module achieves: - ✅ *100% Type Safety* (compile-time guarantees) +- ✅ *100% Memory Safety* (JS GC + no unsafe operations) - ✅ +*Offline-First* (no network dependencies) - ✅ *Reproducible Builds* +(deterministic compilation) -## License +=== License MIT (same as SafeBruteForce parent project) diff --git a/rust_nif/README.md b/rust_nif/README.adoc similarity index 60% rename from rust_nif/README.md rename to rust_nif/README.adoc index 96bfe26..a3babab 100644 --- a/rust_nif/README.md +++ b/rust_nif/README.adoc @@ -1,32 +1,33 @@ - -# Rust NIF Module for SafeBruteForce +== Rust NIF Module for SafeBruteForce -This module provides **100% type-safe AND memory-safe** high-performance pattern generation using Rust NIFs (Native Implemented Functions). +This module provides *100% type-safe AND memory-safe* high-performance +pattern generation using Rust NIFs (Native Implemented Functions). -## Why Rust? +=== Why Rust? -- ✅ **100% compile-time type safety** (strong static typing) -- ✅ **100% memory safety** (ownership system, no GC needed) -- ✅ **Zero-cost abstractions** (compiled, not interpreted) -- ✅ **Parallel processing** (Rayon for multi-core) -- ✅ **No unsafe blocks** (this entire module is safe Rust) +* ✅ *100% compile-time type safety* (strong static typing) +* ✅ *100% memory safety* (ownership system, no GC needed) +* ✅ *Zero-cost abstractions* (compiled, not interpreted) +* ✅ *Parallel processing* (Rayon for multi-core) +* ✅ *No unsafe blocks* (this entire module is safe Rust) -## Safety Guarantees +=== Safety Guarantees -### Type Safety -```rust +==== Type Safety + +[source,rust] +---- // This will NOT compile - type error: let bad = generate_charset_combinations(123, "a", "b"); // ❌ // This WILL compile - types correct: let good = generate_charset_combinations(&charset, 1, 3); // ✅ -``` +---- + +==== Memory Safety -### Memory Safety -```rust +[source,rust] +---- // NO manual memory management // NO use-after-free // NO buffer overflows @@ -34,21 +35,23 @@ let good = generate_charset_combinations(&charset, 1, 3); // ✅ // NO null pointer dereferences // All guaranteed by Rust compiler! -``` +---- -## Building +=== Building -```bash +[source,bash] +---- cd rust_nif cargo build --release # For Erlang integration # The .so file will be in target/release/ -``` +---- -## Usage from Erlang +=== Usage from Erlang -```erlang +[source,erlang] +---- %% Load the NIF -module(sbf_rust). -export([generate_patterns/3]). @@ -61,11 +64,12 @@ init() -> %% Call Rust function generate_patterns(Charset, MinLen, MaxLen) -> sbf_nif:generate_charset_combinations(Charset, MinLen, MaxLen). -``` +---- -## From LFE +=== From LFE -```lisp +[source,lisp] +---- (defun generate-patterns-rust (charset min-len max-len) "Call Rust NIF for high-performance pattern generation" (sbf_nif:generate_charset_combinations_nif charset min-len max-len)) @@ -74,64 +78,71 @@ generate_patterns(Charset, MinLen, MaxLen) -> (defun generate-sequential-fast (start end) "Parallel sequential generation using Rust" (sbf_nif:generate_sequential_parallel_nif start end)) -``` +---- -## Performance +=== Performance -Rust NIFs are **dramatically faster** than pure Erlang for CPU-intensive work: +Rust NIFs are *dramatically faster* than pure Erlang for CPU-intensive +work: -| Operation | Erlang | Rust NIF | Speedup | -|-----------|--------|----------|---------| -| Generate 10k patterns | 500ms | 50ms | 10x | -| Wordlist mutations | 200ms | 20ms | 10x | -| Parallel processing | N/A | 4-core | 3-4x | +[cols=",,,",options="header",] +|=== +|Operation |Erlang |Rust NIF |Speedup +|Generate 10k patterns |500ms |50ms |10x +|Wordlist mutations |200ms |20ms |10x +|Parallel processing |N/A |4-core |3-4x +|=== -## Type-Safe API +=== Type-Safe API All functions have explicit type signatures: -```rust +[source,rust] +---- pub fn generate_charset_combinations( charset: &Charset, // Validated type min_length: usize, // Cannot be negative max_length: usize, // Cannot be negative ) -> Result, GeneratorError> // Explicit errors -``` +---- -## Memory Safety Features +=== Memory Safety Features -1. **Ownership System**: No manual malloc/free -2. **Borrow Checker**: No use-after-free -3. **Bounds Checking**: No buffer overflows -4. **No Null**: Option instead -5. **Thread Safety**: Send/Sync traits -6. **RAII**: Automatic cleanup +[arabic] +. *Ownership System*: No manual malloc/free +. *Borrow Checker*: No use-after-free +. *Bounds Checking*: No buffer overflows +. *No Null*: Option instead +. *Thread Safety*: Send/Sync traits +. *RAII*: Automatic cleanup -## Parallel Processing +=== Parallel Processing Uses Rayon for multi-core processing: -```rust +[source,rust] +---- // Automatically uses all CPU cores let patterns: Vec = (start..=end) .into_par_iter() // Parallel! .map(|n| n.to_string()) .collect(); -``` +---- -## Zero Unsafe Code +=== Zero Unsafe Code -This entire module contains **ZERO unsafe blocks**: +This entire module contains *ZERO unsafe blocks*: -```rust +[source,rust] +---- // ✅ All safe Rust // ✅ Compiler-verified // ✅ No undefined behavior possible -``` +---- -## Architecture +=== Architecture -``` +.... ┌─────────────────────────────────────┐ │ Erlang/LFE (Dynamic) │ │ - OTP Supervision │ @@ -145,20 +156,19 @@ This entire module contains **ZERO unsafe blocks**: │ - Parallel processing │ │ - Zero-copy where possible │ └─────────────────────────────────────┘ -``` +.... -## RSR Compliance +=== RSR Compliance -This module achieves: -- ✅ **100% Type Safety** (Rust compile-time) -- ✅ **100% Memory Safety** (ownership + borrow checker) -- ✅ **100% Reproducible Builds** (Cargo.lock + deterministic) -- ✅ **Offline-First** (no network dependencies) -- ✅ **Zero Unsafe** (no unsafe blocks) +This module achieves: - ✅ *100% Type Safety* (Rust compile-time) - ✅ +*100% Memory Safety* (ownership + borrow checker) - ✅ *100% +Reproducible Builds* (Cargo.lock + deterministic) - ✅ *Offline-First* +(no network dependencies) - ✅ *Zero Unsafe* (no unsafe blocks) -## Testing +=== Testing -```bash +[source,bash] +---- # Run tests cargo test @@ -167,27 +177,33 @@ cargo tarpaulin # Benchmarks cargo bench -``` +---- + +=== Common Patterns -## Common Patterns +==== Pattern Generation -### Pattern Generation -```rust +[source,rust] +---- let charset = Charset::new("abc").unwrap(); let patterns = generate_charset_combinations(&charset, 2, 3)?; -``` +---- -### Mutations -```rust +==== Mutations + +[source,rust] +---- let mutated = apply_mutations("password", MutationLevel::Standard); -``` +---- + +==== Statistics -### Statistics -```rust +[source,rust] +---- let stats = calculate_stats(&patterns); println!("Total: {}, Unique: {}", stats.total_patterns, stats.unique_patterns); -``` +---- -## License +=== License MIT (same as SafeBruteForce parent project)