Configuração do PKCS#11¶
Instalação¶
Pode obter o módulo NetHSM PKCS#11 como um binário pré-compilado ou compilá-lo a partir da fonte.
Binários pré-compilados¶
Download the module file corresponding to your system from the releases page of the repository.
Copie o ficheiro do módulo para o diretório onde as suas aplicações PKCS#11 esperam encontrá-lo.
Compilar a partir da fonte¶
Instalar a cadeia de ferramentas Rust ` <https://www.rust-lang.org/tools/install>` __.
Descarregue e extraia a fonte da página de lançamentos ` <https://github.com/Nitrokey/nethsm-pkcs11/releases>` __ ou clone o repositório ` <https://github.com/Nitrokey/nethsm-pkcs11>` __.
Executar
cargo build --releaseno diretório de origem.
Configuração¶
Por predefinição, o módulo procura ficheiros de configuração em:
/etc/nitrokey/p11nethsm.conf/usr/local/etc/nitrokey/p11nethsm.conf$HOME/.config/nitrokey/p11nethsm.conf
Se estiverem presentes vários ficheiros, as configurações serão combinadas de modo a que as ranhuras de todos os ficheiros de configuração sejam utilizadas pelo módulo.
Pode definir manualmente a localização do ficheiro de configuração (apenas este será lido) com a variável env P11NETHSM_CONFIG_FILE (e.g. P11NETHSM_CONFIG_FILE=./p11nethsm.conf).
Configuration File Format¶
A configuração é formatada em yaml:
# Set this option to true to enable the compatibility option for the C_SetAttributeValue() function.
# This allows the applications using the Java Sun PKCS11 module (like EJBCA) to generate keys.
# When using this, the names given to the keys will be ignored and the keys will have random names.
# Under the hood it will store in memory the name given to the key when calling C_SetAttributeValue(). When a certificate is uploaded it will check if the name was previously passed to C_SetAttributeValue() and translate it to the real name on the NetHSM.
enable_set_attribute_value: false
# Optional log level, acceptable values are Trace, Debug, Info, Warn and Error
log_level: Debug
# By default, the module logs to both syslog and stderr, trying the sockets /dev/log, /var/run/syslog and finally /var/run/log
# A custom socket can be configured:
syslog_socket: /var/nethsm/log
# Instead of a socket, a custom UDP or TCP syslog can be configured:
# syslog_udp:
# to_addr: 127.0.0:1:514
# from_addr: 127.0.0:1:4789
# syslog_tcp: 127.0.0.1:601
# Only one option among "syslog_socket", "syslog_udp", "syslog_tcp" can be configured at the same time
# You can configure the syslog facility ( "kern", "user", "mail", "daemon", "auth", "syslog", "lpr", "news", "uucp", "cron", "authpriv", "ftp", "local0", "local1", "local2", "local3", "local4", "local5", "local6" or "local7"):
syslog_facility: "user"
# You can set the hostname (for use only with syslog_udp or syslog_tcp)
# syslog_hostname: "localhsm-pkcs11"
# You can set the process name (defaults to the process name obtained from the OS)
# syslog_process: "NetHSM Pkcs11"
# You can set the pid used in logs (defaults to the process id obtained from the OS)
# syslog_pid: 0
# You can also configure a custom file, or "-" for stderr.
# log_file: /tmp/p11nethsm.log
# Each "slot" represents a HSM cluster of server that share the same user and keys.
slots:
- label: LocalHSM # Name your NetHSM however you want
description: Local HSM (docker) # Optional description
# Users connecting to the NetHSM server
operator:
username: "operator"
# If the password starts with `env:`, it will obtain the password from an environment variable:
# password: "env:LOCALHSMPASS"
# password: "localpass"
#
# If the field is not provided, it is expected to be given through `C_Login` function with the
# `CKU_USER` userType
administrator:
username: "admin"
# If the password starts with `env:`, it will obtain the password from an environment variable:
# password: "env:LOCALADMINHSMPASS"
# password: "adminpass"
#
# If the field is not provided, it is expected to be given through `C_Login` function with the
# `CKU_SO` userType
# List the NetHSM instances
instances:
- url: "https://keyfender:8443/api/v1" # URL to reach the server
# To avoid having to re-open connections on each requests, the module keeps a connection pool to each instance. If the module is used by a multithreaded application, multiple connections can be opened at the same time.
# This configures the maximum number of connections in the pool at the same time.
# Note that this does not limit the total number of open connections.
# Having a degree of parallelism that is higher than the max number of idle connection can lead overhead as those connections will be closed an re-opened frenquently
max_idle_connections: 10
# By default, the certificate of the HSM will be validated using the system's root certificate authority.
# When the NetHSM uses a self-signed certificate, it can be verified against an allowed list of sha256 fingerprint of the NetHSM's certificate:
sha256_fingerprints:
- "31:92:8E:A4:5E:16:5C:A7:33:44:E8:E9:8E:64:C4:AE:7B:2A:57:E5:77:43:49:F3:69:C9:8F:C4:2F:3A:3B:6E"
# Alternatively certificate checks can be skipped entirely with danger_insecure_cert option.
# This should be avoided if possible and certainly not used with a productive NetHSM.
# danger_insecure_cert: true
# Configure whether the certificates stored in the nethsm are stored in PEM or DER
# The nethsm itself supports both, but some tooling may only support one of the encodings.
# Valid values are PEM or DER. Defaults to PEM
#
# Values exchanged over the PKCS#11 interface will always be DER encoded.
# This config only changes the format they are stored in on the Nethsm itself for compatibility with other tooling.
certificate_format: PEM
# Configure the network retry mechanism. If absent, no retries are attempted on a network error
retries:
# The number of retries after a network error
count: 3
# The delay between retries, in integer seconds
delay_seconds: 1
# it is possible to configure idle connections to make use of TCP keepalives, preventing the closing of connections by a firewall or detecting such cases
tcp_keepalive:
# the number of seconds before keepalives packets start being sent
# Corresponds to `TCP_KEEPIDLE` on Linux, `TCP_KEEPALIVE` on macOS, and the field keepalivetime of tcp_keepalive on Windows
time_seconds: 600
# the number of seconds between each keepalive packet
# Corresponds to `TCP_KEEPINTVL` on Linux and macOS, and the field keepaliveinterval of tcp_keepalive on Windows
interval_seconds: 60
# the number of keepalive packets being sent without a response before the connection
# is considered closed
# Corresponds to `TCP_KEEPCNT` on Linux and macOS, and is not used on Windows
retries: 3
# Time a connection can spend idle before being closed
connections_max_idle_duration: 1800
# Configurable timeout for network operations. If a network operation takes more than, `timeout_seconds`, consider it failed. If `retries` is configured, it will be retried.
# Defaults to infinite
timeout_seconds: 10
Instâncias¶
Se várias instâncias do NetHSM estiverem listadas no mesmo slot, essas instâncias devem ser configuradas num cluster. As credenciais dos utilizadores e as chaves devem ser as mesmas em todas as instâncias.
O módulo utilizará as instâncias de forma round-robin, tentando outra instância se uma falhar.
Verificar com o comando lsusb se o Nitrokey é reconhecido. A saída deve listar o Nitrokey, por exemplo, Bus 001 Device 002: ID 20a0:42b2 Clay Logic Nitrokey 3.¶
Para melhorar a fiabilidade do módulo PKCS#11, é possível configurar tempos limite, novas tentativas, redundância de instâncias e TCP keepalives.
Retries¶
Se uma instância do NetHSM estiver inacessível, o módulo PKCS#11 é capaz de tentar novamente enviar o pedido para outras instâncias ou para a mesma instância (se outras instâncias também estiverem inacessíveis). É possível introduzir um atraso entre as novas tentativas.
Pode utilizar o NetHSM para autenticação SSH. É necessário passar o caminho do módulo PKCS#11 na linha de comando ou na configuração SSH.
If no background thread can be spawned (CKF_LIBRARY_CANT_CREATE_OS_THREADS), failed instances will be tried during normal operations, slowing down the requests. To minimise this, such «inline» health checks are limited to one second timeouts, and only three health checks can be attempted per request (this is a worst case situation that can only be reached if a large number of instances failed).
Por conseguinte:
O número máximo de pedidos enviados para uma chamada à API é:
retries.count+ 1 + 3A duração máxima (pior caso) antes de atingir o tempo limite para uma chamada à API é: (
retries.count+ 1) *timeout_seconds+ 3The maximum timeout for one PKCS#11 function call will vary because some functions will lead to multiple API calls in the NetHSM.
TCP keepalive¶
Para melhorar o desempenho, as ligações são mantidas abertas com as instâncias do NetHSM para evitar a necessidade de as reabrir. É possível que, em uma rede com firewall, essas conexões ociosas possam ser fechadas, levando ao timeout da próxima tentativa de conexão. Para evitar que os timeouts lentos aconteçam e para detetar mais cedo se isso acontecer, é possível configurar TCP keepalives para eles.
Users¶
Os utilizadores operador e administrador são ambos opcionais, mas o módulo não arranca se não estiver configurado nenhum utilizador. Isto permite-lhe configurar o módulo apenas com um utilizador administrador, apenas com um utilizador operador ou com ambos ao mesmo tempo.
Quando os dois utilizadores estiverem definidos, o módulo utilizará o operador por defeito e só utilizará o utilizador administrador quando a ação o necessitar.
O utilizador regular PKCS#11 é mapeado para o operador do NetHSM e o SO PKCS#11 é mapeado para o administrador do NetHSM.
Passwords¶
A palavra-passe pode ser fornecida por vários meios:
Em texto simples na configuração
password: "mypassword"Numa variável de ambiente lida pelo módulo com o prefixo
env::env:ENV_STORING_THE_PASSWORDAtravés da função de login do pkcs11, exemplo para o pcks11-tool:
pkcs11-tool --module libnethsm_pkcs11.so -p opPassphrasePara fornecer a senha de administrador você precisa usar--so-pinem vez disso:pkcs11-tool --module libnethsm_pkcs11.so --login --login-type so --so-pin Administrator
Se a palavra-passe de um utilizador não estiver definida no ficheiro de configuração, será necessário um início de sessão para fornecer a palavra-passe (3.º método).
Uma NetHSM que não esteja operacional é considerada como uma ranhura com o token não presente.