|
| 1 | +import 'dart:convert'; |
| 2 | +import 'dart:io'; |
| 3 | + |
| 4 | +import 'package:basic_utils/basic_utils.dart'; |
| 5 | +import 'package:dio/dio.dart'; |
| 6 | +import 'package:dio/io.dart'; |
| 7 | +import 'package:fa_flutter_api_client/src/ssl_pinning/ssl_pinning_config.dart'; |
| 8 | +import 'package:flutter/foundation.dart'; |
| 9 | + |
| 10 | +/// Custom Dio HttpClientAdapter with SSL Certificate Pinning |
| 11 | +/// |
| 12 | +/// This adapter validates SSL certificates against pinned SHA-256 fingerprints |
| 13 | +/// for specified domains. It uses Dio's native HttpClientAdapter capabilities. |
| 14 | +/// |
| 15 | +/// Usage: |
| 16 | +/// ```dart |
| 17 | +/// final config = SslPinningConfig( |
| 18 | +/// domainFingerprints: { |
| 19 | +/// 'api.example.com': ['MWrOdUsfd6...'], |
| 20 | +/// }, |
| 21 | +/// strictMode: true, |
| 22 | +/// ); |
| 23 | +/// |
| 24 | +/// final dio = Dio(); |
| 25 | +/// dio.httpClientAdapter = SslPinningHttpClientAdapter(config); |
| 26 | +/// ``` |
| 27 | +class SslPinningHttpClientAdapter implements HttpClientAdapter { |
| 28 | + final SslPinningConfig config; |
| 29 | + final IOHttpClientAdapter _ioAdapter = IOHttpClientAdapter(); |
| 30 | + |
| 31 | + SslPinningHttpClientAdapter(this.config) { |
| 32 | + // Configure the underlying adapter's HttpClient creation |
| 33 | + _ioAdapter.createHttpClient = () { |
| 34 | + // Create SecurityContext that doesn't trust any CA certificates by default |
| 35 | + // This forces ALL certificates (valid or invalid) to go through badCertificateCallback |
| 36 | + final securityContext = SecurityContext(withTrustedRoots: false); |
| 37 | + |
| 38 | + final client = HttpClient(context: securityContext); |
| 39 | + |
| 40 | + // CRITICAL: This callback now handles ALL certificates since we disabled trusted roots |
| 41 | + // Every certificate must pass our fingerprint validation |
| 42 | + client.badCertificateCallback = |
| 43 | + (X509Certificate cert, String host, int port) { |
| 44 | + return _validateCertificate(cert, host, port); |
| 45 | + }; |
| 46 | + |
| 47 | + return client; |
| 48 | + }; |
| 49 | + } |
| 50 | + |
| 51 | + @override |
| 52 | + Future<ResponseBody> fetch( |
| 53 | + RequestOptions options, |
| 54 | + Stream<Uint8List>? requestStream, |
| 55 | + Future<void>? cancelFuture, |
| 56 | + ) { |
| 57 | + return _ioAdapter.fetch(options, requestStream, cancelFuture); |
| 58 | + } |
| 59 | + |
| 60 | + @override |
| 61 | + void close({bool force = false}) { |
| 62 | + _ioAdapter.close(force: force); |
| 63 | + } |
| 64 | + |
| 65 | + /// Validate SSL certificate against pinned fingerprints |
| 66 | + bool _validateCertificate(X509Certificate cert, String host, int port) { |
| 67 | + if (!config.enabled) { |
| 68 | + return true; |
| 69 | + } |
| 70 | + |
| 71 | + // Check if domain is pinned |
| 72 | + if (!config.isDomainPinned(host)) { |
| 73 | + if (config.strictMode) { |
| 74 | + // Strict mode: Block unpinned domains |
| 75 | + return false; |
| 76 | + } else { |
| 77 | + // Permissive mode: Allow unpinned domains with standard TLS |
| 78 | + return true; |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + // Domain is pinned - validate certificate fingerprint |
| 83 | + final expectedFingerprints = config.getFingerprintsForDomain(host); |
| 84 | + |
| 85 | + if (expectedFingerprints.isEmpty) { |
| 86 | + return false; |
| 87 | + } |
| 88 | + |
| 89 | + // Calculate SHA-256 fingerprint of the certificate |
| 90 | + final certFingerprint = _getCertificateFingerprint(cert); |
| 91 | + |
| 92 | + // Check if certificate fingerprint matches any expected fingerprint |
| 93 | + final isValid = expectedFingerprints.any((expected) { |
| 94 | + // Normalize both fingerprints (remove colons, convert to uppercase) |
| 95 | + final normalizedExpected = expected.replaceAll(':', '').toUpperCase(); |
| 96 | + final normalizedCert = certFingerprint.replaceAll(':', '').toUpperCase(); |
| 97 | + return normalizedExpected == normalizedCert; |
| 98 | + }); |
| 99 | + |
| 100 | + return isValid; |
| 101 | + } |
| 102 | + |
| 103 | + String _getCertificateFingerprint(X509Certificate cert) { |
| 104 | + try { |
| 105 | + final derBytes = cert.der; |
| 106 | + final base64Der = base64.encode(derBytes); |
| 107 | + final pem = |
| 108 | + '-----BEGIN CERTIFICATE-----\n$base64Der\n-----END CERTIFICATE-----'; |
| 109 | + |
| 110 | + // Parse X509 certificate from PEM |
| 111 | + final x509Cert = X509Utils.x509CertificateFromPem(pem); |
| 112 | + |
| 113 | + // Get the SHA-256 thumbprint of the public key (in hex format) |
| 114 | + final thumbprintHex = |
| 115 | + x509Cert.tbsCertificate?.subjectPublicKeyInfo.sha256Thumbprint ?? ''; |
| 116 | + if (thumbprintHex.isEmpty) { |
| 117 | + return ''; |
| 118 | + } |
| 119 | + // Convert hex string to bytes, then encode to base64 |
| 120 | + final thumbprintBytes = _hexToBytes(thumbprintHex); |
| 121 | + final fingerprint = base64Encode(thumbprintBytes); |
| 122 | + return fingerprint; |
| 123 | + } catch (e) { |
| 124 | + return ''; |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + /// Convert hex string to list of bytes |
| 129 | + /// Example: '919C0DF7A787B597' -> [0x91, 0x9C, 0x0D, 0xF7, 0xA7, 0x87, 0xB5, 0x97] |
| 130 | + List<int> _hexToBytes(String hex) { |
| 131 | + final result = <int>[]; |
| 132 | + for (int i = 0; i < hex.length; i += 2) { |
| 133 | + result.add(int.parse(hex.substring(i, i + 2), radix: 16)); |
| 134 | + } |
| 135 | + return result; |
| 136 | + } |
| 137 | +} |
0 commit comments