Rework argument processing
And also README.
This commit is contained in:
parent
5f0ceead24
commit
79958bb100
55
README.md
55
README.md
|
@ -4,40 +4,43 @@ Python script to replace [MargTools](https://businessconnect.margis.si/output/#o
|
||||||
|
|
||||||
## Usage
|
## 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 <KEY ID>] 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/]
|
margfools -e file -k KEYFILE -c CERTFILE bc-digsign://sign?…
|
||||||
key = <path/to/key.pem>
|
|
||||||
cert = <path/to/cert.pem>
|
|
||||||
|
|
||||||
### 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 <KEY ID> bc-digsign://sign?…
|
||||||
|
|
||||||
|
The script will prompt for the PIN to unlock the smartcard. To find the key ID, run
|
||||||
|
|
||||||
pkcs11-tool -O
|
pkcs11-tool -O
|
||||||
|
|
||||||
Look for "ID:" in the output.
|
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
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
xdg-mime default margfools.desktop x-scheme-handler/bc-digsign
|
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 = <path/to/key.pem>
|
||||||
|
certfile = <path/to/cert.pem>
|
||||||
|
|
||||||
|
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&…
|
||||||
|
|
124
margfools
124
margfools
|
@ -14,25 +14,61 @@ import getpass
|
||||||
# use requests instead of urllib.request for keep-alive connection
|
# use requests instead of urllib.request for keep-alive connection
|
||||||
import requests
|
import requests
|
||||||
|
|
||||||
def sign(b64data, key, pin=None, engine=None):
|
def init(args):
|
||||||
if engine is None:
|
args.params = urllib.parse.parse_qs(args.url.query)
|
||||||
# key in file
|
args.access_token = args.params["accessToken"][0]
|
||||||
cmd = ['openssl', 'pkeyutl', '-sign', '-inkey', key, '-pkeyopt', 'digest:sha256']
|
args.start_token = args.params["startSigningToken"][0]
|
||||||
env = None
|
args.url = args.params['baseUrl'][0]
|
||||||
data = base64.b64decode(b64data)
|
|
||||||
elif engine == 'pkcs11':
|
# if missing, get options from section [url] in ~/.margfools
|
||||||
# key on smartcard
|
config = configparser.ConfigParser()
|
||||||
digest_info = { # from RFC 3447
|
config.read(os.path.expanduser('~') + '/.margfools')
|
||||||
'MD2': '3020300c06082a864886f70d020205000410',
|
if not args.engine:
|
||||||
'MD5': '3020300c06082a864886f70d020505000410',
|
args.engine = config.get(args.url, 'engine', fallback='file')
|
||||||
'SHA-1': '3021300906052b0e03021a05000414',
|
|
||||||
'SHA-256': '3031300d060960864801650304020105000420',
|
match args.engine:
|
||||||
'SHA-384': '3041300d060960864801650304020205000430',
|
case 'file':
|
||||||
'SHA-512': '3051300d060960864801650304020305000440'
|
if not args.keyfile:
|
||||||
}
|
args.keyfile = config.get(args.url, 'keyfile', fallback=None)
|
||||||
cmd = ['pkcs11-tool', '--id', key, '-s', '-m', 'RSA-PKCS', '-p', 'env:PIN']
|
if not args.certfile:
|
||||||
env = {'PIN': pin}
|
args.certfile = config.get(args.url, 'certfile', fallback=None)
|
||||||
data = bytes.fromhex(digest_info['SHA-256']) + base64.b64decode(b64data)
|
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)
|
p = subprocess.run(cmd, env=env, input=data, capture_output=True)
|
||||||
if p.returncode != 0:
|
if p.returncode != 0:
|
||||||
|
@ -43,64 +79,42 @@ def sign(b64data, key, pin=None, engine=None):
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
parser = argparse.ArgumentParser(description='Fake the MargTools application.')
|
parser = argparse.ArgumentParser(description='Fake the MargTools application.')
|
||||||
parser.add_argument('url', type=urllib.parse.urlparse, help='bc-digsign:// url')
|
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('-e', '--engine', choices=('file', 'pkcs11'), help='use key file or PKCS11 token?')
|
||||||
parser.add_argument('-k', '--key', type=pathlib.Path, help='key file')
|
parser.add_argument('-k', '--keyfile', type=pathlib.Path, help='key file')
|
||||||
parser.add_argument('-c', '--cert', type=pathlib.Path, help='certificate file')
|
parser.add_argument('-c', '--certfile', type=pathlib.Path, help='certificate file')
|
||||||
|
parser.add_argument('-i', '--id', type=int, metavar='<KEY ID>', help='key ID on PKCS11 token')
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# parse query string
|
# parse query string and load certificates
|
||||||
params = urllib.parse.parse_qs(args.url.query)
|
init(args)
|
||||||
url = params['baseUrl'][0]
|
|
||||||
token = params['accessToken'][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(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()
|
session = requests.Session()
|
||||||
headers = {'Authorization': f'Bearer {token}'}
|
headers = {'Authorization': f'Bearer {args.access_token}'}
|
||||||
|
|
||||||
# delete old signing session
|
# 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
|
# register a certificate or sign a document, makes no difference to us
|
||||||
if params.get('registerCertificate'):
|
if args.params.get('registerCertificate'):
|
||||||
q = {'registerCertificate': 1}
|
q = {'registerCertificate': 1}
|
||||||
else:
|
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)
|
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
|
# get signature request and mix in my secrets and publics
|
||||||
request = json.loads(r.text)
|
request = json.loads(r.text)
|
||||||
request['AuthenticationToken'] = token
|
request['AuthenticationToken'] = args.access_token
|
||||||
request['CertificatePublicKey'] = args.cert
|
request['CertificatePublicKey'] = args.cert
|
||||||
|
|
||||||
# keep signing whatever they send us
|
# keep signing whatever they send us
|
||||||
while True:
|
while True:
|
||||||
for name in ('AttachmentHashes', 'XmlHashes'):
|
for name in ('AttachmentHashes', 'XmlHashes'):
|
||||||
if values := request.get(name, []):
|
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'},
|
headers=headers | {'Content-Type': 'application/json; charset=utf-8'},
|
||||||
data=json.dumps(request).encode())
|
data=json.dumps(request).encode())
|
||||||
if not r.text:
|
if not r.text:
|
||||||
|
|
Loading…
Reference in a new issue