TLS 証明書検証の無効化

TLS 証明書検証の無効化

説明

rejectUnauthorized: false では、信頼できない証明書やホスト名が一致しない証明書でも TLS 接続が成立する場合があります。NODE_TLS_REJECT_UNAUTHORIZED=0 はプロセス全体の既定の検証に影響します。

想定される影響

通信が暗号化されていても、正規のサーバーになりすました相手に認証情報やセッショントークンが渡ったり、応答を変更されたりするおそれがあります。

対処方法

  • rejectUnauthorized は既定値の true にし、検証を無効にする環境設定を削除してください。テストに使う CA は本番の設定から分離します。
  • https.Agent や tls.connect に ca を指定すると、既定の CA 一覧が置き換わります。必要な CA をすべて含め、ホスト名も検証してください。SNI が必要なサーバーには、tls.connect の host と併せて servername を指定します。
  • 証明書や公開鍵を固定する場合は、信頼できる経路で照合する値を入手し、証明書更新時の動作を確認してください。

例

変更前

javascript
// 変更前の例 1: 証明書検証を全体で無効化
const https = require('https');
const tls = require('tls');

function fetchInsecure() {
  // TLS 検証の全体的な無効化は危険
  process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

  https.get({ hostname: 'api.example.org', path: '/v1/data' }, (res) => {
    res.on('data', () => {});
  });
}

// 変更前の例 2: エージェントで証明書検証を無効化
function postInsecure() {
  const insecureAgent = new https.Agent({ keepAlive: true, rejectUnauthorized: false });

  const req = https.request({
    hostname: 'secure.example.org',
    method: 'POST',
    path: '/login',
    agent: insecureAgent,
    headers: { 'Content-Type': 'application/json' }
  }, (res) => res.resume());

  req.write(JSON.stringify({ user: 'alice', pass: 'secret' }));
  req.end();
}

変更後

javascript
// 変更後: 既定の検証を維持し、信頼する CA バンドルを使用
const https = require('https');
const fs = require('fs');

// 社内または公開 CA バンドルのパスの例
const caBundle = fs.readFileSync('/etc/ssl/certs/company-ca-bundle.pem');

function fetchSecure() {
  // rejectUnauthorized の既定値は true
  const secureAgent = new https.Agent({
    keepAlive: true,
    ca: caBundle,           // 信頼する CA を指定
    // https は要求先ホストから servername を設定するため、無効にしない
  });

  https.get({
    hostname: 'api.example.org',
    path: '/v1/data',
    agent: secureAgent
  }, (res) => {
    let body = '';
    res.on('data', (c) => body += c);
    res.on('end', () => console.log('OK:', body.length));
  });
}

// 必要に応じた証明書ピンニング: 証明書の SHA-256 フィンガープリントを比較
const tls = require('tls');
function connectWithPinning(expectedFingerprint256) {
  const socket = tls.connect({ host: 'secure.example.org', port: 443, ca: caBundle }, () => {
    const cert = socket.getPeerCertificate(true);
    if (!cert || !cert.fingerprint256 || cert.fingerprint256 !== expectedFingerprint256) {
      socket.destroy(new Error('Certificate pinning mismatch'));
      return;
    }
    socket.write('GET / HTTP/1.1\r\nHost: secure.example.org\r\n\r\n');
  });
}

例では CA バンドルを使います。任意の fingerprint256 チェックは証明書全体の SHA-256 フィンガープリントを比較し、不一致ならリクエストの送信前に接続を閉じます。

参考資料