github.com/jasoet/gopki@v1.15.0/compatibility/keypair/ssh_doc.md (about) 1 # SSH (OpenSSH) Compatibility Testing Framework 2 3 This document provides comprehensive documentation for SSH key compatibility testing between GoPKI and OpenSSH tools, ensuring perfect interoperability for SSH key operations. 4 5 ## Overview 6 7 The SSH compatibility framework validates that SSH keys, formats, fingerprints, and cryptographic operations generated by GoPKI are fully compatible with OpenSSH (`ssh-keygen`, `ssh-add`, `ssh-agent`) and vice versa. This ensures that GoPKI can be used as a drop-in replacement for SSH key operations in Go applications. 8 9 ## Test Coverage 10 11 ### Supported Algorithms 12 13 **RSA Keys** 14 - RSA-2048 (minimum secure size for SSH) 15 - RSA-3072 (enhanced security) 16 - RSA-4096 (maximum security) 17 18 **ECDSA Keys** 19 - P-256 (ecdsa-sha2-nistp256) - Most common curve 20 - P-384 (ecdsa-sha2-nistp384) - Enhanced security 21 - P-521 (ecdsa-sha2-nistp521) - Maximum security 22 23 **Ed25519 Keys** 24 - Ed25519 (ssh-ed25519) - Modern, high-performance curve 25 26 ### Test Categories 27 28 #### 1. **Bidirectional Key Generation** 29 - GoPKI generates SSH keys → ssh-keygen validates 30 - ssh-keygen generates keys → GoPKI validates 31 - Full round-trip validation for all algorithms 32 33 #### 2. **Format Compatibility** 34 - OpenSSH private key format (RFC4716) 35 - OpenSSH public key format (authorized_keys) 36 - Passphrase-protected private keys 37 - Comment preservation in public keys 38 39 #### 3. **Fingerprint Validation** 40 - SHA256 fingerprint generation and comparison 41 - MD5 fingerprint generation (legacy support) 42 - Cross-tool fingerprint verification 43 44 #### 4. **Public Key Extraction** 45 - Extract public key from private key using ssh-keygen 46 - Verify extracted key matches original public key 47 - Fingerprint comparison for validation 48 49 #### 5. **Authorized Keys Format** 50 - Single-line format validation 51 - Key type prefix verification (ssh-rsa, ssh-ed25519, etc.) 52 - Comment handling and preservation 53 54 #### 6. **Passphrase Protection** 55 - AES128/AES256 encrypted private keys 56 - Bidirectional passphrase encryption/decryption 57 - Wrong passphrase error handling 58 59 ### Edge Cases and Security 60 61 - Invalid SSH format detection 62 - Corrupted key handling 63 - Wrong passphrase scenarios 64 - Key permission validation 65 - Format boundary testing 66 67 ## Running Tests 68 69 ### Using Taskfile (Recommended) 70 71 ```bash 72 # Run all compatibility tests including SSH 73 task test:compatibility 74 75 # Run SSH-specific tests only 76 go test -tags=compatibility ./compatibility/keypair -v -run TestSSH 77 ``` 78 79 ### Direct Go Testing 80 81 ```bash 82 # All SSH compatibility tests 83 go test -tags=compatibility ./compatibility/keypair -v -run "TestSSH.*" 84 85 # Specific SSH test categories 86 go test -tags=compatibility ./compatibility/keypair -v -run TestSSHKeypairCompatibility 87 go test -tags=compatibility ./compatibility/keypair -v -run TestSSHFingerprintCompatibility 88 go test -tags=compatibility ./compatibility/keypair -v -run TestSSHPublicKeyExtraction 89 go test -tags=compatibility ./compatibility/keypair -v -run TestSSHAuthorizedKeysFormat 90 91 # Specific algorithm tests 92 go test -tags=compatibility ./compatibility/keypair -v -run "TestSSHKeypairCompatibility/RSA" 93 go test -tags=compatibility ./compatibility/keypair -v -run "TestSSHKeypairCompatibility/ECDSA" 94 go test -tags=compatibility ./compatibility/keypair -v -run "TestSSHKeypairCompatibility/Ed25519" 95 ``` 96 97 ## Test Output Interpretation 98 99 ### Successful Test Output 100 101 ``` 102 🔐 Running SSH OpenSSH Compatibility Tests... 103 Testing SSH key generation, validation, and format conversion 104 105 === RUN TestSSHKeypairCompatibility/RSA/RSA_2048/GoPKI_Generate_SSH_Validate 106 → Validating SSH private key with ssh-keygen... 107 → Executing: ssh-keygen -y -f /tmp/ssh_private_validate 108 ✓ SSH private key validation passed 109 → Validating SSH public key with ssh-keygen... 110 → Executing: ssh-keygen -l -f /tmp/ssh_public_validate.pub 111 ✓ SSH public key validation passed: 2048 SHA256:xxxxx test@gopki.com (RSA) 112 ✓ GoPKI RSA-2048 SSH keys validated by ssh-keygen 113 114 --- PASS: TestSSHKeypairCompatibility/RSA/RSA_2048 (0.45s) 115 ``` 116 117 ### Failed Test Indicators 118 119 - `❌ SSH private key validation failed:` - ssh-keygen rejected the private key 120 - `❌ SSH public key validation failed:` - ssh-keygen rejected the public key 121 - `Should fail to load encrypted key without passphrase` - Expected failure for security 122 - Test failure with specific error description 123 124 ## SSH Commands Used 125 126 The framework uses the following ssh-keygen commands for validation: 127 128 ### Key Generation 129 ```bash 130 # RSA key generation 131 ssh-keygen -t rsa -b 2048 -f ssh_private -N "" -q 132 133 # ECDSA key generation 134 ssh-keygen -t ecdsa -b 256 -f ssh_private -N "" -q 135 136 # Ed25519 key generation 137 ssh-keygen -t ed25519 -f ssh_private -N "" -q 138 139 # With passphrase 140 ssh-keygen -t rsa -b 2048 -f ssh_private -N "passphrase" -q 141 ``` 142 143 ### Key Validation 144 ```bash 145 # Validate private key and extract public key 146 ssh-keygen -y -f private_key 147 148 # Get fingerprint and validate public key 149 ssh-keygen -l -f public_key.pub 150 151 # Get SHA256 fingerprint 152 ssh-keygen -l -E sha256 -f public_key.pub 153 154 # Get MD5 fingerprint (legacy) 155 ssh-keygen -l -E md5 -f public_key.pub 156 ``` 157 158 ### Format Conversion 159 ```bash 160 # Convert between formats (PEM to SSH) 161 ssh-keygen -p -m RFC4716 -f key_file -N "" -P "" 162 163 # Extract public key from private key 164 ssh-keygen -y -f private_key > public_key.pub 165 ``` 166 167 ## Framework Architecture 168 169 ### SSH Helper Functions (helpers.go) 170 171 **Key Generation** 172 - `GenerateSSHKeyWithSSHKeygen()` - Generate keys using ssh-keygen 173 - `GenerateSSHKeyWithPassphrase()` - Generate passphrase-protected keys 174 175 **Validation Functions** 176 - `ValidateSSHPrivateKeyWithSSHKeygen()` - Validate private key format 177 - `ValidateSSHPublicKeyWithSSHKeygen()` - Validate public key format 178 - `ValidateAuthorizedKeysFormat()` - Check authorized_keys compatibility 179 180 **Utility Functions** 181 - `GetSSHKeyFingerprint()` - Get SHA256/MD5 fingerprints 182 - `ExtractPublicKeyWithSSHKeygen()` - Extract public from private key 183 - `ConvertPEMToSSHWithSSHKeygen()` - Format conversion 184 185 ### Test Structure (ssh_test.go) 186 187 Each test follows the pattern: 188 1. **Setup** - Create OpenSSL helper and temporary directories 189 2. **Generate** - Create SSH keys using either GoPKI or ssh-keygen 190 3. **Convert** - Transform keys between formats if needed 191 4. **Validate** - Verify compatibility using the other tool 192 5. **Compare** - Ensure fingerprints and key properties match 193 6. **Cleanup** - Remove temporary files 194 195 ### Key Test Functions 196 197 **TestSSHKeypairCompatibility** 198 - Tests all algorithms (RSA, ECDSA, Ed25519) 199 - Bidirectional key generation and validation 200 - Passphrase protection for all algorithms 201 202 **TestSSHFingerprintCompatibility** 203 - SHA256 fingerprint generation 204 - MD5 fingerprint generation 205 - Cross-tool fingerprint comparison 206 207 **TestSSHPublicKeyExtraction** 208 - Extract public key from private key 209 - Verify extraction accuracy 210 - Fingerprint validation 211 212 **TestSSHAuthorizedKeysFormat** 213 - Validate single-line format 214 - Check key type prefixes 215 - Comment preservation 216 217 ## Dependencies 218 219 ### Required Software 220 - OpenSSH 8.0+ (compatible with older versions) 221 - Go 1.21+ with module support 222 - testify assertion library 223 224 ### Go Dependencies 225 ```go 226 import ( 227 "github.com/stretchr/testify/assert" 228 "github.com/stretchr/testify/require" 229 "github.com/jasoet/gopki/keypair" 230 "github.com/jasoet/gopki/keypair/algo" 231 "github.com/jasoet/gopki/keypair/format" 232 ) 233 ``` 234 235 ### OpenSSH Version Compatibility 236 237 The tests are designed to work with: 238 - **OpenSSH 8.x-10.x** (primary target) 239 - **OpenSSH 7.x** (legacy support) 240 - **Portable OpenSSH** (cross-platform) 241 242 Version-specific behavior is handled automatically by the framework. 243 244 ## Security Considerations 245 246 ### Validation Scope 247 248 The compatibility tests verify: 249 - **Format Correctness** - Keys follow OpenSSH format specifications 250 - **Cryptographic Validity** - Keys are mathematically correct 251 - **Passphrase Protection** - Encryption/decryption works correctly 252 - **Fingerprint Accuracy** - Fingerprints match across implementations 253 - **authorized_keys Compatibility** - Keys work in SSH authorized_keys files 254 255 ### Security Boundaries 256 257 The tests do NOT validate: 258 - SSH protocol implementation 259 - Network security aspects 260 - SSH agent forwarding security 261 - Key exchange protocols 262 263 ### Key Material Handling 264 265 - All test keys are generated in temporary directories with 0600 permissions 266 - Private keys are automatically cleaned up after tests 267 - Passphrase-protected keys use strong encryption 268 - No real cryptographic material is exposed 269 - Test keys should never be used in production 270 271 ## Troubleshooting 272 273 ### Common Issues 274 275 **ssh-keygen Not Found** 276 ```bash 277 # Check if ssh-keygen is in PATH 278 which ssh-keygen 279 280 # Check SSH version 281 ssh -V 282 283 # Install OpenSSH on macOS 284 brew install openssh 285 286 # Install OpenSSH on Ubuntu/Debian 287 sudo apt-get install openssh-client 288 289 # Install OpenSSH on RHEL/CentOS 290 sudo yum install openssh-clients 291 ``` 292 293 **Permission Errors** 294 ```bash 295 # Ensure temporary directory is writable 296 chmod 755 /tmp 297 298 # Check file permissions 299 ls -la ~/.ssh/ 300 301 # Fix SSH key permissions 302 chmod 600 ~/.ssh/id_* 303 chmod 644 ~/.ssh/id_*.pub 304 ``` 305 306 **Passphrase Issues** 307 - Ensure passphrase is correctly quoted in tests 308 - Check for special characters that need escaping 309 - Verify encryption algorithm support 310 311 **Format Conversion Failures** 312 - Check OpenSSH version for RFC4716 support 313 - Verify key format is valid before conversion 314 - Check for trailing newlines or whitespace 315 316 ### Debugging Tests 317 318 Enable verbose logging: 319 ```bash 320 # Maximum verbosity 321 go test -tags=compatibility ./compatibility/keypair -v -run TestSSH 322 323 # With detailed output 324 go test -tags=compatibility ./compatibility/keypair -v -run TestSSH -count=1 325 326 # Debug specific algorithm 327 SSH_DEBUG=1 go test -tags=compatibility ./compatibility/keypair -v -run "TestSSH.*RSA" 328 ``` 329 330 ### Performance Considerations 331 332 - RSA-4096 key generation can take 1-2 seconds 333 - Ed25519 offers best performance/security ratio 334 - ECDSA tests are typically faster than RSA 335 - Passphrase encryption adds ~100ms overhead 336 - Parallel test execution is automatically handled 337 338 ## Integration Examples 339 340 ### CI/CD Integration 341 342 ```yaml 343 # GitHub Actions example 344 - name: Run SSH Compatibility Tests 345 run: | 346 task test:compatibility 347 348 # Jenkins example 349 pipeline { 350 stages { 351 stage('SSH Compatibility Tests') { 352 steps { 353 sh 'go test -tags=compatibility ./compatibility/keypair -v -run TestSSH' 354 } 355 } 356 } 357 } 358 ``` 359 360 ### Docker Integration 361 362 ```dockerfile 363 FROM golang:1.21-alpine 364 RUN apk add --no-cache openssh-client 365 COPY . /app 366 WORKDIR /app 367 RUN go test -tags=compatibility ./compatibility/keypair -v -run TestSSH 368 ``` 369 370 ### Using Generated Keys 371 372 ```go 373 // Generate SSH keys with GoPKI 374 manager, _ := keypair.Generate[algo.KeySize, *algo.RSAKeyPair, *rsa.PrivateKey, *rsa.PublicKey](algo.KeySize2048) 375 privateSSH, publicSSH, _ := manager.ToSSH("user@example.com", "passphrase") 376 377 // Save to files for SSH use 378 os.WriteFile("~/.ssh/id_rsa", []byte(privateSSH), 0600) 379 os.WriteFile("~/.ssh/id_rsa.pub", []byte(publicSSH), 0644) 380 381 // Add public key to authorized_keys 382 authorizedKeys, _ := os.ReadFile("~/.ssh/authorized_keys") 383 authorizedKeys = append(authorizedKeys, []byte(publicSSH)...) 384 os.WriteFile("~/.ssh/authorized_keys", authorizedKeys, 0600) 385 ``` 386 387 ## Contributing 388 389 ### Adding New SSH Tests 390 391 1. Add test functions following the existing pattern in `ssh_test.go` 392 2. Use the provided SSH helper functions from `helpers.go` 393 3. Include bidirectional testing (GoPKI ↔ ssh-keygen) 394 4. Add fingerprint validation for new test cases 395 5. Update this documentation with new test coverage 396 397 ### Test Enhancement Guidelines 398 399 - Always use testify assertions (`assert` and `require`) 400 - Include descriptive test names and logging 401 - Test both success and failure cases 402 - Validate edge cases and boundary conditions 403 - Ensure test independence (no shared state) 404 - Clean up all temporary resources 405 406 ### Code Quality Standards 407 408 - Follow Go best practices and idioms 409 - Add comprehensive error handling 410 - Use meaningful variable names 411 - Include comments for complex logic 412 - Maintain consistent formatting 413 414 ## References 415 416 ### OpenSSH Documentation 417 418 - [ssh-keygen Manual](https://man.openbsd.org/ssh-keygen) 419 - [SSH Public Key Format](https://tools.ietf.org/html/rfc4253#section-6.6) 420 - [OpenSSH Private Key Format](https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key) 421 - [authorized_keys Format](https://man.openbsd.org/sshd#AUTHORIZED_KEYS_FILE_FORMAT) 422 423 ### Standards Compliance 424 425 - **RFC 4253** - SSH Transport Layer Protocol (public key format) 426 - **RFC 4716** - SSH Public Key File Format 427 - **RFC 8332** - Use of RSA Keys with SHA-256 and SHA-512 428 - **RFC 8709** - Ed25519 and Ed448 for SSH 429 430 ### GoPKI Integration 431 432 - [Keypair Module Documentation](../../keypair/README.md) 433 - [SSH Format Implementation](../../keypair/format/) 434 - [Algorithm-Specific SSH Support](../../keypair/algo/) 435 436 This framework ensures GoPKI maintains **100% compatibility** with OpenSSH operations across all supported algorithms and key formats.