Skip to content

Commit

Permalink
samples: Add support for pkcs11 module environment variables to confi…
Browse files Browse the repository at this point in the history
…g file

Add support for pkcs11 module environment variables to the config file.
These variables may have the following format:

   env:VARNAME=VALUE

Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>
  • Loading branch information
stefanberger committed Sep 18, 2020
1 parent 3983960 commit 2317ca5
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
9 changes: 9 additions & 0 deletions man/man8/swtpm-localca.conf.pod
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,15 @@ used.
This variable can be set to the port on which B<tcsd> is listening for
connections. By default port I<30003> will be used.

=item B<env:<environment variable name>=<value>>

Environment variables, that are needed by pkcs11 modules, can be set using
this format. An example for such an environment variable may look like this:

env:MY_MODULE_PKCS11_CONFIG = /tmp/mymodule-pkcs11.conf

The line must not contain any trailing spaces.

=back

=head1 EXAMPLE
Expand Down
27 changes: 27 additions & 0 deletions samples/py_swtpm_localca/swtpm_localca.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
# (c) Copyright IBM Corporation 2020
#

import codecs
import fcntl
import getopt
import getpass
Expand Down Expand Up @@ -96,6 +97,27 @@ def get_config_value(lines, configname, default=None):
return default


def get_config_envvars(lines):
""" Extract all environment variables from the config file and return a map.
Environment variable lines must start with 'env:' and must not contain
trailing spaces or a comment starting with '#' """
res = {}

regex = r"^env:([a-zA-Z_][a-zA-Z_0-9]*)\s*=\s*([^\n]*).*"
for line in lines:
match = re.match(regex, line)
if match:
try:
encoded = codecs.encode(match.group(2), "latin-1", "backslashreplace")
res[match.group(1)] = codecs.decode(encoded, "unicode_escape")
except Exception as err:
logerr(LOGFILE, "Invalid character in value of %s environment variable: %s\n" %
(match.group(1), str(err)))
return {}, 1

return res, 0


def write_file(filename, text):
""" Write some text to a file """
try:
Expand Down Expand Up @@ -630,6 +652,11 @@ def main():
swtpm_pkcs11_pin = get_config_value(lines, "SWTPM_PKCS11_PIN", "swtpm-tpmca")
swtpm_cert_env["SWTPM_PKCS11_PIN"] = swtpm_pkcs11_pin
logit(LOGFILE, "CA uses a PKCS#11 key; using SWTPM_PKCS11_PIN\n")
# Get additional environment variables pkcs11 modules may need
envvars, ret = get_config_envvars(lines)
if ret != 0:
sys.exit(1)
swtpm_cert_env.update(envvars)
else:
# if signkey does not exists it will be created...
if not os.access(signkey, os.R_OK):
Expand Down

0 comments on commit 2317ca5

Please sign in to comment.