HSM 관련

SoftHSMv2 사용해보기 with Linux, OpenSSL, pkcs11 provider, OpenSC

crypsec 2024. 10. 26. 16:21
반응형

SoftHSM은 소프트웨어 기반의 하드웨어 보안 모듈(HSM)이다. 즉, SoftHSM은 실제 하드웨어 장비 대신 소프트웨어로 암호화 작업을 수행할 수 있도록 설계되어 있다.
 
모두 소프트웨어로 구현되어 있는데 HSM이란 말을 쓰기는 좀 그렇지만 PKCS#11 인터페이스를 구현하여, 암호화 키와 인증서 같은 민감한 데이터를 안전하게 저장하고 관리하는 데 사용하기 때문에 기본적인 기능상의 차이는 크게 없을 것이다. 내 추측으로 실제 판매되는 HSM들 중에 절반 이상은 SoftHSM을 참고 또는 이용했을 거다.

HSM이 왜 필요한지는 해당 영상으로 이해 가능하다.
 https://youtu.be/szagwwSLbXo?si=WJQKj4yAo1YFwUye


여기서는 SoftHSM2, OpenSSL, OpenSC, pkcs11-provider를 이용하여 키 생성을 해보고 불러오는 등 동작에 대한 감을 익힌다.
 
우선 SoftHSM2는 공식 사이트에서 설치 가능하다.
https://github.com/opendnssec/SoftHSMv2
 
관련 설명들은 여기서 볼 수 있다.
https://wiki.opendnssec.org/
https://www.opendnssec.org/softhsm/
 
SoftHSM은 PKCS #11 인터페이스를 통해 액세스 할 수 있는 암호화 저장소를 구현한 거다. 간단하게 키관리 해주는 소프트웨어(원래는 하드웨어)라고 생각하는 게 편하다.
Github에 설치 관련 내용이 있는데, 해당 글에 정리해 보겠다. 우선 설치에 필요한 패키지이다. WSL2 kali linux를 기준으로 한다. (이미 사용하고 있는 WSL2 ubuntu에는 이미 많은 패키지가 설치되어 있어 혹시 필요한 게 생략될 수 있을 것 같아서 그렇다.)
 
OpenSSL부터 최신 버전으로 설치하면 좋다. 최신버전을 설치하는 이유는 내가 가진 WSL2의 ubuntu22.04 기준으로 default로 설치된 게 3.0.2 버전인데 사용하려는 pkcs11-provider가 3.0.7 이상의 OpenSSL을 요구하기 때문이다. (OpenSSL 1.1.1 버전이라면 provider대신 engine이라는 기능으로 pkcs11 인터페이스를 사용할 수 있는 것 같다. 하지만 3.X.X 버전만을 이제부터 지원할 가능성이 크기 때문에 슬슬 바꾸는 게 좋다. 그리고 provider 관련해서 정보도 많이 없어서 지금부터 써두는 게 좋다)
 
설치방법은 아래와 같고, 파일 다운로드만 https://github.com/openssl/openssl/releases 여기서 받으면 될 것 같다. 취향 것 버전을 선택해서 받으면 된다.
https://crypsec.tistory.com/10
 
만약 apt 패키지로 설치된 or 기존에 기본적으로 설치되어 있는 openssl이 버전이 낮다면 지우거나 백업 처리해줘야 한다. 지우는 걸 추천한다.
 

$ sudo apt remove openssl libssl-dev
$ sudo apt autoremove

 
Kali는 따로 OpenSSL설치 안 해줘도 될 것 같다.

 

$ sudo apt update
더보기

 

원인은 아직도 파악 안됬지만 나의 경우 Ign 이슈가 있었다.

나의 경우 와이파이 쓰다가 유선 랜으로 변경하니 그냥 됬다. DNS 문제가 맞을 것 같긴한게 현재 사용중인 와이파이랑 유선 랜이랑 다른 망? 이긴하다. 사실 잘 모르겠다. Ping이 된다면 DNS쪽 문제일 가능성이 높으니 참고해라


https://www.kali.org/docs/wsl/wsl-preparations/

https://github.com/microsoft/WSL/issues/7491

SoftHSM을 수동으로 설치한다.(apt 패키지로도 있는 걸로 알고 있음)

가장 먼저 autogen.sh 파일을 실행해줘야 한다.

실행하는데 필요한 패키지가 있어서 설치를 진행해 줬다.

$ sudo apt install automake autoconf libtool pkg-config
$ sh autogen.sh

 

 

configure를 실행하기 전에 설치에 필요한 패키지들을 설치한다. 단, OpenSSL을 수동으로 설치했다면 libssl-dev는 빼도(빼야) 좋다. configure 옵션은 필요하다면 공식 사이트에서 보고 넣어주면 된다.

$ sudo apt install libssl-dev gcc g++ make build-essential
$ ./configure
$ make -j8
$ sudo make install

 
이제 SoftHSMv2의 설치가 끝났다. 명령어를 실행해 보자. 참고로 관리자 권한이 필요하다.

$ sudo softhsm2-util --show-slot

slot이라는 걸 생성해줘야 하는데 일단은 키 저장 창고라고 생각하면 된다.

$ sudo softhsm2-util --init-token --free --label <사용하고 싶은 Label 이름>

# sudo softhsm2-util --init-token --free --label "TestToken"

이러면 PIN을 입력하라고 하는데 비밀번호 설정이라고 생각하면 된다. 

이렇게 slot이 생성된 것을 확인할 수 있다.

더보기

그럼 결국 softhsm2에서는 명령어로 키 생성 못하네?

ChatGPT의 말:

ChatGPT

, 맞습니다. softhsm2-util이나 softhsm2-keyconv, softhsm2-dump-file와 같은 도구는 키 생성 기능을 직접적으로 제공하지 않습니다. SoftHSM2는 주로 PKCS#11 API를 구현하는 소프트웨어 HSM이기 때문에, 키 생성은 보통 프로그래밍적으로 이루어집니다.

키 생성 방법 요약

  1. 프로그래밍: C, Python 등과 같은 언어를 사용하여 PKCS#11 API를 통해 키를 생성해야 합니다. 예를 들어, PyKCS11와 같은 라이브러리를 사용하여 코드로 키를 생성할 수 있습니다.
  2. 기타 도구 사용: SoftHSM2와 함께 사용하는 다른 도구나 라이브러리를 통해 키 생성 작업을 수행할 수 있습니다.
  3. 예시 코드: 프로그래밍 방식으로 키를 생성하는 예시를 제공했듯이, 사용자가 필요에 따라 코드를 작성해야 합니다.

따라서, SoftHSM2 자체에는 명령어로 직접 키를 생성하는 기능이 없지만, API를 통해 키 생성이 가능합니다. 추가적인 질문이나 도움이 필요하시면 언제든지 말씀해 주세요!


이제 pkcs11-tool이라는 명령어를 이용해 키를 생성하는 방법을 소개한다.
https://github.com/OpenSC/OpenSC 에서 다운로드를 한다. 나는 release  되어있는 걸 wget으로 받아서 사용했다.

 
https://github.com/OpenSC/OpenSC/wiki/Compiling-and-Installing-on-Unix-flavors
설치 방법인데 요기 wiki만 잘 찾아봐도 잘 쓸 수 있다.
 

 

 
이전에 없던 Configure 파일이 생겼다. 이후 설치 진행을 위해 필요한 패키지들을 설치한다.

$ sudo apt-get install pcscd libccid libpcsclite-dev libssl-dev libreadline-dev autoconf automake build-essential docbook-xsl xsltproc libtool pkg-config

알아서 걸러서 중복되거나 설치하기 싫은 것은 빼고 설치하길 바란다.
 

Makefile이 생김

$ make -j8
$ sudo make install

 

아 또 고질적인 라이브러리 위치 문제가 생겼다. 어디 있나 위치나 찾아보자
 

그냥 잘 있나 위치나 확인해 봤다.

$ sudo ldconfig

Opensc wiki에 보면 명령어 툴이 엄청 많은데 미안하게도 나는 pkcs11-tool만 쓸 거다.

Opensc wiki

pkcs11-tool 명령어로 아까 만든 slot에 타원곡선 키를 만들어준다. 참고로 libsofthsm2.so의 위치를 알아야 하는데, 패키지라면 보통 /usr/lib/softhsm/위치고 수동으로 make install까지 실행했으면 /usr/local/lib/softhsm/ 위치일 가능성이 높다.

$ sudo pkcs11-tool --module /usr/local/lib/softhsm/libsofthsm2.so -l --token-label <아까 위에서 정한 token label> -k --key-type EC:prime256v1 --id <원하는 key id 적기> --label <여기도 원하는 key label 적기>

# sudo pkcs11-tool --module /usr/local/lib/softhsm/libsofthsm2.so -l --token-label "TestToken" -k --key-type EC:prime256v1 --id 1234 --label "

 
 

키가 잘 생성되었는지 확인해 봐야겠지?

$ sudo pkcs11-tool --module /usr/local/lib/softhsm/libsofthsm2.so -T -O -I

 


이제 이 키를 생성했으니 뭘 하면 좋을까? 당연히 키를 불러와서 뭐라도 써봐야지! 그걸 위해 OpenSSL을 이용하겠다. 다른 툴이 있다면 그걸 사용해도 좋다. 그런데 PKCS#11를 제공해야 한다. 안타깝게도 (내가 알기론) OpenSSL 3.X.X 에서는 자체적으로 기능을 제공하지 않는다.
 
하지만 괜찮다. 유저들은 나보다 빠르다. pkcs11-provider를 만들어두었다. 심지어 사용자도 별로 없어서 참 쓰기 어려웠다.
 

GitHub - latchset/pkcs11-provider: A pkcs#11 provider for OpenSSL 3.0+

A pkcs#11 provider for OpenSSL 3.0+. Contribute to latchset/pkcs11-provider development by creating an account on GitHub.

github.com

 
이번에도 release 버전을 사용한다.

$ wget https://github.com/latchset/pkcs11-provider/archive/refs/tags/v0.5.zip

 

$ sudo apt install unzip
$ unzip v0.5.zip

 
https://github.com/latchset/pkcs11-provider/blob/main/BUILD.md
를 참고하여 빌드한다.
 

$ sudo apt install meson ninja-build
$ meson setup builddir

 

일부 no가 뜨는데 cmake, valgrind 같은 툴이 없어서 그런 거고 없어도 사용에는 큰 지장 없다.

$ meson compile -C builddir
$ meson test -C builddir

테스트 왜 fail인지는 모름 알면 누가 댓글 좀

$ sudo meson install -C builddir

 
https://github.com/latchset/pkcs11-provider/blob/main/HOWTO.md
을 참고하여 openssl.cnf 파일을 수정하여 provider 기능을 이용한다.
 
sudo vi /usr/local/ssl/openssl.cnf – openssl을 직접 make install로 설치한 경우(참고로. pc들을 적용하기 위해 export PKG_CONFIG_PATH=/path/to/your/pc/files:$PKG_CONFIG_PATH 로 설정한 후 pkg-config 명령어를 수행해줘야 한다.)
sudo vi /etc/ssl/openssl.cnf – apt 패키지로 설치된 경우
sudo find / -name pkcs11.so - 위치 까먹은 경우

 

# List of providers to load
[provider_sect]
default = default_sect
pkcs11 = pkcs11_sect
# The fips section name should match the section name inside the
# included fipsmodule.cnf.
# fips = fips_sect

# If no providers are activated explicitly, the default one is activated implicitly.
# See man 7 OSSL_PROVIDER-default for more details.
#
# If you add a section explicitly activating any other provider(s), you most
# probably need to explicitly activate the default provider, otherwise it
# becomes unavailable in openssl.  As a consequence applications depending on
# OpenSSL may not work correctly which could lead to significant system
# problems including inability to remotely access the system.
[default_sect]
activate = 1
== 직접 설치한 openssl일 경우의 예시, 그냥 pkcs11.so, libsofthsm2.so의 위치만 잘 찾아서 넣어주면 됨 ==
[pkcs11_sect]
module = /lib/x86_64-linux-gnu/pkcs11.so # /usr/lib/x86_64-linux-gnu/ossl-modules/pkcs11.so
pkcs11-module-path = /usr/local/lib/softhsm/libsofthsm2.so
activate = 1

알아서 잘 껴넣겠지만 아래 접은 글은 ubuntu에서 했었을 때 썼던 openssl.cnf 전체 내용이다. 참고해라

더보기

#

# OpenSSL example configuration file.

# See doc/man5/config.pod for more info.

#

# This is mostly being used for generation of certificate requests,

# but may be used for auto loading of providers

 

# 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                    = .

 

# Use this in order to automatically load providers.

openssl_conf = openssl_init

 

# Comment out the next line to ignore configuration errors

config_diagnostics = 1

 

# 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

 

# For FIPS

# Optionally include a file that is generated by the OpenSSL fipsinstall

# application. This file contains configuration data required by the OpenSSL

# fips provider. It contains a named section e.g. [fips_sect] which is

# referenced from the [provider_sect] below.

# Refer to the OpenSSL security policy for more information.

# .include fipsmodule.cnf

 

[openssl_init]

providers = provider_sect

 

# List of providers to load

[provider_sect]

default = default_sect

pkcs11 = pkcs11_sect

# The fips section name should match the section name inside the

# included fipsmodule.cnf.

# fips = fips_sect

 

# If no providers are activated explicitly, the default one is activated implicitly.

# See man 7 OSSL_PROVIDER-default for more details.

#

# If you add a section explicitly activating any other provider(s), you most

# probably need to explicitly activate the default provider, otherwise it

# becomes unavailable in openssl.  As a consequence applications depending on

# OpenSSL may not work correctly which could lead to significant system

# problems including inability to remotely access the system.

[default_sect]

activate = 1

 

[pkcs11_sect]

module = /lib/x86_64-linux-gnu/pkcs11.so

pkcs11-module-path = /usr/local/lib/softhsm/libsofthsm2.so

activate = 1

 

 

####################################################################

[ ca ]

default_ca      = CA_default            # The default ca section

 

####################################################################

[ CA_default ]

 

dir             = ./demoCA              # 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

 

# This is typical in keyUsage for a client certificate.

# keyUsage = nonRepudiation, digitalSignature, keyEncipherment

 

# 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

 

# This is required for TSA certificates.

# extendedKeyUsage = critical,timeStamping

 

[ 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

 

# 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

 

# This is typical in keyUsage for a client certificate.

# keyUsage = nonRepudiation, digitalSignature, keyEncipherment

 

# 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

 

# 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         = sha256        # algorithm to compute certificate

                                # identifier (optional, default: sha256)

 

[insta] # CMP using Insta Demo CA

# Message transfer

server = pki.certificate.fi:8700

# proxy = # set this as far as needed, e.g., http://192.168.1.1:8080

# tls_use = 0

path = pkix/

 

# Server authentication

recipient = "/C=FI/O=Insta Demo/CN=Insta Demo CA" # or set srvcert or issuer

ignore_keyusage = 1 # potentially needed quirk

unprotected_errors = 1 # potentially needed quirk

extracertsout = insta.extracerts.pem

 

# Client authentication

ref = 3078 # user identification

secret = pass:insta # can be used for both client and server side

 

# Generic message options

cmd = ir # default operation, can be overridden on cmd line with, e.g., kur

 

# Certificate enrollment

subject = "/CN=openssl-cmp-test"

newkey = insta.priv.pem

out_trusted = apps/insta.ca.crt # does not include keyUsage digitalSignature

certout = insta.cert.pem

 

[pbm] # Password-based protection for Insta CA

# Server and client authentication

ref = $insta::ref # 3078

secret = $insta::secret # pass:insta

 

[signature] # Signature-based protection for Insta CA

# Server authentication

trusted = $insta::out_trusted # apps/insta.ca.crt

 

# Client authentication

secret = # disable PBM

key = $insta::newkey # insta.priv.pem

cert = $insta::certout # insta.cert.pem

 

[ir]

cmd = ir

 

[cr]

cmd = cr

 

[kur]

# Certificate update

cmd = kur

oldcert = $insta::certout # insta.cert.pem

 

[rr]

# Certificate revocation

cmd = rr

oldcert = $insta::certout # insta.cert.pem

kali에서 수정한 내용을 캡처했다. 약간 겹치니까 참고해서 보자

 

허허

이제 적용이 잘 됐는지 확인해 본다.

$ openssl list -providers
$ sudo openssl pkey -in pkcs11:id=%12%34 -pubin -pubout -text

근데 key id가 1234인데 왜 %를 붙여야 하는지 provider에도 예시가 하나 있긴 한데, 왜 그래야 하는지 설명도 없고 엄청 헤맸다. (그리고 pin 입력하는 부분이 사라졌다, ubuntu에서는 있었는데...)

어쨌든 이런 식으로 응용해서 키를 불러와 서명 같은 걸 할 수 있다.

참고로 아래는 id에 %를 빼고 실행해 본 결과다

%빼고 실행해보기

https://github.com/latchset/pkcs11-provider/blob/main/tests/README.md
 
 
 근데 좀 이상한 게 id 안 적으면 최근 저장했던 공개키를 불러온다. 아래 예시를 보자
 

이상함...

참고로 키에 접근하기 위한 uri 정보는 id 만 있는게 아니다.


uri 여러개 사용

uri 정보로 token도 있고 여러개 있으니 취향에 따라 하나만 입력해도 되고 여러개 입력하려면 위 사진처럼 하면 된다.

Could not find라고 첫번째 명령어는 일부러 token을 다르게 입력했다. 정보를 잘 인식하는건지 id만 보고 찾는건지 궁금했는데, token도 입력해주면 찾을때 정보로 사용한다.

아래는 ubuntu에서 이것저것 실험했었는데, 예전에 캡처해 둔 거라 내 기억엔 비밀키를 불러오고 싶었던 것과 slot을 두 개 만들었는데 key id가 가장 최근 것만 떠서 해결하려고 몸부림친 흔적들로 기억한다.

 

 

openssl에서는 보안상의 이유로 PKCS#11 모듈에서 개인 키를 직접적으로 내보내는 것이 허용되지 않습니다. 그래서 "Can't export and print private key data"라는 메시지가 출력되는 것입니다. 이는 개인 키를 보호하기 위한 안전장치입니다. https://opendnssec-user.opendnssec.narkive.com/RVxfYrbG/softhsmv2-key-extraction
 

명령어를 잘 보면 pkcs11: 만 해줘도 키가 뜨는데 뭔가 잘 코딩된듯한다.

https://dearzubi.medium.com/integrating-softhsm-with-openssl-using-opensc-pkcs11-184c3f92e397
https://jykim74.tistory.com/140
 
 
글 적는데 너무 버벅거려서 그냥 여기서 마친다. 설명이 몇 개 빠졌는데 그냥 이것저것 실험했던 거라 응용정도는 생략해도 되지 않을까 싶다.

반응형

'HSM 관련' 카테고리의 다른 글

PKCS#11이란?  (0) 2024.10.23