[PATCH 14/14] tests: pkcs11 external password backend with SoftHSM

Angelo Compagnucci angelo.compagnucci at gmail.com
Mon Nov 23 06:24:48 PST 2026


Test the pkcs11 backend with a SoftHSM token. Each test creates its own
token and runs its own wpa_supplicant with SOFTHSM2_CONF set. The tests
check that:
- SAVE_CONFIG stores a passphrase or a raw PSK on the token, and the
  file has only psk=ext:<name>
- the station connects with the PSK read from the token, also after a
  second save replaced it
- the object is private, so it cannot be read without the PIN
- the PIN can come from a pin-source file, and the module from
  pkcs11_module_path
- a wrong PIN makes SAVE_CONFIG fail and leaves the file unchanged
- invalid URIs, and a module or token that is not there, are reported

The tests are skipped when softhsm2-util is not installed or the
backend is not built.

Signed-off-by: Angelo Compagnucci <angelo.compagnucci at gmail.com>
---
 tests/hwsim/test_ext_password.py | 266 +++++++++++++++++++++++++++++++
 1 file changed, 266 insertions(+)

diff --git a/tests/hwsim/test_ext_password.py b/tests/hwsim/test_ext_password.py
index 7e8e07aad..30a876a1f 100644
--- a/tests/hwsim/test_ext_password.py
+++ b/tests/hwsim/test_ext_password.py
@@ -7,10 +7,17 @@
 from remotehost import remote_compatible
 import logging
 logger = logging.getLogger()
+import glob
+import hashlib
 import os
+import shutil
+import signal
+import subprocess
 import tempfile
+import time
 
 import hostapd
+from hwsim import HWSimRadio
 from utils import *
 from wpasupplicant import WpaSupplicant
 from test_ap_hs20 import hs20_ap_params
@@ -201,3 +208,262 @@ def test_ext_password_save_config(dev, apdev, params):
             wpas.interface_remove("wlan5")
         except:
             pass
+
+def softhsm_module():
+    util = shutil.which("softhsm2-util")
+    if not util:
+        raise HwsimSkip("softhsm2-util not available")
+    prefix = os.path.dirname(os.path.dirname(os.path.realpath(util)))
+    paths = [os.path.join(prefix, "lib", "softhsm", "libsofthsm2.so")]
+    paths += glob.glob(os.path.join(prefix, "lib", "*", "softhsm",
+                                    "libsofthsm2.so"))
+    paths += glob.glob(os.path.join(prefix, "lib*", "pkcs11",
+                                    "libsofthsm2.so"))
+    for path in paths:
+        if os.path.exists(path):
+            return util, path
+    raise HwsimSkip("SoftHSM PKCS#11 module not found")
+
+def softhsm_token(params, prefix):
+    """Create a SoftHSM token labeled wifi with user PIN 1234"""
+    util, module = softhsm_module()
+    # Not prefix.*: run-tests.py reads those files after the test
+    tokens = os.path.join(params['logdir'], 'softhsm-' + prefix)
+    if os.path.exists(tokens):
+        shutil.rmtree(tokens)
+    os.mkdir(tokens)
+    conf = os.path.join(params['logdir'], prefix + '.softhsm2.conf')
+    with open(conf, "w") as f:
+        f.write("directories.tokendir = %s\n" % tokens)
+        f.write("objectstore.backend = file\n")
+    env = dict(os.environ, SOFTHSM2_CONF=conf)
+    subprocess.check_call([util, "--init-token", "--free", "--label", "wifi",
+                           "--so-pin", "5678", "--pin", "1234"], env=env,
+                          stdout=subprocess.DEVNULL)
+    return module, env
+
+class Pkcs11Wpas(object):
+    """wpa_supplicant with the pkcs11 backend, in its own environment"""
+
+    def __init__(self, iface, params, prefix, env=None):
+        self.iface = iface
+        self.env = env
+        self.wpas = None
+        self.logfile = os.path.join(params['logdir'], prefix + '.log-wpas')
+        self.pidfile = os.path.join(params['logdir'], prefix + '.pid-wpas')
+        self.conffile = os.path.join(params['logdir'], prefix + '.conf')
+        self.prg = os.path.join(params['logdir'], 'alt-wpa_supplicant',
+                                'wpa_supplicant', 'wpa_supplicant')
+        if not os.path.exists(self.prg):
+            self.prg = '../../wpa_supplicant/wpa_supplicant'
+
+    def log(self):
+        with open(self.logfile, "r") as f:
+            return f.read()
+
+    def start(self, backend, extra="", fail=False):
+        with open(self.conffile, "w") as f:
+            f.write("ctrl_interface=DIR=/var/run/wpa_supplicant\n")
+            f.write("update_config=1\n")
+            f.write(extra)
+            f.write("ext_password_backend=%s\n" % backend)
+            f.write('network={\n\tssid="ext-pw-psk"\n\tpsk=ext:psk1\n')
+            f.write('\tscan_freq=2412\n\tdisabled=1\n}\n')
+        arg = [self.prg, '-BddtK', '-P', self.pidfile, '-f', self.logfile,
+               '-Dnl80211', '-c', self.conffile, '-i', self.iface]
+        logger.info("Start wpa_supplicant: " + str(arg))
+        res = subprocess.call(arg, env=self.env)
+        if res != 0:
+            if "EXT PW PKCS11:" not in self.log():
+                raise HwsimSkip("pkcs11 external password backend not "
+                                "supported in the build")
+            if fail:
+                return None
+            raise Exception("wpa_supplicant did not start")
+        if fail:
+            raise Exception("wpa_supplicant started with an invalid backend")
+        self.wpas = WpaSupplicant(ifname=self.iface)
+        return self.wpas
+
+    def stop(self):
+        if self.wpas:
+            self.wpas.close_monitor()
+            self.wpas.request("TERMINATE")
+            self.wpas = None
+        for i in range(50):
+            if not os.path.exists(self.pidfile):
+                return
+            time.sleep(0.1)
+        with open(self.pidfile, "r") as f:
+            os.kill(int(f.read().strip()), signal.SIGTERM)
+
+    def restart(self, backend, extra=""):
+        self.stop()
+        return self.start(backend, extra)
+
+    def save(self, secret):
+        if "OK" not in self.wpas.request("SAVE_CONFIG"):
+            raise Exception("Failed to save configuration file")
+        with open(self.conffile, "r") as f:
+            data = f.read()
+        logger.info("Configuration file contents: " + data)
+        if "psk=ext:psk1" not in data:
+            raise Exception("External PSK not saved")
+        if secret in data:
+            raise Exception("PSK saved in the configuration file")
+
+def pkcs11_connect(wpas, expect):
+    wpas.select_network(0)
+    ev = wpas.wait_event(["CTRL-EVENT-CONNECTED",
+                          "WPA: 4-Way Handshake failed",
+                          "EXT PW: No PSK found from external storage"],
+                         timeout=15)
+    if ev is None:
+        raise Exception("No connection result reported")
+    if expect not in ev:
+        raise Exception("Unexpected connection result: " + ev)
+    wpas.request("DISCONNECT")
+    if "CTRL-EVENT-CONNECTED" in ev:
+        wpas.wait_disconnected()
+
+def test_ext_password_pkcs11_psk(dev, apdev, params):
+    """External password storage on a PKCS#11 token for PSK"""
+    prefix = "ext_password_pkcs11_psk"
+    hapd = hostapd.add_ap(apdev[0],
+                          hostapd.wpa2_params(ssid="ext-pw-psk",
+                                              passphrase="12345678"))
+    module, env = softhsm_token(params, prefix)
+    with HWSimRadio() as (radio, iface):
+        p = Pkcs11Wpas(iface, params, prefix, env)
+        try:
+            run_ext_password_pkcs11_psk(p, module)
+        finally:
+            p.stop()
+
+def run_ext_password_pkcs11_psk(p, module):
+    uri = "pkcs11:token=wifi?module-path=" + module
+
+    # Nothing is stored on the token yet
+    wpas = p.start(uri + "&pin-value=1234")
+    pkcs11_connect(wpas, "No PSK found")
+
+    # SAVE_CONFIG stores the passphrase on the token
+    wpas.set_network_quoted(0, "psk", "12345678")
+    p.save("12345678")
+    wpas = p.restart(uri + "&pin-value=1234")
+    pkcs11_connect(wpas, "CTRL-EVENT-CONNECTED")
+
+    # A second save replaces it
+    wpas.set_network_quoted(0, "psk", "87654321")
+    p.save("87654321")
+    wpas = p.restart(uri + "&pin-value=1234")
+    pkcs11_connect(wpas, "4-Way Handshake failed")
+    wpas.set_network_quoted(0, "psk", "12345678")
+    p.save("12345678")
+    wpas = p.restart(uri + "&pin-value=1234")
+    pkcs11_connect(wpas, "CTRL-EVENT-CONNECTED")
+
+    # The object is private: it cannot be read without the PIN
+    wpas = p.restart(uri)
+    pkcs11_connect(wpas, "No PSK found")
+
+    # A token that is not there is reported when the PSK is read
+    wpas = p.restart("pkcs11:token=other?module-path=%s&pin-value=1234" %
+                     module)
+    pkcs11_connect(wpas, "No PSK found")
+    if "No token matches the PKCS#11 URI" not in p.log():
+        raise Exception("Missing token not reported")
+
+def test_ext_password_pkcs11_raw_psk(dev, apdev, params):
+    """External password storage on a PKCS#11 token for a raw PSK"""
+    prefix = "ext_password_pkcs11_raw_psk"
+    psk = hashlib.pbkdf2_hmac('sha1', b"12345678", b"ext-pw-psk", 4096,
+                              32).hex()
+    params_ap = hostapd.wpa2_params(ssid="ext-pw-psk")
+    params_ap['wpa_psk'] = psk
+    hapd = hostapd.add_ap(apdev[0], params_ap)
+    module, env = softhsm_token(params, prefix)
+    uri = "pkcs11:token=wifi?module-path=%s&pin-value=1234" % module
+    with HWSimRadio() as (radio, iface):
+        p = Pkcs11Wpas(iface, params, prefix, env)
+        try:
+            wpas = p.start(uri)
+            wpas.set_network(0, "psk", psk)
+            p.save(psk)
+            wpas = p.restart(uri)
+            pkcs11_connect(wpas, "CTRL-EVENT-CONNECTED")
+        finally:
+            p.stop()
+
+def test_ext_password_pkcs11_pin_source(dev, apdev, params):
+    """External password storage on a PKCS#11 token with a PIN file"""
+    prefix = "ext_password_pkcs11_pin_source"
+    hapd = hostapd.add_ap(apdev[0],
+                          hostapd.wpa2_params(ssid="ext-pw-psk",
+                                              passphrase="12345678"))
+    module, env = softhsm_token(params, prefix)
+    pin = os.path.join(params['logdir'], prefix + '.pin')
+    with open(pin, "w") as f:
+        f.write("1234\n")
+    # The module comes from pkcs11_module_path
+    extra = "pkcs11_module_path=%s\n" % module
+    uri = "pkcs11:token=wifi?pin-source=file:" + pin
+    with HWSimRadio() as (radio, iface):
+        p = Pkcs11Wpas(iface, params, prefix, env)
+        try:
+            wpas = p.start(uri, extra)
+            wpas.set_network_quoted(0, "psk", "12345678")
+            p.save("12345678")
+            wpas = p.restart(uri, extra)
+            pkcs11_connect(wpas, "CTRL-EVENT-CONNECTED")
+        finally:
+            p.stop()
+
+def test_ext_password_pkcs11_wrong_pin(dev, apdev, params):
+    """External password storage on a PKCS#11 token with a wrong PIN"""
+    prefix = "ext_password_pkcs11_wrong_pin"
+    hapd = hostapd.add_ap(apdev[0],
+                          hostapd.wpa2_params(ssid="ext-pw-psk",
+                                              passphrase="12345678"))
+    module, env = softhsm_token(params, prefix)
+    uri = "pkcs11:token=wifi?module-path=%s&pin-value=0000" % module
+    with HWSimRadio() as (radio, iface):
+        p = Pkcs11Wpas(iface, params, prefix, env)
+        try:
+            wpas = p.start(uri)
+            with open(p.conffile, "r") as f:
+                before = f.read()
+            # Saving fails when the PSK cannot be stored
+            wpas.set_network_quoted(0, "psk", "12345678")
+            if "FAIL" not in wpas.request("SAVE_CONFIG"):
+                raise Exception("SAVE_CONFIG did not fail")
+            with open(p.conffile, "r") as f:
+                if f.read() != before:
+                    raise Exception("Configuration file changed")
+            wpas = p.restart(uri)
+            pkcs11_connect(wpas, "No PSK found")
+            if "C_Login failed" not in p.log():
+                raise Exception("Wrong PIN not reported")
+        finally:
+            p.stop()
+
+def test_ext_password_pkcs11_uri_errors(dev, apdev, params):
+    """External password storage on a PKCS#11 token with invalid URIs"""
+    tests = [("pkcs11:token=wifi?pin-value=1234&pin-source=file:/dev/null",
+              "pin-value and pin-source cannot be used together"),
+             ("pkcs11:token=wifi;foo=bar",
+              "Unsupported attribute in the PKCS#11 URI"),
+             ("pkcs11:token=%zz", "Invalid PKCS#11 URI"),
+             ("pkcs11:token=wifi?module-path=/nonexistent/libnone.so",
+              "Cannot load /nonexistent/libnone.so")]
+    with HWSimRadio() as (radio, iface):
+        for i, (uri, error) in enumerate(tests):
+            p = Pkcs11Wpas(iface, params,
+                           "ext_password_pkcs11_uri_errors%d" % i)
+            try:
+                p.start(uri, fail=True)
+                if error not in p.log():
+                    raise Exception("Error not reported for %s: %s" %
+                                    (uri, error))
+            finally:
+                p.stop()
-- 
2.53.0




More information about the Hostap mailing list