Skip to content

Token.open() leaks the session when C_Login fails #246

Closed

Description

@WiktorB2004

Environment

  • python-pkcs11 0.10.0 (PyPI sdist) and current master (c7be814, after 0.10.1); the code is identical.
  • Module: SoftHSM2 2.6.1-3 (Debian 13 "trixie", /usr/lib/softhsm/libsofthsm2.so).
  • Python 3.13.5, Debian 13, x86_64.
  • Expected to affect every PKCS#11 module (the leak is on the client side of the C API).

Summary

Token.open() calls C_OpenSession and then C_Login. If C_Login fails (wrong PIN, locked PIN,
CKR_USER_ALREADY_LOGGED_IN, ...), assertRV() raises, but the freshly opened session handle is never passed to
C_CloseSession, and the caller never receives a Session object that could close it. Each failed login therefore
leaves one open session on the token until C_Finalize (or process exit).

The same happens on the ArgumentsBad("Protected authentication is not supported by loaded module") path, which
also raises after C_OpenSession.

For long-running services that retry a login (for example after a wrong PIN or a token that is temporarily locked)
this exhausts the token's session limit (CKR_SESSION_COUNT) and, on tokens that refuse some operations while any
session is open (for example re-initialising the token), blocks them.

Minimal reproduction

repro.py (below, depends only on python-pkcs11 and ctypes). It counts live sessions by probing small handle
numbers with C_GetSessionInfo on the same loaded module.

softhsm2-util --init-token --free --label test --so-pin 12345678 --pin 1234
MODULE=/usr/lib/softhsm/libsofthsm2.so TOKEN=test PIN=1234 python repro.py

Output on 0.10.0:

start                       live sessions: []
good login (inside with)    live sessions: [1]
good login, after close     live sessions: []
bad login #1: PinIncorrect
bad login #2: PinIncorrect
bad login #3: PinIncorrect
after 3 failed logins + gc  live sessions: [2, 3, 4]

Expected vs actual

  • Expected: a failed Token.open() leaves no session behind (same state as before the call).
  • Actual: one session per failed call stays open; garbage collection does not help because no Python object owns
    the handle.

Root cause

pkcs11/_pkcs11.pyx, Token.open():

  • line 528: retval = self.funclist.C_OpenSession(slot_id, flags, NULL, NULL, &handle) obtains handle.
  • lines 534-544: C_Login is called and checked with assertRV(retval); on failure an exception propagates.
  • handle is only handed to Session.make(...) (line 546 onwards) after both succeed, and Session.close()
    (line ~932-942, C_Logout then C_CloseSession) is the only place that closes it.

There is no try/except around the login, so the error path skips C_CloseSession.

Proposed fix

Wrap the login in try ... except BaseException: and call C_CloseSession(handle) before re-raising. I have a
patch with regression tests ready and will open a pull request referencing this issue.

Notes

No existing issue or pull request about this was found (searched open and closed for login, session,
CloseSession, leak). #61 (C_Login can fail with CKR_USER_ALREADY_LOGGED_IN) is loosely related: a retry loop that
hits that error also leaks one session per attempt with the current code.

repro.py
"""Repro: a failed Token.open(user_pin=...) leaves the C_OpenSession session open.

Counts live sessions by probing handles with C_GetSessionInfo on the same
loaded module (ctypes.CDLL on an already loaded path returns the same instance).
Needs a token already initialised (see run_in_trixie.sh) and:
  MODULE=/usr/lib/softhsm/libsofthsm2.so TOKEN=test PIN=1234
"""
import ctypes, os, gc
import pkcs11

MODULE, TOKEN, PIN = os.environ["MODULE"], os.environ["TOKEN"], os.environ["PIN"]


class SessionInfo(ctypes.Structure):
    _fields_ = [(n, ctypes.c_ulong) for n in ("slotID", "state", "flags", "ulDeviceError")]


raw = ctypes.CDLL(MODULE)


def live_sessions(upto=64):
    info = SessionInfo()
    return [h for h in range(1, upto) if raw.C_GetSessionInfo(ctypes.c_ulong(h), ctypes.byref(info)) == 0]


lib = pkcs11.lib(MODULE)
token = lib.get_token(token_label=TOKEN)
print("start                       live sessions:", live_sessions())

with token.open(user_pin=PIN):
    print("good login (inside with)    live sessions:", live_sessions())
gc.collect()
print("good login, after close     live sessions:", live_sessions())

for i in range(3):
    try:
        token.open(user_pin="wrong-pin")
    except pkcs11.PKCS11Error as e:
        print(f"bad login #{i + 1}: {type(e).__name__}")
gc.collect()
print("after 3 failed logins + gc  live sessions:", live_sessions())

Activity

  1. added a commit that references this issue on Oct 25, 2026
    c48f796
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions