- Add DISCOVERY_LOG_LEVEL=debug - Add DISCOVERY_SHOW_PROGRESS=true - Temporary changes for debugging InitializerProcessor fixes on production
397 lines
12 KiB
Markdown
397 lines
12 KiB
Markdown
# Cryptography Module - Konfiguration
|
|
|
|
Konfigurationsoptionen und Setup für das Cryptography Module.
|
|
|
|
## Service-Registrierung
|
|
|
|
### Dependency Injection Setup
|
|
|
|
```php
|
|
use App\Framework\DI\Initializer;
|
|
use App\Framework\DI\Container;
|
|
use App\Framework\Cryptography\KeyDerivationFunction;
|
|
use App\Framework\Cryptography\SecureTokenGenerator;
|
|
use App\Framework\Cryptography\CryptographicUtilities;
|
|
use App\Framework\Cryptography\DigitalSignature;
|
|
use App\Framework\Cryptography\AdvancedHash;
|
|
use App\Framework\Random\SecureRandomGenerator;
|
|
|
|
final readonly class CryptographyInitializer implements Initializer
|
|
{
|
|
public function initialize(Container $container): void
|
|
{
|
|
// Random Generator als Dependency
|
|
$container->singleton(RandomGenerator::class, new SecureRandomGenerator());
|
|
|
|
// Core Cryptography Services
|
|
$container->singleton(KeyDerivationFunction::class, function(Container $c) {
|
|
return new KeyDerivationFunction($c->get(RandomGenerator::class));
|
|
});
|
|
|
|
$container->singleton(SecureTokenGenerator::class, function(Container $c) {
|
|
return new SecureTokenGenerator($c->get(RandomGenerator::class));
|
|
});
|
|
|
|
$container->singleton(CryptographicUtilities::class, function(Container $c) {
|
|
return new CryptographicUtilities($c->get(RandomGenerator::class));
|
|
});
|
|
|
|
$container->singleton(DigitalSignature::class, function(Container $c) {
|
|
return new DigitalSignature($c->get(RandomGenerator::class));
|
|
});
|
|
|
|
$container->singleton(AdvancedHash::class, new AdvancedHash());
|
|
|
|
// Factory Methods als Alternative
|
|
$container->bind('kdf.factory', function(Container $c) {
|
|
return KeyDerivationFunction::create($c->get(RandomGenerator::class));
|
|
});
|
|
}
|
|
}
|
|
```
|
|
|
|
### AppBootstrapper Integration
|
|
|
|
```php
|
|
// In src/Framework/Core/AppBootstrapper.php
|
|
public function bootstrap(): Application
|
|
{
|
|
// ... existing bootstrapping
|
|
|
|
$initializer = new CryptographyInitializer();
|
|
$initializer->initialize($this->container);
|
|
|
|
return $application;
|
|
}
|
|
```
|
|
|
|
## Sicherheitsparameter
|
|
|
|
### Key Derivation Function Konfiguration
|
|
|
|
```php
|
|
final readonly class CryptographyConfig
|
|
{
|
|
public const DEFAULT_KDF_PARAMETERS = [
|
|
'pbkdf2-sha256' => [
|
|
'low' => ['iterations' => 50000, 'key_length' => 32],
|
|
'standard' => ['iterations' => 100000, 'key_length' => 32],
|
|
'high' => ['iterations' => 200000, 'key_length' => 32],
|
|
],
|
|
'argon2id' => [
|
|
'low' => ['memory_cost' => 32768, 'time_cost' => 3, 'threads' => 2],
|
|
'standard' => ['memory_cost' => 65536, 'time_cost' => 4, 'threads' => 3],
|
|
'high' => ['memory_cost' => 131072, 'time_cost' => 6, 'threads' => 4],
|
|
],
|
|
'scrypt' => [
|
|
'low' => ['cost_parameter' => 8192, 'block_size' => 8, 'parallelization' => 1],
|
|
'standard' => ['cost_parameter' => 16384, 'block_size' => 8, 'parallelization' => 1],
|
|
'high' => ['cost_parameter' => 32768, 'block_size' => 8, 'parallelization' => 2],
|
|
]
|
|
];
|
|
|
|
public static function getRecommendedParameters(
|
|
string $algorithm,
|
|
string $securityLevel = 'standard'
|
|
): array {
|
|
return self::DEFAULT_KDF_PARAMETERS[$algorithm][$securityLevel] ??
|
|
throw new InvalidArgumentException("Unsupported configuration: {$algorithm}:{$securityLevel}");
|
|
}
|
|
}
|
|
```
|
|
|
|
### Token-Generator Konfiguration
|
|
|
|
```php
|
|
final readonly class TokenConfig
|
|
{
|
|
public const DEFAULT_TOKEN_LENGTHS = [
|
|
SecureTokenGenerator::TYPE_API_KEY => 32, // 256 Bit
|
|
SecureTokenGenerator::TYPE_SESSION => 32, // 256 Bit
|
|
SecureTokenGenerator::TYPE_CSRF => 32, // 256 Bit
|
|
SecureTokenGenerator::TYPE_REFRESH => 64, // 512 Bit
|
|
SecureTokenGenerator::TYPE_VERIFICATION => 32, // 256 Bit
|
|
SecureTokenGenerator::TYPE_BEARER => 32, // 256 Bit
|
|
SecureTokenGenerator::TYPE_WEBHOOK => 32, // 256 Bit
|
|
];
|
|
|
|
public const DEFAULT_TOKEN_FORMATS = [
|
|
SecureTokenGenerator::TYPE_API_KEY => SecureTokenGenerator::FORMAT_BASE64_URL,
|
|
SecureTokenGenerator::TYPE_SESSION => SecureTokenGenerator::FORMAT_BASE64_URL,
|
|
SecureTokenGenerator::TYPE_OTP => SecureTokenGenerator::FORMAT_NUMERIC,
|
|
];
|
|
|
|
public const TOKEN_EXPIRY_TIMES = [
|
|
SecureTokenGenerator::TYPE_SESSION => 3600 * 24, // 24 Stunden
|
|
SecureTokenGenerator::TYPE_CSRF => 3600, // 1 Stunde
|
|
SecureTokenGenerator::TYPE_VERIFICATION => 3600 * 2, // 2 Stunden
|
|
SecureTokenGenerator::TYPE_OTP => 300, // 5 Minuten
|
|
SecureTokenGenerator::TYPE_REFRESH => 3600 * 24 * 30, // 30 Tage
|
|
];
|
|
}
|
|
```
|
|
|
|
## Environment-basierte Konfiguration
|
|
|
|
### .env Konfiguration
|
|
|
|
```bash
|
|
# Cryptography Configuration
|
|
CRYPTO_DEFAULT_KDF_ALGORITHM=argon2id
|
|
CRYPTO_DEFAULT_SECURITY_LEVEL=standard
|
|
|
|
# Token Configuration
|
|
CRYPTO_DEFAULT_TOKEN_LENGTH=32
|
|
CRYPTO_DEFAULT_TOKEN_FORMAT=base64_url
|
|
|
|
# Digital Signature Configuration
|
|
CRYPTO_DEFAULT_RSA_KEY_SIZE=2048
|
|
CRYPTO_DEFAULT_EC_CURVE=secp256r1
|
|
|
|
# Performance Configuration
|
|
CRYPTO_BATCH_SIZE_LIMIT=1000
|
|
CRYPTO_ENTROPY_THRESHOLD=7.0
|
|
```
|
|
|
|
### Environment-aware Service
|
|
|
|
```php
|
|
use App\Framework\Core\Environment;
|
|
use App\Framework\Core\EnvKey;
|
|
|
|
final readonly class CryptographyConfigService
|
|
{
|
|
public function __construct(
|
|
private Environment $environment
|
|
) {}
|
|
|
|
public function getDefaultKdfAlgorithm(): string
|
|
{
|
|
return $this->environment->get(
|
|
EnvKey::from('CRYPTO_DEFAULT_KDF_ALGORITHM'),
|
|
'argon2id'
|
|
);
|
|
}
|
|
|
|
public function getDefaultSecurityLevel(): string
|
|
{
|
|
return $this->environment->get(
|
|
EnvKey::from('CRYPTO_DEFAULT_SECURITY_LEVEL'),
|
|
'standard'
|
|
);
|
|
}
|
|
|
|
public function getDefaultTokenLength(): int
|
|
{
|
|
return $this->environment->getInt(
|
|
EnvKey::from('CRYPTO_DEFAULT_TOKEN_LENGTH'),
|
|
32
|
|
);
|
|
}
|
|
|
|
public function getEntropyThreshold(): float
|
|
{
|
|
return $this->environment->getFloat(
|
|
EnvKey::from('CRYPTO_ENTROPY_THRESHOLD'),
|
|
7.0
|
|
);
|
|
}
|
|
}
|
|
```
|
|
|
|
## Advanced Configuration
|
|
|
|
### Custom RandomGenerator
|
|
|
|
```php
|
|
// Eigener RandomGenerator für spezielle Anforderungen
|
|
final readonly class CustomSecureRandomGenerator implements RandomGenerator
|
|
{
|
|
public function bytes(int $length): string
|
|
{
|
|
// Custom implementation mit Hardware-RNG
|
|
return $this->getHardwareRandomBytes($length);
|
|
}
|
|
|
|
public function int(int $min = 0, int $max = PHP_INT_MAX): int
|
|
{
|
|
return random_int($min, $max);
|
|
}
|
|
|
|
private function getHardwareRandomBytes(int $length): string
|
|
{
|
|
// Implementation für Hardware-RNG
|
|
// z.B. über /dev/hwrng oder externe HSM
|
|
}
|
|
}
|
|
|
|
// In Initializer registrieren
|
|
$container->singleton(RandomGenerator::class, new CustomSecureRandomGenerator());
|
|
```
|
|
|
|
### Performance-optimierte Konfiguration
|
|
|
|
```php
|
|
final readonly class PerformanceOptimizedCryptoInitializer implements Initializer
|
|
{
|
|
public function initialize(Container $container): void
|
|
{
|
|
// Cached Services für bessere Performance
|
|
$container->singleton(KeyDerivationFunction::class, function(Container $c) {
|
|
$kdf = new KeyDerivationFunction($c->get(RandomGenerator::class));
|
|
return new CachedKeyDerivationFunction($kdf, $c->get(Cache::class));
|
|
});
|
|
|
|
// Batch-optimierte Token-Generierung
|
|
$container->singleton(SecureTokenGenerator::class, function(Container $c) {
|
|
return new BatchOptimizedTokenGenerator(
|
|
$c->get(RandomGenerator::class),
|
|
batchSize: 100 // Tokens in Batches vorgenerieren
|
|
);
|
|
});
|
|
}
|
|
}
|
|
```
|
|
|
|
### Test-Konfiguration
|
|
|
|
```php
|
|
// Für Unit Tests - deterministic aber sichere Werte
|
|
final readonly class TestCryptographyInitializer implements Initializer
|
|
{
|
|
public function initialize(Container $container): void
|
|
{
|
|
if (!$this->isTestEnvironment()) {
|
|
throw new InvalidArgumentException('TestCryptographyInitializer nur in Test-Umgebung verwenden');
|
|
}
|
|
|
|
// Deterministischer aber sicherer Generator für Tests
|
|
$container->singleton(RandomGenerator::class, new TestRandomGenerator());
|
|
|
|
// Reduzierte Parameter für schnellere Tests
|
|
$container->singleton(KeyDerivationFunction::class, function(Container $c) {
|
|
return new KeyDerivationFunction($c->get(RandomGenerator::class));
|
|
});
|
|
}
|
|
|
|
private function isTestEnvironment(): bool
|
|
{
|
|
return defined('PHPUNIT_RUNNING') ||
|
|
(isset($_ENV['APP_ENV']) && $_ENV['APP_ENV'] === 'testing');
|
|
}
|
|
}
|
|
```
|
|
|
|
## Middleware-Integration
|
|
|
|
### Automatic Token Validation
|
|
|
|
```php
|
|
final readonly class CryptoTokenValidationMiddleware
|
|
{
|
|
public function __construct(
|
|
private CryptographicUtilities $utils,
|
|
private CacheInterface $cache
|
|
) {}
|
|
|
|
public function handle(HttpRequest $request, RequestHandler $handler): HttpResponse
|
|
{
|
|
$authHeader = $request->server->getAuthorizationHeader();
|
|
|
|
if ($authHeader && str_starts_with($authHeader, 'Bearer ')) {
|
|
$token = substr($authHeader, 7);
|
|
|
|
// Token-Format validieren
|
|
if (!$this->utils->timingSafeEquals($token, trim($token))) {
|
|
throw new AuthenticationException('Invalid token format');
|
|
}
|
|
|
|
// Cache für Token-Validierung
|
|
$cacheKey = 'token_valid_' . hash('sha256', $token);
|
|
if (!$this->cache->has($cacheKey)) {
|
|
// Token in Datenbank validieren
|
|
$isValid = $this->validateTokenInDatabase($token);
|
|
$this->cache->set($cacheKey, $isValid, 300); // 5 Min Cache
|
|
}
|
|
}
|
|
|
|
return $handler->handle($request);
|
|
}
|
|
}
|
|
```
|
|
|
|
## Monitoring und Logging
|
|
|
|
### Security Event Integration
|
|
|
|
```php
|
|
final readonly class CryptographyEventLogger
|
|
{
|
|
public function __construct(
|
|
private Logger $logger,
|
|
private SecurityEventLogger $securityLogger
|
|
) {}
|
|
|
|
public function logTokenGeneration(SecureToken $token): void
|
|
{
|
|
$this->logger->info('Token generated', [
|
|
'type' => $token->getType(),
|
|
'format' => $token->getFormat(),
|
|
'length' => $token->getLength(),
|
|
'fingerprint' => $token->getShortFingerprint()
|
|
]);
|
|
}
|
|
|
|
public function logSuspiciousTokenActivity(string $token, string $reason): void
|
|
{
|
|
$this->securityLogger->logSecurityEvent(
|
|
new SuspiciousTokenActivityEvent(
|
|
tokenFingerprint: hash('sha256', $token),
|
|
reason: $reason,
|
|
timestamp: new DateTimeImmutable()
|
|
)
|
|
);
|
|
}
|
|
}
|
|
```
|
|
|
|
## Validierung der Konfiguration
|
|
|
|
```php
|
|
final readonly class CryptographyConfigValidator
|
|
{
|
|
public static function validateConfiguration(Container $container): void
|
|
{
|
|
// RandomGenerator verfügbar?
|
|
if (!$container->has(RandomGenerator::class)) {
|
|
throw new ConfigurationException('RandomGenerator nicht registriert');
|
|
}
|
|
|
|
// Cryptography Services verfügbar?
|
|
$requiredServices = [
|
|
KeyDerivationFunction::class,
|
|
SecureTokenGenerator::class,
|
|
CryptographicUtilities::class
|
|
];
|
|
|
|
foreach ($requiredServices as $service) {
|
|
if (!$container->has($service)) {
|
|
throw new ConfigurationException("Service nicht registriert: {$service}");
|
|
}
|
|
}
|
|
|
|
// Sicherheitsparameter validieren
|
|
$kdf = $container->get(KeyDerivationFunction::class);
|
|
try {
|
|
$params = $kdf->getRecommendedParameters('pbkdf2-sha256', 'standard');
|
|
if ($params['iterations'] < 50000) {
|
|
throw new ConfigurationException('PBKDF2 Iterationen zu niedrig (Minimum: 50000)');
|
|
}
|
|
} catch (InvalidArgumentException $e) {
|
|
throw new ConfigurationException('Ungültige KDF-Konfiguration: ' . $e->getMessage());
|
|
}
|
|
}
|
|
}
|
|
```
|
|
|
|
Diese Konfiguration ermöglicht es, das Cryptography Module flexibel an verschiedene Umgebungen und Sicherheitsanforderungen anzupassen, während Best Practices für Sicherheit und Performance eingehalten werden. |