From 79958bb100cfed36e4fdcc9b468201ef768d95b2 Mon Sep 17 00:00:00 2001 From: Timotej Lazar Date: Tue, 16 Jan 2024 21:51:47 +0100 Subject: [PATCH] Rework argument processing And also README. --- README.md | 55 ++++++++++++------------ margfools | 124 ++++++++++++++++++++++++++++++------------------------ 2 files changed, 98 insertions(+), 81 deletions(-) diff --git a/README.md b/README.md index a74658d..c54d551 100644 --- a/README.md +++ b/README.md @@ -4,40 +4,43 @@ Python script to replace [MargTools](https://businessconnect.margis.si/output/#o ## Usage -Create the configuration file `~/.margfools`. The contents are described in the sections below. +Run `margfools -h` for a synopsis of command‐line arguments. Allowed arguments are -### Certificates in files + margfools [-h] [-e {file,pkcs11}] [-k KEYFILE] [-c CERTFILE] [-i ] URL -If you are using certificate files, add the paths to your TLS private key and certificate in PEM format: +To use a signing key and certificate stored in PEM files, install `openssl` and run - [https://gcsign.example.com/BCSign/] - key = - cert = + margfools -e file -k KEYFILE -c CERTFILE bc-digsign://sign?… -### Certificates on smartcards +To sign using a PIV-II smartcard such as the Yubikey, install `pkcs11-tool` from [OpenSC](https://github.com/OpenSC/OpenSC) and run -If you have your certificate on a PIV-II smart card (e.g. Yubikey), first determine the slot on your card which contains the certificate you wish to use: + margfools -e pkcs11 -i bc-digsign://sign?… + +The script will prompt for the PIN to unlock the smartcard. To find the key ID, run pkcs11-tool -O -Look for "ID:" in the output. - -Assuming the ID of your certificate was 07, specify the engine and certificate slot in your config file: - - [https://gcsign.example.com/BCSign/] - engine = pkcs11 - key = 07 - -You will be asked for your pin during signing. - -### Add URL schema - -Section name is the percent-decoded value of `baseURL` in - - bc-digsign://sign?accessToken=…&baseUrl=https%3a%2f%2fgcsign.example.com%2fBCSign%2f&…' - -You can set `margfools` as the default program for `bc-digsign` URLs by copying the `margfools.desktop` file to `~/.local/share/applications/` and running +To use `margfools` from the web app, set it as the default program for `x-scheme-handler/bc-digsign` URLs, or copy the `margfools.desktop` file to `~/.local/share/applications/` and run xdg-mime default margfools.desktop x-scheme-handler/bc-digsign -or by setting the default application in your browser. +For this to work, the script must be configured as described below. + +## Configuration + +Settings can be saved on a per‐site basis in `~/.margfools` using the [configparser](https://docs.python.org/3/library/configparser.html) format. + + [DEFAULT] + engine = pkcs11 + + [https://gcsign.example.org/BCSign/] + id = 02 + + [https://gcsign.example.com/BCSign/] + engine = file + keyfile = + certfile = + +All settings can be specified for all sites in the default section, or for individual sites. The section name should match the percent-decoded value of `baseURL` in + + bc-digsign://sign?…&baseUrl=https%3a%2f%2fgcsign.example.com%2fBCSign%2f&… diff --git a/margfools b/margfools index 5fc52a9..6f6d8d5 100755 --- a/margfools +++ b/margfools @@ -14,25 +14,61 @@ import getpass # use requests instead of urllib.request for keep-alive connection import requests -def sign(b64data, key, pin=None, engine=None): - if engine is None: - # key in file - cmd = ['openssl', 'pkeyutl', '-sign', '-inkey', key, '-pkeyopt', 'digest:sha256'] - env = None - data = base64.b64decode(b64data) - elif engine == 'pkcs11': - # key on smartcard - digest_info = { # from RFC 3447 - 'MD2': '3020300c06082a864886f70d020205000410', - 'MD5': '3020300c06082a864886f70d020505000410', - 'SHA-1': '3021300906052b0e03021a05000414', - 'SHA-256': '3031300d060960864801650304020105000420', - 'SHA-384': '3041300d060960864801650304020205000430', - 'SHA-512': '3051300d060960864801650304020305000440' - } - cmd = ['pkcs11-tool', '--id', key, '-s', '-m', 'RSA-PKCS', '-p', 'env:PIN'] - env = {'PIN': pin} - data = bytes.fromhex(digest_info['SHA-256']) + base64.b64decode(b64data) +def init(args): + args.params = urllib.parse.parse_qs(args.url.query) + args.access_token = args.params["accessToken"][0] + args.start_token = args.params["startSigningToken"][0] + args.url = args.params['baseUrl'][0] + + # if missing, get options from section [url] in ~/.margfools + config = configparser.ConfigParser() + config.read(os.path.expanduser('~') + '/.margfools') + if not args.engine: + args.engine = config.get(args.url, 'engine', fallback='file') + + match args.engine: + case 'file': + if not args.keyfile: + args.keyfile = config.get(args.url, 'keyfile', fallback=None) + if not args.certfile: + args.certfile = config.get(args.url, 'certfile', fallback=None) + if not args.keyfile or not args.certfile: + raise Exception('key or certificate file not specified') + args.cert = ''.join(line.strip() for line in open(args.certfile) if not line.startswith('-----')) + case 'pkcs11': + if not args.id: + args.id = config.get(args.url, 'id', fallback=None) + if not args.id: + raise Exception('key ID not specified') + args.cert = base64.b64encode(subprocess.run(['pkcs11-tool', '--read-object', '--type', 'cert', '--id', args.id], capture_output=True).stdout).decode() + args.pin = getpass.getpass('PIN: ') + case '_': + raise Exception(f'invalid engine {args.engine}') + +def sign(b64data, args): + match args.engine: + case 'file': + if not args.keyfile: + raise Exception('keyfile not specified') + cmd = ['openssl', 'pkeyutl', '-sign', '-inkey', args.keyfile, '-pkeyopt', 'digest:sha256'] + env = None + data = base64.b64decode(b64data) + case 'pkcs11': + if not args.id: + raise Exception('key ID not specified') + digest_info = { # from RFC 3447 + 'MD2': '3020300c06082a864886f70d020205000410', + 'MD5': '3020300c06082a864886f70d020505000410', + 'SHA-1': '3021300906052b0e03021a05000414', + 'SHA-256': '3031300d060960864801650304020105000420', + 'SHA-384': '3041300d060960864801650304020205000430', + 'SHA-512': '3051300d060960864801650304020305000440' + } + cmd = ['pkcs11-tool', '--id', args.id, '-s', '-m', 'RSA-PKCS', '-p', 'env:PIN'] + env = {'PIN': args.pin} + data = bytes.fromhex(digest_info['SHA-256']) + base64.b64decode(b64data) + case '_': + raise Exception(f'invalid engine {args.engine}') p = subprocess.run(cmd, env=env, input=data, capture_output=True) if p.returncode != 0: @@ -43,64 +79,42 @@ def sign(b64data, key, pin=None, engine=None): if __name__ == '__main__': parser = argparse.ArgumentParser(description='Fake the MargTools application.') parser.add_argument('url', type=urllib.parse.urlparse, help='bc-digsign:// url') - parser.add_argument('-e', '--engine', type=str, help='"pkcs11" for smart card') - parser.add_argument('-k', '--key', type=pathlib.Path, help='key file') - parser.add_argument('-c', '--cert', type=pathlib.Path, help='certificate file') + parser.add_argument('-e', '--engine', choices=('file', 'pkcs11'), help='use key file or PKCS11 token?') + parser.add_argument('-k', '--keyfile', type=pathlib.Path, help='key file') + parser.add_argument('-c', '--certfile', type=pathlib.Path, help='certificate file') + parser.add_argument('-i', '--id', type=int, metavar='', help='key ID on PKCS11 token') args = parser.parse_args() try: - # parse query string - params = urllib.parse.parse_qs(args.url.query) - url = params['baseUrl'][0] - token = params['accessToken'][0] + # parse query string and load certificates + init(args) - # if missing, get options from section [url] in ~/.margfools - config = configparser.ConfigParser() - config.read(os.path.expanduser('~') + '/.margfools') - if not args.engine: - args.engine = config.get(url, 'engine', fallback=None) - if not args.key: - args.key = config.get(url, 'key') - if not args.cert: - args.cert = config.get(url, 'cert', fallback=None) - if not args.key: - raise Exception('key not specified') - - pin = None - - if args.engine is None: - if not args.cert: - raise Exception('certificate not specified') - args.cert = ''.join(line.strip() for line in open(args.cert) if not line.startswith('-----')) - elif args.engine == 'pkcs11': - args.cert = base64.b64encode(subprocess.run(['pkcs11-tool', '--read-object', '--type', 'cert', '--id', args.key], capture_output=True).stdout).decode() - pin = getpass.getpass('PIN: ') session = requests.Session() - headers = {'Authorization': f'Bearer {token}'} + headers = {'Authorization': f'Bearer {args.access_token}'} # delete old signing session - r = session.delete(f'{url}/signatures/{params["startSigningToken"][0]}', headers=headers) + r = session.delete(f'{args.url}/signatures/{args.params["startSigningToken"][0]}', headers=headers) # register a certificate or sign a document, makes no difference to us - if params.get('registerCertificate'): + if args.params.get('registerCertificate'): q = {'registerCertificate': 1} else: - q = {'documentId': [i for i in params['documentId'][0].split(',')]} + q = {'documentId': [i for i in args.params['documentId'][0].split(',')]} qs = urllib.parse.urlencode(q, doseq=True) - r = session.post(f'{url}/signatures?{qs}', headers=headers) + r = session.post(f'{args.url}/signatures?{qs}', headers=headers) # get signature request and mix in my secrets and publics request = json.loads(r.text) - request['AuthenticationToken'] = token + request['AuthenticationToken'] = args.access_token request['CertificatePublicKey'] = args.cert # keep signing whatever they send us while True: for name in ('AttachmentHashes', 'XmlHashes'): if values := request.get(name, []): - request[f'Signed{name}'] = [sign(v, args.key, pin, engine=args.engine) for v in values] + request[f'Signed{name}'] = [sign(v, args) for v in values] - r = session.put(f'{url}signatures/{request["SignatureRequestId"]}', + r = session.put(f'{args.url}signatures/{request["SignatureRequestId"]}', headers=headers | {'Content-Type': 'application/json; charset=utf-8'}, data=json.dumps(request).encode()) if not r.text: