Add openssh hardening

This commit is contained in:
mrwho 2026-05-15 00:12:37 +03:00
parent 2c6d0394a1
commit e3eddc2a94
42 changed files with 5783 additions and 6 deletions

View file

@ -6,11 +6,6 @@
# kuber-node01 # kuber-node01
# - 172.20.21.193 # - 172.20.21.193
become: true become: true
vars:
#ansible_ssh_user: root
#ansible_ssh_password: nmklop90
reboot_system: false
hostname: rocky9-template.local.mrwho.ru
roles: roles:
- users - users
- rocky9 - rocky9
@ -19,5 +14,58 @@
- linux_core_dumps_rhel9 - linux_core_dumps_rhel9
- linux_ctrl_alt_del_rhel9 - linux_ctrl_alt_del_rhel9
- linux_dnf_automatic_rhel9 - linux_dnf_automatic_rhel9
# - linux_ssh_hardening_rhel9
- linux_wireless_rhel9 - linux_wireless_rhel9
- openssh
vars:
#ansible_ssh_user: root
#ansible_ssh_password: nmklop90
reboot_system: false
hostname: rocky9-template.local.mrwho.ru
openssh_password_authentication: false
openssh_permit_root_login: "no" # Completely disable root SSH
openssh_challenge_response_auth: false
# Rate limiting and attack mitigation (OpenSSH 9.8+)
openssh_enable_persourcepenalties: true
openssh_persource_authfail_penalty: "10s" # Aggressive penalty
openssh_persource_maxstartups: "5:30:10" # Very restrictive
# Disable all forwarding (prevent lateral movement)
openssh_disable_forwarding_comprehensive: true
openssh_x11_forwarding: false
# Restrict to strongest cryptography only
openssh_ciphers:
- chacha20-poly1305@openssh.com
- aes256-gcm@openssh.com
openssh_kex_algorithms:
- curve25519-sha256
openssh_macs:
- hmac-sha2-512-etm@openssh.com
# Minimum RSA key size
openssh_required_rsa_size: 4096 # Maximum strength (Exceeds NIST/CNSA 3072-bit requirement)
# Aggressive session limits
openssh_max_auth_tries: 2 # (Exceeds PCI DSS 8.3.6 limit of 6)
openssh_login_grace_time: "20s"
openssh_max_sessions: 5
# Aggressive session re-keying
openssh_rekey_limit: "512M 30m"
# Client timeout
openssh_client_alive_interval: 300 # 5 minutes
openssh_client_alive_count_max: 24 # Disconnect after 2 hours idle
# Enhanced forensic logging
# openssh_enable_verbose_logging: true
# openssh_log_level: "VERBOSE"
# openssh_log_verbose_subsystems:
# - "kex.c:*"
# - "key.c:*"
# - "auth*.c:*"
# - "packet.c:*"
# Strict user access control
# openssh_allow_groups:
# - security-admins
# Explicitly deny risky users
openssh_deny_users:
- root
- admin
- test

View file

@ -0,0 +1,71 @@
---
# Ansible-lint configuration
# Uses production profile for highest quality standards
# Profile selection (production is strictest)
profile: production
# Exclude paths
exclude_paths:
- .cache/
- .github/
- collections/
- tests/output/
- '*.md'
- .tox/
- molecule/default/molecule.yml
# Enable specific security-focused rules
enable_list:
- no-log-password # Require no_log for password fields
- risky-file-permissions # Catch overly permissive file modes
- command-instead-of-shell # Prefer command over shell module
- name[casing] # Enforce consistent task naming
- yaml[line-length] # Max line length
- fqcn # Require Fully Qualified Collection Names
- jinja[spacing] # Consistent Jinja2 formatting
# Skip list for rules we explicitly don't need
skip_list:
- role-name[path] # We use namespace in paths (generic/lshw)
- galaxy[no-changelog] # We don't use Galaxy
# Strict mode - warnings become errors
strict: true
# Warn about potential issues
warn_list:
- experimental # Warn about experimental features
- no-changed-when # Tasks should have changed_when
- no-handler # Warn if notify without handler
# Task naming requirements
task_name_prefix: "{stem} | " # Optional prefix for better organization
# Offline mode for CI/CD
offline: false
# Mock modules that may not be available during linting
mock_modules:
- docker_container
- docker_compose
- community.general.docker_compose
# Mock roles for testing
mock_roles:
- community.general
- ansible-role-openssh_server
# Kinds of files to lint
kinds:
- yaml: "**/*.yaml"
- yaml: "**/*.yml"
- playbook: "playbooks/*.yml"
- tasks: "roles/*/tasks/*.yml"
- handlers: "roles/*/handlers/*.yml"
- vars: "roles/*/vars/*.yml"
- vars: "roles/*/defaults/*.yml"
- meta: "roles/*/meta/*.yml"
# Logging
verbosity: 1

40
roles/openssh/.gitignore vendored Normal file
View file

@ -0,0 +1,40 @@
# Ansible
*.retry
.ansible/
ansible.log
# Python
__pycache__/
*.py[cod]
*.pyc
# Testing
.tox/
.pytest_cache/
.cache
htmlcov/
.ruff_cache/
molecule/*/cache/
# IDEs
.vscode/
.idea/
*.swp
*.swo
*~
# OS
.DS_Store
Thumbs.db
# Logs
*.log
# Temporary files
*.tmp
*.temp
*.bak
*.orig
# Build artifacts
*.tar.gz

82
roles/openssh/.yamllint Normal file
View file

@ -0,0 +1,82 @@
---
# yamllint configuration
extends: default
rules:
# Line length - balance readability with long Ansible constructs
line-length:
max: 160
level: warning
allow-non-breakable-words: true
allow-non-breakable-inline-mappings: true
# Indentation - 2 spaces, strict
indentation:
spaces: 2
indent-sequences: true
check-multi-line-strings: false
# Comments - require spacing (ansible-lint compatible)
comments:
min-spaces-from-content: 1 # ansible-lint requires 1
require-starting-space: true
ignore-shebangs: true
comments-indentation: false # ansible-lint requires false
# Truthy values - only true/false allowed (not yes/no)
truthy:
allowed-values: ['true', 'false']
check-keys: true
# Octal values - ansible-lint compatible
octal-values:
forbid-implicit-octal: true # ansible-lint requires true
forbid-explicit-octal: true # ansible-lint requires true
# Brackets - consistent spacing
brackets:
min-spaces-inside: 0
max-spaces-inside: 0
min-spaces-inside-empty: 0
max-spaces-inside-empty: 0
# Braces - consistent spacing
braces:
min-spaces-inside: 0
max-spaces-inside: 1
min-spaces-inside-empty: 0
max-spaces-inside-empty: 0
# Document start - require ---
document-start:
present: true
# Document end - not required
document-end:
present: false
# Empty values - disallow
empty-values:
forbid-in-block-mappings: true
forbid-in-flow-mappings: true
# Key duplicates - error
key-duplicates:
forbid-duplicated-merge-keys: true
# New lines
new-line-at-end-of-file: enable
new-lines:
type: unix
# Trailing spaces
trailing-spaces: enable
# Ignore patterns
ignore: |
.cache/
.tox/
tests/output/
collections/
.github/
molecule/default/molecule.yml

701
roles/openssh/AGENTS.md Normal file
View file

@ -0,0 +1,701 @@
# Agent Instructions: OpenSSH Server Ansible Role
This document provides guidance for AI agents (Claude, etc.) working on this OpenSSH server hardening Ansible role. It captures the principles, methodology, and quality standards established during the development of this project.
## Project Overview
This is a **security-first Ansible role** for hardening OpenSSH server configurations on Debian and Ubuntu systems. It provides:
- **Comprehensive security hardening** with modern cryptography
- **16 compliance frameworks** (PCI DSS, HIPAA, FedRAMP, FISMA, SOC 2, GDPR, ISO 27001+)
- **20+ CVE mitigations** with distribution-specific patch tracking
- **10 supported distributions** (Debian 11-14, Ubuntu 22.04+, Rocky 8-10)
- **Version-aware capability detection** (13 feature flags)
- **Post-quantum cryptography** (ML-KEM) and FIDO2/WebAuthn support
This is a **standalone, independent open source project** that can be composed into other infrastructure management systems.
## Quick Reference for Agents
**Before every task:**
- [ ] Read existing files before editing (`Read` before `Edit`/`Write`)
- [ ] Update docs/docs/CHANGELOG.md for ALL changes
- [ ] Run `yamllint .` and `ansible-lint --profile=production`
**Key commands:**
- Validate YAML: `yamllint .`
- Validate Ansible: `ansible-lint --profile=production`
- Check CVE status: `curl -s https://security-tracker.debian.org/tracker/CVE-YYYY-XXXXX`
**Never do:**
- ❌ Make security claims without verification
- ❌ Break backwards compatibility with Debian Stretch (OpenSSH 7.4p1)
- ❌ Use `yes`/`no` in YAML files (use `true`/`false`)
- ❌ Forget to update docs/CHANGELOG.md
## Development Workflow
### Local Testing Environment
- **Linting**: Use `yamllint .` for YAML validation
- **Best practices**: Use `ansible-lint --profile=production` (strict mode)
- **CVE verification**: Check distribution security trackers before claims
- **Documentation**: Build locally by editing markdown files
### Pre-commit Validation
All changes must pass:
1. `yamllint .` - YAML syntax and style
2. `ansible-lint --profile=production` - Ansible best practices
3. Documentation links verified
4. docs/CHANGELOG.md updated
### File Editing Pattern
```bash
# 1. Read first (REQUIRED)
Read templates/sshd_config.j2
# 2. Make changes with Edit tool
Edit templates/sshd_config.j2
# 3. Validate
yamllint . && ansible-lint --profile=production
# 4. Update docs/CHANGELOG.md
Edit docs/CHANGELOG.md
```
## Tool Usage Priorities
### Research and Verification
1. **WebFetch**: For official documentation (OpenSSH, NIST, BSI, ANSSI)
2. **WebSearch**: For finding authoritative sources
3. **Bash**: For CVE verification commands (`curl -s https://security-tracker.debian.org/...`)
### File Operations
1. **Read**: ALWAYS read before editing (required by Edit tool)
2. **Edit**: For targeted changes to existing files
3. **Write**: Only for new files (not for modifying existing ones)
4. **Glob**: For finding files matching patterns
### Code Quality
1. **Bash**: Run `yamllint .` and `ansible-lint --profile=production`
2. **Read**: Review validation output
3. **Edit**: Fix issues found by linters
### Documentation Updates
Every code change requires updating:
1. docs/CHANGELOG.md (MANDATORY)
2. Relevant docs/ file (e.g., DISTRIBUTIONS.md, CVE-TRACKING.md)
3. README.md (if features/capabilities change)
4. examples/ (if usage patterns change)
## Core Principles
### 1. Security Through Research, Not Assumptions
**CRITICAL**: Never make claims about security without verification.
- **Always verify CVE patch status** using official security trackers:
- Debian: `https://security-tracker.debian.org/tracker/CVE-XXXX-XXXXX`
- Ubuntu: `https://ubuntu.com/security/CVE-XXXX-XXXXX`
- **Understand vendor backports**: A distribution running OpenSSH 8.4p1 may be protected against vulnerabilities fixed in upstream 9.8p1 due to vendor security patches. NEVER assume vulnerability status based solely on version numbers.
- **Research compliance frameworks thoroughly**: When asked about compliance (PCI DSS, HIPAA, FedRAMP, etc.), fetch official documentation and understand actual requirements, not generic security advice.
- **Cite sources**: Every security claim should reference:
- Official OpenSSH security advisories
- CVE database entries
- Government/industry standards (NSA/CISA, BSI, ANSSI, etc.)
- Distribution security trackers
**Example of correct approach**:
```
❌ WRONG: "Debian Bookworm is vulnerable to CVE-2024-6387"
✅ RIGHT: "Debian Bookworm PATCHED CVE-2024-6387 via 1:9.2p1-2+deb12u3
(verified at https://security-tracker.debian.org/tracker/CVE-2024-6387)"
```
### 2. Version-Aware Capability Detection
This role supports 10 key distributions spanning OpenSSH versions 8.0p1 through 10.2p1+. **Never break older distributions** (even if not officially listed).
**13 Capability Flags** (set in [tasks/main.yml](tasks/main.yml)):
- `openssh_has_disable_forwarding` (7.4+)
- `openssh_has_ca_signature_algorithms` (7.9+)
- `openssh_has_fido2` (8.2+)
- `openssh_has_include` (8.2+)
- `openssh_has_log_verbose` (8.5+)
- `openssh_has_required_rsa_size` (9.3+)
- `openssh_has_persourcepenalties` (9.8+)
- `openssh_has_mlkem` (9.9+)
- `openssh_has_rsa_sha2` (7.2+)
- `openssh_has_modern_kex` (7.4+)
- `openssh_blocks_dsa_ca` (7.9+)
- `openssh_removes_dsa` (9.6+)
- `openssh_dh_disabled_default` (10.0+)
**Implementation pattern** in [templates/sshd_config.j2](templates/sshd_config.j2):
```jinja2
{% if openssh_has_persourcepenalties | default(false) and openssh_enable_persourcepenalties %}
PerSourcePenalties yes
{% endif %}
```
**When adding new features**:
1. Check OpenSSH version requirement in release notes
2. Add capability flag to tasks/main.yml
3. Use conditional logic in templates/sshd_config.j2
4. Test on both old (Debian Stretch 7.4p1) and new (Debian Forky 10.0p1) versions
### 3. Compliance Framework Accuracy
**16 frameworks supported**: PCI DSS 4.0, SOX, SAMA CSF, HIPAA, HITRUST CSF, GDPR, ISO 27017/27018/27037/27040/27701, FedRAMP, FISMA, NERC CIP, NCA ECC, UAE IA, SOC 2
**When working with compliance**:
1. **Research the actual framework requirements**:
- PCI DSS 4.0: Multi-factor auth, 12+ char passwords, session timeout, audit logging
- FedRAMP: FIPS 140-2 compatible crypto, NIST 800-53 controls (AC-17, SC-8, SC-13)
- HIPAA: Encryption in transit (NIST SP 800-52), audit trails, addressable encryption
2. **Document which role features satisfy requirements**:
- Map specific role variables to compliance controls
- Show configuration examples (see [examples/](examples/) directory)
- Note limitations (e.g., "FIPS 140-2 compatible algorithms, but full compliance requires OS-level FIPS mode")
3. **Link to authoritative sources** in [docs/COMPLIANCE.md](docs/COMPLIANCE.md)
### 4. Documentation Quality Standards
**Documentation is split into focused topics**:
- `README.md` (~150 lines): Quick start, features, navigation
- `docs/DISTRIBUTIONS.md`: Distribution matrix and capability flags
- `docs/COMPLIANCE.md`: All 16 frameworks with requirements mapping
- `docs/CVE-TRACKING.md`: Vulnerability status by distribution
- `docs/CONFIGURATION.md`: Complete variable reference
- `docs/EXAMPLES.md`: Configuration examples
- `docs/TROUBLESHOOTING.md`: Common issues
**Quality standards**:
1. **Use tables for structured data**: Distribution matrices, CVE status, compliance mappings
2. **Provide specific package versions**: "Debian Bookworm 1:9.2p1-2+deb12u3" not "Debian Bookworm is patched"
3. **Include verification commands**: Show users how to check their status
4. **Link between documents**: Cross-reference related topics
5. **Keep README concise**: Link to detailed docs rather than embedding everything
**Bad example**:
```markdown
## Supported Distributions
Debian and Ubuntu are supported.
```
**Good example**:
```markdown
## Supported Distributions
| Distribution | OpenSSH Version | Feature Level | Security Status |
|--------------|-----------------|---------------|-----------------|
| Debian Bookworm | 9.2p1 | ✅ Modern | PATCHED for CVE-2024-6387 via 1:9.2p1-2+deb12u3 |
```
### 5. Testing and Validation
**ALWAYS run validation** before claiming work is complete:
```bash
# YAML syntax
yamllint .
# Ansible best practices (production profile is strict)
ansible-lint --profile=production
# All must pass with 0 failures, 0 warnings
```
**Common validation failures**:
1. **Truthy values**: Use `true`/`false` not `yes`/`no` in YAML, convert in templates
```yaml
# defaults/main.yml
openssh_verify_host_key_dns: false # boolean
# templates/sshd_config.j2
VerifyHostKeyDNS {{ 'yes' if openssh_verify_host_key_dns else 'no' }}
```
2. **Galaxy role naming**: Must include `namespace` in meta/main.yml
```yaml
galaxy_info:
role_name: openssh_server
namespace: agh # REQUIRED
```
3. **Line length**: Keep YAML lines under 160 characters (yamllint rule)
### 6. Cryptographic Preferences
**Algorithm priority order** (Mozilla Modern + OpenSSH 10.0):
1. **Ciphers** (AEAD preferred):
- `chacha20-poly1305@openssh.com` (highest priority)
- `aes256-gcm@openssh.com`, `aes128-gcm@openssh.com` (AEAD)
- `aes256-ctr`, `aes192-ctr`, `aes128-ctr` (fallback for ANSSI/BSI)
2. **Key Exchange**:
- `mlkem768x25519-sha256` (post-quantum, 9.9+ only)
- `curve25519-sha256` (preferred)
- `ecdh-sha2-nistp521/384/256` (NIST curves)
- `diffie-hellman-group16-sha512`, `diffie-hellman-group18-sha512` (4096-bit DH)
3. **MACs**:
- `hmac-sha2-512-etm@openssh.com` (ETM preferred)
- `hmac-sha2-256-etm@openssh.com`
- `umac-128-etm@openssh.com`
**When researching crypto updates**:
- Check OpenSSH release notes (https://www.openssh.com/releasenotes.html)
- Review Mozilla OpenSSH guidelines (https://infosec.mozilla.org/guidelines/openssh)
- Check international guidance (BSI TR-02102-4, ANSSI NT_OpenSSH)
- Understand algorithm lifecycle (deprecated → removed → blocked)
### 7. CVE Tracking Methodology
**When a new CVE is discovered**:
1. **Research official sources**:
- OpenSSH security page: https://www.openssh.com/security.html
- NVD/CVE database entry
- Vendor security advisories (Qualys, etc.)
2. **Check distribution patch status**:
```bash
# Debian
curl -s https://security-tracker.debian.org/tracker/CVE-YYYY-XXXXX
# Ubuntu
curl -s https://ubuntu.com/security/CVE-YYYY-XXXXX
```
3. **Update docs/CVE-TRACKING.md** with:
- CVE number, CVSS score, description
- Upstream affected versions
- Upstream fixed version
- Distribution-specific patch status with package versions
- Mitigation status (Fully Mitigated / Conditionally Mitigated / Open)
- Configuration-based mitigations if any
4. **Update role if needed**:
- Add/update role variables for mitigation
- Add capability flags if version-specific
- Update defaults for secure-by-default
### 8. International Research Standards
**When asked about international security guidance**:
1. **Five Eyes alliance** (English-speaking):
- 🇺🇸 NSA/CISA (https://www.nsa.gov/, https://www.cisa.gov/)
- 🇨🇦 CCCS (https://www.cyber.gc.ca/)
- 🇦🇺 ACSC (https://www.cyber.gov.au/)
- 🇬🇧 NCSC (https://www.ncsc.gov.uk/)
- 🇳🇿 GCSB/NZISM (https://www.gcsb.govt.nz/)
2. **European standards**:
- 🇩🇪 BSI (https://www.bsi.bund.de/) - TR-02102-4 is most comprehensive
- 🇫🇷 ANSSI (https://cyber.gouv.fr/) - NT_OpenSSH
- 🇪🇺 ENISA (defers to member states)
3. **Middle East**:
- 🇸🇦 NCA ECC (Saudi Arabia National Cybersecurity Authority)
- 🇦🇪 UAE IA (UAE Information Assurance)
**Research approach**:
- Use WebFetch to get actual framework documents
- Look for version-dated guidance (e.g., "BSI TR-02102-4 Version 2025-1")
- Check for post-quantum cryptography roadmaps
- Identify algorithm preferences and minimum key sizes
### 9. Error Correction and Fact-Checking
**CRITICAL LESSON**: During this project, we initially made incorrect claims about CVE-2024-6387 vulnerability status.
**Original incorrect claims**:
- ❌ Debian Bookworm vulnerable (WRONG - patched via backport)
- ❌ Ubuntu 22.04 Jammy vulnerable (WRONG - patched via backport)
- ❌ Ubuntu 20.04 Focal vulnerable (WRONG - not affected, version 8.2p1 predates vulnerable code)
**What we learned**:
1. **Always verify against official trackers** before making vulnerability claims
2. **Understand vendor backports** - don't trust version numbers alone
3. **When user questions accuracy, investigate thoroughly** - they may be right
4. **Update documentation when errors discovered** - accuracy > ego
**If you discover an error**:
1. Acknowledge it immediately
2. Research the correct information using official sources
3. Update ALL affected documentation
4. Explain what was wrong and why to help user understand
### 10. Change Management
**CRITICAL: docs/CHANGELOG.md is the source of truth for all changes to this project.**
**Before making ANY changes**:
1. **Read existing files first**: Use Read tool before Edit/Write
2. **Understand the context**: Check related files (defaults, tasks, templates, meta)
3. **Maintain backwards compatibility**: Test that changes work on Debian Stretch 7.4p1
4. **Update docs/CHANGELOG.md**: Document what changed and why (see below)
5. **Run validation**: yamllint + ansible-lint must pass
### 11. Commit Message Standards
**Format**: Follow [Conventional Commits](https://www.conventionalcommits.org/) style:
```
<type>(<scope>): <subject>
<body>
<footer>
```
**Types**:
- `feat`: New feature (triggers CHANGELOG Added section)
- `fix`: Bug fix (triggers CHANGELOG Fixed section)
- `docs`: Documentation only (triggers CHANGELOG Changed section)
- `security`: Security fix (triggers CHANGELOG Security section)
- `refactor`: Code refactoring (no functional change)
- `test`: Adding/updating tests
- `chore`: Maintenance (deps, tooling)
**Examples**:
```
feat(compliance): Add PCI DSS 4.0 support
- Added openssh_pci_dss_mode variable
- Created examples/pci-dss-4.0.yml playbook
- Updated docs/COMPLIANCE.md with requirement mappings
Addresses PCI DSS 4.0 deadline (March 31, 2025)
```
```
security(cve): Mitigate CVE-2025-26465 by disabling VerifyHostKeyDNS
- Changed default openssh_verify_host_key_dns: false
- Updated docs/CVE-TRACKING.md with vulnerability analysis
- Verified mitigation across all 15 distributions
CVE CVSS: 5.3 (Medium) - DNS spoofing attack vector
```
**Good commit messages**:
- ✅ Reference specific files/components
- ✅ Explain "why" not just "what"
- ✅ Include verification steps taken
- ✅ Link to official sources for security/compliance changes
**Bad commit messages**:
- ❌ "Update docs"
- ❌ "Fix stuff"
- ❌ "WIP"
**docs/CHANGELOG.md Update Requirements**:
Every code change, documentation update, security fix, or feature addition MUST be documented in docs/CHANGELOG.md following [Keep a Changelog](https://keepachangelog.com/) format.
**When to update docs/CHANGELOG.md**: Always. For every session, every change.
**How to update docs/CHANGELOG.md**:
1. **Create an Unreleased section** if one doesn't exist:
```markdown
## [Unreleased]
### Added
### Changed
### Deprecated
### Removed
### Fixed
### Security
```
2. **Choose the correct category**:
- **Added**: New features, capabilities, distributions, compliance frameworks
- **Changed**: Changes to existing functionality, documentation updates
- **Deprecated**: Features marked for removal
- **Removed**: Removed features or support
- **Fixed**: Bug fixes, corrections to documentation
- **Security**: Security-related changes, CVE mitigations
3. **Write clear, actionable entries**:
- ✅ GOOD: "Added support for ML-KEM post-quantum key exchange on OpenSSH 9.9+"
- ✅ GOOD: "Fixed CVE-2025-26465 mitigation by disabling VerifyHostKeyDNS by default"
- ✅ GOOD: "Updated COMPLIANCE.md with PCI DSS 4.0 deadline (March 31, 2025)"
- ❌ BAD: "Updated docs"
- ❌ BAD: "Various fixes"
- ❌ BAD: "Improvements"
4. **Reference specific files/components** when relevant:
- "Updated `docs/CVE-TRACKING.md` with CVE-2024-6387 distribution patch status"
- "Modified `templates/sshd_config.j2` to add PerSourcePenalties support"
5. **Link to issues/PRs** if applicable (future feature when GitHub issues are set up)
**Example CHANGELOG update for this session**:
```markdown
## [Unreleased]
### Changed
- Removed all references to Warden project for standalone release
- Updated terminology from "nation-state level" to "comprehensive" and "sophisticated attacks"
- Simplified license headers to "MIT License" from verbose form
- Enhanced docs/CHANGELOG.md with comprehensive 1.0.0 release summary (210 lines)
### Added
- Created CITATION.cff for academic and professional citation support
- Added detailed statistics section to docs/CHANGELOG.md (569 lines code, 457 lines docs)
- Added Rocky Linux 8 and 9 support including platform-specific sftp paths and package management
```
**Versioning trigger**: When ready to release:
1. Move `[Unreleased]` content to a new version section: `## [X.Y.Z] - YYYY-MM-DD`
2. Update version in `meta/main.yml`
3. Create git tag
4. Leave empty `[Unreleased]` section for future changes
**Making security changes**:
1. **Research first, implement second**: Don't implement based on general knowledge
2. **Check OpenSSH version requirements**: New directives may not work on old versions
3. **Add capability flags**: Use conditional logic for version-specific features
4. **Update documentation**: README, relevant docs/, and examples/
5. **Consider compliance impact**: Does this change affect any of the 16 frameworks?
### 11. Example Playbook Standards
**All examples** in [examples/](examples/) **must**:
1. **Include comprehensive header comments**:
- What the playbook does
- Which compliance framework it satisfies (if applicable)
- Key security features enabled
- Deadlines or important dates (e.g., "PCI DSS 4.0 deadline: March 31, 2025")
2. **Use descriptive variable names**:
- Group related settings with comments
- Explain non-obvious values (e.g., why `openssh_rekey_limit: "512M 30m"`)
3. **Be self-documenting**:
- Comments should explain "why" not just "what"
- Reference compliance requirements (e.g., "# Requirement 8.2.1: Multi-factor authentication")
4. **Be complete and runnable**:
- Specify hosts
- Include `become: true` if needed
- Can be copied and run directly
5. **Reference role correctly**:
- Use `welshwandering.openssh_server` (Galaxy-style full name)
- Not `warden_role_openssh_server` (Warden-specific)
### 12. Professional Development Practices
**This role follows industry best practices**:
1. **Repository structure**:
- Ansible Galaxy-compatible layout
- Separate docs/ directory for topic-based documentation
- examples/ directory with runnable playbooks
- GitHub Actions CI/CD in .github/workflows/
2. **Semantic versioning**: v1.0.0 format (major.minor.patch)
3. **Changelog maintenance**: Keep a Changelog format (keepachangelog.com)
4. **License clarity**: MIT License, properly attributed
5. **Contribution readiness**: Though not yet created, plan for:
- CONTRIBUTING.md (PR process, coding standards)
- CODE_OF_CONDUCT.md
- GitHub issue templates
### 13. Research Methodology
**When asked to research a topic**:
1. **Use WebSearch** for overview and finding authoritative sources
2. **Use WebFetch** to read actual documentation from official sources
3. **Cross-reference multiple sources**: Don't rely on a single article
4. **Prioritize official sources**:
- Government cybersecurity agencies (NSA, BSI, ANSSI)
- OpenSSH project (openssh.com)
- Distribution security trackers (Debian, Ubuntu)
- Standards bodies (NIST, ISO, CIS)
5. **Verify dates**: Standards evolve - check publication/revision dates
**Example research workflow**:
```
User: "Research FedRAMP SSH requirements"
1. WebSearch: "FedRAMP SSH FIPS 140-2 requirements"
→ Find FedRAMP uses NIST SP 800-53 controls
2. WebSearch: "NIST SP 800-53 SSH remote access AC-17 SC-8"
→ Identify specific controls: AC-17, SC-8, SC-13
3. WebFetch: Official FedRAMP documentation
→ Extract baseline requirements (Moderate: 325 controls)
4. Document findings with links to sources
```
### 14. Communication and Clarity
**When working with users**:
1. **Be concise but complete**: Don't over-explain, but provide necessary detail
2. **Use structured formats**: Tables, lists, code blocks for clarity
3. **Provide verification steps**: Show users how to check results
4. **Acknowledge uncertainty**: Say "I'll research that" rather than guessing
5. **Correct mistakes promptly**: If wrong, admit it and fix it
**Formatting standards**:
- Use emoji sparingly (✅ ❌ ⚠️ for status indicators)
- Code blocks with language hints (```yaml, ```bash)
- Tables for comparative data
- Clear section headers with ##
### 15. Testing Philosophy
**This role prioritizes**:
1. **Correctness over speed**: Better to research thoroughly than ship bugs
2. **Backwards compatibility**: Debian Stretch (EOL) should still work
3. **Secure defaults**: Users get security without configuration
4. **Validation before commit**: All code must pass yamllint + ansible-lint
5. **Documentation accuracy**: Every claim must be verifiable
**Molecule testing** (when available):
- Test on multiple distributions (Debian 11/12, Ubuntu 20.04/22.04/24.04)
- Verify capability flags work correctly
- Check that older versions don't break
## Common Tasks
### Adding a New Compliance Framework
1. Research official framework documentation
2. Identify SSH-related requirements
3. Map requirements to role variables
4. Update `docs/COMPLIANCE.md` with new table entry
5. Create example playbook in `examples/` if needed
6. Update README.md feature list
7. **Update docs/CHANGELOG.md** under `[Unreleased]``### Added`
### Adding a New Distribution
1. Check OpenSSH version shipped with distribution
2. Add to distribution tables in `docs/DISTRIBUTIONS.md`
3. Test capability flags work correctly
4. Check CVE patch status for that distribution
5. Update `docs/CVE-TRACKING.md` if needed
6. Add to `meta/main.yml` platforms list
7. Update README.md badges
8. **Update docs/CHANGELOG.md** under `[Unreleased]``### Added`
### Responding to a New CVE
1. Research CVE on openssh.com/security.html and NVD
2. Check all 15 distributions' patch status
3. Determine if role configuration provides mitigation
4. Update `docs/CVE-TRACKING.md` with comprehensive status
5. Update defaults/templates if mitigation needed
6. Create GitHub security advisory if critical
7. **Update docs/CHANGELOG.md** under `[Unreleased]``### Security`
### Updating Cryptographic Standards
1. Check OpenSSH release notes for new algorithms
2. Review Mozilla/NSA/BSI/ANSSI guidance updates
3. Test algorithm availability on Debian Stretch (oldest)
4. Update defaults/main.yml with new preferences
5. Add capability flags if version-specific
6. Update `docs/COMPLIANCE.md` if affects compliance
7. **Update docs/CHANGELOG.md** under `[Unreleased]``### Changed` or `### Security`
## Quality Checklist
Before completing any work, verify:
- [ ] All security claims verified against official sources
- [ ] CVE status checked on distribution security trackers
- [ ] Backwards compatibility maintained (test on Debian Stretch conceptually)
- [ ] Documentation updated (README + relevant docs/)
- [ ] Examples updated if behavior changes
- [ ] **docs/CHANGELOG.md updated with ALL changes** (most important!)
- [ ] CHANGELOG entries are clear, specific, and actionable
- [ ] Changes categorized correctly (Added/Changed/Deprecated/Removed/Fixed/Security)
- [ ] yamllint passes: `yamllint .`
- [ ] ansible-lint passes: `ansible-lint --profile=production`
- [ ] Cross-references between documents are valid
- [ ] All external links work and point to authoritative sources
## Key Expectations from This Session
Based on our work together on this project, here are the established patterns and expectations:
### Language and Terminology
1. **No buzzwords**: Avoid "enterprise-grade", "enterprise-level", "nation-state level", "Advanced Persistent Threats (APTs)"
2. **Use clear, direct language**: "comprehensive", "robust", "sophisticated attacks", "defense-in-depth"
3. **No marketing speak**: Technical accuracy over impressive-sounding claims
### Project Independence
1. **This is a standalone project**: No references to Warden or other parent projects
2. **Can be composed into anything**: Designed to be reusable and independent
3. **Clean attribution**: MIT License, proper copyright headers
4. **Professional citation support**: CITATION.cff included for academic/professional use
### Documentation Standards
1. **docs/CHANGELOG.md is mandatory**: Every change must be documented
2. **Clear, specific entries**: No vague "various fixes" or "improvements"
3. **Proper categorization**: Use Keep a Changelog categories correctly
4. **Reference specific files**: Help future maintainers understand impact
### Quality Over Speed
1. **Research before implementing**: Especially for security claims
2. **Verify CVE status**: Always check official distribution security trackers
3. **Test backwards compatibility**: Debian Stretch (oldest) must still work
4. **Run validation**: yamllint and ansible-lint must pass
### Communication
1. **Be concise but complete**: Don't over-explain, but provide necessary detail
2. **Acknowledge mistakes**: If wrong, admit it and fix it immediately
3. **Show verification steps**: Help users check their own systems
4. **Structure information**: Use tables, lists, code blocks for clarity
## Final Notes
**This role represents security research, not assumptions.**
Every claim about vulnerability status, compliance requirements, or cryptographic preferences is backed by research from authoritative sources. When in doubt, research more. When certain, still verify.
The goal is to provide administrators with a **trustworthy, accurate, and comprehensive** OpenSSH hardening solution that they can deploy with confidence in production environments, including those subject to regulatory compliance.
**Trust is earned through accuracy, not confidence.**
---
*Document created: 2025-10-05*
*Last updated: 2025-10-05*
*Role version: 1.0.0*
*For questions about this role: See docs/ directory or check git commit history*

View file

@ -0,0 +1,31 @@
cff-version: 1.2.0
message: "If you use this Ansible role, please cite it as below."
title: "Ansible Role: OpenSSH Server"
type: software
authors:
- family-names: Howells
given-names: Alex
alias: agh
license: MIT
repository-code: "https://github.com/welshwandering/ansible-role-openssh_server"
url: "https://github.com/welshwandering/ansible-role-openssh_server"
abstract: >-
Comprehensive OpenSSH server hardening for Debian and Ubuntu systems
with support for 16 compliance frameworks, extensive CVE tracking,
and version-aware capability detection. Provides robust security
hardening with modern cryptography including post-quantum support.
keywords:
- ansible
- openssh
- security
- hardening
- compliance
- pci-dss
- hipaa
- fedramp
- ssh
- debian
- ubuntu
- infrastructure-as-code
version: 1.0.0
date-released: "2025-10-05"

21
roles/openssh/LICENSE Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 Gravitino LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

169
roles/openssh/README.md Normal file
View file

@ -0,0 +1,169 @@
# Ansible Role: openssh_server
[![CI](https://img.shields.io/badge/CI-ready-brightgreen)](https://github.com/welshwandering/ansible-role-openssh_server)
[![Debian](https://img.shields.io/badge/Debian-11%20to%2014-A81D33?style=for-the-badge&logo=debian&logoColor=white)](docs/DISTRIBUTIONS.md)
[![Ubuntu](https://img.shields.io/badge/Ubuntu-22.04%20to%2025.10-E95420?style=for-the-badge&logo=ubuntu&logoColor=white)](docs/DISTRIBUTIONS.md)
[![Rocky Linux](https://img.shields.io/badge/Rocky_Linux-8%20to%2010-10B981?style=for-the-badge&logo=rocky-linux&logoColor=white)](docs/DISTRIBUTIONS.md)
[![Fedora](https://img.shields.io/badge/Fedora-43-51A2DA?style=for-the-badge&logo=fedora&logoColor=white)](docs/DISTRIBUTIONS.md)
![Ansible](https://img.shields.io/badge/Ansible-EE0000?style=for-the-badge&logo=ansible&logoColor=white)
[![License](https://img.shields.io/badge/License-MIT-blue?style=for-the-badge)](LICENSE)
Comprehensive OpenSSH server hardening for Debian and Ubuntu systems with support for 16 compliance frameworks, extensive CVE tracking, and version-aware capability detection.
## ✨ Features
- 🔒 **Security-First**: Comprehensive hardening with modern cryptography
- 📋 **16 Compliance Frameworks**: PCI DSS, HIPAA, FedRAMP, FISMA, SOC 2, GDPR, ISO 27001+
- 🛡️ **CVE Tracking**: Comprehensive mitigation status for 20+ OpenSSH vulnerabilities
- 🌍 **Supported Distributions**:
- **Debian**: 11 (Bullseye), 12 (Bookworm), 13 (Trixie), 14 (Forky/Testing)
- **Ubuntu**: 22.04 LTS, 24.04 LTS, 25.10
- **Rocky Linux**: 8, 9, 10
- 🔐 **Post-Quantum Ready**: ML-KEM support for OpenSSH 9.9+
- 🔑 **FIDO2/WebAuthn**: Hardware security key authentication
- 📊 **13 Capability Flags**: Automatic feature detection and version-aware configuration
## 🚀 Quick Start
### Installation
Add to your `requirements.yml`:
```yaml
roles:
- src: https://github.com/welshwandering/ansible-role-openssh_server
name: openssh_server
scm: git
```
Then install:
```bash
ansible-galaxy install -r requirements.yml
```
### Basic Usage
```yaml
---
- hosts: all
become: true
roles:
- role: openssh_server
```
### Advanced Configuration
```yaml
---
- hosts: production_servers
become: true
roles:
- role: openssh_server
vars:
# Disable password authentication
openssh_password_authentication: false
# Restrict root login
openssh_permit_root_login: "prohibit-password"
# Enable advanced security features (version-aware)
openssh_enable_persourcepenalties: true
openssh_enable_verbose_logging: true
openssh_required_rsa_size: 3072
# Limit access to specific users
openssh_allow_users:
- deploy
- admin
```
## 📚 Documentation
- **[Distribution Support](docs/DISTRIBUTIONS.md)** - Debian/Ubuntu version matrix and capability flags
- **[Compliance Frameworks](docs/COMPLIANCE.md)** - PCI DSS, HIPAA, FedRAMP, SOC 2, GDPR, ISO 27001+
- **[CVE Tracking](docs/CVE-TRACKING.md)** - Vulnerability status by distribution with patch details
- **[Configuration Reference](docs/CONFIGURATION.md)** - Complete role variables documentation
- **[Examples](docs/EXAMPLES.md)** - Configuration examples for different use cases
- **[Troubleshooting](docs/TROUBLESHOOTING.md)** - Common issues and debugging
## 🔧 Requirements
- **Ansible**: 2.15+
- **Platform**: Debian 9+ or Ubuntu 16.04+
- **Collections**:
- `ansible.posix` >= 1.5.0
- `community.general` >= 8.0.0
## 🔐 Security Features
### Core Security
- ✅ **Key-based authentication only** (password auth disabled by default)
- ✅ **Modern cryptography** (ChaCha20-Poly1305, AES-GCM preferred over AES-CTR)
- ✅ **Strong key exchange** (Curve25519, DH Group 16/18)
- ✅ **Configuration validation** (sshd -t before applying)
- ✅ **Automatic backups** (previous config saved)
- ✅ **Login attempt limits** (MaxAuthTries, LoginGraceTime)
- ✅ **Client keepalive** (prevents hung connections)
- ✅ **Comprehensive logging** (VERBOSE level with optional LogVerbose)
### Advanced Security Features (Version-Aware)
- **OpenSSH 10.0+**: ML-KEM Post-Quantum Cryptography, Enhanced AES-GCM preference
- **OpenSSH 9.8+**: PerSourcePenalties (automatic rate limiting)
- **OpenSSH 9.3+**: RequiredRSASize (enforce 3072-bit RSA minimum)
- **OpenSSH 8.5+**: LogVerbose (enhanced forensic logging)
- **OpenSSH 8.2+**: FIDO2/WebAuthn hardware security key support
- **All Versions**: Session re-keying, certificate authority support, moduli verification
## 🌍 Compliance Support
This role supports compliance with 16 major regulatory frameworks and standards:
**Financial Services**: PCI DSS 4.0, SOX, SAMA CSF
**Healthcare & Privacy**: HIPAA, HITRUST CSF, GDPR
**Cloud Standards**: ISO/IEC 27017, 27018, 27037, 27040, 27701
**Government**: FedRAMP, FISMA, NERC CIP, NCA ECC, UAE IA
**Trust Frameworks**: SOC 2
See [docs/COMPLIANCE.md](docs/COMPLIANCE.md) for detailed compliance mappings.
## 🛡️ CVE Mitigation
The role provides comprehensive protection against 20+ OpenSSH vulnerabilities:
- **CVE-2024-6387** ("regreSSHion"): Patched on all current LTS distributions
- **CVE-2023-48795** (Terrapin Attack): Patched via vendor backports
- **CVE-2023-38408** (PKCS#11 RCE): Patched on all distributions
- **And many more...** See [docs/CVE-TRACKING.md](docs/CVE-TRACKING.md) for complete status
## 📋 Example Playbooks
See the [examples/](examples/) directory for complete playbooks:
- `basic-hardening.yml` - Simple SSH hardening
- `pci-dss-compliance.yml` - PCI DSS 4.0 configuration
- `fedramp.yml` - FedRAMP Moderate & High baseline
- `maximum-security.yml` - Maximum security hardening
- `fido2-hardware-keys.yml` - Security key authentication
## 🤝 Contributing
Contributions are welcome! This role is designed to be community-driven.
Please see [CONTRIBUTING.md](docs/CONTRIBUTING.md) for detailed guidelines on:
- Development workflow and coding standards
- Testing requirements and validation
- Documentation expectations
- Pull request process
- Security contribution guidelines
## 📝 License
MIT License - Copyright (c) 2025 Gravitino LLC
See [LICENSE](LICENSE) for full details.
---

View file

@ -0,0 +1,8 @@
[defaults]
nocows = 1
host_key_checking = False
retry_files_enabled = False
roles_path = ./.cache/roles
inventory = ./molecule/default/inventory
library = ./library
remote_tmp = /tmp/.ansible-${USER}/tmp

View file

@ -0,0 +1,188 @@
---
# Copyright (c) 2025 Gravitino LLC
# MIT License
# OpenSSH Server Configuration with Security Best Practices
# Supported distributions
# Debian: Stretch (9) through Forky (testing)
# Ubuntu LTS: 16.04 (Xenial) through 24.04 (Noble) with ESM support
# Ubuntu Non-LTS: 24.10 (Oracular), 25.04 (Plucky), 25.10 (Questing) - current only
# Note: EOL non-LTS releases (16.10-23.10) are NOT supported
openssh_supported_distributions:
- Debian
- Ubuntu
# Package state
openssh_server_state: present
# Service management
openssh_service_enabled: true
openssh_service_state: started
# Security settings
openssh_permit_root_login: "prohibit-password" # no, prohibit-password, or yes
openssh_password_authentication: false
openssh_pubkey_authentication: true
openssh_permit_empty_passwords: false
openssh_challenge_response_auth: false
# Network settings
openssh_port: 22
openssh_listen_addresses:
- "0.0.0.0"
- "::"
# Protocol and crypto settings (Mozilla Modern Profile + OpenSSH 10.0 Preferences)
# Cipher preference order: AEAD (ChaCha20, AES-GCM) over CTR mode
openssh_protocol: 2
openssh_ciphers:
- chacha20-poly1305@openssh.com # AEAD - highest priority
- aes256-gcm@openssh.com # AEAD - preferred in OpenSSH 10.0
- aes128-gcm@openssh.com # AEAD
- aes256-ctr # Fallback - ANSSI/BSI approved
- aes192-ctr # Fallback
- aes128-ctr # Fallback
openssh_kex_algorithms:
- curve25519-sha256
- curve25519-sha256@libssh.org
- ecdh-sha2-nistp521
- ecdh-sha2-nistp384
- ecdh-sha2-nistp256
- diffie-hellman-group-exchange-sha256
- diffie-hellman-group16-sha512
- diffie-hellman-group18-sha512
openssh_macs:
- hmac-sha2-512-etm@openssh.com
- hmac-sha2-256-etm@openssh.com
- umac-128-etm@openssh.com
- hmac-sha2-512
- hmac-sha2-256
- umac-128@openssh.com
# Host keys
openssh_host_keys:
- /etc/ssh/ssh_host_ed25519_key
- /etc/ssh/ssh_host_rsa_key
# Login settings
openssh_login_grace_time: "30s"
openssh_max_auth_tries: 3
openssh_max_sessions: 10
openssh_max_startups: "10:30:60"
# Logging
openssh_log_level: "VERBOSE" # QUIET, FATAL, ERROR, INFO, VERBOSE, DEBUG
openssh_syslog_facility: "AUTH"
# Additional security
openssh_use_pam: true
openssh_use_dns: false
openssh_x11_forwarding: false
openssh_print_motd: false
openssh_print_last_log: true
openssh_tcp_keep_alive: true
openssh_client_alive_interval: 300
openssh_client_alive_count_max: 2
# Allow/Deny settings (empty by default)
openssh_allow_users: []
openssh_deny_users: []
openssh_allow_groups: []
openssh_deny_groups: []
# Banner
openssh_banner: "none" # Path to banner file or "none"
# Subsystems
# Path is distribution-aware: Ubuntu uses /usr/lib/openssh/, Debian uses /usr/lib/
openssh_subsystems:
- name: sftp
command: >-
{%- if ansible_os_family == 'RedHat' -%}
/usr/libexec/openssh/sftp-server
{%- elif ansible_distribution == 'Ubuntu' -%}
/usr/lib/openssh/sftp-server
{%- else -%}
/usr/lib/sftp-server
{%- endif -%}
# ============================================================================
# Advanced Security Features (Version-Dependent)
# ============================================================================
# PerSourcePenalties - Automatic rate limiting (OpenSSH 9.8+)
# Automatically enabled if supported by detected OpenSSH version
openssh_enable_persourcepenalties: true
openssh_persource_authfail_penalty: "5s" # Penalty for auth failures
openssh_persource_noauth_penalty: "1s" # Penalty for connections without auth
openssh_persource_crash_penalty: "90s" # Penalty for crashes
openssh_persource_maxstartups: "10:30:60" # Per-source connection limits
openssh_persource_netblock_ipv4: 32 # IPv4 netblock size for penalties
openssh_persource_netblock_ipv6: 128 # IPv6 netblock size for penalties
# ML-KEM Post-Quantum Key Exchange (OpenSSH 9.9+)
# Automatically prepended to KEX list if supported
openssh_enable_mlkem: true
# RequiredRSASize - Minimum RSA key size (OpenSSH 9.3+, NSA/CISA compliant)
openssh_required_rsa_size: 3072
# Enhanced Logging with LogVerbose (OpenSSH 8.5+)
openssh_enable_verbose_logging: true
openssh_log_verbose_subsystems:
- "kex.c:*"
- "key.c:*"
- "auth*.c:*"
# FIDO2/Security Key Support (OpenSSH 8.2+)
# Enable to support hardware security keys like YubiKey
openssh_enable_security_keys: false # Conservative default, opt-in
openssh_pubkey_accepted_key_types:
- sk-ssh-ed25519@openssh.com
- ssh-ed25519
- sk-ecdsa-sha2-nistp256@openssh.com
- rsa-sha2-512
- rsa-sha2-256
openssh_host_key_algorithms:
- sk-ssh-ed25519-cert-v01@openssh.com
- ssh-ed25519-cert-v01@openssh.com
- ssh-ed25519
- rsa-sha2-512
- rsa-sha2-256
# Certificate Authority (CA) Support
# Enable to use SSH certificates for authentication
openssh_enable_ca: false
openssh_trusted_user_ca_keys: [] # List of CA public key file paths
openssh_host_certificate: "" # Path to host certificate file
openssh_ca_signature_algorithms:
- sk-ssh-ed25519@openssh.com
- ssh-ed25519
- rsa-sha2-512
- rsa-sha2-256
# Additional Hardening (All versions)
openssh_disable_forwarding: false # Set true to disable all forwarding
openssh_disable_forwarding_comprehensive: false # Use DisableForwarding directive (7.4+)
openssh_disable_tcp_forwarding: false # Disable TCP forwarding
openssh_disable_x11_forwarding: true # Already set above, kept for clarity
openssh_disable_agent_forwarding: false # Disable SSH agent forwarding
openssh_disable_tunneling: false # Disable tunnel device forwarding
openssh_disable_stream_local_forwarding: false # Disable Unix domain socket forwarding
# Session Re-keying (CCCS ITSP.40.062 Requirement)
# Format: data_limit time_limit (e.g., "1G 1h" = 1GB or 1 hour, whichever comes first)
openssh_rekey_limit: "1G 1h"
# Host Key DNS Verification (CVE-2025-26465 mitigation)
openssh_verify_host_key_dns: false # Disabled by default due to security vulnerability
# Security validation and verification
openssh_verify_moduli: true # Verify DH moduli are 3072-bit minimum
openssh_verify_host_keys: true # Validate host key strengths
# Host key permissions
openssh_hostkey_permissions: "0600"
openssh_hostkey_owner: root
openssh_hostkey_group: root

View file

@ -0,0 +1,224 @@
# Acknowledgements
This OpenSSH server hardening role stands on the shoulders of giants. We are deeply grateful to the projects, organizations, and individuals whose work made this role possible.
## Core Technologies
### OpenSSH Project
**[OpenSSH](https://www.openssh.com/)** - The foundation of secure remote access.
- **Project**: OpenBSD SSH - Open-source SSH protocol implementation
- **Maintained by**: The OpenBSD Project and global contributors
- **Since**: 1999 (25+ years of security excellence)
- **Impact**: Powers secure communication for millions of systems worldwide
- **License**: BSD License
OpenSSH's commitment to security-first development, comprehensive auditing, and rapid vulnerability response sets the standard for secure remote access. This role simply helps administrators configure OpenSSH to maximize its security potential.
**Special recognition**: The OpenSSH team's dedication to publishing detailed security advisories and maintaining backward compatibility across decades of releases enables projects like this to exist.
### Ansible
**[Ansible](https://www.ansible.com/)** - Automation that powers infrastructure as code.
- **Project**: Ansible automation platform
- **Maintained by**: Red Hat and the Ansible community
- **License**: GPL-3.0
- **Impact**: Enables declarative, idempotent infrastructure management
Ansible's elegant YAML-based syntax and extensive module ecosystem make complex security configurations manageable and repeatable. The `ansible.builtin`, `ansible.posix`, and `community.general` collections provide the building blocks for this role.
## Operating System Distributions
### Debian Project
**[Debian](https://www.debian.org/)** - The Universal Operating System.
- **Commitment to stability**: Long-term support releases with security backports
- **Security team**: Proactive vulnerability tracking and rapid patch distribution
- **Impact on this role**: 7 Debian distributions supported (Stretch through Forky)
Debian's security tracker (https://security-tracker.debian.org/) provides transparent, detailed vulnerability status that enables accurate CVE tracking in this role.
### Ubuntu / Canonical
**[Ubuntu](https://ubuntu.com/)** - Linux for human beings.
- **LTS support**: Extended Security Maintenance for critical deployments
- **Security team**: Comprehensive patch backporting and CVE tracking
- **Impact on this role**: 8 Ubuntu distributions supported (16.04 through 25.10)
Ubuntu's commitment to long-term support (up to 12 years with ESM) and detailed security bulletins (https://ubuntu.com/security/cves) enables confident deployment across diverse environments.
## Security Research & Standards Organizations
### Government Cybersecurity Agencies
#### United States
- **[NSA](https://www.nsa.gov/)** & **[CISA](https://www.cisa.gov/)**: Network Infrastructure Security Guide (December 2024) - NSA/CISA cryptographic recommendations inform our RSA key size requirements (3072-bit minimum)
- **[NIST](https://csrc.nist.gov/)**: Special Publications (SP 800-207, SP 800-53, SP 800-52) - Zero Trust Architecture and cryptographic standards
#### Canada
- **[CCCS](https://www.cyber.gc.ca/)**: Canadian Centre for Cyber Security - ITSP.40.062 Secure Network Protocols guidance shapes our session re-keying and AEAD cipher preferences
#### Australia
- **[ACSC](https://www.cyber.gov.au/)**: Australian Cyber Security Centre - Communications infrastructure hardening guidance (Five Eyes collaboration)
#### United Kingdom
- **[NCSC](https://www.ncsc.gov.uk/)**: National Cyber Security Centre - Secure system administration principles
#### New Zealand
- **[GCSB](https://www.gcsb.govt.nz/)**: Government Communications Security Bureau - NZISM v3.9 information security controls
#### Germany
- **[BSI](https://www.bsi.bund.de/)**: Bundesamt für Sicherheit in der Informationstechnik - TR-02102-4 Version 2025-1 provides the most comprehensive cryptographic guidance for SSH, including AES-GCM validity through 2029+
#### France
- **[ANSSI](https://cyber.gouv.fr/)**: Agence nationale de la sécurité des systèmes d'information - NT_OpenSSH technical note and post-quantum cryptography roadmap
### Industry Standards Organizations
- **[Mozilla](https://infosec.mozilla.org/)**: OpenSSH Modern Profile - Our cipher, KEX, and MAC preferences build upon Mozilla's excellent security guidelines
- **[CIS](https://www.cisecurity.org/)**: Center for Internet Security - CIS Benchmarks Section 5.2 SSH hardening
- **[OWASP](https://owasp.org/)**: Open Web Application Security Project - General security principles
## Compliance & Regulatory Frameworks
This role supports 16 compliance frameworks. We acknowledge the organizations that maintain these standards:
### Financial Services
- **[PCI Security Standards Council](https://www.pcisecuritystandards.org/)**: PCI DSS 4.0
- **[U.S. Congress](https://www.congress.gov/)**: Sarbanes-Oxley Act (SOX)
- **[SAMA](https://www.sama.gov.sa/)**: Saudi Arabian Monetary Authority - Cyber Security Framework
### Healthcare & Privacy
- **[U.S. Department of Health and Human Services](https://www.hhs.gov/)**: HIPAA regulations
- **[HITRUST Alliance](https://hitrustalliance.net/)**: HITRUST CSF
- **[European Union](https://gdpr.eu/)**: General Data Protection Regulation (GDPR)
### Cloud & Technology
- **[ISO](https://www.iso.org/)**: International Organization for Standardization - ISO/IEC 27017, 27018, 27037, 27040, 27701
### Government & Critical Infrastructure
- **[FedRAMP](https://www.fedramp.gov/)**: Federal Risk and Authorization Management Program
- **[FISMA](https://www.cisa.gov/topics/cyber-threats-and-advisories/federal-information-security-modernization-act)**: Federal Information Security Management Act
- **[NERC](https://www.nerc.com/)**: North American Electric Reliability Corporation - CIP standards
- **[NCA](https://nca.gov.sa/)**: Saudi Arabia National Cybersecurity Authority - Essential Cybersecurity Controls
- **[UAE Government](https://u.ae/)**: UAE Information Assurance framework
### Trust & Assurance
- **[AICPA](https://www.aicpa.org/)**: American Institute of CPAs - SOC 2 Trust Services Criteria
## Research & Documentation Resources
### CVE & Vulnerability Tracking
- **[MITRE CVE Program](https://cve.mitre.org/)**: Common Vulnerabilities and Exposures database
- **[NVD](https://nvd.nist.gov/)**: National Vulnerability Database - NIST's comprehensive CVE analysis
- **[Debian Security Tracker](https://security-tracker.debian.org/)**: Distribution-specific vulnerability status
- **[Ubuntu Security](https://ubuntu.com/security)**: Ubuntu CVE tracking and security bulletins
### Security Research
- **Qualys**: Regular OpenSSH security research and vulnerability discovery
- **Trail of Bits**: Cryptographic engineering and security auditing
- **OpenSSF**: Open Source Security Foundation - Best practices for open source projects
## Development Tools & Infrastructure
### Code Quality
- **[yamllint](https://github.com/adrienverge/yamllint)** by Adrien Vergé - YAML syntax validation
- **[ansible-lint](https://github.com/ansible/ansible-lint)** by Ansible Community - Ansible best practices enforcement
- **[Molecule](https://github.com/ansible-community/molecule)** by Ansible Community - Testing framework for Ansible roles
### Documentation
- **[Keep a Changelog](https://keepachangelog.com/)** by Olivier Lacan - Changelog format standard
- **[Semantic Versioning](https://semver.org/)** by Tom Preston-Werner - Version numbering standard
- **[Citation File Format](https://citation-file-format.github.io/)** - Software citation standard
### Version Control
- **[Git](https://git-scm.com/)** by Linus Torvalds and the Git community
- **[GitHub](https://github.com/)** - Platform for collaboration and open source
## Inspiration & Prior Art
### SSH Hardening Resources
- **[ssh-audit](https://github.com/jtesta/ssh-audit)** by Joe Testa - SSH configuration auditing tool that validates many of the same security principles
- **[Mozilla SSH Guidelines](https://infosec.mozilla.org/guidelines/openssh)** - Foundation for our cryptographic preferences
- **[dev-sec/ansible-ssh-hardening](https://github.com/dev-sec/ansible-ssh-hardening)** - Another excellent SSH hardening role with different design choices
### Community Knowledge
- **Stack Exchange**: Countless sysadmins sharing SSH configuration knowledge
- **Reddit**: r/sysadmin, r/ansible, r/netsec communities
- **Ansible Galaxy**: Community roles that demonstrate best practices
## Special Thanks
### OpenSSH Security Researchers
To the security researchers who responsibly disclose vulnerabilities and help make OpenSSH more secure with each release.
### Distribution Security Teams
To the Debian and Ubuntu security teams who tirelessly backport security patches, enabling older distributions to remain secure without requiring disruptive upgrades.
### Compliance Framework Authors
To the countless security professionals, lawyers, and technical writers who create and maintain compliance frameworks that help organizations implement security systematically.
### Open Source Contributors
To everyone who has ever:
- Reported a bug in OpenSSH or Ansible
- Contributed to security documentation
- Shared knowledge in forums and discussions
- Maintained open source infrastructure
## Contributing to This Project
Want to add your name to this list? See [CONTRIBUTING.md](CONTRIBUTING.md) for how to contribute to this role.
Significant contributors will be recognized here in future releases.
## About This Role
- **Project**: ansible-role-openssh_server
- **Version**: 1.0.0
- **Author**: Gravitino LLC
- **License**: MIT License
- **Repository**: https://github.com/welshwandering/ansible-role-openssh_server
## License & Attribution
This role is released under the MIT License, allowing free use, modification, and distribution. If you use this role in your infrastructure or build upon it for other projects, we appreciate (but do not require) attribution.
See [CITATION.cff](../CITATION.cff) for academic/professional citation format.
---
**"If I have seen further, it is by standing on the shoulders of giants."** - Isaac Newton
This role represents the collective knowledge and expertise of the security community. Thank you to everyone who contributes to making the internet more secure.
---
*Last updated: 2025-10-05*
*If we've missed acknowledging a project or resource, please open an issue or pull request.*

View file

@ -0,0 +1,59 @@
# Authors
This file lists the significant authors and copyright holders of the **ansible-role-openssh_server** project.
## Copyright Holders
### Project Creator and Primary Author
**Gravitino LLC**
- GitHub: [@Gravitino](https://github.com/Gravitino)
- Role: Primary developer and maintainer
- Years: 2025-present
- Copyright: Copyright (c) 2025 Gravitino LLC
## Legal Notice
This project is released under the MIT License. See [LICENSE](../LICENSE) for full license text.
### What Constitutes Significant Authorship
Following GNU project guidelines, this AUTHORS file lists contributors whose work is "legally significant for copyright purposes." This typically means:
- Substantial code contributions (not small bug fixes)
- Major architectural decisions or design work
- Significant documentation contributions
- Long-term maintenance and stewardship
Small contributions, bug reports, minor fixes, and ideas are not listed here but are greatly appreciated. For a complete list of all contributors, see:
- [CONTRIBUTORS.md](CONTRIBUTORS.md) - All contributors to the project
- [Git commit history](https://github.com/welshwandering/ansible-role-openssh_server/commits/main) - Complete contribution record
## Future Authors
As this project grows, additional significant authors will be listed here with their:
- Full name (or preferred attribution)
- GitHub handle
- Years of contribution
- Areas of significant contribution
- Copyright notice (if applicable)
## Adding Yourself as an Author
If you believe your contributions meet the threshold for authorship:
1. Your contributions should be substantial and legally significant for copyright purposes
2. You should have made multiple significant contributions over time
3. Contact the project maintainer to discuss being added as an author
4. Provide your preferred attribution format
We follow the principle that authorship is earned through sustained, substantial contributions to the project.
## Acknowledgments
While not all contributors appear in this AUTHORS file, **everyone who contributes to this project is valued and appreciated**. See [CONTRIBUTORS.md](CONTRIBUTORS.md) for recognition of all project participants.
---
*Last updated: 2025-10-05*

View file

@ -0,0 +1,268 @@
# Changelog
All notable changes to this project 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).
## [Unreleased]
### Fixed
- Removed client-side SSH options from sshd_config template (`VerifyHostKeyDNS` and `UpdateHostKeys`) that were incorrectly included in server configuration
- Fixed Molecule configuration to use relative paths instead of absolute paths for role discovery
- Added `/run/sshd` privilege separation directory creation in Molecule converge playbook
### Added
- **Rocky Linux Support**: Full support for Rocky Linux 8, 9, and 10 with `dnf` package management
- **Fedora Support**: Verified support for Fedora 43 (Cutting Edge)
- **Debian Trixie/Forky**: Verified support for Debian 13 (Stable) and 14 (Testing)
- **Ubuntu 25.10**: Verified support for Ubuntu 25.10 Questing Quokka
- **Docs**: Comprehensive distribution matrix in `docs/DISTRIBUTIONS.md` including point releases
### Changed
- Updated Molecule configuration to use Jeff Geerling's systemd-enabled Docker images (including Rocky 9)
- Highlighted "Ideal" distribution set: Rocky 8-10, Debian 11-14, Ubuntu 22.04+
- Enhanced Molecule verification tests to check systemd service status
- Updated PCI DSS compliance mapping to Version 4.0 with precise requirement citations
- Renamed `examples/fedramp-moderate.yml` to `examples/fedramp.yml` to reflect broader applicability
- Conducted Global Compliance Audit (Jan 2026): Verified alignment with ISO 27001:2022, NERC CIP-005-7, HIPAA Security Rule, and others
- Updated FedRAMP compliance mapping to NIST SP 800-53 **Revision 5** (AC-17, IA-2, AU-2, SC-8, SC-13)
- Explicitly verified support for **FedRAMP High** baseline (when combined with OS-level FIPS)
- Updated `maximum-security.yml` example with annotations where it exceeds PCI DSS and FedRAMP requirements
## [1.0.0] - 2025-10-05
### Overview
Initial release of a comprehensive, standalone OpenSSH server hardening role for Debian and Ubuntu systems. This role provides production-ready SSH configuration with extensive compliance framework support, CVE tracking, and intelligent version detection across 15 distributions spanning 9 years of releases.
**Post-release Documentation Updates:**
- Consolidated security researcher recognition into `docs/CONTRIBUTORS.md` - removed duplicate "Hall of Fame" section from `docs/SECURITY.md` (now references CONTRIBUTORS.md instead)
- Moved `CHANGELOG.md` from repository root to `docs/CHANGELOG.md` for better organization
- Created `.github/CODEOWNERS` file to define code ownership and automatic review assignment
**Testing Infrastructure:**
- Expanded GitHub Actions CI matrix from 5 to 15 distributions covering all supported versions
- Debian: Stretch (9), Buster (10), Bullseye (11), Bookworm (12), Trixie (13), Sid (testing)
- Ubuntu LTS: 16.04 Xenial, 18.04 Bionic, 20.04 Focal, 22.04 Jammy, 24.04 Noble
- Ubuntu Non-LTS: 24.10 Oracular
- Enhanced Molecule configuration with comprehensive verification tests
- Configuration syntax testing with `sshd -t`
- OpenSSH version reporting
- Security hardening verification
- Note: Full systemd service testing requires systemd-enabled Docker images
- Created `docs/TESTING.md` with comprehensive testing guide for contributors
- Created `docs/TESTING_MACOS.md` with macOS-specific testing instructions
- Docker Desktop compatibility documented (Intel and Apple Silicon)
- Performance optimization tips for macOS
- Troubleshooting guide for common macOS issues
- Alternative setup with Colima for lightweight Docker
- Created `docs/TESTING_MACOS_UPDATE.md` documenting current limitations
- Base Docker images lack systemd - requires pre-built systemd images or custom builds for local testing
- CI tests work correctly with base images
- Workarounds provided for macOS local development
- **Successfully validated Molecule tests on macOS with Jeff Geerling's systemd-enabled images**
- Confirmed tests run correctly on macOS with Docker Desktop
- Used `geerlingguy/docker-debian12-ansible:latest` image
- Verified role application, version detection, and capability flag setting
- Tests correctly identified configuration issues (validation working as intended)
### Platform Support
**Distribution Coverage (10 Distributions)**
- **Debian**: Bullseye (11), Bookworm (12), Trixie (13), Forky (14/Testing)
- **Ubuntu LTS**: 22.04 Jammy, 24.04 Noble
- **Ubuntu Non-LTS**: 25.10 Questing
- **Rocky Linux**: 8, 9, 10
- **Previous Support**: Includes support for older Debian/Ubuntu versions (Stretch-Buster, Xenial-Focal) though now legacy
- **OpenSSH Versions**: 7.2p2 through 10.2p1+ with intelligent capability detection
**Version Detection & Compatibility**
- Automatic OpenSSH version detection using `ssh -V`
- 13 capability flags for version-aware feature enablement
- Graceful degradation on older distributions
- Automatic warnings for EOL and ESM-only distributions
- Distribution-aware subsystem paths (Ubuntu vs Debian)
### Security Features
**Core Security Hardening**
- Key-based authentication by default (password auth disabled)
- Root login restricted to `prohibit-password` mode
- Modern cryptography with AEAD cipher preference (ChaCha20-Poly1305, AES-GCM)
- Strong key exchange algorithms (Curve25519, DH Group 16/18)
- Encrypt-then-MAC (ETM) message authentication codes
- Configuration validation with `sshd -t` before applying changes
- Automatic configuration backups on changes
- Comprehensive logging at VERBOSE level
- Login attempt limits (MaxAuthTries, LoginGraceTime)
- Client keepalive to prevent hung connections
- DH moduli verification for 3072-bit minimum strength
**Advanced Features (Version-Aware)**
- **OpenSSH 10.0+**: ML-KEM post-quantum cryptography, enhanced AES-GCM algorithm preferences
- **OpenSSH 9.9+**: ML-KEM768x25519-sha256 hybrid key exchange (quantum-resistant)
- **OpenSSH 9.8+**: PerSourcePenalties automatic rate limiting and attack mitigation
- **OpenSSH 9.3+**: RequiredRSASize enforcement (3072-bit minimum, NSA/CISA compliant)
- **OpenSSH 8.5+**: LogVerbose enhanced forensic logging for specific subsystems
- **OpenSSH 8.2+**: FIDO2/WebAuthn hardware security key authentication support
- **All Versions**: Session re-keying (CCCS ITSP.40.062), certificate authority support
**Cryptographic Standards**
- Mozilla Modern Profile compliant
- OpenSSH 10.0 algorithm preferences
- FIPS 140-2 compatible algorithms (AES, ChaCha20, SHA2)
- 3072-bit RSA minimum (configurable to 4096-bit)
- 3072-bit DH parameters minimum
- Post-quantum ready with ML-KEM support
### Compliance & Regulatory Support
**International Security Standards (9 Organizations)**
- 🇺🇸 NSA/CISA Network Infrastructure Security Guide (Dec 2024)
- 🇺🇸 NIST SP 800-207 Zero Trust Architecture
- 🇺🇸 CIS Benchmarks Section 5.2
- 🇨🇦 CCCS ITSP.40.062 Secure Network Protocols
- 🇦🇺 ACSC Communications Infrastructure Hardening
- 🇬🇧 NCSC Secure System Administration
- 🇳🇿 GCSB NZISM v3.9
- 🇩🇪 BSI TR-02102-4 Version 2025-1
- 🇫🇷 ANSSI NT_OpenSSH
- 🌍 Mozilla OpenSSH Modern Profile
**Industry & Regulatory Frameworks (16 Frameworks)**
- **Financial**: PCI DSS 4.0, SOX, SAMA CSF
- **Healthcare**: HIPAA, HITRUST CSF, GDPR
- **Cloud**: ISO/IEC 27017, 27018, 27037, 27040, 27701
- **Government**: FedRAMP (Moderate/High), FISMA, NERC CIP, NCA ECC, UAE IA
- **Trust**: SOC 2 (Security TSC)
### CVE Vulnerability Protection
**Comprehensive CVE Tracking (20+ Vulnerabilities)**
- Fully mitigated: CVE-2025-26465, CVE-2020-14145, CVE-2016-0777/0778, and more
- Distribution-specific patch status tracking for all major CVEs
- Detailed mitigation status for CVE-2024-6387 ("regreSSHion"), CVE-2023-48795 ("Terrapin"), CVE-2023-38408
- Vendor security backport recognition (patches applied to older OpenSSH versions)
- Per-distribution security recommendations and upgrade paths
- Verification commands for checking patch status
**CVE Mitigation Highlights**
- **CVE-2024-6387** (regreSSHion RCE): All current LTS distributions patched
- **CVE-2023-48795** (Terrapin Attack): All distributions patched including ESM
- **CVE-2023-38408** (PKCS#11 RCE): All distributions patched with additional role protection
- **CVE-2025-26465** (MITM with VerifyHostKeyDNS): Mitigated via secure defaults
- **CVE-2025-26466** (DoS): Partial mitigation via PerSourcePenalties on 9.8+
### Configuration & Flexibility
**180+ Lines of Configurable Variables**
- 70+ role variables with secure defaults
- Comprehensive cipher, KEX, and MAC algorithm configuration
- User and group access control lists (allow/deny)
- Forwarding controls (TCP, X11, agent, tunnel, stream)
- Session management (timeouts, re-keying, keepalive)
- Certificate authority support with trusted CA keys
- FIDO2 security key configuration
- Per-source penalty tuning for rate limiting
- Custom logging subsystem selection
**Template & Task Implementation**
- 166-line Jinja2 template with version-aware conditionals
- 222-line task file with distribution detection and validation
- Automatic feature detection and safe degradation
- Host key strength validation
- Moduli file verification for strong DH groups
### Documentation
**6 Comprehensive Documentation Files (457 lines)**
- **DISTRIBUTIONS.md**: 15-distribution support matrix with OpenSSH versions, feature levels, and capability flags
- **COMPLIANCE.md**: Detailed mappings for 16 compliance frameworks with specific requirement citations
- **CVE-TRACKING.md**: 20+ CVE vulnerability analysis with distribution-specific patch status
- **CONFIGURATION.md**: Complete variable reference with examples
- **EXAMPLES.md**: Quick configuration examples for common scenarios
- **TROUBLESHOOTING.md**: Common issues and debugging steps
**Example Playbooks (5 Scenarios)**
- `basic-hardening.yml`: Simple SSH hardening for general use
- `pci-dss-compliance.yml`: PCI DSS 4.0 compliant configuration (deadline: March 31, 2025)
- `fedramp-moderate.yml`: FedRAMP Moderate baseline with NIST SP 800-53 controls
- `maximum-security.yml`: Maximum security hardening for critical infrastructure
- `fido2-hardware-keys.yml`: Hardware security key authentication (YubiKey, etc.)
**Project Metadata**
- CITATION.cff for academic and professional citation
- MIT License for maximum reusability
- Production-ready ansible-lint and yamllint configurations
- Comprehensive README with quick start, features, and usage
### Testing & Quality
**Code Quality Tools**
- ansible-lint with production profile (strictest settings)
- yamllint with comprehensive rule set
- Molecule testing framework integration
- CI/CD workflow configuration
- FQCN (Fully Qualified Collection Names) throughout
- No deprecated module usage
### Role Architecture
**Ansible Galaxy Compatibility**
- Namespace: `welshwandering`
- Role name: `openssh_server`
- Minimum Ansible version: 2.15+
- Required collections: `ansible.posix` >= 1.5.0, `community.general` >= 8.0.0
- Zero dependencies (fully standalone)
- 14 Galaxy tags for discoverability
### Notable Design Decisions
**Security-First Approach**
- Password authentication disabled by default
- Modern cryptography preferred over legacy compatibility
- Defense-in-depth with multiple security layers
- Comprehensive logging enabled by default
- Safe defaults that work across all supported distributions
**Backwards Compatibility**
- Graceful feature degradation on older distributions
- Automatic capability detection prevents configuration errors
- Support for EOL distributions (with warnings)
- Ubuntu ESM release compatibility (16.04, 18.04)
**Production Readiness**
- Configuration validation before applying changes
- Automatic backup of previous configurations
- Comprehensive error handling
- Clear user feedback with warnings for EOL systems
- Idempotent operations
### Statistics
- **569 lines** of core implementation (tasks, defaults, templates)
- **457 lines** of documentation
- **10 distributions** supported (Debian, Ubuntu, Rocky)
- **16 compliance frameworks** mapped
- **20+ CVEs** tracked and mitigated
- **13 capability flags** for version detection
- **70+ configuration variables**
- **5 example playbooks** for common scenarios
- **9 years** of distribution support (Ubuntu 16.04 through latest)
### Security
- Disabled VerifyHostKeyDNS by default (CVE-2025-26465 mitigation)
- Mozilla Modern Profile cryptography defaults
- OpenSSH 10.0 algorithm preferences
- FIPS 140-2 compatible algorithms
- 3072-bit RSA minimum (configurable to 4096-bit)
- ChaCha20-Poly1305 and AES-GCM AEAD cipher preference
- Curve25519 key exchange preference
- SHA2-512/256 with ETM MAC algorithms
- Agent forwarding disabled by default
- X11 forwarding disabled by default
[1.0.0]: https://github.com/welshwandering/ansible-role-openssh_server/releases/tag/v1.0.0

View file

@ -0,0 +1,250 @@
# Code of Conduct
## Our Pledge
We as contributors, maintainers, and participants pledge to make participation in the **ansible-role-openssh_server** project a welcoming, safe, and equitable experience for everyone.
We are committed to fostering an inclusive community where all people can contribute, regardless of age, body size, disability (visible or invisible), ethnicity, gender identity and expression, level of experience, education, socioeconomic status, nationality, personal appearance, race, religion, sexual identity and orientation, or any other characteristic.
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, and healthy community focused on improving SSH security for everyone.
## Our Standards
### Encouraged Behaviors
We encourage community members to:
- **Respect the community's purpose**: Keep discussions and contributions focused on SSH security, OpenSSH hardening, compliance frameworks, and related topics
- **Engage with kindness and empathy**: Treat all participants with respect and professionalism
- **Accept different viewpoints**: Understand that security professionals come from diverse backgrounds and may have different approaches
- **Take responsibility**: Acknowledge mistakes, apologize to those affected, and learn from the experience
- **Give constructive feedback**: Provide helpful, actionable suggestions backed by authoritative sources
- **Repair harm when possible**: Make amends when you've made a mistake
- **Promote community well-being**: Act in ways that benefit the broader security community
### Unacceptable Behaviors
The following behaviors are not acceptable in our community:
- **Harassment**: Offensive comments, personal attacks, unwelcome sexual attention, or any form of harassment
- **Character attacks**: Trolling, insulting or derogatory comments, and personal or political attacks
- **Stereotyping**: Making assumptions about people based on their identity or characteristics
- **Inappropriate content**: Sexualized language, imagery, or unwelcome advances
- **Privacy violations**: Publishing others' private information (doxxing) without explicit permission
- **Endangerment**: Threats of violence or inciting violence against any individual
- **Dishonesty**: False security claims, unverified CVE status, or intentionally misleading information
- **Malicious contributions**: Submitting intentionally vulnerable configurations or malicious code
- **Disruptive behavior**: Sustained disruption of discussions or deliberately off-topic conversations
## Scope
This Code of Conduct applies in all project spaces, including but not limited to:
- GitHub repository (issues, pull requests, discussions)
- Project documentation and wikis
- Email communications
- Chat platforms (if established)
- In-person or virtual events representing the project
- Social media when representing the project
This code also applies when representing the project in public spaces.
## Enforcement
### Reporting Issues
If you experience or witness unacceptable behavior, please report it promptly to the project maintainers:
**Reporting Methods:**
- **GitHub**: Use the "Report abuse" feature on GitHub
- **Email**: Contact the maintainer directly (see repository for contact information)
- **Private report**: For sensitive situations, request a private discussion
**What to include in your report:**
- Your contact information
- Description of the incident (what happened, when, where)
- Any supporting evidence (links, screenshots with sensitive data removed)
- Whether you'd like to remain anonymous
- Any other relevant context
### Investigation Process
All complaints will be:
1. **Reviewed as time permits**: This is a volunteer-run hobby project, so please be patient
2. **Investigated thoroughly**: We will gather information from all involved parties
3. **Kept confidential**: Reporter privacy will be respected
4. **Handled impartially**: All parties will be treated fairly
5. **Resolved appropriately**: Based on the severity and context of the violation
**Note**: As this is a hobby project maintained by volunteers in their spare time, response times may vary. We appreciate your patience and understanding.
### Enforcement Guidelines
We follow a graduated enforcement approach based on the severity and frequency of violations:
#### 1. Warning (First Offense - Minor)
**Appropriate for**: Unintentional violations, tone issues, minor disruptions
**Response**:
- Private written warning from maintainers
- Explanation of the violation and why it was inappropriate
- Request for apology (if applicable)
- Guidance on expected future behavior
**Impact**: No immediate restrictions, but incident is documented
#### 2. Temporarily Limited Activities (Second Offense or Moderate)
**Appropriate for**: Repeated minor violations, moderate harassment, false security claims
**Response**:
- Temporary restriction from interaction (7-30 days)
- May include:
- Temporary ban from commenting on issues/PRs
- Requirement for all contributions to be reviewed by maintainers
- Prohibition from contacting specific community members
**Impact**: Limited participation for a defined period
#### 3. Temporary Suspension (Serious Offense)
**Appropriate for**: Serious harassment, malicious contributions, pattern of violations
**Response**:
- Temporary ban from all project participation (30-90 days)
- Public statement about the suspension (without identifying details if reporter requests anonymity)
- No interaction with project or community during suspension
- Conditions for reinstatement clearly defined
**Impact**: Complete removal from community for a defined period
#### 4. Permanent Ban (Severe or Repeated Violations)
**Appropriate for**: Severe harassment, threats of violence, intentional security sabotage, repeated violations after warnings
**Response**:
- Permanent ban from all project participation
- Public statement about the ban
- Removal of previous contributions may be considered (in extreme cases)
- Notification to relevant platforms (GitHub, etc.)
**Impact**: Permanent removal from community
### Appeals Process
Anyone subject to enforcement may appeal by:
1. Contacting the maintainers with additional context or information
2. Requesting reconsideration of the decision
Appeals will be reviewed as time permits by uninvolved maintainers (if available) or community advisors.
**Note**: As a hobby project, appeals will be addressed when maintainers have capacity. We appreciate your patience.
## Special Considerations for Security Projects
Because this project focuses on security, we have additional expectations:
### Accuracy and Integrity
- **Verify security claims**: All security-related statements must be backed by authoritative sources
- **Cite sources**: When discussing CVEs, compliance requirements, or cryptographic standards, provide links
- **Admit uncertainty**: If you're not sure about something, say so—guessing about security is dangerous
- **Correct errors promptly**: If you make a mistake about security, acknowledge and correct it immediately
### Responsible Disclosure
- **Report vulnerabilities privately**: Never disclose security vulnerabilities publicly without coordinated disclosure
- **Respect embargo periods**: Honor coordinated disclosure timelines
- **Credit researchers**: Acknowledge those who responsibly report security issues
### Professional Disagreement
Security professionals may have strong opinions about:
- Cryptographic algorithms
- Compliance framework interpretations
- Risk assessment approaches
- Configuration trade-offs
**We expect**:
- Disagreement backed by research and sources
- Respectful debate focused on technical merits
- Willingness to agree to disagree
- Recognition that perfect security doesn't exist—only risk management
## Maintainer Responsibilities
Project maintainers are responsible for:
- Clarifying and enforcing standards of acceptable behavior
- Taking appropriate and fair corrective action in response to violations
- Removing, editing, or rejecting contributions that violate this Code of Conduct
- Communicating reasons for moderation decisions when appropriate
- Leading by example in all community interactions
Maintainers who do not follow or enforce the Code of Conduct may face temporary or permanent consequences.
## Positive Community Building
We encourage behaviors that build a healthy, productive community:
### Knowledge Sharing
- Share research and findings generously
- Help newcomers learn about SSH security
- Document your discoveries for others
- Contribute to improving documentation
### Constructive Feedback
- Focus on the contribution, not the person
- Provide specific, actionable suggestions
- Acknowledge good work when you see it
- Thank contributors for their efforts
### Inclusive Language
- Use inclusive pronouns and language
- Avoid assumptions about technical background
- Welcome questions from all skill levels
- Explain jargon and acronyms
### Recognition
- Credit others' work and ideas
- Acknowledge contributors in pull requests
- Thank people who help you
- Celebrate community achievements
## Attribution
This Code of Conduct is adapted from:
- [Contributor Covenant, version 3.0](https://www.contributor-covenant.org/version/3/0/code_of_conduct/)
- [GitHub's Open Source Guide on Codes of Conduct](https://opensource.guide/code-of-conduct/)
It is tailored specifically for a security-focused open source project with additional considerations for accuracy, responsible disclosure, and professional technical disagreement.
## Questions or Concerns
If you have questions about this Code of Conduct or need clarification:
- Open a discussion on GitHub
- Contact the maintainers privately
- Suggest improvements via pull request
## License
This Code of Conduct is licensed under [Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/).
---
**Remember**: This project exists to help administrators secure SSH servers and protect critical infrastructure. Our community interactions should reflect the same care and professionalism we expect in security work.
**Thank you for helping make this a welcoming, productive, and secure community!**
---
*Last updated: 2025-10-05*
*Code of Conduct Version: 1.0*

View file

@ -0,0 +1,112 @@
# Compliance Frameworks
## International Security Compliance
This role meets or exceeds security requirements from leading international cybersecurity organizations:
| Organization | Standard/Guideline | Compliance Status | Reference |
|--------------|-------------------|-------------------|-----------|
| 🇺🇸 **NSA/CISA** | Network Infrastructure Security Guide (Dec 2024) | ✅ 3072-bit RSA, 4096-bit DH (Group 16) | [NSA.gov](https://www.nsa.gov/) / [CISA.gov](https://www.cisa.gov/) |
| 🇺🇸 **NIST** | SP 800-207 (Zero Trust Architecture) | ✅ Strong authentication, session controls | [NIST SP 800-207](https://csrc.nist.gov/publications/detail/sp/800-207/final) |
| 🇺🇸 **CIS** | Benchmarks Section 5.2 (SSH Configuration) | ✅ SSH hardening best practices | [CIS Benchmarks](https://www.cisecurity.org/cis-benchmarks) |
| 🇨🇦 **CCCS** | ITSP.40.062 (Secure Network Protocols) | ✅ AEAD ciphers, no CBC, session re-keying | [Cyber.gc.ca](https://www.cyber.gc.ca/) |
| 🇦🇺 **ACSC** | Communications Infrastructure Hardening | ✅ SSH v2 only, strong crypto (Five Eyes) | [Cyber.gov.au](https://www.cyber.gov.au/) |
| 🇬🇧 **NCSC** | Secure System Administration | ✅ General admin security principles | [NCSC.gov.uk](https://www.ncsc.gov.uk/) |
| 🇳🇿 **GCSB** | NZISM v3.9 (April 2025) | ✅ Information security controls | [GCSB.govt.nz](https://www.gcsb.govt.nz/) |
| 🇩🇪 **BSI** | TR-02102-4 Version 2025-1 (March 2025) | ✅ AES-GCM, valid to 2029+ | [BSI.bund.de](https://www.bsi.bund.de/EN/Home/home_node.html) |
| 🇫🇷 **ANSSI** | NT_OpenSSH (Post-Quantum Roadmap) | ✅ AES-CTR, SHA2-ETM MACs | [ANSSI Cyber.gouv.fr](https://cyber.gouv.fr/en) |
| 🌍 **Mozilla** | OpenSSH Modern Profile | ✅ Complete algorithm suite | [Mozilla Guidelines](https://infosec.mozilla.org/guidelines/openssh) |
### Cryptographic Standards Met
- **Minimum Key Sizes**: 3072-bit RSA, 256-bit ECDSA (Ed25519), 3072-bit DH parameters
- **Cipher Preference**: AEAD (ChaCha20-Poly1305, AES-GCM) > CTR mode
- **MAC Algorithms**: SHA2-512/256 with ETM (Encrypt-then-MAC)
- **Key Exchange**: Curve25519, NIST P-curves, DH Group 16/18
- **Post-Quantum Ready**: ML-KEM768x25519-sha256 (OpenSSH 9.9+)
## Industry and Regulatory Compliance Frameworks
This role's SSH hardening supports compliance with major industry regulations and frameworks. While these frameworks don't prescribe specific SSH configurations, they mandate secure remote access controls that this role fulfills.
> **Verification**: Mappings verified against latest framework versions as of **January 2026**.
### Financial Services and Payment Card Industry
| Framework | Jurisdiction | SSH Requirements Met | Notes |
|-----------|--------------|---------------------|-------|
| **PCI DSS 4.0** | Global | ✅ **8.4.2**: Multi-factor auth support (public key + passphrase)<br>**4.2.1**: Strong encryption (AES-256, ChaCha20)<br>**8.2.8**: Automatic 15-min idle session timeout<br>**10.2**: Comprehensive audit logging | **Deadline**: March 31, 2025 for full PCI DSS 4.0 compliance<br>**Key Requirements**: 12+ char passwords, MFA for remote access, encrypted transmission |
| **SOX** | 🇺🇸 USA | ✅ Access controls (§404)<br>✅ Change management audit trail<br>✅ Segregation of duties support | **Sarbanes-Oxley Act of 2002**<br>**Focus**: ICFR (Internal Control over Financial Reporting) |
| **SAMA CSF** | 🇸🇦 Saudi Arabia | ✅ Cyber security controls (3.3.1)<br>✅ Strong authentication and encryption | Saudi Arabian Monetary Authority Cyber Security Framework (v1.0+) |
### Healthcare and Privacy
| Framework | Jurisdiction | SSH Requirements Met | Notes |
|-----------|--------------|---------------------|-------|
| **HIPAA Security Rule** | 🇺🇸 USA | ✅ **§ 164.312(a)(1)**: Access Control<br>**§ 164.312(a)(2)(iv)**: Encryption/Decryption<br>**§ 164.312(d)**: Person or Entity Authentication | **Status**: 45 CFR Part 160/162/164<br>Technical Safeguards for ePHI |
| **HITRUST CSF v11+** | Global | ✅ Harmonized controls from 60+ standards<br>✅ ISO 27001/27002 based access controls<br>✅ Encryption at rest and in transit | HITRUST r2 Validated Assessment ready |
| **GDPR** | 🇪🇺 EU | ✅ **Art. 32(1)(a)**: Pseudonymisation and encryption<br>**Art. 32(1)(b)**: Confidentiality and integrity | General Data Protection Regulation (EU) 2016/679 |
### Cloud and Technology Standards
| Framework | Jurisdiction | SSH Requirements Met | Notes |
|-----------|--------------|---------------------|-------|
| **ISO/IEC 27001:2022** | Global | ✅ **A.8.20**: Networks Security<br>**A.8.24**: Use of Cryptography<br>**A.5.15**: Access Control | Verified against 2022 Amendment (Annex A controls renumbered) |
| **ISO/IEC 27017:2015** | Global | ✅ CLD.6.3.1: Shared roles authentication<br>✅ CLD.9.5.1: Segregation in virtual environments | Code of practice for cloud information security controls |
| **ISO/IEC 27018:2019** | Global | ✅ Encryption of PII in transit<br>✅ Breach notification support (logging) | Protection of PII in public clouds |
| **ISO/IEC 27037** | Global | ✅ Digital evidence handling guidelines | Guidelines for digital evidence |
| **ISO/IEC 27040:2024** | Global | ✅ Storage security and encryption | **Updated**: 2024 revision of storage security guidelines |
### Government and Critical Infrastructure
| Framework | Jurisdiction | SSH Requirements Met | Notes |
|-----------|--------------|---------------------|-------|
| **FedRAMP Moderate / High** | 🇺🇸 USA Federal | ✅ FIPS 140-2 validated cryptography<br>✅ NIST SP 800-53 **Rev 5** controls:<br>**AC-17** (Remote Access)<br>**IA-2** (Authentication)<br>**SC-8/13** (Crypto/Transmission)<br>**AU-2** (Audit) | **Baselines**: Moderate (325 controls), High (421 controls)<br>**Cryptographic Protection**: SC-13 mandates FIPS-validated crypto |
| **FISMA** | 🇺🇸 USA Federal | ✅ NIST 800-53 security controls<br>✅ Remote access controls (AC-17)<br>✅ Transmission confidentiality (SC-8) | Federal Information Security Management Act (2014) |
| **NERC CIP-005-7** | 🇺🇸 USA/Canada | ✅ **CIP-005 R2**: Interactive Remote Access Management<br>**CIP-007 R5**: System Security Management<br>✅ MFA & Encryption mandated | Critical Infrastructure Protection (Bulk Electric System) |
| **NCA ECC-1:2018** | 🇸🇦 Saudi Arabia | ✅ **2-3-3**: Remote Access<br>**2-5-1**: Cryptography<br>**2-5-3**: Communications Security | National Cybersecurity Authority Essential Cybersecurity Controls |
| **UAE IA v1.1** | 🇦🇪 UAE | ✅ Access Control & Cryptography<br>✅ Management of Information Security Operations | UAE Information Assurance Regulation |
### Trust and Assurance Frameworks
| Framework | Jurisdiction | SSH Requirements Met | Notes |
|-----------|--------------|---------------------|-------|
| **SOC 2** | Global | ✅ **CC6.1**: Logical Access<br>**CC6.7**: Transmission Security<br>**CC6.8**: Unauthorized Software Prevention | Based on AICPA Trust Services Criteria (2017) |
### Key Compliance Capabilities
This role provides the technical controls needed for compliance across all frameworks:
- FIPS 140-2 compatible algorithms (AES, Triple-DES)
- Modern ciphers (ChaCha20-Poly1305, AES-GCM)
- TLS-equivalent encryption strength
2. **Access Control**
- Public key authentication (default)
- Multi-factor authentication support (key + passphrase)
- User/group allow/deny lists
- Root login restrictions
3. **Audit and Logging**
- Comprehensive session logging (VERBOSE level)
- Enhanced forensic logging (LogVerbose for specific subsystems)
- Failed login attempt tracking
- Change tracking capability
4. **Session Management**
- Automatic session timeout (LoginGraceTime)
- Maximum authentication attempts (MaxAuthTries)
- Session re-keying (RekeyLimit)
- Client keepalive with timeout
5. **Advanced Security Controls**
- Per-source connection limits and penalties (9.8+)
- Required RSA key size enforcement (9.3+)
- Post-quantum cryptography readiness (9.9+)
- Comprehensive forwarding controls
### Compliance Notes
- **FIPS 140-2**: While this role uses FIPS-compatible algorithms, achieving full FIPS 140-2 compliance requires OpenSSH compiled in FIPS mode and FIPS-validated cryptographic modules at the OS level
- **Framework Versions**: Compliance mappings based on current framework versions as of 2025
- **Audit Requirements**: Most frameworks require regular security assessments - this role provides the technical foundation but doesn't replace compliance audits
- **Documentation**: Maintain documentation of SSH configuration decisions for audit purposes

View file

@ -0,0 +1,53 @@
# Configuration Reference
## Role Variables
### Security Settings
```yaml
# Authentication
openssh_permit_root_login: "prohibit-password" # no, prohibit-password, yes
openssh_password_authentication: false # Use key-based auth only
openssh_pubkey_authentication: true
openssh_permit_empty_passwords: false
openssh_challenge_response_auth: false
# Login limits
openssh_max_auth_tries: 3
openssh_login_grace_time: "30s"
```
### Network Configuration
```yaml
openssh_port: 22
openssh_listen_addresses:
- "0.0.0.0"
- "::"
```
### Cryptography (Secure Defaults)
```yaml
openssh_ciphers:
- chacha20-poly1305@openssh.com
- aes256-gcm@openssh.com
- aes128-gcm@openssh.com
openssh_kex_algorithms:
- curve25519-sha256
- diffie-hellman-group16-sha512
openssh_macs:
- hmac-sha2-512-etm@openssh.com
- hmac-sha2-256-etm@openssh.com
```
### Access Control
```yaml
openssh_allow_users: [] # List of allowed users
openssh_deny_users: [] # List of denied users
openssh_allow_groups: [] # List of allowed groups
openssh_deny_groups: [] # List of denied groups
```

View file

@ -0,0 +1,491 @@
# Contributing to ansible-role-openssh_server
**Want to help secure SSH servers across the internet? Awesome!** 🚀
This OpenSSH server hardening role protects systems running critical infrastructure, compliance-regulated workloads, and sensitive data worldwide. Your contributions help administrators deploy secure SSH configurations with confidence.
Whether you're fixing a typo, adding support for a new distribution, tracking a CVE, or implementing a compliance framework—**all contributions matter**.
## Table of Contents
- [Ways to Contribute](#ways-to-contribute)
- [Communication Channels](#communication-channels)
- [Code of Conduct](#code-of-conduct)
- [Getting Started](#getting-started)
- [Development Workflow](#development-workflow)
- [Coding Standards](#coding-standards)
- [Documentation Standards](#documentation-standards)
- [Testing Requirements](#testing-requirements)
- [Pull Request Process](#pull-request-process)
- [Security Contributions](#security-contributions)
- [Recognition](#recognition)
## Ways to Contribute
You don't have to be a security expert to contribute! Here are ways to help:
### 🐛 Report Bugs
Found an issue? Let us know! See [Reporting Bugs](#reporting-bugs).
### 💡 Suggest Features
Have an idea? We'd love to hear it! Open an issue to discuss.
### 📝 Improve Documentation
Fix typos, clarify instructions, add examples—documentation contributions are invaluable.
### 🔐 Track Security Issues
Research CVE status, verify patch levels, update compliance mappings.
### 🧪 Add Distribution Support
Test on new Debian/Ubuntu releases and contribute compatibility updates.
### 🎯 Implement Compliance Frameworks
Map additional regulatory frameworks (ISO, NIST, etc.) to role configuration.
### 💬 Help Others
Answer questions in issues, review PRs, share your experience.
## Communication Channels
- **GitHub Issues**: Bug reports, feature requests, discussions
- **Pull Requests**: Code contributions and reviews
- **Security Issues**: Email maintainer directly (see repository contacts) or use GitHub Security Advisories
**Note**: This is a volunteer-run hobby project. We'll respond as time permits and appreciate your patience.
## Code of Conduct
This project follows a straightforward code of conduct based on mutual respect:
### Our Standards
- **Be respectful**: Treat all contributors with professionalism and courtesy
- **Be constructive**: Provide helpful, actionable feedback
- **Be accurate**: Back security claims with authoritative sources (links required)
- **Be collaborative**: Work together to improve security for everyone
- **Be inclusive**: Welcome contributors of all skill levels and backgrounds
### Not Acceptable
- Harassment, discriminatory language, or personal attacks
- False or unverified security claims
- Intentionally submitting vulnerable configurations
- Spam or off-topic discussions
### Enforcement
- **First offense**: Warning and request to correct behavior
- **Second offense**: Temporary ban from project participation (7-30 days)
- **Third offense**: Permanent ban from project participation
Maintainers will enforce standards fairly and transparently.
## Reporting Bugs
If you find a bug, please open an issue with:
- **Clear description**: What you expected vs. what happened
- **Environment details**: Distribution, OpenSSH version, Ansible version
- **Reproduction steps**: How to reproduce the issue
- **Configuration**: Relevant role variables (sanitize sensitive data)
### Suggesting Enhancements
We welcome suggestions for:
- New compliance framework support
- Additional security features
- Distribution support expansion
- Documentation improvements
- Performance optimizations
Please open an issue to discuss major changes before implementing them.
### Security Vulnerabilities
**DO NOT** open public issues for security vulnerabilities. Instead:
1. Email the maintainer directly (see repository contacts)
2. Use GitHub Security Advisories (if enabled)
3. Provide CVE numbers, affected versions, and proof of concept if available
## Getting Started
### Prerequisites
- Ansible 2.15+
- Python 3.8+
- Git
- yamllint
- ansible-lint
### Fork and Clone
```bash
# Fork the repository on GitHub, then clone your fork
git clone https://github.com/YOUR_USERNAME/ansible-role-openssh_server.git
cd ansible-role-openssh_server
# Add upstream remote
git remote add upstream https://github.com/welshwandering/ansible-role-openssh_server.git
```
### Install Development Tools
```bash
# Install Python dependencies
pip install yamllint ansible-lint ansible
# Install Ansible collections
ansible-galaxy collection install ansible.posix community.general
```
## Development Workflow
### 1. Create a Feature Branch
```bash
# Update your main branch
git checkout main
git pull upstream main
# Create feature branch
git checkout -b feature/your-feature-name
```
### 2. Make Your Changes
Follow the [Coding Standards](#coding-standards) and [Documentation Standards](#documentation-standards) below.
### 3. Test Your Changes
```bash
# Run YAML linting
yamllint .
# Run Ansible linting (production profile is strict)
ansible-lint --profile=production
# Both must pass with 0 failures, 0 warnings
```
### 4. Update Documentation
- Update relevant files in `docs/` directory
- Update `README.md` if adding features
- **REQUIRED**: Update `docs/CHANGELOG.md` (see below)
### 5. Commit Your Changes
```bash
# Stage your changes
git add .
# Commit with clear message
git commit -m "Add support for XYZ feature
- Detailed description of what changed
- Why the change was needed
- Any breaking changes or considerations"
```
### 6. Push and Create Pull Request
```bash
# Push to your fork
git push origin feature/your-feature-name
# Create pull request on GitHub
```
## Coding Standards
### Ansible Best Practices
1. **Use Fully Qualified Collection Names (FQCN)**:
```yaml
# Good
- ansible.builtin.apt:
name: openssh-server
# Bad
- apt:
name: openssh-server
```
2. **Boolean values as true/false**:
```yaml
# defaults/main.yml
openssh_password_authentication: false # boolean
# templates/sshd_config.j2
PasswordAuthentication {{ 'yes' if openssh_password_authentication else 'no' }}
```
3. **Task naming**:
- Use descriptive names
- Start with verb (e.g., "Install", "Configure", "Verify")
- Be specific about what the task does
4. **Line length**: Keep lines under 160 characters (yamllint rule)
5. **YAML document start**: All YAML files must start with `---`
### Version-Aware Development
This role supports 15 distributions with OpenSSH versions 7.2p2 through 10.0p1. **Never break older distributions**.
**When adding features that require specific OpenSSH versions**:
1. **Check version requirement** in OpenSSH release notes
2. **Add capability flag** in `tasks/main.yml`:
```yaml
openssh_has_new_feature: "{{ openssh_version is defined and openssh_version >= 9.5 }}"
```
3. **Use conditional logic** in `templates/sshd_config.j2`:
```jinja2
{% if openssh_has_new_feature | default(false) and openssh_enable_new_feature %}
NewFeature yes
{% endif %}
```
4. **Test on both old and new versions** conceptually
### Security Contributions
**CRITICAL**: Never make security claims without verification.
1. **Verify CVE patch status** using official trackers:
- Debian: `https://security-tracker.debian.org/tracker/CVE-XXXX-XXXXX`
- Ubuntu: `https://ubuntu.com/security/CVE-XXXX-XXXXX`
2. **Understand vendor backports**: Distribution package version ≠ vulnerability status
3. **Research compliance frameworks thoroughly**: Fetch official documentation
4. **Cite sources**: Reference official advisories, CVE databases, government standards
**Example**:
```markdown
❌ WRONG: "Debian Bookworm is vulnerable to CVE-2024-6387"
✅ RIGHT: "Debian Bookworm PATCHED CVE-2024-6387 via 1:9.2p1-2+deb12u3
(verified at https://security-tracker.debian.org/tracker/CVE-2024-6387)"
```
## Documentation Standards
### File Organization
- `README.md`: Quick start, features, navigation (~150 lines)
- `docs/DISTRIBUTIONS.md`: Distribution matrix and capability flags
- `docs/COMPLIANCE.md`: Compliance framework mappings
- `docs/CVE-TRACKING.md`: Vulnerability status by distribution
- `docs/CONFIGURATION.md`: Complete variable reference
- `docs/EXAMPLES.md`: Configuration examples
- `docs/TROUBLESHOOTING.md`: Common issues
### Quality Standards
1. **Use tables for structured data**: Distribution matrices, CVE status, compliance mappings
2. **Provide specific versions**: "Debian Bookworm 1:9.2p1-2+deb12u3" not "Debian Bookworm is patched"
3. **Include verification commands**: Show users how to check their status
4. **Cross-reference documents**: Link to related topics
5. **Keep README concise**: Link to detailed docs rather than embedding everything
### docs/CHANGELOG.md (REQUIRED)
**Every contribution MUST update docs/CHANGELOG.md** following [Keep a Changelog](https://keepachangelog.com/) format.
1. **Add to Unreleased section**:
```markdown
## [Unreleased]
### Added
- Your new feature
### Changed
- What you modified
### Fixed
- What you fixed
### Security
- Security improvements
```
2. **Write clear entries**:
- ✅ GOOD: "Added support for ML-KEM post-quantum key exchange on OpenSSH 9.9+"
- ✅ GOOD: "Fixed CVE-2025-26465 mitigation by disabling VerifyHostKeyDNS by default"
- ❌ BAD: "Updated docs"
- ❌ BAD: "Various fixes"
3. **Reference specific files**:
- "Updated `docs/CVE-TRACKING.md` with CVE-2024-6387 distribution patch status"
## Testing Requirements
### Linting (Required)
```bash
# YAML syntax validation
yamllint .
# Ansible best practices (production profile is strictest)
ansible-lint --profile=production
```
**Both must pass with 0 failures, 0 warnings.**
### Manual Testing (Recommended)
If possible, test your changes on:
- **Legacy**: Debian Bullseye (OpenSSH 8.4p1) or Ubuntu 20.04 (OpenSSH 8.2p1)
- **Modern**: Debian Bookworm (OpenSSH 9.2p1) or Ubuntu 22.04 (OpenSSH 8.9p1)
- **Latest**: Debian Trixie (OpenSSH 10.0p1) or Ubuntu 24.04 (OpenSSH 9.6p1)
### Molecule Testing (Future)
We plan to implement comprehensive Molecule tests. Contributions to testing infrastructure are welcome!
## Pull Request Process
### Before Submitting
- [ ] Code passes `yamllint .` with 0 failures
- [ ] Code passes `ansible-lint --profile=production` with 0 failures
- [ ] Documentation updated (relevant files in `docs/`)
- [ ] `docs/CHANGELOG.md` updated with clear, specific entries
- [ ] Examples updated if behavior changes
- [ ] Backwards compatibility maintained
- [ ] Security claims verified with authoritative sources
### PR Description Template
```markdown
## Description
Brief description of what this PR does.
## Motivation and Context
Why is this change needed? What problem does it solve?
If it fixes an open issue, link to it here.
## Type of Change
- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to change)
- [ ] Documentation update
- [ ] Security fix
## Testing
How was this tested? Include:
- Distribution(s) tested on
- OpenSSH version(s) tested with
- Test procedure
## Checklist
- [ ] yamllint passes
- [ ] ansible-lint passes
- [ ] Documentation updated
- [ ] docs/CHANGELOG.md updated
- [ ] Examples updated (if applicable)
- [ ] Security claims verified with sources
```
### Review Process
1. **Automated checks**: Linting must pass
2. **Maintainer review**: Code quality, security accuracy, documentation
3. **Community feedback**: Other contributors may provide feedback
4. **Approval and merge**: Once approved, maintainer will merge
### After Your PR is Merged
- Update your fork:
```bash
git checkout main
git pull upstream main
git push origin main
```
- Delete your feature branch:
```bash
git branch -d feature/your-feature-name
git push origin --delete feature/your-feature-name
```
## Common Contribution Types
### Adding a New Compliance Framework
1. Research official framework documentation
2. Identify SSH-related requirements
3. Map requirements to role variables
4. Update `docs/COMPLIANCE.md` with new table entry
5. Create example playbook in `examples/` if needed
6. Update README.md feature list
7. Update `docs/CHANGELOG.md` under `[Unreleased]``### Added`
### Adding a New Distribution
1. Check OpenSSH version shipped with distribution
2. Add to distribution tables in `docs/DISTRIBUTIONS.md`
3. Test capability flags work correctly
4. Check CVE patch status for that distribution
5. Update `docs/CVE-TRACKING.md` if needed
6. Add to `meta/main.yml` platforms list
7. Update README.md badges
8. Update `docs/CHANGELOG.md` under `[Unreleased]``### Added`
### Responding to a New CVE
1. Research CVE on openssh.com/security.html and NVD
2. Check all 15 distributions' patch status
3. Determine if role configuration provides mitigation
4. Update `docs/CVE-TRACKING.md` with comprehensive status
5. Update defaults/templates if mitigation needed
6. Update `docs/CHANGELOG.md` under `[Unreleased]``### Security`
### Updating Cryptographic Standards
1. Check OpenSSH release notes for new algorithms
2. Review Mozilla/NSA/BSI/ANSSI guidance updates
3. Test algorithm availability on Debian Stretch (oldest)
4. Update `defaults/main.yml` with new preferences
5. Add capability flags if version-specific
6. Update `docs/COMPLIANCE.md` if affects compliance
7. Update `docs/CHANGELOG.md` under `[Unreleased]``### Changed` or `### Security`
## Language and Terminology
### Preferred Language
- Use **clear, direct language**: "comprehensive", "robust", "sophisticated attacks"
- Avoid **buzzwords**: "enterprise-grade", "enterprise-level", "nation-state level", "APTs"
- Prefer **technical accuracy** over impressive-sounding claims
### Code Comments
- Explain **why**, not just **what**
- Reference compliance requirements where applicable
- Use comments to make configuration self-documenting
## Questions?
- Check existing [documentation](../README.md)
- Review [AGENTS.md](../AGENTS.md) for detailed development guidelines
- Open an issue for discussion
- Check git commit history for examples
## Recognition
Contributors will be:
- Listed in git commit history
- Recognized in release notes
- Credited in docs/CHANGELOG.md for significant contributions
Thank you for helping make this project better! 🚀
---
*Last updated: 2025-10-05*

View file

@ -0,0 +1,176 @@
# Contributors
Thank you to everyone who has contributed to **ansible-role-openssh_server**! This project exists because of the community.
## How to Be Listed Here
We recognize all types of contributions! You can be added to this list by:
### Code Contributions
- Submitting pull requests (bug fixes, features, improvements)
- Reviewing code and providing feedback
- Improving test coverage
- Fixing typos or formatting
### Documentation Contributions
- Improving documentation
- Adding examples
- Fixing broken links
- Translating documentation
- Writing tutorials or blog posts
### Community Contributions
- Answering questions in issues
- Helping other users troubleshoot problems
- Triaging and reproducing bug reports
- Testing on different distributions
### Security Contributions
- Responsibly reporting security vulnerabilities
- Improving CVE tracking accuracy
- Researching compliance frameworks
- Verifying security claims with authoritative sources
### Other Contributions
- Suggesting features or improvements
- Providing feedback on usability
- Sharing the project with others
- Supporting the project in any way
## Current Contributors
### Project Creator
**Gravitino LLC** ([@Gravitino](https://github.com/Gravitino))
- Role: Creator, primary developer, maintainer
- Contributions: Initial project creation, all 1.0.0 features
### Contributors
<!--
Contributors will be added here as they contribute to the project.
Format:
**[Name or Handle]** ([GitHub Profile](link))
- Contributions: Brief description
- Date: Year(s) of contribution
Example:
**Jane Doe** ([@janedoe](https://github.com/janedoe))
- Contributions: Added support for Debian Trixie, improved CVE tracking
- Date: 2025
-->
*No external contributors yet. Be the first!*
### Security Researchers
We recognize and thank security researchers who responsibly disclose vulnerabilities. Want to be listed here? Find a vulnerability and report it responsibly per our [Security Policy](SECURITY.md)!
<!--
Security researchers will be listed here after coordinated disclosure.
Format:
**[Name or Pseudonym]**
- Disclosed: [CVE-YYYY-XXXXX or brief description]
- Date: YYYY-MM-DD
- Credit preference: [Full name, pseudonym, or anonymous]
Example:
**Security Researcher Name**
- Disclosed: CVE-2025-12345 - SSH configuration vulnerability
- Date: 2025-01-15
- Credit preference: Full name with link to researcher profile
-->
*No vulnerabilities have been reported yet.*
## Acknowledgment Preferences
When contributing, let us know how you'd like to be recognized:
- ✅ **Full name**: Your real name
- ✅ **GitHub handle**: @username
- ✅ **Pseudonym**: A nickname or alias
- ✅ **Email**: Your email address (optional)
- ✅ **Website**: Link to your site or blog (optional)
- ✅ **Anonymous**: Prefer not to be listed (we'll still thank you!)
Please indicate your preference in your pull request or when you contribute.
## Automated Contributors
### All Contributors
For a complete, automatically generated list of all contributors (including small contributions), see:
**Git Contributors**:
```bash
git log --format='%aN <%aE>' | sort -u
```
**GitHub Contributors**:
Visit https://github.com/welshwandering/ansible-role-openssh_server/graphs/contributors
## Project Dependencies & Acknowledgments
This project builds upon the work of many others:
### Core Technologies
- **OpenSSH Project** - The foundation of secure remote access
- **Ansible** - Infrastructure automation platform
- **Debian & Ubuntu** - Distribution security teams who patch and maintain OpenSSH
### Standards & Research
- **NSA/CISA, BSI, ANSSI, CCCS** - Cryptographic guidance and security standards
- **Mozilla** - OpenSSH security guidelines
- **NIST, CIS, OWASP** - Security frameworks and best practices
For a complete list of acknowledgments, see [ACKNOWLEDGEMENTS.md](ACKNOWLEDGEMENTS.md).
## How to Add Yourself
### For Code Contributors
When your pull request is merged:
1. You'll be automatically added to GitHub's contributors graph
2. Optionally, add yourself to this file in your PR:
```markdown
**Your Name** ([@yourhandle](https://github.com/yourhandle))
- Contributions: Brief description
- Date: 2025
```
### For Non-Code Contributors
If you've contributed in other ways:
1. Open a pull request to add yourself to this file
2. Or mention it in an issue and we'll add you
3. Specify how you'd like to be credited
## Thank You! 🎉
Every contribution, no matter how small, makes this project better. We appreciate:
- 🐛 Bug reports and fixes
- ✨ New features and improvements
- 📝 Documentation enhancements
- 🔐 Security research and responsible disclosure
- 💬 Community support and discussions
- 🧪 Testing across different distributions
- ❤️ Using and sharing the project
**Thank you for making the internet more secure!**
---
## Notes
- This file is updated periodically as contributions are merged
- For legal authorship and copyright, see [AUTHORS.md](AUTHORS.md)
- For contribution guidelines, see [CONTRIBUTING.md](CONTRIBUTING.md)
- For security disclosures, see [SECURITY.md](SECURITY.md)
---
*Last updated: 2025-10-05*

View file

@ -0,0 +1,119 @@
# CVE Vulnerability Tracking
### Security Vulnerability Mitigations
This role mitigates numerous OpenSSH vulnerabilities through version detection, configuration hardening, and secure defaults. Below is a comprehensive analysis showing which CVEs are fully mitigated, which are conditionally mitigated based on version, and which remain open.
**Reference**: [Official OpenSSH Security Advisories](https://www.openssh.com/security.html)
#### Fully Mitigated (All Supported Distributions)
These vulnerabilities are mitigated through secure configuration defaults regardless of OpenSSH version:
| CVE | CVSS | Description | Mitigation |
|-----|------|-------------|------------|
| **CVE-2025-26465** | 6.8 | Man-in-the-middle attack when VerifyHostKeyDNS enabled (9.9p1 and earlier) | ✅ `openssh_verify_host_key_dns: false` (default) |
| **CVE-2020-14145** | 5.9 | Observable discrepancy in client algorithm negotiation (5.7-8.4) | ✅ Modern algorithm preference ordering eliminates timing oracle |
| **CVE-2019-6109** | 3.1 | SCP client output spoofing via missing character encoding | ✅ Advisory only - requires MITM during SCP transfer |
| **CVE-2019-6110** | 3.1 | SCP client output spoofing via stderr manipulation | ✅ Advisory only - requires MITM during SCP transfer |
| **CVE-2018-20685** | 5.3 | SCP client accepting arbitrary objects from malicious server | ✅ Advisory only - not a protocol vulnerability |
| **CVE-2016-0777** | 6.5 | Information disclosure in SSH clients 5.4-7.1 (roaming code) | ✅ Fixed in all supported distributions (7.2p2+) |
| **CVE-2016-0778** | 4.6 | Buffer overflow in SSH clients 5.4-7.1 (roaming code) | ✅ Fixed in all supported distributions (7.2p2+) |
#### Conditionally Mitigated (Version-Dependent)
**Important Note**: Modern Debian and Ubuntu releases apply security patches via backports even to older OpenSSH versions. This means a distribution may be protected despite running an OpenSSH version that was originally vulnerable. Always check security tracker status and keep systems updated.
These vulnerabilities are mitigated through vendor security patches. The role automatically enables additional protections when supported:
| CVE | CVSS | Upstream Affects | Upstream Fixed | Distribution Status |
|-----|------|------------------|----------------|---------------------|
| **CVE-2024-6387**<br>("regreSSHion" RCE) | 8.1 | 8.5p1-9.7p1 | 9.8p1 | ✅ **Debian Bookworm**: FIXED via patch 1:9.2p1-2+deb12u3<br>**Debian Bullseye**: NOT AFFECTED (8.4p1 predates vulnerable code)<br>**Debian Trixie/Forky**: FIXED (10.0p1-7/8)<br>**Ubuntu 24.04 Noble**: FIXED via patch 1:9.6p1-3ubuntu13.3<br>**Ubuntu 22.04 Jammy**: FIXED via patch 1:8.9p1-3ubuntu0.10<br>**Ubuntu 20.04 Focal**: NOT AFFECTED (8.2p1 predates vulnerable code)<br>**Ubuntu 16.04/18.04**: NOT AFFECTED |
| **CVE-2025-26466**<br>(DoS via SSH2_MSG_PING) | 6.8 | 9.5p1-9.9p1 | 9.9p2 | ⚠️ **All Distributions**: Awaiting 9.9p2 release<br>🛡️ **Partial Mitigation**: PerSourcePenalties (9.8+) provides DoS protection |
| **CVE-2024-7589**<br>(FreeBSD blacklistd RCE) | 7.4 | FreeBSD only | N/A | ✅ **Not Applicable**: Debian/Ubuntu systems not affected |
| **CVE-2023-48795**<br>("Terrapin Attack" - protocol truncation) | 5.9 | All versions <9.6 | 9.6p1 | **ALL DISTRIBUTIONS PATCHED**:<br>- Debian Bookworm: 1:9.2p1-2+deb12u5<br>- Debian Bullseye: 1:8.4p1-5+deb11u3<br>- Debian Buster: Patched<br>- Ubuntu 24.04: 1:9.6p1-3ubuntu1<br>- Ubuntu 22.04: 1:8.9p1-3ubuntu0.5<br>- Ubuntu 20.04: 1:8.2p1-4ubuntu0.10<br>- Even ESM releases (16.04, 18.04) are patched |
| **CVE-2023-38408**<br>(PKCS#11 RCE via ssh-agent) | 9.8 | ≤9.3p1 | 9.3p2 | ✅ **ALL DISTRIBUTIONS PATCHED**:<br>- Debian Bookworm: 1:9.2p1-2+deb12u7<br>- Debian Bullseye: 1:8.4p1-5+deb11u3<br>- Debian Buster: 1:7.9p1-10+deb10u3<br>- Ubuntu 24.04: 1:9.3p1-1ubuntu2<br>- Ubuntu 22.04: 1:8.9p1-3ubuntu0.3<br>- Ubuntu 20.04: 1:8.2p1-4ubuntu0.8<br>- Even ESM releases patched<br>🛡️ **Additional Protection**: Agent forwarding disabled by default in this role |
| **CVE-2021-41617**<br>(Privilege escalation) | 7.4 | 6.2-8.7 | 8.8 | ✅ **Ubuntu 22.04+**: NOT AFFECTED (8.9p1 > 8.8)<br>**Ubuntu 20.04**: FIXED via patch 1:8.2p1-4ubuntu0.11<br>⚠️ **Ubuntu 18.04**: VULNERABLE (no patch available)<br>**All Debian**: PATCHED via backports<br>🛡️ **Mitigation**: Only exploitable with non-default AuthorizedKeysCommand (not enabled by this role) |
| **CVE-2021-36368**<br>(Double-free in ssh-agent) | 7.8 | 8.2-8.4 | 8.5 | ✅ **Debian Bullseye**: PATCHED despite version 8.4p1<br>**Ubuntu 22.04+**: NOT AFFECTED (8.9p1+)<br>⚠️ **Ubuntu 20.04**: Potentially vulnerable (8.2p1) - verify patch status |
| **CVE-2020-15778**<br>(Command injection in scp) | 7.8 | ≤8.3p1 | 8.4 | ✅ **Most distributions**: PATCHED<br>⚠️ **Debian Buster**: May be vulnerable (7.9p1, EOL)<br>📋 **Workaround**: Use sftp instead of scp |
| **CVE-2019-16905**<br>(Integer overflow with XMSS) | 7.1 | 7.7-8.0 | 8.1 | ✅ **All supported distributions**: NOT AFFECTED or FIXED<br>🛡️ **Note**: Requires experimental XMSS compile-time support (not standard) |
| **CVE-2019-6111**<br>(SCP file overwrite via MITM) | 5.3 | <8.0 | 8.0 | **Modern distributions** (8.2p1+): FIXED<br>⚠️ **Debian Stretch/Buster, Ubuntu 16.04-18.04**: May be vulnerable (EOL) |
#### Version-Specific Capability Mitigations
The role applies these enhanced security controls automatically when the OpenSSH version supports them:
| Feature | Requires | Mitigation | CVEs Addressed |
|---------|----------|------------|----------------|
| **PerSourcePenalties** | 9.8+ | Automatic rate limiting and attack mitigation | CVE-2025-26466 (partial), general DoS attacks |
| **RequiredRSASize 3072** | 9.3+ | Enforces NSA/CISA minimum RSA key size | Weak key attacks, potential future RSA vulnerabilities |
| **ML-KEM Post-Quantum KEX** | 9.9+ | Quantum-resistant key exchange | Future quantum computer attacks on ECDH |
| **DisableForwarding** | 7.4+ | Comprehensive forwarding disable (fixed in 10.0) | Forwarding-based privilege escalation |
| **LogVerbose** | 8.5+ | Enhanced forensic logging for specific subsystems | Improves incident response and attack detection |
| **CASignatureAlgorithms** | 7.9+ | Restricts CA signature algorithms | Prevents weak signature algorithm attacks |
#### Open/Unmitigated Vulnerabilities
**Good News**: With updated systems, most CVEs are patched via vendor security updates. The vulnerabilities below affect only specific EOL or unpatched systems:
| CVE | CVSS | Unpatched Systems | Status | Action Required |
|-----|------|-------------------|--------|-----------------|
| **CVE-2025-26466** | 6.8 | All systems with OpenSSH 9.5p1-9.9p1 | ⚠️ **Awaiting Fix** | Monitor for OpenSSH 9.9p2 release<br>Partial mitigation: PerSourcePenalties (9.8+) |
| **CVE-2021-41617** | 7.4 | Ubuntu 18.04 Bionic (without ESM updates) | ⚠️ **Vulnerable** | **Upgrade to Ubuntu 20.04+** or enable ESM |
| **CVE-2021-36368** | 7.8 | Ubuntu 20.04 Focal (if unpatched) | ⚠️ **Verify Status** | **Run `apt update && apt upgrade openssh-server`** |
| **Multiple CVEs** | Various | Debian Stretch, Buster (EOL)<br>Ubuntu 16.04, 18.04 (without ESM) | 🔴 **End-of-Life** | **Upgrade to supported release** |
#### Distribution-Specific Vulnerability Status
**✅ PATCHED: Secure Against All Known Critical CVEs (with updates applied)**
These distributions have security patches for all major CVEs. **Run `apt update && apt upgrade openssh-server` to ensure patches are applied:**
| Distribution | OpenSSH Version | Security Status | Notes |
|--------------|-----------------|-----------------|-------|
| **Debian Trixie/Forky** | 10.0p1 | ✅ Fully patched | Latest upstream release |
| **Debian Bookworm** | 9.2p1 | ✅ **PATCHED** for CVE-2024-6387 via 1:9.2p1-2+deb12u3 | Despite lower version, all CVEs are patched |
| **Debian Bookworm-backports** | 10.0p1 | ✅ Fully patched | Latest upstream release |
| **Debian Bullseye** | 8.4p1 | ✅ **NOT AFFECTED** by CVE-2024-6387<br>✅ Other CVEs patched | Below vulnerable version range (8.5p1+) |
| **Ubuntu 24.10 Oracular** | 9.7p1+ | ✅ Fully patched | Includes all security patches |
| **Ubuntu 25.04 Plucky** | 9.9p1+ | ✅ Fully patched | Post-quantum ready |
| **Ubuntu 24.04 Noble LTS** | 9.6p1 | ✅ Fully patched | All CVEs addressed via security updates |
| **Ubuntu 22.04 Jammy LTS** | 8.9p1 | ✅ **PATCHED** for CVE-2024-6387 via 1:8.9p1-3ubuntu0.10 | All major CVEs backport-patched |
| **Ubuntu 20.04 Focal LTS** | 8.2p1 | ✅ **NOT AFFECTED** by CVE-2024-6387<br>✅ Most CVEs patched | Below vulnerable version range (8.5p1+) |
**⚠️ VERIFY UPDATES: Potentially Vulnerable if Not Updated**
| Distribution | OpenSSH Version | Action Required |
|--------------|-----------------|-----------------|
| **Debian Buster (LTS)** | 7.9p1 | ⚠️ **End-of-Life** - Verify LTS Extended Security Updates are applied<br>📋 **Recommendation**: Upgrade to Debian 11+ |
| **Ubuntu 20.04 Focal** | 8.2p1 | ⚠️ Verify CVE-2021-36368 patch applied: `apt policy openssh-server`<br>Should show version ≥ 1:8.2p1-4ubuntu0.11 |
| **Ubuntu 18.04 Bionic (ESM)** | 7.6p1 | ⚠️ **Requires Ubuntu Pro** for security updates<br>⚠️ CVE-2021-41617 marked vulnerable without ESM<br>📋 **Recommendation**: Upgrade to Ubuntu 20.04+ LTS |
**🔴 END-OF-LIFE: Multiple Critical Vulnerabilities**
| Distribution | OpenSSH Version | Status | Action Required |
|--------------|-----------------|--------|-----------------|
| **Debian Stretch** | 7.4p1 | 🔴 **EOL since 2022** | **URGENT: Upgrade to Debian 11+**<br>Multiple unpatched critical vulnerabilities |
| **Debian Buster** | 7.9p1 | 🔴 **EOL since 2024** (LTS ends 2026) | **Upgrade to Debian 11+** or ensure LTS support |
| **Ubuntu 16.04 Xenial** | 7.2p2 | 🔴 **Standard support ended 2021** | **Requires Ubuntu Pro (ESM) or upgrade to 20.04+ LTS**<br>Even with ESM, consider upgrading |
**Key Takeaways:**
1. **✅ Most Current LTS Distributions Are Secure**: Debian Bullseye+, Ubuntu 20.04+ all have CVE-2024-6387 and other major CVEs patched
2. **📦 Backports Work**: Vendors apply security patches to older OpenSSH versions - don't just look at version numbers
3. **🔄 Keep Systems Updated**: Run `apt update && apt upgrade` regularly to receive security patches
4. **⚠️ Check EOL Status**: End-of-life distributions (Stretch, Buster, Xenial without ESM) lack security support
5. **📋 ESM Consideration**: Ubuntu 16.04/18.04 require Ubuntu Pro for Extended Security Maintenance
**Verification Command:**
```bash
# Check your OpenSSH version and package version
ssh -V
apt policy openssh-server
# Verify you're on latest security updates
sudo apt update
sudo apt list --upgradable | grep openssh
```
**Recommendation**: For production systems, use **Debian Bullseye+** or **Ubuntu 20.04+ LTS** and maintain regular update schedules. Debian Bookworm and Ubuntu 22.04/24.04 LTS are ideal choices with full vendor support through 2028-2032.

View file

@ -0,0 +1,96 @@
# Supported Distributions
This role automatically detects your distribution and OpenSSH version, enabling advanced features when supported while maintaining backwards compatibility.
## Target Distribution List
| Distribution | Required Versions | Current Support Status | OpenSSH Version |
|--------------|-------------------|-------------------------|-----------------|
| **Debian** | 11, 12, 13, 14 | 11, 12, 13 (Stable), 14 (Testing) | 8.4p1 - 10.2p1+ |
| **Ubuntu** | 22.04, 24.04, 25.10 | 22.04 LTS, 24.04 LTS, 25.10 (Interim) | 8.9p1 - 10.0p1 |
| **Rocky** | 8, 9, 10 | 8, 9, 10 (Current) | 8.0p1 - 9.9p1 |
| **Fedora** | 43 | 43 (Current) | 9.9p1+ |
## Debian Releases
| Distribution | Release Date | Support Until | OpenSSH Version | Feature Level |
|--------------|--------------|---------------|-----------------|---------------|
| **Stretch (9)** | 2017-06 | 2022-06 (EOL) | 7.4p1 | ⚠️ Legacy - Limited features |
| **Buster (10)** | 2019-07 | 2024-06 (LTS) | 7.9p1 | ⚠️ Legacy - No FIDO2 |
| **Bullseye (11)** | 2021-08 | 2026-08 (LTS) | 8.4p1 | ✅ Modern - FIDO2 support |
| **Bookworm (12)** | 2023-06 | 2028-06 (LTS) | 9.2p1 | ✅ Modern - Full featured |
| **Trixie (13)** | 2025-08 | 2030-08 | 10.0p1 | ✅ Latest - All features |
| **Forky (14)** | TBD | Testing | 10.2p1+ | ✅ Latest - Cutting edge |
## Ubuntu LTS Releases
| Distribution | Release Date | Support Until | OpenSSH Version | Feature Level |
|--------------|--------------|---------------|-----------------|---------------|
| **22.04 Jammy** | 2022-04 | 2032-04 (ESM) | 8.9p1 | ✅ Modern - Full featured |
| **24.04 Noble** | 2024-04 | 2034-04 (ESM) | 9.6p1 | ✅ Latest - Advanced features |
## Rocky Linux (RHEL Compatible)
| Distribution | Release Date | Support Until | OpenSSH Version | Feature Level |
|--------------|--------------|---------------|-----------------|---------------|
| **Rocky Linux 8** | 2021-06 | 2029-05 | 8.0p1 | ⚠️ Legacy - No FIDO2 |
| **Rocky Linux 9** | 2022-07 | 2032-05 | 8.7p1 | ✅ Modern - FIDO2 + LogVerbose |
| **Rocky Linux 10** | 2025-06 | 2035-05 | 9.9p1 | ✅ Latest - Post-quantum ready |
## Fedora Releases
| Distribution | Release Date | Support Until | OpenSSH Version | Feature Level |
|--------------|--------------|---------------|-----------------|---------------|
| **Fedora 43** | 2025-10 | 2026-11 | 9.9p1+ | ✅ Latest - Cutting edge |
### Point Release Status (Jan 2026)
- **Debian**: 11.11, 12.12, 13.2
- **Rocky Linux**: 8.10, 9.7, 10.1
## Ubuntu Non-LTS Releases (Current Only)
| Distribution | Release Date | Support Until | OpenSSH Version | Feature Level |
|--------------|--------------|---------------|-----------------|---------------|
| **25.10 Questing** | 2025-10 | 2026-07 | 10.0p1 | ✅ Latest - Cutting edge |
### Non-LTS Support Policy
- ✅ We support **current and upcoming** non-LTS releases only
- ❌ We do **NOT** support EOL non-LTS releases (no security updates)
- ⏰ Non-LTS releases have a **9-month support window**
- 📋 For production use, we **strongly recommend Ubuntu LTS releases**
## Legend
- ✅ **Latest**: OpenSSH 9.6+ with post-quantum crypto readiness
- ✅ **Modern**: OpenSSH 8.2+ with FIDO2 hardware key support
- ⚠️ **Legacy**: Older OpenSSH with limited modern features (still supported)
- **ESM**: Extended Security Maintenance (Ubuntu Pro required for 16.04/18.04)
## Version Detection
The role automatically detects your OpenSSH version using `ssh -V` and sets capability flags that control which features are enabled. This ensures older distributions don't encounter errors when using directives they don't support.
**Note**: The role will display warnings when running on EOL or ESM distributions and automatically disable unsupported features.
## Capability Flags
The role sets 13 version-specific capability flags:
| Flag | Minimum Version | Feature Enabled |
|------|-----------------|-----------------|
| `openssh_has_disable_forwarding` | 7.4 | DisableForwarding directive |
| `openssh_has_ca_signature_algorithms` | 7.9 | CASignatureAlgorithms directive |
| `openssh_has_fido2` | 8.2 | FIDO2/WebAuthn security keys |
| `openssh_has_include` | 8.2 | Include directive support |
| `openssh_has_log_verbose` | 8.5 | LogVerbose directive |
| `openssh_has_required_rsa_size` | 9.3 | RequiredRSASize directive |
| `openssh_has_persourcepenalties` | 9.8 | PerSourcePenalties directive |
| `openssh_has_mlkem` | 9.9 | ML-KEM post-quantum KEX |
| `openssh_has_rsa_sha2` | 7.2 | RSA-SHA2 signature algorithms |
| `openssh_has_modern_kex` | 7.4 | Modern key exchange algorithms |
| `openssh_blocks_dsa_ca` | 7.9 | DSA CA keys blocked |
| `openssh_removes_dsa` | 9.6 | DSA completely removed |
| `openssh_dh_disabled_default` | 10.0 | DH disabled by default |
These flags are set automatically in [tasks/main.yml](../tasks/main.yml) and used throughout [templates/sshd_config.j2](../templates/sshd_config.j2) to enable features only when supported.

View file

@ -0,0 +1,46 @@
# Configuration Examples
## Configuration Examples
### Enable Post-Quantum Cryptography
Post-quantum KEX is automatically enabled on OpenSSH 9.9+. To verify:
```yaml
openssh_enable_mlkem: true # Default, auto-enables when supported
```
### Maximum Security Hardening
```yaml
- hosts: high_security_servers
roles:
- role: openssh_server
vars:
openssh_password_authentication: false
openssh_permit_root_login: "no"
openssh_enable_persourcepenalties: true # Auto-enabled on 9.8+
openssh_enable_verbose_logging: true
openssh_disable_forwarding_comprehensive: true
openssh_max_auth_tries: 3
openssh_rekey_limit: "512M 30m" # Re-key every 512MB or 30min
```
### Enable FIDO2 Hardware Security Keys
```yaml
openssh_enable_security_keys: true
openssh_pubkey_accepted_key_types:
- sk-ssh-ed25519@openssh.com # FIDO2 Ed25519
- ssh-ed25519 # Standard Ed25519
- sk-ecdsa-sha2-nistp256@openssh.com # FIDO2 ECDSA
```
### Certificate Authority Configuration
```yaml
openssh_enable_ca: true
openssh_trusted_user_ca_keys:
- /etc/ssh/ca/user_ca.pub
openssh_host_certificate: /etc/ssh/ssh_host_ed25519_key-cert.pub
```

View file

@ -0,0 +1,224 @@
# Security Policy
## Our Commitment to Security
The ansible-role-openssh_server project is dedicated to helping administrators secure their SSH infrastructure. We take security vulnerabilities in this role very seriously and appreciate responsible disclosure from the security research community.
This role helps protect critical infrastructure, compliance-regulated systems, and sensitive data worldwide. Security issues in this role could affect thousands of systems, so we handle vulnerability reports with urgency and care.
## Supported Versions
We provide security updates for the following versions of this role:
| Version | Supported | Status |
| ------- | ------------------ | ------ |
| 1.x | :white_check_mark: | Current stable release - actively maintained |
| < 1.0 | :x: | Pre-release versions - not supported |
**Note**: We maintain only the latest major version. When 2.x is released, 1.x will receive security updates for 90 days before being deprecated.
## What Qualifies as a Security Vulnerability
We consider the following to be security vulnerabilities:
### High Priority
- **Configuration that weakens SSH security**: Role generates insecure SSH configurations (e.g., weak ciphers, disabled authentication)
- **Privilege escalation**: Role allows unauthorized privilege escalation on managed systems
- **Credential exposure**: Role logs, displays, or stores credentials insecurely
- **Arbitrary code execution**: Role allows execution of arbitrary code on managed systems
- **Authentication bypass**: Role configuration allows bypassing SSH authentication
### Medium Priority
- **Information disclosure**: Role exposes sensitive system information unnecessarily
- **Denial of service**: Role configuration makes SSH service unavailable
- **Insecure defaults**: Role defaults do not follow security best practices
- **CVE tracking errors**: Role documentation incorrectly reports CVE patch status
### Not Security Vulnerabilities
The following are **not** considered security vulnerabilities in this role:
- OpenSSH vulnerabilities (report to OpenSSH project: https://www.openssh.com/security.html)
- Distribution-specific SSH package vulnerabilities (report to Debian/Ubuntu security teams)
- Issues requiring physical access to the system
- Social engineering attacks
- Documentation typos or formatting issues (open a regular issue)
- Feature requests or enhancement suggestions (open a regular issue)
## Reporting a Vulnerability
**⚠️ DO NOT report security vulnerabilities through public GitHub issues.**
### Reporting a Vulnerability
We take security seriously. If you discover a vulnerability, please report it via [GitHub Security Advisories](https://github.com/welshwandering/ansible-role-openssh_server/security/advisories/new).
**DO NOT** open a public issue for sensitive security vulnerabilities.
### Alternative Method: Private Email
If you cannot use GitHub Security Advisories, email the maintainer directly:
- **Email**: See repository maintainer contact information
- **Subject line**: `[SECURITY] ansible-role-openssh_server: Brief description`
- **PGP Key**: Available upon request for encrypted communication
### What to Include in Your Report
To help us understand and address the issue quickly, please include:
1. **Vulnerability Description**
- What is the vulnerability?
- What is the impact?
- Who is affected?
2. **Reproduction Steps**
- Detailed steps to reproduce the issue
- Example playbook or configuration
- Distribution and OpenSSH version affected
3. **Proof of Concept**
- If possible, provide a PoC (sanitized of any sensitive data)
- Screenshots or terminal output (with sensitive data removed)
4. **Suggested Fix** (optional)
- If you have ideas for remediation, we'd love to hear them
- Pull requests for fixes are welcome after coordinated disclosure
5. **Your Contact Information**
- How should we contact you for follow-up?
- Do you want to be credited in the advisory?
## Our Response Process
### Response Process
**Important**: This is a volunteer-run hobby project. While we take security seriously, responses will happen as maintainer time permits.
1. **Acknowledgment**: We'll confirm receipt when we can
2. **Assessment**: We'll evaluate the severity and impact
3. **Updates**: We'll keep you informed as we work on it
4. **Fix Development**: Timeline depends on severity and maintainer availability
5. **Coordinated Disclosure**: We'll work with you on timing
### Our Commitment
We take security seriously and will prioritize critical issues, but please understand:
- This is maintained by volunteers in their spare time
- Response times will vary based on maintainer availability
- Critical issues will be addressed as quickly as possible
- Less severe issues may take longer
We appreciate your patience and understanding.
### What Happens After You Report
1. **We acknowledge your report** and confirm receipt
2. **We assess the vulnerability** and determine severity
3. **We work on a fix** in a private repository
4. **We keep you informed** of our progress
5. **We coordinate disclosure** with you on timing and details
6. **We release the fix** and publish a security advisory
7. **We credit you** in the advisory (if you wish)
## Security Advisory Process
When we fix a security vulnerability:
1. **Private fix development**: We develop the fix in a private fork
2. **Security testing**: We test the fix across all supported distributions
3. **Documentation update**: We update `docs/CVE-TRACKING.md` and `docs/CHANGELOG.md`
4. **Coordinated disclosure**: We coordinate with reporter on disclosure timing
5. **Public release**: We release the fix and publish a security advisory
6. **User notification**: We tag the release and update documentation
## Security Best Practices for Users
While we work to keep this role secure, users should also follow these practices:
### Before Using This Role
- **Review the role**: Read the code before running it in production
- **Test first**: Always test in non-production environments
- **Pin versions**: Use specific git tags or commits, not `main` branch
- **Review changes**: Check diffs when updating to new versions
### When Deploying
- **Use version control**: Store your playbooks in git with proper access controls
- **Protect credentials**: Use Ansible Vault for sensitive variables
- **Limit access**: Restrict who can modify your Ansible playbooks
- **Audit logs**: Enable logging for Ansible playbook runs
### After Deployment
- **Monitor advisories**: Watch this repository for security advisories
- **Stay updated**: Apply role updates promptly
- **Test updates**: Test updates in non-production before deploying
- **Review configurations**: Periodically review generated SSH configurations
## Scope of This Security Policy
### In Scope
- Security vulnerabilities in this Ansible role's code
- Insecure default configurations
- Documentation errors about security or CVE status
- Compliance framework mapping errors
### Out of Scope
- OpenSSH software vulnerabilities (report to OpenSSH project)
- Operating system vulnerabilities (report to Debian/Ubuntu)
- Ansible core vulnerabilities (report to Ansible project)
- Third-party module vulnerabilities (report to module maintainers)
- Infrastructure security (your Ansible control node, SSH keys, etc.)
## CVE Tracking and Updates
This role maintains comprehensive CVE tracking in [docs/CVE-TRACKING.md](docs/CVE-TRACKING.md). We monitor:
- OpenSSH security advisories: https://www.openssh.com/security.html
- Debian security tracker: https://security-tracker.debian.org/
- Ubuntu security bulletins: https://ubuntu.com/security/cves
- NVD database: https://nvd.nist.gov/
When new OpenSSH CVEs are published, we:
1. Assess impact on all supported distributions
2. Verify patch status on distribution security trackers
3. Update `docs/CVE-TRACKING.md` with accurate information
4. Implement configuration mitigations if needed
5. Update `docs/CHANGELOG.md` under `### Security`
**Note**: We track CVEs affecting OpenSSH, but we do not fix vulnerabilities in OpenSSH itself. Distribution security teams handle that.
## Recognition
Security researchers who responsibly disclose vulnerabilities are recognized in [docs/CONTRIBUTORS.md](CONTRIBUTORS.md) under "Security Researchers."
## Questions About Security?
- **General security questions**: Open a [discussion issue](https://github.com/welshwandering/ansible-role-openssh_server/issues/new?template=security.md)
- **Security vulnerabilities**: Use the reporting process above
- **CVE status questions**: Check [docs/CVE-TRACKING.md](docs/CVE-TRACKING.md) or open a discussion
- **Compliance questions**: Check [docs/COMPLIANCE.md](docs/COMPLIANCE.md) or open a discussion
## Additional Resources
- **OpenSSH Security**: https://www.openssh.com/security.html
- **CVE Tracking**: [docs/CVE-TRACKING.md](docs/CVE-TRACKING.md)
- **Compliance Frameworks**: [docs/COMPLIANCE.md](docs/COMPLIANCE.md)
- **Contributing Guidelines**: [docs/CONTRIBUTING.md](docs/CONTRIBUTING.md)
- **Security Discussion Template**: [.github/ISSUE_TEMPLATE/security.md](.github/ISSUE_TEMPLATE/security.md)
## Thank You
Thank you for helping keep ansible-role-openssh_server and the broader SSH ecosystem secure. Your responsible disclosure makes the internet safer for everyone.
---
*Last updated: 2025-10-05*
*Security Policy Version: 1.0*

View file

@ -0,0 +1,283 @@
# Getting Support
Thank you for using **ansible-role-openssh_server**! This document explains how to get help with this OpenSSH server hardening role.
## Important Note
**This is a volunteer-run hobby project.** Maintainers contribute in their spare time. We appreciate your patience and understanding as we help where we can.
## Before Asking for Help
Please try these steps first—they often solve problems quickly:
### 1. Read the Documentation
Start with our comprehensive documentation:
- **[README.md](../README.md)**: Quick start, features, and overview
- **[docs/CONFIGURATION.md](CONFIGURATION.md)**: Complete variable reference
- **[docs/DISTRIBUTIONS.md](DISTRIBUTIONS.md)**: Supported distributions and version compatibility
- **[docs/EXAMPLES.md](EXAMPLES.md)**: Configuration examples for common scenarios
- **[docs/TROUBLESHOOTING.md](TROUBLESHOOTING.md)**: Common issues and solutions
- **[docs/CVE-TRACKING.md](CVE-TRACKING.md)**: CVE status and patch tracking
- **[docs/COMPLIANCE.md](COMPLIANCE.md)**: Compliance framework mappings
### 2. Search Existing Issues
Someone may have already encountered your problem:
1. Go to [GitHub Issues](https://github.com/welshwandering/ansible-role-openssh_server/issues)
2. Search for keywords related to your issue
3. Check both open and closed issues
4. Look for the answer in issue comments
### 3. Check Your Configuration
Many issues are configuration-related:
- Verify your Ansible version: `ansible --version` (need 2.15+)
- Check your OpenSSH version: `ssh -V`
- Confirm your distribution is supported (see [docs/DISTRIBUTIONS.md](DISTRIBUTIONS.md))
- Review your role variables for typos or incorrect values
- Test with default variables to isolate the issue
### 4. Enable Verbose Output
Get more details about what's happening:
```bash
# Run playbook with verbose output
ansible-playbook -vvv your-playbook.yml
# Validate SSH configuration
sudo sshd -t
```
## How to Get Help
### For General Questions
**GitHub Discussions** (Coming Soon)
- General questions about using the role
- "How do I...?" questions
- Configuration advice
- Best practices discussions
Until Discussions are enabled, use the question issue template:
**GitHub Issues** - Use the Question Template
1. Go to [New Issue](https://github.com/welshwandering/ansible-role-openssh_server/issues/new/choose)
2. Select "Question / Discussion"
3. Provide context about what you're trying to do
4. Include your environment details
### For Bug Reports
If you've found a bug in the role:
1. Go to [New Issue](https://github.com/welshwandering/ansible-role-openssh_server/issues/new/choose)
2. Select "Bug Report"
3. Fill out the template completely
4. Include:
- Distribution and version
- OpenSSH version
- Ansible version
- Role version (git commit or tag)
- Relevant role variables
- Error messages
- Steps to reproduce
**Please remove sensitive data** (passwords, keys, IP addresses) from examples!
### For Security Issues
**⚠️ DO NOT use GitHub Issues for security vulnerabilities!**
See [docs/SECURITY.md](SECURITY.md) for how to report security issues privately.
### For Feature Requests
Have an idea for improving the role?
1. Check if it's already requested in [GitHub Issues](https://github.com/welshwandering/ansible-role-openssh_server/issues)
2. Use the [Feature Request template](https://github.com/welshwandering/ansible-role-openssh_server/issues/new/choose)
3. Explain the use case and why it would be valuable
4. Consider contributing the feature yourself (see [CONTRIBUTING.md](CONTRIBUTING.md))
## How to Ask Good Questions
Help us help you! Good questions get faster, better answers.
### Include Key Information
Always include:
- **Distribution and version**: "Debian 12 Bookworm" or "Ubuntu 22.04 Jammy"
- **OpenSSH version**: Output of `ssh -V`
- **Ansible version**: Output of `ansible --version`
- **Role version**: Git commit hash, tag, or "latest from main"
### Provide Context
Explain:
- What you're trying to achieve
- What you expected to happen
- What actually happened
- What you've already tried
### Show Your Work
Include:
- Relevant parts of your playbook (sanitize sensitive data!)
- Role variables you've configured
- Error messages (full text, not screenshots when possible)
- Output from validation: `sudo sshd -t`
### Create a Minimal Example
Reduce your problem to the smallest example that demonstrates the issue:
```yaml
# Good: Minimal example
- hosts: test
roles:
- role: openssh_server
vars:
openssh_password_authentication: false
openssh_port: 2222
```
This is better than posting your entire 500-line playbook!
### Use Code Blocks
Format code and output properly:
````markdown
```yaml
# Your YAML here
```
```bash
# Command output here
```
````
## What NOT to Use GitHub Issues For
Please **do not** use GitHub Issues for:
### Personal Configuration Help
GitHub Issues are for bugs and features in the **role itself**, not debugging your specific infrastructure.
**Instead**:
- Review [docs/TROUBLESHOOTING.md](TROUBLESHOOTING.md)
- Check [docs/EXAMPLES.md](EXAMPLES.md)
- Post a question using the question template (keep it focused on the role)
### OpenSSH Software Issues
This role configures OpenSSH—it doesn't fix bugs in OpenSSH itself.
**Instead**:
- OpenSSH bugs: https://www.openssh.com/report.html
- OpenSSH security: https://www.openssh.com/security.html
### Distribution-Specific Package Issues
We track CVE status, but we don't fix vulnerabilities in OS packages.
**Instead**:
- Debian bugs: https://www.debian.org/Bugs/
- Ubuntu bugs: https://bugs.launchpad.net/ubuntu
- Debian security: https://security-tracker.debian.org/
- Ubuntu security: https://ubuntu.com/security
### Ansible Core Issues
Problems with Ansible itself should go to the Ansible project.
**Instead**: https://github.com/ansible/ansible/issues
## Community Support
### Help Others
If you have experience with this role:
- Answer questions in issues
- Share your configurations (sanitized!)
- Review pull requests
- Improve documentation
Your contributions help build a stronger community!
### Share Your Success
Found a great way to use this role? Let us know:
- Share in discussions (when available)
- Write a blog post and tell us about it
- Contribute an example to [examples/](../examples/)
## Commercial Support
This is an open source hobby project. **No commercial support is available.**
However, you can:
- Hire Ansible consultants who can help with your infrastructure
- Engage security consultants familiar with SSH hardening
- Use this role as-is under the MIT License
## Response Time Expectations
**This is a volunteer-run hobby project.** Please understand:
- Responses will come as maintainer time permits
- There are no guaranteed response times
- Simple questions may get quick answers
- Complex issues may take longer
- Critical security issues will be prioritized
We appreciate your patience!
## Contributing
Want to help improve this project?
- See [docs/CONTRIBUTING.md](CONTRIBUTING.md) for how to contribute
- Review [AGENTS.md](../AGENTS.md) for development guidelines
- Check out [docs/PULL_REQUEST_TEMPLATE.md](PULL_REQUEST_TEMPLATE.md) for PR expectations
## Additional Resources
### SSH Security Resources
- **OpenSSH**: https://www.openssh.com/
- **Mozilla OpenSSH Guidelines**: https://infosec.mozilla.org/guidelines/openssh
- **NIST SP 800-52**: https://csrc.nist.gov/publications/detail/sp/800-52/rev-2/final
### Ansible Resources
- **Ansible Documentation**: https://docs.ansible.com/
- **Ansible Galaxy**: https://galaxy.ansible.com/
- **Best Practices**: https://docs.ansible.com/ansible/latest/tips_tricks/ansible_tips_tricks.html
### Compliance Resources
See [docs/COMPLIANCE.md](COMPLIANCE.md) for links to compliance frameworks and standards.
## Thank You
Thank you for using ansible-role-openssh_server! We're glad to have you in our community.
Remember:
- 📖 Documentation first
- 🔍 Search before asking
- 🎯 Provide details when asking
- 🤝 Help others when you can
- 💚 Be patient and kind
Happy hardening! 🔒
---
*Last updated: 2025-10-05*

View file

@ -0,0 +1,386 @@
# Testing Guide
This document describes the comprehensive testing infrastructure for the OpenSSH server hardening role.
## Overview
Our testing strategy ensures the role works correctly across all 15 supported distributions, from Debian Stretch (OpenSSH 7.4p1) to the latest releases with OpenSSH 10.0p1+.
**✅ macOS Users**: All tests work perfectly on macOS with Docker Desktop! See [TESTING_MACOS.md](TESTING_MACOS.md) for macOS-specific instructions.
## Continuous Integration (GitHub Actions)
### CI Pipeline
The CI pipeline runs on every push to `main`/`develop` branches and all pull requests.
**Workflow:** [`.github/workflows/ci.yml`](../.github/workflows/ci.yml)
### Testing Matrix
#### Lint Job
- **YAML Linting:** `yamllint .`
- **Ansible Linting:** `ansible-lint --profile=production` (strictest profile)
- **Python Version:** 3.11
- **Ansible Version:** 2.15+
#### Molecule Job
Tests across **15 distributions** in parallel:
| Distribution | Docker Image | OpenSSH Version | Feature Level |
|--------------|--------------|-----------------|---------------|
| **Debian 9 (Stretch)** | `debian:stretch` | 7.4p1 | Legacy |
| **Debian 10 (Buster)** | `debian:buster` | 7.9p1 | Legacy |
| **Debian 11 (Bullseye)** | `debian:bullseye` | 8.4p1 | Modern |
| **Debian 12 (Bookworm)** | `debian:bookworm` | 9.2p1 | Modern |
| **Debian 13 (Trixie)** | `debian:trixie` | 10.0p1 | Latest |
| **Debian Sid (Testing)** | `debian:sid` | 10.0p1 | Latest |
| **Ubuntu 16.04 (Xenial)** | `ubuntu:xenial` | 7.2p2 | Legacy |
| **Ubuntu 18.04 (Bionic)** | `ubuntu:bionic` | 7.6p1 | Legacy |
| **Ubuntu 20.04 (Focal)** | `ubuntu:focal` | 8.2p1 | Modern |
| **Ubuntu 22.04 (Jammy)** | `ubuntu:jammy` | 8.9p1 | Modern |
| **Ubuntu 24.04 (Noble)** | `ubuntu:noble` | 9.6p1 | Latest |
| **Ubuntu 24.10 (Oracular)** | `ubuntu:oracular` | 9.7p1 | Latest |
### CI Environment Variables
Each distribution test passes:
- `MOLECULE_DISTRO`: Distribution identifier (e.g., `debian12`, `ubuntu2404`)
- `MOLECULE_IMAGE`: Docker image to use (e.g., `debian:bookworm`, `ubuntu:noble`)
- `MOLECULE_OPENSSH_VERSION`: Expected OpenSSH version (e.g., `9.2p1`, `9.6p1`)
## Molecule Testing
### Test Phases
1. **Dependency:** Install required Ansible collections
2. **Lint:** YAML and Ansible linting (runs in separate job)
3. **Create:** Spin up Docker container for target distribution
4. **Prepare:** Install OpenSSH server and dependencies
5. **Converge:** Apply the openssh_server role
6. **Verify:** Run verification tests
7. **Destroy:** Clean up test container
### Molecule Configuration
**File:** [`molecule/default/molecule.yml`](../molecule/default/molecule.yml)
```yaml
platforms:
- name: "${MOLECULE_DISTRO:-debian12}"
image: "${MOLECULE_IMAGE:-debian:bookworm}"
privileged: true
command: /lib/systemd/systemd
volumes:
- /sys/fs/cgroup:/sys/fs/cgroup:rw
```
The configuration uses environment variables for flexible testing across distributions.
### Converge Phase
**File:** [`molecule/default/converge.yml`](../molecule/default/converge.yml)
1. Updates apt cache
2. Installs `openssh-server` package
3. Applies the `openssh_server` role
### Verification Tests
**File:** [`molecule/default/verify.yml`](../molecule/default/verify.yml)
Comprehensive verification includes:
#### 1. Service Status
- Verifies SSH service is active and running
- Uses systemd to check service state
#### 2. Configuration Validation
- Runs `sshd -t` to validate configuration syntax
- Ensures no syntax errors in generated config
#### 3. Port Availability
- Checks SSH is listening on port 22
- Validates network accessibility
#### 4. Version Verification
- Reports OpenSSH version via `ssh -V`
- Compares with expected version for the distribution
#### 5. Security Hardening
- Verifies key security directives are set:
- `PasswordAuthentication`
- `PermitRootLogin`
- `PubkeyAuthentication`
## Local Testing
### Prerequisites
#### macOS (with Docker Desktop)
```bash
# 1. Install Docker Desktop for Mac
# Download from: https://www.docker.com/products/docker-desktop/
# 2. Install Python dependencies (using Homebrew's Python or system Python)
pip3 install molecule molecule-plugins[docker] ansible-core>=2.15
# 3. Install Ansible collections
ansible-galaxy collection install ansible.posix>=1.5.0
ansible-galaxy collection install community.general>=8.0.0
```
**macOS Notes:**
- ✅ **Fully supported** - All Molecule tests work on macOS with Docker Desktop
- Docker Desktop provides the Docker daemon required for Molecule
- Tests run in Linux containers via Docker Desktop's VM
- Performance may be slower than native Linux due to VM overhead
- No additional configuration needed - just ensure Docker Desktop is running
#### Linux
```bash
# 1. Install Docker
# See: https://docs.docker.com/engine/install/
# 2. Install testing dependencies
pip install molecule molecule-plugins[docker] ansible-core>=2.15
# 3. Install Ansible collections
ansible-galaxy collection install ansible.posix>=1.5.0
ansible-galaxy collection install community.general>=8.0.0
# 4. Add user to docker group (to avoid sudo)
sudo usermod -aG docker $USER
newgrp docker
```
### Run All Tests
```bash
# Run complete test suite (default: Debian 12)
molecule test
# Test specific distribution
MOLECULE_DISTRO=ubuntu2404 \
MOLECULE_IMAGE=ubuntu:noble \
MOLECULE_OPENSSH_VERSION=9.6p1 \
molecule test
```
### Development Workflow
```bash
# Create test environment
molecule create
# Run convergence (apply role)
molecule converge
# Run verification tests
molecule verify
# Login to test container
molecule login
# Destroy test environment
molecule destroy
```
### Test Specific Distributions
```bash
# Debian Bookworm (modern)
MOLECULE_DISTRO=debian12 MOLECULE_IMAGE=debian:bookworm MOLECULE_OPENSSH_VERSION=9.2p1 molecule test
# Ubuntu 24.04 Noble (latest)
MOLECULE_DISTRO=ubuntu2404 MOLECULE_IMAGE=ubuntu:noble MOLECULE_OPENSSH_VERSION=9.6p1 molecule test
# Debian Stretch (legacy - test backwards compatibility)
MOLECULE_DISTRO=debian9 MOLECULE_IMAGE=debian:stretch MOLECULE_OPENSSH_VERSION=7.4p1 molecule test
# Ubuntu 16.04 Xenial (oldest supported)
MOLECULE_DISTRO=ubuntu1604 MOLECULE_IMAGE=ubuntu:xenial MOLECULE_OPENSSH_VERSION=7.2p2 molecule test
```
## Testing Strategy
### Coverage Goals
1. **Distribution Coverage**: All 15 supported distributions
2. **Version Coverage**: OpenSSH 7.2p2 through 10.0p1+
3. **Feature Coverage**: Version-aware capability flags
4. **Security Coverage**: Hardening verification
### Feature Testing
The role's capability flags are tested across versions:
- **Legacy (7.2 - 7.9)**: Basic hardening, limited modern features
- **Modern (8.2 - 9.2)**: FIDO2 support, enhanced logging
- **Latest (9.3+)**: RequiredRSASize, PerSourcePenalties
- **Cutting Edge (9.9+)**: Post-quantum ML-KEM support
### Backwards Compatibility
Testing ensures:
- Older distributions don't fail on unsupported directives
- Capability flags correctly enable/disable features
- Warnings display for EOL distributions
- Graceful degradation on legacy systems
## CI/CD Integration
### Pull Request Checks
All PRs must pass:
1. ✅ YAML linting (yamllint)
2. ✅ Ansible linting (production profile)
3. ✅ Molecule tests on all 15 distributions
### Branch Protection
- `main` branch requires all CI checks to pass
- No PR can be merged with failing tests
- Linting must pass with 0 failures, 0 warnings
### Performance
- Lint job: ~2-3 minutes
- Molecule tests: ~5-10 minutes per distribution (parallel execution)
- Total CI time: ~10-15 minutes with parallelization
## Test Maintenance
### Adding New Distributions
When adding support for a new distribution:
1. **Update CI Matrix** (`.github/workflows/ci.yml`):
```yaml
- distro: ubuntu2504
image: ubuntu:plucky
openssh_version: "9.9p1"
```
2. **Update Documentation**:
- `docs/DISTRIBUTIONS.md` - Add to supported list
- `docs/TESTING.md` - Update test matrix
- `README.md` - Update badges if needed
3. **Test Locally First**:
```bash
MOLECULE_DISTRO=ubuntu2504 \
MOLECULE_IMAGE=ubuntu:plucky \
MOLECULE_OPENSSH_VERSION=9.9p1 \
molecule test
```
4. **Update CHANGELOG**:
```markdown
### Added
- Added support for Ubuntu 25.04 (Plucky) with OpenSSH 9.9p1
```
### Updating OpenSSH Versions
When distributions update OpenSSH versions:
1. Verify new version in distribution repositories
2. Update `openssh_version` in CI matrix
3. Review and update capability flags if needed
4. Update docs/DISTRIBUTIONS.md with new version
5. Run full test suite to verify compatibility
## Troubleshooting
### Common Issues
#### macOS: Docker Desktop Not Running
```bash
# Error: Cannot connect to Docker daemon
# Solution: Ensure Docker Desktop is running
open -a Docker
# Verify Docker is running
docker ps
```
#### macOS: Permission Errors with pip
```bash
# Use user installation to avoid sudo
pip3 install --user molecule molecule-plugins[docker] ansible-core>=2.15
# Or use a virtual environment (recommended)
python3 -m venv venv
source venv/bin/activate
pip install molecule molecule-plugins[docker] ansible-core>=2.15
```
#### macOS: Slow Performance
```bash
# Docker Desktop on macOS runs containers in a VM, which can be slower
# To improve performance:
# 1. Allocate more resources in Docker Desktop preferences
# (Settings → Resources → increase CPUs and Memory)
# 2. Ensure Docker Desktop is using VirtioFS (Settings → General)
# 3. Consider testing only specific distributions instead of all 15
```
#### Linux: Docker Permission Errors
```bash
# Add user to docker group
sudo usermod -aG docker $USER
newgrp docker
```
#### Molecule Not Found
```bash
# Ensure Molecule is installed
pip install --upgrade molecule molecule-plugins[docker]
# On macOS, you may need pip3
pip3 install --upgrade molecule molecule-plugins[docker]
```
#### Systemd in Containers
The role requires systemd for SSH service management. Our Molecule config enables this:
```yaml
privileged: true
command: /lib/systemd/systemd
volumes:
- /sys/fs/cgroup:/sys/fs/cgroup:rw
```
**On macOS**: Docker Desktop supports privileged containers and cgroup mounting, so systemd works correctly.
#### Old Distribution Images
Some older distributions (Debian Stretch, Ubuntu Xenial) may have deprecated mirrors:
- Tests may be slower due to repository access
- Consider skipping EOL distributions in local development
- CI will still test them for compatibility
#### macOS: Platform-Specific Issues
**Issue: "cannot mount /sys/fs/cgroup" errors**
- Solution: This is expected on older Docker Desktop versions. Update to latest Docker Desktop (4.x+)
**Issue: Tests hang during systemd startup**
- Solution: Increase Docker Desktop memory allocation to at least 4GB
- Go to: Docker Desktop → Settings → Resources → Memory
**Issue: IPv6 related warnings**
- Solution: These warnings are harmless and can be ignored on macOS
## Resources
- **Molecule Documentation**: https://molecule.readthedocs.io/
- **GitHub Actions**: https://docs.github.com/en/actions
- **Docker Hub Images**: https://hub.docker.com/
- **Ansible Lint**: https://ansible.readthedocs.io/projects/lint/
---
*Last updated: 2025-10-05*

View file

@ -0,0 +1,424 @@
# Testing on macOS with Docker Desktop
This guide provides macOS-specific instructions for running Molecule tests locally.
## Quick Start (macOS)
### 1. Install Docker Desktop
Download and install Docker Desktop for Mac:
- **URL**: https://www.docker.com/products/docker-desktop/
- **Requirements**: macOS 11+ (Big Sur or later)
- **Architecture**: Supports both Intel and Apple Silicon (M1/M2/M3)
After installation:
1. Open Docker Desktop from Applications
2. Wait for Docker engine to start (whale icon in menu bar should be steady)
3. Verify installation:
```bash
docker ps
# Should show empty list (no containers running)
```
### 2. Install Python Dependencies
Using pip3 (recommended):
```bash
# Install Molecule and dependencies
pip3 install molecule molecule-plugins[docker] ansible-core>=2.15
# Install Ansible collections
ansible-galaxy collection install ansible.posix>=1.5.0
ansible-galaxy collection install community.general>=8.0.0
```
Using virtual environment (alternative):
```bash
# Create virtual environment
python3 -m venv ~/molecule-env
source ~/molecule-env/bin/activate
# Install dependencies
pip install molecule molecule-plugins[docker] ansible-core>=2.15
ansible-galaxy collection install ansible.posix>=1.5.0
ansible-galaxy collection install community.general>=8.0.0
```
### 3. Run Tests
```bash
# Navigate to role directory
cd /path/to/ansible-role-openssh_server
# Run default test (Debian 12)
molecule test
# Test specific distribution
MOLECULE_DISTRO=ubuntu2404 \
MOLECULE_IMAGE=ubuntu:noble \
MOLECULE_OPENSSH_VERSION=9.6p1 \
molecule test
```
## macOS-Specific Configuration
### Docker Desktop Settings
For optimal performance, configure Docker Desktop:
**Settings → Resources:**
- **CPUs**: 4+ cores (8+ recommended for parallel testing)
- **Memory**: 8GB+ (16GB recommended for running multiple tests)
- **Disk**: 64GB+ (container images can be large)
**Settings → General:**
- ✅ Enable "Use VirtioFS" (better file system performance)
- ✅ Enable "Use Rosetta for x86/AMD64 emulation on Apple Silicon" (if on M1/M2/M3)
### Apple Silicon (M1/M2/M3) Notes
Docker Desktop supports ARM64 architecture, but some distribution images may require emulation:
**Native ARM64 (fastest):**
- ✅ Ubuntu 20.04+ (arm64 images available)
- ✅ Debian 11+ (arm64 images available)
**x86/AMD64 Emulation (slower):**
- ⚠️ Older distributions (Debian Stretch, Ubuntu Xenial)
- Uses QEMU emulation via Rosetta or built-in emulation
- Tests will run but may be 2-3x slower
**Running tests on Apple Silicon:**
```bash
# Tests automatically use native ARM64 images when available
molecule test
# Force x86 emulation (if needed for compatibility testing)
docker run --platform linux/amd64 debian:bookworm
```
## Performance Considerations
### Expected Test Duration (macOS)
| System | Single Test | All 15 Distributions (parallel) |
|--------|-------------|----------------------------------|
| Intel Mac (4 cores, 8GB) | 3-5 min | 40-60 min |
| Intel Mac (8 cores, 16GB) | 2-3 min | 20-30 min |
| M1/M2 Mac (8 cores, 16GB) | 2-4 min | 15-25 min |
| M3 Mac (12 cores, 24GB) | 1-2 min | 10-15 min |
**Note**: Times include pulling Docker images on first run. Subsequent runs are faster.
### Optimization Tips
#### 1. Test Only What You Need
```bash
# Instead of testing all 15, test representative samples:
# Test oldest supported (backwards compatibility)
MOLECULE_DISTRO=ubuntu1604 MOLECULE_IMAGE=ubuntu:xenial molecule test
# Test current LTS (most common)
MOLECULE_DISTRO=ubuntu2204 MOLECULE_IMAGE=ubuntu:jammy molecule test
# Test latest (newest features)
MOLECULE_DISTRO=ubuntu2404 MOLECULE_IMAGE=ubuntu:noble molecule test
```
#### 2. Use Development Workflow
```bash
# Create environment once, test multiple times
molecule create
molecule converge # Apply changes
molecule verify # Run tests
# Make code changes...
molecule converge # Re-apply
molecule verify # Re-test
molecule destroy # Clean up when done
```
#### 3. Pre-pull Images
```bash
# Download all images in background before testing
docker pull debian:stretch &
docker pull debian:buster &
docker pull debian:bullseye &
docker pull debian:bookworm &
docker pull ubuntu:xenial &
docker pull ubuntu:bionic &
docker pull ubuntu:focal &
docker pull ubuntu:jammy &
docker pull ubuntu:noble &
wait
```
## Common macOS Issues & Solutions
### Issue: "Cannot connect to Docker daemon"
**Symptoms:**
```
ERROR: Couldn't connect to Docker daemon at unix:///var/run/docker.sock
```
**Solution:**
```bash
# Ensure Docker Desktop is running
open -a Docker
# Wait for startup (watch menu bar icon)
# Try again once whale icon is steady
# Verify Docker is running
docker ps
```
### Issue: "pip3: command not found"
**Symptoms:**
```
zsh: command not found: pip3
```
**Solution:**
```bash
# Install Python 3 via Homebrew
brew install python3
# Verify installation
python3 --version
pip3 --version
# Then install Molecule
pip3 install molecule molecule-plugins[docker]
```
### Issue: Permission Denied on pip Install
**Symptoms:**
```
ERROR: Could not install packages due to an OSError: [Errno 13] Permission denied
```
**Solution:**
```bash
# Use user installation (recommended)
pip3 install --user molecule molecule-plugins[docker] ansible-core>=2.15
# Or use virtual environment
python3 -m venv ~/molecule-env
source ~/molecule-env/bin/activate
pip install molecule molecule-plugins[docker] ansible-core>=2.15
```
### Issue: Slow Test Performance
**Symptoms:**
- Tests take 5-10 minutes each
- High CPU usage during tests
**Solutions:**
1. **Increase Docker Resources:**
- Docker Desktop → Settings → Resources
- Increase CPUs to 8+ and Memory to 16GB+
2. **Enable VirtioFS:**
- Docker Desktop → Settings → General
- ✅ Enable "Use VirtioFS"
3. **On Apple Silicon - Enable Rosetta:**
- Docker Desktop → Settings → General (Features in development)
- ✅ Enable "Use Rosetta for x86/AMD64 emulation"
4. **Use Native ARM64 Images:**
```bash
# Prefer newer distributions with ARM support
MOLECULE_DISTRO=ubuntu2404 molecule test # Fast (native ARM)
MOLECULE_DISTRO=ubuntu1604 molecule test # Slower (x86 emulation)
```
### Issue: Container Fails to Start with systemd
**Symptoms:**
```
Failed to create bus connection: No such file or directory
System has not been booted with systemd as init system
```
**Solution:**
```bash
# This usually means Docker Desktop needs updating
# Update to Docker Desktop 4.0+ which supports systemd in containers
# Check Docker Desktop version
docker --version
# Update via Docker Desktop → Check for Updates
# Or download latest from: https://www.docker.com/products/docker-desktop/
```
### Issue: Port Already in Use
**Symptoms:**
```
Error: bind: address already in use
```
**Solution:**
```bash
# Find process using port 22 (SSH)
sudo lsof -i :22
# Kill existing containers
docker ps -a
docker rm -f $(docker ps -aq)
# Or stop your local SSH service temporarily
sudo launchctl unload /System/Library/LaunchDaemons/ssh.plist
```
## Development Tips for macOS
### Use direnv for Environment Variables
Install direnv to automatically load test configuration:
```bash
# Install direnv
brew install direnv
# Add to ~/.zshrc (for zsh)
eval "$(direnv hook zsh)"
# Create .envrc in role directory
cat > .envrc <<EOF
export MOLECULE_DISTRO=ubuntu2404
export MOLECULE_IMAGE=ubuntu:noble
export MOLECULE_OPENSSH_VERSION=9.6p1
EOF
# Allow direnv
direnv allow .
# Now molecule commands use these variables automatically
molecule test
```
### Use iTerm2 Split Panes
Run multiple tests in parallel:
1. Open iTerm2
2. Split pane horizontally (Cmd+D)
3. Split each pane vertically (Cmd+Shift+D)
4. Run different distribution tests in each pane
### Cleanup Docker Resources
Docker can consume significant disk space:
```bash
# Remove all stopped containers
docker container prune -f
# Remove all unused images
docker image prune -a -f
# Remove all unused volumes
docker volume prune -f
# Nuclear option - remove everything
docker system prune -a --volumes -f
# Check disk usage
docker system df
```
## Testing Workflow Example
Complete workflow for macOS development:
```bash
# 1. Setup (one time)
brew install docker # If using Colima instead of Docker Desktop
pip3 install --user molecule molecule-plugins[docker] ansible-core
ansible-galaxy collection install ansible.posix community.general
# 2. Start Docker Desktop
open -a Docker
sleep 10 # Wait for startup
# 3. Pull common images (optional, for speed)
docker pull debian:bookworm
docker pull ubuntu:noble
# 4. Run quick test on modern distribution
MOLECULE_DISTRO=ubuntu2404 MOLECULE_IMAGE=ubuntu:noble molecule test
# 5. Development cycle
molecule create
molecule converge
# Edit role files...
molecule converge # Re-apply changes
molecule verify # Verify changes
molecule destroy # Cleanup
# 6. Before PR - test key distributions
for distro in debian9:stretch:7.4p1 ubuntu2004:focal:8.2p1 ubuntu2404:noble:9.6p1; do
IFS=: read -r name image version <<< "$distro"
echo "Testing $name..."
MOLECULE_DISTRO=$name MOLECULE_IMAGE=$image MOLECULE_OPENSSH_VERSION=$version molecule test
done
```
## Alternative: Colima (Lightweight Docker)
For a lighter alternative to Docker Desktop:
```bash
# Install Colima (Docker Desktop alternative)
brew install colima docker
# Start Colima with sufficient resources
colima start --cpu 8 --memory 16
# Use Molecule as normal
molecule test
# Stop Colima when done
colima stop
```
**Colima Benefits:**
- ✅ Lighter weight than Docker Desktop
- ✅ Free for all use cases
- ✅ Better resource management
- ✅ CLI-focused workflow
**Colima Limitations:**
- ❌ No GUI
- ❌ Requires manual resource configuration
- ❌ May need additional setup for systemd
## Summary
✅ **Molecule tests work perfectly on macOS with Docker Desktop**
- All 15 distributions are supported
- Performance is good on modern Macs
- No special configuration needed beyond Docker Desktop installation
- Apple Silicon (M1/M2/M3) is fully supported with native ARM64 images
📌 **Key Points:**
1. Install Docker Desktop first
2. Use pip3 for Python dependencies
3. Allocate sufficient resources in Docker Desktop settings
4. On Apple Silicon, newer distributions run faster (native ARM64)
5. Pre-pull images for faster subsequent runs
🚀 **Ready to test?**
```bash
molecule test
```
---
*Last updated: 2025-10-05*

View file

@ -0,0 +1,104 @@
# macOS Testing Limitation and Solution
## Current Status
The Molecule tests as configured for CI (using base Debian/Ubuntu images with systemd) **do not work out-of-the-box on macOS** due to the following issues:
1. **Base images lack systemd**: `debian:bookworm` and `ubuntu:noble` don't include systemd
2. **Base images lack sudo**: Required for Ansible `become` operations
3. **systemd in containers**: Requires special Docker configuration that base images don't have
## Why This Works in CI but Not Locally
- **GitHub Actions CI**: Uses systemd-enabled container images or builds custom images with systemd
- **macOS Docker Desktop**: Base images don't have systemd pre-configured
## Solutions for macOS Testing
### Option 1: Use Pre-built systemd Images (Recommended)
Use Docker images that already have systemd enabled:
```bash
# Install in virtual environment
python3 -m venv .venv
source .venv/bin/activate
pip install molecule 'molecule-plugins[docker]' ansible-core
# Use geerlingguy's systemd-enabled images
MOLECULE_DISTRO=debian12 \
MOLECULE_IMAGE=geerlingguy/docker-debian12-ansible:latest \
molecule test
# Or Ubuntu
MOLECULE_DISTRO=ubuntu2404 \
MOLECULE_IMAGE=geerlingguy/docker-ubuntu2404-ansible:latest \
molecule test
```
### Option 2: Build Custom Systemd Images
Create a custom Dockerfile that adds systemd:
```dockerfile
# Dockerfile.debian
FROM debian:bookworm
RUN apt-get update && \
apt-get install -y systemd sudo python3 && \
rm -rf /var/lib/apt/lists/*
CMD ["/lib/systemd/systemd"]
```
Then build and use:
```bash
docker build -t debian-systemd:bookworm -f Dockerfile.debian .
MOLECULE_DISTRO=debian12 \
MOLECULE_IMAGE=debian-systemd:bookworm \
molecule test
```
### Option 3: Simplified Testing Without systemd
For quick validation without full systemd:
1. Test only configuration generation (not service management)
2. Use `molecule converge` instead of `molecule test`
3. Manually verify `/etc/ssh/sshd_config` is generated correctly
```bash
# Run role application only
molecule converge
# Verify configuration
molecule verify
# Cleanup
molecule destroy
```
## Recommendation
**For local macOS development**: Use Option 1 with pre-built images from geerlingguy or similar.
**For CI**: Continue using base images with systemd configuration (already working).
## Updating CI for macOS Compatibility
To make CI tests also work locally on macOS, we would need to:
1. Add logic to detect local vs CI environment
2. Use different images based on environment
3. Or build custom systemd images in CI
This adds complexity, so the current approach (optimized for CI) is acceptable with documented workarounds for local testing.
## Testing Impact
- ✅ **CI Tests**: Fully working with systemd verification
- ⚠️ **macOS Local Tests**: Require pre-built systemd images or simplified testing
- ✅ **Role Functionality**: Not affected - role works correctly when deployed
---
*Last updated: 2025-10-05*

View file

@ -0,0 +1,52 @@
# Troubleshooting Guide
## Post-Installation
### Add SSH Keys
```bash
# On your local machine
ssh-copy-id user@server
# Or manually
cat ~/.ssh/id_ed25519.pub | ssh user@server "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
```
### Test Configuration
```bash
# Validate config
sudo sshd -t
# Check service status
sudo systemctl status ssh
# View logs
sudo journalctl -u ssh -f
```
## Troubleshooting
### Locked Out?
If you've locked yourself out:
1. Access via console (physical/IPMI/cloud console)
2. Edit `/etc/ssh/sshd_config`
3. Temporarily enable: `PasswordAuthentication yes`
4. Restart: `sudo systemctl restart ssh`
5. Fix your SSH keys
6. Re-disable password auth
### Connection Refused?
```bash
# Check if SSH is running
sudo systemctl status ssh
# Check if port is open
sudo ss -tulpn | grep ssh
# Check firewall
sudo ufw status
```

View file

@ -0,0 +1,30 @@
---
#
# Basic SSH Hardening
#
# This playbook applies basic SSH hardening suitable for most environments.
# - Disables password authentication (key-based only)
# - Restricts root login to key-based auth
# - Enables modern cryptography
# - Sets reasonable login limits
#
- name: Basic SSH hardening
hosts: all
become: true
roles:
- role: welshwandering.openssh_server
vars:
# Disable password authentication (key-based only)
openssh_password_authentication: false
# Allow root login with keys only (no passwords)
openssh_permit_root_login: 'no'
# Login attempt limits
openssh_max_auth_tries: 3
openssh_login_grace_time: "30s"
# Enable verbose logging for security monitoring
openssh_log_level: "VERBOSE"

View file

@ -0,0 +1,48 @@
---
#
# FedRAMP Moderate & High Baseline SSH Configuration
#
# Implements NIST SP 800-53 Rev 5 controls for FedRAMP Moderate and High:
# - AC-17 (Remote Access)
# - IA-2 (Identification and Authentication)
# - SC-8 (Transmission Confidentiality and Integrity)
# - SC-13 (Cryptographic Protection)
# - AU-2 (Audit Events)
# - FIPS 140-2 compatible algorithms
#
# Baselines: Moderate (325 controls) and High (421 controls)
#
- name: FedRAMP Moderate & High baseline SSH
hosts: fedramp_systems
become: true
roles:
- role: welshwandering.openssh_server
vars:
# AC-17: Remote Access Control
# IA-2: Identification and Authentication (Multi-factor)
openssh_password_authentication: false
openssh_permit_root_login: "no"
# SC-13: Cryptographic Protection (FIPS 140-2 compatible)
# Defaults use: AES, ChaCha20, Curve25519, DH Group 16+
# Note: Full FIPS 140-2 requires OS-level FIPS mode
# Enhanced RSA key size (NSA/CISA requirement)
openssh_required_rsa_size: 3072
# AU-2: Audit Events - Comprehensive logging
openssh_enable_verbose_logging: true
openssh_log_level: "VERBOSE"
# Session controls
openssh_max_auth_tries: 3
openssh_login_grace_time: "60s"
# Session re-keying (CCCS ITSP.40.062 also requires this)
openssh_rekey_limit: "512M 30m" # Re-key every 512MB or 30 minutes
# Client timeout for idle sessions (AC-12)
openssh_client_alive_interval: 300
openssh_client_alive_count_max: 0 # Disconnect immediately on timeout

View file

@ -0,0 +1,86 @@
---
#
# FIDO2/WebAuthn Hardware Security Keys
#
# Enables FIDO2 hardware security key authentication (YubiKey, etc.)
# Requires OpenSSH 8.2+ on both client and server
#
# Hardware security keys provide phishing-resistant authentication
# and are recommended by:
# - NIST SP 800-63B (AAL3)
# - CISA Zero Trust guidance
# - NSA Cybersecurity Advisory
#
- name: FIDO2 hardware security keys
hosts: admin_workstations
become: true
roles:
- role: welshwandering.openssh_server
vars:
# Enable FIDO2/WebAuthn security key support
openssh_enable_security_keys: true
# Disable password authentication (keys only)
openssh_password_authentication: false
# Accepted key types (prioritize security keys)
openssh_pubkey_accepted_key_types:
- sk-ssh-ed25519@openssh.com # FIDO2 Ed25519 (preferred)
- sk-ecdsa-sha2-nistp256@openssh.com # FIDO2 ECDSA
- ssh-ed25519 # Standard Ed25519 (fallback)
- rsa-sha2-512 # RSA (fallback)
# Host key algorithms
openssh_host_key_algorithms:
- sk-ssh-ed25519-cert-v01@openssh.com
- ssh-ed25519-cert-v01@openssh.com
- ssh-ed25519
- rsa-sha2-512
# CA signature algorithms (if using SSH certificates)
openssh_ca_signature_algorithms:
- sk-ssh-ed25519@openssh.com
- ssh-ed25519
- rsa-sha2-512
# Standard security settings
openssh_permit_root_login: "prohibit-password"
openssh_max_auth_tries: 3
openssh_login_grace_time: "30s"
post_tasks:
- name: Display FIDO2 setup instructions
ansible.builtin.debug:
msg: |
FIDO2 Hardware Security Keys Enabled
Client Setup:
1. Generate a security key credential:
ssh-keygen -t ed25519-sk -C "user@host"
2. For keys with PIN protection:
ssh-keygen -t ed25519-sk -O verify-required -C "user@host"
3. For keys requiring user presence (touch):
ssh-keygen -t ed25519-sk -O resident -C "user@host"
4. Copy public key to server:
ssh-copy-id -i ~/.ssh/id_ed25519_sk.pub user@{{ inventory_hostname }}
5. Test connection:
ssh user@{{ inventory_hostname }}
(You'll need to touch your security key)
Supported Devices:
- YubiKey 5 Series
- YubiKey Security Key Series
- Feitian ePass FIDO
- SoloKeys
- Any FIDO2/U2F compatible device
Requirements:
- OpenSSH 8.2+ on both client and server
- libfido2 library on client
- Physical FIDO2-compatible security key

View file

@ -0,0 +1,80 @@
---
#
# Maximum Security SSH Configuration
#
# Implements the highest security posture suitable for:
# - Critical infrastructure
# - High-value targets
# - Defense against sophisticated attacks
#
# Features:
# - All password authentication disabled
# - Root login completely disabled
# - All forwarding disabled
# - Per-source rate limiting (9.8+)
# - Aggressive session re-keying
# - Enhanced forensic logging
#
- name: Maximum security hardening
hosts: high_security_servers
become: true
roles:
- role: welshwandering.openssh_server
vars:
# Authentication hardening
openssh_password_authentication: false
openssh_permit_root_login: "no" # Completely disable root SSH
openssh_challenge_response_auth: false
# Rate limiting and attack mitigation (OpenSSH 9.8+)
openssh_enable_persourcepenalties: true
openssh_persource_authfail_penalty: "10s" # Aggressive penalty
openssh_persource_maxstartups: "5:30:10" # Very restrictive
# Disable all forwarding (prevent lateral movement)
openssh_disable_forwarding_comprehensive: true
openssh_x11_forwarding: false
# Restrict to strongest cryptography only
openssh_ciphers:
- chacha20-poly1305@openssh.com
- aes256-gcm@openssh.com
openssh_kex_algorithms:
- curve25519-sha256
openssh_macs:
- hmac-sha2-512-etm@openssh.com
# Minimum RSA key size
openssh_required_rsa_size: 4096 # Maximum strength (Exceeds NIST/CNSA 3072-bit requirement)
# Aggressive session limits
openssh_max_auth_tries: 2 # (Exceeds PCI DSS 8.3.6 limit of 6)
openssh_login_grace_time: "20s"
openssh_max_sessions: 5
# Aggressive session re-keying
openssh_rekey_limit: "512M 30m"
# Client timeout
openssh_client_alive_interval: 180 # 3 minutes (Exceeds PCI DSS 8.2.8 / FedRAMP AC-12 15-min requirement)
openssh_client_alive_count_max: 1 # Disconnect after 6 minutes idle
# Enhanced forensic logging
openssh_enable_verbose_logging: true
openssh_log_level: "VERBOSE"
openssh_log_verbose_subsystems:
- "kex.c:*"
- "key.c:*"
- "auth*.c:*"
- "packet.c:*"
# Strict user access control
openssh_allow_groups:
- security-admins
# Explicitly deny risky users
openssh_deny_users:
- root
- admin
- test

View file

@ -0,0 +1,47 @@
---
#
# PCI DSS 4.0 Compliant SSH Configuration
#
# Meets PCI DSS requirements for secure remote access:
# - Multi-factor authentication support (key + passphrase)
# - Strong encryption (AES-256, ChaCha20)
# - Automatic session timeout
# - Comprehensive audit logging
# - Session re-keying
#
# PCI DSS 4.0 compliance deadline: March 31, 2025
#
- name: PCI DSS 4.0 compliant SSH
hosts: pci_scope
become: true
roles:
- role: welshwandering.openssh_server
vars:
# Requirements 8.4.2 / 8.4.3: Multi-factor authentication
openssh_password_authentication: false # Forces key-based (factor 1)
# Users must use passphrase-protected keys (factor 2)
# Requirement 8.3.6: Account Lockout
openssh_max_auth_tries: 3
openssh_login_grace_time: "30s"
# Requirement 10: Comprehensive logging
openssh_enable_verbose_logging: true
openssh_log_level: "VERBOSE"
# Requirement 4.2.1: Strong cryptography
# (defaults already meet PCI DSS: AES-256, ChaCha20)
# Requirement 8.2.8: Idle Session Timeout
openssh_client_alive_interval: 300 # 5-minute timeout check
openssh_client_alive_count_max: 2 # Auto-disconnect after 10 minutes idle
# Session re-keying for long-running sessions
openssh_rekey_limit: "1G 1h"
# Restrict access to authorized users only
openssh_allow_groups:
- pci-admins
- pci-operators

View file

@ -0,0 +1,9 @@
---
# Copyright (c) 2025 Gravitino LLC
# MIT License
- name: restart openssh
ansible.builtin.systemd:
name: "{{ 'sshd' if ansible_os_family == 'RedHat' else 'ssh' }}"
state: restarted
become: true

View file

@ -0,0 +1,68 @@
---
galaxy_info:
role_name: openssh_server
namespace: welshwandering
author: Gravitino LLC
description: |
Comprehensive OpenSSH server hardening for Debian, Ubuntu, and Rocky Linux systems with support for
16 compliance frameworks (PCI DSS, HIPAA, FedRAMP, FISMA, SOC 2, GDPR, ISO 27001+),
extensive CVE tracking, and version-aware capability detection across 17 distributions.
Features:
- Comprehensive security hardening with defense-in-depth
- 20+ CVE mitigations with distribution-specific patch tracking
- Post-quantum cryptography (ML-KEM) support
- FIDO2/WebAuthn hardware security key authentication
- Automatic version detection and capability flags
- Mozilla Modern Profile + OpenSSH 10.0 cryptography preferences
license: MIT
min_ansible_version: "2.15"
platforms:
- name: Debian
versions:
- stretch
- buster
- bullseye
- bookworm
- trixie
- name: Ubuntu
versions:
- xenial
- bionic
- focal
- jammy
- noble
- name: EL
versions:
- "8"
- "9"
- "10"
- name: Rocky
versions:
- "8"
- "9"
- "10"
- name: Fedora
versions:
- "43"
galaxy_tags:
- security
- ssh
- openssh
- hardening
- compliance
- pci-dss
- hipaa
- fedramp
- fips
- gdpr
- sox
- soc2
- infrastructure
- system
- networking
dependencies: []

View file

@ -0,0 +1,26 @@
---
- name: Converge
hosts: all
become: true
pre_tasks:
- name: Update apt cache (Debian/Ubuntu)
ansible.builtin.apt:
update_cache: true
cache_valid_time: 3600
when: ansible_os_family == 'Debian'
- name: Install OpenSSH server
ansible.builtin.apt:
name: openssh-server
state: present
when: ansible_os_family == 'Debian'
- name: Create privilege separation directory
ansible.builtin.file:
path: /run/sshd
state: directory
mode: '0755'
roles:
- role: ansible-role-openssh_server

View file

@ -0,0 +1,72 @@
---
dependency:
name: galaxy
driver:
name: docker
platforms:
- name: "${MOLECULE_DISTRO:-debian12}"
image: "${MOLECULE_IMAGE:-geerlingguy/docker-debian12-ansible:latest}"
pre_build_image: true
privileged: true
command: "${MOLECULE_COMMAND}"
volumes:
- /sys/fs/cgroup:/sys/fs/cgroup:ro
cgroupns_mode: host
privileged: true
security_opts:
- seccomp=unconfined
tmpfs:
- /run
- /run/lock
- /tmp
provisioner:
name: ansible
options:
diff: true
v: 1
config_options:
defaults:
roles_path: ${MOLECULE_PROJECT_DIRECTORY}/../
inventory:
host_vars:
"${MOLECULE_DISTRO:-debian12}":
openssh_expected_version: "${MOLECULE_OPENSSH_VERSION:-9.2p1}"
debian13:
openssh_expected_version: "9.6p1"
rocky8:
openssh_expected_version: "8.0p1"
ansible_user: root
ansible_python_interpreter: /usr/bin/python3.9
debian11:
openssh_expected_version: "8.4p1"
ansible_user: root
ubuntu2004:
openssh_expected_version: "8.2p1"
ansible_user: root
rocky10:
openssh_expected_version: "9.9"
ansible_user: root
fedora43:
openssh_expected_version: "9.9"
ansible_user: root
debian12:
openssh_expected_version: "9.2p1"
ansible_user: root
debian13:
openssh_expected_version: "9.6p1"
ansible_user: root
ubuntu2204:
openssh_expected_version: "8.9p1"
ansible_user: root
ubuntu2404:
openssh_expected_version: "9.6p1"
ansible_user: root
rocky9:
openssh_expected_version: "8.7p1"
ansible_user: root
verifier:
name: ansible

View file

@ -0,0 +1,15 @@
---
- name: Prepare
hosts: all
gather_facts: false
tasks:
- name: Check for Rocky Linux 8
ansible.builtin.raw: grep -q "Rocky Linux 8" /etc/os-release
register: is_rocky8
changed_when: false
failed_when: false
- name: Install Python 3.9 (Rocky 8)
ansible.builtin.raw: dnf install -y python39
when: is_rocky8.rc == 0
changed_when: true

View file

@ -0,0 +1,67 @@
---
- name: Verify
hosts: all
become: true
tasks:
- name: Check SSH service status
ansible.builtin.systemd:
name: ssh
register: ssh_service
failed_when: false
- name: Display SSH service status
ansible.builtin.debug:
msg: "SSH service state: {{ ssh_service.status.ActiveState | default('unknown') }}"
- name: Validate SSH configuration syntax
ansible.builtin.command: sshd -t
changed_when: false
register: sshd_test
- name: Verify SSH config is valid
ansible.builtin.assert:
that:
- sshd_test.rc == 0
fail_msg: "SSH configuration has errors"
success_msg: "SSH configuration is valid"
- name: Get OpenSSH version
ansible.builtin.command: ssh -V
changed_when: false
register: ssh_version_output
failed_when: false
- name: Display OpenSSH version
ansible.builtin.debug:
msg: "OpenSSH version: {{ ssh_version_output.stderr | default('unknown') }}"
- name: Check sshd_config exists
ansible.builtin.stat:
path: /etc/ssh/sshd_config
register: sshd_config_file
- name: Verify sshd_config was created
ansible.builtin.assert:
that:
- sshd_config_file.stat.exists
fail_msg: "SSH configuration file not found"
success_msg: "SSH configuration file exists"
- name: Check sshd_config for hardening
ansible.builtin.shell: |
set -o pipefail
grep -E '^(PasswordAuthentication|PermitRootLogin|PubkeyAuthentication)' /etc/ssh/sshd_config || true
changed_when: false
register: ssh_hardening
- name: Display hardening configuration
ansible.builtin.debug:
msg: "{{ ssh_hardening.stdout_lines }}"
- name: Verify key hardening settings
ansible.builtin.assert:
that:
- "'PasswordAuthentication' in ssh_hardening.stdout"
- "'PermitRootLogin' in ssh_hardening.stdout"
fail_msg: "Expected hardening settings not found"
success_msg: "Hardening settings are configured"

View file

@ -0,0 +1,257 @@
---
# Copyright (c) 2025 Gravitino LLC
# MIT License
- name: Detect distribution type
ansible.builtin.set_fact:
is_ubuntu: "{{ ansible_distribution == 'Ubuntu' }}"
is_debian: "{{ ansible_distribution == 'Debian' }}"
is_rocky: "{{ ansible_distribution == 'Rocky' }}"
is_redhat: "{{ ansible_os_family == 'RedHat' }}"
ubuntu_version: "{{ ansible_distribution_version if ansible_distribution == 'Ubuntu' else '' }}"
debian_version: "{{ ansible_distribution_major_version if ansible_distribution == 'Debian' else '' }}"
tags:
- openssh
- facts
- name: Display Ubuntu ESM notice for older LTS versions
ansible.builtin.debug:
msg:
- "WARNING: Ubuntu {{ ubuntu_version }} is in Extended Security Maintenance (ESM)."
- "Consider upgrading to a newer LTS or enabling Ubuntu Pro for continued security updates."
- "ESM support for {{ ubuntu_version }} ends in {{ '2026' if ubuntu_version == '16.04' else '2028' }}."
when:
- is_ubuntu
- ubuntu_version in ['16.04', '18.04']
tags:
- openssh
- security
- name: Display Ubuntu non-LTS short lifecycle notice
ansible.builtin.debug:
msg:
- "INFO: Ubuntu {{ ubuntu_version }} is a non-LTS release with a 9-month support window."
- "This release will reach end-of-life and stop receiving security updates."
- "For production use, we recommend upgrading to the latest Ubuntu LTS release."
when:
- is_ubuntu
- ubuntu_version in ['24.10', '25.04', '25.10']
tags:
- openssh
- security
- name: Display Debian EOL warning for old-old-stable
ansible.builtin.debug:
msg:
- "WARNING: Debian {{ debian_version }} ({{ ansible_distribution_release }}) may be past EOL or in LTS."
- "OpenSSH {{ openssh_version | default('unknown') }} has limited modern security features."
- "Consider upgrading to Debian Bullseye (11) or newer for better security."
when:
- is_debian
- debian_version | int < 11
tags:
- openssh
- security
- name: Install OpenSSH server (Debian/Ubuntu)
ansible.builtin.apt:
name: openssh-server
state: "{{ openssh_server_state }}"
update_cache: true
cache_valid_time: 3600
become: true
when: is_debian or is_ubuntu
tags:
- openssh
- packages
- name: Install OpenSSH server (RedHat/Rocky)
ansible.builtin.dnf:
name: openssh-server
state: "{{ openssh_server_state }}"
update_cache: true
become: true
when: is_redhat
tags:
- openssh
- packages
- name: Generate SSH host keys (RedHat/Rocky/Fedora)
ansible.builtin.command: ssh-keygen -A
when: is_redhat
changed_when: false
become: true
tags:
- openssh
- init
- name: Detect OpenSSH version
ansible.builtin.command: ssh -V
register: openssh_version_output
changed_when: false
failed_when: false
tags:
- openssh
- facts
- name: Parse OpenSSH version number
ansible.builtin.set_fact:
openssh_version_string: "{{ openssh_version_output.stderr | regex_search('OpenSSH_([0-9]+\\.[0-9]+)', '\\1') | first }}"
when: openssh_version_output.rc == 0
tags:
- openssh
- facts
- name: Set OpenSSH version as float for comparison
ansible.builtin.set_fact:
openssh_version: "{{ openssh_version_string | float }}"
when: openssh_version_string is defined
tags:
- openssh
- facts
- name: Set OpenSSH capability flags
ansible.builtin.set_fact:
# Core capabilities for backwards compatibility
openssh_has_disable_forwarding: "{{ openssh_version is defined and openssh_version >= 7.4 }}"
openssh_has_ca_signature_algorithms: "{{ openssh_version is defined and openssh_version >= 7.9 }}"
openssh_has_fido2: "{{ openssh_version is defined and openssh_version >= 8.2 }}"
openssh_has_include: "{{ openssh_version is defined and openssh_version >= 8.2 }}"
openssh_has_log_verbose: "{{ openssh_version is defined and openssh_version >= 8.5 }}"
openssh_has_required_rsa_size: "{{ openssh_version is defined and openssh_version >= 9.3 }}"
openssh_has_persourcepenalties: "{{ openssh_version is defined and openssh_version >= 9.8 }}"
openssh_has_mlkem: "{{ openssh_version is defined and openssh_version >= 9.9 }}"
# Algorithm support flags
openssh_has_rsa_sha2: "{{ openssh_version is defined and openssh_version >= 7.2 }}"
openssh_has_modern_kex: "{{ openssh_version is defined and openssh_version >= 7.4 }}"
# Security restriction flags
openssh_blocks_dsa_ca: "{{ openssh_version is defined and openssh_version >= 7.9 }}"
openssh_removes_dsa: "{{ openssh_version is defined and openssh_version >= 9.6 }}"
openssh_dh_disabled_default: "{{ openssh_version is defined and openssh_version >= 10.0 }}"
tags:
- openssh
- facts
- name: Filter unsupported algorithms for older OpenSSH versions
ansible.builtin.set_fact:
openssh_host_key_algorithms: "{{ openssh_host_key_algorithms | reject('match', '^sk-') | list }}"
openssh_pubkey_accepted_key_types: "{{ openssh_pubkey_accepted_key_types | reject('match', '^sk-') | list }}"
openssh_ca_signature_algorithms: "{{ openssh_ca_signature_algorithms | reject('match', '^sk-') | list }}"
when:
- openssh_version is defined
- openssh_version < 8.2
tags:
- openssh
- facts
- name: Display OpenSSH version and capabilities
ansible.builtin.debug:
msg:
- "OpenSSH version: {{ openssh_version | default('unknown') }}"
- "Distribution: {{ ansible_distribution }} {{ ansible_distribution_version }}"
- "Core capabilities:"
- " - DisableForwarding: {{ openssh_has_disable_forwarding | default(false) }}"
- " - CASignatureAlgorithms: {{ openssh_has_ca_signature_algorithms | default(false) }}"
- " - FIDO2 support: {{ openssh_has_fido2 | default(false) }}"
- " - Include directive: {{ openssh_has_include | default(false) }}"
- "Advanced capabilities:"
- " - LogVerbose: {{ openssh_has_log_verbose | default(false) }}"
- " - RequiredRSASize: {{ openssh_has_required_rsa_size | default(false) }}"
- " - PerSourcePenalties: {{ openssh_has_persourcepenalties | default(false) }}"
- " - ML-KEM (Post-Quantum): {{ openssh_has_mlkem | default(false) }}"
when: openssh_version is defined
tags:
- openssh
- facts
- name: Verify moduli file has strong DH groups (3072-bit minimum)
ansible.builtin.shell: |
set -o pipefail
awk '$5 >= 3071' /etc/ssh/moduli > /etc/ssh/moduli.tmp
if [ -s /etc/ssh/moduli.tmp ]; then
mv /etc/ssh/moduli.tmp /etc/ssh/moduli
else
rm -f /etc/ssh/moduli.tmp
fi
args:
executable: /bin/bash
become: true
when: openssh_verify_moduli | default(true)
changed_when: false
tags:
- openssh
- security
- hardening
- name: Validate host key strengths
ansible.builtin.shell: |
set -o pipefail
for key in {{ openssh_host_keys | join(' ') }}; do
if [ -f "${key}" ]; then
if [[ "${key}" == *rsa* ]]; then
bits=$(ssh-keygen -lf "${key}" | awk '{print $1}')
if [ "${bits}" -lt 3072 ]; then
echo "WARNING: ${key} is only ${bits} bits (minimum 3072 recommended)"
fi
fi
fi
done
args:
executable: /bin/bash
become: true
register: hostkey_validation
changed_when: false
failed_when: false
tags:
- openssh
- security
- validation
- name: Display host key validation results
ansible.builtin.debug:
msg: "{{ hostkey_validation.stdout_lines }}"
when:
- hostkey_validation.stdout_lines is defined
- hostkey_validation.stdout_lines | length > 0
tags:
- openssh
- security
- name: Configure OpenSSH server
ansible.builtin.template:
src: sshd_config.j2
dest: /etc/ssh/sshd_config
owner: root
group: root
mode: "0644"
validate: /usr/sbin/sshd -t -f %s
backup: true
become: true
notify: restart openssh
tags:
- openssh
- configuration
- name: Ensure SSH directory exists for root
ansible.builtin.file:
path: /root/.ssh
state: directory
owner: root
group: root
mode: "0700"
become: true
when: openssh_permit_root_login != "no"
tags:
- openssh
- security
- name: Enable and start OpenSSH service
ansible.builtin.systemd:
name: "{{ 'sshd' if is_redhat else 'ssh' }}"
enabled: "{{ openssh_service_enabled }}"
state: "{{ openssh_service_state }}"
daemon_reload: true
become: true
tags:
- openssh
- service

View file

@ -0,0 +1,158 @@
# OpenSSH Server Configuration
# Managed by Ansible
# DO NOT EDIT MANUALLY
# Network
Port {{ openssh_port }}
{% for address in openssh_listen_addresses | sort %}
ListenAddress {{ address }}
{% endfor %}
# Protocol (deprecated directive in newer OpenSSH, kept for compatibility)
{% if openssh_version is defined and openssh_version < 7.4 %}
Protocol {{ openssh_protocol }}
{% endif %}
# Host Keys
{% for key in openssh_host_keys %}
HostKey {{ key }}
{% endfor %}
# Cryptography (Mozilla Modern Profile + Version-Specific Enhancements)
Ciphers {{ openssh_ciphers | join(',') }}
{% if openssh_has_mlkem | default(false) and openssh_enable_mlkem %}
# ML-KEM Post-Quantum KEX (OpenSSH 9.9+)
KexAlgorithms mlkem768x25519-sha256,{{ openssh_kex_algorithms | join(',') }}
{% else %}
KexAlgorithms {{ openssh_kex_algorithms | join(',') }}
{% endif %}
MACs {{ openssh_macs | join(',') }}
# Key Types and Algorithms
{% if openssh_enable_security_keys %}
PubkeyAcceptedKeyTypes {{ openssh_pubkey_accepted_key_types | join(',') }}
{% endif %}
{% if openssh_host_key_algorithms | length > 0 %}
HostKeyAlgorithms {{ openssh_host_key_algorithms | join(',') }}
{% endif %}
{% if openssh_enable_ca and openssh_ca_signature_algorithms | length > 0 and openssh_has_ca_signature_algorithms | default(false) %}
CASignatureAlgorithms {{ openssh_ca_signature_algorithms | join(',') }}
{% endif %}
# RSA Key Size Requirements (OpenSSH 9.3+, NSA/CISA Compliance)
{% if openssh_has_required_rsa_size | default(false) %}
RequiredRSASize {{ openssh_required_rsa_size }}
{% endif %}
# Authentication
PermitRootLogin {{ openssh_permit_root_login }}
PubkeyAuthentication {{ 'yes' if openssh_pubkey_authentication else 'no' }}
PasswordAuthentication {{ 'yes' if openssh_password_authentication else 'no' }}
PermitEmptyPasswords {{ 'yes' if openssh_permit_empty_passwords else 'no' }}
ChallengeResponseAuthentication {{ 'yes' if openssh_challenge_response_auth else 'no' }}
# Login Settings
LoginGraceTime {{ openssh_login_grace_time }}
MaxAuthTries {{ openssh_max_auth_tries }}
MaxSessions {{ openssh_max_sessions }}
MaxStartups {{ openssh_max_startups }}
# Logging
SyslogFacility {{ openssh_syslog_facility }}
LogLevel {{ openssh_log_level }}
{% if openssh_has_log_verbose | default(false) and openssh_enable_verbose_logging %}
# Enhanced Forensic Logging (OpenSSH 8.5+)
LogVerbose {{ openssh_log_verbose_subsystems | join(',') }}
{% endif %}
# PAM and system integration
UsePAM {{ 'yes' if openssh_use_pam else 'no' }}
UseDNS {{ 'yes' if openssh_use_dns else 'no' }}
# Session Re-keying (CCCS ITSP.40.062 Requirement)
RekeyLimit {{ openssh_rekey_limit }}
# Forwarding and features
X11Forwarding {{ 'yes' if openssh_x11_forwarding else 'no' }}
PrintMotd {{ 'yes' if openssh_print_motd else 'no' }}
PrintLastLog {{ 'yes' if openssh_print_last_log else 'no' }}
TCPKeepAlive {{ 'yes' if openssh_tcp_keep_alive else 'no' }}
# Client alive (keepalive)
ClientAliveInterval {{ openssh_client_alive_interval }}
ClientAliveCountMax {{ openssh_client_alive_count_max }}
# Access control
{% if openssh_allow_users | length > 0 %}
AllowUsers {{ openssh_allow_users | sort | join(' ') }}
{% endif %}
{% if openssh_deny_users | length > 0 %}
DenyUsers {{ openssh_deny_users | sort | join(' ') }}
{% endif %}
{% if openssh_allow_groups | length > 0 %}
AllowGroups {{ openssh_allow_groups | sort | join(' ') }}
{% endif %}
{% if openssh_deny_groups | length > 0 %}
DenyGroups {{ openssh_deny_groups | sort | join(' ') }}
{% endif %}
# Banner
{% if openssh_banner != 'none' %}
Banner {{ openssh_banner }}
{% endif %}
# Subsystems
{% for subsystem in openssh_subsystems %}
Subsystem {{ subsystem.name }} {{ subsystem.command }}
{% endfor %}
# Security hardening
StrictModes yes
HostbasedAuthentication no
IgnoreRhosts yes
PermitUserEnvironment no
AcceptEnv LANG LC_*
# Certificate Authority Configuration
{% if openssh_enable_ca %}
{% if openssh_trusted_user_ca_keys | length > 0 %}
{% for ca_key in openssh_trusted_user_ca_keys %}
TrustedUserCAKeys {{ ca_key }}
{% endfor %}
{% endif %}
{% if openssh_host_certificate %}
HostCertificate {{ openssh_host_certificate }}
{% endif %}
{% endif %}
# Additional Hardening Options
{% if openssh_disable_forwarding_comprehensive and openssh_has_disable_forwarding | default(false) %}
# Comprehensive forwarding disable (OpenSSH 7.4+, fixed in 10.0)
DisableForwarding yes
{% else %}
{% if openssh_disable_forwarding or openssh_disable_tcp_forwarding %}
AllowTcpForwarding no
{% else %}
AllowTcpForwarding yes
{% endif %}
{% if openssh_disable_forwarding or openssh_disable_agent_forwarding %}
AllowAgentForwarding no
{% else %}
AllowAgentForwarding yes
{% endif %}
{% if openssh_disable_forwarding or openssh_disable_stream_local_forwarding %}
AllowStreamLocalForwarding no
{% endif %}
{% if openssh_disable_tunneling %}
PermitTunnel no
{% endif %}
{% endif %}
GatewayPorts no
# PerSourcePenalties - Automated Rate Limiting and Attack Mitigation (OpenSSH 9.8+)
{% if openssh_has_persourcepenalties | default(false) and openssh_enable_persourcepenalties %}
# Automatic penalties for repeated failures and suspicious behavior
PerSourcePenalties authfail:{{ openssh_persource_authfail_penalty }} noauth:{{ openssh_persource_noauth_penalty }} crash:{{ openssh_persource_crash_penalty }}
PerSourceMaxStartups {{ openssh_persource_maxstartups }}
PerSourceNetBlockSize {{ openssh_persource_netblock_ipv4 }}:{{ openssh_persource_netblock_ipv6 }}
{% endif %}

87
roles/openssh/test-quick.sh Executable file
View file

@ -0,0 +1,87 @@
#!/usr/bin/env bash
set -e
# Test script for all supported distributions
# Tests each distribution sequentially with proper cleanup
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"
# Molecule path
MOLECULE="${HOME}/.local/pipx/venvs/ansible-core/bin/molecule"
# Distribution configurations
declare -A DISTROS=(
["debian9"]="geerlingguy/docker-debian9-ansible:latest|7.4p1"
["debian10"]="geerlingguy/docker-debian10-ansible:latest|7.9p1"
["debian11"]="geerlingguy/docker-debian11-ansible:latest|8.4p1"
["debian12"]="geerlingguy/docker-debian12-ansible:latest|9.2p1"
["ubuntu1604"]="geerlingguy/docker-ubuntu1604-ansible:latest|7.2p2"
["ubuntu1804"]="geerlingguy/docker-ubuntu1804-ansible:latest|7.6p1"
["ubuntu2004"]="geerlingguy/docker-ubuntu2004-ansible:latest|8.2p1"
["ubuntu2204"]="geerlingguy/docker-ubuntu2204-ansible:latest|8.9p1"
["ubuntu2404"]="geerlingguy/docker-ubuntu2404-ansible:latest|9.6p1"
)
# Results tracking
PASSED=()
FAILED=()
TOTAL=${#DISTROS[@]}
CURRENT=0
echo "=========================================="
echo "Testing ${TOTAL} distributions"
echo "=========================================="
echo ""
for distro in "${!DISTROS[@]}"; do
CURRENT=$((CURRENT + 1))
IFS='|' read -r image version <<< "${DISTROS[$distro]}"
echo "[$CURRENT/$TOTAL] Testing $distro (OpenSSH $version)..."
# Export environment variables
export MOLECULE_DISTRO="$distro"
export MOLECULE_IMAGE="$image"
export MOLECULE_OPENSSH_VERSION="$version"
# Run test with timeout
if timeout 300 "$MOLECULE" test 2>&1 | tee "/tmp/${distro}-test.log" | grep -q "successful"; then
echo "$distro PASSED"
PASSED+=("$distro")
else
echo "$distro FAILED (see /tmp/${distro}-test.log)"
FAILED+=("$distro")
fi
echo ""
done
# Summary
echo "=========================================="
echo "TEST SUMMARY"
echo "=========================================="
echo "Total: $TOTAL"
echo "Passed: ${#PASSED[@]}"
echo "Failed: ${#FAILED[@]}"
echo ""
if [ ${#PASSED[@]} -gt 0 ]; then
echo "✅ PASSED:"
for d in "${PASSED[@]}"; do
echo " - $d"
done
echo ""
fi
if [ ${#FAILED[@]} -gt 0 ]; then
echo "❌ FAILED:"
for d in "${FAILED[@]}"; do
echo " - $d (log: /tmp/${d}-test.log)"
done
echo ""
exit 1
fi
echo "🎉 All tests passed!"
exit 0

View file

@ -0,0 +1 @@
FAILED