How to use PAM modules for local authentication in Linux using GOST-2012 keys on Rutoken

How to use PAM modules for local authentication in Linux using GOST-2012 keys on Rutoken

Simple passwords do not protect, and complex ones are impossible to remember. Therefore, they so often end up on a sticker under the keyboard or on the monitor. So that passwords remain in the minds of “forgetful” users and the reliability of protection is not lost, there is two-factor authentication (2FA).

By combining the factors of owning a device and knowing its PIN, the PIN itself can be simpler and easier to remember. Shortcomings in the length or randomness of the PIN are made up for by the physical possession requirement and restrictions on PIN brute force.

In addition, it happens in state institutions that they want everything to work in accordance with GOST. This variant of 2FA for logging into Linux will be discussed. I'll start from afar.

PAM modules

Pluggable Authentication Modules (PAM) are modules with a standard API and implementations of various authentication mechanisms in applications.
All utilities and applications that can work with PAM pick it up and can use it to authenticate the user.
In practice, this works something like this: the login command calls PAM, which performs all the necessary checks using the modules specified in the configuration file and returns the result back to the login command.

librtpam

The module developed by Aktiv adds two-factor authentication of users using smart cards or USB tokens using asymmetric keys according to the latest standards of domestic cryptography.

Consider the principle of its work:

  • the user certificate and its private key are stored on the token;
  • the certificate is stored in the user's home directory as trusted.

The authentication process goes like this:

  1. Rutoken searches for the user's personal certificate.
  2. The PIN code of the token is requested.
  3. Random data is signed on the private key directly in the Rutoken chip.
  4. The resulting signature is verified using the public key from the user's certificate.
  5. The module returns the result of the signature verification to the calling application.

You can authenticate using keys GOST R 34.10-2012 (length 256 or 512 bits) or outdated GOST R 34.10-2001.

You do not have to worry about the security of keys - they are generated directly in Rutoken and never leave its memory during cryptographic operations.

How to use PAM modules for local authentication in Linux using GOST-2012 keys on Rutoken

Rutoken EDS 2.0 is certified by the FSB and FSTEC according to NDV 4, therefore it can be used in information systems that process confidential information.

Practical use

Almost any modern Linux will do, for example we will use xUbuntu 18.10.

1) Install the necessary packages

sudo apt-get install libccid pcscd opensc
If you want to add a desktop lock screensaver - additionally install the package libpam-pkcs11.

2) Add a PAM module with GOST support

Loading the library from https://download.rutoken.ru/Rutoken/PAM/
Copy the contents of the PAM folder librtpam.so.1.0.0 to the system folder
/usr/lib/ or /usr/lib/x86_64-linux-gnu/or /usr/lib64

3) Install the package with librtpkcs11ecp.so

Download and install the DEB or RPM package from the link: https://www.rutoken.ru/support/download/pkcs/

4) We check that Rutoken EDS 2.0 is working in the system

In the terminal we execute
$ pkcs11-tool --module /usr/lib/librtpkcs11ecp.so -T
If you see the line Rutoken ECP <no label> - it means everything is OK.

5) Read the certificate

Check if the device has a certificate
$ pkcs11-tool --module /usr/lib/librtpkcs11ecp.so -O
If after the line:
Using slot 0 with a present token (0x0)

  • information is displayed about keys and certificates, then you need to read the certificate and save it to disk. To do this, run the following command, where instead of {id} you need to substitute the certificate ID that you saw in the output of the previous command:
    $ pkcs11-tool --module /usr/lib/librtpkcs11ecp.so -r -y cert --id {id} --output-file cert.crt
    If the cert.crt file has been created, go to step 6).
  • there is nothing, means the device is empty. Contact your administrator or create the keys and certificate yourself by following the next step.

5.1) Create a test certificate

Attention! The described methods for generating keys and certificates are suitable for testing and are not intended for use in combat mode. To do this, you need to use keys and certificates issued by your organization's trusted certificate authority or an accredited certification authority.
The PAM module is designed to protect local computers and is designed to work in small organizations. Since there are few users, the Administrator can monitor the revocation of certificates and manually block accounts, as well as the validity period of certificates. The PAM module is not yet able to check certificates against CRLs and build chains of trust.

Easy way (via browser)

To get a test certificate, use web service "Registration Center Rutoken". The process will take no more than 5 minutes.

Geek path (via console and possibly compiler)

Check your OpenSC version
$ opensc-tool --version
If version is less than 0.20 then upgrade or build pkcs11-tool branch with GOST-2012 support from our GitHub (at the time of this article, release 0.20 has not yet been released) or from the master branch of the main OpenSC project no later than commit 8cf1e6f

We generate a key pair with parameters:
--key-type: GOSTR3410-2012-512:А (ГОСТ-2012 512 бит c парамсетом А), GOSTR3410-2012-256:A (ГОСТ-2012 256 бит с парамсетом A)

--id: object identifier (CKA_ID) in the form of two-digit character numbers in hex from the ASCII table. Use only ASCII codes for printable characters, as id will need to be passed to OpenSSL as a string. For example, the ASCII codes "3132" correspond to the string "12". For convenience, you can use online service for converting a string to ASCII codes.

$ ./pkcs11-tool --module /usr/lib/librtpkcs11ecp.so --keypairgen --key-type GOSTR3410-2012-512:A -l --id 3132

Next, we will create a certificate. Two ways will be described below: the first is through the CA (we will use test CAs), the second is self-signed. To do this, you first need to install and configure OpenSSL version 1.1 or later to work with Rutoken through a special rtengine module using the manual Installing and configuring OpenSSL.
For example: for '--id 3132' in OpenSSL must be specified "pkcs11:id=12«.

You can use the services of a test CA, of which there are many, for example, here, here и here, for this we will create a certificate request

Another option - you can succumb to laziness and create a self-signed
$ openssl req -utf8 -new -keyform engine -key "pkcs11:id=12" -engine rtengine -out req.csr

Uploading the certificate to the device
$ openssl req -utf8 -x509 -keyform engine -key "pkcs11:id=12" -engine rtengine -out cert.cer

6) Register the certificate in the system

Make sure your certificate looks like a base64 file:

How to use PAM modules for local authentication in Linux using GOST-2012 keys on Rutoken

If your certificate looks like this:

How to use PAM modules for local authentication in Linux using GOST-2012 keys on Rutoken

then you need to convert the certificate from DER format to PEM format (base64)

$ openssl x509 -in cert.crt -out cert.pem -inform DER -outform PEM
We check again that everything is in order now.

Add the certificate to the list of trusted certificates
$ mkdir ~/.eid
$ chmod 0755 ~/.eid
$ cat cert.pem >> ~/.eid/authorized_certificates
$ chmod 0644 ~/.eid/authorized_certificates

The last line protects the list of trusted certificates from accidental or intentional changes by other users. This prevents someone from adding their certificate here and being able to log in on your behalf.

7) Set up authentication

The configuration of our PAM module is completely standard and is done in the same way as the configuration of other modules. Create to file /usr/share/pam-configs/rutoken-gost-pam containing the full name of the module, whether it is enabled by default, the priority of the module, and authentication options.
Authentication parameters contain requirements for the success of the operation:

  • required: Such modules must return a positive response. If the result of a module call contains a negative response, this will result in an authentication error. The request will be reset, but the rest of the modules will be called.
  • requisite (required): Similar to required, but immediately fails authentication and ignores other modules.
  • sufficient: If before such a module none of the required or sufficient modules returned a negative result, then the module will return a positive response. The remaining modules will be ignored.
  • optional (optional): If there are no required modules on the stack and none of the sufficient modules returned a positive result, then at least one of the optional modules must return a positive response.

Full file content /usr/share/pam-configs/rutoken-gost-pam:
Name: Rutoken PAM GOST
Default: yes
Priority: 800
Auth-Type: Primary
Auth: sufficient /usr/lib/librtpam.so.1.0.0 /usr/lib/librtpkcs11ecp.so

How to use PAM modules for local authentication in Linux using GOST-2012 keys on Rutoken

save the file, then execute
$ sudo pam-auth-update
in the window that appears, put an asterisk next to Rutoken PAM GOST and push OK

How to use PAM modules for local authentication in Linux using GOST-2012 keys on Rutoken

8) Checking the setting

To understand that everything is set up, but at the same time not to lose the ability to log in, enter the command
$ sudo login
Enter a username. Everything is set up correctly if the system requires a device PIN.

How to use PAM modules for local authentication in Linux using GOST-2012 keys on Rutoken

9) Set up a computer lock when extracting a token

Included in the package libpam-pkcs11 utility included pkcs11_eventmgr, which allows you to perform various actions when PKCS # 11 events occur.
For settings pkcs11_eventmgr serves as a configuration file: /etc/pam_pkcs11/pkcs11_eventmgr.conf
For different Linux distributions, the command that causes the account to be blocked when a smart card or token is removed will be different. Cm. event card_remove.
An example configuration file is shown below:

pkcs11_eventmgr
{
    # Запуск в бэкграунде
    daemon = true;
     
    # Настройка сообщений отладки
    debug = false;
 
    # Время опроса в секундах
    polling_time = 1;
 
    # Установка тайм-аута на удаление карты
    # По-умолчанию 0
    expire_time = 0;
 
    # Выбор pkcs11 библиотеки для работы с Рутокен
    pkcs11_module = usr/lib/librtpkcs11ecp.so;
 
    # Действия с картой
    # Карта вставлена:
    event card_insert {
        # Оставляем значения по умолчанию (ничего не происходит)
        on_error = ignore ;
 
        action = "/bin/false";
    }
 
    # Карта извлечена
    event card_remove {
        on_error = ignore;
         
        # Вызываем функцию блокировки экрана
        
        # Для GNOME 
        action = "dbus-send --type=method_call --dest=org.gnome.ScreenSaver /org/gnome/ScreenSaver org.gnome.ScreenSaver.Lock";
        
        # Для XFCE
        # action = "xflock4";
        
        # Для Astra Linux (FLY)
        # action = "fly-wmfunc FLYWM_LOCK";
    }
 
    # Карта долгое время извлечена
    event expire_time {
        # Оставляем значения по умолчанию (ничего не происходит)
        on_error = ignore;
 
        action = "/bin/false";
    }
}

After that add the application pkcs11_eventmgr to autoload. To do this, edit the .bash_profile file:
$ nano /home/<имя_пользователя>/.bash_profile
Add the pkcs11_eventmgr line to the end of the file and reboot.

The described steps for setting up the operating system can be used as instructions in any modern Linux distribution, including domestic ones.

How to use PAM modules for local authentication in Linux using GOST-2012 keys on Rutoken

Conclusion

PCs with Linux in Russian government agencies are becoming more and more popular, and setting up reliable two-factor authentication in this OS is not always easy. We will be happy to help you with this guide to solve the “password problem” and securely protect access to your PC without spending a lot of time on it.

Source: habr.com

Add a comment