# Bypass de SSL Pinning

## **📋 Índice**

1. [Fundamentos do SSL Pinning](#-fundamentos-do-ssl-pinning)
2. [Tipos de SSL Pinning](#-tipos-de-ssl-pinning)
3. [Mecanismos de Bypass](#-mecanismos-de-bypass)
4. [Técnicas de Bypass](#-técnicas-de-bypass)
5. [Ferramentas de Bypass](#-ferramentas-de-bypass)
6. [Bypass Específicos por Framework](#-bypass-específicos-por-framework)
7. [Impacto e Consequências](#-impacto-e-consequências)
8. [Detecção de Bypass](#-detecção-de-bypass)
9. [Mitigações Avançadas](#-mitigações-avançadas)
10. [Checklists de Segurança](#-checklists-de-segurança)

***

## 🔍 **Fundamentos do SSL Pinning**

### **O que é SSL Pinning?**

**SSL Pinning** é uma técnica de segurança que "fixa" (pins) o certificado SSL/TLS esperado de um servidor diretamente no aplicativo. Isso impede que um atacante intercepte o tráfego usando certificados falsos, mesmo que tenha acesso à rede ou tenha comprometido uma Autoridade Certificadora (CA).

### **Princípio de Funcionamento**

```mermaid
sequenceDiagram
    participant A as App
    participant P as Proxy (Atacante)
    participant S as Servidor

    Note over A,S: Conexão Normal
    A->>S: Solicitação HTTPS
    S-->>A: Certificado válido
    A->>A: Valida certificado

    Note over A,P,S: Com SSL Pinning
    A->>P: Solicitação HTTPS
    P->>S: Encaminha
    S-->>P: Certificado válido
    P-->>A: Certificado falso
    A->>A: Verifica pin
    A->>A: Certificado não corresponde
    A-->>P: Conexão rejeitada
```

### **Tipos de SSL Pinning**

| Tipo                    | Descrição                     | Segurança  | Bypass   |
| ----------------------- | ----------------------------- | ---------- | -------- |
| **Certificate Pinning** | Fixa o certificado específico | Alta       | Difícil  |
| **Public Key Pinning**  | Fixa a chave pública          | Média-Alta | Moderado |
| **SPKI Fingerprint**    | Fixa o hash da chave          | Alta       | Difícil  |
| **Hash Pinning**        | Fixa hash do certificado      | Alta       | Difícil  |

***

## 🏗️ **Tipos de SSL Pinning**

### **Implementações Comuns**

```python
#!/usr/bin/env python3
# ssl_pinning_types.py - Tipos de SSL Pinning

class SSLPinningTypes:
    """Análise dos diferentes tipos de SSL Pinning"""
    
    @staticmethod
    def certificate_pinning():
        """Certificate Pinning"""
        print("📜 Certificate Pinning")
        print("=" * 60)
        
        print("""
Funcionamento:
  • Fixa o certificado completo
  • Verifica se o certificado recebido é igual ao esperado
  
Implementação:
  • Armazena o certificado .crt ou .cer no app
  • Compara byte a byte com o certificado recebido
  
Vantagens:
  • Alta segurança
  • Fácil implementação
  
Desvantagens:
  • Certificado expira (precisa atualizar app)
  • Mudança de certificado quebra o app
""")
    
    @staticmethod
    def public_key_pinning():
        """Public Key Pinning"""
        print("\n🔑 Public Key Pinning")
        print("=" * 60)
        
        print("""
Funcionamento:
  • Extrai a chave pública do certificado
  • Verifica se a chave pública corresponde

Implementação:
  • Armazena o hash da chave pública (SPKI)
  • Compara o hash recebido com o armazenado

Vantagens:
  • Mais flexível (chave não expira tão rápido)
  • Permite renovação de certificado

Desvantagens:
  • Mais complexo de implementar
  • Ainda requer atualização em caso de troca de chave
""")
    
    @staticmethod
    def okhttp_pinning():
        """OKHttp Pinning (Android)"""
        print("\n🤖 OKHttp CertificatePinner")
        print("=" * 60)
        
        code = """
// Implementação no OKHttp
CertificatePinner pinner = new CertificatePinner.Builder()
    .add("api.exemplo.com", "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
    .build();

OkHttpClient client = new OkHttpClient.Builder()
    .certificatePinner(pinner)
    .build();
"""
        print(code)
    
    @staticmethod
    def trustmanager_pinning():
        """Custom TrustManager Pinning"""
        print("\n🔐 Custom TrustManager")
        print("=" * 60)
        
        code = """
// Implementação manual com TrustManager
TrustManager[] trustManagers = new TrustManager[] {
    new X509TrustManager() {
        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) {
            // Verificação manual do certificado
            if (!chain[0].getPublicKey().equals(expectedPublicKey)) {
                throw new CertificateException("Invalid certificate");
            }
        }
    }
};
"""
        print(code)

# Executar
SSLPinningTypes.certificate_pinning()
SSLPinningTypes.public_key_pinning()
SSLPinningTypes.okhttp_pinning()
SSLPinningTypes.trustmanager_pinning()
```

***

## ⚔️ **Mecanismos de Bypass**

### **Técnicas de Bypass**

```mermaid
graph TD
    A[SSL Pinning Bypass] --> B[Hooking]
    A --> C[Patch de Código]
    A --> D[Injeção de CA]
    A --> E[SSL Unpinning]
    A --> F[Frida Scripts]
    
    B --> B1[Frida]
    B --> B2[Xposed]
    B --> B3[Objection]
    
    C --> C1[Smali Patch]
    C --> C2[APK Modification]
    
    D --> D1[Magisk Module]
    D --> D2[User CA Install]
    
    E --> E1[SSLUnpinning]
    E --> E2[JustTrustMe]
    
    F --> F1[Universal Scripts]
    F --> F2[Custom Hooks]
    
    style A fill:#ffcc99
    style B fill:#99ccff
    style C fill:#99ccff
```

### **Ferramentas de Bypass**

```yaml
Ferramentas Principais:

  🔧 Frida:
    - Scripts universais de bypass
    - Hooking dinâmico
    - Suporte a múltiplas plataformas

  🔧 Objection:
    - Interface simplificada
    - Comandos automatizados
    - Integração com Frida

  🔧 Xposed:
    - Hooking estático
    - Módulos específicos
    - Requer root

  🔧 Magisk:
    - Módulos de sistema
    - Injeção de CA
    - Persistente
```

***

## 🔧 **Técnicas de Bypass**

### **Técnica 1: Bypass com Frida**

```python
#!/usr/bin/env python3
# frida_ssl_bypass.py - Bypass SSL Pinning com Frida

import frida
import sys

class FridaSSLBypass:
    """Bypass de SSL Pinning usando Frida"""
    
    @staticmethod
    def universal_bypass_script():
        """Script universal de bypass"""
        js_code = """
        Java.perform(function() {
            console.log("[*] Starting SSL Pinning Bypass...");
            
            // 1. Bypass para OkHTTP CertificatePinner
            try {
                var CertificatePinner = Java.use("okhttp3.CertificatePinner");
                CertificatePinner.check.overload('java.lang.String', 'java.util.List').implementation = function() {
                    console.log("[+] OkHTTP CertificatePinner bypassed!");
                    return;
                };
            } catch(e) {}
            
            // 2. Bypass para TrustManager
            try {
                var TrustManager = Java.use("javax.net.ssl.X509TrustManager");
                TrustManager.checkServerTrusted.implementation = function(chain, authType) {
                    console.log("[+] TrustManager bypassed!");
                    return;
                };
            } catch(e) {}
            
            // 3. Bypass para HttpsURLConnection
            try {
                var HttpsURLConnection = Java.use("javax.net.ssl.HttpsURLConnection");
                HttpsURLConnection.setDefaultHostnameVerifier.implementation = function(verifier) {
                    console.log("[+] HttpsURLConnection bypassed!");
                    return;
                };
            } catch(e) {}
            
            // 4. Bypass para Apache HttpClient
            try {
                var AbstractVerifier = Java.use("org.apache.http.conn.ssl.AbstractVerifier");
                AbstractVerifier.verify.implementation = function() {
                    console.log("[+] Apache HttpClient bypassed!");
                    return;
                };
            } catch(e) {}
            
            // 5. Bypass para WebView
            try {
                var WebViewClient = Java.use("android.webkit.WebViewClient");
                WebViewClient.onReceivedSslError.implementation = function(view, handler, error) {
                    console.log("[+] WebView SSL bypassed!");
                    handler.proceed();
                };
            } catch(e) {}
            
            console.log("[*] SSL Pinning bypass completed!");
        });
        """
        
        return js_code
    
    @staticmethod
    def specific_bypass_script(target_class, target_method):
        """Script específico para bypass"""
        js_code = f"""
        Java.perform(function() {{
            console.log("[*] Bypassing {target_class}.{target_method}");
            
            var Target = Java.use("{target_class}");
            Target.{target_method}.implementation = function() {{
                console.log("[+] SSL check bypassed!");
                return;
            }};
        }});
        """
        
        return js_code
    
    @staticmethod
    def execute_bypass(package_name, script_type="universal"):
        """Executar bypass no aplicativo"""
        print(f"[*] Anexando ao processo: {package_name}")
        
        try:
            device = frida.get_usb_device()
            session = device.attach(package_name)
            
            if script_type == "universal":
                script_code = FridaSSLBypass.universal_bypass_script()
            else:
                script_code = FridaSSLBypass.specific_bypass_script(
                    script_type.split('.')[0], 
                    script_type.split('.')[1]
                )
            
            script = session.create_script(script_code)
            script.load()
            
            print("[+] SSL Pinning bypass injetado com sucesso!")
            print("[+] Tráfego HTTPS pode ser interceptado agora")
            
            return session
            
        except Exception as e:
            print(f"[-] Erro: {e}")
            return None

# Uso
if __name__ == "__main__":
    print("🔓 Frida SSL Pinning Bypass")
    print("=" * 60)
    
    package = input("Digite o nome do pacote: ")
    FridaSSLBypass.execute_bypass(package, "universal")
```

### **Técnica 2: Bypass com Objection**

```bash
#!/bin/bash
# objection_ssl_bypass.sh - Bypass com Objection

# 1. Instalar objection
pip3 install objection

# 2. Executar bypass automático
objection -g com.exemplo.app explore

# 3. Comandos dentro do objection
# Listar atividades
android hooking list activities

# Desabilitar SSL Pinning
android sslpinning disable

# Listar hooks ativos
jobs list

# 4. Script personalizado
objection -g com.exemplo.app explore -s "android sslpinning disable"

# 5. Com spawn (app não rodando)
objection -g com.exemplo.app explore --startup-command "android sslpinning disable"
```

### **Técnica 3: Bypass com Xposed**

```java
// XposedSSLUnpinning.java - Módulo Xposed para bypass

import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage;

public class XposedSSLUnpinning implements IXposedHookLoadPackage {
    
    @Override
    public void handleLoadPackage(XC_LoadPackage.LoadPackageParam lpparam) {
        
        // 1. Bypass OkHTTP CertificatePinner
        if (lpparam.packageName.equals("com.exemplo.app")) {
            XposedHelpers.findAndHookMethod(
                "okhttp3.CertificatePinner",
                lpparam.classLoader,
                "check",
                String.class,
                List.class,
                new XC_MethodHook() {
                    @Override
                    protected void beforeHookedMethod(MethodHookParam param) {
                        XposedBridge.log("OkHTTP CertificatePinner bypassed!");
                        param.setResult(null);
                    }
                }
            );
            
            // 2. Bypass TrustManager
            XposedHelpers.findAndHookMethod(
                "javax.net.ssl.X509TrustManager",
                lpparam.classLoader,
                "checkServerTrusted",
                X509Certificate[].class,
                String.class,
                new XC_MethodHook() {
                    @Override
                    protected void beforeHookedMethod(MethodHookParam param) {
                        XposedBridge.log("TrustManager bypassed!");
                        param.setResult(null);
                    }
                }
            );
        }
    }
}
```

### **Técnica 4: Patch de APK**

```bash
#!/bin/bash
# apk_patch_ssl.sh - Patch de APK para bypass SSL

# 1. Decompilar APK
apktool d app.apk -o decompiled/

# 2. Buscar implementações de SSL Pinning
grep -r "CertificatePinner" decompiled/
grep -r "checkServerTrusted" decompiled/

# 3. Modificar smali
# Exemplo: modificar CertificatePinner.check para retornar vazio

# 4. Recompilar APK
apktool b decompiled/ -o app_patched.apk

# 5. Assinar APK
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my.keystore app_patched.apk alias_name

# 6. Instalar
adb install app_patched.apk
```

### **Técnica 5: Injeção de CA via Magisk**

```bash
#!/system/bin/sh
# magisk_ca_inject.sh - Injeção de CA via Magisk

# 1. Criar módulo Magisk
mkdir -p /data/adb/modules/ca_inject/system/etc/security/

# 2. Copiar certificado CA
cp custom_ca.crt /data/adb/modules/ca_inject/system/etc/security/cacerts/

# 3. Calcular hash do certificado
HASH=$(openssl x509 -inform PEM -subject_hash_old -in custom_ca.crt | head -1)

# 4. Renomear certificado
mv /data/adb/modules/ca_inject/system/etc/security/cacerts/custom_ca.crt \
   /data/adb/modules/ca_inject/system/etc/security/cacerts/${HASH}.0

# 5. Configurar módulo
echo "id=ca_inject" > /data/adb/modules/ca_inject/module.prop
echo "name=Custom CA Injector" >> /data/adb/modules/ca_inject/module.prop
echo "version=1.0" >> /data/adb/modules/ca_inject/module.prop
echo "versionCode=1" >> /data/adb/modules/ca_inject/module.prop
echo "author=Attacker" >> /data/adb/modules/ca_inject/module.prop
echo "description=Inject custom CA for SSL interception" >> /data/adb/modules/ca_inject/module.prop

# 6. Reiniciar
reboot
```

***

## 🛠️ **Bypass Específicos por Framework**

### **OkHTTP Bypass**

```python
#!/usr/bin/env python3
# okhttp_bypass.py - Bypass específico para OkHTTP

class OkHTTPBypass:
    """Bypass de SSL Pinning para OkHTTP"""
    
    @staticmethod
    def frida_script():
        """Script Frida para OkHTTP"""
        js_code = """
        Java.perform(function() {
            console.log("[*] Bypassing OkHTTP SSL Pinning");
            
            // OkHTTP 3.x CertificatePinner
            var CertificatePinner = Java.use("okhttp3.CertificatePinner");
            CertificatePinner.check.overload('java.lang.String', 'java.util.List').implementation = function() {
                console.log("[+] OkHTTP 3.x bypassed!");
                return;
            };
            
            // OkHTTP 4.x CertificatePinner
            CertificatePinner.check.overload('java.lang.String', 'java.util.List', 'java.security.cert.Certificate').implementation = function() {
                console.log("[+] OkHTTP 4.x bypassed!");
                return;
            };
        });
        """
        return js_code
    
    @staticmethod
    def xposed_hook():
        """Xposed hook para OkHTTP"""
        java_code = """
        XposedHelpers.findAndHookMethod(
            "okhttp3.CertificatePinner",
            lpparam.classLoader,
            "check",
            String.class,
            List.class,
            new XC_MethodHook() {
                @Override
                protected void beforeHookedMethod(MethodHookParam param) {
                    XposedBridge.log("OkHTTP SSL Pinning bypassed!");
                    param.setResult(null);
                }
            }
        );
        """
        return java_code
```

### **Retrofit Bypass**

```python
#!/usr/bin/env python3
# retrofit_bypass.py - Bypass para Retrofit

class RetrofitBypass:
    """Bypass de SSL Pinning para Retrofit"""
    
    @staticmethod
    def frida_script():
        """Script Frida para Retrofit"""
        js_code = """
        Java.perform(function() {
            console.log("[*] Bypassing Retrofit SSL Pinning");
            
            // Retrofit usa OkHTTP internamente
            var CertificatePinner = Java.use("okhttp3.CertificatePinner");
            CertificatePinner.check.overload('java.lang.String', 'java.util.List').implementation = function() {
                console.log("[+] Retrofit bypassed (via OkHTTP)!");
                return;
            };
        });
        """
        return js_code
```

### **WebView Bypass**

```python
#!/usr/bin/env python3
# webview_bypass.py - Bypass para WebView

class WebViewBypass:
    """Bypass de SSL Pinning para WebView"""
    
    @staticmethod
    def frida_script():
        """Script Frida para WebView"""
        js_code = """
        Java.perform(function() {
            console.log("[*] Bypassing WebView SSL Pinning");
            
            var WebViewClient = Java.use("android.webkit.WebViewClient");
            
            WebViewClient.onReceivedSslError.overload(
                'android.webkit.WebView', 
                'android.webkit.SslErrorHandler', 
                'android.net.http.SslError'
            ).implementation = function(webView, handler, error) {
                console.log("[+] WebView SSL error bypassed!");
                handler.proceed();
            };
            
            var WebChromeClient = Java.use("android.webkit.WebChromeClient");
            // Algumas implementações personalizadas podem precisar de hooks adicionais
        });
        """
        return js_code
    
    @staticmethod
    def custom_webview_client():
        """Implementação de WebViewClient que aceita todos os certificados"""
        java_code = """
        class InsecureWebViewClient extends WebViewClient {
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                // Aceitar todos os erros SSL
                handler.proceed();
            }
        }
        
        // Uso
        webView.setWebViewClient(new InsecureWebViewClient());
        """
        return java_code
```

### **Volley Bypass**

```python
#!/usr/bin/env python3
# volley_bypass.py - Bypass para Volley

class VolleyBypass:
    """Bypass de SSL Pinning para Volley"""
    
    @staticmethod
    def frida_script():
        """Script Frida para Volley"""
        js_code = """
        Java.perform(function() {
            console.log("[*] Bypassing Volley SSL Pinning");
            
            // Volley usa HttpsURLConnection
            var HttpsURLConnection = Java.use("javax.net.ssl.HttpsURLConnection");
            
            HttpsURLConnection.setDefaultHostnameVerifier.implementation = function(verifier) {
                console.log("[+] Volley bypassed!");
                return;
            };
            
            // Bypass TrustManager
            var TrustManager = Java.use("javax.net.ssl.X509TrustManager");
            TrustManager.checkServerTrusted.implementation = function(chain, authType) {
                console.log("[+] TrustManager bypassed for Volley!");
                return;
            };
        });
        """
        return js_code
```

***

## 🔍 **Detecção de Bypass**

### **Monitoramento de Hooks**

```python
#!/usr/bin/env python3
# detect_ssl_bypass.py - Detecção de bypass de SSL Pinning

import frida
import sys

class SSLByPassDetector:
    """Detector de tentativas de bypass de SSL Pinning"""
    
    @staticmethod
    def detect_frida():
        """Detectar Frida"""
        print("[*] Detectando Frida...")
        
        # Verificar portas comuns do Frida
        import socket
        frida_ports = [27042, 27043, 27044]
        
        for port in frida_ports:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            result = sock.connect_ex(('127.0.0.1', port))
            if result == 0:
                print(f"   ⚠️ Frida detectada na porta {port}")
                return True
        
        # Verificar processos
        import subprocess
        result = subprocess.run(['ps', '-A'], capture_output=True, text=True)
        if 'frida' in result.stdout.lower():
            print("   ⚠️ Processo Frida detectado")
            return True
        
        print("   ✅ Nenhuma instância do Frida detectada")
        return False
    
    @staticmethod
    def detect_xposed():
        """Detectar Xposed Framework"""
        print("\n[*] Detectando Xposed...")
        
        # Verificar arquivos do Xposed
        import os
        xposed_paths = [
            "/data/data/de.robv.android.xposed.installer",
            "/system/framework/XposedBridge.jar",
            "/system/lib/libxposed_art.so"
        ]
        
        for path in xposed_paths:
            if os.path.exists(path):
                print(f"   ⚠️ Xposed detectado: {path}")
                return True
        
        print("   ✅ Xposed não detectado")
        return False
    
    @staticmethod
    def detect_magisk():
        """Detectar Magisk"""
        print("\n[*] Detectando Magisk...")
        
        import os
        magisk_paths = [
            "/data/adb/magisk",
            "/sbin/.magisk",
            "/sbin/magisk"
        ]
        
        for path in magisk_paths:
            if os.path.exists(path):
                print(f"   ⚠️ Magisk detectado: {path}")
                return True
        
        print("   ✅ Magisk não detectado")
        return False
    
    @staticmethod
    def detect_debugging():
        """Detectar depuração"""
        print("\n[*] Detectando depuração...")
        
        import subprocess
        result = subprocess.run(['getprop', 'ro.debuggable'], capture_output=True, text=True)
        
        if '1' in result.stdout:
            print("   ⚠️ Sistema debuggable!")
            return True
        
        print("   ✅ Sistema não debuggable")
        return False

# Uso
if __name__ == "__main__":
    print("🔍 SSL Pinning Bypass Detector")
    print("=" * 60)
    
    SSLByPassDetector.detect_frida()
    SSLByPassDetector.detect_xposed()
    SSLByPassDetector.detect_magisk()
    SSLByPassDetector.detect_debugging()
```

***

## 🛡️ **Mitigações Avançadas**

### **Proteções Adicionais**

```yaml
Mitigações Avançadas:

  ✅ Certificate Transparency:
    - Verificar logs CT
    - Detectar certificados fraudulentos

  ✅ Multiple Pinning:
    - Usar múltiplos certificados/pins
    - Backup pins para renovação

  ✅ Dynamic Pinning:
    - Atualizar pins via servidor
    - Pins distribuídos dinamicamente

  ✅ Integrity Checks:
    - Verificar integridade do app
    - Detectar modificações no código

  ✅ Anti-Debugging:
    - Detectar depuração
    - Detectar hooks de Frida/Xposed

  ✅ Obfuscation:
    - Ofuscar código de pinning
    - Esconder pins no código
```

### **Implementação Segura**

```java
// AdvancedSSLPinning.java - SSL Pinning avançado

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;

import java.security.MessageDigest;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Arrays;

import javax.net.ssl.X509TrustManager;

public class AdvancedSSLPinning implements X509TrustManager {
    
    private static final String[] EXPECTED_PINS = {
        "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
        "sha256/BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB="
    };
    
    private Context context;
    
    public AdvancedSSLPinning(Context context) {
        this.context = context;
    }
    
    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType) 
            throws CertificateException {
        
        // 1. Verificação de integridade do app
        if (!isAppIntegrityValid()) {
            throw new CertificateException("App integrity check failed");
        }
        
        // 2. Verificação de anti-debug
        if (isDebuggerAttached()) {
            throw new CertificateException("Debugger detected");
        }
        
        // 3. Verificação do certificado
        for (X509Certificate cert : chain) {
            String pin = generatePin(cert);
            
            boolean found = false;
            for (String expectedPin : EXPECTED_PINS) {
                if (pin.equals(expectedPin)) {
                    found = true;
                    break;
                }
            }
            
            if (!found) {
                throw new CertificateException("Certificate pin mismatch");
            }
        }
    }
    
    private String generatePin(X509Certificate cert) {
        try {
            byte[] publicKey = cert.getPublicKey().getEncoded();
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] digest = md.digest(publicKey);
            return "sha256/" + android.util.Base64.encodeToString(digest, android.util.Base64.NO_WRAP);
        } catch (Exception e) {
            return "";
        }
    }
    
    private boolean isAppIntegrityValid() {
        try {
            PackageInfo packageInfo = context.getPackageManager()
                .getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
            
            Signature[] signatures = packageInfo.signatures;
            // Verificar assinatura do app
            // Comparar com assinatura esperada
            
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    
    private boolean isDebuggerAttached() {
        return android.os.Debug.isDebuggerConnected();
    }
    
    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType) {}
    
    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }
}
```

***

## 📋 **Checklists de Segurança**

### **Checklist para Desenvolvedores**

* [ ] Implementar SSL Pinning em todas as conexões HTTPS
* [ ] Usar múltiplos pins (certificado atual + backup)
* [ ] Implementar anti-debugging
* [ ] Ofuscar código de pinning
* [ ] Verificar integridade do app
* [ ] Atualizar pins via servidor (dynamic pinning)

### **Checklist para Pentesters**

* [ ] Testar bypass com Frida (universal script)
* [ ] Testar bypass com Objection
* [ ] Verificar se há proteções anti-debug
* [ ] Testar patch de APK
* [ ] Verificar múltiplas implementações de pinning
* [ ] Documentar método de bypass utilizado

***

## 📊 **Conclusão**

```yaml
Bypass de SSL Pinning:

  🔴 Principais Técnicas:
    - Frida hooking
    - Xposed modules
    - APK patching
    - CA injection via Magisk

  🛡️ Mitigações Essenciais:
    - Múltiplos pins
    - Anti-debugging
    - Integrity checks
    - Dynamic pinning
    - Code obfuscation

  🎯 Prioridade:
    - CRÍTICA: Apps financeiros/bancários
    - ALTA: Apps com dados sensíveis
    - MÉDIA: Apps corporativos
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://0xmorte.gitbook.io/bibliadopentestbr/tecnicas/sistemas-operacionais/android/bypass-de-ssl-pinning.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
