source: mod_gnutls/test/mgstest/softhsm.py @ b2546f0

proxy-ticket
Last change on this file since b2546f0 was b2546f0, checked in by Fiona Klute <fiona.klute@…>, 9 months ago

mgstest.softhsm: Include type when searching object URLs

The p11tool documentation notes that some tokens require the same
label to be used for a certificate and its private key. That isn't the
case for SoftHSM, but I still want to support the case where a key
pair shares a label.

  • Property mode set to 100644
File size: 7.2 KB
Line 
1# Copyright 2020 Fiona Klute
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""SoftHSM support for testing mod_gnutls' PKCS#11 features."""
16
17import os
18import re
19import shutil
20import subprocess
21import tempfile
22from enum import Enum, auto
23from pathlib import Path
24
25softhsm_libname = 'libsofthsm2.so'
26# common install locations to search for the libsofthsm2 PKCS#11 module
27softhsm_searchpath = [
28    Path('/usr/lib64/pkcs11'),
29    Path('/usr/lib/softhsm'),
30    Path('/usr/lib64/softhsm'),
31    Path('/usr/lib/x86_64-linux-gnu/softhsm'),
32    Path('/usr/lib')
33]
34
35# token directory setting in token config file
36tokendir_re = re.compile(r'^directories\.tokendir\s*=\s*(.*)$')
37
38test_label = 'test_server'
39
40class ObjectType(Enum):
41    """Types that may occur in PKCS#11 URIs (type=...).
42
43    See: https://tools.ietf.org/html/rfc7512#section-2.3
44
45    """
46    CERT = 'cert'
47    DATA = 'data'
48    PRIVATE = 'private'
49    PUBLIC = 'public'
50    SECRET_KEY = 'secret-key'
51
52    def __init__(self, uri_type):
53        self.uri_type = uri_type
54
55    def __str__(self):
56        """
57        >>> str(ObjectType.CERT)
58        'type=cert'
59        """
60        return f'type={self.uri_type}'
61
62    def __repr__(self):
63        """
64        >>> repr(ObjectType.PRIVATE)
65        'ObjectType.PRIVATE'
66        """
67        return f'{self.__class__.__name__!s}.{self.name}'
68
69class Token:
70    """Represents a PKCS#11 token."""
71    def __init__(self, config_file, label='mod_gnutls-test'):
72        """The config_file is what SoftHSM expects as SOFTHSM2_CONF."""
73        self.config = config_file
74        self.label = label
75        # Fixed defaults (for now?)
76        # SO -> security officer
77        self.so_pin = '123456'
78        # export as GNUTLS_PIN for use with GnuTLS tools
79        self.pin = '1234'
80
81        # get tokendir from config file
82        self.tokendir = None
83        with open(self.config) as fh:
84            for line in fh:
85                m = tokendir_re.fullmatch(line.strip())
86                if m:
87                    self.tokendir = Path(m.group(1))
88                    break
89
90        self.softhsm = find_softhsm_bin()
91        self.softhsm_lib = find_softhsm_lib()
92
93        # GnuTLS PKCS#11 tool, currently taken from PATH
94        self.p11tool = ['p11tool', '--provider', self.softhsm_lib]
95        # Lazy initialization
96        self._token_url = None
97        self._object_listing = None
98
99    def reset_db(self):
100        """Delete the SoftHSM database directory, and recreate it."""
101        if self.tokendir.exists():
102            shutil.rmtree(self.tokendir)
103        self.tokendir.mkdir()
104
105    def init_token(self):
106        """Initialize a token. The SoftHSM database directory must already
107        exist."""
108        subprocess.run([self.softhsm, '--init-token',
109                        '--free', '--label', self.label,
110                        '--so-pin', self.so_pin, '--pin', self.pin],
111                       check=True, env={'SOFTHSM2_CONF': self.config})
112
113    @property
114    def token_url(self):
115        if not self._token_url:
116            proc = subprocess.run(self.p11tool + ['--list-token-urls'],
117                                  stdout=subprocess.PIPE, check=True, text=True,
118                                  env={'SOFTHSM2_CONF': self.config})
119            url_re = re.compile(f'^pkcs11:.*token={self.label}\\b.*$')
120            for line in proc.stdout.splitlines():
121                if url_re.fullmatch(line):
122                    self._token_url = line
123                    break
124        return self._token_url
125
126    @property
127    def p11tool_env(self):
128        return {'SOFTHSM2_CONF': self.config, 'GNUTLS_PIN': self.pin}
129
130    def store_key(self, keyfile, label):
131        """Store a private key in this token."""
132        subprocess.run(self.p11tool +
133                       ['--login', '--write', '--label', label,
134                        '--load-privkey', keyfile, self.token_url],
135                       check=True, text=True, env=self.p11tool_env)
136        self._object_listing = None
137
138    def store_cert(self, certfile, label):
139        """Store a certificate in this token."""
140        subprocess.run(self.p11tool +
141                       ['--login', '--write', '--no-mark-private',
142                        '--label', label,
143                        '--load-certificate', certfile, self.token_url],
144                       check=True, text=True, env=self.p11tool_env)
145        self._object_listing = None
146
147    def get_object_url(self, label, type):
148        """Get the PKCS#11 URL for an object in this token, selected by
149        label."""
150        if not self._object_listing:
151            proc = subprocess.run(self.p11tool +
152                                  ['--login', '--list-all', self.token_url],
153                                  stdout=subprocess.PIPE,
154                                  check=True, text=True, env=self.p11tool_env)
155            self._object_listing = proc.stdout.splitlines()
156        object_re = re.compile(f'^\s*URL:\s+(.*object={label}.*)$')
157        for line in self._object_listing:
158            m = object_re.fullmatch(line)
159            if m and str(type) in m.group(1):
160                return m.group(1)
161
162    @property
163    def test_env(self):
164        """The environment variables expected by the mod_gnutls test Apache
165        configuration to use this token."""
166        return {
167            'SOFTHSM2_CONF': str(Path(self.config).resolve()),
168            'SOFTHSM_LIB': str(Path(self.softhsm_lib).resolve()),
169            'P11_PIN': self.pin,
170            'P11_CERT_URL': self.get_object_url(test_label, ObjectType.CERT),
171            'P11_KEY_URL': self.get_object_url(test_label, ObjectType.PRIVATE)
172        }
173
174def find_softhsm_bin():
175    """Find the SoftHSM Util binary to use.
176
177    Returns the value selected by ./configure if available, otherwise
178    searches the PATH for 'softhsm2-util'.
179
180    """
181    softhsm = os.environ.get('SOFTHSM')
182    if softhsm and softhsm != 'no':
183        return softhsm
184    return shutil.which('softhsm2-util')
185
186def find_softhsm_lib(libname=softhsm_libname, searchpath=softhsm_searchpath):
187    """Get the path to the SoftHSM PKCS#11 module.
188
189    Return SOFTHSM_LIB if set, otherwise search a list of directories
190    for libsofthsm2.so.
191
192    """
193    lib = os.environ.get('SOFTHSM_LIB')
194    if lib:
195        return lib
196    for p in searchpath:
197        lib = p.joinpath(libname)
198        if lib.is_file():
199            return str(lib)
200
201def tmp_softhsm_conf(db):
202    """Create a temporary SOFTHSM2_CONF file, using an absolute path for
203    the database.
204
205    """
206    with tempfile.NamedTemporaryFile(
207            prefix='mod_gnutls_test-', suffix='.conf', delete=False) as conf:
208        try:
209            conf.write(b'objectstore.backend = file\n')
210            conf.write(f'directories.tokendir = {Path(db).resolve()!s}\n'
211                       .encode())
212        except:
213            Path(conf).unlink()
214            raise
215        return conf.name
Note: See TracBrowser for help on using the repository browser.