Linux

privacyIDEA: An Open Source MFA Server to Secure Windows and Active Directory

In this tutorial, we will install and configure an MFA server using the privacyIDEA solution on Linux. The goal is to log in to a Windows machine joined to Active Directory with a username and password, while adding a second authentication factor.

privacyIDEA is a free, open source Python application that lets you implement an on-prem MFA server to improve access security through multiple authentication tokens.

As a reminder, MFA, also called "Multi-Factor Authentication", is designed to require one or more authentication factors in addition to a first factor such as a user account name and password, in order to prove identity.

It is an essential security measure today and is probably part of your everyday life: social networks, online banks, and delivery platforms use these systems to prevent accounts from being compromised due to a data leak, for example. Most companies today integrate at least one MFA mechanism into a sign-in flow, whether at logon, during VPN access, or for access to critical services.

The solution presented today, privacyIDEA, offers a wide range of available authentication tokens:

  • TOTP: temporary code generated by an application such as privacyIDEA Authenticator, Google Authenticator, or FreeOTP.
  • HOTP: one-time code based on a counter.
  • Push: notification sent to the phone that the user approves.
  • SMS: one-time code sent by text message.
  • E-mail: code sent to the user’s email address.
  • Passkey / FIDO2 / WebAuthn: authentication with a cryptographic key, optionally protected locally by a fingerprint, face, or PIN.
  • YubiKey, Nitrokey, VASCO, and other hardware tokens.
  • X.509 certificate: possession of a certificate and its private key.
  • TiQR: authentication using a mobile app and a QR code.
  • TAN or paper codes: list of one-time codes.
  • And many more, available in the official documentation.

The project is currently maintained by the German company NetKnights GmbH, which also offers professional support for the solution. Official documentation is available on the privacyidea.org website.

Here is the lab that will be deployed for this tutorial:

  • A Rocky Linux 10.2 VM to host the privacyIDEA application and its database.
  • A Windows Server 2022 VM acting as the Active Directory domain controller.
  • A Windows 11 client VM to test MFA through the privacyIDEA Credential Provider.

Prerequisites

A number of prerequisites are required to install privacyIDEA version 3.14, which is the latest stable release at the time of writing.

First, privacyIDEA can be installed on any Linux distribution using a Python virtual environment. There are also official packages for the following Ubuntu versions: 22.04 LTS, 24.04 LTS, and 26.04 LTS, and deployment via Docker is possible. However, the privacyIDEA server cannot be installed on Windows or macOS.

To make this tutorial useful to as many people as possible, I will install the application using a Python virtual environment.

A Python virtual environment is an isolated folder that contains its own logical Python installation and, above all, its own libraries. It prevents dependencies from multiple projects from being mixed together.

Here are the prerequisites:

  • Supported Python versions range from 3.11 to 3.15. Other versions are not officially tested.
  • privacyIDEA requires a Python virtual environment through the venv module.
  • The application relies on a relational database to store all of its information. Since privacyIDEA is a Python application, it uses the SQLAlchemy utility to communicate with the database. The documentation states that the best results were obtained with a MySQL database. However, it also states that databases supported by SQLAlchemy should work. In my case, I will follow the vendor documentation and install a MySQL database. You can still consult the list of supported databases and versions here.
  • A web server compatible with WSGI must be installed. WSGI stands for "Web Server Gateway Interface" and is a standard that allows a web server to communicate with a Python application. I am choosing Apache with the "mod_wsgi " module.
  • The vendor strongly recommends having working DNS resolution and avoiding static IP addresses to declare the names of your services (for example: a domain controller). It also places special emphasis on correct time synchronization, especially for TOTP tokens, which are time-based.

As for server and database sizing, I could not find any concrete vendor recommendation. You will therefore need to analyze the load and adjust the allocated resources accordingly. The vendor does provide some guidance for diagnosing performance problems on this page, so feel free to use it if you encounter slowness.

Let’s move on to the installation.

Installing privacyIDEA

Installing dependencies

Now that we have reviewed the prerequisites, it is time to proceed with the installation. I personally use a Rocky Linux distribution, which belongs to the Red Hat family of distributions. You will need to adapt the commands below to your distribution.

Before installing the dependencies required by privacyIDEA, it is recommended to update the packages available from the repositories. This ensures up-to-date packages, improves security, and helps avoid dependency conflicts.

sudo dnf update -y

On most modern distributions, a version of Python is already preinstalled. You can check whether Python is installed with the following command:

python3 --version

RockyLinux 10 does not provide mysql packages by default, so I added the official repository and its GPG key using the command below. You may need to do the same depending on the DBMS you want to install and your distribution.

sudo dnf install -y https://dev.mysql.com/get/mysql84-community-release-el10-3.noarch.rpm

We can install the dependencies required by privacyIDEA, namely: Python, a MySQL database, an Apache web server, the wsgi module, the SSL module, and tools for SELinux administration (specific to my distribution). If the installed Python version is supported, you can remove the "python3.x" package.

sudo dnf install python3.12 mysql-community-server httpd python3-mod_wsgi mod_ssl policycoreutils-python-utils -y

Creating the service account and directories

privacyIDEA will rely on a user and on directories that we are going to create to allow the application to function.

Start by creating the "privacyIDEA" user. The account will have the following options:

  • system: marks the account as a system account. It will also have a reserved UID and GID for system accounts.
  • home-dir /opt/privacyidea: this is the user’s home directory.
  • create-home: this option automatically creates the user’s home directory. The /opt/privacyidea directory will be created automatically.
  • shell /sbin/nologin: the account cannot be used for an SSH login or via the su - privacyidea command.

/opt is a directory present on Linux and Unix systems defined in the Filesystem Hierarchy Standard (FHS). This directory is generally used for self-contained third-party applications that were not installed through a package manager.

sudo useradd --system --home-dir /opt/privacyidea --create-home --shell /sbin/nologin privacyidea

We will create the /etc/privacyidea directory as well as the pi.cfg file, which will host the application configuration. Because this directory and file are sensitive, we will protect them with read/write restrictions. The /var/log/privacyidea directory and its privacyidea.log file will store application logs.

sudo mkdir /etc/privacyidea /var/log/privacyideqsudo touch /etc/privacyidea/pi.cfg /var/log/privacyidea/privacyidea.logsudo chmod 750 /etc/privacyidea/
sudo chmod 640 /etc/privacyidea/pi.cfg

Assign rights to the privacyidea user and group on these directories as well as all their contents using the -R (recursive) option.

sudo chown -R privacyidea:privacyidea /etc/privacyidea /var/log/privacyidea/

Database configuration

Now that the directories are created, we are going to prepare the MySQL database to host the application data. Start the mysqld service with the following systemctl command.

sudo systemctl enable --now mysqld

Check that the service is active.

systemctl status mysqld

In the installed version of MySQL, a temporary password is generated in the /var/log/mysqld.log file to use the DBMS root account. I used the command below to retrieve it:

sudo grep 'temporary password' /var/log/mysqld.log

MySQL provides the mysql_secure_installation utility to secure the installation. Run it with the command below:

mysql_secure_installation

We will run the utility twice. During the first run, you will need to change the root password for the DBMS by providing the retrieved temporary password.

For the second run, you will be prompted to change the root password, but also to remove anonymous users, disable remote root access, and so on. Everything is clearly explained. Here is an example from my server to guide you.

The first thing we are going to configure is the MySQL database by adding a database and a user with rights on that database.

Connect to your database as root and enter the DBMS root password (the one defined when running mysql_secure_installation):

mysql -u root -p

Once in the MySQL shell, enter the commands below to create the pi database, the pi@localhost user, and give it rights on the database.

CREATE DATABASE pi;
CREATE USER "pi"@"localhost" IDENTIFIED BY "motdepasse";
GRANT ALL PRIVILEGES ON pi.* TO "pi"@"localhost";
exit;

The result of these three commands should return "Query OK", as shown in the screenshot below.

SQLAlchemy configuration

Now that the pi instance has been created, we are going to tell privacyIDEA how to connect to the database in the configuration file /etc/privacyidea/pi.cfg. I took the template from the official documentation and commented it to help you understand the parameters.

sudo nano /etc/privacyidea/pi.cfg
# ============================================================
# Active configuration
# ============================================================

# Realms allowed to contain privacyIDEA administrators
SUPERUSER_REALM = ['super', 'administrators']

# Database connection URI.
SQLALCHEMY_DATABASE_URI = 'sqlite:////etc/privacyidea/data.sqlite'

# Encryption key for sensitive token data
PI_ENCFILE = '/etc/privacyidea/enckey'

# Audit log signing keys
PI_AUDIT_KEY_PRIVATE = '/etc/privacyidea/private.pem'
PI_AUDIT_KEY_PUBLIC = '/etc/privacyidea/public.pem'

# Log file
PI_LOGFILE = '/var/log/privacyidea/privacyidea.log'

# Log level: (10 = DEBUG | 20 = INFO | 30 = WARNING | 40 = ERROR | 50 = CRITICAL)
PI_LOGLEVEL = 20

# Public URL of the privacyIDEA server. Used for password recovery links (only when the directory is writable)
PI_BASE_URL = "https://privacyidea.it-connect.local"

# Enable Content Security Policy to strengthen security
PI_ENABLE_CSP = True

# Force HTTPS usage
PI_FORCE_HTTPS = True


# ============================================================
# Available / disabled options
# ============================================================
# Interface languages, in order of preference
#PI_PREFERRED_LANGUAGE = ["en"]

# Advanced SQLAlchemy options
# SQLALCHEMY_ENGINE_OPTIONS = {"max_identifier_length": 128}

# Custom audit module
# PI_AUDIT_MODULE = <python audit module>

# Separate database for audit
# PI_AUDIT_SQL_URI = <special audit log DB uri>

# SQL-specific options for the audit database
# PI_AUDIT_SQL_OPTIONS = {}

# Python function executed during initialization
# PI_INIT_CHECK_HOOK = 'your.module.function'

# Completely disable the Web UI
# PI_UI_DEACTIVATED = True

The parameter that interests us here is "SQLALCHEMY_DATABASE_URI". Here is the change we are going to apply to this parameter:

SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://pi:MOT_DE_PASSE@localhost/pi'

Let’s break down this URL to better understand it:

  • mysql+pymysql means that we are using the "MySQL" database engine along with the pymsql driver to communicate with the database.
  • The two slashes are used to introduce credentials. Only the SQLite DBMS uses three slashes, since it does not have a server to contact.
  • pi:MOT_DE_PASSE indicates the user and password to use when connecting to the database.
  • @localhost/pi indicates that we are using the pi database created earlier on the local host.

This URL may change depending on the DBMS used. You can find configuration examples on the official SQLAlchemy website.

Configuring the web server and WSGI

To start the application, Apache will use a WSGI script provided by privacyIDEA. The documentation indicates that it is possible to run several privacyIDEA instances. For more details about setting up a multi-instance configuration, click here.

The script is not yet present on the machine, but it will be present after privacyIDEA is installed. Enable the Apache service to start at boot.

sudo systemctl enable httpd

Create the privacyidea.conf file containing the WSGI script that Apache must execute as well as the parameters to apply. As for the certificate and key that Apache will use for the HTTPS connection, they will be generated in the next step.

sudo nano /etc/httpd/conf.d/privacyidea.conf
# Apache listening port
Listen 443 https

# Reduce information exposed by Apache
ServerTokens Prod
ServerSignature Off
TraceEnable off

# VirtualHost and listening port
<VirtualHost _default_:443>

    # Server DNS name
    ServerName privacyidea.it-connect.local

    # privacyIDEA WSGI application
    WSGIScriptAlias / /etc/privacyidea/privacyideaapp.wsgi

    # Deny access to system files by default
    <Directory />
        Require all denied
    </Directory>

    # Allow only the privacyIDEA WSGI script
    <Directory /etc/privacyidea>
        <Files privacyideaapp.wsgi>
            Require all granted
        </Files>
    </Directory>

    # Dedicated WSGI process and privacyIDEA Python virtual environment
    WSGIDaemonProcess privacyidea \
        processes=1 \
        threads=15 \
        display-name=%{GROUP} \
        user=privacyidea \
        group=privacyidea \
        python-home=/opt/privacyidea

    # Use the privacyIDEA process
    WSGIProcessGroup privacyidea

    # Python compatibility with WSGI
    WSGIApplicationGroup %{GLOBAL}

    # Pass the Authorization header
    WSGIPassAuthorization On

    # Apache logs
    ErrorLog /var/log/httpd/privacyidea_error.log
    CustomLog /var/log/httpd/privacyidea_access.log combined
    LogLevel warn

    # Enable HTTPS
    SSLEngine on

    # TLS certificate
    SSLCertificateFile /etc/pki/tls/certs/privacyidea.crt
    SSLCertificateKeyFile /etc/pki/tls/private/privacyidea.key

</VirtualHost>

The httpd service may fail to start because of a missing certificate declared in the ssl.conf configuration file. This is a generic file generated by the SSL module. Rename it with the mv command. Do the same for Apache’s default welcome page.

sudo mv /etc/httpd/conf.d/ssl.conf /etc/httpd/conf.d/ssl.conf.disabled
sudo mv /etc/httpd/conf.d/welcome.conf /etc/httpd/conf.d/welcome.conf.disabled

Check that the modules are loaded correctly with the following command:

httpd -M | grep -E 'wsgi|ssl'

We are going to generate the certificate and key to allow HTTPS using OpenSSL. In my case, this is a self-signed certificate, but the best option would still be to generate it with a recognized certificate authority (external or internal depending on the use case).

Install the OpenSSL package:

sudo dnf install openssl -y

Then generate the RSA private key and certificate using the command below. About the options used:

  • -x509: directly creates a self-signed certificate without going through a certificate authority.
  • -newkey rsa:4096: creates a new 4096-bit RSA private key.
  • -sha256: uses SHA-256 to sign the certificate.
  • -noenc: leaves the private key without a password so that Apache can start without intervention.
  • -keyout: indicates where to write the private key. Here, it is the path /etc/pki/tls/private/privacyidea.key.
  • -out: indicates where to write the certificate. In our case, the path is /etc/pki/tls/certs/privacyidea.crt.
  • -days 365: makes the certificate valid for 365 days.
  • -subj: defines its common name, here privacyidea.it-connect.local. You can use the FQDN of your server.
  • subjectAltName=DNS:...: adds the DNS name that clients must verify. This is essential for name validation. Be sure to change this field with your server’s FQDN.
  • extendedKeyUsage=serverAuth: indicates that the certificate is intended for TLS server authentication.
sudo openssl req -x509 -newkey rsa:4096 -sha256 -noenc \
  -keyout /etc/pki/tls/private/privacyidea.key \
  -out /etc/pki/tls/certs/privacyidea.crt \
  -days 365 \
  -subj "/CN=privacyidea.it-connect.local" \
  -addext "subjectAltName=DNS:privacyidea.it-connect.local" \
  -addext "extendedKeyUsage=serverAuth"

Before starting the service, we will proceed with the installation and hardening of privacyIDEA.

Installing privacyIDEA

Before downloading the application, declare the /opt/privacyidea directory as a Python virtual environment. However, since it is the privacyidea user that has rights on the directory, but we cannot log in with that user’s shell, we will open bash under the identity of the privacyidea user. The -H option allows us to use the home directory of privacyidea.

sudo -u privacyidea -H bash

Then declare /opt/privacyidea as a Python virtual environment using the Python venv module.

python3 -m venv /opt/privacyidea/

From now on, all Python commands will point to the isolated environment and will not affect the system as a whole.

Move into the directory and activate the Python virtual environment with the activate binary.

cd /opt/privacyidea
source bin/activate

You can see that the terminal changes, since it is prefixed with "(privacyidea)":

To install all the Python dependencies required by privacyidea 3.14, the vendor provides a text file hosted on GitHub.

By retrieving it with the Python package manager pip, along with the -r option to read a file listing dependencies, and the URL, the whole set of dependencies and compatible versions will be installed automatically.

pip install -r https://raw.githubusercontent.com/privacyidea/privacyidea/v3.14/requirements.txt

You should see all the packages being installed progressively until you get the following result:

It is now time to install the application with the pip package manager. This is version 3.14.

pip install privacyidea==3.14

As usual, a message should appear to inform you that the installation was successful:

Hardening

We will now secure the application and the stored data using cryptographic secrets. In the pi.cfg file, two variables contain cryptographic secrets:

  • PI_PEPPER is a secret used to protect administrator passwords. It also protects reset codes and API key secrets.
  • SECRET_KEY is used to sign the authentication JWT returned by /auth after a successful authentication.

We will generate a random string for both variables using the translate command, and add them to the file.

PEPPER="$(tr -dc A-Za-z0-9_ </dev/urandom | head -c24)"
echo "PI_PEPPER = '$PEPPER'" | tee -a /etc/privacyidea/pi.cfg > /dev/null
SECRET="$(tr -dc A-Za-z0-9_ </dev/urandom | head -c24)"
echo "SECRET_KEY = '$SECRET'" | tee -a /etc/privacyidea/pi.cfg > /dev/null

The result of the command should add both variables followed by a random string to the end of the pi.cfg file.

All that remains is to secure the data in the database and to sign the audit logs with the following two commands:

pi-manage setup create_enckey 
pi-manage setup create_audit_keys

The first one creates a encryption key in /etc/privacyidea/ used to protect sensitive data stored in the database, including certain token data and passwords.

The second creates a pair of RSA private and public keys to sign each entry with the private key and later verify the signature with the public key. The main goal is therefore to detect if someone has modified a log entry afterward.

A warning message about user permissions will appear for both commands. Don’t worry: the required permissions were already set earlier and only the service account has rights to view the contents.

Finishing the installation

Let’s finish installing the solution by creating the tables in the SQL database using the provided script:

pi-manage setup create_tables

Then create a local administration account using the following command, providing a password in the interactive shell.

pi-manage admin add IDENTIFIANT

The result of the first command should show the URL being used, and the second should show that the administrator account was created successfully.

The script is provided by privacyIDEA to make the application work. We will create it in the same location as the one declared in the Apache configuration file. The script content is provided in the official documentation.

nano /etc/privacyidea/privacyideaapp.wsgi
import sys
sys.stdout = sys.stderr
from privacyidea.app import create_app
# Now we can select the config file:
application = create_app(config_name="production", config_file="/etc/privacyidea/pi.cfg")

Close the privacyIDEA user shell with the command:

exit
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

Also remember to open port 443 on the machine’s firewall so your clients can access the site:

Add the Apache user to the privacyidea group and change permissions to add read and execute rights for the group on the /opt/privacyidea directory.

sudo usermod -aG privacyidea apache
sudo chmod 750 /opt/privacyidea

Some database data is no longer useful and may eventually fill up storage. The documentation strongly recommends setting up purge jobs using cron. They are however included in a Docker-based installation or Ubuntu packages.

Create the /etc/cron.d/privacyidea file.

sudo nano /etc/cron.d/privacyidea

Add the following content:

*/5 * * * *  privacyidea  /opt/privacyidea/bin/privacyidea-cron run_scheduled -c
0 1 * * *    privacyidea  /opt/privacyidea/bin/pi-manage config challenge cleanup > /dev/null
10 1 * * *   privacyidea  /opt/privacyidea/bin/pi-manage config remembered_device cleanup > /dev/null
20 1 * * *   privacyidea  /opt/privacyidea/bin/pi-manage config authcache cleanup > /dev/null
30 1 * * *   privacyidea  /opt/privacyidea/bin/pi-manage config metrics cleanup > /dev/null
40 1 * * *   privacyidea  /opt/privacyidea/bin/pi-manage conditionalaccess purge-expired-blocks > /dev/null
40 1 * * *   privacyidea  /opt/privacyidea/bin/pi-manage conditionalaccess purge-expired-locks > /dev/null
50 1 * * *   privacyidea  /opt/privacyidea/bin/privacyidea-usercache-cleanup > /dev/null

The final step is to configure SELinux (if it is enabled). As a reminder, SELinux is a security mechanism generally enabled by default on Red Hat family distributions. Its main purpose is to restrict the actions an application can perform according to defined security policies.

  • The first command declares that the /var/log/privacyidea directory contains log files that Apache may use.
  • The second applies the SELinux context defined for the directory and its contents.
  • Finally, the third allows Apache to establish network connections to a database and an LDAP directory.
sudo semanage fcontext -a -t httpd_sys_rw_content_t "/var/log/privacyidea(/.*)?"
sudo restorecon -Rv /var/log/privacyidea
sudo setsebool -P httpd_can_network_connect_db=on httpd_can_connect_ldap=on

If you plan to send emails, add:
sudo setsebool -P httpd_can_sendmail=on

And for connections to remote services (HTTP, SMS gateways, PUSH tokens, RADIUS servers, Keycloak, Entra ID...), add:
sudo setsebool -P httpd_can_network_connect=on

Check the file syntax and start Apache with the following commands:

sudo apachectl configtest # Must display "Syntax OK"
sudo systemctl start httpd

Normally, access to the website should work via the URL: https://host_or_IP

If your privacyIDEA page does not look like mine and seems to have no CSS style loaded, disable the PI_ENABLE_CSP setting by commenting it out or setting it to "False" in /etc/privacyidea/pi.cfg. At the time of writing, this very useful security mechanism (especially against XSS flaws) does not seem to be compatible with the latest version. Remember to re-enable it once the issue is fixed. The HTTPS redirect enforced by PI_FORCE_HTTPS is also disabled because it requires CSP to be active.

I opened an issue on the project’s GitHub to fix this problem.

Configuration

Exploring the dashboard

Log in with the account created using the pi-manage admin add IDENTIFIANT command. Skip the welcome message about the values of Open Source and refuse the creation of the "Realm" for now.

If the login is successful, you should have access to the dashboard.

Let’s quickly describe the available tabs.

  • The Dashboard tab provides an overview of the solution and its activity: authentication, tokens, resolver response times...
  • The Tokens tab is used to manage enrollment, activation, deactivation, synchronization, and assignment of authentication tokens to users. It is also possible to create "Containers", which are logical objects used to group several tokens under one umbrella.
  • The Users tab is related to user management in privacyIDEA.
  • The Policies tab lets you create policies to control the behavior of the application based on different parameters. You can also add API clients for integration with external solutions such as NextCloud, AD FS... and event handlers to automate actions based on events.
  • The Subscription tab allows you to import a privacyIDEA professional support subscription file.
  • The Audit tab contains all event logs and all actions performed in the application. It also includes blocked IPs and users, as well as authentication logs.
  • The External Services tab is used to declare external services that can be used with privacyIDEA: SMTP server, RADIUS, certificate authority, SMS gateway, other privacyIDEA servers...
  • The Config tab is used to configure the solution: the system, tokens, machine resolvers, and machines, as well as periodic tasks.

Setting up Active Directory resolvers

A resolver allows privacyIDEA to know where to look for the users and machines it will need to authenticate. There are two types of resolvers:

  • The first resolver is the "Machine resolver", which makes it possible to retrieve machines either via a local file (/etc/hosts for example) or via an LDAP directory such as Active Directory or OpenLDAP.
  • The second resolver is the "User resolver", which makes it possible to retrieve users from several data sources: a local file such as /etc/passwd, an LDAP directory, an SQL database, a SCIM connector, or an HTTP server.

The "User" resolver is the one we are interested in for this tutorial. Go to "Users" > "Resolvers" and click "New resolver" to add an LDAP resolver.

Then fill in the following information:

  • "Create User Source" and "Connection Details" sections:
    • Resolver Name: I chose the domain controller name, namely "dc01.it-connect.local". You can use any name you want.
    • Type: Choose "LDAP"
    • Scope: Search scopes determine how deep a query searches the directory from the base DN. There are three options: Base (only the specified object), LEVEL (search only among the immediate children of the base object), and SUBTREE (search the base object and all its descendants). Your choice should be SUBTREE if privacyIDEA needs to explore all objects under your base DN, or LEVEL if your users are located directly under the OU. In my case, LEVEL is enough because my users are not spread across sub-OUs.
    • Base DN: This is the base from which privacyIDEA will look for directory users. In my case, it is the default container located at CN=Users,DC=it-connect,DC=local.
    • Server URI: This is a standard format for connecting to an LDAP server. Enter it in the form "ldap://fqdn" or, if needed, "ldap://ip". If you have a working LDAPS setup, use "ldaps://fqdn_or_ip:636" to specify LDAP combined with TLS on port 636. It is also possible to specify multiple domain controllers by separating the URIs with a comma and a space.
  • "Credentials" and "Settings" sections
    • STARTTLS: In my situation, I uncheck it because I do not have a valid certificate on the server. However, I strongly encourage you to use STARTTLS or LDAPS because otherwise traffic is sent in clear text over the network. I also recommend leaving "Verify TLS" enabled if you use LDAPS or STARTTLS to verify that the certificate was issued by a trusted root authority.
    • Bind DN: This field identifies the service account used to query the directory. In my case, it is the "Sync_PrivacyIDEA" account, which has no rights other than read access to the directory. Please do not assign administrative rights to this service account!
    • Bind Password: Service account password
    • Bind Type: Simple
    • Timeout: This is the number of seconds privacyIDEA will wait for an LDAP operation before giving up. This setting prevents a request from being blocked for too long.
    • Size Limit: This number corresponds to the maximum number of LDAP entries a search can return.
    • Cache Timeout: privacyIDEA has a cache to keep previous user queries in memory and improve performance.
    • Server pool retry rounds: the number of full passes privacyIDEA will attempt across the LDAP server list before abandoning the request.
    • Server pool skip timeout (seconds): the amount of time an LDAP server detected as unavailable is set aside before being tried again.

Finally, click the "Preset Active Directory" button to automatically fill in the filters and attributes to use for an Active Directory directory. By default, privacyIDEA uses the sAMAccountName attribute to identify user logins. You can still use userPrincipalName if needed.

Then click "Test Connection" to test your configuration. A message indicating that the connection was successful, followed by the number of detected entries, should appear.

Click "Save" to save the changes.

Creating a realm

For users from resolvers to appear in the privacyIDEA interface, it is necessary to create a realm.

A realm corresponds to a logical grouping of one or more user resolvers. It therefore makes it possible to bring together users from different sources within the same logical space.

For example, it is possible to create a realm named it-connect.local that groups together:

  • An LDAP resolver connected to an Active Directory directory;
  • An SQL resolver containing another user population.

privacyIDEA will then look for users in the it-connect.local realm across all the associated resolvers.

Realm creation is done in the "Users" > "Realms" menu. In the "Resolvers" field, choose the LDAP resolver created earlier. It is possible to create the realm from resolvers located on several privacyIDEA nodes or locally.

Here, nothing changes because we only have one node. It is also possible to assign a priority to resolvers. This priority ranges from 1 to 999 and the default value is 1000, with the lowest value being the resolver with the highest priority.

Then give your realm a name and click the "Create" button.

Now that the realm is created, verify that the users are returned by clicking the "Users" > "Overview" menu.

Setting up policies

The application allows you to define "policies" in order to tell privacyIDEA how to react and behave when it receives a request. Each Policy has a name, a scope, one or more conditions, and one or more associated actions.

The scopes are somewhat like "application domains" and determine when and in what context the policy will apply. There are currently 11 available scopes:

  • Admin policies: These policies are used to regulate the actions that administrators are allowed to perform.
  • User policies: User policies define the actions users are allowed to perform on their own portal when they log in to their portal.
  • Authentication policies: Authentication policies allow better control over how users authenticate.
  • Authorization policies: These are policies related to user permission management.
  • Enrollment policies: The enrollment scope lets you control actions related to token enrollment, whether performed by an administrator or a user.
  • WebUI policies: WebUI stands for "Web User Interface"; these are policies related to the expected behavior of the web page.
  • Register policy: This scope is deprecated and is intended to disappear in future releases of the solution. It allows a user who does not exist in any realm or resolver to register and create their own account.
  • Container policies: We will see what containers are a little later in the article (not Docker...), these policies allow you to frame and configure the direct interactions between a physical device (the container, such as a smartphone) and the privacyIDEA server.
  • Token policies: The token scope is used to define global rules for token behavior and management.
  • Hardening policies: The purpose of this scope is to reduce the amount of information privacyIDEA exposes to unidentified clients.
  • Conditional access policies: This scope makes it possible to detect too many failed login attempts and react automatically. These policies are particularly useful for limiting brute-force attacks.

We are going to set up a few policies together in order to explore how they work. However, I will not go through every scope. I encourage you to use the documentation to build policies adapted to your needs and context.

To help us set up policies, privacyIDEA offers some templates available in the "Policies" > "Create Policy" menu and by clicking the " Policy Templates" button.

The first policy we are going to create will hide the welcome message that appears every time you log in to explain how great open source is. Even if that is true, being reminded of it at every login is a bit annoying.

It turns out that an existing template is available. By clicking the "hide_welcome" template, information is prefilled automatically.

You can see that the policy name, scope, condition, and action are filled in automatically. It is also possible to assign it a priority and a description.

In the "Condition" tab, you can see that the policy applies to all users since no filter is present. I could have applied it only to users in my realm and my dc01.it-connect.local resolver, in which case my Administrator user would still see the pop-up at every login.

It is also possible to add "environment" conditions, including:

  • privacyIDEA Nodes: limits the policy to one or more specific nodes in a clustered deployment.
  • Valid time: limits its application to days and time ranges, for example Monday to Friday, from 8 a.m. to 6 p.m.
  • Client: filters by client IP address, with support for subnets.
  • User Agent: filters based on the software or plugin sending the request. privacyIDEA compares the name only, regardless of version; Add Custom User Agent lets you add one.

Finally, it is possible to add additional conditions to meet specific needs based on a key, an operator, and a value.

Next, go to the "Action" tab. As its name suggests, this tab lets you define the behavior to adopt if the policy conditions are met. Inside, you will find all available actions provided by the "WebUI" scope. The policy action is clearly indicated, and you can add other WebUI-related actions.

Once we consider that our policy is configured, we can save it by clicking "Save".

After I logged in again, the pop-up did not appear.

Let’s set up another policy, this time in the "enrollment" scope to limit the number of active tokens available per user.

By clicking "Create New Policy", I give it a meaningful name such as "limit_users_tokens" and set the "enrollment" scope. In terms of conditions, I want this policy to apply to users in my realm "it-connect.local" and to my resolver "dc01.it-connect.local".

In the "Action" tab, expand the "token" action group to find the "max__active_token_per_user" parameter. You can use the search bar provided by privacyIDEA to make the search easier.

After finding my parameter, I set the value to "2", which means my users can have at most two active assigned tokens. Click the "+" button to add it to the policy actions.

You can do the same to let users benefit from self-service token management using the "user" scope. For the conditions, I kept the same ones as the previous policy, meaning it only applies to the it-connect.local realm. In terms of actions, I defined a list of actions that the user can perform independently when logging in to the portal:

Another interesting policy allows the user to log in for the first time when they have no token available. The onboarding_no_token policy, using the "authentication" scope, lets a user authenticate to privacyIDEA when they do not have a token available. This option avoids prompting for the token while still verifying the password against the Active Directory domain controllers. The term "userstore" refers to the configured Active Directory resolver and/or another user source.

Warning! If you allow your users to delete their tokens and they remove all of them, they will be able to bypass your MFA policy thanks to this policy. In any case, it is better for a technician to assign a token to an employee when they join the company.

Managing administrator rights

Let’s move on to setting up administrative profiles such as "Technician" or "Administrator" in privacyIDEA by relying on Active Directory groups and policies.

privacyIDEA does not provide rights management by matching a privacyIDEA group/profile to an Active Directory group like most tools such as GLPI or Zabbix do. I will use a diagram to help you better understand how administrative rights are managed in the application.

We consider as "Administrators" all people who have extended rights assigned through the "admin" scope. There are two ways to have administrator accounts:

  • The first way is to create a user directly in the internal MySQL database with the command "pi manage admin add IDENTIFIANT". This is how we created the account we are currently logged in with. In this case, it is possible to assign policies to local administrators by naming them explicitly in the policy conditions.
  • The second way, which we will use, is to rely on an external resolver and a realm as we did with the it-connect.local realm and the dc01.it-connect.local resolver. However, there is a major difference: the created realm must be declared as "SUPERUSER_REALM" in the pi.cfg file so that privacyIDEA considers the users to be administrators.

We cannot declare the existing it-connect.local realm as a SUPERUSER_REALM, because that would mean all users would be administrators, which is problematic... We will therefore create two different realms and two LDAP resolvers (based on the same domain controllers):

  • A realm named "pi-helpdesk", associated with the resolver "dc01-helpdesk.it-connect.local", which will allow rights to be granted to technicians.
  • A realm named "pi-administrators" associated with the resolver "dc01-administrators.it-connect.local", to provide rights to administrators.

Let’s begin by creating the resolvers.

In "Users" > "Resolvers", note the configuration of your current resolver and then click "New Resolver". The configuration of the other two resolvers will be exactly the same with a few adjustments.

For the first resolver dc01-helpdesk.it-connect.local, I changed the base DN because my IT team accounts are located in a different OU than the standard users, and I added the following filter for my LDAP search: (sAMAccountName=*)(objectCategory=person)(memberOf=CN=NOMDUGROUPE,OU=Groupes,OU=IT,DC=it-connect,DC=local).

For dc01-administrators.it-connect.local, I only changed the group name in my LDAP filter.

Then click in the "Realms" menu, create the two realms, and assign the corresponding resolvers to them:

We will now modify the pi.cfg file to add our two realms to the "SUPERUSER_REALM" setting. You can remove the two realms listed by default, as they are not used.

Restart Apache with the command:

sudo systemctl restart httpd

Before moving on to policy configuration, we need to add a temporary one for our local administrator. Indeed, once a policy in the "admin" scope is defined, local administrators no longer have full powers. It is therefore necessary to create a full-privilege policy for our current administrator.

Click "Create New Policy", then "Show Template" and select "superuser". In the "Admin Name" text field, type the name of your administrator user, click the "+" button, and save the policy.

To avoid making the tutorial more complex and because the goal is to show you how administrative rights are assigned, I will rely on the "helpdesk" and "superuser" templates provided by privacyIDEA and focus on the "conditions". After clicking the "helpdesk" template, the admin scope is set automatically.

You can then choose an "Admin-Realm" to which the policy will apply; here, since these are technicians, I choose "pi-helpdesk". I do not want technicians to be able to perform administrative actions on administrators or other technicians, so I restrict the policy to the it-connect.local realm.

For the administrator policy with the "superuser" template, I choose the "pi-administrators" realm for the Admin Realm. For the User Realm, I select both of my realms so that administrative actions can be used on users from the it-connect.local realm (standard users) and those from the helpdesk realm.

This separation by realm implies a few changes when logging in to privacyIDEA. Let’s take a technician. When they want to log in, they will have two options:

  • Log in as a "self-service" user with the identifier: login@it-connect.local.
  • Log in as a technician with their administration account via: login@pi-helpdesk. If they are an administrator, the principle is the same with login@pi-administrators.

privacyIDEA provides a feature to display the available realms on the login page for authentication. This is the realm_dropdown parameter in the "webui" scope. A simple policy is enough to set it up. This option can also be restricted to a predefined list of realms. If you decide to enable it, I strongly recommend applying it only to technicians/administrators so as not to reveal the list of realms.

At this point, logging in with a technician and administrator account should work with: login@admin_realm and the Active Directory password.

You can now disable the temporary policy that protected the local administrator so that you can use your AD administration accounts.

privacyIDEA Credential Provider

privacyIDEA Credential Provider is an open source plugin provided by NetKnights (the vendor), which allows an additional second authentication factor to be requested directly when logging in to Windows. A MSI installer is also provided by the vendor.

Be careful before deploying it across your entire environment: the Credential Provider is one of the plugins subject to a usage limit without a subscription: it works for free as long as privacyIDEA has no more than 50 users with an active token. Beyond that, some of the plugin’s requests are rejected with the error No subscription for your client.

The MSI can be downloaded from the project’s GitHub release page at the following link: privacyIDEA Credential Provider.

When running the MSI, click "Next" until you reach this configuration page. Set the URL and the default realm "it-connect.local". You can also check the option "Send the UPN if detected in username field...", if your environment explicitly uses UPNs for privacyIDEA authentication.

If you do not have a certificate recognized by a certificate authority (internal or external), select the "Unkown CA" option. This is obviously valid only in a lab and is not valid in production. Another option (the one I used) is to place the previously generated self-signed certificate in the computer’s store of Trusted Root Certification Authorities.

Rest assured, the options you provide during installation can be changed later in the Registry Editor.

After clicking "Next", you can define what the application will display when the user logs on. I personally recommend the following options:

  • Logo: lets you display the logo of your choice in .bmp format (version 3) at 128 x 128 pixels. The logo must remain constantly available at the path provided after installing the privacyIDEA Credential Provider. I personally stored it in C:\privacyIDEA\.
  • Prompt for username and password first: changes the authentication flow so that the username and Active Directory password are requested first, then the second MFA factor. Without this option, the order is username, MFA, then Active Directory password.
  • Send domain password to privacyIDEA: sends the Active Directory password to the privacyIDEA server. This option is especially required to use the onboarding_no_token policy, so that a user with no token can be authenticated directly against Active Directory.
  • Show an option to reset authentification: displays an option to restart the authentication process, especially after a failure.
  • Prefill username with last logged-in user: prepopulates the last user who logged in on the machine when reconnecting.
  • Hide the username and domain when locked: hides the user and domain when the workstation is locked.

The next window is very important and will define when the privacyIDEA Credential Provider will intervene. It can be configured for three scenarios:

  • Logon: when logging in to a Windows session.
  • Unlock: when unlocking an open Windows session.
  • CredUI: when a login window appears, such as when running an application as Administrator.

By default, privacyIDEA applies to all local scenarios on the workstation or remote scenarios (RDP) but still allows another authentication method (such as Windows’ own). It is nevertheless possible to define when MFA is enforced or not by checking the "Enable Filter" box.

Personally, I will enable it and leave it on "local and remote" for all three scenarios.

It is also possible to enable the privacyIDEA Credential Provider during safe boot. I do not necessarily recommend that.

A major point of attention must be considered: with this configuration, only the privacyIDEA Credential Provider will be able to authenticate users and, as a result, local accounts cannot be used to log in because an OTP will be required. The on_boarding_no_token policy will not apply either because it does not know your user.

To exclude a specific account or group (local or AD), you can add an exclusion for a single account or for a given group by modifying a value in the Registry Editor. Here are the two commands to enter in CMD before rebooting the machine and after installing the Credential Provider:

# For a SINGLE account
reg add "HKLM\SOFTWARE\NetKnights GmbH\PrivacyIDEA-CP" /v excluded_account /t REG_SZ /d "SRV-LOCAL\pi-secours" /f 
# For a group
reg add "HKLM\SOFTWARE\NetKnights GmbH\PrivacyIDEA-CP" /v excluded_group /t REG_SZ /d "IT-Connect\pi-secours-group" /f

The fourth configuration page lets you configure FIDO parameters. The fifth page lets you specify the txt or json file to use to store OTP tokens in offline mode with the privacyIDEA server. Compatible tokens for this mechanism include HOTP and FIDO.

Be careful with the permissions assigned to the file storing offline tokens! It must not be accessible to everyone on the machine, otherwise people with more or less malicious intent could access HOTP hashes or replace the trusted FIDO public key.

Here are the available parameters:

  • Offline file path: path to the JSON file storing offline authentication data. Default: C:\offlineFile.json.
  • Offline threshold: number of OTPs remaining below which the Credential Provider tries to refill from the server. 25 is the value suggested by the installer.
  • Offline try window: maximum number of OTP values compared against the entered code. Default: 10.
  • Show token info if an offline token is found: displays information about the available offline tokens for the user. This is particularly useful to tell the user that an offline authentication method is available.

Finally, the last page lets you manage expiration through the "Token expiration" parameter and the "Delete stale tokens" option for locally stored MFA tokens used for offline authentication.

When no value is set, no expiration or automatic deletion will be performed. I recommend configuring these two parameters if you plan to provide offline tokens to your users.

To change the parameters set during installation, you can use the Windows Registry Editor. You will find all the parameters (and others) at the following path:

HKEY_LOCAL_MACHINE\SOFTWARE\Netknights GmbH\PrivacyIDEA-CP

Click "Install" then "Finish" and restart the computer. You should see the privacyIDEA logo or your company logo appear. When you log in, you will see that your user is authenticated directly. This is normal: thanks to the "onboarding_no_token" policy, the user can log in directly when no tokens are available.

Self-service TOTP token enrollment

Now that we are logged in for the first time, we can go to the privacyIDEA portal so the user can enroll their first authentication token.

As a reminder, a "TOTP", which stands for "Time-based One Time Password", is a time-based one-time code. On the server and on the device generating the code, the code changes at regular intervals, usually 30 or 60 seconds.

However, TOTP has two constraints:

  • The server and the device generating the code must be synchronized in time.
  • Communication is mandatory between the server and the workstation / client service, which means this token cannot be used offline because the server will not be able to validate it.

To enroll the token, log in to the portal with your user account.

Thanks to the configured self-service policy, we can see that only three tabs are available: "Tokens Overview" to view your tokens, "Tokens Enrollment" for enrollment, and "User Details" which displays only user information. By clicking "Enroll a new token", TOTP is automatically selected because it is the only token the user can enroll themselves.

The default values shown to the user (such as the hash algorithm, code length, and so on) for a TOTP token are customizable via policy, among other things. It is indeed difficult to ask users to choose a suitable hash algorithm themselves... Here is an example policy that enforces the "SHA-512" hash algorithm, an 8-character length, and a 60-second interval for users enrolling a TOTP:

The user will still be able to "customize" these options from their perspective, but the policy will enforce the settings.

When you click "Enroll Token", a QR code to scan appears to provision the TOTP token. In itself, any MFA authenticator app such as Microsoft Authenticator would work. However, privacyIDEA offers an iOS and Android app called "privacyIDEA Authenticator". After scanning the QR code with the app, the token appears:

It is possible to rename the token in the application by selecting it, swiping right, and clicking "Edit".

On the privacyIDEA web page, by clicking on "Token Overview", we can see that the token is indeed visible in the privacyIDEA server interface. Clicking it gives us token details.

Now that my user has a token available, if I lock the session, the TOTP code will be requested.

Enrolling an offline HOTP token

In some cases, your user may need to use their workstation without being able to contact the privacyIDEA server.

The solution to this problem is to deploy authentication tokens that can be used without a direct connection to the privacyIDEA server. For this tutorial, we will look at a relatively easy-to-understand example, namely HOTP. HOTP, which stands for "HMAC One Time Password", is an algorithm that generates one-time codes based on a counter and a shared secret between the server and the application generating the codes. With each successful authentication, the counter increments, making the previous code unusable.

In a standard setup, HOTP requires communication between the client and the server to validate that the code matches. However, as you saw during the privacyIDEA Credential Provider installation, it is possible to ask the server for a specific number of tokens that can be used offline. The server then sends the hashes of the next codes associated with a counter value. When a code is entered, the client checks locally whether it matches a stored hash. It can therefore validate it without receiving the shared secret.

Although HOTP is practical for understanding and testing offline authentication, privacyIDEA no longer recommends using it for this scenario:

  • The main problem is that reserving codes for one PC advances the server counter, which prevents them from being used on another workstation or another service.
  • In addition, the local reserve runs out and must be renewed by connecting to the server and logging in with a HOTP code when the server is online.

For a production deployment, the vendor recommends using FIDO/WebAuthn/Passkey tokens instead, which do not rely on reserving a sequence of one-time codes in advance and can be used both online and offline. For our demonstration and with an administrator profile (since the user is only allowed to enroll TOTP tokens, according to my policies), I enrolled an HOTP token for my user.

A QR code then appeared, which I scanned with the app, and the HOTP token appeared.

To retrieve tokens in advance and use them offline, you need to log in once with the HOTP code provided by the available privacyIDEA server. Before that, and so that the server sends the HOTP hashes locally to the workstation, you must modify certain token parameters.

On the server side, in the "Tokens Overview" menu, click the token that was created:

  • Max Count: maximum number of authentication attempts before the token is locked.
  • Count Window: HOTP value window, used to tolerate a few generated but unused codes.
  • Sync Window: counter look-ahead window to recover the application position in case of desynchronization.

Select "Use Offline".

A window will appear with two parameters:

  • Count: the number of offline tokens delivered during the first authentication. Here, about one hundred will be delivered at the first login. For token renewal, this will depend on the parameters entered during Credential Provider installation.
  • Rounds: the number of PBKDF2 iterations used to hash each HOTP code prepared for offline use. The higher the Rounds value, the more expensive it is to compute a stolen hash, and the slower offline verification may be. I personally left the default value.

You can now log in for the first time with the HOTP code to receive the codes usable offline from the privacyIDEA server. Once the code is entered, you must click the arrow in the app so that the code changes and the counter increments. This is an action that must be performed each time an HOTP is used.

You also need to be careful not to press the arrow too many times without consuming the code in the privacyIDEA Authenticator app, otherwise the counter between the server and the app will drift despite the margin provided. If you inspect the offline_token.json file defined during application installation, you can see the HOTP hashes and the expiration date there.

Don’t forget to check the permissions on this file. It is a sensitive file, so only assign rights to the SYSTEM user and an administrators group if needed.

By disconnecting my virtual machine from the network, offline login worked perfectly.

Additional features

privacyIDEA is a complete tool that also offers a few features I did not cover in the article but that are worth highlighting.

Containers

In privacyIDEA, a container represents a device that groups several tokens, for example a phone with an HOTP token and a TOTP token, allowing centralized management of the tokens. The main benefit is device management: if the user loses their phone, the administrator can disable all tokens in the container in a single operation. For existing users with assigned tokens, you can attach them to the container by selecting your user and adding their tokens.

You can then manage the entire container through the "state" field.

Machine Resolver

The "Machine Resolver" works on the same principle as the "User Resolver" except that it can retrieve machines either through a local file (/etc/hosts for example) or through an LDAP directory such as Active Directory or OpenLDAP.

The configuration is quite similar to the User Resolver, with a few details. It can be useful in several situations, such as decrypting a Linux disk encrypted with a YubiKey or finding directory servers so their authorized SSH public keys can be associated. However, I have not seen many documented use cases for it.

Event Handler

The Event Handler lets you automate an action when an event occurs in privacyIDEA, with or without conditions. A simple example would be automatically sending an email to the user when an action is performed on one of their tokens (creation, deactivation, etc.).

Periodic Task

Periodic Tasks execute an action at regular intervals, for example every hour.

The modules currently provided by privacyIDEA are two in number:

  • SimpleStat: records the number of tokens each day to track deployment growth.
  • EventCounter: records the failed authentication counter every hour (fed by an Event Handler) to track its evolution.

Conclusion

This tutorial comes to an end. We have taken a tour of the privacyIDEA solution. As you have seen, it is a complete and highly customizable solution that can fit into your information system.

In March 2022, a report published by CISA and the FBI, based on industry research, reminds us that users with MFA are up to 99% less likely to have their accounts compromised. I hope this tutorial helped you better understand how MFA works and gave you the keys to strengthen your access security with privacyIDEA.

Whether you are a student, enthusiast, administrator, or cybersecurity expert, feel free to share your feedback and suggestions on my article. Thank you for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.