萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP cURL 處理 HTTPS 請求:SSL 證書驗證失敗的兩種解決方案與最佳實踐

錯誤現象

SSL certificate problem: unable to get local issuer certificate
// 或
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

原因:cURL 內建 CA 憑證庫過期/缺失,或目標站點使用自簽名/私有 CA 證書。

方案一:跳過驗證 (⚠ 僅限開發/測試/內網)

<?php
function curlInsecure($url) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false, // 不驗證證書
        CURLOPT_SSL_VERIFYHOST => 0,     // 不驗證域名匹配
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_TIMEOUT => 30,
    ]);
    $response = curl_exec($ch);
    $err = curl_error($ch);
    curl_close($ch);
    if ($err) throw new Exception($err);
    return $response;
}
// ⚠ 生產環境嚴禁使用!中間人攻擊風險極高

方案二:配置正確 CA 憑證包 (✅ 生產環境標準)

步驟 1:獲取最新 CA Bundle

# 下載 Mozilla 信任根證書庫 (定期更新)
curl -o cacert.pem https://curl.se/ca/cacert.pem
# 或從 https://github.com/bagder/ca-bundle 獲取

步驟 2:配置 php.ini (全域生效)

; php.ini
curl.cainfo = "/absolute/path/to/cacert.pem"
openssl.cafile = "/absolute/path/to/cacert.pem"  # 也影響 file_get_contents、SoapClient 等

步驟 3:或在程式碼中指定 (單一請求控制)

<?php
function curlSecure($url, $caFile = null) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => true,   // 必須開啟
        CURLOPT_SSL_VERIFYHOST => 2,      // 必須為 2 (檢查 CN/SAN)
        CURLOPT_CAINFO => $caFile ?? __DIR__ . '/cacert.pem', // 指定 CA 文件
        // CURLOPT_CAPATH => '/etc/ssl/certs', // 或指定目錄
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_TIMEOUT => 30,
    ]);
    $response = curl_exec($ch);
    if (curl_errno($ch)) throw new Exception(curl_error($ch));
    curl_close($ch);
    return $response;
}

進階:自簽名/私有 CA 證書支援

<?php
// 合併系統 CA + 自定義 CA
$customCa = __DIR__ . '/custom-ca.pem'; // 你的私有 CA 證書
$systemCa = __DIR__ . '/cacert.pem';    // Mozilla CA

// 方案 A:合併成單一檔案 (cat cacert.pem custom-ca.pem > combined-ca.pem)
curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . '/combined-ca.pem');

// 方案 B:使用 CURLOPT_CAPATH 指定目錄 (需 c_rehash 處理)
// curl_setopt($ch, CURLOPT_CAPATH, '/etc/ssl/certs');

// 方案 C:運行時動態添加 (需 OpenSSL 1.1.1+)
$ctx = stream_context_create([
    'ssl' => [
        'cafile' => $systemCa,
        'capath' => '/etc/ssl/certs',
        'verify_peer' => true,
        'verify_peer_name' => true,
    ]
]);
// 但 cURL 不直接支援 stream context,需編譯支援或用 file_get_contents

證書釘選 - 最高安全等級

防止 CA 被入侵簽發偽造證書,直接釘選目標站點公鑰雜湊:

<?php
function curlWithPinning($url, array $pinnedSha256) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,
        CURLOPT_CAINFO => __DIR__ . '/cacert.pem',
        CURLOPT_PINNEDPUBLICKEY => 'sha256//' . $pinnedSha256[0], // 主鍵
        // CURLOPT_PINNEDPUBLICKEY 可接受多個: 'sha256//key1;sha256//key2'
    ]);
    // 注意:CURLOPT_PINNEDPUBLICKEY 需要 cURL 7.39+ 與 OpenSSL/GnuTLS 支援
    return curl_exec($ch);
}

// 獲取目標站點公鑰 SHA256
// openssl s_client -connect api.example.com:443 -servername api.example.com < /dev/null \
//   | openssl x509 -pubkey -noout | openssl pkey -pubin -outform der | openssl dgst -sha256 -binary | base64

常見問題排查表

CURLE_SSL_CACERT_BADFILE
錯誤原因解決
unable to get local issuer certificateCA Bundle 缺失/過期更新 cacert.pem 並配置 curl.cainfo
certificate verify failed: self signed certificate目標使用自簽名證書將自簽名 CA 加入 CA Bundle 或使用證書釘選
certificate verify failed: certificate has expired目標證書過期通知站點更新證書,或暫時跳過驗證(風險自負)
SSL: no alternative certificate subject name matches target host name證書 CN/SAN 不包含請求域名檢查域名拼寫、CDN 配置、虛擬主機 SNI
CA 文件路徑錯誤/格式錯誤確認絕對路徑、PEM 格式、讀取權限

容器化部署注意事項

# Dockerfile
FROM php:8.2-fpm
# 安裝 ca-certificates (包含系統 CA)
RUN apt-get update && apt-get install -y ca-certificates curl \
    && rm -rf /var/lib/apt/lists/*
# 複製自定義 CA (如有)
COPY custom-ca.pem /usr/local/share/ca-certificates/
RUN update-ca-certificates
# PHP 會自動使用系統 /etc/ssl/certs

總結

  1. 生產環境必須啟用驗證:CURLOPT_SSL_VERIFYPEER => true
  2. 維護最新 CA Bundle:定期更新 cacert.pem,配置 curl.cainfo
  3. 自簽名/私有 CA:合併至 CA Bundle 或使用證書釘選
  4. 高安全場景:實施 Public Key Pinning (HPKP 替代方案)
  5. 除錯技巧:curl -v、openssl s_client、CURLOPT_VERBOSE
copyright © 萬盛學電腦網 all rights reserved