-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathsmartcard.py
More file actions
283 lines (246 loc) · 11.2 KB
/
smartcard.py
File metadata and controls
283 lines (246 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
from __future__ import annotations
from typing import TYPE_CHECKING
from pytest_mh import MultihostHost, MultihostUtility
from pytest_mh.cli import CLIBuilder, CLIBuilderArgs
from pytest_mh.utils.fs import LinuxFileSystem
from pytest_mh.utils.services import SystemdServices
if TYPE_CHECKING:
from ..roles.client import Client
__all__ = [
"SmartCardUtils",
]
class SmartCardUtils(MultihostUtility[MultihostHost]):
"""
Utility class for managing smart card operations using SoftHSM and PKCS#11.
"""
SOFTHSM2_CONF_PATH = "/opt/test_ca/softhsm2.conf"
TOKEN_STORAGE_PATH = "/opt/test_ca/tokens"
OPENSC_CACHE_PATHS = [
"$HOME/.cache/opensc/",
"/run/sssd/.cache/opensc/",
]
def __init__(self, host: MultihostHost, fs: LinuxFileSystem, svc: SystemdServices) -> None:
"""
:param host: Multihost object.
:type host: MultihostHost
:param fs: Filesystem utility object.
:type fs: LinuxFileSystem
:param svc: Systemd svc utility object.
:type svc: SystemdServices
"""
super().__init__(host)
self.cli: CLIBuilder = host.cli
"""CLI builder utility for command construction."""
self.fs: LinuxFileSystem = fs
"""Filesystem utility used to handle file operations."""
self.svc: SystemdServices = svc
"""Systemd utility to manage and interact with svc."""
def initialize_card(self, label: str = "sc_test", so_pin: str = "12345678", user_pin: str = "123456") -> None:
"""
Initializes a SoftHSM token with the given label and PINs.
Cleans cache directories and prepares the token directory.
:param label: Token label, defaults to "sc_test"
:type label: str, optional
:param so_pin: Security Officer PIN, defaults to "12345678"
:type so_pin: str, optional
:param user_pin: User PIN, defaults to "123456"
:type user_pin: str, optional
"""
for path in self.OPENSC_CACHE_PATHS:
self.fs.rm(path)
self.fs.rm(self.TOKEN_STORAGE_PATH)
self.fs.mkdir_p(self.TOKEN_STORAGE_PATH)
args: CLIBuilderArgs = {
"label": (self.cli.option.VALUE, label),
"free": (self.cli.option.SWITCH, True),
"so-pin": (self.cli.option.VALUE, so_pin),
"pin": (self.cli.option.VALUE, user_pin),
}
self.host.conn.run(
self.cli.command("softhsm2-util --init-token", args), env={"SOFTHSM2_CONF": self.SOFTHSM2_CONF_PATH}
)
def initialize_additional_token(self, label: str, so_pin: str = "12345678", user_pin: str = "123456") -> None:
"""
Initializes an additional SoftHSM token without wiping existing tokens.
Unlike :meth:`initialize_card`, this method does **not** remove the
existing token storage directory. It simply calls
``softhsm2-util --init-token --free`` with the given *label* so that a
new slot is allocated alongside any tokens that are already present.
Use this after an initial :meth:`initialize_card` call to create a
multi-token environment (simulating multiple physical smart cards).
:param label: Token label (must be unique among existing tokens).
:type label: str
:param so_pin: Security Officer PIN, defaults to "12345678"
:type so_pin: str, optional
:param user_pin: User PIN, defaults to "123456"
:type user_pin: str, optional
"""
args: CLIBuilderArgs = {
"label": (self.cli.option.VALUE, label),
"free": (self.cli.option.SWITCH, True),
"so-pin": (self.cli.option.VALUE, so_pin),
"pin": (self.cli.option.VALUE, user_pin),
}
self.host.conn.run(
self.cli.command("softhsm2-util --init-token", args), env={"SOFTHSM2_CONF": self.SOFTHSM2_CONF_PATH}
)
def add_cert(
self,
cert_path: str,
cert_id: str = "01",
pin: str = "123456",
private: bool | None = False,
token_label: str | None = None,
label: str | None = None,
) -> None:
"""
Adds a certificate or private key to the smart card.
:param cert_path: Path to the certificate or key file.
:type cert_path: str
:param cert_id: Object ID, defaults to "01"
:type cert_id: str, optional
:param pin: User PIN, defaults to "123456"
:type pin: str, optional
:param private: Whether the object is a private key. Defaults to False.
:type private: bool, optional
:param token_label: Label of the target token. When ``None`` (the
default) ``pkcs11-tool`` writes to the first available token.
Set this when multiple tokens exist to target a specific one.
:type token_label: str | None, optional
:param label: Label for the PKCS#11 object being written. Required
when ``p11_child`` accesses the token directly (i.e. without
``virt_cacard``), because the response parser expects a
non-empty label.
:type label: str | None, optional
"""
obj_type = "privkey" if private else "cert"
args: CLIBuilderArgs = {
"module": (self.cli.option.VALUE, "/usr/lib64/pkcs11/libsofthsm2.so"),
"login": (self.cli.option.SWITCH, True),
"pin": (self.cli.option.VALUE, pin),
"write-object": (self.cli.option.VALUE, cert_path),
"type": (self.cli.option.VALUE, obj_type),
"id": (self.cli.option.VALUE, cert_id),
}
if token_label is not None:
args["token-label"] = (self.cli.option.VALUE, token_label)
if label is not None:
args["label"] = (self.cli.option.VALUE, label)
self.host.conn.run(self.cli.command("pkcs11-tool", args), env={"SOFTHSM2_CONF": self.SOFTHSM2_CONF_PATH})
def add_key(
self,
key_path: str,
key_id: str = "01",
pin: str = "123456",
token_label: str | None = None,
label: str | None = None,
) -> None:
"""
Adds a private key to the smart card.
:param key_path: Path to the private key.
:type key_path: str
:param key_id: Key ID, defaults to "01"
:type key_id: str, optional
:param pin: User PIN, defaults to "123456"
:type pin: str, optional
:param token_label: Label of the target token (see :meth:`add_cert`).
:type token_label: str | None, optional
:param label: Label for the PKCS#11 object (see :meth:`add_cert`).
:type label: str | None, optional
"""
self.add_cert(cert_path=key_path, cert_id=key_id, pin=pin, private=True, token_label=token_label, label=label)
def generate_cert(
self,
key_path: str = "/tmp/selfsigned.key",
cert_path: str = "/tmp/selfsigned.crt",
subj: str = "/CN=Test Cert",
) -> tuple[str, str]:
"""
Generates a self-signed certificate and private key.
:param key_path: Output path for the private key, defaults to "/tmp/selfsigned.key"
:type key_path: str, optional
:param cert_path: Output path for the certificate, defaults to "/tmp/selfsigned.crt"
:type cert_path: str, optional
:param subj: Subject for the certificate, defaults to "/CN=Test Cert"
:type subj: str, optional
:return: Tuple of (key_path, cert_path)
:rtype: tuple
"""
args: CLIBuilderArgs = {
"x509": (self.cli.option.SWITCH, True),
"nodes": (self.cli.option.SWITCH, True),
"sha256": (self.cli.option.SWITCH, True),
"days": (self.cli.option.VALUE, "365"),
"newkey": (self.cli.option.VALUE, "rsa:2048"),
"keyout": (self.cli.option.VALUE, key_path),
"out": (self.cli.option.VALUE, cert_path),
"subj": (self.cli.option.VALUE, subj),
}
self.host.conn.run(self.cli.command("openssl req", args))
return key_path, cert_path
def register_for_p11_child(self) -> None:
"""
Register SoftHSM as a system-wide p11-kit module visible to ``p11_child``.
This is required for multi-token scenarios where ``p11_child`` must
iterate all PKCS#11 slots. The method:
1. Ensures ``slots.removable = true`` is set in the SoftHSM config.
2. Copies the SoftHSM config to ``/etc/softhsm2.conf`` so that
``p11_child`` (running as the *sssd* user) can find it without
``SOFTHSM2_CONF`` in its environment.
3. Registers the SoftHSM module with p11-kit.
4. Creates a systemd drop-in for ``sssd.service`` that exports
``SOFTHSM2_CONF``.
5. Adjusts file permissions so the *sssd* user can access the token
storage directory.
"""
conf = self.SOFTHSM2_CONF_PATH
module = "/usr/lib64/pkcs11/libsofthsm2.so"
self.host.conn.run(f"grep -q 'slots.removable' {conf} || echo 'slots.removable = true' >> {conf}")
self.host.conn.run(f"cp {conf} /etc/softhsm2.conf")
self.host.conn.run(f'echo "module: {module}" > /etc/pkcs11/modules/softhsm2.module')
self.fs.mkdir_p("/etc/systemd/system/sssd.service.d")
self.host.conn.run(
f'printf "[Service]\\nEnvironment=SOFTHSM2_CONF={conf}\\n" '
f"> /etc/systemd/system/sssd.service.d/softhsm.conf"
)
self.host.conn.run("systemctl daemon-reload")
self.host.conn.run("chmod -R o+rX /opt/test_ca/")
self.host.conn.run(
f"chown -R sssd:sssd {self.TOKEN_STORAGE_PATH}/ " f"&& chmod -R 770 {self.TOKEN_STORAGE_PATH}/"
)
def insert_card(self) -> None:
"""
Simulates card insertion by starting the smart card service.
"""
self.svc.start("virt_cacard.service")
def remove_card(self) -> None:
"""
Simulates card removal by stopping the smart card service.
"""
self.svc.stop("virt_cacard.service")
def setup_local_card(self, client: Client, username: str) -> None:
"""
Setup local system for smart card authentication.
.. code-block:: python
:caption: Example usage
@pytest.mark.topology(KnownTopology.Client)
def test_example(client: Client):
client.smartcard.setup_local_card(client, 'localuser1')
result = client.host.conn.run("su - localuser1 -c 'su - localuser1 -c whoami'", input="123456")
assert "PIN" in result.stderr
assert "localuser1" in result.stdout
"""
client.host.fs.rm("/etc/sssd/pki/sssd_auth_ca_db.pem")
key, cert = self.generate_cert()
self.initialize_card()
self.add_key(key)
self.add_cert(cert)
client.authselect.select("sssd", ["with-smartcard"])
self.svc.restart("virt_cacard.service")
client.sssd.common.local()
client.sssd.dom("local")["local_auth_policy"] = "only"
client.sssd.section(f"certmap/local/{username}")["matchrule"] = "<SUBJECT>.*CN=Test Cert.*"
client.sssd.pam["pam_cert_auth"] = "True"
data = client.host.fs.read(cert)
client.host.fs.append("/etc/sssd/pki/sssd_auth_ca_db.pem", data)
client.sssd.start()