lib-agent 1.0.9__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,439 @@
1
+ """
2
+ TREZOR support for ECDSA GPG signatures.
3
+
4
+ See these links for more details:
5
+ - https://www.gnupg.org/faq/whats-new-in-2.1.html
6
+ - https://tools.ietf.org/html/rfc4880
7
+ - https://tools.ietf.org/html/rfc6637
8
+ - https://tools.ietf.org/html/draft-irtf-cfrg-eddsa-05
9
+ """
10
+
11
+ import argparse
12
+ import contextlib
13
+ import functools
14
+ import logging
15
+ import os
16
+ import re
17
+ import subprocess
18
+ import sys
19
+ import time
20
+
21
+ import Crypto.Hash
22
+ import Crypto.PublicKey
23
+ import Crypto.Signature
24
+ import semver
25
+ from Crypto.Hash import SHA256, SHA512
26
+ from Crypto.PublicKey import RSA
27
+ from Crypto.Signature import pkcs1_15
28
+
29
+ from .. import device, formats, server, util
30
+ from . import agent, client, encode, keyring, protocol
31
+
32
+ log = logging.getLogger(__name__)
33
+
34
+
35
+ def export_public_key(device_type, args):
36
+ """Generate a new pubkey for a new/existing GPG identity."""
37
+ c = client.Client(device=device_type())
38
+ identity = client.create_identity(user_id=args.user_id,
39
+ curve_name=args.ecdsa_curve)
40
+ if device_type.package_name() == 'onlykey-agent':
41
+ if hasattr(device_type, 'import_pubkey'):
42
+ return device_type.import_pubkey
43
+
44
+ verifying_key = c.pubkey(identity=identity, ecdh=False)
45
+ decryption_key = c.pubkey(identity=identity, ecdh=True)
46
+ signer_func = functools.partial(c.sign, identity=identity)
47
+
48
+ if args.subkey: # add as subkey
49
+ log.info('adding %s GPG subkey for "%s" to existing key',
50
+ args.ecdsa_curve, args.user_id)
51
+ # subkey for signing
52
+ signing_key = protocol.PublicKey(
53
+ curve_name=args.ecdsa_curve, created=args.time,
54
+ verifying_key=verifying_key, ecdh=False)
55
+ # subkey for encryption
56
+ encryption_key = protocol.PublicKey(
57
+ curve_name=formats.get_ecdh_curve_name(args.ecdsa_curve),
58
+ created=args.time, verifying_key=decryption_key, ecdh=True)
59
+ primary_bytes = keyring.export_public_key(args.user_id)
60
+ result = encode.create_subkey(primary_bytes=primary_bytes,
61
+ subkey=signing_key,
62
+ signer_func=signer_func)
63
+ result = encode.create_subkey(primary_bytes=result,
64
+ subkey=encryption_key,
65
+ signer_func=signer_func)
66
+ else: # add as primary
67
+ log.info('creating new %s GPG primary key for "%s"',
68
+ args.ecdsa_curve, args.user_id)
69
+ # primary key for signing
70
+ primary = protocol.PublicKey(
71
+ curve_name=args.ecdsa_curve, created=args.time,
72
+ verifying_key=verifying_key, ecdh=False)
73
+ # subkey for encryption
74
+ subkey = protocol.PublicKey(
75
+ curve_name=formats.get_ecdh_curve_name(args.ecdsa_curve),
76
+ created=args.time, verifying_key=decryption_key, ecdh=True)
77
+
78
+ result = encode.create_primary(user_id=args.user_id,
79
+ pubkey=primary,
80
+ signer_func=signer_func)
81
+ result = encode.create_subkey(primary_bytes=result,
82
+ subkey=subkey,
83
+ signer_func=signer_func)
84
+
85
+ return protocol.armor(result, 'PUBLIC KEY BLOCK')
86
+
87
+
88
+ def verify_gpg_version():
89
+ """Make sure that the installed GnuPG is not too old."""
90
+ existing_gpg = keyring.gpg_version().decode('ascii')
91
+ required_gpg = '>=2.1.11'
92
+ msg = 'Existing GnuPG has version "{}" ({} required)'.format(existing_gpg,
93
+ required_gpg)
94
+ if not semver.match(existing_gpg, required_gpg):
95
+ log.error(msg)
96
+
97
+
98
+ def check_output(args):
99
+ """Runs command and returns the output as string."""
100
+ log.debug('run: %s', args)
101
+ out = subprocess.check_output(args=args).decode('utf-8')
102
+ log.debug('out: %r', out)
103
+ return out
104
+
105
+
106
+ def check_call(args, stdin=None, env=None):
107
+ """Runs command and verifies its success."""
108
+ log.debug('run: %s%s', args, ' {}'.format(env) if env else '')
109
+ subprocess.check_call(args=args, stdin=stdin, env=env)
110
+
111
+
112
+ def write_file(path, data):
113
+ """Writes data to specified path."""
114
+ with open(path, 'w') as f:
115
+ log.debug('setting %s contents:\n%s', path, data)
116
+ f.write(data)
117
+ return f
118
+
119
+
120
+ def _windowless_python():
121
+ """Windows: pythonw.exe next to this Python (no console window), else this Python."""
122
+ pythonw = os.path.join(os.path.dirname(sys.executable), 'pythonw.exe')
123
+ return pythonw if os.path.isfile(pythonw) else sys.executable
124
+
125
+
126
+ def run_init(device_type, args):
127
+ """Initialize hardware-based GnuPG identity."""
128
+ util.setup_logging(verbosity=args.verbose)
129
+
130
+ verify_gpg_version()
131
+
132
+ # Prepare new GPG home directory for hardware-based identity
133
+ device_name = device_type.package_name().rsplit('-', 1)[0]
134
+ log.info('device name: %s', device_name)
135
+ homedir = args.homedir
136
+ if not homedir:
137
+ homedir = os.path.expanduser('~/.gnupg/{}'.format(device_name))
138
+
139
+ # Save homedir as environment variable
140
+ os.environ['AGENTHOMEDIR'] = homedir
141
+
142
+ log.info('GPG home directory: %s', homedir)
143
+
144
+ if os.path.exists(homedir):
145
+ log.error('GPG home directory %s exists, '
146
+ 'remove it manually if required', homedir)
147
+ sys.exit(1)
148
+
149
+ # os.makedirs/os.chmod, not the mkdir/chmod programs: Windows has neither
150
+ # (outside a Git Bash or MSYS shell). On Windows chmod only sets the
151
+ # read-only bit, which 0o700 leaves off.
152
+ os.makedirs(homedir)
153
+ os.chmod(homedir, 0o700)
154
+
155
+ agent_path = util.which('{}-gpg-agent'.format(device_name))
156
+
157
+ # Prepare GPG agent invocation script (to pass the PATH from environment).
158
+ if device_type.package_name() == 'onlykey-agent':
159
+ if args.import_pub is not None:
160
+ with args.import_pub as f:
161
+ device_type.import_pub(device_type, f.read())
162
+ agent_flags = ['--skey-slot={skey}', '--dkey-slot={dkey}']
163
+ else:
164
+ agent_flags = ['--pin-entry-binary={pin_entry_binary}',
165
+ '--passphrase-entry-binary={passphrase_entry_binary}',
166
+ '--cache-expiry-seconds={cache_expiry_seconds}']
167
+ # Not -vv: the launcher used to start the agent at DEBUG, and the agent's
168
+ # log (~/.gnupg/<device>/gpg-agent.log) then recorded every Assuan 'D' line
169
+ # it sent - including the PGP session key on every decrypt. The user can
170
+ # still add -v flags to the generated launcher for a debugging session.
171
+ agent_flags = [flag.format(**vars(args)) for flag in agent_flags]
172
+
173
+ if sys.platform == 'win32':
174
+ # gpg on Windows starts agent-program with CreateProcess, which cannot
175
+ # run a shell script (error 193, "not a valid Win32 application"), so
176
+ # the launcher is a batch file doing what run-agent.sh does: set PATH,
177
+ # then start the agent with these flags and gpg's own arguments (%*).
178
+ # The agent runs under pythonw.exe (pip's .exe launchers are zip files
179
+ # Python can run): a console program started from gpg would open a
180
+ # console window, every time gpg starts its agent.
181
+ run_agent_script = os.path.join(homedir, 'run-agent.cmd')
182
+ with open(run_agent_script, 'w') as f:
183
+ f.write('@echo off\nset "PATH={0}"\n"{1}" "{2}" {3} %*\n'.format(
184
+ os.environ['PATH'], _windowless_python(), agent_path,
185
+ ' '.join(agent_flags)))
186
+ else:
187
+ run_agent_script = os.path.join(homedir, 'run-agent.sh')
188
+ with open(run_agent_script, 'w') as f:
189
+ f.write('#!/bin/sh\nexport PATH="{0}"\n{1} \\\n{2} \\\n$*\n'.format(
190
+ os.environ['PATH'], agent_path,
191
+ ' \\\n'.join(agent_flags)))
192
+ os.chmod(run_agent_script, 0o700)
193
+
194
+ # Prepare GPG configuration file
195
+ with open(os.path.join(homedir, 'gpg.conf'), 'w') as f:
196
+ f.write("""# Hardware-based GPG configuration
197
+ agent-program {0}
198
+ personal-digest-preferences SHA512
199
+ default-key \"{1}\"
200
+ """.format(run_agent_script, args.user_id))
201
+
202
+ # Prepare a helper script for setting up the new identity
203
+ with open(os.path.join(homedir, 'env'), 'w') as f:
204
+ f.write("""#!/bin/bash
205
+ set -eu
206
+ export GNUPGHOME={0}
207
+ COMMAND=$*
208
+ if [ -z "${{COMMAND}}" ]
209
+ then
210
+ ${{SHELL}}
211
+ else
212
+ ${{COMMAND}}
213
+ fi
214
+ """.format(homedir))
215
+ os.chmod(f.name, 0o700)
216
+
217
+ # Generate new GPG identity and import into GPG keyring
218
+ pubkey = write_file(os.path.join(homedir, 'pubkey.asc'),
219
+ export_public_key(device_type, args))
220
+ verbosity = ('-' + ('v' * args.verbose)) if args.verbose else '--quiet'
221
+ check_call(keyring.gpg_command(['--homedir', homedir, verbosity,
222
+ '--import', pubkey.name]))
223
+
224
+ # Make new GPG identity with "ultimate" trust (via its fingerprint)
225
+ out = check_output(keyring.gpg_command(['--homedir', homedir,
226
+ '--list-public-keys',
227
+ '--with-fingerprint',
228
+ '--with-colons']))
229
+ fpr = re.findall('fpr:::::::::([0-9A-F]+):', out)[0]
230
+ f = write_file(os.path.join(homedir, 'ownertrust.txt'), fpr + ':6\n')
231
+ check_call(keyring.gpg_command(['--homedir', homedir,
232
+ '--import-ownertrust', f.name]))
233
+
234
+ # Load agent and make sure it responds with the new identity
235
+ check_call(keyring.gpg_command(['--homedir', homedir,
236
+ '--list-secret-keys', args.user_id]))
237
+
238
+
239
+ def run_unlock(device_type, args):
240
+ """Unlock hardware device (for future interaction)."""
241
+ util.setup_logging(verbosity=args.verbose)
242
+ with device_type() as d:
243
+ log.info('unlocked %s device', d)
244
+
245
+
246
+ def _server_from_assuan_fd(env):
247
+ fd = env.get('_assuan_connection_fd')
248
+ if fd is None:
249
+ return None
250
+ log.info('using fd=%r for UNIX socket server', fd)
251
+ return server.unix_domain_socket_server_from_fd(int(fd))
252
+
253
+
254
+ def _server_from_sock_path(env):
255
+ sock_path = keyring.get_agent_sock_path(env=env)
256
+ if sys.platform == 'win32':
257
+ # GnuPG for Windows has no UNIX sockets: it reads libassuan's socket
258
+ # file (a loopback port and a nonce) at the same path.
259
+ return server.assuan_nonce_socket_server(sock_path)
260
+ return server.unix_domain_socket_server(sock_path)
261
+
262
+
263
+ def run_agent(device_type):
264
+ """Run a simple GPG-agent server."""
265
+ p = argparse.ArgumentParser()
266
+ p.add_argument('--homedir', default=os.environ.get('GNUPGHOME'))
267
+ p.add_argument('-v', '--verbose', default=0, action='count')
268
+ p.add_argument('--server', default=False, action='store_true',
269
+ help='Use stdin/stdout for communication with GPG.')
270
+ if device_type.package_name() == 'onlykey-agent':
271
+ p.add_argument('-sk', '--skey', type=str, metavar='SIGN_KEY',
272
+ default='ECC32',
273
+ help='signing key: RSA1-4, ECC1-16, ECC32 (derived, default) or derived-v2 (HKDF)')
274
+ p.add_argument('-dk', '--dkey', type=str, metavar='DECRYPT_KEY',
275
+ default='ECC32',
276
+ help='decryption key: RSA1-4, ECC1-16, ECC32 (derived, default) or derived-v2 (HKDF)')
277
+ else:
278
+ p.add_argument('--passphrase-entry-binary', type=str, default='pinentry',
279
+ help='Path to passphrase entry UI helper.')
280
+ p.add_argument('--cache-expiry-seconds', type=float, default=float('inf'),
281
+ help='Expire passphrase from cache after this duration.')
282
+ p.add_argument('--daemon', default=False, action='store_true',
283
+ help='Daemonize the agent.')
284
+
285
+ args, _ = p.parse_known_args()
286
+
287
+ if args.daemon and sys.platform == 'win32':
288
+ # gpg starts agent-program with --daemon and waits for it to exit, then
289
+ # connects to the socket. python-daemon cannot run on Windows, so the
290
+ # agent starts a detached copy of itself without --daemon, and exits.
291
+ # The copy gets no handles from gpg: gpg would wait for them to close.
292
+ # It also leaves the job object of pip's .exe launcher, which kills
293
+ # every process in the job when the launcher exits.
294
+ script = sys.argv[0]
295
+ if not os.path.isfile(script) and os.path.isfile(script + '.exe'):
296
+ script += '.exe' # started through pip's launcher: argv[0] has no .exe
297
+ argv = [_windowless_python(), script] + [a for a in sys.argv[1:] if a != '--daemon']
298
+ flags = subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP
299
+ try:
300
+ subprocess.Popen(argv, close_fds=True, stdin=subprocess.DEVNULL,
301
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
302
+ creationflags=flags | subprocess.CREATE_BREAKAWAY_FROM_JOB)
303
+ except OSError:
304
+ # A job that does not allow breakaway refuses the flag (access
305
+ # denied); the copy is then started inside that job.
306
+ subprocess.Popen(argv, close_fds=True, stdin=subprocess.DEVNULL,
307
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
308
+ creationflags=flags)
309
+ elif args.daemon:
310
+ # Imported here, not at the top: python-daemon needs the Unix-only
311
+ # `pwd` module, so a top-level import stopped every lib-agent command
312
+ # from starting on Windows (onlykey-agent, onlykey-gpg init) although
313
+ # only --daemon uses it. Daemonizing stays Unix-only.
314
+ import daemon # pylint: disable=import-outside-toplevel
315
+ with daemon.DaemonContext():
316
+ run_agent_internal(args, device_type)
317
+ else:
318
+ run_agent_internal(args, device_type)
319
+
320
+
321
+ def run_agent_internal(args, device_type):
322
+ """Actually run the server."""
323
+ assert args.homedir
324
+
325
+ # Save homedir as environment variable
326
+ os.environ['AGENTHOMEDIR'] = args.homedir
327
+
328
+ log_file = os.path.join(args.homedir, 'gpg-agent.log')
329
+ util.setup_logging(verbosity=args.verbose, filename=log_file)
330
+
331
+ log.debug('sys.argv: %s', sys.argv)
332
+ log.debug('os.environ: %s', os.environ)
333
+ log.debug('pid: %d, parent pid: %d', os.getpid(), os.getppid())
334
+ try:
335
+ env = {'GNUPGHOME': args.homedir, 'PATH': os.environ['PATH']}
336
+ pubkey_bytes = keyring.export_public_keys(env=env)
337
+ device_type.ui = device.ui.UI(device_type=device_type,
338
+ config=vars(args))
339
+ handler = agent.Handler(device=device_type(),
340
+ pubkey_bytes=pubkey_bytes)
341
+
342
+ sock_server = _server_from_assuan_fd(os.environ)
343
+ if sock_server is None:
344
+ sock_server = _server_from_sock_path(env)
345
+
346
+ with sock_server as sock:
347
+ for conn in agent.yield_connections(sock):
348
+ with contextlib.closing(conn):
349
+ try:
350
+ handler.handle(conn)
351
+ except agent.AgentStop:
352
+ log.info('stopping gpg-agent')
353
+ except ConnectionResetError as e:
354
+ # Windows reports gpg closing its connection as a reset
355
+ # (WinError 10054) where POSIX gives end-of-file: that
356
+ # client is gone, and the agent keeps serving the next.
357
+ log.debug('connection reset: %s', e)
358
+ except IOError as e:
359
+ log.info('connection closed: %s', e)
360
+ return
361
+ except Exception as e: # pylint: disable=broad-except
362
+ log.exception('handler failed: %s', e)
363
+
364
+ except Exception as e: # pylint: disable=broad-except
365
+ log.exception('gpg-agent failed: %s', e)
366
+
367
+
368
+ def main(device_type):
369
+ """Parse command-line arguments."""
370
+ epilog = ('See https://github.com/romanz/trezor-agent/blob/master/'
371
+ 'doc/README-GPG.md for usage examples.')
372
+ parser = argparse.ArgumentParser(epilog=epilog)
373
+
374
+ agent_package = device_type.package_name()
375
+ parser.add_argument('--version', help='print the version info',
376
+ action='version', version=util.format_versions(agent_package))
377
+
378
+ subparsers = parser.add_subparsers(title='Action', dest='action')
379
+ subparsers.required = True
380
+
381
+ p = subparsers.add_parser('init',
382
+ help='initialize hardware-based GnuPG identity')
383
+ p.add_argument('user_id')
384
+ p.add_argument('-v', '--verbose', default=0, action='count')
385
+ p.add_argument('-s', '--subkey', default=False, action='store_true')
386
+
387
+ if agent_package == 'onlykey-agent':
388
+ p.add_argument('-e', '--ecdsa-curve', default='ed25519')
389
+ p.add_argument('-sk', '--skey', type=str, metavar='SIGN_KEY',
390
+ default='ECC32',
391
+ help='signing key: RSA1-4, ECC1-16, ECC32 (derived, default) or derived-v2 (HKDF)')
392
+ p.add_argument('-dk', '--dkey', type=str, metavar='DECRYPT_KEY',
393
+ default='ECC32',
394
+ help='decryption key: RSA1-4, ECC1-16, ECC32 (derived, default) or derived-v2 (HKDF)')
395
+ p.add_argument('-i', '--import-pub', type=argparse.FileType('r'),
396
+ metavar='IMPORT_PUBLIC_KEY',
397
+ default=None,
398
+ help=('import existing OpenPGP public key to use '
399
+ '(Load private using OnlyKey App)'))
400
+ p.add_argument('-t', '--time', type=int, default=0)
401
+
402
+ p.add_argument('--homedir', type=str, default=os.environ.get('GNUPGHOME'),
403
+ help='Customize GnuPG home directory for the new identity.')
404
+
405
+ p.set_defaults(func=run_init)
406
+
407
+ else:
408
+ p.add_argument('-e', '--ecdsa-curve', default='nist256p1')
409
+ p.add_argument('-t', '--time', type=int, default=0)
410
+ p.add_argument('--homedir', type=str, default=os.environ.get('GNUPGHOME'),
411
+ help='Customize GnuPG home directory for the new identity.')
412
+
413
+ p.add_argument('--pin-entry-binary', type=str, default='pinentry',
414
+ help='Path to PIN entry UI helper.')
415
+ p.add_argument('--passphrase-entry-binary', type=str, default='pinentry',
416
+ help='Path to passphrase entry UI helper.')
417
+ p.add_argument('--cache-expiry-seconds', type=float, default=float('inf'),
418
+ help='Expire passphrase from cache after this duration.')
419
+
420
+ p.set_defaults(func=run_init)
421
+
422
+ p = subparsers.add_parser('unlock', help='unlock the hardware device')
423
+ p.add_argument('-v', '--verbose', default=0, action='count')
424
+
425
+ p.set_defaults(func=run_unlock)
426
+
427
+ args = parser.parse_args()
428
+
429
+ if agent_package == 'onlykey-agent':
430
+ device_type.set_skey(device_type, args.skey)
431
+ device_type.set_dkey(device_type, args.dkey)
432
+ else:
433
+ device_type.ui = device.ui.UI(device_type=device_type, config=vars(args))
434
+
435
+ try:
436
+ return args.func(device_type=device_type, args=args)
437
+ except device.interface.DeviceError as e:
438
+ log.error('%s', e)
439
+ return 1