LoginSignup
1
2

More than 3 years have passed since last update.

OpenSSL で Visual Studio の コード署名 (コードサイニング) 用 pfx ファイルを作る。

Posted at

1. はじめに

 OpenSSLを使ってコード署名 (コードサイニング) 用のpfxファイルを自作した際にはまった点がいくつかありました。解決までに2週間近く掛かってしまったものもありましたので手順とポイントをまとめてみました。

2. OpenSSLによるコード署名用pfxファイル作成手順

2.1. 下準備

 ここではホームディレクトリ配下に「demoSSL/CodeSigning」ディレクトリを作成し、その下に各種ファイルを保存するようにします。

mkdir $HOME/demoSSL
cd $HOME/demoSSL
mkdir -p ./CodeSigning/certs
mkdir -p ./CodeSigning/csr
mkdir -p ./CodeSigning/crl
mkdir -p ./CodeSigning/newcerts
mkdir -p ./CodeSigning/private
mkdir -p ./CodeSigning/pkcs12
touch ./CodeSigning/index.txt
echo 00 > ./CodeSigning/crlnumber

2.2. openssl.cnfの編集

 openssl.cnfファイルの[ CA_default ]セクションの「dir」を「./demoCA」から「./CodeSigning」に変更します。
 また、[ usr_cert ]セクションに証明書のExtensionに関する3行を設定します。
 (「basicConstraints=CA:FALSE」はデフォルトで設定されていると思います。)

cd $HOME/demoSSL
cp /etc/ssl/openssl.cnf ./openssl-CodeSigning.cnf

=============================================================
※ openssl.cnfのコピー元は環境によって異なります。
  /etc/ssl/openssl.cnf
  /usr/share/ssl/openssl.cnf
  /etc/pki/tls/openssl.cnf
   :
=============================================================

vi ./openssl-CodeSigning.cnf
=============================================================
[ CA_default ]

# 「./demoCA」を「./CodeSigning」に修正。
dir          = ./CodeSigning         # Where everything is kept

[ usr_cert ]
 :
# デフォルトで記述あり。
basicConstraints=CA:FALSE
 :
# 新規に追加。
keyUsage = digitalSignature
 :
# 新規に追加。
extendedKeyUsage = codeSigning
=============================================================

diff openssl-CodeSigning.cnf /etc/ssl/openssl.cnf
=============================================================
45c45
< dir           = ./CodeSigning         # Where everything is kept
---
> dir           = ./demoCA              # Where everything is kept
191d190
< keyUsage = digitalSignature
219d217
< extendedKeyUsage = codeSigning
=============================================================


【参考】今回使用した「openssl-CodeSigning.cnf」全体
#
# OpenSSL example configuration file.
# This is mostly being used for generation of certificate requests.
#

# Note that you can include other files from the main configuration
# file using the .include directive.
#.include filename

# This definition stops the following lines choking if HOME isn't
# defined.
HOME                    = .

# Extra OBJECT IDENTIFIER info:
#oid_file               = $ENV::HOME/.oid
oid_section             = new_oids

# To use this configuration file with the "-extfile" option of the
# "openssl x509" utility, name here the section containing the
# X.509v3 extensions to use:
# extensions            =
# (Alternatively, use a configuration file that has only
# X.509v3 extensions in its main [= default] section.)

[ new_oids ]

# We can add new OIDs in here for use by 'ca', 'req' and 'ts'.
# Add a simple OID like this:
# testoid1=1.2.3.4
# Or use config file substitution like this:
# testoid2=${testoid1}.5.6

# Policies used by the TSA examples.
tsa_policy1 = 1.2.3.4.1
tsa_policy2 = 1.2.3.4.5.6
tsa_policy3 = 1.2.3.4.5.7

####################################################################
[ ca ]
default_ca      = CA_default            # The default ca section

####################################################################
[ CA_default ]

dir             = ./CodeSigning         # Where everything is kept
certs           = $dir/certs            # Where the issued certs are kept
crl_dir         = $dir/crl              # Where the issued crl are kept
database        = $dir/index.txt        # database index file.
#unique_subject = no                    # Set to 'no' to allow creation of
                                        # several certs with same subject.
new_certs_dir   = $dir/newcerts         # default place for new certs.

certificate     = $dir/cacert.pem       # The CA certificate
serial          = $dir/serial           # The current serial number
crlnumber       = $dir/crlnumber        # the current crl number
                                        # must be commented out to leave a V1 CRL
crl             = $dir/crl.pem          # The current CRL
private_key     = $dir/private/cakey.pem# The private key

x509_extensions = usr_cert              # The extensions to add to the cert

# Comment out the following two lines for the "traditional"
# (and highly broken) format.
name_opt        = ca_default            # Subject Name options
cert_opt        = ca_default            # Certificate field options

# Extension copying option: use with caution.
# copy_extensions = copy

# Extensions to add to a CRL. Note: Netscape communicator chokes on V2 CRLs
# so this is commented out by default to leave a V1 CRL.
# crlnumber must also be commented out to leave a V1 CRL.
# crl_extensions        = crl_ext

default_days    = 365                   # how long to certify for
default_crl_days= 30                    # how long before next CRL
default_md      = default               # use public key default MD
preserve        = no                    # keep passed DN ordering

# A few difference way of specifying how similar the request should look
# For type CA, the listed attributes must be the same, and the optional
# and supplied fields are just that :-)
policy          = policy_match

# For the CA policy
[ policy_match ]
countryName             = match
stateOrProvinceName     = match
organizationName        = match
organizationalUnitName  = optional
commonName              = supplied
emailAddress            = optional

# For the 'anything' policy
# At this point in time, you must list all acceptable 'object'
# types.
[ policy_anything ]
countryName             = optional
stateOrProvinceName     = optional
localityName            = optional
organizationName        = optional
organizationalUnitName  = optional
commonName              = supplied
emailAddress            = optional

####################################################################
[ req ]
default_bits            = 2048
default_keyfile         = privkey.pem
distinguished_name      = req_distinguished_name
attributes              = req_attributes
x509_extensions = v3_ca # The extensions to add to the self signed cert

# Passwords for private keys if not present they will be prompted for
# input_password = secret
# output_password = secret

# This sets a mask for permitted string types. There are several options.
# default: PrintableString, T61String, BMPString.
# pkix   : PrintableString, BMPString (PKIX recommendation before 2004)
# utf8only: only UTF8Strings (PKIX recommendation after 2004).
# nombstr : PrintableString, T61String (no BMPStrings or UTF8Strings).
# MASK:XXXX a literal mask value.
# WARNING: ancient versions of Netscape crash on BMPStrings or UTF8Strings.
string_mask = utf8only

# req_extensions = v3_req # The extensions to add to a certificate request

[ req_distinguished_name ]
countryName                     = Country Name (2 letter code)
countryName_default             = AU
countryName_min                 = 2
countryName_max                 = 2

stateOrProvinceName             = State or Province Name (full name)
stateOrProvinceName_default     = Some-State

localityName                    = Locality Name (eg, city)

0.organizationName              = Organization Name (eg, company)
0.organizationName_default      = Internet Widgits Pty Ltd

# we can do this but it is not needed normally :-)
#1.organizationName             = Second Organization Name (eg, company)
#1.organizationName_default     = World Wide Web Pty Ltd

organizationalUnitName          = Organizational Unit Name (eg, section)
#organizationalUnitName_default =

commonName                      = Common Name (e.g. server FQDN or YOUR name)
commonName_max                  = 64

emailAddress                    = Email Address
emailAddress_max                = 64

# SET-ex3                       = SET extension number 3

[ req_attributes ]
challengePassword               = A challenge password
challengePassword_min           = 4
challengePassword_max           = 20

unstructuredName                = An optional company name

[ usr_cert ]

# These extensions are added when 'ca' signs a request.

# This goes against PKIX guidelines but some CAs do it and some software
# requires this to avoid interpreting an end user certificate as a CA.

basicConstraints=CA:FALSE

# Here are some examples of the usage of nsCertType. If it is omitted
# the certificate can be used for anything *except* object signing.

# This is OK for an SSL server.
# nsCertType                    = server

# For an object signing certificate this would be used.
# nsCertType = objsign

# For normal client use this is typical
# nsCertType = client, email

# and for everything including object signing:
# nsCertType = client, email, objsign

# This is typical in keyUsage for a client certificate.
# keyUsage = nonRepudiation, digitalSignature, keyEncipherment
keyUsage = digitalSignature

# This will be displayed in Netscape's comment listbox.
nsComment                       = "OpenSSL Generated Certificate"

# PKIX recommendations harmless if included in all certificates.
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer

# This stuff is for subjectAltName and issuerAltname.
# Import the email address.
# subjectAltName=email:copy
# An alternative to produce certificates that aren't
# deprecated according to PKIX.
# subjectAltName=email:move

# Copy subject details
# issuerAltName=issuer:copy

#nsCaRevocationUrl              = http://www.domain.dom/ca-crl.pem
#nsBaseUrl
#nsRevocationUrl
#nsRenewalUrl
#nsCaPolicyUrl
#nsSslServerName

# This is required for TSA certificates.
# extendedKeyUsage = critical,timeStamping
extendedKeyUsage = codeSigning

[ v3_req ]

# Extensions to add to a certificate request

basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment

[ v3_ca ]


# Extensions for a typical CA


# PKIX recommendation.

subjectKeyIdentifier=hash

authorityKeyIdentifier=keyid:always,issuer

basicConstraints = critical,CA:true

# Key usage: this is typical for a CA certificate. However since it will
# prevent it being used as an test self-signed certificate it is best
# left out by default.
# keyUsage = cRLSign, keyCertSign

# Some might want this also
# nsCertType = sslCA, emailCA

# Include email address in subject alt name: another PKIX recommendation
# subjectAltName=email:copy
# Copy issuer details
# issuerAltName=issuer:copy

# DER hex encoding of an extension: beware experts only!
# obj=DER:02:03
# Where 'obj' is a standard or added object
# You can even override a supported extension:
# basicConstraints= critical, DER:30:03:01:01:FF

[ crl_ext ]

# CRL extensions.
# Only issuerAltName and authorityKeyIdentifier make any sense in a CRL.

# issuerAltName=issuer:copy
authorityKeyIdentifier=keyid:always

[ proxy_cert_ext ]
# These extensions should be added when creating a proxy certificate

# This goes against PKIX guidelines but some CAs do it and some software
# requires this to avoid interpreting an end user certificate as a CA.

basicConstraints=CA:FALSE

# Here are some examples of the usage of nsCertType. If it is omitted
# the certificate can be used for anything *except* object signing.

# This is OK for an SSL server.
# nsCertType                    = server

# For an object signing certificate this would be used.
# nsCertType = objsign

# For normal client use this is typical
# nsCertType = client, email

# and for everything including object signing:
# nsCertType = client, email, objsign

# This is typical in keyUsage for a client certificate.
# keyUsage = nonRepudiation, digitalSignature, keyEncipherment

# This will be displayed in Netscape's comment listbox.
nsComment                       = "OpenSSL Generated Certificate"

# PKIX recommendations harmless if included in all certificates.
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer

# This stuff is for subjectAltName and issuerAltname.
# Import the email address.
# subjectAltName=email:copy
# An alternative to produce certificates that aren't
# deprecated according to PKIX.
# subjectAltName=email:move

# Copy subject details
# issuerAltName=issuer:copy

#nsCaRevocationUrl              = http://www.domain.dom/ca-crl.pem
#nsBaseUrl
#nsRevocationUrl
#nsRenewalUrl
#nsCaPolicyUrl
#nsSslServerName

# This really needs to be in place for it to be a proxy certificate.
proxyCertInfo=critical,language:id-ppl-anyLanguage,pathlen:3,policy:foo

####################################################################
[ tsa ]

default_tsa = tsa_config1       # the default TSA section

[ tsa_config1 ]

# These are used by the TSA reply generation only.
dir             = ./demoCA              # TSA root directory
serial          = $dir/tsaserial        # The current serial number (mandatory)
crypto_device   = builtin               # OpenSSL engine to use for signing
signer_cert     = $dir/tsacert.pem      # The TSA signing certificate
                                        # (optional)
certs           = $dir/cacert.pem       # Certificate chain to include in reply
                                        # (optional)
signer_key      = $dir/private/tsakey.pem # The TSA private key (optional)
signer_digest  = sha256                 # Signing digest to use. (Optional)
default_policy  = tsa_policy1           # Policy if request did not specify it
                                        # (optional)
other_policies  = tsa_policy2, tsa_policy3      # acceptable policies (optional)
digests     = sha1, sha256, sha384, sha512  # Acceptable message digests (mandatory)
accuracy        = secs:1, millisecs:500, microsecs:100  # (optional)
clock_precision_digits  = 0     # number of digits after dot. (optional)
ordering                = yes   # Is ordering defined for timestamps?
                                # (optional, default: no)
tsa_name                = yes   # Must the TSA name be included in the reply?
                                # (optional, default: no)
ess_cert_id_chain       = no    # Must the ESS cert id chain be included?
                                # (optional, default: no)
ess_cert_id_alg         = sha1  # algorithm to compute certificate
                                # identifier (optional, default: sha1)


2.3. 鍵ペアの生成

cd $HOME/demoSSL
openssl genrsa -aes256 2048 > CodeSigning/private/CodeSignPrivKey-001.pem

=============================================================
Enter pass phrase: ← 秘密鍵のパスフレーズを設定する。
Verifying - Enter pass phrase: ← 同上(再入力)
=============================================================

2.4. CSRの生成


openssl req \
-config ./openssl-CodeSigning.cnf \
-new \
-key ./CodeSigning/private/CodeSignPrivKey-001.pem \
-out ./CodeSigning/csr/CodeSignCsr-001.pem

=============================================================
Enter pass phrase for ./CodeSigning/private/PrivateKey.pem: ← 秘密鍵のパスフレーズ。
You are about to be asked to enter information that will be incororated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]: ← そのまま。
State or Province Name (full name) [Some-State]: ← そのまま。
Locality Name (eg, city) []: ← そのまま。
Organization Name (eg, company) [Internet Widgits Pty Ltd]: ← そのまま。
Organizational Unit Name (eg, section) []: ← そのまま。
Common Name (e.g. server FQDN or YOUR name) []: CodeSigningTest-001
Email Address []: ← そのまま。

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []: ← そのまま
An optional company name []: ← そのまま
=============================================================

2.5. 自己署名証明書の生成

openssl ca \
-config ./openssl-CodeSigning.cnf \
-create_serial \
-out ./CodeSigning/certs/CodeSignCert-001.pem \
-days 180 \
-batch \
-keyfile ./CodeSigning/private/CodeSignPrivKey-001.pem \
-selfsign \
-infiles ./CodeSigning/csr/CodeSignCsr-001.pem

=============================================================
Using configuration from ./openssl-CodeSigning.cnf
Enter pass phrase for ./CodeSigning/private/CodeSignPrivKey-001.pem: ← 秘密鍵のパスフレーズ。

Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number:
            1a:90:a7:1c:9c:4b:bd:a1:16:23:6d:28:ec:78:0b:c8:5f:e1:df:93
        Validity
            Not Before: May  4 00:47:36 2021 GMT
            Not After : Oct 31 00:47:36 2021 GMT
        Subject:
            countryName               = AU
            stateOrProvinceName       = Some-State
            organizationName          = Internet Widgits Pty Ltd
            commonName                = CodeSigningTest-001
        X509v3 extensions:
            X509v3 Basic Constraints: ← 設定内容が正しいか確認する。
                CA:FALSE
            X509v3 Key Usage: ← 設定内容が正しいか確認する。
                Digital Signature
            Netscape Comment:
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier:
                4E:E2:61:1E:4E:9C:75:5C:12:E2:EE:79:DA:D4:86:9D:C9:EF:48:CC
            X509v3 Authority Key Identifier:
                keyid:4E:E2:61:1E:4E:9C:75:5C:12:E2:EE:79:DA:D4:86:9D:C9:EF:48:CC

            X509v3 Extended Key Usage: ← 設定内容が正しいか確認する。
                Code Signing
Certificate is to be certified until Oct 31 00:47:36 2021 GMT (180 days)

Write out database with 1 new entries
Data Base Updated
=============================================================

2.6. pfxファイルの生成

 Visual Studioのコード署名で利用する場合、pfxファイル生成の際に「-keysig」オプションを付けます。

openssl pkcs12 \
-export \
-keysig \
-in ./CodeSigning/certs/CodeSignCert-001.pem \
-inkey ./CodeSigning/private/CodeSignPrivKey-001.pem \
-out ./CodeSigning/pkcs12/CodeSignPkcs12-001.pfx

=============================================================
Enter pass phrase for ./CodeSigning/private/CodeSignPrivKey-001.pem: ← 秘密鍵のパスフレーズ。
Enter Export Password: ← pfxファイルのパスワードを設定する。
Verifying - Enter Export Password: ← 同上(再入力)
=============================================================

3. openssl.cnfの設定ポイント

3.1. openssl.cnfの設定一覧

 OpenSSLで発行するVisual Studioのコード署名用証明書は、Extension設定に注意が必要です。openssl.confファイルの設定との紐づけを表にまとめます。

No. Extension MSBuild
プロパティ
Enable
Signing
Checks
設定
検証チェック内容
(※1から抜粋)
OpenSSL設定
(openssl.cnf)
1 Extended Key Usage TrueでもFalseでも検証される。 [拡張キー使用法] プロパティの値に [コード署名] が含まれているかどうかを確認します。 [ usr_cert ]セクションに

extendedKeyUsage = codeSigning

の1行を追加する。
2 Basic Constraints Trueの時に検証される。 [基本的な制約] 拡張機能の存在とその値を確認します。値は Subject Type=End Entity か、未指定かのいずれかである必要があります。 [ usr_cert ]セクションに

basicConstraints=CA:FALSE

の1行があることを確認する。
(デフォルトで存在。)
3 Key Usage Trueの時に検証される。 [KeyUsage (KU)] プロパティの値を確認します。[設定解除] または [DigitalSignature] のいずれかである必要があります。 [ usr_cert ]セクションに

keyUsage = digitalSignature

の1行を追加する。

参考
※1 [Microsoft] Visual Studio がアプリケーションに署名するために使用する証明書の管理
※5 [Qiita][@yoshikita] [UWP]コードサイン証明書でアプリパッケージを署名するときにトラブったのでメモ

3.2. Extension設定に不備がある場合のエラー例

 例えば「Extended Key Usage」が「codeSigning」ではなく「timeStamping」になっている場合、「ClickOnce」でpfxファイルをインポートしようとすると以下のエラーになります。
EkuNg-ClickOnce-001.jpg

4. pfxファイル生成時のポイント

4.1. ファイルの拡張子を「.pfx」にする。

 ファイルの拡張子は「.p12」などではなく「.pfx」とする必要があります。

参考
※3 [Microsoft] 方法 : アプリケーション マニフェストおよび配置マニフェストに署名する

注意
このオプションでは、拡張子「.pfx」 を持つファイルのみがサポートされます。 これ以外の形式のキー ファイルや証明書がある場合は、Windows 証明書ストアに格納し、前の手順で説明した証明書を選択します。 選択した証明書の用途に、コードの署名が含まれている必要があります。

4.1.1. 拡張子が「.pfx」以外のファイルを ClickOnceでインポートする場合

 ClickOnceの場合は「.pfx」以外の拡張子は読み込めないようになっています。
ClickOnce-006.jpg
Not-pfx-FileNameExtension-001.jpg

4.1.2. 拡張子が「.pfx」以外のファイルを 「アセンブリに署名する」で利用する場合

 「アセンブリに署名する」の場合は「.pfx」以外の拡張子でもインポートは可能ですが、通常はインポートのタイミングで表示されるパスワード入力画面が表示されません。
 この状態でビルドを行うと「CS7020」エラーになります。
Sign-Assembly-006-NG.jpg
Sign-Assembly-008-NG.jpg

4.2. pfx 生成時に「-keysig」オプションを付ける。

 このオプションを付けずに生成されたpfxファイルをVisual Studioの「アセンブリに署名する」からインポートしようとすると、以下のポップアップが表示されインポートに失敗します。(「ClickOnce」の場合は問題無いようです。)

Sign-Assembly-002.jpg
Sign-Assembly-003.jpg
ImportError.jpg

参考
※6 [Stack Overflow] How to generate public and private keys usable for both C and Java?
※7 [Stack Overflow] Cannot import the keyfile 'blah.pfx' - error 'The keyfile may be password protected'

4.3. その他のポイント

4.3.1. pfx 生成時に証明書チェーンを含めてはならない。

 今回は自己署名証明書のため直接関係はありませんが、以下「※3」によれば、pfxに上位のCA証明書など証明書チェーンが含まれているとVisual Studioでのインポート時にエラーとなりインポートできないようです。

参考
※3 [Microsoft] 方法 : アプリケーション マニフェストおよび配置マニフェストに署名する

注意
.pfx ファイルには証明書チェーンの情報を含めることはできません。 含まれる場合は、次のインポート エラーが発生します。暗号化の解除のための証明書と秘密キーが見つかりません。 証明書チェーンの情報を削除するには、Certmgr.msc を使用して、*.pfx ファイルをエクスポートするときに すべての証明書を含める ための オプションを無効にすることができます。

4.3.2. 秘密鍵とpfxファイルのパスワード長は6文字以上にする。

 以下「※2」によればパスワード長を6文字以上にする必要があるようです。

参考
※2 [Microsoft] [署名] ページ (プロジェクト デザイナー)

ここでキー ファイル名を指定し、パスワードを使用してキー ファイルを保護することができます。 パスワードの長さは 6 文字以上にする必要があります。

5. 参考文献

※1 [Microsoft] Visual Studio がアプリケーションに署名するために使用する証明書の管理
※2 [Microsoft] [署名] ページ (プロジェクト デザイナー)
※3 [Microsoft] 方法 : アプリケーション マニフェストおよび配置マニフェストに署名する
※4 [Microsoft] Visual Studio 内でアセンブリに署名する方法
※5 [Qiita][@yoshikita] [UWP]コードサイン証明書でアプリパッケージを署名するときにトラブったのでメモ
※6 [Stack Overflow] How to generate public and private keys usable for both C and Java?
※7 [Stack Overflow] Cannot import the keyfile 'blah.pfx' - error 'The keyfile may be password protected'

1
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2