Weathernews Tech Blog
🔒

AWS Private CA で AKI 付き証明書を発行してみた

に公開

まとめ

  • Python 3.13 環境で自己署名証明書を使うと発生した Missing Authority Key Identifier エラーの原因と対処方法を検証しました。
  • AWS Private CA を使ってプライベート CA を用意し、AKI(Authority Key Identifier)付きの証明書を発行しました。
    • 認証局は CloudFormation で作成しました。
    • 証明書発行は Python スクリプトで自動化しました。

技術スタック

  • 言語 / ランタイム: Python 3.13
  • 主要ライブラリ: boto3, cryptography, requests
  • クラウド / サービス: AWS Private CA (ACM PCA), AWS SSM (Parameter Store)
  • IaC / ツール: CloudFormation, OpenSSL (CSR 作成)
  • 検証環境: macOS / OpenSSL, ローカル Python 環境

はじめに

はじめまして、株式会社ウェザーニューズの tanimo と申します。2021 年に新卒入社して以来、弊社インフラの監視システム開発・運用を行っており、いかにインシデントを最小にするか、頭を悩ませる日々を過ごしています。

今回は、プライベート証明書運用で遭遇した Authority Key Identifier (AKI) に関する問題と、その解決手順を整理して紹介します。

今回の課題

Python の requests パッケージで https アクセスする際に、自己署名証明書を使用したサーバにアクセスできなくなりました。

Authority Key Identifier Error

エラー内容

urllib3.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: Missing Authority Key Identifier (_ssl.c:1032)

エラーを見ると、証明書の検証に失敗している様子。「Authority Key Identifier」が足りないようです。証明書を使わない設定もできます[1]が、今回は正しく証明書を使用する方法を検証します。

目指す実行形式

以下のように、環境変数 REQUESTS_CA_BUNDLE にカスタム証明書を設定することで、エラーなく実行できる環境を目指します。

import os
import requests

os.environ["REQUESTS_CA_BUNDLE"] = "/Path/To/Your/CustomCert.pem"
response = requests.get("https://example.com/api")
print(f"Status Code: {response.status_code}")

調べてみた

Python3.13 の証明書検証方法変化

調べてみると、Python3.13 から証明書の検証が変更されたようです。参考にさせていただいたこちらの記事で、詳細な検証がされています。

この変更では、SSL 検証のデフォルトに VERIFY_X509_STRICT というフラグが追加されました。これにより、RFC 5280 に厳格に準拠した実装が求められるようになり、Authority Key Identifier を含まない証明書は不適切と判定されるようになったようです。

The default settings for this context include VERIFY_X509_PARTIAL_CHAIN and VERIFY_X509_STRICT. These make the underlying OpenSSL implementation behave more like a conforming implementation of RFC 5280, in exchange for a small amount of incompatibility with older X.509 certificates. (引用: Python3.13 Documentation)

そもそも 「Authority Key Identifier (AKI)」 とは?

RFC 5280 のドキュメントを参照し、 Authority Key Identifier について詳細を調べます。

The keyIdentifier field of the authorityKeyIdentifier extension MUST be included in all certificates generated by conforming CAs to facilitate certification path construction.
There is one exception; where a CA distributes its public key in the form of a "self-signed" certificate, the authority key identifier MAY be omitted.
The signature on a self-signed certificate is generated with the private key associated with the certificate's subject public key. (This proves that the issuer possesses both the public and private keys.) (引用:RFC 5280: Authority-Key-Identifier)

つまり、

  • 証明書の署名に使用された秘密鍵に対応する 公開鍵を識別する手段 で、原則証明書に含まれている必要がある。
  • 例外として、自己署名証明書では Subject Key Identifier (SKI) と一致するため、省略可能。

ということのようです。今回発生したエラーは、AKI を含まない自己署名証明書を使っていたため、Python 3.13 のデフォルト検証で弾かれた、と解釈できます。Python 3.13 以降の厳格モードでは、AKI が実質的に必須となったといえるでしょう。

これを解決するには、以下 2 つのアプローチが考えられます。

  1. AKI を含む自己署名証明書を発行する。
  2. 証明書に署名するプライベート認証局を作成する。

今回は、2 番目のアプローチを取り、AWS Private CA を使用して認証局を作成してみます。

作成する構成は以下のようになります。

Build Authentication Infra Using AWS Private CA

AWS Private CA を使用する

学習方法

余談ですが、社内的に知見がなかった AWS Private CA を理解するにあたり、

AWS ドキュメント(English/PDF) + Notebook LM

の学習スタイルで、ドキュメントを読み解いていきました。

  1. Notebook LM のサマリで概要を把握する。
  2. 疑問点をチャット形式で確認し、ドキュメントの該当箇所を特定する。
  3. ドキュメント本文にあたって、 Notebook LM の回答を確認し、周辺情報を理解する。[2]

という形式を繰り返すことで、比較的短時間で概要を理解することができました。

やってみた

CloudFormation で AWS Private CA を構築する

まずは、AWS Private CA でルート認証局を作ります。

CloudFormation Template
template.yaml
AWSTemplateFormatVersion: 2010-09-09
Description: Cloudformation template to setup Private Root CA.
Transform:
  - AWS::Serverless-2016-10-31
  - AWS::LanguageExtensions

Resources:
  RootCA:
    Type: "AWS::ACMPCA::CertificateAuthority"
    Properties:
      Type: ROOT
      KeyAlgorithm: RSA_2048
      SigningAlgorithm: SHA256WITHRSA
      Subject:
        Country: JP
        Organization: WNI
        OrganizationalUnit: hoge
        State: hoge
        CommonName: hoge
        Locality: hoge
        GenerationQualifier: G1
      RevocationConfiguration:
        CrlConfiguration:
          Enabled: false # 失効設定: まずは検証のため false で設定し、後から有効化できます。
      UsageMode: GENERAL_PURPOSE

  RootCaSsmParameter:
    Type: AWS::SSM::Parameter
    Properties:
      Name: !Sub /PrivateCA/RootCA/arn
      Type: String
      Value: !GetAtt RootCA.Arn
  • 作成した認証局の ARN は証明書作成に使用されるため、利用しやすいように SSM パラメータストアに出力しています。
  • 各設定値については、AWS Private CA ドキュメント を参照してください。

これを CloudFormation でデプロイすると、ステータスが Pending certificate の認証局が作成されます。次の手順で証明書をインポートすることで、ステータスが Active に変わります。

証明書を発行する

AWS Private CA において、証明書を発行するには、次の手順をたどります。

手順 AWS Private CA 向けの証明書の場合 他のエンティティ向けの証明書の場合
1 CSR の発行 get_certificate_authority_csr 非認証サーバで CSR を発行する(OpenSSL など)
2 テンプレート+ CSR で証明書を発行する issue_certificate issue_certificate
3 証明書を取得する get_certificate get_certificate
4 認証対象に証明書をインポートする import_certificate_authority_certificate 非認証サーバに証明書をインポート

AWS Private CA では、証明書発行時にテンプレートを指定する必要があります。テンプレートは AWS Private CA template definitions から、以下のように選択します。

例示すると、

  • 「拡張機能つき」+「ルート認証局の証明書」 → RootCACertificate_APIPassthrough/V1
  • 「パス長 0」+「中間証明書」→ SubordinateCACertificate_PathLen0/V1

など。

AKI つきの CA 証明書を発行する手順は、AWS ドキュメントに記載されている「Activate a Product Attestation Authority (PAA)」に示されています。サンプルは Java ベースのため、本記事では Python での実装例を示します。

1. AKI つき CA 証明書を発行する

ルート認証局には、自分自身を認証局と認める自己署名証明書が必要になります。この後の手順では、ルート認証局の自己署名証明書を発行しています。

構築対象1

まずは下準備。セッションを張ります。

Python Sample: make_pca_client
import boto3
from botocore.client import BaseClient


def make_pca_client(region_name: str, profile_name: str) -> BaseClient:
    session = boto3.Session(profile_name=profile_name)
    return session.client("acm-pca", region_name=region_name)


pca_client = make_pca_client(region_name="ap-northeast-1", profile_name="your-profile-name")
1.1. CSR を発行する

ルート認証局自身から CSR (証明書署名要求) を取得します。

Python Sample: get_csr
from botocore.client import BaseClient


def get_csr(pca_client: BaseClient, root_ca_arn: str) -> str:
    response = pca_client.get_certificate_authority_csr(
        CertificateAuthorityArn=root_ca_arn,
    )
    csr = response["Csr"]
    print("CSRを取得しました\n%s", csr)
    return csr


csr = get_csr(pca_client=pca_client, root_ca_arn="your root ca arn")
1.2. AKI つき証明書を発行する

前述の通り、 Authority Key Identifier (AKI) は Subject Key Identifier (SKI) から算出できますが、この SKI は CSR から取得できます。

CSR → SKI → AKI という取得手順で AKI の値を算出し、証明書発行時に指定してあげます。

python で AKI を算出するにあたり, cryptography パッケージを使用しました。

Python Sample: AKI の算出
import base64

from cryptography import x509
from cryptography.hazmat.backends import default_backend


def get_ski_from_csr(
    csr_pem: str,
) -> x509.SubjectKeyIdentifier:
    csr = x509.load_pem_x509_csr(
        csr_pem.encode(),
        default_backend(),
    )
    public_key = csr.public_key()
    return x509.SubjectKeyIdentifier.from_public_key(public_key)


def generate_aki_from_ski(
    subject_key_identifier: x509.SubjectKeyIdentifier,
) -> str:
    ski_digest = subject_key_identifier.digest
    authority_key_identifier = x509.AuthorityKeyIdentifier(
        key_identifier=ski_digest,
        authority_cert_issuer=None,
        authority_cert_serial_number=None,
    )
    return base64.b64encode(authority_key_identifier.public_bytes()).decode()


subject_key_identifier = get_ski_from_csr(csr)
encoded_authority_key_identifier = generate_aki_from_ski(subject_key_identifier)

AKI はカスタム拡張に含まれるため、ApiPassthrough を使用できる証明書テンプレート "arn:aws:acm-pca:::template/RootCACertificate_APIPassthrough/V1" を使用する必要があります。CustomExtensions に、AKI のオブジェクト識別子 2.5.29.35 を指定し、以下のように証明書を発行します。

from botocore.client import BaseClient


def issue_certificate(
    pca_client: BaseClient,
    root_ca_arn: str,
    template_arn: str,
    csr: str,
    custom_extensions: dict[str, str] | None = None,
) -> str:
    issue_request = {
        "CertificateAuthorityArn": root_ca_arn,
        "Csr": csr.encode("utf-8"),
        "SigningAlgorithm": "SHA256WITHRSA",
        "TemplateArn": template_arn,
        "Validity": {"Value": 100, "Type": "DAYS"},
    }

    if custom_extensions:
        issue_request["ApiPassthrough"] = {"Extensions": {"CustomExtensions": custom_extensions}}

    response = pca_client.issue_certificate(**issue_request)
    return response["CertificateArn"]


root_certificate_arn = issue_certificate(
    pca_client=pca_client,
    root_ca_arn=root_ca_arn,
    template_arn="arn:aws:acm-pca:::template/RootCACertificate_APIPassthrough/V1",  # 条件に合わせてテンプレートを変更する
    csr=csr,
    custom_extensions={
        "ObjectIdentifier": "2.5.29.35", # AKI 拡張機能を示すオブジェクト識別子(OID)
        "Value": encoded_authority_key_identifier,  # 算出結果
    },
)
1.3. 証明書を取得する

発行完了を待機し、発行された証明書を取得します。この証明書は、以下の 2 つの用途で使用します。

  1. ルート認証局へインポートする。
  2. 被認証サーバにアクセスするクライアント PC の信頼ストアに配布する。
from botocore.client import BaseClient


def get_certificate(
    pca_client: BaseClient,
    certificate_arn: str,
    certificate_authority_arn: str,
) -> str:
    certificate_request = {
        "CertificateArn": certificate_arn,
        "CertificateAuthorityArn": certificate_authority_arn,
    }
    # 証明書が発行されるまで待機してから取得する
    waiter = pca_client.get_waiter("CertificateIssued")
    waiter.wait(**certificate_request)
    response = pca_client.get_certificate(**certificate_request)
    return response["Certificate"]
1.4. 発行した証明書をルート認証局にインポートする

証明書をルート認証局にインポートします。このアクション後、認証局のステータスが Active に変化し、認証局として使用可能になります。

Python Sample: import_certificate_authority_certificate
from botocore.client import BaseClient


def import_certificate_authority_certificate(
    pca_client: BaseClient,
    root_certificate: str,
    root_ca_arn: str,
) -> None:
    import_request = {
        "Certificate": root_certificate.encode("utf-8"),
        "CertificateAuthorityArn": root_ca_arn,
    }

    pca_client.import_certificate_authority_certificate(**import_request)
    print("Product Attestation Authority (PAA) activated successfully.")

2. 中間証明書 or エンドエンティティ証明書を発行する

次に、アクティブ化されたプライベートルート認証局を使って、サーバ(エンドエンティティ)証明書を発行します。

構築対象2

2.1. CSR を参照する

証明書を取得したいサーバのキーペアを使用して、OpenSSL 等を使用して CSR を発行します。以下の手順では、発行した CSR をローカルファイルに保存し、python に読ませて実行しています。

2.2. テンプレートを使って証明書を発行する

CA 証明書発行時と同じ issue_certificate() をつかって、以下のように発行します。使用する証明書テンプレートは、

  • エンドエンティティ証明書用
  • 中間証明書用

のどちらかになります。必要なパス長に合わせてテンプレートを使い分けてください。

chain_certificate_arn = issue_certificate(
    pca_client=pca_client,
    root_ca_arn=root_ca_arn,
    template_arn="arn:aws:acm-pca:::template/EndEntityCertificate/V1",
    csr=csr,
)
2.3. 証明書を取得する

こちらも CA 証明書発行時と同じ get_certificate() をつかって、発行済みの証明書を取得します。

chain_certificate = get_certificate(
    pca_client=pca_client,
    certificate_arn=chain_certificate_arn,
    certificate_authority_arn=root_ca_arn,
)

最後に、被認証サーバに証明書をインポートして完了です。

結果

クライアント PC に配布するために、作成した CA 証明書はローカルファイル (pem 形式) にも保存します。証明書に AKI が含まれているか、以下のコマンドで確認できます。

openssl x509 -in /Path/To/Your/CustomCert.pem -text -noout | grep -A 1 "Authority Key Identifier"

AKIの確認

冒頭に示した通り、作成した CA 証明書を REQUESTS_CA_BUNDLE に設定し、requests を実行してみると

結果は...

エラーがでない!実行できました!

おわりに

  • 今回の検証で、AWS Private CA の基本的な使い方(CA の作成、AKI 付き証明書の発行、CA へのインポート、エンドエンティティ証明書の発行)を一通り試せました。
  • AWS Private CA はコマンドの役割や名前に似ているものが多く、一連の手順を理解するのに苦労しました。
  • 本記事が、プライベート CA を使った証明書運用(特に Python 3.13 以降の証明書検証に関するトラブルシュート)の参考になれば幸いです。
脚注
  1. requests.get("https://example.com/api", verify=False) を設定すると、証明書検証を無視できますが、推奨されません。 ↩︎

  2. AI をつかった疑問点解消のみでは、関心の外にある情報を漏らす危険性があると考えています。AI はドキュメントの索引のように使用し、あくまでドキュメント本文を読む補助として活用するよう心がけています。 ↩︎

  3. AWS Private CA では認証局一つあたり、月額 400 USD かかります(執筆時点 2025/12/22)。運用するには少しインパクトのあるお値段ですが、30 日間は無料で試せます。(参照: AWS Private CA pricing) ↩︎

Weathernews Tech Blog
Weathernews Tech Blog

Discussion